@ouro.bot/cli 0.1.0-alpha.13 → 0.1.0-alpha.1300

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