@ouro.bot/cli 0.1.0-alpha.16 → 0.1.0-alpha.1600

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 (1682) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +281 -171
  3. package/RepairGuide.ouro/agent.json +5 -0
  4. package/RepairGuide.ouro/psyche/IDENTITY.md +19 -0
  5. package/RepairGuide.ouro/psyche/SOUL.md +55 -0
  6. package/RepairGuide.ouro/skills/diagnose-broken-remote.md +63 -0
  7. package/RepairGuide.ouro/skills/diagnose-stacked-typed-issues.md +35 -0
  8. package/RepairGuide.ouro/skills/diagnose-sync-blocked.md +54 -0
  9. package/RepairGuide.ouro/skills/diagnose-vault-expired.md +60 -0
  10. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +4 -2
  11. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +4 -4
  12. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +2 -2
  13. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  14. package/assets/bluebubbles-host +264 -0
  15. package/assets/sanctuary-host-launcher.sh +16 -0
  16. package/changelog.json +10351 -0
  17. package/deploy/unraid/Dockerfile +85 -0
  18. package/deploy/unraid/INSTALL.md +64 -0
  19. package/deploy/unraid/README.txt +3034 -0
  20. package/deploy/unraid/audit-container-spec.sh +4 -0
  21. package/deploy/unraid/container-runtime.json +1 -0
  22. package/deploy/unraid/credit-gateway.md +95 -0
  23. package/deploy/unraid/docker-man-template-transaction.mjs +733 -0
  24. package/deploy/unraid/docker-man-template-xml.cjs +105 -0
  25. package/deploy/unraid/github_known_hosts +3 -0
  26. package/deploy/unraid/install.sh +274 -0
  27. package/deploy/unraid/migrate-sanctuary-bundle.mjs +63 -0
  28. package/deploy/unraid/ouro-events/bootstrap-spool.sh +92 -0
  29. package/deploy/unraid/ouro-events/emit-event.mjs +310 -0
  30. package/deploy/unraid/ouro-events/emit-usenet-event.sh +54 -0
  31. package/deploy/unraid/ouro-events/install-usenet-guard.sh +435 -0
  32. package/deploy/unraid/ouro-events/usenet-health.sh +176 -0
  33. package/deploy/unraid/ouro-host-lock.mjs +245 -0
  34. package/deploy/unraid/ouro-sync-ssh +98 -0
  35. package/deploy/unraid/ouro-sync.sudoers +3 -0
  36. package/deploy/unraid/sanctuary-acceptance-adapter.sh +43 -0
  37. package/deploy/unraid/sanctuary-acceptance-contract.json +198 -0
  38. package/deploy/unraid/sanctuary-acceptance-harness.sh +23 -0
  39. package/deploy/unraid/sanctuary-authority-installation.json +36 -0
  40. package/deploy/unraid/sanctuary-authority-service.sh +30 -0
  41. package/deploy/unraid/sanctuary-butler-upgrade.mjs +1604 -0
  42. package/deploy/unraid/sanctuary-deployment-target.mjs +710 -0
  43. package/deploy/unraid/sanctuary-replay-gate.mjs +2781 -0
  44. package/deploy/unraid/sanctuary-safe-rename.py +24 -0
  45. package/deploy/unraid/sanctuary-sync-cutover.sh +1039 -0
  46. package/deploy/unraid/sanctuary-unit16-host-broker.mjs +2088 -0
  47. package/deploy/unraid/sanctuary-unit16-run.sh +570 -0
  48. package/deploy/unraid/sanctuary-unit18-target-audit.sh +27 -0
  49. package/deploy/unraid/sanctuary.ouro/agent.json +72 -0
  50. package/deploy/unraid/sanctuary.ouro/arc/README.md +3 -0
  51. package/deploy/unraid/sanctuary.ouro/awaiting/house-care-sweep.md +17 -0
  52. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +5 -0
  53. package/deploy/unraid/sanctuary.ouro/habits/sanctuary-health.md +8 -0
  54. package/deploy/unraid/sanctuary.ouro/mcp/media-mcp.mjs +2533 -0
  55. package/deploy/unraid/sanctuary.ouro/product/PRODUCT.md +13 -0
  56. package/deploy/unraid/sanctuary.ouro/provider-readiness.json +11 -0
  57. package/deploy/unraid/sanctuary.ouro/psyche/ASPIRATIONS.md +5 -0
  58. package/deploy/unraid/sanctuary.ouro/psyche/IDENTITY.md +7 -0
  59. package/deploy/unraid/sanctuary.ouro/psyche/LORE.md +7 -0
  60. package/deploy/unraid/sanctuary.ouro/psyche/SOUL.md +15 -0
  61. package/deploy/unraid/sanctuary.ouro/psyche/TACIT.md +3 -0
  62. package/deploy/unraid/sanctuary.ouro/state/policy/steward.json +7 -0
  63. package/deploy/unraid/sanctuary.ouro/tool-profiles.json +274 -0
  64. package/deploy/unraid/sanctuary.xml +30 -0
  65. package/desk.lock.json +8 -0
  66. package/dist/a2a/approval-relay-forward.js +117 -0
  67. package/dist/a2a/approval-relay.js +95 -0
  68. package/dist/a2a/approval-request-wire.js +123 -0
  69. package/dist/a2a/card.js +57 -0
  70. package/dist/a2a/client.js +331 -0
  71. package/dist/a2a/config.js +50 -0
  72. package/dist/a2a/delegated-command-grants.js +93 -0
  73. package/dist/a2a/delegated-command.js +200 -0
  74. package/dist/a2a/delegation-stores.js +56 -0
  75. package/dist/a2a/did-resolution.js +205 -0
  76. package/dist/a2a/escalation-grants.js +84 -0
  77. package/dist/a2a/escalation-wiring.js +60 -0
  78. package/dist/a2a/identity.js +258 -0
  79. package/dist/a2a/inbound-share.js +131 -0
  80. package/dist/a2a/mission-result-wire.js +265 -0
  81. package/dist/a2a/onboarding.js +133 -0
  82. package/dist/a2a/operator-trust.js +399 -0
  83. package/dist/a2a/outbox-client.js +59 -0
  84. package/dist/a2a/outbox-store.js +245 -0
  85. package/dist/a2a/outbox-wire.js +106 -0
  86. package/dist/a2a/pin-store.js +167 -0
  87. package/dist/a2a/refusals.js +55 -0
  88. package/dist/a2a/relay-client.js +106 -0
  89. package/dist/a2a/relay-config-vault.js +64 -0
  90. package/dist/a2a/relay-contacts.js +120 -0
  91. package/dist/a2a/relay-inbox.js +360 -0
  92. package/dist/a2a/relay-retirements.js +89 -0
  93. package/dist/a2a/replay-grant-holders.js +33 -0
  94. package/dist/a2a/replay-harness.js +188 -0
  95. package/dist/a2a/resolution-proof.js +53 -0
  96. package/dist/a2a/sealed-chat.js +142 -0
  97. package/dist/a2a/seen-ledger.js +216 -0
  98. package/dist/a2a/server.js +1088 -0
  99. package/dist/a2a/task-store.js +69 -0
  100. package/dist/a2a/transport.js +100 -0
  101. package/dist/a2a/trust-commands.js +203 -0
  102. package/dist/a2a/trusted-files.js +185 -0
  103. package/dist/a2a/types.js +3 -0
  104. package/dist/actions/generated/mailbox/actions.json +592 -0
  105. package/dist/actions/generated/mailbox/commands.json +181 -0
  106. package/dist/actions/generated/mailbox/mcp.json +454 -0
  107. package/dist/actions/generated/mailbox-tools/tools.json +516 -0
  108. package/dist/arc/attention-types.js +8 -0
  109. package/dist/arc/cares.js +360 -0
  110. package/dist/arc/episodes.js +118 -0
  111. package/dist/arc/evolution.js +490 -0
  112. package/dist/arc/flight-recorder.js +1009 -0
  113. package/dist/arc/intentions.js +134 -0
  114. package/dist/arc/json-store.js +117 -0
  115. package/dist/arc/obligations.js +386 -0
  116. package/dist/arc/packets.js +336 -0
  117. package/dist/arc/presence.js +185 -0
  118. package/dist/arc/task-lifecycle.js +57 -0
  119. package/dist/commerce/store.js +755 -0
  120. package/dist/commerce/types.js +3 -0
  121. package/dist/eval/assertions/index.js +378 -0
  122. package/dist/eval/billing-guard.js +23 -0
  123. package/dist/eval/budget.js +142 -0
  124. package/dist/eval/domain/case.js +115 -0
  125. package/dist/eval/domain/stats.js +19 -0
  126. package/dist/eval/guest-entry.js +18 -0
  127. package/dist/eval/h-guest-entry.js +19 -0
  128. package/dist/eval/interview-entry.js +174 -0
  129. package/dist/eval/interview-grade-entry.js +36 -0
  130. package/dist/eval/interview-guest-entry.js +19 -0
  131. package/dist/eval/interviews/allocation.js +90 -0
  132. package/dist/eval/interviews/final.js +133 -0
  133. package/dist/eval/interviews/grader.js +209 -0
  134. package/dist/eval/interviews/guest/arms.js +173 -0
  135. package/dist/eval/interviews/guest/ax/ax-command.js +792 -0
  136. package/dist/eval/interviews/guest/ax/effects.js +51 -0
  137. package/dist/eval/interviews/guest/ax/exit-codes.js +51 -0
  138. package/dist/eval/interviews/guest/ax/help.js +181 -0
  139. package/dist/eval/interviews/guest/ax/mcp.js +246 -0
  140. package/dist/eval/interviews/guest/ax/outcome.js +211 -0
  141. package/dist/eval/interviews/guest/ax/output.js +53 -0
  142. package/dist/eval/interviews/guest/ax/precise-copy.js +200 -0
  143. package/dist/eval/interviews/guest/ax/problem.js +95 -0
  144. package/dist/eval/interviews/guest/ax/voice.js +83 -0
  145. package/dist/eval/interviews/guest/ax/wait.js +158 -0
  146. package/dist/eval/interviews/guest/books-core.js +54 -0
  147. package/dist/eval/interviews/guest/cli-shell.js +267 -0
  148. package/dist/eval/interviews/guest/h/codex.js +201 -0
  149. package/dist/eval/interviews/guest/h/fidelity.js +59 -0
  150. package/dist/eval/interviews/guest/h/openhands.js +176 -0
  151. package/dist/eval/interviews/guest/h/run.js +99 -0
  152. package/dist/eval/interviews/guest/h/wire.js +403 -0
  153. package/dist/eval/interviews/guest/loop.js +87 -0
  154. package/dist/eval/interviews/guest/operations.js +108 -0
  155. package/dist/eval/interviews/guest/run.js +81 -0
  156. package/dist/eval/interviews/guest/u/arms.js +268 -0
  157. package/dist/eval/interviews/h/kit.js +119 -0
  158. package/dist/eval/interviews/latch.js +143 -0
  159. package/dist/eval/interviews/protocol.js +120 -0
  160. package/dist/eval/interviews/rewrite.js +57 -0
  161. package/dist/eval/interviews/runner.js +354 -0
  162. package/dist/eval/interviews/u/kit.js +117 -0
  163. package/dist/eval/kill-switch.js +33 -0
  164. package/dist/eval/month-ledger.js +95 -0
  165. package/dist/eval/readback/hedges.js +39 -0
  166. package/dist/eval/remote-entry.js +32 -0
  167. package/dist/eval/report.js +85 -0
  168. package/dist/eval/run-command.js +188 -0
  169. package/dist/eval/run-entry.js +93 -0
  170. package/dist/eval/sandbox/agent-profile.js +74 -0
  171. package/dist/eval/sandbox/declared-gaps.js +17 -0
  172. package/dist/eval/sandbox/docker.js +353 -0
  173. package/dist/eval/sandbox/guest.js +55 -0
  174. package/dist/eval/sandbox/host-lock.js +62 -0
  175. package/dist/eval/sandbox/images.js +39 -0
  176. package/dist/eval/sandbox/oracle.js +32 -0
  177. package/dist/eval/sandbox/projection.js +127 -0
  178. package/dist/eval/sandbox/readback.js +137 -0
  179. package/dist/eval/sandbox/remote.js +102 -0
  180. package/dist/eval/sandbox/slugger-projection.js +377 -0
  181. package/dist/eval/self-test.js +84 -0
  182. package/dist/eval/stop-command.js +71 -0
  183. package/dist/eval/stop-entry.js +46 -0
  184. package/dist/eval/targets/index.js +127 -0
  185. package/dist/eval/transport/provider-proxy.js +262 -0
  186. package/dist/eval/transport/synthetic-sanctuary.js +111 -0
  187. package/dist/eval/transport/telegram-turn.js +241 -0
  188. package/dist/eval/watch/cli.js +63 -0
  189. package/dist/eval/watch/guarded-fs.js +254 -0
  190. package/dist/eval/watch/log-reader.js +99 -0
  191. package/dist/eval/watch/rows.js +143 -0
  192. package/dist/eval/watch/run-watch.js +160 -0
  193. package/dist/eval/watch-entry.js +26 -0
  194. package/dist/gateway/keys.js +117 -0
  195. package/dist/gateway/server.js +429 -0
  196. package/dist/heart/active-work.js +1009 -0
  197. package/dist/heart/agent-entry.js +255 -4
  198. package/dist/heart/approval-files.js +94 -0
  199. package/dist/heart/approval-store.js +1000 -0
  200. package/dist/heart/atomic-file.js +115 -0
  201. package/dist/heart/attachments/downloaded-store.js +89 -0
  202. package/dist/heart/attachments/image-normalize.js +201 -0
  203. package/dist/heart/attachments/materialize.js +97 -0
  204. package/dist/heart/attachments/originals.js +102 -0
  205. package/dist/heart/attachments/render.js +29 -0
  206. package/dist/heart/attachments/sources/bluebubbles.js +155 -0
  207. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  208. package/dist/heart/attachments/sources/downloaded.js +76 -0
  209. package/dist/heart/attachments/sources/index.js +19 -0
  210. package/dist/heart/attachments/store.js +132 -0
  211. package/dist/heart/attachments/transcribe-audio.js +231 -0
  212. package/dist/heart/attachments/types.js +93 -0
  213. package/dist/heart/attachments/understand.js +195 -0
  214. package/dist/heart/auth/auth-flow.js +589 -0
  215. package/dist/heart/auth/github-device-login.js +104 -0
  216. package/dist/heart/autonomy-budget.js +426 -0
  217. package/dist/heart/awaiting/a2a-await-delivery.js +109 -0
  218. package/dist/heart/awaiting/await-alert.js +152 -0
  219. package/dist/heart/awaiting/await-expiry.js +143 -0
  220. package/dist/heart/awaiting/await-loader.js +91 -0
  221. package/dist/heart/awaiting/await-parser.js +152 -0
  222. package/dist/heart/awaiting/await-runtime-state.js +130 -0
  223. package/dist/heart/awaiting/await-scheduler.js +462 -0
  224. package/dist/heart/background-operations.js +281 -0
  225. package/dist/heart/bluebubbles-host-account.js +78 -0
  226. package/dist/heart/bridges/manager.js +478 -0
  227. package/dist/heart/bridges/state-machine.js +135 -0
  228. package/dist/heart/bridges/store.js +135 -0
  229. package/dist/heart/bundle-state.js +168 -0
  230. package/dist/heart/chat-interaction.js +69 -0
  231. package/dist/heart/commitments.js +135 -0
  232. package/dist/heart/config-registry.js +340 -0
  233. package/dist/heart/config.js +217 -149
  234. package/dist/heart/context-loss-gauntlet.js +387 -0
  235. package/dist/heart/context-loss-sentinel.js +1260 -0
  236. package/dist/heart/core.js +2920 -355
  237. package/dist/heart/cross-chat-delivery.js +153 -0
  238. package/dist/heart/daemon/agent-config-check.js +494 -0
  239. package/dist/heart/daemon/agent-discovery.js +382 -0
  240. package/dist/heart/daemon/agent-home.js +409 -0
  241. package/dist/heart/daemon/agent-service.js +542 -0
  242. package/dist/heart/daemon/agentic-repair.js +548 -0
  243. package/dist/heart/daemon/app-sessions-record.js +82 -0
  244. package/dist/heart/daemon/await-private-wake.js +59 -0
  245. package/dist/heart/daemon/bluebubbles-cli-integration.js +71 -0
  246. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  247. package/dist/heart/daemon/bluebubbles-host-protocol.js +433 -0
  248. package/dist/heart/daemon/bluebubbles-host.js +273 -0
  249. package/dist/heart/daemon/boot-sync-probe.js +223 -0
  250. package/dist/heart/daemon/cadence.js +200 -0
  251. package/dist/heart/daemon/cli-arg-redaction.js +26 -0
  252. package/dist/heart/daemon/cli-commands/a2a.js +26 -0
  253. package/dist/heart/daemon/cli-commands/cards.js +68 -0
  254. package/dist/heart/daemon/cli-commands/coding-tools.js +13 -0
  255. package/dist/heart/daemon/cli-commands/desk.js +43 -0
  256. package/dist/heart/daemon/cli-commands/dns.js +13 -0
  257. package/dist/heart/daemon/cli-commands/entry-points.js +182 -0
  258. package/dist/heart/daemon/cli-commands/failure-code.js +11 -0
  259. package/dist/heart/daemon/cli-commands/friends.js +18 -0
  260. package/dist/heart/daemon/cli-commands/habits.js +15 -0
  261. package/dist/heart/daemon/cli-commands/lifecycle.js +42 -0
  262. package/dist/heart/daemon/cli-commands/mail.js +11 -0
  263. package/dist/heart/daemon/cli-commands/mind.js +25 -0
  264. package/dist/heart/daemon/cli-commands/presence.js +28 -0
  265. package/dist/heart/daemon/cli-commands/providers.js +20 -0
  266. package/dist/heart/daemon/cli-commands/rsvp.js +20 -0
  267. package/dist/heart/daemon/cli-commands/shepherd.js +17 -0
  268. package/dist/heart/daemon/cli-commands/vault.js +23 -0
  269. package/dist/heart/daemon/cli-defaults.js +997 -0
  270. package/dist/heart/daemon/cli-desk.js +346 -0
  271. package/dist/heart/daemon/cli-exec.js +9660 -0
  272. package/dist/heart/daemon/cli-gate.js +198 -0
  273. package/dist/heart/daemon/cli-help.js +800 -0
  274. package/dist/heart/daemon/cli-manifest.js +115 -0
  275. package/dist/heart/daemon/cli-parse.js +3635 -0
  276. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  277. package/dist/heart/daemon/cli-render.js +816 -0
  278. package/dist/heart/daemon/cli-types.js +8 -0
  279. package/dist/heart/daemon/compile-cache.js +69 -0
  280. package/dist/heart/daemon/connect-bay.js +323 -0
  281. package/dist/heart/daemon/container-credential-bootstrap.js +273 -0
  282. package/dist/heart/daemon/container-healthcheck.js +123 -0
  283. package/dist/heart/daemon/container-runtime.js +97 -0
  284. package/dist/heart/daemon/container-spec-auditor-main.js +187 -0
  285. package/dist/heart/daemon/container-spec-auditor.js +261 -0
  286. package/dist/heart/daemon/daemon-bootstrap-startup.js +115 -0
  287. package/dist/heart/daemon/daemon-cli.js +30 -1051
  288. package/dist/heart/daemon/daemon-entry.js +1174 -12
  289. package/dist/heart/daemon/daemon-health.js +186 -0
  290. package/dist/heart/daemon/daemon-rollup.js +57 -0
  291. package/dist/heart/daemon/daemon-runtime-sync.js +346 -0
  292. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  293. package/dist/heart/daemon/daemon.js +2286 -40
  294. package/dist/heart/daemon/desk-admin.js +420 -0
  295. package/dist/heart/daemon/dns-workflow.js +394 -0
  296. package/dist/heart/daemon/doctor-types.js +8 -0
  297. package/dist/heart/daemon/doctor.js +1890 -0
  298. package/dist/heart/daemon/freshness.js +345 -0
  299. package/dist/heart/daemon/habit-private-wake.js +61 -0
  300. package/dist/heart/daemon/handoff-blockers.js +117 -0
  301. package/dist/heart/daemon/health-monitor.js +256 -12
  302. package/dist/heart/daemon/home-filesystem.js +93 -0
  303. package/dist/heart/daemon/hook-post-tool-use.js +149 -0
  304. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  305. package/dist/heart/daemon/hooks/bundle-meta.js +226 -0
  306. package/dist/heart/daemon/http-health-probe.js +80 -0
  307. package/dist/heart/daemon/human-command-screens.js +234 -0
  308. package/dist/heart/daemon/human-readiness.js +114 -0
  309. package/dist/heart/daemon/inner-status.js +78 -0
  310. package/dist/heart/daemon/interactive-repair.js +394 -0
  311. package/dist/heart/daemon/launchd.js +191 -0
  312. package/dist/heart/daemon/linux-service.js +382 -0
  313. package/dist/heart/daemon/log-tailer.js +82 -12
  314. package/dist/heart/daemon/logs-prune.js +132 -0
  315. package/dist/heart/daemon/mailroom-copy-proof.js +158 -0
  316. package/dist/heart/daemon/mcp-canary.js +525 -0
  317. package/dist/heart/daemon/message-router.js +80 -11
  318. package/dist/heart/daemon/migrate-to-desk.js +848 -0
  319. package/dist/heart/daemon/os-cron-deps.js +156 -0
  320. package/dist/heart/daemon/os-cron.js +50 -15
  321. package/dist/heart/daemon/ouro-bot-entry.js +8 -3
  322. package/dist/heart/daemon/ouro-cli-main.js +50 -0
  323. package/dist/heart/daemon/ouro-entry.js +43 -20
  324. package/dist/heart/daemon/owner-alert-routes.js +159 -0
  325. package/dist/heart/daemon/owner-channel-outage.js +386 -0
  326. package/dist/heart/daemon/plugin-cli.js +432 -0
  327. package/dist/heart/daemon/portable-git-install.js +265 -0
  328. package/dist/heart/daemon/portable-git.js +179 -0
  329. package/dist/heart/daemon/presence-daemon.js +265 -0
  330. package/dist/heart/daemon/presence-roster.js +260 -0
  331. package/dist/heart/daemon/presence.js +469 -0
  332. package/dist/heart/daemon/process-manager.js +847 -53
  333. package/dist/heart/daemon/process-tree.js +109 -0
  334. package/dist/heart/daemon/provider-discovery.js +171 -0
  335. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  336. package/dist/heart/daemon/prunable-bundle.js +144 -0
  337. package/dist/heart/daemon/pulse.js +511 -0
  338. package/dist/heart/daemon/readiness-repair.js +365 -0
  339. package/dist/heart/daemon/run-hooks.js +39 -0
  340. package/dist/heart/daemon/runtime-logging.js +99 -16
  341. package/dist/heart/daemon/runtime-metadata.js +191 -0
  342. package/dist/{repertoire/tasks/lifecycle.js → heart/daemon/runtime-mode.js} +37 -39
  343. package/dist/heart/daemon/runtime-replacement-handoff.js +207 -0
  344. package/dist/heart/daemon/safe-mode.js +161 -0
  345. package/dist/heart/daemon/sanctuary-acceptance-adapter.js +2659 -0
  346. package/dist/heart/daemon/sanctuary-acceptance-harness.js +1832 -0
  347. package/dist/heart/daemon/sanctuary-acceptance-marker.js +267 -0
  348. package/dist/heart/daemon/sanctuary-acceptance-scenarios.js +956 -0
  349. package/dist/heart/daemon/sanctuary-authority-codec.js +86 -0
  350. package/dist/heart/daemon/sanctuary-authority-epoch.js +291 -0
  351. package/dist/heart/daemon/sanctuary-authority-installation.js +161 -0
  352. package/dist/heart/daemon/sanctuary-authority-ledger.js +241 -0
  353. package/dist/heart/daemon/sanctuary-authority-root-lifecycle.js +1370 -0
  354. package/dist/heart/daemon/sanctuary-authority-vault-migration.js +79 -0
  355. package/dist/heart/daemon/sanctuary-bundle-migration.js +974 -0
  356. package/dist/heart/daemon/sanctuary-host-authority.js +1008 -0
  357. package/dist/heart/daemon/sanctuary-host-detached-supervisor.js +493 -0
  358. package/dist/heart/daemon/sanctuary-host-executor.js +670 -0
  359. package/dist/heart/daemon/sanctuary-host-linux-kernel.js +334 -0
  360. package/dist/heart/daemon/sanctuary-host-supervisor-entry.js +210 -0
  361. package/dist/heart/daemon/sanctuary-host-supervisor.js +95 -0
  362. package/dist/heart/daemon/sanctuary-package-management.js +113 -0
  363. package/dist/heart/daemon/sanctuary-scheduler-liveness.js +227 -0
  364. package/dist/heart/daemon/sanctuary-scheduler-origin.js +132 -0
  365. package/dist/heart/daemon/sanctuary-telegram-authority-entry.js +481 -0
  366. package/dist/heart/daemon/sanctuary-telegram-authority-gateway.js +614 -0
  367. package/dist/heart/daemon/sanctuary-telegram-authority-service.js +763 -0
  368. package/dist/heart/daemon/sanctuary-telegram-test-driver-entry.js +97 -0
  369. package/dist/heart/daemon/sanctuary-telegram-test-driver.js +294 -0
  370. package/dist/heart/daemon/sense-manager.js +1108 -49
  371. package/dist/heart/daemon/session-id-resolver.js +131 -0
  372. package/dist/heart/daemon/skill-management-installer.js +94 -0
  373. package/dist/heart/daemon/socket-client.js +370 -0
  374. package/dist/heart/daemon/stale-bundle-prune.js +113 -0
  375. package/dist/heart/daemon/startup-tui.js +339 -0
  376. package/dist/heart/daemon/state-retention.js +234 -0
  377. package/dist/heart/daemon/supercronic-supervisor.js +282 -0
  378. package/dist/heart/daemon/task-scheduler.js +117 -39
  379. package/dist/heart/daemon/terminal-ui.js +503 -0
  380. package/dist/heart/daemon/thoughts.js +591 -0
  381. package/dist/heart/daemon/up-progress.js +366 -0
  382. package/dist/heart/daemon/vault-items.js +56 -0
  383. package/dist/heart/daemon/vault-outage.js +74 -0
  384. package/dist/heart/delegated-work-report.js +115 -0
  385. package/dist/heart/delegation.js +59 -0
  386. package/dist/heart/external-events/router.js +1556 -0
  387. package/dist/heart/failure-reports.js +398 -0
  388. package/dist/heart/file-lock.js +109 -0
  389. package/dist/heart/frontend-approval-runtime.js +506 -0
  390. package/dist/heart/frontend-journal.js +215 -0
  391. package/dist/heart/frontend-session-service.js +330 -0
  392. package/dist/heart/frontend-socket-client.js +173 -0
  393. package/dist/heart/frontend-socket.js +434 -0
  394. package/dist/heart/frontend-turn-errors.js +20 -0
  395. package/dist/heart/git-binary.js +115 -0
  396. package/dist/heart/habits/habit-cancel.js +810 -0
  397. package/dist/heart/habits/habit-lifecycle.js +1324 -0
  398. package/dist/heart/habits/habit-migration.js +194 -0
  399. package/dist/heart/habits/habit-parser.js +258 -0
  400. package/dist/heart/habits/habit-runtime-state.js +93 -0
  401. package/dist/heart/habits/habit-scheduler.js +678 -0
  402. package/dist/heart/habits/habit-session-summary.js +318 -0
  403. package/dist/heart/habits/habit-session.js +638 -0
  404. package/dist/heart/{daemon → hatch}/hatch-animation.js +10 -3
  405. package/dist/heart/{daemon → hatch}/hatch-flow.js +70 -129
  406. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  407. package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +2 -2
  408. package/dist/heart/{daemon → hatch}/specialist-prompt.js +18 -11
  409. package/dist/heart/hatch/specialist-tools.js +395 -0
  410. package/dist/heart/identity.js +456 -69
  411. package/dist/heart/kept-notes.js +289 -0
  412. package/dist/heart/kicks.js +2 -20
  413. package/dist/heart/letters/doors-tools.js +63 -0
  414. package/dist/heart/letters/doors.js +436 -0
  415. package/dist/heart/letters/letter-index.js +89 -0
  416. package/dist/heart/letters/letter.js +247 -0
  417. package/dist/heart/letters/store.js +210 -0
  418. package/dist/heart/letters/writer.js +298 -0
  419. package/dist/heart/machine-identity.js +175 -0
  420. package/dist/heart/mail-import-discovery.js +356 -0
  421. package/dist/heart/mcp/mcp-server.js +922 -0
  422. package/dist/heart/migrate-config.js +100 -0
  423. package/dist/heart/model-capabilities.js +130 -0
  424. package/dist/heart/model-limits.js +49 -0
  425. package/dist/heart/optional-packages.js +77 -0
  426. package/dist/heart/orientation-frame.js +393 -0
  427. package/dist/heart/platform.js +81 -0
  428. package/dist/heart/primitives.js +1 -1
  429. package/dist/heart/private-runtime/decision-renderer.js +158 -0
  430. package/dist/heart/private-runtime/index.js +18 -0
  431. package/dist/heart/private-runtime/ledger.js +212 -0
  432. package/dist/heart/private-runtime/policy.js +303 -0
  433. package/dist/heart/private-runtime/types.js +2 -0
  434. package/dist/heart/progress-story.js +42 -0
  435. package/dist/heart/provider-attempt.js +137 -0
  436. package/dist/heart/provider-binding-resolver.js +273 -0
  437. package/dist/heart/provider-credentials.js +449 -0
  438. package/dist/heart/provider-failover.js +311 -0
  439. package/dist/heart/provider-fallback.js +228 -0
  440. package/dist/heart/provider-models.js +96 -0
  441. package/dist/heart/provider-ping-child.js +125 -0
  442. package/dist/heart/provider-ping-entry.js +8 -0
  443. package/dist/heart/provider-ping.js +298 -0
  444. package/dist/heart/provider-readiness-cache.js +119 -0
  445. package/dist/heart/provider-visibility.js +188 -0
  446. package/dist/heart/providers/account-pool.js +717 -0
  447. package/dist/heart/providers/anthropic-token.js +131 -0
  448. package/dist/heart/providers/anthropic.js +431 -75
  449. package/dist/heart/providers/azure.js +107 -13
  450. package/dist/heart/providers/error-classification.js +129 -0
  451. package/dist/heart/providers/github-copilot.js +252 -0
  452. package/dist/heart/providers/minimax-vlm.js +189 -0
  453. package/dist/heart/providers/minimax.js +29 -7
  454. package/dist/heart/providers/openai-codex-token.js +349 -0
  455. package/dist/heart/providers/openai-codex.js +63 -39
  456. package/dist/heart/providers/openai-compatible.js +177 -0
  457. package/dist/heart/quota/fleet-readings.js +222 -0
  458. package/dist/heart/quota/tranche.js +59 -0
  459. package/dist/heart/reach-channel.js +85 -0
  460. package/dist/heart/reply-style.js +52 -0
  461. package/dist/heart/run-ledger.js +247 -0
  462. package/dist/heart/runtime-capability-check.js +170 -0
  463. package/dist/heart/runtime-credentials.js +647 -0
  464. package/dist/heart/runtime-cwd.js +87 -0
  465. package/dist/heart/sense-truth.js +26 -4
  466. package/dist/heart/sent-message-ledger.js +98 -0
  467. package/dist/heart/session-activity.js +239 -0
  468. package/dist/heart/session-events.js +1609 -0
  469. package/dist/heart/session-playback-cli-main.js +10 -0
  470. package/dist/heart/session-playback-cli.js +36 -0
  471. package/dist/heart/session-playback.js +231 -0
  472. package/dist/heart/session-redaction-repair-cli-main.js +34 -0
  473. package/dist/heart/session-redaction-repair.js +552 -0
  474. package/dist/heart/session-stats-cli-main.js +10 -0
  475. package/dist/heart/session-stats.js +183 -0
  476. package/dist/heart/session-transcript.js +133 -0
  477. package/dist/heart/shelf-claims.js +136 -0
  478. package/dist/heart/shepherd/custody-types.js +2 -0
  479. package/dist/heart/shepherd/mandates.js +352 -0
  480. package/dist/heart/shepherd/operation-commands.js +19 -0
  481. package/dist/heart/shepherd/operations.js +139 -0
  482. package/dist/heart/shepherd/supervision-read.js +131 -0
  483. package/dist/heart/shepherd/supervision.js +114 -0
  484. package/dist/heart/shepherd/types.js +2 -0
  485. package/dist/heart/shepherd-config.js +113 -0
  486. package/dist/heart/source-grounding.js +313 -0
  487. package/dist/heart/sqlite.js +18 -0
  488. package/dist/heart/start-of-turn-packet.js +372 -0
  489. package/dist/heart/steward-policy.js +656 -0
  490. package/dist/heart/streaming.js +726 -208
  491. package/dist/heart/structured-output.js +196 -0
  492. package/dist/heart/sync-classification.js +176 -0
  493. package/dist/heart/sync-health.js +152 -0
  494. package/dist/heart/sync-lock.js +431 -0
  495. package/dist/heart/sync.js +1583 -0
  496. package/dist/heart/target-resolution.js +127 -0
  497. package/dist/heart/tempo.js +93 -0
  498. package/dist/heart/temporal-view.js +41 -0
  499. package/dist/heart/termination-guard.js +27 -0
  500. package/dist/heart/timeouts.js +101 -0
  501. package/dist/heart/tool-activity-callbacks.js +59 -0
  502. package/dist/heart/tool-approval.js +382 -0
  503. package/dist/heart/tool-description.js +155 -0
  504. package/dist/heart/tool-friction.js +55 -0
  505. package/dist/heart/tool-images.js +42 -0
  506. package/dist/heart/tool-loop.js +206 -0
  507. package/dist/heart/tool-output-budget.js +41 -0
  508. package/dist/heart/turn-context.js +503 -0
  509. package/dist/heart/turn-coordinator.js +28 -0
  510. package/dist/heart/turn-execution-lease.js +78 -0
  511. package/dist/heart/turn-summary.js +216 -0
  512. package/dist/heart/versioning/host-self-update.js +118 -0
  513. package/dist/heart/versioning/ouro-bot-global-installer.js +129 -0
  514. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +3 -2
  515. package/dist/heart/versioning/ouro-path-installer.js +432 -0
  516. package/dist/heart/versioning/ouro-recovery-launcher.js +98 -0
  517. package/dist/heart/versioning/ouro-version-manager.js +432 -0
  518. package/dist/heart/versioning/release-sources.js +185 -0
  519. package/dist/heart/versioning/self-update-defaults.js +486 -0
  520. package/dist/heart/versioning/self-update.js +270 -0
  521. package/dist/heart/versioning/staged-restart.js +146 -0
  522. package/dist/heart/versioning/update-checker.js +88 -0
  523. package/dist/heart/versioning/update-hooks.js +160 -0
  524. package/dist/heart/versioning/update-state.js +134 -0
  525. package/dist/heart/versioning/updater-launchd.js +204 -0
  526. package/dist/heart/versioning/version-intent.js +114 -0
  527. package/dist/heart/versioning/wrapper-publish-guard.js +86 -0
  528. package/dist/heart/work-card.js +380 -0
  529. package/dist/mailroom/attention.js +167 -0
  530. package/dist/mailroom/autonomy.js +209 -0
  531. package/dist/mailroom/azure-sdk.js +27 -0
  532. package/dist/mailroom/blob-store.js +991 -0
  533. package/dist/mailroom/body-cache.js +61 -0
  534. package/dist/mailroom/cache-sync-cli.js +58 -0
  535. package/dist/mailroom/core.js +813 -0
  536. package/dist/mailroom/entry.js +169 -0
  537. package/dist/mailroom/file-store.js +568 -0
  538. package/dist/mailroom/hosted-cache-sync.js +384 -0
  539. package/dist/mailroom/mbox-import.js +393 -0
  540. package/dist/mailroom/migration.js +164 -0
  541. package/dist/mailroom/outbound.js +380 -0
  542. package/dist/mailroom/policy.js +263 -0
  543. package/dist/mailroom/reader.js +308 -0
  544. package/dist/mailroom/search-cache.js +513 -0
  545. package/dist/mailroom/search-relevance.js +319 -0
  546. package/dist/mailroom/smtp-ingress.js +176 -0
  547. package/dist/mailroom/source-state.js +176 -0
  548. package/dist/mailroom/sweep-orphans-cli.js +34 -0
  549. package/dist/mailroom/thread.js +109 -0
  550. package/dist/mailroom/travel-extract.js +89 -0
  551. package/dist/mind/bundle-manifest.js +37 -2
  552. package/dist/mind/context.js +352 -104
  553. package/dist/mind/desk-section.js +332 -0
  554. package/dist/mind/diary-integrity.js +60 -0
  555. package/dist/mind/{memory.js → diary.js} +96 -100
  556. package/dist/mind/embedding-provider.js +60 -0
  557. package/dist/mind/file-state.js +179 -0
  558. package/dist/mind/first-impressions.js +16 -2
  559. package/dist/mind/friend-link-codes.js +209 -0
  560. package/dist/mind/friend-merge.js +336 -0
  561. package/dist/mind/house-names.js +43 -0
  562. package/dist/mind/{associative-recall.js → note-search.js} +61 -60
  563. package/dist/mind/obligation-steering.js +227 -0
  564. package/dist/mind/outbound-record.js +176 -0
  565. package/dist/mind/pending.js +360 -10
  566. package/dist/mind/phrases.js +1 -0
  567. package/dist/mind/prompt-budget.js +511 -0
  568. package/dist/mind/prompt-refresh.js +3 -2
  569. package/dist/mind/prompt.js +1297 -191
  570. package/dist/mind/provenance-trust.js +26 -0
  571. package/dist/mind/record-paths.js +312 -0
  572. package/dist/mind/scrutiny.js +121 -0
  573. package/dist/mind/session-transaction.js +642 -0
  574. package/dist/mind/token-estimate.js +25 -12
  575. package/dist/mind/where-am-i.js +176 -0
  576. package/dist/nerves/cli-logging.js +22 -3
  577. package/dist/nerves/coverage/audit-rules.js +15 -6
  578. package/dist/nerves/coverage/audit.js +28 -2
  579. package/dist/nerves/coverage/cli-main.js +6 -1
  580. package/dist/nerves/coverage/cli.js +1 -1
  581. package/dist/nerves/coverage/contract.js +5 -5
  582. package/dist/nerves/coverage/file-completeness.js +153 -5
  583. package/dist/nerves/coverage/run-artifacts.js +56 -36
  584. package/dist/nerves/coverage/source-scanner.js +4 -4
  585. package/dist/nerves/event-buffer.js +111 -0
  586. package/dist/nerves/index.js +307 -9
  587. package/dist/nerves/observation.js +18 -0
  588. package/dist/nerves/redact.js +79 -0
  589. package/dist/nerves/review/cli-main.js +10 -0
  590. package/dist/nerves/review/cli.js +156 -0
  591. package/dist/nerves/review/core.js +159 -0
  592. package/dist/nerves/runtime.js +21 -2
  593. package/dist/repertoire/ado-client.js +15 -56
  594. package/dist/repertoire/ado-semantic.js +114 -40
  595. package/dist/repertoire/api-client.js +97 -0
  596. package/dist/repertoire/auth-required.js +22 -0
  597. package/dist/repertoire/bitwarden-native.js +458 -0
  598. package/dist/repertoire/bitwarden-store.js +1296 -0
  599. package/dist/repertoire/bundle-templates.js +71 -0
  600. package/dist/repertoire/bw-installer.js +268 -0
  601. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  602. package/dist/repertoire/coding/context-pack.js +331 -0
  603. package/dist/repertoire/coding/feedback.js +302 -0
  604. package/dist/repertoire/coding/index.js +63 -3
  605. package/dist/repertoire/coding/manager.js +237 -14
  606. package/dist/repertoire/coding/orca-client.js +194 -0
  607. package/dist/repertoire/coding/orca-manager.js +534 -0
  608. package/dist/repertoire/coding/router.js +124 -0
  609. package/dist/repertoire/coding/spawner.js +61 -14
  610. package/dist/repertoire/coding/tools.js +340 -24
  611. package/dist/repertoire/coding/workbench-client.js +272 -0
  612. package/dist/repertoire/coding/workbench-manager.js +404 -0
  613. package/dist/repertoire/commerce-errors.js +109 -0
  614. package/dist/repertoire/commerce-self-test.js +156 -0
  615. package/dist/repertoire/credential-access.js +183 -0
  616. package/dist/repertoire/desk/classifier.js +362 -0
  617. package/dist/repertoire/desk-mcp.js +204 -0
  618. package/dist/repertoire/duffel-client.js +185 -0
  619. package/dist/repertoire/github-client.js +14 -55
  620. package/dist/repertoire/graph-client.js +11 -52
  621. package/dist/repertoire/guardrails.js +1394 -0
  622. package/dist/repertoire/house-sweep.js +471 -0
  623. package/dist/repertoire/in-turn-tools-door.js +55 -0
  624. package/dist/repertoire/mcp-client.js +307 -0
  625. package/dist/repertoire/mcp-declared-tools.js +156 -0
  626. package/dist/repertoire/mcp-manager.js +514 -0
  627. package/dist/repertoire/mcp-tools.js +199 -0
  628. package/dist/repertoire/mcp-write-guard.js +85 -0
  629. package/dist/repertoire/plugin-mcp.js +175 -0
  630. package/dist/repertoire/plugins.js +253 -0
  631. package/dist/repertoire/relationship-authorization.js +322 -0
  632. package/dist/repertoire/sanctuary-container-policy.js +50 -0
  633. package/dist/repertoire/shell-sessions.js +136 -0
  634. package/dist/repertoire/skill-search.js +177 -0
  635. package/dist/repertoire/skill-summaries.js +129 -0
  636. package/dist/repertoire/skills.js +45 -24
  637. package/dist/repertoire/stripe-client.js +163 -0
  638. package/dist/repertoire/tool-arguments.js +180 -0
  639. package/dist/repertoire/tool-candidates.js +50 -0
  640. package/dist/repertoire/tool-catalog.js +228 -0
  641. package/dist/repertoire/tool-error-code.js +30 -0
  642. package/dist/repertoire/tool-limits.js +20 -0
  643. package/dist/repertoire/tool-results.js +29 -0
  644. package/dist/repertoire/tools-a2a.js +792 -0
  645. package/dist/repertoire/tools-app-sessions.js +219 -0
  646. package/dist/repertoire/tools-attachments.js +302 -0
  647. package/dist/repertoire/tools-awaiting.js +934 -0
  648. package/dist/repertoire/tools-base.js +88 -706
  649. package/dist/repertoire/tools-bridge.js +153 -0
  650. package/dist/repertoire/tools-bundle.js +998 -0
  651. package/dist/repertoire/tools-chat.js +185 -0
  652. package/dist/repertoire/tools-commerce.js +272 -0
  653. package/dist/repertoire/tools-config.js +199 -0
  654. package/dist/repertoire/tools-continuity.js +648 -0
  655. package/dist/repertoire/tools-credential.js +410 -0
  656. package/dist/repertoire/tools-escalation.js +98 -0
  657. package/dist/repertoire/tools-evolution.js +560 -0
  658. package/dist/repertoire/tools-files.js +521 -0
  659. package/dist/repertoire/tools-flight.js +313 -0
  660. package/dist/repertoire/tools-flow.js +171 -0
  661. package/dist/repertoire/tools-friend-link.js +65 -0
  662. package/dist/repertoire/tools-github.js +12 -10
  663. package/dist/repertoire/tools-habits.js +111 -0
  664. package/dist/repertoire/tools-house-care.js +190 -0
  665. package/dist/repertoire/tools-mail.js +1930 -0
  666. package/dist/repertoire/tools-notes.js +571 -0
  667. package/dist/repertoire/tools-obligations.js +187 -0
  668. package/dist/repertoire/tools-orientation.js +36 -0
  669. package/dist/repertoire/tools-record.js +497 -0
  670. package/dist/repertoire/tools-rsvp.js +148 -0
  671. package/dist/repertoire/tools-runtime.js +260 -0
  672. package/dist/repertoire/tools-sanctuary-host.js +213 -0
  673. package/dist/repertoire/tools-session.js +1198 -0
  674. package/dist/repertoire/tools-shell.js +275 -0
  675. package/dist/repertoire/tools-shepherd-guidance.js +183 -0
  676. package/dist/repertoire/tools-shepherd.js +369 -0
  677. package/dist/repertoire/tools-steward-policy.js +157 -0
  678. package/dist/repertoire/tools-stripe.js +244 -0
  679. package/dist/repertoire/tools-surface.js +557 -0
  680. package/dist/repertoire/tools-teams.js +79 -76
  681. package/dist/repertoire/tools-telegram-contacts.js +41 -0
  682. package/dist/repertoire/tools-travel.js +142 -0
  683. package/dist/repertoire/tools-trip.js +1041 -0
  684. package/dist/repertoire/tools-unraid.js +627 -0
  685. package/dist/repertoire/tools-user-profile.js +166 -0
  686. package/dist/repertoire/tools-vault.js +46 -0
  687. package/dist/repertoire/tools-voice-local.js +210 -0
  688. package/dist/repertoire/tools-voice.js +153 -0
  689. package/dist/repertoire/tools-web.js +238 -0
  690. package/dist/repertoire/tools.js +639 -133
  691. package/dist/repertoire/travel-api-client.js +463 -0
  692. package/dist/repertoire/unraid-client.js +155 -0
  693. package/dist/repertoire/unraid-restart.js +342 -0
  694. package/dist/repertoire/user-profile.js +131 -0
  695. package/dist/repertoire/vault-setup.js +298 -0
  696. package/dist/repertoire/vault-unlock.js +816 -0
  697. package/dist/rsvp/aisleplanner-client.js +354 -0
  698. package/dist/rsvp/cli.js +936 -0
  699. package/dist/rsvp/config.js +327 -0
  700. package/dist/rsvp/cutover.js +453 -0
  701. package/dist/rsvp/diagnostics.js +232 -0
  702. package/dist/rsvp/diff-renderer.js +176 -0
  703. package/dist/rsvp/habit-policy.js +109 -0
  704. package/dist/rsvp/habit-stage.js +122 -0
  705. package/dist/rsvp/incident-bundle.js +97 -0
  706. package/dist/rsvp/migration.js +204 -0
  707. package/dist/rsvp/native-habit-runner.js +621 -0
  708. package/dist/rsvp/outbound-state.js +628 -0
  709. package/dist/rsvp/query.js +118 -0
  710. package/dist/rsvp/replay.js +233 -0
  711. package/dist/rsvp/snapshot.js +232 -0
  712. package/dist/rsvp/spend-ledger.js +175 -0
  713. package/dist/scripts/claude-code-hook.js +41 -0
  714. package/dist/scripts/claude-code-stop-hook.js +48 -0
  715. package/dist/senses/a2a-entry.js +145 -0
  716. package/dist/senses/acp-server.js +386 -0
  717. package/dist/senses/app-sessions/client.js +128 -0
  718. package/dist/senses/app-sessions/digest-cards.js +263 -0
  719. package/dist/senses/app-sessions/digest-push.js +108 -0
  720. package/dist/senses/app-sessions/digest-sources.js +204 -0
  721. package/dist/senses/app-sessions/digest.js +284 -0
  722. package/dist/senses/app-sessions/run-command.js +51 -0
  723. package/dist/senses/app-sessions/sense.js +242 -0
  724. package/dist/senses/app-sessions/shepherd-cli.js +166 -0
  725. package/dist/senses/app-sessions/shepherd-rows.js +67 -0
  726. package/dist/senses/app-sessions/store.js +149 -0
  727. package/dist/senses/app-sessions/waiting-prompts.js +137 -0
  728. package/dist/senses/app-sessions/waiting-status.js +23 -0
  729. package/dist/senses/app-sessions-entry.js +87 -0
  730. package/dist/senses/attention-queue.js +186 -0
  731. package/dist/senses/await-turn-message.js +65 -0
  732. package/dist/senses/bluebubbles/active-turns.js +241 -0
  733. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  734. package/dist/senses/bluebubbles/attachment-download.js +143 -0
  735. package/dist/senses/bluebubbles/client.js +874 -0
  736. package/dist/senses/bluebubbles/context-packet.js +207 -0
  737. package/dist/senses/bluebubbles/context-smoke.js +144 -0
  738. package/dist/senses/bluebubbles/entry.js +80 -0
  739. package/dist/senses/bluebubbles/host-account-verifier.js +113 -0
  740. package/dist/senses/bluebubbles/inbound-log.js +127 -0
  741. package/dist/senses/bluebubbles/index.js +4701 -0
  742. package/dist/senses/bluebubbles/latest-turn.js +342 -0
  743. package/dist/senses/bluebubbles/media.js +255 -0
  744. package/dist/senses/bluebubbles/model.js +383 -0
  745. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +57 -6
  746. package/dist/senses/bluebubbles/outbound-state.js +335 -0
  747. package/dist/senses/bluebubbles/processed-log.js +133 -0
  748. package/dist/senses/bluebubbles/reactions.js +18 -0
  749. package/dist/senses/bluebubbles/replay.js +284 -0
  750. package/dist/senses/bluebubbles/runtime-state.js +160 -0
  751. package/dist/senses/bluebubbles/semantic-receipts.js +2014 -0
  752. package/dist/senses/bluebubbles/send-file.js +20 -0
  753. package/dist/senses/bluebubbles/send-health.js +126 -0
  754. package/dist/senses/bluebubbles/session-cleanup.js +72 -0
  755. package/dist/senses/bluebubbles/webhook-registration.js +257 -0
  756. package/dist/senses/bluebubbles-meta-guard.js +39 -0
  757. package/dist/senses/chat-file.js +75 -0
  758. package/dist/senses/cli/bracketed-paste.js +82 -0
  759. package/dist/senses/cli/image-paste.js +287 -0
  760. package/dist/senses/cli/image-ref-navigation.js +75 -0
  761. package/dist/senses/cli/ink-app.js +156 -0
  762. package/dist/senses/cli/inline-diff.js +64 -0
  763. package/dist/senses/cli/input-keys.js +209 -0
  764. package/dist/senses/cli/kill-ring.js +86 -0
  765. package/dist/senses/cli/message-list.js +51 -0
  766. package/dist/senses/cli/ouro-tui.js +633 -0
  767. package/dist/senses/cli/spinner-imperative.js +135 -0
  768. package/dist/senses/cli/spinner.js +101 -0
  769. package/dist/senses/cli/status-line.js +60 -0
  770. package/dist/senses/cli/streaming-markdown.js +526 -0
  771. package/dist/senses/cli/tool-display.js +85 -0
  772. package/dist/senses/cli/tool-render.js +85 -0
  773. package/dist/senses/cli/tui-store.js +252 -0
  774. package/dist/senses/cli/virtual-list.js +35 -0
  775. package/dist/senses/cli-entry.js +62 -9
  776. package/dist/senses/cli-layout.js +187 -0
  777. package/dist/senses/cli.js +828 -308
  778. package/dist/senses/commands.js +66 -3
  779. package/dist/senses/context-packet-ledger.js +367 -0
  780. package/dist/senses/context-packets.js +154 -0
  781. package/dist/senses/continuity.js +94 -0
  782. package/dist/senses/habit-lifecycle-guard.js +24 -0
  783. package/dist/senses/habit-turn-message.js +160 -0
  784. package/dist/senses/inbound-journal.js +186 -0
  785. package/dist/senses/ingress-evidence.js +2 -0
  786. package/dist/senses/mail-entry.js +69 -0
  787. package/dist/senses/mail.js +524 -0
  788. package/dist/senses/ordinary-owner-decision.js +98 -0
  789. package/dist/senses/pipeline.js +1426 -0
  790. package/dist/senses/private-runtime-worker.js +820 -0
  791. package/dist/senses/private-runtime.js +1648 -0
  792. package/dist/senses/proactive-content-guard.js +144 -0
  793. package/dist/senses/program-status.js +155 -0
  794. package/dist/senses/repeat-while.js +36 -0
  795. package/dist/senses/reply-gate.js +237 -0
  796. package/dist/senses/root-host-approval-port.js +345 -0
  797. package/dist/senses/root-host-approval-runtime.js +393 -0
  798. package/dist/senses/sanctuary-authority-resident.js +102 -0
  799. package/dist/senses/sanctuary-download-credit-presentation.js +31 -0
  800. package/dist/senses/sanctuary-full-visibility-contract.js +302 -0
  801. package/dist/senses/sanctuary-grounding.js +118 -0
  802. package/dist/senses/sanctuary-health-acceptance-probe-entry.js +21 -0
  803. package/dist/senses/sanctuary-health-acceptance-probe.js +802 -0
  804. package/dist/senses/sanctuary-health-runner.js +106 -0
  805. package/dist/senses/sanctuary-health.js +442 -0
  806. package/dist/senses/sanctuary-house.js +97 -0
  807. package/dist/senses/sanctuary-install-state-contract.js +169 -0
  808. package/dist/senses/sanctuary-interactive-control.js +410 -0
  809. package/dist/senses/sanctuary-media-catalog-contract.js +268 -0
  810. package/dist/senses/sanctuary-media-optimization.js +517 -0
  811. package/dist/senses/sanctuary-runtime.js +392 -0
  812. package/dist/senses/sanctuary-sab.js +85 -0
  813. package/dist/senses/sanctuary-storage-optimization-contract.js +32 -0
  814. package/dist/senses/sense-shutdown.js +72 -0
  815. package/dist/senses/shared-turn.js +840 -0
  816. package/dist/senses/shepherd/agent-presentation.js +88 -0
  817. package/dist/senses/shepherd/attention-page.js +166 -0
  818. package/dist/senses/shepherd/attention-sidebar.js +76 -0
  819. package/dist/senses/shepherd/attention.js +295 -0
  820. package/dist/senses/shepherd/checkin-config.js +76 -0
  821. package/dist/senses/shepherd/checkin-store.js +383 -0
  822. package/dist/senses/shepherd/client.js +196 -0
  823. package/dist/senses/shepherd/cmux.js +483 -0
  824. package/dist/senses/shepherd/composer.js +336 -0
  825. package/dist/senses/shepherd/conversation-hold.js +78 -0
  826. package/dist/senses/shepherd/feedback-reply.js +108 -0
  827. package/dist/senses/shepherd/feedback-source.js +20 -0
  828. package/dist/senses/shepherd/feedback-store.js +328 -0
  829. package/dist/senses/shepherd/feedback-submit.js +182 -0
  830. package/dist/senses/shepherd/feedback-worker.js +208 -0
  831. package/dist/senses/shepherd/guidance.js +273 -0
  832. package/dist/senses/shepherd/herdr.js +427 -0
  833. package/dist/senses/shepherd/host.js +14 -0
  834. package/dist/senses/shepherd/human-decision-guard.js +29 -0
  835. package/dist/senses/shepherd/judge-evaluation-command.js +185 -0
  836. package/dist/senses/shepherd/judge-evaluation-entry.js +20 -0
  837. package/dist/senses/shepherd/judge-evaluation.js +144 -0
  838. package/dist/senses/shepherd/judge.js +210 -0
  839. package/dist/senses/shepherd/notice-outbox.js +254 -0
  840. package/dist/senses/shepherd/observation-publisher.js +320 -0
  841. package/dist/senses/shepherd/operations-defaults.js +86 -0
  842. package/dist/senses/shepherd/operations.js +159 -0
  843. package/dist/senses/shepherd/owner-notice.js +496 -0
  844. package/dist/senses/shepherd/prompt-state.js +60 -0
  845. package/dist/senses/shepherd/recovery.js +543 -0
  846. package/dist/senses/shepherd/redact.js +66 -0
  847. package/dist/senses/shepherd/returns.js +79 -0
  848. package/dist/senses/shepherd/sense.js +862 -0
  849. package/dist/senses/shepherd/shepherd-judge-corpus-v1.json +170 -0
  850. package/dist/senses/shepherd/surface.js +125 -0
  851. package/dist/senses/shepherd/target-binding.js +13 -0
  852. package/dist/senses/shepherd/terminal-process.js +147 -0
  853. package/dist/senses/shepherd-entry.js +98 -0
  854. package/dist/senses/surface-tool.js +121 -0
  855. package/dist/senses/teams-attachments.js +68 -0
  856. package/dist/senses/teams-entry.js +80 -9
  857. package/dist/senses/teams-image.js +128 -0
  858. package/dist/senses/teams-inbound.js +76 -0
  859. package/dist/senses/teams-off-turn.js +199 -0
  860. package/dist/senses/teams-outbox.js +249 -0
  861. package/dist/senses/teams.js +1664 -229
  862. package/dist/senses/telegram-admission.js +700 -0
  863. package/dist/senses/telegram-approval-relay.js +293 -0
  864. package/dist/senses/telegram-approval-runtime.js +831 -0
  865. package/dist/senses/telegram-attachments.js +128 -0
  866. package/dist/senses/telegram-audit-ledger.js +220 -0
  867. package/dist/senses/telegram-authority-transport.js +233 -0
  868. package/dist/senses/telegram-chat-actions.js +57 -0
  869. package/dist/senses/telegram-client.js +1896 -0
  870. package/dist/senses/telegram-effect-adapter.js +892 -0
  871. package/dist/senses/telegram-entry.js +87 -0
  872. package/dist/senses/telegram-handoff.js +150 -0
  873. package/dist/senses/telegram-identity-key.js +143 -0
  874. package/dist/senses/telegram-markdown.js +331 -0
  875. package/dist/senses/telegram-owner-route.js +129 -0
  876. package/dist/senses/telegram.js +2799 -0
  877. package/dist/senses/terminal-handoff.js +44 -0
  878. package/dist/senses/trust-gate.js +207 -2
  879. package/dist/senses/turn-attempts.js +171 -0
  880. package/dist/senses/turn-watch.js +268 -0
  881. package/dist/senses/voice/audio-playback.js +237 -0
  882. package/dist/senses/voice/audio-routing.js +119 -0
  883. package/dist/senses/voice/call-auth.js +250 -0
  884. package/dist/senses/voice/elevenlabs.js +202 -0
  885. package/dist/senses/voice/floor-control.js +431 -0
  886. package/dist/senses/voice/floor-controller.js +115 -0
  887. package/dist/senses/voice/golden-path.js +116 -0
  888. package/dist/senses/voice/index.js +29 -0
  889. package/dist/senses/voice/local-audio-control.js +344 -0
  890. package/dist/senses/voice/local-audio-devices.js +516 -0
  891. package/dist/senses/voice/local-audio-disclosure.js +174 -0
  892. package/dist/senses/voice/local-audio-identity.js +103 -0
  893. package/dist/senses/voice/local-audio-join.js +325 -0
  894. package/dist/senses/voice/local-audio-mute.js +199 -0
  895. package/dist/senses/voice/local-audio-notify.js +124 -0
  896. package/dist/senses/voice/local-audio-prompts.js +116 -0
  897. package/dist/senses/voice/local-audio-transport.js +427 -0
  898. package/dist/senses/voice/local-audio.js +281 -0
  899. package/dist/senses/voice/local-media-stream.js +145 -0
  900. package/dist/senses/voice/meeting.js +113 -0
  901. package/dist/senses/voice/outbound.js +190 -0
  902. package/dist/senses/voice/phone.js +33 -0
  903. package/dist/senses/voice/playback.js +139 -0
  904. package/dist/senses/voice/process-guards.js +51 -0
  905. package/dist/senses/voice/realtime-eval.js +496 -0
  906. package/dist/senses/voice/realtime-tool-schema.js +195 -0
  907. package/dist/senses/voice/realtime-trace.js +531 -0
  908. package/dist/senses/voice/realtime-utterances.js +158 -0
  909. package/dist/senses/voice/transcript.js +70 -0
  910. package/dist/senses/voice/turn.js +219 -0
  911. package/dist/senses/voice/twilio-phone-runtime.js +836 -0
  912. package/dist/senses/voice/twilio-phone.js +5660 -0
  913. package/dist/senses/voice/types.js +2 -0
  914. package/dist/senses/voice/utterances.js +207 -0
  915. package/dist/senses/voice/whisper.js +153 -0
  916. package/dist/senses/voice-entry.js +84 -0
  917. package/dist/senses/voice-realtime-eval-command.js +99 -0
  918. package/dist/senses/voice-realtime-eval-entry.js +25 -0
  919. package/dist/senses/voice-twilio-entry.js +88 -0
  920. package/dist/trips/core.js +138 -0
  921. package/dist/trips/store.js +265 -0
  922. package/dist/util/frontmatter.js +69 -0
  923. package/node_modules/@ouro.bot/friends/LICENSE +201 -0
  924. package/node_modules/@ouro.bot/friends/README.md +687 -0
  925. package/node_modules/@ouro.bot/friends/actions/generated/mcp.json +1105 -0
  926. package/node_modules/@ouro.bot/friends/changelog.json +197 -0
  927. package/node_modules/@ouro.bot/friends/dist/a2a-client/a2a-message.d.ts +39 -0
  928. package/node_modules/@ouro.bot/friends/dist/a2a-client/a2a-message.js +54 -0
  929. package/node_modules/@ouro.bot/friends/dist/a2a-client/adapter.d.ts +117 -0
  930. package/node_modules/@ouro.bot/friends/dist/a2a-client/adapter.js +202 -0
  931. package/node_modules/@ouro.bot/friends/dist/a2a-client/agent-card.d.ts +50 -0
  932. package/node_modules/@ouro.bot/friends/dist/a2a-client/agent-card.js +32 -0
  933. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-key.d.ts +38 -0
  934. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-key.js +120 -0
  935. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-verifier.d.ts +195 -0
  936. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-verifier.js +342 -0
  937. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-web.d.ts +26 -0
  938. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-web.js +140 -0
  939. package/node_modules/@ouro.bot/friends/dist/a2a-client/envelope-binding.d.ts +62 -0
  940. package/node_modules/@ouro.bot/friends/dist/a2a-client/envelope-binding.js +83 -0
  941. package/node_modules/@ouro.bot/friends/dist/a2a-client/index.d.ts +26 -0
  942. package/node_modules/@ouro.bot/friends/dist/a2a-client/index.js +82 -0
  943. package/node_modules/@ouro.bot/friends/dist/a2a-client/jcs.d.ts +5 -0
  944. package/node_modules/@ouro.bot/friends/dist/a2a-client/jcs.js +84 -0
  945. package/node_modules/@ouro.bot/friends/dist/a2a-client/reachability.d.ts +22 -0
  946. package/node_modules/@ouro.bot/friends/dist/a2a-client/reachability.js +17 -0
  947. package/node_modules/@ouro.bot/friends/dist/a2a-client/roster-verify.d.ts +15 -0
  948. package/node_modules/@ouro.bot/friends/dist/a2a-client/roster-verify.js +61 -0
  949. package/node_modules/@ouro.bot/friends/dist/a2a-client/seal.d.ts +47 -0
  950. package/node_modules/@ouro.bot/friends/dist/a2a-client/seal.js +95 -0
  951. package/node_modules/@ouro.bot/friends/dist/a2a-client/sealed-envelope.d.ts +58 -0
  952. package/node_modules/@ouro.bot/friends/dist/a2a-client/sealed-envelope.js +113 -0
  953. package/node_modules/@ouro.bot/friends/dist/a2a-client/sign.d.ts +42 -0
  954. package/node_modules/@ouro.bot/friends/dist/a2a-client/sign.js +87 -0
  955. package/node_modules/@ouro.bot/friends/dist/a2a-client/sodium.d.ts +5 -0
  956. package/node_modules/@ouro.bot/friends/dist/a2a-client/sodium.js +19 -0
  957. package/node_modules/@ouro.bot/friends/dist/account-roster.d.ts +52 -0
  958. package/node_modules/@ouro.bot/friends/dist/account-roster.js +108 -0
  959. package/node_modules/@ouro.bot/friends/dist/agent-peer.d.ts +26 -0
  960. package/node_modules/@ouro.bot/friends/dist/agent-peer.js +138 -0
  961. package/node_modules/@ouro.bot/friends/dist/audit.d.ts +42 -0
  962. package/node_modules/@ouro.bot/friends/dist/audit.js +86 -0
  963. package/node_modules/@ouro.bot/friends/dist/channel.d.ts +16 -0
  964. package/node_modules/@ouro.bot/friends/dist/channel.js +172 -0
  965. package/node_modules/@ouro.bot/friends/dist/connect-authority.d.ts +43 -0
  966. package/node_modules/@ouro.bot/friends/dist/connect-authority.js +84 -0
  967. package/node_modules/@ouro.bot/friends/dist/connect.d.ts +56 -0
  968. package/node_modules/@ouro.bot/friends/dist/connect.js +163 -0
  969. package/node_modules/@ouro.bot/friends/dist/consent.d.ts +34 -0
  970. package/node_modules/@ouro.bot/friends/dist/consent.js +65 -0
  971. package/node_modules/@ouro.bot/friends/dist/coordination.d.ts +116 -0
  972. package/node_modules/@ouro.bot/friends/dist/coordination.js +329 -0
  973. package/node_modules/@ouro.bot/friends/dist/delegation-grant.d.ts +21 -0
  974. package/node_modules/@ouro.bot/friends/dist/delegation-grant.js +39 -0
  975. package/node_modules/@ouro.bot/friends/dist/file-bundle.d.ts +17 -0
  976. package/node_modules/@ouro.bot/friends/dist/file-bundle.js +27 -0
  977. package/node_modules/@ouro.bot/friends/dist/friend-lookup.d.ts +9 -0
  978. package/node_modules/@ouro.bot/friends/dist/friend-lookup.js +69 -0
  979. package/node_modules/@ouro.bot/friends/dist/grant-store-file.d.ts +19 -0
  980. package/node_modules/@ouro.bot/friends/dist/grant-store-file.js +157 -0
  981. package/node_modules/@ouro.bot/friends/dist/grant-store.d.ts +7 -0
  982. package/node_modules/@ouro.bot/friends/dist/grant-store.js +8 -0
  983. package/node_modules/@ouro.bot/friends/dist/grants.d.ts +43 -0
  984. package/node_modules/@ouro.bot/friends/dist/grants.js +100 -0
  985. package/node_modules/@ouro.bot/friends/dist/group-context.d.ts +21 -0
  986. package/node_modules/@ouro.bot/friends/dist/group-context.js +145 -0
  987. package/node_modules/@ouro.bot/friends/dist/identity.d.ts +17 -0
  988. package/node_modules/@ouro.bot/friends/dist/identity.js +68 -0
  989. package/node_modules/@ouro.bot/friends/dist/index.d.ts +73 -0
  990. package/node_modules/@ouro.bot/friends/dist/index.js +164 -0
  991. package/node_modules/@ouro.bot/friends/dist/link-identity.d.ts +14 -0
  992. package/node_modules/@ouro.bot/friends/dist/link-identity.js +157 -0
  993. package/node_modules/@ouro.bot/friends/dist/mailbox/index.d.ts +105 -0
  994. package/node_modules/@ouro.bot/friends/dist/mailbox/index.js +205 -0
  995. package/node_modules/@ouro.bot/friends/dist/mcp/bin.d.ts +2 -0
  996. package/node_modules/@ouro.bot/friends/dist/mcp/bin.js +17 -0
  997. package/node_modules/@ouro.bot/friends/dist/mcp/dispatch.d.ts +40 -0
  998. package/node_modules/@ouro.bot/friends/dist/mcp/dispatch.js +744 -0
  999. package/node_modules/@ouro.bot/friends/dist/mcp/index.d.ts +6 -0
  1000. package/node_modules/@ouro.bot/friends/dist/mcp/index.js +14 -0
  1001. package/node_modules/@ouro.bot/friends/dist/mcp/run-main.d.ts +7 -0
  1002. package/node_modules/@ouro.bot/friends/dist/mcp/run-main.js +59 -0
  1003. package/node_modules/@ouro.bot/friends/dist/mcp/schemas.d.ts +10 -0
  1004. package/node_modules/@ouro.bot/friends/dist/mcp/schemas.js +23 -0
  1005. package/node_modules/@ouro.bot/friends/dist/mcp/server.d.ts +30 -0
  1006. package/node_modules/@ouro.bot/friends/dist/mcp/server.js +195 -0
  1007. package/node_modules/@ouro.bot/friends/dist/message.d.ts +93 -0
  1008. package/node_modules/@ouro.bot/friends/dist/message.js +129 -0
  1009. package/node_modules/@ouro.bot/friends/dist/mission-result.d.ts +89 -0
  1010. package/node_modules/@ouro.bot/friends/dist/mission-result.js +207 -0
  1011. package/node_modules/@ouro.bot/friends/dist/mission-share.d.ts +94 -0
  1012. package/node_modules/@ouro.bot/friends/dist/mission-share.js +232 -0
  1013. package/node_modules/@ouro.bot/friends/dist/mission-store-file.d.ts +18 -0
  1014. package/node_modules/@ouro.bot/friends/dist/mission-store-file.js +169 -0
  1015. package/node_modules/@ouro.bot/friends/dist/mission-store.d.ts +10 -0
  1016. package/node_modules/@ouro.bot/friends/dist/mission-store.js +9 -0
  1017. package/node_modules/@ouro.bot/friends/dist/missions.d.ts +31 -0
  1018. package/node_modules/@ouro.bot/friends/dist/missions.js +99 -0
  1019. package/node_modules/@ouro.bot/friends/dist/notes.d.ts +11 -0
  1020. package/node_modules/@ouro.bot/friends/dist/notes.js +90 -0
  1021. package/node_modules/@ouro.bot/friends/dist/observability.d.ts +27 -0
  1022. package/node_modules/@ouro.bot/friends/dist/observability.js +31 -0
  1023. package/node_modules/@ouro.bot/friends/dist/outcomes.d.ts +9 -0
  1024. package/node_modules/@ouro.bot/friends/dist/outcomes.js +51 -0
  1025. package/node_modules/@ouro.bot/friends/dist/resolver.d.ts +59 -0
  1026. package/node_modules/@ouro.bot/friends/dist/resolver.js +276 -0
  1027. package/node_modules/@ouro.bot/friends/dist/results.d.ts +10 -0
  1028. package/node_modules/@ouro.bot/friends/dist/results.js +2 -0
  1029. package/node_modules/@ouro.bot/friends/dist/room.d.ts +22 -0
  1030. package/node_modules/@ouro.bot/friends/dist/room.js +40 -0
  1031. package/node_modules/@ouro.bot/friends/dist/roster-store-file.d.ts +16 -0
  1032. package/node_modules/@ouro.bot/friends/dist/roster-store-file.js +125 -0
  1033. package/node_modules/@ouro.bot/friends/dist/roster-store-memory.d.ts +9 -0
  1034. package/node_modules/@ouro.bot/friends/dist/roster-store-memory.js +20 -0
  1035. package/node_modules/@ouro.bot/friends/dist/roster-store.d.ts +29 -0
  1036. package/node_modules/@ouro.bot/friends/dist/roster-store.js +9 -0
  1037. package/node_modules/@ouro.bot/friends/dist/roster-verifier.d.ts +23 -0
  1038. package/node_modules/@ouro.bot/friends/dist/roster-verifier.js +47 -0
  1039. package/node_modules/@ouro.bot/friends/dist/share.d.ts +113 -0
  1040. package/node_modules/@ouro.bot/friends/dist/share.js +314 -0
  1041. package/node_modules/@ouro.bot/friends/dist/standing.d.ts +83 -0
  1042. package/node_modules/@ouro.bot/friends/dist/standing.js +111 -0
  1043. package/node_modules/@ouro.bot/friends/dist/store-file.d.ts +82 -0
  1044. package/node_modules/@ouro.bot/friends/dist/store-file.js +1089 -0
  1045. package/node_modules/@ouro.bot/friends/dist/store.d.ts +43 -0
  1046. package/node_modules/@ouro.bot/friends/dist/tokens.d.ts +10 -0
  1047. package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/tokens.js +7 -4
  1048. package/node_modules/@ouro.bot/friends/dist/trust-explanation.d.ts +22 -0
  1049. package/node_modules/@ouro.bot/friends/dist/trust-explanation.js +90 -0
  1050. package/node_modules/@ouro.bot/friends/dist/trust-mutation.d.ts +16 -0
  1051. package/node_modules/@ouro.bot/friends/dist/trust-mutation.js +67 -0
  1052. package/node_modules/@ouro.bot/friends/dist/types.d.ts +333 -0
  1053. package/node_modules/@ouro.bot/friends/dist/types.js +55 -0
  1054. package/node_modules/@ouro.bot/friends/dist/util/cap-string.d.ts +7 -0
  1055. package/node_modules/@ouro.bot/friends/dist/util/cap-string.js +35 -0
  1056. package/node_modules/@ouro.bot/friends/dist/util/safe-id.d.ts +1 -0
  1057. package/node_modules/@ouro.bot/friends/dist/util/safe-id.js +10 -0
  1058. package/node_modules/@ouro.bot/friends/dist/verifier.d.ts +11 -0
  1059. package/node_modules/@ouro.bot/friends/dist/verifier.js +29 -0
  1060. package/node_modules/@ouro.bot/friends/dist/whoami.d.ts +7 -0
  1061. package/node_modules/@ouro.bot/friends/dist/whoami.js +39 -0
  1062. package/node_modules/@ouro.bot/friends/package.json +82 -0
  1063. package/node_modules/libsodium/LICENSE +16 -0
  1064. package/node_modules/libsodium/README.md +281 -0
  1065. package/node_modules/libsodium/dist/modules/libsodium.js +1 -0
  1066. package/node_modules/libsodium/dist/modules-esm/libsodium.mjs +1 -0
  1067. package/node_modules/libsodium/package.json +54 -0
  1068. package/node_modules/libsodium-wrappers/LICENSE +16 -0
  1069. package/node_modules/libsodium-wrappers/README.md +281 -0
  1070. package/node_modules/libsodium-wrappers/dist/modules/libsodium-wrappers.d.ts +2155 -0
  1071. package/node_modules/libsodium-wrappers/dist/modules/libsodium-wrappers.js +1 -0
  1072. package/node_modules/libsodium-wrappers/dist/modules-esm/libsodium-wrappers.d.mts +2743 -0
  1073. package/node_modules/libsodium-wrappers/dist/modules-esm/libsodium-wrappers.mjs +1 -0
  1074. package/node_modules/libsodium-wrappers/package.json +74 -0
  1075. package/npm-shrinkwrap.json +8789 -0
  1076. package/package.json +106 -13
  1077. package/skills/agent-commerce.md +116 -0
  1078. package/skills/browser-navigation.md +120 -0
  1079. package/skills/commerce-setup-guide.md +116 -0
  1080. package/skills/commerce-setup.md +87 -0
  1081. package/skills/configure-dev-tools.md +99 -0
  1082. package/skills/sense-setup.md +56 -0
  1083. package/skills/travel-planning.md +141 -0
  1084. package/vendor/desk/.claude-plugin/plugin.json +35 -0
  1085. package/vendor/desk/.mcp.claude-codex.json +28 -0
  1086. package/vendor/desk/.mcp.copilot.json +16 -0
  1087. package/vendor/desk/.ouro-desk.json +6 -0
  1088. package/vendor/desk/CHANGELOG.md +7644 -0
  1089. package/vendor/desk/README.md +195 -0
  1090. package/vendor/desk/activation/README.md +98 -0
  1091. package/vendor/desk/activation/copilot-root.flattened-bundle.json +38 -0
  1092. package/vendor/desk/activation/desk.activation.json +251 -0
  1093. package/vendor/desk/activation/host-capability-evidence.md +46 -0
  1094. package/vendor/desk/activation/support-matrix.json +84 -0
  1095. package/vendor/desk/agency.json +20 -0
  1096. package/vendor/desk/agents/observer.agent.md +26 -0
  1097. package/vendor/desk/agents/observer.md +29 -0
  1098. package/vendor/desk/agents/worker.agent.md +32 -0
  1099. package/vendor/desk/agents/worker.md +40 -0
  1100. package/vendor/desk/artifacts/tombstones/tombstone.schema.json +53 -0
  1101. package/vendor/desk/artifacts/tombstones/tombstones.jsonl +1 -0
  1102. package/vendor/desk/changelog.d/README.md +12 -0
  1103. package/vendor/desk/docs/agent-files.md +104 -0
  1104. package/vendor/desk/docs/agentic-engineering-v2-rfc.md +206 -0
  1105. package/vendor/desk/docs/agentic-engineering-v3-rfc.md +109 -0
  1106. package/vendor/desk/docs/browser-remote-desktops.md +69 -0
  1107. package/vendor/desk/docs/dependency-activation-stories-and-criteria.md +500 -0
  1108. package/vendor/desk/docs/evaluation-packet.md +363 -0
  1109. package/vendor/desk/docs/factory-local-capture.md +651 -0
  1110. package/vendor/desk/docs/factory-store-playbook.md +927 -0
  1111. package/vendor/desk/docs/images/factory-site.png +0 -0
  1112. package/vendor/desk/docs/issue-drains.md +81 -0
  1113. package/vendor/desk/docs/lfs-inspection.md +55 -0
  1114. package/vendor/desk/docs/preview-diagnostics.md +11 -0
  1115. package/vendor/desk/docs/relays.md +88 -0
  1116. package/vendor/desk/docs/schedules.md +69 -0
  1117. package/vendor/desk/docs/search-recovery.md +22 -0
  1118. package/vendor/desk/docs/session-labels.md +157 -0
  1119. package/vendor/desk/docs/session-retention.md +125 -0
  1120. package/vendor/desk/docs/sessions.md +17 -0
  1121. package/vendor/desk/docs/stalled-nudges.md +54 -0
  1122. package/vendor/desk/docs/webhooks.md +80 -0
  1123. package/vendor/desk/docs/workspace-tidy.md +74 -0
  1124. package/vendor/desk/hooks/boot-checks.cjs +7 -0
  1125. package/vendor/desk/hooks/claude-session-start.cjs +123 -0
  1126. package/vendor/desk/hooks/compatible-node.cjs +97 -0
  1127. package/vendor/desk/hooks/copilot-boot-prompt.cjs +69 -0
  1128. package/vendor/desk/hooks/copilot-durable-files.cjs +8 -0
  1129. package/vendor/desk/hooks/copilot-hooks.json +61 -0
  1130. package/vendor/desk/hooks/copilot-intake-context.cjs +5 -0
  1131. package/vendor/desk/hooks/copilot-lane-model.cjs +8 -0
  1132. package/vendor/desk/hooks/copilot-session-start.cjs +264 -0
  1133. package/vendor/desk/hooks/copilot-skill-current.cjs +28 -0
  1134. package/vendor/desk/hooks/factory-end.cjs +5 -0
  1135. package/vendor/desk/hooks/factory-start.cjs +27 -0
  1136. package/vendor/desk/hooks/hooks.json +40 -0
  1137. package/vendor/desk/hooks/lib/boot-checks.cjs +643 -0
  1138. package/vendor/desk/hooks/lib/child-agent.cjs +14 -0
  1139. package/vendor/desk/hooks/lib/copilot-intake-context.cjs +73 -0
  1140. package/vendor/desk/hooks/lib/current-release.cjs +162 -0
  1141. package/vendor/desk/hooks/lib/delivery-stop.cjs +326 -0
  1142. package/vendor/desk/hooks/lib/detach-worker.cjs +43 -0
  1143. package/vendor/desk/hooks/lib/durable-files.cjs +102 -0
  1144. package/vendor/desk/hooks/lib/factory-end.cjs +330 -0
  1145. package/vendor/desk/hooks/lib/lane-model.cjs +82 -0
  1146. package/vendor/desk/hooks/lib/node-required.cjs +56 -0
  1147. package/vendor/desk/hooks/lib/orca-session-title.cjs +60 -0
  1148. package/vendor/desk/hooks/lib/session-end.cjs +30 -0
  1149. package/vendor/desk/hooks/lib/sync-end.cjs +89 -0
  1150. package/vendor/desk/hooks/loop-start.cjs +105 -0
  1151. package/vendor/desk/hooks/node-missing.sh +78 -0
  1152. package/vendor/desk/hooks/orca-session-title.cjs +8 -0
  1153. package/vendor/desk/hooks/session-end.cjs +8 -0
  1154. package/vendor/desk/mcp/README.md +277 -0
  1155. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1156. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1157. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1158. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1159. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1160. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1161. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1162. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1163. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1164. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1165. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1166. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1167. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1168. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1169. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1170. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/support-matrix.json +72 -0
  1171. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1172. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1173. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1174. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1175. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1176. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1177. package/vendor/desk/mcp/artifacts/runtime-deps/README.md +25 -0
  1178. package/vendor/desk/mcp/bootstrap.cjs +787 -0
  1179. package/vendor/desk/mcp/docs/private-feedback.md +13 -0
  1180. package/vendor/desk/mcp/idle-proxy.cjs +431 -0
  1181. package/vendor/desk/mcp/index.js +813 -0
  1182. package/vendor/desk/mcp/package-lock.json +3717 -0
  1183. package/vendor/desk/mcp/package.json +44 -0
  1184. package/vendor/desk/mcp/scripts/agency-desk-channel.js +7 -0
  1185. package/vendor/desk/mcp/scripts/build-runtime-deps-pack.js +5 -0
  1186. package/vendor/desk/mcp/scripts/crew.js +89 -0
  1187. package/vendor/desk/mcp/scripts/drains-launcher.mjs +330 -0
  1188. package/vendor/desk/mcp/scripts/drains.js +5 -0
  1189. package/vendor/desk/mcp/scripts/factory.js +666 -0
  1190. package/vendor/desk/mcp/scripts/file-desk-problem.js +9 -0
  1191. package/vendor/desk/mcp/scripts/finish-commit.js +7 -0
  1192. package/vendor/desk/mcp/scripts/lfs.js +37 -0
  1193. package/vendor/desk/mcp/scripts/local-recovery.js +445 -0
  1194. package/vendor/desk/mcp/scripts/migrations.js +11 -0
  1195. package/vendor/desk/mcp/scripts/private-view.js +177 -0
  1196. package/vendor/desk/mcp/scripts/resolve-desk-root.js +105 -0
  1197. package/vendor/desk/mcp/scripts/session-boot.js +22 -0
  1198. package/vendor/desk/mcp/scripts/session-retention.js +5 -0
  1199. package/vendor/desk/mcp/scripts/session-sync.js +10 -0
  1200. package/vendor/desk/mcp/scripts/sessions.js +5 -0
  1201. package/vendor/desk/mcp/scripts/sync-push.js +13 -0
  1202. package/vendor/desk/mcp/scripts/tidy-status.js +8 -0
  1203. package/vendor/desk/mcp/scripts/verify-runtime-deps-pack.js +5 -0
  1204. package/vendor/desk/mcp/src/actions/desk-read.actions.mts +73 -0
  1205. package/vendor/desk/mcp/src/actions/desk-session.actions.mts +57 -0
  1206. package/vendor/desk/mcp/src/actions/desk-web.actions.mts +52 -0
  1207. package/vendor/desk/mcp/src/actions/desk.actions.mts +5 -0
  1208. package/vendor/desk/mcp/src/actions/generated/desk/OuroActions.swift +649 -0
  1209. package/vendor/desk/mcp/src/actions/generated/desk/OuroActionsReins.swift +61 -0
  1210. package/vendor/desk/mcp/src/actions/generated/desk/actions.json +315 -0
  1211. package/vendor/desk/mcp/src/actions/generated/desk/commands.json +145 -0
  1212. package/vendor/desk/mcp/src/actions/generated/desk/mcp.json +289 -0
  1213. package/vendor/desk/mcp/src/actions/generated/desk/web.ts +59 -0
  1214. package/vendor/desk/mcp/src/actions/generated/desk/webmcp.json +250 -0
  1215. package/vendor/desk/mcp/src/actions/generated/desk-web/OuroActions.swift +241 -0
  1216. package/vendor/desk/mcp/src/actions/generated/desk-web/OuroActionsReins.swift +25 -0
  1217. package/vendor/desk/mcp/src/actions/generated/desk-web/actions.json +73 -0
  1218. package/vendor/desk/mcp/src/actions/generated/desk-web/commands.json +53 -0
  1219. package/vendor/desk/mcp/src/actions/generated/desk-web/mcp.json +83 -0
  1220. package/vendor/desk/mcp/src/actions/generated/desk-web/web.ts +47 -0
  1221. package/vendor/desk/mcp/src/actions/generated/desk-web/webmcp.json +81 -0
  1222. package/vendor/desk/mcp/src/actions/served.js +5 -0
  1223. package/vendor/desk/mcp/src/activation/admit.js +77 -0
  1224. package/vendor/desk/mcp/src/activation/failures.js +65 -0
  1225. package/vendor/desk/mcp/src/activation/readiness-policy.js +102 -0
  1226. package/vendor/desk/mcp/src/activation/schema.js +17 -0
  1227. package/vendor/desk/mcp/src/activation/superpowers-context.js +274 -0
  1228. package/vendor/desk/mcp/src/activation/validate.js +540 -0
  1229. package/vendor/desk/mcp/src/artifacts/tombstones.js +61 -0
  1230. package/vendor/desk/mcp/src/crew/initiative.js +287 -0
  1231. package/vendor/desk/mcp/src/crew/workspace.js +1285 -0
  1232. package/vendor/desk/mcp/src/db/init.js +75 -0
  1233. package/vendor/desk/mcp/src/db/schema.sql +83 -0
  1234. package/vendor/desk/mcp/src/desk/active-tasks.js +408 -0
  1235. package/vendor/desk/mcp/src/desk/card-commit-guard.js +282 -0
  1236. package/vendor/desk/mcp/src/desk/cleanup-index.js +53 -0
  1237. package/vendor/desk/mcp/src/desk/content-home.js +262 -0
  1238. package/vendor/desk/mcp/src/desk/crew-config.js +102 -0
  1239. package/vendor/desk/mcp/src/desk/crew-member.js +196 -0
  1240. package/vendor/desk/mcp/src/desk/crew-roster.js +151 -0
  1241. package/vendor/desk/mcp/src/desk/frontmatter-lite.js +228 -0
  1242. package/vendor/desk/mcp/src/desk/gh-logins.js +109 -0
  1243. package/vendor/desk/mcp/src/desk/handles.js +123 -0
  1244. package/vendor/desk/mcp/src/desk/handoff-reference.js +35 -0
  1245. package/vendor/desk/mcp/src/desk/improvement-authority.js +3 -0
  1246. package/vendor/desk/mcp/src/desk/improvement-cards.js +704 -0
  1247. package/vendor/desk/mcp/src/desk/improvement-person.js +51 -0
  1248. package/vendor/desk/mcp/src/desk/lifecycle.js +16 -0
  1249. package/vendor/desk/mcp/src/desk/machine-desks.js +119 -0
  1250. package/vendor/desk/mcp/src/desk/naming.js +333 -0
  1251. package/vendor/desk/mcp/src/desk/organization.js +592 -0
  1252. package/vendor/desk/mcp/src/desk/resources.js +274 -0
  1253. package/vendor/desk/mcp/src/desk/runtime-resolver.js +30 -0
  1254. package/vendor/desk/mcp/src/desk/scratch-paths.js +44 -0
  1255. package/vendor/desk/mcp/src/desk/step-delivery.js +140 -0
  1256. package/vendor/desk/mcp/src/desk/steps.js +263 -0
  1257. package/vendor/desk/mcp/src/desk/tidy.js +930 -0
  1258. package/vendor/desk/mcp/src/desk/unsigned-deliveries.js +359 -0
  1259. package/vendor/desk/mcp/src/factory/agent-types.js +45 -0
  1260. package/vendor/desk/mcp/src/factory/andon-watch.js +109 -0
  1261. package/vendor/desk/mcp/src/factory/binding.js +612 -0
  1262. package/vendor/desk/mcp/src/factory/boot-check.js +645 -0
  1263. package/vendor/desk/mcp/src/factory/capture-classify.js +158 -0
  1264. package/vendor/desk/mcp/src/factory/capture-count.js +183 -0
  1265. package/vendor/desk/mcp/src/factory/capture-flush.js +268 -0
  1266. package/vendor/desk/mcp/src/factory/capture-publish.js +141 -0
  1267. package/vendor/desk/mcp/src/factory/capture-schema.js +193 -0
  1268. package/vendor/desk/mcp/src/factory/capture-sweep.js +239 -0
  1269. package/vendor/desk/mcp/src/factory/catch-point.js +60 -0
  1270. package/vendor/desk/mcp/src/factory/commit-resolve.js +94 -0
  1271. package/vendor/desk/mcp/src/factory/consent-answer.js +37 -0
  1272. package/vendor/desk/mcp/src/factory/context-capability.js +15 -0
  1273. package/vendor/desk/mcp/src/factory/context-outbox.js +885 -0
  1274. package/vendor/desk/mcp/src/factory/context-run.js +386 -0
  1275. package/vendor/desk/mcp/src/factory/context-schema.js +249 -0
  1276. package/vendor/desk/mcp/src/factory/copilot-turn-index.js +93 -0
  1277. package/vendor/desk/mcp/src/factory/copilot-usage.js +148 -0
  1278. package/vendor/desk/mcp/src/factory/credential.js +45 -0
  1279. package/vendor/desk/mcp/src/factory/derive-claude.js +960 -0
  1280. package/vendor/desk/mcp/src/factory/derive-codex.js +734 -0
  1281. package/vendor/desk/mcp/src/factory/derive-common.js +279 -0
  1282. package/vendor/desk/mcp/src/factory/derive-copilot.js +1057 -0
  1283. package/vendor/desk/mcp/src/factory/derive-run.js +807 -0
  1284. package/vendor/desk/mcp/src/factory/desk-problem-file.js +310 -0
  1285. package/vendor/desk/mcp/src/factory/desk-problem-fingerprint.js +70 -0
  1286. package/vendor/desk/mcp/src/factory/desk-problem-known.js +246 -0
  1287. package/vendor/desk/mcp/src/factory/desk-problem-template.js +107 -0
  1288. package/vendor/desk/mcp/src/factory/desk-repo.js +1223 -0
  1289. package/vendor/desk/mcp/src/factory/desk-task-line.js +28 -0
  1290. package/vendor/desk/mcp/src/factory/desk-visibility.js +48 -0
  1291. package/vendor/desk/mcp/src/factory/end-hook.js +14 -0
  1292. package/vendor/desk/mcp/src/factory/evaluate-kick.js +164 -0
  1293. package/vendor/desk/mcp/src/factory/evaluate-run.js +678 -0
  1294. package/vendor/desk/mcp/src/factory/evaluator-step.js +484 -0
  1295. package/vendor/desk/mcp/src/factory/filer-launch.js +79 -0
  1296. package/vendor/desk/mcp/src/factory/flush-health.js +26 -0
  1297. package/vendor/desk/mcp/src/factory/flush.js +1758 -0
  1298. package/vendor/desk/mcp/src/factory/focus.js +326 -0
  1299. package/vendor/desk/mcp/src/factory/headless-flag.cjs +32 -0
  1300. package/vendor/desk/mcp/src/factory/headless-flag.js +25 -0
  1301. package/vendor/desk/mcp/src/factory/headless-ledger.js +743 -0
  1302. package/vendor/desk/mcp/src/factory/headless.js +567 -0
  1303. package/vendor/desk/mcp/src/factory/held-route.js +93 -0
  1304. package/vendor/desk/mcp/src/factory/host-flags.js +36 -0
  1305. package/vendor/desk/mcp/src/factory/improvement-verify.js +429 -0
  1306. package/vendor/desk/mcp/src/factory/kaizen-file.js +231 -0
  1307. package/vendor/desk/mcp/src/factory/label-binding.js +90 -0
  1308. package/vendor/desk/mcp/src/factory/label-schema.js +426 -0
  1309. package/vendor/desk/mcp/src/factory/local-status.js +368 -0
  1310. package/vendor/desk/mcp/src/factory/loop-conditions.js +121 -0
  1311. package/vendor/desk/mcp/src/factory/loop-health.js +500 -0
  1312. package/vendor/desk/mcp/src/factory/loop-slot.js +90 -0
  1313. package/vendor/desk/mcp/src/factory/loop-status.js +100 -0
  1314. package/vendor/desk/mcp/src/factory/loop-switch.cjs +14 -0
  1315. package/vendor/desk/mcp/src/factory/loop-worker-state.js +96 -0
  1316. package/vendor/desk/mcp/src/factory/loop-worker.js +290 -0
  1317. package/vendor/desk/mcp/src/factory/marker.js +61 -0
  1318. package/vendor/desk/mcp/src/factory/mirror-step.js +145 -0
  1319. package/vendor/desk/mcp/src/factory/os-protect.js +243 -0
  1320. package/vendor/desk/mcp/src/factory/outbox.js +2231 -0
  1321. package/vendor/desk/mcp/src/factory/outcome.js +431 -0
  1322. package/vendor/desk/mcp/src/factory/pipeline/andon.js +319 -0
  1323. package/vendor/desk/mcp/src/factory/pipeline/attention-rollup.js +158 -0
  1324. package/vendor/desk/mcp/src/factory/pipeline/attention.js +146 -0
  1325. package/vendor/desk/mcp/src/factory/pipeline/build.js +299 -0
  1326. package/vendor/desk/mcp/src/factory/pipeline/compare.js +148 -0
  1327. package/vendor/desk/mcp/src/factory/pipeline/formulas.js +652 -0
  1328. package/vendor/desk/mcp/src/factory/pipeline/kaizen.js +387 -0
  1329. package/vendor/desk/mcp/src/factory/pipeline/lifecycle-clocks.js +345 -0
  1330. package/vendor/desk/mcp/src/factory/pipeline/normalize.js +73 -0
  1331. package/vendor/desk/mcp/src/factory/pipeline/number-states.js +154 -0
  1332. package/vendor/desk/mcp/src/factory/pipeline/outcomes.js +268 -0
  1333. package/vendor/desk/mcp/src/factory/pipeline/report.js +737 -0
  1334. package/vendor/desk/mcp/src/factory/pipeline/rollups.js +883 -0
  1335. package/vendor/desk/mcp/src/factory/pipeline/stretches.js +523 -0
  1336. package/vendor/desk/mcp/src/factory/pipeline/timeline.js +199 -0
  1337. package/vendor/desk/mcp/src/factory/pipeline/validate-pr.js +238 -0
  1338. package/vendor/desk/mcp/src/factory/pipeline/versions.js +42 -0
  1339. package/vendor/desk/mcp/src/factory/pipeline/walk.js +1177 -0
  1340. package/vendor/desk/mcp/src/factory/plugin-registry.js +72 -0
  1341. package/vendor/desk/mcp/src/factory/plugin-sources.cjs +249 -0
  1342. package/vendor/desk/mcp/src/factory/pr-green.js +77 -0
  1343. package/vendor/desk/mcp/src/factory/process-lock.js +142 -0
  1344. package/vendor/desk/mcp/src/factory/proof-session.js +75 -0
  1345. package/vendor/desk/mcp/src/factory/publish.js +637 -0
  1346. package/vendor/desk/mcp/src/factory/published-schema.js +648 -0
  1347. package/vendor/desk/mcp/src/factory/reconcile-reasons.js +22 -0
  1348. package/vendor/desk/mcp/src/factory/reconcile-step.js +251 -0
  1349. package/vendor/desk/mcp/src/factory/reconcile.js +808 -0
  1350. package/vendor/desk/mcp/src/factory/release-version.js +134 -0
  1351. package/vendor/desk/mcp/src/factory/repo-name.js +13 -0
  1352. package/vendor/desk/mcp/src/factory/retention.js +60 -0
  1353. package/vendor/desk/mcp/src/factory/route-desk.js +40 -0
  1354. package/vendor/desk/mcp/src/factory/route-issues.js +251 -0
  1355. package/vendor/desk/mcp/src/factory/route-local.js +264 -0
  1356. package/vendor/desk/mcp/src/factory/schema.js +957 -0
  1357. package/vendor/desk/mcp/src/factory/session-kind.js +16 -0
  1358. package/vendor/desk/mcp/src/factory/session-lifetime.js +56 -0
  1359. package/vendor/desk/mcp/src/factory/session-route.js +183 -0
  1360. package/vendor/desk/mcp/src/factory/shell-git.js +500 -0
  1361. package/vendor/desk/mcp/src/factory/store-issues.js +143 -0
  1362. package/vendor/desk/mcp/src/factory/store-route.js +208 -0
  1363. package/vendor/desk/mcp/src/factory/test-state-guard.js +103 -0
  1364. package/vendor/desk/mcp/src/factory/time.js +36 -0
  1365. package/vendor/desk/mcp/src/factory/tool-issue-file.js +84 -0
  1366. package/vendor/desk/mcp/src/factory/tool-kinds.js +87 -0
  1367. package/vendor/desk/mcp/src/factory/triage-schema.js +233 -0
  1368. package/vendor/desk/mcp/src/factory/windows-acl.js +679 -0
  1369. package/vendor/desk/mcp/src/indexer/chunk.js +232 -0
  1370. package/vendor/desk/mcp/src/indexer/discover.js +442 -0
  1371. package/vendor/desk/mcp/src/indexer/exclusions.js +247 -0
  1372. package/vendor/desk/mcp/src/indexer/index.js +167 -0
  1373. package/vendor/desk/mcp/src/indexer/refs.js +0 -0
  1374. package/vendor/desk/mcp/src/indexer/text-hash.js +18 -0
  1375. package/vendor/desk/mcp/src/lib/ouro-actions/actions.claims.json +75 -0
  1376. package/vendor/desk/mcp/src/lib/ouro-actions/dist-manifest.json +70 -0
  1377. package/vendor/desk/mcp/src/lib/ouro-actions/ouro-actions.mts +1416 -0
  1378. package/vendor/desk/mcp/src/lib/ouro-ui/LICENSE +21 -0
  1379. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/ax-claims.ts +191 -0
  1380. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/ax-command.ts +1040 -0
  1381. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/checks.ts +343 -0
  1382. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/cli.ts +240 -0
  1383. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/component.ts +430 -0
  1384. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/dev-commands.ts +204 -0
  1385. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/doctor.ts +126 -0
  1386. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/effects.ts +68 -0
  1387. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/exit-codes.ts +75 -0
  1388. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/help.ts +220 -0
  1389. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/mcp.ts +268 -0
  1390. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/outcome.ts +265 -0
  1391. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/output.ts +67 -0
  1392. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/precise-copy.ts +235 -0
  1393. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/problem.ts +124 -0
  1394. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/surfaces.kit.mts +8 -0
  1395. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/surfaces.ts +568 -0
  1396. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/terminal.ts +245 -0
  1397. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/voice.ts +136 -0
  1398. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/wait.ts +226 -0
  1399. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/work-event.ts +181 -0
  1400. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/xray.kit.mts +18 -0
  1401. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/xray.ts +2110 -0
  1402. package/vendor/desk/mcp/src/package-metadata.js +20 -0
  1403. package/vendor/desk/mcp/src/protected/legacy-ledger.js +55 -0
  1404. package/vendor/desk/mcp/src/readiness/leftovers.js +75 -0
  1405. package/vendor/desk/mcp/src/readiness/process-start.js +149 -0
  1406. package/vendor/desk/mcp/src/runtime/admission-worker.js +194 -0
  1407. package/vendor/desk/mcp/src/runtime/admission.js +177 -0
  1408. package/vendor/desk/mcp/src/runtime/agency-desk-channel.js +342 -0
  1409. package/vendor/desk/mcp/src/runtime/agents-md.js +62 -0
  1410. package/vendor/desk/mcp/src/runtime/append-lane.js +68 -0
  1411. package/vendor/desk/mcp/src/runtime/argv-safe-reason.js +55 -0
  1412. package/vendor/desk/mcp/src/runtime/boot-dependencies.js +75 -0
  1413. package/vendor/desk/mcp/src/runtime/boot-text.js +504 -0
  1414. package/vendor/desk/mcp/src/runtime/boot.js +1676 -0
  1415. package/vendor/desk/mcp/src/runtime/bootstrap.js +1455 -0
  1416. package/vendor/desk/mcp/src/runtime/chunked-import.js +102 -0
  1417. package/vendor/desk/mcp/src/runtime/copilot-commit-trailer.js +133 -0
  1418. package/vendor/desk/mcp/src/runtime/copilot-session.js +155 -0
  1419. package/vendor/desk/mcp/src/runtime/deliver.js +506 -0
  1420. package/vendor/desk/mcp/src/runtime/desk-channel.js +86 -0
  1421. package/vendor/desk/mcp/src/runtime/desk-failure.js +26 -0
  1422. package/vendor/desk/mcp/src/runtime/desk-health.js +168 -0
  1423. package/vendor/desk/mcp/src/runtime/desk-session.js +1451 -0
  1424. package/vendor/desk/mcp/src/runtime/diagnostic-server.js +72 -0
  1425. package/vendor/desk/mcp/src/runtime/diagnostics.js +241 -0
  1426. package/vendor/desk/mcp/src/runtime/drains-cli.js +195 -0
  1427. package/vendor/desk/mcp/src/runtime/drains.js +1220 -0
  1428. package/vendor/desk/mcp/src/runtime/elsewhere-note.js +9 -0
  1429. package/vendor/desk/mcp/src/runtime/failure-evidence.js +21 -0
  1430. package/vendor/desk/mcp/src/runtime/fast-refs.js +209 -0
  1431. package/vendor/desk/mcp/src/runtime/filer-throttle.js +66 -0
  1432. package/vendor/desk/mcp/src/runtime/focused-card.js +147 -0
  1433. package/vendor/desk/mcp/src/runtime/front-door.js +204 -0
  1434. package/vendor/desk/mcp/src/runtime/gate-wait.js +2 -0
  1435. package/vendor/desk/mcp/src/runtime/git-inspection.js +201 -0
  1436. package/vendor/desk/mcp/src/runtime/git-read-worker.js +157 -0
  1437. package/vendor/desk/mcp/src/runtime/health.js +50 -0
  1438. package/vendor/desk/mcp/src/runtime/hooks.js +353 -0
  1439. package/vendor/desk/mcp/src/runtime/hosted.js +165 -0
  1440. package/vendor/desk/mcp/src/runtime/inbox.js +102 -0
  1441. package/vendor/desk/mcp/src/runtime/index-drift.js +118 -0
  1442. package/vendor/desk/mcp/src/runtime/last-start.js +133 -0
  1443. package/vendor/desk/mcp/src/runtime/lesson-section.js +92 -0
  1444. package/vendor/desk/mcp/src/runtime/lessons-shelf.js +100 -0
  1445. package/vendor/desk/mcp/src/runtime/lfs.js +319 -0
  1446. package/vendor/desk/mcp/src/runtime/native-path.js +12 -0
  1447. package/vendor/desk/mcp/src/runtime/newest-release.js +197 -0
  1448. package/vendor/desk/mcp/src/runtime/node-selection.js +233 -0
  1449. package/vendor/desk/mcp/src/runtime/orca-session-title.js +225 -0
  1450. package/vendor/desk/mcp/src/runtime/other-sessions.js +183 -0
  1451. package/vendor/desk/mcp/src/runtime/pending-migrations.js +657 -0
  1452. package/vendor/desk/mcp/src/runtime/plugin-update.js +215 -0
  1453. package/vendor/desk/mcp/src/runtime/pluginless-runtimes.js +34 -0
  1454. package/vendor/desk/mcp/src/runtime/pr-publication.js +252 -0
  1455. package/vendor/desk/mcp/src/runtime/preview-snapshot.js +23 -0
  1456. package/vendor/desk/mcp/src/runtime/publication-mode.js +19 -0
  1457. package/vendor/desk/mcp/src/runtime/relays.js +983 -0
  1458. package/vendor/desk/mcp/src/runtime/release-alert.js +148 -0
  1459. package/vendor/desk/mcp/src/runtime/remote-identity.js +162 -0
  1460. package/vendor/desk/mcp/src/runtime/resolve-here.js +4 -0
  1461. package/vendor/desk/mcp/src/runtime/runtime-deps-cli.js +65 -0
  1462. package/vendor/desk/mcp/src/runtime/runtime-deps.js +1109 -0
  1463. package/vendor/desk/mcp/src/runtime/runtime-identity.js +22 -0
  1464. package/vendor/desk/mcp/src/runtime/runtime-swap.js +101 -0
  1465. package/vendor/desk/mcp/src/runtime/schedules.js +235 -0
  1466. package/vendor/desk/mcp/src/runtime/session-activity.js +190 -0
  1467. package/vendor/desk/mcp/src/runtime/session-label.js +30 -0
  1468. package/vendor/desk/mcp/src/runtime/session-retention.js +662 -0
  1469. package/vendor/desk/mcp/src/runtime/session-sync.js +333 -0
  1470. package/vendor/desk/mcp/src/runtime/session-trailer.js +126 -0
  1471. package/vendor/desk/mcp/src/runtime/sessions-cli.js +301 -0
  1472. package/vendor/desk/mcp/src/runtime/signoff-listed.js +81 -0
  1473. package/vendor/desk/mcp/src/runtime/skills.js +76 -0
  1474. package/vendor/desk/mcp/src/runtime/stale-card-lead.js +52 -0
  1475. package/vendor/desk/mcp/src/runtime/stale-desk-refresh.js +198 -0
  1476. package/vendor/desk/mcp/src/runtime/stale-desk.js +219 -0
  1477. package/vendor/desk/mcp/src/runtime/stalled.js +255 -0
  1478. package/vendor/desk/mcp/src/runtime/standing-authority.js +79 -0
  1479. package/vendor/desk/mcp/src/runtime/startup-boot.js +341 -0
  1480. package/vendor/desk/mcp/src/runtime/startup-resolve.js +140 -0
  1481. package/vendor/desk/mcp/src/runtime/state-branch.js +203 -0
  1482. package/vendor/desk/mcp/src/runtime/status-compact.js +165 -0
  1483. package/vendor/desk/mcp/src/runtime/status-inspection-child.js +26 -0
  1484. package/vendor/desk/mcp/src/runtime/status-inspection.js +147 -0
  1485. package/vendor/desk/mcp/src/runtime/status-root.js +39 -0
  1486. package/vendor/desk/mcp/src/runtime/sync-worker.js +913 -0
  1487. package/vendor/desk/mcp/src/runtime/test-state-guard.js +107 -0
  1488. package/vendor/desk/mcp/src/runtime/unmerged-saves.js +273 -0
  1489. package/vendor/desk/mcp/src/runtime/workspace-claim.js +53 -0
  1490. package/vendor/desk/mcp/src/runtime/workspace-evidence.js +96 -0
  1491. package/vendor/desk/mcp/src/runtime/workspace-tidy.js +509 -0
  1492. package/vendor/desk/mcp/src/search/direct-lexical.js +54 -0
  1493. package/vendor/desk/mcp/src/search/embedder.js +108 -0
  1494. package/vendor/desk/mcp/src/search/engine.js +406 -0
  1495. package/vendor/desk/mcp/src/search/files-router.js +22 -0
  1496. package/vendor/desk/mcp/src/search/old-index.js +46 -0
  1497. package/vendor/desk/mcp/src/search/vectors.js +60 -0
  1498. package/vendor/desk/mcp/src/server.js +390 -0
  1499. package/vendor/desk/mcp/src/tool-names.js +71 -0
  1500. package/vendor/desk/mcp/src/tool-refusal.cjs +35 -0
  1501. package/vendor/desk/mcp/src/tool-schema-parts.js +12 -0
  1502. package/vendor/desk/mcp/src/tool-schemas.js +320 -0
  1503. package/vendor/desk/mcp/src/tools/_card-commit.js +148 -0
  1504. package/vendor/desk/mcp/src/tools/archive-links.js +188 -0
  1505. package/vendor/desk/mcp/src/tools/archive-move.js +18 -0
  1506. package/vendor/desk/mcp/src/tools/archive-native-session.js +728 -0
  1507. package/vendor/desk/mcp/src/tools/archive-state.js +513 -0
  1508. package/vendor/desk/mcp/src/tools/delivery-gate.js +251 -0
  1509. package/vendor/desk/mcp/src/tools/desk-save.js +449 -0
  1510. package/vendor/desk/mcp/src/tools/doctor.js +122 -0
  1511. package/vendor/desk/mcp/src/tools/done-evidence.js +260 -0
  1512. package/vendor/desk/mcp/src/tools/factory-context.js +204 -0
  1513. package/vendor/desk/mcp/src/tools/friction.js +332 -0
  1514. package/vendor/desk/mcp/src/tools/improvement.js +156 -0
  1515. package/vendor/desk/mcp/src/tools/lesson-lines.js +22 -0
  1516. package/vendor/desk/mcp/src/tools/lesson-owners.js +137 -0
  1517. package/vendor/desk/mcp/src/tools/lesson-team.js +169 -0
  1518. package/vendor/desk/mcp/src/tools/lesson.js +254 -0
  1519. package/vendor/desk/mcp/src/tools/local-only.js +151 -0
  1520. package/vendor/desk/mcp/src/tools/move.js +823 -0
  1521. package/vendor/desk/mcp/src/tools/native-stage-context.js +32 -0
  1522. package/vendor/desk/mcp/src/tools/note.js +267 -0
  1523. package/vendor/desk/mcp/src/tools/search.js +634 -0
  1524. package/vendor/desk/mcp/src/tools/shared-write.js +196 -0
  1525. package/vendor/desk/mcp/src/tools/sibling-desk.js +43 -0
  1526. package/vendor/desk/mcp/src/tools/status.js +236 -0
  1527. package/vendor/desk/mcp/src/tools/task-archive-due.js +9 -0
  1528. package/vendor/desk/mcp/src/tools/task-archived-resource.js +53 -0
  1529. package/vendor/desk/mcp/src/tools/task-body.js +141 -0
  1530. package/vendor/desk/mcp/src/tools/task-focus.js +164 -0
  1531. package/vendor/desk/mcp/src/tools/task-log.js +80 -0
  1532. package/vendor/desk/mcp/src/tools/task-signoff.js +155 -0
  1533. package/vendor/desk/mcp/src/tools/task.js +1780 -0
  1534. package/vendor/desk/mcp/src/tools/track-row.js +89 -0
  1535. package/vendor/desk/mcp/src/tools/track.js +240 -0
  1536. package/vendor/desk/mcp/src/util/agency-session.cjs +29 -0
  1537. package/vendor/desk/mcp/src/util/archive-links.js +105 -0
  1538. package/vendor/desk/mcp/src/util/bash.js +36 -0
  1539. package/vendor/desk/mcp/src/util/capture-record.js +73 -0
  1540. package/vendor/desk/mcp/src/util/cas-commit.js +252 -0
  1541. package/vendor/desk/mcp/src/util/citations.js +54 -0
  1542. package/vendor/desk/mcp/src/util/created-dirs.js +71 -0
  1543. package/vendor/desk/mcp/src/util/deferred-tools.js +51 -0
  1544. package/vendor/desk/mcp/src/util/desk-owner.js +99 -0
  1545. package/vendor/desk/mcp/src/util/env-value.js +13 -0
  1546. package/vendor/desk/mcp/src/util/file-identity.js +40 -0
  1547. package/vendor/desk/mcp/src/util/finish-commit.js +145 -0
  1548. package/vendor/desk/mcp/src/util/fm.js +410 -0
  1549. package/vendor/desk/mcp/src/util/git-config-file.js +85 -0
  1550. package/vendor/desk/mcp/src/util/git-stage.js +440 -0
  1551. package/vendor/desk/mcp/src/util/main-publish.js +240 -0
  1552. package/vendor/desk/mcp/src/util/markdown-links.cjs +555 -0
  1553. package/vendor/desk/mcp/src/util/object-input.js +59 -0
  1554. package/vendor/desk/mcp/src/util/paths.js +647 -0
  1555. package/vendor/desk/mcp/src/util/rank.js +189 -0
  1556. package/vendor/desk/mcp/src/util/redact.js +92 -0
  1557. package/vendor/desk/mcp/src/util/remove-retry.js +35 -0
  1558. package/vendor/desk/mcp/src/util/rename-retry.js +73 -0
  1559. package/vendor/desk/mcp/src/util/route-around.js +265 -0
  1560. package/vendor/desk/mcp/src/util/shell-quote.js +18 -0
  1561. package/vendor/desk/mcp/src/util/startup-direction.js +124 -0
  1562. package/vendor/desk/mcp/src/util/state-ignore.js +33 -0
  1563. package/vendor/desk/mcp/src/util/tool-commits.js +64 -0
  1564. package/vendor/desk/mcp/src/util/unicode-16/LICENSE-MIT.txt +7 -0
  1565. package/vendor/desk/mcp/src/util/unicode-16/README.md +9 -0
  1566. package/vendor/desk/mcp/src/util/unicode-16/letter.cjs +1 -0
  1567. package/vendor/desk/mcp/src/util/unicode-16/mark.cjs +1 -0
  1568. package/vendor/desk/mcp/src/util/unicode-16/number.cjs +1 -0
  1569. package/vendor/desk/mcp/web-auth.cjs +1914 -0
  1570. package/vendor/desk/mcp/web-browser-discovery.cjs +53 -0
  1571. package/vendor/desk/mcp/web-catalog.json +34 -0
  1572. package/vendor/desk/mcp/web-launch.cjs +101 -0
  1573. package/vendor/desk/mcp/web-sso.cjs +52 -0
  1574. package/vendor/desk/mcp/web.cjs +1239 -0
  1575. package/vendor/desk/migrations/01-move-to-ourostack-desk.md +188 -0
  1576. package/vendor/desk/migrations/02-tidy-desk.md +87 -0
  1577. package/vendor/desk/migrations/03-desk-release-channel.md +38 -0
  1578. package/vendor/desk/optional/session-label/consumer.mjs +237 -0
  1579. package/vendor/desk/optional/session-label/extension.mjs +32 -0
  1580. package/vendor/desk/plugin.json +54 -0
  1581. package/vendor/desk/settings.json +3 -0
  1582. package/vendor/desk/skills/add-workspace-mcp/SKILL.md +180 -0
  1583. package/vendor/desk/skills/adopt-inflight-work/SKILL.md +212 -0
  1584. package/vendor/desk/skills/archive-workflow/SKILL.md +132 -0
  1585. package/vendor/desk/skills/content-routing/SKILL.md +95 -0
  1586. package/vendor/desk/skills/coordinating-lanes/SKILL.md +24 -0
  1587. package/vendor/desk/skills/core-meeting-capture/SKILL.md +47 -0
  1588. package/vendor/desk/skills/core-meeting-capture/references/capture-contract.md +175 -0
  1589. package/vendor/desk/skills/curator/SKILL.md +103 -0
  1590. package/vendor/desk/skills/delightful-decks/SKILL.md +67 -0
  1591. package/vendor/desk/skills/desk-problem/SKILL.md +87 -0
  1592. package/vendor/desk/skills/directory-structure/SKILL.md +169 -0
  1593. package/vendor/desk/skills/doc-review-rigor/SKILL.md +63 -0
  1594. package/vendor/desk/skills/draining-issues/SKILL.md +62 -0
  1595. package/vendor/desk/skills/evaluate-release/SKILL.md +96 -0
  1596. package/vendor/desk/skills/evidence-discipline/SKILL.md +146 -0
  1597. package/vendor/desk/skills/factory-evaluator/SKILL.md +122 -0
  1598. package/vendor/desk/skills/factory-task-context/SKILL.md +116 -0
  1599. package/vendor/desk/skills/factory-work/SKILL.md +16 -0
  1600. package/vendor/desk/skills/fast-honest-ci/SKILL.md +70 -0
  1601. package/vendor/desk/skills/fast-honest-ci/examples.md +49 -0
  1602. package/vendor/desk/skills/first-run-bootstrap/SKILL.md +95 -0
  1603. package/vendor/desk/skills/friction-management/SKILL.md +98 -0
  1604. package/vendor/desk/skills/git-hygiene/SKILL.md +259 -0
  1605. package/vendor/desk/skills/independent-review/SKILL.md +34 -0
  1606. package/vendor/desk/skills/interaction-style/SKILL.md +241 -0
  1607. package/vendor/desk/skills/lesson-capture/SKILL.md +85 -0
  1608. package/vendor/desk/skills/lesson-capture/agents-md-budget.mjs +61 -0
  1609. package/vendor/desk/skills/live-ui-iteration/SKILL.md +35 -0
  1610. package/vendor/desk/skills/online-evaluation/SKILL.md +81 -0
  1611. package/vendor/desk/skills/operator-voice-comments/LICENSE-humanize +21 -0
  1612. package/vendor/desk/skills/operator-voice-comments/SKILL.md +94 -0
  1613. package/vendor/desk/skills/operator-voice-comments/human-voice.md +43 -0
  1614. package/vendor/desk/skills/outside-approval/SKILL.md +10 -0
  1615. package/vendor/desk/skills/peer-pr-review/SKILL.md +104 -0
  1616. package/vendor/desk/skills/pr-feedback-on-own-pr/SKILL.md +149 -0
  1617. package/vendor/desk/skills/pr-review-interrogation/SKILL.md +121 -0
  1618. package/vendor/desk/skills/pr-reviewer-audit/SKILL.md +68 -0
  1619. package/vendor/desk/skills/pr-reviewer-audit/helpers/audit.py +353 -0
  1620. package/vendor/desk/skills/pr-reviewer-audit/helpers/test_audit.py +522 -0
  1621. package/vendor/desk/skills/pr-self-review/SKILL.md +86 -0
  1622. package/vendor/desk/skills/pr-surface-hygiene/SKILL.md +129 -0
  1623. package/vendor/desk/skills/pr-surface-hygiene/check-visual-proof.cjs +112 -0
  1624. package/vendor/desk/skills/pr-surface-hygiene/repository-setup.md +19 -0
  1625. package/vendor/desk/skills/pr-surface-hygiene/resources/pr-visual-proof.yml +29 -0
  1626. package/vendor/desk/skills/pr-surface-hygiene/resources/pull-request-template.md +5 -0
  1627. package/vendor/desk/skills/preflight-actions/SKILL.md +60 -0
  1628. package/vendor/desk/skills/preview-feedback/SKILL.md +70 -0
  1629. package/vendor/desk/skills/prior-art/SKILL.md +14 -0
  1630. package/vendor/desk/skills/repo-handling/SKILL.md +67 -0
  1631. package/vendor/desk/skills/rnd-lab/SKILL.md +52 -0
  1632. package/vendor/desk/skills/runtime-symptom-investigation/SKILL.md +110 -0
  1633. package/vendor/desk/skills/session-resumption/SKILL.md +128 -0
  1634. package/vendor/desk/skills/session-start/SKILL.md +54 -0
  1635. package/vendor/desk/skills/session-start/details.md +150 -0
  1636. package/vendor/desk/skills/session-start-migrations/README.md +71 -0
  1637. package/vendor/desk/skills/session-start-migrations/SKILL.md +108 -0
  1638. package/vendor/desk/skills/start-task/SKILL.md +88 -0
  1639. package/vendor/desk/skills/task-card-format/SKILL.md +198 -0
  1640. package/vendor/desk/skills/task-lifecycle/SKILL.md +217 -0
  1641. package/vendor/desk/skills/track-card-format/SKILL.md +90 -0
  1642. package/vendor/desk/skills/using-desk/SKILL.md +58 -0
  1643. package/vendor/desk/skills/using-superpowers-with-desk/SKILL.md +158 -0
  1644. package/vendor/desk/skills/visual-proof/SKILL.md +42 -0
  1645. package/vendor/desk/skills/work-orchestration/SKILL.md +177 -0
  1646. package/dist/heart/daemon/ouro-path-installer.js +0 -177
  1647. package/dist/heart/daemon/specialist-tools.js +0 -234
  1648. package/dist/heart/daemon/subagent-installer.js +0 -134
  1649. package/dist/mind/friends/channel.js +0 -49
  1650. package/dist/mind/friends/resolver.js +0 -84
  1651. package/dist/mind/friends/store-file.js +0 -171
  1652. package/dist/mind/friends/types.js +0 -21
  1653. package/dist/repertoire/tasks/board.js +0 -122
  1654. package/dist/repertoire/tasks/index.js +0 -210
  1655. package/dist/repertoire/tasks/middleware.js +0 -65
  1656. package/dist/repertoire/tasks/parser.js +0 -173
  1657. package/dist/repertoire/tasks/scanner.js +0 -132
  1658. package/dist/repertoire/tasks/transitions.js +0 -145
  1659. package/dist/senses/bluebubbles-client.js +0 -279
  1660. package/dist/senses/bluebubbles-entry.js +0 -11
  1661. package/dist/senses/bluebubbles-model.js +0 -253
  1662. package/dist/senses/bluebubbles.js +0 -332
  1663. package/dist/senses/inner-dialog-worker.js +0 -61
  1664. package/dist/senses/inner-dialog.js +0 -231
  1665. package/subagents/README.md +0 -73
  1666. package/subagents/work-doer.md +0 -233
  1667. package/subagents/work-merger.md +0 -624
  1668. package/subagents/work-planner.md +0 -373
  1669. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  1670. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  1671. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  1672. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  1673. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  1674. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  1675. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  1676. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  1677. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  1678. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  1679. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  1680. /package/dist/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +0 -0
  1681. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  1682. /package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/store.js +0 -0
@@ -1,97 +1,245 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.hasToolIntent = exports.buildSystem = exports.toResponsesTools = exports.toResponsesInput = exports.streamResponsesApi = exports.streamChatCompletion = exports.getToolsForChannel = exports.summarizeArgs = exports.execTool = exports.tools = void 0;
3
+ exports.STEP_BUDGET_NOTICE_AT = exports.MAX_PROVIDER_ITERATIONS_CEILING = exports.STEP_BUDGET_EXTENSION = exports.MAX_PROVIDER_ITERATIONS = void 0;
4
+ exports.validateToolCallBatchAtProductionBoundary = validateToolCallBatchAtProductionBoundary;
4
5
  exports.createProviderRegistry = createProviderRegistry;
6
+ exports.getProviderRuntime = getProviderRuntime;
5
7
  exports.resetProviderRuntime = resetProviderRuntime;
6
8
  exports.getModel = getModel;
7
9
  exports.getProvider = getProvider;
8
10
  exports.createSummarize = createSummarize;
9
11
  exports.getProviderDisplayLabel = getProviderDisplayLabel;
12
+ exports.createHabitCallbackBuffer = createHabitCallbackBuffer;
13
+ exports.stepBudgetNotice = stepBudgetNotice;
14
+ exports.resumeApprovalContinuation = resumeApprovalContinuation;
15
+ exports.unsentSurfaceResult = unsentSurfaceResult;
16
+ exports.unansweredActLines = unansweredActLines;
17
+ exports.surfacesReachedLater = surfacesReachedLater;
18
+ exports.isChatStyleChannel = isChatStyleChannel;
19
+ exports.buildPonderResult = buildPonderResult;
20
+ exports.isExternalStateQuery = isExternalStateQuery;
21
+ exports.settleContentMismatchError = settleContentMismatchError;
22
+ exports.getSettleRetryError = getSettleRetryError;
10
23
  exports.stripLastToolCalls = stripLastToolCalls;
11
24
  exports.repairOrphanedToolCalls = repairOrphanedToolCalls;
12
- exports.isTransientError = isTransientError;
13
- exports.classifyTransientError = classifyTransientError;
25
+ exports.isRejectedRequest = isRejectedRequest;
26
+ exports.dropReplayedReasoning = dropReplayedReasoning;
14
27
  exports.runAgent = runAgent;
15
28
  const config_1 = require("./config");
16
29
  const identity_1 = require("./identity");
30
+ const model_limits_1 = require("./model-limits");
31
+ const source_grounding_1 = require("./source-grounding");
32
+ const shelf_claims_1 = require("./shelf-claims");
33
+ const reply_style_1 = require("./reply-style");
34
+ const tool_catalog_1 = require("../repertoire/tool-catalog");
35
+ const skill_search_1 = require("../repertoire/skill-search");
36
+ const skill_summaries_1 = require("../repertoire/skill-summaries");
17
37
  const tools_1 = require("../repertoire/tools");
18
- const channel_1 = require("../mind/friends/channel");
19
- // Kick detection preserved but disabled — see comment in agent loop below.
20
- // import { detectKick } from "./kicks";
21
- // import type { KickReason } from "./kicks";
38
+ const tools_base_1 = require("../repertoire/tools-base");
39
+ const tools_flow_1 = require("../repertoire/tools-flow");
40
+ const tool_images_1 = require("./tool-images");
41
+ const tool_arguments_1 = require("../repertoire/tool-arguments");
42
+ const session_events_1 = require("./session-events");
43
+ const tool_approval_1 = require("./tool-approval");
44
+ const friends_1 = require("@ouro.bot/friends");
45
+ const streaming_1 = require("./streaming");
22
46
  const runtime_1 = require("../nerves/runtime");
47
+ function validateToolCallBatchAtProductionBoundary(calls, activeTools) {
48
+ const callIdCounts = new Map();
49
+ for (const call of calls)
50
+ callIdCounts.set(call.id, (callIdCounts.get(call.id) ?? 0) + 1);
51
+ return calls.map((call) => {
52
+ if (callIdCounts.get(call.id) !== 1)
53
+ return { call, error: "duplicate tool call id" };
54
+ const advertised = activeTools.find((tool) => tool.function.name === call.name);
55
+ if (!advertised || !advertised.function.parameters || typeof advertised.function.parameters !== "object")
56
+ return { call, error: "tool was not advertised with a valid argument schema" };
57
+ const validated = (0, tool_arguments_1.validateAdvertisedToolArguments)(call.arguments, advertised.function.parameters);
58
+ return validated.ok ? { call, advertised, validated: validated.value } : { call, error: validated.reason };
59
+ });
60
+ }
23
61
  const context_1 = require("../mind/context");
62
+ const pending_1 = require("../mind/pending");
63
+ const prompt_budget_1 = require("../mind/prompt-budget");
24
64
  const prompt_1 = require("../mind/prompt");
25
- const associative_recall_1 = require("../mind/associative-recall");
65
+ const kept_notes_1 = require("./kept-notes");
66
+ const error_classification_1 = require("./providers/error-classification");
26
67
  const anthropic_1 = require("./providers/anthropic");
27
68
  const azure_1 = require("./providers/azure");
28
69
  const minimax_1 = require("./providers/minimax");
29
70
  const openai_codex_1 = require("./providers/openai-codex");
30
- let _providerRuntime = null;
31
- function createProviderRegistry() {
32
- const factories = {
33
- azure: azure_1.createAzureProviderRuntime,
34
- anthropic: anthropic_1.createAnthropicProviderRuntime,
35
- minimax: minimax_1.createMinimaxProviderRuntime,
36
- "openai-codex": openai_codex_1.createOpenAICodexProviderRuntime,
71
+ const github_copilot_1 = require("./providers/github-copilot");
72
+ const openai_compatible_1 = require("./providers/openai-compatible");
73
+ const orientation_frame_1 = require("./orientation-frame");
74
+ const identity_2 = require("./identity");
75
+ const socket_client_1 = require("./daemon/socket-client");
76
+ const obligations_1 = require("../arc/obligations");
77
+ const tool_loop_1 = require("./tool-loop");
78
+ const packets_1 = require("../arc/packets");
79
+ const tool_friction_1 = require("./tool-friction");
80
+ const tool_output_budget_1 = require("./tool-output-budget");
81
+ const delegated_command_1 = require("../a2a/delegated-command");
82
+ const provider_models_1 = require("./provider-models");
83
+ const provider_credentials_1 = require("./provider-credentials");
84
+ const provider_fallback_1 = require("./provider-fallback");
85
+ const habit_session_1 = require("./habits/habit-session");
86
+ const provider_attempt_1 = require("./provider-attempt");
87
+ const openai_codex_token_1 = require("./providers/openai-codex-token");
88
+ const turn_summary_1 = require("./turn-summary");
89
+ // Cache only immutable provider construction inputs. ProviderRuntime owns
90
+ // mutable per-turn state (for example Responses nativeInput), so every caller
91
+ // must receive a fresh instance even when its binding fingerprint is unchanged.
92
+ const _providerRuntimeFactories = {
93
+ human: null,
94
+ agent: null,
95
+ };
96
+ function providerLaneForFacing(facing) {
97
+ return facing === "human" ? "outward" : "inner";
98
+ }
99
+ function resolveRuntimeProviderBinding(facing, owner) {
100
+ const lane = providerLaneForFacing(facing);
101
+ const config = (0, identity_1.loadAgentConfig)(owner);
102
+ const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
103
+ return { lane, provider: facingConfig.provider, model: facingConfig.model };
104
+ }
105
+ async function getProviderRuntimeFingerprint(facing, owner) {
106
+ const agentName = owner?.agentName ?? (0, identity_2.getAgentName)();
107
+ const binding = resolveRuntimeProviderBinding(facing, owner);
108
+ const credential = await (0, provider_credentials_1.readProviderCredentialRecord)(agentName, binding.provider);
109
+ if (!credential.ok) {
110
+ throw new Error([
111
+ `${binding.lane} provider ${binding.provider} (${binding.model}) has no credentials for ${agentName}.`,
112
+ credential.error,
113
+ `Run \`ouro auth --agent ${agentName} --provider ${binding.provider}\`.`,
114
+ ].join("\n"));
115
+ }
116
+ let record = credential.record;
117
+ if (binding.provider === "openai-codex") {
118
+ const refresh = await (0, openai_codex_token_1.refreshOpenAICodexProviderCredentials)(agentName, {
119
+ record,
120
+ reason: "runtime-init",
121
+ });
122
+ if (refresh.ok) {
123
+ record = refresh.record;
124
+ }
125
+ }
126
+ return {
127
+ binding,
128
+ fingerprint: JSON.stringify({
129
+ ...(owner ? { agentName: owner.agentName, agentRoot: owner.agentRoot } : {}),
130
+ lane: binding.lane,
131
+ provider: binding.provider,
132
+ model: binding.model,
133
+ credentialRevision: record.revision,
134
+ }),
135
+ credential: record,
37
136
  };
137
+ }
138
+ function createProviderRegistry() {
38
139
  return {
39
- resolve() {
40
- const provider = (0, identity_1.loadAgentConfig)().provider;
41
- return factories[provider]();
140
+ resolve(provider, model, credential, owner) {
141
+ const providerConfig = { ...credential.config, ...credential.credentials };
142
+ switch (provider) {
143
+ case "azure":
144
+ return (0, azure_1.createAzureProviderRuntime)(model, providerConfig);
145
+ case "anthropic":
146
+ return (0, anthropic_1.createAnthropicProviderRuntime)(model, providerConfig);
147
+ case "minimax":
148
+ return (0, minimax_1.createMinimaxProviderRuntime)(model, providerConfig);
149
+ case "openai-codex":
150
+ return (0, openai_codex_1.createOpenAICodexProviderRuntime)(model, providerConfig);
151
+ case "github-copilot":
152
+ return (0, github_copilot_1.createGithubCopilotProviderRuntime)(model, providerConfig, owner);
153
+ case "openai-compatible":
154
+ case "openai-compatible-gemini":
155
+ return (0, openai_compatible_1.createOpenAICompatibleProviderRuntime)(provider, model, providerConfig);
156
+ }
42
157
  },
43
158
  };
44
159
  }
45
- function getProviderRuntime() {
46
- if (!_providerRuntime) {
47
- try {
48
- _providerRuntime = createProviderRegistry().resolve();
49
- }
50
- catch (error) {
51
- const msg = error instanceof Error ? error.message : String(error);
52
- (0, runtime_1.emitNervesEvent)({
53
- level: "error",
54
- event: "engine.provider_init_error",
55
- component: "engine",
56
- message: msg,
57
- meta: {},
58
- });
59
- // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
60
- console.error(`\n[fatal] ${msg}\n`);
61
- process.exit(1);
62
- throw new Error("unreachable");
160
+ async function getProviderRuntime(facing = "human", owner) {
161
+ const scope = owner ? { agentName: owner.agentName, agentRoot: owner.agentRoot } : undefined;
162
+ let runtime = null;
163
+ try {
164
+ const { binding, fingerprint, credential } = await getProviderRuntimeFingerprint(facing, scope);
165
+ const cached = _providerRuntimeFactories[facing];
166
+ if (!cached || cached.fingerprint !== fingerprint) {
167
+ const agentName = scope?.agentName ?? (0, identity_2.getAgentName)();
168
+ const runtimeOwner = { agentName, agentRoot: scope?.agentRoot ?? (0, identity_2.getAgentRoot)(agentName) };
169
+ const create = () => createProviderRegistry().resolve(binding.provider, binding.model, credential, runtimeOwner);
170
+ runtime = create();
171
+ _providerRuntimeFactories[facing] = runtime ? { fingerprint, create } : null;
63
172
  }
64
- if (!_providerRuntime) {
65
- (0, runtime_1.emitNervesEvent)({
66
- level: "error",
67
- event: "engine.provider_init_error",
68
- component: "engine",
69
- message: "provider runtime could not be initialized.",
70
- meta: {},
71
- });
72
- process.exit(1);
73
- throw new Error("unreachable");
173
+ else {
174
+ runtime = cached.create();
74
175
  }
75
176
  }
76
- return _providerRuntime;
177
+ catch (error) {
178
+ const msg = error instanceof Error ? error.message : String(error);
179
+ (0, runtime_1.emitNervesEvent)({
180
+ level: "error",
181
+ event: "engine.provider_init_error",
182
+ component: "engine",
183
+ message: msg,
184
+ meta: { facing },
185
+ });
186
+ // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
187
+ console.error(`\n[fatal] ${msg}\n`);
188
+ throw error instanceof Error ? error : new Error(msg);
189
+ }
190
+ if (!runtime) {
191
+ const msg = "provider runtime could not be initialized.";
192
+ (0, runtime_1.emitNervesEvent)({
193
+ level: "error",
194
+ event: "engine.provider_init_error",
195
+ component: "engine",
196
+ message: msg,
197
+ meta: { facing },
198
+ });
199
+ // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
200
+ console.error(`\n[fatal] ${msg}\n`);
201
+ throw new Error(msg);
202
+ }
203
+ await (0, model_limits_1.learnContextWindow)(runtime);
204
+ // The shared tool loop supplies approval continuation to every provider adapter.
205
+ return { ...runtime, capabilities: new Set([...runtime.capabilities, "approval-continuation"]) };
206
+ }
207
+ /** A runtime for one entry of an agent's provider fallback chain, built fresh from its vault credentials. */
208
+ async function getChainEntryRuntime(entry, owner) {
209
+ const agentName = owner?.agentName ?? (0, identity_2.getAgentName)();
210
+ const credential = await (0, provider_credentials_1.readProviderCredentialRecord)(agentName, entry.provider);
211
+ if (!credential.ok)
212
+ throw new Error(`${entry.provider} (${entry.model}) has no credentials for ${agentName}: ${credential.error}`);
213
+ const runtimeOwner = { agentName, agentRoot: owner?.agentRoot ?? (0, identity_2.getAgentRoot)(agentName) };
214
+ const runtime = createProviderRegistry().resolve(entry.provider, entry.model, credential.record, runtimeOwner);
215
+ /* v8 ignore next -- defensive: the registry resolves every provider id @preserve */
216
+ if (!runtime)
217
+ throw new Error(`${entry.provider} (${entry.model}) runtime could not be initialized.`);
218
+ await (0, model_limits_1.learnContextWindow)(runtime);
219
+ return { ...runtime, capabilities: new Set([...runtime.capabilities, "approval-continuation"]) };
220
+ }
221
+ // Called after getProviderRuntime has loaded the same agent.json, so a bad config has already failed the turn.
222
+ function resolveTurnFallbackChain(facing, owner) {
223
+ return (0, provider_fallback_1.providerFallbackChain)((0, identity_1.loadAgentConfig)(owner), providerLaneForFacing(facing));
77
224
  }
78
225
  /**
79
- * Clear the cached provider runtime so the next call to getProviderRuntime()
80
- * re-creates it from current config. Used by the adoption specialist to
81
- * switch provider context without restarting the process.
226
+ * Clear cached provider construction inputs so the next access re-reads them
227
+ * from current config. Runtime instances are always per-caller and are never
228
+ * shared across turns.
82
229
  */
83
230
  function resetProviderRuntime() {
84
- _providerRuntime = null;
231
+ _providerRuntimeFactories.human = null;
232
+ _providerRuntimeFactories.agent = null;
85
233
  }
86
- function getModel() {
87
- return getProviderRuntime().model;
234
+ function getModel(facing = "human") {
235
+ return resolveRuntimeProviderBinding(facing).model;
88
236
  }
89
- function getProvider() {
90
- return getProviderRuntime().id;
237
+ function getProvider(facing = "human") {
238
+ return resolveRuntimeProviderBinding(facing).provider;
91
239
  }
92
- function createSummarize() {
240
+ function createSummarize(facing = "human") {
93
241
  return async (transcript, instruction) => {
94
- const runtime = getProviderRuntime();
242
+ const runtime = await getProviderRuntime(facing);
95
243
  const client = runtime.client;
96
244
  const response = await client.chat.completions.create({
97
245
  model: runtime.model,
@@ -104,43 +252,710 @@ function createSummarize() {
104
252
  return response.choices?.[0]?.message?.content ?? transcript;
105
253
  };
106
254
  }
107
- function getProviderDisplayLabel() {
108
- const model = getModel();
255
+ function getProviderDisplayLabel(facing = "human") {
256
+ const binding = resolveRuntimeProviderBinding(facing);
257
+ const provider = binding.provider;
258
+ const model = binding.model || "unknown";
109
259
  const providerLabelBuilders = {
110
- azure: () => `azure openai (${(0, config_1.getAzureConfig)().deployment || "default"}, model: ${model})`,
260
+ azure: () => {
261
+ return `azure openai (model: ${model})`;
262
+ },
111
263
  anthropic: () => `anthropic (${model})`,
112
264
  minimax: () => `minimax (${model})`,
113
265
  "openai-codex": () => `openai codex (${model})`,
266
+ /* v8 ignore next -- branch: tested via display label unit test @preserve */
267
+ "github-copilot": () => `github copilot (${model})`,
268
+ "openai-compatible": () => `z.ai openai-compatible (${model})`,
269
+ "openai-compatible-gemini": () => `gemini openai-compatible (${model})`,
270
+ };
271
+ return providerLabelBuilders[provider]();
272
+ }
273
+ function createCallbackBuffer(callbacks, mode) {
274
+ const events = [];
275
+ const bufferedCallbacks = {
276
+ ...callbacks,
277
+ onTextChunk: (text) => { events.push({ kind: "text", text }); },
278
+ onClearText: () => { events.push({ kind: "clear" }); },
279
+ flushNow: () => { events.push({ kind: "flush" }); },
280
+ };
281
+ if (mode === "all") {
282
+ bufferedCallbacks.onModelStreamStart = () => { events.push({ kind: "stream-start" }); };
283
+ bufferedCallbacks.onReasoningChunk = (text) => { events.push({ kind: "reasoning", text }); };
284
+ }
285
+ return {
286
+ callbacks: bufferedCallbacks,
287
+ async flush() {
288
+ for (const event of events.splice(0)) {
289
+ switch (event.kind) {
290
+ case "stream-start":
291
+ callbacks.onModelStreamStart();
292
+ break;
293
+ case "text":
294
+ callbacks.onTextChunk(event.text);
295
+ break;
296
+ case "reasoning":
297
+ callbacks.onReasoningChunk(event.text);
298
+ break;
299
+ case "clear":
300
+ callbacks.onClearText?.();
301
+ break;
302
+ case "flush":
303
+ await callbacks.flushNow?.();
304
+ break;
305
+ }
306
+ }
307
+ },
308
+ discard() {
309
+ events.splice(0);
310
+ },
311
+ };
312
+ }
313
+ function createHabitCallbackBuffer(callbacks) {
314
+ return createCallbackBuffer(callbacks, "all");
315
+ }
316
+ function createFinalOnlyTextBuffer(callbacks) {
317
+ return createCallbackBuffer(callbacks, "text-only");
318
+ }
319
+ /** Base per-turn provider-call budget. Grows while tool calls keep making progress. */
320
+ exports.MAX_PROVIDER_ITERATIONS = 8;
321
+ /** How many provider calls each progress-earned extension adds. */
322
+ exports.STEP_BUDGET_EXTENSION = 4;
323
+ /** Hard ceiling on the per-turn provider-call budget, however much progress is made. */
324
+ exports.MAX_PROVIDER_ITERATIONS_CEILING = 24;
325
+ const STEP_BUDGET_REPORT_INSTRUCTION = "the step budget for this turn is used up. do not call any more work tools; none of the tool calls in your last message were executed. call settle now with a short progress report: what is done (with evidence from tool results above), what is still in flight, and what you will do next. say you can continue where you left off when the conversation resumes.";
326
+ /** How few tool-running steps a turn has left before the model is told, so it finishes the asked-for change before the stop. */
327
+ exports.STEP_BUDGET_NOTICE_AT = 2;
328
+ /**
329
+ * The note on a batch's last tool result once the turn is near its step budget: how many more steps can run tools, whether
330
+ * more can still be earned, and what to do with them. `left` counts the steps that will run tools if no further call makes
331
+ * progress; `ceilingLeft` the most the turn can ever get.
332
+ */
333
+ function stepBudgetNotice(left, ceilingLeft, wrapUpTool) {
334
+ if (left <= 0)
335
+ return `[step budget] that was the last step in this turn that can run tools. call ${wrapUpTool} now: what is done (with evidence from the results above), what is still open, and what you will do next.`;
336
+ const steps = left === 1 ? "at most 1 more step" : `at most ${left} more steps`;
337
+ const more = left >= ceilingLeft ? ", and that is this turn's limit" : "; more come only while new calls keep succeeding";
338
+ return `[step budget] ${steps} in this turn can run tools${more}. finish what was asked first (a change or a send you have ready), leave extra checks for later, then call ${wrapUpTool}.`;
339
+ }
340
+ const STEP_BUDGET_REST_INSTRUCTION = "the step budget for this turn is used up. do not call any more work tools; none of the tool calls in your last message were executed. call rest now with a short note: what is done, what is still open, and what to pick up next time.";
341
+ function continuationCallbacks(callbacks, text) {
342
+ const noop = () => undefined;
343
+ return {
344
+ onModelStart: callbacks.onModelStart ?? noop,
345
+ onModelStreamStart: callbacks.onModelStreamStart ?? noop,
346
+ onTextChunk: (chunk) => {
347
+ text.value += chunk;
348
+ callbacks.onTextChunk?.(chunk);
349
+ },
350
+ onReasoningChunk: callbacks.onReasoningChunk ?? noop,
351
+ onToolStart: callbacks.onToolStart ?? noop,
352
+ ...(callbacks.onToolDispatch ? { onToolDispatch: callbacks.onToolDispatch } : {}),
353
+ onToolEnd: callbacks.onToolEnd ?? noop,
354
+ onError: callbacks.onError ?? noop,
355
+ ...(callbacks.onClearText ? { onClearText: callbacks.onClearText } : {}),
356
+ ...(callbacks.flushNow ? { flushNow: callbacks.flushNow } : {}),
357
+ ...(callbacks.settleOutputMode ? { settleOutputMode: callbacks.settleOutputMode } : {}),
358
+ };
359
+ }
360
+ async function resumeApprovalContinuation(options) {
361
+ const claim = options.claimContinuation();
362
+ if (!claim.claimed) {
363
+ if (claim.interruptedAfterAttempt) {
364
+ const notice = "the approval continuation was interrupted after provider work began; its outcome is indeterminate and it will not be retried automatically";
365
+ await options.deliver(notice);
366
+ (0, runtime_1.emitNervesEvent)({
367
+ level: "error",
368
+ component: "engine",
369
+ event: "engine.approval_continuation_indeterminate",
370
+ message: "approval continuation interrupted after provider attempt",
371
+ meta: { approvalId: options.record.approvalId, continuationState: claim.record.continuationState },
372
+ });
373
+ return { outcome: "terminal_notice", messages: structuredClone(options.sessionMessages) };
374
+ }
375
+ (0, runtime_1.emitNervesEvent)({
376
+ component: "engine",
377
+ event: "engine.approval_continuation_duplicate",
378
+ message: "approval continuation was already consumed",
379
+ meta: { approvalId: options.record.approvalId },
380
+ });
381
+ return { outcome: "already_continued", messages: structuredClone(options.sessionMessages) };
382
+ }
383
+ const materialized = (0, session_events_1.materializeApprovalTerminal)({
384
+ messages: options.sessionMessages,
385
+ checkpoint: options.checkpoint,
386
+ record: options.record,
387
+ currentSessionRevision: options.currentSessionRevision,
388
+ materializedApprovalIds: options.materializedApprovalIds,
389
+ });
390
+ const recoveredMaterialization = claim.record.continuationState === "materialized";
391
+ if (!recoveredMaterialization) {
392
+ await options.persist(materialized.messages);
393
+ await options.markContinuationMaterialized();
394
+ }
395
+ const currentOptions = options.revalidate ? await options.revalidate()
396
+ : options.runAgentOptions?.toolContext?.relationshipAuthorization ? null : options.runAgentOptions;
397
+ if (!materialized.resumeProvider || currentOptions === null) {
398
+ if (currentOptions === null)
399
+ (0, runtime_1.emitNervesEvent)({
400
+ level: "warn", component: "engine", event: "engine.approval_continuation_authority_block",
401
+ message: "approval continuation has no current relationship authority",
402
+ meta: { approvalId: options.record.approvalId, state: options.record.state },
403
+ });
404
+ const effect = options.record.state === "succeeded" ? "the approved action completed"
405
+ : options.record.state === "failed" ? "the approved action failed" : "the protected action was not executed";
406
+ await options.deliver(materialized.directNotice ?? `${effect}; current relationship access is unavailable, so no model continuation was run`);
407
+ await options.completeContinuation();
408
+ return { outcome: "terminal_notice", messages: materialized.messages };
409
+ }
410
+ const outward = { value: "" };
411
+ const callbacks = continuationCallbacks(options.callbacks, outward);
412
+ await options.markContinuationAttempted();
413
+ const result = await options.runAgent(materialized.messages, callbacks, options.channel, options.signal, currentOptions);
414
+ if (result.outcome === "suspended") {
415
+ await options.completeContinuation();
416
+ return { outcome: result.outcome, messages: materialized.messages, suspension: result.suspension };
417
+ }
418
+ await options.persist(materialized.messages, result);
419
+ if (outward.value)
420
+ await options.deliver(outward.value);
421
+ await options.completeContinuation();
422
+ (0, runtime_1.emitNervesEvent)({
423
+ component: "engine",
424
+ event: "engine.approval_continuation_completed",
425
+ message: "approval continuation completed through existing provider loop",
426
+ meta: { approvalId: options.record.approvalId, outcome: result.outcome },
427
+ });
428
+ return { outcome: result.outcome, messages: materialized.messages };
429
+ }
430
+ /**
431
+ * Strip <think>...</think> blocks for the violation-detection check at the
432
+ * end of a streaming turn. Used to tell legitimate text-only responses
433
+ * apart from the MiniMax-M2.7 "only thinking, no tool call" violation
434
+ * shape. Mirrors the more thorough stripThinkBlocks helper in
435
+ * senses/shared-turn.ts (which is for operator-facing output) — kept
436
+ * inline here to avoid pulling senses/ into the core module's import graph.
437
+ */
438
+ function stripThinkBlocksForViolationCheck(input) {
439
+ let out = input;
440
+ for (;;) {
441
+ const open = out.indexOf("<think>");
442
+ if (open === -1)
443
+ break;
444
+ const close = out.indexOf("</think>", open + "<think>".length);
445
+ if (close === -1) {
446
+ out = out.slice(0, open);
447
+ break;
448
+ }
449
+ out = out.slice(0, open) + out.slice(close + "</think>".length);
450
+ }
451
+ return out.trim();
452
+ }
453
+ /** Who a send was for: its friendId, or for a surface addressed only by delegationId, that held thought. */
454
+ const surfaceFriendKey = (record) => {
455
+ const friendId = (record.args.friendId ?? "").trim().toLowerCase();
456
+ return friendId || (record.args.delegationId ? `delegation:${record.args.delegationId.trim()}` : "");
457
+ };
458
+ const isUnsentSurface = (record) => record.name === "surface" && /\(code: surface-not-sent\)$/u.test(record.result);
459
+ /** A surface or send_message that reached the friend now, or may have (unconfirmed). */
460
+ const reachedSurfaceFriend = (record) => (record.name === "surface" && /^(?:delivered|forwarded|unconfirmed)\b/u.test(record.result))
461
+ || (record.name === "send_message" && /^delivered now$/mu.test(record.result) && !/\(code: [a-z0-9-]+\)$/u.test(record.result));
462
+ /**
463
+ * This turn's newest surface result that came back not sent (it ends with the surface-not-sent code), among the
464
+ * friends no later surface or send_message reached. Rest uses it to say once that the person was not told.
465
+ */
466
+ function unsentSurfaceResult(records) {
467
+ const unsent = new Map();
468
+ for (const record of records) {
469
+ const friend = surfaceFriendKey(record);
470
+ if (isUnsentSurface(record)) {
471
+ unsent.delete(friend);
472
+ unsent.set(friend, record.result);
473
+ }
474
+ else if (reachedSurfaceFriend(record)) {
475
+ unsent.delete(friend);
476
+ }
477
+ }
478
+ return [...unsent.values()].at(-1) ?? null;
479
+ }
480
+ /**
481
+ * The ACT: lines of this turn's shell results that no later send reached (or queued for) anyone after. A habit's scan prints them
482
+ * for work it did or found that a person must hear about, so rest says once that nobody was told.
483
+ */
484
+ function unansweredActLines(records) {
485
+ let lines = [];
486
+ for (const record of records) {
487
+ if (reachedSurfaceFriend(record) || (record.name === "send_message" && /^queued for later$/mu.test(record.result)))
488
+ lines = [];
489
+ else if (record.name === "shell")
490
+ lines.push(...record.result.split("\n").map((line) => line.trim()).filter((line) => line.startsWith("ACT:")));
491
+ }
492
+ return lines.length > 0 ? lines.join("\n") : null;
493
+ }
494
+ const sameWords = (left, right) => {
495
+ const words = (text) => (text ?? "").trim().replace(/\s+/gu, " ").toLowerCase();
496
+ return words(left) !== "" && words(left) === words(right);
497
+ };
498
+ /**
499
+ * When the newest record reached a friend with the same words as surfaces to that friend saved earlier this turn,
500
+ * those saved copies are now redundant. Different words leave the saved copy alone, since that news has not reached
501
+ * them. A surface addressed only by delegationId names no friend and is left alone.
502
+ */
503
+ function surfacesReachedLater(records) {
504
+ const latest = records.at(-1);
505
+ if (!latest || !reachedSurfaceFriend(latest) || !latest.args.friendId?.trim())
506
+ return [];
507
+ const said = latest.args.content;
508
+ let saved = [];
509
+ for (const record of records.slice(0, -1)) {
510
+ if (surfaceFriendKey(record) !== surfaceFriendKey(latest))
511
+ continue;
512
+ if (isUnsentSurface(record) && sameWords(record.args.content, said))
513
+ saved.push({ friendId: record.args.friendId.trim(), content: record.args.content });
514
+ else if (reachedSurfaceFriend(record) && sameWords(record.args.content, said))
515
+ saved = [];
516
+ }
517
+ return saved;
518
+ }
519
+ function hasFreshPendingWork(options) {
520
+ const pendingMessages = options?.pendingMessages;
521
+ if (!Array.isArray(pendingMessages))
522
+ return false;
523
+ return pendingMessages.some((message) => typeof message?.content === "string"
524
+ && message.content.trim().length > 0);
525
+ }
526
+ function recordBlockedHabitSurfaceAttempts(habitSession, toolCalls, reason) {
527
+ if (toolCalls.some((call) => call.name !== "send_message" && call.name !== "surface")) {
528
+ habitSession?.recordError?.(`blocked habit tool batch: ${reason}`);
529
+ }
530
+ if (!habitSession?.recordSurfaceAttempt)
531
+ return;
532
+ for (const call of toolCalls) {
533
+ if (call.name !== "send_message" && call.name !== "surface")
534
+ continue;
535
+ // The canonical pre-batch schema gate guarantees object arguments here.
536
+ const args = JSON.parse(call.arguments);
537
+ habitSession.recordSurfaceAttempt({
538
+ recipient: String(args.friendId ?? args.delegationId ?? "unknown"),
539
+ channel: String(args.channel ?? call.name),
540
+ reason: "blocked",
541
+ result: "blocked",
542
+ rawStatus: "blocked",
543
+ error: reason,
544
+ });
545
+ }
546
+ }
547
+ async function habitToolBatchBlockReason(habitSession, toolCalls, delegatedOrigins) {
548
+ if (!habitSession)
549
+ return null;
550
+ // A habit has the agent's normal tools. Only messaging outward is bounded, by the habit's return routes.
551
+ for (const call of toolCalls) {
552
+ if (call.name !== "send_message" && call.name !== "surface")
553
+ continue;
554
+ if (habitSession.permissionEnvelope.deniedTools.includes(call.name))
555
+ return `habit tool '${call.name}' is denied by this habit session`;
556
+ // The canonical pre-batch schema gate guarantees object arguments here.
557
+ const args = JSON.parse(call.arguments);
558
+ const route = await (0, habit_session_1.resolveHabitReturnRoute)({
559
+ agentRoot: (0, identity_2.getAgentRoot)(),
560
+ envelope: habitSession.permissionEnvelope,
561
+ toolName: call.name,
562
+ args,
563
+ friendStore: habitSession.friendStore,
564
+ delegatedOrigins,
565
+ });
566
+ if (!route.allowed)
567
+ return route.reason;
568
+ }
569
+ return null;
570
+ }
571
+ /** Channels that deliberately support mid-turn delivery expose `speak`.
572
+ * BlueBubbles is final-only: its adapter owns one accepted visibility boundary.
573
+ * The private runtime has `ponder`; MCP returns synchronously; mail is batch. */
574
+ function isChatStyleChannel(channel) {
575
+ return (0, friends_1.getChannelCapabilities)(channel).chatStyle;
576
+ }
577
+ function bindCurrentIngressEvidenceLocator(toolList, evidence) {
578
+ if (!evidence
579
+ || evidence.schemaVersion !== 1
580
+ || evidence.provider !== "bluebubbles"
581
+ || !/^[a-f0-9]{64}$/.test(evidence.captureKeyHash))
582
+ return toolList;
583
+ const locator = `capture:${evidence.captureKeyHash}`;
584
+ return toolList.map((tool) => {
585
+ if (tool.function.name !== "habit_cancel")
586
+ return tool;
587
+ const parameters = tool.function.parameters;
588
+ const properties = parameters.properties;
589
+ return {
590
+ ...tool,
591
+ function: {
592
+ ...tool.function,
593
+ parameters: {
594
+ ...parameters,
595
+ properties: {
596
+ ...properties,
597
+ evidence: {
598
+ ...properties.evidence,
599
+ enum: [locator],
600
+ },
601
+ },
602
+ },
603
+ },
604
+ };
605
+ });
606
+ }
607
+ // Sole-call tools must be the only tool call in a turn. When they appear
608
+ // alongside other tools, the sole-call tool is rejected with this message.
609
+ const SOLE_CALL_REJECTION = {
610
+ settle: tools_flow_1.FLOW_TOOL_REFUSALS.settleAlone,
611
+ observe: tools_flow_1.FLOW_TOOL_REFUSALS.observeAlone,
612
+ rest: tools_flow_1.FLOW_TOOL_REFUSALS.restAlone,
613
+ };
614
+ function parseSettlePayload(argumentsText) {
615
+ const parsed = JSON.parse(argumentsText);
616
+ // Provider finalization validates settle.answer as a string before this
617
+ // terminal handling path. Keep this parser focused on projection instead
618
+ // of carrying an unreachable second shape check.
619
+ const answer = parsed.answer;
620
+ const rawIntent = parsed.intent;
621
+ const intent = rawIntent === "complete" || rawIntent === "blocked" || rawIntent === "direct_reply"
622
+ ? rawIntent
623
+ : undefined;
624
+ return { answer, intent };
625
+ }
626
+ function parsePonderPayload(argumentsText) {
627
+ // The canonical pre-batch schema gate guarantees a valid object payload.
628
+ return JSON.parse(argumentsText);
629
+ }
630
+ function parseSuccessCriteria(raw) {
631
+ if (typeof raw !== "string")
632
+ return null;
633
+ const criteria = raw
634
+ .split("\n")
635
+ .map((line) => line.replace(/^\s*[-*]\s*/, "").trim())
636
+ .filter((line) => line.length > 0);
637
+ return criteria.length > 0 ? criteria : null;
638
+ }
639
+ function parsePacketPayload(raw) {
640
+ if (typeof raw !== "string")
641
+ return null;
642
+ try {
643
+ const parsed = JSON.parse(raw);
644
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
645
+ ? parsed
646
+ : null;
647
+ }
648
+ catch {
649
+ return null;
650
+ }
651
+ }
652
+ function normalizeLegacyPonderArgs(parsed) {
653
+ if (typeof parsed.thought !== "string" || parsed.thought.trim().length === 0) {
654
+ return parsed;
655
+ }
656
+ return {
657
+ action: "create",
658
+ kind: "reflection",
659
+ objective: parsed.thought.trim(),
660
+ summary: typeof parsed.say === "string" ? parsed.say.trim() : "",
661
+ success_criteria: "- preserve the thread for later work",
662
+ payload_json: "{}",
114
663
  };
115
- return providerLabelBuilders[getProvider()]();
116
- }
117
- // Re-export tools, execTool, summarizeArgs from ./tools for backward compat
118
- var tools_2 = require("../repertoire/tools");
119
- Object.defineProperty(exports, "tools", { enumerable: true, get: function () { return tools_2.tools; } });
120
- Object.defineProperty(exports, "execTool", { enumerable: true, get: function () { return tools_2.execTool; } });
121
- Object.defineProperty(exports, "summarizeArgs", { enumerable: true, get: function () { return tools_2.summarizeArgs; } });
122
- Object.defineProperty(exports, "getToolsForChannel", { enumerable: true, get: function () { return tools_2.getToolsForChannel; } });
123
- // Re-export streaming functions for backward compat
124
- var streaming_1 = require("./streaming");
125
- Object.defineProperty(exports, "streamChatCompletion", { enumerable: true, get: function () { return streaming_1.streamChatCompletion; } });
126
- Object.defineProperty(exports, "streamResponsesApi", { enumerable: true, get: function () { return streaming_1.streamResponsesApi; } });
127
- Object.defineProperty(exports, "toResponsesInput", { enumerable: true, get: function () { return streaming_1.toResponsesInput; } });
128
- Object.defineProperty(exports, "toResponsesTools", { enumerable: true, get: function () { return streaming_1.toResponsesTools; } });
129
- // Re-export prompt functions for backward compat
130
- var prompt_2 = require("../mind/prompt");
131
- Object.defineProperty(exports, "buildSystem", { enumerable: true, get: function () { return prompt_2.buildSystem; } });
132
- // Re-export kick utilities for backward compat
133
- var kicks_1 = require("./kicks");
134
- Object.defineProperty(exports, "hasToolIntent", { enumerable: true, get: function () { return kicks_1.hasToolIntent; } });
135
- function upsertSystemPrompt(messages, systemText) {
664
+ }
665
+ function messageContentText(content) {
666
+ if (typeof content === "string")
667
+ return content;
668
+ if (!Array.isArray(content))
669
+ return "";
670
+ return content
671
+ .map((part) => {
672
+ if (typeof part === "string")
673
+ return part;
674
+ if (!part || typeof part !== "object")
675
+ return "";
676
+ const maybeText = part.text;
677
+ return typeof maybeText === "string" ? maybeText : "";
678
+ })
679
+ .filter(Boolean)
680
+ .join("\n");
681
+ }
682
+ function toolResultIndicatesFailure(content) {
683
+ const normalized = content.trim().toLowerCase();
684
+ return normalized.startsWith("error:")
685
+ || normalized.startsWith("invalid tool arguments:")
686
+ || normalized.startsWith("unknown:")
687
+ || normalized.startsWith("relationship authorization required:")
688
+ || normalized.startsWith("orientation hold:")
689
+ || normalized.startsWith("commerce authority required:")
690
+ || normalized.startsWith("blocked:")
691
+ || normalized.startsWith("rejected:");
692
+ }
693
+ function requiredToolResultSucceeded(name, content, args, validate) {
694
+ if (toolResultIndicatesFailure(content))
695
+ return false;
696
+ return validate?.(name, content, args) ?? true;
697
+ }
698
+ function effectFingerprint(name, rawArguments, selection) {
699
+ let args;
700
+ try {
701
+ const parsed = JSON.parse(rawArguments);
702
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
703
+ return null;
704
+ args = { ...parsed };
705
+ }
706
+ catch {
707
+ return null;
708
+ }
709
+ const profile = (0, tools_1.riskProfileForToolName)(name, args, selection);
710
+ if (!profile || profile.mutates === "none")
711
+ return null;
712
+ delete args.expectedVersion;
713
+ return (0, tool_arguments_1.digestJson)({ name, args });
714
+ }
715
+ function historicalFailedEffectsForExactRepeatedRequest(messages, selection) {
716
+ const userRequests = [];
717
+ for (let index = 0; index < messages.length; index += 1) {
718
+ const message = messages[index];
719
+ if (message?.role !== "user")
720
+ continue;
721
+ const text = messageContentText(message.content).replace(/\s+/g, " ").trim();
722
+ if (!text)
723
+ continue;
724
+ userRequests.push({ index, text });
725
+ }
726
+ const current = userRequests.at(-1);
727
+ if (!current)
728
+ return [];
729
+ const prior = userRequests.slice(0, -1).find((request) => request.text === current.text);
730
+ if (!prior)
731
+ return [];
732
+ const effectsByCallId = new Map();
733
+ const failedEffects = new Map();
734
+ // Scan through the end: an effect the approval runtime already ran after the current request (the owner tapped
735
+ // Approve) is resolved by its success. A failure after the current request never adds a new forced effect.
736
+ for (let index = prior.index + 1; index < messages.length; index += 1) {
737
+ if (index === current.index)
738
+ continue;
739
+ const message = messages[index];
740
+ if (message?.role === "assistant" && Array.isArray(message.tool_calls)) {
741
+ for (const call of message.tool_calls) {
742
+ if (call.type !== "function" || !call.id || !call.function.name)
743
+ continue;
744
+ const fingerprint = effectFingerprint(call.function.name, call.function.arguments, selection);
745
+ if (fingerprint)
746
+ effectsByCallId.set(call.id, { name: call.function.name, fingerprint });
747
+ }
748
+ continue;
749
+ }
750
+ if (message?.role !== "tool")
751
+ continue;
752
+ const content = messageContentText(message.content);
753
+ const effect = effectsByCallId.get(message.tool_call_id);
754
+ if (!effect)
755
+ continue;
756
+ if (toolResultIndicatesFailure(content)) {
757
+ if (index < current.index)
758
+ failedEffects.set(effect.fingerprint, effect);
759
+ }
760
+ else {
761
+ failedEffects.delete(effect.fingerprint);
762
+ }
763
+ }
764
+ return [...failedEffects.values()];
765
+ }
766
+ const ANSWER_GATE_MAX_REJECTIONS = 2;
767
+ /** Brevity and shelf claims are retried once; after that the reply goes out (an unbacked shelf claim with a disclosure), because a real draft beats another lap. */
768
+ const ANSWER_STYLE_MAX_RETRIES = 1;
769
+ function privateGateNote(reason) {
770
+ return `[private runtime note, not from the person: do not mention, quote or acknowledge it. your draft was not sent and the person has not seen it, so send the whole corrected reply as if it were your first, never as a correction or follow-up] ${reason}`;
771
+ }
772
+ /** A reply that talks about the runtime's correction (its formatting rules, the retry itself) instead of answering the person. */
773
+ const GATE_NOTE_ECHO = /\b(?:markdown|bold\s+(?:section\s+)?labels?|section\s+labels?|question\s+at\s+the\s+end|closing\s+question|settle\s+again|rewrite\s+the\s+reply|cap\s+it|runtime\s+note|private\s+note)\b/i;
774
+ /** The settle call as delivered, so the history holds what the person got rather than a draft the runtime replaced. */
775
+ function withSettleAnswer(msg, settleArgs, answer) {
776
+ const call = msg.tool_calls[0];
777
+ const args = { ...settleArgs, answer };
778
+ return { ...msg, tool_calls: [{ ...call, function: { ...call.function, arguments: JSON.stringify(args) } }, ...msg.tool_calls.slice(1)] };
779
+ }
780
+ function userTexts(messages) {
781
+ return messages.filter((message) => message.role === "user").map((message) => messageContentText(message.content));
782
+ }
783
+ /** What earlier turns already said or read: assistant replies and tool results before the latest user message. Names in them are not new to this turn. */
784
+ function priorTurnsText(messages) {
785
+ const latest = messages.findLastIndex((message) => message.role === "user");
786
+ return messages.slice(0, Math.max(latest, 0)).filter((message) => message.role === "assistant" || message.role === "tool").map((message) => messageContentText(message.content)).join("\n");
787
+ }
788
+ function latestUserMessageText(messages) {
789
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
790
+ const message = messages[i];
791
+ if (message?.role !== "user")
792
+ continue;
793
+ const text = messageContentText(message.content).trim();
794
+ if (text.length > 0)
795
+ return text;
796
+ }
797
+ return "";
798
+ }
799
+ function truncatePonderDelegatedContent(value) {
800
+ return value.length > 120 ? `${value.slice(0, 117)}...` : value;
801
+ }
802
+ function buildPonderDelegatedContent(input) {
803
+ const primary = (input.summary || input.objective).trim();
804
+ const sourceRequest = input.sourceRequest.trim();
805
+ if (!sourceRequest || sourceRequest === primary || sourceRequest === input.objective.trim()) {
806
+ return truncatePonderDelegatedContent(primary);
807
+ }
808
+ return truncatePonderDelegatedContent(`${primary}\nsource request: ${sourceRequest}`);
809
+ }
810
+ function looksLikePrivateReturnRequest(text) {
811
+ const normalized = text.toLowerCase();
812
+ return /\b(private|privately|private-attention|think|reflect|reflection)\b/.test(normalized)
813
+ && /\b(return|bring back|come back|surface|report back)\b/.test(normalized);
814
+ }
815
+ function extractPrivateReturnHeldTokens(text) {
816
+ const tokens = new Set();
817
+ for (const match of text.matchAll(/\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+){2,}\b/g)) {
818
+ const token = match[0];
819
+ if (token.length >= 8)
820
+ tokens.add(token);
821
+ }
822
+ return [...tokens];
823
+ }
824
+ function privateReturnAckLeakError(answer, heldTokens) {
825
+ if (!answer || heldTokens.size === 0)
826
+ return null;
827
+ for (const token of heldTokens) {
828
+ if (answer.includes(token)) {
829
+ return "private return is queued; do not repeat private markers or requested private-return content in the outward acknowledgement. Say only that the private pass is queued and will return when ready.";
830
+ }
831
+ }
832
+ return null;
833
+ }
834
+ function claimsPrivateReturnQueued(answer) {
835
+ if (!answer)
836
+ return false;
837
+ const normalized = answer.toLowerCase();
838
+ return /\b(queued|queue|will return|return when|when .*complete|when .*completes|private pass|private runtime completes|inner dialog completes|later)\b/.test(normalized)
839
+ && /\b(private|inner|return|queued|later)\b/.test(normalized);
840
+ }
841
+ function privateReturnMissingPonderError(input) {
842
+ if (input.sawPonder)
843
+ return null;
844
+ if (!looksLikePrivateReturnRequest(input.latestUserRequest))
845
+ return null;
846
+ if (!claimsPrivateReturnQueued(input.answer))
847
+ return null;
848
+ return "private-return acknowledgement claimed work was queued, but no ponder packet was created this turn. Call ponder(action=create, ...) first so the return has a packet, return obligation, and private-runtime wake; then settle with only a queued acknowledgement. If you cannot create the packet, ask a blocking clarification without saying it is queued.";
849
+ }
850
+ function activeReturnObligationId(agentName, obligationId) {
851
+ if (!obligationId)
852
+ return null;
853
+ const obligation = (0, obligations_1.readReturnObligation)(agentName, obligationId);
854
+ return obligation?.status === "queued" || obligation?.status === "running" ? obligationId : null;
855
+ }
856
+ function ponderReturnSessionId(packet) {
857
+ const origin = packet.origin;
858
+ if (!origin)
859
+ return "unknown/unknown/unknown";
860
+ return `${origin.friendId}/${origin.channel}/${origin.key}`;
861
+ }
862
+ function buildPonderReturnPrivateWakeOptions(input) {
863
+ const sessionId = ponderReturnSessionId(input.packet);
864
+ return {
865
+ reason: "ponder return obligation private attention",
866
+ triggerSource: "ponder-return-obligation",
867
+ budgetClass: "interactive",
868
+ idempotencyKey: `ponder-return:${input.agentName}:${input.returnObligationId}:${input.packet.id}:${sessionId}`,
869
+ originRefs: [
870
+ { kind: "tool", id: "ponder" },
871
+ { kind: "ponder-packet", id: input.packet.id },
872
+ { kind: "return-obligation", id: input.returnObligationId },
873
+ { kind: "session", id: sessionId },
874
+ ],
875
+ };
876
+ }
877
+ function buildPonderResult(packet, action, returnObligationId) {
878
+ return JSON.stringify({
879
+ ok: true,
880
+ packet_id: packet.id,
881
+ action,
882
+ status: packet.status,
883
+ return_obligation_id: returnObligationId,
884
+ private_return_contract: returnObligationId
885
+ ? "queued for private-runtime attention; do not present the requested private answer as complete in this same outward turn. if you answer now, only say the private pass is queued and will return when ready."
886
+ : null,
887
+ }, null, 2);
888
+ }
889
+ /** Returns true when a tool call queries external state (GitHub, npm registry). */
890
+ function isExternalStateQuery(toolName, args) {
891
+ if (toolName !== "shell")
892
+ return false;
893
+ const cmd = String(args.command ?? "");
894
+ return /\bgh\s+(pr|run|api|issue)\b/.test(cmd) || /\bnpm\s+(view|info|show)\b/.test(cmd);
895
+ }
896
+ const SETTLE_CONTENT_MISMATCH_MIN_CHARS = 40;
897
+ // Markdown markers and smart punctuation differ between a reply and its settle copy without changing it.
898
+ const normalizeForSettleComparison = (text) => text.replace(/[*_`>#~]/g, "").replace(/[\u2018\u2019]/g, "'").replace(/[\u201c\u201d]/g, '"').replace(/[\u2013\u2014]/g, "-").replace(/\s+/g, " ").trim().toLowerCase();
899
+ /**
900
+ * Only `settle.answer` reaches the friend; assistant message text in the same
901
+ * message does not. When a model writes its real reply as message text and puts
902
+ * something else (often a third-person recap) in the answer, the friend gets the
903
+ * recap. Ask once for the reply to be resent as the answer. Short preambles and
904
+ * text the answer already contains (or that contains the answer) pass.
905
+ */
906
+ function settleContentMismatchError(content, answer) {
907
+ if (typeof content !== "string")
908
+ return null;
909
+ const text = normalizeForSettleComparison(content);
910
+ if (text.length < SETTLE_CONTENT_MISMATCH_MIN_CHARS)
911
+ return null;
912
+ const reply = normalizeForSettleComparison(answer);
913
+ if (reply.includes(text) || text.includes(reply))
914
+ return null;
915
+ return "only settle.answer reaches the person; the message text you wrote alongside it does not. if that text is your reply, call settle again with the complete reply, in your own voice, as answer. if it was only working notes, call settle again with the same answer.";
916
+ }
917
+ function getSettleRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp, _delegationDecision, sawSendMessageSelf, sawPonder, _sawQuerySession, currentObligation, innerJob, _sawExternalStateQuery) {
918
+ // Delegation adherence removed: the delegation decision is surfaced in the
919
+ // system prompt as a suggestion. Hard-gating settle caused infinite
920
+ // rejection loops where the agent couldn't respond to the user at all.
921
+ // The agent is free to follow or ignore the delegation hint.
922
+ // 2. Pending obligation not addressed
923
+ if (innerJob?.obligationStatus === "pending" && !sawSendMessageSelf && !sawPonder) {
924
+ return "you're still holding something from an earlier conversation -- someone is waiting for your answer. finish the thought first, or ponder to keep working on it privately.";
925
+ }
926
+ // 3. mustResolveBeforeHandoff + missing intent
927
+ if (mustResolveBeforeHandoff && !intent) {
928
+ return "your settle is missing required intent. when you must keep going until done or blocked, call settle again with answer plus intent=complete, blocked, or direct_reply.";
929
+ }
930
+ // 4. mustResolveBeforeHandoff + direct_reply without follow-up
931
+ if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
932
+ return "your settle used intent=direct_reply without a newer steering follow-up. continue the unresolved work, or call settle again with intent=complete or blocked when appropriate.";
933
+ }
934
+ // 5. mustResolveBeforeHandoff + complete while a live return loop is still active
935
+ if (mustResolveBeforeHandoff && intent === "complete" && currentObligation && !sawSteeringFollowUp) {
936
+ return "you still owe the live session a visible return on this work. don't end the turn yet — continue until you've brought back the external-state update, or use intent=blocked with the concrete blocker.";
937
+ }
938
+ return null;
939
+ }
940
+ function upsertSystemPrompt(messages, systemText, protectedSystemMessages = []) {
136
941
  const systemMessage = { role: "system", content: systemText };
137
- if (messages[0]?.role === "system") {
942
+ const protectedMessages = new Set(protectedSystemMessages.filter((message) => message.role === "system"));
943
+ if (messages[0]?.role === "system" && !protectedMessages.has(messages[0])) {
138
944
  messages[0] = systemMessage;
139
945
  }
140
946
  else {
141
947
  messages.unshift(systemMessage);
142
948
  }
143
949
  }
950
+ /**
951
+ * A prompt refresh failure must not revive any generated text from an older
952
+ * turn or release. Even the nominally stable region contains actor-scoped trust,
953
+ * tool, and channel context, so it is not safe to reconstruct. Fail closed to a
954
+ * neutral base and put the freshly derived trigger first.
955
+ */
956
+ function repairFallbackSystemPrompt(orientationFrame) {
957
+ return `${(0, orientation_frame_1.renderOrientationFrame)(orientationFrame)}\n\nYou are a helpful assistant.`;
958
+ }
144
959
  // Remove orphan tool_calls from the last assistant message and any
145
960
  // trailing tool-result messages that lack a matching tool_call.
146
961
  // This keeps the conversation valid after an abort or tool-loop limit.
@@ -169,27 +984,39 @@ const TOOL_SCAN_BOUNDARY_ROLES = new Set(["assistant", "user"]);
169
984
  // 1. If an assistant message has tool_calls but missing tool results, inject synthetic error results.
170
985
  // 2. If a tool result's tool_call_id doesn't match any tool_calls in a preceding assistant message, remove it.
171
986
  // This prevents 400 errors from the API after an aborted turn.
987
+ //
988
+ // Position-aware: a tool result is orphaned when its tool_call_id hasn't been
989
+ // defined by an assistant message AT THIS POSITION yet. MiniMax-M2.7 reuses
990
+ // canonical tool_call_ids across turns, so the global-set check that this
991
+ // function used previously kept misordered tool results that MiniMax then
992
+ // rejected with error 2013 ("tool result's tool id not found"). Walking
993
+ // in order matches what MiniMax actually enforces.
172
994
  function repairOrphanedToolCalls(messages) {
173
- // Pass 1: collect all valid tool_call IDs from assistant messages
174
- const validCallIds = new Set();
175
- for (const msg of messages) {
995
+ // Pass 1: walk in order, accumulate seen tool_call_ids per-position, and
996
+ // mark tool results for removal if their id hasn't been defined yet.
997
+ const seenCallIds = new Set();
998
+ const removeIndices = [];
999
+ for (let i = 0; i < messages.length; i++) {
1000
+ const msg = messages[i];
176
1001
  if (msg.role === "assistant") {
177
1002
  const asst = msg;
178
1003
  if (asst.tool_calls) {
179
1004
  for (const tc of asst.tool_calls)
180
- validCallIds.add(tc.id);
1005
+ seenCallIds.add(tc.id);
181
1006
  }
1007
+ continue;
182
1008
  }
183
- }
184
- // Pass 2: remove orphaned tool results (tool_call_id not in any assistant's tool_calls)
185
- for (let i = messages.length - 1; i >= 0; i--) {
186
- if (messages[i].role === "tool") {
187
- const toolMsg = messages[i];
188
- if (!validCallIds.has(toolMsg.tool_call_id)) {
189
- messages.splice(i, 1);
1009
+ if (msg.role === "tool") {
1010
+ const toolMsg = msg;
1011
+ if (!seenCallIds.has(toolMsg.tool_call_id)) {
1012
+ removeIndices.push(i);
190
1013
  }
191
1014
  }
192
1015
  }
1016
+ // Splice from the end so earlier indices stay valid.
1017
+ for (let i = removeIndices.length - 1; i >= 0; i--) {
1018
+ messages.splice(removeIndices[i], 1);
1019
+ }
193
1020
  // Pass 3: inject synthetic results for tool_calls missing their tool results
194
1021
  for (let i = 0; i < messages.length; i++) {
195
1022
  const msg = messages[i];
@@ -211,10 +1038,13 @@ function repairOrphanedToolCalls(messages) {
211
1038
  }
212
1039
  const missing = asst.tool_calls.filter((tc) => !resultIds.has(tc.id));
213
1040
  if (missing.length > 0) {
1041
+ // AX rule: the agent must see what happened. Don't say "interrupted"
1042
+ // — that's vague. Tell them the result was lost, possible causes,
1043
+ // and what to do next.
214
1044
  const syntheticResults = missing.map((tc) => ({
215
1045
  role: "tool",
216
1046
  tool_call_id: tc.id,
217
- content: "error: tool call was interrupted (previous turn timed out or was aborted)",
1047
+ content: "error: this tool call's result was lost — the previous turn ended before the tool finished (provider rejection, daemon interrupt, or the tool itself errored). if the work needs to be done, retry the tool call now.",
218
1048
  }));
219
1049
  let insertAt = i + 1;
220
1050
  while (insertAt < messages.length && messages[insertAt].role === "tool")
@@ -237,51 +1067,177 @@ function isContextOverflow(err) {
237
1067
  return true;
238
1068
  return false;
239
1069
  }
240
- // Detect transient network errors worth retrying
241
- function isTransientError(err) {
242
- if (!(err instanceof Error))
243
- return false;
244
- const msg = err.message || "";
245
- const code = err.code || "";
246
- // Node.js network error codes
247
- if (["ECONNRESET", "ECONNREFUSED", "ENOTFOUND", "ETIMEDOUT", "EPIPE",
248
- "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "ECONNABORTED"].includes(code))
249
- return true;
250
- // OpenAI SDK / fetch errors
251
- if (msg.includes("fetch failed"))
252
- return true;
253
- if (msg.includes("network") && !msg.includes("context"))
254
- return true;
255
- if (msg.includes("ECONNRESET") || msg.includes("ETIMEDOUT"))
256
- return true;
257
- if (msg.includes("socket hang up"))
258
- return true;
259
- if (msg.includes("getaddrinfo"))
260
- return true;
261
- // HTTP 429 / 500 / 502 / 503 / 504
262
- const status = err.status;
263
- if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504)
264
- return true;
265
- return false;
1070
+ // The provider refused the request itself (a 400 that is not a context overflow): something in what the runtime sent, not
1071
+ // an outage. The agent gets one corrected retry instead of the turn failing (a replayed reasoning signature, a gap in tool results).
1072
+ function isRejectedRequest(err) {
1073
+ return err instanceof Error && err.status === 400 && !isContextOverflow(err);
1074
+ }
1075
+ // Reasoning blocks replayed from earlier turns are the agent's private scratch, and a provider may refuse their signatures.
1076
+ // The current turn's own blocks stay: the provider needs them to continue tool use within the turn.
1077
+ function dropReplayedReasoning(messages, keepFrom) {
1078
+ return messages.map((message, index) => {
1079
+ if (index >= keepFrom || message.role !== "assistant")
1080
+ return message;
1081
+ const record = message;
1082
+ if (!("_thinking_blocks" in record) && !("_reasoning_items" in record))
1083
+ return message;
1084
+ const { _thinking_blocks: _thinking, _reasoning_items: _reasoning, ...rest } = record;
1085
+ return rest;
1086
+ });
1087
+ }
1088
+ const RETRY_LABELS = {
1089
+ "auth-failure": "auth error",
1090
+ "usage-limit": "usage limit",
1091
+ "rate-limit": "rate limited",
1092
+ "server-error": "server error",
1093
+ "network-error": "network error",
1094
+ "unknown": "error",
1095
+ };
1096
+ function waitForProviderRetry(delayMs, signal) {
1097
+ if (!signal) {
1098
+ return new Promise((resolve) => {
1099
+ setTimeout(resolve, delayMs);
1100
+ });
1101
+ }
1102
+ return new Promise((resolve, reject) => {
1103
+ let timer;
1104
+ const onAbort = () => {
1105
+ clearTimeout(timer);
1106
+ reject(new provider_attempt_1.ProviderAttemptAbortError());
1107
+ };
1108
+ timer = setTimeout(() => {
1109
+ signal.removeEventListener("abort", onAbort);
1110
+ resolve();
1111
+ }, delayMs);
1112
+ if (signal.aborted) {
1113
+ onAbort();
1114
+ return;
1115
+ }
1116
+ signal.addEventListener("abort", onAbort, { once: true });
1117
+ });
1118
+ }
1119
+ function buildAuthFailureGuidance(provider, model, agentName, detail) {
1120
+ const mismatch = (0, provider_models_1.getProviderModelMismatchMessage)(provider, model);
1121
+ const modelLabel = model
1122
+ ? mismatch
1123
+ ? `${provider} [configured model: ${model}]`
1124
+ : `${provider} (${model})`
1125
+ : provider;
1126
+ const lines = [`${modelLabel} authentication failed.`];
1127
+ const cleanDetail = detail.replace(/\s+/g, " ").trim();
1128
+ if (cleanDetail)
1129
+ lines.push(`provider detail: ${cleanDetail.length > 300 ? `${cleanDetail.slice(0, 297)}...` : cleanDetail}`);
1130
+ lines.push("");
1131
+ lines.push("To keep using this provider:");
1132
+ lines.push(` 1. Run \`ouro auth --agent ${agentName} --provider ${provider}\``);
1133
+ if (mismatch) {
1134
+ const defaultModel = (0, provider_models_1.getDefaultModelForProvider)(provider);
1135
+ lines.push("");
1136
+ lines.push("Config warning:");
1137
+ lines.push(` - ${mismatch}`);
1138
+ lines.push(" - Repair the configured model with:");
1139
+ lines.push(` \`ouro use --agent ${agentName} --lane outward --provider ${provider} --model ${defaultModel}\``);
1140
+ lines.push(` \`ouro use --agent ${agentName} --lane inner --provider ${provider} --model ${defaultModel}\``);
1141
+ }
1142
+ lines.push("");
1143
+ lines.push(`To use another configured provider instead, run \`ouro use --agent ${agentName} --lane <outward|inner> --provider <provider> --model <model>\`.`);
1144
+ return lines.join("\n");
266
1145
  }
267
- function classifyTransientError(err) {
268
- if (!(err instanceof Error))
269
- return "unknown error";
270
- const status = err.status;
271
- if (status === 429)
272
- return "rate limited";
273
- if (status === 401 || status === 403)
274
- return "auth error";
275
- if (status && status >= 500)
276
- return "server error";
277
- return "network error";
278
- }
279
- const MAX_RETRIES = 3;
280
- const RETRY_BASE_MS = 2000;
281
1146
  async function runAgent(messages, callbacks, channel, signal, options) {
282
- const providerRuntime = getProviderRuntime();
1147
+ // engine.turn_summary (counts only; see turn-summary.ts) is emitted once however the turn ends, a throw included.
1148
+ const turnTally = new turn_summary_1.TurnTally();
1149
+ let result;
1150
+ try {
1151
+ result = await runCountedTurn(turnTally, messages, (0, turn_summary_1.tallyToolEnds)(callbacks, turnTally), channel, signal, options);
1152
+ return result;
1153
+ }
1154
+ finally {
1155
+ (0, turn_summary_1.emitTurnSummary)(turnTally, {
1156
+ channel,
1157
+ outcome: result?.outcome ?? "errored",
1158
+ errorClass: result ? result.errorClassification ?? "none" : "unknown",
1159
+ traceId: options?.traceId,
1160
+ });
1161
+ }
1162
+ }
1163
+ async function runCountedTurn(turnTally, messages, callbacks, channel, signal, options) {
1164
+ const generatedMessages = [];
1165
+ let nextAttemptControls = [];
1166
+ let rejectedAttempt = [];
1167
+ const pushGenerated = (...next) => {
1168
+ messages.push(...next);
1169
+ generatedMessages.push(...structuredClone(next));
1170
+ if (rejectedAttempt.length > 0) {
1171
+ rejectedAttempt = [];
1172
+ providerRuntime.resetTurnState(messages);
1173
+ }
1174
+ };
1175
+ const facing = (0, friends_1.channelToFacing)(channel);
1176
+ const owner = options?.toolContext?.agentName && options.toolContext.agentRoot
1177
+ ? { agentName: options.toolContext.agentName, agentRoot: options.toolContext.agentRoot }
1178
+ : undefined;
1179
+ // Automatic fallback (opt-in via agent.json providerFallback): start on the first chain entry not cooling down.
1180
+ let providerRuntime = options?.providerRuntimeOverride ?? await getProviderRuntime(facing, owner);
1181
+ turnTally.route(providerRuntime.id, providerRuntime.model);
1182
+ const fallbackChain = options?.providerRuntimeOverride ? [] : resolveTurnFallbackChain(facing, owner);
1183
+ let chainIndex = 0;
1184
+ const switchToChainEntry = async (from, firstCandidate, reason) => {
1185
+ for (let candidate = firstCandidate; candidate !== null; candidate = (0, provider_fallback_1.nextReadyChainIndex)(fallbackChain, candidate)) {
1186
+ try {
1187
+ providerRuntime = await getChainEntryRuntime(fallbackChain[candidate], owner);
1188
+ turnTally.route(providerRuntime.id, providerRuntime.model);
1189
+ chainIndex = candidate;
1190
+ (0, runtime_1.emitNervesEvent)({
1191
+ level: "warn",
1192
+ component: "engine",
1193
+ event: "engine.provider_fallback",
1194
+ message: reason ? "provider failed with an error the agent cannot fix; the turn carries on with the next provider" : "turn starts on a fallback provider while the primary cools down",
1195
+ meta: {
1196
+ lane: providerLaneForFacing(facing),
1197
+ fromProvider: fallbackChain[from].provider,
1198
+ fromModel: fallbackChain[from].model,
1199
+ toProvider: fallbackChain[candidate].provider,
1200
+ toModel: fallbackChain[candidate].model,
1201
+ classification: reason?.classification ?? "cooling-down",
1202
+ ...(reason ? { error: reason.error.message.slice(0, 200) } : {}),
1203
+ },
1204
+ });
1205
+ return true;
1206
+ }
1207
+ catch (error) {
1208
+ (0, provider_fallback_1.coolDownProviderEntry)(fallbackChain[candidate], "auth-failure", error instanceof Error ? error : /* v8 ignore next @preserve */ new Error(String(error)));
1209
+ (0, runtime_1.emitNervesEvent)({
1210
+ level: "warn",
1211
+ component: "engine",
1212
+ event: "engine.provider_fallback_unavailable",
1213
+ message: "fallback provider could not be built; trying the next one",
1214
+ meta: { provider: fallbackChain[candidate].provider, model: fallbackChain[candidate].model, error: error instanceof Error ? error.message : /* v8 ignore next @preserve */ String(error) },
1215
+ });
1216
+ }
1217
+ }
1218
+ return false;
1219
+ };
1220
+ if (fallbackChain.length > 0) {
1221
+ const startIndex = (0, provider_fallback_1.firstReadyChainIndex)(fallbackChain);
1222
+ if (startIndex > 0)
1223
+ await switchToChainEntry(0, startIndex, null);
1224
+ }
1225
+ const rebuildCurrentRuntime = () => chainIndex === 0
1226
+ ? getProviderRuntime(facing, owner)
1227
+ : getChainEntryRuntime(fallbackChain[chainIndex], owner);
1228
+ const fallBackAfterTerminalError = async (error, classification) => {
1229
+ if (fallbackChain.length === 0 || !(0, provider_fallback_1.fallsBackOn)(classification))
1230
+ return false;
1231
+ (0, provider_fallback_1.coolDownProviderEntry)(fallbackChain[chainIndex], classification, error);
1232
+ const from = chainIndex;
1233
+ if (!await switchToChainEntry(from, (0, provider_fallback_1.nextReadyChainIndex)(fallbackChain, from), { classification, error }))
1234
+ return false;
1235
+ providerRuntime.resetTurnState(messages);
1236
+ return true;
1237
+ };
1238
+ let servedByProvider = false;
283
1239
  const provider = providerRuntime.id;
284
- const toolChoiceRequired = options?.toolChoiceRequired ?? true;
1240
+ const toolChoiceRequired = options?.hardDisableTools ? false : options?.toolChoiceRequired ?? true;
285
1241
  const traceId = options?.traceId;
286
1242
  (0, runtime_1.emitNervesEvent)({
287
1243
  event: "engine.turn_start",
@@ -300,19 +1256,88 @@ async function runAgent(messages, callbacks, channel, signal, options) {
300
1256
  currentContext = { ...currentContext, friend: freshFriend };
301
1257
  }
302
1258
  }
1259
+ const turnOrientationFrame = options?.orientationFrame
1260
+ ?? (channel ? (0, orientation_frame_1.buildOrientationFrame)({ channel, messages }) : undefined);
1261
+ if (options?.requiredPromptEvidence) {
1262
+ let structuralFloor;
1263
+ try {
1264
+ structuralFloor = (0, prompt_budget_1.assessRequiredPromptEvidenceBudget)({
1265
+ messages,
1266
+ requiredPromptEvidence: options.requiredPromptEvidence,
1267
+ provider: providerRuntime.id,
1268
+ model: providerRuntime.model,
1269
+ contextWindowTokens: (0, config_1.getContextConfig)(providerRuntime.model).maxTokens,
1270
+ });
1271
+ }
1272
+ catch (error) {
1273
+ const invalidEvidenceError = error instanceof Error ? error : new Error(String(error));
1274
+ callbacks.onError(invalidEvidenceError, "terminal");
1275
+ options.captureGeneratedMessages?.([]);
1276
+ (0, runtime_1.emitNervesEvent)({
1277
+ event: "engine.turn_end",
1278
+ trace_id: traceId,
1279
+ component: "engine",
1280
+ message: "runAgent turn completed",
1281
+ meta: { done: true, sawPonder: false, sawQuerySession: false, sawBridgeManage: false },
1282
+ });
1283
+ return {
1284
+ outcome: "errored",
1285
+ error: invalidEvidenceError,
1286
+ errorClassification: "unknown",
1287
+ };
1288
+ }
1289
+ if (structuralFloor.status === "required_evidence_over_budget") {
1290
+ const budgetError = new Error(`required_evidence_over_budget: required current-turn evidence needs ${structuralFloor.estimatedTokens} tokens but the provider input limit is ${structuralFloor.budget.inputTokenLimit}`);
1291
+ callbacks.onError(budgetError, "terminal");
1292
+ options.captureGeneratedMessages?.([]);
1293
+ (0, runtime_1.emitNervesEvent)({
1294
+ event: "engine.turn_end",
1295
+ trace_id: traceId,
1296
+ component: "engine",
1297
+ message: "runAgent turn completed",
1298
+ meta: { done: true, sawPonder: false, sawQuerySession: false, sawBridgeManage: false },
1299
+ });
1300
+ return {
1301
+ outcome: "errored",
1302
+ error: budgetError,
1303
+ errorClassification: "unknown",
1304
+ };
1305
+ }
1306
+ }
303
1307
  // Refresh system prompt at start of each turn when channel is provided.
304
- // If refresh fails, keep existing system prompt (or inject a minimal safe fallback)
305
- // so turn execution remains consistent and non-fatal.
1308
+ // If refresh fails, retain only a recognised stable prefix (or inject a
1309
+ // minimal safe fallback) so stale dynamic state cannot regain authority.
1310
+ let structuredSystemPrompt;
306
1311
  if (channel) {
307
1312
  try {
308
- const refreshed = await (0, prompt_1.buildSystem)(channel, options, currentContext);
309
- upsertSystemPrompt(messages, refreshed);
1313
+ const buildSystemOptions = {
1314
+ ...options,
1315
+ relationshipContextScopes: options?.toolContext?.relationshipAuthorization?.authorizedContextScopes,
1316
+ relationshipProfileId: options?.toolContext?.relationshipAuthorization?.profileId,
1317
+ orientationFrame: turnOrientationFrame,
1318
+ ...(options?.toolContext?.delegatedCommand ? { delegatedCommand: options.toolContext.delegatedCommand } : {}),
1319
+ resumePriorWork: options?.resumePriorWork === true,
1320
+ providerCapabilities: providerRuntime.capabilities,
1321
+ supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
1322
+ };
1323
+ const refreshed = await (0, prompt_1.buildSystem)(channel, buildSystemOptions, currentContext);
1324
+ structuredSystemPrompt = refreshed;
1325
+ upsertSystemPrompt(messages, (0, prompt_1.flattenSystemPrompt)(refreshed), [
1326
+ ...(options?.promptOnlyEvidenceMessages ?? []),
1327
+ ...(options?.requiredPromptEvidence?.verifiedPredecessorMessage
1328
+ ? [options.requiredPromptEvidence.verifiedPredecessorMessage]
1329
+ : []),
1330
+ ]);
310
1331
  }
311
1332
  catch (error) {
312
1333
  const hadExistingSystemPrompt = messages[0]?.role === "system" && typeof messages[0].content === "string";
313
- const existingSystemText = hadExistingSystemPrompt ? messages[0].content : undefined;
314
- const fallback = existingSystemText ?? "You are a helpful assistant.";
315
- upsertSystemPrompt(messages, fallback);
1334
+ const fallback = repairFallbackSystemPrompt(turnOrientationFrame);
1335
+ upsertSystemPrompt(messages, fallback, [
1336
+ ...(options?.promptOnlyEvidenceMessages ?? []),
1337
+ ...(options?.requiredPromptEvidence?.verifiedPredecessorMessage
1338
+ ? [options.requiredPromptEvidence.verifiedPredecessorMessage]
1339
+ : []),
1340
+ ]);
316
1341
  (0, runtime_1.emitNervesEvent)({
317
1342
  level: "warn",
318
1343
  event: "mind.step_error",
@@ -327,254 +1352,1788 @@ async function runAgent(messages, callbacks, channel, signal, options) {
327
1352
  });
328
1353
  }
329
1354
  }
330
- await (0, associative_recall_1.injectAssociativeRecall)(messages);
331
- // kickCount and lastKickReason preserved but unused while kick detection is disabled.
332
- // let kickCount = 0;
333
- // let lastKickReason: KickReason | null = null;
1355
+ if (channel && options?.skipKeptNotes !== true) {
1356
+ await (0, kept_notes_1.injectKeptNotes)(messages, {
1357
+ channel,
1358
+ friend: currentContext?.friend,
1359
+ judge: async (input) => (0, kept_notes_1.createKeptNotesJudge)(await getProviderRuntime("agent", owner), signal)(input),
1360
+ signal,
1361
+ traceId,
1362
+ });
1363
+ }
334
1364
  let done = false;
335
1365
  let lastUsage;
336
1366
  let overflowRetried = false;
337
- let retryCount = 0;
1367
+ let rejectedRequestRetried = false;
1368
+ let replayedReasoningDropped = false;
1369
+ let outcome = "settled";
1370
+ let completion;
1371
+ let suspension;
1372
+ let terminalError;
1373
+ let terminalErrorClassification;
1374
+ let sawSteeringFollowUp = false;
1375
+ let mustResolveBeforeHandoffActive = options?.mustResolveBeforeHandoff === true;
1376
+ let currentReasoningEffort = "medium";
1377
+ let sawSendMessageSelf = false;
1378
+ let sawPonder = false;
1379
+ let sawSettleContentMismatch = false;
1380
+ let sawQuerySession = false;
1381
+ let sawBridgeManage = false;
1382
+ let sawExternalStateQuery = false;
1383
+ const turnToolRecords = [];
1384
+ // The engine pushes its own user messages mid-turn (steering, retry nudges); the person's turn ends where this one began.
1385
+ const turnStartLength = messages.length;
1386
+ let groundingRejections = 0;
1387
+ let brevityRejections = 0;
1388
+ let shelfRejections = 0;
1389
+ let lastRealDraft = null;
1390
+ const privateReturnHeldTokens = new Set();
1391
+ // Once-per-turn flag for the fresh-work rest gate. Without this, an agent
1392
+ // that called rest, was told "fresh work arrived", processed the items,
1393
+ // and called rest again would get the same message forever — the gate
1394
+ // condition is read from the turn-start snapshot of pendingMessages,
1395
+ // which doesn't update mid-turn. The agent only needs to be told once;
1396
+ // after that, repeated rest attempts mean they've acknowledged.
1397
+ let freshWorkGateFired = false;
1398
+ // Once-per-turn flag for the unsent-surface rest gate: the agent is told once
1399
+ // that a person it meant to tell was not reached; a second rest is its answer.
1400
+ let surfaceNotSentGateFired = false;
1401
+ let actGateFired = false;
1402
+ // Counter for no-tool-call violations. MiniMax reasoning models occasionally
1403
+ // emit only a <think>...</think> block and stop, without any tool call — even
1404
+ // when tool_choice is set to "required". Private-return requests also need
1405
+ // a hard no-tool guard: a text-only "queued" acknowledgement is false unless
1406
+ // a ponder packet created the return obligation in this turn.
1407
+ let noToolCallRetries = 0;
1408
+ const NO_TOOL_CALL_MAX_RETRIES = 2;
1409
+ let unresolvedHistoricalEffects = [];
1410
+ let historicalToolFailureRetries = 0;
1411
+ let providerIterations = 0;
1412
+ // Adaptive step budget: starts at the base, grows while tool calls make progress.
1413
+ let stepBudget = exports.MAX_PROVIDER_ITERATIONS;
1414
+ const stepBudgetCeiling = Math.max(exports.MAX_PROVIDER_ITERATIONS, (0, config_1.getContextConfig)().maxStepsPerTurn ?? exports.MAX_PROVIDER_ITERATIONS_CEILING);
1415
+ // The iteration whose tool calls last made progress. The budget grows when any of the last few iterations did, so one
1416
+ // step without progress at the boundary (a speak, a check that exits 1, a rejected call) does not end a working turn.
1417
+ let lastProgressIteration = 0;
1418
+ const progressedRecently = () => lastProgressIteration > 0 && lastProgressIteration >= providerIterations - exports.STEP_BUDGET_EXTENSION;
1419
+ let stepReportIteration = null;
1420
+ // The one tool a turn may call after its step budget is used up: settle for conversations, rest for private turns.
1421
+ let stepReportTool = "settle";
1422
+ // A pre-dispatch contract check may reject the same call twice in a turn; after that it is advisory, so a check no call can satisfy never traps the turn.
1423
+ const requiredDispatchRejectionCounts = new Map();
1424
+ const budgetExhausted = () => {
1425
+ if (providerIterations < stepBudget)
1426
+ return false;
1427
+ if (progressedRecently() && stepBudget < stepBudgetCeiling) {
1428
+ stepBudget = Math.min(stepBudgetCeiling, stepBudget + exports.STEP_BUDGET_EXTENSION);
1429
+ (0, runtime_1.emitNervesEvent)({ component: "engine", event: "engine.step_budget_extended", message: "tool progress extended the per-turn step budget", meta: { stepBudget } });
1430
+ return providerIterations >= stepBudget;
1431
+ }
1432
+ return true;
1433
+ };
1434
+ // After this iteration's calls: how many later steps will run tools if nothing more makes progress, told to the model
1435
+ // once that is STEP_BUDGET_NOTICE_AT or fewer, so a prepared change is not cut off by a stop it never saw coming.
1436
+ const nearBudgetNotice = (toolNames) => {
1437
+ // The next boundary is the first later step that reaches the budget; it extends only if this or an earlier step's
1438
+ // progress still falls in its window, and a second extension is never earned without new progress.
1439
+ const boundary = Math.max(providerIterations + 1, stepBudget);
1440
+ const grows = lastProgressIteration > 0 && lastProgressIteration >= boundary - exports.STEP_BUDGET_EXTENSION && stepBudget < stepBudgetCeiling;
1441
+ const budget = grows ? Math.min(stepBudgetCeiling, stepBudget + exports.STEP_BUDGET_EXTENSION) : stepBudget;
1442
+ const left = Math.max(0, budget - providerIterations - 1);
1443
+ if (left > exports.STEP_BUDGET_NOTICE_AT)
1444
+ return null;
1445
+ const wrapUpTool = toolNames.has("settle") ? "settle" : toolNames.has("rest") ? "rest" : null;
1446
+ if (!wrapUpTool)
1447
+ return null;
1448
+ return stepBudgetNotice(left, stepBudgetCeiling - providerIterations - 1, wrapUpTool);
1449
+ };
1450
+ // Adds the note, when there is one, to the last result the model gets for this step's batch.
1451
+ const withBudgetNote = (content, isLast, toolNames) => {
1452
+ const note = isLast && stepReportIteration === null ? nearBudgetNotice(toolNames) : null;
1453
+ return note ? `${content}\n\n${note}` : content;
1454
+ };
1455
+ const requiredToolCallNames = [...new Set(options?.requiredToolCalls?.names ?? [])];
1456
+ const dispatchedRequiredToolCalls = new Set();
1457
+ const rejectAttempt = (assistant, controls) => {
1458
+ rejectedAttempt = [structuredClone(assistant)];
1459
+ nextAttemptControls = controls;
1460
+ };
1461
+ // Answer gates run only for agents that opt in (ToolContext.answerGates), on every reply the person would receive: a settle answer
1462
+ // and a plain-text reply with no tool call alike (alpha.886 replay: a plain-text reply skipped them and an invented cast went out).
1463
+ // A request-specific contract (options.requiredToolCalls) already validates its own terminal answer. Each gate has its own bounded
1464
+ // retry, and none spends the last provider iteration.
1465
+ // A rejected reply never reaches the person, and neither does the runtime's note about it: the retry gets the reason as a private
1466
+ // note, and a retry that only talks about that note is replaced by the last real draft (2026-10-11: "got it. dummy bad, no markdown,
1467
+ // no question at the end. just plain answer, cap it." went to Sam).
1468
+ // `replacement` is the text to deliver instead of the answer, with any disclosure already applied; null delivers the answer as is.
1469
+ const answerGateVerdict = (answer, intent) => {
1470
+ if (lastRealDraft !== null && GATE_NOTE_ECHO.test(answer)) {
1471
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "engine", event: "engine.answer_gate_echo_replaced", message: "a retry talked about the runtime's note instead of answering; delivering the last real draft", meta: { length: answer.length } });
1472
+ return { error: null, replacement: disclosed(lastRealDraft, answerGateCheck(lastRealDraft, intent, true)) };
1473
+ }
1474
+ const verdict = answerGateCheck(answer, intent, false);
1475
+ if (verdict.error) {
1476
+ lastRealDraft = answer;
1477
+ return { error: privateGateNote(verdict.error), replacement: null };
1478
+ }
1479
+ const delivered = disclosed(answer, verdict);
1480
+ return { error: null, replacement: delivered === answer ? null : delivered };
1481
+ };
1482
+ const disclosed = (answer, verdict) => {
1483
+ const shelfChecked = verdict.shelfUnverified ? (0, shelf_claims_1.withShelfDisclosure)(answer, turnToolRecords) : answer;
1484
+ return verdict.unverifiedNames ? (0, source_grounding_1.withUnverifiedDisclosure)(shelfChecked, verdict.unverifiedNames) : shelfChecked;
1485
+ };
1486
+ // `final` grades a draft that is going out regardless: nothing is rejected, and what would have been is disclosed instead.
1487
+ const answerGateCheck = (answer, intent, final) => {
1488
+ const gates = options?.requiredToolCalls ? undefined : options?.toolContext?.answerGates;
1489
+ const retriesLeft = !final && providerIterations < stepBudget - 1;
1490
+ let groundingError = null;
1491
+ let unverifiedNames = null;
1492
+ const grounding = gates?.sourceGrounding ? (0, source_grounding_1.sourceGroundingFinding)({ answer, userText: userTexts(messages).join("\n"), latestUserText: latestUserMessageText(messages.slice(0, turnStartLength)), knownText: priorTurnsText(messages.slice(0, turnStartLength)), tools: turnToolRecords }) : null;
1493
+ if (grounding) {
1494
+ if (groundingRejections < ANSWER_GATE_MAX_REJECTIONS && retriesLeft) {
1495
+ groundingRejections += 1;
1496
+ groundingError = grounding.message;
1497
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "engine", event: "engine.answer_gate_rejected", message: "answer named things from a work that the turn did not look up; sending the model back", meta: { gate: "source_grounding", rejection: groundingRejections, cap: ANSWER_GATE_MAX_REJECTIONS, lookupsRun: grounding.lookups } });
1498
+ }
1499
+ else {
1500
+ unverifiedNames = grounding.names;
1501
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "engine", event: "engine.answer_gate_disclosed", message: "unsourced names survived the retries; delivering with a disclosure", meta: { gate: "source_grounding", names: grounding.names.length } });
1502
+ }
1503
+ }
1504
+ let shelfError = null;
1505
+ let shelfUnverified = false;
1506
+ const shelfFinding = !groundingError && gates?.shelfClaims ? (0, shelf_claims_1.shelfClaimError)(answer, turnToolRecords) : null;
1507
+ if (shelfFinding && shelfRejections < ANSWER_STYLE_MAX_RETRIES && retriesLeft) {
1508
+ shelfRejections += 1;
1509
+ shelfError = shelfFinding;
1510
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "engine", event: "engine.answer_gate_rejected", message: "answer said something is on the shelf that no lookup this turn found there; sending the model back", meta: { gate: "shelf_claims", rejection: shelfRejections, cap: ANSWER_STYLE_MAX_RETRIES } });
1511
+ }
1512
+ else if (shelfFinding) {
1513
+ shelfUnverified = true;
1514
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "engine", event: "engine.answer_gate_disclosed", message: "an unbacked shelf claim survived the retry; delivering with a disclosure", meta: { gate: "shelf_claims" } });
1515
+ }
1516
+ let brevityError = null;
1517
+ if (!groundingError && !shelfError && gates?.brevity && !options?.toolContext?.context?.isGroupChat && brevityRejections < ANSWER_STYLE_MAX_RETRIES && retriesLeft
1518
+ && (0, reply_style_1.briefStyleRequested)(userTexts(messages), (0, reply_style_1.savedCommunicationPreference)(options?.toolContext?.context?.friend))) {
1519
+ brevityError = (0, reply_style_1.briefStyleViolation)(answer, intent);
1520
+ if (brevityError) {
1521
+ brevityRejections += 1;
1522
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "engine", event: "engine.answer_gate_rejected", message: "answer broke the person's brevity request; sending the model back", meta: { gate: "brevity", rejection: brevityRejections, cap: ANSWER_STYLE_MAX_RETRIES } });
1523
+ }
1524
+ }
1525
+ return { error: groundingError ?? shelfError ?? brevityError, unverifiedNames, shelfUnverified };
1526
+ };
1527
+ // The tools this step offered, so a whole-batch rejection can carry the step-budget note too.
1528
+ let budgetNoteToolNames = new Set();
1529
+ const rejectToolBatch = (assistant, reasons) => {
1530
+ const calls = assistant.tool_calls;
1531
+ rejectAttempt(assistant, calls.map((call, index) => ({
1532
+ role: "tool", tool_call_id: call.id, content: withBudgetNote(reasons[index], index === calls.length - 1, budgetNoteToolNames),
1533
+ })));
1534
+ };
1535
+ const pendingRequiredToolCalls = () => {
1536
+ const missing = requiredToolCallNames.filter((name) => !dispatchedRequiredToolCalls.has(name));
1537
+ return missing.length > 0
1538
+ ? { missing, message: `${options.requiredToolCalls.retryMessage} Missing required tool calls: ${missing.join(", ")}.` }
1539
+ : null;
1540
+ };
1541
+ const queueRequiredCorrection = (assistant, message, limitContext) => {
1542
+ if (budgetExhausted())
1543
+ throw new Error(`provider iteration limit exhausted at response ${stepBudget} ${limitContext}`);
1544
+ // A rejected tool call (settle, a terminal tool) is answered by its own tool result, so the agent reads why and corrects course.
1545
+ if (assistant.tool_calls?.length)
1546
+ rejectToolBatch(assistant, assistant.tool_calls.map(() => message));
1547
+ else
1548
+ rejectAttempt(assistant, [{ role: "user", content: message }]);
1549
+ };
1550
+ const toolLoopState = (0, tool_loop_1.createToolLoopState)();
1551
+ const toolFrictionLedger = (0, tool_friction_1.createToolFrictionLedger)();
1552
+ const finishTerminalProviderError = (error, classification) => {
1553
+ terminalError = error;
1554
+ terminalErrorClassification = classification;
1555
+ /* v8 ignore start — auth-failure guidance: tested via provider error classification tests @preserve */
1556
+ if (terminalErrorClassification === "auth-failure") {
1557
+ const agentName = (0, identity_2.getAgentName)();
1558
+ const currentProvider = providerRuntime.id;
1559
+ callbacks.onError(new Error(buildAuthFailureGuidance(currentProvider, providerRuntime.model, agentName, terminalError.message)), "terminal");
1560
+ }
1561
+ else {
1562
+ callbacks.onError(terminalError, "terminal");
1563
+ }
1564
+ /* v8 ignore stop */
1565
+ const errorDetails = (0, error_classification_1.extractProviderErrorDetails)(terminalError);
1566
+ (0, runtime_1.emitNervesEvent)({
1567
+ level: "error",
1568
+ event: "engine.error",
1569
+ trace_id: traceId,
1570
+ component: "engine",
1571
+ message: terminalError.message,
1572
+ meta: {
1573
+ provider: providerRuntime.id,
1574
+ model: providerRuntime.model,
1575
+ errorClassification: terminalErrorClassification,
1576
+ ...(errorDetails.status !== undefined ? { httpStatus: errorDetails.status } : {}),
1577
+ ...(errorDetails.bodyExcerpt ? { bodyExcerpt: errorDetails.bodyExcerpt } : {}),
1578
+ summary: (0, error_classification_1.summarizeProviderError)(terminalError, terminalErrorClassification, providerRuntime.id, providerRuntime.model),
1579
+ },
1580
+ });
1581
+ // Only legacy input can still contain unaccepted calls. Generated output
1582
+ // has crossed acceptance; a later provider failure cannot revoke effects.
1583
+ if (generatedMessages.length === 0)
1584
+ stripLastToolCalls(messages);
1585
+ outcome = "errored";
1586
+ done = true;
1587
+ };
338
1588
  // Prevent MaxListenersExceeded warning — each iteration adds a listener
339
1589
  try {
340
1590
  require("events").setMaxListeners(50, signal);
341
1591
  }
342
1592
  catch { /* unsupported */ }
343
- const toolPreferences = currentContext?.friend?.toolPreferences;
344
- const baseTools = options?.tools ?? (0, tools_1.getToolsForChannel)(channel ? (0, channel_1.getChannelCapabilities)(channel) : undefined, toolPreferences && Object.keys(toolPreferences).length > 0 ? toolPreferences : undefined);
345
- // Rebase provider-owned turn state from canonical messages at user-turn start.
346
- // This prevents stale provider caches from replaying prior-turn context.
347
- providerRuntime.resetTurnState(messages);
348
- while (!done) {
349
- // When toolChoiceRequired is true (the default), include final_answer
350
- // so the model can signal completion. With tool_choice: required, the
351
- // model must call a tool every turn — final_answer is how it exits.
352
- // Overridable via options.toolChoiceRequired = false (e.g. CLI).
353
- const activeTools = toolChoiceRequired ? [...baseTools, tools_1.finalAnswerTool] : baseTools;
354
- const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
355
- if (steeringFollowUps.length > 0) {
356
- for (const followUp of steeringFollowUps) {
357
- messages.push({ role: "user", content: followUp.text });
1593
+ try {
1594
+ const toolPreferences = currentContext?.friend?.toolPreferences;
1595
+ const filterTrustedTools = (tools, selected) => tools.filter((tool) => !selected.engine.some((engine) => engine.function.name === tool.function.name)
1596
+ && (channel !== "inner" || options?.toolProfile === "sanctuary-health-private" || !["send_message", "surface"].includes(tool.function.name)
1597
+ || selected.ordinary.some((definition) => definition.tool.function.name === tool.function.name)));
1598
+ const selectCurrentTools = () => {
1599
+ if (options?.hardDisableTools)
1600
+ return Object.freeze({ ordinary: Object.freeze([]), engine: Object.freeze([]) });
1601
+ const selected = (0, tools_1.selectToolsForChannel)(channel ? (0, friends_1.getChannelCapabilities)(channel) : undefined, toolPreferences, currentContext, providerRuntime.capabilities, options?.mcpManager, providerRuntime.model, { ...options?.toolContext, ...(options?.habitSession ? { habitSession: options.habitSession } : {}) });
1602
+ const ordinary = options?.tools !== undefined && !options.toolContext?.relationshipAuthorization
1603
+ ? filterTrustedTools(options.tools, selected).flatMap((tool) => {
1604
+ const definition = (0, tools_1.resolveToolDefinition)(tool.function.name, selected) ?? (0, tools_1.resolveToolDefinition)(tool.function.name);
1605
+ return definition ? [{ ...definition, tool }] : [];
1606
+ })
1607
+ : selected.ordinary;
1608
+ const bound = bindCurrentIngressEvidenceLocator(ordinary.map((definition) => definition.tool), options?.toolContext?.currentIngressEvidence);
1609
+ return Object.freeze({
1610
+ ordinary: Object.freeze(ordinary.map((definition, index) => definition.tool === bound[index]
1611
+ ? definition : Object.freeze({ ...definition, tool: bound[index] }))),
1612
+ engine: selected.engine,
1613
+ });
1614
+ };
1615
+ let toolSelection = selectCurrentTools();
1616
+ const relationship = options?.toolContext?.relationshipAuthorization;
1617
+ if (!options?.hardDisableTools && options?.tools !== undefined) {
1618
+ if (relationship) {
1619
+ toolSelection = (0, tools_1.reduceToolSelection)(toolSelection, options.tools);
358
1620
  }
359
- providerRuntime.resetTurnState(messages);
360
1621
  }
361
- // Yield so pending I/O (stdin Ctrl-C) can be processed between iterations
362
- await new Promise((r) => setImmediate(r));
363
- if (signal?.aborted)
364
- break;
365
- try {
366
- callbacks.onModelStart();
367
- const result = await providerRuntime.streamTurn({
368
- messages,
369
- activeTools,
370
- callbacks,
371
- signal,
372
- traceId,
373
- toolChoiceRequired,
374
- });
375
- // Track usage from the latest API call
376
- if (result.usage)
377
- lastUsage = result.usage;
378
- retryCount = 0; // reset on success
379
- // SHARED: build CC-format assistant message from TurnResult
380
- const msg = {
381
- role: "assistant",
382
- };
383
- if (result.content)
384
- msg.content = result.content;
385
- if (result.toolCalls.length)
386
- msg.tool_calls = result.toolCalls.map((tc) => ({
387
- id: tc.id,
388
- type: "function",
389
- function: { name: tc.name, arguments: tc.arguments },
390
- }));
391
- // Store reasoning items from the API response on the assistant message
392
- // so they persist through session save/load and can be restored in toResponsesInput
393
- const reasoningItems = result.outputItems.filter((item) => "type" in item && item.type === "reasoning");
394
- if (reasoningItems.length > 0) {
395
- msg._reasoning_items = reasoningItems;
1622
+ const unboundBaseTools = !options?.hardDisableTools && !relationship && options?.tools
1623
+ ? filterTrustedTools(options.tools, toolSelection)
1624
+ : toolSelection.ordinary.map((definition) => definition.tool);
1625
+ const relationshipToolNames = options?.toolContext?.relationshipAuthorization?.advertisedToolNames;
1626
+ const relationshipScopedTools = relationshipToolNames
1627
+ ? unboundBaseTools.filter((tool) => relationshipToolNames.includes(tool.function.name))
1628
+ : unboundBaseTools;
1629
+ const baseTools = bindCurrentIngressEvidenceLocator(relationshipScopedTools, options?.toolContext?.currentIngressEvidence);
1630
+ // Augment tool context with reasoning effort controls from provider
1631
+ const baseToolContext = options?.toolContext
1632
+ ?? { signin: async () => undefined, ...(turnOrientationFrame ? { orientationFrame: turnOrientationFrame } : {}) };
1633
+ const habitSession = options?.habitSession ?? baseToolContext?.habitSession;
1634
+ const augmentedToolContext = {
1635
+ ...baseToolContext,
1636
+ supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
1637
+ setReasoningEffort: (level) => { currentReasoningEffort = level; },
1638
+ activeWorkFrame: options?.activeWorkFrame,
1639
+ orientationFrame: turnOrientationFrame ?? baseToolContext.orientationFrame,
1640
+ ...(habitSession ? { habitSession } : {}),
1641
+ toolSelection,
1642
+ selectCurrentTools,
1643
+ };
1644
+ const trustedToolContext = options?.toolContext || turnOrientationFrame || habitSession ? augmentedToolContext : undefined;
1645
+ // For one call: executeTool calls beforeHandler only once its guards pass, just before the handler runs.
1646
+ const withDispatchNotice = (context, name) => ({
1647
+ ...context,
1648
+ beforeHandler: () => callbacks.onToolDispatch?.(name),
1649
+ });
1650
+ unresolvedHistoricalEffects = historicalFailedEffectsForExactRepeatedRequest(messages, toolSelection);
1651
+ // Rebase provider-owned turn state from canonical messages at user-turn start.
1652
+ // This prevents stale provider caches from replaying prior-turn context.
1653
+ providerRuntime.resetTurnState(messages);
1654
+ const loadedDeferredTools = [];
1655
+ const ordinaryDefinitionsByName = new Map(toolSelection.ordinary.map((definition) => [definition.tool.function.name, definition]));
1656
+ while (!done) {
1657
+ // Channel-based tool filtering:
1658
+ // - Private runtime: exclude send_message (delivery via surface), observe (no one to observe)
1659
+ // - All outward channels (1:1, group, reaction): observe available
1660
+ //
1661
+ // ponder, settle/rest, surface, and observe are always assembled based on channel context.
1662
+ // ponder is available in ALL channels (outer: think privately, inner: keep turning).
1663
+ // Private runtime gets restTool instead of settleTool (rest = end turn, gated by attention queue).
1664
+ // toolChoiceRequired only controls whether tool_choice: "required" is set in the API call.
1665
+ const isPrivateRuntimeChannel = channel === "inner";
1666
+ const unscopedOrdinaryActiveTools = [
1667
+ ...baseTools,
1668
+ ...toolSelection.engine,
1669
+ ];
1670
+ const scopedOrdinaryActiveTools = relationshipToolNames
1671
+ ? unscopedOrdinaryActiveTools.filter((tool) => relationshipToolNames.includes(tool.function.name))
1672
+ : unscopedOrdinaryActiveTools;
1673
+ // The catalog narrows only what is advertised; the scoped list above is still the authority on what may exist.
1674
+ // Doors whose card isn't eager wait for find_tools (or a skill that declares them).
1675
+ // A caller that hands the turn its own tool list has already chosen the menu, so only the default selection defers.
1676
+ const deferralPossible = !options?.hardDisableTools && options?.tools === undefined && options?.toolProfile !== "sanctuary-health-private";
1677
+ const deferralKeep = new Set(requiredToolCallNames);
1678
+ for (const effect of unresolvedHistoricalEffects)
1679
+ deferralKeep.add(effect.name);
1680
+ const toolCatalog = (0, tool_catalog_1.buildToolCatalog)(scopedOrdinaryActiveTools.map((tool) => {
1681
+ const definition = ordinaryDefinitionsByName.get(tool.function.name);
1682
+ return { tool, ax: definition?.ax, mcpServer: definition?.mcpServer };
1683
+ }));
1684
+ const deferralPool = deferralPossible ? (0, tool_catalog_1.partitionCatalog)(scopedOrdinaryActiveTools, toolCatalog, [], deferralKeep).deferred : [];
1685
+ const deferralHistory = deferralPossible ? (0, tool_catalog_1.namesLoadedInHistory)(messages, new Set(deferralPool.map((tool) => tool.function.name))) : [];
1686
+ const ordinaryActiveTools = deferralPossible
1687
+ ? (0, tool_catalog_1.partitionCatalog)(scopedOrdinaryActiveTools, toolCatalog, [...new Set([...loadedDeferredTools, ...deferralHistory])], deferralKeep).active
1688
+ : scopedOrdinaryActiveTools;
1689
+ const candidateActiveTools = options?.hardDisableTools
1690
+ ? []
1691
+ : options?.toolProfile === "sanctuary-health-private"
1692
+ ? (() => {
1693
+ const sendTools = baseTools.filter((tool) => tool.function.name === "send_message");
1694
+ if (channel !== "inner" || sendTools.length !== 1 || baseTools.length !== 1) {
1695
+ throw new Error("sanctuary-health-private requires inner channel with exactly one canonical send_message definition");
1696
+ }
1697
+ return [sendTools[0], tools_1.restTool];
1698
+ })()
1699
+ : ordinaryActiveTools;
1700
+ const candidateToolNames = new Set(candidateActiveTools.map((tool) => tool.function.name));
1701
+ turnTally.offer(candidateActiveTools, deferralPool, ordinaryDefinitionsByName);
1702
+ budgetNoteToolNames = candidateToolNames;
1703
+ const unadvertisedRequiredTool = requiredToolCallNames.find((name) => !candidateToolNames.has(name));
1704
+ if (unadvertisedRequiredTool) {
1705
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "engine", event: "engine.required_tool_unadvertised", message: "required tool is not advertised for the active channel", meta: { toolName: unadvertisedRequiredTool, channel: String(channel) } });
1706
+ throw new Error(`required tool is not advertised for this channel: ${unadvertisedRequiredTool}`);
1707
+ }
1708
+ const forcedHistoricalToolNames = new Set(unresolvedHistoricalEffects
1709
+ .map((effect) => effect.name)
1710
+ .filter((name) => candidateToolNames.has(name)));
1711
+ const forcingHistoricalEffect = forcedHistoricalToolNames.size > 0;
1712
+ const activeTools = stepReportIteration !== null
1713
+ ? candidateActiveTools.filter((tool) => tool.function.name === stepReportTool)
1714
+ : forcingHistoricalEffect
1715
+ ? candidateActiveTools.filter((tool) => forcedHistoricalToolNames.has(tool.function.name))
1716
+ : candidateActiveTools;
1717
+ const activeToolNames = new Set(activeTools.map((tool) => tool.function.name));
1718
+ const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
1719
+ if (steeringFollowUps.length > 0) {
1720
+ const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
1721
+ if (hasSupersedingFollowUp) {
1722
+ mustResolveBeforeHandoffActive = false;
1723
+ options?.setMustResolveBeforeHandoff?.(false);
1724
+ outcome = "superseded";
1725
+ break;
1726
+ }
1727
+ if (steeringFollowUps.some((followUp) => followUp.effect === "set_no_handoff")) {
1728
+ mustResolveBeforeHandoffActive = true;
1729
+ options?.setMustResolveBeforeHandoff?.(true);
1730
+ }
1731
+ sawSteeringFollowUp = true;
1732
+ for (const followUp of steeringFollowUps) {
1733
+ messages.push({ role: "user", content: followUp.text });
1734
+ }
1735
+ providerRuntime.resetTurnState(messages);
396
1736
  }
397
- if (!result.toolCalls.length) {
398
- // Kick detection is disabled while tool_choice: required + final_answer
399
- // is the primary loop control mechanism. The model should never reach
400
- // this path (tool_choice: required forces a tool call), but if it does,
401
- // accept the response as-is rather than risk false-positive kicks.
402
- //
403
- // Preserved for future use — re-enable by uncommenting:
404
- // const kick = detectKick(result.content, options);
405
- // if (kick) {
406
- // kickCount++;
407
- // lastKickReason = kick.reason;
408
- // callbacks.onKick?.();
409
- // const kickContent = result.content
410
- // ? result.content + "\n\n" + kick.message
411
- // : kick.message;
412
- // messages.push({ role: "assistant", content: kickContent });
413
- // providerRuntime.resetTurnState(messages);
414
- // continue;
415
- // }
416
- messages.push(msg);
417
- done = true;
1737
+ // Yield so pending I/O (stdin Ctrl-C) can be processed between iterations
1738
+ await new Promise((r) => setImmediate(r));
1739
+ if (signal?.aborted) {
1740
+ outcome = "aborted";
1741
+ break;
418
1742
  }
419
- else {
420
- // Check for final_answer sole call: intercept before tool execution
421
- const isSoleFinalAnswer = result.toolCalls.length === 1 && result.toolCalls[0].name === "final_answer";
422
- if (isSoleFinalAnswer) {
423
- // Extract answer from the tool call arguments.
424
- // Supports: {"answer":"text"}, "text" (JSON string), retry on failure.
425
- let answer;
1743
+ try {
1744
+ const budgetOptions = {
1745
+ requiredPromptEvidence: options?.requiredPromptEvidence,
1746
+ provider: providerRuntime.id,
1747
+ model: providerRuntime.model,
1748
+ contextWindowTokens: (0, config_1.getContextConfig)(providerRuntime.model).maxTokens,
1749
+ };
1750
+ const canonicalBudget = (0, prompt_budget_1.applyPromptBudget)({ ...budgetOptions, messages });
1751
+ const currentUserMessage = budgetOptions.requiredPromptEvidence?.currentUserMessage
1752
+ ?? canonicalBudget.messages.findLast((message) => message.role === "user");
1753
+ // Keep retry controls attached to the genuine request, not to canonical history.
1754
+ let attemptMessages = rejectedAttempt.length > 0
1755
+ ? [...(0, prompt_budget_1.applyPromptBudget)({
1756
+ ...budgetOptions,
1757
+ requiredPromptEvidence: budgetOptions.requiredPromptEvidence ?? (currentUserMessage ? { currentUserMessage } : undefined),
1758
+ messages: [...canonicalBudget.messages, ...rejectedAttempt, ...nextAttemptControls],
1759
+ }).messages]
1760
+ : [...canonicalBudget.messages];
1761
+ // Whatever path built this request, every tool call reaches the provider with a result: a gap the runtime left must
1762
+ // never 400 the turn and leave the agent unable to answer.
1763
+ repairOrphanedToolCalls(attemptMessages);
1764
+ const currentTurnStart = () => currentUserMessage ? Math.max(0, attemptMessages.indexOf(currentUserMessage)) : 0;
1765
+ if (replayedReasoningDropped)
1766
+ attemptMessages = dropReplayedReasoning(attemptMessages, currentTurnStart());
1767
+ if (rejectedAttempt.length > 0 || canonicalBudget.status !== "within_budget" || replayedReasoningDropped)
1768
+ providerRuntime.resetTurnState(attemptMessages);
1769
+ const turnCallbackBufferRef = { current: null };
1770
+ const callProviderTurn = async () => {
1771
+ callbacks.onModelStart();
1772
+ turnCallbackBufferRef.current = habitSession
1773
+ ? createHabitCallbackBuffer(callbacks)
1774
+ : callbacks.settleOutputMode === "final_only" || relationship !== undefined
1775
+ ? createFinalOnlyTextBuffer(callbacks)
1776
+ : null;
1777
+ try {
1778
+ return await providerRuntime.streamTurn({
1779
+ messages: attemptMessages,
1780
+ activeTools,
1781
+ // A step narrowed to one tool (a step report, a forced repeat) sends no held-back doors either.
1782
+ ...(deferralPool.length > 0 && activeTools === candidateActiveTools ? { deferredTools: deferralPool } : {}),
1783
+ callbacks: turnCallbackBufferRef.current?.callbacks ?? callbacks,
1784
+ signal,
1785
+ traceId,
1786
+ toolChoiceRequired: options?.hardDisableTools ? false : forcingHistoricalEffect || toolChoiceRequired,
1787
+ reasoningEffort: currentReasoningEffort,
1788
+ eagerSettleStreaming: true,
1789
+ systemPrompt: structuredSystemPrompt,
1790
+ });
1791
+ }
1792
+ catch (error) {
1793
+ turnCallbackBufferRef.current?.discard();
1794
+ turnCallbackBufferRef.current = null;
1795
+ if (signal?.aborted)
1796
+ throw new provider_attempt_1.ProviderAttemptAbortError();
1797
+ throw error;
1798
+ }
1799
+ };
1800
+ const callProviderTurnWithOverflowRecovery = async () => {
426
1801
  try {
427
- const parsed = JSON.parse(result.toolCalls[0].arguments);
428
- if (typeof parsed === "string") {
429
- answer = parsed;
1802
+ return await callProviderTurn();
1803
+ }
1804
+ catch (error) {
1805
+ if (error instanceof provider_attempt_1.ProviderAttemptAbortError)
1806
+ throw error;
1807
+ if (isContextOverflow(error) && !overflowRetried) {
1808
+ overflowRetried = true;
1809
+ const protectedStart = currentUserMessage ? Math.max(0, attemptMessages.indexOf(currentUserMessage)) : 0;
1810
+ const currentAttempt = attemptMessages.slice(protectedStart);
1811
+ const overflowMessages = attemptMessages.slice(0, protectedStart).map((message) => message.role === "assistant" ? { ...message } : message);
1812
+ stripLastToolCalls(overflowMessages);
1813
+ overflowMessages.push(...currentAttempt);
1814
+ const { maxTokens, contextMargin } = (0, config_1.getContextConfig)(providerRuntime.model);
1815
+ const trimmed = (0, context_1.trimMessages)(overflowMessages, maxTokens, contextMargin, maxTokens * 2);
1816
+ const requiredEvidence = options?.requiredPromptEvidence;
1817
+ const requiredMessages = new Set([
1818
+ ...(requiredEvidence?.verifiedPredecessorMessage ? [requiredEvidence.verifiedPredecessorMessage] : []),
1819
+ ...currentAttempt,
1820
+ ]);
1821
+ const trimmedMessages = new Set(trimmed);
1822
+ attemptMessages = requiredMessages.size === 0
1823
+ ? trimmed
1824
+ : overflowMessages.filter((message) => trimmedMessages.has(message) || requiredMessages.has(message));
1825
+ providerRuntime.resetTurnState(attemptMessages);
1826
+ callbacks.onError(new Error("context trimmed, retrying..."), "transient");
1827
+ return callProviderTurn();
1828
+ }
1829
+ // A 400 for spent credit is not a malformed request: correcting history cannot fix it.
1830
+ if (isRejectedRequest(error) && !rejectedRequestRetried && providerRuntime.classifyError(error) !== "usage-limit") {
1831
+ // Never leave the agent unable to answer: correct what the runtime sent, tell the agent why, and let it carry on.
1832
+ rejectedRequestRetried = true;
1833
+ replayedReasoningDropped = true;
1834
+ const detail = error.message;
1835
+ attemptMessages = dropReplayedReasoning(attemptMessages, currentTurnStart());
1836
+ repairOrphanedToolCalls(attemptMessages);
1837
+ attemptMessages = [...attemptMessages, {
1838
+ role: "user",
1839
+ content: `[runtime] The provider refused my last request (${detail}). The runtime dropped reasoning replayed from earlier turns and closed any tool call left without a result. I carry on with the turn from here.`,
1840
+ }];
1841
+ providerRuntime.resetTurnState(attemptMessages);
1842
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "engine", event: "engine.rejected_request_recovered", message: "provider refused the request; retrying once with corrected history", meta: { provider: providerRuntime.id, model: providerRuntime.model, detail: String(detail).slice(0, 300) } });
1843
+ callbacks.onError(new Error("provider refused the request, correcting and retrying..."), "transient");
1844
+ return callProviderTurn();
1845
+ }
1846
+ throw error;
1847
+ }
1848
+ };
1849
+ const attempt = await (0, provider_attempt_1.runProviderAttempt)({
1850
+ operation: "turn",
1851
+ provider: providerRuntime.id,
1852
+ model: providerRuntime.model,
1853
+ run: callProviderTurnWithOverflowRecovery,
1854
+ classifyError: (error) => providerRuntime.classifyError(error),
1855
+ // Spent credit will not come back in seconds: move straight to the next provider when one is ready.
1856
+ shouldRetry: (classification) => classification !== "usage-limit" || (0, provider_fallback_1.nextReadyChainIndex)(fallbackChain, chainIndex) === null,
1857
+ onRetry: async (record, maxAttempts) => {
1858
+ const delayMs = record.delayMs;
1859
+ const seconds = delayMs / 1000;
1860
+ const cause = RETRY_LABELS[record.classification];
1861
+ try {
1862
+ const agentName = owner?.agentName ?? (0, identity_2.getAgentName)();
1863
+ if (record.provider === "openai-codex" && record.classification === "auth-failure") {
1864
+ await (0, openai_codex_token_1.refreshOpenAICodexProviderCredentials)(agentName, {
1865
+ force: true,
1866
+ reason: "turn-auth-failure",
1867
+ });
1868
+ }
1869
+ await (0, provider_credentials_1.refreshProviderCredentialPool)(agentName, {
1870
+ preserveCachedOnFailure: true,
1871
+ providers: [record.provider],
1872
+ });
1873
+ _providerRuntimeFactories[facing] = null;
1874
+ providerRuntime = await rebuildCurrentRuntime();
1875
+ providerRuntime.resetTurnState(attemptMessages);
430
1876
  }
431
- else if (parsed.answer != null) {
432
- answer = parsed.answer;
1877
+ catch (refreshError) {
1878
+ (0, runtime_1.emitNervesEvent)({
1879
+ level: "warn",
1880
+ component: "engine",
1881
+ event: "engine.provider_retry_refresh_failed",
1882
+ message: "provider credential refresh failed during retry",
1883
+ meta: { provider: record.provider, model: record.model, reason: refreshError instanceof Error ? refreshError.message : String(refreshError) },
1884
+ });
1885
+ }
1886
+ callbacks.onError(new Error(`${cause}, retrying in ${seconds}s (${record.attempt}/${maxAttempts})...`), "transient");
1887
+ },
1888
+ sleep: async (delayMs) => {
1889
+ await waitForProviderRetry(delayMs, signal);
1890
+ providerRuntime.resetTurnState(attemptMessages);
1891
+ },
1892
+ });
1893
+ if (!attempt.ok) {
1894
+ if (await fallBackAfterTerminalError(attempt.error, attempt.classification))
1895
+ continue;
1896
+ finishTerminalProviderError(attempt.error, attempt.classification);
1897
+ continue;
1898
+ }
1899
+ const result = attempt.value;
1900
+ servedByProvider = true;
1901
+ nextAttemptControls = [];
1902
+ providerIterations += 1;
1903
+ turnTally.step(result.usage, providerRuntime.id, providerRuntime.model);
1904
+ if (stepReportIteration !== null) {
1905
+ // The progress-report call is the last one: it must settle (or rest), or the turn errors.
1906
+ const settledReport = result.toolCalls.length === 1 && result.toolCalls[0].name === stepReportTool;
1907
+ if (providerIterations > stepReportIteration || (result.toolCalls.length > 0 && !settledReport)) {
1908
+ throw new Error(`provider iteration limit exhausted at response ${providerIterations} before the progress report settled`);
1909
+ }
1910
+ }
1911
+ const streamCallbackBuffer = turnCallbackBufferRef.current;
1912
+ turnCallbackBufferRef.current = null;
1913
+ // Track usage from the latest API call
1914
+ if (result.usage)
1915
+ lastUsage = result.usage;
1916
+ // SHARED: build CC-format assistant message from TurnResult
1917
+ const msg = {
1918
+ role: "assistant",
1919
+ };
1920
+ // Persist assistant content WITHOUT inline <think>...</think> blocks.
1921
+ // Reasoning content already routed through onReasoningChunk for live
1922
+ // surfacing and persisted separately as `_reasoning_items` for
1923
+ // providers that support a reasoning channel; saving it inline AND
1924
+ // alongside tool_calls causes MiniMax to reject the replayed turn
1925
+ // with "tool result's tool id not found" (error code 2013) because
1926
+ // it can't reconcile reasoning-with-tools in the same assistant
1927
+ // message. Strip aggressively at persist so the next replay is
1928
+ // clean; preserve the original reasoning trace on the message via
1929
+ // `_inline_reasoning` so debug/audit paths can still see it.
1930
+ if (result.content) {
1931
+ const stripped = stripThinkBlocksForViolationCheck(result.content);
1932
+ if (stripped.length > 0)
1933
+ msg.content = stripped;
1934
+ if (stripped.length !== result.content.length) {
1935
+ msg._inline_reasoning = result.content;
1936
+ (0, runtime_1.emitNervesEvent)({
1937
+ level: "info",
1938
+ component: "engine",
1939
+ event: "engine.inline_reasoning_stripped",
1940
+ message: "stripped inline <think> blocks from persisted assistant message; preserved on _inline_reasoning",
1941
+ meta: {
1942
+ provider: providerRuntime.id,
1943
+ model: providerRuntime.model,
1944
+ originalLength: result.content.length,
1945
+ strippedLength: stripped.length,
1946
+ },
1947
+ });
1948
+ }
1949
+ }
1950
+ if (result.toolCalls.length)
1951
+ msg.tool_calls = result.toolCalls.map((tc) => ({
1952
+ id: tc.id,
1953
+ type: "function",
1954
+ function: { name: tc.name, arguments: tc.arguments },
1955
+ }));
1956
+ // Store reasoning items from the API response on the assistant message
1957
+ // so they persist through session save/load and can be restored in toResponsesInput
1958
+ const reasoningItems = result.outputItems.filter((item) => "type" in item && item.type === "reasoning");
1959
+ if (reasoningItems.length > 0) {
1960
+ msg._reasoning_items = reasoningItems;
1961
+ }
1962
+ // Store thinking blocks (Anthropic) on the assistant message for round-tripping
1963
+ const thinkingItems = result.outputItems.filter((item) => "type" in item && (item.type === "thinking" || item.type === "redacted_thinking"));
1964
+ if (thinkingItems.length > 0) {
1965
+ msg._thinking_blocks = thinkingItems;
1966
+ }
1967
+ if (result.settleFinalization && !result.settleFinalization.ok) {
1968
+ // An unparseable settle is the agent's own output: nothing reached anyone, so the agent reads why and settles again.
1969
+ // Retractable callbacks have already cleared; core-owned callback buffers are discarded with the attempt.
1970
+ streamCallbackBuffer?.discard();
1971
+ queueRequiredCorrection(msg, `settle was not delivered: its arguments did not parse (${result.settleFinalization.errorCode}). Call settle again with valid JSON arguments.`, "after an unparseable settle");
1972
+ continue;
1973
+ }
1974
+ const settlingNow = result.toolCalls.length === 1 && (result.toolCalls[0].name === "settle" || result.toolCalls[0].name === "rest");
1975
+ if (stepReportIteration === null && result.toolCalls.length > 0 && !settlingNow && budgetExhausted()) {
1976
+ const wrapUpTool = candidateToolNames.has("settle") ? "settle" : candidateToolNames.has("rest") ? "rest" : null;
1977
+ if (!wrapUpTool) {
1978
+ throw new Error(`provider iteration limit exhausted at response ${stepBudget} before tool execution`);
1979
+ }
1980
+ // Do not error into the reply: give the model one settle-only (or rest-only) call to report progress.
1981
+ streamCallbackBuffer?.discard();
1982
+ stepReportIteration = providerIterations + 1;
1983
+ stepReportTool = wrapUpTool;
1984
+ rejectAttempt(msg, [
1985
+ ...result.toolCalls.map((tc) => ({ role: "tool", tool_call_id: tc.id, content: "not executed: the step budget for this turn is used up." })),
1986
+ { role: "user", content: wrapUpTool === "settle" ? STEP_BUDGET_REPORT_INSTRUCTION : STEP_BUDGET_REST_INSTRUCTION },
1987
+ ]);
1988
+ callbacks.onClearText?.();
1989
+ turnTally.stepBudgetExhausted();
1990
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "engine", event: "engine.step_budget_exhausted", message: `step budget used up; requesting a ${wrapUpTool}-only progress report`, meta: { stepBudget, providerIterations } });
1991
+ continue;
1992
+ }
1993
+ // Phase annotation for Codex provider
1994
+ const hasPhaseAnnotation = providerRuntime.capabilities.has("phase-annotation");
1995
+ const isSoleSettle = result.toolCalls.length === 1 && result.toolCalls[0].name === "settle";
1996
+ if (hasPhaseAnnotation) {
1997
+ msg.phase = isSoleSettle ? "settle" : "commentary";
1998
+ }
1999
+ // Detect the MiniMax "only-thinking, no tool call" violation: no tool
2000
+ // calls returned, and the content is empty after stripping
2001
+ // <think>...</think> blocks. This is a narrow check — legitimate
2002
+ // content-only responses (text without think tags, or text outside
2003
+ // think tags) still flow through the original "no tool calls →
2004
+ // accept as-is" path so existing channels and tests are unaffected.
2005
+ const onlyThinkContent = !result.toolCalls.length
2006
+ && typeof result.content === "string"
2007
+ && stripThinkBlocksForViolationCheck(result.content).length === 0
2008
+ && result.content.length > 0;
2009
+ const privateReturnTextAckRetryError = !result.toolCalls.length
2010
+ ? privateReturnMissingPonderError({
2011
+ latestUserRequest: latestUserMessageText(messages),
2012
+ answer: stripThinkBlocksForViolationCheck(result.content),
2013
+ sawPonder,
2014
+ })
2015
+ : null;
2016
+ if (!result.toolCalls.length) {
2017
+ if (forcingHistoricalEffect) {
2018
+ streamCallbackBuffer?.discard();
2019
+ callbacks.onClearText?.();
2020
+ const retryableHistoricalTools = [...forcedHistoricalToolNames];
2021
+ if (historicalToolFailureRetries >= NO_TOOL_CALL_MAX_RETRIES) {
2022
+ const blockedAnswer = "I could not finish the change that failed earlier: I didn't manage to try it again this time, so it is not done.";
2023
+ (0, runtime_1.emitNervesEvent)({
2024
+ level: "warn",
2025
+ component: "engine",
2026
+ event: "engine.historical_tool_failure_retry",
2027
+ message: "unresolved historical effect exhausted deterministic tool-call retries; failing closed",
2028
+ meta: { provider: providerRuntime.id, model: providerRuntime.model, toolNames: retryableHistoricalTools, cap: NO_TOOL_CALL_MAX_RETRIES },
2029
+ });
2030
+ pushGenerated({ role: "assistant", content: blockedAnswer });
2031
+ callbacks.onTextChunk(blockedAnswer);
2032
+ completion = { answer: blockedAnswer, intent: "blocked" };
2033
+ outcome = "blocked";
2034
+ done = true;
2035
+ continue;
433
2036
  }
434
- // else: valid JSON but no answer field — answer stays undefined (retry)
2037
+ historicalToolFailureRetries += 1;
2038
+ (0, runtime_1.emitNervesEvent)({
2039
+ level: "warn",
2040
+ component: "engine",
2041
+ event: "engine.historical_tool_failure_retry",
2042
+ message: "unresolved historical effect returned no tool call; forcing another exact-effect attempt",
2043
+ meta: {
2044
+ provider: providerRuntime.id,
2045
+ model: providerRuntime.model,
2046
+ toolNames: retryableHistoricalTools,
2047
+ attempt: historicalToolFailureRetries,
2048
+ cap: NO_TOOL_CALL_MAX_RETRIES,
2049
+ },
2050
+ });
2051
+ rejectAttempt(msg, [{
2052
+ role: "user",
2053
+ content: `this exact request previously reached a tool that is advertised again now. Its unresolved historical effect is through ${retryableHistoricalTools.join(", ")}. Only that tool is available now. Read current state if needed, then retry the exact failed effect. Do not report completion until the effect succeeds.`,
2054
+ }]);
2055
+ continue;
435
2056
  }
436
- catch {
437
- // JSON parsing failed (e.g. truncated output) — answer stays undefined (retry)
2057
+ const requiredToolCallsGate = pendingRequiredToolCalls();
2058
+ if (requiredToolCallsGate) {
2059
+ streamCallbackBuffer?.discard();
2060
+ callbacks.onClearText?.();
2061
+ queueRequiredCorrection(msg, requiredToolCallsGate.message, "before required tool calls completed");
2062
+ (0, runtime_1.emitNervesEvent)({
2063
+ level: "warn",
2064
+ component: "engine",
2065
+ event: "engine.required_tool_calls_pending",
2066
+ message: "terminal response rejected until required tool handlers dispatch",
2067
+ meta: { missingToolNames: requiredToolCallsGate.missing },
2068
+ });
2069
+ continue;
2070
+ }
2071
+ const requiredAnswerRejection = options?.requiredToolCalls?.validateTerminalAnswer?.(String(msg.content ?? ""));
2072
+ if (requiredAnswerRejection) {
2073
+ streamCallbackBuffer?.discard();
2074
+ callbacks.onClearText?.();
2075
+ queueRequiredCorrection(msg, requiredAnswerRejection, "before required terminal answer validation completed");
2076
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "engine", event: "engine.required_tool_answer_rejected", message: "unsupported terminal answer rejected after required reads", meta: { answerLength: String(msg.content ?? "").length } });
2077
+ continue;
438
2078
  }
439
- if (answer != null) {
440
- if (result.finalAnswerStreamed) {
441
- // The streaming layer already parsed and emitted the answer
442
- // progressively via FinalAnswerParser. Skip clearing and
443
- // re-emitting to avoid double-delivery.
2079
+ if (privateReturnTextAckRetryError) {
2080
+ streamCallbackBuffer?.discard();
2081
+ callbacks.onClearText?.();
2082
+ if (noToolCallRetries < NO_TOOL_CALL_MAX_RETRIES) {
2083
+ noToolCallRetries++;
2084
+ (0, runtime_1.emitNervesEvent)({
2085
+ level: "warn",
2086
+ component: "engine",
2087
+ event: "engine.no_tool_call_retry",
2088
+ message: "model returned a text-only private-return acknowledgement without ponder; retrying with corrective nudge",
2089
+ meta: {
2090
+ attempt: noToolCallRetries,
2091
+ cap: NO_TOOL_CALL_MAX_RETRIES,
2092
+ provider: providerRuntime.id,
2093
+ model: providerRuntime.model,
2094
+ reason: "private_return_missing_ponder",
2095
+ contentLength: result.content.length,
2096
+ },
2097
+ });
2098
+ rejectAttempt(msg, [{
2099
+ role: "user",
2100
+ content: `${privateReturnTextAckRetryError} Emit the ponder(action=create, ...) tool call now, or ask a blocking clarification without saying the private work is queued.`,
2101
+ }]);
2102
+ continue;
444
2103
  }
445
- else {
446
- // Clear any streamed noise (e.g. refusal text) before emitting.
447
- callbacks.onClearText?.();
448
- // Emit the answer through the callback pipeline so channels receive it.
449
- // Never truncate -- channel adapters handle splitting long messages.
450
- callbacks.onTextChunk(answer);
451
- }
452
- // Keep the full assistant message (with tool_calls) for debuggability,
453
- // plus a synthetic tool response so the conversation stays valid on resume.
454
- messages.push(msg);
455
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: "(delivered)" });
456
- providerRuntime.appendToolOutput(result.toolCalls[0].id, "(delivered)");
2104
+ const blockedAnswer = "I could not start the private pass. No private-attention packet was created, so no return work was queued.";
2105
+ (0, runtime_1.emitNervesEvent)({
2106
+ level: "error",
2107
+ component: "engine",
2108
+ event: "engine.private_return_missing_ponder_blocked",
2109
+ message: "private-return text acknowledgement skipped ponder through the retry cap; failing closed",
2110
+ meta: {
2111
+ cap: NO_TOOL_CALL_MAX_RETRIES,
2112
+ provider: providerRuntime.id,
2113
+ model: providerRuntime.model,
2114
+ contentLength: result.content.length,
2115
+ },
2116
+ });
2117
+ pushGenerated({ role: "assistant", content: blockedAnswer });
2118
+ callbacks.onTextChunk(blockedAnswer);
2119
+ completion = { answer: blockedAnswer, intent: "blocked" };
2120
+ outcome = "blocked";
457
2121
  done = true;
2122
+ continue;
2123
+ }
2124
+ if (onlyThinkContent && toolChoiceRequired && noToolCallRetries < NO_TOOL_CALL_MAX_RETRIES) {
2125
+ streamCallbackBuffer?.discard();
2126
+ // Provider-level violation: tool_choice was required, model emitted
2127
+ // only a <think>...</think> block (or empty content) with no tool
2128
+ // call. Retry with a corrective nudge up to NO_TOOL_CALL_MAX_RETRIES
2129
+ // times. After cap, accept as-is (the readback path strips think
2130
+ // tags and surfaces a clear diagnostic).
2131
+ noToolCallRetries++;
2132
+ (0, runtime_1.emitNervesEvent)({
2133
+ level: "warn",
2134
+ component: "engine",
2135
+ event: "engine.no_tool_call_retry",
2136
+ message: "model returned only <think> content with no tool call despite tool_choice=required; retrying with corrective nudge",
2137
+ meta: {
2138
+ attempt: noToolCallRetries,
2139
+ cap: NO_TOOL_CALL_MAX_RETRIES,
2140
+ provider: providerRuntime.id,
2141
+ model: providerRuntime.model,
2142
+ contentLength: result.content.length,
2143
+ },
2144
+ });
2145
+ rejectAttempt(msg, [{
2146
+ role: "user",
2147
+ content: isPrivateRuntimeChannel
2148
+ ? augmentedToolContext?.noSend === true
2149
+ ? "no tool was called this turn. this is an immutable no-send turn; call rest now without creating a continuation."
2150
+ : "no tool was called this turn. you must end every turn by calling rest (or surface, ponder, observe). emit the tool call now."
2151
+ : "no tool was called this turn. you must end every turn by calling settle with your answer (or ponder/observe). emit the tool call now.",
2152
+ }]);
2153
+ continue;
458
2154
  }
459
- else {
460
- // Answer is undefined -- the model's final_answer was incomplete or
461
- // malformed. Clear any partial streamed text or noise, then push the
462
- // assistant msg + error tool result and let the model try again.
2155
+ // A plain-text reply reaches the person just as a settle answer does, so the answer gates hold it too.
2156
+ const textAnswer = isPrivateRuntimeChannel ? "" : stripThinkBlocksForViolationCheck(result.content).trim();
2157
+ const textVerdict = textAnswer ? answerGateVerdict(textAnswer) : null;
2158
+ if (textVerdict?.error) {
2159
+ streamCallbackBuffer?.discard();
463
2160
  callbacks.onClearText?.();
464
- const retryError = "your final_answer was incomplete or malformed. call final_answer again with your complete response.";
465
- messages.push(msg);
466
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: retryError });
467
- providerRuntime.appendToolOutput(result.toolCalls[0].id, retryError);
2161
+ rejectAttempt(msg, [{ role: "user", content: textVerdict.error }]);
2162
+ continue;
468
2163
  }
469
- continue;
2164
+ if (textVerdict?.replacement) {
2165
+ streamCallbackBuffer?.discard();
2166
+ callbacks.onClearText?.();
2167
+ callbacks.onTextChunk(textVerdict.replacement);
2168
+ pushGenerated({ ...msg, content: textVerdict.replacement });
2169
+ done = true;
2170
+ continue;
2171
+ }
2172
+ // Legitimate text-only response, or cap reached — accept as-is.
2173
+ await streamCallbackBuffer?.flush();
2174
+ pushGenerated(msg);
2175
+ done = true;
470
2176
  }
471
- messages.push(msg);
472
- // SHARED: execute tools (final_answer in mixed calls is rejected inline)
473
- for (const tc of result.toolCalls) {
474
- if (signal?.aborted)
475
- break;
476
- // Intercept final_answer in mixed call: reject it
477
- if (tc.name === "final_answer") {
478
- const rejection = "rejected: final_answer must be the only tool call. Finish your work first, then call final_answer alone.";
479
- messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
480
- providerRuntime.appendToolOutput(tc.id, rejection);
2177
+ else {
2178
+ // Reset the retry counter on any successful tool call.
2179
+ noToolCallRetries = 0;
2180
+ const preCallMessages = structuredClone(messages.filter((message) => message.role !== "system"));
2181
+ // A held-back door called by name (find_tools's description lists every one) counts as found: it is checked
2182
+ // against its own schema, runs, and stays loaded. A step narrowed to one tool admits none.
2183
+ const calledHeldBack = activeTools === candidateActiveTools
2184
+ ? deferralPool.filter((tool) => !activeToolNames.has(tool.function.name) && result.toolCalls.some((call) => call.name === tool.function.name))
2185
+ : [];
2186
+ // Not advertised means not yet loaded, so each is new to the loaded list.
2187
+ for (const tool of calledHeldBack)
2188
+ loadedDeferredTools.push(tool.function.name);
2189
+ const callableTools = [...activeTools, ...calledHeldBack];
2190
+ const callableToolNames = new Set(callableTools.map((tool) => tool.function.name));
2191
+ const validatedCalls = validateToolCallBatchAtProductionBoundary(result.toolCalls, callableTools);
2192
+ const invalidCall = validatedCalls.find((entry) => "error" in entry);
2193
+ if (invalidCall) {
2194
+ streamCallbackBuffer?.discard();
2195
+ const unadvertisedCall = validatedCalls.find((entry) => !callableToolNames.has(entry.call.name));
2196
+ const rejections = [];
2197
+ for (const entry of validatedCalls) {
2198
+ const detail = "error" in entry ? entry.error : "another call in this batch had invalid arguments";
2199
+ const rejection = unadvertisedCall
2200
+ ? (0, tools_base_1.withCode)(`rejected: ${entry.call.name} was not advertised for this channel; no handler was executed.`, "unknown-tool")
2201
+ : (0, tools_base_1.withCode)(`invalid tool arguments: ${detail}`, "invalid-arguments");
2202
+ rejections.push(rejection);
2203
+ // A rejected call never reaches onToolEnd; count it as a failed call (a name the turn never offered is "unknown").
2204
+ turnTally.rejected(entry.call.name);
2205
+ options?.toolBoundaryObserver?.({
2206
+ name: entry.call.name,
2207
+ reason: callableToolNames.has(entry.call.name) ? "invalid_arguments" : "profile_excluded",
2208
+ globallyResolvable: typeof (0, tools_1.resolveToolDefinition)(entry.call.name)?.handler === "function",
2209
+ invoked: false,
2210
+ sideEffect: false,
2211
+ });
2212
+ }
2213
+ rejectToolBatch(msg, rejections);
2214
+ if (unadvertisedCall) {
2215
+ (0, runtime_1.emitNervesEvent)({
2216
+ level: "warn",
2217
+ component: "engine",
2218
+ event: "engine.unadvertised_tool_blocked",
2219
+ message: "blocked an unadvertised tool call before batch execution",
2220
+ meta: { channel: String(channel), toolName: unadvertisedCall.call.name },
2221
+ });
2222
+ }
2223
+ else {
2224
+ (0, runtime_1.emitNervesEvent)({
2225
+ level: "warn",
2226
+ component: "engine",
2227
+ event: "engine.tool_arguments_rejected",
2228
+ message: "tool batch rejected before execution because arguments were invalid",
2229
+ meta: { toolCallId: invalidCall.call.id, toolName: invalidCall.call.name },
2230
+ });
2231
+ }
481
2232
  continue;
482
2233
  }
483
- let args = {};
484
- try {
485
- args = JSON.parse(tc.arguments);
2234
+ const validCalls = validatedCalls;
2235
+ const validatedCallArguments = new Map(validCalls.map((entry) => [
2236
+ entry.call,
2237
+ entry.validated.arguments,
2238
+ ]));
2239
+ const preflightRejections = new Map();
2240
+ for (const entry of validCalls) {
2241
+ if (entry.call.name === tool_catalog_1.FIND_TOOLS_NAME)
2242
+ continue;
2243
+ if (!relationship && !toolSelection.engine.some((tool) => tool.function.name === entry.call.name))
2244
+ continue;
2245
+ const prepared = await (0, tools_1.preflightToolCall)(entry.call.name, validatedCallArguments.get(entry.call), augmentedToolContext);
2246
+ if (prepared.kind !== "ready")
2247
+ preflightRejections.set(entry.call.id, prepared.text);
2248
+ }
2249
+ if (preflightRejections.size > 0) {
2250
+ streamCallbackBuffer?.discard();
2251
+ rejectToolBatch(msg, result.toolCalls.map((call) => preflightRejections.get(call.id)
2252
+ ?? "rejected: another call in this batch failed current authorization; no handler was executed."));
2253
+ continue;
2254
+ }
2255
+ const habitBlockReason = await habitToolBatchBlockReason(habitSession, result.toolCalls, augmentedToolContext?.delegatedOrigins);
2256
+ if (habitBlockReason) {
2257
+ streamCallbackBuffer?.discard();
2258
+ recordBlockedHabitSurfaceAttempts(habitSession, result.toolCalls, habitBlockReason);
2259
+ const blockedOutput = `blocked: ${habitBlockReason}. No tool side effects from this assistant message were executed.`;
2260
+ rejectToolBatch(msg, result.toolCalls.map(() => blockedOutput));
2261
+ (0, runtime_1.emitNervesEvent)({
2262
+ level: "warn",
2263
+ component: "engine",
2264
+ event: "engine.habit_tool_batch_blocked",
2265
+ message: "habit tool batch blocked before side effects",
2266
+ meta: { reason: habitBlockReason, toolCalls: result.toolCalls.map((call) => call.name) },
2267
+ });
2268
+ continue;
2269
+ }
2270
+ const soleViolation = result.toolCalls.length > 1
2271
+ ? result.toolCalls.find((call) => SOLE_CALL_REJECTION[call.name] !== undefined || (0, tools_1.resolveToolDefinition)(call.name, toolSelection)?.terminalProjection?.requiresSoleCall === true)
2272
+ : undefined;
2273
+ if (soleViolation) {
2274
+ streamCallbackBuffer?.discard();
2275
+ const reason = SOLE_CALL_REJECTION[soleViolation.name] ?? `rejected: ${soleViolation.name} must be the only tool call.`;
2276
+ rejectToolBatch(msg, result.toolCalls.map(() => reason));
2277
+ continue;
2278
+ }
2279
+ const soleTerminalCall = result.toolCalls.length === 1
2280
+ ? result.toolCalls[0]
2281
+ : null;
2282
+ const soleTerminalProjection = soleTerminalCall
2283
+ ? (0, tools_1.resolveToolDefinition)(soleTerminalCall.name, toolSelection)?.terminalProjection
2284
+ : undefined;
2285
+ if (soleTerminalCall && soleTerminalProjection?.mode === "verbatim") {
2286
+ const terminalArgs = validatedCallArguments.get(soleTerminalCall);
2287
+ if (soleTerminalProjection.clearBufferedText
2288
+ || callbacks.settleOutputMode === "final_only") {
2289
+ streamCallbackBuffer?.discard();
2290
+ }
2291
+ else {
2292
+ await streamCallbackBuffer?.flush();
2293
+ }
2294
+ if (soleTerminalProjection.clearBufferedText)
2295
+ callbacks.onClearText?.();
2296
+ callbacks.onToolStart(soleTerminalCall.name, terminalArgs);
2297
+ let terminalResult;
2298
+ let terminalSucceeded = false;
2299
+ try {
2300
+ if (options?.execTool && !relationship) {
2301
+ callbacks.onToolDispatch?.(soleTerminalCall.name);
2302
+ terminalResult = await options.execTool(soleTerminalCall.name, terminalArgs, trustedToolContext);
2303
+ terminalSucceeded = true;
2304
+ }
2305
+ else {
2306
+ const execution = await (0, tools_1.executeTool)(soleTerminalCall.name, terminalArgs, withDispatchNotice(augmentedToolContext, soleTerminalCall.name), options?.execTool);
2307
+ terminalResult = "error" in execution
2308
+ ? `error: ${execution.error instanceof Error ? execution.error.message : String(execution.error)}`
2309
+ : execution.text;
2310
+ terminalSucceeded = execution.kind === "handler_succeeded";
2311
+ }
2312
+ }
2313
+ catch (error) {
2314
+ terminalResult = error instanceof Error ? `error: ${error.message}` : `error: ${String(error)}`;
2315
+ }
2316
+ callbacks.onToolEnd(soleTerminalCall.name, (0, tools_1.summarizeArgs)(soleTerminalCall.name, terminalArgs, toolSelection), terminalSucceeded);
2317
+ pushGenerated(msg);
2318
+ const shieldedTerminalResult = (0, delegated_command_1.shieldDelegatedBanner)(terminalResult);
2319
+ pushGenerated({ role: "tool", tool_call_id: soleTerminalCall.id, content: shieldedTerminalResult });
2320
+ providerRuntime.appendToolOutput(soleTerminalCall.id, shieldedTerminalResult);
2321
+ callbacks.onTextChunk(terminalResult);
2322
+ completion = { answer: terminalResult, intent: terminalSucceeded ? "complete" : "blocked" };
2323
+ outcome = terminalSucceeded ? "settled" : "blocked";
2324
+ done = true;
2325
+ continue;
2326
+ }
2327
+ // Check for settle sole call: intercept before tool execution
2328
+ if (isSoleSettle) {
2329
+ const settleArgs = validatedCallArguments.get(result.toolCalls[0]);
2330
+ callbacks.onToolStart("settle", settleArgs);
2331
+ const requiredToolCallsGate = pendingRequiredToolCalls();
2332
+ if (requiredToolCallsGate) {
2333
+ streamCallbackBuffer?.discard();
2334
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs, toolSelection), false);
2335
+ callbacks.onClearText?.();
2336
+ queueRequiredCorrection(msg, requiredToolCallsGate.message, "before required tool calls completed");
2337
+ (0, runtime_1.emitNervesEvent)({
2338
+ level: "warn",
2339
+ component: "engine",
2340
+ event: "engine.required_tool_calls_pending",
2341
+ message: "settle rejected until required tool handlers dispatch",
2342
+ meta: { missingToolNames: requiredToolCallsGate.missing },
2343
+ });
2344
+ continue;
2345
+ }
2346
+ // Private-runtime attention queue gate: reject settle if items remain
2347
+ const attentionQueue = augmentedToolContext?.delegatedOrigins;
2348
+ if (isPrivateRuntimeChannel && attentionQueue && attentionQueue.length > 0) {
2349
+ streamCallbackBuffer?.discard();
2350
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs, toolSelection), false);
2351
+ callbacks.onClearText?.();
2352
+ const gateMessage = tools_flow_1.FLOW_TOOL_REFUSALS.settleHeldWork;
2353
+ rejectToolBatch(msg, [gateMessage]);
2354
+ continue;
2355
+ }
2356
+ // Extract answer from the tool call arguments.
2357
+ // Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
2358
+ const { answer, intent } = parseSettlePayload(result.toolCalls[0].arguments);
2359
+ const requiredAnswerRejection = options?.requiredToolCalls?.validateTerminalAnswer?.(answer);
2360
+ if (requiredAnswerRejection) {
2361
+ streamCallbackBuffer?.discard();
2362
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs, toolSelection), false);
2363
+ callbacks.onClearText?.();
2364
+ queueRequiredCorrection(msg, requiredAnswerRejection, "before required terminal answer validation completed");
2365
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "engine", event: "engine.required_tool_answer_rejected", message: "unsupported settle answer rejected after required reads", meta: { answerLength: answer.length } });
2366
+ continue;
2367
+ }
2368
+ // Private-runtime settle: no CompletionMetadata, "(settled)" ack
2369
+ if (isPrivateRuntimeChannel) {
2370
+ streamCallbackBuffer?.discard();
2371
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs, toolSelection), true);
2372
+ pushGenerated(msg);
2373
+ const settled = "(settled)";
2374
+ pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: settled });
2375
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, settled);
2376
+ outcome = "settled";
2377
+ done = true;
2378
+ continue;
2379
+ }
2380
+ // The provider finalizer has already established a top-level string
2381
+ // answer before ordinary settle handling reaches this point.
2382
+ const deliveredAnswer = answer;
2383
+ // Never spend the last provider iteration on this optional retry: delivering the recap beats delivering nothing.
2384
+ const contentMismatch = sawSettleContentMismatch || providerIterations >= stepBudget - 1 ? null : settleContentMismatchError(msg.content, deliveredAnswer);
2385
+ if (contentMismatch) {
2386
+ sawSettleContentMismatch = true;
2387
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "engine", event: "engine.settle_content_mismatch", message: "settle answer differs from the reply text written beside it; asking once for the reply as the answer", meta: { answerLength: deliveredAnswer.length, contentLength: msg.content.length } });
2388
+ }
2389
+ const { error: answerGateError, replacement } = answerGateVerdict(deliveredAnswer, intent);
2390
+ const retryError = contentMismatch
2391
+ ?? answerGateError
2392
+ ?? privateReturnAckLeakError(deliveredAnswer, privateReturnHeldTokens)
2393
+ ?? privateReturnMissingPonderError({
2394
+ latestUserRequest: latestUserMessageText(messages),
2395
+ answer: deliveredAnswer,
2396
+ sawPonder,
2397
+ })
2398
+ ?? getSettleRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp, options?.delegationDecision, sawSendMessageSelf, sawPonder, sawQuerySession, options?.currentObligation ?? null, options?.activeWorkFrame?.inner?.job, sawExternalStateQuery);
2399
+ const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
2400
+ // A check-back is filed only once every gate has passed, through await_condition itself, so it is bound and
2401
+ // permitted exactly as that tool would be. If it can't be filed, nothing is sent and the model is told why.
2402
+ let checkBackError = null;
2403
+ let checkBackFiled = null;
2404
+ if (retryError === null && (settleArgs.check_back_at !== undefined || settleArgs.condition !== undefined)) {
2405
+ // The schema gate has already made both strings when present.
2406
+ const at = (settleArgs.check_back_at ?? "").trim();
2407
+ const condition = (settleArgs.condition ?? "").trim();
2408
+ if (!at || !condition) {
2409
+ checkBackError = tools_flow_1.FLOW_TOOL_REFUSALS.settleCheckBackIncomplete;
2410
+ }
2411
+ else {
2412
+ const awaitArgs = { name: `check-back-${Date.now().toString(36)}`, condition, cadence: tools_flow_1.SETTLE_CHECK_BACK_CADENCE, wake_at: at };
2413
+ let filedText;
2414
+ try {
2415
+ if (options?.execTool && !relationship) {
2416
+ filedText = await options.execTool("await_condition", awaitArgs, trustedToolContext);
2417
+ }
2418
+ else {
2419
+ // A failed execution's text is its error, which reads below as the reason.
2420
+ filedText = (await (0, tools_1.executeTool)("await_condition", awaitArgs, augmentedToolContext, options?.execTool)).text;
2421
+ }
2422
+ }
2423
+ catch (error) {
2424
+ filedText = JSON.stringify({ error: error instanceof Error ? error.message : String(error) });
2425
+ }
2426
+ let parsed = {};
2427
+ try {
2428
+ parsed = JSON.parse(filedText);
2429
+ }
2430
+ catch {
2431
+ parsed = { error: filedText };
2432
+ }
2433
+ if (parsed.filed === awaitArgs.name) {
2434
+ checkBackFiled = { name: awaitArgs.name, at };
2435
+ }
2436
+ else {
2437
+ checkBackError = tools_flow_1.FLOW_TOOL_REFUSALS.settleCheckBackNotFiled(typeof parsed.error === "string" ? parsed.error : "await_condition gave no receipt");
2438
+ }
2439
+ }
2440
+ (0, runtime_1.emitNervesEvent)({
2441
+ level: checkBackError ? "warn" : "info",
2442
+ component: "engine",
2443
+ event: "engine.settle_check_back",
2444
+ message: "settle asked to leave a check-back",
2445
+ meta: { filed: checkBackFiled !== null },
2446
+ });
2447
+ }
2448
+ if (retryError === null && checkBackError === null) {
2449
+ const finalAnswer = replacement ?? deliveredAnswer;
2450
+ const rewritten = replacement !== null;
2451
+ try {
2452
+ if (rewritten && result.settleStreamed)
2453
+ callbacks.onClearText?.();
2454
+ if (rewritten || !result.settleStreamed) {
2455
+ const acceptedOutputCallbacks = streamCallbackBuffer?.callbacks ?? callbacks;
2456
+ acceptedOutputCallbacks.onTextChunk(finalAnswer);
2457
+ }
2458
+ await streamCallbackBuffer?.flush();
2459
+ }
2460
+ catch (error) {
2461
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs, toolSelection), false);
2462
+ streamCallbackBuffer?.discard();
2463
+ finishTerminalProviderError(new streaming_1.SettleFinalizationCallbackError(error), "unknown");
2464
+ continue;
2465
+ }
2466
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs, toolSelection), true);
2467
+ completion = {
2468
+ answer: finalAnswer,
2469
+ intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
2470
+ };
2471
+ // Retractable owners already hold the validated answer. Final-only
2472
+ // owners receive it here, after every semantic continuation gate.
2473
+ pushGenerated(rewritten ? withSettleAnswer(msg, settleArgs, finalAnswer) : msg);
2474
+ if (validDirectReply) {
2475
+ const resumeWork = "direct reply delivered. resume the unresolved obligation now and keep working until you can finish or clearly report that you are blocked.";
2476
+ pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: resumeWork });
2477
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, resumeWork);
2478
+ }
2479
+ else {
2480
+ const delivered = checkBackFiled ? `(delivered; check-back ${checkBackFiled.name} filed for ${checkBackFiled.at})` : "(delivered)";
2481
+ pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
2482
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
2483
+ outcome = intent === "blocked" ? "blocked" : "settled";
2484
+ done = true;
2485
+ }
2486
+ }
2487
+ else {
2488
+ // The payload is structurally final, but a semantic continuation
2489
+ // gate rejected it. Return that exact gate reason to the model.
2490
+ streamCallbackBuffer?.discard();
2491
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs, toolSelection), false);
2492
+ callbacks.onClearText?.();
2493
+ rejectToolBatch(msg, [(retryError ?? checkBackError)]);
2494
+ }
2495
+ continue;
486
2496
  }
487
- catch {
488
- /* ignore */
2497
+ // Check for observe sole call: intercept before tool execution
2498
+ const isSoleObserve = result.toolCalls.length === 1 && result.toolCalls[0].name === "observe";
2499
+ if (isSoleObserve) {
2500
+ streamCallbackBuffer?.discard();
2501
+ const observeArgs = validatedCallArguments.get(result.toolCalls[0]);
2502
+ let reason;
2503
+ if (typeof observeArgs?.reason === "string")
2504
+ reason = observeArgs.reason;
2505
+ callbacks.onToolStart("observe", observeArgs);
2506
+ (0, runtime_1.emitNervesEvent)({
2507
+ component: "engine",
2508
+ event: "engine.observe",
2509
+ message: "agent observed without responding",
2510
+ meta: { ...(reason ? { reason } : {}) },
2511
+ });
2512
+ callbacks.onToolEnd("observe", (0, tools_1.summarizeArgs)("observe", observeArgs, toolSelection), true);
2513
+ pushGenerated(msg);
2514
+ const silenced = "(silenced)";
2515
+ pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: silenced });
2516
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, silenced);
2517
+ outcome = "observed";
2518
+ done = true;
2519
+ continue;
489
2520
  }
490
- const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
491
- // Confirmation check for mutate tools
492
- if ((0, tools_1.isConfirmationRequired)(tc.name) && !options?.skipConfirmation) {
493
- let decision = "denied";
494
- if (callbacks.onConfirmAction) {
495
- decision = await callbacks.onConfirmAction(tc.name, args);
496
- }
497
- if (decision !== "confirmed") {
498
- const cancelled = "Action cancelled by user.";
499
- callbacks.onToolStart(tc.name, args);
500
- callbacks.onToolEnd(tc.name, argSummary, false);
501
- messages.push({ role: "tool", tool_call_id: tc.id, content: cancelled });
502
- providerRuntime.appendToolOutput(tc.id, cancelled);
2521
+ // Check for rest sole call: intercept before tool execution
2522
+ const isSoleRest = result.toolCalls.length === 1 && result.toolCalls[0].name === "rest";
2523
+ if (isSoleRest) {
2524
+ streamCallbackBuffer?.discard();
2525
+ const restArgs = validatedCallArguments.get(result.toolCalls[0]);
2526
+ callbacks.onToolStart("rest", restArgs);
2527
+ // Attention queue gate: reject rest if items remain
2528
+ // A budget wrap-up rest is final: held work and fresh messages wait for the next turn.
2529
+ const wrappingUp = stepReportIteration !== null;
2530
+ const attentionQueue = augmentedToolContext?.delegatedOrigins;
2531
+ if (!wrappingUp && attentionQueue && attentionQueue.length > 0) {
2532
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs, toolSelection), false);
2533
+ const gateMessage = tools_flow_1.FLOW_TOOL_REFUSALS.restHeldWork;
2534
+ rejectToolBatch(msg, [gateMessage]);
2535
+ continue;
2536
+ }
2537
+ if (!wrappingUp && hasFreshPendingWork(options) && !freshWorkGateFired) {
2538
+ freshWorkGateFired = true;
2539
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs, toolSelection), false);
2540
+ const gateMessage = tools_flow_1.FLOW_TOOL_REFUSALS.restFreshWork;
2541
+ rejectToolBatch(msg, [gateMessage]);
2542
+ (0, runtime_1.emitNervesEvent)({
2543
+ level: "info",
2544
+ component: "engine",
2545
+ event: "engine.fresh_work_gate_fired",
2546
+ message: "rest deferred once because pending work arrived this turn; agent has been notified",
2547
+ meta: { pendingCount: options.pendingMessages.length },
2548
+ });
2549
+ continue;
2550
+ }
2551
+ const unsentSurface = !wrappingUp && !surfaceNotSentGateFired ? unsentSurfaceResult(turnToolRecords) : null;
2552
+ if (unsentSurface) {
2553
+ surfaceNotSentGateFired = true;
2554
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs, toolSelection), false);
2555
+ rejectToolBatch(msg, [tools_flow_1.FLOW_TOOL_REFUSALS.restSurfaceNotSent(unsentSurface)]);
2556
+ (0, runtime_1.emitNervesEvent)({
2557
+ level: "info",
2558
+ component: "engine",
2559
+ event: "engine.surface_not_sent_gate_fired",
2560
+ message: "rest deferred once because a surface this turn was not sent; agent has been notified",
2561
+ meta: {},
2562
+ });
2563
+ continue;
2564
+ }
2565
+ const actLines = !wrappingUp && !actGateFired ? unansweredActLines(turnToolRecords) : null;
2566
+ if (actLines) {
2567
+ actGateFired = true;
2568
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs, toolSelection), false);
2569
+ rejectToolBatch(msg, [tools_flow_1.FLOW_TOOL_REFUSALS.restActUnanswered(actLines)]);
2570
+ (0, runtime_1.emitNervesEvent)({
2571
+ level: "info",
2572
+ component: "engine",
2573
+ event: "engine.act_gate_fired",
2574
+ message: "rest deferred once because a tool printed ACT: lines and nobody was told; agent has been notified",
2575
+ meta: { lines: actLines.split("\n").length },
2576
+ });
503
2577
  continue;
504
2578
  }
2579
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs, toolSelection), true);
2580
+ pushGenerated(msg);
2581
+ const ack = "(resting)";
2582
+ pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
2583
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
2584
+ (0, runtime_1.emitNervesEvent)({
2585
+ component: "engine",
2586
+ event: "engine.rested",
2587
+ message: "resting until next heartbeat",
2588
+ meta: { ...(typeof restArgs?.status === "string" ? { status: restArgs.status } : {}) },
2589
+ });
2590
+ outcome = "rested";
2591
+ done = true;
2592
+ continue;
505
2593
  }
506
- callbacks.onToolStart(tc.name, args);
507
- let toolResult;
508
- let success;
509
- try {
510
- const execToolFn = options?.execTool ?? tools_1.execTool;
511
- toolResult = await execToolFn(tc.name, args, options?.toolContext);
512
- success = true;
2594
+ const requiredDispatchRejections = new Map();
2595
+ for (const entry of validCalls) {
2596
+ const requiredArgs = entry.validated.arguments;
2597
+ const rejection = options?.requiredToolCalls?.validateToolCallBeforeDispatch?.(entry.call.name, requiredArgs);
2598
+ if (!rejection)
2599
+ continue;
2600
+ const rejectionKey = `${entry.call.name}\0${rejection}`;
2601
+ const priorRejections = requiredDispatchRejectionCounts.get(rejectionKey) ?? 0;
2602
+ if (priorRejections >= 2) {
2603
+ (0, runtime_1.emitNervesEvent)({
2604
+ level: "warn", component: "engine", event: "engine.required_tool_dispatch_advisory",
2605
+ message: "required tool dependency rejected twice this turn; letting the call through",
2606
+ meta: { toolName: entry.call.name },
2607
+ });
2608
+ continue;
2609
+ }
2610
+ requiredDispatchRejectionCounts.set(rejectionKey, priorRejections + 1);
2611
+ requiredDispatchRejections.set(entry.call.id, { name: entry.call.name, args: requiredArgs, message: rejection });
513
2612
  }
514
- catch (e) {
515
- toolResult = `error: ${e}`;
516
- success = false;
2613
+ if (requiredDispatchRejections.size > 0) {
2614
+ streamCallbackBuffer?.discard();
2615
+ for (const rejection of requiredDispatchRejections.values()) {
2616
+ callbacks.onToolStart(rejection.name, rejection.args);
2617
+ callbacks.onToolEnd(rejection.name, (0, tools_1.summarizeArgs)(rejection.name, rejection.args, toolSelection), false);
2618
+ options?.toolBoundaryObserver?.({
2619
+ name: rejection.name, reason: "dependency_rejected",
2620
+ globallyResolvable: typeof (0, tools_1.resolveToolDefinition)(rejection.name)?.handler === "function",
2621
+ invoked: false, sideEffect: false,
2622
+ });
2623
+ (0, runtime_1.emitNervesEvent)({
2624
+ level: "warn", component: "engine", event: "engine.required_tool_dispatch_rejected",
2625
+ message: "required tool dependency rejected before approval and handler dispatch",
2626
+ meta: { toolName: rejection.name },
2627
+ });
2628
+ }
2629
+ rejectToolBatch(msg, result.toolCalls.map((call) => requiredDispatchRejections.get(call.id)?.message
2630
+ ?? "rejected: another call in this batch has an unsatisfied required dependency; no handler was executed."));
2631
+ continue;
2632
+ }
2633
+ const executionRejections = new Map();
2634
+ for (const entry of validCalls) {
2635
+ const args = validatedCallArguments.get(entry.call);
2636
+ const fingerprint = effectFingerprint(entry.call.name, entry.call.arguments, toolSelection);
2637
+ if (forcingHistoricalEffect && fingerprint && !unresolvedHistoricalEffects.some((effect) => effect.fingerprint === fingerprint)) {
2638
+ executionRejections.set(entry.call.id, "rejected: this turn is retrying an unresolved historical effect, and these mutation arguments do not match it. Read current state or retry the exact failed effect.");
2639
+ }
2640
+ else if (entry.call.name === "send_message" && args.friendId === "self" && !isPrivateRuntimeChannel && looksLikePrivateReturnRequest(latestUserMessageText(messages))) {
2641
+ executionRejections.set(entry.call.id, "private-return requests must use ponder, not send_message(friendId=self). Create a typed ponder packet with the marker/source request preserved, then only acknowledge that the private pass is queued.");
2642
+ }
2643
+ else if (entry.call.name !== "speak" && entry.call.name !== "ponder") {
2644
+ const loop = (0, tool_loop_1.detectToolLoop)(toolLoopState, entry.call.name, args);
2645
+ if (loop.stuck)
2646
+ executionRejections.set(entry.call.id, `loop guard: ${loop.message}`);
2647
+ }
2648
+ }
2649
+ if (executionRejections.size > 0) {
2650
+ streamCallbackBuffer?.discard();
2651
+ for (const entry of validCalls) {
2652
+ if (!executionRejections.has(entry.call.id))
2653
+ continue;
2654
+ const args = validatedCallArguments.get(entry.call);
2655
+ callbacks.onToolStart(entry.call.name, args);
2656
+ callbacks.onToolEnd(entry.call.name, (0, tools_1.summarizeArgs)(entry.call.name, args, toolSelection), false);
2657
+ }
2658
+ rejectToolBatch(msg, result.toolCalls.map((call) => executionRejections.get(call.id)
2659
+ ?? "rejected: another call in this batch was inadmissible; no handler was executed."));
2660
+ continue;
2661
+ }
2662
+ const approvalCalls = await Promise.all(validCalls.map(async (entry) => {
2663
+ const classification = await (0, tools_1.classifyApprovalForInvocation)(entry.call.name, entry.validated.arguments, augmentedToolContext);
2664
+ return {
2665
+ ...entry,
2666
+ ...classification,
2667
+ };
2668
+ }));
2669
+ const protectedCall = approvalCalls.find((entry) => entry.policy.kind === "required");
2670
+ if (protectedCall && result.toolCalls.length !== 1) {
2671
+ streamCallbackBuffer?.discard();
2672
+ rejectToolBatch(msg, result.toolCalls.map(() => "rejected: approval-eligible tool must be the sole call; no call in this batch was executed."));
2673
+ (0, runtime_1.emitNervesEvent)({
2674
+ level: "warn",
2675
+ component: "engine",
2676
+ event: "engine.approval_mixed_batch_rejected",
2677
+ message: "protected tool batch rejected before every handler",
2678
+ meta: { toolCallCount: result.toolCalls.length, protectedToolName: protectedCall.call.name },
2679
+ });
2680
+ continue;
2681
+ }
2682
+ if (protectedCall && protectedCall.policy.kind === "required") {
2683
+ if (!options?.approvalCoordinator) {
2684
+ streamCallbackBuffer?.discard();
2685
+ const rejection = tools_1.APPROVAL_UNAVAILABLE_REJECTION;
2686
+ rejectToolBatch(msg, [rejection]);
2687
+ (0, runtime_1.emitNervesEvent)({
2688
+ level: "warn",
2689
+ component: "engine",
2690
+ event: "engine.approval_coordinator_unavailable",
2691
+ message: "protected tool failed closed before handler execution",
2692
+ meta: { toolName: protectedCall.call.name, toolCallId: protectedCall.call.id },
2693
+ });
2694
+ continue;
2695
+ }
2696
+ streamCallbackBuffer?.discard();
2697
+ const toolDigest = (0, tool_approval_1.digestApprovalToolDefinition)((0, tools_1.resolveToolDefinition)(protectedCall.call.name, toolSelection), protectedCall.validated.schemaDigest, protectedCall.policy.policyId);
2698
+ const policyDigest = (0, tool_arguments_1.digestJson)({
2699
+ policyId: protectedCall.policy.policyId,
2700
+ actionClass: protectedCall.policy.actionClass,
2701
+ classification: "required",
2702
+ });
2703
+ const committed = await options.approvalCoordinator.propose({
2704
+ toolCall: structuredClone(msg.tool_calls[0]),
2705
+ arguments: structuredClone(protectedCall.validated.arguments),
2706
+ preCallMessages,
2707
+ frozenAssistantMessage: structuredClone(msg),
2708
+ schemaDigest: protectedCall.validated.schemaDigest,
2709
+ toolDigest,
2710
+ policyDigest,
2711
+ policyId: protectedCall.policy.policyId,
2712
+ actionClass: protectedCall.policy.actionClass,
2713
+ liveToolContext: augmentedToolContext,
2714
+ });
2715
+ pushGenerated(msg);
2716
+ suspension = {
2717
+ approvalId: committed.approvalId,
2718
+ toolCallId: protectedCall.call.id,
2719
+ checkpointDigest: committed.checkpointDigest,
2720
+ suspendedSessionRevision: committed.suspendedSessionRevision,
2721
+ };
2722
+ outcome = "suspended";
2723
+ done = true;
2724
+ (0, runtime_1.emitNervesEvent)({
2725
+ component: "engine",
2726
+ event: "engine.approval_turn_suspended",
2727
+ message: "agent turn suspended before protected tool execution",
2728
+ meta: { approvalId: committed.approvalId, toolCallId: protectedCall.call.id },
2729
+ });
2730
+ continue;
2731
+ }
2732
+ await streamCallbackBuffer?.flush();
2733
+ pushGenerated(msg);
2734
+ const batchToolImages = [];
2735
+ // Every pre-dispatch gate accepted the complete batch.
2736
+ const isLastCall = (tc) => tc === result.toolCalls[result.toolCalls.length - 1];
2737
+ for (const tc of result.toolCalls) {
2738
+ if (signal?.aborted)
2739
+ break;
2740
+ const args = validatedCallArguments.get(tc);
2741
+ const currentEffectFingerprint = effectFingerprint(tc.name, tc.arguments, toolSelection);
2742
+ if (tc.name === "send_message" && args.friendId === "self") {
2743
+ sawSendMessageSelf = true;
2744
+ }
2745
+ if (tc.name === tool_catalog_1.FIND_TOOLS_NAME) {
2746
+ // The pre-batch schema gate guarantees a string query.
2747
+ const query = args.query;
2748
+ callbacks.onToolStart(tool_catalog_1.FIND_TOOLS_NAME, { query });
2749
+ const matchedNames = (0, tool_catalog_1.searchCatalog)(toolCatalog, deferralPool, query);
2750
+ const matched = deferralPool.filter((tool) => matchedNames.includes(tool.function.name))
2751
+ .sort((a, b) => matchedNames.indexOf(a.function.name) - matchedNames.indexOf(b.function.name));
2752
+ for (const name of matchedNames)
2753
+ if (!loadedDeferredTools.includes(name))
2754
+ loadedDeferredTools.push(name);
2755
+ turnTally.findTools(matched.map((tool) => tool.function.name));
2756
+ // A job a bundle does with a command its skill documents has no door to find; the skill's section answers.
2757
+ const skills = (0, skill_search_1.findToolsSkillNote)(query, activeToolNames);
2758
+ if (matched.length > 0 || skills.hits > 0)
2759
+ lastProgressIteration = providerIterations;
2760
+ const found = withBudgetNote((0, tool_catalog_1.formatFindToolsReply)(matched, skills.note), isLastCall(tc), candidateToolNames);
2761
+ pushGenerated({ role: "tool", tool_call_id: tc.id, content: found });
2762
+ providerRuntime.appendToolOutput(tc.id, found);
2763
+ // onToolEnd's success means a door was loaded; a skill-only reply loaded none, but is still progress.
2764
+ callbacks.onToolEnd(tool_catalog_1.FIND_TOOLS_NAME, query, matched.length > 0);
2765
+ (0, tool_catalog_1.recordFindTools)({ query, matched: matched.length, deferred: deferralPool.length, skills: skills.hits });
2766
+ continue;
2767
+ }
2768
+ if (tc.name === "speak") {
2769
+ // The canonical pre-batch schema gate guarantees a required string.
2770
+ const speakArgs = JSON.parse(tc.arguments);
2771
+ const speakMessage = speakArgs.message;
2772
+ const argSummary = (0, tools_1.summarizeArgs)("speak", { message: speakMessage }, toolSelection);
2773
+ callbacks.onToolStart("speak", { message: speakMessage });
2774
+ if (speakMessage.trim().length === 0) {
2775
+ const err = withBudgetNote(tools_flow_1.FLOW_TOOL_REFUSALS.speakEmpty, isLastCall(tc), candidateToolNames);
2776
+ callbacks.onToolEnd("speak", argSummary, false);
2777
+ pushGenerated({ role: "tool", tool_call_id: tc.id, content: err });
2778
+ providerRuntime.appendToolOutput(tc.id, err);
2779
+ (0, runtime_1.emitNervesEvent)({
2780
+ level: "warn",
2781
+ component: "engine",
2782
+ event: "engine.speak_invalid",
2783
+ message: "speak rejected: missing or empty message",
2784
+ meta: {},
2785
+ });
2786
+ continue;
2787
+ }
2788
+ callbacks.onToolDispatch?.("speak");
2789
+ callbacks.onTextChunk(speakMessage);
2790
+ let speakDeliveryError = null;
2791
+ try {
2792
+ await callbacks.flushNow?.();
2793
+ }
2794
+ catch (err) {
2795
+ speakDeliveryError = err instanceof Error ? err : new Error(String(err));
2796
+ }
2797
+ if (speakDeliveryError) {
2798
+ callbacks.onToolEnd("speak", argSummary, false);
2799
+ const failMsg = withBudgetNote(tools_flow_1.FLOW_TOOL_REFUSALS.speakNotDelivered(speakDeliveryError.message), isLastCall(tc), candidateToolNames);
2800
+ pushGenerated({ role: "tool", tool_call_id: tc.id, content: failMsg });
2801
+ providerRuntime.appendToolOutput(tc.id, failMsg);
2802
+ (0, runtime_1.emitNervesEvent)({
2803
+ level: "error",
2804
+ component: "engine",
2805
+ event: "engine.speak_delivery_failed",
2806
+ message: "speak delivery failed",
2807
+ meta: { error: speakDeliveryError.message, messageLength: speakMessage.length },
2808
+ });
2809
+ continue;
2810
+ }
2811
+ callbacks.onToolEnd("speak", argSummary, true);
2812
+ const ack = withBudgetNote("(spoken)", isLastCall(tc), candidateToolNames);
2813
+ pushGenerated({ role: "tool", tool_call_id: tc.id, content: ack });
2814
+ providerRuntime.appendToolOutput(tc.id, ack);
2815
+ (0, runtime_1.emitNervesEvent)({
2816
+ component: "engine",
2817
+ event: "engine.speak",
2818
+ message: "agent spoke mid-turn",
2819
+ meta: { messageLength: speakMessage.length },
2820
+ });
2821
+ continue;
2822
+ }
2823
+ if (tc.name === "ponder") {
2824
+ const parsedArgs = normalizeLegacyPonderArgs(parsePonderPayload(tc.arguments));
2825
+ const argSummary = (0, tools_1.summarizeArgs)(tc.name, parsedArgs, toolSelection);
2826
+ callbacks.onToolStart(tc.name, parsedArgs);
2827
+ callbacks.onToolDispatch?.(tc.name);
2828
+ let toolResult;
2829
+ let success = false;
2830
+ try {
2831
+ const action = parsedArgs.action ?? "create";
2832
+ const currentSession = augmentedToolContext?.currentSession;
2833
+ const currentOrigin = currentSession
2834
+ ? { friendId: currentSession.friendId, channel: currentSession.channel, key: currentSession.key }
2835
+ : undefined;
2836
+ const isInnerChannel = currentOrigin?.friendId === "self" && currentOrigin?.channel === "inner";
2837
+ const shouldCreateReturnObligation = !!currentOrigin && !isInnerChannel;
2838
+ const attentionQueue = augmentedToolContext?.delegatedOrigins ?? [];
2839
+ const successCriteria = parseSuccessCriteria(parsedArgs.success_criteria);
2840
+ const payload = parsePacketPayload(parsedArgs.payload_json);
2841
+ let packet;
2842
+ let returnObligationId = null;
2843
+ let resultAction = "created";
2844
+ let privateReturnSourceRequest = "";
2845
+ if (action === "create") {
2846
+ if (isInnerChannel && attentionQueue.length > 0) {
2847
+ throw new Error(tools_flow_1.FLOW_TOOL_REFUSALS.ponderHeldWork);
2848
+ }
2849
+ const kind = parsedArgs.kind;
2850
+ const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
2851
+ const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
2852
+ const sourceRequest = currentOrigin && !isInnerChannel ? latestUserMessageText(messages) : "";
2853
+ privateReturnSourceRequest = sourceRequest;
2854
+ if (!kind || !objective || !successCriteria || !payload) {
2855
+ throw new Error(tools_flow_1.FLOW_TOOL_REFUSALS.ponderCreateIncomplete);
2856
+ }
2857
+ const packetPayload = sourceRequest
2858
+ ? { ...payload, sourceRequest }
2859
+ : payload;
2860
+ const createLinkedReturnObligation = (id, packetId) => {
2861
+ (0, obligations_1.createReturnObligation)((0, identity_2.getAgentName)(), {
2862
+ id,
2863
+ origin: currentOrigin,
2864
+ status: "queued",
2865
+ delegatedContent: buildPonderDelegatedContent({ summary, objective, sourceRequest }),
2866
+ packetId,
2867
+ createdAt: Date.now(),
2868
+ });
2869
+ };
2870
+ const agentRoot = (0, identity_2.getAgentRoot)();
2871
+ let relatedObligationId;
2872
+ if (currentOrigin && !isInnerChannel) {
2873
+ try {
2874
+ const obligation = (0, obligations_1.createObligation)(agentRoot, {
2875
+ origin: currentOrigin,
2876
+ content: objective,
2877
+ });
2878
+ relatedObligationId = obligation.id;
2879
+ }
2880
+ catch {
2881
+ relatedObligationId = undefined;
2882
+ }
2883
+ }
2884
+ const frictionSignature = kind === "harness_friction" && typeof packetPayload.frictionSignature === "string"
2885
+ ? packetPayload.frictionSignature
2886
+ : null;
2887
+ const existing = frictionSignature && currentOrigin
2888
+ ? (0, packets_1.findHarnessFrictionPacket)(agentRoot, currentOrigin, frictionSignature)
2889
+ : null;
2890
+ if (existing) {
2891
+ resultAction = "revised";
2892
+ const existingActiveReturnId = shouldCreateReturnObligation
2893
+ ? activeReturnObligationId((0, identity_2.getAgentName)(), existing.relatedReturnObligationId)
2894
+ : null;
2895
+ returnObligationId = existingActiveReturnId
2896
+ ?? (shouldCreateReturnObligation ? (0, obligations_1.generateObligationId)(Date.now()) : null);
2897
+ packet = existing.status === "drafting"
2898
+ ? (0, packets_1.revisePonderPacket)(agentRoot, existing.id, {
2899
+ kind,
2900
+ objective,
2901
+ summary,
2902
+ successCriteria,
2903
+ payload: packetPayload,
2904
+ })
2905
+ : existing;
2906
+ if (returnObligationId && returnObligationId !== existing.relatedReturnObligationId) {
2907
+ packet = (0, packets_1.advancePonderPacket)(agentRoot, packet.id, { relatedReturnObligationId: returnObligationId });
2908
+ createLinkedReturnObligation(returnObligationId, packet.id);
2909
+ }
2910
+ }
2911
+ else {
2912
+ returnObligationId = shouldCreateReturnObligation ? (0, obligations_1.generateObligationId)(Date.now()) : null;
2913
+ packet = (0, packets_1.createPonderPacket)(agentRoot, {
2914
+ kind,
2915
+ objective,
2916
+ summary,
2917
+ successCriteria,
2918
+ ...(currentOrigin ? { origin: currentOrigin } : {}),
2919
+ ...(relatedObligationId ? { relatedObligationId } : {}),
2920
+ ...(returnObligationId ? { relatedReturnObligationId: returnObligationId } : {}),
2921
+ ...(parsedArgs.follows_packet_id ? { followsPacketId: parsedArgs.follows_packet_id } : {}),
2922
+ payload: packetPayload,
2923
+ });
2924
+ if (returnObligationId) {
2925
+ createLinkedReturnObligation(returnObligationId, packet.id);
2926
+ }
2927
+ }
2928
+ }
2929
+ else {
2930
+ const packetId = typeof parsedArgs.packet_id === "string" ? parsedArgs.packet_id.trim() : "";
2931
+ const kind = parsedArgs.kind;
2932
+ const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
2933
+ const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
2934
+ if (!packetId || !kind || !objective || !successCriteria || !payload) {
2935
+ throw new Error(tools_flow_1.FLOW_TOOL_REFUSALS.ponderReviseIncomplete);
2936
+ }
2937
+ packet = (0, packets_1.revisePonderPacket)((0, identity_2.getAgentRoot)(), packetId, {
2938
+ kind,
2939
+ objective,
2940
+ summary,
2941
+ successCriteria,
2942
+ payload,
2943
+ });
2944
+ returnObligationId = packet.relatedReturnObligationId
2945
+ && !(packet.origin?.friendId === "self" && packet.origin.channel === "inner")
2946
+ ? packet.relatedReturnObligationId
2947
+ : null;
2948
+ resultAction = "revised";
2949
+ }
2950
+ if (returnObligationId) {
2951
+ for (const token of extractPrivateReturnHeldTokens(privateReturnSourceRequest)) {
2952
+ privateReturnHeldTokens.add(token);
2953
+ }
2954
+ const agentName = (0, identity_2.getAgentName)();
2955
+ await (0, socket_client_1.requestPrivateWake)(agentName, augmentedToolContext?.daemonSocketPath, buildPonderReturnPrivateWakeOptions({ agentName, packet, returnObligationId })).catch(() => undefined);
2956
+ }
2957
+ sawPonder = true;
2958
+ toolResult = buildPonderResult(packet, resultAction, returnObligationId);
2959
+ success = true;
2960
+ (0, runtime_1.emitNervesEvent)({
2961
+ component: "engine",
2962
+ event: "engine.ponder_packet",
2963
+ message: "ponder packet touched",
2964
+ meta: {
2965
+ action: resultAction,
2966
+ packetId: packet.id,
2967
+ kind: packet.kind,
2968
+ status: packet.status,
2969
+ },
2970
+ });
2971
+ }
2972
+ catch (error) {
2973
+ toolResult = error instanceof Error ? error.message : String(error);
2974
+ }
2975
+ callbacks.onToolEnd(tc.name, argSummary, success);
2976
+ const shieldedToolResult = withBudgetNote((0, delegated_command_1.shieldDelegatedBanner)(toolResult), isLastCall(tc), candidateToolNames);
2977
+ pushGenerated({ role: "tool", tool_call_id: tc.id, content: shieldedToolResult });
2978
+ providerRuntime.appendToolOutput(tc.id, shieldedToolResult);
2979
+ continue;
2980
+ }
2981
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
2982
+ if (tc.name === "query_session")
2983
+ sawQuerySession = true;
2984
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
2985
+ if (tc.name === "bridge_manage")
2986
+ sawBridgeManage = true;
2987
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
2988
+ if (isExternalStateQuery(tc.name, args))
2989
+ sawExternalStateQuery = true;
2990
+ callbacks.onToolStart(tc.name, args);
2991
+ let toolResult;
2992
+ let success;
2993
+ let invoked = false;
2994
+ const toolImages = [];
2995
+ const withToolImageSink = (context) => context
2996
+ ? { ...context, attachToolImages: (images) => { toolImages.push(...images); } }
2997
+ : context;
2998
+ try {
2999
+ const routineActionSelection = approvalCalls.find((entry) => entry.call.id === tc.id)?.routineActionSelection;
3000
+ const executionToolContext = routineActionSelection && augmentedToolContext ? { ...augmentedToolContext, routineActionSelection } : augmentedToolContext;
3001
+ if (options?.execTool && !relationship) {
3002
+ invoked = true;
3003
+ callbacks.onToolDispatch?.(tc.name);
3004
+ toolResult = await options.execTool(tc.name, args, withToolImageSink(trustedToolContext));
3005
+ success = true;
3006
+ }
3007
+ else {
3008
+ const execution = await (0, tools_1.executeTool)(tc.name, args, withToolImageSink(withDispatchNotice(executionToolContext, tc.name)), options?.execTool);
3009
+ invoked = execution.kind !== "rejected_before_handler";
3010
+ success = execution.kind === "handler_succeeded";
3011
+ toolResult = "error" in execution ? `error: ${execution.error}` : execution.text;
3012
+ }
3013
+ }
3014
+ catch (e) {
3015
+ toolResult = `error: ${e}`;
3016
+ success = false;
3017
+ }
3018
+ if (success && tc.name === "load_skill") {
3019
+ // A skill names the doors its steps use; they load with it so the agent needn't find them one by one.
3020
+ const declared = (0, skill_summaries_1.declaredTools)(toolResult);
3021
+ const skillDoors = deferralPool.filter((tool) => declared.includes(tool.function.name));
3022
+ for (const tool of skillDoors)
3023
+ if (!loadedDeferredTools.includes(tool.function.name))
3024
+ loadedDeferredTools.push(tool.function.name);
3025
+ if (skillDoors.length > 0)
3026
+ toolResult = `${toolResult}\n\n${(0, tool_catalog_1.formatLoadedDoors)(skillDoors)}`;
3027
+ }
3028
+ if (success && toolImages.length > 0) {
3029
+ const visible = (0, tool_images_1.canModelSeeToolImages)(providerRuntime.model);
3030
+ toolResult = `${toolResult}${toolResult ? "\n\n" : ""}${(0, tool_images_1.toolImagesNote)(toolImages.length, providerRuntime.model, visible)}`;
3031
+ if (visible)
3032
+ batchToolImages.push({ toolName: tc.name, callId: tc.id, images: toolImages });
3033
+ }
3034
+ if (invoked && requiredToolCallNames.includes(tc.name) && !options?.requiredToolCalls?.requireSuccessfulResults)
3035
+ dispatchedRequiredToolCalls.add(tc.name);
3036
+ turnToolRecords.push({ name: tc.name, args, result: toolResult });
3037
+ for (const saved of surfacesReachedLater(turnToolRecords)) {
3038
+ try {
3039
+ (0, pending_1.withdrawDeferredReturn)((0, identity_2.getAgentName)(), saved.friendId, saved.content);
3040
+ }
3041
+ catch { /* a stale saved copy only repeats the news */ }
3042
+ }
3043
+ if (success && !(0, tool_loop_1.hasRecordedToolCall)(toolLoopState, tc.name, args))
3044
+ lastProgressIteration = providerIterations;
3045
+ const fittedResult = (0, delegated_command_1.shieldDelegatedBanner)((0, tool_output_budget_1.fitToolOutputForModel)(tc.name, (0, tool_friction_1.rewriteToolResultForModel)(tc.name, toolResult, toolFrictionLedger)));
3046
+ const modelResult = withBudgetNote(fittedResult, isLastCall(tc), candidateToolNames);
3047
+ pushGenerated({ role: "tool", tool_call_id: tc.id, content: modelResult });
3048
+ providerRuntime.appendToolOutput(tc.id, modelResult);
3049
+ if (!success)
3050
+ augmentedToolContext?.habitSession?.recordError?.(toolResult);
3051
+ const validatedRequiredResult = success && requiredToolCallNames.includes(tc.name) && options?.requiredToolCalls?.requireSuccessfulResults
3052
+ ? requiredToolResultSucceeded(tc.name, toolResult, args, options.requiredToolCalls.validateRequiredToolResult)
3053
+ : false;
3054
+ if (validatedRequiredResult) {
3055
+ dispatchedRequiredToolCalls.add(tc.name);
3056
+ for (const requiredName of options?.requiredToolCalls?.requiredToolCallsAfterResult?.(tc.name, args, toolResult) ?? []) {
3057
+ if (!candidateToolNames.has(requiredName)) {
3058
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "engine", event: "engine.required_tool_unadvertised", message: "dependent required tool is not advertised for the active channel", meta: { toolName: requiredName, channel: String(channel) } });
3059
+ throw new Error(`dependent required tool is not advertised for this channel: ${requiredName}`);
3060
+ }
3061
+ if (!requiredToolCallNames.includes(requiredName))
3062
+ requiredToolCallNames.push(requiredName);
3063
+ }
3064
+ }
3065
+ if (success && currentEffectFingerprint && !toolResultIndicatesFailure(toolResult)) {
3066
+ unresolvedHistoricalEffects = unresolvedHistoricalEffects.filter((effect) => effect.fingerprint !== currentEffectFingerprint);
3067
+ }
3068
+ const dispatchedDefinition = (0, tools_1.resolveToolDefinition)(tc.name, toolSelection);
3069
+ const resolvedRiskProfile = dispatchedDefinition?.riskProfile;
3070
+ const toolRiskProfile = typeof resolvedRiskProfile === "function" ? resolvedRiskProfile(args) : resolvedRiskProfile;
3071
+ // A low-risk profile can still change state; the card's effect says whether it does.
3072
+ const changesState = toolRiskProfile?.mutates !== "none" || (dispatchedDefinition?.ax !== undefined && dispatchedDefinition.ax.effect !== "read");
3073
+ options?.toolBoundaryObserver?.({
3074
+ name: tc.name,
3075
+ reason: "dispatched",
3076
+ globallyResolvable: typeof dispatchedDefinition?.handler === "function",
3077
+ invoked,
3078
+ sideEffect: success && changesState,
3079
+ });
3080
+ (0, tool_loop_1.recordToolOutcome)(toolLoopState, tc.name, args, fittedResult, success);
3081
+ callbacks.onToolEnd(tc.name, (0, tools_1.buildToolResultSummary)(tc.name, args, modelResult, success, toolSelection), success);
3082
+ callbacks.onToolResult?.(messages);
3083
+ }
3084
+ if (batchToolImages.length > 0 && !signal?.aborted) {
3085
+ pushGenerated((0, tool_images_1.buildToolImagesMessage)(batchToolImages));
3086
+ // Responses-API providers keep native input; rebuild it so the images reach the next call.
3087
+ providerRuntime.resetTurnState(messages);
517
3088
  }
518
- callbacks.onToolEnd(tc.name, argSummary, success);
519
- messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
520
- providerRuntime.appendToolOutput(tc.id, toolResult);
521
3089
  }
522
3090
  }
523
- }
524
- catch (e) {
525
- // Abort is not an error — just stop cleanly
526
- if (signal?.aborted) {
527
- stripLastToolCalls(messages);
528
- break;
529
- }
530
- // Context overflow: trim aggressively and retry once
531
- if (isContextOverflow(e) && !overflowRetried) {
532
- overflowRetried = true;
533
- stripLastToolCalls(messages);
534
- const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
535
- const trimmed = (0, context_1.trimMessages)(messages, maxTokens, contextMargin, maxTokens * 2);
536
- messages.splice(0, messages.length, ...trimmed);
537
- providerRuntime.resetTurnState(messages);
538
- callbacks.onError(new Error("context trimmed, retrying..."), "transient");
539
- continue;
540
- }
541
- // Transient errors: retry with exponential backoff
542
- if (isTransientError(e) && retryCount < MAX_RETRIES) {
543
- retryCount++;
544
- const delay = RETRY_BASE_MS * Math.pow(2, retryCount - 1);
545
- const cause = classifyTransientError(e);
546
- callbacks.onError(new Error(`${cause}, retrying in ${delay / 1000}s (${retryCount}/${MAX_RETRIES})...`), "transient");
547
- // Wait with abort support
548
- const aborted = await new Promise((resolve) => {
549
- const timer = setTimeout(() => resolve(false), delay);
550
- if (signal) {
551
- const onAbort = () => { clearTimeout(timer); resolve(true); };
552
- if (signal.aborted) {
553
- clearTimeout(timer);
554
- resolve(true);
555
- return;
556
- }
557
- signal.addEventListener("abort", onAbort, { once: true });
558
- }
559
- });
560
- if (aborted) {
561
- stripLastToolCalls(messages);
3091
+ catch (e) {
3092
+ // Abort is not an error — just stop cleanly
3093
+ if (e instanceof provider_attempt_1.ProviderAttemptAbortError || signal?.aborted) {
3094
+ if (generatedMessages.length === 0)
3095
+ stripLastToolCalls(messages);
3096
+ outcome = "aborted";
562
3097
  break;
563
3098
  }
564
- providerRuntime.resetTurnState(messages);
565
- continue;
3099
+ const errorForClassification = e instanceof Error ? e : /* v8 ignore next -- defensive @preserve */ new Error(String(e));
3100
+ let providerClassification;
3101
+ try {
3102
+ providerClassification = providerRuntime.classifyError(errorForClassification);
3103
+ }
3104
+ catch {
3105
+ /* v8 ignore next -- defensive: classifyError should not throw @preserve */
3106
+ providerClassification = "unknown";
3107
+ }
3108
+ finishTerminalProviderError(errorForClassification, providerClassification);
566
3109
  }
567
- callbacks.onError(e instanceof Error ? e : new Error(String(e)), "terminal");
568
- (0, runtime_1.emitNervesEvent)({
569
- level: "error",
570
- event: "engine.error",
571
- trace_id: traceId,
572
- component: "engine",
573
- message: e instanceof Error ? e.message : String(e),
574
- meta: {},
3110
+ }
3111
+ }
3112
+ catch (error) {
3113
+ if (!(error instanceof tools_1.ToolSelectionError))
3114
+ throw error;
3115
+ finishTerminalProviderError(error, "unknown");
3116
+ }
3117
+ finally {
3118
+ nextAttemptControls = [];
3119
+ rejectedAttempt = [];
3120
+ providerRuntime.resetTurnState(messages);
3121
+ }
3122
+ options?.captureGeneratedMessages?.(structuredClone(generatedMessages));
3123
+ if (servedByProvider && !terminalError) {
3124
+ const chain = fallbackChain.length > 0 ? fallbackChain : [{ provider: providerRuntime.id, model: providerRuntime.model }];
3125
+ try {
3126
+ (0, provider_fallback_1.noteProviderServed)({
3127
+ agentName: owner?.agentName ?? (0, identity_2.getAgentName)(),
3128
+ agentRoot: owner?.agentRoot ?? (0, identity_2.getAgentRoot)(),
3129
+ lane: providerLaneForFacing(facing),
3130
+ chain,
3131
+ index: fallbackChain.length > 0 ? chainIndex : 0,
575
3132
  });
576
- stripLastToolCalls(messages);
577
- done = true;
3133
+ /* v8 ignore next 3 -- defensive: attribution must never fail a turn that already answered @preserve */
3134
+ }
3135
+ catch {
3136
+ // The answer stands; attribution is best effort.
578
3137
  }
579
3138
  }
580
3139
  (0, runtime_1.emitNervesEvent)({
@@ -582,7 +3141,13 @@ async function runAgent(messages, callbacks, channel, signal, options) {
582
3141
  trace_id: traceId,
583
3142
  component: "engine",
584
3143
  message: "runAgent turn completed",
585
- meta: { done },
3144
+ meta: { done, sawPonder, sawQuerySession, sawBridgeManage },
586
3145
  });
587
- return { usage: lastUsage };
3146
+ return {
3147
+ usage: lastUsage,
3148
+ outcome,
3149
+ completion,
3150
+ ...(suspension ? { suspension } : {}),
3151
+ ...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
3152
+ };
588
3153
  }