@ouro.bot/cli 0.1.0-alpha.73 → 0.1.0-alpha.730

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 (527) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +146 -23
  3. package/RepairGuide.ouro/agent.json +5 -0
  4. package/RepairGuide.ouro/psyche/IDENTITY.md +19 -0
  5. package/RepairGuide.ouro/psyche/SOUL.md +55 -0
  6. package/RepairGuide.ouro/skills/diagnose-broken-remote.md +63 -0
  7. package/RepairGuide.ouro/skills/diagnose-stacked-typed-issues.md +35 -0
  8. package/RepairGuide.ouro/skills/diagnose-sync-blocked.md +54 -0
  9. package/RepairGuide.ouro/skills/diagnose-vault-expired.md +60 -0
  10. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +4 -2
  11. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +2 -2
  12. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  13. package/assets/bluebubbles-host +264 -0
  14. package/changelog.json +4633 -14
  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 +1034 -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 +874 -43
  44. package/dist/heart/agent-entry.js +190 -3
  45. package/dist/heart/approval-store.js +791 -0
  46. package/dist/heart/attachments/image-normalize.js +194 -0
  47. package/dist/heart/attachments/materialize.js +97 -0
  48. package/dist/heart/attachments/originals.js +88 -0
  49. package/dist/heart/attachments/render.js +29 -0
  50. package/dist/heart/attachments/sources/bluebubbles.js +156 -0
  51. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  52. package/dist/heart/attachments/sources/index.js +16 -0
  53. package/dist/heart/attachments/store.js +103 -0
  54. package/dist/heart/attachments/types.js +93 -0
  55. package/dist/heart/auth/auth-flow.js +479 -0
  56. package/dist/heart/autonomy-budget.js +434 -0
  57. package/dist/heart/awaiting/await-alert.js +146 -0
  58. package/dist/heart/awaiting/await-expiry.js +108 -0
  59. package/dist/heart/awaiting/await-loader.js +91 -0
  60. package/dist/heart/awaiting/await-parser.js +141 -0
  61. package/dist/heart/awaiting/await-runtime-state.js +100 -0
  62. package/dist/heart/awaiting/await-scheduler.js +378 -0
  63. package/dist/heart/background-operations.js +281 -0
  64. package/dist/heart/bridges/manager.js +137 -17
  65. package/dist/heart/bridges/store.js +14 -2
  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 +120 -129
  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 +1763 -320
  73. package/dist/heart/cross-chat-delivery.js +8 -22
  74. package/dist/heart/daemon/agent-config-check.js +451 -0
  75. package/dist/heart/daemon/agent-discovery.js +185 -3
  76. package/dist/heart/daemon/agent-service.js +542 -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-cli-integration.js +71 -0
  80. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  81. package/dist/heart/daemon/bluebubbles-host-protocol.js +433 -0
  82. package/dist/heart/daemon/bluebubbles-host.js +273 -0
  83. package/dist/heart/daemon/boot-sync-probe.js +197 -0
  84. package/dist/heart/daemon/cadence.js +180 -0
  85. package/dist/heart/daemon/cli-defaults.js +832 -0
  86. package/dist/heart/daemon/cli-desk.js +322 -0
  87. package/dist/heart/daemon/cli-exec.js +8586 -0
  88. package/dist/heart/daemon/cli-help.js +700 -0
  89. package/dist/heart/daemon/cli-parse.js +2688 -0
  90. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  91. package/dist/heart/daemon/cli-render.js +777 -0
  92. package/dist/heart/daemon/cli-types.js +8 -0
  93. package/dist/heart/daemon/connect-bay.js +323 -0
  94. package/dist/heart/daemon/daemon-cli.js +29 -2093
  95. package/dist/heart/daemon/daemon-entry.js +842 -10
  96. package/dist/heart/daemon/daemon-health.js +176 -0
  97. package/dist/heart/daemon/daemon-rollup.js +57 -0
  98. package/dist/heart/daemon/daemon-runtime-sync.js +88 -13
  99. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  100. package/dist/heart/daemon/daemon.js +1610 -87
  101. package/dist/heart/daemon/dns-workflow.js +394 -0
  102. package/dist/heart/daemon/doctor-types.js +8 -0
  103. package/dist/heart/daemon/doctor.js +1440 -0
  104. package/dist/heart/daemon/freshness.js +343 -0
  105. package/dist/heart/daemon/habit-private-wake.js +61 -0
  106. package/dist/heart/daemon/health-monitor.js +142 -11
  107. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  108. package/dist/heart/daemon/hooks/bundle-meta.js +135 -1
  109. package/dist/heart/daemon/http-health-probe.js +80 -0
  110. package/dist/heart/daemon/human-command-screens.js +234 -0
  111. package/dist/heart/daemon/human-readiness.js +114 -0
  112. package/dist/heart/daemon/inner-status.js +78 -0
  113. package/dist/heart/daemon/interactive-repair.js +394 -0
  114. package/dist/heart/daemon/launchd.js +37 -8
  115. package/dist/heart/daemon/log-tailer.js +79 -10
  116. package/dist/heart/daemon/logs-prune.js +110 -0
  117. package/dist/heart/daemon/mcp-canary.js +524 -0
  118. package/dist/heart/daemon/message-router.js +45 -5
  119. package/dist/heart/daemon/migrate-to-desk.js +848 -0
  120. package/dist/heart/daemon/os-cron-deps.js +135 -0
  121. package/dist/heart/daemon/os-cron.js +22 -14
  122. package/dist/heart/daemon/ouro-bot-entry.js +4 -2
  123. package/dist/heart/daemon/ouro-entry.js +3 -1
  124. package/dist/heart/daemon/plugin-cli.js +432 -0
  125. package/dist/heart/daemon/process-manager.js +624 -61
  126. package/dist/heart/daemon/provider-discovery.js +137 -0
  127. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  128. package/dist/heart/daemon/pulse.js +511 -0
  129. package/dist/heart/daemon/readiness-repair.js +365 -0
  130. package/dist/heart/daemon/run-hooks.js +2 -0
  131. package/dist/heart/daemon/runtime-logging.js +41 -14
  132. package/dist/heart/daemon/runtime-metadata.js +2 -30
  133. package/dist/heart/daemon/safe-mode.js +161 -0
  134. package/dist/heart/daemon/sense-manager.js +670 -48
  135. package/dist/heart/daemon/session-id-resolver.js +131 -0
  136. package/dist/heart/daemon/skill-management-installer.js +1 -1
  137. package/dist/heart/daemon/socket-client.js +180 -12
  138. package/dist/heart/daemon/stale-bundle-prune.js +113 -0
  139. package/dist/heart/daemon/startup-tui.js +338 -0
  140. package/dist/heart/daemon/task-scheduler.js +117 -39
  141. package/dist/heart/daemon/terminal-ui.js +499 -0
  142. package/dist/heart/daemon/thoughts.js +255 -43
  143. package/dist/heart/daemon/up-progress.js +366 -0
  144. package/dist/heart/daemon/vault-items.js +56 -0
  145. package/dist/heart/delegation.js +1 -4
  146. package/dist/heart/external-events/router.js +121 -0
  147. package/dist/heart/habits/habit-cancel.js +810 -0
  148. package/dist/heart/habits/habit-lifecycle.js +1327 -0
  149. package/dist/heart/habits/habit-migration.js +194 -0
  150. package/dist/heart/habits/habit-parser.js +278 -0
  151. package/dist/heart/habits/habit-runtime-state.js +93 -0
  152. package/dist/heart/habits/habit-scheduler.js +649 -0
  153. package/dist/heart/habits/habit-session-summary.js +318 -0
  154. package/dist/heart/habits/habit-session.js +636 -0
  155. package/dist/heart/{daemon → hatch}/hatch-flow.js +55 -62
  156. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  157. package/dist/heart/{daemon → hatch}/specialist-prompt.js +12 -9
  158. package/dist/heart/{daemon → hatch}/specialist-tools.js +53 -18
  159. package/dist/heart/identity.js +174 -59
  160. package/dist/heart/kept-notes.js +289 -0
  161. package/dist/heart/kicks.js +1 -1
  162. package/dist/heart/machine-identity.js +161 -0
  163. package/dist/heart/mail-import-discovery.js +353 -0
  164. package/dist/heart/mailbox/mailbox-http-hooks.js +98 -0
  165. package/dist/heart/mailbox/mailbox-http-response.js +7 -0
  166. package/dist/heart/mailbox/mailbox-http-routes.js +398 -0
  167. package/dist/heart/mailbox/mailbox-http-static.js +103 -0
  168. package/dist/heart/mailbox/mailbox-http-transport.js +116 -0
  169. package/dist/heart/mailbox/mailbox-http.js +99 -0
  170. package/dist/heart/mailbox/mailbox-read.js +39 -0
  171. package/dist/heart/mailbox/mailbox-types.js +27 -0
  172. package/dist/heart/mailbox/mailbox-view.js +197 -0
  173. package/dist/heart/mailbox/readers/agent-machine.js +428 -0
  174. package/dist/heart/mailbox/readers/continuity-readers.js +329 -0
  175. package/dist/heart/mailbox/readers/mail.js +375 -0
  176. package/dist/heart/mailbox/readers/runtime-readers.js +823 -0
  177. package/dist/heart/mailbox/readers/sessions.js +232 -0
  178. package/dist/heart/mailbox/readers/shared.js +111 -0
  179. package/dist/heart/mcp/mcp-server.js +696 -0
  180. package/dist/heart/migrate-config.js +100 -0
  181. package/dist/heart/model-capabilities.js +11 -0
  182. package/dist/heart/orientation-frame.js +345 -0
  183. package/dist/heart/platform.js +81 -0
  184. package/dist/heart/primitives.js +1 -1
  185. package/dist/heart/private-runtime/decision-renderer.js +156 -0
  186. package/dist/heart/private-runtime/index.js +18 -0
  187. package/dist/heart/private-runtime/ledger.js +218 -0
  188. package/dist/heart/private-runtime/policy.js +214 -0
  189. package/dist/heart/private-runtime/types.js +2 -0
  190. package/dist/heart/progress-story.js +1 -1
  191. package/dist/heart/provider-attempt.js +137 -0
  192. package/dist/heart/provider-binding-resolver.js +273 -0
  193. package/dist/heart/provider-credentials.js +441 -0
  194. package/dist/heart/provider-failover.js +311 -0
  195. package/dist/heart/provider-models.js +81 -0
  196. package/dist/heart/provider-ping.js +262 -0
  197. package/dist/heart/provider-readiness-cache.js +119 -0
  198. package/dist/heart/provider-visibility.js +188 -0
  199. package/dist/heart/providers/anthropic-token.js +131 -0
  200. package/dist/heart/providers/anthropic.js +173 -60
  201. package/dist/heart/providers/azure.js +23 -11
  202. package/dist/heart/providers/error-classification.js +127 -0
  203. package/dist/heart/providers/github-copilot.js +34 -38
  204. package/dist/heart/providers/minimax-vlm.js +189 -0
  205. package/dist/heart/providers/minimax.js +26 -8
  206. package/dist/heart/providers/openai-codex-token.js +349 -0
  207. package/dist/heart/providers/openai-codex.js +55 -40
  208. package/dist/heart/run-ledger.js +247 -0
  209. package/dist/heart/runtime-capability-check.js +170 -0
  210. package/dist/heart/runtime-credentials.js +398 -0
  211. package/dist/heart/runtime-cwd.js +87 -0
  212. package/dist/heart/sense-truth.js +20 -4
  213. package/dist/heart/session-activity.js +90 -24
  214. package/dist/heart/session-events.js +1300 -0
  215. package/dist/heart/session-playback-cli-main.js +5 -0
  216. package/dist/heart/session-playback-cli.js +36 -0
  217. package/dist/heart/session-playback.js +231 -0
  218. package/dist/heart/session-stats-cli-main.js +5 -0
  219. package/dist/heart/session-stats.js +182 -0
  220. package/dist/heart/session-transcript.js +133 -0
  221. package/dist/heart/start-of-turn-packet.js +368 -0
  222. package/dist/heart/streaming.js +604 -207
  223. package/dist/heart/structured-output.js +196 -0
  224. package/dist/heart/sync-classification.js +176 -0
  225. package/dist/heart/sync.js +449 -0
  226. package/dist/heart/target-resolution.js +11 -7
  227. package/dist/heart/tempo.js +93 -0
  228. package/dist/heart/temporal-view.js +41 -0
  229. package/dist/heart/timeouts.js +101 -0
  230. package/dist/heart/tool-activity-callbacks.js +59 -0
  231. package/dist/heart/tool-approval.js +339 -0
  232. package/dist/heart/tool-description.js +155 -0
  233. package/dist/heart/tool-friction.js +55 -0
  234. package/dist/heart/tool-loop.js +200 -0
  235. package/dist/heart/turn-context.js +472 -0
  236. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +6 -5
  237. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  238. package/dist/heart/versioning/ouro-path-installer.js +432 -0
  239. package/dist/heart/versioning/ouro-recovery-launcher.js +76 -0
  240. package/dist/heart/versioning/ouro-version-manager.js +409 -0
  241. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  242. package/dist/heart/{daemon → versioning}/update-checker.js +6 -1
  243. package/dist/heart/versioning/update-hooks.js +154 -0
  244. package/dist/heart/versioning/version-intent.js +114 -0
  245. package/dist/heart/work-card.js +380 -0
  246. package/dist/mailbox-ui/assets/index-Du_9G9WO.css +1 -0
  247. package/dist/mailbox-ui/assets/index-J8zDwHmE.js +1 -0
  248. package/dist/mailbox-ui/assets/vendor-CcN1XpQ9.js +61 -0
  249. package/dist/mailbox-ui/index.html +16 -0
  250. package/dist/mailroom/attention.js +167 -0
  251. package/dist/mailroom/autonomy.js +209 -0
  252. package/dist/mailroom/blob-store.js +715 -0
  253. package/dist/mailroom/body-cache.js +61 -0
  254. package/dist/mailroom/core.js +788 -0
  255. package/dist/mailroom/entry.js +160 -0
  256. package/dist/mailroom/file-store.js +568 -0
  257. package/dist/mailroom/mbox-import.js +393 -0
  258. package/dist/mailroom/migration.js +164 -0
  259. package/dist/mailroom/outbound.js +380 -0
  260. package/dist/mailroom/policy.js +263 -0
  261. package/dist/mailroom/reader.js +233 -0
  262. package/dist/mailroom/search-cache.js +334 -0
  263. package/dist/mailroom/search-relevance.js +319 -0
  264. package/dist/mailroom/smtp-ingress.js +176 -0
  265. package/dist/mailroom/source-state.js +176 -0
  266. package/dist/mailroom/thread.js +109 -0
  267. package/dist/mailroom/travel-extract.js +89 -0
  268. package/dist/mind/bundle-manifest.js +24 -2
  269. package/dist/mind/context.js +273 -111
  270. package/dist/mind/desk-section.js +362 -0
  271. package/dist/mind/diary-integrity.js +60 -0
  272. package/dist/mind/{memory.js → diary.js} +68 -77
  273. package/dist/mind/embedding-provider.js +60 -0
  274. package/dist/mind/file-state.js +179 -0
  275. package/dist/mind/{associative-recall.js → note-search.js} +47 -58
  276. package/dist/mind/obligation-steering.js +227 -0
  277. package/dist/mind/pending.js +13 -8
  278. package/dist/mind/prompt-budget.js +479 -0
  279. package/dist/mind/prompt-refresh.js +3 -2
  280. package/dist/mind/prompt.js +1058 -172
  281. package/dist/mind/provenance-trust.js +26 -0
  282. package/dist/mind/record-paths.js +312 -0
  283. package/dist/mind/scrutiny.js +173 -0
  284. package/dist/mind/session-transaction.js +379 -0
  285. package/dist/nerves/cli-logging.js +7 -1
  286. package/dist/nerves/coverage/audit-rules.js +15 -6
  287. package/dist/nerves/coverage/audit.js +28 -2
  288. package/dist/nerves/coverage/cli.js +1 -1
  289. package/dist/nerves/coverage/contract.js +5 -5
  290. package/dist/nerves/coverage/file-completeness.js +139 -5
  291. package/dist/nerves/coverage/run-artifacts.js +55 -35
  292. package/dist/nerves/event-buffer.js +111 -0
  293. package/dist/nerves/index.js +234 -4
  294. package/dist/nerves/observation.js +20 -0
  295. package/dist/nerves/redact.js +79 -0
  296. package/dist/nerves/review/cli-main.js +5 -0
  297. package/dist/nerves/review/cli.js +156 -0
  298. package/dist/nerves/review/core.js +159 -0
  299. package/dist/nerves/runtime.js +5 -1
  300. package/dist/repertoire/ado-client.js +15 -56
  301. package/dist/repertoire/ado-semantic.js +16 -10
  302. package/dist/repertoire/api-client.js +97 -0
  303. package/dist/repertoire/bitwarden-store.js +1045 -0
  304. package/dist/repertoire/bundle-templates.js +71 -0
  305. package/dist/repertoire/bw-installer.js +180 -0
  306. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  307. package/dist/repertoire/coding/context-pack.js +331 -0
  308. package/dist/repertoire/coding/feedback.js +218 -30
  309. package/dist/repertoire/coding/index.js +15 -3
  310. package/dist/repertoire/coding/manager.js +166 -10
  311. package/dist/repertoire/coding/spawner.js +58 -11
  312. package/dist/repertoire/coding/tools.js +242 -14
  313. package/dist/repertoire/coding/workbench-client.js +272 -0
  314. package/dist/repertoire/coding/workbench-manager.js +346 -0
  315. package/dist/repertoire/commerce-errors.js +109 -0
  316. package/dist/repertoire/commerce-self-test.js +156 -0
  317. package/dist/repertoire/credential-access.js +178 -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 +138 -18
  323. package/dist/repertoire/mcp-client.js +44 -3
  324. package/dist/repertoire/mcp-manager.js +259 -20
  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 +48 -4
  330. package/dist/repertoire/stripe-client.js +131 -0
  331. package/dist/repertoire/tool-arguments.js +104 -0
  332. package/dist/repertoire/tool-results.js +29 -0
  333. package/dist/repertoire/tools-a2a.js +699 -0
  334. package/dist/repertoire/tools-attachments.js +317 -0
  335. package/dist/repertoire/tools-awaiting.js +372 -0
  336. package/dist/repertoire/tools-base.js +67 -1095
  337. package/dist/repertoire/tools-bluebubbles.js +2 -0
  338. package/dist/repertoire/tools-bridge.js +144 -0
  339. package/dist/repertoire/tools-bundle.js +993 -0
  340. package/dist/repertoire/tools-commerce.js +253 -0
  341. package/dist/repertoire/tools-config.js +186 -0
  342. package/dist/repertoire/tools-continuity.js +252 -0
  343. package/dist/repertoire/tools-credential.js +383 -0
  344. package/dist/repertoire/tools-evolution.js +527 -0
  345. package/dist/repertoire/tools-files.js +344 -0
  346. package/dist/repertoire/tools-flight.js +290 -0
  347. package/dist/repertoire/tools-flow.js +119 -0
  348. package/dist/repertoire/tools-github.js +3 -8
  349. package/dist/repertoire/tools-habits.js +103 -0
  350. package/dist/repertoire/tools-mail.js +1975 -0
  351. package/dist/repertoire/tools-notes.js +459 -0
  352. package/dist/repertoire/tools-obligations.js +182 -0
  353. package/dist/repertoire/tools-orientation.js +31 -0
  354. package/dist/repertoire/tools-record.js +482 -0
  355. package/dist/repertoire/tools-rsvp.js +139 -0
  356. package/dist/repertoire/tools-runtime.js +150 -0
  357. package/dist/repertoire/tools-session.js +881 -0
  358. package/dist/repertoire/tools-shell.js +133 -0
  359. package/dist/repertoire/tools-stripe.js +224 -0
  360. package/dist/repertoire/tools-surface.js +355 -0
  361. package/dist/repertoire/tools-teams.js +12 -39
  362. package/dist/repertoire/tools-travel.js +125 -0
  363. package/dist/repertoire/tools-trip.js +982 -0
  364. package/dist/repertoire/tools-user-profile.js +146 -0
  365. package/dist/repertoire/tools-vault.js +40 -0
  366. package/dist/repertoire/tools-voice.js +145 -0
  367. package/dist/repertoire/tools.js +258 -79
  368. package/dist/repertoire/travel-api-client.js +360 -0
  369. package/dist/repertoire/user-profile.js +131 -0
  370. package/dist/repertoire/vault-setup.js +246 -0
  371. package/dist/repertoire/vault-unlock.js +594 -0
  372. package/dist/rsvp/aisleplanner-client.js +354 -0
  373. package/dist/rsvp/cli.js +926 -0
  374. package/dist/rsvp/config.js +327 -0
  375. package/dist/rsvp/cutover.js +433 -0
  376. package/dist/rsvp/diagnostics.js +232 -0
  377. package/dist/rsvp/diff-renderer.js +176 -0
  378. package/dist/rsvp/habit-policy.js +110 -0
  379. package/dist/rsvp/habit-stage.js +123 -0
  380. package/dist/rsvp/incident-bundle.js +97 -0
  381. package/dist/rsvp/migration.js +204 -0
  382. package/dist/rsvp/native-habit-runner.js +630 -0
  383. package/dist/rsvp/outbound-state.js +628 -0
  384. package/dist/rsvp/query.js +118 -0
  385. package/dist/rsvp/replay.js +233 -0
  386. package/dist/rsvp/snapshot.js +232 -0
  387. package/dist/rsvp/spend-ledger.js +175 -0
  388. package/dist/scripts/claude-code-hook.js +41 -0
  389. package/dist/scripts/claude-code-stop-hook.js +47 -0
  390. package/dist/senses/a2a-entry.js +115 -0
  391. package/dist/senses/attention-queue.js +186 -0
  392. package/dist/senses/await-turn-message.js +58 -0
  393. package/dist/senses/bluebubbles/active-turns.js +216 -0
  394. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  395. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  396. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +355 -40
  397. package/dist/senses/bluebubbles/context-packet.js +207 -0
  398. package/dist/senses/bluebubbles/context-smoke.js +144 -0
  399. package/dist/senses/bluebubbles/entry.js +90 -0
  400. package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +21 -3
  401. package/dist/senses/bluebubbles/index.js +3839 -0
  402. package/dist/senses/bluebubbles/latest-turn.js +311 -0
  403. package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +121 -71
  404. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +159 -28
  405. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +24 -13
  406. package/dist/senses/bluebubbles/outbound-state.js +308 -0
  407. package/dist/senses/bluebubbles/processed-log.js +133 -0
  408. package/dist/senses/bluebubbles/reaction-policy.js +47 -0
  409. package/dist/senses/bluebubbles/replay.js +284 -0
  410. package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +30 -2
  411. package/dist/senses/bluebubbles/semantic-receipts.js +1986 -0
  412. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
  413. package/dist/senses/bluebubbles/webhook-registration.js +228 -0
  414. package/dist/senses/bluebubbles-meta-guard.js +39 -0
  415. package/dist/senses/cli/bracketed-paste.js +82 -0
  416. package/dist/senses/cli/image-paste.js +287 -0
  417. package/dist/senses/cli/image-ref-navigation.js +75 -0
  418. package/dist/senses/cli/ink-app.js +156 -0
  419. package/dist/senses/cli/inline-diff.js +64 -0
  420. package/dist/senses/cli/input-keys.js +174 -0
  421. package/dist/senses/cli/kill-ring.js +86 -0
  422. package/dist/senses/cli/message-list.js +51 -0
  423. package/dist/senses/cli/ouro-tui.js +607 -0
  424. package/dist/senses/cli/spinner-imperative.js +135 -0
  425. package/dist/senses/cli/spinner.js +101 -0
  426. package/dist/senses/cli/status-line.js +60 -0
  427. package/dist/senses/cli/streaming-markdown.js +526 -0
  428. package/dist/senses/cli/tool-display.js +85 -0
  429. package/dist/senses/cli/tool-render.js +85 -0
  430. package/dist/senses/cli/tui-store.js +241 -0
  431. package/dist/senses/cli/virtual-list.js +35 -0
  432. package/dist/senses/cli-entry.js +60 -8
  433. package/dist/senses/cli-layout.js +100 -0
  434. package/dist/senses/cli.js +640 -312
  435. package/dist/senses/commands.js +66 -3
  436. package/dist/senses/context-packet-ledger.js +371 -0
  437. package/dist/senses/context-packets.js +154 -0
  438. package/dist/senses/habit-lifecycle-guard.js +24 -0
  439. package/dist/senses/habit-turn-message.js +160 -0
  440. package/dist/senses/ingress-evidence.js +2 -0
  441. package/dist/senses/mail-entry.js +66 -0
  442. package/dist/senses/mail.js +524 -0
  443. package/dist/senses/pipeline.js +1075 -176
  444. package/dist/senses/private-runtime-worker.js +740 -0
  445. package/dist/senses/private-runtime.js +1212 -0
  446. package/dist/senses/proactive-content-guard.js +51 -0
  447. package/dist/senses/shared-turn.js +424 -0
  448. package/dist/senses/surface-tool.js +109 -0
  449. package/dist/senses/teams-entry.js +60 -8
  450. package/dist/senses/teams.js +515 -217
  451. package/dist/senses/trust-gate.js +104 -9
  452. package/dist/senses/voice/audio-playback.js +237 -0
  453. package/dist/senses/voice/audio-routing.js +119 -0
  454. package/dist/senses/voice/elevenlabs.js +202 -0
  455. package/dist/senses/voice/floor-control.js +431 -0
  456. package/dist/senses/voice/floor-controller.js +115 -0
  457. package/dist/senses/voice/golden-path.js +116 -0
  458. package/dist/senses/voice/index.js +29 -0
  459. package/dist/senses/voice/meeting.js +113 -0
  460. package/dist/senses/voice/outbound.js +190 -0
  461. package/dist/senses/voice/phone.js +33 -0
  462. package/dist/senses/voice/playback.js +139 -0
  463. package/dist/senses/voice/realtime-eval.js +496 -0
  464. package/dist/senses/voice/realtime-trace.js +531 -0
  465. package/dist/senses/voice/transcript.js +70 -0
  466. package/dist/senses/voice/turn.js +191 -0
  467. package/dist/senses/voice/twilio-phone-runtime.js +807 -0
  468. package/dist/senses/voice/twilio-phone.js +5081 -0
  469. package/dist/senses/voice/types.js +2 -0
  470. package/dist/senses/voice/whisper.js +161 -0
  471. package/dist/senses/voice-entry.js +81 -0
  472. package/dist/senses/voice-realtime-eval-command.js +99 -0
  473. package/dist/senses/voice-realtime-eval-entry.js +21 -0
  474. package/dist/senses/voice-twilio-entry.js +87 -0
  475. package/dist/trips/core.js +138 -0
  476. package/dist/trips/store.js +265 -0
  477. package/dist/util/frontmatter.js +69 -0
  478. package/package.json +65 -12
  479. package/skills/agent-commerce.md +113 -0
  480. package/skills/browser-navigation.md +117 -0
  481. package/skills/commerce-setup-guide.md +116 -0
  482. package/skills/commerce-setup.md +84 -0
  483. package/skills/configure-dev-tools.md +99 -0
  484. package/skills/travel-planning.md +138 -0
  485. package/dist/heart/daemon/auth-flow.js +0 -430
  486. package/dist/heart/daemon/ouro-path-installer.js +0 -178
  487. package/dist/heart/daemon/update-hooks.js +0 -138
  488. package/dist/heart/safe-workspace.js +0 -228
  489. package/dist/heart/session-recall.js +0 -116
  490. package/dist/mind/friends/channel.js +0 -84
  491. package/dist/mind/friends/group-context.js +0 -144
  492. package/dist/mind/friends/resolver.js +0 -84
  493. package/dist/mind/friends/store-file.js +0 -190
  494. package/dist/mind/friends/store.js +0 -4
  495. package/dist/mind/friends/tokens.js +0 -26
  496. package/dist/mind/friends/trust-explanation.js +0 -74
  497. package/dist/mind/friends/types.js +0 -29
  498. package/dist/repertoire/tasks/board.js +0 -134
  499. package/dist/repertoire/tasks/index.js +0 -224
  500. package/dist/repertoire/tasks/lifecycle.js +0 -80
  501. package/dist/repertoire/tasks/middleware.js +0 -65
  502. package/dist/repertoire/tasks/parser.js +0 -173
  503. package/dist/repertoire/tasks/scanner.js +0 -132
  504. package/dist/repertoire/tasks/transitions.js +0 -144
  505. package/dist/senses/bluebubbles-entry.js +0 -13
  506. package/dist/senses/bluebubbles.js +0 -1180
  507. package/dist/senses/debug-activity.js +0 -148
  508. package/dist/senses/inner-dialog-worker.js +0 -90
  509. package/dist/senses/inner-dialog.js +0 -480
  510. package/subagents/README.md +0 -7
  511. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  512. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  513. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  514. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  515. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  516. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  517. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  518. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  519. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  520. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  521. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  522. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  523. /package/dist/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +0 -0
  524. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  525. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  526. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  527. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
@@ -1,80 +1,130 @@
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.resumeApprovalContinuation = resumeApprovalContinuation;
11
+ exports.isChatStyleChannel = isChatStyleChannel;
12
+ exports.buildPonderResult = buildPonderResult;
13
+ exports.isExternalStateQuery = isExternalStateQuery;
14
+ exports.getSettleRetryError = getSettleRetryError;
10
15
  exports.stripLastToolCalls = stripLastToolCalls;
11
16
  exports.repairOrphanedToolCalls = repairOrphanedToolCalls;
12
- exports.isTransientError = isTransientError;
13
- exports.classifyTransientError = classifyTransientError;
14
17
  exports.runAgent = runAgent;
15
18
  const config_1 = require("./config");
16
19
  const identity_1 = require("./identity");
17
20
  const tools_1 = require("../repertoire/tools");
18
- const channel_1 = require("../mind/friends/channel");
21
+ const tool_arguments_1 = require("../repertoire/tool-arguments");
22
+ const session_events_1 = require("./session-events");
23
+ const friends_1 = require("@ouro.bot/friends");
24
+ const tools_2 = require("../repertoire/tools");
25
+ const streaming_1 = require("./streaming");
19
26
  const runtime_1 = require("../nerves/runtime");
20
27
  const context_1 = require("../mind/context");
28
+ const prompt_budget_1 = require("../mind/prompt-budget");
21
29
  const prompt_1 = require("../mind/prompt");
22
- const associative_recall_1 = require("../mind/associative-recall");
30
+ const kept_notes_1 = require("./kept-notes");
31
+ const error_classification_1 = require("./providers/error-classification");
23
32
  const anthropic_1 = require("./providers/anthropic");
24
33
  const azure_1 = require("./providers/azure");
25
34
  const minimax_1 = require("./providers/minimax");
26
35
  const openai_codex_1 = require("./providers/openai-codex");
27
36
  const github_copilot_1 = require("./providers/github-copilot");
28
- let _providerRuntime = null;
29
- function getProviderRuntimeFingerprint() {
30
- const provider = (0, identity_1.loadAgentConfig)().provider;
31
- /* v8 ignore next -- switch: not all provider branches exercised in CI @preserve */
32
- switch (provider) {
33
- case "azure": {
34
- const { apiKey, endpoint, deployment, modelName, apiVersion, managedIdentityClientId } = (0, config_1.getAzureConfig)();
35
- return JSON.stringify({ provider, apiKey, endpoint, deployment, modelName, apiVersion, managedIdentityClientId });
36
- }
37
- case "anthropic": {
38
- const { model, setupToken } = (0, config_1.getAnthropicConfig)();
39
- return JSON.stringify({ provider, model, setupToken });
40
- }
41
- case "minimax": {
42
- const { apiKey, model } = (0, config_1.getMinimaxConfig)();
43
- return JSON.stringify({ provider, apiKey, model });
44
- }
45
- case "openai-codex": {
46
- const { model, oauthAccessToken } = (0, config_1.getOpenAICodexConfig)();
47
- return JSON.stringify({ provider, model, oauthAccessToken });
48
- }
49
- /* v8 ignore start -- fingerprint: tested via provider init tests @preserve */
50
- case "github-copilot": {
51
- const { model, githubToken, baseUrl } = (0, config_1.getGithubCopilotConfig)();
52
- return JSON.stringify({ provider, model, githubToken, baseUrl });
37
+ const orientation_frame_1 = require("./orientation-frame");
38
+ const identity_2 = require("./identity");
39
+ const socket_client_1 = require("./daemon/socket-client");
40
+ const obligations_1 = require("../arc/obligations");
41
+ const tool_loop_1 = require("./tool-loop");
42
+ const packets_1 = require("../arc/packets");
43
+ const tool_friction_1 = require("./tool-friction");
44
+ const provider_models_1 = require("./provider-models");
45
+ const provider_credentials_1 = require("./provider-credentials");
46
+ const habit_session_1 = require("./habits/habit-session");
47
+ const provider_attempt_1 = require("./provider-attempt");
48
+ const openai_codex_token_1 = require("./providers/openai-codex-token");
49
+ // Cache only immutable provider construction inputs. ProviderRuntime owns
50
+ // mutable per-turn state (for example Responses nativeInput), so every caller
51
+ // must receive a fresh instance even when its binding fingerprint is unchanged.
52
+ const _providerRuntimeFactories = {
53
+ human: null,
54
+ agent: null,
55
+ };
56
+ function providerLaneForFacing(facing) {
57
+ return facing === "human" ? "outward" : "inner";
58
+ }
59
+ function resolveRuntimeProviderBinding(facing) {
60
+ const lane = providerLaneForFacing(facing);
61
+ const config = (0, identity_1.loadAgentConfig)();
62
+ const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
63
+ return { lane, provider: facingConfig.provider, model: facingConfig.model };
64
+ }
65
+ async function getProviderRuntimeFingerprint(facing) {
66
+ const agentName = (0, identity_2.getAgentName)();
67
+ const binding = resolveRuntimeProviderBinding(facing);
68
+ const credential = await (0, provider_credentials_1.readProviderCredentialRecord)(agentName, binding.provider);
69
+ if (!credential.ok) {
70
+ throw new Error([
71
+ `${binding.lane} provider ${binding.provider} (${binding.model}) has no credentials for ${agentName}.`,
72
+ credential.error,
73
+ `Run \`ouro auth --agent ${agentName} --provider ${binding.provider}\`.`,
74
+ ].join("\n"));
75
+ }
76
+ let record = credential.record;
77
+ if (binding.provider === "openai-codex") {
78
+ const refresh = await (0, openai_codex_token_1.refreshOpenAICodexProviderCredentials)(agentName, {
79
+ record,
80
+ reason: "runtime-init",
81
+ });
82
+ if (refresh.ok) {
83
+ record = refresh.record;
53
84
  }
54
- /* v8 ignore stop */
55
85
  }
86
+ return {
87
+ binding,
88
+ fingerprint: JSON.stringify({
89
+ lane: binding.lane,
90
+ provider: binding.provider,
91
+ model: binding.model,
92
+ credentialRevision: record.revision,
93
+ }),
94
+ credential: record,
95
+ };
56
96
  }
57
97
  function createProviderRegistry() {
58
- const factories = {
59
- azure: azure_1.createAzureProviderRuntime,
60
- anthropic: anthropic_1.createAnthropicProviderRuntime,
61
- minimax: minimax_1.createMinimaxProviderRuntime,
62
- "openai-codex": openai_codex_1.createOpenAICodexProviderRuntime,
63
- "github-copilot": github_copilot_1.createGithubCopilotProviderRuntime,
64
- };
65
98
  return {
66
- resolve() {
67
- const provider = (0, identity_1.loadAgentConfig)().provider;
68
- return factories[provider]();
99
+ resolve(provider, model, credential) {
100
+ const providerConfig = { ...credential.config, ...credential.credentials };
101
+ switch (provider) {
102
+ case "azure":
103
+ return (0, azure_1.createAzureProviderRuntime)(model, providerConfig);
104
+ case "anthropic":
105
+ return (0, anthropic_1.createAnthropicProviderRuntime)(model, providerConfig);
106
+ case "minimax":
107
+ return (0, minimax_1.createMinimaxProviderRuntime)(model, providerConfig);
108
+ case "openai-codex":
109
+ return (0, openai_codex_1.createOpenAICodexProviderRuntime)(model, providerConfig);
110
+ case "github-copilot":
111
+ return (0, github_copilot_1.createGithubCopilotProviderRuntime)(model, providerConfig);
112
+ }
69
113
  },
70
114
  };
71
115
  }
72
- function getProviderRuntime() {
116
+ async function getProviderRuntime(facing = "human") {
117
+ let runtime = null;
73
118
  try {
74
- const fingerprint = getProviderRuntimeFingerprint();
75
- if (!_providerRuntime || _providerRuntime.fingerprint !== fingerprint) {
76
- const runtime = createProviderRegistry().resolve();
77
- _providerRuntime = runtime ? { fingerprint, runtime } : null;
119
+ const { binding, fingerprint, credential } = await getProviderRuntimeFingerprint(facing);
120
+ const cached = _providerRuntimeFactories[facing];
121
+ if (!cached || cached.fingerprint !== fingerprint) {
122
+ const create = () => createProviderRegistry().resolve(binding.provider, binding.model, credential);
123
+ runtime = create();
124
+ _providerRuntimeFactories[facing] = runtime ? { fingerprint, create } : null;
125
+ }
126
+ else {
127
+ runtime = cached.create();
78
128
  }
79
129
  }
80
130
  catch (error) {
@@ -84,43 +134,45 @@ function getProviderRuntime() {
84
134
  event: "engine.provider_init_error",
85
135
  component: "engine",
86
136
  message: msg,
87
- meta: {},
137
+ meta: { facing },
88
138
  });
89
139
  // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
90
140
  console.error(`\n[fatal] ${msg}\n`);
91
- process.exit(1);
92
- throw new Error("unreachable");
141
+ throw error instanceof Error ? error : new Error(msg);
93
142
  }
94
- if (!_providerRuntime) {
143
+ if (!runtime) {
144
+ const msg = "provider runtime could not be initialized.";
95
145
  (0, runtime_1.emitNervesEvent)({
96
146
  level: "error",
97
147
  event: "engine.provider_init_error",
98
148
  component: "engine",
99
- message: "provider runtime could not be initialized.",
100
- meta: {},
149
+ message: msg,
150
+ meta: { facing },
101
151
  });
102
- process.exit(1);
103
- throw new Error("unreachable");
152
+ // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
153
+ console.error(`\n[fatal] ${msg}\n`);
154
+ throw new Error(msg);
104
155
  }
105
- return _providerRuntime.runtime;
156
+ return runtime;
106
157
  }
107
158
  /**
108
- * Clear the cached provider runtime so the next access re-creates it from
109
- * current config. Runtime access also auto-refreshes when the selected
110
- * provider fingerprint changes on disk.
159
+ * Clear cached provider construction inputs so the next access re-reads them
160
+ * from current config. Runtime instances are always per-caller and are never
161
+ * shared across turns.
111
162
  */
112
163
  function resetProviderRuntime() {
113
- _providerRuntime = null;
164
+ _providerRuntimeFactories.human = null;
165
+ _providerRuntimeFactories.agent = null;
114
166
  }
115
- function getModel() {
116
- return getProviderRuntime().model;
167
+ function getModel(facing = "human") {
168
+ return resolveRuntimeProviderBinding(facing).model;
117
169
  }
118
- function getProvider() {
119
- return getProviderRuntime().id;
170
+ function getProvider(facing = "human") {
171
+ return resolveRuntimeProviderBinding(facing).provider;
120
172
  }
121
- function createSummarize() {
173
+ function createSummarize(facing = "human") {
122
174
  return async (transcript, instruction) => {
123
- const runtime = getProviderRuntime();
175
+ const runtime = await getProviderRuntime(facing);
124
176
  const client = runtime.client;
125
177
  const response = await client.chat.completions.create({
126
178
  model: runtime.model,
@@ -133,77 +185,530 @@ function createSummarize() {
133
185
  return response.choices?.[0]?.message?.content ?? transcript;
134
186
  };
135
187
  }
136
- function getProviderDisplayLabel() {
137
- const provider = (0, identity_1.loadAgentConfig)().provider;
188
+ function getProviderDisplayLabel(facing = "human") {
189
+ const binding = resolveRuntimeProviderBinding(facing);
190
+ const provider = binding.provider;
191
+ const model = binding.model || "unknown";
138
192
  const providerLabelBuilders = {
139
193
  azure: () => {
140
- const config = (0, config_1.getAzureConfig)();
141
- return `azure openai (${config.deployment || "default"}, model: ${config.modelName || "unknown"})`;
194
+ return `azure openai (model: ${model})`;
142
195
  },
143
- anthropic: () => `anthropic (${(0, config_1.getAnthropicConfig)().model || "unknown"})`,
144
- minimax: () => `minimax (${(0, config_1.getMinimaxConfig)().model || "unknown"})`,
145
- "openai-codex": () => `openai codex (${(0, config_1.getOpenAICodexConfig)().model || "unknown"})`,
196
+ anthropic: () => `anthropic (${model})`,
197
+ minimax: () => `minimax (${model})`,
198
+ "openai-codex": () => `openai codex (${model})`,
146
199
  /* v8 ignore next -- branch: tested via display label unit test @preserve */
147
- "github-copilot": () => `github copilot (${(0, config_1.getGithubCopilotConfig)().model || "unknown"})`,
200
+ "github-copilot": () => `github copilot (${model})`,
148
201
  };
149
202
  return providerLabelBuilders[provider]();
150
203
  }
151
- // Re-export tools, execTool, summarizeArgs from ./tools for backward compat
152
- var tools_2 = require("../repertoire/tools");
153
- Object.defineProperty(exports, "tools", { enumerable: true, get: function () { return tools_2.tools; } });
154
- Object.defineProperty(exports, "execTool", { enumerable: true, get: function () { return tools_2.execTool; } });
155
- Object.defineProperty(exports, "summarizeArgs", { enumerable: true, get: function () { return tools_2.summarizeArgs; } });
156
- Object.defineProperty(exports, "getToolsForChannel", { enumerable: true, get: function () { return tools_2.getToolsForChannel; } });
157
- // Re-export streaming functions for backward compat
158
- var streaming_1 = require("./streaming");
159
- Object.defineProperty(exports, "streamChatCompletion", { enumerable: true, get: function () { return streaming_1.streamChatCompletion; } });
160
- Object.defineProperty(exports, "streamResponsesApi", { enumerable: true, get: function () { return streaming_1.streamResponsesApi; } });
161
- Object.defineProperty(exports, "toResponsesInput", { enumerable: true, get: function () { return streaming_1.toResponsesInput; } });
162
- Object.defineProperty(exports, "toResponsesTools", { enumerable: true, get: function () { return streaming_1.toResponsesTools; } });
163
- // Re-export prompt functions for backward compat
164
- var prompt_2 = require("../mind/prompt");
165
- Object.defineProperty(exports, "buildSystem", { enumerable: true, get: function () { return prompt_2.buildSystem; } });
166
- function parseFinalAnswerPayload(argumentsText) {
204
+ function createCallbackBuffer(callbacks, mode) {
205
+ const events = [];
206
+ const bufferedCallbacks = {
207
+ ...callbacks,
208
+ onTextChunk: (text) => { events.push({ kind: "text", text }); },
209
+ onClearText: () => { events.push({ kind: "clear" }); },
210
+ flushNow: () => { events.push({ kind: "flush" }); },
211
+ };
212
+ if (mode === "all") {
213
+ bufferedCallbacks.onModelStreamStart = () => { events.push({ kind: "stream-start" }); };
214
+ bufferedCallbacks.onReasoningChunk = (text) => { events.push({ kind: "reasoning", text }); };
215
+ }
216
+ return {
217
+ callbacks: bufferedCallbacks,
218
+ async flush() {
219
+ for (const event of events.splice(0)) {
220
+ switch (event.kind) {
221
+ case "stream-start":
222
+ callbacks.onModelStreamStart();
223
+ break;
224
+ case "text":
225
+ callbacks.onTextChunk(event.text);
226
+ break;
227
+ case "reasoning":
228
+ callbacks.onReasoningChunk(event.text);
229
+ break;
230
+ case "clear":
231
+ callbacks.onClearText?.();
232
+ break;
233
+ case "flush":
234
+ await callbacks.flushNow?.();
235
+ break;
236
+ }
237
+ }
238
+ },
239
+ discard() {
240
+ events.splice(0);
241
+ },
242
+ };
243
+ }
244
+ function createHabitCallbackBuffer(callbacks) {
245
+ return createCallbackBuffer(callbacks, "all");
246
+ }
247
+ function createFinalOnlyTextBuffer(callbacks) {
248
+ return createCallbackBuffer(callbacks, "text-only");
249
+ }
250
+ function continuationCallbacks(callbacks, text) {
251
+ const noop = () => undefined;
252
+ return {
253
+ onModelStart: callbacks.onModelStart ?? noop,
254
+ onModelStreamStart: callbacks.onModelStreamStart ?? noop,
255
+ onTextChunk: (chunk) => {
256
+ text.value += chunk;
257
+ callbacks.onTextChunk?.(chunk);
258
+ },
259
+ onReasoningChunk: callbacks.onReasoningChunk ?? noop,
260
+ onToolStart: callbacks.onToolStart ?? noop,
261
+ onToolEnd: callbacks.onToolEnd ?? noop,
262
+ onError: callbacks.onError ?? noop,
263
+ ...(callbacks.onClearText ? { onClearText: callbacks.onClearText } : {}),
264
+ ...(callbacks.flushNow ? { flushNow: callbacks.flushNow } : {}),
265
+ ...(callbacks.settleOutputMode ? { settleOutputMode: callbacks.settleOutputMode } : {}),
266
+ };
267
+ }
268
+ async function resumeApprovalContinuation(options) {
269
+ const claim = options.claimContinuation();
270
+ if (!claim.claimed) {
271
+ if (claim.interruptedAfterAttempt) {
272
+ const notice = "the approval continuation was interrupted after provider work began; its outcome is indeterminate and it will not be retried automatically";
273
+ await options.deliver(notice);
274
+ (0, runtime_1.emitNervesEvent)({
275
+ level: "error",
276
+ component: "engine",
277
+ event: "engine.approval_continuation_indeterminate",
278
+ message: "approval continuation interrupted after provider attempt",
279
+ meta: { approvalId: options.record.approvalId, continuationState: claim.record.continuationState },
280
+ });
281
+ return { outcome: "terminal_notice", messages: structuredClone(options.sessionMessages) };
282
+ }
283
+ (0, runtime_1.emitNervesEvent)({
284
+ component: "engine",
285
+ event: "engine.approval_continuation_duplicate",
286
+ message: "approval continuation was already consumed",
287
+ meta: { approvalId: options.record.approvalId },
288
+ });
289
+ return { outcome: "already_continued", messages: structuredClone(options.sessionMessages) };
290
+ }
291
+ const materialized = (0, session_events_1.materializeApprovalTerminal)({
292
+ messages: options.sessionMessages,
293
+ checkpoint: options.checkpoint,
294
+ record: options.record,
295
+ currentSessionRevision: options.currentSessionRevision,
296
+ materializedApprovalIds: options.materializedApprovalIds,
297
+ });
298
+ const recoveredMaterialization = claim.record.continuationState === "materialized";
299
+ if (!recoveredMaterialization) {
300
+ await options.persist(materialized.messages);
301
+ await options.markContinuationMaterialized();
302
+ }
303
+ if (!materialized.resumeProvider) {
304
+ await options.deliver(materialized.directNotice);
305
+ await options.completeContinuation();
306
+ return { outcome: "terminal_notice", messages: materialized.messages };
307
+ }
308
+ const outward = { value: "" };
309
+ const callbacks = continuationCallbacks(options.callbacks, outward);
310
+ await options.markContinuationAttempted();
311
+ const result = await options.runAgent(materialized.messages, callbacks, options.channel, options.signal, options.runAgentOptions);
312
+ if (result.outcome === "suspended") {
313
+ await options.completeContinuation();
314
+ return { outcome: result.outcome, messages: materialized.messages, suspension: result.suspension };
315
+ }
316
+ await options.persist(materialized.messages, result);
317
+ if (outward.value)
318
+ await options.deliver(outward.value);
319
+ await options.completeContinuation();
320
+ (0, runtime_1.emitNervesEvent)({
321
+ component: "engine",
322
+ event: "engine.approval_continuation_completed",
323
+ message: "approval continuation completed through existing provider loop",
324
+ meta: { approvalId: options.record.approvalId, outcome: result.outcome },
325
+ });
326
+ return { outcome: result.outcome, messages: materialized.messages };
327
+ }
328
+ /**
329
+ * Strip <think>...</think> blocks for the violation-detection check at the
330
+ * end of a streaming turn. Used to tell legitimate text-only responses
331
+ * apart from the MiniMax-M2.7 "only thinking, no tool call" violation
332
+ * shape. Mirrors the more thorough stripThinkBlocks helper in
333
+ * senses/shared-turn.ts (which is for operator-facing output) — kept
334
+ * inline here to avoid pulling senses/ into the core module's import graph.
335
+ */
336
+ function stripThinkBlocksForViolationCheck(input) {
337
+ let out = input;
338
+ for (;;) {
339
+ const open = out.indexOf("<think>");
340
+ if (open === -1)
341
+ break;
342
+ const close = out.indexOf("</think>", open + "<think>".length);
343
+ if (close === -1) {
344
+ out = out.slice(0, open);
345
+ break;
346
+ }
347
+ out = out.slice(0, open) + out.slice(close + "</think>".length);
348
+ }
349
+ return out.trim();
350
+ }
351
+ function hasFreshPendingWork(options) {
352
+ const pendingMessages = options?.pendingMessages;
353
+ if (!Array.isArray(pendingMessages))
354
+ return false;
355
+ return pendingMessages.some((message) => typeof message?.content === "string"
356
+ && message.content.trim().length > 0);
357
+ }
358
+ const HABIT_CONTROL_TOOLS = new Set(["rest", "ponder", "observe"]);
359
+ function habitToolArgs(call) {
167
360
  try {
168
- const parsed = JSON.parse(argumentsText);
169
- if (typeof parsed === "string") {
170
- return { answer: parsed };
361
+ const parsed = JSON.parse(call.arguments);
362
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
363
+ return { ok: false, reason: `habit tool '${call.name}' arguments must be a JSON object` };
171
364
  }
172
- if (!parsed || typeof parsed !== "object") {
173
- return {};
365
+ return { ok: true, args: parsed };
366
+ }
367
+ catch {
368
+ return { ok: false, reason: `habit tool '${call.name}' has malformed JSON arguments` };
369
+ }
370
+ }
371
+ function highRiskExternalMutation(profile) {
372
+ if (profile.risk !== "high")
373
+ return null;
374
+ const mutates = typeof profile.mutates === "string" ? [profile.mutates] : [...profile.mutates];
375
+ return mutates.includes("external_side_effect") ? mutates.join(", ") : null;
376
+ }
377
+ function recordBlockedHabitSurfaceAttempts(habitSession, toolCalls, reason) {
378
+ if (toolCalls.some((call) => call.name !== "send_message" && call.name !== "surface")) {
379
+ habitSession?.recordError?.(`blocked habit tool batch: ${reason}`);
380
+ }
381
+ if (!habitSession?.recordSurfaceAttempt)
382
+ return;
383
+ for (const call of toolCalls) {
384
+ if (call.name !== "send_message" && call.name !== "surface")
385
+ continue;
386
+ const parsed = habitToolArgs(call);
387
+ const args = parsed.ok ? parsed.args : {};
388
+ habitSession.recordSurfaceAttempt({
389
+ recipient: String(args.friendId ?? args.delegationId ?? "unknown"),
390
+ channel: String(args.channel ?? call.name),
391
+ reason: "blocked",
392
+ result: "blocked",
393
+ rawStatus: "blocked",
394
+ error: reason,
395
+ });
396
+ }
397
+ }
398
+ async function habitToolBatchBlockReason(habitSession, toolCalls, delegatedOrigins, activeToolNames, noSend) {
399
+ if (noSend && toolCalls.some((call) => call.name === "ponder")) {
400
+ return "habit tool 'ponder' cannot create continuations under immutable no-send authority";
401
+ }
402
+ if (!habitSession)
403
+ return null;
404
+ const granted = new Set(habitSession.toolPolicy.grantedTools);
405
+ const denied = new Set(habitSession.toolPolicy.deniedTools);
406
+ for (const call of toolCalls) {
407
+ if (denied.has(call.name))
408
+ return `habit tool '${call.name}' is denied by this habit session`;
409
+ if (!activeToolNames.has(call.name))
410
+ return `habit tool '${call.name}' was not advertised to this model turn`;
411
+ if (HABIT_CONTROL_TOOLS.has(call.name))
412
+ continue;
413
+ if (!granted.has(call.name))
414
+ return `habit tool '${call.name}' was not granted to this habit session`;
415
+ const parsed = habitToolArgs(call);
416
+ if (!parsed.ok)
417
+ return parsed.reason;
418
+ const riskProfile = (0, tools_1.riskProfileForToolName)(call.name, parsed.args);
419
+ if (!riskProfile)
420
+ return `habit tool '${call.name}' does not have a known executable risk profile`;
421
+ const externalMutation = highRiskExternalMutation(riskProfile);
422
+ if (externalMutation && call.name !== "send_message" && call.name !== "surface") {
423
+ return `habit tool '${call.name}' has high-risk executable mutation ${externalMutation}: ${riskProfile.reason}`;
424
+ }
425
+ if (call.name === "send_message" || call.name === "surface") {
426
+ const route = await (0, habit_session_1.resolveHabitReturnRoute)({
427
+ agentRoot: (0, identity_2.getAgentRoot)(),
428
+ envelope: habitSession.permissionEnvelope,
429
+ toolName: call.name,
430
+ args: parsed.args,
431
+ friendStore: habitSession.friendStore,
432
+ delegatedOrigins,
433
+ });
434
+ if (!route.allowed)
435
+ return route.reason;
174
436
  }
175
- const answer = typeof parsed.answer === "string" ? parsed.answer : undefined;
176
- const rawIntent = parsed.intent;
177
- const intent = rawIntent === "complete" || rawIntent === "blocked" || rawIntent === "direct_reply"
178
- ? rawIntent
179
- : undefined;
180
- return { answer, intent };
437
+ }
438
+ return null;
439
+ }
440
+ /** Channels that deliberately support mid-turn delivery expose `speak`.
441
+ * BlueBubbles is final-only: its adapter owns one accepted visibility boundary.
442
+ * The private runtime has `ponder`; MCP returns synchronously; mail is batch. */
443
+ function isChatStyleChannel(channel) {
444
+ return channel === "cli" || channel === "teams" || channel === "voice";
445
+ }
446
+ function bindCurrentIngressEvidenceLocator(toolList, evidence) {
447
+ if (!evidence
448
+ || evidence.schemaVersion !== 1
449
+ || evidence.provider !== "bluebubbles"
450
+ || !/^[a-f0-9]{64}$/.test(evidence.captureKeyHash))
451
+ return toolList;
452
+ const locator = `capture:${evidence.captureKeyHash}`;
453
+ return toolList.map((tool) => {
454
+ if (tool.function.name !== "habit_cancel")
455
+ return tool;
456
+ const parameters = tool.function.parameters;
457
+ const properties = parameters.properties;
458
+ return {
459
+ ...tool,
460
+ function: {
461
+ ...tool.function,
462
+ parameters: {
463
+ ...parameters,
464
+ properties: {
465
+ ...properties,
466
+ evidence: {
467
+ ...properties.evidence,
468
+ enum: [locator],
469
+ },
470
+ },
471
+ },
472
+ },
473
+ };
474
+ });
475
+ }
476
+ // Sole-call tools must be the only tool call in a turn. When they appear
477
+ // alongside other tools, the sole-call tool is rejected with this message.
478
+ const SOLE_CALL_REJECTION = {
479
+ settle: "rejected: settle must be the only tool call. finish your work first, then call settle alone.",
480
+ observe: "rejected: observe must be the only tool call. call observe alone when you want to stay silent.",
481
+ rest: "rejected: rest must be the only tool call. finish your work first, then call rest alone.",
482
+ };
483
+ function parseSettlePayload(argumentsText) {
484
+ const parsed = JSON.parse(argumentsText);
485
+ // Provider finalization validates settle.answer as a string before this
486
+ // terminal handling path. Keep this parser focused on projection instead
487
+ // of carrying an unreachable second shape check.
488
+ const answer = parsed.answer;
489
+ const rawIntent = parsed.intent;
490
+ const intent = rawIntent === "complete" || rawIntent === "blocked" || rawIntent === "direct_reply"
491
+ ? rawIntent
492
+ : undefined;
493
+ return { answer, intent };
494
+ }
495
+ function parsePonderPayload(argumentsText) {
496
+ try {
497
+ const parsed = JSON.parse(argumentsText);
498
+ return parsed && typeof parsed === "object" ? parsed : {};
181
499
  }
182
500
  catch {
183
501
  return {};
184
502
  }
185
503
  }
186
- function getFinalAnswerRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp) {
504
+ function parseSuccessCriteria(raw) {
505
+ if (typeof raw !== "string")
506
+ return null;
507
+ const criteria = raw
508
+ .split("\n")
509
+ .map((line) => line.replace(/^\s*[-*]\s*/, "").trim())
510
+ .filter((line) => line.length > 0);
511
+ return criteria.length > 0 ? criteria : null;
512
+ }
513
+ function parsePacketPayload(raw) {
514
+ if (typeof raw !== "string")
515
+ return null;
516
+ try {
517
+ const parsed = JSON.parse(raw);
518
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
519
+ ? parsed
520
+ : null;
521
+ }
522
+ catch {
523
+ return null;
524
+ }
525
+ }
526
+ function normalizeLegacyPonderArgs(parsed) {
527
+ if (typeof parsed.thought !== "string" || parsed.thought.trim().length === 0) {
528
+ return parsed;
529
+ }
530
+ return {
531
+ action: "create",
532
+ kind: "reflection",
533
+ objective: parsed.thought.trim(),
534
+ summary: typeof parsed.say === "string" ? parsed.say.trim() : "",
535
+ success_criteria: "- preserve the thread for later work",
536
+ payload_json: "{}",
537
+ };
538
+ }
539
+ function messageContentText(content) {
540
+ if (typeof content === "string")
541
+ return content;
542
+ if (!Array.isArray(content))
543
+ return "";
544
+ return content
545
+ .map((part) => {
546
+ if (typeof part === "string")
547
+ return part;
548
+ if (!part || typeof part !== "object")
549
+ return "";
550
+ const maybeText = part.text;
551
+ return typeof maybeText === "string" ? maybeText : "";
552
+ })
553
+ .filter(Boolean)
554
+ .join("\n");
555
+ }
556
+ function isHarnessCorrectiveUserText(text) {
557
+ return text.startsWith("no tool was called this turn. you must end every turn")
558
+ || text.startsWith("private-return acknowledgement claimed work was queued, but no ponder packet was created this turn.");
559
+ }
560
+ function latestUserMessageText(messages) {
561
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
562
+ const message = messages[i];
563
+ if (message?.role !== "user")
564
+ continue;
565
+ const text = messageContentText(message.content).trim();
566
+ if (isHarnessCorrectiveUserText(text))
567
+ continue;
568
+ if (text.length > 0)
569
+ return text;
570
+ }
571
+ return "";
572
+ }
573
+ function truncatePonderDelegatedContent(value) {
574
+ return value.length > 120 ? `${value.slice(0, 117)}...` : value;
575
+ }
576
+ function buildPonderDelegatedContent(input) {
577
+ const primary = (input.summary || input.objective).trim();
578
+ const sourceRequest = input.sourceRequest.trim();
579
+ if (!sourceRequest || sourceRequest === primary || sourceRequest === input.objective.trim()) {
580
+ return truncatePonderDelegatedContent(primary);
581
+ }
582
+ return truncatePonderDelegatedContent(`${primary}\nsource request: ${sourceRequest}`);
583
+ }
584
+ function looksLikePrivateReturnRequest(text) {
585
+ const normalized = text.toLowerCase();
586
+ return /\b(private|privately|private-attention|think|reflect|reflection)\b/.test(normalized)
587
+ && /\b(return|bring back|come back|surface|report back)\b/.test(normalized);
588
+ }
589
+ function extractPrivateReturnHeldTokens(text) {
590
+ const tokens = new Set();
591
+ for (const match of text.matchAll(/\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+){2,}\b/g)) {
592
+ const token = match[0];
593
+ if (token.length >= 8)
594
+ tokens.add(token);
595
+ }
596
+ return [...tokens];
597
+ }
598
+ function privateReturnAckLeakError(answer, heldTokens) {
599
+ if (!answer || heldTokens.size === 0)
600
+ return null;
601
+ for (const token of heldTokens) {
602
+ if (answer.includes(token)) {
603
+ 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.";
604
+ }
605
+ }
606
+ return null;
607
+ }
608
+ function claimsPrivateReturnQueued(answer) {
609
+ if (!answer)
610
+ return false;
611
+ const normalized = answer.toLowerCase();
612
+ return /\b(queued|queue|will return|return when|when .*complete|when .*completes|private pass|private runtime completes|inner dialog completes|later)\b/.test(normalized)
613
+ && /\b(private|inner|return|queued|later)\b/.test(normalized);
614
+ }
615
+ function privateReturnMissingPonderError(input) {
616
+ if (input.sawPonder)
617
+ return null;
618
+ if (!looksLikePrivateReturnRequest(input.latestUserRequest))
619
+ return null;
620
+ if (!claimsPrivateReturnQueued(input.answer))
621
+ return null;
622
+ 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.";
623
+ }
624
+ function activeReturnObligationId(agentName, obligationId) {
625
+ if (!obligationId)
626
+ return null;
627
+ const obligation = (0, obligations_1.readReturnObligation)(agentName, obligationId);
628
+ return obligation?.status === "queued" || obligation?.status === "running" ? obligationId : null;
629
+ }
630
+ function ponderReturnSessionId(packet) {
631
+ const origin = packet.origin;
632
+ if (!origin)
633
+ return "unknown/unknown/unknown";
634
+ return `${origin.friendId}/${origin.channel}/${origin.key}`;
635
+ }
636
+ function buildPonderReturnPrivateWakeOptions(input) {
637
+ const sessionId = ponderReturnSessionId(input.packet);
638
+ return {
639
+ reason: "ponder return obligation private attention",
640
+ triggerSource: "ponder-return-obligation",
641
+ budgetClass: "interactive",
642
+ idempotencyKey: `ponder-return:${input.agentName}:${input.returnObligationId}:${input.packet.id}:${sessionId}`,
643
+ originRefs: [
644
+ { kind: "tool", id: "ponder" },
645
+ { kind: "ponder-packet", id: input.packet.id },
646
+ { kind: "return-obligation", id: input.returnObligationId },
647
+ { kind: "session", id: sessionId },
648
+ ],
649
+ };
650
+ }
651
+ function buildPonderResult(packet, action, returnObligationId) {
652
+ return JSON.stringify({
653
+ ok: true,
654
+ packet_id: packet.id,
655
+ action,
656
+ status: packet.status,
657
+ return_obligation_id: returnObligationId,
658
+ private_return_contract: returnObligationId
659
+ ? "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."
660
+ : null,
661
+ }, null, 2);
662
+ }
663
+ /** Returns true when a tool call queries external state (GitHub, npm registry). */
664
+ function isExternalStateQuery(toolName, args) {
665
+ if (toolName !== "shell")
666
+ return false;
667
+ const cmd = String(args.command ?? "");
668
+ return /\bgh\s+(pr|run|api|issue)\b/.test(cmd) || /\bnpm\s+(view|info|show)\b/.test(cmd);
669
+ }
670
+ function getSettleRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp, _delegationDecision, sawSendMessageSelf, sawPonder, _sawQuerySession, currentObligation, innerJob, _sawExternalStateQuery) {
671
+ // Delegation adherence removed: the delegation decision is surfaced in the
672
+ // system prompt as a suggestion. Hard-gating settle caused infinite
673
+ // rejection loops where the agent couldn't respond to the user at all.
674
+ // The agent is free to follow or ignore the delegation hint.
675
+ // 2. Pending obligation not addressed
676
+ if (innerJob?.obligationStatus === "pending" && !sawSendMessageSelf && !sawPonder) {
677
+ 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.";
678
+ }
679
+ // 3. mustResolveBeforeHandoff + missing intent
187
680
  if (mustResolveBeforeHandoff && !intent) {
188
- return "your final_answer is missing required intent. when you must keep going until done or blocked, call final_answer again with answer plus intent=complete, blocked, or direct_reply.";
681
+ 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.";
189
682
  }
683
+ // 4. mustResolveBeforeHandoff + direct_reply without follow-up
190
684
  if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
191
- return "your final_answer used intent=direct_reply without a newer steering follow-up. continue the unresolved work, or call final_answer again with intent=complete or blocked when appropriate.";
685
+ 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.";
192
686
  }
193
- return "your final_answer was incomplete or malformed. call final_answer again with your complete response.";
687
+ // 5. mustResolveBeforeHandoff + complete while a live return loop is still active
688
+ if (mustResolveBeforeHandoff && intent === "complete" && currentObligation && !sawSteeringFollowUp) {
689
+ 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.";
690
+ }
691
+ return null;
194
692
  }
195
- // Re-export kick utilities for backward compat
196
- var kicks_1 = require("./kicks");
197
- Object.defineProperty(exports, "hasToolIntent", { enumerable: true, get: function () { return kicks_1.hasToolIntent; } });
198
- function upsertSystemPrompt(messages, systemText) {
693
+ function upsertSystemPrompt(messages, systemText, protectedSystemMessages = []) {
199
694
  const systemMessage = { role: "system", content: systemText };
200
- if (messages[0]?.role === "system") {
695
+ const protectedMessages = new Set(protectedSystemMessages.filter((message) => message.role === "system"));
696
+ if (messages[0]?.role === "system" && !protectedMessages.has(messages[0])) {
201
697
  messages[0] = systemMessage;
202
698
  }
203
699
  else {
204
700
  messages.unshift(systemMessage);
205
701
  }
206
702
  }
703
+ /**
704
+ * A prompt refresh failure must not revive any generated text from an older
705
+ * turn or release. Even the nominally stable region contains actor-scoped trust,
706
+ * tool, and channel context, so it is not safe to reconstruct. Fail closed to a
707
+ * neutral base and put the freshly derived trigger first.
708
+ */
709
+ function repairFallbackSystemPrompt(orientationFrame) {
710
+ return `${(0, orientation_frame_1.renderOrientationFrame)(orientationFrame)}\n\nYou are a helpful assistant.`;
711
+ }
207
712
  // Remove orphan tool_calls from the last assistant message and any
208
713
  // trailing tool-result messages that lack a matching tool_call.
209
714
  // This keeps the conversation valid after an abort or tool-loop limit.
@@ -232,27 +737,39 @@ const TOOL_SCAN_BOUNDARY_ROLES = new Set(["assistant", "user"]);
232
737
  // 1. If an assistant message has tool_calls but missing tool results, inject synthetic error results.
233
738
  // 2. If a tool result's tool_call_id doesn't match any tool_calls in a preceding assistant message, remove it.
234
739
  // This prevents 400 errors from the API after an aborted turn.
740
+ //
741
+ // Position-aware: a tool result is orphaned when its tool_call_id hasn't been
742
+ // defined by an assistant message AT THIS POSITION yet. MiniMax-M2.7 reuses
743
+ // canonical tool_call_ids across turns, so the global-set check that this
744
+ // function used previously kept misordered tool results that MiniMax then
745
+ // rejected with error 2013 ("tool result's tool id not found"). Walking
746
+ // in order matches what MiniMax actually enforces.
235
747
  function repairOrphanedToolCalls(messages) {
236
- // Pass 1: collect all valid tool_call IDs from assistant messages
237
- const validCallIds = new Set();
238
- for (const msg of messages) {
748
+ // Pass 1: walk in order, accumulate seen tool_call_ids per-position, and
749
+ // mark tool results for removal if their id hasn't been defined yet.
750
+ const seenCallIds = new Set();
751
+ const removeIndices = [];
752
+ for (let i = 0; i < messages.length; i++) {
753
+ const msg = messages[i];
239
754
  if (msg.role === "assistant") {
240
755
  const asst = msg;
241
756
  if (asst.tool_calls) {
242
757
  for (const tc of asst.tool_calls)
243
- validCallIds.add(tc.id);
758
+ seenCallIds.add(tc.id);
244
759
  }
760
+ continue;
245
761
  }
246
- }
247
- // Pass 2: remove orphaned tool results (tool_call_id not in any assistant's tool_calls)
248
- for (let i = messages.length - 1; i >= 0; i--) {
249
- if (messages[i].role === "tool") {
250
- const toolMsg = messages[i];
251
- if (!validCallIds.has(toolMsg.tool_call_id)) {
252
- messages.splice(i, 1);
762
+ if (msg.role === "tool") {
763
+ const toolMsg = msg;
764
+ if (!seenCallIds.has(toolMsg.tool_call_id)) {
765
+ removeIndices.push(i);
253
766
  }
254
767
  }
255
768
  }
769
+ // Splice from the end so earlier indices stay valid.
770
+ for (let i = removeIndices.length - 1; i >= 0; i--) {
771
+ messages.splice(removeIndices[i], 1);
772
+ }
256
773
  // Pass 3: inject synthetic results for tool_calls missing their tool results
257
774
  for (let i = 0; i < messages.length; i++) {
258
775
  const msg = messages[i];
@@ -274,10 +791,13 @@ function repairOrphanedToolCalls(messages) {
274
791
  }
275
792
  const missing = asst.tool_calls.filter((tc) => !resultIds.has(tc.id));
276
793
  if (missing.length > 0) {
794
+ // AX rule: the agent must see what happened. Don't say "interrupted"
795
+ // — that's vague. Tell them the result was lost, possible causes,
796
+ // and what to do next.
277
797
  const syntheticResults = missing.map((tc) => ({
278
798
  role: "tool",
279
799
  tool_call_id: tc.id,
280
- content: "error: tool call was interrupted (previous turn timed out or was aborted)",
800
+ 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.",
281
801
  }));
282
802
  let insertAt = i + 1;
283
803
  while (insertAt < messages.length && messages[insertAt].role === "tool")
@@ -300,49 +820,72 @@ function isContextOverflow(err) {
300
820
  return true;
301
821
  return false;
302
822
  }
303
- // Detect transient network errors worth retrying
304
- function isTransientError(err) {
305
- if (!(err instanceof Error))
306
- return false;
307
- const msg = err.message || "";
308
- const code = err.code || "";
309
- // Node.js network error codes
310
- if (["ECONNRESET", "ECONNREFUSED", "ENOTFOUND", "ETIMEDOUT", "EPIPE",
311
- "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "ECONNABORTED"].includes(code))
312
- return true;
313
- // OpenAI SDK / fetch errors
314
- if (msg.includes("fetch failed"))
315
- return true;
316
- if (msg.includes("network") && !msg.includes("context"))
317
- return true;
318
- if (msg.includes("ECONNRESET") || msg.includes("ETIMEDOUT"))
319
- return true;
320
- if (msg.includes("socket hang up"))
321
- return true;
322
- if (msg.includes("getaddrinfo"))
323
- return true;
324
- // HTTP 429 / 500 / 502 / 503 / 504
325
- const status = err.status;
326
- if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504)
327
- return true;
328
- return false;
823
+ const RETRY_LABELS = {
824
+ "auth-failure": "auth error",
825
+ "usage-limit": "usage limit",
826
+ "rate-limit": "rate limited",
827
+ "server-error": "server error",
828
+ "network-error": "network error",
829
+ "unknown": "error",
830
+ };
831
+ function waitForProviderRetry(delayMs, signal) {
832
+ if (!signal) {
833
+ return new Promise((resolve) => {
834
+ setTimeout(resolve, delayMs);
835
+ });
836
+ }
837
+ return new Promise((resolve, reject) => {
838
+ let timer;
839
+ const onAbort = () => {
840
+ clearTimeout(timer);
841
+ reject(new provider_attempt_1.ProviderAttemptAbortError());
842
+ };
843
+ timer = setTimeout(() => {
844
+ signal.removeEventListener("abort", onAbort);
845
+ resolve();
846
+ }, delayMs);
847
+ if (signal.aborted) {
848
+ onAbort();
849
+ return;
850
+ }
851
+ signal.addEventListener("abort", onAbort, { once: true });
852
+ });
853
+ }
854
+ function buildAuthFailureGuidance(provider, model, agentName, detail) {
855
+ const mismatch = (0, provider_models_1.getProviderModelMismatchMessage)(provider, model);
856
+ const modelLabel = model
857
+ ? mismatch
858
+ ? `${provider} [configured model: ${model}]`
859
+ : `${provider} (${model})`
860
+ : provider;
861
+ const lines = [`${modelLabel} authentication failed.`];
862
+ const cleanDetail = detail.replace(/\s+/g, " ").trim();
863
+ if (cleanDetail)
864
+ lines.push(`provider detail: ${cleanDetail.length > 300 ? `${cleanDetail.slice(0, 297)}...` : cleanDetail}`);
865
+ lines.push("");
866
+ lines.push("To keep using this provider:");
867
+ lines.push(` 1. Run \`ouro auth --agent ${agentName} --provider ${provider}\``);
868
+ if (mismatch) {
869
+ const defaultModel = (0, provider_models_1.getDefaultModelForProvider)(provider);
870
+ lines.push("");
871
+ lines.push("Config warning:");
872
+ lines.push(` - ${mismatch}`);
873
+ lines.push(" - Repair the configured model with:");
874
+ lines.push(` \`ouro use --agent ${agentName} --lane outward --provider ${provider} --model ${defaultModel}\``);
875
+ lines.push(` \`ouro use --agent ${agentName} --lane inner --provider ${provider} --model ${defaultModel}\``);
876
+ }
877
+ lines.push("");
878
+ lines.push(`To use another configured provider instead, run \`ouro use --agent ${agentName} --lane <outward|inner> --provider <provider> --model <model>\`.`);
879
+ return lines.join("\n");
329
880
  }
330
- function classifyTransientError(err) {
331
- if (!(err instanceof Error))
332
- return "unknown error";
333
- const status = err.status;
334
- if (status === 429)
335
- return "rate limited";
336
- if (status === 401 || status === 403)
337
- return "auth error";
338
- if (status && status >= 500)
339
- return "server error";
340
- return "network error";
341
- }
342
- const MAX_RETRIES = 3;
343
- const RETRY_BASE_MS = 2000;
344
881
  async function runAgent(messages, callbacks, channel, signal, options) {
345
- const providerRuntime = getProviderRuntime();
882
+ const generatedMessages = [];
883
+ const pushGenerated = (...next) => {
884
+ messages.push(...next);
885
+ generatedMessages.push(...structuredClone(next));
886
+ };
887
+ const facing = (0, friends_1.channelToFacing)(channel);
888
+ let providerRuntime = await getProviderRuntime(facing);
346
889
  const provider = providerRuntime.id;
347
890
  const toolChoiceRequired = options?.toolChoiceRequired ?? true;
348
891
  const traceId = options?.traceId;
@@ -363,24 +906,85 @@ async function runAgent(messages, callbacks, channel, signal, options) {
363
906
  currentContext = { ...currentContext, friend: freshFriend };
364
907
  }
365
908
  }
909
+ const turnOrientationFrame = options?.orientationFrame
910
+ ?? (channel ? (0, orientation_frame_1.buildOrientationFrame)({ channel, messages }) : undefined);
911
+ if (options?.requiredPromptEvidence) {
912
+ let structuralFloor;
913
+ try {
914
+ structuralFloor = (0, prompt_budget_1.assessRequiredPromptEvidenceBudget)({
915
+ messages,
916
+ requiredPromptEvidence: options.requiredPromptEvidence,
917
+ provider: providerRuntime.id,
918
+ model: providerRuntime.model,
919
+ contextWindowTokens: (0, config_1.getContextConfig)().maxTokens,
920
+ });
921
+ }
922
+ catch (error) {
923
+ const invalidEvidenceError = error instanceof Error ? error : new Error(String(error));
924
+ callbacks.onError(invalidEvidenceError, "terminal");
925
+ options.captureGeneratedMessages?.([]);
926
+ (0, runtime_1.emitNervesEvent)({
927
+ event: "engine.turn_end",
928
+ trace_id: traceId,
929
+ component: "engine",
930
+ message: "runAgent turn completed",
931
+ meta: { done: true, sawPonder: false, sawQuerySession: false, sawBridgeManage: false },
932
+ });
933
+ return {
934
+ outcome: "errored",
935
+ error: invalidEvidenceError,
936
+ errorClassification: "unknown",
937
+ };
938
+ }
939
+ if (structuralFloor.status === "required_evidence_over_budget") {
940
+ const budgetError = new Error(`required_evidence_over_budget: required current-turn evidence needs ${structuralFloor.estimatedTokens} tokens but the provider input limit is ${structuralFloor.budget.inputTokenLimit}`);
941
+ callbacks.onError(budgetError, "terminal");
942
+ options.captureGeneratedMessages?.([]);
943
+ (0, runtime_1.emitNervesEvent)({
944
+ event: "engine.turn_end",
945
+ trace_id: traceId,
946
+ component: "engine",
947
+ message: "runAgent turn completed",
948
+ meta: { done: true, sawPonder: false, sawQuerySession: false, sawBridgeManage: false },
949
+ });
950
+ return {
951
+ outcome: "errored",
952
+ error: budgetError,
953
+ errorClassification: "unknown",
954
+ };
955
+ }
956
+ }
366
957
  // Refresh system prompt at start of each turn when channel is provided.
367
- // If refresh fails, keep existing system prompt (or inject a minimal safe fallback)
368
- // so turn execution remains consistent and non-fatal.
958
+ // If refresh fails, retain only a recognised stable prefix (or inject a
959
+ // minimal safe fallback) so stale dynamic state cannot regain authority.
960
+ let structuredSystemPrompt;
369
961
  if (channel) {
370
962
  try {
371
963
  const buildSystemOptions = {
372
964
  ...options,
965
+ orientationFrame: turnOrientationFrame,
966
+ resumePriorWork: options?.resumePriorWork === true,
373
967
  providerCapabilities: providerRuntime.capabilities,
374
968
  supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
375
969
  };
376
970
  const refreshed = await (0, prompt_1.buildSystem)(channel, buildSystemOptions, currentContext);
377
- upsertSystemPrompt(messages, refreshed);
971
+ structuredSystemPrompt = refreshed;
972
+ upsertSystemPrompt(messages, (0, prompt_1.flattenSystemPrompt)(refreshed), [
973
+ ...(options?.promptOnlyEvidenceMessages ?? []),
974
+ ...(options?.requiredPromptEvidence?.verifiedPredecessorMessage
975
+ ? [options.requiredPromptEvidence.verifiedPredecessorMessage]
976
+ : []),
977
+ ]);
378
978
  }
379
979
  catch (error) {
380
980
  const hadExistingSystemPrompt = messages[0]?.role === "system" && typeof messages[0].content === "string";
381
- const existingSystemText = hadExistingSystemPrompt ? messages[0].content : undefined;
382
- const fallback = existingSystemText ?? "You are a helpful assistant.";
383
- upsertSystemPrompt(messages, fallback);
981
+ const fallback = repairFallbackSystemPrompt(turnOrientationFrame);
982
+ upsertSystemPrompt(messages, fallback, [
983
+ ...(options?.promptOnlyEvidenceMessages ?? []),
984
+ ...(options?.requiredPromptEvidence?.verifiedPredecessorMessage
985
+ ? [options.requiredPromptEvidence.verifiedPredecessorMessage]
986
+ : []),
987
+ ]);
384
988
  (0, runtime_1.emitNervesEvent)({
385
989
  level: "warn",
386
990
  event: "mind.step_error",
@@ -395,42 +999,143 @@ async function runAgent(messages, callbacks, channel, signal, options) {
395
999
  });
396
1000
  }
397
1001
  }
398
- await (0, associative_recall_1.injectAssociativeRecall)(messages);
1002
+ if (channel && options?.skipKeptNotes !== true) {
1003
+ await (0, kept_notes_1.injectKeptNotes)(messages, {
1004
+ channel,
1005
+ friend: currentContext?.friend,
1006
+ judge: async (input) => (0, kept_notes_1.createKeptNotesJudge)(await getProviderRuntime("agent"), signal)(input),
1007
+ signal,
1008
+ traceId,
1009
+ });
1010
+ }
399
1011
  let done = false;
400
1012
  let lastUsage;
401
1013
  let overflowRetried = false;
402
- let retryCount = 0;
403
- let outcome = "complete";
1014
+ let outcome = "settled";
404
1015
  let completion;
1016
+ let suspension;
1017
+ let terminalError;
1018
+ let terminalErrorClassification;
405
1019
  let sawSteeringFollowUp = false;
406
1020
  let mustResolveBeforeHandoffActive = options?.mustResolveBeforeHandoff === true;
407
1021
  let currentReasoningEffort = "medium";
1022
+ let sawSendMessageSelf = false;
1023
+ let sawPonder = false;
1024
+ let sawQuerySession = false;
1025
+ let sawBridgeManage = false;
1026
+ let sawExternalStateQuery = false;
1027
+ const privateReturnHeldTokens = new Set();
1028
+ // Once-per-turn flag for the fresh-work rest gate. Without this, an agent
1029
+ // that called rest, was told "fresh work arrived", processed the items,
1030
+ // and called rest again would get the same message forever — the gate
1031
+ // condition is read from the turn-start snapshot of pendingMessages,
1032
+ // which doesn't update mid-turn. The agent only needs to be told once;
1033
+ // after that, repeated rest attempts mean they've acknowledged.
1034
+ let freshWorkGateFired = false;
1035
+ // Counter for no-tool-call violations. MiniMax reasoning models occasionally
1036
+ // emit only a <think>...</think> block and stop, without any tool call — even
1037
+ // when tool_choice is set to "required". Private-return requests also need
1038
+ // a hard no-tool guard: a text-only "queued" acknowledgement is false unless
1039
+ // a ponder packet created the return obligation in this turn.
1040
+ let noToolCallRetries = 0;
1041
+ const NO_TOOL_CALL_MAX_RETRIES = 2;
1042
+ const toolLoopState = (0, tool_loop_1.createToolLoopState)();
1043
+ const toolFrictionLedger = (0, tool_friction_1.createToolFrictionLedger)();
1044
+ const finishTerminalProviderError = (error, classification) => {
1045
+ terminalError = error;
1046
+ terminalErrorClassification = classification;
1047
+ /* v8 ignore start — auth-failure guidance: tested via provider error classification tests @preserve */
1048
+ if (terminalErrorClassification === "auth-failure") {
1049
+ const agentName = (0, identity_2.getAgentName)();
1050
+ const currentProvider = providerRuntime.id;
1051
+ callbacks.onError(new Error(buildAuthFailureGuidance(currentProvider, providerRuntime.model, agentName, terminalError.message)), "terminal");
1052
+ }
1053
+ else {
1054
+ callbacks.onError(terminalError, "terminal");
1055
+ }
1056
+ /* v8 ignore stop */
1057
+ const errorDetails = (0, error_classification_1.extractProviderErrorDetails)(terminalError);
1058
+ (0, runtime_1.emitNervesEvent)({
1059
+ level: "error",
1060
+ event: "engine.error",
1061
+ trace_id: traceId,
1062
+ component: "engine",
1063
+ message: terminalError.message,
1064
+ meta: {
1065
+ provider: providerRuntime.id,
1066
+ model: providerRuntime.model,
1067
+ errorClassification: terminalErrorClassification,
1068
+ ...(errorDetails.status !== undefined ? { httpStatus: errorDetails.status } : {}),
1069
+ ...(errorDetails.bodyExcerpt ? { bodyExcerpt: errorDetails.bodyExcerpt } : {}),
1070
+ summary: (0, error_classification_1.summarizeProviderError)(terminalError, terminalErrorClassification, providerRuntime.id, providerRuntime.model),
1071
+ },
1072
+ });
1073
+ stripLastToolCalls(messages);
1074
+ stripLastToolCalls(generatedMessages);
1075
+ outcome = "errored";
1076
+ done = true;
1077
+ };
408
1078
  // Prevent MaxListenersExceeded warning — each iteration adds a listener
409
1079
  try {
410
1080
  require("events").setMaxListeners(50, signal);
411
1081
  }
412
1082
  catch { /* unsupported */ }
413
1083
  const toolPreferences = currentContext?.friend?.toolPreferences;
414
- const baseTools = options?.tools ?? (0, tools_1.getToolsForChannel)(channel ? (0, channel_1.getChannelCapabilities)(channel) : undefined, toolPreferences && Object.keys(toolPreferences).length > 0 ? toolPreferences : undefined, currentContext, providerRuntime.capabilities);
1084
+ const unboundBaseTools = 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);
1085
+ const baseTools = bindCurrentIngressEvidenceLocator(unboundBaseTools, options?.toolContext?.currentIngressEvidence);
415
1086
  // Augment tool context with reasoning effort controls from provider
416
- const augmentedToolContext = options?.toolContext
1087
+ const baseToolContext = options?.toolContext
1088
+ ?? (turnOrientationFrame ? { signin: async () => undefined, orientationFrame: turnOrientationFrame } : undefined);
1089
+ const habitSession = options?.habitSession ?? baseToolContext?.habitSession;
1090
+ const augmentedToolContext = baseToolContext
417
1091
  ? {
418
- ...options.toolContext,
1092
+ ...baseToolContext,
419
1093
  supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
420
1094
  setReasoningEffort: (level) => { currentReasoningEffort = level; },
1095
+ activeWorkFrame: options?.activeWorkFrame,
1096
+ orientationFrame: turnOrientationFrame ?? baseToolContext.orientationFrame,
1097
+ ...(habitSession ? { habitSession } : {}),
421
1098
  }
422
- : undefined;
1099
+ : habitSession
1100
+ ? {
1101
+ signin: async () => undefined,
1102
+ habitSession,
1103
+ supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
1104
+ setReasoningEffort: (level) => { currentReasoningEffort = level; },
1105
+ }
1106
+ : undefined;
423
1107
  // Rebase provider-owned turn state from canonical messages at user-turn start.
424
1108
  // This prevents stale provider caches from replaying prior-turn context.
425
1109
  providerRuntime.resetTurnState(messages);
426
1110
  while (!done) {
427
- // When toolChoiceRequired is true (the default), include final_answer
428
- // so the model can signal completion. With tool_choice: required, the
429
- // model must call a tool every turn — final_answer is how it exits.
430
- // Overridable via options.toolChoiceRequired = false (e.g. CLI).
431
- const activeTools = toolChoiceRequired
432
- ? [...baseTools, ...(currentContext?.isGroupChat ? [tools_1.noResponseTool] : []), tools_1.finalAnswerTool]
1111
+ // Channel-based tool filtering:
1112
+ // - Private runtime: exclude send_message (delivery via surface), observe (no one to observe)
1113
+ // - All outward channels (1:1, group, reaction): observe available
1114
+ //
1115
+ // ponder, settle/rest, surface, and observe are always assembled based on channel context.
1116
+ // ponder is available in ALL channels (outer: think privately, inner: keep turning).
1117
+ // Private runtime gets restTool instead of settleTool (rest = end turn, gated by attention queue).
1118
+ // toolChoiceRequired only controls whether tool_choice: "required" is set in the API call.
1119
+ const isPrivateRuntimeChannel = channel === "inner";
1120
+ const privateRuntimeHabitCanSendMessage = isPrivateRuntimeChannel
1121
+ && habitSession?.toolPolicy.outwardMessagingAllowed === true
1122
+ && habitSession.toolPolicy.grantedTools.includes("send_message");
1123
+ const privateRuntimeHabitCanSurface = isPrivateRuntimeChannel
1124
+ && (!habitSession || (habitSession.toolPolicy.outwardMessagingAllowed === true
1125
+ && habitSession.toolPolicy.grantedTools.includes("surface")));
1126
+ const filteredBaseTools = isPrivateRuntimeChannel
1127
+ ? baseTools.filter((t) => privateRuntimeHabitCanSendMessage || t.function.name !== "send_message")
433
1128
  : baseTools;
1129
+ const activeTools = [
1130
+ ...filteredBaseTools,
1131
+ ...(augmentedToolContext?.noSend === true ? [] : [tools_1.ponderTool]),
1132
+ ...(isPrivateRuntimeChannel && privateRuntimeHabitCanSurface ? [tools_2.surfaceToolDef] : []),
1133
+ ...(isPrivateRuntimeChannel ? [tools_1.restTool] : []),
1134
+ ...(!isPrivateRuntimeChannel ? [tools_1.observeTool] : []),
1135
+ ...(!isPrivateRuntimeChannel ? [tools_1.settleTool] : []),
1136
+ ...(isChatStyleChannel(channel ?? "") ? [tools_1.speakTool] : []),
1137
+ ];
1138
+ const activeToolNames = new Set(activeTools.map((tool) => tool.function.name));
434
1139
  const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
435
1140
  if (steeringFollowUps.length > 0) {
436
1141
  const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
@@ -457,26 +1162,170 @@ async function runAgent(messages, callbacks, channel, signal, options) {
457
1162
  break;
458
1163
  }
459
1164
  try {
460
- callbacks.onModelStart();
461
- const result = await providerRuntime.streamTurn({
462
- messages,
463
- activeTools,
464
- callbacks,
465
- signal,
466
- traceId,
467
- toolChoiceRequired,
468
- reasoningEffort: currentReasoningEffort,
1165
+ const turnCallbackBufferRef = { current: null };
1166
+ const callProviderTurn = async () => {
1167
+ callbacks.onModelStart();
1168
+ turnCallbackBufferRef.current = habitSession
1169
+ ? createHabitCallbackBuffer(callbacks)
1170
+ : callbacks.settleOutputMode === "final_only"
1171
+ ? createFinalOnlyTextBuffer(callbacks)
1172
+ : null;
1173
+ try {
1174
+ const promptBudget = (0, prompt_budget_1.applyPromptBudget)({
1175
+ messages,
1176
+ requiredPromptEvidence: options?.requiredPromptEvidence,
1177
+ provider: providerRuntime.id,
1178
+ model: providerRuntime.model,
1179
+ contextWindowTokens: (0, config_1.getContextConfig)().maxTokens,
1180
+ });
1181
+ if (promptBudget.status !== "within_budget") {
1182
+ messages.splice(0, messages.length, ...promptBudget.messages);
1183
+ providerRuntime.resetTurnState(messages);
1184
+ }
1185
+ return await providerRuntime.streamTurn({
1186
+ messages,
1187
+ activeTools,
1188
+ callbacks: turnCallbackBufferRef.current?.callbacks ?? callbacks,
1189
+ signal,
1190
+ traceId,
1191
+ toolChoiceRequired,
1192
+ reasoningEffort: currentReasoningEffort,
1193
+ eagerSettleStreaming: true,
1194
+ systemPrompt: structuredSystemPrompt,
1195
+ });
1196
+ }
1197
+ catch (error) {
1198
+ turnCallbackBufferRef.current?.discard();
1199
+ turnCallbackBufferRef.current = null;
1200
+ if (signal?.aborted)
1201
+ throw new provider_attempt_1.ProviderAttemptAbortError();
1202
+ throw error;
1203
+ }
1204
+ };
1205
+ const callProviderTurnWithOverflowRecovery = async () => {
1206
+ try {
1207
+ return await callProviderTurn();
1208
+ }
1209
+ catch (error) {
1210
+ if (error instanceof provider_attempt_1.ProviderAttemptAbortError)
1211
+ throw error;
1212
+ if (isContextOverflow(error) && !overflowRetried) {
1213
+ overflowRetried = true;
1214
+ stripLastToolCalls(messages);
1215
+ stripLastToolCalls(generatedMessages);
1216
+ const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
1217
+ const trimmed = (0, context_1.trimMessages)(messages, maxTokens, contextMargin, maxTokens * 2);
1218
+ const requiredEvidence = options?.requiredPromptEvidence;
1219
+ const requiredMessages = new Set([
1220
+ ...(requiredEvidence?.verifiedPredecessorMessage ? [requiredEvidence.verifiedPredecessorMessage] : []),
1221
+ ...(requiredEvidence?.currentUserMessage ? [requiredEvidence.currentUserMessage] : []),
1222
+ ]);
1223
+ const trimmedMessages = new Set(trimmed);
1224
+ const overflowRetryMessages = requiredMessages.size === 0
1225
+ ? trimmed
1226
+ : messages.filter((message) => trimmedMessages.has(message) || requiredMessages.has(message));
1227
+ messages.splice(0, messages.length, ...overflowRetryMessages);
1228
+ providerRuntime.resetTurnState(messages);
1229
+ callbacks.onError(new Error("context trimmed, retrying..."), "transient");
1230
+ return callProviderTurn();
1231
+ }
1232
+ throw error;
1233
+ }
1234
+ };
1235
+ const attempt = await (0, provider_attempt_1.runProviderAttempt)({
1236
+ operation: "turn",
1237
+ provider: providerRuntime.id,
1238
+ model: providerRuntime.model,
1239
+ run: callProviderTurnWithOverflowRecovery,
1240
+ classifyError: (error) => providerRuntime.classifyError(error),
1241
+ onRetry: async (record, maxAttempts) => {
1242
+ const delayMs = record.delayMs;
1243
+ const seconds = delayMs / 1000;
1244
+ const cause = RETRY_LABELS[record.classification];
1245
+ try {
1246
+ if (record.provider === "openai-codex" && record.classification === "auth-failure") {
1247
+ await (0, openai_codex_token_1.refreshOpenAICodexProviderCredentials)((0, identity_2.getAgentName)(), {
1248
+ force: true,
1249
+ reason: "turn-auth-failure",
1250
+ });
1251
+ }
1252
+ await (0, provider_credentials_1.refreshProviderCredentialPool)((0, identity_2.getAgentName)(), {
1253
+ preserveCachedOnFailure: true,
1254
+ providers: [record.provider],
1255
+ });
1256
+ _providerRuntimeFactories[facing] = null;
1257
+ providerRuntime = await getProviderRuntime(facing);
1258
+ providerRuntime.resetTurnState(messages);
1259
+ }
1260
+ catch (refreshError) {
1261
+ (0, runtime_1.emitNervesEvent)({
1262
+ level: "warn",
1263
+ component: "engine",
1264
+ event: "engine.provider_retry_refresh_failed",
1265
+ message: "provider credential refresh failed during retry",
1266
+ meta: { provider: record.provider, model: record.model, reason: refreshError instanceof Error ? refreshError.message : String(refreshError) },
1267
+ });
1268
+ }
1269
+ callbacks.onError(new Error(`${cause}, retrying in ${seconds}s (${record.attempt}/${maxAttempts})...`), "transient");
1270
+ },
1271
+ sleep: async (delayMs) => {
1272
+ await waitForProviderRetry(delayMs, signal);
1273
+ providerRuntime.resetTurnState(messages);
1274
+ },
469
1275
  });
1276
+ if (!attempt.ok) {
1277
+ finishTerminalProviderError(attempt.error, attempt.classification);
1278
+ continue;
1279
+ }
1280
+ const result = attempt.value;
1281
+ const streamCallbackBuffer = turnCallbackBufferRef.current;
1282
+ turnCallbackBufferRef.current = null;
1283
+ if (result.settleFinalization && !result.settleFinalization.ok) {
1284
+ // A completed settle payload is terminal provider output, not a prompt
1285
+ // for another model turn. Retractable callbacks have already cleared;
1286
+ // core-owned callback buffers must be discarded before surfacing the exact
1287
+ // parser failure through the ordinary terminal-error path.
1288
+ streamCallbackBuffer?.discard();
1289
+ finishTerminalProviderError(new Error(result.settleFinalization.errorCode), "unknown");
1290
+ continue;
1291
+ }
470
1292
  // Track usage from the latest API call
471
1293
  if (result.usage)
472
1294
  lastUsage = result.usage;
473
- retryCount = 0; // reset on success
474
1295
  // SHARED: build CC-format assistant message from TurnResult
475
1296
  const msg = {
476
1297
  role: "assistant",
477
1298
  };
478
- if (result.content)
479
- msg.content = result.content;
1299
+ // Persist assistant content WITHOUT inline <think>...</think> blocks.
1300
+ // Reasoning content already routed through onReasoningChunk for live
1301
+ // surfacing and persisted separately as `_reasoning_items` for
1302
+ // providers that support a reasoning channel; saving it inline AND
1303
+ // alongside tool_calls causes MiniMax to reject the replayed turn
1304
+ // with "tool result's tool id not found" (error code 2013) because
1305
+ // it can't reconcile reasoning-with-tools in the same assistant
1306
+ // message. Strip aggressively at persist so the next replay is
1307
+ // clean; preserve the original reasoning trace on the message via
1308
+ // `_inline_reasoning` so debug/audit paths can still see it.
1309
+ if (result.content) {
1310
+ const stripped = stripThinkBlocksForViolationCheck(result.content);
1311
+ if (stripped.length > 0)
1312
+ msg.content = stripped;
1313
+ if (stripped.length !== result.content.length) {
1314
+ msg._inline_reasoning = result.content;
1315
+ (0, runtime_1.emitNervesEvent)({
1316
+ level: "info",
1317
+ component: "engine",
1318
+ event: "engine.inline_reasoning_stripped",
1319
+ message: "stripped inline <think> blocks from persisted assistant message; preserved on _inline_reasoning",
1320
+ meta: {
1321
+ provider: providerRuntime.id,
1322
+ model: providerRuntime.model,
1323
+ originalLength: result.content.length,
1324
+ strippedLength: stripped.length,
1325
+ },
1326
+ });
1327
+ }
1328
+ }
480
1329
  if (result.toolCalls.length)
481
1330
  msg.tool_calls = result.toolCalls.map((tc) => ({
482
1331
  id: tc.id,
@@ -496,111 +1345,501 @@ async function runAgent(messages, callbacks, channel, signal, options) {
496
1345
  }
497
1346
  // Phase annotation for Codex provider
498
1347
  const hasPhaseAnnotation = providerRuntime.capabilities.has("phase-annotation");
499
- const isSoleFinalAnswer = result.toolCalls.length === 1 && result.toolCalls[0].name === "final_answer";
1348
+ const isSoleSettle = result.toolCalls.length === 1 && result.toolCalls[0].name === "settle";
500
1349
  if (hasPhaseAnnotation) {
501
- msg.phase = isSoleFinalAnswer ? "final_answer" : "commentary";
1350
+ msg.phase = isSoleSettle ? "settle" : "commentary";
502
1351
  }
1352
+ // Detect the MiniMax "only-thinking, no tool call" violation: no tool
1353
+ // calls returned, and the content is empty after stripping
1354
+ // <think>...</think> blocks. This is a narrow check — legitimate
1355
+ // content-only responses (text without think tags, or text outside
1356
+ // think tags) still flow through the original "no tool calls →
1357
+ // accept as-is" path so existing channels and tests are unaffected.
1358
+ const onlyThinkContent = !result.toolCalls.length
1359
+ && typeof result.content === "string"
1360
+ && stripThinkBlocksForViolationCheck(result.content).length === 0
1361
+ && result.content.length > 0;
1362
+ const privateReturnTextAckRetryError = !result.toolCalls.length
1363
+ ? privateReturnMissingPonderError({
1364
+ latestUserRequest: latestUserMessageText(messages),
1365
+ answer: stripThinkBlocksForViolationCheck(result.content),
1366
+ sawPonder,
1367
+ })
1368
+ : null;
503
1369
  if (!result.toolCalls.length) {
504
- // No tool calls — accept response as-is.
505
- // (Kick detection disabled; tool_choice: required + final_answer
506
- // is the primary loop control. See src/heart/kicks.ts to re-enable.)
507
- messages.push(msg);
1370
+ if (privateReturnTextAckRetryError) {
1371
+ streamCallbackBuffer?.discard();
1372
+ callbacks.onClearText?.();
1373
+ if (noToolCallRetries < NO_TOOL_CALL_MAX_RETRIES) {
1374
+ noToolCallRetries++;
1375
+ (0, runtime_1.emitNervesEvent)({
1376
+ level: "warn",
1377
+ component: "engine",
1378
+ event: "engine.no_tool_call_retry",
1379
+ message: "model returned a text-only private-return acknowledgement without ponder; retrying with corrective nudge",
1380
+ meta: {
1381
+ attempt: noToolCallRetries,
1382
+ cap: NO_TOOL_CALL_MAX_RETRIES,
1383
+ provider: providerRuntime.id,
1384
+ model: providerRuntime.model,
1385
+ reason: "private_return_missing_ponder",
1386
+ contentLength: result.content.length,
1387
+ },
1388
+ });
1389
+ pushGenerated(msg);
1390
+ messages.push({
1391
+ role: "user",
1392
+ content: `${privateReturnTextAckRetryError} Emit the ponder(action=create, ...) tool call now, or ask a blocking clarification without saying the private work is queued.`,
1393
+ });
1394
+ continue;
1395
+ }
1396
+ const blockedAnswer = "I could not start the private pass. No private-attention packet was created, so no return work was queued.";
1397
+ (0, runtime_1.emitNervesEvent)({
1398
+ level: "error",
1399
+ component: "engine",
1400
+ event: "engine.private_return_missing_ponder_blocked",
1401
+ message: "private-return text acknowledgement skipped ponder through the retry cap; failing closed",
1402
+ meta: {
1403
+ cap: NO_TOOL_CALL_MAX_RETRIES,
1404
+ provider: providerRuntime.id,
1405
+ model: providerRuntime.model,
1406
+ contentLength: result.content.length,
1407
+ },
1408
+ });
1409
+ msg.content = blockedAnswer;
1410
+ pushGenerated(msg);
1411
+ callbacks.onTextChunk(blockedAnswer);
1412
+ completion = { answer: blockedAnswer, intent: "blocked" };
1413
+ outcome = "blocked";
1414
+ done = true;
1415
+ continue;
1416
+ }
1417
+ if (onlyThinkContent && toolChoiceRequired && noToolCallRetries < NO_TOOL_CALL_MAX_RETRIES) {
1418
+ streamCallbackBuffer?.discard();
1419
+ // Provider-level violation: tool_choice was required, model emitted
1420
+ // only a <think>...</think> block (or empty content) with no tool
1421
+ // call. Retry with a corrective nudge up to NO_TOOL_CALL_MAX_RETRIES
1422
+ // times. After cap, accept as-is (the readback path strips think
1423
+ // tags and surfaces a clear diagnostic).
1424
+ noToolCallRetries++;
1425
+ (0, runtime_1.emitNervesEvent)({
1426
+ level: "warn",
1427
+ component: "engine",
1428
+ event: "engine.no_tool_call_retry",
1429
+ message: "model returned only <think> content with no tool call despite tool_choice=required; retrying with corrective nudge",
1430
+ meta: {
1431
+ attempt: noToolCallRetries,
1432
+ cap: NO_TOOL_CALL_MAX_RETRIES,
1433
+ provider: providerRuntime.id,
1434
+ model: providerRuntime.model,
1435
+ contentLength: result.content.length,
1436
+ },
1437
+ });
1438
+ pushGenerated(msg);
1439
+ messages.push({
1440
+ role: "user",
1441
+ content: isPrivateRuntimeChannel
1442
+ ? augmentedToolContext?.noSend === true
1443
+ ? "no tool was called this turn. this is an immutable no-send turn; call rest now without creating a continuation."
1444
+ : "no tool was called this turn. you must end every turn by calling rest (or surface, ponder, observe). emit the tool call now."
1445
+ : "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.",
1446
+ });
1447
+ continue;
1448
+ }
1449
+ // Legitimate text-only response, or cap reached — accept as-is.
1450
+ await streamCallbackBuffer?.flush();
1451
+ pushGenerated(msg);
508
1452
  done = true;
509
1453
  }
510
1454
  else {
511
- // Check for final_answer sole call: intercept before tool execution
512
- if (isSoleFinalAnswer) {
1455
+ // Reset the retry counter on any successful tool call.
1456
+ noToolCallRetries = 0;
1457
+ const habitBlockReason = await habitToolBatchBlockReason(habitSession, result.toolCalls, augmentedToolContext?.delegatedOrigins, activeToolNames, augmentedToolContext?.noSend === true);
1458
+ if (habitBlockReason) {
1459
+ streamCallbackBuffer?.discard();
1460
+ recordBlockedHabitSurfaceAttempts(habitSession, result.toolCalls, habitBlockReason);
1461
+ pushGenerated(msg);
1462
+ const blockedOutput = `blocked: ${habitBlockReason}. No tool side effects from this assistant message were executed.`;
1463
+ for (const call of result.toolCalls) {
1464
+ pushGenerated({ role: "tool", tool_call_id: call.id, content: blockedOutput });
1465
+ providerRuntime.appendToolOutput(call.id, blockedOutput);
1466
+ }
1467
+ (0, runtime_1.emitNervesEvent)({
1468
+ level: "warn",
1469
+ component: "engine",
1470
+ event: "engine.habit_tool_batch_blocked",
1471
+ message: "habit tool batch blocked before side effects",
1472
+ meta: { reason: habitBlockReason, toolCalls: result.toolCalls.map((call) => call.name) },
1473
+ });
1474
+ continue;
1475
+ }
1476
+ const soleTerminalCall = result.toolCalls.length === 1
1477
+ ? result.toolCalls[0]
1478
+ : null;
1479
+ const soleTerminalProjection = soleTerminalCall
1480
+ ? (0, tools_1.resolveToolDefinition)(soleTerminalCall.name)?.terminalProjection
1481
+ : undefined;
1482
+ if (soleTerminalCall && soleTerminalProjection?.mode === "verbatim") {
1483
+ let terminalArgs = {};
1484
+ try {
1485
+ const parsed = JSON.parse(soleTerminalCall.arguments);
1486
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1487
+ terminalArgs = parsed;
1488
+ }
1489
+ }
1490
+ catch {
1491
+ // The registered handler owns exact argument validation.
1492
+ }
1493
+ if (soleTerminalProjection.clearBufferedText
1494
+ || callbacks.settleOutputMode === "final_only") {
1495
+ streamCallbackBuffer?.discard();
1496
+ }
1497
+ else {
1498
+ await streamCallbackBuffer?.flush();
1499
+ }
1500
+ if (soleTerminalProjection.clearBufferedText)
1501
+ callbacks.onClearText?.();
1502
+ callbacks.onToolStart(soleTerminalCall.name, terminalArgs);
1503
+ let terminalResult;
1504
+ try {
1505
+ const execToolFn = options?.execTool ?? tools_1.execTool;
1506
+ terminalResult = await execToolFn(soleTerminalCall.name, terminalArgs, augmentedToolContext);
1507
+ }
1508
+ catch (error) {
1509
+ callbacks.onToolEnd(soleTerminalCall.name, (0, tools_1.summarizeArgs)(soleTerminalCall.name, terminalArgs), false);
1510
+ pushGenerated(msg);
1511
+ const failure = error instanceof Error ? `error: ${error.message}` : `error: ${String(error)}`;
1512
+ pushGenerated({ role: "tool", tool_call_id: soleTerminalCall.id, content: failure });
1513
+ providerRuntime.appendToolOutput(soleTerminalCall.id, failure);
1514
+ callbacks.onTextChunk(failure);
1515
+ completion = { answer: failure, intent: "blocked" };
1516
+ outcome = "blocked";
1517
+ done = true;
1518
+ continue;
1519
+ }
1520
+ callbacks.onToolEnd(soleTerminalCall.name, (0, tools_1.summarizeArgs)(soleTerminalCall.name, terminalArgs), true);
1521
+ pushGenerated(msg);
1522
+ pushGenerated({ role: "tool", tool_call_id: soleTerminalCall.id, content: terminalResult });
1523
+ providerRuntime.appendToolOutput(soleTerminalCall.id, terminalResult);
1524
+ callbacks.onTextChunk(terminalResult);
1525
+ completion = { answer: terminalResult, intent: "complete" };
1526
+ outcome = "settled";
1527
+ done = true;
1528
+ continue;
1529
+ }
1530
+ // Check for settle sole call: intercept before tool execution
1531
+ if (isSoleSettle) {
1532
+ /* v8 ignore next -- defensive: JSON.parse catch for malformed settle args @preserve */
1533
+ const settleArgs = (() => { try {
1534
+ return JSON.parse(result.toolCalls[0].arguments);
1535
+ }
1536
+ catch {
1537
+ return {};
1538
+ } })();
1539
+ callbacks.onToolStart("settle", settleArgs);
1540
+ // Private-runtime attention queue gate: reject settle if items remain
1541
+ const attentionQueue = augmentedToolContext?.delegatedOrigins;
1542
+ if (isPrivateRuntimeChannel && attentionQueue && attentionQueue.length > 0) {
1543
+ streamCallbackBuffer?.discard();
1544
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
1545
+ callbacks.onClearText?.();
1546
+ pushGenerated(msg);
1547
+ 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.";
1548
+ pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
1549
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
1550
+ continue;
1551
+ }
513
1552
  // Extract answer from the tool call arguments.
514
1553
  // Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
515
- const { answer, intent } = parseFinalAnswerPayload(result.toolCalls[0].arguments);
1554
+ const { answer, intent } = parseSettlePayload(result.toolCalls[0].arguments);
1555
+ // Private-runtime settle: no CompletionMetadata, "(settled)" ack
1556
+ if (isPrivateRuntimeChannel) {
1557
+ streamCallbackBuffer?.discard();
1558
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
1559
+ pushGenerated(msg);
1560
+ const settled = "(settled)";
1561
+ pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: settled });
1562
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, settled);
1563
+ outcome = "settled";
1564
+ done = true;
1565
+ continue;
1566
+ }
1567
+ // The provider finalizer has already established a top-level string
1568
+ // answer before ordinary settle handling reaches this point.
1569
+ const deliveredAnswer = answer;
1570
+ const retryError = privateReturnAckLeakError(deliveredAnswer, privateReturnHeldTokens)
1571
+ ?? privateReturnMissingPonderError({
1572
+ latestUserRequest: latestUserMessageText(messages),
1573
+ answer: deliveredAnswer,
1574
+ sawPonder,
1575
+ })
1576
+ ?? getSettleRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp, options?.delegationDecision, sawSendMessageSelf, sawPonder, sawQuerySession, options?.currentObligation ?? null, options?.activeWorkFrame?.inner?.job, sawExternalStateQuery);
516
1577
  const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
517
- const validTerminalIntent = intent === "complete" || intent === "blocked";
518
- const validClosure = answer != null
519
- && (!mustResolveBeforeHandoffActive || validDirectReply || validTerminalIntent);
520
- if (validClosure) {
1578
+ if (retryError === null) {
1579
+ try {
1580
+ if (!result.settleStreamed) {
1581
+ const acceptedOutputCallbacks = streamCallbackBuffer?.callbacks ?? callbacks;
1582
+ acceptedOutputCallbacks.onTextChunk(deliveredAnswer);
1583
+ }
1584
+ await streamCallbackBuffer?.flush();
1585
+ }
1586
+ catch (error) {
1587
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
1588
+ streamCallbackBuffer?.discard();
1589
+ finishTerminalProviderError(new streaming_1.SettleFinalizationCallbackError(error), "unknown");
1590
+ continue;
1591
+ }
1592
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
521
1593
  completion = {
522
- answer,
1594
+ answer: deliveredAnswer,
523
1595
  intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
524
1596
  };
525
- if (result.finalAnswerStreamed) {
526
- // The streaming layer already parsed and emitted the answer
527
- // progressively via FinalAnswerParser. Skip clearing and
528
- // re-emitting to avoid double-delivery.
529
- }
530
- else {
531
- // Clear any streamed noise (e.g. refusal text) before emitting.
532
- callbacks.onClearText?.();
533
- // Emit the answer through the callback pipeline so channels receive it.
534
- // Never truncate -- channel adapters handle splitting long messages.
535
- callbacks.onTextChunk(answer);
536
- }
537
- messages.push(msg);
1597
+ // Retractable owners already hold the validated answer. Final-only
1598
+ // owners receive it here, after every semantic continuation gate.
1599
+ pushGenerated(msg);
538
1600
  if (validDirectReply) {
539
1601
  const resumeWork = "direct reply delivered. resume the unresolved obligation now and keep working until you can finish or clearly report that you are blocked.";
540
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: resumeWork });
1602
+ pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: resumeWork });
541
1603
  providerRuntime.appendToolOutput(result.toolCalls[0].id, resumeWork);
542
1604
  }
543
1605
  else {
544
1606
  const delivered = "(delivered)";
545
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
1607
+ pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
546
1608
  providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
547
- outcome = intent === "blocked" ? "blocked" : "complete";
1609
+ outcome = intent === "blocked" ? "blocked" : "settled";
548
1610
  done = true;
549
1611
  }
550
1612
  }
551
1613
  else {
552
- // Answer is undefined -- the model's final_answer was incomplete or
553
- // malformed. Clear any partial streamed text or noise, then push the
554
- // assistant msg + error tool result and let the model try again.
1614
+ // The payload is structurally final, but a semantic continuation
1615
+ // gate rejected it. Return that exact gate reason to the model.
1616
+ streamCallbackBuffer?.discard();
1617
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
555
1618
  callbacks.onClearText?.();
556
- const retryError = getFinalAnswerRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp);
557
- messages.push(msg);
558
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: retryError });
559
- providerRuntime.appendToolOutput(result.toolCalls[0].id, retryError);
1619
+ pushGenerated(msg);
1620
+ const toolRetryMessage = retryError;
1621
+ pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: toolRetryMessage });
1622
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, toolRetryMessage);
560
1623
  }
561
1624
  continue;
562
1625
  }
563
- // Check for no_response sole call: intercept before tool execution
564
- const isSoleNoResponse = result.toolCalls.length === 1 && result.toolCalls[0].name === "no_response";
565
- if (isSoleNoResponse) {
566
- let reason;
567
- try {
568
- const parsed = JSON.parse(result.toolCalls[0].arguments);
569
- if (typeof parsed?.reason === "string")
570
- reason = parsed.reason;
1626
+ // Check for observe sole call: intercept before tool execution
1627
+ const isSoleObserve = result.toolCalls.length === 1 && result.toolCalls[0].name === "observe";
1628
+ if (isSoleObserve) {
1629
+ streamCallbackBuffer?.discard();
1630
+ /* v8 ignore next -- defensive: JSON.parse catch for malformed observe args @preserve */
1631
+ const observeArgs = (() => { try {
1632
+ return JSON.parse(result.toolCalls[0].arguments);
571
1633
  }
572
- catch { /* ignore */ }
1634
+ catch {
1635
+ return {};
1636
+ } })();
1637
+ let reason;
1638
+ if (typeof observeArgs?.reason === "string")
1639
+ reason = observeArgs.reason;
1640
+ callbacks.onToolStart("observe", observeArgs);
573
1641
  (0, runtime_1.emitNervesEvent)({
574
1642
  component: "engine",
575
- event: "engine.no_response",
576
- message: "agent declined to respond in group chat",
1643
+ event: "engine.observe",
1644
+ message: "agent observed without responding",
577
1645
  meta: { ...(reason ? { reason } : {}) },
578
1646
  });
579
- messages.push(msg);
1647
+ callbacks.onToolEnd("observe", (0, tools_1.summarizeArgs)("observe", observeArgs), true);
1648
+ pushGenerated(msg);
580
1649
  const silenced = "(silenced)";
581
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: silenced });
1650
+ pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: silenced });
582
1651
  providerRuntime.appendToolOutput(result.toolCalls[0].id, silenced);
583
- outcome = "no_response";
1652
+ outcome = "observed";
1653
+ done = true;
1654
+ continue;
1655
+ }
1656
+ // Check for rest sole call: intercept before tool execution
1657
+ const isSoleRest = result.toolCalls.length === 1 && result.toolCalls[0].name === "rest";
1658
+ if (isSoleRest) {
1659
+ streamCallbackBuffer?.discard();
1660
+ const restArgs = (() => { try {
1661
+ return JSON.parse(result.toolCalls[0].arguments);
1662
+ }
1663
+ catch {
1664
+ return {};
1665
+ } })();
1666
+ callbacks.onToolStart("rest", restArgs);
1667
+ // Attention queue gate: reject rest if items remain
1668
+ const attentionQueue = augmentedToolContext?.delegatedOrigins;
1669
+ if (attentionQueue && attentionQueue.length > 0) {
1670
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), false);
1671
+ pushGenerated(msg);
1672
+ 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.";
1673
+ pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
1674
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
1675
+ continue;
1676
+ }
1677
+ if (hasFreshPendingWork(options) && !freshWorkGateFired) {
1678
+ freshWorkGateFired = true;
1679
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), false);
1680
+ pushGenerated(msg);
1681
+ const gateMessage = "fresh work arrived for me this turn — inspect the pending messages above and take the next concrete action before you rest.";
1682
+ pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
1683
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
1684
+ (0, runtime_1.emitNervesEvent)({
1685
+ level: "info",
1686
+ component: "engine",
1687
+ event: "engine.fresh_work_gate_fired",
1688
+ message: "rest deferred once because pending work arrived this turn; agent has been notified",
1689
+ meta: { pendingCount: options.pendingMessages.length },
1690
+ });
1691
+ continue;
1692
+ }
1693
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), true);
1694
+ pushGenerated(msg);
1695
+ const ack = "(resting)";
1696
+ pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
1697
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
1698
+ (0, runtime_1.emitNervesEvent)({
1699
+ component: "engine",
1700
+ event: "engine.rested",
1701
+ message: "resting until next heartbeat",
1702
+ meta: { ...(typeof restArgs?.status === "string" ? { status: restArgs.status } : {}) },
1703
+ });
1704
+ outcome = "rested";
1705
+ done = true;
1706
+ continue;
1707
+ }
1708
+ const preCallMessages = structuredClone(messages.filter((message) => message.role !== "system"));
1709
+ const validatedCalls = options?.approvalCoordinator
1710
+ ? result.toolCalls.map((call) => {
1711
+ const advertised = activeTools.find((tool) => tool.function.name === call.name);
1712
+ if (!advertised || !advertised.function.parameters || typeof advertised.function.parameters !== "object") {
1713
+ return { call, error: "tool was not advertised with a valid argument schema" };
1714
+ }
1715
+ const validated = (0, tool_arguments_1.validateAdvertisedToolArguments)(call.arguments, advertised.function.parameters);
1716
+ return validated.ok
1717
+ ? { call, advertised, validated: validated.value }
1718
+ : { call, error: validated.reason };
1719
+ })
1720
+ : null;
1721
+ const invalidApprovalCall = validatedCalls?.find((entry) => "error" in entry);
1722
+ if (invalidApprovalCall) {
1723
+ await streamCallbackBuffer?.flush();
1724
+ pushGenerated(msg);
1725
+ for (const entry of validatedCalls) {
1726
+ const detail = "error" in entry ? entry.error : "another call in this batch had invalid arguments";
1727
+ const rejection = `invalid tool arguments: ${detail}`;
1728
+ pushGenerated({ role: "tool", tool_call_id: entry.call.id, content: rejection });
1729
+ providerRuntime.appendToolOutput(entry.call.id, rejection);
1730
+ }
1731
+ (0, runtime_1.emitNervesEvent)({
1732
+ level: "warn",
1733
+ component: "engine",
1734
+ event: "engine.tool_arguments_rejected",
1735
+ message: "tool batch rejected before execution because arguments were invalid",
1736
+ meta: { toolCallId: invalidApprovalCall.call.id, toolName: invalidApprovalCall.call.name },
1737
+ });
1738
+ continue;
1739
+ }
1740
+ const approvalCalls = validatedCalls?.map((entry) => ({
1741
+ ...entry,
1742
+ policy: (0, tools_1.approvalPolicyForToolName)(entry.call.name, entry.validated.arguments),
1743
+ })) ?? [];
1744
+ const protectedCall = approvalCalls.find((entry) => entry.policy.kind === "required");
1745
+ if (protectedCall && result.toolCalls.length !== 1) {
1746
+ streamCallbackBuffer?.discard();
1747
+ pushGenerated(msg);
1748
+ for (const call of result.toolCalls) {
1749
+ const rejection = "rejected: approval-eligible tool must be the sole call; no call in this batch was executed.";
1750
+ pushGenerated({ role: "tool", tool_call_id: call.id, content: rejection });
1751
+ providerRuntime.appendToolOutput(call.id, rejection);
1752
+ }
1753
+ (0, runtime_1.emitNervesEvent)({
1754
+ level: "warn",
1755
+ component: "engine",
1756
+ event: "engine.approval_mixed_batch_rejected",
1757
+ message: "protected tool batch rejected before every handler",
1758
+ meta: { toolCallCount: result.toolCalls.length, protectedToolName: protectedCall.call.name },
1759
+ });
1760
+ continue;
1761
+ }
1762
+ if (protectedCall && protectedCall.policy.kind === "required") {
1763
+ streamCallbackBuffer?.discard();
1764
+ pushGenerated(msg);
1765
+ const toolDigest = (0, tool_arguments_1.digestJson)({
1766
+ name: protectedCall.call.name,
1767
+ schemaDigest: protectedCall.validated.schemaDigest,
1768
+ policyId: protectedCall.policy.policyId,
1769
+ });
1770
+ const policyDigest = (0, tool_arguments_1.digestJson)({
1771
+ policyId: protectedCall.policy.policyId,
1772
+ actionClass: protectedCall.policy.actionClass,
1773
+ classification: "required",
1774
+ });
1775
+ const committed = await options.approvalCoordinator.propose({
1776
+ toolCall: structuredClone(msg.tool_calls[0]),
1777
+ arguments: structuredClone(protectedCall.validated.arguments),
1778
+ preCallMessages,
1779
+ frozenAssistantMessage: structuredClone(msg),
1780
+ schemaDigest: protectedCall.validated.schemaDigest,
1781
+ toolDigest,
1782
+ policyDigest,
1783
+ policyId: protectedCall.policy.policyId,
1784
+ actionClass: protectedCall.policy.actionClass,
1785
+ });
1786
+ suspension = {
1787
+ approvalId: committed.approvalId,
1788
+ toolCallId: protectedCall.call.id,
1789
+ checkpointDigest: committed.checkpointDigest,
1790
+ suspendedSessionRevision: committed.suspendedSessionRevision,
1791
+ };
1792
+ outcome = "suspended";
584
1793
  done = true;
1794
+ (0, runtime_1.emitNervesEvent)({
1795
+ component: "engine",
1796
+ event: "engine.approval_turn_suspended",
1797
+ message: "agent turn suspended before protected tool execution",
1798
+ meta: { approvalId: committed.approvalId, toolCallId: protectedCall.call.id },
1799
+ });
585
1800
  continue;
586
1801
  }
587
- messages.push(msg);
588
- // SHARED: execute tools (final_answer and no_response in mixed calls are rejected inline)
1802
+ const containsSoleCallOnlyViolation = result.toolCalls.length > 1
1803
+ && result.toolCalls.some((call) => {
1804
+ const terminalProjection = (0, tools_1.resolveToolDefinition)(call.name)?.terminalProjection;
1805
+ return SOLE_CALL_REJECTION[call.name] !== undefined
1806
+ || terminalProjection?.requiresSoleCall === true;
1807
+ });
1808
+ if (callbacks.settleOutputMode === "final_only" && containsSoleCallOnlyViolation) {
1809
+ streamCallbackBuffer?.discard();
1810
+ }
1811
+ else {
1812
+ await streamCallbackBuffer?.flush();
1813
+ }
1814
+ pushGenerated(msg);
1815
+ // Execute tools (sole-call tools in mixed calls are rejected inline)
589
1816
  for (const tc of result.toolCalls) {
590
1817
  if (signal?.aborted)
591
1818
  break;
592
- // Intercept final_answer in mixed call: reject it
593
- if (tc.name === "final_answer") {
594
- const rejection = "rejected: final_answer must be the only tool call. Finish your work first, then call final_answer alone.";
595
- messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
1819
+ if (tc.name === "speak" && !activeToolNames.has("speak")) {
1820
+ const rejection = "rejected: speak was not advertised for this channel; no outward message was sent.";
1821
+ callbacks.onToolStart(tc.name, {});
1822
+ callbacks.onToolEnd(tc.name, "", false);
1823
+ pushGenerated({ role: "tool", tool_call_id: tc.id, content: rejection });
596
1824
  providerRuntime.appendToolOutput(tc.id, rejection);
1825
+ (0, runtime_1.emitNervesEvent)({
1826
+ level: "warn",
1827
+ component: "engine",
1828
+ event: "engine.unadvertised_speak_blocked",
1829
+ message: "blocked an unadvertised speak tool call",
1830
+ meta: { channel: String(channel) },
1831
+ });
597
1832
  continue;
598
1833
  }
599
- // Intercept no_response in mixed call: reject it
600
- if (tc.name === "no_response") {
601
- const rejection = "rejected: no_response must be the only tool call. call no_response alone when you want to stay silent.";
602
- messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
603
- providerRuntime.appendToolOutput(tc.id, rejection);
1834
+ // Reject sole-call tools when mixed with other tool calls
1835
+ const terminalProjection = (0, tools_1.resolveToolDefinition)(tc.name)?.terminalProjection;
1836
+ const soleCallRejection = SOLE_CALL_REJECTION[tc.name]
1837
+ ?? (terminalProjection?.requiresSoleCall
1838
+ ? `rejected: ${tc.name} must be the only tool call.`
1839
+ : undefined);
1840
+ if (soleCallRejection) {
1841
+ pushGenerated({ role: "tool", tool_call_id: tc.id, content: soleCallRejection });
1842
+ providerRuntime.appendToolOutput(tc.id, soleCallRejection);
604
1843
  continue;
605
1844
  }
606
1845
  let args = {};
@@ -610,105 +1849,309 @@ async function runAgent(messages, callbacks, channel, signal, options) {
610
1849
  catch {
611
1850
  /* ignore */
612
1851
  }
613
- const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
614
- // Confirmation check for mutate tools
615
- if ((0, tools_1.isConfirmationRequired)(tc.name) && !options?.skipConfirmation) {
616
- let decision = "denied";
617
- if (callbacks.onConfirmAction) {
618
- decision = await callbacks.onConfirmAction(tc.name, args);
619
- }
620
- if (decision !== "confirmed") {
621
- const cancelled = "Action cancelled by user.";
1852
+ if (tc.name === "send_message" && args.friendId === "self") {
1853
+ const latestUserText = latestUserMessageText(messages);
1854
+ if (!isPrivateRuntimeChannel && looksLikePrivateReturnRequest(latestUserText)) {
1855
+ const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
1856
+ 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.";
622
1857
  callbacks.onToolStart(tc.name, args);
623
1858
  callbacks.onToolEnd(tc.name, argSummary, false);
624
- messages.push({ role: "tool", tool_call_id: tc.id, content: cancelled });
625
- providerRuntime.appendToolOutput(tc.id, cancelled);
1859
+ pushGenerated({ role: "tool", tool_call_id: tc.id, content: rejection });
1860
+ providerRuntime.appendToolOutput(tc.id, rejection);
1861
+ continue;
1862
+ }
1863
+ sawSendMessageSelf = true;
1864
+ }
1865
+ if (tc.name === "speak") {
1866
+ let speakArgs = {};
1867
+ try {
1868
+ speakArgs = JSON.parse(tc.arguments);
1869
+ }
1870
+ catch { /* malformed */ }
1871
+ const speakMessage = typeof speakArgs.message === "string" ? speakArgs.message : "";
1872
+ const argSummary = (0, tools_1.summarizeArgs)("speak", { message: speakMessage });
1873
+ callbacks.onToolStart("speak", { message: speakMessage });
1874
+ if (speakMessage.trim().length === 0) {
1875
+ const err = "speak requires a non-empty `message` string.";
1876
+ callbacks.onToolEnd("speak", argSummary, false);
1877
+ pushGenerated({ role: "tool", tool_call_id: tc.id, content: err });
1878
+ providerRuntime.appendToolOutput(tc.id, err);
1879
+ (0, runtime_1.emitNervesEvent)({
1880
+ level: "warn",
1881
+ component: "engine",
1882
+ event: "engine.speak_invalid",
1883
+ message: "speak rejected: missing or empty message",
1884
+ meta: {},
1885
+ });
626
1886
  continue;
627
1887
  }
1888
+ callbacks.onTextChunk(speakMessage);
1889
+ let speakDeliveryError = null;
1890
+ try {
1891
+ await callbacks.flushNow?.();
1892
+ }
1893
+ catch (err) {
1894
+ speakDeliveryError = err instanceof Error ? err : new Error(String(err));
1895
+ }
1896
+ if (speakDeliveryError) {
1897
+ callbacks.onToolEnd("speak", argSummary, false);
1898
+ const failMsg = `speak delivery failed: ${speakDeliveryError.message}. the message did not reach your friend; do not assume they saw it.`;
1899
+ pushGenerated({ role: "tool", tool_call_id: tc.id, content: failMsg });
1900
+ providerRuntime.appendToolOutput(tc.id, failMsg);
1901
+ (0, runtime_1.emitNervesEvent)({
1902
+ level: "error",
1903
+ component: "engine",
1904
+ event: "engine.speak_delivery_failed",
1905
+ message: "speak delivery failed",
1906
+ meta: { error: speakDeliveryError.message, messageLength: speakMessage.length },
1907
+ });
1908
+ continue;
1909
+ }
1910
+ callbacks.onToolEnd("speak", argSummary, true);
1911
+ const ack = "(spoken)";
1912
+ pushGenerated({ role: "tool", tool_call_id: tc.id, content: ack });
1913
+ providerRuntime.appendToolOutput(tc.id, ack);
1914
+ (0, runtime_1.emitNervesEvent)({
1915
+ component: "engine",
1916
+ event: "engine.speak",
1917
+ message: "agent spoke mid-turn",
1918
+ meta: { messageLength: speakMessage.length },
1919
+ });
1920
+ continue;
1921
+ }
1922
+ if (tc.name === "ponder") {
1923
+ const parsedArgs = normalizeLegacyPonderArgs(parsePonderPayload(tc.arguments));
1924
+ const argSummary = (0, tools_1.summarizeArgs)(tc.name, parsedArgs);
1925
+ callbacks.onToolStart(tc.name, parsedArgs);
1926
+ let toolResult;
1927
+ let success = false;
1928
+ try {
1929
+ const action = parsedArgs.action ?? "create";
1930
+ const currentSession = augmentedToolContext?.currentSession;
1931
+ const currentOrigin = currentSession
1932
+ ? { friendId: currentSession.friendId, channel: currentSession.channel, key: currentSession.key }
1933
+ : undefined;
1934
+ const isInnerChannel = currentOrigin?.friendId === "self" && currentOrigin?.channel === "inner";
1935
+ const shouldCreateReturnObligation = !!currentOrigin && !isInnerChannel;
1936
+ const attentionQueue = augmentedToolContext?.delegatedOrigins ?? [];
1937
+ const successCriteria = parseSuccessCriteria(parsedArgs.success_criteria);
1938
+ const payload = parsePacketPayload(parsedArgs.payload_json);
1939
+ let packet;
1940
+ let returnObligationId = null;
1941
+ let resultAction = "created";
1942
+ let privateReturnSourceRequest = "";
1943
+ if (action === "create") {
1944
+ if (isInnerChannel && attentionQueue.length > 0) {
1945
+ 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.");
1946
+ }
1947
+ const kind = parsedArgs.kind;
1948
+ const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
1949
+ const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
1950
+ const sourceRequest = currentOrigin && !isInnerChannel ? latestUserMessageText(messages) : "";
1951
+ privateReturnSourceRequest = sourceRequest;
1952
+ if (!kind || !objective || !successCriteria || !payload) {
1953
+ throw new Error("ponder create requires kind, objective, success_criteria, and valid payload_json.");
1954
+ }
1955
+ const packetPayload = sourceRequest
1956
+ ? { ...payload, sourceRequest }
1957
+ : payload;
1958
+ const createLinkedReturnObligation = (id, packetId) => {
1959
+ (0, obligations_1.createReturnObligation)((0, identity_2.getAgentName)(), {
1960
+ id,
1961
+ origin: currentOrigin,
1962
+ status: "queued",
1963
+ delegatedContent: buildPonderDelegatedContent({ summary, objective, sourceRequest }),
1964
+ packetId,
1965
+ createdAt: Date.now(),
1966
+ });
1967
+ };
1968
+ const agentRoot = (0, identity_2.getAgentRoot)();
1969
+ let relatedObligationId;
1970
+ if (currentOrigin && !isInnerChannel) {
1971
+ try {
1972
+ const obligation = (0, obligations_1.createObligation)(agentRoot, {
1973
+ origin: currentOrigin,
1974
+ content: objective,
1975
+ });
1976
+ relatedObligationId = obligation.id;
1977
+ }
1978
+ catch {
1979
+ relatedObligationId = undefined;
1980
+ }
1981
+ }
1982
+ const frictionSignature = kind === "harness_friction" && typeof packetPayload.frictionSignature === "string"
1983
+ ? packetPayload.frictionSignature
1984
+ : null;
1985
+ const existing = frictionSignature && currentOrigin
1986
+ ? (0, packets_1.findHarnessFrictionPacket)(agentRoot, currentOrigin, frictionSignature)
1987
+ : null;
1988
+ if (existing) {
1989
+ resultAction = "revised";
1990
+ const existingActiveReturnId = shouldCreateReturnObligation
1991
+ ? activeReturnObligationId((0, identity_2.getAgentName)(), existing.relatedReturnObligationId)
1992
+ : null;
1993
+ returnObligationId = existingActiveReturnId
1994
+ ?? (shouldCreateReturnObligation ? (0, obligations_1.generateObligationId)(Date.now()) : null);
1995
+ packet = existing.status === "drafting"
1996
+ ? (0, packets_1.revisePonderPacket)(agentRoot, existing.id, {
1997
+ kind,
1998
+ objective,
1999
+ summary,
2000
+ successCriteria,
2001
+ payload: packetPayload,
2002
+ })
2003
+ : existing;
2004
+ if (returnObligationId && returnObligationId !== existing.relatedReturnObligationId) {
2005
+ packet = (0, packets_1.advancePonderPacket)(agentRoot, packet.id, { relatedReturnObligationId: returnObligationId });
2006
+ createLinkedReturnObligation(returnObligationId, packet.id);
2007
+ }
2008
+ }
2009
+ else {
2010
+ returnObligationId = shouldCreateReturnObligation ? (0, obligations_1.generateObligationId)(Date.now()) : null;
2011
+ packet = (0, packets_1.createPonderPacket)(agentRoot, {
2012
+ kind,
2013
+ objective,
2014
+ summary,
2015
+ successCriteria,
2016
+ ...(currentOrigin ? { origin: currentOrigin } : {}),
2017
+ ...(relatedObligationId ? { relatedObligationId } : {}),
2018
+ ...(returnObligationId ? { relatedReturnObligationId: returnObligationId } : {}),
2019
+ ...(parsedArgs.follows_packet_id ? { followsPacketId: parsedArgs.follows_packet_id } : {}),
2020
+ payload: packetPayload,
2021
+ });
2022
+ if (returnObligationId) {
2023
+ createLinkedReturnObligation(returnObligationId, packet.id);
2024
+ }
2025
+ }
2026
+ }
2027
+ else if (action === "revise") {
2028
+ const packetId = typeof parsedArgs.packet_id === "string" ? parsedArgs.packet_id.trim() : "";
2029
+ const kind = parsedArgs.kind;
2030
+ const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
2031
+ const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
2032
+ if (!packetId || !kind || !objective || !successCriteria || !payload) {
2033
+ throw new Error("ponder revise requires packet_id, kind, objective, success_criteria, and valid payload_json.");
2034
+ }
2035
+ packet = (0, packets_1.revisePonderPacket)((0, identity_2.getAgentRoot)(), packetId, {
2036
+ kind,
2037
+ objective,
2038
+ summary,
2039
+ successCriteria,
2040
+ payload,
2041
+ });
2042
+ returnObligationId = packet.relatedReturnObligationId
2043
+ && !(packet.origin?.friendId === "self" && packet.origin.channel === "inner")
2044
+ ? packet.relatedReturnObligationId
2045
+ : null;
2046
+ resultAction = "revised";
2047
+ }
2048
+ else {
2049
+ throw new Error("ponder requires action=create or revise.");
2050
+ }
2051
+ if (returnObligationId) {
2052
+ for (const token of extractPrivateReturnHeldTokens(privateReturnSourceRequest)) {
2053
+ privateReturnHeldTokens.add(token);
2054
+ }
2055
+ const agentName = (0, identity_2.getAgentName)();
2056
+ await (0, socket_client_1.requestPrivateWake)(agentName, augmentedToolContext?.daemonSocketPath, buildPonderReturnPrivateWakeOptions({ agentName, packet, returnObligationId })).catch(() => undefined);
2057
+ }
2058
+ sawPonder = true;
2059
+ toolResult = buildPonderResult(packet, resultAction, returnObligationId);
2060
+ success = true;
2061
+ (0, runtime_1.emitNervesEvent)({
2062
+ component: "engine",
2063
+ event: "engine.ponder_packet",
2064
+ message: "ponder packet touched",
2065
+ meta: {
2066
+ action: resultAction,
2067
+ packetId: packet.id,
2068
+ kind: packet.kind,
2069
+ status: packet.status,
2070
+ },
2071
+ });
2072
+ }
2073
+ catch (error) {
2074
+ toolResult = error instanceof Error ? error.message : String(error);
2075
+ }
2076
+ callbacks.onToolEnd(tc.name, argSummary, success);
2077
+ pushGenerated({ role: "tool", tool_call_id: tc.id, content: toolResult });
2078
+ providerRuntime.appendToolOutput(tc.id, toolResult);
2079
+ continue;
2080
+ }
2081
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
2082
+ if (tc.name === "query_session")
2083
+ sawQuerySession = true;
2084
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
2085
+ if (tc.name === "bridge_manage")
2086
+ sawBridgeManage = true;
2087
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
2088
+ if (isExternalStateQuery(tc.name, args))
2089
+ sawExternalStateQuery = true;
2090
+ const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
2091
+ const toolLoop = (0, tool_loop_1.detectToolLoop)(toolLoopState, tc.name, args);
2092
+ if (toolLoop.stuck) {
2093
+ const rejection = `loop guard: ${toolLoop.message}`;
2094
+ callbacks.onToolStart(tc.name, args);
2095
+ callbacks.onToolEnd(tc.name, argSummary, false);
2096
+ pushGenerated({ role: "tool", tool_call_id: tc.id, content: rejection });
2097
+ providerRuntime.appendToolOutput(tc.id, rejection);
2098
+ continue;
628
2099
  }
629
2100
  callbacks.onToolStart(tc.name, args);
630
2101
  let toolResult;
631
2102
  let success;
632
2103
  try {
633
2104
  const execToolFn = options?.execTool ?? tools_1.execTool;
634
- toolResult = await execToolFn(tc.name, args, augmentedToolContext ?? options?.toolContext);
2105
+ toolResult = await execToolFn(tc.name, args, augmentedToolContext);
635
2106
  success = true;
636
2107
  }
637
2108
  catch (e) {
638
2109
  toolResult = `error: ${e}`;
639
2110
  success = false;
2111
+ augmentedToolContext?.habitSession?.recordError?.(toolResult);
640
2112
  }
641
- callbacks.onToolEnd(tc.name, argSummary, success);
642
- messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
2113
+ toolResult = (0, tool_friction_1.rewriteToolResultForModel)(tc.name, toolResult, toolFrictionLedger);
2114
+ (0, tool_loop_1.recordToolOutcome)(toolLoopState, tc.name, args, toolResult, success);
2115
+ callbacks.onToolEnd(tc.name, (0, tools_1.buildToolResultSummary)(tc.name, args, toolResult, success), success);
2116
+ pushGenerated({ role: "tool", tool_call_id: tc.id, content: toolResult });
643
2117
  providerRuntime.appendToolOutput(tc.id, toolResult);
2118
+ callbacks.onToolResult?.(messages);
644
2119
  }
645
2120
  }
646
2121
  }
647
2122
  catch (e) {
648
2123
  // Abort is not an error — just stop cleanly
649
- if (signal?.aborted) {
2124
+ if (e instanceof provider_attempt_1.ProviderAttemptAbortError || signal?.aborted) {
650
2125
  stripLastToolCalls(messages);
2126
+ stripLastToolCalls(generatedMessages);
651
2127
  outcome = "aborted";
652
2128
  break;
653
2129
  }
654
- // Context overflow: trim aggressively and retry once
655
- if (isContextOverflow(e) && !overflowRetried) {
656
- overflowRetried = true;
657
- stripLastToolCalls(messages);
658
- const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
659
- const trimmed = (0, context_1.trimMessages)(messages, maxTokens, contextMargin, maxTokens * 2);
660
- messages.splice(0, messages.length, ...trimmed);
661
- providerRuntime.resetTurnState(messages);
662
- callbacks.onError(new Error("context trimmed, retrying..."), "transient");
663
- continue;
2130
+ const errorForClassification = e instanceof Error ? e : /* v8 ignore next -- defensive @preserve */ new Error(String(e));
2131
+ let providerClassification;
2132
+ try {
2133
+ providerClassification = providerRuntime.classifyError(errorForClassification);
664
2134
  }
665
- // Transient errors: retry with exponential backoff
666
- if (isTransientError(e) && retryCount < MAX_RETRIES) {
667
- retryCount++;
668
- const delay = RETRY_BASE_MS * Math.pow(2, retryCount - 1);
669
- const cause = classifyTransientError(e);
670
- callbacks.onError(new Error(`${cause}, retrying in ${delay / 1000}s (${retryCount}/${MAX_RETRIES})...`), "transient");
671
- // Wait with abort support
672
- const aborted = await new Promise((resolve) => {
673
- const timer = setTimeout(() => resolve(false), delay);
674
- if (signal) {
675
- const onAbort = () => { clearTimeout(timer); resolve(true); };
676
- if (signal.aborted) {
677
- clearTimeout(timer);
678
- resolve(true);
679
- return;
680
- }
681
- signal.addEventListener("abort", onAbort, { once: true });
682
- }
683
- });
684
- if (aborted) {
685
- stripLastToolCalls(messages);
686
- outcome = "aborted";
687
- break;
688
- }
689
- providerRuntime.resetTurnState(messages);
690
- continue;
2135
+ catch {
2136
+ /* v8 ignore next -- defensive: classifyError should not throw @preserve */
2137
+ providerClassification = "unknown";
691
2138
  }
692
- callbacks.onError(e instanceof Error ? e : new Error(String(e)), "terminal");
693
- (0, runtime_1.emitNervesEvent)({
694
- level: "error",
695
- event: "engine.error",
696
- trace_id: traceId,
697
- component: "engine",
698
- message: e instanceof Error ? e.message : String(e),
699
- meta: {},
700
- });
701
- stripLastToolCalls(messages);
702
- outcome = "errored";
703
- done = true;
2139
+ finishTerminalProviderError(errorForClassification, providerClassification);
704
2140
  }
705
2141
  }
2142
+ options?.captureGeneratedMessages?.(structuredClone(generatedMessages));
706
2143
  (0, runtime_1.emitNervesEvent)({
707
2144
  event: "engine.turn_end",
708
2145
  trace_id: traceId,
709
2146
  component: "engine",
710
2147
  message: "runAgent turn completed",
711
- meta: { done },
2148
+ meta: { done, sawPonder, sawQuerySession, sawBridgeManage },
712
2149
  });
713
- return { usage: lastUsage, outcome, completion };
2150
+ return {
2151
+ usage: lastUsage,
2152
+ outcome,
2153
+ completion,
2154
+ ...(suspension ? { suspension } : {}),
2155
+ ...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
2156
+ };
714
2157
  }