@ouro.bot/cli 0.1.0-alpha.83 → 0.1.0-alpha.831

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