@ouro.bot/cli 0.1.0-alpha.56 → 0.1.0-alpha.561

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