@ouro.bot/cli 0.1.0-alpha.12 → 0.1.0-alpha.121

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 (130) hide show
  1. package/AdoptionSpecialist.ouro/psyche/SOUL.md +2 -2
  2. package/AdoptionSpecialist.ouro/psyche/identities/monty.md +2 -2
  3. package/README.md +147 -205
  4. package/assets/ouroboros.png +0 -0
  5. package/changelog.json +737 -0
  6. package/dist/heart/active-work.js +622 -0
  7. package/dist/heart/bridges/manager.js +358 -0
  8. package/dist/heart/bridges/state-machine.js +135 -0
  9. package/dist/heart/bridges/store.js +123 -0
  10. package/dist/heart/commitments.js +105 -0
  11. package/dist/heart/config.js +68 -23
  12. package/dist/heart/core.js +528 -100
  13. package/dist/heart/cross-chat-delivery.js +146 -0
  14. package/dist/heart/daemon/agent-discovery.js +81 -0
  15. package/dist/heart/daemon/auth-flow.js +430 -0
  16. package/dist/heart/daemon/daemon-cli.js +1601 -207
  17. package/dist/heart/daemon/daemon-entry.js +43 -2
  18. package/dist/heart/daemon/daemon-runtime-sync.js +212 -0
  19. package/dist/heart/daemon/daemon.js +226 -1
  20. package/dist/heart/daemon/hatch-animation.js +10 -3
  21. package/dist/heart/daemon/hatch-flow.js +7 -82
  22. package/dist/heart/daemon/hooks/bundle-meta.js +92 -0
  23. package/dist/heart/daemon/launchd.js +159 -0
  24. package/dist/heart/daemon/log-tailer.js +4 -3
  25. package/dist/heart/daemon/message-router.js +17 -8
  26. package/dist/heart/daemon/ouro-bot-entry.js +0 -0
  27. package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
  28. package/dist/heart/daemon/ouro-entry.js +0 -0
  29. package/dist/heart/daemon/ouro-path-installer.js +59 -15
  30. package/dist/heart/daemon/ouro-uti.js +11 -2
  31. package/dist/heart/daemon/ouro-version-manager.js +171 -0
  32. package/dist/heart/daemon/process-manager.js +13 -0
  33. package/dist/heart/daemon/run-hooks.js +37 -0
  34. package/dist/heart/daemon/runtime-logging.js +58 -15
  35. package/dist/heart/daemon/runtime-metadata.js +219 -0
  36. package/dist/heart/daemon/runtime-mode.js +67 -0
  37. package/dist/heart/daemon/sense-manager.js +43 -2
  38. package/dist/heart/daemon/skill-management-installer.js +94 -0
  39. package/dist/heart/daemon/socket-client.js +202 -0
  40. package/dist/heart/daemon/specialist-orchestrator.js +37 -94
  41. package/dist/heart/daemon/specialist-prompt.js +50 -12
  42. package/dist/heart/daemon/specialist-tools.js +211 -60
  43. package/dist/heart/daemon/staged-restart.js +114 -0
  44. package/dist/heart/daemon/thoughts.js +507 -0
  45. package/dist/heart/daemon/update-checker.js +111 -0
  46. package/dist/heart/daemon/update-hooks.js +138 -0
  47. package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
  48. package/dist/heart/delegation.js +62 -0
  49. package/dist/heart/identity.js +64 -21
  50. package/dist/heart/kicks.js +1 -19
  51. package/dist/heart/model-capabilities.js +48 -0
  52. package/dist/heart/obligations.js +197 -0
  53. package/dist/heart/progress-story.js +42 -0
  54. package/dist/heart/provider-failover.js +88 -0
  55. package/dist/heart/provider-ping.js +151 -0
  56. package/dist/heart/providers/anthropic.js +107 -20
  57. package/dist/heart/providers/azure.js +115 -9
  58. package/dist/heart/providers/github-copilot.js +157 -0
  59. package/dist/heart/providers/minimax.js +33 -3
  60. package/dist/heart/providers/openai-codex.js +49 -14
  61. package/dist/heart/safe-workspace.js +381 -0
  62. package/dist/heart/session-activity.js +169 -0
  63. package/dist/heart/session-recall.js +216 -0
  64. package/dist/heart/streaming.js +108 -24
  65. package/dist/heart/target-resolution.js +123 -0
  66. package/dist/heart/tool-loop.js +194 -0
  67. package/dist/heart/turn-coordinator.js +28 -0
  68. package/dist/mind/associative-recall.js +14 -2
  69. package/dist/mind/bundle-manifest.js +70 -0
  70. package/dist/mind/context.js +60 -14
  71. package/dist/mind/first-impressions.js +16 -2
  72. package/dist/mind/friends/channel.js +35 -0
  73. package/dist/mind/friends/group-context.js +144 -0
  74. package/dist/mind/friends/store-file.js +19 -0
  75. package/dist/mind/friends/trust-explanation.js +74 -0
  76. package/dist/mind/friends/types.js +8 -0
  77. package/dist/mind/memory.js +27 -26
  78. package/dist/mind/obligation-steering.js +221 -0
  79. package/dist/mind/pending.js +76 -9
  80. package/dist/mind/phrases.js +1 -0
  81. package/dist/mind/prompt.js +459 -77
  82. package/dist/mind/token-estimate.js +8 -12
  83. package/dist/nerves/cli-logging.js +15 -2
  84. package/dist/nerves/coverage/run-artifacts.js +1 -1
  85. package/dist/nerves/index.js +12 -0
  86. package/dist/repertoire/ado-client.js +4 -2
  87. package/dist/repertoire/coding/context-pack.js +254 -0
  88. package/dist/repertoire/coding/feedback.js +301 -0
  89. package/dist/repertoire/coding/index.js +4 -1
  90. package/dist/repertoire/coding/manager.js +210 -4
  91. package/dist/repertoire/coding/spawner.js +39 -9
  92. package/dist/repertoire/coding/tools.js +171 -4
  93. package/dist/repertoire/data/ado-endpoints.json +188 -0
  94. package/dist/repertoire/guardrails.js +290 -0
  95. package/dist/repertoire/mcp-client.js +254 -0
  96. package/dist/repertoire/mcp-manager.js +195 -0
  97. package/dist/repertoire/skills.js +3 -26
  98. package/dist/repertoire/tasks/board.js +12 -0
  99. package/dist/repertoire/tasks/index.js +23 -9
  100. package/dist/repertoire/tasks/transitions.js +1 -2
  101. package/dist/repertoire/tools-base.js +925 -250
  102. package/dist/repertoire/tools-bluebubbles.js +93 -0
  103. package/dist/repertoire/tools-teams.js +58 -25
  104. package/dist/repertoire/tools.js +106 -53
  105. package/dist/senses/bluebubbles-client.js +210 -5
  106. package/dist/senses/bluebubbles-entry.js +2 -0
  107. package/dist/senses/bluebubbles-inbound-log.js +109 -0
  108. package/dist/senses/bluebubbles-media.js +339 -0
  109. package/dist/senses/bluebubbles-model.js +12 -4
  110. package/dist/senses/bluebubbles-mutation-log.js +45 -5
  111. package/dist/senses/bluebubbles-runtime-state.js +109 -0
  112. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  113. package/dist/senses/bluebubbles.js +912 -45
  114. package/dist/senses/cli-layout.js +187 -0
  115. package/dist/senses/cli.js +477 -170
  116. package/dist/senses/continuity.js +94 -0
  117. package/dist/senses/debug-activity.js +154 -0
  118. package/dist/senses/inner-dialog-worker.js +47 -18
  119. package/dist/senses/inner-dialog.js +388 -83
  120. package/dist/senses/pipeline.js +444 -0
  121. package/dist/senses/teams.js +607 -129
  122. package/dist/senses/trust-gate.js +112 -2
  123. package/package.json +14 -3
  124. package/subagents/README.md +4 -70
  125. package/dist/heart/daemon/specialist-session.js +0 -177
  126. package/dist/heart/daemon/subagent-installer.js +0 -134
  127. package/dist/inner-worker-entry.js +0 -4
  128. package/subagents/work-doer.md +0 -233
  129. package/subagents/work-merger.md +0 -624
  130. package/subagents/work-planner.md +0 -373
@@ -7,7 +7,10 @@ exports.getModel = getModel;
7
7
  exports.getProvider = getProvider;
8
8
  exports.createSummarize = createSummarize;
9
9
  exports.getProviderDisplayLabel = getProviderDisplayLabel;
10
+ exports.isExternalStateQuery = isExternalStateQuery;
11
+ exports.getFinalAnswerRetryError = getFinalAnswerRetryError;
10
12
  exports.stripLastToolCalls = stripLastToolCalls;
13
+ exports.repairOrphanedToolCalls = repairOrphanedToolCalls;
11
14
  exports.isTransientError = isTransientError;
12
15
  exports.classifyTransientError = classifyTransientError;
13
16
  exports.runAgent = runAgent;
@@ -15,9 +18,6 @@ const config_1 = require("./config");
15
18
  const identity_1 = require("./identity");
16
19
  const tools_1 = require("../repertoire/tools");
17
20
  const channel_1 = require("../mind/friends/channel");
18
- // Kick detection preserved but disabled — see comment in agent loop below.
19
- // import { detectKick } from "./kicks";
20
- // import type { KickReason } from "./kicks";
21
21
  const runtime_1 = require("../nerves/runtime");
22
22
  const context_1 = require("../mind/context");
23
23
  const prompt_1 = require("../mind/prompt");
@@ -26,13 +26,48 @@ const anthropic_1 = require("./providers/anthropic");
26
26
  const azure_1 = require("./providers/azure");
27
27
  const minimax_1 = require("./providers/minimax");
28
28
  const openai_codex_1 = require("./providers/openai-codex");
29
+ const github_copilot_1 = require("./providers/github-copilot");
30
+ const pending_1 = require("../mind/pending");
31
+ const identity_2 = require("./identity");
32
+ const socket_client_1 = require("./daemon/socket-client");
33
+ const obligations_1 = require("./obligations");
34
+ const tool_loop_1 = require("./tool-loop");
29
35
  let _providerRuntime = null;
36
+ function getProviderRuntimeFingerprint() {
37
+ const provider = (0, identity_1.loadAgentConfig)().provider;
38
+ /* v8 ignore next -- switch: not all provider branches exercised in CI @preserve */
39
+ switch (provider) {
40
+ case "azure": {
41
+ const { apiKey, endpoint, deployment, modelName, apiVersion, managedIdentityClientId } = (0, config_1.getAzureConfig)();
42
+ return JSON.stringify({ provider, apiKey, endpoint, deployment, modelName, apiVersion, managedIdentityClientId });
43
+ }
44
+ case "anthropic": {
45
+ const { model, setupToken } = (0, config_1.getAnthropicConfig)();
46
+ return JSON.stringify({ provider, model, setupToken });
47
+ }
48
+ case "minimax": {
49
+ const { apiKey, model } = (0, config_1.getMinimaxConfig)();
50
+ return JSON.stringify({ provider, apiKey, model });
51
+ }
52
+ case "openai-codex": {
53
+ const { model, oauthAccessToken } = (0, config_1.getOpenAICodexConfig)();
54
+ return JSON.stringify({ provider, model, oauthAccessToken });
55
+ }
56
+ /* v8 ignore start -- fingerprint: tested via provider init tests @preserve */
57
+ case "github-copilot": {
58
+ const { model, githubToken, baseUrl } = (0, config_1.getGithubCopilotConfig)();
59
+ return JSON.stringify({ provider, model, githubToken, baseUrl });
60
+ }
61
+ /* v8 ignore stop */
62
+ }
63
+ }
30
64
  function createProviderRegistry() {
31
65
  const factories = {
32
66
  azure: azure_1.createAzureProviderRuntime,
33
67
  anthropic: anthropic_1.createAnthropicProviderRuntime,
34
68
  minimax: minimax_1.createMinimaxProviderRuntime,
35
69
  "openai-codex": openai_codex_1.createOpenAICodexProviderRuntime,
70
+ "github-copilot": github_copilot_1.createGithubCopilotProviderRuntime,
36
71
  };
37
72
  return {
38
73
  resolve() {
@@ -42,42 +77,44 @@ function createProviderRegistry() {
42
77
  };
43
78
  }
44
79
  function getProviderRuntime() {
45
- if (!_providerRuntime) {
46
- try {
47
- _providerRuntime = createProviderRegistry().resolve();
48
- }
49
- catch (error) {
50
- const msg = error instanceof Error ? error.message : String(error);
51
- (0, runtime_1.emitNervesEvent)({
52
- level: "error",
53
- event: "engine.provider_init_error",
54
- component: "engine",
55
- message: msg,
56
- meta: {},
57
- });
58
- // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
59
- console.error(`\n[fatal] ${msg}\n`);
60
- process.exit(1);
61
- throw new Error("unreachable");
62
- }
63
- if (!_providerRuntime) {
64
- (0, runtime_1.emitNervesEvent)({
65
- level: "error",
66
- event: "engine.provider_init_error",
67
- component: "engine",
68
- message: "provider runtime could not be initialized.",
69
- meta: {},
70
- });
71
- process.exit(1);
72
- throw new Error("unreachable");
80
+ try {
81
+ const fingerprint = getProviderRuntimeFingerprint();
82
+ if (!_providerRuntime || _providerRuntime.fingerprint !== fingerprint) {
83
+ const runtime = createProviderRegistry().resolve();
84
+ _providerRuntime = runtime ? { fingerprint, runtime } : null;
73
85
  }
74
86
  }
75
- return _providerRuntime;
87
+ catch (error) {
88
+ const msg = error instanceof Error ? error.message : String(error);
89
+ (0, runtime_1.emitNervesEvent)({
90
+ level: "error",
91
+ event: "engine.provider_init_error",
92
+ component: "engine",
93
+ message: msg,
94
+ meta: {},
95
+ });
96
+ // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
97
+ console.error(`\n[fatal] ${msg}\n`);
98
+ process.exit(1);
99
+ throw new Error("unreachable");
100
+ }
101
+ if (!_providerRuntime) {
102
+ (0, runtime_1.emitNervesEvent)({
103
+ level: "error",
104
+ event: "engine.provider_init_error",
105
+ component: "engine",
106
+ message: "provider runtime could not be initialized.",
107
+ meta: {},
108
+ });
109
+ process.exit(1);
110
+ throw new Error("unreachable");
111
+ }
112
+ return _providerRuntime.runtime;
76
113
  }
77
114
  /**
78
- * Clear the cached provider runtime so the next call to getProviderRuntime()
79
- * re-creates it from current config. Used by the adoption specialist to
80
- * switch provider context without restarting the process.
115
+ * Clear the cached provider runtime so the next access re-creates it from
116
+ * current config. Runtime access also auto-refreshes when the selected
117
+ * provider fingerprint changes on disk.
81
118
  */
82
119
  function resetProviderRuntime() {
83
120
  _providerRuntime = null;
@@ -104,14 +141,19 @@ function createSummarize() {
104
141
  };
105
142
  }
106
143
  function getProviderDisplayLabel() {
107
- const model = getModel();
144
+ const provider = (0, identity_1.loadAgentConfig)().provider;
108
145
  const providerLabelBuilders = {
109
- azure: () => `azure openai (${(0, config_1.getAzureConfig)().deployment || "default"}, model: ${model})`,
110
- anthropic: () => `anthropic (${model})`,
111
- minimax: () => `minimax (${model})`,
112
- "openai-codex": () => `openai codex (${model})`,
146
+ azure: () => {
147
+ const config = (0, config_1.getAzureConfig)();
148
+ return `azure openai (${config.deployment || "default"}, model: ${config.modelName || "unknown"})`;
149
+ },
150
+ anthropic: () => `anthropic (${(0, config_1.getAnthropicConfig)().model || "unknown"})`,
151
+ minimax: () => `minimax (${(0, config_1.getMinimaxConfig)().model || "unknown"})`,
152
+ "openai-codex": () => `openai codex (${(0, config_1.getOpenAICodexConfig)().model || "unknown"})`,
153
+ /* v8 ignore next -- branch: tested via display label unit test @preserve */
154
+ "github-copilot": () => `github copilot (${(0, config_1.getGithubCopilotConfig)().model || "unknown"})`,
113
155
  };
114
- return providerLabelBuilders[getProvider()]();
156
+ return providerLabelBuilders[provider]();
115
157
  }
116
158
  // Re-export tools, execTool, summarizeArgs from ./tools for backward compat
117
159
  var tools_2 = require("../repertoire/tools");
@@ -128,6 +170,109 @@ Object.defineProperty(exports, "toResponsesTools", { enumerable: true, get: func
128
170
  // Re-export prompt functions for backward compat
129
171
  var prompt_2 = require("../mind/prompt");
130
172
  Object.defineProperty(exports, "buildSystem", { enumerable: true, get: function () { return prompt_2.buildSystem; } });
173
+ const DELEGATION_REASON_PROSE_HANDOFF = {
174
+ explicit_reflection: "something in the conversation called for reflection",
175
+ cross_session: "this touches other conversations",
176
+ bridge_state: "there's shared work spanning sessions",
177
+ task_state: "there are active tasks that relate to this",
178
+ non_fast_path_tool: "this needs tools beyond a simple reply",
179
+ unresolved_obligation: "there's an unresolved commitment from an earlier conversation",
180
+ };
181
+ function buildGoInwardHandoffPacket(params) {
182
+ const reasons = params.delegationDecision?.reasons ?? [];
183
+ const reasonProse = reasons.length > 0
184
+ ? reasons.map((r) => DELEGATION_REASON_PROSE_HANDOFF[r]).join("; ")
185
+ : "this felt like it needed more thought";
186
+ const returnAddress = params.currentSession
187
+ ? `${params.currentSession.friendId}/${params.currentSession.channel}/${params.currentSession.key}`
188
+ : "no specific return -- just thinking";
189
+ let obligationLine;
190
+ if (params.outwardClosureRequired && params.currentSession) {
191
+ obligationLine = `i need to come back to ${params.currentSession.friendId} with something`;
192
+ }
193
+ else {
194
+ obligationLine = "no obligation -- just thinking";
195
+ }
196
+ return [
197
+ "## what i need to think about",
198
+ params.content,
199
+ "",
200
+ "## why this came up",
201
+ reasonProse,
202
+ "",
203
+ "## where to bring it back",
204
+ returnAddress,
205
+ "",
206
+ "## what i owe",
207
+ obligationLine,
208
+ "",
209
+ "## thinking mode",
210
+ params.mode,
211
+ ].join("\n");
212
+ }
213
+ function parseFinalAnswerPayload(argumentsText) {
214
+ try {
215
+ const parsed = JSON.parse(argumentsText);
216
+ if (typeof parsed === "string") {
217
+ return { answer: parsed };
218
+ }
219
+ if (!parsed || typeof parsed !== "object") {
220
+ return {};
221
+ }
222
+ const answer = typeof parsed.answer === "string" ? parsed.answer : undefined;
223
+ const rawIntent = parsed.intent;
224
+ const intent = rawIntent === "complete" || rawIntent === "blocked" || rawIntent === "direct_reply"
225
+ ? rawIntent
226
+ : undefined;
227
+ return { answer, intent };
228
+ }
229
+ catch {
230
+ return {};
231
+ }
232
+ }
233
+ /** Returns true when a tool call queries external state (GitHub, npm registry). */
234
+ function isExternalStateQuery(toolName, args) {
235
+ if (toolName !== "shell")
236
+ return false;
237
+ const cmd = String(args.command ?? "");
238
+ return /\bgh\s+(pr|run|api|issue)\b/.test(cmd) || /\bnpm\s+(view|info|show)\b/.test(cmd);
239
+ }
240
+ function getFinalAnswerRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp, delegationDecision, sawSendMessageSelf, sawGoInward, sawQuerySession, currentObligation, innerJob, sawExternalStateQuery) {
241
+ // 1. Delegation adherence: delegate-inward without evidence of inward action
242
+ if (delegationDecision?.target === "delegate-inward" && !sawSendMessageSelf && !sawGoInward && !sawQuerySession) {
243
+ (0, runtime_1.emitNervesEvent)({
244
+ event: "engine.delegation_adherence_rejected",
245
+ component: "engine",
246
+ message: "delegation adherence check rejected final_answer",
247
+ meta: {
248
+ target: delegationDecision.target,
249
+ reasons: delegationDecision.reasons,
250
+ },
251
+ });
252
+ return "you're reaching for a final answer, but part of you knows this needs more thought. take it inward -- go_inward will let you think privately, or send_message(self) if you just want to leave yourself a note.";
253
+ }
254
+ // 2. Pending obligation not addressed
255
+ if (innerJob?.obligationStatus === "pending" && !sawSendMessageSelf && !sawGoInward) {
256
+ return "you're still holding something from an earlier conversation -- someone is waiting for your answer. finish the thought first, or go_inward to keep working on it privately.";
257
+ }
258
+ // 3. mustResolveBeforeHandoff + missing intent
259
+ if (mustResolveBeforeHandoff && !intent) {
260
+ 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.";
261
+ }
262
+ // 4. mustResolveBeforeHandoff + direct_reply without follow-up
263
+ if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
264
+ 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.";
265
+ }
266
+ // 5. mustResolveBeforeHandoff + complete while a live return loop is still active
267
+ if (mustResolveBeforeHandoff && intent === "complete" && currentObligation && !sawSteeringFollowUp) {
268
+ 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.";
269
+ }
270
+ // 6. External-state grounding: obligation + complete requires fresh external verification
271
+ if (intent === "complete" && currentObligation && !sawExternalStateQuery && !sawSteeringFollowUp) {
272
+ 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 final_answer.";
273
+ }
274
+ return null;
275
+ }
131
276
  // Re-export kick utilities for backward compat
132
277
  var kicks_1 = require("./kicks");
133
278
  Object.defineProperty(exports, "hasToolIntent", { enumerable: true, get: function () { return kicks_1.hasToolIntent; } });
@@ -160,6 +305,68 @@ function stripLastToolCalls(messages) {
160
305
  }
161
306
  }
162
307
  }
308
+ // Roles that end a tool-result scan. When scanning forward from an assistant
309
+ // message, stop at the next assistant or user message (tool results must be
310
+ // adjacent to their originating assistant message).
311
+ const TOOL_SCAN_BOUNDARY_ROLES = new Set(["assistant", "user"]);
312
+ // Repair orphaned tool_calls and tool results anywhere in the message history.
313
+ // 1. If an assistant message has tool_calls but missing tool results, inject synthetic error results.
314
+ // 2. If a tool result's tool_call_id doesn't match any tool_calls in a preceding assistant message, remove it.
315
+ // This prevents 400 errors from the API after an aborted turn.
316
+ function repairOrphanedToolCalls(messages) {
317
+ // Pass 1: collect all valid tool_call IDs from assistant messages
318
+ const validCallIds = new Set();
319
+ for (const msg of messages) {
320
+ if (msg.role === "assistant") {
321
+ const asst = msg;
322
+ if (asst.tool_calls) {
323
+ for (const tc of asst.tool_calls)
324
+ validCallIds.add(tc.id);
325
+ }
326
+ }
327
+ }
328
+ // Pass 2: remove orphaned tool results (tool_call_id not in any assistant's tool_calls)
329
+ for (let i = messages.length - 1; i >= 0; i--) {
330
+ if (messages[i].role === "tool") {
331
+ const toolMsg = messages[i];
332
+ if (!validCallIds.has(toolMsg.tool_call_id)) {
333
+ messages.splice(i, 1);
334
+ }
335
+ }
336
+ }
337
+ // Pass 3: inject synthetic results for tool_calls missing their tool results
338
+ for (let i = 0; i < messages.length; i++) {
339
+ const msg = messages[i];
340
+ if (msg.role !== "assistant")
341
+ continue;
342
+ const asst = msg;
343
+ if (!asst.tool_calls || asst.tool_calls.length === 0)
344
+ continue;
345
+ // Collect tool result IDs that follow this assistant message
346
+ const resultIds = new Set();
347
+ for (let j = i + 1; j < messages.length; j++) {
348
+ const following = messages[j];
349
+ if (following.role === "tool") {
350
+ resultIds.add(following.tool_call_id);
351
+ }
352
+ else if (TOOL_SCAN_BOUNDARY_ROLES.has(following.role)) {
353
+ break;
354
+ }
355
+ }
356
+ const missing = asst.tool_calls.filter((tc) => !resultIds.has(tc.id));
357
+ if (missing.length > 0) {
358
+ const syntheticResults = missing.map((tc) => ({
359
+ role: "tool",
360
+ tool_call_id: tc.id,
361
+ content: "error: tool call was interrupted (previous turn timed out or was aborted)",
362
+ }));
363
+ let insertAt = i + 1;
364
+ while (insertAt < messages.length && messages[insertAt].role === "tool")
365
+ insertAt++;
366
+ messages.splice(insertAt, 0, ...syntheticResults);
367
+ }
368
+ }
369
+ }
163
370
  // Detect context overflow errors from Azure or MiniMax
164
371
  function isContextOverflow(err) {
165
372
  if (!(err instanceof Error))
@@ -215,6 +422,14 @@ function classifyTransientError(err) {
215
422
  }
216
423
  const MAX_RETRIES = 3;
217
424
  const RETRY_BASE_MS = 2000;
425
+ const TRANSIENT_RETRY_LABELS = {
426
+ "auth-failure": "auth error",
427
+ "usage-limit": "usage limit",
428
+ "rate-limit": "rate limited",
429
+ "server-error": "server error",
430
+ "network-error": "network error",
431
+ "unknown": "error",
432
+ };
218
433
  async function runAgent(messages, callbacks, channel, signal, options) {
219
434
  const providerRuntime = getProviderRuntime();
220
435
  const provider = providerRuntime.id;
@@ -242,7 +457,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
242
457
  // so turn execution remains consistent and non-fatal.
243
458
  if (channel) {
244
459
  try {
245
- const refreshed = await (0, prompt_1.buildSystem)(channel, options, currentContext);
460
+ const buildSystemOptions = {
461
+ ...options,
462
+ providerCapabilities: providerRuntime.capabilities,
463
+ supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
464
+ };
465
+ const refreshed = await (0, prompt_1.buildSystem)(channel, buildSystemOptions, currentContext);
246
466
  upsertSystemPrompt(messages, refreshed);
247
467
  }
248
468
  catch (error) {
@@ -265,20 +485,39 @@ async function runAgent(messages, callbacks, channel, signal, options) {
265
485
  }
266
486
  }
267
487
  await (0, associative_recall_1.injectAssociativeRecall)(messages);
268
- // kickCount and lastKickReason preserved but unused while kick detection is disabled.
269
- // let kickCount = 0;
270
- // let lastKickReason: KickReason | null = null;
271
488
  let done = false;
272
489
  let lastUsage;
273
490
  let overflowRetried = false;
274
491
  let retryCount = 0;
492
+ let outcome = "complete";
493
+ let completion;
494
+ let terminalError;
495
+ let terminalErrorClassification;
496
+ let sawSteeringFollowUp = false;
497
+ let mustResolveBeforeHandoffActive = options?.mustResolveBeforeHandoff === true;
498
+ let currentReasoningEffort = "medium";
499
+ let sawSendMessageSelf = false;
500
+ let sawGoInward = false;
501
+ let sawQuerySession = false;
502
+ let sawBridgeManage = false;
503
+ let sawExternalStateQuery = false;
504
+ const toolLoopState = (0, tool_loop_1.createToolLoopState)();
275
505
  // Prevent MaxListenersExceeded warning — each iteration adds a listener
276
506
  try {
277
507
  require("events").setMaxListeners(50, signal);
278
508
  }
279
509
  catch { /* unsupported */ }
280
510
  const toolPreferences = currentContext?.friend?.toolPreferences;
281
- const baseTools = (0, tools_1.getToolsForChannel)(channel ? (0, channel_1.getChannelCapabilities)(channel) : undefined, toolPreferences && Object.keys(toolPreferences).length > 0 ? toolPreferences : undefined);
511
+ 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);
512
+ // Augment tool context with reasoning effort controls from provider
513
+ const augmentedToolContext = options?.toolContext
514
+ ? {
515
+ ...options.toolContext,
516
+ supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
517
+ setReasoningEffort: (level) => { currentReasoningEffort = level; },
518
+ activeWorkFrame: options?.activeWorkFrame,
519
+ }
520
+ : undefined;
282
521
  // Rebase provider-owned turn state from canonical messages at user-turn start.
283
522
  // This prevents stale provider caches from replaying prior-turn context.
284
523
  providerRuntime.resetTurnState(messages);
@@ -287,9 +526,23 @@ async function runAgent(messages, callbacks, channel, signal, options) {
287
526
  // so the model can signal completion. With tool_choice: required, the
288
527
  // model must call a tool every turn — final_answer is how it exits.
289
528
  // Overridable via options.toolChoiceRequired = false (e.g. CLI).
290
- const activeTools = toolChoiceRequired ? [...baseTools, tools_1.finalAnswerTool] : baseTools;
529
+ const activeTools = toolChoiceRequired
530
+ ? [...baseTools, tools_1.goInwardTool, ...(currentContext?.isGroupChat ? [tools_1.noResponseTool] : []), tools_1.finalAnswerTool]
531
+ : baseTools;
291
532
  const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
292
533
  if (steeringFollowUps.length > 0) {
534
+ const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
535
+ if (hasSupersedingFollowUp) {
536
+ mustResolveBeforeHandoffActive = false;
537
+ options?.setMustResolveBeforeHandoff?.(false);
538
+ outcome = "superseded";
539
+ break;
540
+ }
541
+ if (steeringFollowUps.some((followUp) => followUp.effect === "set_no_handoff")) {
542
+ mustResolveBeforeHandoffActive = true;
543
+ options?.setMustResolveBeforeHandoff?.(true);
544
+ }
545
+ sawSteeringFollowUp = true;
293
546
  for (const followUp of steeringFollowUps) {
294
547
  messages.push({ role: "user", content: followUp.text });
295
548
  }
@@ -297,8 +550,10 @@ async function runAgent(messages, callbacks, channel, signal, options) {
297
550
  }
298
551
  // Yield so pending I/O (stdin Ctrl-C) can be processed between iterations
299
552
  await new Promise((r) => setImmediate(r));
300
- if (signal?.aborted)
553
+ if (signal?.aborted) {
554
+ outcome = "aborted";
301
555
  break;
556
+ }
302
557
  try {
303
558
  callbacks.onModelStart();
304
559
  const result = await providerRuntime.streamTurn({
@@ -308,6 +563,8 @@ async function runAgent(messages, callbacks, channel, signal, options) {
308
563
  signal,
309
564
  traceId,
310
565
  toolChoiceRequired,
566
+ reasoningEffort: currentReasoningEffort,
567
+ eagerFinalAnswerStreaming: true,
311
568
  });
312
569
  // Track usage from the latest API call
313
570
  if (result.usage)
@@ -331,49 +588,42 @@ async function runAgent(messages, callbacks, channel, signal, options) {
331
588
  if (reasoningItems.length > 0) {
332
589
  msg._reasoning_items = reasoningItems;
333
590
  }
591
+ // Store thinking blocks (Anthropic) on the assistant message for round-tripping
592
+ const thinkingItems = result.outputItems.filter((item) => "type" in item && (item.type === "thinking" || item.type === "redacted_thinking"));
593
+ if (thinkingItems.length > 0) {
594
+ msg._thinking_blocks = thinkingItems;
595
+ }
596
+ // Phase annotation for Codex provider
597
+ const hasPhaseAnnotation = providerRuntime.capabilities.has("phase-annotation");
598
+ const isSoleFinalAnswer = result.toolCalls.length === 1 && result.toolCalls[0].name === "final_answer";
599
+ if (hasPhaseAnnotation) {
600
+ msg.phase = isSoleFinalAnswer ? "final_answer" : "commentary";
601
+ }
334
602
  if (!result.toolCalls.length) {
335
- // Kick detection is disabled while tool_choice: required + final_answer
336
- // is the primary loop control mechanism. The model should never reach
337
- // this path (tool_choice: required forces a tool call), but if it does,
338
- // accept the response as-is rather than risk false-positive kicks.
339
- //
340
- // Preserved for future use — re-enable by uncommenting:
341
- // const kick = detectKick(result.content, options);
342
- // if (kick) {
343
- // kickCount++;
344
- // lastKickReason = kick.reason;
345
- // callbacks.onKick?.();
346
- // const kickContent = result.content
347
- // ? result.content + "\n\n" + kick.message
348
- // : kick.message;
349
- // messages.push({ role: "assistant", content: kickContent });
350
- // providerRuntime.resetTurnState(messages);
351
- // continue;
352
- // }
603
+ // No tool calls accept response as-is.
604
+ // (Kick detection disabled; tool_choice: required + final_answer
605
+ // is the primary loop control. See src/heart/kicks.ts to re-enable.)
353
606
  messages.push(msg);
354
607
  done = true;
355
608
  }
356
609
  else {
357
610
  // Check for final_answer sole call: intercept before tool execution
358
- const isSoleFinalAnswer = result.toolCalls.length === 1 && result.toolCalls[0].name === "final_answer";
359
611
  if (isSoleFinalAnswer) {
360
612
  // Extract answer from the tool call arguments.
361
- // Supports: {"answer":"text"}, "text" (JSON string), retry on failure.
362
- let answer;
363
- try {
364
- const parsed = JSON.parse(result.toolCalls[0].arguments);
365
- if (typeof parsed === "string") {
366
- answer = parsed;
367
- }
368
- else if (parsed.answer != null) {
369
- answer = parsed.answer;
370
- }
371
- // else: valid JSON but no answer field — answer stays undefined (retry)
372
- }
373
- catch {
374
- // JSON parsing failed (e.g. truncated output) — answer stays undefined (retry)
375
- }
376
- if (answer != null) {
613
+ // Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
614
+ const { answer, intent } = parseFinalAnswerPayload(result.toolCalls[0].arguments);
615
+ const retryError = getFinalAnswerRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp, options?.delegationDecision, sawSendMessageSelf, sawGoInward, sawQuerySession, options?.currentObligation ?? null, options?.activeWorkFrame?.inner?.job, sawExternalStateQuery);
616
+ const deliveredAnswer = answer;
617
+ const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
618
+ const validTerminalIntent = intent === "complete" || intent === "blocked";
619
+ const validClosure = deliveredAnswer != null
620
+ && !retryError
621
+ && (!mustResolveBeforeHandoffActive || validDirectReply || validTerminalIntent);
622
+ if (validClosure) {
623
+ completion = {
624
+ answer: deliveredAnswer,
625
+ intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
626
+ };
377
627
  if (result.finalAnswerStreamed) {
378
628
  // The streaming layer already parsed and emitted the answer
379
629
  // progressively via FinalAnswerParser. Skip clearing and
@@ -384,29 +634,145 @@ async function runAgent(messages, callbacks, channel, signal, options) {
384
634
  callbacks.onClearText?.();
385
635
  // Emit the answer through the callback pipeline so channels receive it.
386
636
  // Never truncate -- channel adapters handle splitting long messages.
387
- callbacks.onTextChunk(answer);
637
+ callbacks.onTextChunk(deliveredAnswer);
388
638
  }
389
- // Keep the full assistant message (with tool_calls) for debuggability,
390
- // plus a synthetic tool response so the conversation stays valid on resume.
391
639
  messages.push(msg);
392
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: "(delivered)" });
393
- providerRuntime.appendToolOutput(result.toolCalls[0].id, "(delivered)");
394
- done = true;
640
+ if (validDirectReply) {
641
+ const resumeWork = "direct reply delivered. resume the unresolved obligation now and keep working until you can finish or clearly report that you are blocked.";
642
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: resumeWork });
643
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, resumeWork);
644
+ }
645
+ else {
646
+ const delivered = "(delivered)";
647
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
648
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
649
+ outcome = intent === "blocked" ? "blocked" : "complete";
650
+ done = true;
651
+ }
395
652
  }
396
653
  else {
397
654
  // Answer is undefined -- the model's final_answer was incomplete or
398
655
  // malformed. Clear any partial streamed text or noise, then push the
399
656
  // assistant msg + error tool result and let the model try again.
400
657
  callbacks.onClearText?.();
401
- const retryError = "your final_answer was incomplete or malformed. call final_answer again with your complete response.";
402
658
  messages.push(msg);
403
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: retryError });
404
- providerRuntime.appendToolOutput(result.toolCalls[0].id, retryError);
659
+ const toolRetryMessage = retryError
660
+ ?? "your final_answer was incomplete or malformed. call final_answer again with your complete response.";
661
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: toolRetryMessage });
662
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, toolRetryMessage);
663
+ }
664
+ continue;
665
+ }
666
+ // Check for no_response sole call: intercept before tool execution
667
+ const isSoleNoResponse = result.toolCalls.length === 1 && result.toolCalls[0].name === "no_response";
668
+ if (isSoleNoResponse) {
669
+ let reason;
670
+ try {
671
+ const parsed = JSON.parse(result.toolCalls[0].arguments);
672
+ if (typeof parsed?.reason === "string")
673
+ reason = parsed.reason;
674
+ }
675
+ catch { /* ignore */ }
676
+ (0, runtime_1.emitNervesEvent)({
677
+ component: "engine",
678
+ event: "engine.no_response",
679
+ message: "agent declined to respond in group chat",
680
+ meta: { ...(reason ? { reason } : {}) },
681
+ });
682
+ messages.push(msg);
683
+ const silenced = "(silenced)";
684
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: silenced });
685
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, silenced);
686
+ outcome = "no_response";
687
+ done = true;
688
+ continue;
689
+ }
690
+ // Check for go_inward sole call: intercept before tool execution
691
+ const isSoleGoInward = result.toolCalls.length === 1 && result.toolCalls[0].name === "go_inward";
692
+ if (isSoleGoInward) {
693
+ let parsedArgs = {};
694
+ try {
695
+ parsedArgs = JSON.parse(result.toolCalls[0].arguments);
696
+ }
697
+ catch { /* ignore */ }
698
+ /* v8 ignore next -- defensive: content always string from model @preserve */
699
+ const content = typeof parsedArgs.content === "string" ? parsedArgs.content : "";
700
+ const answer = typeof parsedArgs.answer === "string" ? parsedArgs.answer : undefined;
701
+ const parsedMode = parsedArgs.mode === "reflect" || parsedArgs.mode === "plan" || parsedArgs.mode === "relay"
702
+ ? parsedArgs.mode
703
+ : undefined;
704
+ const mode = parsedMode || "reflect";
705
+ // Emit outward answer if provided
706
+ if (answer) {
707
+ callbacks.onClearText?.();
708
+ callbacks.onTextChunk(answer);
709
+ }
710
+ // Build handoff packet and enqueue
711
+ const handoffContent = buildGoInwardHandoffPacket({
712
+ content,
713
+ mode,
714
+ delegationDecision: options?.delegationDecision,
715
+ currentSession: options?.toolContext?.currentSession ?? null,
716
+ currentObligation: options?.currentObligation ?? null,
717
+ outwardClosureRequired: options?.delegationDecision?.outwardClosureRequired ?? false,
718
+ });
719
+ const pendingDir = (0, pending_1.getInnerDialogPendingDir)((0, identity_2.getAgentName)());
720
+ const currentSession = options?.toolContext?.currentSession;
721
+ const isInnerChannel = currentSession?.friendId === "self" && currentSession?.channel === "inner";
722
+ const envelope = {
723
+ from: (0, identity_2.getAgentName)(),
724
+ friendId: "self",
725
+ channel: "inner",
726
+ key: "dialog",
727
+ content: handoffContent,
728
+ timestamp: Date.now(),
729
+ mode,
730
+ ...(currentSession && !isInnerChannel ? {
731
+ delegatedFrom: {
732
+ friendId: currentSession.friendId,
733
+ channel: currentSession.channel,
734
+ key: currentSession.key,
735
+ },
736
+ obligationStatus: "pending",
737
+ } : {}),
738
+ };
739
+ (0, pending_1.queuePendingMessage)(pendingDir, envelope);
740
+ if (currentSession && !isInnerChannel) {
741
+ try {
742
+ (0, obligations_1.createObligation)((0, identity_2.getAgentRoot)(), {
743
+ origin: {
744
+ friendId: currentSession.friendId,
745
+ channel: currentSession.channel,
746
+ key: currentSession.key,
747
+ },
748
+ content,
749
+ });
750
+ }
751
+ catch {
752
+ /* v8 ignore next -- defensive: obligation store write failure should not break go_inward @preserve */
753
+ }
405
754
  }
755
+ try {
756
+ await (0, socket_client_1.requestInnerWake)((0, identity_2.getAgentName)());
757
+ }
758
+ catch { /* daemon may not be running */ }
759
+ sawGoInward = true;
760
+ messages.push(msg);
761
+ const ack = "(going inward)";
762
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
763
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
764
+ (0, runtime_1.emitNervesEvent)({
765
+ component: "engine",
766
+ event: "engine.go_inward",
767
+ message: "taking thread inward",
768
+ meta: { mode, hasAnswer: answer !== undefined, contentSnippet: content.slice(0, 80) },
769
+ });
770
+ outcome = "go_inward";
771
+ done = true;
406
772
  continue;
407
773
  }
408
774
  messages.push(msg);
409
- // SHARED: execute tools (final_answer in mixed calls is rejected inline)
775
+ // SHARED: execute tools (final_answer, no_response, go_inward in mixed calls are rejected inline)
410
776
  for (const tc of result.toolCalls) {
411
777
  if (signal?.aborted)
412
778
  break;
@@ -417,6 +783,20 @@ async function runAgent(messages, callbacks, channel, signal, options) {
417
783
  providerRuntime.appendToolOutput(tc.id, rejection);
418
784
  continue;
419
785
  }
786
+ // Intercept no_response in mixed call: reject it
787
+ if (tc.name === "no_response") {
788
+ const rejection = "rejected: no_response must be the only tool call. call no_response alone when you want to stay silent.";
789
+ messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
790
+ providerRuntime.appendToolOutput(tc.id, rejection);
791
+ continue;
792
+ }
793
+ // Intercept go_inward in mixed call: reject it
794
+ if (tc.name === "go_inward") {
795
+ const rejection = "rejected: go_inward must be the only tool call. finish your other work first, then call go_inward alone.";
796
+ messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
797
+ providerRuntime.appendToolOutput(tc.id, rejection);
798
+ continue;
799
+ }
420
800
  let args = {};
421
801
  try {
422
802
  args = JSON.parse(tc.arguments);
@@ -424,7 +804,28 @@ async function runAgent(messages, callbacks, channel, signal, options) {
424
804
  catch {
425
805
  /* ignore */
426
806
  }
807
+ if (tc.name === "send_message" && args.friendId === "self") {
808
+ sawSendMessageSelf = true;
809
+ }
810
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
811
+ if (tc.name === "query_session")
812
+ sawQuerySession = true;
813
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
814
+ if (tc.name === "bridge_manage")
815
+ sawBridgeManage = true;
816
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
817
+ if (isExternalStateQuery(tc.name, args))
818
+ sawExternalStateQuery = true;
427
819
  const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
820
+ const toolLoop = (0, tool_loop_1.detectToolLoop)(toolLoopState, tc.name, args);
821
+ if (toolLoop.stuck) {
822
+ const rejection = `loop guard: ${toolLoop.message}`;
823
+ callbacks.onToolStart(tc.name, args);
824
+ callbacks.onToolEnd(tc.name, argSummary, false);
825
+ messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
826
+ providerRuntime.appendToolOutput(tc.id, rejection);
827
+ continue;
828
+ }
428
829
  // Confirmation check for mutate tools
429
830
  if ((0, tools_1.isConfirmationRequired)(tc.name) && !options?.skipConfirmation) {
430
831
  let decision = "denied";
@@ -444,13 +845,15 @@ async function runAgent(messages, callbacks, channel, signal, options) {
444
845
  let toolResult;
445
846
  let success;
446
847
  try {
447
- toolResult = await (0, tools_1.execTool)(tc.name, args, options?.toolContext);
848
+ const execToolFn = options?.execTool ?? tools_1.execTool;
849
+ toolResult = await execToolFn(tc.name, args, augmentedToolContext ?? options?.toolContext);
448
850
  success = true;
449
851
  }
450
852
  catch (e) {
451
853
  toolResult = `error: ${e}`;
452
854
  success = false;
453
855
  }
856
+ (0, tool_loop_1.recordToolOutcome)(toolLoopState, tc.name, args, toolResult, success);
454
857
  callbacks.onToolEnd(tc.name, argSummary, success);
455
858
  messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
456
859
  providerRuntime.appendToolOutput(tc.id, toolResult);
@@ -461,6 +864,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
461
864
  // Abort is not an error — just stop cleanly
462
865
  if (signal?.aborted) {
463
866
  stripLastToolCalls(messages);
867
+ outcome = "aborted";
464
868
  break;
465
869
  }
466
870
  // Context overflow: trim aggressively and retry once
@@ -478,7 +882,16 @@ async function runAgent(messages, callbacks, channel, signal, options) {
478
882
  if (isTransientError(e) && retryCount < MAX_RETRIES) {
479
883
  retryCount++;
480
884
  const delay = RETRY_BASE_MS * Math.pow(2, retryCount - 1);
481
- const cause = classifyTransientError(e);
885
+ let classification;
886
+ try {
887
+ classification = providerRuntime.classifyError(e instanceof Error ? e : /* v8 ignore next -- defensive: errors are always Error instances @preserve */ new Error(String(e)));
888
+ }
889
+ catch {
890
+ /* v8 ignore next -- defensive: classifyError should not throw @preserve */
891
+ classification = classifyTransientError(e);
892
+ }
893
+ /* v8 ignore next -- defensive: all classifications have labels @preserve */
894
+ const cause = TRANSIENT_RETRY_LABELS[classification] ?? classification;
482
895
  callbacks.onError(new Error(`${cause}, retrying in ${delay / 1000}s (${retryCount}/${MAX_RETRIES})...`), "transient");
483
896
  // Wait with abort support
484
897
  const aborted = await new Promise((resolve) => {
@@ -495,21 +908,31 @@ async function runAgent(messages, callbacks, channel, signal, options) {
495
908
  });
496
909
  if (aborted) {
497
910
  stripLastToolCalls(messages);
911
+ outcome = "aborted";
498
912
  break;
499
913
  }
500
914
  providerRuntime.resetTurnState(messages);
501
915
  continue;
502
916
  }
503
- callbacks.onError(e instanceof Error ? e : new Error(String(e)), "terminal");
917
+ terminalError = e instanceof Error ? e : new Error(String(e));
918
+ try {
919
+ terminalErrorClassification = providerRuntime.classifyError(terminalError);
920
+ }
921
+ catch {
922
+ /* v8 ignore next -- defensive: classifyError should not throw @preserve */
923
+ terminalErrorClassification = "unknown";
924
+ }
925
+ callbacks.onError(terminalError, "terminal");
504
926
  (0, runtime_1.emitNervesEvent)({
505
927
  level: "error",
506
928
  event: "engine.error",
507
929
  trace_id: traceId,
508
930
  component: "engine",
509
- message: e instanceof Error ? e.message : String(e),
510
- meta: {},
931
+ message: terminalError.message,
932
+ meta: { errorClassification: terminalErrorClassification },
511
933
  });
512
934
  stripLastToolCalls(messages);
935
+ outcome = "errored";
513
936
  done = true;
514
937
  }
515
938
  }
@@ -518,7 +941,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
518
941
  trace_id: traceId,
519
942
  component: "engine",
520
943
  message: "runAgent turn completed",
521
- meta: { done },
944
+ meta: { done, sawGoInward, sawQuerySession, sawBridgeManage },
522
945
  });
523
- return { usage: lastUsage };
946
+ return {
947
+ usage: lastUsage,
948
+ outcome,
949
+ completion,
950
+ ...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
951
+ };
524
952
  }