@ouro.bot/cli 0.1.0-alpha.8 → 0.1.0-alpha.800

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