@ouro.bot/cli 0.1.0-alpha.89 → 0.1.0-alpha.891

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