@ouro.bot/cli 0.1.0-alpha.145 → 0.1.0-alpha.1450

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