@ouro.bot/cli 0.1.0-alpha.69 → 0.1.0-alpha.690

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