@ouro.bot/cli 0.1.0-alpha.50 → 0.1.0-alpha.501

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