@ouro.bot/cli 0.1.0-alpha.10 → 0.1.0-alpha.100

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