@ouro.bot/cli 0.1.0-alpha.75 → 0.1.0-alpha.750

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