@ouro.bot/cli 0.1.0-alpha.3 → 0.1.0-alpha.300

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 (289) hide show
  1. package/README.md +188 -190
  2. package/SerpentGuide.ouro/agent.json +82 -0
  3. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +6 -3
  4. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +2 -2
  5. package/SerpentGuide.ouro/psyche/identities/python.md +31 -0
  6. package/assets/ouroboros.png +0 -0
  7. package/changelog.json +1888 -0
  8. package/dist/arc/attention-types.js +8 -0
  9. package/dist/arc/cares.js +140 -0
  10. package/dist/arc/episodes.js +117 -0
  11. package/dist/arc/intentions.js +133 -0
  12. package/dist/arc/json-store.js +117 -0
  13. package/dist/arc/obligations.js +237 -0
  14. package/dist/arc/packets.js +203 -0
  15. package/dist/arc/presence.js +185 -0
  16. package/dist/heart/active-work.js +832 -0
  17. package/dist/heart/agent-entry.js +37 -2
  18. package/dist/heart/attachments/image-normalize.js +194 -0
  19. package/dist/heart/attachments/materialize.js +230 -0
  20. package/dist/heart/attachments/render.js +29 -0
  21. package/dist/heart/attachments/store.js +103 -0
  22. package/dist/heart/attachments/types.js +138 -0
  23. package/dist/heart/auth/auth-flow.js +456 -0
  24. package/dist/heart/bridges/manager.js +358 -0
  25. package/dist/heart/bridges/state-machine.js +135 -0
  26. package/dist/heart/bridges/store.js +123 -0
  27. package/dist/heart/bundle-state.js +168 -0
  28. package/dist/heart/commitments.js +111 -0
  29. package/dist/heart/config-registry.js +304 -0
  30. package/dist/heart/config.js +123 -28
  31. package/dist/heart/core.js +738 -191
  32. package/dist/heart/cross-chat-delivery.js +131 -0
  33. package/dist/heart/daemon/agent-config-check.js +149 -0
  34. package/dist/heart/daemon/agent-discovery.js +157 -0
  35. package/dist/heart/daemon/agent-service.js +360 -0
  36. package/dist/heart/daemon/cadence.js +70 -0
  37. package/dist/heart/daemon/cli-defaults.js +574 -0
  38. package/dist/heart/daemon/cli-exec.js +1945 -0
  39. package/dist/heart/daemon/cli-parse.js +808 -0
  40. package/dist/heart/daemon/cli-render.js +503 -0
  41. package/dist/heart/daemon/cli-types.js +8 -0
  42. package/dist/heart/daemon/daemon-cli.js +29 -673
  43. package/dist/heart/daemon/daemon-entry.js +259 -8
  44. package/dist/heart/daemon/daemon-health.js +136 -0
  45. package/dist/heart/daemon/daemon-runtime-sync.js +231 -0
  46. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  47. package/dist/heart/daemon/daemon.js +745 -18
  48. package/dist/heart/daemon/health-monitor.js +38 -0
  49. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  50. package/dist/heart/daemon/hooks/bundle-meta.js +206 -0
  51. package/dist/heart/daemon/inner-status.js +89 -0
  52. package/dist/heart/daemon/launchd.js +171 -0
  53. package/dist/heart/daemon/log-tailer.js +82 -12
  54. package/dist/heart/daemon/logs-prune.js +105 -0
  55. package/dist/heart/daemon/message-router.js +17 -8
  56. package/dist/heart/daemon/os-cron-deps.js +134 -0
  57. package/dist/heart/daemon/ouro-bot-entry.js +1 -1
  58. package/dist/heart/daemon/process-manager.js +181 -1
  59. package/dist/heart/daemon/pulse.js +463 -0
  60. package/dist/heart/daemon/run-hooks.js +39 -0
  61. package/dist/heart/daemon/runtime-logging.js +70 -15
  62. package/dist/heart/daemon/runtime-metadata.js +219 -0
  63. package/dist/heart/daemon/runtime-mode.js +67 -0
  64. package/dist/heart/daemon/safe-mode.js +161 -0
  65. package/dist/heart/daemon/sense-manager.js +335 -0
  66. package/dist/heart/daemon/session-id-resolver.js +131 -0
  67. package/dist/heart/daemon/skill-management-installer.js +94 -0
  68. package/dist/heart/daemon/socket-client.js +307 -0
  69. package/dist/heart/daemon/task-scheduler.js +3 -25
  70. package/dist/heart/daemon/thoughts.js +510 -0
  71. package/dist/heart/delegation.js +62 -0
  72. package/dist/heart/habits/habit-migration.js +181 -0
  73. package/dist/heart/habits/habit-parser.js +140 -0
  74. package/dist/heart/habits/habit-scheduler.js +371 -0
  75. package/dist/heart/hatch/hatch-animation.js +35 -0
  76. package/dist/heart/{daemon → hatch}/hatch-flow.js +31 -130
  77. package/dist/heart/{daemon → hatch}/hatch-specialist.js +7 -2
  78. package/dist/heart/hatch/specialist-orchestrator.js +129 -0
  79. package/dist/heart/hatch/specialist-prompt.js +101 -0
  80. package/dist/heart/hatch/specialist-tools.js +283 -0
  81. package/dist/heart/identity.js +241 -54
  82. package/dist/heart/kicks.js +2 -20
  83. package/dist/heart/mcp/mcp-server.js +653 -0
  84. package/dist/heart/migrate-config.js +127 -0
  85. package/dist/heart/model-capabilities.js +59 -0
  86. package/dist/heart/outlook/outlook-http.js +439 -0
  87. package/dist/heart/outlook/outlook-read.js +1618 -0
  88. package/dist/heart/outlook/outlook-render.js +1032 -0
  89. package/dist/heart/outlook/outlook-types.js +7 -0
  90. package/dist/heart/outlook/outlook-view.js +194 -0
  91. package/dist/heart/progress-story.js +42 -0
  92. package/dist/heart/provider-failover.js +88 -0
  93. package/dist/heart/provider-ping.js +162 -0
  94. package/dist/heart/providers/anthropic-token.js +163 -0
  95. package/dist/heart/providers/anthropic.js +181 -41
  96. package/dist/heart/providers/azure.js +98 -11
  97. package/dist/heart/providers/error-classification.js +63 -0
  98. package/dist/heart/providers/github-copilot.js +136 -0
  99. package/dist/heart/providers/minimax-vlm.js +189 -0
  100. package/dist/heart/providers/minimax.js +23 -5
  101. package/dist/heart/providers/openai-codex.js +33 -22
  102. package/dist/heart/sense-truth.js +61 -0
  103. package/dist/heart/session-activity.js +172 -0
  104. package/dist/heart/session-recall.js +216 -0
  105. package/dist/heart/start-of-turn-packet.js +339 -0
  106. package/dist/heart/streaming.js +120 -33
  107. package/dist/heart/sync.js +332 -0
  108. package/dist/heart/target-resolution.js +127 -0
  109. package/dist/heart/tempo.js +93 -0
  110. package/dist/heart/temporal-view.js +41 -0
  111. package/dist/heart/tool-activity-callbacks.js +36 -0
  112. package/dist/heart/tool-description.js +135 -0
  113. package/dist/heart/tool-friction.js +55 -0
  114. package/dist/heart/tool-loop.js +200 -0
  115. package/dist/heart/turn-context.js +358 -0
  116. package/dist/heart/turn-coordinator.js +28 -0
  117. package/dist/heart/versioning/ouro-bot-global-installer.js +128 -0
  118. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +5 -4
  119. package/dist/heart/versioning/ouro-path-installer.js +221 -0
  120. package/dist/heart/{daemon → versioning}/ouro-uti.js +11 -2
  121. package/dist/heart/versioning/ouro-version-manager.js +295 -0
  122. package/dist/heart/versioning/staged-restart.js +146 -0
  123. package/dist/heart/versioning/update-checker.js +113 -0
  124. package/dist/heart/versioning/update-hooks.js +142 -0
  125. package/dist/heart/versioning/wrapper-publish-guard.js +86 -0
  126. package/dist/mind/associative-recall.js +135 -66
  127. package/dist/mind/bundle-manifest.js +77 -1
  128. package/dist/mind/context.js +125 -14
  129. package/dist/mind/diary-integrity.js +60 -0
  130. package/dist/mind/{memory.js → diary.js} +84 -96
  131. package/dist/mind/embedding-provider.js +60 -0
  132. package/dist/mind/file-state.js +179 -0
  133. package/dist/mind/first-impressions.js +16 -2
  134. package/dist/mind/friends/channel.js +64 -0
  135. package/dist/mind/friends/group-context.js +144 -0
  136. package/dist/mind/friends/resolver.js +37 -0
  137. package/dist/mind/friends/store-file.js +58 -3
  138. package/dist/mind/friends/trust-explanation.js +74 -0
  139. package/dist/mind/friends/types.js +9 -1
  140. package/dist/mind/journal-index.js +161 -0
  141. package/dist/mind/obligation-steering.js +221 -0
  142. package/dist/mind/pending.js +76 -9
  143. package/dist/mind/phrases.js +1 -0
  144. package/dist/mind/prompt.js +1011 -107
  145. package/dist/mind/scrutiny.js +173 -0
  146. package/dist/mind/token-estimate.js +8 -12
  147. package/dist/nerves/cli-logging.js +22 -3
  148. package/dist/nerves/coverage/audit.js +1 -1
  149. package/dist/nerves/coverage/file-completeness.js +59 -5
  150. package/dist/nerves/coverage/run-artifacts.js +1 -1
  151. package/dist/nerves/event-buffer.js +111 -0
  152. package/dist/nerves/index.js +224 -4
  153. package/dist/nerves/observation.js +20 -0
  154. package/dist/nerves/redact.js +79 -0
  155. package/dist/nerves/runtime.js +5 -1
  156. package/dist/outlook-ui/assets/index-Ck8agNeO.js +61 -0
  157. package/dist/outlook-ui/assets/index-LwChZTgL.css +1 -0
  158. package/dist/outlook-ui/index.html +15 -0
  159. package/dist/repertoire/ado-client.js +17 -56
  160. package/dist/repertoire/ado-semantic.js +11 -10
  161. package/dist/repertoire/api-client.js +97 -0
  162. package/dist/repertoire/bitwarden-store.js +319 -0
  163. package/dist/repertoire/bundle-templates.js +72 -0
  164. package/dist/repertoire/bw-installer.js +79 -0
  165. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  166. package/dist/repertoire/coding/context-pack.js +330 -0
  167. package/dist/repertoire/coding/feedback.js +301 -0
  168. package/dist/repertoire/coding/index.js +4 -1
  169. package/dist/repertoire/coding/manager.js +220 -13
  170. package/dist/repertoire/coding/spawner.js +58 -12
  171. package/dist/repertoire/coding/tools.js +209 -7
  172. package/dist/repertoire/commerce-errors.js +109 -0
  173. package/dist/repertoire/commerce-self-test.js +156 -0
  174. package/dist/repertoire/credential-access.js +527 -0
  175. package/dist/repertoire/data/ado-endpoints.json +188 -0
  176. package/dist/repertoire/duffel-client.js +185 -0
  177. package/dist/repertoire/github-client.js +14 -55
  178. package/dist/repertoire/graph-client.js +11 -52
  179. package/dist/repertoire/guardrails.js +375 -0
  180. package/dist/repertoire/mcp-client.js +255 -0
  181. package/dist/repertoire/mcp-manager.js +305 -0
  182. package/dist/repertoire/mcp-tools.js +63 -0
  183. package/dist/repertoire/shell-sessions.js +133 -0
  184. package/dist/repertoire/skills.js +14 -23
  185. package/dist/repertoire/stripe-client.js +131 -0
  186. package/dist/repertoire/tasks/board.js +43 -5
  187. package/dist/repertoire/tasks/fix.js +182 -0
  188. package/dist/repertoire/tasks/index.js +28 -10
  189. package/dist/repertoire/tasks/lifecycle.js +2 -2
  190. package/dist/repertoire/tasks/parser.js +3 -2
  191. package/dist/repertoire/tasks/scanner.js +194 -37
  192. package/dist/repertoire/tasks/transitions.js +11 -28
  193. package/dist/repertoire/tool-results.js +29 -0
  194. package/dist/repertoire/tools-attachments.js +316 -0
  195. package/dist/repertoire/tools-base.js +45 -707
  196. package/dist/repertoire/tools-bluebubbles.js +94 -0
  197. package/dist/repertoire/tools-bridge.js +141 -0
  198. package/dist/repertoire/tools-bundle.js +984 -0
  199. package/dist/repertoire/tools-config.js +185 -0
  200. package/dist/repertoire/tools-continuity.js +248 -0
  201. package/dist/repertoire/tools-credential.js +182 -0
  202. package/dist/repertoire/tools-files.js +342 -0
  203. package/dist/repertoire/tools-flight.js +224 -0
  204. package/dist/repertoire/tools-flow.js +105 -0
  205. package/dist/repertoire/tools-github.js +1 -7
  206. package/dist/repertoire/tools-memory.js +374 -0
  207. package/dist/repertoire/tools-session.js +739 -0
  208. package/dist/repertoire/tools-shell.js +120 -0
  209. package/dist/repertoire/tools-stripe.js +180 -0
  210. package/dist/repertoire/tools-surface.js +243 -0
  211. package/dist/repertoire/tools-teams.js +64 -61
  212. package/dist/repertoire/tools-travel.js +125 -0
  213. package/dist/repertoire/tools-user-profile.js +144 -0
  214. package/dist/repertoire/tools-vault.js +110 -0
  215. package/dist/repertoire/tools.js +149 -98
  216. package/dist/repertoire/travel-api-client.js +360 -0
  217. package/dist/repertoire/user-profile.js +118 -0
  218. package/dist/repertoire/vault-setup.js +241 -0
  219. package/dist/scripts/claude-code-hook.js +41 -0
  220. package/dist/scripts/claude-code-stop-hook.js +47 -0
  221. package/dist/senses/attention-queue.js +116 -0
  222. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  223. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  224. package/dist/senses/bluebubbles/client.js +568 -0
  225. package/dist/senses/bluebubbles/entry.js +13 -0
  226. package/dist/senses/bluebubbles/inbound-log.js +113 -0
  227. package/dist/senses/bluebubbles/index.js +1427 -0
  228. package/dist/senses/bluebubbles/media.js +390 -0
  229. package/dist/senses/bluebubbles/model.js +282 -0
  230. package/dist/senses/bluebubbles/mutation-log.js +116 -0
  231. package/dist/senses/bluebubbles/replay.js +129 -0
  232. package/dist/senses/bluebubbles/runtime-state.js +109 -0
  233. package/dist/senses/bluebubbles/session-cleanup.js +72 -0
  234. package/dist/senses/cli/bracketed-paste.js +82 -0
  235. package/dist/senses/cli/image-paste.js +287 -0
  236. package/dist/senses/cli/image-ref-navigation.js +75 -0
  237. package/dist/senses/cli/ink-app.js +156 -0
  238. package/dist/senses/cli/inline-diff.js +64 -0
  239. package/dist/senses/cli/input-keys.js +174 -0
  240. package/dist/senses/cli/kill-ring.js +86 -0
  241. package/dist/senses/cli/message-list.js +51 -0
  242. package/dist/senses/cli/ouro-tui.js +595 -0
  243. package/dist/senses/cli/spinner-imperative.js +135 -0
  244. package/dist/senses/cli/spinner.js +101 -0
  245. package/dist/senses/cli/status-line.js +60 -0
  246. package/dist/senses/cli/streaming-markdown.js +526 -0
  247. package/dist/senses/cli/tool-display.js +83 -0
  248. package/dist/senses/cli/tool-render.js +85 -0
  249. package/dist/senses/cli/tui-store.js +240 -0
  250. package/dist/senses/cli/virtual-list.js +35 -0
  251. package/dist/senses/cli-entry.js +1 -1
  252. package/dist/senses/cli-layout.js +187 -0
  253. package/dist/senses/cli.js +772 -264
  254. package/dist/senses/commands.js +65 -1
  255. package/dist/senses/continuity.js +94 -0
  256. package/dist/senses/habit-turn-message.js +108 -0
  257. package/dist/senses/inner-dialog-worker.js +112 -19
  258. package/dist/senses/inner-dialog.js +633 -86
  259. package/dist/senses/pipeline.js +560 -0
  260. package/dist/senses/shared-turn.js +195 -0
  261. package/dist/senses/surface-tool.js +68 -0
  262. package/dist/senses/teams.js +814 -196
  263. package/dist/senses/trust-gate.js +112 -2
  264. package/package.json +25 -9
  265. package/skills/agent-commerce.md +106 -0
  266. package/skills/browser-navigation.md +110 -0
  267. package/skills/commerce-setup-guide.md +116 -0
  268. package/skills/commerce-setup.md +84 -0
  269. package/skills/configure-dev-tools.md +81 -0
  270. package/skills/travel-planning.md +138 -0
  271. package/AdoptionSpecialist.ouro/agent.json +0 -20
  272. package/AdoptionSpecialist.ouro/psyche/identities/python.md +0 -1
  273. package/dist/heart/daemon/subagent-installer.js +0 -125
  274. package/dist/inner-worker-entry.js +0 -4
  275. package/subagents/README.md +0 -73
  276. package/subagents/work-doer.md +0 -233
  277. package/subagents/work-merger.md +0 -624
  278. package/subagents/work-planner.md +0 -373
  279. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  280. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  281. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  282. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  283. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  284. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  285. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  286. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  287. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  288. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +0 -0
  289. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
@@ -1,22 +1,22 @@
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;
4
+ exports.resetProviderRuntime = resetProviderRuntime;
5
5
  exports.getModel = getModel;
6
6
  exports.getProvider = getProvider;
7
7
  exports.createSummarize = createSummarize;
8
8
  exports.getProviderDisplayLabel = getProviderDisplayLabel;
9
+ exports.isExternalStateQuery = isExternalStateQuery;
10
+ exports.getSettleRetryError = getSettleRetryError;
9
11
  exports.stripLastToolCalls = stripLastToolCalls;
10
- exports.isTransientError = isTransientError;
11
- exports.classifyTransientError = classifyTransientError;
12
+ exports.repairOrphanedToolCalls = repairOrphanedToolCalls;
13
+ exports.isRetryBlocked = isRetryBlocked;
12
14
  exports.runAgent = runAgent;
13
15
  const config_1 = require("./config");
14
16
  const identity_1 = require("./identity");
15
17
  const tools_1 = require("../repertoire/tools");
16
18
  const channel_1 = require("../mind/friends/channel");
17
- // Kick detection preserved but disabled — see comment in agent loop below.
18
- // import { detectKick } from "./kicks";
19
- // import type { KickReason } from "./kicks";
19
+ const tools_2 = require("../repertoire/tools");
20
20
  const runtime_1 = require("../nerves/runtime");
21
21
  const context_1 = require("../mind/context");
22
22
  const prompt_1 = require("../mind/prompt");
@@ -25,63 +25,97 @@ const anthropic_1 = require("./providers/anthropic");
25
25
  const azure_1 = require("./providers/azure");
26
26
  const minimax_1 = require("./providers/minimax");
27
27
  const openai_codex_1 = require("./providers/openai-codex");
28
- let _providerRuntime = null;
28
+ const github_copilot_1 = require("./providers/github-copilot");
29
+ const identity_2 = require("./identity");
30
+ const socket_client_1 = require("./daemon/socket-client");
31
+ const obligations_1 = require("../arc/obligations");
32
+ const tool_loop_1 = require("./tool-loop");
33
+ const packets_1 = require("../arc/packets");
34
+ const tool_friction_1 = require("./tool-friction");
35
+ const _providerRuntimes = {
36
+ human: null,
37
+ agent: null,
38
+ };
39
+ function getProviderRuntimeFingerprint(facing) {
40
+ const config = (0, identity_1.loadAgentConfig)();
41
+ const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
42
+ const provider = facingConfig.provider;
43
+ const model = facingConfig.model;
44
+ const providerConfig = (0, config_1.getProviderConfig)(provider);
45
+ return JSON.stringify({ provider, model, ...providerConfig });
46
+ }
29
47
  function createProviderRegistry() {
30
48
  const factories = {
31
49
  azure: azure_1.createAzureProviderRuntime,
32
50
  anthropic: anthropic_1.createAnthropicProviderRuntime,
33
51
  minimax: minimax_1.createMinimaxProviderRuntime,
34
52
  "openai-codex": openai_codex_1.createOpenAICodexProviderRuntime,
53
+ "github-copilot": github_copilot_1.createGithubCopilotProviderRuntime,
35
54
  };
36
55
  return {
37
- resolve() {
38
- const provider = (0, identity_1.loadAgentConfig)().provider;
39
- return factories[provider]();
56
+ resolve(provider, model) {
57
+ const resolvedProvider = provider ?? (0, identity_1.loadAgentConfig)().humanFacing.provider;
58
+ const resolvedModel = model ?? (0, identity_1.loadAgentConfig)().humanFacing.model;
59
+ return factories[resolvedProvider](resolvedModel);
40
60
  },
41
61
  };
42
62
  }
43
- function getProviderRuntime() {
44
- if (!_providerRuntime) {
45
- try {
46
- _providerRuntime = createProviderRegistry().resolve();
47
- }
48
- catch (error) {
49
- const msg = error instanceof Error ? error.message : String(error);
50
- (0, runtime_1.emitNervesEvent)({
51
- level: "error",
52
- event: "engine.provider_init_error",
53
- component: "engine",
54
- message: msg,
55
- meta: {},
56
- });
57
- // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
58
- console.error(`\n[fatal] ${msg}\n`);
59
- process.exit(1);
60
- throw new Error("unreachable");
61
- }
62
- if (!_providerRuntime) {
63
- (0, runtime_1.emitNervesEvent)({
64
- level: "error",
65
- event: "engine.provider_init_error",
66
- component: "engine",
67
- message: "provider runtime could not be initialized.",
68
- meta: {},
69
- });
70
- process.exit(1);
71
- throw new Error("unreachable");
63
+ function getProviderRuntime(facing = "human") {
64
+ try {
65
+ const fingerprint = getProviderRuntimeFingerprint(facing);
66
+ const cached = _providerRuntimes[facing];
67
+ if (!cached || cached.fingerprint !== fingerprint) {
68
+ const config = (0, identity_1.loadAgentConfig)();
69
+ const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
70
+ const runtime = createProviderRegistry().resolve(facingConfig.provider, facingConfig.model);
71
+ _providerRuntimes[facing] = runtime ? { fingerprint, runtime } : null;
72
72
  }
73
73
  }
74
- return _providerRuntime;
74
+ catch (error) {
75
+ const msg = error instanceof Error ? error.message : String(error);
76
+ (0, runtime_1.emitNervesEvent)({
77
+ level: "error",
78
+ event: "engine.provider_init_error",
79
+ component: "engine",
80
+ message: msg,
81
+ meta: {},
82
+ });
83
+ // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
84
+ console.error(`\n[fatal] ${msg}\n`);
85
+ process.exit(1);
86
+ throw new Error("unreachable");
87
+ }
88
+ if (!_providerRuntimes[facing]) {
89
+ (0, runtime_1.emitNervesEvent)({
90
+ level: "error",
91
+ event: "engine.provider_init_error",
92
+ component: "engine",
93
+ message: "provider runtime could not be initialized.",
94
+ meta: {},
95
+ });
96
+ process.exit(1);
97
+ throw new Error("unreachable");
98
+ }
99
+ return _providerRuntimes[facing].runtime;
75
100
  }
76
- function getModel() {
77
- return getProviderRuntime().model;
101
+ /**
102
+ * Clear the cached provider runtime so the next access re-creates it from
103
+ * current config. Runtime access also auto-refreshes when the selected
104
+ * provider fingerprint changes on disk.
105
+ */
106
+ function resetProviderRuntime() {
107
+ _providerRuntimes.human = null;
108
+ _providerRuntimes.agent = null;
78
109
  }
79
- function getProvider() {
80
- return getProviderRuntime().id;
110
+ function getModel(facing = "human") {
111
+ return getProviderRuntime(facing).model;
81
112
  }
82
- function createSummarize() {
113
+ function getProvider(facing = "human") {
114
+ return getProviderRuntime(facing).id;
115
+ }
116
+ function createSummarize(facing = "human") {
83
117
  return async (transcript, instruction) => {
84
- const runtime = getProviderRuntime();
118
+ const runtime = getProviderRuntime(facing);
85
119
  const client = runtime.client;
86
120
  const response = await client.chat.completions.create({
87
121
  model: runtime.model,
@@ -94,34 +128,138 @@ function createSummarize() {
94
128
  return response.choices?.[0]?.message?.content ?? transcript;
95
129
  };
96
130
  }
97
- function getProviderDisplayLabel() {
98
- const model = getModel();
131
+ function getProviderDisplayLabel(facing = "human") {
132
+ const config = (0, identity_1.loadAgentConfig)();
133
+ const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
134
+ const provider = facingConfig.provider;
135
+ const model = facingConfig.model || "unknown";
99
136
  const providerLabelBuilders = {
100
- azure: () => `azure openai (${(0, config_1.getAzureConfig)().deployment || "default"}, model: ${model})`,
137
+ azure: () => {
138
+ const azureCfg = (0, config_1.getAzureConfig)();
139
+ return `azure openai (${azureCfg.deployment || "default"}, model: ${model})`;
140
+ },
101
141
  anthropic: () => `anthropic (${model})`,
102
142
  minimax: () => `minimax (${model})`,
103
143
  "openai-codex": () => `openai codex (${model})`,
144
+ /* v8 ignore next -- branch: tested via display label unit test @preserve */
145
+ "github-copilot": () => `github copilot (${model})`,
146
+ };
147
+ return providerLabelBuilders[provider]();
148
+ }
149
+ // Sole-call tools must be the only tool call in a turn. When they appear
150
+ // alongside other tools, the sole-call tool is rejected with this message.
151
+ const SOLE_CALL_REJECTION = {
152
+ settle: "rejected: settle must be the only tool call. finish your work first, then call settle alone.",
153
+ observe: "rejected: observe must be the only tool call. call observe alone when you want to stay silent.",
154
+ rest: "rejected: rest must be the only tool call. finish your work first, then call rest alone.",
155
+ };
156
+ function parseSettlePayload(argumentsText) {
157
+ try {
158
+ const parsed = JSON.parse(argumentsText);
159
+ if (typeof parsed === "string") {
160
+ return { answer: parsed };
161
+ }
162
+ if (!parsed || typeof parsed !== "object") {
163
+ return {};
164
+ }
165
+ const answer = typeof parsed.answer === "string" ? parsed.answer : undefined;
166
+ const rawIntent = parsed.intent;
167
+ const intent = rawIntent === "complete" || rawIntent === "blocked" || rawIntent === "direct_reply"
168
+ ? rawIntent
169
+ : undefined;
170
+ return { answer, intent };
171
+ }
172
+ catch {
173
+ return {};
174
+ }
175
+ }
176
+ function parsePonderPayload(argumentsText) {
177
+ try {
178
+ const parsed = JSON.parse(argumentsText);
179
+ return parsed && typeof parsed === "object" ? parsed : {};
180
+ }
181
+ catch {
182
+ return {};
183
+ }
184
+ }
185
+ function parseSuccessCriteria(raw) {
186
+ if (typeof raw !== "string")
187
+ return null;
188
+ const criteria = raw
189
+ .split("\n")
190
+ .map((line) => line.replace(/^\s*[-*]\s*/, "").trim())
191
+ .filter((line) => line.length > 0);
192
+ return criteria.length > 0 ? criteria : null;
193
+ }
194
+ function parsePacketPayload(raw) {
195
+ if (typeof raw !== "string")
196
+ return null;
197
+ try {
198
+ const parsed = JSON.parse(raw);
199
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
200
+ ? parsed
201
+ : null;
202
+ }
203
+ catch {
204
+ return null;
205
+ }
206
+ }
207
+ function normalizeLegacyPonderArgs(parsed) {
208
+ if (typeof parsed.thought !== "string" || parsed.thought.trim().length === 0) {
209
+ return parsed;
210
+ }
211
+ return {
212
+ action: "create",
213
+ kind: "reflection",
214
+ objective: parsed.thought.trim(),
215
+ summary: typeof parsed.say === "string" ? parsed.say.trim() : "",
216
+ success_criteria: "- preserve the thread for later work",
217
+ payload_json: "{}",
104
218
  };
105
- return providerLabelBuilders[getProvider()]();
106
219
  }
107
- // Re-export tools, execTool, summarizeArgs from ./tools for backward compat
108
- var tools_2 = require("../repertoire/tools");
109
- Object.defineProperty(exports, "tools", { enumerable: true, get: function () { return tools_2.tools; } });
110
- Object.defineProperty(exports, "execTool", { enumerable: true, get: function () { return tools_2.execTool; } });
111
- Object.defineProperty(exports, "summarizeArgs", { enumerable: true, get: function () { return tools_2.summarizeArgs; } });
112
- Object.defineProperty(exports, "getToolsForChannel", { enumerable: true, get: function () { return tools_2.getToolsForChannel; } });
113
- // Re-export streaming functions for backward compat
114
- var streaming_1 = require("./streaming");
115
- Object.defineProperty(exports, "streamChatCompletion", { enumerable: true, get: function () { return streaming_1.streamChatCompletion; } });
116
- Object.defineProperty(exports, "streamResponsesApi", { enumerable: true, get: function () { return streaming_1.streamResponsesApi; } });
117
- Object.defineProperty(exports, "toResponsesInput", { enumerable: true, get: function () { return streaming_1.toResponsesInput; } });
118
- Object.defineProperty(exports, "toResponsesTools", { enumerable: true, get: function () { return streaming_1.toResponsesTools; } });
119
- // Re-export prompt functions for backward compat
120
- var prompt_2 = require("../mind/prompt");
121
- Object.defineProperty(exports, "buildSystem", { enumerable: true, get: function () { return prompt_2.buildSystem; } });
122
- // Re-export kick utilities for backward compat
123
- var kicks_1 = require("./kicks");
124
- Object.defineProperty(exports, "hasToolIntent", { enumerable: true, get: function () { return kicks_1.hasToolIntent; } });
220
+ function buildPonderResult(packet, action, returnObligationId) {
221
+ return JSON.stringify({
222
+ ok: true,
223
+ packet_id: packet.id,
224
+ action,
225
+ status: packet.status,
226
+ return_obligation_id: returnObligationId,
227
+ }, null, 2);
228
+ }
229
+ /** Returns true when a tool call queries external state (GitHub, npm registry). */
230
+ function isExternalStateQuery(toolName, args) {
231
+ if (toolName !== "shell")
232
+ return false;
233
+ const cmd = String(args.command ?? "");
234
+ return /\bgh\s+(pr|run|api|issue)\b/.test(cmd) || /\bnpm\s+(view|info|show)\b/.test(cmd);
235
+ }
236
+ function getSettleRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp, _delegationDecision, sawSendMessageSelf, sawPonder, _sawQuerySession, currentObligation, innerJob, sawExternalStateQuery) {
237
+ // Delegation adherence removed: the delegation decision is surfaced in the
238
+ // system prompt as a suggestion. Hard-gating settle caused infinite
239
+ // rejection loops where the agent couldn't respond to the user at all.
240
+ // The agent is free to follow or ignore the delegation hint.
241
+ // 2. Pending obligation not addressed
242
+ if (innerJob?.obligationStatus === "pending" && !sawSendMessageSelf && !sawPonder) {
243
+ 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.";
244
+ }
245
+ // 3. mustResolveBeforeHandoff + missing intent
246
+ if (mustResolveBeforeHandoff && !intent) {
247
+ 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.";
248
+ }
249
+ // 4. mustResolveBeforeHandoff + direct_reply without follow-up
250
+ if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
251
+ 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.";
252
+ }
253
+ // 5. mustResolveBeforeHandoff + complete while a live return loop is still active
254
+ if (mustResolveBeforeHandoff && intent === "complete" && currentObligation && !sawSteeringFollowUp) {
255
+ 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.";
256
+ }
257
+ // 6. External-state grounding: obligation + complete requires fresh external verification
258
+ if (intent === "complete" && currentObligation && !sawExternalStateQuery && !sawSteeringFollowUp) {
259
+ return "you're claiming this work is complete, but the external state hasn't been verified this turn. ground your claim with a fresh check (gh pr view, npm view, gh run view, etc.) before calling settle.";
260
+ }
261
+ return null;
262
+ }
125
263
  function upsertSystemPrompt(messages, systemText) {
126
264
  const systemMessage = { role: "system", content: systemText };
127
265
  if (messages[0]?.role === "system") {
@@ -151,6 +289,68 @@ function stripLastToolCalls(messages) {
151
289
  }
152
290
  }
153
291
  }
292
+ // Roles that end a tool-result scan. When scanning forward from an assistant
293
+ // message, stop at the next assistant or user message (tool results must be
294
+ // adjacent to their originating assistant message).
295
+ const TOOL_SCAN_BOUNDARY_ROLES = new Set(["assistant", "user"]);
296
+ // Repair orphaned tool_calls and tool results anywhere in the message history.
297
+ // 1. If an assistant message has tool_calls but missing tool results, inject synthetic error results.
298
+ // 2. If a tool result's tool_call_id doesn't match any tool_calls in a preceding assistant message, remove it.
299
+ // This prevents 400 errors from the API after an aborted turn.
300
+ function repairOrphanedToolCalls(messages) {
301
+ // Pass 1: collect all valid tool_call IDs from assistant messages
302
+ const validCallIds = new Set();
303
+ for (const msg of messages) {
304
+ if (msg.role === "assistant") {
305
+ const asst = msg;
306
+ if (asst.tool_calls) {
307
+ for (const tc of asst.tool_calls)
308
+ validCallIds.add(tc.id);
309
+ }
310
+ }
311
+ }
312
+ // Pass 2: remove orphaned tool results (tool_call_id not in any assistant's tool_calls)
313
+ for (let i = messages.length - 1; i >= 0; i--) {
314
+ if (messages[i].role === "tool") {
315
+ const toolMsg = messages[i];
316
+ if (!validCallIds.has(toolMsg.tool_call_id)) {
317
+ messages.splice(i, 1);
318
+ }
319
+ }
320
+ }
321
+ // Pass 3: inject synthetic results for tool_calls missing their tool results
322
+ for (let i = 0; i < messages.length; i++) {
323
+ const msg = messages[i];
324
+ if (msg.role !== "assistant")
325
+ continue;
326
+ const asst = msg;
327
+ if (!asst.tool_calls || asst.tool_calls.length === 0)
328
+ continue;
329
+ // Collect tool result IDs that follow this assistant message
330
+ const resultIds = new Set();
331
+ for (let j = i + 1; j < messages.length; j++) {
332
+ const following = messages[j];
333
+ if (following.role === "tool") {
334
+ resultIds.add(following.tool_call_id);
335
+ }
336
+ else if (TOOL_SCAN_BOUNDARY_ROLES.has(following.role)) {
337
+ break;
338
+ }
339
+ }
340
+ const missing = asst.tool_calls.filter((tc) => !resultIds.has(tc.id));
341
+ if (missing.length > 0) {
342
+ const syntheticResults = missing.map((tc) => ({
343
+ role: "tool",
344
+ tool_call_id: tc.id,
345
+ content: "error: tool call was interrupted (previous turn timed out or was aborted)",
346
+ }));
347
+ let insertAt = i + 1;
348
+ while (insertAt < messages.length && messages[insertAt].role === "tool")
349
+ insertAt++;
350
+ messages.splice(insertAt, 0, ...syntheticResults);
351
+ }
352
+ }
353
+ }
154
354
  // Detect context overflow errors from Azure or MiniMax
155
355
  function isContextOverflow(err) {
156
356
  if (!(err instanceof Error))
@@ -165,49 +365,49 @@ function isContextOverflow(err) {
165
365
  return true;
166
366
  return false;
167
367
  }
168
- // Detect transient network errors worth retrying
169
- function isTransientError(err) {
170
- if (!(err instanceof Error))
171
- return false;
172
- const msg = err.message || "";
173
- const code = err.code || "";
174
- // Node.js network error codes
175
- if (["ECONNRESET", "ECONNREFUSED", "ENOTFOUND", "ETIMEDOUT", "EPIPE",
176
- "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "ECONNABORTED"].includes(code))
368
+ // HTTP statuses that will never become retryable on their own — the request is
369
+ // semantically wrong (malformed, unauthorized, missing route, etc.) and the
370
+ // caller has to do something different before it can succeed.
371
+ const NON_RETRYABLE_HTTP_STATUSES = new Set([
372
+ 400, // Bad Request — malformed payload
373
+ 401, // Unauthorized — credentials invalid/expired
374
+ 403, // Forbidden — credentials lack permission
375
+ 404, // Not Found — model/route doesn't exist
376
+ 422, // Unprocessable Entity — semantic validation failure
377
+ ]);
378
+ // Provider-classified error categories that we never retry. usage-limit is
379
+ // distinct from rate-limit: rate limits clear in seconds (retryable), usage
380
+ // limits are billing quotas that take hours/days to reset.
381
+ const NON_RETRYABLE_CLASSIFICATIONS = new Set([
382
+ "auth-failure",
383
+ "usage-limit",
384
+ ]);
385
+ // Default policy: retry every error from the provider, EXCEPT the small set
386
+ // above. The user explicitly requested this — past behavior was to retry only
387
+ // on a known-transient list, which silently dropped real harness/SDK timeouts
388
+ // (e.g. OpenAI SDK's "Request timed out." has no err.code and no status, so
389
+ // the substring matchers missed it).
390
+ function isRetryBlocked(error, classification) {
391
+ const status = error.status;
392
+ if (status !== undefined && NON_RETRYABLE_HTTP_STATUSES.has(status))
177
393
  return true;
178
- // OpenAI SDK / fetch errors
179
- if (msg.includes("fetch failed"))
180
- return true;
181
- if (msg.includes("network") && !msg.includes("context"))
182
- return true;
183
- if (msg.includes("ECONNRESET") || msg.includes("ETIMEDOUT"))
184
- return true;
185
- if (msg.includes("socket hang up"))
186
- return true;
187
- if (msg.includes("getaddrinfo"))
188
- return true;
189
- // HTTP 429 / 500 / 502 / 503 / 504
190
- const status = err.status;
191
- if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504)
394
+ if (NON_RETRYABLE_CLASSIFICATIONS.has(classification))
192
395
  return true;
193
396
  return false;
194
397
  }
195
- function classifyTransientError(err) {
196
- if (!(err instanceof Error))
197
- return "unknown error";
198
- const status = err.status;
199
- if (status === 429)
200
- return "rate limited";
201
- if (status === 401 || status === 403)
202
- return "auth error";
203
- if (status && status >= 500)
204
- return "server error";
205
- return "network error";
206
- }
207
398
  const MAX_RETRIES = 3;
208
399
  const RETRY_BASE_MS = 2000;
400
+ const RETRY_LABELS = {
401
+ "auth-failure": "auth error",
402
+ "usage-limit": "usage limit",
403
+ "rate-limit": "rate limited",
404
+ "server-error": "server error",
405
+ "network-error": "network error",
406
+ "unknown": "error",
407
+ };
209
408
  async function runAgent(messages, callbacks, channel, signal, options) {
210
- const providerRuntime = getProviderRuntime();
409
+ const facing = (0, channel_1.channelToFacing)(channel);
410
+ const providerRuntime = getProviderRuntime(facing);
211
411
  const provider = providerRuntime.id;
212
412
  const toolChoiceRequired = options?.toolChoiceRequired ?? true;
213
413
  const traceId = options?.traceId;
@@ -233,7 +433,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
233
433
  // so turn execution remains consistent and non-fatal.
234
434
  if (channel) {
235
435
  try {
236
- const refreshed = await (0, prompt_1.buildSystem)(channel, options, currentContext);
436
+ const buildSystemOptions = {
437
+ ...options,
438
+ providerCapabilities: providerRuntime.capabilities,
439
+ supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
440
+ };
441
+ const refreshed = await (0, prompt_1.buildSystem)(channel, buildSystemOptions, currentContext);
237
442
  upsertSystemPrompt(messages, refreshed);
238
443
  }
239
444
  catch (error) {
@@ -256,31 +461,78 @@ async function runAgent(messages, callbacks, channel, signal, options) {
256
461
  }
257
462
  }
258
463
  await (0, associative_recall_1.injectAssociativeRecall)(messages);
259
- // kickCount and lastKickReason preserved but unused while kick detection is disabled.
260
- // let kickCount = 0;
261
- // let lastKickReason: KickReason | null = null;
262
464
  let done = false;
263
465
  let lastUsage;
264
466
  let overflowRetried = false;
265
467
  let retryCount = 0;
468
+ let outcome = "settled";
469
+ let completion;
470
+ let terminalError;
471
+ let terminalErrorClassification;
472
+ let sawSteeringFollowUp = false;
473
+ let mustResolveBeforeHandoffActive = options?.mustResolveBeforeHandoff === true;
474
+ let currentReasoningEffort = "medium";
475
+ let sawSendMessageSelf = false;
476
+ let sawPonder = false;
477
+ let sawQuerySession = false;
478
+ let sawBridgeManage = false;
479
+ let sawExternalStateQuery = false;
480
+ const toolLoopState = (0, tool_loop_1.createToolLoopState)();
481
+ const toolFrictionLedger = (0, tool_friction_1.createToolFrictionLedger)();
266
482
  // Prevent MaxListenersExceeded warning — each iteration adds a listener
267
483
  try {
268
484
  require("events").setMaxListeners(50, signal);
269
485
  }
270
486
  catch { /* unsupported */ }
271
487
  const toolPreferences = currentContext?.friend?.toolPreferences;
272
- const baseTools = (0, tools_1.getToolsForChannel)(channel ? (0, channel_1.getChannelCapabilities)(channel) : undefined, toolPreferences && Object.keys(toolPreferences).length > 0 ? toolPreferences : undefined);
488
+ const baseTools = options?.tools ?? (0, tools_1.getToolsForChannel)(channel ? (0, channel_1.getChannelCapabilities)(channel) : undefined, toolPreferences && Object.keys(toolPreferences).length > 0 ? toolPreferences : undefined, currentContext, providerRuntime.capabilities, options?.mcpManager, providerRuntime.model);
489
+ // Augment tool context with reasoning effort controls from provider
490
+ const augmentedToolContext = options?.toolContext
491
+ ? {
492
+ ...options.toolContext,
493
+ supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
494
+ setReasoningEffort: (level) => { currentReasoningEffort = level; },
495
+ activeWorkFrame: options?.activeWorkFrame,
496
+ }
497
+ : undefined;
273
498
  // Rebase provider-owned turn state from canonical messages at user-turn start.
274
499
  // This prevents stale provider caches from replaying prior-turn context.
275
500
  providerRuntime.resetTurnState(messages);
276
501
  while (!done) {
277
- // When toolChoiceRequired is true (the default), include final_answer
278
- // so the model can signal completion. With tool_choice: required, the
279
- // model must call a tool every turn — final_answer is how it exits.
280
- // Overridable via options.toolChoiceRequired = false (e.g. CLI).
281
- const activeTools = toolChoiceRequired ? [...baseTools, tools_1.finalAnswerTool] : baseTools;
502
+ // Channel-based tool filtering:
503
+ // - Inner dialog: exclude send_message (delivery via surface), observe (no one to observe)
504
+ // - 1:1 sessions: exclude observe (can't ignore someone talking directly to you)
505
+ // - Group chats: observe available
506
+ //
507
+ // ponder, settle/rest, surface, and observe are always assembled based on channel context.
508
+ // ponder is available in ALL channels (outer: think privately, inner: keep turning).
509
+ // Inner dialog gets restTool instead of settleTool (rest = end turn, gated by attention queue).
510
+ // toolChoiceRequired only controls whether tool_choice: "required" is set in the API call.
511
+ const isInnerDialog = channel === "inner";
512
+ const filteredBaseTools = isInnerDialog
513
+ ? baseTools.filter((t) => t.function.name !== "send_message")
514
+ : baseTools;
515
+ const activeTools = [
516
+ ...filteredBaseTools,
517
+ tools_1.ponderTool,
518
+ ...(isInnerDialog ? [tools_2.surfaceToolDef, tools_1.restTool] : []),
519
+ ...((currentContext?.isGroupChat || options?.isReactionSignal) && !isInnerDialog ? [tools_1.observeTool] : []),
520
+ ...(!isInnerDialog ? [tools_1.settleTool] : []),
521
+ ];
282
522
  const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
283
523
  if (steeringFollowUps.length > 0) {
524
+ const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
525
+ if (hasSupersedingFollowUp) {
526
+ mustResolveBeforeHandoffActive = false;
527
+ options?.setMustResolveBeforeHandoff?.(false);
528
+ outcome = "superseded";
529
+ break;
530
+ }
531
+ if (steeringFollowUps.some((followUp) => followUp.effect === "set_no_handoff")) {
532
+ mustResolveBeforeHandoffActive = true;
533
+ options?.setMustResolveBeforeHandoff?.(true);
534
+ }
535
+ sawSteeringFollowUp = true;
284
536
  for (const followUp of steeringFollowUps) {
285
537
  messages.push({ role: "user", content: followUp.text });
286
538
  }
@@ -288,8 +540,10 @@ async function runAgent(messages, callbacks, channel, signal, options) {
288
540
  }
289
541
  // Yield so pending I/O (stdin Ctrl-C) can be processed between iterations
290
542
  await new Promise((r) => setImmediate(r));
291
- if (signal?.aborted)
543
+ if (signal?.aborted) {
544
+ outcome = "aborted";
292
545
  break;
546
+ }
293
547
  try {
294
548
  callbacks.onModelStart();
295
549
  const result = await providerRuntime.streamTurn({
@@ -299,6 +553,8 @@ async function runAgent(messages, callbacks, channel, signal, options) {
299
553
  signal,
300
554
  traceId,
301
555
  toolChoiceRequired,
556
+ reasoningEffort: currentReasoningEffort,
557
+ eagerSettleStreaming: true,
302
558
  });
303
559
  // Track usage from the latest API call
304
560
  if (result.usage)
@@ -322,52 +578,76 @@ async function runAgent(messages, callbacks, channel, signal, options) {
322
578
  if (reasoningItems.length > 0) {
323
579
  msg._reasoning_items = reasoningItems;
324
580
  }
581
+ // Store thinking blocks (Anthropic) on the assistant message for round-tripping
582
+ const thinkingItems = result.outputItems.filter((item) => "type" in item && (item.type === "thinking" || item.type === "redacted_thinking"));
583
+ if (thinkingItems.length > 0) {
584
+ msg._thinking_blocks = thinkingItems;
585
+ }
586
+ // Phase annotation for Codex provider
587
+ const hasPhaseAnnotation = providerRuntime.capabilities.has("phase-annotation");
588
+ const isSoleSettle = result.toolCalls.length === 1 && result.toolCalls[0].name === "settle";
589
+ if (hasPhaseAnnotation) {
590
+ msg.phase = isSoleSettle ? "settle" : "commentary";
591
+ }
325
592
  if (!result.toolCalls.length) {
326
- // Kick detection is disabled while tool_choice: required + final_answer
327
- // is the primary loop control mechanism. The model should never reach
328
- // this path (tool_choice: required forces a tool call), but if it does,
329
- // accept the response as-is rather than risk false-positive kicks.
330
- //
331
- // Preserved for future use — re-enable by uncommenting:
332
- // const kick = detectKick(result.content, options);
333
- // if (kick) {
334
- // kickCount++;
335
- // lastKickReason = kick.reason;
336
- // callbacks.onKick?.();
337
- // const kickContent = result.content
338
- // ? result.content + "\n\n" + kick.message
339
- // : kick.message;
340
- // messages.push({ role: "assistant", content: kickContent });
341
- // providerRuntime.resetTurnState(messages);
342
- // continue;
343
- // }
593
+ // No tool calls — accept response as-is.
594
+ // (Kick detection disabled; tool_choice: required + settle
595
+ // is the primary loop control. See src/heart/kicks.ts to re-enable.)
344
596
  messages.push(msg);
345
597
  done = true;
346
598
  }
347
599
  else {
348
- // Check for final_answer sole call: intercept before tool execution
349
- const isSoleFinalAnswer = result.toolCalls.length === 1 && result.toolCalls[0].name === "final_answer";
350
- if (isSoleFinalAnswer) {
351
- // Extract answer from the tool call arguments.
352
- // Supports: {"answer":"text"}, "text" (JSON string), retry on failure.
353
- let answer;
354
- try {
355
- const parsed = JSON.parse(result.toolCalls[0].arguments);
356
- if (typeof parsed === "string") {
357
- answer = parsed;
358
- }
359
- else if (parsed.answer != null) {
360
- answer = parsed.answer;
361
- }
362
- // else: valid JSON but no answer field — answer stays undefined (retry)
600
+ // Check for settle sole call: intercept before tool execution
601
+ if (isSoleSettle) {
602
+ /* v8 ignore next -- defensive: JSON.parse catch for malformed settle args @preserve */
603
+ const settleArgs = (() => { try {
604
+ return JSON.parse(result.toolCalls[0].arguments);
363
605
  }
364
606
  catch {
365
- // JSON parsing failed (e.g. truncated output) — answer stays undefined (retry)
607
+ return {};
608
+ } })();
609
+ callbacks.onToolStart("settle", settleArgs);
610
+ // Inner dialog attention queue gate: reject settle if items remain
611
+ const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
612
+ if (isInnerDialog && attentionQueue && attentionQueue.length > 0) {
613
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
614
+ callbacks.onClearText?.();
615
+ messages.push(msg);
616
+ const gateMessage = "you're holding thoughts someone is waiting for — surface them before you settle.";
617
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
618
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
619
+ continue;
620
+ }
621
+ // Extract answer from the tool call arguments.
622
+ // Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
623
+ const { answer, intent } = parseSettlePayload(result.toolCalls[0].arguments);
624
+ // Inner dialog settle: no CompletionMetadata, "(settled)" ack
625
+ if (isInnerDialog) {
626
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
627
+ messages.push(msg);
628
+ const settled = "(settled)";
629
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: settled });
630
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, settled);
631
+ outcome = "settled";
632
+ done = true;
633
+ continue;
366
634
  }
367
- if (answer != null) {
368
- if (result.finalAnswerStreamed) {
635
+ const retryError = getSettleRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp, options?.delegationDecision, sawSendMessageSelf, sawPonder, sawQuerySession, options?.currentObligation ?? null, options?.activeWorkFrame?.inner?.job, sawExternalStateQuery);
636
+ const deliveredAnswer = answer;
637
+ const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
638
+ const validTerminalIntent = intent === "complete" || intent === "blocked";
639
+ const validClosure = deliveredAnswer != null
640
+ && !retryError
641
+ && (!mustResolveBeforeHandoffActive || validDirectReply || validTerminalIntent);
642
+ if (validClosure) {
643
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
644
+ completion = {
645
+ answer: deliveredAnswer,
646
+ intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
647
+ };
648
+ if (result.settleStreamed) {
369
649
  // The streaming layer already parsed and emitted the answer
370
- // progressively via FinalAnswerParser. Skip clearing and
650
+ // progressively via SettleParser. Skip clearing and
371
651
  // re-emitting to avoid double-delivery.
372
652
  }
373
653
  else {
@@ -375,37 +655,110 @@ async function runAgent(messages, callbacks, channel, signal, options) {
375
655
  callbacks.onClearText?.();
376
656
  // Emit the answer through the callback pipeline so channels receive it.
377
657
  // Never truncate -- channel adapters handle splitting long messages.
378
- callbacks.onTextChunk(answer);
658
+ callbacks.onTextChunk(deliveredAnswer);
379
659
  }
380
- // Keep the full assistant message (with tool_calls) for debuggability,
381
- // plus a synthetic tool response so the conversation stays valid on resume.
382
660
  messages.push(msg);
383
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: "(delivered)" });
384
- providerRuntime.appendToolOutput(result.toolCalls[0].id, "(delivered)");
385
- done = true;
661
+ if (validDirectReply) {
662
+ const resumeWork = "direct reply delivered. resume the unresolved obligation now and keep working until you can finish or clearly report that you are blocked.";
663
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: resumeWork });
664
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, resumeWork);
665
+ }
666
+ else {
667
+ const delivered = "(delivered)";
668
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
669
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
670
+ outcome = intent === "blocked" ? "blocked" : "settled";
671
+ done = true;
672
+ }
386
673
  }
387
674
  else {
388
- // Answer is undefined -- the model's final_answer was incomplete or
675
+ // Answer is undefined -- the model's settle was incomplete or
389
676
  // malformed. Clear any partial streamed text or noise, then push the
390
677
  // assistant msg + error tool result and let the model try again.
678
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
391
679
  callbacks.onClearText?.();
392
- const retryError = "your final_answer was incomplete or malformed. call final_answer again with your complete response.";
393
680
  messages.push(msg);
394
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: retryError });
395
- providerRuntime.appendToolOutput(result.toolCalls[0].id, retryError);
681
+ const toolRetryMessage = retryError
682
+ ?? "your settle was incomplete or malformed. call settle again with your complete response.";
683
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: toolRetryMessage });
684
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, toolRetryMessage);
685
+ }
686
+ continue;
687
+ }
688
+ // Check for observe sole call: intercept before tool execution
689
+ const isSoleObserve = result.toolCalls.length === 1 && result.toolCalls[0].name === "observe";
690
+ if (isSoleObserve) {
691
+ /* v8 ignore next -- defensive: JSON.parse catch for malformed observe args @preserve */
692
+ const observeArgs = (() => { try {
693
+ return JSON.parse(result.toolCalls[0].arguments);
694
+ }
695
+ catch {
696
+ return {};
697
+ } })();
698
+ let reason;
699
+ if (typeof observeArgs?.reason === "string")
700
+ reason = observeArgs.reason;
701
+ callbacks.onToolStart("observe", observeArgs);
702
+ (0, runtime_1.emitNervesEvent)({
703
+ component: "engine",
704
+ event: "engine.observe",
705
+ message: "agent observed without responding",
706
+ meta: { ...(reason ? { reason } : {}) },
707
+ });
708
+ callbacks.onToolEnd("observe", (0, tools_1.summarizeArgs)("observe", observeArgs), true);
709
+ messages.push(msg);
710
+ const silenced = "(silenced)";
711
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: silenced });
712
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, silenced);
713
+ outcome = "observed";
714
+ done = true;
715
+ continue;
716
+ }
717
+ // Check for rest sole call: intercept before tool execution
718
+ const isSoleRest = result.toolCalls.length === 1 && result.toolCalls[0].name === "rest";
719
+ if (isSoleRest) {
720
+ const restArgs = (() => { try {
721
+ return JSON.parse(result.toolCalls[0].arguments);
722
+ }
723
+ catch {
724
+ return {};
725
+ } })();
726
+ callbacks.onToolStart("rest", restArgs);
727
+ // Attention queue gate: reject rest if items remain
728
+ const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
729
+ if (attentionQueue && attentionQueue.length > 0) {
730
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), false);
731
+ messages.push(msg);
732
+ const gateMessage = "you're holding thoughts someone is waiting for — surface them before you rest.";
733
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
734
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
735
+ continue;
396
736
  }
737
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), true);
738
+ messages.push(msg);
739
+ const ack = "(resting)";
740
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
741
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
742
+ (0, runtime_1.emitNervesEvent)({
743
+ component: "engine",
744
+ event: "engine.rested",
745
+ message: "resting until next heartbeat",
746
+ meta: { ...(typeof restArgs?.status === "string" ? { status: restArgs.status } : {}) },
747
+ });
748
+ outcome = "rested";
749
+ done = true;
397
750
  continue;
398
751
  }
399
752
  messages.push(msg);
400
- // SHARED: execute tools (final_answer in mixed calls is rejected inline)
753
+ // Execute tools (sole-call tools in mixed calls are rejected inline)
401
754
  for (const tc of result.toolCalls) {
402
755
  if (signal?.aborted)
403
756
  break;
404
- // Intercept final_answer in mixed call: reject it
405
- if (tc.name === "final_answer") {
406
- const rejection = "rejected: final_answer must be the only tool call. Finish your work first, then call final_answer alone.";
407
- messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
408
- providerRuntime.appendToolOutput(tc.id, rejection);
757
+ // Reject sole-call tools when mixed with other tool calls
758
+ const soleCallRejection = SOLE_CALL_REJECTION[tc.name];
759
+ if (soleCallRejection) {
760
+ messages.push({ role: "tool", tool_call_id: tc.id, content: soleCallRejection });
761
+ providerRuntime.appendToolOutput(tc.id, soleCallRejection);
409
762
  continue;
410
763
  }
411
764
  let args = {};
@@ -415,36 +768,175 @@ async function runAgent(messages, callbacks, channel, signal, options) {
415
768
  catch {
416
769
  /* ignore */
417
770
  }
418
- const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
419
- // Confirmation check for mutate tools
420
- if ((0, tools_1.isConfirmationRequired)(tc.name) && !options?.skipConfirmation) {
421
- let decision = "denied";
422
- if (callbacks.onConfirmAction) {
423
- decision = await callbacks.onConfirmAction(tc.name, args);
771
+ if (tc.name === "send_message" && args.friendId === "self") {
772
+ sawSendMessageSelf = true;
773
+ }
774
+ if (tc.name === "ponder") {
775
+ const parsedArgs = normalizeLegacyPonderArgs(parsePonderPayload(tc.arguments));
776
+ const argSummary = (0, tools_1.summarizeArgs)(tc.name, parsedArgs);
777
+ callbacks.onToolStart(tc.name, parsedArgs);
778
+ let toolResult;
779
+ let success = false;
780
+ try {
781
+ const action = parsedArgs.action ?? "create";
782
+ const currentSession = (augmentedToolContext ?? options?.toolContext)?.currentSession;
783
+ const currentOrigin = currentSession
784
+ ? { friendId: currentSession.friendId, channel: currentSession.channel, key: currentSession.key }
785
+ : undefined;
786
+ const isInnerChannel = currentOrigin?.friendId === "self" && currentOrigin?.channel === "inner";
787
+ const successCriteria = parseSuccessCriteria(parsedArgs.success_criteria);
788
+ const payload = parsePacketPayload(parsedArgs.payload_json);
789
+ let packet;
790
+ let returnObligationId = null;
791
+ let resultAction = "created";
792
+ if (action === "create") {
793
+ const kind = parsedArgs.kind;
794
+ const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
795
+ const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
796
+ if (!kind || !objective || !successCriteria || !payload) {
797
+ throw new Error("ponder create requires kind, objective, success_criteria, and valid payload_json.");
798
+ }
799
+ const agentRoot = (0, identity_2.getAgentRoot)();
800
+ let relatedObligationId;
801
+ if (currentOrigin && !isInnerChannel) {
802
+ try {
803
+ const obligation = (0, obligations_1.createObligation)(agentRoot, {
804
+ origin: currentOrigin,
805
+ content: objective,
806
+ });
807
+ relatedObligationId = obligation.id;
808
+ }
809
+ catch {
810
+ relatedObligationId = undefined;
811
+ }
812
+ }
813
+ const frictionSignature = kind === "harness_friction" && typeof payload.frictionSignature === "string"
814
+ ? payload.frictionSignature
815
+ : null;
816
+ const existing = frictionSignature && currentOrigin
817
+ ? (0, packets_1.findHarnessFrictionPacket)(agentRoot, currentOrigin, frictionSignature)
818
+ : null;
819
+ if (existing) {
820
+ resultAction = "revised";
821
+ returnObligationId = existing.relatedReturnObligationId ?? null;
822
+ packet = existing.status === "drafting"
823
+ ? (0, packets_1.revisePonderPacket)(agentRoot, existing.id, {
824
+ kind,
825
+ objective,
826
+ summary,
827
+ successCriteria,
828
+ payload,
829
+ })
830
+ : existing;
831
+ }
832
+ else {
833
+ returnObligationId = (0, obligations_1.generateObligationId)(Date.now());
834
+ packet = (0, packets_1.createPonderPacket)(agentRoot, {
835
+ kind,
836
+ objective,
837
+ summary,
838
+ successCriteria,
839
+ ...(currentOrigin ? { origin: currentOrigin } : {}),
840
+ ...(relatedObligationId ? { relatedObligationId } : {}),
841
+ relatedReturnObligationId: returnObligationId,
842
+ ...(parsedArgs.follows_packet_id ? { followsPacketId: parsedArgs.follows_packet_id } : {}),
843
+ payload,
844
+ });
845
+ (0, obligations_1.createReturnObligation)((0, identity_2.getAgentName)(), {
846
+ id: returnObligationId,
847
+ origin: currentOrigin ?? { friendId: "self", channel: "inner", key: "dialog" },
848
+ status: "queued",
849
+ delegatedContent: (summary || objective).length > 120 ? `${(summary || objective).slice(0, 117)}...` : (summary || objective),
850
+ packetId: packet.id,
851
+ createdAt: Date.now(),
852
+ });
853
+ }
854
+ }
855
+ else if (action === "revise") {
856
+ const packetId = typeof parsedArgs.packet_id === "string" ? parsedArgs.packet_id.trim() : "";
857
+ const kind = parsedArgs.kind;
858
+ const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
859
+ const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
860
+ if (!packetId || !kind || !objective || !successCriteria || !payload) {
861
+ throw new Error("ponder revise requires packet_id, kind, objective, success_criteria, and valid payload_json.");
862
+ }
863
+ packet = (0, packets_1.revisePonderPacket)((0, identity_2.getAgentRoot)(), packetId, {
864
+ kind,
865
+ objective,
866
+ summary,
867
+ successCriteria,
868
+ payload,
869
+ });
870
+ returnObligationId = packet.relatedReturnObligationId ?? null;
871
+ resultAction = "revised";
872
+ }
873
+ else {
874
+ throw new Error("ponder requires action=create or revise.");
875
+ }
876
+ try {
877
+ await (0, socket_client_1.requestInnerWake)((0, identity_2.getAgentName)());
878
+ }
879
+ catch { /* daemon may not be running */ }
880
+ sawPonder = true;
881
+ toolResult = buildPonderResult(packet, resultAction, returnObligationId);
882
+ success = true;
883
+ (0, runtime_1.emitNervesEvent)({
884
+ component: "engine",
885
+ event: "engine.ponder_packet",
886
+ message: "ponder packet touched",
887
+ meta: {
888
+ action: resultAction,
889
+ packetId: packet.id,
890
+ kind: packet.kind,
891
+ status: packet.status,
892
+ },
893
+ });
424
894
  }
425
- if (decision !== "confirmed") {
426
- const cancelled = "Action cancelled by user.";
427
- callbacks.onToolStart(tc.name, args);
428
- callbacks.onToolEnd(tc.name, argSummary, false);
429
- messages.push({ role: "tool", tool_call_id: tc.id, content: cancelled });
430
- providerRuntime.appendToolOutput(tc.id, cancelled);
431
- continue;
895
+ catch (error) {
896
+ toolResult = error instanceof Error ? error.message : String(error);
432
897
  }
898
+ callbacks.onToolEnd(tc.name, argSummary, success);
899
+ messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
900
+ providerRuntime.appendToolOutput(tc.id, toolResult);
901
+ continue;
902
+ }
903
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
904
+ if (tc.name === "query_session")
905
+ sawQuerySession = true;
906
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
907
+ if (tc.name === "bridge_manage")
908
+ sawBridgeManage = true;
909
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
910
+ if (isExternalStateQuery(tc.name, args))
911
+ sawExternalStateQuery = true;
912
+ const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
913
+ const toolLoop = (0, tool_loop_1.detectToolLoop)(toolLoopState, tc.name, args);
914
+ if (toolLoop.stuck) {
915
+ const rejection = `loop guard: ${toolLoop.message}`;
916
+ callbacks.onToolStart(tc.name, args);
917
+ callbacks.onToolEnd(tc.name, argSummary, false);
918
+ messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
919
+ providerRuntime.appendToolOutput(tc.id, rejection);
920
+ continue;
433
921
  }
434
922
  callbacks.onToolStart(tc.name, args);
435
923
  let toolResult;
436
924
  let success;
437
925
  try {
438
- toolResult = await (0, tools_1.execTool)(tc.name, args, options?.toolContext);
926
+ const execToolFn = options?.execTool ?? tools_1.execTool;
927
+ toolResult = await execToolFn(tc.name, args, augmentedToolContext ?? options?.toolContext);
439
928
  success = true;
440
929
  }
441
930
  catch (e) {
442
931
  toolResult = `error: ${e}`;
443
932
  success = false;
444
933
  }
445
- callbacks.onToolEnd(tc.name, argSummary, success);
934
+ toolResult = (0, tool_friction_1.rewriteToolResultForModel)(tc.name, toolResult, toolFrictionLedger);
935
+ (0, tool_loop_1.recordToolOutcome)(toolLoopState, tc.name, args, toolResult, success);
936
+ callbacks.onToolEnd(tc.name, (0, tools_1.buildToolResultSummary)(tc.name, args, toolResult, success), success);
446
937
  messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
447
938
  providerRuntime.appendToolOutput(tc.id, toolResult);
939
+ callbacks.onToolResult?.(messages);
448
940
  }
449
941
  }
450
942
  }
@@ -452,6 +944,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
452
944
  // Abort is not an error — just stop cleanly
453
945
  if (signal?.aborted) {
454
946
  stripLastToolCalls(messages);
947
+ outcome = "aborted";
455
948
  break;
456
949
  }
457
950
  // Context overflow: trim aggressively and retry once
@@ -465,11 +958,45 @@ async function runAgent(messages, callbacks, channel, signal, options) {
465
958
  callbacks.onError(new Error("context trimmed, retrying..."), "transient");
466
959
  continue;
467
960
  }
468
- // Transient errors: retry with exponential backoff
469
- if (isTransientError(e) && retryCount < MAX_RETRIES) {
961
+ // Retry policy: retry every error EXCEPT those on the blocklist
962
+ // (NON_RETRYABLE_HTTP_STATUSES / NON_RETRYABLE_CLASSIFICATIONS).
963
+ // The classification still drives the user-facing label and the
964
+ // auth-failure guidance message below — it just no longer gates retries.
965
+ const errorForClassification = e instanceof Error ? e : /* v8 ignore next -- defensive @preserve */ new Error(String(e));
966
+ let providerClassification;
967
+ try {
968
+ providerClassification = providerRuntime.classifyError(errorForClassification);
969
+ }
970
+ catch {
971
+ /* v8 ignore next -- defensive: classifyError should not throw @preserve */
972
+ providerClassification = "unknown";
973
+ }
974
+ const blocked = isRetryBlocked(errorForClassification, providerClassification);
975
+ const shouldRetry = !blocked && retryCount < MAX_RETRIES;
976
+ (0, runtime_1.emitNervesEvent)({
977
+ level: shouldRetry ? "info" : "warn",
978
+ event: shouldRetry ? "engine.provider_retry" : "engine.provider_retry_skip",
979
+ component: "engine",
980
+ message: shouldRetry
981
+ ? `provider error is retryable (attempt ${retryCount + 1}/${MAX_RETRIES})`
982
+ : blocked
983
+ ? `provider error is on retry blocklist`
984
+ : `provider error retries exhausted`,
985
+ meta: {
986
+ provider: providerRuntime.id,
987
+ model: providerRuntime.model,
988
+ retryCount,
989
+ maxRetries: MAX_RETRIES,
990
+ blocked,
991
+ providerClassification,
992
+ errorMessage: errorForClassification.message.slice(0, 200),
993
+ httpStatus: e.status ?? null,
994
+ },
995
+ });
996
+ if (shouldRetry) {
470
997
  retryCount++;
471
998
  const delay = RETRY_BASE_MS * Math.pow(2, retryCount - 1);
472
- const cause = classifyTransientError(e);
999
+ const cause = RETRY_LABELS[providerClassification];
473
1000
  callbacks.onError(new Error(`${cause}, retrying in ${delay / 1000}s (${retryCount}/${MAX_RETRIES})...`), "transient");
474
1001
  // Wait with abort support
475
1002
  const aborted = await new Promise((resolve) => {
@@ -486,21 +1013,36 @@ async function runAgent(messages, callbacks, channel, signal, options) {
486
1013
  });
487
1014
  if (aborted) {
488
1015
  stripLastToolCalls(messages);
1016
+ outcome = "aborted";
489
1017
  break;
490
1018
  }
491
1019
  providerRuntime.resetTurnState(messages);
492
1020
  continue;
493
1021
  }
494
- callbacks.onError(e instanceof Error ? e : new Error(String(e)), "terminal");
1022
+ terminalError = errorForClassification;
1023
+ terminalErrorClassification = providerClassification;
1024
+ /* v8 ignore start — auth-failure guidance: tested via provider error classification tests @preserve */
1025
+ if (terminalErrorClassification === "auth-failure") {
1026
+ const agentName = (0, identity_2.getAgentName)();
1027
+ const currentProvider = providerRuntime.id;
1028
+ callbacks.onError(new Error(`${currentProvider} (${providerRuntime.model}) encountered an error. ` +
1029
+ `Run \`ouro auth --agent ${agentName} --provider ${currentProvider}\` to refresh credentials, ` +
1030
+ `or \`ouro auth switch --agent ${agentName} --provider <other>\` to switch providers.`), "terminal");
1031
+ }
1032
+ else {
1033
+ callbacks.onError(terminalError, "terminal");
1034
+ }
1035
+ /* v8 ignore stop */
495
1036
  (0, runtime_1.emitNervesEvent)({
496
1037
  level: "error",
497
1038
  event: "engine.error",
498
1039
  trace_id: traceId,
499
1040
  component: "engine",
500
- message: e instanceof Error ? e.message : String(e),
501
- meta: {},
1041
+ message: terminalError.message,
1042
+ meta: { errorClassification: terminalErrorClassification },
502
1043
  });
503
1044
  stripLastToolCalls(messages);
1045
+ outcome = "errored";
504
1046
  done = true;
505
1047
  }
506
1048
  }
@@ -509,7 +1051,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
509
1051
  trace_id: traceId,
510
1052
  component: "engine",
511
1053
  message: "runAgent turn completed",
512
- meta: { done },
1054
+ meta: { done, sawPonder, sawQuerySession, sawBridgeManage },
513
1055
  });
514
- return { usage: lastUsage };
1056
+ return {
1057
+ usage: lastUsage,
1058
+ outcome,
1059
+ completion,
1060
+ ...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
1061
+ };
515
1062
  }