@ouro.bot/cli 0.1.0-alpha.7 → 0.1.0-alpha.700

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