@ouro.bot/cli 0.1.0-alpha.74 → 0.1.0-alpha.741

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