@ouro.bot/cli 0.1.0-alpha.53 → 0.1.0-alpha.531

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 (382) hide show
  1. package/README.md +133 -19
  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-bootstrap-drift.md +54 -0
  6. package/RepairGuide.ouro/skills/diagnose-broken-remote.md +63 -0
  7. package/RepairGuide.ouro/skills/diagnose-stacked-typed-issues.md +35 -0
  8. package/RepairGuide.ouro/skills/diagnose-sync-blocked.md +54 -0
  9. package/RepairGuide.ouro/skills/diagnose-vault-expired.md +60 -0
  10. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +4 -2
  11. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +2 -2
  12. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  13. package/changelog.json +3434 -0
  14. package/dist/arc/attention-types.js +8 -0
  15. package/dist/arc/cares.js +140 -0
  16. package/dist/arc/episodes.js +117 -0
  17. package/dist/arc/intentions.js +133 -0
  18. package/dist/arc/json-store.js +117 -0
  19. package/dist/arc/obligations.js +237 -0
  20. package/dist/arc/packets.js +193 -0
  21. package/dist/arc/presence.js +185 -0
  22. package/dist/arc/task-lifecycle.js +65 -0
  23. package/dist/heart/active-work.js +837 -26
  24. package/dist/heart/agent-entry.js +58 -3
  25. package/dist/heart/attachments/image-normalize.js +194 -0
  26. package/dist/heart/attachments/materialize.js +97 -0
  27. package/dist/heart/attachments/originals.js +88 -0
  28. package/dist/heart/attachments/render.js +29 -0
  29. package/dist/heart/attachments/sources/adapter.js +2 -0
  30. package/dist/heart/attachments/sources/bluebubbles.js +156 -0
  31. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  32. package/dist/heart/attachments/sources/index.js +16 -0
  33. package/dist/heart/attachments/store.js +103 -0
  34. package/dist/heart/attachments/types.js +93 -0
  35. package/dist/heart/auth/auth-flow.js +427 -0
  36. package/dist/heart/background-operations.js +281 -0
  37. package/dist/heart/bundle-state.js +168 -0
  38. package/dist/heart/commitments.js +111 -0
  39. package/dist/heart/config-registry.js +304 -0
  40. package/dist/heart/config.js +119 -129
  41. package/dist/heart/core.js +948 -243
  42. package/dist/heart/cross-chat-delivery.js +3 -18
  43. package/dist/heart/daemon/agent-config-check.js +512 -0
  44. package/dist/heart/daemon/agent-discovery.js +102 -3
  45. package/dist/heart/daemon/agent-service.js +522 -0
  46. package/dist/heart/daemon/agentic-repair.js +554 -0
  47. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  48. package/dist/heart/daemon/boot-sync-probe.js +197 -0
  49. package/dist/heart/daemon/cadence.js +70 -0
  50. package/dist/heart/daemon/cli-defaults.js +643 -0
  51. package/dist/heart/daemon/cli-exec.js +7544 -0
  52. package/dist/heart/daemon/cli-help.js +498 -0
  53. package/dist/heart/daemon/cli-parse.js +1561 -0
  54. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  55. package/dist/heart/daemon/cli-render.js +728 -0
  56. package/dist/heart/daemon/cli-types.js +8 -0
  57. package/dist/heart/daemon/connect-bay.js +323 -0
  58. package/dist/heart/daemon/daemon-cli.js +29 -1650
  59. package/dist/heart/daemon/daemon-entry.js +384 -2
  60. package/dist/heart/daemon/daemon-health.js +183 -0
  61. package/dist/heart/daemon/daemon-rollup.js +58 -0
  62. package/dist/heart/daemon/daemon-runtime-sync.js +190 -12
  63. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  64. package/dist/heart/daemon/daemon.js +798 -69
  65. package/dist/heart/daemon/dns-workflow.js +394 -0
  66. package/dist/heart/daemon/doctor-types.js +8 -0
  67. package/dist/heart/daemon/doctor.js +844 -0
  68. package/dist/heart/daemon/drift-detection.js +146 -0
  69. package/dist/heart/daemon/health-monitor.js +117 -1
  70. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  71. package/dist/heart/daemon/hooks/bundle-meta.js +115 -1
  72. package/dist/heart/daemon/http-health-probe.js +80 -0
  73. package/dist/heart/daemon/human-command-screens.js +234 -0
  74. package/dist/heart/daemon/human-readiness.js +114 -0
  75. package/dist/heart/daemon/inner-status.js +102 -0
  76. package/dist/heart/daemon/interactive-repair.js +394 -0
  77. package/dist/heart/daemon/launchd.js +22 -5
  78. package/dist/heart/daemon/log-tailer.js +82 -12
  79. package/dist/heart/daemon/logs-prune.js +110 -0
  80. package/dist/heart/daemon/message-router.js +2 -2
  81. package/dist/heart/daemon/os-cron-deps.js +134 -0
  82. package/dist/heart/daemon/ouro-bot-entry.js +4 -2
  83. package/dist/heart/daemon/ouro-entry.js +3 -1
  84. package/dist/heart/daemon/process-manager.js +375 -33
  85. package/dist/heart/daemon/provider-discovery.js +137 -0
  86. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  87. package/dist/heart/daemon/pulse.js +475 -0
  88. package/dist/heart/daemon/readiness-repair.js +365 -0
  89. package/dist/heart/daemon/run-hooks.js +2 -0
  90. package/dist/heart/daemon/runtime-logging.js +67 -16
  91. package/dist/heart/daemon/runtime-metadata.js +73 -0
  92. package/dist/heart/daemon/safe-mode.js +161 -0
  93. package/dist/heart/daemon/sense-manager.js +341 -37
  94. package/dist/heart/daemon/session-id-resolver.js +131 -0
  95. package/dist/heart/daemon/skill-management-installer.js +94 -0
  96. package/dist/heart/daemon/socket-client.js +109 -4
  97. package/dist/heart/daemon/stale-bundle-prune.js +96 -0
  98. package/dist/heart/daemon/startup-tui.js +330 -0
  99. package/dist/heart/daemon/task-scheduler.js +3 -25
  100. package/dist/heart/daemon/terminal-ui.js +499 -0
  101. package/dist/heart/daemon/thoughts.js +162 -17
  102. package/dist/heart/daemon/up-progress.js +366 -0
  103. package/dist/heart/daemon/vault-items.js +56 -0
  104. package/dist/heart/delegation.js +1 -1
  105. package/dist/heart/habits/habit-migration.js +189 -0
  106. package/dist/heart/habits/habit-parser.js +140 -0
  107. package/dist/heart/habits/habit-runtime-state.js +100 -0
  108. package/dist/heart/habits/habit-scheduler.js +372 -0
  109. package/dist/heart/{daemon → hatch}/hatch-flow.js +52 -117
  110. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  111. package/dist/heart/{daemon → hatch}/specialist-prompt.js +12 -9
  112. package/dist/heart/{daemon → hatch}/specialist-tools.js +35 -12
  113. package/dist/heart/identity.js +205 -66
  114. package/dist/heart/kept-notes.js +357 -0
  115. package/dist/heart/kicks.js +1 -1
  116. package/dist/heart/machine-identity.js +161 -0
  117. package/dist/heart/mail-import-discovery.js +353 -0
  118. package/dist/heart/mailbox/mailbox-http-hooks.js +66 -0
  119. package/dist/heart/mailbox/mailbox-http-response.js +7 -0
  120. package/dist/heart/mailbox/mailbox-http-routes.js +246 -0
  121. package/dist/heart/mailbox/mailbox-http-static.js +103 -0
  122. package/dist/heart/mailbox/mailbox-http-transport.js +116 -0
  123. package/dist/heart/mailbox/mailbox-http.js +99 -0
  124. package/dist/heart/mailbox/mailbox-read.js +31 -0
  125. package/dist/heart/mailbox/mailbox-types.js +27 -0
  126. package/dist/heart/mailbox/mailbox-view.js +195 -0
  127. package/dist/heart/mailbox/readers/agent-machine.js +382 -0
  128. package/dist/heart/mailbox/readers/continuity-readers.js +338 -0
  129. package/dist/heart/mailbox/readers/mail.js +362 -0
  130. package/dist/heart/mailbox/readers/runtime-readers.js +651 -0
  131. package/dist/heart/mailbox/readers/sessions.js +232 -0
  132. package/dist/heart/mailbox/readers/shared.js +111 -0
  133. package/dist/heart/mcp/mcp-server.js +653 -0
  134. package/dist/heart/migrate-config.js +100 -0
  135. package/dist/heart/model-capabilities.js +19 -0
  136. package/dist/heart/platform.js +81 -0
  137. package/dist/heart/provider-attempt.js +134 -0
  138. package/dist/heart/provider-binding-resolver.js +255 -0
  139. package/dist/heart/provider-credentials.js +425 -0
  140. package/dist/heart/provider-failover.js +301 -0
  141. package/dist/heart/provider-models.js +81 -0
  142. package/dist/heart/provider-ping.js +262 -0
  143. package/dist/heart/provider-state.js +216 -0
  144. package/dist/heart/provider-visibility.js +188 -0
  145. package/dist/heart/providers/anthropic-token.js +131 -0
  146. package/dist/heart/providers/anthropic.js +139 -52
  147. package/dist/heart/providers/azure.js +97 -13
  148. package/dist/heart/providers/error-classification.js +127 -0
  149. package/dist/heart/providers/github-copilot.js +145 -0
  150. package/dist/heart/providers/minimax-vlm.js +189 -0
  151. package/dist/heart/providers/minimax.js +26 -8
  152. package/dist/heart/providers/openai-codex.js +55 -40
  153. package/dist/heart/runtime-capability-check.js +170 -0
  154. package/dist/heart/runtime-credentials.js +367 -0
  155. package/dist/heart/sense-truth.js +11 -4
  156. package/dist/heart/session-activity.js +43 -22
  157. package/dist/heart/session-events.js +1149 -0
  158. package/dist/heart/session-playback-cli-main.js +5 -0
  159. package/dist/heart/session-playback-cli.js +36 -0
  160. package/dist/heart/session-playback.js +231 -0
  161. package/dist/heart/session-stats-cli-main.js +5 -0
  162. package/dist/heart/session-stats.js +182 -0
  163. package/dist/heart/session-transcript.js +243 -0
  164. package/dist/heart/start-of-turn-packet.js +345 -0
  165. package/dist/heart/streaming.js +44 -27
  166. package/dist/heart/sync-classification.js +176 -0
  167. package/dist/heart/sync.js +449 -0
  168. package/dist/heart/target-resolution.js +9 -5
  169. package/dist/heart/tempo.js +93 -0
  170. package/dist/heart/temporal-view.js +41 -0
  171. package/dist/heart/timeouts.js +101 -0
  172. package/dist/heart/tool-activity-callbacks.js +59 -0
  173. package/dist/heart/tool-description.js +139 -0
  174. package/dist/heart/tool-friction.js +55 -0
  175. package/dist/heart/tool-loop.js +200 -0
  176. package/dist/heart/turn-context.js +381 -0
  177. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +1 -1
  178. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  179. package/dist/heart/versioning/ouro-path-installer.js +425 -0
  180. package/dist/heart/versioning/ouro-version-manager.js +295 -0
  181. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  182. package/dist/heart/{daemon → versioning}/update-checker.js +5 -1
  183. package/dist/heart/{daemon → versioning}/update-hooks.js +63 -59
  184. package/dist/mailbox-ui/assets/index-BPr5vNuM.css +1 -0
  185. package/dist/mailbox-ui/assets/index-Cm51CY9W.js +61 -0
  186. package/dist/mailbox-ui/index.html +15 -0
  187. package/dist/mailroom/attention.js +167 -0
  188. package/dist/mailroom/autonomy.js +209 -0
  189. package/dist/mailroom/blob-store.js +606 -0
  190. package/dist/mailroom/body-cache.js +61 -0
  191. package/dist/mailroom/core.js +672 -0
  192. package/dist/mailroom/entry.js +160 -0
  193. package/dist/mailroom/file-store.js +426 -0
  194. package/dist/mailroom/mbox-import.js +382 -0
  195. package/dist/mailroom/outbound.js +380 -0
  196. package/dist/mailroom/policy.js +263 -0
  197. package/dist/mailroom/reader.js +228 -0
  198. package/dist/mailroom/search-cache.js +182 -0
  199. package/dist/mailroom/search-relevance.js +319 -0
  200. package/dist/mailroom/smtp-ingress.js +176 -0
  201. package/dist/mailroom/source-state.js +176 -0
  202. package/dist/mailroom/thread.js +109 -0
  203. package/dist/mailroom/travel-extract.js +89 -0
  204. package/dist/mind/bundle-manifest.js +7 -1
  205. package/dist/mind/context.js +165 -101
  206. package/dist/mind/diary-integrity.js +60 -0
  207. package/dist/mind/{memory.js → diary.js} +74 -93
  208. package/dist/mind/embedding-provider.js +60 -0
  209. package/dist/mind/file-state.js +179 -0
  210. package/dist/mind/friends/channel.js +30 -0
  211. package/dist/mind/friends/resolver.js +54 -2
  212. package/dist/mind/friends/store-file.js +39 -3
  213. package/dist/mind/friends/types.js +2 -2
  214. package/dist/mind/journal-index.js +161 -0
  215. package/dist/mind/note-search.js +268 -0
  216. package/dist/mind/obligation-steering.js +221 -0
  217. package/dist/mind/pending.js +4 -0
  218. package/dist/mind/prompt-refresh.js +3 -2
  219. package/dist/mind/prompt.js +942 -122
  220. package/dist/mind/provenance-trust.js +26 -0
  221. package/dist/mind/scrutiny.js +173 -0
  222. package/dist/nerves/cli-logging.js +7 -1
  223. package/dist/nerves/coverage/audit-rules.js +15 -6
  224. package/dist/nerves/coverage/audit.js +28 -2
  225. package/dist/nerves/coverage/cli.js +1 -1
  226. package/dist/nerves/coverage/contract.js +5 -5
  227. package/dist/nerves/coverage/file-completeness.js +139 -5
  228. package/dist/nerves/coverage/run-artifacts.js +1 -1
  229. package/dist/nerves/event-buffer.js +111 -0
  230. package/dist/nerves/index.js +224 -4
  231. package/dist/nerves/observation.js +20 -0
  232. package/dist/nerves/redact.js +79 -0
  233. package/dist/nerves/review/cli-main.js +5 -0
  234. package/dist/nerves/review/cli.js +156 -0
  235. package/dist/nerves/review/core.js +152 -0
  236. package/dist/nerves/runtime.js +5 -1
  237. package/dist/repertoire/ado-client.js +15 -56
  238. package/dist/repertoire/ado-semantic.js +11 -10
  239. package/dist/repertoire/api-client.js +97 -0
  240. package/dist/repertoire/bitwarden-store.js +816 -0
  241. package/dist/repertoire/bundle-templates.js +72 -0
  242. package/dist/repertoire/bw-installer.js +180 -0
  243. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  244. package/dist/repertoire/coding/context-pack.js +330 -0
  245. package/dist/repertoire/coding/feedback.js +197 -30
  246. package/dist/repertoire/coding/manager.js +158 -9
  247. package/dist/repertoire/coding/spawner.js +55 -9
  248. package/dist/repertoire/coding/tools.js +170 -7
  249. package/dist/repertoire/commerce-errors.js +109 -0
  250. package/dist/repertoire/commerce-self-test.js +156 -0
  251. package/dist/repertoire/credential-access.js +111 -0
  252. package/dist/repertoire/duffel-client.js +185 -0
  253. package/dist/repertoire/github-client.js +14 -55
  254. package/dist/repertoire/graph-client.js +11 -52
  255. package/dist/repertoire/guardrails.js +396 -0
  256. package/dist/repertoire/mcp-client.js +255 -0
  257. package/dist/repertoire/mcp-manager.js +305 -0
  258. package/dist/repertoire/mcp-tools.js +63 -0
  259. package/dist/repertoire/shell-sessions.js +133 -0
  260. package/dist/repertoire/skills.js +15 -24
  261. package/dist/repertoire/stripe-client.js +131 -0
  262. package/dist/repertoire/tasks/board.js +31 -5
  263. package/dist/repertoire/tasks/fix.js +182 -0
  264. package/dist/repertoire/tasks/index.js +16 -4
  265. package/dist/repertoire/tasks/lifecycle.js +2 -2
  266. package/dist/repertoire/tasks/parser.js +3 -2
  267. package/dist/repertoire/tasks/scanner.js +194 -37
  268. package/dist/repertoire/tasks/transitions.js +16 -78
  269. package/dist/repertoire/tool-results.js +29 -0
  270. package/dist/repertoire/tools-attachments.js +317 -0
  271. package/dist/repertoire/tools-base.js +47 -1075
  272. package/dist/repertoire/tools-bluebubbles.js +1 -0
  273. package/dist/repertoire/tools-bridge.js +142 -0
  274. package/dist/repertoire/tools-bundle.js +984 -0
  275. package/dist/repertoire/tools-config.js +185 -0
  276. package/dist/repertoire/tools-continuity.js +248 -0
  277. package/dist/repertoire/tools-credential.js +381 -0
  278. package/dist/repertoire/tools-files.js +342 -0
  279. package/dist/repertoire/tools-flight.js +224 -0
  280. package/dist/repertoire/tools-flow.js +119 -0
  281. package/dist/repertoire/tools-github.js +1 -7
  282. package/dist/repertoire/tools-mail.js +1477 -0
  283. package/dist/repertoire/tools-notes.js +421 -0
  284. package/dist/repertoire/tools-session.js +750 -0
  285. package/dist/repertoire/tools-shell.js +120 -0
  286. package/dist/repertoire/tools-stripe.js +180 -0
  287. package/dist/repertoire/tools-surface.js +243 -0
  288. package/dist/repertoire/tools-teams.js +9 -39
  289. package/dist/repertoire/tools-travel.js +125 -0
  290. package/dist/repertoire/tools-trip.js +422 -0
  291. package/dist/repertoire/tools-user-profile.js +144 -0
  292. package/dist/repertoire/tools-vault.js +40 -0
  293. package/dist/repertoire/tools.js +108 -100
  294. package/dist/repertoire/travel-api-client.js +360 -0
  295. package/dist/repertoire/user-profile.js +131 -0
  296. package/dist/repertoire/vault-setup.js +246 -0
  297. package/dist/repertoire/vault-unlock.js +561 -0
  298. package/dist/scripts/claude-code-hook.js +41 -0
  299. package/dist/scripts/claude-code-stop-hook.js +47 -0
  300. package/dist/senses/attention-queue.js +116 -0
  301. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  302. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  303. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +219 -18
  304. package/dist/senses/bluebubbles/entry.js +77 -0
  305. package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +20 -3
  306. package/dist/senses/bluebubbles/index.js +2236 -0
  307. package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +121 -70
  308. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +33 -12
  309. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +3 -3
  310. package/dist/senses/bluebubbles/processed-log.js +111 -0
  311. package/dist/senses/bluebubbles/replay.js +129 -0
  312. package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +16 -2
  313. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
  314. package/dist/senses/cli/bracketed-paste.js +82 -0
  315. package/dist/senses/cli/image-paste.js +287 -0
  316. package/dist/senses/cli/image-ref-navigation.js +75 -0
  317. package/dist/senses/cli/ink-app.js +156 -0
  318. package/dist/senses/cli/inline-diff.js +64 -0
  319. package/dist/senses/cli/input-keys.js +174 -0
  320. package/dist/senses/cli/kill-ring.js +86 -0
  321. package/dist/senses/cli/message-list.js +51 -0
  322. package/dist/senses/cli/ouro-tui.js +607 -0
  323. package/dist/senses/cli/spinner-imperative.js +135 -0
  324. package/dist/senses/cli/spinner.js +101 -0
  325. package/dist/senses/cli/status-line.js +60 -0
  326. package/dist/senses/cli/streaming-markdown.js +526 -0
  327. package/dist/senses/cli/tool-display.js +85 -0
  328. package/dist/senses/cli/tool-render.js +85 -0
  329. package/dist/senses/cli/tui-store.js +240 -0
  330. package/dist/senses/cli/virtual-list.js +35 -0
  331. package/dist/senses/cli-entry.js +60 -8
  332. package/dist/senses/cli-layout.js +187 -0
  333. package/dist/senses/cli.js +520 -209
  334. package/dist/senses/commands.js +66 -3
  335. package/dist/senses/habit-turn-message.js +108 -0
  336. package/dist/senses/inner-dialog-worker.js +175 -21
  337. package/dist/senses/inner-dialog.js +330 -27
  338. package/dist/senses/mail-entry.js +66 -0
  339. package/dist/senses/mail.js +379 -0
  340. package/dist/senses/pipeline.js +569 -182
  341. package/dist/senses/proactive-content-guard.js +51 -0
  342. package/dist/senses/shared-turn.js +248 -0
  343. package/dist/senses/surface-tool.js +68 -0
  344. package/dist/senses/teams-entry.js +60 -8
  345. package/dist/senses/teams.js +387 -98
  346. package/dist/senses/trust-gate.js +100 -5
  347. package/dist/trips/core.js +138 -0
  348. package/dist/trips/store.js +146 -0
  349. package/package.json +38 -7
  350. package/skills/agent-commerce.md +106 -0
  351. package/skills/browser-navigation.md +117 -0
  352. package/skills/commerce-setup-guide.md +116 -0
  353. package/skills/commerce-setup.md +84 -0
  354. package/skills/configure-dev-tools.md +101 -0
  355. package/skills/travel-planning.md +138 -0
  356. package/dist/heart/daemon/ouro-path-installer.js +0 -178
  357. package/dist/heart/daemon/subagent-installer.js +0 -166
  358. package/dist/heart/session-recall.js +0 -116
  359. package/dist/mind/associative-recall.js +0 -209
  360. package/dist/senses/bluebubbles-entry.js +0 -13
  361. package/dist/senses/bluebubbles.js +0 -1177
  362. package/dist/senses/debug-activity.js +0 -148
  363. package/subagents/README.md +0 -86
  364. package/subagents/work-doer.md +0 -237
  365. package/subagents/work-merger.md +0 -618
  366. package/subagents/work-planner.md +0 -390
  367. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  368. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  369. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  370. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  371. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  372. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  373. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  374. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  375. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  376. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  377. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  378. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  379. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  380. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  381. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  382. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
@@ -1,94 +1,162 @@
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.isChatStyleChannel = isChatStyleChannel;
10
+ exports.isExternalStateQuery = isExternalStateQuery;
11
+ exports.getSettleRetryError = getSettleRetryError;
10
12
  exports.stripLastToolCalls = stripLastToolCalls;
11
13
  exports.repairOrphanedToolCalls = repairOrphanedToolCalls;
12
- exports.isTransientError = isTransientError;
13
- exports.classifyTransientError = classifyTransientError;
14
14
  exports.runAgent = runAgent;
15
15
  const config_1 = require("./config");
16
16
  const identity_1 = require("./identity");
17
17
  const tools_1 = require("../repertoire/tools");
18
18
  const channel_1 = require("../mind/friends/channel");
19
+ const tools_2 = require("../repertoire/tools");
19
20
  const runtime_1 = require("../nerves/runtime");
20
21
  const context_1 = require("../mind/context");
21
22
  const prompt_1 = require("../mind/prompt");
22
- const associative_recall_1 = require("../mind/associative-recall");
23
+ const kept_notes_1 = require("./kept-notes");
24
+ const error_classification_1 = require("./providers/error-classification");
23
25
  const anthropic_1 = require("./providers/anthropic");
24
26
  const azure_1 = require("./providers/azure");
25
27
  const minimax_1 = require("./providers/minimax");
26
28
  const openai_codex_1 = require("./providers/openai-codex");
27
- let _providerRuntime = null;
28
- function createProviderRegistry() {
29
- const factories = {
30
- azure: azure_1.createAzureProviderRuntime,
31
- anthropic: anthropic_1.createAnthropicProviderRuntime,
32
- minimax: minimax_1.createMinimaxProviderRuntime,
33
- "openai-codex": openai_codex_1.createOpenAICodexProviderRuntime,
29
+ const github_copilot_1 = require("./providers/github-copilot");
30
+ const identity_2 = require("./identity");
31
+ const socket_client_1 = require("./daemon/socket-client");
32
+ const obligations_1 = require("../arc/obligations");
33
+ const tool_loop_1 = require("./tool-loop");
34
+ const packets_1 = require("../arc/packets");
35
+ const tool_friction_1 = require("./tool-friction");
36
+ const provider_models_1 = require("./provider-models");
37
+ const provider_credentials_1 = require("./provider-credentials");
38
+ const provider_state_1 = require("./provider-state");
39
+ const provider_attempt_1 = require("./provider-attempt");
40
+ const _providerRuntimes = {
41
+ human: null,
42
+ agent: null,
43
+ };
44
+ function providerLaneForFacing(facing) {
45
+ return facing === "human" ? "outward" : "inner";
46
+ }
47
+ function resolveRuntimeProviderBinding(facing) {
48
+ const agentName = (0, identity_2.getAgentName)();
49
+ const lane = providerLaneForFacing(facing);
50
+ const stateResult = (0, provider_state_1.readProviderState)((0, identity_2.getAgentRoot)(agentName));
51
+ if (stateResult.ok) {
52
+ const binding = stateResult.state.lanes[lane];
53
+ return { lane, provider: binding.provider, model: binding.model };
54
+ }
55
+ if (stateResult.reason === "invalid") {
56
+ throw new Error(`provider state for ${agentName} is invalid at ${stateResult.statePath}: ${stateResult.error}`);
57
+ }
58
+ // First-run and SerpentGuide bootstrap path. Daemon startup normally
59
+ // bootstraps state/providers.json from agent.json before model calls.
60
+ const config = (0, identity_1.loadAgentConfig)();
61
+ const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
62
+ return { lane, provider: facingConfig.provider, model: facingConfig.model };
63
+ }
64
+ async function getProviderRuntimeFingerprint(facing) {
65
+ const agentName = (0, identity_2.getAgentName)();
66
+ const binding = resolveRuntimeProviderBinding(facing);
67
+ const credential = await (0, provider_credentials_1.readProviderCredentialRecord)(agentName, binding.provider);
68
+ if (!credential.ok) {
69
+ throw new Error([
70
+ `${binding.lane} provider ${binding.provider} (${binding.model}) has no credentials for ${agentName}.`,
71
+ credential.error,
72
+ `Run \`ouro auth --agent ${agentName} --provider ${binding.provider}\`.`,
73
+ ].join("\n"));
74
+ }
75
+ return {
76
+ binding,
77
+ fingerprint: JSON.stringify({
78
+ lane: binding.lane,
79
+ provider: binding.provider,
80
+ model: binding.model,
81
+ credentialRevision: credential.record.revision,
82
+ }),
83
+ credential: credential.record,
34
84
  };
85
+ }
86
+ function createProviderRegistry() {
35
87
  return {
36
- resolve() {
37
- const provider = (0, identity_1.loadAgentConfig)().provider;
38
- return factories[provider]();
88
+ resolve(provider, model, credential) {
89
+ const providerConfig = { ...credential.config, ...credential.credentials };
90
+ switch (provider) {
91
+ case "azure":
92
+ return (0, azure_1.createAzureProviderRuntime)(model, providerConfig);
93
+ case "anthropic":
94
+ return (0, anthropic_1.createAnthropicProviderRuntime)(model, providerConfig);
95
+ case "minimax":
96
+ return (0, minimax_1.createMinimaxProviderRuntime)(model, providerConfig);
97
+ case "openai-codex":
98
+ return (0, openai_codex_1.createOpenAICodexProviderRuntime)(model, providerConfig);
99
+ case "github-copilot":
100
+ return (0, github_copilot_1.createGithubCopilotProviderRuntime)(model, providerConfig);
101
+ }
39
102
  },
40
103
  };
41
104
  }
42
- function getProviderRuntime() {
43
- if (!_providerRuntime) {
44
- try {
45
- _providerRuntime = createProviderRegistry().resolve();
46
- }
47
- catch (error) {
48
- const msg = error instanceof Error ? error.message : String(error);
49
- (0, runtime_1.emitNervesEvent)({
50
- level: "error",
51
- event: "engine.provider_init_error",
52
- component: "engine",
53
- message: msg,
54
- meta: {},
55
- });
56
- // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
57
- console.error(`\n[fatal] ${msg}\n`);
58
- process.exit(1);
59
- throw new Error("unreachable");
60
- }
61
- if (!_providerRuntime) {
62
- (0, runtime_1.emitNervesEvent)({
63
- level: "error",
64
- event: "engine.provider_init_error",
65
- component: "engine",
66
- message: "provider runtime could not be initialized.",
67
- meta: {},
68
- });
69
- process.exit(1);
70
- throw new Error("unreachable");
105
+ async function getProviderRuntime(facing = "human") {
106
+ try {
107
+ const { binding, fingerprint, credential } = await getProviderRuntimeFingerprint(facing);
108
+ const cached = _providerRuntimes[facing];
109
+ if (!cached || cached.fingerprint !== fingerprint) {
110
+ const runtime = createProviderRegistry().resolve(binding.provider, binding.model, credential);
111
+ _providerRuntimes[facing] = runtime ? { fingerprint, runtime } : null;
71
112
  }
72
113
  }
73
- return _providerRuntime;
114
+ catch (error) {
115
+ const msg = error instanceof Error ? error.message : String(error);
116
+ (0, runtime_1.emitNervesEvent)({
117
+ level: "error",
118
+ event: "engine.provider_init_error",
119
+ component: "engine",
120
+ message: msg,
121
+ meta: { facing },
122
+ });
123
+ // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
124
+ console.error(`\n[fatal] ${msg}\n`);
125
+ throw error instanceof Error ? error : new Error(msg);
126
+ }
127
+ if (!_providerRuntimes[facing]) {
128
+ const msg = "provider runtime could not be initialized.";
129
+ (0, runtime_1.emitNervesEvent)({
130
+ level: "error",
131
+ event: "engine.provider_init_error",
132
+ component: "engine",
133
+ message: msg,
134
+ meta: { facing },
135
+ });
136
+ // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
137
+ console.error(`\n[fatal] ${msg}\n`);
138
+ throw new Error(msg);
139
+ }
140
+ return _providerRuntimes[facing].runtime;
74
141
  }
75
142
  /**
76
- * Clear the cached provider runtime so the next call to getProviderRuntime()
77
- * re-creates it from current config. Used by the adoption specialist to
78
- * switch provider context without restarting the process.
143
+ * Clear the cached provider runtime so the next access re-creates it from
144
+ * current config. Runtime access also auto-refreshes when the selected
145
+ * provider fingerprint changes on disk.
79
146
  */
80
147
  function resetProviderRuntime() {
81
- _providerRuntime = null;
148
+ _providerRuntimes.human = null;
149
+ _providerRuntimes.agent = null;
82
150
  }
83
- function getModel() {
84
- return getProviderRuntime().model;
151
+ function getModel(facing = "human") {
152
+ return resolveRuntimeProviderBinding(facing).model;
85
153
  }
86
- function getProvider() {
87
- return getProviderRuntime().id;
154
+ function getProvider(facing = "human") {
155
+ return resolveRuntimeProviderBinding(facing).provider;
88
156
  }
89
- function createSummarize() {
157
+ function createSummarize(facing = "human") {
90
158
  return async (transcript, instruction) => {
91
- const runtime = getProviderRuntime();
159
+ const runtime = await getProviderRuntime(facing);
92
160
  const client = runtime.client;
93
161
  const response = await client.chat.completions.create({
94
162
  model: runtime.model,
@@ -101,32 +169,66 @@ function createSummarize() {
101
169
  return response.choices?.[0]?.message?.content ?? transcript;
102
170
  };
103
171
  }
104
- function getProviderDisplayLabel() {
105
- const model = getModel();
172
+ function getProviderDisplayLabel(facing = "human") {
173
+ const binding = resolveRuntimeProviderBinding(facing);
174
+ const provider = binding.provider;
175
+ const model = binding.model || "unknown";
106
176
  const providerLabelBuilders = {
107
- azure: () => `azure openai (${(0, config_1.getAzureConfig)().deployment || "default"}, model: ${model})`,
177
+ azure: () => {
178
+ return `azure openai (model: ${model})`;
179
+ },
108
180
  anthropic: () => `anthropic (${model})`,
109
181
  minimax: () => `minimax (${model})`,
110
182
  "openai-codex": () => `openai codex (${model})`,
183
+ /* v8 ignore next -- branch: tested via display label unit test @preserve */
184
+ "github-copilot": () => `github copilot (${model})`,
111
185
  };
112
- return providerLabelBuilders[getProvider()]();
186
+ return providerLabelBuilders[provider]();
187
+ }
188
+ /**
189
+ * Strip <think>...</think> blocks for the violation-detection check at the
190
+ * end of a streaming turn. Used to tell legitimate text-only responses
191
+ * apart from the MiniMax-M2.7 "only thinking, no tool call" violation
192
+ * shape. Mirrors the more thorough stripThinkBlocks helper in
193
+ * senses/shared-turn.ts (which is for operator-facing output) — kept
194
+ * inline here to avoid pulling senses/ into the core module's import graph.
195
+ */
196
+ function stripThinkBlocksForViolationCheck(input) {
197
+ let out = input;
198
+ for (;;) {
199
+ const open = out.indexOf("<think>");
200
+ if (open === -1)
201
+ break;
202
+ const close = out.indexOf("</think>", open + "<think>".length);
203
+ if (close === -1) {
204
+ out = out.slice(0, open);
205
+ break;
206
+ }
207
+ out = out.slice(0, open) + out.slice(close + "</think>".length);
208
+ }
209
+ return out.trim();
210
+ }
211
+ function hasFreshPendingWork(options) {
212
+ const pendingMessages = options?.pendingMessages;
213
+ if (!Array.isArray(pendingMessages))
214
+ return false;
215
+ return pendingMessages.some((message) => typeof message?.content === "string"
216
+ && message.content.trim().length > 0);
113
217
  }
114
- // Re-export tools, execTool, summarizeArgs from ./tools for backward compat
115
- var tools_2 = require("../repertoire/tools");
116
- Object.defineProperty(exports, "tools", { enumerable: true, get: function () { return tools_2.tools; } });
117
- Object.defineProperty(exports, "execTool", { enumerable: true, get: function () { return tools_2.execTool; } });
118
- Object.defineProperty(exports, "summarizeArgs", { enumerable: true, get: function () { return tools_2.summarizeArgs; } });
119
- Object.defineProperty(exports, "getToolsForChannel", { enumerable: true, get: function () { return tools_2.getToolsForChannel; } });
120
- // Re-export streaming functions for backward compat
121
- var streaming_1 = require("./streaming");
122
- Object.defineProperty(exports, "streamChatCompletion", { enumerable: true, get: function () { return streaming_1.streamChatCompletion; } });
123
- Object.defineProperty(exports, "streamResponsesApi", { enumerable: true, get: function () { return streaming_1.streamResponsesApi; } });
124
- Object.defineProperty(exports, "toResponsesInput", { enumerable: true, get: function () { return streaming_1.toResponsesInput; } });
125
- Object.defineProperty(exports, "toResponsesTools", { enumerable: true, get: function () { return streaming_1.toResponsesTools; } });
126
- // Re-export prompt functions for backward compat
127
- var prompt_2 = require("../mind/prompt");
128
- Object.defineProperty(exports, "buildSystem", { enumerable: true, get: function () { return prompt_2.buildSystem; } });
129
- function parseFinalAnswerPayload(argumentsText) {
218
+ /** Chat-style channels expose the `speak` tool outer human-conversation channels
219
+ * where mid-turn delivery is meaningful. Inner dialog has `ponder`. MCP returns
220
+ * synchronously. Mail is batch. Anything else (unknown channel) treats as non-chat. */
221
+ function isChatStyleChannel(channel) {
222
+ return channel === "cli" || channel === "teams" || channel === "bluebubbles";
223
+ }
224
+ // Sole-call tools must be the only tool call in a turn. When they appear
225
+ // alongside other tools, the sole-call tool is rejected with this message.
226
+ const SOLE_CALL_REJECTION = {
227
+ settle: "rejected: settle must be the only tool call. finish your work first, then call settle alone.",
228
+ observe: "rejected: observe must be the only tool call. call observe alone when you want to stay silent.",
229
+ rest: "rejected: rest must be the only tool call. finish your work first, then call rest alone.",
230
+ };
231
+ function parseSettlePayload(argumentsText) {
130
232
  try {
131
233
  const parsed = JSON.parse(argumentsText);
132
234
  if (typeof parsed === "string") {
@@ -146,18 +248,93 @@ function parseFinalAnswerPayload(argumentsText) {
146
248
  return {};
147
249
  }
148
250
  }
149
- function getFinalAnswerRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp) {
251
+ function parsePonderPayload(argumentsText) {
252
+ try {
253
+ const parsed = JSON.parse(argumentsText);
254
+ return parsed && typeof parsed === "object" ? parsed : {};
255
+ }
256
+ catch {
257
+ return {};
258
+ }
259
+ }
260
+ function parseSuccessCriteria(raw) {
261
+ if (typeof raw !== "string")
262
+ return null;
263
+ const criteria = raw
264
+ .split("\n")
265
+ .map((line) => line.replace(/^\s*[-*]\s*/, "").trim())
266
+ .filter((line) => line.length > 0);
267
+ return criteria.length > 0 ? criteria : null;
268
+ }
269
+ function parsePacketPayload(raw) {
270
+ if (typeof raw !== "string")
271
+ return null;
272
+ try {
273
+ const parsed = JSON.parse(raw);
274
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
275
+ ? parsed
276
+ : null;
277
+ }
278
+ catch {
279
+ return null;
280
+ }
281
+ }
282
+ function normalizeLegacyPonderArgs(parsed) {
283
+ if (typeof parsed.thought !== "string" || parsed.thought.trim().length === 0) {
284
+ return parsed;
285
+ }
286
+ return {
287
+ action: "create",
288
+ kind: "reflection",
289
+ objective: parsed.thought.trim(),
290
+ summary: typeof parsed.say === "string" ? parsed.say.trim() : "",
291
+ success_criteria: "- preserve the thread for later work",
292
+ payload_json: "{}",
293
+ };
294
+ }
295
+ function buildPonderResult(packet, action, returnObligationId) {
296
+ return JSON.stringify({
297
+ ok: true,
298
+ packet_id: packet.id,
299
+ action,
300
+ status: packet.status,
301
+ return_obligation_id: returnObligationId,
302
+ }, null, 2);
303
+ }
304
+ /** Returns true when a tool call queries external state (GitHub, npm registry). */
305
+ function isExternalStateQuery(toolName, args) {
306
+ if (toolName !== "shell")
307
+ return false;
308
+ const cmd = String(args.command ?? "");
309
+ return /\bgh\s+(pr|run|api|issue)\b/.test(cmd) || /\bnpm\s+(view|info|show)\b/.test(cmd);
310
+ }
311
+ function getSettleRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp, _delegationDecision, sawSendMessageSelf, sawPonder, _sawQuerySession, currentObligation, innerJob, sawExternalStateQuery) {
312
+ // Delegation adherence removed: the delegation decision is surfaced in the
313
+ // system prompt as a suggestion. Hard-gating settle caused infinite
314
+ // rejection loops where the agent couldn't respond to the user at all.
315
+ // The agent is free to follow or ignore the delegation hint.
316
+ // 2. Pending obligation not addressed
317
+ if (innerJob?.obligationStatus === "pending" && !sawSendMessageSelf && !sawPonder) {
318
+ 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.";
319
+ }
320
+ // 3. mustResolveBeforeHandoff + missing intent
150
321
  if (mustResolveBeforeHandoff && !intent) {
151
- 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.";
322
+ 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.";
152
323
  }
324
+ // 4. mustResolveBeforeHandoff + direct_reply without follow-up
153
325
  if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
154
- 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.";
326
+ 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.";
155
327
  }
156
- return "your final_answer was incomplete or malformed. call final_answer again with your complete response.";
328
+ // 5. mustResolveBeforeHandoff + complete while a live return loop is still active
329
+ if (mustResolveBeforeHandoff && intent === "complete" && currentObligation && !sawSteeringFollowUp) {
330
+ 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.";
331
+ }
332
+ // 6. External-state grounding: obligation + complete requires fresh external verification
333
+ if (intent === "complete" && currentObligation && !sawExternalStateQuery && !sawSteeringFollowUp) {
334
+ return "you're claiming this work is complete, but the external state hasn't been verified this turn. ground your claim with a fresh check (gh pr view, npm view, gh run view, etc.) before calling settle.";
335
+ }
336
+ return null;
157
337
  }
158
- // Re-export kick utilities for backward compat
159
- var kicks_1 = require("./kicks");
160
- Object.defineProperty(exports, "hasToolIntent", { enumerable: true, get: function () { return kicks_1.hasToolIntent; } });
161
338
  function upsertSystemPrompt(messages, systemText) {
162
339
  const systemMessage = { role: "system", content: systemText };
163
340
  if (messages[0]?.role === "system") {
@@ -195,27 +372,39 @@ const TOOL_SCAN_BOUNDARY_ROLES = new Set(["assistant", "user"]);
195
372
  // 1. If an assistant message has tool_calls but missing tool results, inject synthetic error results.
196
373
  // 2. If a tool result's tool_call_id doesn't match any tool_calls in a preceding assistant message, remove it.
197
374
  // This prevents 400 errors from the API after an aborted turn.
375
+ //
376
+ // Position-aware: a tool result is orphaned when its tool_call_id hasn't been
377
+ // defined by an assistant message AT THIS POSITION yet. MiniMax-M2.7 reuses
378
+ // canonical tool_call_ids across turns, so the global-set check that this
379
+ // function used previously kept misordered tool results that MiniMax then
380
+ // rejected with error 2013 ("tool result's tool id not found"). Walking
381
+ // in order matches what MiniMax actually enforces.
198
382
  function repairOrphanedToolCalls(messages) {
199
- // Pass 1: collect all valid tool_call IDs from assistant messages
200
- const validCallIds = new Set();
201
- for (const msg of messages) {
383
+ // Pass 1: walk in order, accumulate seen tool_call_ids per-position, and
384
+ // mark tool results for removal if their id hasn't been defined yet.
385
+ const seenCallIds = new Set();
386
+ const removeIndices = [];
387
+ for (let i = 0; i < messages.length; i++) {
388
+ const msg = messages[i];
202
389
  if (msg.role === "assistant") {
203
390
  const asst = msg;
204
391
  if (asst.tool_calls) {
205
392
  for (const tc of asst.tool_calls)
206
- validCallIds.add(tc.id);
393
+ seenCallIds.add(tc.id);
207
394
  }
395
+ continue;
208
396
  }
209
- }
210
- // Pass 2: remove orphaned tool results (tool_call_id not in any assistant's tool_calls)
211
- for (let i = messages.length - 1; i >= 0; i--) {
212
- if (messages[i].role === "tool") {
213
- const toolMsg = messages[i];
214
- if (!validCallIds.has(toolMsg.tool_call_id)) {
215
- messages.splice(i, 1);
397
+ if (msg.role === "tool") {
398
+ const toolMsg = msg;
399
+ if (!seenCallIds.has(toolMsg.tool_call_id)) {
400
+ removeIndices.push(i);
216
401
  }
217
402
  }
218
403
  }
404
+ // Splice from the end so earlier indices stay valid.
405
+ for (let i = removeIndices.length - 1; i >= 0; i--) {
406
+ messages.splice(removeIndices[i], 1);
407
+ }
219
408
  // Pass 3: inject synthetic results for tool_calls missing their tool results
220
409
  for (let i = 0; i < messages.length; i++) {
221
410
  const msg = messages[i];
@@ -237,10 +426,13 @@ function repairOrphanedToolCalls(messages) {
237
426
  }
238
427
  const missing = asst.tool_calls.filter((tc) => !resultIds.has(tc.id));
239
428
  if (missing.length > 0) {
429
+ // AX rule: the agent must see what happened. Don't say "interrupted"
430
+ // — that's vague. Tell them the result was lost, possible causes,
431
+ // and what to do next.
240
432
  const syntheticResults = missing.map((tc) => ({
241
433
  role: "tool",
242
434
  tool_call_id: tc.id,
243
- content: "error: tool call was interrupted (previous turn timed out or was aborted)",
435
+ 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.",
244
436
  }));
245
437
  let insertAt = i + 1;
246
438
  while (insertAt < messages.length && messages[insertAt].role === "tool")
@@ -263,49 +455,67 @@ function isContextOverflow(err) {
263
455
  return true;
264
456
  return false;
265
457
  }
266
- // Detect transient network errors worth retrying
267
- function isTransientError(err) {
268
- if (!(err instanceof Error))
269
- return false;
270
- const msg = err.message || "";
271
- const code = err.code || "";
272
- // Node.js network error codes
273
- if (["ECONNRESET", "ECONNREFUSED", "ENOTFOUND", "ETIMEDOUT", "EPIPE",
274
- "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "ECONNABORTED"].includes(code))
275
- return true;
276
- // OpenAI SDK / fetch errors
277
- if (msg.includes("fetch failed"))
278
- return true;
279
- if (msg.includes("network") && !msg.includes("context"))
280
- return true;
281
- if (msg.includes("ECONNRESET") || msg.includes("ETIMEDOUT"))
282
- return true;
283
- if (msg.includes("socket hang up"))
284
- return true;
285
- if (msg.includes("getaddrinfo"))
286
- return true;
287
- // HTTP 429 / 500 / 502 / 503 / 504
288
- const status = err.status;
289
- if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504)
290
- return true;
291
- return false;
458
+ const RETRY_LABELS = {
459
+ "auth-failure": "auth error",
460
+ "usage-limit": "usage limit",
461
+ "rate-limit": "rate limited",
462
+ "server-error": "server error",
463
+ "network-error": "network error",
464
+ "unknown": "error",
465
+ };
466
+ function waitForProviderRetry(delayMs, signal) {
467
+ if (!signal) {
468
+ return new Promise((resolve) => {
469
+ setTimeout(resolve, delayMs);
470
+ });
471
+ }
472
+ return new Promise((resolve, reject) => {
473
+ let timer;
474
+ const onAbort = () => {
475
+ clearTimeout(timer);
476
+ reject(new provider_attempt_1.ProviderAttemptAbortError());
477
+ };
478
+ timer = setTimeout(() => {
479
+ signal.removeEventListener("abort", onAbort);
480
+ resolve();
481
+ }, delayMs);
482
+ if (signal.aborted) {
483
+ onAbort();
484
+ return;
485
+ }
486
+ signal.addEventListener("abort", onAbort, { once: true });
487
+ });
292
488
  }
293
- function classifyTransientError(err) {
294
- if (!(err instanceof Error))
295
- return "unknown error";
296
- const status = err.status;
297
- if (status === 429)
298
- return "rate limited";
299
- if (status === 401 || status === 403)
300
- return "auth error";
301
- if (status && status >= 500)
302
- return "server error";
303
- return "network error";
489
+ function buildAuthFailureGuidance(provider, model, agentName, detail) {
490
+ const mismatch = (0, provider_models_1.getProviderModelMismatchMessage)(provider, model);
491
+ const modelLabel = model
492
+ ? mismatch
493
+ ? `${provider} [configured model: ${model}]`
494
+ : `${provider} (${model})`
495
+ : provider;
496
+ const lines = [`${modelLabel} authentication failed.`];
497
+ const cleanDetail = detail.replace(/\s+/g, " ").trim();
498
+ if (cleanDetail)
499
+ lines.push(`provider detail: ${cleanDetail.length > 300 ? `${cleanDetail.slice(0, 297)}...` : cleanDetail}`);
500
+ lines.push("");
501
+ lines.push("To keep using this provider:");
502
+ lines.push(` 1. Run \`ouro auth --agent ${agentName} --provider ${provider}\``);
503
+ if (mismatch) {
504
+ const defaultModel = (0, provider_models_1.getDefaultModelForProvider)(provider);
505
+ lines.push("");
506
+ lines.push("Config warning:");
507
+ lines.push(` - ${mismatch}`);
508
+ lines.push(" - Repair the configured model with:");
509
+ lines.push(` \`ouro config model --agent ${agentName} --facing human ${defaultModel}\``);
510
+ lines.push(` \`ouro config model --agent ${agentName} --facing agent ${defaultModel}\``);
511
+ }
512
+ lines.push("");
513
+ lines.push(`To use another configured provider instead, run \`ouro auth switch --agent ${agentName} --provider <provider>\`.`);
514
+ return lines.join("\n");
304
515
  }
305
- const MAX_RETRIES = 3;
306
- const RETRY_BASE_MS = 2000;
307
516
  async function runAgent(messages, callbacks, channel, signal, options) {
308
- const providerRuntime = getProviderRuntime();
517
+ const facing = (0, channel_1.channelToFacing)(channel);
518
+ let providerRuntime = await getProviderRuntime(facing);
309
519
  const provider = providerRuntime.id;
310
520
  const toolChoiceRequired = options?.toolChoiceRequired ?? true;
311
521
  const traceId = options?.traceId;
@@ -329,6 +539,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
329
539
  // Refresh system prompt at start of each turn when channel is provided.
330
540
  // If refresh fails, keep existing system prompt (or inject a minimal safe fallback)
331
541
  // so turn execution remains consistent and non-fatal.
542
+ let structuredSystemPrompt;
332
543
  if (channel) {
333
544
  try {
334
545
  const buildSystemOptions = {
@@ -337,7 +548,8 @@ async function runAgent(messages, callbacks, channel, signal, options) {
337
548
  supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
338
549
  };
339
550
  const refreshed = await (0, prompt_1.buildSystem)(channel, buildSystemOptions, currentContext);
340
- upsertSystemPrompt(messages, refreshed);
551
+ structuredSystemPrompt = refreshed;
552
+ upsertSystemPrompt(messages, (0, prompt_1.flattenSystemPrompt)(refreshed));
341
553
  }
342
554
  catch (error) {
343
555
  const hadExistingSystemPrompt = messages[0]?.role === "system" && typeof messages[0].content === "string";
@@ -358,40 +570,120 @@ async function runAgent(messages, callbacks, channel, signal, options) {
358
570
  });
359
571
  }
360
572
  }
361
- await (0, associative_recall_1.injectAssociativeRecall)(messages);
573
+ if (channel) {
574
+ await (0, kept_notes_1.injectKeptNotes)(messages, {
575
+ channel,
576
+ friend: currentContext?.friend,
577
+ judge: async (input) => (0, kept_notes_1.createKeptNotesJudge)(await getProviderRuntime("agent"), signal)(input),
578
+ signal,
579
+ traceId,
580
+ });
581
+ }
362
582
  let done = false;
363
583
  let lastUsage;
364
584
  let overflowRetried = false;
365
- let retryCount = 0;
366
- let outcome = "complete";
585
+ let outcome = "settled";
367
586
  let completion;
587
+ let terminalError;
588
+ let terminalErrorClassification;
368
589
  let sawSteeringFollowUp = false;
369
590
  let mustResolveBeforeHandoffActive = options?.mustResolveBeforeHandoff === true;
370
591
  let currentReasoningEffort = "medium";
592
+ let sawSendMessageSelf = false;
593
+ let sawPonder = false;
594
+ let sawQuerySession = false;
595
+ let sawBridgeManage = false;
596
+ let sawExternalStateQuery = false;
597
+ // Once-per-turn flag for the fresh-work rest gate. Without this, an agent
598
+ // that called rest, was told "fresh work arrived", processed the items,
599
+ // and called rest again would get the same message forever — the gate
600
+ // condition is read from the turn-start snapshot of pendingMessages,
601
+ // which doesn't update mid-turn. The agent only needs to be told once;
602
+ // after that, repeated rest attempts mean they've acknowledged.
603
+ let freshWorkGateFired = false;
604
+ // Counter for "no tool call returned despite tool_choice=required" violations.
605
+ // MiniMax reasoning models occasionally emit only a <think>...</think>
606
+ // block and stop, without any tool call — even when tool_choice is set to
607
+ // "required". This is a provider-level violation; the harness retries with
608
+ // a corrective nudge up to a small cap rather than silently accepting an
609
+ // empty turn.
610
+ let noToolCallRetries = 0;
611
+ const NO_TOOL_CALL_MAX_RETRIES = 2;
612
+ const toolLoopState = (0, tool_loop_1.createToolLoopState)();
613
+ const toolFrictionLedger = (0, tool_friction_1.createToolFrictionLedger)();
614
+ const finishTerminalProviderError = (error, classification) => {
615
+ terminalError = error;
616
+ terminalErrorClassification = classification;
617
+ /* v8 ignore start — auth-failure guidance: tested via provider error classification tests @preserve */
618
+ if (terminalErrorClassification === "auth-failure") {
619
+ const agentName = (0, identity_2.getAgentName)();
620
+ const currentProvider = providerRuntime.id;
621
+ callbacks.onError(new Error(buildAuthFailureGuidance(currentProvider, providerRuntime.model, agentName, terminalError.message)), "terminal");
622
+ }
623
+ else {
624
+ callbacks.onError(terminalError, "terminal");
625
+ }
626
+ /* v8 ignore stop */
627
+ const errorDetails = (0, error_classification_1.extractProviderErrorDetails)(terminalError);
628
+ (0, runtime_1.emitNervesEvent)({
629
+ level: "error",
630
+ event: "engine.error",
631
+ trace_id: traceId,
632
+ component: "engine",
633
+ message: terminalError.message,
634
+ meta: {
635
+ provider: providerRuntime.id,
636
+ model: providerRuntime.model,
637
+ errorClassification: terminalErrorClassification,
638
+ ...(errorDetails.status !== undefined ? { httpStatus: errorDetails.status } : {}),
639
+ ...(errorDetails.bodyExcerpt ? { bodyExcerpt: errorDetails.bodyExcerpt } : {}),
640
+ summary: (0, error_classification_1.summarizeProviderError)(terminalError, terminalErrorClassification, providerRuntime.id, providerRuntime.model),
641
+ },
642
+ });
643
+ stripLastToolCalls(messages);
644
+ outcome = "errored";
645
+ done = true;
646
+ };
371
647
  // Prevent MaxListenersExceeded warning — each iteration adds a listener
372
648
  try {
373
649
  require("events").setMaxListeners(50, signal);
374
650
  }
375
651
  catch { /* unsupported */ }
376
652
  const toolPreferences = currentContext?.friend?.toolPreferences;
377
- 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);
653
+ 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, options?.mcpManager, providerRuntime.model);
378
654
  // Augment tool context with reasoning effort controls from provider
379
655
  const augmentedToolContext = options?.toolContext
380
656
  ? {
381
657
  ...options.toolContext,
382
658
  supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
383
659
  setReasoningEffort: (level) => { currentReasoningEffort = level; },
660
+ activeWorkFrame: options?.activeWorkFrame,
384
661
  }
385
662
  : undefined;
386
663
  // Rebase provider-owned turn state from canonical messages at user-turn start.
387
664
  // This prevents stale provider caches from replaying prior-turn context.
388
665
  providerRuntime.resetTurnState(messages);
389
666
  while (!done) {
390
- // When toolChoiceRequired is true (the default), include final_answer
391
- // so the model can signal completion. With tool_choice: required, the
392
- // model must call a tool every turn final_answer is how it exits.
393
- // Overridable via options.toolChoiceRequired = false (e.g. CLI).
394
- const activeTools = toolChoiceRequired ? [...baseTools, tools_1.finalAnswerTool] : baseTools;
667
+ // Channel-based tool filtering:
668
+ // - Inner dialog: exclude send_message (delivery via surface), observe (no one to observe)
669
+ // - All outward channels (1:1, group, reaction): observe available
670
+ //
671
+ // ponder, settle/rest, surface, and observe are always assembled based on channel context.
672
+ // ponder is available in ALL channels (outer: think privately, inner: keep turning).
673
+ // Inner dialog gets restTool instead of settleTool (rest = end turn, gated by attention queue).
674
+ // toolChoiceRequired only controls whether tool_choice: "required" is set in the API call.
675
+ const isInnerDialog = channel === "inner";
676
+ const filteredBaseTools = isInnerDialog
677
+ ? baseTools.filter((t) => t.function.name !== "send_message")
678
+ : baseTools;
679
+ const activeTools = [
680
+ ...filteredBaseTools,
681
+ tools_1.ponderTool,
682
+ ...(isInnerDialog ? [tools_2.surfaceToolDef, tools_1.restTool] : []),
683
+ ...(!isInnerDialog ? [tools_1.observeTool] : []),
684
+ ...(!isInnerDialog ? [tools_1.settleTool] : []),
685
+ ...(isChatStyleChannel(channel ?? "") ? [tools_1.speakTool] : []),
686
+ ];
395
687
  const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
396
688
  if (steeringFollowUps.length > 0) {
397
689
  const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
@@ -418,26 +710,124 @@ async function runAgent(messages, callbacks, channel, signal, options) {
418
710
  break;
419
711
  }
420
712
  try {
421
- callbacks.onModelStart();
422
- const result = await providerRuntime.streamTurn({
423
- messages,
424
- activeTools,
425
- callbacks,
426
- signal,
427
- traceId,
428
- toolChoiceRequired,
429
- reasoningEffort: currentReasoningEffort,
713
+ const callProviderTurn = async () => {
714
+ callbacks.onModelStart();
715
+ try {
716
+ return await providerRuntime.streamTurn({
717
+ messages,
718
+ activeTools,
719
+ callbacks,
720
+ signal,
721
+ traceId,
722
+ toolChoiceRequired,
723
+ reasoningEffort: currentReasoningEffort,
724
+ eagerSettleStreaming: true,
725
+ systemPrompt: structuredSystemPrompt,
726
+ });
727
+ }
728
+ catch (error) {
729
+ if (signal?.aborted)
730
+ throw new provider_attempt_1.ProviderAttemptAbortError();
731
+ throw error;
732
+ }
733
+ };
734
+ const callProviderTurnWithOverflowRecovery = async () => {
735
+ try {
736
+ return await callProviderTurn();
737
+ }
738
+ catch (error) {
739
+ if (error instanceof provider_attempt_1.ProviderAttemptAbortError)
740
+ throw error;
741
+ if (isContextOverflow(error) && !overflowRetried) {
742
+ overflowRetried = true;
743
+ stripLastToolCalls(messages);
744
+ const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
745
+ const trimmed = (0, context_1.trimMessages)(messages, maxTokens, contextMargin, maxTokens * 2);
746
+ messages.splice(0, messages.length, ...trimmed);
747
+ providerRuntime.resetTurnState(messages);
748
+ callbacks.onError(new Error("context trimmed, retrying..."), "transient");
749
+ return callProviderTurn();
750
+ }
751
+ throw error;
752
+ }
753
+ };
754
+ const attempt = await (0, provider_attempt_1.runProviderAttempt)({
755
+ operation: "turn",
756
+ provider: providerRuntime.id,
757
+ model: providerRuntime.model,
758
+ run: callProviderTurnWithOverflowRecovery,
759
+ classifyError: (error) => providerRuntime.classifyError(error),
760
+ onRetry: async (record, maxAttempts) => {
761
+ const delayMs = record.delayMs;
762
+ const seconds = delayMs / 1000;
763
+ const cause = RETRY_LABELS[record.classification];
764
+ try {
765
+ await (0, provider_credentials_1.refreshProviderCredentialPool)((0, identity_2.getAgentName)(), {
766
+ preserveCachedOnFailure: true,
767
+ providers: [record.provider],
768
+ });
769
+ _providerRuntimes[facing] = null;
770
+ providerRuntime = await getProviderRuntime(facing);
771
+ providerRuntime.resetTurnState(messages);
772
+ }
773
+ catch (refreshError) {
774
+ (0, runtime_1.emitNervesEvent)({
775
+ level: "warn",
776
+ component: "engine",
777
+ event: "engine.provider_retry_refresh_failed",
778
+ message: "provider credential refresh failed during retry",
779
+ meta: { provider: record.provider, model: record.model, reason: refreshError instanceof Error ? refreshError.message : String(refreshError) },
780
+ });
781
+ }
782
+ callbacks.onError(new Error(`${cause}, retrying in ${seconds}s (${record.attempt}/${maxAttempts})...`), "transient");
783
+ },
784
+ sleep: async (delayMs) => {
785
+ await waitForProviderRetry(delayMs, signal);
786
+ providerRuntime.resetTurnState(messages);
787
+ },
430
788
  });
789
+ if (!attempt.ok) {
790
+ finishTerminalProviderError(attempt.error, attempt.classification);
791
+ continue;
792
+ }
793
+ const result = attempt.value;
431
794
  // Track usage from the latest API call
432
795
  if (result.usage)
433
796
  lastUsage = result.usage;
434
- retryCount = 0; // reset on success
435
797
  // SHARED: build CC-format assistant message from TurnResult
436
798
  const msg = {
437
799
  role: "assistant",
438
800
  };
439
- if (result.content)
440
- msg.content = result.content;
801
+ // Persist assistant content WITHOUT inline <think>...</think> blocks.
802
+ // Reasoning content already routed through onReasoningChunk for live
803
+ // surfacing and persisted separately as `_reasoning_items` for
804
+ // providers that support a reasoning channel; saving it inline AND
805
+ // alongside tool_calls causes MiniMax to reject the replayed turn
806
+ // with "tool result's tool id not found" (error code 2013) because
807
+ // it can't reconcile reasoning-with-tools in the same assistant
808
+ // message. Strip aggressively at persist so the next replay is
809
+ // clean; preserve the original reasoning trace on the message via
810
+ // `_inline_reasoning` so debug/audit paths can still see it.
811
+ if (result.content) {
812
+ const stripped = stripThinkBlocksForViolationCheck(result.content);
813
+ if (stripped.length > 0)
814
+ msg.content = stripped;
815
+ if (stripped.length !== result.content.length) {
816
+ msg._inline_reasoning = result.content;
817
+ (0, runtime_1.emitNervesEvent)({
818
+ level: "info",
819
+ component: "engine",
820
+ event: "engine.inline_reasoning_stripped",
821
+ message: "stripped inline <think> blocks from persisted assistant message; preserved on _inline_reasoning",
822
+ meta: {
823
+ provider: providerRuntime.id,
824
+ model: providerRuntime.model,
825
+ originalLength: result.content.length,
826
+ strippedLength: stripped.length,
827
+ },
828
+ });
829
+ }
830
+ }
441
831
  if (result.toolCalls.length)
442
832
  msg.tool_calls = result.toolCalls.map((tc) => ({
443
833
  id: tc.id,
@@ -457,35 +847,108 @@ async function runAgent(messages, callbacks, channel, signal, options) {
457
847
  }
458
848
  // Phase annotation for Codex provider
459
849
  const hasPhaseAnnotation = providerRuntime.capabilities.has("phase-annotation");
460
- const isSoleFinalAnswer = result.toolCalls.length === 1 && result.toolCalls[0].name === "final_answer";
850
+ const isSoleSettle = result.toolCalls.length === 1 && result.toolCalls[0].name === "settle";
461
851
  if (hasPhaseAnnotation) {
462
- msg.phase = isSoleFinalAnswer ? "final_answer" : "commentary";
852
+ msg.phase = isSoleSettle ? "settle" : "commentary";
463
853
  }
854
+ // Detect the MiniMax "only-thinking, no tool call" violation: no tool
855
+ // calls returned, and the content is empty after stripping
856
+ // <think>...</think> blocks. This is a narrow check — legitimate
857
+ // content-only responses (text without think tags, or text outside
858
+ // think tags) still flow through the original "no tool calls →
859
+ // accept as-is" path so existing channels and tests are unaffected.
860
+ const onlyThinkContent = !result.toolCalls.length
861
+ && typeof result.content === "string"
862
+ && stripThinkBlocksForViolationCheck(result.content).length === 0
863
+ && result.content.length > 0;
464
864
  if (!result.toolCalls.length) {
465
- // No tool calls accept response as-is.
466
- // (Kick detection disabled; tool_choice: required + final_answer
467
- // is the primary loop control. See src/heart/kicks.ts to re-enable.)
865
+ if (onlyThinkContent && toolChoiceRequired && noToolCallRetries < NO_TOOL_CALL_MAX_RETRIES) {
866
+ // Provider-level violation: tool_choice was required, model emitted
867
+ // only a <think>...</think> block (or empty content) with no tool
868
+ // call. Retry with a corrective nudge up to NO_TOOL_CALL_MAX_RETRIES
869
+ // times. After cap, accept as-is (the readback path strips think
870
+ // tags and surfaces a clear diagnostic).
871
+ noToolCallRetries++;
872
+ (0, runtime_1.emitNervesEvent)({
873
+ level: "warn",
874
+ component: "engine",
875
+ event: "engine.no_tool_call_retry",
876
+ message: "model returned only <think> content with no tool call despite tool_choice=required; retrying with corrective nudge",
877
+ meta: {
878
+ attempt: noToolCallRetries,
879
+ cap: NO_TOOL_CALL_MAX_RETRIES,
880
+ provider: providerRuntime.id,
881
+ model: providerRuntime.model,
882
+ contentLength: result.content.length,
883
+ },
884
+ });
885
+ messages.push(msg);
886
+ messages.push({
887
+ role: "user",
888
+ content: isInnerDialog
889
+ ? "no tool was called this turn. you must end every turn by calling rest (or surface, ponder, observe). emit the tool call now."
890
+ : "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.",
891
+ });
892
+ continue;
893
+ }
894
+ // Legitimate text-only response, or cap reached — accept as-is.
468
895
  messages.push(msg);
469
896
  done = true;
470
897
  }
471
898
  else {
472
- // Check for final_answer sole call: intercept before tool execution
473
- if (isSoleFinalAnswer) {
899
+ // Reset the retry counter on any successful tool call.
900
+ noToolCallRetries = 0;
901
+ // Check for settle sole call: intercept before tool execution
902
+ if (isSoleSettle) {
903
+ /* v8 ignore next -- defensive: JSON.parse catch for malformed settle args @preserve */
904
+ const settleArgs = (() => { try {
905
+ return JSON.parse(result.toolCalls[0].arguments);
906
+ }
907
+ catch {
908
+ return {};
909
+ } })();
910
+ callbacks.onToolStart("settle", settleArgs);
911
+ // Inner dialog attention queue gate: reject settle if items remain
912
+ const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
913
+ if (isInnerDialog && attentionQueue && attentionQueue.length > 0) {
914
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
915
+ callbacks.onClearText?.();
916
+ messages.push(msg);
917
+ const gateMessage = "you're holding thoughts someone is waiting for — surface them before you settle.";
918
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
919
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
920
+ continue;
921
+ }
474
922
  // Extract answer from the tool call arguments.
475
923
  // Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
476
- const { answer, intent } = parseFinalAnswerPayload(result.toolCalls[0].arguments);
924
+ const { answer, intent } = parseSettlePayload(result.toolCalls[0].arguments);
925
+ // Inner dialog settle: no CompletionMetadata, "(settled)" ack
926
+ if (isInnerDialog) {
927
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
928
+ messages.push(msg);
929
+ const settled = "(settled)";
930
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: settled });
931
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, settled);
932
+ outcome = "settled";
933
+ done = true;
934
+ continue;
935
+ }
936
+ const retryError = getSettleRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp, options?.delegationDecision, sawSendMessageSelf, sawPonder, sawQuerySession, options?.currentObligation ?? null, options?.activeWorkFrame?.inner?.job, sawExternalStateQuery);
937
+ const deliveredAnswer = answer;
477
938
  const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
478
939
  const validTerminalIntent = intent === "complete" || intent === "blocked";
479
- const validClosure = answer != null
940
+ const validClosure = deliveredAnswer != null
941
+ && !retryError
480
942
  && (!mustResolveBeforeHandoffActive || validDirectReply || validTerminalIntent);
481
943
  if (validClosure) {
944
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
482
945
  completion = {
483
- answer,
946
+ answer: deliveredAnswer,
484
947
  intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
485
948
  };
486
- if (result.finalAnswerStreamed) {
949
+ if (result.settleStreamed) {
487
950
  // The streaming layer already parsed and emitted the answer
488
- // progressively via FinalAnswerParser. Skip clearing and
951
+ // progressively via SettleParser. Skip clearing and
489
952
  // re-emitting to avoid double-delivery.
490
953
  }
491
954
  else {
@@ -493,7 +956,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
493
956
  callbacks.onClearText?.();
494
957
  // Emit the answer through the callback pipeline so channels receive it.
495
958
  // Never truncate -- channel adapters handle splitting long messages.
496
- callbacks.onTextChunk(answer);
959
+ callbacks.onTextChunk(deliveredAnswer);
497
960
  }
498
961
  messages.push(msg);
499
962
  if (validDirectReply) {
@@ -505,32 +968,114 @@ async function runAgent(messages, callbacks, channel, signal, options) {
505
968
  const delivered = "(delivered)";
506
969
  messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
507
970
  providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
508
- outcome = intent === "blocked" ? "blocked" : "complete";
971
+ outcome = intent === "blocked" ? "blocked" : "settled";
509
972
  done = true;
510
973
  }
511
974
  }
512
975
  else {
513
- // Answer is undefined -- the model's final_answer was incomplete or
976
+ // Answer is undefined -- the model's settle was incomplete or
514
977
  // malformed. Clear any partial streamed text or noise, then push the
515
978
  // assistant msg + error tool result and let the model try again.
979
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
516
980
  callbacks.onClearText?.();
517
- const retryError = getFinalAnswerRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp);
518
981
  messages.push(msg);
519
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: retryError });
520
- providerRuntime.appendToolOutput(result.toolCalls[0].id, retryError);
982
+ const toolRetryMessage = retryError
983
+ ?? "your settle was incomplete or malformed. call settle again with your complete response.";
984
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: toolRetryMessage });
985
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, toolRetryMessage);
986
+ }
987
+ continue;
988
+ }
989
+ // Check for observe sole call: intercept before tool execution
990
+ const isSoleObserve = result.toolCalls.length === 1 && result.toolCalls[0].name === "observe";
991
+ if (isSoleObserve) {
992
+ /* v8 ignore next -- defensive: JSON.parse catch for malformed observe args @preserve */
993
+ const observeArgs = (() => { try {
994
+ return JSON.parse(result.toolCalls[0].arguments);
995
+ }
996
+ catch {
997
+ return {};
998
+ } })();
999
+ let reason;
1000
+ if (typeof observeArgs?.reason === "string")
1001
+ reason = observeArgs.reason;
1002
+ callbacks.onToolStart("observe", observeArgs);
1003
+ (0, runtime_1.emitNervesEvent)({
1004
+ component: "engine",
1005
+ event: "engine.observe",
1006
+ message: "agent observed without responding",
1007
+ meta: { ...(reason ? { reason } : {}) },
1008
+ });
1009
+ callbacks.onToolEnd("observe", (0, tools_1.summarizeArgs)("observe", observeArgs), true);
1010
+ messages.push(msg);
1011
+ const silenced = "(silenced)";
1012
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: silenced });
1013
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, silenced);
1014
+ outcome = "observed";
1015
+ done = true;
1016
+ continue;
1017
+ }
1018
+ // Check for rest sole call: intercept before tool execution
1019
+ const isSoleRest = result.toolCalls.length === 1 && result.toolCalls[0].name === "rest";
1020
+ if (isSoleRest) {
1021
+ const restArgs = (() => { try {
1022
+ return JSON.parse(result.toolCalls[0].arguments);
1023
+ }
1024
+ catch {
1025
+ return {};
1026
+ } })();
1027
+ callbacks.onToolStart("rest", restArgs);
1028
+ // Attention queue gate: reject rest if items remain
1029
+ const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
1030
+ if (attentionQueue && attentionQueue.length > 0) {
1031
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), false);
1032
+ messages.push(msg);
1033
+ const gateMessage = "you're holding thoughts someone is waiting for — surface them before you rest.";
1034
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
1035
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
1036
+ continue;
1037
+ }
1038
+ if (hasFreshPendingWork(options) && !freshWorkGateFired) {
1039
+ freshWorkGateFired = true;
1040
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), false);
1041
+ messages.push(msg);
1042
+ const gateMessage = "fresh work arrived for me this turn — inspect the pending messages above and take the next concrete action before you rest.";
1043
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
1044
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
1045
+ (0, runtime_1.emitNervesEvent)({
1046
+ level: "info",
1047
+ component: "engine",
1048
+ event: "engine.fresh_work_gate_fired",
1049
+ message: "rest deferred once because pending work arrived this turn; agent has been notified",
1050
+ meta: { pendingCount: options.pendingMessages.length },
1051
+ });
1052
+ continue;
521
1053
  }
1054
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), true);
1055
+ messages.push(msg);
1056
+ const ack = "(resting)";
1057
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
1058
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
1059
+ (0, runtime_1.emitNervesEvent)({
1060
+ component: "engine",
1061
+ event: "engine.rested",
1062
+ message: "resting until next heartbeat",
1063
+ meta: { ...(typeof restArgs?.status === "string" ? { status: restArgs.status } : {}) },
1064
+ });
1065
+ outcome = "rested";
1066
+ done = true;
522
1067
  continue;
523
1068
  }
524
1069
  messages.push(msg);
525
- // SHARED: execute tools (final_answer in mixed calls is rejected inline)
1070
+ // Execute tools (sole-call tools in mixed calls are rejected inline)
526
1071
  for (const tc of result.toolCalls) {
527
1072
  if (signal?.aborted)
528
1073
  break;
529
- // Intercept final_answer in mixed call: reject it
530
- if (tc.name === "final_answer") {
531
- const rejection = "rejected: final_answer must be the only tool call. Finish your work first, then call final_answer alone.";
532
- messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
533
- providerRuntime.appendToolOutput(tc.id, rejection);
1074
+ // Reject sole-call tools when mixed with other tool calls
1075
+ const soleCallRejection = SOLE_CALL_REJECTION[tc.name];
1076
+ if (soleCallRejection) {
1077
+ messages.push({ role: "tool", tool_call_id: tc.id, content: soleCallRejection });
1078
+ providerRuntime.appendToolOutput(tc.id, soleCallRejection);
534
1079
  continue;
535
1080
  }
536
1081
  let args = {};
@@ -540,21 +1085,213 @@ async function runAgent(messages, callbacks, channel, signal, options) {
540
1085
  catch {
541
1086
  /* ignore */
542
1087
  }
543
- const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
544
- // Confirmation check for mutate tools
545
- if ((0, tools_1.isConfirmationRequired)(tc.name) && !options?.skipConfirmation) {
546
- let decision = "denied";
547
- if (callbacks.onConfirmAction) {
548
- decision = await callbacks.onConfirmAction(tc.name, args);
1088
+ if (tc.name === "send_message" && args.friendId === "self") {
1089
+ sawSendMessageSelf = true;
1090
+ }
1091
+ if (tc.name === "speak") {
1092
+ let speakArgs = {};
1093
+ try {
1094
+ speakArgs = JSON.parse(tc.arguments);
1095
+ }
1096
+ catch { /* malformed */ }
1097
+ const speakMessage = typeof speakArgs.message === "string" ? speakArgs.message : "";
1098
+ const argSummary = (0, tools_1.summarizeArgs)("speak", { message: speakMessage });
1099
+ callbacks.onToolStart("speak", { message: speakMessage });
1100
+ if (speakMessage.trim().length === 0) {
1101
+ const err = "speak requires a non-empty `message` string.";
1102
+ callbacks.onToolEnd("speak", argSummary, false);
1103
+ messages.push({ role: "tool", tool_call_id: tc.id, content: err });
1104
+ providerRuntime.appendToolOutput(tc.id, err);
1105
+ (0, runtime_1.emitNervesEvent)({
1106
+ level: "warn",
1107
+ component: "engine",
1108
+ event: "engine.speak_invalid",
1109
+ message: "speak rejected: missing or empty message",
1110
+ meta: {},
1111
+ });
1112
+ continue;
1113
+ }
1114
+ callbacks.onTextChunk(speakMessage);
1115
+ let speakDeliveryError = null;
1116
+ try {
1117
+ await callbacks.flushNow?.();
1118
+ }
1119
+ catch (err) {
1120
+ speakDeliveryError = err instanceof Error ? err : new Error(String(err));
549
1121
  }
550
- if (decision !== "confirmed") {
551
- const cancelled = "Action cancelled by user.";
552
- callbacks.onToolStart(tc.name, args);
553
- callbacks.onToolEnd(tc.name, argSummary, false);
554
- messages.push({ role: "tool", tool_call_id: tc.id, content: cancelled });
555
- providerRuntime.appendToolOutput(tc.id, cancelled);
1122
+ if (speakDeliveryError) {
1123
+ callbacks.onToolEnd("speak", argSummary, false);
1124
+ const failMsg = `speak delivery failed: ${speakDeliveryError.message}. the message did not reach your friend; do not assume they saw it.`;
1125
+ messages.push({ role: "tool", tool_call_id: tc.id, content: failMsg });
1126
+ providerRuntime.appendToolOutput(tc.id, failMsg);
1127
+ (0, runtime_1.emitNervesEvent)({
1128
+ level: "error",
1129
+ component: "engine",
1130
+ event: "engine.speak_delivery_failed",
1131
+ message: "speak delivery failed",
1132
+ meta: { error: speakDeliveryError.message, messageLength: speakMessage.length },
1133
+ });
556
1134
  continue;
557
1135
  }
1136
+ callbacks.onToolEnd("speak", argSummary, true);
1137
+ const ack = "(spoken)";
1138
+ messages.push({ role: "tool", tool_call_id: tc.id, content: ack });
1139
+ providerRuntime.appendToolOutput(tc.id, ack);
1140
+ (0, runtime_1.emitNervesEvent)({
1141
+ component: "engine",
1142
+ event: "engine.speak",
1143
+ message: "agent spoke mid-turn",
1144
+ meta: { messageLength: speakMessage.length },
1145
+ });
1146
+ continue;
1147
+ }
1148
+ if (tc.name === "ponder") {
1149
+ const parsedArgs = normalizeLegacyPonderArgs(parsePonderPayload(tc.arguments));
1150
+ const argSummary = (0, tools_1.summarizeArgs)(tc.name, parsedArgs);
1151
+ callbacks.onToolStart(tc.name, parsedArgs);
1152
+ let toolResult;
1153
+ let success = false;
1154
+ try {
1155
+ const action = parsedArgs.action ?? "create";
1156
+ const currentSession = (augmentedToolContext ?? options?.toolContext)?.currentSession;
1157
+ const currentOrigin = currentSession
1158
+ ? { friendId: currentSession.friendId, channel: currentSession.channel, key: currentSession.key }
1159
+ : undefined;
1160
+ const isInnerChannel = currentOrigin?.friendId === "self" && currentOrigin?.channel === "inner";
1161
+ const successCriteria = parseSuccessCriteria(parsedArgs.success_criteria);
1162
+ const payload = parsePacketPayload(parsedArgs.payload_json);
1163
+ let packet;
1164
+ let returnObligationId = null;
1165
+ let resultAction = "created";
1166
+ if (action === "create") {
1167
+ const kind = parsedArgs.kind;
1168
+ const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
1169
+ const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
1170
+ if (!kind || !objective || !successCriteria || !payload) {
1171
+ throw new Error("ponder create requires kind, objective, success_criteria, and valid payload_json.");
1172
+ }
1173
+ const agentRoot = (0, identity_2.getAgentRoot)();
1174
+ let relatedObligationId;
1175
+ if (currentOrigin && !isInnerChannel) {
1176
+ try {
1177
+ const obligation = (0, obligations_1.createObligation)(agentRoot, {
1178
+ origin: currentOrigin,
1179
+ content: objective,
1180
+ });
1181
+ relatedObligationId = obligation.id;
1182
+ }
1183
+ catch {
1184
+ relatedObligationId = undefined;
1185
+ }
1186
+ }
1187
+ const frictionSignature = kind === "harness_friction" && typeof payload.frictionSignature === "string"
1188
+ ? payload.frictionSignature
1189
+ : null;
1190
+ const existing = frictionSignature && currentOrigin
1191
+ ? (0, packets_1.findHarnessFrictionPacket)(agentRoot, currentOrigin, frictionSignature)
1192
+ : null;
1193
+ if (existing) {
1194
+ resultAction = "revised";
1195
+ returnObligationId = existing.relatedReturnObligationId ?? null;
1196
+ packet = existing.status === "drafting"
1197
+ ? (0, packets_1.revisePonderPacket)(agentRoot, existing.id, {
1198
+ kind,
1199
+ objective,
1200
+ summary,
1201
+ successCriteria,
1202
+ payload,
1203
+ })
1204
+ : existing;
1205
+ }
1206
+ else {
1207
+ returnObligationId = (0, obligations_1.generateObligationId)(Date.now());
1208
+ packet = (0, packets_1.createPonderPacket)(agentRoot, {
1209
+ kind,
1210
+ objective,
1211
+ summary,
1212
+ successCriteria,
1213
+ ...(currentOrigin ? { origin: currentOrigin } : {}),
1214
+ ...(relatedObligationId ? { relatedObligationId } : {}),
1215
+ relatedReturnObligationId: returnObligationId,
1216
+ ...(parsedArgs.follows_packet_id ? { followsPacketId: parsedArgs.follows_packet_id } : {}),
1217
+ payload,
1218
+ });
1219
+ (0, obligations_1.createReturnObligation)((0, identity_2.getAgentName)(), {
1220
+ id: returnObligationId,
1221
+ origin: currentOrigin ?? { friendId: "self", channel: "inner", key: "dialog" },
1222
+ status: "queued",
1223
+ delegatedContent: (summary || objective).length > 120 ? `${(summary || objective).slice(0, 117)}...` : (summary || objective),
1224
+ packetId: packet.id,
1225
+ createdAt: Date.now(),
1226
+ });
1227
+ }
1228
+ }
1229
+ else if (action === "revise") {
1230
+ const packetId = typeof parsedArgs.packet_id === "string" ? parsedArgs.packet_id.trim() : "";
1231
+ const kind = parsedArgs.kind;
1232
+ const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
1233
+ const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
1234
+ if (!packetId || !kind || !objective || !successCriteria || !payload) {
1235
+ throw new Error("ponder revise requires packet_id, kind, objective, success_criteria, and valid payload_json.");
1236
+ }
1237
+ packet = (0, packets_1.revisePonderPacket)((0, identity_2.getAgentRoot)(), packetId, {
1238
+ kind,
1239
+ objective,
1240
+ summary,
1241
+ successCriteria,
1242
+ payload,
1243
+ });
1244
+ returnObligationId = packet.relatedReturnObligationId ?? null;
1245
+ resultAction = "revised";
1246
+ }
1247
+ else {
1248
+ throw new Error("ponder requires action=create or revise.");
1249
+ }
1250
+ try {
1251
+ await (0, socket_client_1.requestInnerWake)((0, identity_2.getAgentName)());
1252
+ }
1253
+ catch { /* daemon may not be running */ }
1254
+ sawPonder = true;
1255
+ toolResult = buildPonderResult(packet, resultAction, returnObligationId);
1256
+ success = true;
1257
+ (0, runtime_1.emitNervesEvent)({
1258
+ component: "engine",
1259
+ event: "engine.ponder_packet",
1260
+ message: "ponder packet touched",
1261
+ meta: {
1262
+ action: resultAction,
1263
+ packetId: packet.id,
1264
+ kind: packet.kind,
1265
+ status: packet.status,
1266
+ },
1267
+ });
1268
+ }
1269
+ catch (error) {
1270
+ toolResult = error instanceof Error ? error.message : String(error);
1271
+ }
1272
+ callbacks.onToolEnd(tc.name, argSummary, success);
1273
+ messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
1274
+ providerRuntime.appendToolOutput(tc.id, toolResult);
1275
+ continue;
1276
+ }
1277
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
1278
+ if (tc.name === "query_session")
1279
+ sawQuerySession = true;
1280
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
1281
+ if (tc.name === "bridge_manage")
1282
+ sawBridgeManage = true;
1283
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
1284
+ if (isExternalStateQuery(tc.name, args))
1285
+ sawExternalStateQuery = true;
1286
+ const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
1287
+ const toolLoop = (0, tool_loop_1.detectToolLoop)(toolLoopState, tc.name, args);
1288
+ if (toolLoop.stuck) {
1289
+ const rejection = `loop guard: ${toolLoop.message}`;
1290
+ callbacks.onToolStart(tc.name, args);
1291
+ callbacks.onToolEnd(tc.name, argSummary, false);
1292
+ messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
1293
+ providerRuntime.appendToolOutput(tc.id, rejection);
1294
+ continue;
558
1295
  }
559
1296
  callbacks.onToolStart(tc.name, args);
560
1297
  let toolResult;
@@ -568,69 +1305,32 @@ async function runAgent(messages, callbacks, channel, signal, options) {
568
1305
  toolResult = `error: ${e}`;
569
1306
  success = false;
570
1307
  }
571
- callbacks.onToolEnd(tc.name, argSummary, success);
1308
+ toolResult = (0, tool_friction_1.rewriteToolResultForModel)(tc.name, toolResult, toolFrictionLedger);
1309
+ (0, tool_loop_1.recordToolOutcome)(toolLoopState, tc.name, args, toolResult, success);
1310
+ callbacks.onToolEnd(tc.name, (0, tools_1.buildToolResultSummary)(tc.name, args, toolResult, success), success);
572
1311
  messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
573
1312
  providerRuntime.appendToolOutput(tc.id, toolResult);
1313
+ callbacks.onToolResult?.(messages);
574
1314
  }
575
1315
  }
576
1316
  }
577
1317
  catch (e) {
578
1318
  // Abort is not an error — just stop cleanly
579
- if (signal?.aborted) {
1319
+ if (e instanceof provider_attempt_1.ProviderAttemptAbortError || signal?.aborted) {
580
1320
  stripLastToolCalls(messages);
581
1321
  outcome = "aborted";
582
1322
  break;
583
1323
  }
584
- // Context overflow: trim aggressively and retry once
585
- if (isContextOverflow(e) && !overflowRetried) {
586
- overflowRetried = true;
587
- stripLastToolCalls(messages);
588
- const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
589
- const trimmed = (0, context_1.trimMessages)(messages, maxTokens, contextMargin, maxTokens * 2);
590
- messages.splice(0, messages.length, ...trimmed);
591
- providerRuntime.resetTurnState(messages);
592
- callbacks.onError(new Error("context trimmed, retrying..."), "transient");
593
- continue;
1324
+ const errorForClassification = e instanceof Error ? e : /* v8 ignore next -- defensive @preserve */ new Error(String(e));
1325
+ let providerClassification;
1326
+ try {
1327
+ providerClassification = providerRuntime.classifyError(errorForClassification);
594
1328
  }
595
- // Transient errors: retry with exponential backoff
596
- if (isTransientError(e) && retryCount < MAX_RETRIES) {
597
- retryCount++;
598
- const delay = RETRY_BASE_MS * Math.pow(2, retryCount - 1);
599
- const cause = classifyTransientError(e);
600
- callbacks.onError(new Error(`${cause}, retrying in ${delay / 1000}s (${retryCount}/${MAX_RETRIES})...`), "transient");
601
- // Wait with abort support
602
- const aborted = await new Promise((resolve) => {
603
- const timer = setTimeout(() => resolve(false), delay);
604
- if (signal) {
605
- const onAbort = () => { clearTimeout(timer); resolve(true); };
606
- if (signal.aborted) {
607
- clearTimeout(timer);
608
- resolve(true);
609
- return;
610
- }
611
- signal.addEventListener("abort", onAbort, { once: true });
612
- }
613
- });
614
- if (aborted) {
615
- stripLastToolCalls(messages);
616
- outcome = "aborted";
617
- break;
618
- }
619
- providerRuntime.resetTurnState(messages);
620
- continue;
1329
+ catch {
1330
+ /* v8 ignore next -- defensive: classifyError should not throw @preserve */
1331
+ providerClassification = "unknown";
621
1332
  }
622
- callbacks.onError(e instanceof Error ? e : new Error(String(e)), "terminal");
623
- (0, runtime_1.emitNervesEvent)({
624
- level: "error",
625
- event: "engine.error",
626
- trace_id: traceId,
627
- component: "engine",
628
- message: e instanceof Error ? e.message : String(e),
629
- meta: {},
630
- });
631
- stripLastToolCalls(messages);
632
- outcome = "errored";
633
- done = true;
1333
+ finishTerminalProviderError(errorForClassification, providerClassification);
634
1334
  }
635
1335
  }
636
1336
  (0, runtime_1.emitNervesEvent)({
@@ -638,7 +1338,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
638
1338
  trace_id: traceId,
639
1339
  component: "engine",
640
1340
  message: "runAgent turn completed",
641
- meta: { done },
1341
+ meta: { done, sawPonder, sawQuerySession, sawBridgeManage },
642
1342
  });
643
- return { usage: lastUsage, outcome, completion };
1343
+ return {
1344
+ usage: lastUsage,
1345
+ outcome,
1346
+ completion,
1347
+ ...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
1348
+ };
644
1349
  }