@ouro.bot/cli 0.1.0-alpha.92 → 0.1.0-alpha.920

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