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