@ouro.bot/cli 0.1.0-alpha.16 → 0.1.0-alpha.160

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 (165) hide show
  1. package/AdoptionSpecialist.ouro/agent.json +3 -2
  2. package/AdoptionSpecialist.ouro/psyche/SOUL.md +3 -3
  3. package/AdoptionSpecialist.ouro/psyche/identities/monty.md +2 -2
  4. package/README.md +186 -191
  5. package/changelog.json +1081 -0
  6. package/dist/heart/active-work.js +633 -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 +40 -30
  12. package/dist/heart/core.js +608 -123
  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/agent-service.js +360 -0
  16. package/dist/heart/daemon/auth-flow.js +477 -0
  17. package/dist/heart/daemon/cadence.js +70 -0
  18. package/dist/heart/daemon/daemon-cli.js +2467 -205
  19. package/dist/heart/daemon/daemon-entry.js +131 -4
  20. package/dist/heart/daemon/daemon-health.js +136 -0
  21. package/dist/heart/daemon/daemon-runtime-sync.js +212 -0
  22. package/dist/heart/daemon/daemon-tombstone.js +123 -0
  23. package/dist/heart/daemon/daemon.js +434 -17
  24. package/dist/heart/daemon/habit-migration.js +181 -0
  25. package/dist/heart/daemon/habit-parser.js +119 -0
  26. package/dist/heart/daemon/habit-scheduler.js +369 -0
  27. package/dist/heart/daemon/hatch-animation.js +10 -3
  28. package/dist/heart/daemon/hatch-flow.js +30 -111
  29. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  30. package/dist/heart/daemon/hooks/bundle-meta.js +92 -0
  31. package/dist/heart/daemon/inner-status.js +89 -0
  32. package/dist/heart/daemon/launchd.js +159 -0
  33. package/dist/heart/daemon/log-tailer.js +4 -3
  34. package/dist/heart/daemon/mcp-server.js +591 -0
  35. package/dist/heart/daemon/message-router.js +17 -8
  36. package/dist/heart/daemon/os-cron-deps.js +134 -0
  37. package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
  38. package/dist/heart/daemon/ouro-path-installer.js +78 -34
  39. package/dist/heart/daemon/ouro-version-manager.js +171 -0
  40. package/dist/heart/daemon/outlook-http.js +307 -0
  41. package/dist/heart/daemon/outlook-read.js +1281 -0
  42. package/dist/heart/daemon/outlook-render.js +1032 -0
  43. package/dist/heart/daemon/outlook-types.js +7 -0
  44. package/dist/heart/daemon/outlook-view.js +194 -0
  45. package/dist/heart/daemon/process-manager.js +75 -0
  46. package/dist/heart/daemon/run-hooks.js +39 -0
  47. package/dist/heart/daemon/runtime-logging.js +58 -15
  48. package/dist/heart/daemon/runtime-metadata.js +219 -0
  49. package/dist/heart/daemon/runtime-mode.js +67 -0
  50. package/dist/heart/daemon/safe-mode.js +161 -0
  51. package/dist/heart/daemon/sense-manager.js +50 -2
  52. package/dist/heart/daemon/session-id-resolver.js +131 -0
  53. package/dist/heart/daemon/skill-management-installer.js +94 -0
  54. package/dist/heart/daemon/socket-client.js +202 -0
  55. package/dist/heart/daemon/specialist-orchestrator.js +2 -2
  56. package/dist/heart/daemon/specialist-prompt.js +13 -8
  57. package/dist/heart/daemon/specialist-tools.js +53 -4
  58. package/dist/heart/daemon/staged-restart.js +114 -0
  59. package/dist/heart/daemon/task-scheduler.js +3 -25
  60. package/dist/heart/daemon/thoughts.js +507 -0
  61. package/dist/heart/daemon/update-checker.js +111 -0
  62. package/dist/heart/daemon/update-hooks.js +138 -0
  63. package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
  64. package/dist/heart/delegation.js +62 -0
  65. package/dist/heart/identity.js +136 -55
  66. package/dist/heart/kicks.js +2 -20
  67. package/dist/heart/migrate-config.js +127 -0
  68. package/dist/heart/model-capabilities.js +48 -0
  69. package/dist/heart/obligations.js +197 -0
  70. package/dist/heart/progress-story.js +42 -0
  71. package/dist/heart/provider-failover.js +88 -0
  72. package/dist/heart/provider-ping.js +172 -0
  73. package/dist/heart/providers/anthropic-token.js +163 -0
  74. package/dist/heart/providers/anthropic.js +196 -36
  75. package/dist/heart/providers/azure.js +116 -10
  76. package/dist/heart/providers/github-copilot.js +157 -0
  77. package/dist/heart/providers/minimax.js +33 -3
  78. package/dist/heart/providers/openai-codex.js +51 -16
  79. package/dist/heart/session-activity.js +172 -0
  80. package/dist/heart/session-recall.js +216 -0
  81. package/dist/heart/streaming.js +117 -33
  82. package/dist/heart/target-resolution.js +127 -0
  83. package/dist/heart/tool-activity-callbacks.js +36 -0
  84. package/dist/heart/tool-description.js +135 -0
  85. package/dist/heart/tool-loop.js +200 -0
  86. package/dist/heart/turn-coordinator.js +28 -0
  87. package/dist/mind/associative-recall.js +122 -32
  88. package/dist/mind/bundle-manifest.js +14 -0
  89. package/dist/mind/context.js +125 -14
  90. package/dist/mind/{memory.js → diary.js} +70 -56
  91. package/dist/mind/first-impressions.js +16 -2
  92. package/dist/mind/friends/channel.js +56 -0
  93. package/dist/mind/friends/group-context.js +144 -0
  94. package/dist/mind/friends/store-file.js +19 -0
  95. package/dist/mind/friends/trust-explanation.js +74 -0
  96. package/dist/mind/friends/types.js +8 -0
  97. package/dist/mind/journal-index.js +161 -0
  98. package/dist/mind/obligation-steering.js +221 -0
  99. package/dist/mind/obligations.js +134 -0
  100. package/dist/mind/pending.js +76 -9
  101. package/dist/mind/phrases.js +1 -0
  102. package/dist/mind/prompt.js +651 -91
  103. package/dist/mind/token-estimate.js +8 -12
  104. package/dist/nerves/cli-logging.js +15 -2
  105. package/dist/nerves/coverage/run-artifacts.js +1 -1
  106. package/dist/nerves/event-buffer.js +111 -0
  107. package/dist/nerves/index.js +63 -3
  108. package/dist/nerves/observation.js +20 -0
  109. package/dist/nerves/runtime.js +5 -1
  110. package/dist/repertoire/ado-semantic.js +6 -0
  111. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  112. package/dist/repertoire/coding/context-pack.js +254 -0
  113. package/dist/repertoire/coding/feedback.js +301 -0
  114. package/dist/repertoire/coding/index.js +4 -1
  115. package/dist/repertoire/coding/manager.js +210 -4
  116. package/dist/repertoire/coding/spawner.js +58 -12
  117. package/dist/repertoire/coding/tools.js +176 -4
  118. package/dist/repertoire/guardrails.js +291 -0
  119. package/dist/repertoire/mcp-client.js +254 -0
  120. package/dist/repertoire/mcp-manager.js +198 -0
  121. package/dist/repertoire/skills.js +14 -23
  122. package/dist/repertoire/tasks/board.js +43 -5
  123. package/dist/repertoire/tasks/fix.js +182 -0
  124. package/dist/repertoire/tasks/index.js +28 -10
  125. package/dist/repertoire/tasks/lifecycle.js +2 -2
  126. package/dist/repertoire/tasks/parser.js +3 -2
  127. package/dist/repertoire/tasks/scanner.js +194 -37
  128. package/dist/repertoire/tasks/transitions.js +11 -28
  129. package/dist/repertoire/tools-base.js +992 -273
  130. package/dist/repertoire/tools-bluebubbles.js +94 -0
  131. package/dist/repertoire/tools-github.js +1 -6
  132. package/dist/repertoire/tools-teams.js +12 -59
  133. package/dist/repertoire/tools.js +281 -101
  134. package/dist/scripts/claude-code-hook.js +41 -0
  135. package/dist/scripts/claude-code-stop-hook.js +47 -0
  136. package/dist/senses/attention-queue.js +97 -0
  137. package/dist/senses/bluebubbles-client.js +258 -5
  138. package/dist/senses/bluebubbles-entry.js +2 -0
  139. package/dist/senses/bluebubbles-inbound-log.js +109 -0
  140. package/dist/senses/bluebubbles-media.js +339 -0
  141. package/dist/senses/bluebubbles-model.js +12 -4
  142. package/dist/senses/bluebubbles-mutation-log.js +45 -5
  143. package/dist/senses/bluebubbles-runtime-state.js +109 -0
  144. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  145. package/dist/senses/bluebubbles.js +1040 -45
  146. package/dist/senses/cli-entry.js +1 -1
  147. package/dist/senses/cli-layout.js +187 -0
  148. package/dist/senses/cli.js +419 -152
  149. package/dist/senses/commands.js +38 -1
  150. package/dist/senses/continuity.js +94 -0
  151. package/dist/senses/habit-turn-message.js +108 -0
  152. package/dist/senses/inner-dialog-worker.js +112 -19
  153. package/dist/senses/inner-dialog.js +592 -84
  154. package/dist/senses/pipeline.js +502 -0
  155. package/dist/senses/shared-turn.js +196 -0
  156. package/dist/senses/surface-tool.js +95 -0
  157. package/dist/senses/teams.js +667 -120
  158. package/dist/senses/trust-gate.js +112 -2
  159. package/package.json +12 -4
  160. package/skills/configure-dev-tools.md +81 -0
  161. package/subagents/README.md +4 -70
  162. package/dist/heart/daemon/subagent-installer.js +0 -134
  163. package/subagents/work-doer.md +0 -233
  164. package/subagents/work-merger.md +0 -624
  165. package/subagents/work-planner.md +0 -373
@@ -7,6 +7,8 @@ exports.getModel = getModel;
7
7
  exports.getProvider = getProvider;
8
8
  exports.createSummarize = createSummarize;
9
9
  exports.getProviderDisplayLabel = getProviderDisplayLabel;
10
+ exports.isExternalStateQuery = isExternalStateQuery;
11
+ exports.getSettleRetryError = getSettleRetryError;
10
12
  exports.stripLastToolCalls = stripLastToolCalls;
11
13
  exports.repairOrphanedToolCalls = repairOrphanedToolCalls;
12
14
  exports.isTransientError = isTransientError;
@@ -16,9 +18,7 @@ const config_1 = require("./config");
16
18
  const identity_1 = require("./identity");
17
19
  const tools_1 = require("../repertoire/tools");
18
20
  const channel_1 = require("../mind/friends/channel");
19
- // Kick detection preserved but disabled — see comment in agent loop below.
20
- // import { detectKick } from "./kicks";
21
- // import type { KickReason } from "./kicks";
21
+ const surface_tool_1 = require("../senses/surface-tool");
22
22
  const runtime_1 = require("../nerves/runtime");
23
23
  const context_1 = require("../mind/context");
24
24
  const prompt_1 = require("../mind/prompt");
@@ -27,71 +27,119 @@ const anthropic_1 = require("./providers/anthropic");
27
27
  const azure_1 = require("./providers/azure");
28
28
  const minimax_1 = require("./providers/minimax");
29
29
  const openai_codex_1 = require("./providers/openai-codex");
30
- let _providerRuntime = null;
30
+ const github_copilot_1 = require("./providers/github-copilot");
31
+ const pending_1 = require("../mind/pending");
32
+ const identity_2 = require("./identity");
33
+ const socket_client_1 = require("./daemon/socket-client");
34
+ const obligations_1 = require("./obligations");
35
+ const tool_loop_1 = require("./tool-loop");
36
+ const _providerRuntimes = {
37
+ human: null,
38
+ agent: null,
39
+ };
40
+ function getProviderRuntimeFingerprint(facing) {
41
+ const config = (0, identity_1.loadAgentConfig)();
42
+ const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
43
+ const provider = facingConfig.provider;
44
+ const model = facingConfig.model;
45
+ /* v8 ignore next -- switch: not all provider branches exercised in CI @preserve */
46
+ switch (provider) {
47
+ case "azure": {
48
+ const { apiKey, endpoint, deployment, apiVersion, managedIdentityClientId } = (0, config_1.getAzureConfig)();
49
+ return JSON.stringify({ provider, model, apiKey, endpoint, deployment, apiVersion, managedIdentityClientId });
50
+ }
51
+ case "anthropic": {
52
+ const { setupToken } = (0, config_1.getAnthropicConfig)();
53
+ return JSON.stringify({ provider, model, setupToken });
54
+ }
55
+ case "minimax": {
56
+ const { apiKey } = (0, config_1.getMinimaxConfig)();
57
+ return JSON.stringify({ provider, model, apiKey });
58
+ }
59
+ case "openai-codex": {
60
+ const { oauthAccessToken } = (0, config_1.getOpenAICodexConfig)();
61
+ return JSON.stringify({ provider, model, oauthAccessToken });
62
+ }
63
+ /* v8 ignore start -- fingerprint: tested via provider init tests @preserve */
64
+ case "github-copilot": {
65
+ const { githubToken, baseUrl } = (0, config_1.getGithubCopilotConfig)();
66
+ return JSON.stringify({ provider, model, githubToken, baseUrl });
67
+ }
68
+ /* v8 ignore stop */
69
+ }
70
+ }
31
71
  function createProviderRegistry() {
32
72
  const factories = {
33
73
  azure: azure_1.createAzureProviderRuntime,
34
74
  anthropic: anthropic_1.createAnthropicProviderRuntime,
35
75
  minimax: minimax_1.createMinimaxProviderRuntime,
36
76
  "openai-codex": openai_codex_1.createOpenAICodexProviderRuntime,
77
+ "github-copilot": github_copilot_1.createGithubCopilotProviderRuntime,
37
78
  };
38
79
  return {
39
- resolve() {
40
- const provider = (0, identity_1.loadAgentConfig)().provider;
41
- return factories[provider]();
80
+ resolve(provider, model) {
81
+ const resolvedProvider = provider ?? (0, identity_1.loadAgentConfig)().humanFacing.provider;
82
+ const resolvedModel = model ?? (0, identity_1.loadAgentConfig)().humanFacing.model;
83
+ return factories[resolvedProvider](resolvedModel);
42
84
  },
43
85
  };
44
86
  }
45
- function getProviderRuntime() {
46
- if (!_providerRuntime) {
47
- try {
48
- _providerRuntime = createProviderRegistry().resolve();
49
- }
50
- catch (error) {
51
- const msg = error instanceof Error ? error.message : String(error);
52
- (0, runtime_1.emitNervesEvent)({
53
- level: "error",
54
- event: "engine.provider_init_error",
55
- component: "engine",
56
- message: msg,
57
- meta: {},
58
- });
59
- // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
60
- console.error(`\n[fatal] ${msg}\n`);
61
- process.exit(1);
62
- throw new Error("unreachable");
63
- }
64
- if (!_providerRuntime) {
65
- (0, runtime_1.emitNervesEvent)({
66
- level: "error",
67
- event: "engine.provider_init_error",
68
- component: "engine",
69
- message: "provider runtime could not be initialized.",
70
- meta: {},
71
- });
72
- process.exit(1);
73
- throw new Error("unreachable");
87
+ function getProviderRuntime(facing = "human") {
88
+ try {
89
+ const fingerprint = getProviderRuntimeFingerprint(facing);
90
+ const cached = _providerRuntimes[facing];
91
+ if (!cached || cached.fingerprint !== fingerprint) {
92
+ const config = (0, identity_1.loadAgentConfig)();
93
+ const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
94
+ const runtime = createProviderRegistry().resolve(facingConfig.provider, facingConfig.model);
95
+ _providerRuntimes[facing] = runtime ? { fingerprint, runtime } : null;
74
96
  }
75
97
  }
76
- return _providerRuntime;
98
+ catch (error) {
99
+ const msg = error instanceof Error ? error.message : String(error);
100
+ (0, runtime_1.emitNervesEvent)({
101
+ level: "error",
102
+ event: "engine.provider_init_error",
103
+ component: "engine",
104
+ message: msg,
105
+ meta: {},
106
+ });
107
+ // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
108
+ console.error(`\n[fatal] ${msg}\n`);
109
+ process.exit(1);
110
+ throw new Error("unreachable");
111
+ }
112
+ if (!_providerRuntimes[facing]) {
113
+ (0, runtime_1.emitNervesEvent)({
114
+ level: "error",
115
+ event: "engine.provider_init_error",
116
+ component: "engine",
117
+ message: "provider runtime could not be initialized.",
118
+ meta: {},
119
+ });
120
+ process.exit(1);
121
+ throw new Error("unreachable");
122
+ }
123
+ return _providerRuntimes[facing].runtime;
77
124
  }
78
125
  /**
79
- * Clear the cached provider runtime so the next call to getProviderRuntime()
80
- * re-creates it from current config. Used by the adoption specialist to
81
- * switch provider context without restarting the process.
126
+ * Clear the cached provider runtime so the next access re-creates it from
127
+ * current config. Runtime access also auto-refreshes when the selected
128
+ * provider fingerprint changes on disk.
82
129
  */
83
130
  function resetProviderRuntime() {
84
- _providerRuntime = null;
131
+ _providerRuntimes.human = null;
132
+ _providerRuntimes.agent = null;
85
133
  }
86
- function getModel() {
87
- return getProviderRuntime().model;
134
+ function getModel(facing = "human") {
135
+ return getProviderRuntime(facing).model;
88
136
  }
89
- function getProvider() {
90
- return getProviderRuntime().id;
137
+ function getProvider(facing = "human") {
138
+ return getProviderRuntime(facing).id;
91
139
  }
92
- function createSummarize() {
140
+ function createSummarize(facing = "human") {
93
141
  return async (transcript, instruction) => {
94
- const runtime = getProviderRuntime();
142
+ const runtime = getProviderRuntime(facing);
95
143
  const client = runtime.client;
96
144
  const response = await client.chat.completions.create({
97
145
  model: runtime.model,
@@ -104,15 +152,23 @@ function createSummarize() {
104
152
  return response.choices?.[0]?.message?.content ?? transcript;
105
153
  };
106
154
  }
107
- function getProviderDisplayLabel() {
108
- const model = getModel();
155
+ function getProviderDisplayLabel(facing = "human") {
156
+ const config = (0, identity_1.loadAgentConfig)();
157
+ const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
158
+ const provider = facingConfig.provider;
159
+ const model = facingConfig.model || "unknown";
109
160
  const providerLabelBuilders = {
110
- azure: () => `azure openai (${(0, config_1.getAzureConfig)().deployment || "default"}, model: ${model})`,
161
+ azure: () => {
162
+ const azureCfg = (0, config_1.getAzureConfig)();
163
+ return `azure openai (${azureCfg.deployment || "default"}, model: ${model})`;
164
+ },
111
165
  anthropic: () => `anthropic (${model})`,
112
166
  minimax: () => `minimax (${model})`,
113
167
  "openai-codex": () => `openai codex (${model})`,
168
+ /* v8 ignore next -- branch: tested via display label unit test @preserve */
169
+ "github-copilot": () => `github copilot (${model})`,
114
170
  };
115
- return providerLabelBuilders[getProvider()]();
171
+ return providerLabelBuilders[provider]();
116
172
  }
117
173
  // Re-export tools, execTool, summarizeArgs from ./tools for backward compat
118
174
  var tools_2 = require("../repertoire/tools");
@@ -129,6 +185,108 @@ Object.defineProperty(exports, "toResponsesTools", { enumerable: true, get: func
129
185
  // Re-export prompt functions for backward compat
130
186
  var prompt_2 = require("../mind/prompt");
131
187
  Object.defineProperty(exports, "buildSystem", { enumerable: true, get: function () { return prompt_2.buildSystem; } });
188
+ // Sole-call tools must be the only tool call in a turn. When they appear
189
+ // alongside other tools, the sole-call tool is rejected with this message.
190
+ const SOLE_CALL_REJECTION = {
191
+ settle: "rejected: settle must be the only tool call. finish your work first, then call settle alone.",
192
+ observe: "rejected: observe must be the only tool call. call observe alone when you want to stay silent.",
193
+ ponder: "rejected: ponder must be the only tool call. finish your other work first, then call ponder alone.",
194
+ rest: "rejected: rest must be the only tool call. finish your work first, then call rest alone.",
195
+ };
196
+ const DELEGATION_REASON_PROSE_HANDOFF = {
197
+ explicit_reflection: "something in the conversation called for reflection",
198
+ cross_session: "this touches other conversations",
199
+ bridge_state: "there's shared work spanning sessions",
200
+ task_state: "there are active tasks that relate to this",
201
+ non_fast_path_tool: "this needs tools beyond a simple reply",
202
+ unresolved_obligation: "there's an unresolved commitment from an earlier conversation",
203
+ };
204
+ function buildPonderHandoffPacket(params) {
205
+ const reasons = params.delegationDecision?.reasons ?? [];
206
+ const reasonProse = reasons.length > 0
207
+ ? reasons.map((r) => DELEGATION_REASON_PROSE_HANDOFF[r]).join("; ")
208
+ : "this felt like it needed more thought";
209
+ const whoAsked = params.currentSession
210
+ ? params.currentSession.friendId
211
+ : "no one -- just thinking";
212
+ let holdingLine;
213
+ if (params.outwardClosureRequired && params.currentSession) {
214
+ holdingLine = `i'm holding something for ${params.currentSession.friendId}`;
215
+ }
216
+ else {
217
+ holdingLine = "nothing -- just thinking";
218
+ }
219
+ return [
220
+ "## what i need to think about",
221
+ params.topic,
222
+ "",
223
+ "## why this came up",
224
+ reasonProse,
225
+ "",
226
+ "## who asked",
227
+ whoAsked,
228
+ "",
229
+ "## what i'm holding",
230
+ holdingLine,
231
+ "",
232
+ "## thinking mode",
233
+ params.mode,
234
+ ].join("\n");
235
+ }
236
+ function parseSettlePayload(argumentsText) {
237
+ try {
238
+ const parsed = JSON.parse(argumentsText);
239
+ if (typeof parsed === "string") {
240
+ return { answer: parsed };
241
+ }
242
+ if (!parsed || typeof parsed !== "object") {
243
+ return {};
244
+ }
245
+ const answer = typeof parsed.answer === "string" ? parsed.answer : undefined;
246
+ const rawIntent = parsed.intent;
247
+ const intent = rawIntent === "complete" || rawIntent === "blocked" || rawIntent === "direct_reply"
248
+ ? rawIntent
249
+ : undefined;
250
+ return { answer, intent };
251
+ }
252
+ catch {
253
+ return {};
254
+ }
255
+ }
256
+ /** Returns true when a tool call queries external state (GitHub, npm registry). */
257
+ function isExternalStateQuery(toolName, args) {
258
+ if (toolName !== "shell")
259
+ return false;
260
+ const cmd = String(args.command ?? "");
261
+ return /\bgh\s+(pr|run|api|issue)\b/.test(cmd) || /\bnpm\s+(view|info|show)\b/.test(cmd);
262
+ }
263
+ function getSettleRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp, _delegationDecision, sawSendMessageSelf, sawPonder, _sawQuerySession, currentObligation, innerJob, sawExternalStateQuery) {
264
+ // Delegation adherence removed: the delegation decision is surfaced in the
265
+ // system prompt as a suggestion. Hard-gating settle caused infinite
266
+ // rejection loops where the agent couldn't respond to the user at all.
267
+ // The agent is free to follow or ignore the delegation hint.
268
+ // 2. Pending obligation not addressed
269
+ if (innerJob?.obligationStatus === "pending" && !sawSendMessageSelf && !sawPonder) {
270
+ 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.";
271
+ }
272
+ // 3. mustResolveBeforeHandoff + missing intent
273
+ if (mustResolveBeforeHandoff && !intent) {
274
+ 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.";
275
+ }
276
+ // 4. mustResolveBeforeHandoff + direct_reply without follow-up
277
+ if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
278
+ 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.";
279
+ }
280
+ // 5. mustResolveBeforeHandoff + complete while a live return loop is still active
281
+ if (mustResolveBeforeHandoff && intent === "complete" && currentObligation && !sawSteeringFollowUp) {
282
+ 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.";
283
+ }
284
+ // 6. External-state grounding: obligation + complete requires fresh external verification
285
+ if (intent === "complete" && currentObligation && !sawExternalStateQuery && !sawSteeringFollowUp) {
286
+ 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.";
287
+ }
288
+ return null;
289
+ }
132
290
  // Re-export kick utilities for backward compat
133
291
  var kicks_1 = require("./kicks");
134
292
  Object.defineProperty(exports, "hasToolIntent", { enumerable: true, get: function () { return kicks_1.hasToolIntent; } });
@@ -278,8 +436,17 @@ function classifyTransientError(err) {
278
436
  }
279
437
  const MAX_RETRIES = 3;
280
438
  const RETRY_BASE_MS = 2000;
439
+ const TRANSIENT_RETRY_LABELS = {
440
+ "auth-failure": "auth error",
441
+ "usage-limit": "usage limit",
442
+ "rate-limit": "rate limited",
443
+ "server-error": "server error",
444
+ "network-error": "network error",
445
+ "unknown": "error",
446
+ };
281
447
  async function runAgent(messages, callbacks, channel, signal, options) {
282
- const providerRuntime = getProviderRuntime();
448
+ const facing = (0, channel_1.channelToFacing)(channel);
449
+ const providerRuntime = getProviderRuntime(facing);
283
450
  const provider = providerRuntime.id;
284
451
  const toolChoiceRequired = options?.toolChoiceRequired ?? true;
285
452
  const traceId = options?.traceId;
@@ -305,7 +472,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
305
472
  // so turn execution remains consistent and non-fatal.
306
473
  if (channel) {
307
474
  try {
308
- const refreshed = await (0, prompt_1.buildSystem)(channel, options, currentContext);
475
+ const buildSystemOptions = {
476
+ ...options,
477
+ providerCapabilities: providerRuntime.capabilities,
478
+ supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
479
+ };
480
+ const refreshed = await (0, prompt_1.buildSystem)(channel, buildSystemOptions, currentContext);
309
481
  upsertSystemPrompt(messages, refreshed);
310
482
  }
311
483
  catch (error) {
@@ -328,31 +500,77 @@ async function runAgent(messages, callbacks, channel, signal, options) {
328
500
  }
329
501
  }
330
502
  await (0, associative_recall_1.injectAssociativeRecall)(messages);
331
- // kickCount and lastKickReason preserved but unused while kick detection is disabled.
332
- // let kickCount = 0;
333
- // let lastKickReason: KickReason | null = null;
334
503
  let done = false;
335
504
  let lastUsage;
336
505
  let overflowRetried = false;
337
506
  let retryCount = 0;
507
+ let outcome = "settled";
508
+ let completion;
509
+ let terminalError;
510
+ let terminalErrorClassification;
511
+ let sawSteeringFollowUp = false;
512
+ let mustResolveBeforeHandoffActive = options?.mustResolveBeforeHandoff === true;
513
+ let currentReasoningEffort = "medium";
514
+ let sawSendMessageSelf = false;
515
+ let sawPonder = false;
516
+ let sawQuerySession = false;
517
+ let sawBridgeManage = false;
518
+ let sawExternalStateQuery = false;
519
+ const toolLoopState = (0, tool_loop_1.createToolLoopState)();
338
520
  // Prevent MaxListenersExceeded warning — each iteration adds a listener
339
521
  try {
340
522
  require("events").setMaxListeners(50, signal);
341
523
  }
342
524
  catch { /* unsupported */ }
343
525
  const toolPreferences = currentContext?.friend?.toolPreferences;
344
- const baseTools = options?.tools ?? (0, tools_1.getToolsForChannel)(channel ? (0, channel_1.getChannelCapabilities)(channel) : undefined, toolPreferences && Object.keys(toolPreferences).length > 0 ? toolPreferences : undefined);
526
+ 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);
527
+ // Augment tool context with reasoning effort controls from provider
528
+ const augmentedToolContext = options?.toolContext
529
+ ? {
530
+ ...options.toolContext,
531
+ supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
532
+ setReasoningEffort: (level) => { currentReasoningEffort = level; },
533
+ activeWorkFrame: options?.activeWorkFrame,
534
+ }
535
+ : undefined;
345
536
  // Rebase provider-owned turn state from canonical messages at user-turn start.
346
537
  // This prevents stale provider caches from replaying prior-turn context.
347
538
  providerRuntime.resetTurnState(messages);
348
539
  while (!done) {
349
- // When toolChoiceRequired is true (the default), include final_answer
350
- // so the model can signal completion. With tool_choice: required, the
351
- // model must call a tool every turn — final_answer is how it exits.
352
- // Overridable via options.toolChoiceRequired = false (e.g. CLI).
353
- const activeTools = toolChoiceRequired ? [...baseTools, tools_1.finalAnswerTool] : baseTools;
540
+ // Channel-based tool filtering:
541
+ // - Inner dialog: exclude send_message (delivery via surface), observe (no one to observe)
542
+ // - 1:1 sessions: exclude observe (can't ignore someone talking directly to you)
543
+ // - Group chats: observe available
544
+ //
545
+ // ponder, settle/rest, surface, and observe are always assembled based on channel context.
546
+ // ponder is available in ALL channels (outer: think privately, inner: keep turning).
547
+ // Inner dialog gets restTool instead of settleTool (rest = end turn, gated by attention queue).
548
+ // toolChoiceRequired only controls whether tool_choice: "required" is set in the API call.
549
+ const isInnerDialog = channel === "inner";
550
+ const filteredBaseTools = isInnerDialog
551
+ ? baseTools.filter((t) => t.function.name !== "send_message")
552
+ : baseTools;
553
+ const activeTools = [
554
+ ...filteredBaseTools,
555
+ tools_1.ponderTool,
556
+ ...(isInnerDialog ? [surface_tool_1.surfaceToolDef, tools_1.restTool] : []),
557
+ ...((currentContext?.isGroupChat || options?.isReactionSignal) && !isInnerDialog ? [tools_1.observeTool] : []),
558
+ ...(!isInnerDialog ? [tools_1.settleTool] : []),
559
+ ];
354
560
  const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
355
561
  if (steeringFollowUps.length > 0) {
562
+ const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
563
+ if (hasSupersedingFollowUp) {
564
+ mustResolveBeforeHandoffActive = false;
565
+ options?.setMustResolveBeforeHandoff?.(false);
566
+ outcome = "superseded";
567
+ break;
568
+ }
569
+ if (steeringFollowUps.some((followUp) => followUp.effect === "set_no_handoff")) {
570
+ mustResolveBeforeHandoffActive = true;
571
+ options?.setMustResolveBeforeHandoff?.(true);
572
+ }
573
+ sawSteeringFollowUp = true;
356
574
  for (const followUp of steeringFollowUps) {
357
575
  messages.push({ role: "user", content: followUp.text });
358
576
  }
@@ -360,8 +578,10 @@ async function runAgent(messages, callbacks, channel, signal, options) {
360
578
  }
361
579
  // Yield so pending I/O (stdin Ctrl-C) can be processed between iterations
362
580
  await new Promise((r) => setImmediate(r));
363
- if (signal?.aborted)
581
+ if (signal?.aborted) {
582
+ outcome = "aborted";
364
583
  break;
584
+ }
365
585
  try {
366
586
  callbacks.onModelStart();
367
587
  const result = await providerRuntime.streamTurn({
@@ -371,6 +591,8 @@ async function runAgent(messages, callbacks, channel, signal, options) {
371
591
  signal,
372
592
  traceId,
373
593
  toolChoiceRequired,
594
+ reasoningEffort: currentReasoningEffort,
595
+ eagerSettleStreaming: true,
374
596
  });
375
597
  // Track usage from the latest API call
376
598
  if (result.usage)
@@ -394,52 +616,76 @@ async function runAgent(messages, callbacks, channel, signal, options) {
394
616
  if (reasoningItems.length > 0) {
395
617
  msg._reasoning_items = reasoningItems;
396
618
  }
619
+ // Store thinking blocks (Anthropic) on the assistant message for round-tripping
620
+ const thinkingItems = result.outputItems.filter((item) => "type" in item && (item.type === "thinking" || item.type === "redacted_thinking"));
621
+ if (thinkingItems.length > 0) {
622
+ msg._thinking_blocks = thinkingItems;
623
+ }
624
+ // Phase annotation for Codex provider
625
+ const hasPhaseAnnotation = providerRuntime.capabilities.has("phase-annotation");
626
+ const isSoleSettle = result.toolCalls.length === 1 && result.toolCalls[0].name === "settle";
627
+ if (hasPhaseAnnotation) {
628
+ msg.phase = isSoleSettle ? "settle" : "commentary";
629
+ }
397
630
  if (!result.toolCalls.length) {
398
- // Kick detection is disabled while tool_choice: required + final_answer
399
- // is the primary loop control mechanism. The model should never reach
400
- // this path (tool_choice: required forces a tool call), but if it does,
401
- // accept the response as-is rather than risk false-positive kicks.
402
- //
403
- // Preserved for future use — re-enable by uncommenting:
404
- // const kick = detectKick(result.content, options);
405
- // if (kick) {
406
- // kickCount++;
407
- // lastKickReason = kick.reason;
408
- // callbacks.onKick?.();
409
- // const kickContent = result.content
410
- // ? result.content + "\n\n" + kick.message
411
- // : kick.message;
412
- // messages.push({ role: "assistant", content: kickContent });
413
- // providerRuntime.resetTurnState(messages);
414
- // continue;
415
- // }
631
+ // No tool calls — accept response as-is.
632
+ // (Kick detection disabled; tool_choice: required + settle
633
+ // is the primary loop control. See src/heart/kicks.ts to re-enable.)
416
634
  messages.push(msg);
417
635
  done = true;
418
636
  }
419
637
  else {
420
- // Check for final_answer sole call: intercept before tool execution
421
- const isSoleFinalAnswer = result.toolCalls.length === 1 && result.toolCalls[0].name === "final_answer";
422
- if (isSoleFinalAnswer) {
423
- // Extract answer from the tool call arguments.
424
- // Supports: {"answer":"text"}, "text" (JSON string), retry on failure.
425
- let answer;
426
- try {
427
- const parsed = JSON.parse(result.toolCalls[0].arguments);
428
- if (typeof parsed === "string") {
429
- answer = parsed;
430
- }
431
- else if (parsed.answer != null) {
432
- answer = parsed.answer;
433
- }
434
- // else: valid JSON but no answer field — answer stays undefined (retry)
638
+ // Check for settle sole call: intercept before tool execution
639
+ if (isSoleSettle) {
640
+ /* v8 ignore next -- defensive: JSON.parse catch for malformed settle args @preserve */
641
+ const settleArgs = (() => { try {
642
+ return JSON.parse(result.toolCalls[0].arguments);
435
643
  }
436
644
  catch {
437
- // JSON parsing failed (e.g. truncated output) — answer stays undefined (retry)
645
+ return {};
646
+ } })();
647
+ callbacks.onToolStart("settle", settleArgs);
648
+ // Inner dialog attention queue gate: reject settle if items remain
649
+ const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
650
+ if (isInnerDialog && attentionQueue && attentionQueue.length > 0) {
651
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
652
+ callbacks.onClearText?.();
653
+ messages.push(msg);
654
+ const gateMessage = "you're holding thoughts someone is waiting for — surface them before you settle.";
655
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
656
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
657
+ continue;
438
658
  }
439
- if (answer != null) {
440
- if (result.finalAnswerStreamed) {
659
+ // Extract answer from the tool call arguments.
660
+ // Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
661
+ const { answer, intent } = parseSettlePayload(result.toolCalls[0].arguments);
662
+ // Inner dialog settle: no CompletionMetadata, "(settled)" ack
663
+ if (isInnerDialog) {
664
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
665
+ messages.push(msg);
666
+ const settled = "(settled)";
667
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: settled });
668
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, settled);
669
+ outcome = "settled";
670
+ done = true;
671
+ continue;
672
+ }
673
+ const retryError = getSettleRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp, options?.delegationDecision, sawSendMessageSelf, sawPonder, sawQuerySession, options?.currentObligation ?? null, options?.activeWorkFrame?.inner?.job, sawExternalStateQuery);
674
+ const deliveredAnswer = answer;
675
+ const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
676
+ const validTerminalIntent = intent === "complete" || intent === "blocked";
677
+ const validClosure = deliveredAnswer != null
678
+ && !retryError
679
+ && (!mustResolveBeforeHandoffActive || validDirectReply || validTerminalIntent);
680
+ if (validClosure) {
681
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
682
+ completion = {
683
+ answer: deliveredAnswer,
684
+ intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
685
+ };
686
+ if (result.settleStreamed) {
441
687
  // The streaming layer already parsed and emitted the answer
442
- // progressively via FinalAnswerParser. Skip clearing and
688
+ // progressively via SettleParser. Skip clearing and
443
689
  // re-emitting to avoid double-delivery.
444
690
  }
445
691
  else {
@@ -447,37 +693,229 @@ async function runAgent(messages, callbacks, channel, signal, options) {
447
693
  callbacks.onClearText?.();
448
694
  // Emit the answer through the callback pipeline so channels receive it.
449
695
  // Never truncate -- channel adapters handle splitting long messages.
450
- callbacks.onTextChunk(answer);
696
+ callbacks.onTextChunk(deliveredAnswer);
451
697
  }
452
- // Keep the full assistant message (with tool_calls) for debuggability,
453
- // plus a synthetic tool response so the conversation stays valid on resume.
454
698
  messages.push(msg);
455
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: "(delivered)" });
456
- providerRuntime.appendToolOutput(result.toolCalls[0].id, "(delivered)");
457
- done = true;
699
+ if (validDirectReply) {
700
+ const resumeWork = "direct reply delivered. resume the unresolved obligation now and keep working until you can finish or clearly report that you are blocked.";
701
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: resumeWork });
702
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, resumeWork);
703
+ }
704
+ else {
705
+ const delivered = "(delivered)";
706
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
707
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
708
+ outcome = intent === "blocked" ? "blocked" : "settled";
709
+ done = true;
710
+ }
458
711
  }
459
712
  else {
460
- // Answer is undefined -- the model's final_answer was incomplete or
713
+ // Answer is undefined -- the model's settle was incomplete or
461
714
  // malformed. Clear any partial streamed text or noise, then push the
462
715
  // assistant msg + error tool result and let the model try again.
716
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
717
+ callbacks.onClearText?.();
718
+ messages.push(msg);
719
+ const toolRetryMessage = retryError
720
+ ?? "your settle was incomplete or malformed. call settle again with your complete response.";
721
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: toolRetryMessage });
722
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, toolRetryMessage);
723
+ }
724
+ continue;
725
+ }
726
+ // Check for observe sole call: intercept before tool execution
727
+ const isSoleObserve = result.toolCalls.length === 1 && result.toolCalls[0].name === "observe";
728
+ if (isSoleObserve) {
729
+ /* v8 ignore next -- defensive: JSON.parse catch for malformed observe args @preserve */
730
+ const observeArgs = (() => { try {
731
+ return JSON.parse(result.toolCalls[0].arguments);
732
+ }
733
+ catch {
734
+ return {};
735
+ } })();
736
+ let reason;
737
+ if (typeof observeArgs?.reason === "string")
738
+ reason = observeArgs.reason;
739
+ callbacks.onToolStart("observe", observeArgs);
740
+ (0, runtime_1.emitNervesEvent)({
741
+ component: "engine",
742
+ event: "engine.observe",
743
+ message: "agent observed without responding",
744
+ meta: { ...(reason ? { reason } : {}) },
745
+ });
746
+ callbacks.onToolEnd("observe", (0, tools_1.summarizeArgs)("observe", observeArgs), true);
747
+ messages.push(msg);
748
+ const silenced = "(silenced)";
749
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: silenced });
750
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, silenced);
751
+ outcome = "observed";
752
+ done = true;
753
+ continue;
754
+ }
755
+ // Check for ponder sole call: intercept before tool execution
756
+ const isSolePonder = result.toolCalls.length === 1 && result.toolCalls[0].name === "ponder";
757
+ if (isSolePonder) {
758
+ let parsedArgs = {};
759
+ try {
760
+ parsedArgs = JSON.parse(result.toolCalls[0].arguments);
761
+ }
762
+ catch { /* ignore */ }
763
+ callbacks.onToolStart("ponder", parsedArgs);
764
+ const currentSession = options?.toolContext?.currentSession;
765
+ const isInnerChannel = currentSession?.friendId === "self" && currentSession?.channel === "inner";
766
+ if (!isInnerChannel) {
767
+ // Outer session: thought and say are required
768
+ const thought = typeof parsedArgs.thought === "string" ? parsedArgs.thought : undefined;
769
+ const say = typeof parsedArgs.say === "string" ? parsedArgs.say : undefined;
770
+ if (!thought || !say) {
771
+ callbacks.onToolEnd("ponder", (0, tools_1.summarizeArgs)("ponder", parsedArgs), false);
772
+ messages.push(msg);
773
+ const errorMsg = "ponder requires both thought and say when called from a conversation. thought is what needs more thinking; say is what you tell them before going quiet.";
774
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: errorMsg });
775
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, errorMsg);
776
+ continue;
777
+ }
778
+ // Emit outward say text
463
779
  callbacks.onClearText?.();
464
- const retryError = "your final_answer was incomplete or malformed. call final_answer again with your complete response.";
780
+ callbacks.onTextChunk(say);
781
+ // Build handoff packet and enqueue
782
+ const handoffContent = buildPonderHandoffPacket({
783
+ topic: thought,
784
+ mode: "reflect",
785
+ delegationDecision: options?.delegationDecision,
786
+ currentSession: currentSession ?? null,
787
+ currentObligation: options?.currentObligation ?? null,
788
+ outwardClosureRequired: options?.delegationDecision?.outwardClosureRequired ?? false,
789
+ });
790
+ const pendingDir = (0, pending_1.getInnerDialogPendingDir)((0, identity_2.getAgentName)());
791
+ // Create obligation FIRST so we can attach its ID to the pending message
792
+ let createdObligationId;
793
+ if (currentSession) {
794
+ try {
795
+ const obligation = (0, obligations_1.createObligation)((0, identity_2.getAgentRoot)(), {
796
+ origin: {
797
+ friendId: currentSession.friendId,
798
+ channel: currentSession.channel,
799
+ key: currentSession.key,
800
+ },
801
+ content: thought,
802
+ });
803
+ createdObligationId = obligation.id;
804
+ }
805
+ catch {
806
+ /* v8 ignore next -- defensive: obligation store write failure should not break ponder @preserve */
807
+ }
808
+ }
809
+ const envelope = {
810
+ from: (0, identity_2.getAgentName)(),
811
+ friendId: "self",
812
+ channel: "inner",
813
+ key: "dialog",
814
+ content: handoffContent,
815
+ timestamp: Date.now(),
816
+ ...(currentSession ? {
817
+ delegatedFrom: {
818
+ friendId: currentSession.friendId,
819
+ channel: currentSession.channel,
820
+ key: currentSession.key,
821
+ },
822
+ obligationStatus: "pending",
823
+ /* v8 ignore next -- defensive: createdObligationId is undefined only when obligation store write fails @preserve */
824
+ ...(createdObligationId ? { obligationId: createdObligationId } : {}),
825
+ } : {}),
826
+ };
827
+ (0, pending_1.queuePendingMessage)(pendingDir, envelope);
828
+ try {
829
+ await (0, socket_client_1.requestInnerWake)((0, identity_2.getAgentName)());
830
+ }
831
+ catch { /* daemon may not be running */ }
832
+ callbacks.onToolEnd("ponder", (0, tools_1.summarizeArgs)("ponder", parsedArgs), true);
833
+ sawPonder = true;
465
834
  messages.push(msg);
466
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: retryError });
467
- providerRuntime.appendToolOutput(result.toolCalls[0].id, retryError);
835
+ const ack = "(pondering)";
836
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
837
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
838
+ (0, runtime_1.emitNervesEvent)({
839
+ component: "engine",
840
+ event: "engine.pondered",
841
+ message: "pondering",
842
+ meta: { hasThought: true, hasSay: true, contentSnippet: thought.slice(0, 80) },
843
+ });
844
+ }
845
+ else {
846
+ // Inner dialog: parameterless, enqueue synthetic pending WITHOUT delegatedFrom
847
+ const pendingDir = (0, pending_1.getInnerDialogPendingDir)((0, identity_2.getAgentName)());
848
+ const envelope = {
849
+ from: (0, identity_2.getAgentName)(),
850
+ friendId: "self",
851
+ channel: "inner",
852
+ key: "dialog",
853
+ content: "continuing to think...",
854
+ timestamp: Date.now(),
855
+ };
856
+ (0, pending_1.queuePendingMessage)(pendingDir, envelope);
857
+ callbacks.onToolEnd("ponder", (0, tools_1.summarizeArgs)("ponder", parsedArgs), true);
858
+ sawPonder = true;
859
+ messages.push(msg);
860
+ const ack = "(pondering)";
861
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
862
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
863
+ (0, runtime_1.emitNervesEvent)({
864
+ component: "engine",
865
+ event: "engine.pondered",
866
+ message: "pondering from inner dialog",
867
+ meta: { inner: true },
868
+ });
869
+ }
870
+ outcome = "pondered";
871
+ done = true;
872
+ continue;
873
+ }
874
+ // Check for rest sole call: intercept before tool execution
875
+ const isSoleRest = result.toolCalls.length === 1 && result.toolCalls[0].name === "rest";
876
+ if (isSoleRest) {
877
+ const restArgs = (() => { try {
878
+ return JSON.parse(result.toolCalls[0].arguments);
879
+ }
880
+ catch {
881
+ return {};
882
+ } })();
883
+ callbacks.onToolStart("rest", restArgs);
884
+ // Attention queue gate: reject rest if items remain
885
+ const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
886
+ if (attentionQueue && attentionQueue.length > 0) {
887
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), false);
888
+ messages.push(msg);
889
+ const gateMessage = "you're holding thoughts someone is waiting for — surface them before you rest.";
890
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
891
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
892
+ continue;
468
893
  }
894
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), true);
895
+ messages.push(msg);
896
+ const ack = "(resting)";
897
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
898
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
899
+ (0, runtime_1.emitNervesEvent)({
900
+ component: "engine",
901
+ event: "engine.rested",
902
+ message: "resting until next heartbeat",
903
+ meta: {},
904
+ });
905
+ outcome = "rested";
906
+ done = true;
469
907
  continue;
470
908
  }
471
909
  messages.push(msg);
472
- // SHARED: execute tools (final_answer in mixed calls is rejected inline)
910
+ // Execute tools (sole-call tools in mixed calls are rejected inline)
473
911
  for (const tc of result.toolCalls) {
474
912
  if (signal?.aborted)
475
913
  break;
476
- // Intercept final_answer in mixed call: reject it
477
- if (tc.name === "final_answer") {
478
- const rejection = "rejected: final_answer must be the only tool call. Finish your work first, then call final_answer alone.";
479
- messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
480
- providerRuntime.appendToolOutput(tc.id, rejection);
914
+ // Reject sole-call tools when mixed with other tool calls
915
+ const soleCallRejection = SOLE_CALL_REJECTION[tc.name];
916
+ if (soleCallRejection) {
917
+ messages.push({ role: "tool", tool_call_id: tc.id, content: soleCallRejection });
918
+ providerRuntime.appendToolOutput(tc.id, soleCallRejection);
481
919
  continue;
482
920
  }
483
921
  let args = {};
@@ -487,7 +925,28 @@ async function runAgent(messages, callbacks, channel, signal, options) {
487
925
  catch {
488
926
  /* ignore */
489
927
  }
928
+ if (tc.name === "send_message" && args.friendId === "self") {
929
+ sawSendMessageSelf = true;
930
+ }
931
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
932
+ if (tc.name === "query_session")
933
+ sawQuerySession = true;
934
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
935
+ if (tc.name === "bridge_manage")
936
+ sawBridgeManage = true;
937
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
938
+ if (isExternalStateQuery(tc.name, args))
939
+ sawExternalStateQuery = true;
490
940
  const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
941
+ const toolLoop = (0, tool_loop_1.detectToolLoop)(toolLoopState, tc.name, args);
942
+ if (toolLoop.stuck) {
943
+ const rejection = `loop guard: ${toolLoop.message}`;
944
+ callbacks.onToolStart(tc.name, args);
945
+ callbacks.onToolEnd(tc.name, argSummary, false);
946
+ messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
947
+ providerRuntime.appendToolOutput(tc.id, rejection);
948
+ continue;
949
+ }
491
950
  // Confirmation check for mutate tools
492
951
  if ((0, tools_1.isConfirmationRequired)(tc.name) && !options?.skipConfirmation) {
493
952
  let decision = "denied";
@@ -508,13 +967,14 @@ async function runAgent(messages, callbacks, channel, signal, options) {
508
967
  let success;
509
968
  try {
510
969
  const execToolFn = options?.execTool ?? tools_1.execTool;
511
- toolResult = await execToolFn(tc.name, args, options?.toolContext);
970
+ toolResult = await execToolFn(tc.name, args, augmentedToolContext ?? options?.toolContext);
512
971
  success = true;
513
972
  }
514
973
  catch (e) {
515
974
  toolResult = `error: ${e}`;
516
975
  success = false;
517
976
  }
977
+ (0, tool_loop_1.recordToolOutcome)(toolLoopState, tc.name, args, toolResult, success);
518
978
  callbacks.onToolEnd(tc.name, argSummary, success);
519
979
  messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
520
980
  providerRuntime.appendToolOutput(tc.id, toolResult);
@@ -525,6 +985,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
525
985
  // Abort is not an error — just stop cleanly
526
986
  if (signal?.aborted) {
527
987
  stripLastToolCalls(messages);
988
+ outcome = "aborted";
528
989
  break;
529
990
  }
530
991
  // Context overflow: trim aggressively and retry once
@@ -542,7 +1003,16 @@ async function runAgent(messages, callbacks, channel, signal, options) {
542
1003
  if (isTransientError(e) && retryCount < MAX_RETRIES) {
543
1004
  retryCount++;
544
1005
  const delay = RETRY_BASE_MS * Math.pow(2, retryCount - 1);
545
- const cause = classifyTransientError(e);
1006
+ let classification;
1007
+ try {
1008
+ classification = providerRuntime.classifyError(e instanceof Error ? e : /* v8 ignore next -- defensive: errors are always Error instances @preserve */ new Error(String(e)));
1009
+ }
1010
+ catch {
1011
+ /* v8 ignore next -- defensive: classifyError should not throw @preserve */
1012
+ classification = classifyTransientError(e);
1013
+ }
1014
+ /* v8 ignore next -- defensive: all classifications have labels @preserve */
1015
+ const cause = TRANSIENT_RETRY_LABELS[classification] ?? classification;
546
1016
  callbacks.onError(new Error(`${cause}, retrying in ${delay / 1000}s (${retryCount}/${MAX_RETRIES})...`), "transient");
547
1017
  // Wait with abort support
548
1018
  const aborted = await new Promise((resolve) => {
@@ -559,21 +1029,31 @@ async function runAgent(messages, callbacks, channel, signal, options) {
559
1029
  });
560
1030
  if (aborted) {
561
1031
  stripLastToolCalls(messages);
1032
+ outcome = "aborted";
562
1033
  break;
563
1034
  }
564
1035
  providerRuntime.resetTurnState(messages);
565
1036
  continue;
566
1037
  }
567
- callbacks.onError(e instanceof Error ? e : new Error(String(e)), "terminal");
1038
+ terminalError = e instanceof Error ? e : new Error(String(e));
1039
+ try {
1040
+ terminalErrorClassification = providerRuntime.classifyError(terminalError);
1041
+ }
1042
+ catch {
1043
+ /* v8 ignore next -- defensive: classifyError should not throw @preserve */
1044
+ terminalErrorClassification = "unknown";
1045
+ }
1046
+ callbacks.onError(terminalError, "terminal");
568
1047
  (0, runtime_1.emitNervesEvent)({
569
1048
  level: "error",
570
1049
  event: "engine.error",
571
1050
  trace_id: traceId,
572
1051
  component: "engine",
573
- message: e instanceof Error ? e.message : String(e),
574
- meta: {},
1052
+ message: terminalError.message,
1053
+ meta: { errorClassification: terminalErrorClassification },
575
1054
  });
576
1055
  stripLastToolCalls(messages);
1056
+ outcome = "errored";
577
1057
  done = true;
578
1058
  }
579
1059
  }
@@ -582,7 +1062,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
582
1062
  trace_id: traceId,
583
1063
  component: "engine",
584
1064
  message: "runAgent turn completed",
585
- meta: { done },
1065
+ meta: { done, sawPonder, sawQuerySession, sawBridgeManage },
586
1066
  });
587
- return { usage: lastUsage };
1067
+ return {
1068
+ usage: lastUsage,
1069
+ outcome,
1070
+ completion,
1071
+ ...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
1072
+ };
588
1073
  }