@ouro.bot/cli 0.1.0-alpha.81 → 0.1.0-alpha.811

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