@ouro.bot/cli 0.1.0-alpha.5 → 0.1.0-alpha.500

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 (380) hide show
  1. package/README.md +226 -183
  2. package/SerpentGuide.ouro/agent.json +82 -0
  3. package/SerpentGuide.ouro/psyche/SOUL.md +25 -0
  4. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +2 -2
  5. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  6. package/assets/ouroboros.png +0 -0
  7. package/changelog.json +3418 -0
  8. package/dist/arc/attention-types.js +8 -0
  9. package/dist/arc/cares.js +140 -0
  10. package/dist/arc/episodes.js +117 -0
  11. package/dist/arc/intentions.js +133 -0
  12. package/dist/arc/json-store.js +117 -0
  13. package/dist/arc/obligations.js +237 -0
  14. package/dist/arc/packets.js +193 -0
  15. package/dist/arc/presence.js +185 -0
  16. package/dist/arc/task-lifecycle.js +65 -0
  17. package/dist/heart/active-work.js +989 -0
  18. package/dist/heart/agent-entry.js +58 -3
  19. package/dist/heart/attachments/image-normalize.js +194 -0
  20. package/dist/heart/attachments/materialize.js +97 -0
  21. package/dist/heart/attachments/originals.js +88 -0
  22. package/dist/heart/attachments/render.js +29 -0
  23. package/dist/heart/attachments/sources/adapter.js +2 -0
  24. package/dist/heart/attachments/sources/bluebubbles.js +156 -0
  25. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  26. package/dist/heart/attachments/sources/index.js +16 -0
  27. package/dist/heart/attachments/store.js +103 -0
  28. package/dist/heart/attachments/types.js +93 -0
  29. package/dist/heart/auth/auth-flow.js +426 -0
  30. package/dist/heart/background-operations.js +281 -0
  31. package/dist/heart/bridges/manager.js +358 -0
  32. package/dist/heart/bridges/state-machine.js +135 -0
  33. package/dist/heart/bridges/store.js +123 -0
  34. package/dist/heart/bundle-state.js +168 -0
  35. package/dist/heart/commitments.js +111 -0
  36. package/dist/heart/config-registry.js +304 -0
  37. package/dist/heart/config.js +193 -130
  38. package/dist/heart/core.js +1010 -261
  39. package/dist/heart/cross-chat-delivery.js +131 -0
  40. package/dist/heart/daemon/agent-config-check.js +490 -0
  41. package/dist/heart/daemon/agent-discovery.js +157 -0
  42. package/dist/heart/daemon/agent-service.js +360 -0
  43. package/dist/heart/daemon/agentic-repair.js +216 -0
  44. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  45. package/dist/heart/daemon/cadence.js +70 -0
  46. package/dist/heart/daemon/cli-defaults.js +640 -0
  47. package/dist/heart/daemon/cli-exec.js +7239 -0
  48. package/dist/heart/daemon/cli-help.js +493 -0
  49. package/dist/heart/daemon/cli-parse.js +1533 -0
  50. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  51. package/dist/heart/daemon/cli-render.js +561 -0
  52. package/dist/heart/daemon/cli-types.js +8 -0
  53. package/dist/heart/daemon/connect-bay.js +323 -0
  54. package/dist/heart/daemon/daemon-cli.js +30 -697
  55. package/dist/heart/daemon/daemon-entry.js +359 -8
  56. package/dist/heart/daemon/daemon-health.js +141 -0
  57. package/dist/heart/daemon/daemon-runtime-sync.js +268 -0
  58. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  59. package/dist/heart/daemon/daemon.js +813 -19
  60. package/dist/heart/daemon/dns-workflow.js +394 -0
  61. package/dist/heart/daemon/doctor-types.js +8 -0
  62. package/dist/heart/daemon/doctor.js +615 -0
  63. package/dist/heart/daemon/health-monitor.js +92 -1
  64. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  65. package/dist/heart/daemon/hooks/bundle-meta.js +206 -0
  66. package/dist/heart/daemon/http-health-probe.js +80 -0
  67. package/dist/heart/daemon/human-command-screens.js +234 -0
  68. package/dist/heart/daemon/human-readiness.js +114 -0
  69. package/dist/heart/daemon/inner-status.js +89 -0
  70. package/dist/heart/daemon/interactive-repair.js +394 -0
  71. package/dist/heart/daemon/launchd.js +171 -0
  72. package/dist/heart/daemon/log-tailer.js +82 -12
  73. package/dist/heart/daemon/logs-prune.js +110 -0
  74. package/dist/heart/daemon/message-router.js +17 -8
  75. package/dist/heart/daemon/os-cron-deps.js +134 -0
  76. package/dist/heart/daemon/ouro-bot-entry.js +4 -2
  77. package/dist/heart/daemon/ouro-entry.js +3 -1
  78. package/dist/heart/daemon/process-manager.js +215 -1
  79. package/dist/heart/daemon/provider-discovery.js +137 -0
  80. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  81. package/dist/heart/daemon/pulse.js +475 -0
  82. package/dist/heart/daemon/readiness-repair.js +365 -0
  83. package/dist/heart/daemon/run-hooks.js +39 -0
  84. package/dist/heart/daemon/runtime-logging.js +67 -16
  85. package/dist/heart/daemon/runtime-metadata.js +191 -0
  86. package/dist/heart/daemon/runtime-mode.js +67 -0
  87. package/dist/heart/daemon/safe-mode.js +161 -0
  88. package/dist/heart/daemon/sense-manager.js +431 -0
  89. package/dist/heart/daemon/session-id-resolver.js +131 -0
  90. package/dist/heart/daemon/skill-management-installer.js +94 -0
  91. package/dist/heart/daemon/socket-client.js +307 -0
  92. package/dist/heart/daemon/stale-bundle-prune.js +96 -0
  93. package/dist/heart/daemon/startup-tui.js +264 -0
  94. package/dist/heart/daemon/task-scheduler.js +3 -25
  95. package/dist/heart/daemon/terminal-ui.js +499 -0
  96. package/dist/heart/daemon/thoughts.js +524 -0
  97. package/dist/heart/daemon/up-progress.js +366 -0
  98. package/dist/heart/daemon/vault-items.js +56 -0
  99. package/dist/heart/delegation.js +62 -0
  100. package/dist/heart/habits/habit-migration.js +189 -0
  101. package/dist/heart/habits/habit-parser.js +140 -0
  102. package/dist/heart/habits/habit-runtime-state.js +100 -0
  103. package/dist/heart/habits/habit-scheduler.js +372 -0
  104. package/dist/heart/{daemon → hatch}/hatch-animation.js +10 -3
  105. package/dist/heart/{daemon → hatch}/hatch-flow.js +54 -136
  106. package/dist/heart/{daemon → hatch}/hatch-specialist.js +3 -3
  107. package/dist/heart/hatch/specialist-orchestrator.js +129 -0
  108. package/dist/heart/hatch/specialist-prompt.js +102 -0
  109. package/dist/heart/hatch/specialist-tools.js +306 -0
  110. package/dist/heart/identity.js +274 -61
  111. package/dist/heart/kept-notes.js +357 -0
  112. package/dist/heart/kicks.js +2 -20
  113. package/dist/heart/machine-identity.js +161 -0
  114. package/dist/heart/mail-import-discovery.js +353 -0
  115. package/dist/heart/mcp/mcp-server.js +653 -0
  116. package/dist/heart/migrate-config.js +100 -0
  117. package/dist/heart/model-capabilities.js +59 -0
  118. package/dist/heart/outlook/outlook-http-hooks.js +66 -0
  119. package/dist/heart/outlook/outlook-http-response.js +7 -0
  120. package/dist/heart/outlook/outlook-http-routes.js +244 -0
  121. package/dist/heart/outlook/outlook-http-static.js +103 -0
  122. package/dist/heart/outlook/outlook-http-transport.js +116 -0
  123. package/dist/heart/outlook/outlook-http.js +99 -0
  124. package/dist/heart/outlook/outlook-read.js +31 -0
  125. package/dist/heart/outlook/outlook-types.js +27 -0
  126. package/dist/heart/outlook/outlook-view.js +195 -0
  127. package/dist/heart/outlook/readers/agent-machine.js +382 -0
  128. package/dist/heart/outlook/readers/continuity-readers.js +336 -0
  129. package/dist/heart/outlook/readers/mail.js +362 -0
  130. package/dist/heart/outlook/readers/runtime-readers.js +644 -0
  131. package/dist/heart/outlook/readers/sessions.js +232 -0
  132. package/dist/heart/outlook/readers/shared.js +111 -0
  133. package/dist/heart/platform.js +81 -0
  134. package/dist/heart/progress-story.js +42 -0
  135. package/dist/heart/provider-attempt.js +134 -0
  136. package/dist/heart/provider-binding-resolver.js +255 -0
  137. package/dist/heart/provider-credentials.js +424 -0
  138. package/dist/heart/provider-failover.js +301 -0
  139. package/dist/heart/provider-models.js +81 -0
  140. package/dist/heart/provider-ping.js +262 -0
  141. package/dist/heart/provider-state.js +216 -0
  142. package/dist/heart/provider-visibility.js +188 -0
  143. package/dist/heart/providers/anthropic-token.js +131 -0
  144. package/dist/heart/providers/anthropic.js +202 -50
  145. package/dist/heart/providers/azure.js +104 -13
  146. package/dist/heart/providers/error-classification.js +63 -0
  147. package/dist/heart/providers/github-copilot.js +145 -0
  148. package/dist/heart/providers/minimax-vlm.js +189 -0
  149. package/dist/heart/providers/minimax.js +29 -7
  150. package/dist/heart/providers/openai-codex.js +63 -39
  151. package/dist/heart/runtime-capability-check.js +170 -0
  152. package/dist/heart/runtime-credentials.js +260 -0
  153. package/dist/heart/sense-truth.js +68 -0
  154. package/dist/heart/session-activity.js +190 -0
  155. package/dist/heart/session-events.js +1089 -0
  156. package/dist/heart/session-playback-cli-main.js +5 -0
  157. package/dist/heart/session-playback-cli.js +36 -0
  158. package/dist/heart/session-playback.js +231 -0
  159. package/dist/heart/session-transcript.js +167 -0
  160. package/dist/heart/start-of-turn-packet.js +345 -0
  161. package/dist/heart/streaming.js +129 -34
  162. package/dist/heart/sync.js +332 -0
  163. package/dist/heart/target-resolution.js +127 -0
  164. package/dist/heart/tempo.js +93 -0
  165. package/dist/heart/temporal-view.js +41 -0
  166. package/dist/heart/tool-activity-callbacks.js +36 -0
  167. package/dist/heart/tool-description.js +135 -0
  168. package/dist/heart/tool-friction.js +55 -0
  169. package/dist/heart/tool-loop.js +200 -0
  170. package/dist/heart/turn-context.js +372 -0
  171. package/dist/heart/turn-coordinator.js +28 -0
  172. package/dist/heart/versioning/ouro-bot-global-installer.js +128 -0
  173. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  174. package/dist/heart/versioning/ouro-path-installer.js +425 -0
  175. package/dist/heart/{daemon → versioning}/ouro-uti.js +11 -2
  176. package/dist/heart/versioning/ouro-version-manager.js +295 -0
  177. package/dist/heart/versioning/staged-restart.js +146 -0
  178. package/dist/heart/versioning/update-checker.js +115 -0
  179. package/dist/heart/versioning/update-hooks.js +142 -0
  180. package/dist/heart/versioning/wrapper-publish-guard.js +86 -0
  181. package/dist/mailroom/attention.js +167 -0
  182. package/dist/mailroom/autonomy.js +209 -0
  183. package/dist/mailroom/blob-store.js +606 -0
  184. package/dist/mailroom/core.js +672 -0
  185. package/dist/mailroom/entry.js +160 -0
  186. package/dist/mailroom/file-store.js +426 -0
  187. package/dist/mailroom/mbox-import.js +382 -0
  188. package/dist/mailroom/outbound.js +380 -0
  189. package/dist/mailroom/policy.js +263 -0
  190. package/dist/mailroom/reader.js +219 -0
  191. package/dist/mailroom/search-cache.js +182 -0
  192. package/dist/mailroom/search-relevance.js +319 -0
  193. package/dist/mailroom/smtp-ingress.js +176 -0
  194. package/dist/mailroom/source-state.js +176 -0
  195. package/dist/mailroom/thread.js +109 -0
  196. package/dist/mailroom/travel-extract.js +89 -0
  197. package/dist/mind/bundle-manifest.js +77 -1
  198. package/dist/mind/context.js +173 -94
  199. package/dist/mind/diary-integrity.js +60 -0
  200. package/dist/mind/{memory.js → diary.js} +84 -96
  201. package/dist/mind/embedding-provider.js +60 -0
  202. package/dist/mind/file-state.js +179 -0
  203. package/dist/mind/first-impressions.js +16 -2
  204. package/dist/mind/friends/channel.js +73 -0
  205. package/dist/mind/friends/group-context.js +144 -0
  206. package/dist/mind/friends/resolver.js +54 -2
  207. package/dist/mind/friends/store-file.js +58 -3
  208. package/dist/mind/friends/trust-explanation.js +74 -0
  209. package/dist/mind/friends/types.js +10 -2
  210. package/dist/mind/journal-index.js +161 -0
  211. package/dist/mind/note-search.js +268 -0
  212. package/dist/mind/obligation-steering.js +221 -0
  213. package/dist/mind/pending.js +76 -9
  214. package/dist/mind/phrases.js +1 -0
  215. package/dist/mind/prompt-refresh.js +3 -2
  216. package/dist/mind/prompt.js +1144 -117
  217. package/dist/mind/provenance-trust.js +26 -0
  218. package/dist/mind/scrutiny.js +173 -0
  219. package/dist/mind/token-estimate.js +8 -12
  220. package/dist/nerves/cli-logging.js +22 -3
  221. package/dist/nerves/coverage/audit-rules.js +15 -6
  222. package/dist/nerves/coverage/audit.js +28 -2
  223. package/dist/nerves/coverage/cli.js +1 -1
  224. package/dist/nerves/coverage/contract.js +5 -5
  225. package/dist/nerves/coverage/file-completeness.js +101 -5
  226. package/dist/nerves/coverage/run-artifacts.js +1 -1
  227. package/dist/nerves/event-buffer.js +111 -0
  228. package/dist/nerves/index.js +224 -4
  229. package/dist/nerves/observation.js +20 -0
  230. package/dist/nerves/redact.js +79 -0
  231. package/dist/nerves/runtime.js +5 -1
  232. package/dist/outlook-ui/assets/index-BPr5vNuM.css +1 -0
  233. package/dist/outlook-ui/assets/index-Cm51CY9W.js +61 -0
  234. package/dist/outlook-ui/index.html +15 -0
  235. package/dist/repertoire/ado-client.js +17 -56
  236. package/dist/repertoire/ado-semantic.js +11 -10
  237. package/dist/repertoire/api-client.js +97 -0
  238. package/dist/repertoire/bitwarden-store.js +774 -0
  239. package/dist/repertoire/bundle-templates.js +72 -0
  240. package/dist/repertoire/bw-installer.js +180 -0
  241. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  242. package/dist/repertoire/coding/context-pack.js +330 -0
  243. package/dist/repertoire/coding/feedback.js +301 -0
  244. package/dist/repertoire/coding/index.js +4 -1
  245. package/dist/repertoire/coding/manager.js +220 -13
  246. package/dist/repertoire/coding/spawner.js +58 -12
  247. package/dist/repertoire/coding/tools.js +209 -7
  248. package/dist/repertoire/commerce-errors.js +109 -0
  249. package/dist/repertoire/commerce-self-test.js +156 -0
  250. package/dist/repertoire/credential-access.js +111 -0
  251. package/dist/repertoire/data/ado-endpoints.json +188 -0
  252. package/dist/repertoire/duffel-client.js +185 -0
  253. package/dist/repertoire/github-client.js +14 -55
  254. package/dist/repertoire/graph-client.js +11 -52
  255. package/dist/repertoire/guardrails.js +396 -0
  256. package/dist/repertoire/mcp-client.js +255 -0
  257. package/dist/repertoire/mcp-manager.js +305 -0
  258. package/dist/repertoire/mcp-tools.js +63 -0
  259. package/dist/repertoire/shell-sessions.js +133 -0
  260. package/dist/repertoire/skills.js +15 -24
  261. package/dist/repertoire/stripe-client.js +131 -0
  262. package/dist/repertoire/tasks/board.js +43 -5
  263. package/dist/repertoire/tasks/fix.js +182 -0
  264. package/dist/repertoire/tasks/index.js +39 -13
  265. package/dist/repertoire/tasks/lifecycle.js +2 -2
  266. package/dist/repertoire/tasks/parser.js +3 -2
  267. package/dist/repertoire/tasks/scanner.js +194 -37
  268. package/dist/repertoire/tasks/transitions.js +16 -79
  269. package/dist/repertoire/tool-results.js +29 -0
  270. package/dist/repertoire/tools-attachments.js +317 -0
  271. package/dist/repertoire/tools-base.js +49 -707
  272. package/dist/repertoire/tools-bluebubbles.js +94 -0
  273. package/dist/repertoire/tools-bridge.js +141 -0
  274. package/dist/repertoire/tools-bundle.js +984 -0
  275. package/dist/repertoire/tools-config.js +185 -0
  276. package/dist/repertoire/tools-continuity.js +248 -0
  277. package/dist/repertoire/tools-credential.js +381 -0
  278. package/dist/repertoire/tools-files.js +342 -0
  279. package/dist/repertoire/tools-flight.js +224 -0
  280. package/dist/repertoire/tools-flow.js +105 -0
  281. package/dist/repertoire/tools-github.js +1 -7
  282. package/dist/repertoire/tools-mail.js +1377 -0
  283. package/dist/repertoire/tools-notes.js +376 -0
  284. package/dist/repertoire/tools-session.js +749 -0
  285. package/dist/repertoire/tools-shell.js +120 -0
  286. package/dist/repertoire/tools-stripe.js +180 -0
  287. package/dist/repertoire/tools-surface.js +243 -0
  288. package/dist/repertoire/tools-teams.js +64 -61
  289. package/dist/repertoire/tools-travel.js +125 -0
  290. package/dist/repertoire/tools-trip.js +356 -0
  291. package/dist/repertoire/tools-user-profile.js +144 -0
  292. package/dist/repertoire/tools-vault.js +40 -0
  293. package/dist/repertoire/tools.js +149 -98
  294. package/dist/repertoire/travel-api-client.js +360 -0
  295. package/dist/repertoire/user-profile.js +131 -0
  296. package/dist/repertoire/vault-setup.js +246 -0
  297. package/dist/repertoire/vault-unlock.js +561 -0
  298. package/dist/scripts/claude-code-hook.js +41 -0
  299. package/dist/scripts/claude-code-stop-hook.js +47 -0
  300. package/dist/senses/attention-queue.js +116 -0
  301. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  302. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  303. package/dist/senses/bluebubbles/client.js +685 -0
  304. package/dist/senses/bluebubbles/entry.js +73 -0
  305. package/dist/senses/bluebubbles/inbound-log.js +126 -0
  306. package/dist/senses/bluebubbles/index.js +1881 -0
  307. package/dist/senses/bluebubbles/media.js +389 -0
  308. package/dist/senses/bluebubbles/model.js +282 -0
  309. package/dist/senses/bluebubbles/mutation-log.js +116 -0
  310. package/dist/senses/bluebubbles/processed-log.js +111 -0
  311. package/dist/senses/bluebubbles/replay.js +129 -0
  312. package/dist/senses/bluebubbles/runtime-state.js +109 -0
  313. package/dist/senses/bluebubbles/session-cleanup.js +72 -0
  314. package/dist/senses/cli/bracketed-paste.js +82 -0
  315. package/dist/senses/cli/image-paste.js +287 -0
  316. package/dist/senses/cli/image-ref-navigation.js +75 -0
  317. package/dist/senses/cli/ink-app.js +156 -0
  318. package/dist/senses/cli/inline-diff.js +64 -0
  319. package/dist/senses/cli/input-keys.js +174 -0
  320. package/dist/senses/cli/kill-ring.js +86 -0
  321. package/dist/senses/cli/message-list.js +51 -0
  322. package/dist/senses/cli/ouro-tui.js +605 -0
  323. package/dist/senses/cli/spinner-imperative.js +135 -0
  324. package/dist/senses/cli/spinner.js +101 -0
  325. package/dist/senses/cli/status-line.js +60 -0
  326. package/dist/senses/cli/streaming-markdown.js +526 -0
  327. package/dist/senses/cli/tool-display.js +83 -0
  328. package/dist/senses/cli/tool-render.js +85 -0
  329. package/dist/senses/cli/tui-store.js +240 -0
  330. package/dist/senses/cli/virtual-list.js +35 -0
  331. package/dist/senses/cli-entry.js +60 -8
  332. package/dist/senses/cli-layout.js +187 -0
  333. package/dist/senses/cli.js +768 -264
  334. package/dist/senses/commands.js +66 -3
  335. package/dist/senses/continuity.js +94 -0
  336. package/dist/senses/habit-turn-message.js +108 -0
  337. package/dist/senses/inner-dialog-worker.js +199 -16
  338. package/dist/senses/inner-dialog.js +640 -91
  339. package/dist/senses/mail-entry.js +66 -0
  340. package/dist/senses/mail.js +379 -0
  341. package/dist/senses/pipeline.js +665 -0
  342. package/dist/senses/proactive-content-guard.js +51 -0
  343. package/dist/senses/shared-turn.js +248 -0
  344. package/dist/senses/surface-tool.js +68 -0
  345. package/dist/senses/teams-entry.js +60 -8
  346. package/dist/senses/teams.js +844 -197
  347. package/dist/senses/trust-gate.js +207 -2
  348. package/dist/trips/core.js +138 -0
  349. package/dist/trips/store.js +146 -0
  350. package/package.json +47 -6
  351. package/skills/agent-commerce.md +106 -0
  352. package/skills/browser-navigation.md +117 -0
  353. package/skills/commerce-setup-guide.md +116 -0
  354. package/skills/commerce-setup.md +84 -0
  355. package/skills/configure-dev-tools.md +101 -0
  356. package/skills/travel-planning.md +138 -0
  357. package/AdoptionSpecialist.ouro/agent.json +0 -20
  358. package/AdoptionSpecialist.ouro/psyche/SOUL.md +0 -22
  359. package/dist/heart/daemon/specialist-orchestrator.js +0 -160
  360. package/dist/heart/daemon/specialist-prompt.js +0 -40
  361. package/dist/heart/daemon/specialist-session.js +0 -142
  362. package/dist/heart/daemon/specialist-tools.js +0 -128
  363. package/dist/heart/daemon/subagent-installer.js +0 -125
  364. package/dist/inner-worker-entry.js +0 -4
  365. package/dist/mind/associative-recall.js +0 -197
  366. package/subagents/README.md +0 -73
  367. package/subagents/work-doer.md +0 -233
  368. package/subagents/work-merger.md +0 -624
  369. package/subagents/work-planner.md +0 -373
  370. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  371. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  372. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  373. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  374. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  375. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  376. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  377. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  378. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  379. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  380. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
@@ -1,96 +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
- exports.isTransientError = isTransientError;
12
- exports.classifyTransientError = classifyTransientError;
12
+ exports.repairOrphanedToolCalls = repairOrphanedToolCalls;
13
13
  exports.runAgent = runAgent;
14
14
  const config_1 = require("./config");
15
15
  const identity_1 = require("./identity");
16
16
  const tools_1 = require("../repertoire/tools");
17
17
  const channel_1 = require("../mind/friends/channel");
18
- // Kick detection preserved but disabled — see comment in agent loop below.
19
- // import { detectKick } from "./kicks";
20
- // import type { KickReason } from "./kicks";
18
+ const tools_2 = require("../repertoire/tools");
21
19
  const runtime_1 = require("../nerves/runtime");
22
20
  const context_1 = require("../mind/context");
23
21
  const prompt_1 = require("../mind/prompt");
24
- const associative_recall_1 = require("../mind/associative-recall");
22
+ const kept_notes_1 = require("./kept-notes");
25
23
  const anthropic_1 = require("./providers/anthropic");
26
24
  const azure_1 = require("./providers/azure");
27
25
  const minimax_1 = require("./providers/minimax");
28
26
  const openai_codex_1 = require("./providers/openai-codex");
29
- let _providerRuntime = null;
30
- function createProviderRegistry() {
31
- const factories = {
32
- azure: azure_1.createAzureProviderRuntime,
33
- anthropic: anthropic_1.createAnthropicProviderRuntime,
34
- minimax: minimax_1.createMinimaxProviderRuntime,
35
- "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,
36
82
  };
83
+ }
84
+ function createProviderRegistry() {
37
85
  return {
38
- resolve() {
39
- const provider = (0, identity_1.loadAgentConfig)().provider;
40
- 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
+ }
41
100
  },
42
101
  };
43
102
  }
44
- function getProviderRuntime() {
45
- if (!_providerRuntime) {
46
- try {
47
- _providerRuntime = createProviderRegistry().resolve();
48
- }
49
- catch (error) {
50
- const msg = error instanceof Error ? error.message : String(error);
51
- (0, runtime_1.emitNervesEvent)({
52
- level: "error",
53
- event: "engine.provider_init_error",
54
- component: "engine",
55
- message: msg,
56
- meta: {},
57
- });
58
- // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
59
- console.error(`\n[fatal] ${msg}\n`);
60
- process.exit(1);
61
- throw new Error("unreachable");
62
- }
63
- if (!_providerRuntime) {
64
- (0, runtime_1.emitNervesEvent)({
65
- level: "error",
66
- event: "engine.provider_init_error",
67
- component: "engine",
68
- message: "provider runtime could not be initialized.",
69
- meta: {},
70
- });
71
- process.exit(1);
72
- 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;
73
110
  }
74
111
  }
75
- 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;
76
136
  }
77
137
  /**
78
- * Clear the cached provider runtime so the next call to getProviderRuntime()
79
- * re-creates it from current config. Used by the adoption specialist to
80
- * 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.
81
141
  */
82
142
  function resetProviderRuntime() {
83
- _providerRuntime = null;
143
+ _providerRuntimes.human = null;
144
+ _providerRuntimes.agent = null;
84
145
  }
85
- function getModel() {
86
- return getProviderRuntime().model;
146
+ function getModel(facing = "human") {
147
+ return resolveRuntimeProviderBinding(facing).model;
87
148
  }
88
- function getProvider() {
89
- return getProviderRuntime().id;
149
+ function getProvider(facing = "human") {
150
+ return resolveRuntimeProviderBinding(facing).provider;
90
151
  }
91
- function createSummarize() {
152
+ function createSummarize(facing = "human") {
92
153
  return async (transcript, instruction) => {
93
- const runtime = getProviderRuntime();
154
+ const runtime = await getProviderRuntime(facing);
94
155
  const client = runtime.client;
95
156
  const response = await client.chat.completions.create({
96
157
  model: runtime.model,
@@ -103,34 +164,166 @@ function createSummarize() {
103
164
  return response.choices?.[0]?.message?.content ?? transcript;
104
165
  };
105
166
  }
106
- function getProviderDisplayLabel() {
107
- const model = getModel();
167
+ function getProviderDisplayLabel(facing = "human") {
168
+ const binding = resolveRuntimeProviderBinding(facing);
169
+ const provider = binding.provider;
170
+ const model = binding.model || "unknown";
108
171
  const providerLabelBuilders = {
109
- azure: () => `azure openai (${(0, config_1.getAzureConfig)().deployment || "default"}, model: ${model})`,
172
+ azure: () => {
173
+ return `azure openai (model: ${model})`;
174
+ },
110
175
  anthropic: () => `anthropic (${model})`,
111
176
  minimax: () => `minimax (${model})`,
112
177
  "openai-codex": () => `openai codex (${model})`,
178
+ /* v8 ignore next -- branch: tested via display label unit test @preserve */
179
+ "github-copilot": () => `github copilot (${model})`,
180
+ };
181
+ return providerLabelBuilders[provider]();
182
+ }
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) {
221
+ try {
222
+ const parsed = JSON.parse(argumentsText);
223
+ if (typeof parsed === "string") {
224
+ return { answer: parsed };
225
+ }
226
+ if (!parsed || typeof parsed !== "object") {
227
+ return {};
228
+ }
229
+ const answer = typeof parsed.answer === "string" ? parsed.answer : undefined;
230
+ const rawIntent = parsed.intent;
231
+ const intent = rawIntent === "complete" || rawIntent === "blocked" || rawIntent === "direct_reply"
232
+ ? rawIntent
233
+ : undefined;
234
+ return { answer, intent };
235
+ }
236
+ catch {
237
+ return {};
238
+ }
239
+ }
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: "{}",
113
282
  };
114
- return providerLabelBuilders[getProvider()]();
115
283
  }
116
- // Re-export tools, execTool, summarizeArgs from ./tools for backward compat
117
- var tools_2 = require("../repertoire/tools");
118
- Object.defineProperty(exports, "tools", { enumerable: true, get: function () { return tools_2.tools; } });
119
- Object.defineProperty(exports, "execTool", { enumerable: true, get: function () { return tools_2.execTool; } });
120
- Object.defineProperty(exports, "summarizeArgs", { enumerable: true, get: function () { return tools_2.summarizeArgs; } });
121
- Object.defineProperty(exports, "getToolsForChannel", { enumerable: true, get: function () { return tools_2.getToolsForChannel; } });
122
- // Re-export streaming functions for backward compat
123
- var streaming_1 = require("./streaming");
124
- Object.defineProperty(exports, "streamChatCompletion", { enumerable: true, get: function () { return streaming_1.streamChatCompletion; } });
125
- Object.defineProperty(exports, "streamResponsesApi", { enumerable: true, get: function () { return streaming_1.streamResponsesApi; } });
126
- Object.defineProperty(exports, "toResponsesInput", { enumerable: true, get: function () { return streaming_1.toResponsesInput; } });
127
- Object.defineProperty(exports, "toResponsesTools", { enumerable: true, get: function () { return streaming_1.toResponsesTools; } });
128
- // Re-export prompt functions for backward compat
129
- var prompt_2 = require("../mind/prompt");
130
- Object.defineProperty(exports, "buildSystem", { enumerable: true, get: function () { return prompt_2.buildSystem; } });
131
- // Re-export kick utilities for backward compat
132
- var kicks_1 = require("./kicks");
133
- Object.defineProperty(exports, "hasToolIntent", { enumerable: true, get: function () { return kicks_1.hasToolIntent; } });
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
310
+ if (mustResolveBeforeHandoff && !intent) {
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.";
312
+ }
313
+ // 4. mustResolveBeforeHandoff + direct_reply without follow-up
314
+ if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
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.";
320
+ }
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;
326
+ }
134
327
  function upsertSystemPrompt(messages, systemText) {
135
328
  const systemMessage = { role: "system", content: systemText };
136
329
  if (messages[0]?.role === "system") {
@@ -160,6 +353,83 @@ function stripLastToolCalls(messages) {
160
353
  }
161
354
  }
162
355
  }
356
+ // Roles that end a tool-result scan. When scanning forward from an assistant
357
+ // message, stop at the next assistant or user message (tool results must be
358
+ // adjacent to their originating assistant message).
359
+ const TOOL_SCAN_BOUNDARY_ROLES = new Set(["assistant", "user"]);
360
+ // Repair orphaned tool_calls and tool results anywhere in the message history.
361
+ // 1. If an assistant message has tool_calls but missing tool results, inject synthetic error results.
362
+ // 2. If a tool result's tool_call_id doesn't match any tool_calls in a preceding assistant message, remove it.
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.
371
+ function repairOrphanedToolCalls(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];
378
+ if (msg.role === "assistant") {
379
+ const asst = msg;
380
+ if (asst.tool_calls) {
381
+ for (const tc of asst.tool_calls)
382
+ seenCallIds.add(tc.id);
383
+ }
384
+ continue;
385
+ }
386
+ if (msg.role === "tool") {
387
+ const toolMsg = msg;
388
+ if (!seenCallIds.has(toolMsg.tool_call_id)) {
389
+ removeIndices.push(i);
390
+ }
391
+ }
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
+ }
397
+ // Pass 3: inject synthetic results for tool_calls missing their tool results
398
+ for (let i = 0; i < messages.length; i++) {
399
+ const msg = messages[i];
400
+ if (msg.role !== "assistant")
401
+ continue;
402
+ const asst = msg;
403
+ if (!asst.tool_calls || asst.tool_calls.length === 0)
404
+ continue;
405
+ // Collect tool result IDs that follow this assistant message
406
+ const resultIds = new Set();
407
+ for (let j = i + 1; j < messages.length; j++) {
408
+ const following = messages[j];
409
+ if (following.role === "tool") {
410
+ resultIds.add(following.tool_call_id);
411
+ }
412
+ else if (TOOL_SCAN_BOUNDARY_ROLES.has(following.role)) {
413
+ break;
414
+ }
415
+ }
416
+ const missing = asst.tool_calls.filter((tc) => !resultIds.has(tc.id));
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.
421
+ const syntheticResults = missing.map((tc) => ({
422
+ role: "tool",
423
+ tool_call_id: tc.id,
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.",
425
+ }));
426
+ let insertAt = i + 1;
427
+ while (insertAt < messages.length && messages[insertAt].role === "tool")
428
+ insertAt++;
429
+ messages.splice(insertAt, 0, ...syntheticResults);
430
+ }
431
+ }
432
+ }
163
433
  // Detect context overflow errors from Azure or MiniMax
164
434
  function isContextOverflow(err) {
165
435
  if (!(err instanceof Error))
@@ -174,49 +444,67 @@ function isContextOverflow(err) {
174
444
  return true;
175
445
  return false;
176
446
  }
177
- // Detect transient network errors worth retrying
178
- function isTransientError(err) {
179
- if (!(err instanceof Error))
180
- return false;
181
- const msg = err.message || "";
182
- const code = err.code || "";
183
- // Node.js network error codes
184
- if (["ECONNRESET", "ECONNREFUSED", "ENOTFOUND", "ETIMEDOUT", "EPIPE",
185
- "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "ECONNABORTED"].includes(code))
186
- return true;
187
- // OpenAI SDK / fetch errors
188
- if (msg.includes("fetch failed"))
189
- return true;
190
- if (msg.includes("network") && !msg.includes("context"))
191
- return true;
192
- if (msg.includes("ECONNRESET") || msg.includes("ETIMEDOUT"))
193
- return true;
194
- if (msg.includes("socket hang up"))
195
- return true;
196
- if (msg.includes("getaddrinfo"))
197
- return true;
198
- // HTTP 429 / 500 / 502 / 503 / 504
199
- const status = err.status;
200
- if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504)
201
- return true;
202
- 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
+ });
203
477
  }
204
- function classifyTransientError(err) {
205
- if (!(err instanceof Error))
206
- return "unknown error";
207
- const status = err.status;
208
- if (status === 429)
209
- return "rate limited";
210
- if (status === 401 || status === 403)
211
- return "auth error";
212
- if (status && status >= 500)
213
- return "server error";
214
- 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");
215
504
  }
216
- const MAX_RETRIES = 3;
217
- const RETRY_BASE_MS = 2000;
218
505
  async function runAgent(messages, callbacks, channel, signal, options) {
219
- const providerRuntime = getProviderRuntime();
506
+ const facing = (0, channel_1.channelToFacing)(channel);
507
+ let providerRuntime = await getProviderRuntime(facing);
220
508
  const provider = providerRuntime.id;
221
509
  const toolChoiceRequired = options?.toolChoiceRequired ?? true;
222
510
  const traceId = options?.traceId;
@@ -240,10 +528,17 @@ async function runAgent(messages, callbacks, channel, signal, options) {
240
528
  // Refresh system prompt at start of each turn when channel is provided.
241
529
  // If refresh fails, keep existing system prompt (or inject a minimal safe fallback)
242
530
  // so turn execution remains consistent and non-fatal.
531
+ let structuredSystemPrompt;
243
532
  if (channel) {
244
533
  try {
245
- const refreshed = await (0, prompt_1.buildSystem)(channel, options, currentContext);
246
- 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));
247
542
  }
248
543
  catch (error) {
249
544
  const hadExistingSystemPrompt = messages[0]?.role === "system" && typeof messages[0].content === "string";
@@ -264,32 +559,129 @@ async function runAgent(messages, callbacks, channel, signal, options) {
264
559
  });
265
560
  }
266
561
  }
267
- await (0, associative_recall_1.injectAssociativeRecall)(messages);
268
- // kickCount and lastKickReason preserved but unused while kick detection is disabled.
269
- // let kickCount = 0;
270
- // let lastKickReason: KickReason | null = null;
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
+ }
271
571
  let done = false;
272
572
  let lastUsage;
273
573
  let overflowRetried = false;
274
- let retryCount = 0;
574
+ let outcome = "settled";
575
+ let completion;
576
+ let terminalError;
577
+ let terminalErrorClassification;
578
+ let sawSteeringFollowUp = false;
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
+ };
275
632
  // Prevent MaxListenersExceeded warning — each iteration adds a listener
276
633
  try {
277
634
  require("events").setMaxListeners(50, signal);
278
635
  }
279
636
  catch { /* unsupported */ }
280
637
  const toolPreferences = currentContext?.friend?.toolPreferences;
281
- const baseTools = (0, tools_1.getToolsForChannel)(channel ? (0, channel_1.getChannelCapabilities)(channel) : undefined, toolPreferences && Object.keys(toolPreferences).length > 0 ? toolPreferences : undefined);
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;
282
648
  // Rebase provider-owned turn state from canonical messages at user-turn start.
283
649
  // This prevents stale provider caches from replaying prior-turn context.
284
650
  providerRuntime.resetTurnState(messages);
285
651
  while (!done) {
286
- // When toolChoiceRequired is true (the default), include final_answer
287
- // so the model can signal completion. With tool_choice: required, the
288
- // model must call a tool every turn final_answer is how it exits.
289
- // Overridable via options.toolChoiceRequired = false (e.g. CLI).
290
- 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
+ ];
291
671
  const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
292
672
  if (steeringFollowUps.length > 0) {
673
+ const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
674
+ if (hasSupersedingFollowUp) {
675
+ mustResolveBeforeHandoffActive = false;
676
+ options?.setMustResolveBeforeHandoff?.(false);
677
+ outcome = "superseded";
678
+ break;
679
+ }
680
+ if (steeringFollowUps.some((followUp) => followUp.effect === "set_no_handoff")) {
681
+ mustResolveBeforeHandoffActive = true;
682
+ options?.setMustResolveBeforeHandoff?.(true);
683
+ }
684
+ sawSteeringFollowUp = true;
293
685
  for (const followUp of steeringFollowUps) {
294
686
  messages.push({ role: "user", content: followUp.text });
295
687
  }
@@ -297,28 +689,126 @@ async function runAgent(messages, callbacks, channel, signal, options) {
297
689
  }
298
690
  // Yield so pending I/O (stdin Ctrl-C) can be processed between iterations
299
691
  await new Promise((r) => setImmediate(r));
300
- if (signal?.aborted)
692
+ if (signal?.aborted) {
693
+ outcome = "aborted";
301
694
  break;
695
+ }
302
696
  try {
303
- callbacks.onModelStart();
304
- const result = await providerRuntime.streamTurn({
305
- messages,
306
- activeTools,
307
- callbacks,
308
- signal,
309
- traceId,
310
- 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
+ },
311
769
  });
770
+ if (!attempt.ok) {
771
+ finishTerminalProviderError(attempt.error, attempt.classification);
772
+ continue;
773
+ }
774
+ const result = attempt.value;
312
775
  // Track usage from the latest API call
313
776
  if (result.usage)
314
777
  lastUsage = result.usage;
315
- retryCount = 0; // reset on success
316
778
  // SHARED: build CC-format assistant message from TurnResult
317
779
  const msg = {
318
780
  role: "assistant",
319
781
  };
320
- if (result.content)
321
- 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
+ }
322
812
  if (result.toolCalls.length)
323
813
  msg.tool_calls = result.toolCalls.map((tc) => ({
324
814
  id: tc.id,
@@ -331,52 +821,115 @@ async function runAgent(messages, callbacks, channel, signal, options) {
331
821
  if (reasoningItems.length > 0) {
332
822
  msg._reasoning_items = reasoningItems;
333
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;
334
845
  if (!result.toolCalls.length) {
335
- // Kick detection is disabled while tool_choice: required + final_answer
336
- // is the primary loop control mechanism. The model should never reach
337
- // this path (tool_choice: required forces a tool call), but if it does,
338
- // accept the response as-is rather than risk false-positive kicks.
339
- //
340
- // Preserved for future use re-enable by uncommenting:
341
- // const kick = detectKick(result.content, options);
342
- // if (kick) {
343
- // kickCount++;
344
- // lastKickReason = kick.reason;
345
- // callbacks.onKick?.();
346
- // const kickContent = result.content
347
- // ? result.content + "\n\n" + kick.message
348
- // : kick.message;
349
- // messages.push({ role: "assistant", content: kickContent });
350
- // providerRuntime.resetTurnState(messages);
351
- // continue;
352
- // }
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.
353
876
  messages.push(msg);
354
877
  done = true;
355
878
  }
356
879
  else {
357
- // Check for final_answer sole call: intercept before tool execution
358
- const isSoleFinalAnswer = result.toolCalls.length === 1 && result.toolCalls[0].name === "final_answer";
359
- if (isSoleFinalAnswer) {
360
- // Extract answer from the tool call arguments.
361
- // Supports: {"answer":"text"}, "text" (JSON string), retry on failure.
362
- let answer;
363
- try {
364
- const parsed = JSON.parse(result.toolCalls[0].arguments);
365
- if (typeof parsed === "string") {
366
- answer = parsed;
367
- }
368
- else if (parsed.answer != null) {
369
- answer = parsed.answer;
370
- }
371
- // else: valid JSON but no answer field — answer stays undefined (retry)
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);
372
887
  }
373
888
  catch {
374
- // JSON parsing failed (e.g. truncated output) — answer stays undefined (retry)
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;
375
902
  }
376
- if (answer != null) {
377
- if (result.finalAnswerStreamed) {
903
+ // Extract answer from the tool call arguments.
904
+ // Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
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;
919
+ const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
920
+ const validTerminalIntent = intent === "complete" || intent === "blocked";
921
+ const validClosure = deliveredAnswer != null
922
+ && !retryError
923
+ && (!mustResolveBeforeHandoffActive || validDirectReply || validTerminalIntent);
924
+ if (validClosure) {
925
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
926
+ completion = {
927
+ answer: deliveredAnswer,
928
+ intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
929
+ };
930
+ if (result.settleStreamed) {
378
931
  // The streaming layer already parsed and emitted the answer
379
- // progressively via FinalAnswerParser. Skip clearing and
932
+ // progressively via SettleParser. Skip clearing and
380
933
  // re-emitting to avoid double-delivery.
381
934
  }
382
935
  else {
@@ -384,37 +937,126 @@ async function runAgent(messages, callbacks, channel, signal, options) {
384
937
  callbacks.onClearText?.();
385
938
  // Emit the answer through the callback pipeline so channels receive it.
386
939
  // Never truncate -- channel adapters handle splitting long messages.
387
- callbacks.onTextChunk(answer);
940
+ callbacks.onTextChunk(deliveredAnswer);
388
941
  }
389
- // Keep the full assistant message (with tool_calls) for debuggability,
390
- // plus a synthetic tool response so the conversation stays valid on resume.
391
942
  messages.push(msg);
392
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: "(delivered)" });
393
- providerRuntime.appendToolOutput(result.toolCalls[0].id, "(delivered)");
394
- done = true;
943
+ if (validDirectReply) {
944
+ const resumeWork = "direct reply delivered. resume the unresolved obligation now and keep working until you can finish or clearly report that you are blocked.";
945
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: resumeWork });
946
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, resumeWork);
947
+ }
948
+ else {
949
+ const delivered = "(delivered)";
950
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
951
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
952
+ outcome = intent === "blocked" ? "blocked" : "settled";
953
+ done = true;
954
+ }
395
955
  }
396
956
  else {
397
- // Answer is undefined -- the model's final_answer was incomplete or
957
+ // Answer is undefined -- the model's settle was incomplete or
398
958
  // malformed. Clear any partial streamed text or noise, then push the
399
959
  // assistant msg + error tool result and let the model try again.
960
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
400
961
  callbacks.onClearText?.();
401
- const retryError = "your final_answer was incomplete or malformed. call final_answer again with your complete response.";
402
962
  messages.push(msg);
403
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: retryError });
404
- 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);
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;
405
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;
406
1048
  continue;
407
1049
  }
408
1050
  messages.push(msg);
409
- // SHARED: execute tools (final_answer in mixed calls is rejected inline)
1051
+ // Execute tools (sole-call tools in mixed calls are rejected inline)
410
1052
  for (const tc of result.toolCalls) {
411
1053
  if (signal?.aborted)
412
1054
  break;
413
- // Intercept final_answer in mixed call: reject it
414
- if (tc.name === "final_answer") {
415
- const rejection = "rejected: final_answer must be the only tool call. Finish your work first, then call final_answer alone.";
416
- messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
417
- 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);
418
1060
  continue;
419
1061
  }
420
1062
  let args = {};
@@ -424,93 +1066,195 @@ async function runAgent(messages, callbacks, channel, signal, options) {
424
1066
  catch {
425
1067
  /* ignore */
426
1068
  }
427
- const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
428
- // Confirmation check for mutate tools
429
- if ((0, tools_1.isConfirmationRequired)(tc.name) && !options?.skipConfirmation) {
430
- let decision = "denied";
431
- if (callbacks.onConfirmAction) {
432
- 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
+ });
433
1192
  }
434
- if (decision !== "confirmed") {
435
- const cancelled = "Action cancelled by user.";
436
- callbacks.onToolStart(tc.name, args);
437
- callbacks.onToolEnd(tc.name, argSummary, false);
438
- messages.push({ role: "tool", tool_call_id: tc.id, content: cancelled });
439
- providerRuntime.appendToolOutput(tc.id, cancelled);
440
- continue;
1193
+ catch (error) {
1194
+ toolResult = error instanceof Error ? error.message : String(error);
441
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;
442
1219
  }
443
1220
  callbacks.onToolStart(tc.name, args);
444
1221
  let toolResult;
445
1222
  let success;
446
1223
  try {
447
- toolResult = await (0, tools_1.execTool)(tc.name, args, options?.toolContext);
1224
+ const execToolFn = options?.execTool ?? tools_1.execTool;
1225
+ toolResult = await execToolFn(tc.name, args, augmentedToolContext ?? options?.toolContext);
448
1226
  success = true;
449
1227
  }
450
1228
  catch (e) {
451
1229
  toolResult = `error: ${e}`;
452
1230
  success = false;
453
1231
  }
454
- 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);
455
1235
  messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
456
1236
  providerRuntime.appendToolOutput(tc.id, toolResult);
1237
+ callbacks.onToolResult?.(messages);
457
1238
  }
458
1239
  }
459
1240
  }
460
1241
  catch (e) {
461
1242
  // Abort is not an error — just stop cleanly
462
- if (signal?.aborted) {
1243
+ if (e instanceof provider_attempt_1.ProviderAttemptAbortError || signal?.aborted) {
463
1244
  stripLastToolCalls(messages);
1245
+ outcome = "aborted";
464
1246
  break;
465
1247
  }
466
- // Context overflow: trim aggressively and retry once
467
- if (isContextOverflow(e) && !overflowRetried) {
468
- overflowRetried = true;
469
- stripLastToolCalls(messages);
470
- const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
471
- const trimmed = (0, context_1.trimMessages)(messages, maxTokens, contextMargin, maxTokens * 2);
472
- messages.splice(0, messages.length, ...trimmed);
473
- providerRuntime.resetTurnState(messages);
474
- callbacks.onError(new Error("context trimmed, retrying..."), "transient");
475
- 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);
476
1252
  }
477
- // Transient errors: retry with exponential backoff
478
- if (isTransientError(e) && retryCount < MAX_RETRIES) {
479
- retryCount++;
480
- const delay = RETRY_BASE_MS * Math.pow(2, retryCount - 1);
481
- const cause = classifyTransientError(e);
482
- callbacks.onError(new Error(`${cause}, retrying in ${delay / 1000}s (${retryCount}/${MAX_RETRIES})...`), "transient");
483
- // Wait with abort support
484
- const aborted = await new Promise((resolve) => {
485
- const timer = setTimeout(() => resolve(false), delay);
486
- if (signal) {
487
- const onAbort = () => { clearTimeout(timer); resolve(true); };
488
- if (signal.aborted) {
489
- clearTimeout(timer);
490
- resolve(true);
491
- return;
492
- }
493
- signal.addEventListener("abort", onAbort, { once: true });
494
- }
495
- });
496
- if (aborted) {
497
- stripLastToolCalls(messages);
498
- break;
499
- }
500
- providerRuntime.resetTurnState(messages);
501
- continue;
1253
+ catch {
1254
+ /* v8 ignore next -- defensive: classifyError should not throw @preserve */
1255
+ providerClassification = "unknown";
502
1256
  }
503
- callbacks.onError(e instanceof Error ? e : new Error(String(e)), "terminal");
504
- (0, runtime_1.emitNervesEvent)({
505
- level: "error",
506
- event: "engine.error",
507
- trace_id: traceId,
508
- component: "engine",
509
- message: e instanceof Error ? e.message : String(e),
510
- meta: {},
511
- });
512
- stripLastToolCalls(messages);
513
- done = true;
1257
+ finishTerminalProviderError(errorForClassification, providerClassification);
514
1258
  }
515
1259
  }
516
1260
  (0, runtime_1.emitNervesEvent)({
@@ -518,7 +1262,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
518
1262
  trace_id: traceId,
519
1263
  component: "engine",
520
1264
  message: "runAgent turn completed",
521
- meta: { done },
1265
+ meta: { done, sawPonder, sawQuerySession, sawBridgeManage },
522
1266
  });
523
- return { usage: lastUsage };
1267
+ return {
1268
+ usage: lastUsage,
1269
+ outcome,
1270
+ completion,
1271
+ ...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
1272
+ };
524
1273
  }