@ouro.bot/cli 0.1.0-alpha.9 → 0.1.0-alpha.900

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