@ouro.bot/cli 0.1.0-alpha.139 → 0.1.0-alpha.1392

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