@ouro.bot/cli 0.1.0-alpha.71 → 0.1.0-alpha.710

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 (505) hide show
  1. package/README.md +133 -23
  2. package/RepairGuide.ouro/agent.json +5 -0
  3. package/RepairGuide.ouro/psyche/IDENTITY.md +19 -0
  4. package/RepairGuide.ouro/psyche/SOUL.md +55 -0
  5. package/RepairGuide.ouro/skills/diagnose-broken-remote.md +63 -0
  6. package/RepairGuide.ouro/skills/diagnose-stacked-typed-issues.md +35 -0
  7. package/RepairGuide.ouro/skills/diagnose-sync-blocked.md +54 -0
  8. package/RepairGuide.ouro/skills/diagnose-vault-expired.md +60 -0
  9. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +4 -2
  10. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +2 -2
  11. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  12. package/changelog.json +4510 -14
  13. package/dist/a2a/card.js +57 -0
  14. package/dist/a2a/client.js +180 -0
  15. package/dist/a2a/config.js +50 -0
  16. package/dist/a2a/delegation-stores.js +56 -0
  17. package/dist/a2a/did-resolution.js +93 -0
  18. package/dist/a2a/identity.js +170 -0
  19. package/dist/a2a/inbound-share.js +107 -0
  20. package/dist/a2a/mission-result-wire.js +196 -0
  21. package/dist/a2a/onboarding.js +115 -0
  22. package/dist/a2a/pin-store.js +132 -0
  23. package/dist/a2a/seen-ledger.js +120 -0
  24. package/dist/a2a/server.js +604 -0
  25. package/dist/a2a/task-store.js +69 -0
  26. package/dist/a2a/transport.js +45 -0
  27. package/dist/a2a/types.js +3 -0
  28. package/dist/arc/attention-types.js +8 -0
  29. package/dist/arc/cares.js +144 -0
  30. package/dist/arc/episodes.js +118 -0
  31. package/dist/arc/evolution.js +490 -0
  32. package/dist/arc/flight-recorder.js +928 -0
  33. package/dist/arc/intentions.js +134 -0
  34. package/dist/arc/json-store.js +117 -0
  35. package/dist/arc/obligations.js +348 -0
  36. package/dist/arc/packets.js +336 -0
  37. package/dist/arc/presence.js +185 -0
  38. package/dist/arc/task-lifecycle.js +57 -0
  39. package/dist/commerce/store.js +755 -0
  40. package/dist/commerce/types.js +3 -0
  41. package/dist/heart/active-work.js +867 -43
  42. package/dist/heart/agent-entry.js +190 -3
  43. package/dist/heart/attachments/image-normalize.js +194 -0
  44. package/dist/heart/attachments/materialize.js +97 -0
  45. package/dist/heart/attachments/originals.js +88 -0
  46. package/dist/heart/attachments/render.js +29 -0
  47. package/dist/heart/attachments/sources/bluebubbles.js +156 -0
  48. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  49. package/dist/heart/attachments/sources/index.js +16 -0
  50. package/dist/heart/attachments/store.js +103 -0
  51. package/dist/heart/attachments/types.js +93 -0
  52. package/dist/heart/auth/auth-flow.js +479 -0
  53. package/dist/heart/autonomy-budget.js +434 -0
  54. package/dist/heart/awaiting/await-alert.js +146 -0
  55. package/dist/heart/awaiting/await-expiry.js +108 -0
  56. package/dist/heart/awaiting/await-loader.js +91 -0
  57. package/dist/heart/awaiting/await-parser.js +141 -0
  58. package/dist/heart/awaiting/await-runtime-state.js +100 -0
  59. package/dist/heart/awaiting/await-scheduler.js +378 -0
  60. package/dist/heart/background-operations.js +281 -0
  61. package/dist/heart/bridges/manager.js +137 -17
  62. package/dist/heart/bridges/store.js +14 -2
  63. package/dist/heart/bundle-state.js +168 -0
  64. package/dist/heart/commitments.js +135 -0
  65. package/dist/heart/config-registry.js +331 -0
  66. package/dist/heart/config.js +119 -127
  67. package/dist/heart/context-loss-gauntlet.js +354 -0
  68. package/dist/heart/context-loss-sentinel.js +1155 -0
  69. package/dist/heart/core.js +1306 -278
  70. package/dist/heart/cross-chat-delivery.js +8 -22
  71. package/dist/heart/daemon/agent-config-check.js +451 -0
  72. package/dist/heart/daemon/agent-discovery.js +185 -3
  73. package/dist/heart/daemon/agent-service.js +523 -0
  74. package/dist/heart/daemon/agentic-repair.js +547 -0
  75. package/dist/heart/daemon/await-private-wake.js +59 -0
  76. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  77. package/dist/heart/daemon/boot-sync-probe.js +197 -0
  78. package/dist/heart/daemon/cadence.js +180 -0
  79. package/dist/heart/daemon/cli-defaults.js +825 -0
  80. package/dist/heart/daemon/cli-desk.js +322 -0
  81. package/dist/heart/daemon/cli-exec.js +8194 -0
  82. package/dist/heart/daemon/cli-help.js +678 -0
  83. package/dist/heart/daemon/cli-parse.js +2476 -0
  84. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  85. package/dist/heart/daemon/cli-render.js +770 -0
  86. package/dist/heart/daemon/cli-types.js +8 -0
  87. package/dist/heart/daemon/connect-bay.js +323 -0
  88. package/dist/heart/daemon/daemon-cli.js +29 -1943
  89. package/dist/heart/daemon/daemon-entry.js +842 -10
  90. package/dist/heart/daemon/daemon-health.js +176 -0
  91. package/dist/heart/daemon/daemon-rollup.js +57 -0
  92. package/dist/heart/daemon/daemon-runtime-sync.js +88 -13
  93. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  94. package/dist/heart/daemon/daemon.js +1289 -84
  95. package/dist/heart/daemon/dns-workflow.js +394 -0
  96. package/dist/heart/daemon/doctor-types.js +8 -0
  97. package/dist/heart/daemon/doctor.js +1126 -0
  98. package/dist/heart/daemon/habit-private-wake.js +56 -0
  99. package/dist/heart/daemon/health-monitor.js +142 -11
  100. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  101. package/dist/heart/daemon/hooks/bundle-meta.js +135 -1
  102. package/dist/heart/daemon/http-health-probe.js +80 -0
  103. package/dist/heart/daemon/human-command-screens.js +234 -0
  104. package/dist/heart/daemon/human-readiness.js +114 -0
  105. package/dist/heart/daemon/inner-status.js +78 -0
  106. package/dist/heart/daemon/interactive-repair.js +394 -0
  107. package/dist/heart/daemon/launchd.js +37 -8
  108. package/dist/heart/daemon/log-tailer.js +79 -10
  109. package/dist/heart/daemon/logs-prune.js +110 -0
  110. package/dist/heart/daemon/mcp-canary.js +297 -0
  111. package/dist/heart/daemon/message-router.js +45 -5
  112. package/dist/heart/daemon/migrate-to-desk.js +848 -0
  113. package/dist/heart/daemon/os-cron-deps.js +135 -0
  114. package/dist/heart/daemon/os-cron.js +22 -14
  115. package/dist/heart/daemon/ouro-bot-entry.js +4 -2
  116. package/dist/heart/daemon/ouro-entry.js +3 -1
  117. package/dist/heart/daemon/plugin-cli.js +432 -0
  118. package/dist/heart/daemon/process-manager.js +519 -40
  119. package/dist/heart/daemon/provider-discovery.js +137 -0
  120. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  121. package/dist/heart/daemon/pulse.js +511 -0
  122. package/dist/heart/daemon/readiness-repair.js +365 -0
  123. package/dist/heart/daemon/run-hooks.js +2 -0
  124. package/dist/heart/daemon/runtime-logging.js +41 -14
  125. package/dist/heart/daemon/runtime-metadata.js +2 -30
  126. package/dist/heart/daemon/safe-mode.js +161 -0
  127. package/dist/heart/daemon/sense-manager.js +670 -48
  128. package/dist/heart/daemon/session-id-resolver.js +131 -0
  129. package/dist/heart/daemon/skill-management-installer.js +1 -1
  130. package/dist/heart/daemon/socket-client.js +171 -12
  131. package/dist/heart/daemon/stale-bundle-prune.js +113 -0
  132. package/dist/heart/daemon/startup-tui.js +338 -0
  133. package/dist/heart/daemon/task-scheduler.js +117 -39
  134. package/dist/heart/daemon/terminal-ui.js +499 -0
  135. package/dist/heart/daemon/thoughts.js +255 -43
  136. package/dist/heart/daemon/up-progress.js +366 -0
  137. package/dist/heart/daemon/vault-items.js +56 -0
  138. package/dist/heart/delegation.js +1 -4
  139. package/dist/heart/external-events/router.js +121 -0
  140. package/dist/heart/habits/habit-migration.js +189 -0
  141. package/dist/heart/habits/habit-parser.js +214 -0
  142. package/dist/heart/habits/habit-runtime-state.js +114 -0
  143. package/dist/heart/habits/habit-scheduler.js +431 -0
  144. package/dist/heart/habits/habit-session-summary.js +318 -0
  145. package/dist/heart/habits/habit-session.js +617 -0
  146. package/dist/heart/{daemon → hatch}/hatch-flow.js +51 -60
  147. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  148. package/dist/heart/{daemon → hatch}/specialist-prompt.js +12 -9
  149. package/dist/heart/{daemon → hatch}/specialist-tools.js +53 -18
  150. package/dist/heart/identity.js +174 -59
  151. package/dist/heart/kept-notes.js +289 -0
  152. package/dist/heart/kicks.js +1 -1
  153. package/dist/heart/machine-identity.js +161 -0
  154. package/dist/heart/mail-import-discovery.js +353 -0
  155. package/dist/heart/mailbox/mailbox-http-hooks.js +96 -0
  156. package/dist/heart/mailbox/mailbox-http-response.js +7 -0
  157. package/dist/heart/mailbox/mailbox-http-routes.js +375 -0
  158. package/dist/heart/mailbox/mailbox-http-static.js +103 -0
  159. package/dist/heart/mailbox/mailbox-http-transport.js +116 -0
  160. package/dist/heart/mailbox/mailbox-http.js +99 -0
  161. package/dist/heart/mailbox/mailbox-read.js +37 -0
  162. package/dist/heart/mailbox/mailbox-types.js +27 -0
  163. package/dist/heart/mailbox/mailbox-view.js +197 -0
  164. package/dist/heart/mailbox/readers/agent-machine.js +428 -0
  165. package/dist/heart/mailbox/readers/continuity-readers.js +329 -0
  166. package/dist/heart/mailbox/readers/mail.js +375 -0
  167. package/dist/heart/mailbox/readers/runtime-readers.js +815 -0
  168. package/dist/heart/mailbox/readers/sessions.js +232 -0
  169. package/dist/heart/mailbox/readers/shared.js +111 -0
  170. package/dist/heart/mcp/mcp-server.js +696 -0
  171. package/dist/heart/migrate-config.js +100 -0
  172. package/dist/heart/model-capabilities.js +11 -0
  173. package/dist/heart/orientation-frame.js +217 -0
  174. package/dist/heart/platform.js +81 -0
  175. package/dist/heart/primitives.js +1 -1
  176. package/dist/heart/private-runtime/decision-renderer.js +156 -0
  177. package/dist/heart/private-runtime/index.js +18 -0
  178. package/dist/heart/private-runtime/ledger.js +218 -0
  179. package/dist/heart/private-runtime/policy.js +214 -0
  180. package/dist/heart/private-runtime/types.js +2 -0
  181. package/dist/heart/progress-story.js +1 -1
  182. package/dist/heart/provider-attempt.js +134 -0
  183. package/dist/heart/provider-binding-resolver.js +273 -0
  184. package/dist/heart/provider-credentials.js +441 -0
  185. package/dist/heart/provider-failover.js +311 -0
  186. package/dist/heart/provider-models.js +81 -0
  187. package/dist/heart/provider-ping.js +262 -0
  188. package/dist/heart/provider-readiness-cache.js +119 -0
  189. package/dist/heart/provider-visibility.js +188 -0
  190. package/dist/heart/providers/anthropic-token.js +131 -0
  191. package/dist/heart/providers/anthropic.js +139 -52
  192. package/dist/heart/providers/azure.js +23 -11
  193. package/dist/heart/providers/error-classification.js +127 -0
  194. package/dist/heart/providers/github-copilot.js +34 -38
  195. package/dist/heart/providers/minimax-vlm.js +189 -0
  196. package/dist/heart/providers/minimax.js +26 -8
  197. package/dist/heart/providers/openai-codex-token.js +349 -0
  198. package/dist/heart/providers/openai-codex.js +55 -40
  199. package/dist/heart/run-ledger.js +247 -0
  200. package/dist/heart/runtime-capability-check.js +170 -0
  201. package/dist/heart/runtime-credentials.js +398 -0
  202. package/dist/heart/runtime-cwd.js +87 -0
  203. package/dist/heart/sense-truth.js +20 -4
  204. package/dist/heart/session-activity.js +90 -24
  205. package/dist/heart/session-events.js +1133 -0
  206. package/dist/heart/session-playback-cli-main.js +5 -0
  207. package/dist/heart/session-playback-cli.js +36 -0
  208. package/dist/heart/session-playback.js +231 -0
  209. package/dist/heart/session-stats-cli-main.js +5 -0
  210. package/dist/heart/session-stats.js +182 -0
  211. package/dist/heart/session-transcript.js +133 -0
  212. package/dist/heart/start-of-turn-packet.js +365 -0
  213. package/dist/heart/streaming.js +44 -27
  214. package/dist/heart/structured-output.js +196 -0
  215. package/dist/heart/sync-classification.js +176 -0
  216. package/dist/heart/sync.js +449 -0
  217. package/dist/heart/target-resolution.js +11 -7
  218. package/dist/heart/tempo.js +93 -0
  219. package/dist/heart/temporal-view.js +41 -0
  220. package/dist/heart/timeouts.js +101 -0
  221. package/dist/heart/tool-activity-callbacks.js +59 -0
  222. package/dist/heart/tool-description.js +155 -0
  223. package/dist/heart/tool-friction.js +55 -0
  224. package/dist/heart/tool-loop.js +200 -0
  225. package/dist/heart/turn-context.js +472 -0
  226. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +6 -5
  227. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  228. package/dist/heart/versioning/ouro-path-installer.js +426 -0
  229. package/dist/heart/versioning/ouro-version-manager.js +409 -0
  230. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  231. package/dist/heart/{daemon → versioning}/update-checker.js +6 -1
  232. package/dist/heart/versioning/update-hooks.js +154 -0
  233. package/dist/heart/work-card.js +380 -0
  234. package/dist/mailbox-ui/assets/index-Du_9G9WO.css +1 -0
  235. package/dist/mailbox-ui/assets/index-J8zDwHmE.js +1 -0
  236. package/dist/mailbox-ui/assets/vendor-CcN1XpQ9.js +61 -0
  237. package/dist/mailbox-ui/index.html +16 -0
  238. package/dist/mailroom/attention.js +167 -0
  239. package/dist/mailroom/autonomy.js +209 -0
  240. package/dist/mailroom/blob-store.js +715 -0
  241. package/dist/mailroom/body-cache.js +61 -0
  242. package/dist/mailroom/core.js +788 -0
  243. package/dist/mailroom/entry.js +160 -0
  244. package/dist/mailroom/file-store.js +568 -0
  245. package/dist/mailroom/mbox-import.js +393 -0
  246. package/dist/mailroom/migration.js +164 -0
  247. package/dist/mailroom/outbound.js +380 -0
  248. package/dist/mailroom/policy.js +263 -0
  249. package/dist/mailroom/reader.js +233 -0
  250. package/dist/mailroom/search-cache.js +334 -0
  251. package/dist/mailroom/search-relevance.js +319 -0
  252. package/dist/mailroom/smtp-ingress.js +176 -0
  253. package/dist/mailroom/source-state.js +176 -0
  254. package/dist/mailroom/thread.js +109 -0
  255. package/dist/mailroom/travel-extract.js +89 -0
  256. package/dist/mind/bundle-manifest.js +24 -2
  257. package/dist/mind/context.js +250 -101
  258. package/dist/mind/desk-section.js +362 -0
  259. package/dist/mind/diary-integrity.js +60 -0
  260. package/dist/mind/{memory.js → diary.js} +68 -77
  261. package/dist/mind/embedding-provider.js +60 -0
  262. package/dist/mind/file-state.js +179 -0
  263. package/dist/mind/{associative-recall.js → note-search.js} +47 -58
  264. package/dist/mind/obligation-steering.js +221 -0
  265. package/dist/mind/pending.js +13 -8
  266. package/dist/mind/prompt-budget.js +380 -0
  267. package/dist/mind/prompt-refresh.js +3 -2
  268. package/dist/mind/prompt.js +1028 -169
  269. package/dist/mind/provenance-trust.js +26 -0
  270. package/dist/mind/record-paths.js +312 -0
  271. package/dist/mind/scrutiny.js +173 -0
  272. package/dist/nerves/cli-logging.js +7 -1
  273. package/dist/nerves/coverage/audit-rules.js +15 -6
  274. package/dist/nerves/coverage/audit.js +28 -2
  275. package/dist/nerves/coverage/cli.js +1 -1
  276. package/dist/nerves/coverage/contract.js +5 -5
  277. package/dist/nerves/coverage/file-completeness.js +139 -5
  278. package/dist/nerves/event-buffer.js +111 -0
  279. package/dist/nerves/index.js +234 -4
  280. package/dist/nerves/observation.js +20 -0
  281. package/dist/nerves/redact.js +79 -0
  282. package/dist/nerves/review/cli-main.js +5 -0
  283. package/dist/nerves/review/cli.js +156 -0
  284. package/dist/nerves/review/core.js +152 -0
  285. package/dist/nerves/runtime.js +5 -1
  286. package/dist/repertoire/ado-client.js +15 -56
  287. package/dist/repertoire/ado-semantic.js +16 -10
  288. package/dist/repertoire/api-client.js +97 -0
  289. package/dist/repertoire/bitwarden-store.js +1021 -0
  290. package/dist/repertoire/bundle-templates.js +71 -0
  291. package/dist/repertoire/bw-installer.js +180 -0
  292. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  293. package/dist/repertoire/coding/context-pack.js +331 -0
  294. package/dist/repertoire/coding/feedback.js +218 -30
  295. package/dist/repertoire/coding/index.js +15 -3
  296. package/dist/repertoire/coding/manager.js +166 -10
  297. package/dist/repertoire/coding/spawner.js +58 -11
  298. package/dist/repertoire/coding/tools.js +242 -14
  299. package/dist/repertoire/coding/workbench-client.js +272 -0
  300. package/dist/repertoire/coding/workbench-manager.js +346 -0
  301. package/dist/repertoire/commerce-errors.js +109 -0
  302. package/dist/repertoire/commerce-self-test.js +156 -0
  303. package/dist/repertoire/credential-access.js +178 -0
  304. package/dist/repertoire/desk/classifier.js +362 -0
  305. package/dist/repertoire/duffel-client.js +185 -0
  306. package/dist/repertoire/github-client.js +14 -55
  307. package/dist/repertoire/graph-client.js +11 -52
  308. package/dist/repertoire/guardrails.js +156 -27
  309. package/dist/repertoire/mcp-client.js +44 -3
  310. package/dist/repertoire/mcp-manager.js +259 -20
  311. package/dist/repertoire/mcp-tools.js +83 -0
  312. package/dist/repertoire/plugin-mcp.js +175 -0
  313. package/dist/repertoire/plugins.js +253 -0
  314. package/dist/repertoire/shell-sessions.js +133 -0
  315. package/dist/repertoire/skills.js +48 -4
  316. package/dist/repertoire/stripe-client.js +131 -0
  317. package/dist/repertoire/tool-results.js +29 -0
  318. package/dist/repertoire/tools-a2a.js +699 -0
  319. package/dist/repertoire/tools-attachments.js +317 -0
  320. package/dist/repertoire/tools-awaiting.js +372 -0
  321. package/dist/repertoire/tools-base.js +65 -1095
  322. package/dist/repertoire/tools-bluebubbles.js +2 -0
  323. package/dist/repertoire/tools-bridge.js +144 -0
  324. package/dist/repertoire/tools-bundle.js +993 -0
  325. package/dist/repertoire/tools-commerce.js +253 -0
  326. package/dist/repertoire/tools-config.js +186 -0
  327. package/dist/repertoire/tools-continuity.js +252 -0
  328. package/dist/repertoire/tools-credential.js +383 -0
  329. package/dist/repertoire/tools-evolution.js +527 -0
  330. package/dist/repertoire/tools-files.js +344 -0
  331. package/dist/repertoire/tools-flight.js +290 -0
  332. package/dist/repertoire/tools-flow.js +119 -0
  333. package/dist/repertoire/tools-github.js +3 -8
  334. package/dist/repertoire/tools-mail.js +1975 -0
  335. package/dist/repertoire/tools-notes.js +459 -0
  336. package/dist/repertoire/tools-obligations.js +182 -0
  337. package/dist/repertoire/tools-orientation.js +31 -0
  338. package/dist/repertoire/tools-record.js +482 -0
  339. package/dist/repertoire/tools-rsvp.js +139 -0
  340. package/dist/repertoire/tools-runtime.js +150 -0
  341. package/dist/repertoire/tools-session.js +881 -0
  342. package/dist/repertoire/tools-shell.js +120 -0
  343. package/dist/repertoire/tools-stripe.js +224 -0
  344. package/dist/repertoire/tools-surface.js +355 -0
  345. package/dist/repertoire/tools-teams.js +12 -39
  346. package/dist/repertoire/tools-travel.js +125 -0
  347. package/dist/repertoire/tools-trip.js +982 -0
  348. package/dist/repertoire/tools-user-profile.js +146 -0
  349. package/dist/repertoire/tools-vault.js +40 -0
  350. package/dist/repertoire/tools-voice.js +145 -0
  351. package/dist/repertoire/tools.js +250 -80
  352. package/dist/repertoire/travel-api-client.js +360 -0
  353. package/dist/repertoire/user-profile.js +131 -0
  354. package/dist/repertoire/vault-setup.js +246 -0
  355. package/dist/repertoire/vault-unlock.js +594 -0
  356. package/dist/rsvp/aisleplanner-client.js +354 -0
  357. package/dist/rsvp/cli.js +758 -0
  358. package/dist/rsvp/config.js +327 -0
  359. package/dist/rsvp/cutover.js +433 -0
  360. package/dist/rsvp/diagnostics.js +222 -0
  361. package/dist/rsvp/diff-renderer.js +161 -0
  362. package/dist/rsvp/habit-policy.js +85 -0
  363. package/dist/rsvp/habit-stage.js +98 -0
  364. package/dist/rsvp/incident-bundle.js +97 -0
  365. package/dist/rsvp/migration.js +204 -0
  366. package/dist/rsvp/native-habit-runner.js +321 -0
  367. package/dist/rsvp/outbound-state.js +268 -0
  368. package/dist/rsvp/query.js +118 -0
  369. package/dist/rsvp/replay.js +233 -0
  370. package/dist/rsvp/snapshot.js +232 -0
  371. package/dist/rsvp/spend-ledger.js +175 -0
  372. package/dist/scripts/claude-code-hook.js +41 -0
  373. package/dist/scripts/claude-code-stop-hook.js +47 -0
  374. package/dist/senses/a2a-entry.js +115 -0
  375. package/dist/senses/attention-queue.js +186 -0
  376. package/dist/senses/await-turn-message.js +58 -0
  377. package/dist/senses/bluebubbles/active-turns.js +216 -0
  378. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  379. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  380. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +226 -19
  381. package/dist/senses/bluebubbles/context-packet.js +101 -0
  382. package/dist/senses/bluebubbles/context-smoke.js +144 -0
  383. package/dist/senses/bluebubbles/entry.js +77 -0
  384. package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +20 -3
  385. package/dist/senses/bluebubbles/index.js +2881 -0
  386. package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +121 -71
  387. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +33 -12
  388. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +3 -3
  389. package/dist/senses/bluebubbles/outbound-state.js +304 -0
  390. package/dist/senses/bluebubbles/processed-log.js +133 -0
  391. package/dist/senses/bluebubbles/replay.js +284 -0
  392. package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +30 -2
  393. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
  394. package/dist/senses/bluebubbles-meta-guard.js +39 -0
  395. package/dist/senses/cli/bracketed-paste.js +82 -0
  396. package/dist/senses/cli/image-paste.js +287 -0
  397. package/dist/senses/cli/image-ref-navigation.js +75 -0
  398. package/dist/senses/cli/ink-app.js +156 -0
  399. package/dist/senses/cli/inline-diff.js +64 -0
  400. package/dist/senses/cli/input-keys.js +174 -0
  401. package/dist/senses/cli/kill-ring.js +86 -0
  402. package/dist/senses/cli/message-list.js +51 -0
  403. package/dist/senses/cli/ouro-tui.js +607 -0
  404. package/dist/senses/cli/spinner-imperative.js +135 -0
  405. package/dist/senses/cli/spinner.js +101 -0
  406. package/dist/senses/cli/status-line.js +60 -0
  407. package/dist/senses/cli/streaming-markdown.js +526 -0
  408. package/dist/senses/cli/tool-display.js +85 -0
  409. package/dist/senses/cli/tool-render.js +85 -0
  410. package/dist/senses/cli/tui-store.js +240 -0
  411. package/dist/senses/cli/virtual-list.js +35 -0
  412. package/dist/senses/cli-entry.js +60 -8
  413. package/dist/senses/cli-layout.js +100 -0
  414. package/dist/senses/cli.js +521 -214
  415. package/dist/senses/commands.js +66 -3
  416. package/dist/senses/context-packet-ledger.js +245 -0
  417. package/dist/senses/context-packets.js +154 -0
  418. package/dist/senses/habit-turn-message.js +160 -0
  419. package/dist/senses/mail-entry.js +66 -0
  420. package/dist/senses/mail.js +395 -0
  421. package/dist/senses/pipeline.js +952 -178
  422. package/dist/senses/private-runtime-worker.js +739 -0
  423. package/dist/senses/private-runtime.js +1157 -0
  424. package/dist/senses/proactive-content-guard.js +51 -0
  425. package/dist/senses/shared-turn.js +416 -0
  426. package/dist/senses/surface-tool.js +109 -0
  427. package/dist/senses/teams-entry.js +60 -8
  428. package/dist/senses/teams.js +397 -112
  429. package/dist/senses/trust-gate.js +104 -9
  430. package/dist/senses/voice/audio-playback.js +237 -0
  431. package/dist/senses/voice/audio-routing.js +119 -0
  432. package/dist/senses/voice/elevenlabs.js +202 -0
  433. package/dist/senses/voice/floor-control.js +431 -0
  434. package/dist/senses/voice/floor-controller.js +115 -0
  435. package/dist/senses/voice/golden-path.js +116 -0
  436. package/dist/senses/voice/index.js +29 -0
  437. package/dist/senses/voice/meeting.js +113 -0
  438. package/dist/senses/voice/outbound.js +190 -0
  439. package/dist/senses/voice/phone.js +33 -0
  440. package/dist/senses/voice/playback.js +139 -0
  441. package/dist/senses/voice/realtime-eval.js +496 -0
  442. package/dist/senses/voice/realtime-trace.js +531 -0
  443. package/dist/senses/voice/transcript.js +70 -0
  444. package/dist/senses/voice/turn.js +191 -0
  445. package/dist/senses/voice/twilio-phone-runtime.js +807 -0
  446. package/dist/senses/voice/twilio-phone.js +5081 -0
  447. package/dist/senses/voice/types.js +2 -0
  448. package/dist/senses/voice/whisper.js +161 -0
  449. package/dist/senses/voice-entry.js +81 -0
  450. package/dist/senses/voice-realtime-eval-command.js +99 -0
  451. package/dist/senses/voice-realtime-eval-entry.js +21 -0
  452. package/dist/senses/voice-twilio-entry.js +87 -0
  453. package/dist/trips/core.js +138 -0
  454. package/dist/trips/store.js +265 -0
  455. package/dist/util/frontmatter.js +69 -0
  456. package/package.json +57 -12
  457. package/skills/agent-commerce.md +113 -0
  458. package/skills/browser-navigation.md +117 -0
  459. package/skills/commerce-setup-guide.md +116 -0
  460. package/skills/commerce-setup.md +84 -0
  461. package/skills/configure-dev-tools.md +99 -0
  462. package/skills/travel-planning.md +138 -0
  463. package/dist/heart/daemon/auth-flow.js +0 -409
  464. package/dist/heart/daemon/ouro-path-installer.js +0 -178
  465. package/dist/heart/daemon/update-hooks.js +0 -138
  466. package/dist/heart/safe-workspace.js +0 -228
  467. package/dist/heart/session-recall.js +0 -116
  468. package/dist/mind/friends/channel.js +0 -84
  469. package/dist/mind/friends/group-context.js +0 -144
  470. package/dist/mind/friends/resolver.js +0 -84
  471. package/dist/mind/friends/store-file.js +0 -190
  472. package/dist/mind/friends/store.js +0 -4
  473. package/dist/mind/friends/tokens.js +0 -26
  474. package/dist/mind/friends/trust-explanation.js +0 -74
  475. package/dist/mind/friends/types.js +0 -29
  476. package/dist/repertoire/tasks/board.js +0 -134
  477. package/dist/repertoire/tasks/index.js +0 -224
  478. package/dist/repertoire/tasks/lifecycle.js +0 -80
  479. package/dist/repertoire/tasks/middleware.js +0 -65
  480. package/dist/repertoire/tasks/parser.js +0 -173
  481. package/dist/repertoire/tasks/scanner.js +0 -132
  482. package/dist/repertoire/tasks/transitions.js +0 -144
  483. package/dist/senses/bluebubbles-entry.js +0 -13
  484. package/dist/senses/bluebubbles.js +0 -1180
  485. package/dist/senses/debug-activity.js +0 -148
  486. package/dist/senses/inner-dialog-worker.js +0 -90
  487. package/dist/senses/inner-dialog.js +0 -480
  488. package/subagents/README.md +0 -7
  489. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  490. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  491. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  492. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  493. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  494. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  495. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  496. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  497. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  498. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  499. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  500. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  501. /package/dist/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +0 -0
  502. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  503. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  504. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  505. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
@@ -1,80 +1,117 @@
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;
4
3
  exports.createProviderRegistry = createProviderRegistry;
5
4
  exports.resetProviderRuntime = resetProviderRuntime;
6
5
  exports.getModel = getModel;
7
6
  exports.getProvider = getProvider;
8
7
  exports.createSummarize = createSummarize;
9
8
  exports.getProviderDisplayLabel = getProviderDisplayLabel;
9
+ exports.createHabitCallbackBuffer = createHabitCallbackBuffer;
10
+ exports.isChatStyleChannel = isChatStyleChannel;
11
+ exports.buildPonderResult = buildPonderResult;
12
+ exports.isExternalStateQuery = isExternalStateQuery;
13
+ exports.getSettleRetryError = getSettleRetryError;
10
14
  exports.stripLastToolCalls = stripLastToolCalls;
11
15
  exports.repairOrphanedToolCalls = repairOrphanedToolCalls;
12
- exports.isTransientError = isTransientError;
13
- exports.classifyTransientError = classifyTransientError;
14
16
  exports.runAgent = runAgent;
15
17
  const config_1 = require("./config");
16
18
  const identity_1 = require("./identity");
17
19
  const tools_1 = require("../repertoire/tools");
18
- const channel_1 = require("../mind/friends/channel");
20
+ const friends_1 = require("@ouro.bot/friends");
21
+ const tools_2 = require("../repertoire/tools");
19
22
  const runtime_1 = require("../nerves/runtime");
20
23
  const context_1 = require("../mind/context");
24
+ const prompt_budget_1 = require("../mind/prompt-budget");
21
25
  const prompt_1 = require("../mind/prompt");
22
- const associative_recall_1 = require("../mind/associative-recall");
26
+ const kept_notes_1 = require("./kept-notes");
27
+ const error_classification_1 = require("./providers/error-classification");
23
28
  const anthropic_1 = require("./providers/anthropic");
24
29
  const azure_1 = require("./providers/azure");
25
30
  const minimax_1 = require("./providers/minimax");
26
31
  const openai_codex_1 = require("./providers/openai-codex");
27
32
  const github_copilot_1 = require("./providers/github-copilot");
28
- let _providerRuntime = null;
29
- function getProviderRuntimeFingerprint() {
30
- const provider = (0, identity_1.loadAgentConfig)().provider;
31
- /* v8 ignore next -- switch: not all provider branches exercised in CI @preserve */
32
- switch (provider) {
33
- case "azure": {
34
- const { apiKey, endpoint, deployment, modelName, apiVersion, managedIdentityClientId } = (0, config_1.getAzureConfig)();
35
- return JSON.stringify({ provider, apiKey, endpoint, deployment, modelName, apiVersion, managedIdentityClientId });
36
- }
37
- case "anthropic": {
38
- const { model, setupToken } = (0, config_1.getAnthropicConfig)();
39
- return JSON.stringify({ provider, model, setupToken });
40
- }
41
- case "minimax": {
42
- const { apiKey, model } = (0, config_1.getMinimaxConfig)();
43
- return JSON.stringify({ provider, apiKey, model });
44
- }
45
- case "openai-codex": {
46
- const { model, oauthAccessToken } = (0, config_1.getOpenAICodexConfig)();
47
- return JSON.stringify({ provider, model, oauthAccessToken });
48
- }
49
- /* v8 ignore start -- fingerprint: tested via provider init tests @preserve */
50
- case "github-copilot": {
51
- const { model, githubToken, baseUrl } = (0, config_1.getGithubCopilotConfig)();
52
- return JSON.stringify({ provider, model, githubToken, baseUrl });
33
+ const identity_2 = require("./identity");
34
+ const socket_client_1 = require("./daemon/socket-client");
35
+ const obligations_1 = require("../arc/obligations");
36
+ const tool_loop_1 = require("./tool-loop");
37
+ const packets_1 = require("../arc/packets");
38
+ const tool_friction_1 = require("./tool-friction");
39
+ const provider_models_1 = require("./provider-models");
40
+ const provider_credentials_1 = require("./provider-credentials");
41
+ const habit_session_1 = require("./habits/habit-session");
42
+ const provider_attempt_1 = require("./provider-attempt");
43
+ const openai_codex_token_1 = require("./providers/openai-codex-token");
44
+ const _providerRuntimes = {
45
+ human: null,
46
+ agent: null,
47
+ };
48
+ function providerLaneForFacing(facing) {
49
+ return facing === "human" ? "outward" : "inner";
50
+ }
51
+ function resolveRuntimeProviderBinding(facing) {
52
+ const lane = providerLaneForFacing(facing);
53
+ const config = (0, identity_1.loadAgentConfig)();
54
+ const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
55
+ return { lane, provider: facingConfig.provider, model: facingConfig.model };
56
+ }
57
+ async function getProviderRuntimeFingerprint(facing) {
58
+ const agentName = (0, identity_2.getAgentName)();
59
+ const binding = resolveRuntimeProviderBinding(facing);
60
+ const credential = await (0, provider_credentials_1.readProviderCredentialRecord)(agentName, binding.provider);
61
+ if (!credential.ok) {
62
+ throw new Error([
63
+ `${binding.lane} provider ${binding.provider} (${binding.model}) has no credentials for ${agentName}.`,
64
+ credential.error,
65
+ `Run \`ouro auth --agent ${agentName} --provider ${binding.provider}\`.`,
66
+ ].join("\n"));
67
+ }
68
+ let record = credential.record;
69
+ if (binding.provider === "openai-codex") {
70
+ const refresh = await (0, openai_codex_token_1.refreshOpenAICodexProviderCredentials)(agentName, {
71
+ record,
72
+ reason: "runtime-init",
73
+ });
74
+ if (refresh.ok) {
75
+ record = refresh.record;
53
76
  }
54
- /* v8 ignore stop */
55
77
  }
78
+ return {
79
+ binding,
80
+ fingerprint: JSON.stringify({
81
+ lane: binding.lane,
82
+ provider: binding.provider,
83
+ model: binding.model,
84
+ credentialRevision: record.revision,
85
+ }),
86
+ credential: record,
87
+ };
56
88
  }
57
89
  function createProviderRegistry() {
58
- const factories = {
59
- azure: azure_1.createAzureProviderRuntime,
60
- anthropic: anthropic_1.createAnthropicProviderRuntime,
61
- minimax: minimax_1.createMinimaxProviderRuntime,
62
- "openai-codex": openai_codex_1.createOpenAICodexProviderRuntime,
63
- "github-copilot": github_copilot_1.createGithubCopilotProviderRuntime,
64
- };
65
90
  return {
66
- resolve() {
67
- const provider = (0, identity_1.loadAgentConfig)().provider;
68
- return factories[provider]();
91
+ resolve(provider, model, credential) {
92
+ const providerConfig = { ...credential.config, ...credential.credentials };
93
+ switch (provider) {
94
+ case "azure":
95
+ return (0, azure_1.createAzureProviderRuntime)(model, providerConfig);
96
+ case "anthropic":
97
+ return (0, anthropic_1.createAnthropicProviderRuntime)(model, providerConfig);
98
+ case "minimax":
99
+ return (0, minimax_1.createMinimaxProviderRuntime)(model, providerConfig);
100
+ case "openai-codex":
101
+ return (0, openai_codex_1.createOpenAICodexProviderRuntime)(model, providerConfig);
102
+ case "github-copilot":
103
+ return (0, github_copilot_1.createGithubCopilotProviderRuntime)(model, providerConfig);
104
+ }
69
105
  },
70
106
  };
71
107
  }
72
- function getProviderRuntime() {
108
+ async function getProviderRuntime(facing = "human") {
73
109
  try {
74
- const fingerprint = getProviderRuntimeFingerprint();
75
- if (!_providerRuntime || _providerRuntime.fingerprint !== fingerprint) {
76
- const runtime = createProviderRegistry().resolve();
77
- _providerRuntime = runtime ? { fingerprint, runtime } : null;
110
+ const { binding, fingerprint, credential } = await getProviderRuntimeFingerprint(facing);
111
+ const cached = _providerRuntimes[facing];
112
+ if (!cached || cached.fingerprint !== fingerprint) {
113
+ const runtime = createProviderRegistry().resolve(binding.provider, binding.model, credential);
114
+ _providerRuntimes[facing] = runtime ? { fingerprint, runtime } : null;
78
115
  }
79
116
  }
80
117
  catch (error) {
@@ -84,25 +121,26 @@ function getProviderRuntime() {
84
121
  event: "engine.provider_init_error",
85
122
  component: "engine",
86
123
  message: msg,
87
- meta: {},
124
+ meta: { facing },
88
125
  });
89
126
  // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
90
127
  console.error(`\n[fatal] ${msg}\n`);
91
- process.exit(1);
92
- throw new Error("unreachable");
128
+ throw error instanceof Error ? error : new Error(msg);
93
129
  }
94
- if (!_providerRuntime) {
130
+ if (!_providerRuntimes[facing]) {
131
+ const msg = "provider runtime could not be initialized.";
95
132
  (0, runtime_1.emitNervesEvent)({
96
133
  level: "error",
97
134
  event: "engine.provider_init_error",
98
135
  component: "engine",
99
- message: "provider runtime could not be initialized.",
100
- meta: {},
136
+ message: msg,
137
+ meta: { facing },
101
138
  });
102
- process.exit(1);
103
- throw new Error("unreachable");
139
+ // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
140
+ console.error(`\n[fatal] ${msg}\n`);
141
+ throw new Error(msg);
104
142
  }
105
- return _providerRuntime.runtime;
143
+ return _providerRuntimes[facing].runtime;
106
144
  }
107
145
  /**
108
146
  * Clear the cached provider runtime so the next access re-creates it from
@@ -110,17 +148,18 @@ function getProviderRuntime() {
110
148
  * provider fingerprint changes on disk.
111
149
  */
112
150
  function resetProviderRuntime() {
113
- _providerRuntime = null;
151
+ _providerRuntimes.human = null;
152
+ _providerRuntimes.agent = null;
114
153
  }
115
- function getModel() {
116
- return getProviderRuntime().model;
154
+ function getModel(facing = "human") {
155
+ return resolveRuntimeProviderBinding(facing).model;
117
156
  }
118
- function getProvider() {
119
- return getProviderRuntime().id;
157
+ function getProvider(facing = "human") {
158
+ return resolveRuntimeProviderBinding(facing).provider;
120
159
  }
121
- function createSummarize() {
160
+ function createSummarize(facing = "human") {
122
161
  return async (transcript, instruction) => {
123
- const runtime = getProviderRuntime();
162
+ const runtime = await getProviderRuntime(facing);
124
163
  const client = runtime.client;
125
164
  const response = await client.chat.completions.create({
126
165
  model: runtime.model,
@@ -133,37 +172,182 @@ function createSummarize() {
133
172
  return response.choices?.[0]?.message?.content ?? transcript;
134
173
  };
135
174
  }
136
- function getProviderDisplayLabel() {
137
- const provider = (0, identity_1.loadAgentConfig)().provider;
175
+ function getProviderDisplayLabel(facing = "human") {
176
+ const binding = resolveRuntimeProviderBinding(facing);
177
+ const provider = binding.provider;
178
+ const model = binding.model || "unknown";
138
179
  const providerLabelBuilders = {
139
180
  azure: () => {
140
- const config = (0, config_1.getAzureConfig)();
141
- return `azure openai (${config.deployment || "default"}, model: ${config.modelName || "unknown"})`;
181
+ return `azure openai (model: ${model})`;
142
182
  },
143
- anthropic: () => `anthropic (${(0, config_1.getAnthropicConfig)().model || "unknown"})`,
144
- minimax: () => `minimax (${(0, config_1.getMinimaxConfig)().model || "unknown"})`,
145
- "openai-codex": () => `openai codex (${(0, config_1.getOpenAICodexConfig)().model || "unknown"})`,
183
+ anthropic: () => `anthropic (${model})`,
184
+ minimax: () => `minimax (${model})`,
185
+ "openai-codex": () => `openai codex (${model})`,
146
186
  /* v8 ignore next -- branch: tested via display label unit test @preserve */
147
- "github-copilot": () => `github copilot (${(0, config_1.getGithubCopilotConfig)().model || "unknown"})`,
187
+ "github-copilot": () => `github copilot (${model})`,
148
188
  };
149
189
  return providerLabelBuilders[provider]();
150
190
  }
151
- // Re-export tools, execTool, summarizeArgs from ./tools for backward compat
152
- var tools_2 = require("../repertoire/tools");
153
- Object.defineProperty(exports, "tools", { enumerable: true, get: function () { return tools_2.tools; } });
154
- Object.defineProperty(exports, "execTool", { enumerable: true, get: function () { return tools_2.execTool; } });
155
- Object.defineProperty(exports, "summarizeArgs", { enumerable: true, get: function () { return tools_2.summarizeArgs; } });
156
- Object.defineProperty(exports, "getToolsForChannel", { enumerable: true, get: function () { return tools_2.getToolsForChannel; } });
157
- // Re-export streaming functions for backward compat
158
- var streaming_1 = require("./streaming");
159
- Object.defineProperty(exports, "streamChatCompletion", { enumerable: true, get: function () { return streaming_1.streamChatCompletion; } });
160
- Object.defineProperty(exports, "streamResponsesApi", { enumerable: true, get: function () { return streaming_1.streamResponsesApi; } });
161
- Object.defineProperty(exports, "toResponsesInput", { enumerable: true, get: function () { return streaming_1.toResponsesInput; } });
162
- Object.defineProperty(exports, "toResponsesTools", { enumerable: true, get: function () { return streaming_1.toResponsesTools; } });
163
- // Re-export prompt functions for backward compat
164
- var prompt_2 = require("../mind/prompt");
165
- Object.defineProperty(exports, "buildSystem", { enumerable: true, get: function () { return prompt_2.buildSystem; } });
166
- function parseFinalAnswerPayload(argumentsText) {
191
+ function createHabitCallbackBuffer(callbacks) {
192
+ const events = [];
193
+ return {
194
+ callbacks: {
195
+ ...callbacks,
196
+ onModelStreamStart: () => { events.push({ kind: "stream-start" }); },
197
+ onTextChunk: (text) => { events.push({ kind: "text", text }); },
198
+ onReasoningChunk: (text) => { events.push({ kind: "reasoning", text }); },
199
+ onClearText: () => { events.push({ kind: "clear" }); },
200
+ flushNow: () => { events.push({ kind: "flush" }); },
201
+ },
202
+ async flush() {
203
+ for (const event of events.splice(0)) {
204
+ switch (event.kind) {
205
+ case "stream-start":
206
+ callbacks.onModelStreamStart();
207
+ break;
208
+ case "text":
209
+ callbacks.onTextChunk(event.text);
210
+ break;
211
+ case "reasoning":
212
+ callbacks.onReasoningChunk(event.text);
213
+ break;
214
+ case "clear":
215
+ callbacks.onClearText?.();
216
+ break;
217
+ case "flush":
218
+ await callbacks.flushNow?.();
219
+ break;
220
+ }
221
+ }
222
+ },
223
+ discard() {
224
+ events.splice(0);
225
+ },
226
+ };
227
+ }
228
+ /**
229
+ * Strip <think>...</think> blocks for the violation-detection check at the
230
+ * end of a streaming turn. Used to tell legitimate text-only responses
231
+ * apart from the MiniMax-M2.7 "only thinking, no tool call" violation
232
+ * shape. Mirrors the more thorough stripThinkBlocks helper in
233
+ * senses/shared-turn.ts (which is for operator-facing output) — kept
234
+ * inline here to avoid pulling senses/ into the core module's import graph.
235
+ */
236
+ function stripThinkBlocksForViolationCheck(input) {
237
+ let out = input;
238
+ for (;;) {
239
+ const open = out.indexOf("<think>");
240
+ if (open === -1)
241
+ break;
242
+ const close = out.indexOf("</think>", open + "<think>".length);
243
+ if (close === -1) {
244
+ out = out.slice(0, open);
245
+ break;
246
+ }
247
+ out = out.slice(0, open) + out.slice(close + "</think>".length);
248
+ }
249
+ return out.trim();
250
+ }
251
+ function hasFreshPendingWork(options) {
252
+ const pendingMessages = options?.pendingMessages;
253
+ if (!Array.isArray(pendingMessages))
254
+ return false;
255
+ return pendingMessages.some((message) => typeof message?.content === "string"
256
+ && message.content.trim().length > 0);
257
+ }
258
+ const HABIT_CONTROL_TOOLS = new Set(["rest", "ponder", "observe"]);
259
+ function habitToolArgs(call) {
260
+ try {
261
+ const parsed = JSON.parse(call.arguments);
262
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
263
+ return { ok: false, reason: `habit tool '${call.name}' arguments must be a JSON object` };
264
+ }
265
+ return { ok: true, args: parsed };
266
+ }
267
+ catch {
268
+ return { ok: false, reason: `habit tool '${call.name}' has malformed JSON arguments` };
269
+ }
270
+ }
271
+ function highRiskExternalMutation(profile) {
272
+ if (profile.risk !== "high")
273
+ return null;
274
+ const mutates = typeof profile.mutates === "string" ? [profile.mutates] : [...profile.mutates];
275
+ return mutates.includes("external_side_effect") ? mutates.join(", ") : null;
276
+ }
277
+ function recordBlockedHabitSurfaceAttempts(habitSession, toolCalls, reason) {
278
+ if (toolCalls.some((call) => call.name !== "send_message" && call.name !== "surface")) {
279
+ habitSession?.recordError?.(`blocked habit tool batch: ${reason}`);
280
+ }
281
+ if (!habitSession?.recordSurfaceAttempt)
282
+ return;
283
+ for (const call of toolCalls) {
284
+ if (call.name !== "send_message" && call.name !== "surface")
285
+ continue;
286
+ const parsed = habitToolArgs(call);
287
+ const args = parsed.ok ? parsed.args : {};
288
+ habitSession.recordSurfaceAttempt({
289
+ recipient: String(args.friendId ?? args.delegationId ?? "unknown"),
290
+ channel: String(args.channel ?? call.name),
291
+ reason: "blocked",
292
+ result: "blocked",
293
+ rawStatus: "blocked",
294
+ error: reason,
295
+ });
296
+ }
297
+ }
298
+ async function habitToolBatchBlockReason(habitSession, toolCalls, delegatedOrigins, activeToolNames) {
299
+ if (!habitSession)
300
+ return null;
301
+ const granted = new Set(habitSession.toolPolicy.grantedTools);
302
+ const denied = new Set(habitSession.toolPolicy.deniedTools);
303
+ for (const call of toolCalls) {
304
+ if (denied.has(call.name))
305
+ return `habit tool '${call.name}' is denied by this habit session`;
306
+ if (!activeToolNames.has(call.name))
307
+ return `habit tool '${call.name}' was not advertised to this model turn`;
308
+ if (HABIT_CONTROL_TOOLS.has(call.name))
309
+ continue;
310
+ if (!granted.has(call.name))
311
+ return `habit tool '${call.name}' was not granted to this habit session`;
312
+ const parsed = habitToolArgs(call);
313
+ if (!parsed.ok)
314
+ return parsed.reason;
315
+ const riskProfile = (0, tools_1.riskProfileForToolName)(call.name, parsed.args);
316
+ if (!riskProfile)
317
+ return `habit tool '${call.name}' does not have a known executable risk profile`;
318
+ const externalMutation = highRiskExternalMutation(riskProfile);
319
+ if (externalMutation && call.name !== "send_message" && call.name !== "surface") {
320
+ return `habit tool '${call.name}' has high-risk executable mutation ${externalMutation}: ${riskProfile.reason}`;
321
+ }
322
+ if (call.name === "send_message" || call.name === "surface") {
323
+ const route = await (0, habit_session_1.resolveHabitReturnRoute)({
324
+ agentRoot: (0, identity_2.getAgentRoot)(),
325
+ envelope: habitSession.permissionEnvelope,
326
+ toolName: call.name,
327
+ args: parsed.args,
328
+ friendStore: habitSession.friendStore,
329
+ delegatedOrigins,
330
+ });
331
+ if (!route.allowed)
332
+ return route.reason;
333
+ }
334
+ }
335
+ return null;
336
+ }
337
+ /** Chat-style channels expose the `speak` tool — outer human-conversation channels
338
+ * where mid-turn delivery is meaningful. The private runtime has `ponder`. MCP returns
339
+ * synchronously. Mail is batch. Anything else (unknown channel) treats as non-chat. */
340
+ function isChatStyleChannel(channel) {
341
+ return channel === "cli" || channel === "teams" || channel === "bluebubbles" || channel === "voice";
342
+ }
343
+ // Sole-call tools must be the only tool call in a turn. When they appear
344
+ // alongside other tools, the sole-call tool is rejected with this message.
345
+ const SOLE_CALL_REJECTION = {
346
+ settle: "rejected: settle must be the only tool call. finish your work first, then call settle alone.",
347
+ observe: "rejected: observe must be the only tool call. call observe alone when you want to stay silent.",
348
+ rest: "rejected: rest must be the only tool call. finish your work first, then call rest alone.",
349
+ };
350
+ function parseSettlePayload(argumentsText) {
167
351
  try {
168
352
  const parsed = JSON.parse(argumentsText);
169
353
  if (typeof parsed === "string") {
@@ -183,18 +367,204 @@ function parseFinalAnswerPayload(argumentsText) {
183
367
  return {};
184
368
  }
185
369
  }
186
- function getFinalAnswerRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp) {
370
+ function parsePonderPayload(argumentsText) {
371
+ try {
372
+ const parsed = JSON.parse(argumentsText);
373
+ return parsed && typeof parsed === "object" ? parsed : {};
374
+ }
375
+ catch {
376
+ return {};
377
+ }
378
+ }
379
+ function parseSuccessCriteria(raw) {
380
+ if (typeof raw !== "string")
381
+ return null;
382
+ const criteria = raw
383
+ .split("\n")
384
+ .map((line) => line.replace(/^\s*[-*]\s*/, "").trim())
385
+ .filter((line) => line.length > 0);
386
+ return criteria.length > 0 ? criteria : null;
387
+ }
388
+ function parsePacketPayload(raw) {
389
+ if (typeof raw !== "string")
390
+ return null;
391
+ try {
392
+ const parsed = JSON.parse(raw);
393
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
394
+ ? parsed
395
+ : null;
396
+ }
397
+ catch {
398
+ return null;
399
+ }
400
+ }
401
+ function normalizeLegacyPonderArgs(parsed) {
402
+ if (typeof parsed.thought !== "string" || parsed.thought.trim().length === 0) {
403
+ return parsed;
404
+ }
405
+ return {
406
+ action: "create",
407
+ kind: "reflection",
408
+ objective: parsed.thought.trim(),
409
+ summary: typeof parsed.say === "string" ? parsed.say.trim() : "",
410
+ success_criteria: "- preserve the thread for later work",
411
+ payload_json: "{}",
412
+ };
413
+ }
414
+ function messageContentText(content) {
415
+ if (typeof content === "string")
416
+ return content;
417
+ if (!Array.isArray(content))
418
+ return "";
419
+ return content
420
+ .map((part) => {
421
+ if (typeof part === "string")
422
+ return part;
423
+ if (!part || typeof part !== "object")
424
+ return "";
425
+ const maybeText = part.text;
426
+ return typeof maybeText === "string" ? maybeText : "";
427
+ })
428
+ .filter(Boolean)
429
+ .join("\n");
430
+ }
431
+ function isHarnessCorrectiveUserText(text) {
432
+ return text.startsWith("no tool was called this turn. you must end every turn")
433
+ || text.startsWith("private-return acknowledgement claimed work was queued, but no ponder packet was created this turn.");
434
+ }
435
+ function latestUserMessageText(messages) {
436
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
437
+ const message = messages[i];
438
+ if (message?.role !== "user")
439
+ continue;
440
+ const text = messageContentText(message.content).trim();
441
+ if (isHarnessCorrectiveUserText(text))
442
+ continue;
443
+ if (text.length > 0)
444
+ return text;
445
+ }
446
+ return "";
447
+ }
448
+ function truncatePonderDelegatedContent(value) {
449
+ return value.length > 120 ? `${value.slice(0, 117)}...` : value;
450
+ }
451
+ function buildPonderDelegatedContent(input) {
452
+ const primary = (input.summary || input.objective).trim();
453
+ const sourceRequest = input.sourceRequest.trim();
454
+ if (!sourceRequest || sourceRequest === primary || sourceRequest === input.objective.trim()) {
455
+ return truncatePonderDelegatedContent(primary);
456
+ }
457
+ return truncatePonderDelegatedContent(`${primary}\nsource request: ${sourceRequest}`);
458
+ }
459
+ function looksLikePrivateReturnRequest(text) {
460
+ const normalized = text.toLowerCase();
461
+ return /\b(private|privately|private-attention|think|reflect|reflection)\b/.test(normalized)
462
+ && /\b(return|bring back|come back|surface|report back)\b/.test(normalized);
463
+ }
464
+ function extractPrivateReturnHeldTokens(text) {
465
+ const tokens = new Set();
466
+ for (const match of text.matchAll(/\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+){2,}\b/g)) {
467
+ const token = match[0];
468
+ if (token.length >= 8)
469
+ tokens.add(token);
470
+ }
471
+ return [...tokens];
472
+ }
473
+ function privateReturnAckLeakError(answer, heldTokens) {
474
+ if (!answer || heldTokens.size === 0)
475
+ return null;
476
+ for (const token of heldTokens) {
477
+ if (answer.includes(token)) {
478
+ 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.";
479
+ }
480
+ }
481
+ return null;
482
+ }
483
+ function claimsPrivateReturnQueued(answer) {
484
+ if (!answer)
485
+ return false;
486
+ const normalized = answer.toLowerCase();
487
+ return /\b(queued|queue|will return|return when|when .*complete|when .*completes|private pass|private runtime completes|inner dialog completes|later)\b/.test(normalized)
488
+ && /\b(private|inner|return|queued|later)\b/.test(normalized);
489
+ }
490
+ function privateReturnMissingPonderError(input) {
491
+ if (input.sawPonder)
492
+ return null;
493
+ if (!looksLikePrivateReturnRequest(input.latestUserRequest))
494
+ return null;
495
+ if (!claimsPrivateReturnQueued(input.answer))
496
+ return null;
497
+ 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.";
498
+ }
499
+ function activeReturnObligationId(agentName, obligationId) {
500
+ if (!obligationId)
501
+ return null;
502
+ const obligation = (0, obligations_1.readReturnObligation)(agentName, obligationId);
503
+ return obligation?.status === "queued" || obligation?.status === "running" ? obligationId : null;
504
+ }
505
+ function ponderReturnSessionId(packet) {
506
+ const origin = packet.origin;
507
+ if (!origin)
508
+ return "unknown/unknown/unknown";
509
+ return `${origin.friendId}/${origin.channel}/${origin.key}`;
510
+ }
511
+ function buildPonderReturnPrivateWakeOptions(input) {
512
+ const sessionId = ponderReturnSessionId(input.packet);
513
+ return {
514
+ reason: "ponder return obligation private attention",
515
+ triggerSource: "ponder-return-obligation",
516
+ budgetClass: "interactive",
517
+ idempotencyKey: `ponder-return:${input.agentName}:${input.returnObligationId}:${input.packet.id}:${sessionId}`,
518
+ originRefs: [
519
+ { kind: "tool", id: "ponder" },
520
+ { kind: "ponder-packet", id: input.packet.id },
521
+ { kind: "return-obligation", id: input.returnObligationId },
522
+ { kind: "session", id: sessionId },
523
+ ],
524
+ };
525
+ }
526
+ function buildPonderResult(packet, action, returnObligationId) {
527
+ return JSON.stringify({
528
+ ok: true,
529
+ packet_id: packet.id,
530
+ action,
531
+ status: packet.status,
532
+ return_obligation_id: returnObligationId,
533
+ private_return_contract: returnObligationId
534
+ ? "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."
535
+ : null,
536
+ }, null, 2);
537
+ }
538
+ /** Returns true when a tool call queries external state (GitHub, npm registry). */
539
+ function isExternalStateQuery(toolName, args) {
540
+ if (toolName !== "shell")
541
+ return false;
542
+ const cmd = String(args.command ?? "");
543
+ return /\bgh\s+(pr|run|api|issue)\b/.test(cmd) || /\bnpm\s+(view|info|show)\b/.test(cmd);
544
+ }
545
+ function getSettleRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp, _delegationDecision, sawSendMessageSelf, sawPonder, _sawQuerySession, currentObligation, innerJob, _sawExternalStateQuery) {
546
+ // Delegation adherence removed: the delegation decision is surfaced in the
547
+ // system prompt as a suggestion. Hard-gating settle caused infinite
548
+ // rejection loops where the agent couldn't respond to the user at all.
549
+ // The agent is free to follow or ignore the delegation hint.
550
+ // 2. Pending obligation not addressed
551
+ if (innerJob?.obligationStatus === "pending" && !sawSendMessageSelf && !sawPonder) {
552
+ return "you're still holding something from an earlier conversation -- someone is waiting for your answer. finish the thought first, or ponder to keep working on it privately.";
553
+ }
554
+ // 3. mustResolveBeforeHandoff + missing intent
187
555
  if (mustResolveBeforeHandoff && !intent) {
188
- return "your final_answer is missing required intent. when you must keep going until done or blocked, call final_answer again with answer plus intent=complete, blocked, or direct_reply.";
556
+ return "your settle is missing required intent. when you must keep going until done or blocked, call settle again with answer plus intent=complete, blocked, or direct_reply.";
189
557
  }
558
+ // 4. mustResolveBeforeHandoff + direct_reply without follow-up
190
559
  if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
191
- return "your final_answer used intent=direct_reply without a newer steering follow-up. continue the unresolved work, or call final_answer again with intent=complete or blocked when appropriate.";
560
+ return "your settle used intent=direct_reply without a newer steering follow-up. continue the unresolved work, or call settle again with intent=complete or blocked when appropriate.";
561
+ }
562
+ // 5. mustResolveBeforeHandoff + complete while a live return loop is still active
563
+ if (mustResolveBeforeHandoff && intent === "complete" && currentObligation && !sawSteeringFollowUp) {
564
+ return "you still owe the live session a visible return on this work. don't end the turn yet — continue until you've brought back the external-state update, or use intent=blocked with the concrete blocker.";
192
565
  }
193
- return "your final_answer was incomplete or malformed. call final_answer again with your complete response.";
566
+ return null;
194
567
  }
195
- // Re-export kick utilities for backward compat
196
- var kicks_1 = require("./kicks");
197
- Object.defineProperty(exports, "hasToolIntent", { enumerable: true, get: function () { return kicks_1.hasToolIntent; } });
198
568
  function upsertSystemPrompt(messages, systemText) {
199
569
  const systemMessage = { role: "system", content: systemText };
200
570
  if (messages[0]?.role === "system") {
@@ -232,27 +602,39 @@ const TOOL_SCAN_BOUNDARY_ROLES = new Set(["assistant", "user"]);
232
602
  // 1. If an assistant message has tool_calls but missing tool results, inject synthetic error results.
233
603
  // 2. If a tool result's tool_call_id doesn't match any tool_calls in a preceding assistant message, remove it.
234
604
  // This prevents 400 errors from the API after an aborted turn.
605
+ //
606
+ // Position-aware: a tool result is orphaned when its tool_call_id hasn't been
607
+ // defined by an assistant message AT THIS POSITION yet. MiniMax-M2.7 reuses
608
+ // canonical tool_call_ids across turns, so the global-set check that this
609
+ // function used previously kept misordered tool results that MiniMax then
610
+ // rejected with error 2013 ("tool result's tool id not found"). Walking
611
+ // in order matches what MiniMax actually enforces.
235
612
  function repairOrphanedToolCalls(messages) {
236
- // Pass 1: collect all valid tool_call IDs from assistant messages
237
- const validCallIds = new Set();
238
- for (const msg of messages) {
613
+ // Pass 1: walk in order, accumulate seen tool_call_ids per-position, and
614
+ // mark tool results for removal if their id hasn't been defined yet.
615
+ const seenCallIds = new Set();
616
+ const removeIndices = [];
617
+ for (let i = 0; i < messages.length; i++) {
618
+ const msg = messages[i];
239
619
  if (msg.role === "assistant") {
240
620
  const asst = msg;
241
621
  if (asst.tool_calls) {
242
622
  for (const tc of asst.tool_calls)
243
- validCallIds.add(tc.id);
623
+ seenCallIds.add(tc.id);
244
624
  }
625
+ continue;
245
626
  }
246
- }
247
- // Pass 2: remove orphaned tool results (tool_call_id not in any assistant's tool_calls)
248
- for (let i = messages.length - 1; i >= 0; i--) {
249
- if (messages[i].role === "tool") {
250
- const toolMsg = messages[i];
251
- if (!validCallIds.has(toolMsg.tool_call_id)) {
252
- messages.splice(i, 1);
627
+ if (msg.role === "tool") {
628
+ const toolMsg = msg;
629
+ if (!seenCallIds.has(toolMsg.tool_call_id)) {
630
+ removeIndices.push(i);
253
631
  }
254
632
  }
255
633
  }
634
+ // Splice from the end so earlier indices stay valid.
635
+ for (let i = removeIndices.length - 1; i >= 0; i--) {
636
+ messages.splice(removeIndices[i], 1);
637
+ }
256
638
  // Pass 3: inject synthetic results for tool_calls missing their tool results
257
639
  for (let i = 0; i < messages.length; i++) {
258
640
  const msg = messages[i];
@@ -274,10 +656,13 @@ function repairOrphanedToolCalls(messages) {
274
656
  }
275
657
  const missing = asst.tool_calls.filter((tc) => !resultIds.has(tc.id));
276
658
  if (missing.length > 0) {
659
+ // AX rule: the agent must see what happened. Don't say "interrupted"
660
+ // — that's vague. Tell them the result was lost, possible causes,
661
+ // and what to do next.
277
662
  const syntheticResults = missing.map((tc) => ({
278
663
  role: "tool",
279
664
  tool_call_id: tc.id,
280
- content: "error: tool call was interrupted (previous turn timed out or was aborted)",
665
+ content: "error: this tool call's result was lost — the previous turn ended before the tool finished (provider rejection, daemon interrupt, or the tool itself errored). if the work needs to be done, retry the tool call now.",
281
666
  }));
282
667
  let insertAt = i + 1;
283
668
  while (insertAt < messages.length && messages[insertAt].role === "tool")
@@ -300,49 +685,67 @@ function isContextOverflow(err) {
300
685
  return true;
301
686
  return false;
302
687
  }
303
- // Detect transient network errors worth retrying
304
- function isTransientError(err) {
305
- if (!(err instanceof Error))
306
- return false;
307
- const msg = err.message || "";
308
- const code = err.code || "";
309
- // Node.js network error codes
310
- if (["ECONNRESET", "ECONNREFUSED", "ENOTFOUND", "ETIMEDOUT", "EPIPE",
311
- "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "ECONNABORTED"].includes(code))
312
- return true;
313
- // OpenAI SDK / fetch errors
314
- if (msg.includes("fetch failed"))
315
- return true;
316
- if (msg.includes("network") && !msg.includes("context"))
317
- return true;
318
- if (msg.includes("ECONNRESET") || msg.includes("ETIMEDOUT"))
319
- return true;
320
- if (msg.includes("socket hang up"))
321
- return true;
322
- if (msg.includes("getaddrinfo"))
323
- return true;
324
- // HTTP 429 / 500 / 502 / 503 / 504
325
- const status = err.status;
326
- if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504)
327
- return true;
328
- return false;
688
+ const RETRY_LABELS = {
689
+ "auth-failure": "auth error",
690
+ "usage-limit": "usage limit",
691
+ "rate-limit": "rate limited",
692
+ "server-error": "server error",
693
+ "network-error": "network error",
694
+ "unknown": "error",
695
+ };
696
+ function waitForProviderRetry(delayMs, signal) {
697
+ if (!signal) {
698
+ return new Promise((resolve) => {
699
+ setTimeout(resolve, delayMs);
700
+ });
701
+ }
702
+ return new Promise((resolve, reject) => {
703
+ let timer;
704
+ const onAbort = () => {
705
+ clearTimeout(timer);
706
+ reject(new provider_attempt_1.ProviderAttemptAbortError());
707
+ };
708
+ timer = setTimeout(() => {
709
+ signal.removeEventListener("abort", onAbort);
710
+ resolve();
711
+ }, delayMs);
712
+ if (signal.aborted) {
713
+ onAbort();
714
+ return;
715
+ }
716
+ signal.addEventListener("abort", onAbort, { once: true });
717
+ });
718
+ }
719
+ function buildAuthFailureGuidance(provider, model, agentName, detail) {
720
+ const mismatch = (0, provider_models_1.getProviderModelMismatchMessage)(provider, model);
721
+ const modelLabel = model
722
+ ? mismatch
723
+ ? `${provider} [configured model: ${model}]`
724
+ : `${provider} (${model})`
725
+ : provider;
726
+ const lines = [`${modelLabel} authentication failed.`];
727
+ const cleanDetail = detail.replace(/\s+/g, " ").trim();
728
+ if (cleanDetail)
729
+ lines.push(`provider detail: ${cleanDetail.length > 300 ? `${cleanDetail.slice(0, 297)}...` : cleanDetail}`);
730
+ lines.push("");
731
+ lines.push("To keep using this provider:");
732
+ lines.push(` 1. Run \`ouro auth --agent ${agentName} --provider ${provider}\``);
733
+ if (mismatch) {
734
+ const defaultModel = (0, provider_models_1.getDefaultModelForProvider)(provider);
735
+ lines.push("");
736
+ lines.push("Config warning:");
737
+ lines.push(` - ${mismatch}`);
738
+ lines.push(" - Repair the configured model with:");
739
+ lines.push(` \`ouro use --agent ${agentName} --lane outward --provider ${provider} --model ${defaultModel}\``);
740
+ lines.push(` \`ouro use --agent ${agentName} --lane inner --provider ${provider} --model ${defaultModel}\``);
741
+ }
742
+ lines.push("");
743
+ lines.push(`To use another configured provider instead, run \`ouro use --agent ${agentName} --lane <outward|inner> --provider <provider> --model <model>\`.`);
744
+ return lines.join("\n");
329
745
  }
330
- function classifyTransientError(err) {
331
- if (!(err instanceof Error))
332
- return "unknown error";
333
- const status = err.status;
334
- if (status === 429)
335
- return "rate limited";
336
- if (status === 401 || status === 403)
337
- return "auth error";
338
- if (status && status >= 500)
339
- return "server error";
340
- return "network error";
341
- }
342
- const MAX_RETRIES = 3;
343
- const RETRY_BASE_MS = 2000;
344
746
  async function runAgent(messages, callbacks, channel, signal, options) {
345
- const providerRuntime = getProviderRuntime();
747
+ const facing = (0, friends_1.channelToFacing)(channel);
748
+ let providerRuntime = await getProviderRuntime(facing);
346
749
  const provider = providerRuntime.id;
347
750
  const toolChoiceRequired = options?.toolChoiceRequired ?? true;
348
751
  const traceId = options?.traceId;
@@ -366,6 +769,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
366
769
  // Refresh system prompt at start of each turn when channel is provided.
367
770
  // If refresh fails, keep existing system prompt (or inject a minimal safe fallback)
368
771
  // so turn execution remains consistent and non-fatal.
772
+ let structuredSystemPrompt;
369
773
  if (channel) {
370
774
  try {
371
775
  const buildSystemOptions = {
@@ -374,7 +778,8 @@ async function runAgent(messages, callbacks, channel, signal, options) {
374
778
  supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
375
779
  };
376
780
  const refreshed = await (0, prompt_1.buildSystem)(channel, buildSystemOptions, currentContext);
377
- upsertSystemPrompt(messages, refreshed);
781
+ structuredSystemPrompt = refreshed;
782
+ upsertSystemPrompt(messages, (0, prompt_1.flattenSystemPrompt)(refreshed));
378
783
  }
379
784
  catch (error) {
380
785
  const hadExistingSystemPrompt = messages[0]?.role === "system" && typeof messages[0].content === "string";
@@ -395,42 +800,140 @@ async function runAgent(messages, callbacks, channel, signal, options) {
395
800
  });
396
801
  }
397
802
  }
398
- await (0, associative_recall_1.injectAssociativeRecall)(messages);
803
+ if (channel && options?.skipKeptNotes !== true) {
804
+ await (0, kept_notes_1.injectKeptNotes)(messages, {
805
+ channel,
806
+ friend: currentContext?.friend,
807
+ judge: async (input) => (0, kept_notes_1.createKeptNotesJudge)(await getProviderRuntime("agent"), signal)(input),
808
+ signal,
809
+ traceId,
810
+ });
811
+ }
399
812
  let done = false;
400
813
  let lastUsage;
401
814
  let overflowRetried = false;
402
- let retryCount = 0;
403
- let outcome = "complete";
815
+ let outcome = "settled";
404
816
  let completion;
817
+ let terminalError;
818
+ let terminalErrorClassification;
405
819
  let sawSteeringFollowUp = false;
406
820
  let mustResolveBeforeHandoffActive = options?.mustResolveBeforeHandoff === true;
407
821
  let currentReasoningEffort = "medium";
822
+ let sawSendMessageSelf = false;
823
+ let sawPonder = false;
824
+ let sawQuerySession = false;
825
+ let sawBridgeManage = false;
826
+ let sawExternalStateQuery = false;
827
+ const privateReturnHeldTokens = new Set();
828
+ // Once-per-turn flag for the fresh-work rest gate. Without this, an agent
829
+ // that called rest, was told "fresh work arrived", processed the items,
830
+ // and called rest again would get the same message forever — the gate
831
+ // condition is read from the turn-start snapshot of pendingMessages,
832
+ // which doesn't update mid-turn. The agent only needs to be told once;
833
+ // after that, repeated rest attempts mean they've acknowledged.
834
+ let freshWorkGateFired = false;
835
+ // Counter for no-tool-call violations. MiniMax reasoning models occasionally
836
+ // emit only a <think>...</think> block and stop, without any tool call — even
837
+ // when tool_choice is set to "required". Private-return requests also need
838
+ // a hard no-tool guard: a text-only "queued" acknowledgement is false unless
839
+ // a ponder packet created the return obligation in this turn.
840
+ let noToolCallRetries = 0;
841
+ const NO_TOOL_CALL_MAX_RETRIES = 2;
842
+ const toolLoopState = (0, tool_loop_1.createToolLoopState)();
843
+ const toolFrictionLedger = (0, tool_friction_1.createToolFrictionLedger)();
844
+ const finishTerminalProviderError = (error, classification) => {
845
+ terminalError = error;
846
+ terminalErrorClassification = classification;
847
+ /* v8 ignore start — auth-failure guidance: tested via provider error classification tests @preserve */
848
+ if (terminalErrorClassification === "auth-failure") {
849
+ const agentName = (0, identity_2.getAgentName)();
850
+ const currentProvider = providerRuntime.id;
851
+ callbacks.onError(new Error(buildAuthFailureGuidance(currentProvider, providerRuntime.model, agentName, terminalError.message)), "terminal");
852
+ }
853
+ else {
854
+ callbacks.onError(terminalError, "terminal");
855
+ }
856
+ /* v8 ignore stop */
857
+ const errorDetails = (0, error_classification_1.extractProviderErrorDetails)(terminalError);
858
+ (0, runtime_1.emitNervesEvent)({
859
+ level: "error",
860
+ event: "engine.error",
861
+ trace_id: traceId,
862
+ component: "engine",
863
+ message: terminalError.message,
864
+ meta: {
865
+ provider: providerRuntime.id,
866
+ model: providerRuntime.model,
867
+ errorClassification: terminalErrorClassification,
868
+ ...(errorDetails.status !== undefined ? { httpStatus: errorDetails.status } : {}),
869
+ ...(errorDetails.bodyExcerpt ? { bodyExcerpt: errorDetails.bodyExcerpt } : {}),
870
+ summary: (0, error_classification_1.summarizeProviderError)(terminalError, terminalErrorClassification, providerRuntime.id, providerRuntime.model),
871
+ },
872
+ });
873
+ stripLastToolCalls(messages);
874
+ outcome = "errored";
875
+ done = true;
876
+ };
408
877
  // Prevent MaxListenersExceeded warning — each iteration adds a listener
409
878
  try {
410
879
  require("events").setMaxListeners(50, signal);
411
880
  }
412
881
  catch { /* unsupported */ }
413
882
  const toolPreferences = currentContext?.friend?.toolPreferences;
414
- const baseTools = options?.tools ?? (0, tools_1.getToolsForChannel)(channel ? (0, channel_1.getChannelCapabilities)(channel) : undefined, toolPreferences && Object.keys(toolPreferences).length > 0 ? toolPreferences : undefined, currentContext, providerRuntime.capabilities);
883
+ const baseTools = options?.tools ?? (0, tools_1.getToolsForChannel)(channel ? (0, friends_1.getChannelCapabilities)(channel) : undefined, toolPreferences && Object.keys(toolPreferences).length > 0 ? toolPreferences : undefined, currentContext, providerRuntime.capabilities, options?.mcpManager, providerRuntime.model);
415
884
  // Augment tool context with reasoning effort controls from provider
416
- const augmentedToolContext = options?.toolContext
885
+ const baseToolContext = options?.toolContext
886
+ ?? (options?.orientationFrame ? { signin: async () => undefined, orientationFrame: options.orientationFrame } : undefined);
887
+ const habitSession = options?.habitSession ?? baseToolContext?.habitSession;
888
+ const augmentedToolContext = baseToolContext
417
889
  ? {
418
- ...options.toolContext,
890
+ ...baseToolContext,
419
891
  supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
420
892
  setReasoningEffort: (level) => { currentReasoningEffort = level; },
893
+ activeWorkFrame: options?.activeWorkFrame,
894
+ orientationFrame: options?.orientationFrame ?? baseToolContext.orientationFrame,
895
+ ...(habitSession ? { habitSession } : {}),
421
896
  }
422
- : undefined;
897
+ : habitSession
898
+ ? {
899
+ signin: async () => undefined,
900
+ habitSession,
901
+ supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
902
+ setReasoningEffort: (level) => { currentReasoningEffort = level; },
903
+ }
904
+ : undefined;
423
905
  // Rebase provider-owned turn state from canonical messages at user-turn start.
424
906
  // This prevents stale provider caches from replaying prior-turn context.
425
907
  providerRuntime.resetTurnState(messages);
426
908
  while (!done) {
427
- // When toolChoiceRequired is true (the default), include final_answer
428
- // so the model can signal completion. With tool_choice: required, the
429
- // model must call a tool every turn — final_answer is how it exits.
430
- // Overridable via options.toolChoiceRequired = false (e.g. CLI).
431
- const activeTools = toolChoiceRequired
432
- ? [...baseTools, ...(currentContext?.isGroupChat ? [tools_1.noResponseTool] : []), tools_1.finalAnswerTool]
909
+ // Channel-based tool filtering:
910
+ // - Private runtime: exclude send_message (delivery via surface), observe (no one to observe)
911
+ // - All outward channels (1:1, group, reaction): observe available
912
+ //
913
+ // ponder, settle/rest, surface, and observe are always assembled based on channel context.
914
+ // ponder is available in ALL channels (outer: think privately, inner: keep turning).
915
+ // Private runtime gets restTool instead of settleTool (rest = end turn, gated by attention queue).
916
+ // toolChoiceRequired only controls whether tool_choice: "required" is set in the API call.
917
+ const isPrivateRuntimeChannel = channel === "inner";
918
+ const privateRuntimeHabitCanSendMessage = isPrivateRuntimeChannel
919
+ && habitSession?.toolPolicy.outwardMessagingAllowed === true
920
+ && habitSession.toolPolicy.grantedTools.includes("send_message");
921
+ const privateRuntimeHabitCanSurface = isPrivateRuntimeChannel
922
+ && (!habitSession || (habitSession.toolPolicy.outwardMessagingAllowed === true
923
+ && habitSession.toolPolicy.grantedTools.includes("surface")));
924
+ const filteredBaseTools = isPrivateRuntimeChannel
925
+ ? baseTools.filter((t) => privateRuntimeHabitCanSendMessage || t.function.name !== "send_message")
433
926
  : baseTools;
927
+ const activeTools = [
928
+ ...filteredBaseTools,
929
+ tools_1.ponderTool,
930
+ ...(isPrivateRuntimeChannel && privateRuntimeHabitCanSurface ? [tools_2.surfaceToolDef] : []),
931
+ ...(isPrivateRuntimeChannel ? [tools_1.restTool] : []),
932
+ ...(!isPrivateRuntimeChannel ? [tools_1.observeTool] : []),
933
+ ...(!isPrivateRuntimeChannel ? [tools_1.settleTool] : []),
934
+ ...(isChatStyleChannel(channel ?? "") ? [tools_1.speakTool] : []),
935
+ ];
936
+ const activeToolNames = new Set(activeTools.map((tool) => tool.function.name));
434
937
  const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
435
938
  if (steeringFollowUps.length > 0) {
436
939
  const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
@@ -457,26 +960,146 @@ async function runAgent(messages, callbacks, channel, signal, options) {
457
960
  break;
458
961
  }
459
962
  try {
460
- callbacks.onModelStart();
461
- const result = await providerRuntime.streamTurn({
462
- messages,
463
- activeTools,
464
- callbacks,
465
- signal,
466
- traceId,
467
- toolChoiceRequired,
468
- reasoningEffort: currentReasoningEffort,
963
+ const habitCallbackBufferRef = { current: null };
964
+ const callProviderTurn = async () => {
965
+ callbacks.onModelStart();
966
+ habitCallbackBufferRef.current = habitSession ? createHabitCallbackBuffer(callbacks) : null;
967
+ try {
968
+ const promptBudget = (0, prompt_budget_1.applyPromptBudget)({
969
+ messages,
970
+ provider: providerRuntime.id,
971
+ model: providerRuntime.model,
972
+ contextWindowTokens: (0, config_1.getContextConfig)().maxTokens,
973
+ });
974
+ if (promptBudget.status !== "within_budget") {
975
+ messages.splice(0, messages.length, ...promptBudget.messages);
976
+ providerRuntime.resetTurnState(messages);
977
+ }
978
+ return await providerRuntime.streamTurn({
979
+ messages,
980
+ activeTools,
981
+ callbacks: habitCallbackBufferRef.current?.callbacks ?? callbacks,
982
+ signal,
983
+ traceId,
984
+ toolChoiceRequired,
985
+ reasoningEffort: currentReasoningEffort,
986
+ eagerSettleStreaming: true,
987
+ systemPrompt: structuredSystemPrompt,
988
+ });
989
+ }
990
+ catch (error) {
991
+ habitCallbackBufferRef.current?.discard();
992
+ habitCallbackBufferRef.current = null;
993
+ if (signal?.aborted)
994
+ throw new provider_attempt_1.ProviderAttemptAbortError();
995
+ throw error;
996
+ }
997
+ };
998
+ const callProviderTurnWithOverflowRecovery = async () => {
999
+ try {
1000
+ return await callProviderTurn();
1001
+ }
1002
+ catch (error) {
1003
+ if (error instanceof provider_attempt_1.ProviderAttemptAbortError)
1004
+ throw error;
1005
+ if (isContextOverflow(error) && !overflowRetried) {
1006
+ overflowRetried = true;
1007
+ stripLastToolCalls(messages);
1008
+ const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
1009
+ const trimmed = (0, context_1.trimMessages)(messages, maxTokens, contextMargin, maxTokens * 2);
1010
+ messages.splice(0, messages.length, ...trimmed);
1011
+ providerRuntime.resetTurnState(messages);
1012
+ callbacks.onError(new Error("context trimmed, retrying..."), "transient");
1013
+ return callProviderTurn();
1014
+ }
1015
+ throw error;
1016
+ }
1017
+ };
1018
+ const attempt = await (0, provider_attempt_1.runProviderAttempt)({
1019
+ operation: "turn",
1020
+ provider: providerRuntime.id,
1021
+ model: providerRuntime.model,
1022
+ run: callProviderTurnWithOverflowRecovery,
1023
+ classifyError: (error) => providerRuntime.classifyError(error),
1024
+ onRetry: async (record, maxAttempts) => {
1025
+ const delayMs = record.delayMs;
1026
+ const seconds = delayMs / 1000;
1027
+ const cause = RETRY_LABELS[record.classification];
1028
+ try {
1029
+ if (record.provider === "openai-codex" && record.classification === "auth-failure") {
1030
+ await (0, openai_codex_token_1.refreshOpenAICodexProviderCredentials)((0, identity_2.getAgentName)(), {
1031
+ force: true,
1032
+ reason: "turn-auth-failure",
1033
+ });
1034
+ }
1035
+ await (0, provider_credentials_1.refreshProviderCredentialPool)((0, identity_2.getAgentName)(), {
1036
+ preserveCachedOnFailure: true,
1037
+ providers: [record.provider],
1038
+ });
1039
+ _providerRuntimes[facing] = null;
1040
+ providerRuntime = await getProviderRuntime(facing);
1041
+ providerRuntime.resetTurnState(messages);
1042
+ }
1043
+ catch (refreshError) {
1044
+ (0, runtime_1.emitNervesEvent)({
1045
+ level: "warn",
1046
+ component: "engine",
1047
+ event: "engine.provider_retry_refresh_failed",
1048
+ message: "provider credential refresh failed during retry",
1049
+ meta: { provider: record.provider, model: record.model, reason: refreshError instanceof Error ? refreshError.message : String(refreshError) },
1050
+ });
1051
+ }
1052
+ callbacks.onError(new Error(`${cause}, retrying in ${seconds}s (${record.attempt}/${maxAttempts})...`), "transient");
1053
+ },
1054
+ sleep: async (delayMs) => {
1055
+ await waitForProviderRetry(delayMs, signal);
1056
+ providerRuntime.resetTurnState(messages);
1057
+ },
469
1058
  });
1059
+ if (!attempt.ok) {
1060
+ finishTerminalProviderError(attempt.error, attempt.classification);
1061
+ continue;
1062
+ }
1063
+ const result = attempt.value;
1064
+ const streamCallbackBuffer = habitCallbackBufferRef.current;
1065
+ habitCallbackBufferRef.current = null;
470
1066
  // Track usage from the latest API call
471
1067
  if (result.usage)
472
1068
  lastUsage = result.usage;
473
- retryCount = 0; // reset on success
474
1069
  // SHARED: build CC-format assistant message from TurnResult
475
1070
  const msg = {
476
1071
  role: "assistant",
477
1072
  };
478
- if (result.content)
479
- msg.content = result.content;
1073
+ // Persist assistant content WITHOUT inline <think>...</think> blocks.
1074
+ // Reasoning content already routed through onReasoningChunk for live
1075
+ // surfacing and persisted separately as `_reasoning_items` for
1076
+ // providers that support a reasoning channel; saving it inline AND
1077
+ // alongside tool_calls causes MiniMax to reject the replayed turn
1078
+ // with "tool result's tool id not found" (error code 2013) because
1079
+ // it can't reconcile reasoning-with-tools in the same assistant
1080
+ // message. Strip aggressively at persist so the next replay is
1081
+ // clean; preserve the original reasoning trace on the message via
1082
+ // `_inline_reasoning` so debug/audit paths can still see it.
1083
+ if (result.content) {
1084
+ const stripped = stripThinkBlocksForViolationCheck(result.content);
1085
+ if (stripped.length > 0)
1086
+ msg.content = stripped;
1087
+ if (stripped.length !== result.content.length) {
1088
+ msg._inline_reasoning = result.content;
1089
+ (0, runtime_1.emitNervesEvent)({
1090
+ level: "info",
1091
+ component: "engine",
1092
+ event: "engine.inline_reasoning_stripped",
1093
+ message: "stripped inline <think> blocks from persisted assistant message; preserved on _inline_reasoning",
1094
+ meta: {
1095
+ provider: providerRuntime.id,
1096
+ model: providerRuntime.model,
1097
+ originalLength: result.content.length,
1098
+ strippedLength: stripped.length,
1099
+ },
1100
+ });
1101
+ }
1102
+ }
480
1103
  if (result.toolCalls.length)
481
1104
  msg.tool_calls = result.toolCalls.map((tc) => ({
482
1105
  id: tc.id,
@@ -496,35 +1119,188 @@ async function runAgent(messages, callbacks, channel, signal, options) {
496
1119
  }
497
1120
  // Phase annotation for Codex provider
498
1121
  const hasPhaseAnnotation = providerRuntime.capabilities.has("phase-annotation");
499
- const isSoleFinalAnswer = result.toolCalls.length === 1 && result.toolCalls[0].name === "final_answer";
1122
+ const isSoleSettle = result.toolCalls.length === 1 && result.toolCalls[0].name === "settle";
500
1123
  if (hasPhaseAnnotation) {
501
- msg.phase = isSoleFinalAnswer ? "final_answer" : "commentary";
1124
+ msg.phase = isSoleSettle ? "settle" : "commentary";
502
1125
  }
1126
+ // Detect the MiniMax "only-thinking, no tool call" violation: no tool
1127
+ // calls returned, and the content is empty after stripping
1128
+ // <think>...</think> blocks. This is a narrow check — legitimate
1129
+ // content-only responses (text without think tags, or text outside
1130
+ // think tags) still flow through the original "no tool calls →
1131
+ // accept as-is" path so existing channels and tests are unaffected.
1132
+ const onlyThinkContent = !result.toolCalls.length
1133
+ && typeof result.content === "string"
1134
+ && stripThinkBlocksForViolationCheck(result.content).length === 0
1135
+ && result.content.length > 0;
1136
+ const privateReturnTextAckRetryError = !result.toolCalls.length
1137
+ ? privateReturnMissingPonderError({
1138
+ latestUserRequest: latestUserMessageText(messages),
1139
+ answer: stripThinkBlocksForViolationCheck(result.content),
1140
+ sawPonder,
1141
+ })
1142
+ : null;
503
1143
  if (!result.toolCalls.length) {
504
- // No tool calls — accept response as-is.
505
- // (Kick detection disabled; tool_choice: required + final_answer
506
- // is the primary loop control. See src/heart/kicks.ts to re-enable.)
1144
+ await streamCallbackBuffer?.flush();
1145
+ if (privateReturnTextAckRetryError) {
1146
+ callbacks.onClearText?.();
1147
+ if (noToolCallRetries < NO_TOOL_CALL_MAX_RETRIES) {
1148
+ noToolCallRetries++;
1149
+ (0, runtime_1.emitNervesEvent)({
1150
+ level: "warn",
1151
+ component: "engine",
1152
+ event: "engine.no_tool_call_retry",
1153
+ message: "model returned a text-only private-return acknowledgement without ponder; retrying with corrective nudge",
1154
+ meta: {
1155
+ attempt: noToolCallRetries,
1156
+ cap: NO_TOOL_CALL_MAX_RETRIES,
1157
+ provider: providerRuntime.id,
1158
+ model: providerRuntime.model,
1159
+ reason: "private_return_missing_ponder",
1160
+ contentLength: result.content.length,
1161
+ },
1162
+ });
1163
+ messages.push(msg);
1164
+ messages.push({
1165
+ role: "user",
1166
+ content: `${privateReturnTextAckRetryError} Emit the ponder(action=create, ...) tool call now, or ask a blocking clarification without saying the private work is queued.`,
1167
+ });
1168
+ continue;
1169
+ }
1170
+ const blockedAnswer = "I could not start the private pass. No private-attention packet was created, so no return work was queued.";
1171
+ (0, runtime_1.emitNervesEvent)({
1172
+ level: "error",
1173
+ component: "engine",
1174
+ event: "engine.private_return_missing_ponder_blocked",
1175
+ message: "private-return text acknowledgement skipped ponder through the retry cap; failing closed",
1176
+ meta: {
1177
+ cap: NO_TOOL_CALL_MAX_RETRIES,
1178
+ provider: providerRuntime.id,
1179
+ model: providerRuntime.model,
1180
+ contentLength: result.content.length,
1181
+ },
1182
+ });
1183
+ msg.content = blockedAnswer;
1184
+ messages.push(msg);
1185
+ callbacks.onTextChunk(blockedAnswer);
1186
+ completion = { answer: blockedAnswer, intent: "blocked" };
1187
+ outcome = "blocked";
1188
+ done = true;
1189
+ continue;
1190
+ }
1191
+ if (onlyThinkContent && toolChoiceRequired && noToolCallRetries < NO_TOOL_CALL_MAX_RETRIES) {
1192
+ // Provider-level violation: tool_choice was required, model emitted
1193
+ // only a <think>...</think> block (or empty content) with no tool
1194
+ // call. Retry with a corrective nudge up to NO_TOOL_CALL_MAX_RETRIES
1195
+ // times. After cap, accept as-is (the readback path strips think
1196
+ // tags and surfaces a clear diagnostic).
1197
+ noToolCallRetries++;
1198
+ (0, runtime_1.emitNervesEvent)({
1199
+ level: "warn",
1200
+ component: "engine",
1201
+ event: "engine.no_tool_call_retry",
1202
+ message: "model returned only <think> content with no tool call despite tool_choice=required; retrying with corrective nudge",
1203
+ meta: {
1204
+ attempt: noToolCallRetries,
1205
+ cap: NO_TOOL_CALL_MAX_RETRIES,
1206
+ provider: providerRuntime.id,
1207
+ model: providerRuntime.model,
1208
+ contentLength: result.content.length,
1209
+ },
1210
+ });
1211
+ messages.push(msg);
1212
+ messages.push({
1213
+ role: "user",
1214
+ content: isPrivateRuntimeChannel
1215
+ ? "no tool was called this turn. you must end every turn by calling rest (or surface, ponder, observe). emit the tool call now."
1216
+ : "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.",
1217
+ });
1218
+ continue;
1219
+ }
1220
+ // Legitimate text-only response, or cap reached — accept as-is.
507
1221
  messages.push(msg);
508
1222
  done = true;
509
1223
  }
510
1224
  else {
511
- // Check for final_answer sole call: intercept before tool execution
512
- if (isSoleFinalAnswer) {
1225
+ // Reset the retry counter on any successful tool call.
1226
+ noToolCallRetries = 0;
1227
+ const habitBlockReason = await habitToolBatchBlockReason(habitSession, result.toolCalls, augmentedToolContext?.delegatedOrigins, activeToolNames);
1228
+ if (habitBlockReason) {
1229
+ streamCallbackBuffer?.discard();
1230
+ recordBlockedHabitSurfaceAttempts(habitSession, result.toolCalls, habitBlockReason);
1231
+ messages.push(msg);
1232
+ const blockedOutput = `blocked: ${habitBlockReason}. No tool side effects from this assistant message were executed.`;
1233
+ for (const call of result.toolCalls) {
1234
+ messages.push({ role: "tool", tool_call_id: call.id, content: blockedOutput });
1235
+ providerRuntime.appendToolOutput(call.id, blockedOutput);
1236
+ }
1237
+ (0, runtime_1.emitNervesEvent)({
1238
+ level: "warn",
1239
+ component: "engine",
1240
+ event: "engine.habit_tool_batch_blocked",
1241
+ message: "habit tool batch blocked before side effects",
1242
+ meta: { reason: habitBlockReason, toolCalls: result.toolCalls.map((call) => call.name) },
1243
+ });
1244
+ continue;
1245
+ }
1246
+ await streamCallbackBuffer?.flush();
1247
+ // Check for settle sole call: intercept before tool execution
1248
+ if (isSoleSettle) {
1249
+ /* v8 ignore next -- defensive: JSON.parse catch for malformed settle args @preserve */
1250
+ const settleArgs = (() => { try {
1251
+ return JSON.parse(result.toolCalls[0].arguments);
1252
+ }
1253
+ catch {
1254
+ return {};
1255
+ } })();
1256
+ callbacks.onToolStart("settle", settleArgs);
1257
+ // Private-runtime attention queue gate: reject settle if items remain
1258
+ const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
1259
+ if (isPrivateRuntimeChannel && attentionQueue && attentionQueue.length > 0) {
1260
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
1261
+ callbacks.onClearText?.();
1262
+ messages.push(msg);
1263
+ const gateMessage = "current held-work frame still has unsurfaced items — return each listed item with surface(delegationId=...) before you settle. Older transcript claims are historical; only the current held-work frame is the gate.";
1264
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
1265
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
1266
+ continue;
1267
+ }
513
1268
  // Extract answer from the tool call arguments.
514
1269
  // Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
515
- const { answer, intent } = parseFinalAnswerPayload(result.toolCalls[0].arguments);
1270
+ const { answer, intent } = parseSettlePayload(result.toolCalls[0].arguments);
1271
+ // Private-runtime settle: no CompletionMetadata, "(settled)" ack
1272
+ if (isPrivateRuntimeChannel) {
1273
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
1274
+ messages.push(msg);
1275
+ const settled = "(settled)";
1276
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: settled });
1277
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, settled);
1278
+ outcome = "settled";
1279
+ done = true;
1280
+ continue;
1281
+ }
1282
+ const deliveredAnswer = answer;
1283
+ const retryError = privateReturnAckLeakError(deliveredAnswer, privateReturnHeldTokens)
1284
+ ?? privateReturnMissingPonderError({
1285
+ latestUserRequest: latestUserMessageText(messages),
1286
+ answer: deliveredAnswer,
1287
+ sawPonder,
1288
+ })
1289
+ ?? getSettleRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp, options?.delegationDecision, sawSendMessageSelf, sawPonder, sawQuerySession, options?.currentObligation ?? null, options?.activeWorkFrame?.inner?.job, sawExternalStateQuery);
516
1290
  const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
517
1291
  const validTerminalIntent = intent === "complete" || intent === "blocked";
518
- const validClosure = answer != null
1292
+ const validClosure = deliveredAnswer != null
1293
+ && !retryError
519
1294
  && (!mustResolveBeforeHandoffActive || validDirectReply || validTerminalIntent);
520
1295
  if (validClosure) {
1296
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
521
1297
  completion = {
522
- answer,
1298
+ answer: deliveredAnswer,
523
1299
  intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
524
1300
  };
525
- if (result.finalAnswerStreamed) {
1301
+ if (result.settleStreamed) {
526
1302
  // The streaming layer already parsed and emitted the answer
527
- // progressively via FinalAnswerParser. Skip clearing and
1303
+ // progressively via SettleParser. Skip clearing and
528
1304
  // re-emitting to avoid double-delivery.
529
1305
  }
530
1306
  else {
@@ -532,7 +1308,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
532
1308
  callbacks.onClearText?.();
533
1309
  // Emit the answer through the callback pipeline so channels receive it.
534
1310
  // Never truncate -- channel adapters handle splitting long messages.
535
- callbacks.onTextChunk(answer);
1311
+ callbacks.onTextChunk(deliveredAnswer);
536
1312
  }
537
1313
  messages.push(msg);
538
1314
  if (validDirectReply) {
@@ -544,63 +1320,114 @@ async function runAgent(messages, callbacks, channel, signal, options) {
544
1320
  const delivered = "(delivered)";
545
1321
  messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
546
1322
  providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
547
- outcome = intent === "blocked" ? "blocked" : "complete";
1323
+ outcome = intent === "blocked" ? "blocked" : "settled";
548
1324
  done = true;
549
1325
  }
550
1326
  }
551
1327
  else {
552
- // Answer is undefined -- the model's final_answer was incomplete or
1328
+ // Answer is undefined -- the model's settle was incomplete or
553
1329
  // malformed. Clear any partial streamed text or noise, then push the
554
1330
  // assistant msg + error tool result and let the model try again.
1331
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
555
1332
  callbacks.onClearText?.();
556
- const retryError = getFinalAnswerRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp);
557
1333
  messages.push(msg);
558
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: retryError });
559
- providerRuntime.appendToolOutput(result.toolCalls[0].id, retryError);
1334
+ const toolRetryMessage = retryError
1335
+ ?? "your settle was incomplete or malformed. call settle again with your complete response.";
1336
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: toolRetryMessage });
1337
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, toolRetryMessage);
560
1338
  }
561
1339
  continue;
562
1340
  }
563
- // Check for no_response sole call: intercept before tool execution
564
- const isSoleNoResponse = result.toolCalls.length === 1 && result.toolCalls[0].name === "no_response";
565
- if (isSoleNoResponse) {
566
- let reason;
567
- try {
568
- const parsed = JSON.parse(result.toolCalls[0].arguments);
569
- if (typeof parsed?.reason === "string")
570
- reason = parsed.reason;
1341
+ // Check for observe sole call: intercept before tool execution
1342
+ const isSoleObserve = result.toolCalls.length === 1 && result.toolCalls[0].name === "observe";
1343
+ if (isSoleObserve) {
1344
+ /* v8 ignore next -- defensive: JSON.parse catch for malformed observe args @preserve */
1345
+ const observeArgs = (() => { try {
1346
+ return JSON.parse(result.toolCalls[0].arguments);
571
1347
  }
572
- catch { /* ignore */ }
1348
+ catch {
1349
+ return {};
1350
+ } })();
1351
+ let reason;
1352
+ if (typeof observeArgs?.reason === "string")
1353
+ reason = observeArgs.reason;
1354
+ callbacks.onToolStart("observe", observeArgs);
573
1355
  (0, runtime_1.emitNervesEvent)({
574
1356
  component: "engine",
575
- event: "engine.no_response",
576
- message: "agent declined to respond in group chat",
1357
+ event: "engine.observe",
1358
+ message: "agent observed without responding",
577
1359
  meta: { ...(reason ? { reason } : {}) },
578
1360
  });
1361
+ callbacks.onToolEnd("observe", (0, tools_1.summarizeArgs)("observe", observeArgs), true);
579
1362
  messages.push(msg);
580
1363
  const silenced = "(silenced)";
581
1364
  messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: silenced });
582
1365
  providerRuntime.appendToolOutput(result.toolCalls[0].id, silenced);
583
- outcome = "no_response";
1366
+ outcome = "observed";
1367
+ done = true;
1368
+ continue;
1369
+ }
1370
+ // Check for rest sole call: intercept before tool execution
1371
+ const isSoleRest = result.toolCalls.length === 1 && result.toolCalls[0].name === "rest";
1372
+ if (isSoleRest) {
1373
+ const restArgs = (() => { try {
1374
+ return JSON.parse(result.toolCalls[0].arguments);
1375
+ }
1376
+ catch {
1377
+ return {};
1378
+ } })();
1379
+ callbacks.onToolStart("rest", restArgs);
1380
+ // Attention queue gate: reject rest if items remain
1381
+ const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
1382
+ if (attentionQueue && attentionQueue.length > 0) {
1383
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), false);
1384
+ messages.push(msg);
1385
+ const gateMessage = "current held-work frame still has unsurfaced items — return each listed item with surface(delegationId=...) before you rest. Older transcript claims are historical; only the current held-work frame is the gate.";
1386
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
1387
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
1388
+ continue;
1389
+ }
1390
+ if (hasFreshPendingWork(options) && !freshWorkGateFired) {
1391
+ freshWorkGateFired = true;
1392
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), false);
1393
+ messages.push(msg);
1394
+ const gateMessage = "fresh work arrived for me this turn — inspect the pending messages above and take the next concrete action before you rest.";
1395
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
1396
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
1397
+ (0, runtime_1.emitNervesEvent)({
1398
+ level: "info",
1399
+ component: "engine",
1400
+ event: "engine.fresh_work_gate_fired",
1401
+ message: "rest deferred once because pending work arrived this turn; agent has been notified",
1402
+ meta: { pendingCount: options.pendingMessages.length },
1403
+ });
1404
+ continue;
1405
+ }
1406
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), true);
1407
+ messages.push(msg);
1408
+ const ack = "(resting)";
1409
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
1410
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
1411
+ (0, runtime_1.emitNervesEvent)({
1412
+ component: "engine",
1413
+ event: "engine.rested",
1414
+ message: "resting until next heartbeat",
1415
+ meta: { ...(typeof restArgs?.status === "string" ? { status: restArgs.status } : {}) },
1416
+ });
1417
+ outcome = "rested";
584
1418
  done = true;
585
1419
  continue;
586
1420
  }
587
1421
  messages.push(msg);
588
- // SHARED: execute tools (final_answer and no_response in mixed calls are rejected inline)
1422
+ // Execute tools (sole-call tools in mixed calls are rejected inline)
589
1423
  for (const tc of result.toolCalls) {
590
1424
  if (signal?.aborted)
591
1425
  break;
592
- // Intercept final_answer in mixed call: reject it
593
- if (tc.name === "final_answer") {
594
- const rejection = "rejected: final_answer must be the only tool call. Finish your work first, then call final_answer alone.";
595
- messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
596
- providerRuntime.appendToolOutput(tc.id, rejection);
597
- continue;
598
- }
599
- // Intercept no_response in mixed call: reject it
600
- if (tc.name === "no_response") {
601
- const rejection = "rejected: no_response must be the only tool call. call no_response alone when you want to stay silent.";
602
- messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
603
- providerRuntime.appendToolOutput(tc.id, rejection);
1426
+ // Reject sole-call tools when mixed with other tool calls
1427
+ const soleCallRejection = SOLE_CALL_REJECTION[tc.name];
1428
+ if (soleCallRejection) {
1429
+ messages.push({ role: "tool", tool_call_id: tc.id, content: soleCallRejection });
1430
+ providerRuntime.appendToolOutput(tc.id, soleCallRejection);
604
1431
  continue;
605
1432
  }
606
1433
  let args = {};
@@ -610,21 +1437,253 @@ async function runAgent(messages, callbacks, channel, signal, options) {
610
1437
  catch {
611
1438
  /* ignore */
612
1439
  }
613
- const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
614
- // Confirmation check for mutate tools
615
- if ((0, tools_1.isConfirmationRequired)(tc.name) && !options?.skipConfirmation) {
616
- let decision = "denied";
617
- if (callbacks.onConfirmAction) {
618
- decision = await callbacks.onConfirmAction(tc.name, args);
619
- }
620
- if (decision !== "confirmed") {
621
- const cancelled = "Action cancelled by user.";
1440
+ if (tc.name === "send_message" && args.friendId === "self") {
1441
+ const latestUserText = latestUserMessageText(messages);
1442
+ if (!isPrivateRuntimeChannel && looksLikePrivateReturnRequest(latestUserText)) {
1443
+ const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
1444
+ const rejection = "private-return requests must use ponder, not send_message(friendId=self). Create a typed ponder packet with the marker/source request preserved, then only acknowledge that the private pass is queued.";
622
1445
  callbacks.onToolStart(tc.name, args);
623
1446
  callbacks.onToolEnd(tc.name, argSummary, false);
624
- messages.push({ role: "tool", tool_call_id: tc.id, content: cancelled });
625
- providerRuntime.appendToolOutput(tc.id, cancelled);
1447
+ messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
1448
+ providerRuntime.appendToolOutput(tc.id, rejection);
1449
+ continue;
1450
+ }
1451
+ sawSendMessageSelf = true;
1452
+ }
1453
+ if (tc.name === "speak") {
1454
+ let speakArgs = {};
1455
+ try {
1456
+ speakArgs = JSON.parse(tc.arguments);
1457
+ }
1458
+ catch { /* malformed */ }
1459
+ const speakMessage = typeof speakArgs.message === "string" ? speakArgs.message : "";
1460
+ const argSummary = (0, tools_1.summarizeArgs)("speak", { message: speakMessage });
1461
+ callbacks.onToolStart("speak", { message: speakMessage });
1462
+ if (speakMessage.trim().length === 0) {
1463
+ const err = "speak requires a non-empty `message` string.";
1464
+ callbacks.onToolEnd("speak", argSummary, false);
1465
+ messages.push({ role: "tool", tool_call_id: tc.id, content: err });
1466
+ providerRuntime.appendToolOutput(tc.id, err);
1467
+ (0, runtime_1.emitNervesEvent)({
1468
+ level: "warn",
1469
+ component: "engine",
1470
+ event: "engine.speak_invalid",
1471
+ message: "speak rejected: missing or empty message",
1472
+ meta: {},
1473
+ });
1474
+ continue;
1475
+ }
1476
+ callbacks.onTextChunk(speakMessage);
1477
+ let speakDeliveryError = null;
1478
+ try {
1479
+ await callbacks.flushNow?.();
1480
+ }
1481
+ catch (err) {
1482
+ speakDeliveryError = err instanceof Error ? err : new Error(String(err));
1483
+ }
1484
+ if (speakDeliveryError) {
1485
+ callbacks.onToolEnd("speak", argSummary, false);
1486
+ const failMsg = `speak delivery failed: ${speakDeliveryError.message}. the message did not reach your friend; do not assume they saw it.`;
1487
+ messages.push({ role: "tool", tool_call_id: tc.id, content: failMsg });
1488
+ providerRuntime.appendToolOutput(tc.id, failMsg);
1489
+ (0, runtime_1.emitNervesEvent)({
1490
+ level: "error",
1491
+ component: "engine",
1492
+ event: "engine.speak_delivery_failed",
1493
+ message: "speak delivery failed",
1494
+ meta: { error: speakDeliveryError.message, messageLength: speakMessage.length },
1495
+ });
626
1496
  continue;
627
1497
  }
1498
+ callbacks.onToolEnd("speak", argSummary, true);
1499
+ const ack = "(spoken)";
1500
+ messages.push({ role: "tool", tool_call_id: tc.id, content: ack });
1501
+ providerRuntime.appendToolOutput(tc.id, ack);
1502
+ (0, runtime_1.emitNervesEvent)({
1503
+ component: "engine",
1504
+ event: "engine.speak",
1505
+ message: "agent spoke mid-turn",
1506
+ meta: { messageLength: speakMessage.length },
1507
+ });
1508
+ continue;
1509
+ }
1510
+ if (tc.name === "ponder") {
1511
+ const parsedArgs = normalizeLegacyPonderArgs(parsePonderPayload(tc.arguments));
1512
+ const argSummary = (0, tools_1.summarizeArgs)(tc.name, parsedArgs);
1513
+ callbacks.onToolStart(tc.name, parsedArgs);
1514
+ let toolResult;
1515
+ let success = false;
1516
+ try {
1517
+ const action = parsedArgs.action ?? "create";
1518
+ const currentSession = (augmentedToolContext ?? options?.toolContext)?.currentSession;
1519
+ const currentOrigin = currentSession
1520
+ ? { friendId: currentSession.friendId, channel: currentSession.channel, key: currentSession.key }
1521
+ : undefined;
1522
+ const isInnerChannel = currentOrigin?.friendId === "self" && currentOrigin?.channel === "inner";
1523
+ const shouldCreateReturnObligation = !!currentOrigin && !isInnerChannel;
1524
+ const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins ?? [];
1525
+ const successCriteria = parseSuccessCriteria(parsedArgs.success_criteria);
1526
+ const payload = parsePacketPayload(parsedArgs.payload_json);
1527
+ let packet;
1528
+ let returnObligationId = null;
1529
+ let resultAction = "created";
1530
+ let privateReturnSourceRequest = "";
1531
+ if (action === "create") {
1532
+ if (isInnerChannel && attentionQueue.length > 0) {
1533
+ throw new Error("private runtime already has held return work in the attention queue; surface the existing delegationId instead of creating a replacement ponder packet.");
1534
+ }
1535
+ const kind = parsedArgs.kind;
1536
+ const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
1537
+ const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
1538
+ const sourceRequest = currentOrigin && !isInnerChannel ? latestUserMessageText(messages) : "";
1539
+ privateReturnSourceRequest = sourceRequest;
1540
+ if (!kind || !objective || !successCriteria || !payload) {
1541
+ throw new Error("ponder create requires kind, objective, success_criteria, and valid payload_json.");
1542
+ }
1543
+ const packetPayload = sourceRequest
1544
+ ? { ...payload, sourceRequest }
1545
+ : payload;
1546
+ const createLinkedReturnObligation = (id, packetId) => {
1547
+ (0, obligations_1.createReturnObligation)((0, identity_2.getAgentName)(), {
1548
+ id,
1549
+ origin: currentOrigin,
1550
+ status: "queued",
1551
+ delegatedContent: buildPonderDelegatedContent({ summary, objective, sourceRequest }),
1552
+ packetId,
1553
+ createdAt: Date.now(),
1554
+ });
1555
+ };
1556
+ const agentRoot = (0, identity_2.getAgentRoot)();
1557
+ let relatedObligationId;
1558
+ if (currentOrigin && !isInnerChannel) {
1559
+ try {
1560
+ const obligation = (0, obligations_1.createObligation)(agentRoot, {
1561
+ origin: currentOrigin,
1562
+ content: objective,
1563
+ });
1564
+ relatedObligationId = obligation.id;
1565
+ }
1566
+ catch {
1567
+ relatedObligationId = undefined;
1568
+ }
1569
+ }
1570
+ const frictionSignature = kind === "harness_friction" && typeof packetPayload.frictionSignature === "string"
1571
+ ? packetPayload.frictionSignature
1572
+ : null;
1573
+ const existing = frictionSignature && currentOrigin
1574
+ ? (0, packets_1.findHarnessFrictionPacket)(agentRoot, currentOrigin, frictionSignature)
1575
+ : null;
1576
+ if (existing) {
1577
+ resultAction = "revised";
1578
+ const existingActiveReturnId = shouldCreateReturnObligation
1579
+ ? activeReturnObligationId((0, identity_2.getAgentName)(), existing.relatedReturnObligationId)
1580
+ : null;
1581
+ returnObligationId = existingActiveReturnId
1582
+ ?? (shouldCreateReturnObligation ? (0, obligations_1.generateObligationId)(Date.now()) : null);
1583
+ packet = existing.status === "drafting"
1584
+ ? (0, packets_1.revisePonderPacket)(agentRoot, existing.id, {
1585
+ kind,
1586
+ objective,
1587
+ summary,
1588
+ successCriteria,
1589
+ payload: packetPayload,
1590
+ })
1591
+ : existing;
1592
+ if (returnObligationId && returnObligationId !== existing.relatedReturnObligationId) {
1593
+ packet = (0, packets_1.advancePonderPacket)(agentRoot, packet.id, { relatedReturnObligationId: returnObligationId });
1594
+ createLinkedReturnObligation(returnObligationId, packet.id);
1595
+ }
1596
+ }
1597
+ else {
1598
+ returnObligationId = shouldCreateReturnObligation ? (0, obligations_1.generateObligationId)(Date.now()) : null;
1599
+ packet = (0, packets_1.createPonderPacket)(agentRoot, {
1600
+ kind,
1601
+ objective,
1602
+ summary,
1603
+ successCriteria,
1604
+ ...(currentOrigin ? { origin: currentOrigin } : {}),
1605
+ ...(relatedObligationId ? { relatedObligationId } : {}),
1606
+ ...(returnObligationId ? { relatedReturnObligationId: returnObligationId } : {}),
1607
+ ...(parsedArgs.follows_packet_id ? { followsPacketId: parsedArgs.follows_packet_id } : {}),
1608
+ payload: packetPayload,
1609
+ });
1610
+ if (returnObligationId) {
1611
+ createLinkedReturnObligation(returnObligationId, packet.id);
1612
+ }
1613
+ }
1614
+ }
1615
+ else if (action === "revise") {
1616
+ const packetId = typeof parsedArgs.packet_id === "string" ? parsedArgs.packet_id.trim() : "";
1617
+ const kind = parsedArgs.kind;
1618
+ const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
1619
+ const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
1620
+ if (!packetId || !kind || !objective || !successCriteria || !payload) {
1621
+ throw new Error("ponder revise requires packet_id, kind, objective, success_criteria, and valid payload_json.");
1622
+ }
1623
+ packet = (0, packets_1.revisePonderPacket)((0, identity_2.getAgentRoot)(), packetId, {
1624
+ kind,
1625
+ objective,
1626
+ summary,
1627
+ successCriteria,
1628
+ payload,
1629
+ });
1630
+ returnObligationId = packet.relatedReturnObligationId
1631
+ && !(packet.origin?.friendId === "self" && packet.origin.channel === "inner")
1632
+ ? packet.relatedReturnObligationId
1633
+ : null;
1634
+ resultAction = "revised";
1635
+ }
1636
+ else {
1637
+ throw new Error("ponder requires action=create or revise.");
1638
+ }
1639
+ if (returnObligationId) {
1640
+ for (const token of extractPrivateReturnHeldTokens(privateReturnSourceRequest)) {
1641
+ privateReturnHeldTokens.add(token);
1642
+ }
1643
+ const agentName = (0, identity_2.getAgentName)();
1644
+ await (0, socket_client_1.requestPrivateWake)(agentName, augmentedToolContext?.daemonSocketPath, buildPonderReturnPrivateWakeOptions({ agentName, packet, returnObligationId })).catch(() => undefined);
1645
+ }
1646
+ sawPonder = true;
1647
+ toolResult = buildPonderResult(packet, resultAction, returnObligationId);
1648
+ success = true;
1649
+ (0, runtime_1.emitNervesEvent)({
1650
+ component: "engine",
1651
+ event: "engine.ponder_packet",
1652
+ message: "ponder packet touched",
1653
+ meta: {
1654
+ action: resultAction,
1655
+ packetId: packet.id,
1656
+ kind: packet.kind,
1657
+ status: packet.status,
1658
+ },
1659
+ });
1660
+ }
1661
+ catch (error) {
1662
+ toolResult = error instanceof Error ? error.message : String(error);
1663
+ }
1664
+ callbacks.onToolEnd(tc.name, argSummary, success);
1665
+ messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
1666
+ providerRuntime.appendToolOutput(tc.id, toolResult);
1667
+ continue;
1668
+ }
1669
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
1670
+ if (tc.name === "query_session")
1671
+ sawQuerySession = true;
1672
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
1673
+ if (tc.name === "bridge_manage")
1674
+ sawBridgeManage = true;
1675
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
1676
+ if (isExternalStateQuery(tc.name, args))
1677
+ sawExternalStateQuery = true;
1678
+ const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
1679
+ const toolLoop = (0, tool_loop_1.detectToolLoop)(toolLoopState, tc.name, args);
1680
+ if (toolLoop.stuck) {
1681
+ const rejection = `loop guard: ${toolLoop.message}`;
1682
+ callbacks.onToolStart(tc.name, args);
1683
+ callbacks.onToolEnd(tc.name, argSummary, false);
1684
+ messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
1685
+ providerRuntime.appendToolOutput(tc.id, rejection);
1686
+ continue;
628
1687
  }
629
1688
  callbacks.onToolStart(tc.name, args);
630
1689
  let toolResult;
@@ -637,70 +1696,34 @@ async function runAgent(messages, callbacks, channel, signal, options) {
637
1696
  catch (e) {
638
1697
  toolResult = `error: ${e}`;
639
1698
  success = false;
1699
+ augmentedToolContext?.habitSession?.recordError?.(toolResult);
640
1700
  }
641
- callbacks.onToolEnd(tc.name, argSummary, success);
1701
+ toolResult = (0, tool_friction_1.rewriteToolResultForModel)(tc.name, toolResult, toolFrictionLedger);
1702
+ (0, tool_loop_1.recordToolOutcome)(toolLoopState, tc.name, args, toolResult, success);
1703
+ callbacks.onToolEnd(tc.name, (0, tools_1.buildToolResultSummary)(tc.name, args, toolResult, success), success);
642
1704
  messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
643
1705
  providerRuntime.appendToolOutput(tc.id, toolResult);
1706
+ callbacks.onToolResult?.(messages);
644
1707
  }
645
1708
  }
646
1709
  }
647
1710
  catch (e) {
648
1711
  // Abort is not an error — just stop cleanly
649
- if (signal?.aborted) {
1712
+ if (e instanceof provider_attempt_1.ProviderAttemptAbortError || signal?.aborted) {
650
1713
  stripLastToolCalls(messages);
651
1714
  outcome = "aborted";
652
1715
  break;
653
1716
  }
654
- // Context overflow: trim aggressively and retry once
655
- if (isContextOverflow(e) && !overflowRetried) {
656
- overflowRetried = true;
657
- stripLastToolCalls(messages);
658
- const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
659
- const trimmed = (0, context_1.trimMessages)(messages, maxTokens, contextMargin, maxTokens * 2);
660
- messages.splice(0, messages.length, ...trimmed);
661
- providerRuntime.resetTurnState(messages);
662
- callbacks.onError(new Error("context trimmed, retrying..."), "transient");
663
- continue;
1717
+ const errorForClassification = e instanceof Error ? e : /* v8 ignore next -- defensive @preserve */ new Error(String(e));
1718
+ let providerClassification;
1719
+ try {
1720
+ providerClassification = providerRuntime.classifyError(errorForClassification);
664
1721
  }
665
- // Transient errors: retry with exponential backoff
666
- if (isTransientError(e) && retryCount < MAX_RETRIES) {
667
- retryCount++;
668
- const delay = RETRY_BASE_MS * Math.pow(2, retryCount - 1);
669
- const cause = classifyTransientError(e);
670
- callbacks.onError(new Error(`${cause}, retrying in ${delay / 1000}s (${retryCount}/${MAX_RETRIES})...`), "transient");
671
- // Wait with abort support
672
- const aborted = await new Promise((resolve) => {
673
- const timer = setTimeout(() => resolve(false), delay);
674
- if (signal) {
675
- const onAbort = () => { clearTimeout(timer); resolve(true); };
676
- if (signal.aborted) {
677
- clearTimeout(timer);
678
- resolve(true);
679
- return;
680
- }
681
- signal.addEventListener("abort", onAbort, { once: true });
682
- }
683
- });
684
- if (aborted) {
685
- stripLastToolCalls(messages);
686
- outcome = "aborted";
687
- break;
688
- }
689
- providerRuntime.resetTurnState(messages);
690
- continue;
1722
+ catch {
1723
+ /* v8 ignore next -- defensive: classifyError should not throw @preserve */
1724
+ providerClassification = "unknown";
691
1725
  }
692
- callbacks.onError(e instanceof Error ? e : new Error(String(e)), "terminal");
693
- (0, runtime_1.emitNervesEvent)({
694
- level: "error",
695
- event: "engine.error",
696
- trace_id: traceId,
697
- component: "engine",
698
- message: e instanceof Error ? e.message : String(e),
699
- meta: {},
700
- });
701
- stripLastToolCalls(messages);
702
- outcome = "errored";
703
- done = true;
1726
+ finishTerminalProviderError(errorForClassification, providerClassification);
704
1727
  }
705
1728
  }
706
1729
  (0, runtime_1.emitNervesEvent)({
@@ -708,7 +1731,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
708
1731
  trace_id: traceId,
709
1732
  component: "engine",
710
1733
  message: "runAgent turn completed",
711
- meta: { done },
1734
+ meta: { done, sawPonder, sawQuerySession, sawBridgeManage },
712
1735
  });
713
- return { usage: lastUsage, outcome, completion };
1736
+ return {
1737
+ usage: lastUsage,
1738
+ outcome,
1739
+ completion,
1740
+ ...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
1741
+ };
714
1742
  }