@ouro.bot/cli 0.1.0-alpha.14 → 0.1.0-alpha.140
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.
- package/AdoptionSpecialist.ouro/psyche/SOUL.md +2 -2
- package/AdoptionSpecialist.ouro/psyche/identities/monty.md +2 -2
- package/README.md +151 -205
- package/changelog.json +902 -0
- package/dist/heart/active-work.js +633 -0
- package/dist/heart/bridges/manager.js +358 -0
- package/dist/heart/bridges/state-machine.js +135 -0
- package/dist/heart/bridges/store.js +123 -0
- package/dist/heart/commitments.js +105 -0
- package/dist/heart/config.js +66 -21
- package/dist/heart/core.js +579 -112
- package/dist/heart/cross-chat-delivery.js +146 -0
- package/dist/heart/daemon/agent-discovery.js +81 -0
- package/dist/heart/daemon/agent-service.js +467 -0
- package/dist/heart/daemon/auth-flow.js +457 -0
- package/dist/heart/daemon/daemon-cli.js +1840 -196
- package/dist/heart/daemon/daemon-entry.js +80 -3
- package/dist/heart/daemon/daemon-runtime-sync.js +212 -0
- package/dist/heart/daemon/daemon.js +301 -1
- package/dist/heart/daemon/hatch-animation.js +10 -3
- package/dist/heart/daemon/hatch-flow.js +15 -80
- package/dist/heart/daemon/heartbeat-timer.js +131 -0
- package/dist/heart/daemon/hooks/bundle-meta.js +92 -0
- package/dist/heart/daemon/launchd.js +159 -0
- package/dist/heart/daemon/log-tailer.js +4 -3
- package/dist/heart/daemon/mcp-server.js +464 -0
- package/dist/heart/daemon/message-router.js +17 -8
- package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
- package/dist/heart/daemon/ouro-path-installer.js +67 -34
- package/dist/heart/daemon/ouro-version-manager.js +171 -0
- package/dist/heart/daemon/process-manager.js +13 -0
- package/dist/heart/daemon/run-hooks.js +37 -0
- package/dist/heart/daemon/runtime-logging.js +58 -15
- package/dist/heart/daemon/runtime-metadata.js +219 -0
- package/dist/heart/daemon/runtime-mode.js +67 -0
- package/dist/heart/daemon/sense-manager.js +50 -2
- package/dist/heart/daemon/skill-management-installer.js +94 -0
- package/dist/heart/daemon/socket-client.js +202 -0
- package/dist/heart/daemon/specialist-orchestrator.js +2 -2
- package/dist/heart/daemon/specialist-prompt.js +10 -7
- package/dist/heart/daemon/specialist-tools.js +52 -3
- package/dist/heart/daemon/staged-restart.js +114 -0
- package/dist/heart/daemon/thoughts.js +507 -0
- package/dist/heart/daemon/update-checker.js +111 -0
- package/dist/heart/daemon/update-hooks.js +138 -0
- package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
- package/dist/heart/delegation.js +62 -0
- package/dist/heart/identity.js +64 -21
- package/dist/heart/kicks.js +2 -20
- package/dist/heart/model-capabilities.js +48 -0
- package/dist/heart/obligations.js +197 -0
- package/dist/heart/progress-story.js +42 -0
- package/dist/heart/provider-failover.js +88 -0
- package/dist/heart/provider-ping.js +159 -0
- package/dist/heart/providers/anthropic-token.js +163 -0
- package/dist/heart/providers/anthropic.js +195 -34
- package/dist/heart/providers/azure.js +115 -9
- package/dist/heart/providers/github-copilot.js +157 -0
- package/dist/heart/providers/minimax.js +33 -3
- package/dist/heart/providers/openai-codex.js +49 -14
- package/dist/heart/session-activity.js +173 -0
- package/dist/heart/session-recall.js +216 -0
- package/dist/heart/streaming.js +117 -33
- package/dist/heart/target-resolution.js +123 -0
- package/dist/heart/tool-loop.js +198 -0
- package/dist/heart/turn-coordinator.js +28 -0
- package/dist/mind/associative-recall.js +122 -32
- package/dist/mind/bundle-manifest.js +14 -0
- package/dist/mind/context.js +124 -14
- package/dist/mind/{memory.js → diary.js} +70 -56
- package/dist/mind/first-impressions.js +16 -2
- package/dist/mind/friends/channel.js +35 -0
- package/dist/mind/friends/group-context.js +144 -0
- package/dist/mind/friends/store-file.js +19 -0
- package/dist/mind/friends/trust-explanation.js +74 -0
- package/dist/mind/friends/types.js +8 -0
- package/dist/mind/journal-index.js +161 -0
- package/dist/mind/obligation-steering.js +221 -0
- package/dist/mind/obligations.js +134 -0
- package/dist/mind/pending.js +76 -9
- package/dist/mind/phrases.js +1 -0
- package/dist/mind/prompt.js +554 -88
- package/dist/mind/token-estimate.js +8 -12
- package/dist/nerves/cli-logging.js +15 -2
- package/dist/nerves/coverage/run-artifacts.js +1 -1
- package/dist/nerves/index.js +12 -0
- package/dist/nerves/runtime.js +5 -1
- package/dist/repertoire/ado-client.js +4 -2
- package/dist/repertoire/ado-semantic.js +6 -0
- package/dist/repertoire/coding/codex-jsonl.js +64 -0
- package/dist/repertoire/coding/context-pack.js +254 -0
- package/dist/repertoire/coding/feedback.js +301 -0
- package/dist/repertoire/coding/index.js +4 -1
- package/dist/repertoire/coding/manager.js +210 -4
- package/dist/repertoire/coding/spawner.js +59 -12
- package/dist/repertoire/coding/tools.js +176 -4
- package/dist/repertoire/data/ado-endpoints.json +188 -0
- package/dist/repertoire/guardrails.js +290 -0
- package/dist/repertoire/mcp-client.js +254 -0
- package/dist/repertoire/mcp-manager.js +198 -0
- package/dist/repertoire/skills.js +14 -23
- package/dist/repertoire/tasks/board.js +12 -0
- package/dist/repertoire/tasks/index.js +23 -9
- package/dist/repertoire/tasks/transitions.js +1 -2
- package/dist/repertoire/tools-base.js +975 -271
- package/dist/repertoire/tools-bluebubbles.js +94 -0
- package/dist/repertoire/tools-github.js +1 -6
- package/dist/repertoire/tools-teams.js +65 -59
- package/dist/repertoire/tools.js +265 -91
- package/dist/senses/attention-queue.js +97 -0
- package/dist/senses/bluebubbles-client.js +210 -5
- package/dist/senses/bluebubbles-entry.js +2 -0
- package/dist/senses/bluebubbles-inbound-log.js +109 -0
- package/dist/senses/bluebubbles-media.js +339 -0
- package/dist/senses/bluebubbles-model.js +12 -4
- package/dist/senses/bluebubbles-mutation-log.js +45 -5
- package/dist/senses/bluebubbles-runtime-state.js +109 -0
- package/dist/senses/bluebubbles-session-cleanup.js +72 -0
- package/dist/senses/bluebubbles.js +944 -45
- package/dist/senses/cli-entry.js +1 -1
- package/dist/senses/cli-layout.js +187 -0
- package/dist/senses/cli.js +374 -131
- package/dist/senses/contextual-heartbeat.js +102 -0
- package/dist/senses/continuity.js +94 -0
- package/dist/senses/debug-activity.js +154 -0
- package/dist/senses/inner-dialog-worker.js +47 -18
- package/dist/senses/inner-dialog.js +500 -84
- package/dist/senses/pipeline.js +454 -0
- package/dist/senses/surface-tool.js +82 -0
- package/dist/senses/teams.js +607 -129
- package/dist/senses/trust-gate.js +112 -2
- package/package.json +12 -4
- package/skills/configure-dev-tools.md +109 -0
- package/subagents/README.md +4 -70
- package/dist/heart/daemon/subagent-installer.js +0 -134
- package/subagents/work-doer.md +0 -233
- package/subagents/work-merger.md +0 -624
- package/subagents/work-planner.md +0 -373
package/dist/heart/core.js
CHANGED
|
@@ -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.getSettleRetryError = getSettleRetryError;
|
|
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,7 @@ 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
|
-
|
|
19
|
-
// import { detectKick } from "./kicks";
|
|
20
|
-
// import type { KickReason } from "./kicks";
|
|
21
|
+
const surface_tool_1 = require("../senses/surface-tool");
|
|
21
22
|
const runtime_1 = require("../nerves/runtime");
|
|
22
23
|
const context_1 = require("../mind/context");
|
|
23
24
|
const prompt_1 = require("../mind/prompt");
|
|
@@ -26,13 +27,48 @@ const anthropic_1 = require("./providers/anthropic");
|
|
|
26
27
|
const azure_1 = require("./providers/azure");
|
|
27
28
|
const minimax_1 = require("./providers/minimax");
|
|
28
29
|
const openai_codex_1 = require("./providers/openai-codex");
|
|
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");
|
|
29
36
|
let _providerRuntime = null;
|
|
37
|
+
function getProviderRuntimeFingerprint() {
|
|
38
|
+
const provider = (0, identity_1.loadAgentConfig)().provider;
|
|
39
|
+
/* v8 ignore next -- switch: not all provider branches exercised in CI @preserve */
|
|
40
|
+
switch (provider) {
|
|
41
|
+
case "azure": {
|
|
42
|
+
const { apiKey, endpoint, deployment, modelName, apiVersion, managedIdentityClientId } = (0, config_1.getAzureConfig)();
|
|
43
|
+
return JSON.stringify({ provider, apiKey, endpoint, deployment, modelName, apiVersion, managedIdentityClientId });
|
|
44
|
+
}
|
|
45
|
+
case "anthropic": {
|
|
46
|
+
const { model, setupToken } = (0, config_1.getAnthropicConfig)();
|
|
47
|
+
return JSON.stringify({ provider, model, setupToken });
|
|
48
|
+
}
|
|
49
|
+
case "minimax": {
|
|
50
|
+
const { apiKey, model } = (0, config_1.getMinimaxConfig)();
|
|
51
|
+
return JSON.stringify({ provider, apiKey, model });
|
|
52
|
+
}
|
|
53
|
+
case "openai-codex": {
|
|
54
|
+
const { model, oauthAccessToken } = (0, config_1.getOpenAICodexConfig)();
|
|
55
|
+
return JSON.stringify({ provider, model, oauthAccessToken });
|
|
56
|
+
}
|
|
57
|
+
/* v8 ignore start -- fingerprint: tested via provider init tests @preserve */
|
|
58
|
+
case "github-copilot": {
|
|
59
|
+
const { model, githubToken, baseUrl } = (0, config_1.getGithubCopilotConfig)();
|
|
60
|
+
return JSON.stringify({ provider, model, githubToken, baseUrl });
|
|
61
|
+
}
|
|
62
|
+
/* v8 ignore stop */
|
|
63
|
+
}
|
|
64
|
+
}
|
|
30
65
|
function createProviderRegistry() {
|
|
31
66
|
const factories = {
|
|
32
67
|
azure: azure_1.createAzureProviderRuntime,
|
|
33
68
|
anthropic: anthropic_1.createAnthropicProviderRuntime,
|
|
34
69
|
minimax: minimax_1.createMinimaxProviderRuntime,
|
|
35
70
|
"openai-codex": openai_codex_1.createOpenAICodexProviderRuntime,
|
|
71
|
+
"github-copilot": github_copilot_1.createGithubCopilotProviderRuntime,
|
|
36
72
|
};
|
|
37
73
|
return {
|
|
38
74
|
resolve() {
|
|
@@ -42,42 +78,44 @@ function createProviderRegistry() {
|
|
|
42
78
|
};
|
|
43
79
|
}
|
|
44
80
|
function getProviderRuntime() {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
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");
|
|
81
|
+
try {
|
|
82
|
+
const fingerprint = getProviderRuntimeFingerprint();
|
|
83
|
+
if (!_providerRuntime || _providerRuntime.fingerprint !== fingerprint) {
|
|
84
|
+
const runtime = createProviderRegistry().resolve();
|
|
85
|
+
_providerRuntime = runtime ? { fingerprint, runtime } : null;
|
|
73
86
|
}
|
|
74
87
|
}
|
|
75
|
-
|
|
88
|
+
catch (error) {
|
|
89
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
90
|
+
(0, runtime_1.emitNervesEvent)({
|
|
91
|
+
level: "error",
|
|
92
|
+
event: "engine.provider_init_error",
|
|
93
|
+
component: "engine",
|
|
94
|
+
message: msg,
|
|
95
|
+
meta: {},
|
|
96
|
+
});
|
|
97
|
+
// eslint-disable-next-line no-console -- pre-boot guard: provider init failure
|
|
98
|
+
console.error(`\n[fatal] ${msg}\n`);
|
|
99
|
+
process.exit(1);
|
|
100
|
+
throw new Error("unreachable");
|
|
101
|
+
}
|
|
102
|
+
if (!_providerRuntime) {
|
|
103
|
+
(0, runtime_1.emitNervesEvent)({
|
|
104
|
+
level: "error",
|
|
105
|
+
event: "engine.provider_init_error",
|
|
106
|
+
component: "engine",
|
|
107
|
+
message: "provider runtime could not be initialized.",
|
|
108
|
+
meta: {},
|
|
109
|
+
});
|
|
110
|
+
process.exit(1);
|
|
111
|
+
throw new Error("unreachable");
|
|
112
|
+
}
|
|
113
|
+
return _providerRuntime.runtime;
|
|
76
114
|
}
|
|
77
115
|
/**
|
|
78
|
-
* Clear the cached provider runtime so the next
|
|
79
|
-
*
|
|
80
|
-
*
|
|
116
|
+
* Clear the cached provider runtime so the next access re-creates it from
|
|
117
|
+
* current config. Runtime access also auto-refreshes when the selected
|
|
118
|
+
* provider fingerprint changes on disk.
|
|
81
119
|
*/
|
|
82
120
|
function resetProviderRuntime() {
|
|
83
121
|
_providerRuntime = null;
|
|
@@ -104,14 +142,19 @@ function createSummarize() {
|
|
|
104
142
|
};
|
|
105
143
|
}
|
|
106
144
|
function getProviderDisplayLabel() {
|
|
107
|
-
const
|
|
145
|
+
const provider = (0, identity_1.loadAgentConfig)().provider;
|
|
108
146
|
const providerLabelBuilders = {
|
|
109
|
-
azure: () =>
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
147
|
+
azure: () => {
|
|
148
|
+
const config = (0, config_1.getAzureConfig)();
|
|
149
|
+
return `azure openai (${config.deployment || "default"}, model: ${config.modelName || "unknown"})`;
|
|
150
|
+
},
|
|
151
|
+
anthropic: () => `anthropic (${(0, config_1.getAnthropicConfig)().model || "unknown"})`,
|
|
152
|
+
minimax: () => `minimax (${(0, config_1.getMinimaxConfig)().model || "unknown"})`,
|
|
153
|
+
"openai-codex": () => `openai codex (${(0, config_1.getOpenAICodexConfig)().model || "unknown"})`,
|
|
154
|
+
/* v8 ignore next -- branch: tested via display label unit test @preserve */
|
|
155
|
+
"github-copilot": () => `github copilot (${(0, config_1.getGithubCopilotConfig)().model || "unknown"})`,
|
|
113
156
|
};
|
|
114
|
-
return providerLabelBuilders[
|
|
157
|
+
return providerLabelBuilders[provider]();
|
|
115
158
|
}
|
|
116
159
|
// Re-export tools, execTool, summarizeArgs from ./tools for backward compat
|
|
117
160
|
var tools_2 = require("../repertoire/tools");
|
|
@@ -128,6 +171,107 @@ Object.defineProperty(exports, "toResponsesTools", { enumerable: true, get: func
|
|
|
128
171
|
// Re-export prompt functions for backward compat
|
|
129
172
|
var prompt_2 = require("../mind/prompt");
|
|
130
173
|
Object.defineProperty(exports, "buildSystem", { enumerable: true, get: function () { return prompt_2.buildSystem; } });
|
|
174
|
+
// Sole-call tools must be the only tool call in a turn. When they appear
|
|
175
|
+
// alongside other tools, the sole-call tool is rejected with this message.
|
|
176
|
+
const SOLE_CALL_REJECTION = {
|
|
177
|
+
settle: "rejected: settle must be the only tool call. finish your work first, then call settle alone.",
|
|
178
|
+
observe: "rejected: observe must be the only tool call. call observe alone when you want to stay silent.",
|
|
179
|
+
descend: "rejected: descend must be the only tool call. finish your other work first, then call descend alone.",
|
|
180
|
+
};
|
|
181
|
+
const DELEGATION_REASON_PROSE_HANDOFF = {
|
|
182
|
+
explicit_reflection: "something in the conversation called for reflection",
|
|
183
|
+
cross_session: "this touches other conversations",
|
|
184
|
+
bridge_state: "there's shared work spanning sessions",
|
|
185
|
+
task_state: "there are active tasks that relate to this",
|
|
186
|
+
non_fast_path_tool: "this needs tools beyond a simple reply",
|
|
187
|
+
unresolved_obligation: "there's an unresolved commitment from an earlier conversation",
|
|
188
|
+
};
|
|
189
|
+
function buildDescendHandoffPacket(params) {
|
|
190
|
+
const reasons = params.delegationDecision?.reasons ?? [];
|
|
191
|
+
const reasonProse = reasons.length > 0
|
|
192
|
+
? reasons.map((r) => DELEGATION_REASON_PROSE_HANDOFF[r]).join("; ")
|
|
193
|
+
: "this felt like it needed more thought";
|
|
194
|
+
const whoAsked = params.currentSession
|
|
195
|
+
? params.currentSession.friendId
|
|
196
|
+
: "no one -- just thinking";
|
|
197
|
+
let holdingLine;
|
|
198
|
+
if (params.outwardClosureRequired && params.currentSession) {
|
|
199
|
+
holdingLine = `i'm holding something for ${params.currentSession.friendId}`;
|
|
200
|
+
}
|
|
201
|
+
else {
|
|
202
|
+
holdingLine = "nothing -- just thinking";
|
|
203
|
+
}
|
|
204
|
+
return [
|
|
205
|
+
"## what i need to think about",
|
|
206
|
+
params.topic,
|
|
207
|
+
"",
|
|
208
|
+
"## why this came up",
|
|
209
|
+
reasonProse,
|
|
210
|
+
"",
|
|
211
|
+
"## who asked",
|
|
212
|
+
whoAsked,
|
|
213
|
+
"",
|
|
214
|
+
"## what i'm holding",
|
|
215
|
+
holdingLine,
|
|
216
|
+
"",
|
|
217
|
+
"## thinking mode",
|
|
218
|
+
params.mode,
|
|
219
|
+
].join("\n");
|
|
220
|
+
}
|
|
221
|
+
function parseSettlePayload(argumentsText) {
|
|
222
|
+
try {
|
|
223
|
+
const parsed = JSON.parse(argumentsText);
|
|
224
|
+
if (typeof parsed === "string") {
|
|
225
|
+
return { answer: parsed };
|
|
226
|
+
}
|
|
227
|
+
if (!parsed || typeof parsed !== "object") {
|
|
228
|
+
return {};
|
|
229
|
+
}
|
|
230
|
+
const answer = typeof parsed.answer === "string" ? parsed.answer : undefined;
|
|
231
|
+
const rawIntent = parsed.intent;
|
|
232
|
+
const intent = rawIntent === "complete" || rawIntent === "blocked" || rawIntent === "direct_reply"
|
|
233
|
+
? rawIntent
|
|
234
|
+
: undefined;
|
|
235
|
+
return { answer, intent };
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
return {};
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/** Returns true when a tool call queries external state (GitHub, npm registry). */
|
|
242
|
+
function isExternalStateQuery(toolName, args) {
|
|
243
|
+
if (toolName !== "shell")
|
|
244
|
+
return false;
|
|
245
|
+
const cmd = String(args.command ?? "");
|
|
246
|
+
return /\bgh\s+(pr|run|api|issue)\b/.test(cmd) || /\bnpm\s+(view|info|show)\b/.test(cmd);
|
|
247
|
+
}
|
|
248
|
+
function getSettleRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp, _delegationDecision, sawSendMessageSelf, sawDescend, _sawQuerySession, currentObligation, innerJob, sawExternalStateQuery) {
|
|
249
|
+
// Delegation adherence removed: the delegation decision is surfaced in the
|
|
250
|
+
// system prompt as a suggestion. Hard-gating settle caused infinite
|
|
251
|
+
// rejection loops where the agent couldn't respond to the user at all.
|
|
252
|
+
// The agent is free to follow or ignore the delegation hint.
|
|
253
|
+
// 2. Pending obligation not addressed
|
|
254
|
+
if (innerJob?.obligationStatus === "pending" && !sawSendMessageSelf && !sawDescend) {
|
|
255
|
+
return "you're still holding something from an earlier conversation -- someone is waiting for your answer. finish the thought first, or descend to keep working on it privately.";
|
|
256
|
+
}
|
|
257
|
+
// 3. mustResolveBeforeHandoff + missing intent
|
|
258
|
+
if (mustResolveBeforeHandoff && !intent) {
|
|
259
|
+
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.";
|
|
260
|
+
}
|
|
261
|
+
// 4. mustResolveBeforeHandoff + direct_reply without follow-up
|
|
262
|
+
if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
|
|
263
|
+
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.";
|
|
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 settle.";
|
|
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))
|
|
@@ -215,6 +421,14 @@ function classifyTransientError(err) {
|
|
|
215
421
|
}
|
|
216
422
|
const MAX_RETRIES = 3;
|
|
217
423
|
const RETRY_BASE_MS = 2000;
|
|
424
|
+
const TRANSIENT_RETRY_LABELS = {
|
|
425
|
+
"auth-failure": "auth error",
|
|
426
|
+
"usage-limit": "usage limit",
|
|
427
|
+
"rate-limit": "rate limited",
|
|
428
|
+
"server-error": "server error",
|
|
429
|
+
"network-error": "network error",
|
|
430
|
+
"unknown": "error",
|
|
431
|
+
};
|
|
218
432
|
async function runAgent(messages, callbacks, channel, signal, options) {
|
|
219
433
|
const providerRuntime = getProviderRuntime();
|
|
220
434
|
const provider = providerRuntime.id;
|
|
@@ -242,7 +456,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
242
456
|
// so turn execution remains consistent and non-fatal.
|
|
243
457
|
if (channel) {
|
|
244
458
|
try {
|
|
245
|
-
const
|
|
459
|
+
const buildSystemOptions = {
|
|
460
|
+
...options,
|
|
461
|
+
providerCapabilities: providerRuntime.capabilities,
|
|
462
|
+
supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
|
|
463
|
+
};
|
|
464
|
+
const refreshed = await (0, prompt_1.buildSystem)(channel, buildSystemOptions, currentContext);
|
|
246
465
|
upsertSystemPrompt(messages, refreshed);
|
|
247
466
|
}
|
|
248
467
|
catch (error) {
|
|
@@ -265,31 +484,75 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
265
484
|
}
|
|
266
485
|
}
|
|
267
486
|
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
487
|
let done = false;
|
|
272
488
|
let lastUsage;
|
|
273
489
|
let overflowRetried = false;
|
|
274
490
|
let retryCount = 0;
|
|
491
|
+
let outcome = "settled";
|
|
492
|
+
let completion;
|
|
493
|
+
let terminalError;
|
|
494
|
+
let terminalErrorClassification;
|
|
495
|
+
let sawSteeringFollowUp = false;
|
|
496
|
+
let mustResolveBeforeHandoffActive = options?.mustResolveBeforeHandoff === true;
|
|
497
|
+
let currentReasoningEffort = "medium";
|
|
498
|
+
let sawSendMessageSelf = false;
|
|
499
|
+
let sawDescend = false;
|
|
500
|
+
let sawQuerySession = false;
|
|
501
|
+
let sawBridgeManage = false;
|
|
502
|
+
let sawExternalStateQuery = false;
|
|
503
|
+
const toolLoopState = (0, tool_loop_1.createToolLoopState)();
|
|
275
504
|
// Prevent MaxListenersExceeded warning — each iteration adds a listener
|
|
276
505
|
try {
|
|
277
506
|
require("events").setMaxListeners(50, signal);
|
|
278
507
|
}
|
|
279
508
|
catch { /* unsupported */ }
|
|
280
509
|
const toolPreferences = currentContext?.friend?.toolPreferences;
|
|
281
|
-
const baseTools = options?.tools ?? (0, tools_1.getToolsForChannel)(channel ? (0, channel_1.getChannelCapabilities)(channel) : undefined, toolPreferences && Object.keys(toolPreferences).length > 0 ? toolPreferences : undefined);
|
|
510
|
+
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);
|
|
511
|
+
// Augment tool context with reasoning effort controls from provider
|
|
512
|
+
const augmentedToolContext = options?.toolContext
|
|
513
|
+
? {
|
|
514
|
+
...options.toolContext,
|
|
515
|
+
supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
|
|
516
|
+
setReasoningEffort: (level) => { currentReasoningEffort = level; },
|
|
517
|
+
activeWorkFrame: options?.activeWorkFrame,
|
|
518
|
+
}
|
|
519
|
+
: undefined;
|
|
282
520
|
// Rebase provider-owned turn state from canonical messages at user-turn start.
|
|
283
521
|
// This prevents stale provider caches from replaying prior-turn context.
|
|
284
522
|
providerRuntime.resetTurnState(messages);
|
|
285
523
|
while (!done) {
|
|
286
|
-
//
|
|
287
|
-
//
|
|
288
|
-
//
|
|
289
|
-
//
|
|
290
|
-
|
|
524
|
+
// Channel-based tool filtering:
|
|
525
|
+
// - Inner dialog: exclude descend (already inward), send_message (delivery via surface), observe (no one to observe)
|
|
526
|
+
// - 1:1 sessions: exclude observe (can't ignore someone talking directly to you)
|
|
527
|
+
// - Group chats: observe available
|
|
528
|
+
//
|
|
529
|
+
// descend, settle, surface, and observe are always assembled based on channel context.
|
|
530
|
+
// toolChoiceRequired only controls whether tool_choice: "required" is set in the API call.
|
|
531
|
+
const isInnerDialog = channel === "inner";
|
|
532
|
+
const filteredBaseTools = isInnerDialog
|
|
533
|
+
? baseTools.filter((t) => t.function.name !== "send_message")
|
|
534
|
+
: baseTools;
|
|
535
|
+
const activeTools = [
|
|
536
|
+
...filteredBaseTools,
|
|
537
|
+
...(!isInnerDialog ? [tools_1.descendTool] : []),
|
|
538
|
+
...(isInnerDialog ? [surface_tool_1.surfaceToolDef] : []),
|
|
539
|
+
...(currentContext?.isGroupChat && !isInnerDialog ? [tools_1.observeTool] : []),
|
|
540
|
+
tools_1.settleTool,
|
|
541
|
+
];
|
|
291
542
|
const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
|
|
292
543
|
if (steeringFollowUps.length > 0) {
|
|
544
|
+
const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
|
|
545
|
+
if (hasSupersedingFollowUp) {
|
|
546
|
+
mustResolveBeforeHandoffActive = false;
|
|
547
|
+
options?.setMustResolveBeforeHandoff?.(false);
|
|
548
|
+
outcome = "superseded";
|
|
549
|
+
break;
|
|
550
|
+
}
|
|
551
|
+
if (steeringFollowUps.some((followUp) => followUp.effect === "set_no_handoff")) {
|
|
552
|
+
mustResolveBeforeHandoffActive = true;
|
|
553
|
+
options?.setMustResolveBeforeHandoff?.(true);
|
|
554
|
+
}
|
|
555
|
+
sawSteeringFollowUp = true;
|
|
293
556
|
for (const followUp of steeringFollowUps) {
|
|
294
557
|
messages.push({ role: "user", content: followUp.text });
|
|
295
558
|
}
|
|
@@ -297,8 +560,10 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
297
560
|
}
|
|
298
561
|
// Yield so pending I/O (stdin Ctrl-C) can be processed between iterations
|
|
299
562
|
await new Promise((r) => setImmediate(r));
|
|
300
|
-
if (signal?.aborted)
|
|
563
|
+
if (signal?.aborted) {
|
|
564
|
+
outcome = "aborted";
|
|
301
565
|
break;
|
|
566
|
+
}
|
|
302
567
|
try {
|
|
303
568
|
callbacks.onModelStart();
|
|
304
569
|
const result = await providerRuntime.streamTurn({
|
|
@@ -308,6 +573,8 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
308
573
|
signal,
|
|
309
574
|
traceId,
|
|
310
575
|
toolChoiceRequired,
|
|
576
|
+
reasoningEffort: currentReasoningEffort,
|
|
577
|
+
eagerSettleStreaming: true,
|
|
311
578
|
});
|
|
312
579
|
// Track usage from the latest API call
|
|
313
580
|
if (result.usage)
|
|
@@ -331,52 +598,76 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
331
598
|
if (reasoningItems.length > 0) {
|
|
332
599
|
msg._reasoning_items = reasoningItems;
|
|
333
600
|
}
|
|
601
|
+
// Store thinking blocks (Anthropic) on the assistant message for round-tripping
|
|
602
|
+
const thinkingItems = result.outputItems.filter((item) => "type" in item && (item.type === "thinking" || item.type === "redacted_thinking"));
|
|
603
|
+
if (thinkingItems.length > 0) {
|
|
604
|
+
msg._thinking_blocks = thinkingItems;
|
|
605
|
+
}
|
|
606
|
+
// Phase annotation for Codex provider
|
|
607
|
+
const hasPhaseAnnotation = providerRuntime.capabilities.has("phase-annotation");
|
|
608
|
+
const isSoleSettle = result.toolCalls.length === 1 && result.toolCalls[0].name === "settle";
|
|
609
|
+
if (hasPhaseAnnotation) {
|
|
610
|
+
msg.phase = isSoleSettle ? "settle" : "commentary";
|
|
611
|
+
}
|
|
334
612
|
if (!result.toolCalls.length) {
|
|
335
|
-
//
|
|
336
|
-
//
|
|
337
|
-
//
|
|
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
|
-
// }
|
|
613
|
+
// No tool calls — accept response as-is.
|
|
614
|
+
// (Kick detection disabled; tool_choice: required + settle
|
|
615
|
+
// is the primary loop control. See src/heart/kicks.ts to re-enable.)
|
|
353
616
|
messages.push(msg);
|
|
354
617
|
done = true;
|
|
355
618
|
}
|
|
356
619
|
else {
|
|
357
|
-
// Check for
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
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)
|
|
620
|
+
// Check for settle sole call: intercept before tool execution
|
|
621
|
+
if (isSoleSettle) {
|
|
622
|
+
/* v8 ignore next -- defensive: JSON.parse catch for malformed settle args @preserve */
|
|
623
|
+
const settleArgs = (() => { try {
|
|
624
|
+
return JSON.parse(result.toolCalls[0].arguments);
|
|
372
625
|
}
|
|
373
626
|
catch {
|
|
374
|
-
|
|
627
|
+
return {};
|
|
628
|
+
} })();
|
|
629
|
+
callbacks.onToolStart("settle", settleArgs);
|
|
630
|
+
// Inner dialog attention queue gate: reject settle if items remain
|
|
631
|
+
const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
|
|
632
|
+
if (isInnerDialog && attentionQueue && attentionQueue.length > 0) {
|
|
633
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
|
|
634
|
+
callbacks.onClearText?.();
|
|
635
|
+
messages.push(msg);
|
|
636
|
+
const gateMessage = "you're holding thoughts someone is waiting for — surface them before you settle.";
|
|
637
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
|
|
638
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
|
|
639
|
+
continue;
|
|
640
|
+
}
|
|
641
|
+
// Extract answer from the tool call arguments.
|
|
642
|
+
// Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
|
|
643
|
+
const { answer, intent } = parseSettlePayload(result.toolCalls[0].arguments);
|
|
644
|
+
// Inner dialog settle: no CompletionMetadata, "(settled)" ack
|
|
645
|
+
if (isInnerDialog) {
|
|
646
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
|
|
647
|
+
messages.push(msg);
|
|
648
|
+
const settled = "(settled)";
|
|
649
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: settled });
|
|
650
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, settled);
|
|
651
|
+
outcome = "settled";
|
|
652
|
+
done = true;
|
|
653
|
+
continue;
|
|
375
654
|
}
|
|
376
|
-
|
|
377
|
-
|
|
655
|
+
const retryError = getSettleRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp, options?.delegationDecision, sawSendMessageSelf, sawDescend, sawQuerySession, options?.currentObligation ?? null, options?.activeWorkFrame?.inner?.job, sawExternalStateQuery);
|
|
656
|
+
const deliveredAnswer = answer;
|
|
657
|
+
const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
|
|
658
|
+
const validTerminalIntent = intent === "complete" || intent === "blocked";
|
|
659
|
+
const validClosure = deliveredAnswer != null
|
|
660
|
+
&& !retryError
|
|
661
|
+
&& (!mustResolveBeforeHandoffActive || validDirectReply || validTerminalIntent);
|
|
662
|
+
if (validClosure) {
|
|
663
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
|
|
664
|
+
completion = {
|
|
665
|
+
answer: deliveredAnswer,
|
|
666
|
+
intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
|
|
667
|
+
};
|
|
668
|
+
if (result.settleStreamed) {
|
|
378
669
|
// The streaming layer already parsed and emitted the answer
|
|
379
|
-
// progressively via
|
|
670
|
+
// progressively via SettleParser. Skip clearing and
|
|
380
671
|
// re-emitting to avoid double-delivery.
|
|
381
672
|
}
|
|
382
673
|
else {
|
|
@@ -384,37 +675,166 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
384
675
|
callbacks.onClearText?.();
|
|
385
676
|
// Emit the answer through the callback pipeline so channels receive it.
|
|
386
677
|
// Never truncate -- channel adapters handle splitting long messages.
|
|
387
|
-
callbacks.onTextChunk(
|
|
678
|
+
callbacks.onTextChunk(deliveredAnswer);
|
|
388
679
|
}
|
|
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
680
|
messages.push(msg);
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
681
|
+
if (validDirectReply) {
|
|
682
|
+
const resumeWork = "direct reply delivered. resume the unresolved obligation now and keep working until you can finish or clearly report that you are blocked.";
|
|
683
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: resumeWork });
|
|
684
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, resumeWork);
|
|
685
|
+
}
|
|
686
|
+
else {
|
|
687
|
+
const delivered = "(delivered)";
|
|
688
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
|
|
689
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
|
|
690
|
+
outcome = intent === "blocked" ? "blocked" : "settled";
|
|
691
|
+
done = true;
|
|
692
|
+
}
|
|
395
693
|
}
|
|
396
694
|
else {
|
|
397
|
-
// Answer is undefined -- the model's
|
|
695
|
+
// Answer is undefined -- the model's settle was incomplete or
|
|
398
696
|
// malformed. Clear any partial streamed text or noise, then push the
|
|
399
697
|
// assistant msg + error tool result and let the model try again.
|
|
698
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
|
|
400
699
|
callbacks.onClearText?.();
|
|
401
|
-
const retryError = "your final_answer was incomplete or malformed. call final_answer again with your complete response.";
|
|
402
700
|
messages.push(msg);
|
|
403
|
-
|
|
404
|
-
|
|
701
|
+
const toolRetryMessage = retryError
|
|
702
|
+
?? "your settle was incomplete or malformed. call settle again with your complete response.";
|
|
703
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: toolRetryMessage });
|
|
704
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, toolRetryMessage);
|
|
405
705
|
}
|
|
406
706
|
continue;
|
|
407
707
|
}
|
|
708
|
+
// Check for observe sole call: intercept before tool execution
|
|
709
|
+
const isSoleObserve = result.toolCalls.length === 1 && result.toolCalls[0].name === "observe";
|
|
710
|
+
if (isSoleObserve) {
|
|
711
|
+
/* v8 ignore next -- defensive: JSON.parse catch for malformed observe args @preserve */
|
|
712
|
+
const observeArgs = (() => { try {
|
|
713
|
+
return JSON.parse(result.toolCalls[0].arguments);
|
|
714
|
+
}
|
|
715
|
+
catch {
|
|
716
|
+
return {};
|
|
717
|
+
} })();
|
|
718
|
+
let reason;
|
|
719
|
+
if (typeof observeArgs?.reason === "string")
|
|
720
|
+
reason = observeArgs.reason;
|
|
721
|
+
callbacks.onToolStart("observe", observeArgs);
|
|
722
|
+
(0, runtime_1.emitNervesEvent)({
|
|
723
|
+
component: "engine",
|
|
724
|
+
event: "engine.observe",
|
|
725
|
+
message: "agent declined to respond in group chat",
|
|
726
|
+
meta: { ...(reason ? { reason } : {}) },
|
|
727
|
+
});
|
|
728
|
+
callbacks.onToolEnd("observe", (0, tools_1.summarizeArgs)("observe", observeArgs), true);
|
|
729
|
+
messages.push(msg);
|
|
730
|
+
const silenced = "(silenced)";
|
|
731
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: silenced });
|
|
732
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, silenced);
|
|
733
|
+
outcome = "observed";
|
|
734
|
+
done = true;
|
|
735
|
+
continue;
|
|
736
|
+
}
|
|
737
|
+
// Check for descend sole call: intercept before tool execution
|
|
738
|
+
const isSoleDescend = result.toolCalls.length === 1 && result.toolCalls[0].name === "descend";
|
|
739
|
+
if (isSoleDescend) {
|
|
740
|
+
let parsedArgs = {};
|
|
741
|
+
try {
|
|
742
|
+
parsedArgs = JSON.parse(result.toolCalls[0].arguments);
|
|
743
|
+
}
|
|
744
|
+
catch { /* ignore */ }
|
|
745
|
+
callbacks.onToolStart("descend", parsedArgs);
|
|
746
|
+
/* v8 ignore next -- defensive: topic always string from model @preserve */
|
|
747
|
+
const topic = typeof parsedArgs.topic === "string" ? parsedArgs.topic : "";
|
|
748
|
+
const answer = typeof parsedArgs.answer === "string" ? parsedArgs.answer : undefined;
|
|
749
|
+
const parsedMode = parsedArgs.mode === "reflect" || parsedArgs.mode === "plan" || parsedArgs.mode === "relay"
|
|
750
|
+
? parsedArgs.mode
|
|
751
|
+
: undefined;
|
|
752
|
+
const mode = parsedMode || "reflect";
|
|
753
|
+
// Emit outward answer if provided
|
|
754
|
+
if (answer) {
|
|
755
|
+
callbacks.onClearText?.();
|
|
756
|
+
callbacks.onTextChunk(answer);
|
|
757
|
+
}
|
|
758
|
+
// Build handoff packet and enqueue
|
|
759
|
+
const handoffContent = buildDescendHandoffPacket({
|
|
760
|
+
topic,
|
|
761
|
+
mode,
|
|
762
|
+
delegationDecision: options?.delegationDecision,
|
|
763
|
+
currentSession: options?.toolContext?.currentSession ?? null,
|
|
764
|
+
currentObligation: options?.currentObligation ?? null,
|
|
765
|
+
outwardClosureRequired: options?.delegationDecision?.outwardClosureRequired ?? false,
|
|
766
|
+
});
|
|
767
|
+
const pendingDir = (0, pending_1.getInnerDialogPendingDir)((0, identity_2.getAgentName)());
|
|
768
|
+
const currentSession = options?.toolContext?.currentSession;
|
|
769
|
+
const isInnerChannel = currentSession?.friendId === "self" && currentSession?.channel === "inner";
|
|
770
|
+
// Create obligation FIRST so we can attach its ID to the pending message
|
|
771
|
+
let createdObligationId;
|
|
772
|
+
if (currentSession && !isInnerChannel) {
|
|
773
|
+
try {
|
|
774
|
+
const obligation = (0, obligations_1.createObligation)((0, identity_2.getAgentRoot)(), {
|
|
775
|
+
origin: {
|
|
776
|
+
friendId: currentSession.friendId,
|
|
777
|
+
channel: currentSession.channel,
|
|
778
|
+
key: currentSession.key,
|
|
779
|
+
},
|
|
780
|
+
content: topic,
|
|
781
|
+
});
|
|
782
|
+
createdObligationId = obligation.id;
|
|
783
|
+
}
|
|
784
|
+
catch {
|
|
785
|
+
/* v8 ignore next -- defensive: obligation store write failure should not break descend @preserve */
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
const envelope = {
|
|
789
|
+
from: (0, identity_2.getAgentName)(),
|
|
790
|
+
friendId: "self",
|
|
791
|
+
channel: "inner",
|
|
792
|
+
key: "dialog",
|
|
793
|
+
content: handoffContent,
|
|
794
|
+
timestamp: Date.now(),
|
|
795
|
+
mode,
|
|
796
|
+
...(currentSession && !isInnerChannel ? {
|
|
797
|
+
delegatedFrom: {
|
|
798
|
+
friendId: currentSession.friendId,
|
|
799
|
+
channel: currentSession.channel,
|
|
800
|
+
key: currentSession.key,
|
|
801
|
+
},
|
|
802
|
+
obligationStatus: "pending",
|
|
803
|
+
/* v8 ignore next -- defensive: createdObligationId is undefined only when obligation store write fails @preserve */
|
|
804
|
+
...(createdObligationId ? { obligationId: createdObligationId } : {}),
|
|
805
|
+
} : {}),
|
|
806
|
+
};
|
|
807
|
+
(0, pending_1.queuePendingMessage)(pendingDir, envelope);
|
|
808
|
+
try {
|
|
809
|
+
await (0, socket_client_1.requestInnerWake)((0, identity_2.getAgentName)());
|
|
810
|
+
}
|
|
811
|
+
catch { /* daemon may not be running */ }
|
|
812
|
+
callbacks.onToolEnd("descend", (0, tools_1.summarizeArgs)("descend", parsedArgs), true);
|
|
813
|
+
sawDescend = true;
|
|
814
|
+
messages.push(msg);
|
|
815
|
+
const ack = "(going inward)";
|
|
816
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
|
|
817
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
|
|
818
|
+
(0, runtime_1.emitNervesEvent)({
|
|
819
|
+
component: "engine",
|
|
820
|
+
event: "engine.descended",
|
|
821
|
+
message: "taking thread inward",
|
|
822
|
+
meta: { mode, hasAnswer: answer !== undefined, contentSnippet: topic.slice(0, 80) },
|
|
823
|
+
});
|
|
824
|
+
outcome = "descended";
|
|
825
|
+
done = true;
|
|
826
|
+
continue;
|
|
827
|
+
}
|
|
408
828
|
messages.push(msg);
|
|
409
|
-
//
|
|
829
|
+
// Execute tools (sole-call tools in mixed calls are rejected inline)
|
|
410
830
|
for (const tc of result.toolCalls) {
|
|
411
831
|
if (signal?.aborted)
|
|
412
832
|
break;
|
|
413
|
-
//
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
messages.push({ role: "tool", tool_call_id: tc.id, content:
|
|
417
|
-
providerRuntime.appendToolOutput(tc.id,
|
|
833
|
+
// Reject sole-call tools when mixed with other tool calls
|
|
834
|
+
const soleCallRejection = SOLE_CALL_REJECTION[tc.name];
|
|
835
|
+
if (soleCallRejection) {
|
|
836
|
+
messages.push({ role: "tool", tool_call_id: tc.id, content: soleCallRejection });
|
|
837
|
+
providerRuntime.appendToolOutput(tc.id, soleCallRejection);
|
|
418
838
|
continue;
|
|
419
839
|
}
|
|
420
840
|
let args = {};
|
|
@@ -424,7 +844,28 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
424
844
|
catch {
|
|
425
845
|
/* ignore */
|
|
426
846
|
}
|
|
847
|
+
if (tc.name === "send_message" && args.friendId === "self") {
|
|
848
|
+
sawSendMessageSelf = true;
|
|
849
|
+
}
|
|
850
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
851
|
+
if (tc.name === "query_session")
|
|
852
|
+
sawQuerySession = true;
|
|
853
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
854
|
+
if (tc.name === "bridge_manage")
|
|
855
|
+
sawBridgeManage = true;
|
|
856
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
857
|
+
if (isExternalStateQuery(tc.name, args))
|
|
858
|
+
sawExternalStateQuery = true;
|
|
427
859
|
const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
|
|
860
|
+
const toolLoop = (0, tool_loop_1.detectToolLoop)(toolLoopState, tc.name, args);
|
|
861
|
+
if (toolLoop.stuck) {
|
|
862
|
+
const rejection = `loop guard: ${toolLoop.message}`;
|
|
863
|
+
callbacks.onToolStart(tc.name, args);
|
|
864
|
+
callbacks.onToolEnd(tc.name, argSummary, false);
|
|
865
|
+
messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
|
|
866
|
+
providerRuntime.appendToolOutput(tc.id, rejection);
|
|
867
|
+
continue;
|
|
868
|
+
}
|
|
428
869
|
// Confirmation check for mutate tools
|
|
429
870
|
if ((0, tools_1.isConfirmationRequired)(tc.name) && !options?.skipConfirmation) {
|
|
430
871
|
let decision = "denied";
|
|
@@ -445,13 +886,14 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
445
886
|
let success;
|
|
446
887
|
try {
|
|
447
888
|
const execToolFn = options?.execTool ?? tools_1.execTool;
|
|
448
|
-
toolResult = await execToolFn(tc.name, args, options?.toolContext);
|
|
889
|
+
toolResult = await execToolFn(tc.name, args, augmentedToolContext ?? options?.toolContext);
|
|
449
890
|
success = true;
|
|
450
891
|
}
|
|
451
892
|
catch (e) {
|
|
452
893
|
toolResult = `error: ${e}`;
|
|
453
894
|
success = false;
|
|
454
895
|
}
|
|
896
|
+
(0, tool_loop_1.recordToolOutcome)(toolLoopState, tc.name, args, toolResult, success);
|
|
455
897
|
callbacks.onToolEnd(tc.name, argSummary, success);
|
|
456
898
|
messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
|
|
457
899
|
providerRuntime.appendToolOutput(tc.id, toolResult);
|
|
@@ -462,6 +904,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
462
904
|
// Abort is not an error — just stop cleanly
|
|
463
905
|
if (signal?.aborted) {
|
|
464
906
|
stripLastToolCalls(messages);
|
|
907
|
+
outcome = "aborted";
|
|
465
908
|
break;
|
|
466
909
|
}
|
|
467
910
|
// Context overflow: trim aggressively and retry once
|
|
@@ -479,7 +922,16 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
479
922
|
if (isTransientError(e) && retryCount < MAX_RETRIES) {
|
|
480
923
|
retryCount++;
|
|
481
924
|
const delay = RETRY_BASE_MS * Math.pow(2, retryCount - 1);
|
|
482
|
-
|
|
925
|
+
let classification;
|
|
926
|
+
try {
|
|
927
|
+
classification = providerRuntime.classifyError(e instanceof Error ? e : /* v8 ignore next -- defensive: errors are always Error instances @preserve */ new Error(String(e)));
|
|
928
|
+
}
|
|
929
|
+
catch {
|
|
930
|
+
/* v8 ignore next -- defensive: classifyError should not throw @preserve */
|
|
931
|
+
classification = classifyTransientError(e);
|
|
932
|
+
}
|
|
933
|
+
/* v8 ignore next -- defensive: all classifications have labels @preserve */
|
|
934
|
+
const cause = TRANSIENT_RETRY_LABELS[classification] ?? classification;
|
|
483
935
|
callbacks.onError(new Error(`${cause}, retrying in ${delay / 1000}s (${retryCount}/${MAX_RETRIES})...`), "transient");
|
|
484
936
|
// Wait with abort support
|
|
485
937
|
const aborted = await new Promise((resolve) => {
|
|
@@ -496,21 +948,31 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
496
948
|
});
|
|
497
949
|
if (aborted) {
|
|
498
950
|
stripLastToolCalls(messages);
|
|
951
|
+
outcome = "aborted";
|
|
499
952
|
break;
|
|
500
953
|
}
|
|
501
954
|
providerRuntime.resetTurnState(messages);
|
|
502
955
|
continue;
|
|
503
956
|
}
|
|
504
|
-
|
|
957
|
+
terminalError = e instanceof Error ? e : new Error(String(e));
|
|
958
|
+
try {
|
|
959
|
+
terminalErrorClassification = providerRuntime.classifyError(terminalError);
|
|
960
|
+
}
|
|
961
|
+
catch {
|
|
962
|
+
/* v8 ignore next -- defensive: classifyError should not throw @preserve */
|
|
963
|
+
terminalErrorClassification = "unknown";
|
|
964
|
+
}
|
|
965
|
+
callbacks.onError(terminalError, "terminal");
|
|
505
966
|
(0, runtime_1.emitNervesEvent)({
|
|
506
967
|
level: "error",
|
|
507
968
|
event: "engine.error",
|
|
508
969
|
trace_id: traceId,
|
|
509
970
|
component: "engine",
|
|
510
|
-
message:
|
|
511
|
-
meta: {},
|
|
971
|
+
message: terminalError.message,
|
|
972
|
+
meta: { errorClassification: terminalErrorClassification },
|
|
512
973
|
});
|
|
513
974
|
stripLastToolCalls(messages);
|
|
975
|
+
outcome = "errored";
|
|
514
976
|
done = true;
|
|
515
977
|
}
|
|
516
978
|
}
|
|
@@ -519,7 +981,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
519
981
|
trace_id: traceId,
|
|
520
982
|
component: "engine",
|
|
521
983
|
message: "runAgent turn completed",
|
|
522
|
-
meta: { done },
|
|
984
|
+
meta: { done, sawDescend, sawQuerySession, sawBridgeManage },
|
|
523
985
|
});
|
|
524
|
-
return {
|
|
986
|
+
return {
|
|
987
|
+
usage: lastUsage,
|
|
988
|
+
outcome,
|
|
989
|
+
completion,
|
|
990
|
+
...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
|
|
991
|
+
};
|
|
525
992
|
}
|