@ouro.bot/cli 0.1.0-alpha.14 → 0.1.0-alpha.141
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 +913 -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 +645 -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 +200 -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 +125 -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 +980 -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 +266 -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,108 @@ 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
|
+
ponder: "rejected: ponder must be the only tool call. finish your other work first, then call ponder alone.",
|
|
180
|
+
rest: "rejected: rest must be the only tool call. finish your work first, then call rest alone.",
|
|
181
|
+
};
|
|
182
|
+
const DELEGATION_REASON_PROSE_HANDOFF = {
|
|
183
|
+
explicit_reflection: "something in the conversation called for reflection",
|
|
184
|
+
cross_session: "this touches other conversations",
|
|
185
|
+
bridge_state: "there's shared work spanning sessions",
|
|
186
|
+
task_state: "there are active tasks that relate to this",
|
|
187
|
+
non_fast_path_tool: "this needs tools beyond a simple reply",
|
|
188
|
+
unresolved_obligation: "there's an unresolved commitment from an earlier conversation",
|
|
189
|
+
};
|
|
190
|
+
function buildPonderHandoffPacket(params) {
|
|
191
|
+
const reasons = params.delegationDecision?.reasons ?? [];
|
|
192
|
+
const reasonProse = reasons.length > 0
|
|
193
|
+
? reasons.map((r) => DELEGATION_REASON_PROSE_HANDOFF[r]).join("; ")
|
|
194
|
+
: "this felt like it needed more thought";
|
|
195
|
+
const whoAsked = params.currentSession
|
|
196
|
+
? params.currentSession.friendId
|
|
197
|
+
: "no one -- just thinking";
|
|
198
|
+
let holdingLine;
|
|
199
|
+
if (params.outwardClosureRequired && params.currentSession) {
|
|
200
|
+
holdingLine = `i'm holding something for ${params.currentSession.friendId}`;
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
holdingLine = "nothing -- just thinking";
|
|
204
|
+
}
|
|
205
|
+
return [
|
|
206
|
+
"## what i need to think about",
|
|
207
|
+
params.topic,
|
|
208
|
+
"",
|
|
209
|
+
"## why this came up",
|
|
210
|
+
reasonProse,
|
|
211
|
+
"",
|
|
212
|
+
"## who asked",
|
|
213
|
+
whoAsked,
|
|
214
|
+
"",
|
|
215
|
+
"## what i'm holding",
|
|
216
|
+
holdingLine,
|
|
217
|
+
"",
|
|
218
|
+
"## thinking mode",
|
|
219
|
+
params.mode,
|
|
220
|
+
].join("\n");
|
|
221
|
+
}
|
|
222
|
+
function parseSettlePayload(argumentsText) {
|
|
223
|
+
try {
|
|
224
|
+
const parsed = JSON.parse(argumentsText);
|
|
225
|
+
if (typeof parsed === "string") {
|
|
226
|
+
return { answer: parsed };
|
|
227
|
+
}
|
|
228
|
+
if (!parsed || typeof parsed !== "object") {
|
|
229
|
+
return {};
|
|
230
|
+
}
|
|
231
|
+
const answer = typeof parsed.answer === "string" ? parsed.answer : undefined;
|
|
232
|
+
const rawIntent = parsed.intent;
|
|
233
|
+
const intent = rawIntent === "complete" || rawIntent === "blocked" || rawIntent === "direct_reply"
|
|
234
|
+
? rawIntent
|
|
235
|
+
: undefined;
|
|
236
|
+
return { answer, intent };
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
return {};
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
/** Returns true when a tool call queries external state (GitHub, npm registry). */
|
|
243
|
+
function isExternalStateQuery(toolName, args) {
|
|
244
|
+
if (toolName !== "shell")
|
|
245
|
+
return false;
|
|
246
|
+
const cmd = String(args.command ?? "");
|
|
247
|
+
return /\bgh\s+(pr|run|api|issue)\b/.test(cmd) || /\bnpm\s+(view|info|show)\b/.test(cmd);
|
|
248
|
+
}
|
|
249
|
+
function getSettleRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp, _delegationDecision, sawSendMessageSelf, sawPonder, _sawQuerySession, currentObligation, innerJob, sawExternalStateQuery) {
|
|
250
|
+
// Delegation adherence removed: the delegation decision is surfaced in the
|
|
251
|
+
// system prompt as a suggestion. Hard-gating settle caused infinite
|
|
252
|
+
// rejection loops where the agent couldn't respond to the user at all.
|
|
253
|
+
// The agent is free to follow or ignore the delegation hint.
|
|
254
|
+
// 2. Pending obligation not addressed
|
|
255
|
+
if (innerJob?.obligationStatus === "pending" && !sawSendMessageSelf && !sawPonder) {
|
|
256
|
+
return "you're still holding something from an earlier conversation -- someone is waiting for your answer. finish the thought first, or ponder to keep working on it privately.";
|
|
257
|
+
}
|
|
258
|
+
// 3. mustResolveBeforeHandoff + missing intent
|
|
259
|
+
if (mustResolveBeforeHandoff && !intent) {
|
|
260
|
+
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.";
|
|
261
|
+
}
|
|
262
|
+
// 4. mustResolveBeforeHandoff + direct_reply without follow-up
|
|
263
|
+
if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
|
|
264
|
+
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.";
|
|
265
|
+
}
|
|
266
|
+
// 5. mustResolveBeforeHandoff + complete while a live return loop is still active
|
|
267
|
+
if (mustResolveBeforeHandoff && intent === "complete" && currentObligation && !sawSteeringFollowUp) {
|
|
268
|
+
return "you still owe the live session a visible return on this work. don't end the turn yet — continue until you've brought back the external-state update, or use intent=blocked with the concrete blocker.";
|
|
269
|
+
}
|
|
270
|
+
// 6. External-state grounding: obligation + complete requires fresh external verification
|
|
271
|
+
if (intent === "complete" && currentObligation && !sawExternalStateQuery && !sawSteeringFollowUp) {
|
|
272
|
+
return "you're claiming this work is complete, but the external state hasn't been verified this turn. ground your claim with a fresh check (gh pr view, npm view, gh run view, etc.) before calling settle.";
|
|
273
|
+
}
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
131
276
|
// Re-export kick utilities for backward compat
|
|
132
277
|
var kicks_1 = require("./kicks");
|
|
133
278
|
Object.defineProperty(exports, "hasToolIntent", { enumerable: true, get: function () { return kicks_1.hasToolIntent; } });
|
|
@@ -160,6 +305,68 @@ function stripLastToolCalls(messages) {
|
|
|
160
305
|
}
|
|
161
306
|
}
|
|
162
307
|
}
|
|
308
|
+
// Roles that end a tool-result scan. When scanning forward from an assistant
|
|
309
|
+
// message, stop at the next assistant or user message (tool results must be
|
|
310
|
+
// adjacent to their originating assistant message).
|
|
311
|
+
const TOOL_SCAN_BOUNDARY_ROLES = new Set(["assistant", "user"]);
|
|
312
|
+
// Repair orphaned tool_calls and tool results anywhere in the message history.
|
|
313
|
+
// 1. If an assistant message has tool_calls but missing tool results, inject synthetic error results.
|
|
314
|
+
// 2. If a tool result's tool_call_id doesn't match any tool_calls in a preceding assistant message, remove it.
|
|
315
|
+
// This prevents 400 errors from the API after an aborted turn.
|
|
316
|
+
function repairOrphanedToolCalls(messages) {
|
|
317
|
+
// Pass 1: collect all valid tool_call IDs from assistant messages
|
|
318
|
+
const validCallIds = new Set();
|
|
319
|
+
for (const msg of messages) {
|
|
320
|
+
if (msg.role === "assistant") {
|
|
321
|
+
const asst = msg;
|
|
322
|
+
if (asst.tool_calls) {
|
|
323
|
+
for (const tc of asst.tool_calls)
|
|
324
|
+
validCallIds.add(tc.id);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
// Pass 2: remove orphaned tool results (tool_call_id not in any assistant's tool_calls)
|
|
329
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
330
|
+
if (messages[i].role === "tool") {
|
|
331
|
+
const toolMsg = messages[i];
|
|
332
|
+
if (!validCallIds.has(toolMsg.tool_call_id)) {
|
|
333
|
+
messages.splice(i, 1);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
// Pass 3: inject synthetic results for tool_calls missing their tool results
|
|
338
|
+
for (let i = 0; i < messages.length; i++) {
|
|
339
|
+
const msg = messages[i];
|
|
340
|
+
if (msg.role !== "assistant")
|
|
341
|
+
continue;
|
|
342
|
+
const asst = msg;
|
|
343
|
+
if (!asst.tool_calls || asst.tool_calls.length === 0)
|
|
344
|
+
continue;
|
|
345
|
+
// Collect tool result IDs that follow this assistant message
|
|
346
|
+
const resultIds = new Set();
|
|
347
|
+
for (let j = i + 1; j < messages.length; j++) {
|
|
348
|
+
const following = messages[j];
|
|
349
|
+
if (following.role === "tool") {
|
|
350
|
+
resultIds.add(following.tool_call_id);
|
|
351
|
+
}
|
|
352
|
+
else if (TOOL_SCAN_BOUNDARY_ROLES.has(following.role)) {
|
|
353
|
+
break;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
const missing = asst.tool_calls.filter((tc) => !resultIds.has(tc.id));
|
|
357
|
+
if (missing.length > 0) {
|
|
358
|
+
const syntheticResults = missing.map((tc) => ({
|
|
359
|
+
role: "tool",
|
|
360
|
+
tool_call_id: tc.id,
|
|
361
|
+
content: "error: tool call was interrupted (previous turn timed out or was aborted)",
|
|
362
|
+
}));
|
|
363
|
+
let insertAt = i + 1;
|
|
364
|
+
while (insertAt < messages.length && messages[insertAt].role === "tool")
|
|
365
|
+
insertAt++;
|
|
366
|
+
messages.splice(insertAt, 0, ...syntheticResults);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
163
370
|
// Detect context overflow errors from Azure or MiniMax
|
|
164
371
|
function isContextOverflow(err) {
|
|
165
372
|
if (!(err instanceof Error))
|
|
@@ -215,6 +422,14 @@ function classifyTransientError(err) {
|
|
|
215
422
|
}
|
|
216
423
|
const MAX_RETRIES = 3;
|
|
217
424
|
const RETRY_BASE_MS = 2000;
|
|
425
|
+
const TRANSIENT_RETRY_LABELS = {
|
|
426
|
+
"auth-failure": "auth error",
|
|
427
|
+
"usage-limit": "usage limit",
|
|
428
|
+
"rate-limit": "rate limited",
|
|
429
|
+
"server-error": "server error",
|
|
430
|
+
"network-error": "network error",
|
|
431
|
+
"unknown": "error",
|
|
432
|
+
};
|
|
218
433
|
async function runAgent(messages, callbacks, channel, signal, options) {
|
|
219
434
|
const providerRuntime = getProviderRuntime();
|
|
220
435
|
const provider = providerRuntime.id;
|
|
@@ -242,7 +457,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
242
457
|
// so turn execution remains consistent and non-fatal.
|
|
243
458
|
if (channel) {
|
|
244
459
|
try {
|
|
245
|
-
const
|
|
460
|
+
const buildSystemOptions = {
|
|
461
|
+
...options,
|
|
462
|
+
providerCapabilities: providerRuntime.capabilities,
|
|
463
|
+
supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
|
|
464
|
+
};
|
|
465
|
+
const refreshed = await (0, prompt_1.buildSystem)(channel, buildSystemOptions, currentContext);
|
|
246
466
|
upsertSystemPrompt(messages, refreshed);
|
|
247
467
|
}
|
|
248
468
|
catch (error) {
|
|
@@ -265,31 +485,77 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
265
485
|
}
|
|
266
486
|
}
|
|
267
487
|
await (0, associative_recall_1.injectAssociativeRecall)(messages);
|
|
268
|
-
// kickCount and lastKickReason preserved but unused while kick detection is disabled.
|
|
269
|
-
// let kickCount = 0;
|
|
270
|
-
// let lastKickReason: KickReason | null = null;
|
|
271
488
|
let done = false;
|
|
272
489
|
let lastUsage;
|
|
273
490
|
let overflowRetried = false;
|
|
274
491
|
let retryCount = 0;
|
|
492
|
+
let outcome = "settled";
|
|
493
|
+
let completion;
|
|
494
|
+
let terminalError;
|
|
495
|
+
let terminalErrorClassification;
|
|
496
|
+
let sawSteeringFollowUp = false;
|
|
497
|
+
let mustResolveBeforeHandoffActive = options?.mustResolveBeforeHandoff === true;
|
|
498
|
+
let currentReasoningEffort = "medium";
|
|
499
|
+
let sawSendMessageSelf = false;
|
|
500
|
+
let sawPonder = false;
|
|
501
|
+
let sawQuerySession = false;
|
|
502
|
+
let sawBridgeManage = false;
|
|
503
|
+
let sawExternalStateQuery = false;
|
|
504
|
+
const toolLoopState = (0, tool_loop_1.createToolLoopState)();
|
|
275
505
|
// Prevent MaxListenersExceeded warning — each iteration adds a listener
|
|
276
506
|
try {
|
|
277
507
|
require("events").setMaxListeners(50, signal);
|
|
278
508
|
}
|
|
279
509
|
catch { /* unsupported */ }
|
|
280
510
|
const toolPreferences = currentContext?.friend?.toolPreferences;
|
|
281
|
-
const baseTools = options?.tools ?? (0, tools_1.getToolsForChannel)(channel ? (0, channel_1.getChannelCapabilities)(channel) : undefined, toolPreferences && Object.keys(toolPreferences).length > 0 ? toolPreferences : undefined);
|
|
511
|
+
const baseTools = options?.tools ?? (0, tools_1.getToolsForChannel)(channel ? (0, channel_1.getChannelCapabilities)(channel) : undefined, toolPreferences && Object.keys(toolPreferences).length > 0 ? toolPreferences : undefined, currentContext, providerRuntime.capabilities);
|
|
512
|
+
// Augment tool context with reasoning effort controls from provider
|
|
513
|
+
const augmentedToolContext = options?.toolContext
|
|
514
|
+
? {
|
|
515
|
+
...options.toolContext,
|
|
516
|
+
supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
|
|
517
|
+
setReasoningEffort: (level) => { currentReasoningEffort = level; },
|
|
518
|
+
activeWorkFrame: options?.activeWorkFrame,
|
|
519
|
+
}
|
|
520
|
+
: undefined;
|
|
282
521
|
// Rebase provider-owned turn state from canonical messages at user-turn start.
|
|
283
522
|
// This prevents stale provider caches from replaying prior-turn context.
|
|
284
523
|
providerRuntime.resetTurnState(messages);
|
|
285
524
|
while (!done) {
|
|
286
|
-
//
|
|
287
|
-
//
|
|
288
|
-
//
|
|
289
|
-
//
|
|
290
|
-
|
|
525
|
+
// Channel-based tool filtering:
|
|
526
|
+
// - Inner dialog: exclude send_message (delivery via surface), observe (no one to observe)
|
|
527
|
+
// - 1:1 sessions: exclude observe (can't ignore someone talking directly to you)
|
|
528
|
+
// - Group chats: observe available
|
|
529
|
+
//
|
|
530
|
+
// ponder, settle/rest, surface, and observe are always assembled based on channel context.
|
|
531
|
+
// ponder is available in ALL channels (outer: think privately, inner: keep turning).
|
|
532
|
+
// Inner dialog gets restTool instead of settleTool (rest = end turn, gated by attention queue).
|
|
533
|
+
// toolChoiceRequired only controls whether tool_choice: "required" is set in the API call.
|
|
534
|
+
const isInnerDialog = channel === "inner";
|
|
535
|
+
const filteredBaseTools = isInnerDialog
|
|
536
|
+
? baseTools.filter((t) => t.function.name !== "send_message")
|
|
537
|
+
: baseTools;
|
|
538
|
+
const activeTools = [
|
|
539
|
+
...filteredBaseTools,
|
|
540
|
+
tools_1.ponderTool,
|
|
541
|
+
...(isInnerDialog ? [surface_tool_1.surfaceToolDef, tools_1.restTool] : []),
|
|
542
|
+
...(currentContext?.isGroupChat && !isInnerDialog ? [tools_1.observeTool] : []),
|
|
543
|
+
...(!isInnerDialog ? [tools_1.settleTool] : []),
|
|
544
|
+
];
|
|
291
545
|
const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
|
|
292
546
|
if (steeringFollowUps.length > 0) {
|
|
547
|
+
const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
|
|
548
|
+
if (hasSupersedingFollowUp) {
|
|
549
|
+
mustResolveBeforeHandoffActive = false;
|
|
550
|
+
options?.setMustResolveBeforeHandoff?.(false);
|
|
551
|
+
outcome = "superseded";
|
|
552
|
+
break;
|
|
553
|
+
}
|
|
554
|
+
if (steeringFollowUps.some((followUp) => followUp.effect === "set_no_handoff")) {
|
|
555
|
+
mustResolveBeforeHandoffActive = true;
|
|
556
|
+
options?.setMustResolveBeforeHandoff?.(true);
|
|
557
|
+
}
|
|
558
|
+
sawSteeringFollowUp = true;
|
|
293
559
|
for (const followUp of steeringFollowUps) {
|
|
294
560
|
messages.push({ role: "user", content: followUp.text });
|
|
295
561
|
}
|
|
@@ -297,8 +563,10 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
297
563
|
}
|
|
298
564
|
// Yield so pending I/O (stdin Ctrl-C) can be processed between iterations
|
|
299
565
|
await new Promise((r) => setImmediate(r));
|
|
300
|
-
if (signal?.aborted)
|
|
566
|
+
if (signal?.aborted) {
|
|
567
|
+
outcome = "aborted";
|
|
301
568
|
break;
|
|
569
|
+
}
|
|
302
570
|
try {
|
|
303
571
|
callbacks.onModelStart();
|
|
304
572
|
const result = await providerRuntime.streamTurn({
|
|
@@ -308,6 +576,8 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
308
576
|
signal,
|
|
309
577
|
traceId,
|
|
310
578
|
toolChoiceRequired,
|
|
579
|
+
reasoningEffort: currentReasoningEffort,
|
|
580
|
+
eagerSettleStreaming: true,
|
|
311
581
|
});
|
|
312
582
|
// Track usage from the latest API call
|
|
313
583
|
if (result.usage)
|
|
@@ -331,52 +601,76 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
331
601
|
if (reasoningItems.length > 0) {
|
|
332
602
|
msg._reasoning_items = reasoningItems;
|
|
333
603
|
}
|
|
604
|
+
// Store thinking blocks (Anthropic) on the assistant message for round-tripping
|
|
605
|
+
const thinkingItems = result.outputItems.filter((item) => "type" in item && (item.type === "thinking" || item.type === "redacted_thinking"));
|
|
606
|
+
if (thinkingItems.length > 0) {
|
|
607
|
+
msg._thinking_blocks = thinkingItems;
|
|
608
|
+
}
|
|
609
|
+
// Phase annotation for Codex provider
|
|
610
|
+
const hasPhaseAnnotation = providerRuntime.capabilities.has("phase-annotation");
|
|
611
|
+
const isSoleSettle = result.toolCalls.length === 1 && result.toolCalls[0].name === "settle";
|
|
612
|
+
if (hasPhaseAnnotation) {
|
|
613
|
+
msg.phase = isSoleSettle ? "settle" : "commentary";
|
|
614
|
+
}
|
|
334
615
|
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
|
-
// }
|
|
616
|
+
// No tool calls — accept response as-is.
|
|
617
|
+
// (Kick detection disabled; tool_choice: required + settle
|
|
618
|
+
// is the primary loop control. See src/heart/kicks.ts to re-enable.)
|
|
353
619
|
messages.push(msg);
|
|
354
620
|
done = true;
|
|
355
621
|
}
|
|
356
622
|
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)
|
|
623
|
+
// Check for settle sole call: intercept before tool execution
|
|
624
|
+
if (isSoleSettle) {
|
|
625
|
+
/* v8 ignore next -- defensive: JSON.parse catch for malformed settle args @preserve */
|
|
626
|
+
const settleArgs = (() => { try {
|
|
627
|
+
return JSON.parse(result.toolCalls[0].arguments);
|
|
372
628
|
}
|
|
373
629
|
catch {
|
|
374
|
-
|
|
630
|
+
return {};
|
|
631
|
+
} })();
|
|
632
|
+
callbacks.onToolStart("settle", settleArgs);
|
|
633
|
+
// Inner dialog attention queue gate: reject settle if items remain
|
|
634
|
+
const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
|
|
635
|
+
if (isInnerDialog && attentionQueue && attentionQueue.length > 0) {
|
|
636
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
|
|
637
|
+
callbacks.onClearText?.();
|
|
638
|
+
messages.push(msg);
|
|
639
|
+
const gateMessage = "you're holding thoughts someone is waiting for — surface them before you settle.";
|
|
640
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
|
|
641
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
|
|
642
|
+
continue;
|
|
643
|
+
}
|
|
644
|
+
// Extract answer from the tool call arguments.
|
|
645
|
+
// Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
|
|
646
|
+
const { answer, intent } = parseSettlePayload(result.toolCalls[0].arguments);
|
|
647
|
+
// Inner dialog settle: no CompletionMetadata, "(settled)" ack
|
|
648
|
+
if (isInnerDialog) {
|
|
649
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
|
|
650
|
+
messages.push(msg);
|
|
651
|
+
const settled = "(settled)";
|
|
652
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: settled });
|
|
653
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, settled);
|
|
654
|
+
outcome = "settled";
|
|
655
|
+
done = true;
|
|
656
|
+
continue;
|
|
375
657
|
}
|
|
376
|
-
|
|
377
|
-
|
|
658
|
+
const retryError = getSettleRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp, options?.delegationDecision, sawSendMessageSelf, sawPonder, sawQuerySession, options?.currentObligation ?? null, options?.activeWorkFrame?.inner?.job, sawExternalStateQuery);
|
|
659
|
+
const deliveredAnswer = answer;
|
|
660
|
+
const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
|
|
661
|
+
const validTerminalIntent = intent === "complete" || intent === "blocked";
|
|
662
|
+
const validClosure = deliveredAnswer != null
|
|
663
|
+
&& !retryError
|
|
664
|
+
&& (!mustResolveBeforeHandoffActive || validDirectReply || validTerminalIntent);
|
|
665
|
+
if (validClosure) {
|
|
666
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
|
|
667
|
+
completion = {
|
|
668
|
+
answer: deliveredAnswer,
|
|
669
|
+
intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
|
|
670
|
+
};
|
|
671
|
+
if (result.settleStreamed) {
|
|
378
672
|
// The streaming layer already parsed and emitted the answer
|
|
379
|
-
// progressively via
|
|
673
|
+
// progressively via SettleParser. Skip clearing and
|
|
380
674
|
// re-emitting to avoid double-delivery.
|
|
381
675
|
}
|
|
382
676
|
else {
|
|
@@ -384,37 +678,229 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
384
678
|
callbacks.onClearText?.();
|
|
385
679
|
// Emit the answer through the callback pipeline so channels receive it.
|
|
386
680
|
// Never truncate -- channel adapters handle splitting long messages.
|
|
387
|
-
callbacks.onTextChunk(
|
|
681
|
+
callbacks.onTextChunk(deliveredAnswer);
|
|
388
682
|
}
|
|
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
683
|
messages.push(msg);
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
684
|
+
if (validDirectReply) {
|
|
685
|
+
const resumeWork = "direct reply delivered. resume the unresolved obligation now and keep working until you can finish or clearly report that you are blocked.";
|
|
686
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: resumeWork });
|
|
687
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, resumeWork);
|
|
688
|
+
}
|
|
689
|
+
else {
|
|
690
|
+
const delivered = "(delivered)";
|
|
691
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
|
|
692
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
|
|
693
|
+
outcome = intent === "blocked" ? "blocked" : "settled";
|
|
694
|
+
done = true;
|
|
695
|
+
}
|
|
395
696
|
}
|
|
396
697
|
else {
|
|
397
|
-
// Answer is undefined -- the model's
|
|
698
|
+
// Answer is undefined -- the model's settle was incomplete or
|
|
398
699
|
// malformed. Clear any partial streamed text or noise, then push the
|
|
399
700
|
// assistant msg + error tool result and let the model try again.
|
|
701
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
|
|
702
|
+
callbacks.onClearText?.();
|
|
703
|
+
messages.push(msg);
|
|
704
|
+
const toolRetryMessage = retryError
|
|
705
|
+
?? "your settle was incomplete or malformed. call settle again with your complete response.";
|
|
706
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: toolRetryMessage });
|
|
707
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, toolRetryMessage);
|
|
708
|
+
}
|
|
709
|
+
continue;
|
|
710
|
+
}
|
|
711
|
+
// Check for observe sole call: intercept before tool execution
|
|
712
|
+
const isSoleObserve = result.toolCalls.length === 1 && result.toolCalls[0].name === "observe";
|
|
713
|
+
if (isSoleObserve) {
|
|
714
|
+
/* v8 ignore next -- defensive: JSON.parse catch for malformed observe args @preserve */
|
|
715
|
+
const observeArgs = (() => { try {
|
|
716
|
+
return JSON.parse(result.toolCalls[0].arguments);
|
|
717
|
+
}
|
|
718
|
+
catch {
|
|
719
|
+
return {};
|
|
720
|
+
} })();
|
|
721
|
+
let reason;
|
|
722
|
+
if (typeof observeArgs?.reason === "string")
|
|
723
|
+
reason = observeArgs.reason;
|
|
724
|
+
callbacks.onToolStart("observe", observeArgs);
|
|
725
|
+
(0, runtime_1.emitNervesEvent)({
|
|
726
|
+
component: "engine",
|
|
727
|
+
event: "engine.observe",
|
|
728
|
+
message: "agent declined to respond in group chat",
|
|
729
|
+
meta: { ...(reason ? { reason } : {}) },
|
|
730
|
+
});
|
|
731
|
+
callbacks.onToolEnd("observe", (0, tools_1.summarizeArgs)("observe", observeArgs), true);
|
|
732
|
+
messages.push(msg);
|
|
733
|
+
const silenced = "(silenced)";
|
|
734
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: silenced });
|
|
735
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, silenced);
|
|
736
|
+
outcome = "observed";
|
|
737
|
+
done = true;
|
|
738
|
+
continue;
|
|
739
|
+
}
|
|
740
|
+
// Check for ponder sole call: intercept before tool execution
|
|
741
|
+
const isSolePonder = result.toolCalls.length === 1 && result.toolCalls[0].name === "ponder";
|
|
742
|
+
if (isSolePonder) {
|
|
743
|
+
let parsedArgs = {};
|
|
744
|
+
try {
|
|
745
|
+
parsedArgs = JSON.parse(result.toolCalls[0].arguments);
|
|
746
|
+
}
|
|
747
|
+
catch { /* ignore */ }
|
|
748
|
+
callbacks.onToolStart("ponder", parsedArgs);
|
|
749
|
+
const currentSession = options?.toolContext?.currentSession;
|
|
750
|
+
const isInnerChannel = currentSession?.friendId === "self" && currentSession?.channel === "inner";
|
|
751
|
+
if (!isInnerChannel) {
|
|
752
|
+
// Outer session: thought and say are required
|
|
753
|
+
const thought = typeof parsedArgs.thought === "string" ? parsedArgs.thought : undefined;
|
|
754
|
+
const say = typeof parsedArgs.say === "string" ? parsedArgs.say : undefined;
|
|
755
|
+
if (!thought || !say) {
|
|
756
|
+
callbacks.onToolEnd("ponder", (0, tools_1.summarizeArgs)("ponder", parsedArgs), false);
|
|
757
|
+
messages.push(msg);
|
|
758
|
+
const errorMsg = "ponder requires both thought and say when called from a conversation. thought is what needs more thinking; say is what you tell them before going quiet.";
|
|
759
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: errorMsg });
|
|
760
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, errorMsg);
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
// Emit outward say text
|
|
400
764
|
callbacks.onClearText?.();
|
|
401
|
-
|
|
765
|
+
callbacks.onTextChunk(say);
|
|
766
|
+
// Build handoff packet and enqueue
|
|
767
|
+
const handoffContent = buildPonderHandoffPacket({
|
|
768
|
+
topic: thought,
|
|
769
|
+
mode: "reflect",
|
|
770
|
+
delegationDecision: options?.delegationDecision,
|
|
771
|
+
currentSession: currentSession ?? null,
|
|
772
|
+
currentObligation: options?.currentObligation ?? null,
|
|
773
|
+
outwardClosureRequired: options?.delegationDecision?.outwardClosureRequired ?? false,
|
|
774
|
+
});
|
|
775
|
+
const pendingDir = (0, pending_1.getInnerDialogPendingDir)((0, identity_2.getAgentName)());
|
|
776
|
+
// Create obligation FIRST so we can attach its ID to the pending message
|
|
777
|
+
let createdObligationId;
|
|
778
|
+
if (currentSession) {
|
|
779
|
+
try {
|
|
780
|
+
const obligation = (0, obligations_1.createObligation)((0, identity_2.getAgentRoot)(), {
|
|
781
|
+
origin: {
|
|
782
|
+
friendId: currentSession.friendId,
|
|
783
|
+
channel: currentSession.channel,
|
|
784
|
+
key: currentSession.key,
|
|
785
|
+
},
|
|
786
|
+
content: thought,
|
|
787
|
+
});
|
|
788
|
+
createdObligationId = obligation.id;
|
|
789
|
+
}
|
|
790
|
+
catch {
|
|
791
|
+
/* v8 ignore next -- defensive: obligation store write failure should not break ponder @preserve */
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
const envelope = {
|
|
795
|
+
from: (0, identity_2.getAgentName)(),
|
|
796
|
+
friendId: "self",
|
|
797
|
+
channel: "inner",
|
|
798
|
+
key: "dialog",
|
|
799
|
+
content: handoffContent,
|
|
800
|
+
timestamp: Date.now(),
|
|
801
|
+
...(currentSession ? {
|
|
802
|
+
delegatedFrom: {
|
|
803
|
+
friendId: currentSession.friendId,
|
|
804
|
+
channel: currentSession.channel,
|
|
805
|
+
key: currentSession.key,
|
|
806
|
+
},
|
|
807
|
+
obligationStatus: "pending",
|
|
808
|
+
/* v8 ignore next -- defensive: createdObligationId is undefined only when obligation store write fails @preserve */
|
|
809
|
+
...(createdObligationId ? { obligationId: createdObligationId } : {}),
|
|
810
|
+
} : {}),
|
|
811
|
+
};
|
|
812
|
+
(0, pending_1.queuePendingMessage)(pendingDir, envelope);
|
|
813
|
+
try {
|
|
814
|
+
await (0, socket_client_1.requestInnerWake)((0, identity_2.getAgentName)());
|
|
815
|
+
}
|
|
816
|
+
catch { /* daemon may not be running */ }
|
|
817
|
+
callbacks.onToolEnd("ponder", (0, tools_1.summarizeArgs)("ponder", parsedArgs), true);
|
|
818
|
+
sawPonder = true;
|
|
819
|
+
messages.push(msg);
|
|
820
|
+
const ack = "(pondering)";
|
|
821
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
|
|
822
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
|
|
823
|
+
(0, runtime_1.emitNervesEvent)({
|
|
824
|
+
component: "engine",
|
|
825
|
+
event: "engine.pondered",
|
|
826
|
+
message: "pondering",
|
|
827
|
+
meta: { hasThought: true, hasSay: true, contentSnippet: thought.slice(0, 80) },
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
else {
|
|
831
|
+
// Inner dialog: parameterless, enqueue synthetic pending WITHOUT delegatedFrom
|
|
832
|
+
const pendingDir = (0, pending_1.getInnerDialogPendingDir)((0, identity_2.getAgentName)());
|
|
833
|
+
const envelope = {
|
|
834
|
+
from: (0, identity_2.getAgentName)(),
|
|
835
|
+
friendId: "self",
|
|
836
|
+
channel: "inner",
|
|
837
|
+
key: "dialog",
|
|
838
|
+
content: "continuing to think...",
|
|
839
|
+
timestamp: Date.now(),
|
|
840
|
+
};
|
|
841
|
+
(0, pending_1.queuePendingMessage)(pendingDir, envelope);
|
|
842
|
+
callbacks.onToolEnd("ponder", (0, tools_1.summarizeArgs)("ponder", parsedArgs), true);
|
|
843
|
+
sawPonder = true;
|
|
844
|
+
messages.push(msg);
|
|
845
|
+
const ack = "(pondering)";
|
|
846
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
|
|
847
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
|
|
848
|
+
(0, runtime_1.emitNervesEvent)({
|
|
849
|
+
component: "engine",
|
|
850
|
+
event: "engine.pondered",
|
|
851
|
+
message: "pondering from inner dialog",
|
|
852
|
+
meta: { inner: true },
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
outcome = "pondered";
|
|
856
|
+
done = true;
|
|
857
|
+
continue;
|
|
858
|
+
}
|
|
859
|
+
// Check for rest sole call: intercept before tool execution
|
|
860
|
+
const isSoleRest = result.toolCalls.length === 1 && result.toolCalls[0].name === "rest";
|
|
861
|
+
if (isSoleRest) {
|
|
862
|
+
const restArgs = (() => { try {
|
|
863
|
+
return JSON.parse(result.toolCalls[0].arguments);
|
|
864
|
+
}
|
|
865
|
+
catch {
|
|
866
|
+
return {};
|
|
867
|
+
} })();
|
|
868
|
+
callbacks.onToolStart("rest", restArgs);
|
|
869
|
+
// Attention queue gate: reject rest if items remain
|
|
870
|
+
const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
|
|
871
|
+
if (attentionQueue && attentionQueue.length > 0) {
|
|
872
|
+
callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), false);
|
|
402
873
|
messages.push(msg);
|
|
403
|
-
|
|
404
|
-
|
|
874
|
+
const gateMessage = "you're holding thoughts someone is waiting for — surface them before you rest.";
|
|
875
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
|
|
876
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
|
|
877
|
+
continue;
|
|
405
878
|
}
|
|
879
|
+
callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), true);
|
|
880
|
+
messages.push(msg);
|
|
881
|
+
const ack = "(resting)";
|
|
882
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
|
|
883
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
|
|
884
|
+
(0, runtime_1.emitNervesEvent)({
|
|
885
|
+
component: "engine",
|
|
886
|
+
event: "engine.rested",
|
|
887
|
+
message: "resting until next heartbeat",
|
|
888
|
+
meta: {},
|
|
889
|
+
});
|
|
890
|
+
outcome = "rested";
|
|
891
|
+
done = true;
|
|
406
892
|
continue;
|
|
407
893
|
}
|
|
408
894
|
messages.push(msg);
|
|
409
|
-
//
|
|
895
|
+
// Execute tools (sole-call tools in mixed calls are rejected inline)
|
|
410
896
|
for (const tc of result.toolCalls) {
|
|
411
897
|
if (signal?.aborted)
|
|
412
898
|
break;
|
|
413
|
-
//
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
messages.push({ role: "tool", tool_call_id: tc.id, content:
|
|
417
|
-
providerRuntime.appendToolOutput(tc.id,
|
|
899
|
+
// Reject sole-call tools when mixed with other tool calls
|
|
900
|
+
const soleCallRejection = SOLE_CALL_REJECTION[tc.name];
|
|
901
|
+
if (soleCallRejection) {
|
|
902
|
+
messages.push({ role: "tool", tool_call_id: tc.id, content: soleCallRejection });
|
|
903
|
+
providerRuntime.appendToolOutput(tc.id, soleCallRejection);
|
|
418
904
|
continue;
|
|
419
905
|
}
|
|
420
906
|
let args = {};
|
|
@@ -424,7 +910,28 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
424
910
|
catch {
|
|
425
911
|
/* ignore */
|
|
426
912
|
}
|
|
913
|
+
if (tc.name === "send_message" && args.friendId === "self") {
|
|
914
|
+
sawSendMessageSelf = true;
|
|
915
|
+
}
|
|
916
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
917
|
+
if (tc.name === "query_session")
|
|
918
|
+
sawQuerySession = true;
|
|
919
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
920
|
+
if (tc.name === "bridge_manage")
|
|
921
|
+
sawBridgeManage = true;
|
|
922
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
923
|
+
if (isExternalStateQuery(tc.name, args))
|
|
924
|
+
sawExternalStateQuery = true;
|
|
427
925
|
const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
|
|
926
|
+
const toolLoop = (0, tool_loop_1.detectToolLoop)(toolLoopState, tc.name, args);
|
|
927
|
+
if (toolLoop.stuck) {
|
|
928
|
+
const rejection = `loop guard: ${toolLoop.message}`;
|
|
929
|
+
callbacks.onToolStart(tc.name, args);
|
|
930
|
+
callbacks.onToolEnd(tc.name, argSummary, false);
|
|
931
|
+
messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
|
|
932
|
+
providerRuntime.appendToolOutput(tc.id, rejection);
|
|
933
|
+
continue;
|
|
934
|
+
}
|
|
428
935
|
// Confirmation check for mutate tools
|
|
429
936
|
if ((0, tools_1.isConfirmationRequired)(tc.name) && !options?.skipConfirmation) {
|
|
430
937
|
let decision = "denied";
|
|
@@ -445,13 +952,14 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
445
952
|
let success;
|
|
446
953
|
try {
|
|
447
954
|
const execToolFn = options?.execTool ?? tools_1.execTool;
|
|
448
|
-
toolResult = await execToolFn(tc.name, args, options?.toolContext);
|
|
955
|
+
toolResult = await execToolFn(tc.name, args, augmentedToolContext ?? options?.toolContext);
|
|
449
956
|
success = true;
|
|
450
957
|
}
|
|
451
958
|
catch (e) {
|
|
452
959
|
toolResult = `error: ${e}`;
|
|
453
960
|
success = false;
|
|
454
961
|
}
|
|
962
|
+
(0, tool_loop_1.recordToolOutcome)(toolLoopState, tc.name, args, toolResult, success);
|
|
455
963
|
callbacks.onToolEnd(tc.name, argSummary, success);
|
|
456
964
|
messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
|
|
457
965
|
providerRuntime.appendToolOutput(tc.id, toolResult);
|
|
@@ -462,6 +970,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
462
970
|
// Abort is not an error — just stop cleanly
|
|
463
971
|
if (signal?.aborted) {
|
|
464
972
|
stripLastToolCalls(messages);
|
|
973
|
+
outcome = "aborted";
|
|
465
974
|
break;
|
|
466
975
|
}
|
|
467
976
|
// Context overflow: trim aggressively and retry once
|
|
@@ -479,7 +988,16 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
479
988
|
if (isTransientError(e) && retryCount < MAX_RETRIES) {
|
|
480
989
|
retryCount++;
|
|
481
990
|
const delay = RETRY_BASE_MS * Math.pow(2, retryCount - 1);
|
|
482
|
-
|
|
991
|
+
let classification;
|
|
992
|
+
try {
|
|
993
|
+
classification = providerRuntime.classifyError(e instanceof Error ? e : /* v8 ignore next -- defensive: errors are always Error instances @preserve */ new Error(String(e)));
|
|
994
|
+
}
|
|
995
|
+
catch {
|
|
996
|
+
/* v8 ignore next -- defensive: classifyError should not throw @preserve */
|
|
997
|
+
classification = classifyTransientError(e);
|
|
998
|
+
}
|
|
999
|
+
/* v8 ignore next -- defensive: all classifications have labels @preserve */
|
|
1000
|
+
const cause = TRANSIENT_RETRY_LABELS[classification] ?? classification;
|
|
483
1001
|
callbacks.onError(new Error(`${cause}, retrying in ${delay / 1000}s (${retryCount}/${MAX_RETRIES})...`), "transient");
|
|
484
1002
|
// Wait with abort support
|
|
485
1003
|
const aborted = await new Promise((resolve) => {
|
|
@@ -496,21 +1014,31 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
496
1014
|
});
|
|
497
1015
|
if (aborted) {
|
|
498
1016
|
stripLastToolCalls(messages);
|
|
1017
|
+
outcome = "aborted";
|
|
499
1018
|
break;
|
|
500
1019
|
}
|
|
501
1020
|
providerRuntime.resetTurnState(messages);
|
|
502
1021
|
continue;
|
|
503
1022
|
}
|
|
504
|
-
|
|
1023
|
+
terminalError = e instanceof Error ? e : new Error(String(e));
|
|
1024
|
+
try {
|
|
1025
|
+
terminalErrorClassification = providerRuntime.classifyError(terminalError);
|
|
1026
|
+
}
|
|
1027
|
+
catch {
|
|
1028
|
+
/* v8 ignore next -- defensive: classifyError should not throw @preserve */
|
|
1029
|
+
terminalErrorClassification = "unknown";
|
|
1030
|
+
}
|
|
1031
|
+
callbacks.onError(terminalError, "terminal");
|
|
505
1032
|
(0, runtime_1.emitNervesEvent)({
|
|
506
1033
|
level: "error",
|
|
507
1034
|
event: "engine.error",
|
|
508
1035
|
trace_id: traceId,
|
|
509
1036
|
component: "engine",
|
|
510
|
-
message:
|
|
511
|
-
meta: {},
|
|
1037
|
+
message: terminalError.message,
|
|
1038
|
+
meta: { errorClassification: terminalErrorClassification },
|
|
512
1039
|
});
|
|
513
1040
|
stripLastToolCalls(messages);
|
|
1041
|
+
outcome = "errored";
|
|
514
1042
|
done = true;
|
|
515
1043
|
}
|
|
516
1044
|
}
|
|
@@ -519,7 +1047,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
519
1047
|
trace_id: traceId,
|
|
520
1048
|
component: "engine",
|
|
521
1049
|
message: "runAgent turn completed",
|
|
522
|
-
meta: { done },
|
|
1050
|
+
meta: { done, sawPonder, sawQuerySession, sawBridgeManage },
|
|
523
1051
|
});
|
|
524
|
-
return {
|
|
1052
|
+
return {
|
|
1053
|
+
usage: lastUsage,
|
|
1054
|
+
outcome,
|
|
1055
|
+
completion,
|
|
1056
|
+
...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
|
|
1057
|
+
};
|
|
525
1058
|
}
|