@ouro.bot/cli 0.1.0-alpha.159 → 0.1.0-alpha.1591

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