@ouro.bot/cli 0.1.0-alpha.14 → 0.1.0-alpha.1400

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