@ouro.bot/cli 0.1.0-alpha.165 → 0.1.0-alpha.1650

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