@ouro.bot/cli 0.1.0-alpha.48 → 0.1.0-alpha.480
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 +132 -19
- package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +3 -2
- package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +2 -2
- package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
- package/changelog.json +3061 -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/packets.js +193 -0
- package/dist/arc/presence.js +185 -0
- package/dist/arc/task-lifecycle.js +65 -0
- package/dist/heart/active-work.js +857 -0
- package/dist/heart/agent-entry.js +58 -3
- package/dist/heart/attachments/image-normalize.js +194 -0
- package/dist/heart/attachments/materialize.js +97 -0
- package/dist/heart/attachments/originals.js +88 -0
- package/dist/heart/attachments/render.js +29 -0
- package/dist/heart/attachments/sources/adapter.js +2 -0
- package/dist/heart/attachments/sources/bluebubbles.js +156 -0
- package/dist/heart/attachments/sources/cli-local-file.js +78 -0
- package/dist/heart/attachments/sources/index.js +16 -0
- package/dist/heart/attachments/store.js +103 -0
- package/dist/heart/attachments/types.js +93 -0
- package/dist/heart/auth/auth-flow.js +426 -0
- package/dist/heart/background-operations.js +234 -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 +168 -0
- package/dist/heart/commitments.js +111 -0
- package/dist/heart/config-registry.js +304 -0
- package/dist/heart/config.js +110 -128
- package/dist/heart/core.js +745 -227
- package/dist/heart/cross-chat-delivery.js +131 -0
- package/dist/heart/daemon/agent-config-check.js +490 -0
- package/dist/heart/daemon/agent-discovery.js +79 -3
- package/dist/heart/daemon/agent-service.js +360 -0
- package/dist/heart/daemon/agentic-repair.js +216 -0
- package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
- package/dist/heart/daemon/cadence.js +70 -0
- package/dist/heart/daemon/cli-defaults.js +640 -0
- package/dist/heart/daemon/cli-exec.js +6933 -0
- package/dist/heart/daemon/cli-help.js +487 -0
- package/dist/heart/daemon/cli-parse.js +1527 -0
- package/dist/heart/daemon/cli-render-doctor.js +57 -0
- package/dist/heart/daemon/cli-render.js +561 -0
- package/dist/heart/daemon/cli-types.js +8 -0
- package/dist/heart/daemon/connect-bay.js +323 -0
- package/dist/heart/daemon/daemon-cli.js +29 -1616
- package/dist/heart/daemon/daemon-entry.js +345 -3
- package/dist/heart/daemon/daemon-health.js +141 -0
- package/dist/heart/daemon/daemon-runtime-sync.js +190 -12
- package/dist/heart/daemon/daemon-tombstone.js +236 -0
- package/dist/heart/daemon/daemon.js +677 -58
- package/dist/heart/daemon/dns-workflow.js +394 -0
- package/dist/heart/daemon/doctor-types.js +8 -0
- package/dist/heart/daemon/doctor.js +486 -0
- package/dist/heart/daemon/health-monitor.js +92 -1
- 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/http-health-probe.js +80 -0
- package/dist/heart/daemon/human-command-screens.js +234 -0
- package/dist/heart/daemon/human-readiness.js +114 -0
- package/dist/heart/daemon/inner-status.js +89 -0
- package/dist/heart/daemon/interactive-repair.js +394 -0
- package/dist/heart/daemon/launchd.js +25 -5
- package/dist/heart/daemon/log-tailer.js +82 -12
- package/dist/heart/daemon/logs-prune.js +110 -0
- package/dist/heart/daemon/message-router.js +2 -2
- package/dist/heart/daemon/os-cron-deps.js +134 -0
- package/dist/heart/daemon/ouro-bot-entry.js +4 -2
- package/dist/heart/daemon/ouro-entry.js +3 -1
- package/dist/heart/daemon/process-manager.js +214 -0
- package/dist/heart/daemon/provider-discovery.js +137 -0
- package/dist/heart/daemon/provider-ping-progress.js +83 -0
- package/dist/heart/daemon/pulse.js +475 -0
- package/dist/heart/daemon/readiness-repair.js +365 -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 +73 -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 +178 -37
- 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 +109 -4
- package/dist/heart/daemon/stale-bundle-prune.js +96 -0
- package/dist/heart/daemon/startup-tui.js +264 -0
- package/dist/heart/daemon/task-scheduler.js +3 -25
- package/dist/heart/daemon/terminal-ui.js +499 -0
- package/dist/heart/daemon/thoughts.js +149 -10
- package/dist/heart/daemon/up-progress.js +366 -0
- package/dist/heart/daemon/vault-items.js +56 -0
- package/dist/heart/delegation.js +62 -0
- package/dist/heart/habits/habit-migration.js +189 -0
- package/dist/heart/habits/habit-parser.js +140 -0
- package/dist/heart/habits/habit-runtime-state.js +100 -0
- package/dist/heart/habits/habit-scheduler.js +372 -0
- package/dist/heart/{daemon → hatch}/hatch-flow.js +52 -117
- package/dist/heart/{daemon → hatch}/hatch-specialist.js +3 -3
- package/dist/heart/{daemon → hatch}/specialist-prompt.js +12 -9
- package/dist/heart/{daemon → hatch}/specialist-tools.js +35 -12
- package/dist/heart/identity.js +201 -66
- package/dist/heart/kept-notes.js +357 -0
- package/dist/heart/kicks.js +1 -1
- package/dist/heart/machine-identity.js +161 -0
- package/dist/heart/mcp/mcp-server.js +653 -0
- package/dist/heart/migrate-config.js +100 -0
- package/dist/heart/model-capabilities.js +59 -0
- package/dist/heart/outlook/outlook-http-hooks.js +66 -0
- package/dist/heart/outlook/outlook-http-response.js +7 -0
- package/dist/heart/outlook/outlook-http-routes.js +244 -0
- package/dist/heart/outlook/outlook-http-static.js +99 -0
- package/dist/heart/outlook/outlook-http-transport.js +116 -0
- package/dist/heart/outlook/outlook-http.js +99 -0
- package/dist/heart/outlook/outlook-read.js +31 -0
- package/dist/heart/outlook/outlook-types.js +27 -0
- package/dist/heart/outlook/outlook-view.js +195 -0
- package/dist/heart/outlook/readers/agent-machine.js +359 -0
- package/dist/heart/outlook/readers/continuity-readers.js +332 -0
- package/dist/heart/outlook/readers/mail.js +362 -0
- package/dist/heart/outlook/readers/runtime-readers.js +644 -0
- package/dist/heart/outlook/readers/sessions.js +232 -0
- package/dist/heart/outlook/readers/shared.js +111 -0
- package/dist/heart/platform.js +81 -0
- package/dist/heart/progress-story.js +42 -0
- package/dist/heart/provider-attempt.js +134 -0
- package/dist/heart/provider-binding-resolver.js +255 -0
- package/dist/heart/provider-credentials.js +424 -0
- package/dist/heart/provider-failover.js +266 -0
- package/dist/heart/provider-models.js +81 -0
- package/dist/heart/provider-ping.js +262 -0
- package/dist/heart/provider-state.js +216 -0
- package/dist/heart/provider-visibility.js +188 -0
- package/dist/heart/providers/anthropic-token.js +131 -0
- package/dist/heart/providers/anthropic.js +193 -55
- package/dist/heart/providers/azure.js +103 -12
- package/dist/heart/providers/error-classification.js +63 -0
- package/dist/heart/providers/github-copilot.js +145 -0
- package/dist/heart/providers/minimax-vlm.js +189 -0
- package/dist/heart/providers/minimax.js +29 -7
- package/dist/heart/providers/openai-codex.js +62 -38
- package/dist/heart/runtime-capability-check.js +170 -0
- package/dist/heart/runtime-credentials.js +260 -0
- package/dist/heart/sense-truth.js +11 -4
- package/dist/heart/session-activity.js +190 -0
- package/dist/heart/session-events.js +855 -0
- package/dist/heart/session-transcript.js +167 -0
- package/dist/heart/start-of-turn-packet.js +345 -0
- package/dist/heart/streaming.js +36 -27
- package/dist/heart/sync.js +332 -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-friction.js +55 -0
- package/dist/heart/tool-loop.js +200 -0
- package/dist/heart/turn-context.js +361 -0
- package/dist/heart/turn-coordinator.js +24 -1
- package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +1 -1
- package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
- package/dist/heart/versioning/ouro-path-installer.js +425 -0
- 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 +5 -1
- package/dist/heart/{daemon → versioning}/update-hooks.js +63 -59
- package/dist/mailroom/attention.js +167 -0
- package/dist/mailroom/autonomy.js +209 -0
- package/dist/mailroom/blob-store.js +558 -0
- package/dist/mailroom/core.js +658 -0
- package/dist/mailroom/entry.js +160 -0
- package/dist/mailroom/file-store.js +400 -0
- package/dist/mailroom/mbox-import.js +341 -0
- package/dist/mailroom/outbound.js +380 -0
- package/dist/mailroom/policy.js +263 -0
- package/dist/mailroom/reader.js +197 -0
- package/dist/mailroom/smtp-ingress.js +176 -0
- package/dist/mailroom/source-state.js +176 -0
- package/dist/mailroom/travel-extract.js +89 -0
- package/dist/mind/bundle-manifest.js +7 -1
- package/dist/mind/context.js +132 -93
- package/dist/mind/diary-integrity.js +60 -0
- package/dist/mind/{memory.js → diary.js} +74 -93
- package/dist/mind/embedding-provider.js +60 -0
- package/dist/mind/file-state.js +179 -0
- package/dist/mind/friends/channel.js +30 -0
- package/dist/mind/friends/group-context.js +144 -0
- package/dist/mind/friends/resolver.js +38 -1
- package/dist/mind/friends/store-file.js +39 -3
- package/dist/mind/friends/trust-explanation.js +74 -0
- package/dist/mind/friends/types.js +2 -2
- package/dist/mind/journal-index.js +161 -0
- package/dist/mind/note-search.js +268 -0
- package/dist/mind/obligation-steering.js +221 -0
- package/dist/mind/pending.js +66 -7
- package/dist/mind/prompt-refresh.js +3 -2
- package/dist/mind/prompt.js +978 -169
- package/dist/mind/provenance-trust.js +26 -0
- package/dist/mind/scrutiny.js +173 -0
- package/dist/nerves/cli-logging.js +7 -1
- package/dist/nerves/coverage/audit-rules.js +15 -6
- package/dist/nerves/coverage/audit.js +28 -2
- package/dist/nerves/coverage/cli.js +1 -1
- package/dist/nerves/coverage/contract.js +5 -5
- package/dist/nerves/coverage/file-completeness.js +84 -5
- package/dist/nerves/coverage/run-artifacts.js +1 -1
- package/dist/nerves/event-buffer.js +111 -0
- package/dist/nerves/index.js +224 -4
- package/dist/nerves/observation.js +20 -0
- package/dist/nerves/redact.js +79 -0
- package/dist/nerves/runtime.js +5 -1
- package/dist/outlook-ui/assets/index-BPr5vNuM.css +1 -0
- package/dist/outlook-ui/assets/index-CPfhbn13.js +61 -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 +774 -0
- package/dist/repertoire/bundle-templates.js +72 -0
- package/dist/repertoire/bw-installer.js +180 -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 +158 -9
- 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 +111 -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 +396 -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 +15 -24
- 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 +37 -4
- 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 +16 -78
- package/dist/repertoire/tool-results.js +29 -0
- package/dist/repertoire/tools-attachments.js +317 -0
- package/dist/repertoire/tools-base.js +44 -740
- package/dist/repertoire/tools-bluebubbles.js +1 -0
- package/dist/repertoire/tools-bridge.js +141 -0
- package/dist/repertoire/tools-bundle.js +984 -0
- package/dist/repertoire/tools-config.js +185 -0
- package/dist/repertoire/tools-continuity.js +248 -0
- package/dist/repertoire/tools-credential.js +381 -0
- package/dist/repertoire/tools-files.js +342 -0
- package/dist/repertoire/tools-flight.js +224 -0
- package/dist/repertoire/tools-flow.js +105 -0
- package/dist/repertoire/tools-github.js +1 -7
- package/dist/repertoire/tools-mail.js +896 -0
- package/dist/repertoire/tools-notes.js +376 -0
- package/dist/repertoire/tools-session.js +746 -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 +9 -39
- package/dist/repertoire/tools-travel.js +125 -0
- package/dist/repertoire/tools-user-profile.js +144 -0
- package/dist/repertoire/tools-vault.js +40 -0
- package/dist/repertoire/tools.js +144 -113
- package/dist/repertoire/travel-api-client.js +360 -0
- package/dist/repertoire/user-profile.js +131 -0
- package/dist/repertoire/vault-setup.js +246 -0
- package/dist/repertoire/vault-unlock.js +561 -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 +116 -0
- package/dist/senses/bluebubbles/attachment-cache.js +53 -0
- package/dist/senses/bluebubbles/attachment-download.js +137 -0
- package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +219 -18
- package/dist/senses/bluebubbles/entry.js +73 -0
- package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +7 -3
- package/dist/senses/{bluebubbles.js → bluebubbles/index.js} +705 -116
- package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +121 -70
- package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +33 -12
- package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +3 -3
- package/dist/senses/bluebubbles/replay.js +129 -0
- package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +2 -2
- package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
- package/dist/senses/cli/bracketed-paste.js +82 -0
- package/dist/senses/cli/image-paste.js +287 -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 +605 -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 +60 -8
- package/dist/senses/cli-layout.js +187 -0
- package/dist/senses/cli.js +516 -211
- package/dist/senses/commands.js +66 -3
- package/dist/senses/habit-turn-message.js +108 -0
- package/dist/senses/inner-dialog-worker.js +97 -17
- package/dist/senses/inner-dialog.js +404 -14
- package/dist/senses/mail-entry.js +66 -0
- package/dist/senses/mail.js +232 -0
- package/dist/senses/pipeline.js +533 -72
- package/dist/senses/proactive-content-guard.js +51 -0
- package/dist/senses/shared-turn.js +205 -0
- package/dist/senses/surface-tool.js +68 -0
- package/dist/senses/teams-entry.js +60 -8
- package/dist/senses/teams.js +413 -163
- package/dist/senses/trust-gate.js +5 -5
- package/package.json +37 -7
- package/skills/agent-commerce.md +106 -0
- package/skills/browser-navigation.md +117 -0
- package/skills/commerce-setup-guide.md +116 -0
- package/skills/commerce-setup.md +84 -0
- package/skills/configure-dev-tools.md +101 -0
- package/skills/travel-planning.md +138 -0
- package/dist/heart/daemon/ouro-path-installer.js +0 -178
- package/dist/heart/daemon/subagent-installer.js +0 -166
- package/dist/mind/associative-recall.js +0 -209
- package/dist/senses/bluebubbles-entry.js +0 -13
- package/dist/senses/debug-activity.js +0 -127
- package/subagents/README.md +0 -86
- package/subagents/work-doer.md +0 -237
- package/subagents/work-merger.md +0 -618
- package/subagents/work-planner.md +0 -390
- /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-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,94 +1,159 @@
|
|
|
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.isTransientError = isTransientError;
|
|
13
|
-
exports.classifyTransientError = classifyTransientError;
|
|
14
13
|
exports.runAgent = runAgent;
|
|
15
14
|
const config_1 = require("./config");
|
|
16
15
|
const identity_1 = require("./identity");
|
|
17
16
|
const tools_1 = require("../repertoire/tools");
|
|
18
17
|
const channel_1 = require("../mind/friends/channel");
|
|
18
|
+
const tools_2 = require("../repertoire/tools");
|
|
19
19
|
const runtime_1 = require("../nerves/runtime");
|
|
20
20
|
const context_1 = require("../mind/context");
|
|
21
21
|
const prompt_1 = require("../mind/prompt");
|
|
22
|
-
const
|
|
22
|
+
const kept_notes_1 = require("./kept-notes");
|
|
23
23
|
const anthropic_1 = require("./providers/anthropic");
|
|
24
24
|
const azure_1 = require("./providers/azure");
|
|
25
25
|
const minimax_1 = require("./providers/minimax");
|
|
26
26
|
const openai_codex_1 = require("./providers/openai-codex");
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
27
|
+
const github_copilot_1 = require("./providers/github-copilot");
|
|
28
|
+
const identity_2 = require("./identity");
|
|
29
|
+
const socket_client_1 = require("./daemon/socket-client");
|
|
30
|
+
const obligations_1 = require("../arc/obligations");
|
|
31
|
+
const tool_loop_1 = require("./tool-loop");
|
|
32
|
+
const packets_1 = require("../arc/packets");
|
|
33
|
+
const tool_friction_1 = require("./tool-friction");
|
|
34
|
+
const provider_models_1 = require("./provider-models");
|
|
35
|
+
const provider_credentials_1 = require("./provider-credentials");
|
|
36
|
+
const provider_state_1 = require("./provider-state");
|
|
37
|
+
const provider_attempt_1 = require("./provider-attempt");
|
|
38
|
+
const _providerRuntimes = {
|
|
39
|
+
human: null,
|
|
40
|
+
agent: null,
|
|
41
|
+
};
|
|
42
|
+
function providerLaneForFacing(facing) {
|
|
43
|
+
return facing === "human" ? "outward" : "inner";
|
|
44
|
+
}
|
|
45
|
+
function resolveRuntimeProviderBinding(facing) {
|
|
46
|
+
const agentName = (0, identity_2.getAgentName)();
|
|
47
|
+
const lane = providerLaneForFacing(facing);
|
|
48
|
+
const stateResult = (0, provider_state_1.readProviderState)((0, identity_2.getAgentRoot)(agentName));
|
|
49
|
+
if (stateResult.ok) {
|
|
50
|
+
const binding = stateResult.state.lanes[lane];
|
|
51
|
+
return { lane, provider: binding.provider, model: binding.model };
|
|
52
|
+
}
|
|
53
|
+
if (stateResult.reason === "invalid") {
|
|
54
|
+
throw new Error(`provider state for ${agentName} is invalid at ${stateResult.statePath}: ${stateResult.error}`);
|
|
55
|
+
}
|
|
56
|
+
// First-run and SerpentGuide bootstrap path. Daemon startup normally
|
|
57
|
+
// bootstraps state/providers.json from agent.json before model calls.
|
|
58
|
+
const config = (0, identity_1.loadAgentConfig)();
|
|
59
|
+
const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
|
|
60
|
+
return { lane, provider: facingConfig.provider, model: facingConfig.model };
|
|
61
|
+
}
|
|
62
|
+
async function getProviderRuntimeFingerprint(facing) {
|
|
63
|
+
const agentName = (0, identity_2.getAgentName)();
|
|
64
|
+
const binding = resolveRuntimeProviderBinding(facing);
|
|
65
|
+
const credential = await (0, provider_credentials_1.readProviderCredentialRecord)(agentName, binding.provider);
|
|
66
|
+
if (!credential.ok) {
|
|
67
|
+
throw new Error([
|
|
68
|
+
`${binding.lane} provider ${binding.provider} (${binding.model}) has no credentials for ${agentName}.`,
|
|
69
|
+
credential.error,
|
|
70
|
+
`Run \`ouro auth --agent ${agentName} --provider ${binding.provider}\`.`,
|
|
71
|
+
].join("\n"));
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
binding,
|
|
75
|
+
fingerprint: JSON.stringify({
|
|
76
|
+
lane: binding.lane,
|
|
77
|
+
provider: binding.provider,
|
|
78
|
+
model: binding.model,
|
|
79
|
+
credentialRevision: credential.record.revision,
|
|
80
|
+
}),
|
|
81
|
+
credential: credential.record,
|
|
34
82
|
};
|
|
83
|
+
}
|
|
84
|
+
function createProviderRegistry() {
|
|
35
85
|
return {
|
|
36
|
-
resolve() {
|
|
37
|
-
const
|
|
38
|
-
|
|
86
|
+
resolve(provider, model, credential) {
|
|
87
|
+
const providerConfig = { ...credential.config, ...credential.credentials };
|
|
88
|
+
switch (provider) {
|
|
89
|
+
case "azure":
|
|
90
|
+
return (0, azure_1.createAzureProviderRuntime)(model, providerConfig);
|
|
91
|
+
case "anthropic":
|
|
92
|
+
return (0, anthropic_1.createAnthropicProviderRuntime)(model, providerConfig);
|
|
93
|
+
case "minimax":
|
|
94
|
+
return (0, minimax_1.createMinimaxProviderRuntime)(model, providerConfig);
|
|
95
|
+
case "openai-codex":
|
|
96
|
+
return (0, openai_codex_1.createOpenAICodexProviderRuntime)(model, providerConfig);
|
|
97
|
+
case "github-copilot":
|
|
98
|
+
return (0, github_copilot_1.createGithubCopilotProviderRuntime)(model, providerConfig);
|
|
99
|
+
}
|
|
39
100
|
},
|
|
40
101
|
};
|
|
41
102
|
}
|
|
42
|
-
function getProviderRuntime() {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
(0, runtime_1.emitNervesEvent)({
|
|
50
|
-
level: "error",
|
|
51
|
-
event: "engine.provider_init_error",
|
|
52
|
-
component: "engine",
|
|
53
|
-
message: msg,
|
|
54
|
-
meta: {},
|
|
55
|
-
});
|
|
56
|
-
// eslint-disable-next-line no-console -- pre-boot guard: provider init failure
|
|
57
|
-
console.error(`\n[fatal] ${msg}\n`);
|
|
58
|
-
process.exit(1);
|
|
59
|
-
throw new Error("unreachable");
|
|
60
|
-
}
|
|
61
|
-
if (!_providerRuntime) {
|
|
62
|
-
(0, runtime_1.emitNervesEvent)({
|
|
63
|
-
level: "error",
|
|
64
|
-
event: "engine.provider_init_error",
|
|
65
|
-
component: "engine",
|
|
66
|
-
message: "provider runtime could not be initialized.",
|
|
67
|
-
meta: {},
|
|
68
|
-
});
|
|
69
|
-
process.exit(1);
|
|
70
|
-
throw new Error("unreachable");
|
|
103
|
+
async function getProviderRuntime(facing = "human") {
|
|
104
|
+
try {
|
|
105
|
+
const { binding, fingerprint, credential } = await getProviderRuntimeFingerprint(facing);
|
|
106
|
+
const cached = _providerRuntimes[facing];
|
|
107
|
+
if (!cached || cached.fingerprint !== fingerprint) {
|
|
108
|
+
const runtime = createProviderRegistry().resolve(binding.provider, binding.model, credential);
|
|
109
|
+
_providerRuntimes[facing] = runtime ? { fingerprint, runtime } : null;
|
|
71
110
|
}
|
|
72
111
|
}
|
|
73
|
-
|
|
112
|
+
catch (error) {
|
|
113
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
114
|
+
(0, runtime_1.emitNervesEvent)({
|
|
115
|
+
level: "error",
|
|
116
|
+
event: "engine.provider_init_error",
|
|
117
|
+
component: "engine",
|
|
118
|
+
message: msg,
|
|
119
|
+
meta: {},
|
|
120
|
+
});
|
|
121
|
+
// eslint-disable-next-line no-console -- pre-boot guard: provider init failure
|
|
122
|
+
console.error(`\n[fatal] ${msg}\n`);
|
|
123
|
+
process.exit(1);
|
|
124
|
+
throw new Error("unreachable");
|
|
125
|
+
}
|
|
126
|
+
if (!_providerRuntimes[facing]) {
|
|
127
|
+
(0, runtime_1.emitNervesEvent)({
|
|
128
|
+
level: "error",
|
|
129
|
+
event: "engine.provider_init_error",
|
|
130
|
+
component: "engine",
|
|
131
|
+
message: "provider runtime could not be initialized.",
|
|
132
|
+
meta: {},
|
|
133
|
+
});
|
|
134
|
+
process.exit(1);
|
|
135
|
+
throw new Error("unreachable");
|
|
136
|
+
}
|
|
137
|
+
return _providerRuntimes[facing].runtime;
|
|
74
138
|
}
|
|
75
139
|
/**
|
|
76
|
-
* Clear the cached provider runtime so the next
|
|
77
|
-
*
|
|
78
|
-
*
|
|
140
|
+
* Clear the cached provider runtime so the next access re-creates it from
|
|
141
|
+
* current config. Runtime access also auto-refreshes when the selected
|
|
142
|
+
* provider fingerprint changes on disk.
|
|
79
143
|
*/
|
|
80
144
|
function resetProviderRuntime() {
|
|
81
|
-
|
|
145
|
+
_providerRuntimes.human = null;
|
|
146
|
+
_providerRuntimes.agent = null;
|
|
82
147
|
}
|
|
83
|
-
function getModel() {
|
|
84
|
-
return
|
|
148
|
+
function getModel(facing = "human") {
|
|
149
|
+
return resolveRuntimeProviderBinding(facing).model;
|
|
85
150
|
}
|
|
86
|
-
function getProvider() {
|
|
87
|
-
return
|
|
151
|
+
function getProvider(facing = "human") {
|
|
152
|
+
return resolveRuntimeProviderBinding(facing).provider;
|
|
88
153
|
}
|
|
89
|
-
function createSummarize() {
|
|
154
|
+
function createSummarize(facing = "human") {
|
|
90
155
|
return async (transcript, instruction) => {
|
|
91
|
-
const runtime = getProviderRuntime();
|
|
156
|
+
const runtime = await getProviderRuntime(facing);
|
|
92
157
|
const client = runtime.client;
|
|
93
158
|
const response = await client.chat.completions.create({
|
|
94
159
|
model: runtime.model,
|
|
@@ -101,32 +166,30 @@ function createSummarize() {
|
|
|
101
166
|
return response.choices?.[0]?.message?.content ?? transcript;
|
|
102
167
|
};
|
|
103
168
|
}
|
|
104
|
-
function getProviderDisplayLabel() {
|
|
105
|
-
const
|
|
169
|
+
function getProviderDisplayLabel(facing = "human") {
|
|
170
|
+
const binding = resolveRuntimeProviderBinding(facing);
|
|
171
|
+
const provider = binding.provider;
|
|
172
|
+
const model = binding.model || "unknown";
|
|
106
173
|
const providerLabelBuilders = {
|
|
107
|
-
azure: () =>
|
|
174
|
+
azure: () => {
|
|
175
|
+
return `azure openai (model: ${model})`;
|
|
176
|
+
},
|
|
108
177
|
anthropic: () => `anthropic (${model})`,
|
|
109
178
|
minimax: () => `minimax (${model})`,
|
|
110
179
|
"openai-codex": () => `openai codex (${model})`,
|
|
180
|
+
/* v8 ignore next -- branch: tested via display label unit test @preserve */
|
|
181
|
+
"github-copilot": () => `github copilot (${model})`,
|
|
111
182
|
};
|
|
112
|
-
return providerLabelBuilders[
|
|
183
|
+
return providerLabelBuilders[provider]();
|
|
113
184
|
}
|
|
114
|
-
//
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
Object.defineProperty(exports, "streamChatCompletion", { enumerable: true, get: function () { return streaming_1.streamChatCompletion; } });
|
|
123
|
-
Object.defineProperty(exports, "streamResponsesApi", { enumerable: true, get: function () { return streaming_1.streamResponsesApi; } });
|
|
124
|
-
Object.defineProperty(exports, "toResponsesInput", { enumerable: true, get: function () { return streaming_1.toResponsesInput; } });
|
|
125
|
-
Object.defineProperty(exports, "toResponsesTools", { enumerable: true, get: function () { return streaming_1.toResponsesTools; } });
|
|
126
|
-
// Re-export prompt functions for backward compat
|
|
127
|
-
var prompt_2 = require("../mind/prompt");
|
|
128
|
-
Object.defineProperty(exports, "buildSystem", { enumerable: true, get: function () { return prompt_2.buildSystem; } });
|
|
129
|
-
function parseFinalAnswerPayload(argumentsText) {
|
|
185
|
+
// Sole-call tools must be the only tool call in a turn. When they appear
|
|
186
|
+
// alongside other tools, the sole-call tool is rejected with this message.
|
|
187
|
+
const SOLE_CALL_REJECTION = {
|
|
188
|
+
settle: "rejected: settle must be the only tool call. finish your work first, then call settle alone.",
|
|
189
|
+
observe: "rejected: observe must be the only tool call. call observe alone when you want to stay silent.",
|
|
190
|
+
rest: "rejected: rest must be the only tool call. finish your work first, then call rest alone.",
|
|
191
|
+
};
|
|
192
|
+
function parseSettlePayload(argumentsText) {
|
|
130
193
|
try {
|
|
131
194
|
const parsed = JSON.parse(argumentsText);
|
|
132
195
|
if (typeof parsed === "string") {
|
|
@@ -146,18 +209,93 @@ function parseFinalAnswerPayload(argumentsText) {
|
|
|
146
209
|
return {};
|
|
147
210
|
}
|
|
148
211
|
}
|
|
149
|
-
function
|
|
212
|
+
function parsePonderPayload(argumentsText) {
|
|
213
|
+
try {
|
|
214
|
+
const parsed = JSON.parse(argumentsText);
|
|
215
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
return {};
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
function parseSuccessCriteria(raw) {
|
|
222
|
+
if (typeof raw !== "string")
|
|
223
|
+
return null;
|
|
224
|
+
const criteria = raw
|
|
225
|
+
.split("\n")
|
|
226
|
+
.map((line) => line.replace(/^\s*[-*]\s*/, "").trim())
|
|
227
|
+
.filter((line) => line.length > 0);
|
|
228
|
+
return criteria.length > 0 ? criteria : null;
|
|
229
|
+
}
|
|
230
|
+
function parsePacketPayload(raw) {
|
|
231
|
+
if (typeof raw !== "string")
|
|
232
|
+
return null;
|
|
233
|
+
try {
|
|
234
|
+
const parsed = JSON.parse(raw);
|
|
235
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
|
236
|
+
? parsed
|
|
237
|
+
: null;
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
function normalizeLegacyPonderArgs(parsed) {
|
|
244
|
+
if (typeof parsed.thought !== "string" || parsed.thought.trim().length === 0) {
|
|
245
|
+
return parsed;
|
|
246
|
+
}
|
|
247
|
+
return {
|
|
248
|
+
action: "create",
|
|
249
|
+
kind: "reflection",
|
|
250
|
+
objective: parsed.thought.trim(),
|
|
251
|
+
summary: typeof parsed.say === "string" ? parsed.say.trim() : "",
|
|
252
|
+
success_criteria: "- preserve the thread for later work",
|
|
253
|
+
payload_json: "{}",
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
function buildPonderResult(packet, action, returnObligationId) {
|
|
257
|
+
return JSON.stringify({
|
|
258
|
+
ok: true,
|
|
259
|
+
packet_id: packet.id,
|
|
260
|
+
action,
|
|
261
|
+
status: packet.status,
|
|
262
|
+
return_obligation_id: returnObligationId,
|
|
263
|
+
}, null, 2);
|
|
264
|
+
}
|
|
265
|
+
/** Returns true when a tool call queries external state (GitHub, npm registry). */
|
|
266
|
+
function isExternalStateQuery(toolName, args) {
|
|
267
|
+
if (toolName !== "shell")
|
|
268
|
+
return false;
|
|
269
|
+
const cmd = String(args.command ?? "");
|
|
270
|
+
return /\bgh\s+(pr|run|api|issue)\b/.test(cmd) || /\bnpm\s+(view|info|show)\b/.test(cmd);
|
|
271
|
+
}
|
|
272
|
+
function getSettleRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp, _delegationDecision, sawSendMessageSelf, sawPonder, _sawQuerySession, currentObligation, innerJob, sawExternalStateQuery) {
|
|
273
|
+
// Delegation adherence removed: the delegation decision is surfaced in the
|
|
274
|
+
// system prompt as a suggestion. Hard-gating settle caused infinite
|
|
275
|
+
// rejection loops where the agent couldn't respond to the user at all.
|
|
276
|
+
// The agent is free to follow or ignore the delegation hint.
|
|
277
|
+
// 2. Pending obligation not addressed
|
|
278
|
+
if (innerJob?.obligationStatus === "pending" && !sawSendMessageSelf && !sawPonder) {
|
|
279
|
+
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.";
|
|
280
|
+
}
|
|
281
|
+
// 3. mustResolveBeforeHandoff + missing intent
|
|
150
282
|
if (mustResolveBeforeHandoff && !intent) {
|
|
151
|
-
return "your
|
|
283
|
+
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.";
|
|
152
284
|
}
|
|
285
|
+
// 4. mustResolveBeforeHandoff + direct_reply without follow-up
|
|
153
286
|
if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
|
|
154
|
-
return "your
|
|
287
|
+
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.";
|
|
288
|
+
}
|
|
289
|
+
// 5. mustResolveBeforeHandoff + complete while a live return loop is still active
|
|
290
|
+
if (mustResolveBeforeHandoff && intent === "complete" && currentObligation && !sawSteeringFollowUp) {
|
|
291
|
+
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.";
|
|
155
292
|
}
|
|
156
|
-
|
|
293
|
+
// 6. External-state grounding: obligation + complete requires fresh external verification
|
|
294
|
+
if (intent === "complete" && currentObligation && !sawExternalStateQuery && !sawSteeringFollowUp) {
|
|
295
|
+
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.";
|
|
296
|
+
}
|
|
297
|
+
return null;
|
|
157
298
|
}
|
|
158
|
-
// Re-export kick utilities for backward compat
|
|
159
|
-
var kicks_1 = require("./kicks");
|
|
160
|
-
Object.defineProperty(exports, "hasToolIntent", { enumerable: true, get: function () { return kicks_1.hasToolIntent; } });
|
|
161
299
|
function upsertSystemPrompt(messages, systemText) {
|
|
162
300
|
const systemMessage = { role: "system", content: systemText };
|
|
163
301
|
if (messages[0]?.role === "system") {
|
|
@@ -263,49 +401,67 @@ function isContextOverflow(err) {
|
|
|
263
401
|
return true;
|
|
264
402
|
return false;
|
|
265
403
|
}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
404
|
+
const RETRY_LABELS = {
|
|
405
|
+
"auth-failure": "auth error",
|
|
406
|
+
"usage-limit": "usage limit",
|
|
407
|
+
"rate-limit": "rate limited",
|
|
408
|
+
"server-error": "server error",
|
|
409
|
+
"network-error": "network error",
|
|
410
|
+
"unknown": "error",
|
|
411
|
+
};
|
|
412
|
+
function waitForProviderRetry(delayMs, signal) {
|
|
413
|
+
if (!signal) {
|
|
414
|
+
return new Promise((resolve) => {
|
|
415
|
+
setTimeout(resolve, delayMs);
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
return new Promise((resolve, reject) => {
|
|
419
|
+
let timer;
|
|
420
|
+
const onAbort = () => {
|
|
421
|
+
clearTimeout(timer);
|
|
422
|
+
reject(new provider_attempt_1.ProviderAttemptAbortError());
|
|
423
|
+
};
|
|
424
|
+
timer = setTimeout(() => {
|
|
425
|
+
signal.removeEventListener("abort", onAbort);
|
|
426
|
+
resolve();
|
|
427
|
+
}, delayMs);
|
|
428
|
+
if (signal.aborted) {
|
|
429
|
+
onAbort();
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
433
|
+
});
|
|
292
434
|
}
|
|
293
|
-
function
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
435
|
+
function buildAuthFailureGuidance(provider, model, agentName, detail) {
|
|
436
|
+
const mismatch = (0, provider_models_1.getProviderModelMismatchMessage)(provider, model);
|
|
437
|
+
const modelLabel = model
|
|
438
|
+
? mismatch
|
|
439
|
+
? `${provider} [configured model: ${model}]`
|
|
440
|
+
: `${provider} (${model})`
|
|
441
|
+
: provider;
|
|
442
|
+
const lines = [`${modelLabel} authentication failed.`];
|
|
443
|
+
const cleanDetail = detail.replace(/\s+/g, " ").trim();
|
|
444
|
+
if (cleanDetail)
|
|
445
|
+
lines.push(`provider detail: ${cleanDetail.length > 300 ? `${cleanDetail.slice(0, 297)}...` : cleanDetail}`);
|
|
446
|
+
lines.push("");
|
|
447
|
+
lines.push("To keep using this provider:");
|
|
448
|
+
lines.push(` 1. Run \`ouro auth --agent ${agentName} --provider ${provider}\``);
|
|
449
|
+
if (mismatch) {
|
|
450
|
+
const defaultModel = (0, provider_models_1.getDefaultModelForProvider)(provider);
|
|
451
|
+
lines.push("");
|
|
452
|
+
lines.push("Config warning:");
|
|
453
|
+
lines.push(` - ${mismatch}`);
|
|
454
|
+
lines.push(" - Repair the configured model with:");
|
|
455
|
+
lines.push(` \`ouro config model --agent ${agentName} --facing human ${defaultModel}\``);
|
|
456
|
+
lines.push(` \`ouro config model --agent ${agentName} --facing agent ${defaultModel}\``);
|
|
457
|
+
}
|
|
458
|
+
lines.push("");
|
|
459
|
+
lines.push(`To use another configured provider instead, run \`ouro auth switch --agent ${agentName} --provider <provider>\`.`);
|
|
460
|
+
return lines.join("\n");
|
|
304
461
|
}
|
|
305
|
-
const MAX_RETRIES = 3;
|
|
306
|
-
const RETRY_BASE_MS = 2000;
|
|
307
462
|
async function runAgent(messages, callbacks, channel, signal, options) {
|
|
308
|
-
const
|
|
463
|
+
const facing = (0, channel_1.channelToFacing)(channel);
|
|
464
|
+
let providerRuntime = await getProviderRuntime(facing);
|
|
309
465
|
const provider = providerRuntime.id;
|
|
310
466
|
const toolChoiceRequired = options?.toolChoiceRequired ?? true;
|
|
311
467
|
const traceId = options?.traceId;
|
|
@@ -329,10 +485,17 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
329
485
|
// Refresh system prompt at start of each turn when channel is provided.
|
|
330
486
|
// If refresh fails, keep existing system prompt (or inject a minimal safe fallback)
|
|
331
487
|
// so turn execution remains consistent and non-fatal.
|
|
488
|
+
let structuredSystemPrompt;
|
|
332
489
|
if (channel) {
|
|
333
490
|
try {
|
|
334
|
-
const
|
|
335
|
-
|
|
491
|
+
const buildSystemOptions = {
|
|
492
|
+
...options,
|
|
493
|
+
providerCapabilities: providerRuntime.capabilities,
|
|
494
|
+
supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
|
|
495
|
+
};
|
|
496
|
+
const refreshed = await (0, prompt_1.buildSystem)(channel, buildSystemOptions, currentContext);
|
|
497
|
+
structuredSystemPrompt = refreshed;
|
|
498
|
+
upsertSystemPrompt(messages, (0, prompt_1.flattenSystemPrompt)(refreshed));
|
|
336
499
|
}
|
|
337
500
|
catch (error) {
|
|
338
501
|
const hadExistingSystemPrompt = messages[0]?.role === "system" && typeof messages[0].content === "string";
|
|
@@ -353,30 +516,100 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
353
516
|
});
|
|
354
517
|
}
|
|
355
518
|
}
|
|
356
|
-
|
|
519
|
+
if (channel) {
|
|
520
|
+
await (0, kept_notes_1.injectKeptNotes)(messages, {
|
|
521
|
+
channel,
|
|
522
|
+
friend: currentContext?.friend,
|
|
523
|
+
judge: async (input) => (0, kept_notes_1.createKeptNotesJudge)(await getProviderRuntime("agent"), signal)(input),
|
|
524
|
+
signal,
|
|
525
|
+
traceId,
|
|
526
|
+
});
|
|
527
|
+
}
|
|
357
528
|
let done = false;
|
|
358
529
|
let lastUsage;
|
|
359
530
|
let overflowRetried = false;
|
|
360
|
-
let
|
|
361
|
-
let
|
|
531
|
+
let outcome = "settled";
|
|
532
|
+
let completion;
|
|
533
|
+
let terminalError;
|
|
534
|
+
let terminalErrorClassification;
|
|
362
535
|
let sawSteeringFollowUp = false;
|
|
363
536
|
let mustResolveBeforeHandoffActive = options?.mustResolveBeforeHandoff === true;
|
|
537
|
+
let currentReasoningEffort = "medium";
|
|
538
|
+
let sawSendMessageSelf = false;
|
|
539
|
+
let sawPonder = false;
|
|
540
|
+
let sawQuerySession = false;
|
|
541
|
+
let sawBridgeManage = false;
|
|
542
|
+
let sawExternalStateQuery = false;
|
|
543
|
+
const toolLoopState = (0, tool_loop_1.createToolLoopState)();
|
|
544
|
+
const toolFrictionLedger = (0, tool_friction_1.createToolFrictionLedger)();
|
|
545
|
+
const finishTerminalProviderError = (error, classification) => {
|
|
546
|
+
terminalError = error;
|
|
547
|
+
terminalErrorClassification = classification;
|
|
548
|
+
/* v8 ignore start — auth-failure guidance: tested via provider error classification tests @preserve */
|
|
549
|
+
if (terminalErrorClassification === "auth-failure") {
|
|
550
|
+
const agentName = (0, identity_2.getAgentName)();
|
|
551
|
+
const currentProvider = providerRuntime.id;
|
|
552
|
+
callbacks.onError(new Error(buildAuthFailureGuidance(currentProvider, providerRuntime.model, agentName, terminalError.message)), "terminal");
|
|
553
|
+
}
|
|
554
|
+
else {
|
|
555
|
+
callbacks.onError(terminalError, "terminal");
|
|
556
|
+
}
|
|
557
|
+
/* v8 ignore stop */
|
|
558
|
+
(0, runtime_1.emitNervesEvent)({
|
|
559
|
+
level: "error",
|
|
560
|
+
event: "engine.error",
|
|
561
|
+
trace_id: traceId,
|
|
562
|
+
component: "engine",
|
|
563
|
+
message: terminalError.message,
|
|
564
|
+
meta: {
|
|
565
|
+
provider: providerRuntime.id,
|
|
566
|
+
model: providerRuntime.model,
|
|
567
|
+
errorClassification: terminalErrorClassification,
|
|
568
|
+
},
|
|
569
|
+
});
|
|
570
|
+
stripLastToolCalls(messages);
|
|
571
|
+
outcome = "errored";
|
|
572
|
+
done = true;
|
|
573
|
+
};
|
|
364
574
|
// Prevent MaxListenersExceeded warning — each iteration adds a listener
|
|
365
575
|
try {
|
|
366
576
|
require("events").setMaxListeners(50, signal);
|
|
367
577
|
}
|
|
368
578
|
catch { /* unsupported */ }
|
|
369
579
|
const toolPreferences = currentContext?.friend?.toolPreferences;
|
|
370
|
-
const baseTools = options?.tools ?? (0, tools_1.getToolsForChannel)(channel ? (0, channel_1.getChannelCapabilities)(channel) : undefined, toolPreferences && Object.keys(toolPreferences).length > 0 ? toolPreferences : undefined, currentContext);
|
|
580
|
+
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);
|
|
581
|
+
// Augment tool context with reasoning effort controls from provider
|
|
582
|
+
const augmentedToolContext = options?.toolContext
|
|
583
|
+
? {
|
|
584
|
+
...options.toolContext,
|
|
585
|
+
supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
|
|
586
|
+
setReasoningEffort: (level) => { currentReasoningEffort = level; },
|
|
587
|
+
activeWorkFrame: options?.activeWorkFrame,
|
|
588
|
+
}
|
|
589
|
+
: undefined;
|
|
371
590
|
// Rebase provider-owned turn state from canonical messages at user-turn start.
|
|
372
591
|
// This prevents stale provider caches from replaying prior-turn context.
|
|
373
592
|
providerRuntime.resetTurnState(messages);
|
|
374
593
|
while (!done) {
|
|
375
|
-
//
|
|
376
|
-
//
|
|
377
|
-
//
|
|
378
|
-
//
|
|
379
|
-
|
|
594
|
+
// Channel-based tool filtering:
|
|
595
|
+
// - Inner dialog: exclude send_message (delivery via surface), observe (no one to observe)
|
|
596
|
+
// - All outward channels (1:1, group, reaction): observe available
|
|
597
|
+
//
|
|
598
|
+
// ponder, settle/rest, surface, and observe are always assembled based on channel context.
|
|
599
|
+
// ponder is available in ALL channels (outer: think privately, inner: keep turning).
|
|
600
|
+
// Inner dialog gets restTool instead of settleTool (rest = end turn, gated by attention queue).
|
|
601
|
+
// toolChoiceRequired only controls whether tool_choice: "required" is set in the API call.
|
|
602
|
+
const isInnerDialog = channel === "inner";
|
|
603
|
+
const filteredBaseTools = isInnerDialog
|
|
604
|
+
? baseTools.filter((t) => t.function.name !== "send_message")
|
|
605
|
+
: baseTools;
|
|
606
|
+
const activeTools = [
|
|
607
|
+
...filteredBaseTools,
|
|
608
|
+
tools_1.ponderTool,
|
|
609
|
+
...(isInnerDialog ? [tools_2.surfaceToolDef, tools_1.restTool] : []),
|
|
610
|
+
...(!isInnerDialog ? [tools_1.observeTool] : []),
|
|
611
|
+
...(!isInnerDialog ? [tools_1.settleTool] : []),
|
|
612
|
+
];
|
|
380
613
|
const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
|
|
381
614
|
if (steeringFollowUps.length > 0) {
|
|
382
615
|
const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
|
|
@@ -403,19 +636,87 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
403
636
|
break;
|
|
404
637
|
}
|
|
405
638
|
try {
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
639
|
+
const callProviderTurn = async () => {
|
|
640
|
+
callbacks.onModelStart();
|
|
641
|
+
try {
|
|
642
|
+
return await providerRuntime.streamTurn({
|
|
643
|
+
messages,
|
|
644
|
+
activeTools,
|
|
645
|
+
callbacks,
|
|
646
|
+
signal,
|
|
647
|
+
traceId,
|
|
648
|
+
toolChoiceRequired,
|
|
649
|
+
reasoningEffort: currentReasoningEffort,
|
|
650
|
+
eagerSettleStreaming: true,
|
|
651
|
+
systemPrompt: structuredSystemPrompt,
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
catch (error) {
|
|
655
|
+
if (signal?.aborted)
|
|
656
|
+
throw new provider_attempt_1.ProviderAttemptAbortError();
|
|
657
|
+
throw error;
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
const callProviderTurnWithOverflowRecovery = async () => {
|
|
661
|
+
try {
|
|
662
|
+
return await callProviderTurn();
|
|
663
|
+
}
|
|
664
|
+
catch (error) {
|
|
665
|
+
if (error instanceof provider_attempt_1.ProviderAttemptAbortError)
|
|
666
|
+
throw error;
|
|
667
|
+
if (isContextOverflow(error) && !overflowRetried) {
|
|
668
|
+
overflowRetried = true;
|
|
669
|
+
stripLastToolCalls(messages);
|
|
670
|
+
const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
|
|
671
|
+
const trimmed = (0, context_1.trimMessages)(messages, maxTokens, contextMargin, maxTokens * 2);
|
|
672
|
+
messages.splice(0, messages.length, ...trimmed);
|
|
673
|
+
providerRuntime.resetTurnState(messages);
|
|
674
|
+
callbacks.onError(new Error("context trimmed, retrying..."), "transient");
|
|
675
|
+
return callProviderTurn();
|
|
676
|
+
}
|
|
677
|
+
throw error;
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
const attempt = await (0, provider_attempt_1.runProviderAttempt)({
|
|
681
|
+
operation: "turn",
|
|
682
|
+
provider: providerRuntime.id,
|
|
683
|
+
model: providerRuntime.model,
|
|
684
|
+
run: callProviderTurnWithOverflowRecovery,
|
|
685
|
+
classifyError: (error) => providerRuntime.classifyError(error),
|
|
686
|
+
onRetry: async (record, maxAttempts) => {
|
|
687
|
+
const delayMs = record.delayMs;
|
|
688
|
+
const seconds = delayMs / 1000;
|
|
689
|
+
const cause = RETRY_LABELS[record.classification];
|
|
690
|
+
try {
|
|
691
|
+
await (0, provider_credentials_1.refreshProviderCredentialPool)((0, identity_2.getAgentName)(), { preserveCachedOnFailure: true });
|
|
692
|
+
_providerRuntimes[facing] = null;
|
|
693
|
+
providerRuntime = await getProviderRuntime(facing);
|
|
694
|
+
providerRuntime.resetTurnState(messages);
|
|
695
|
+
}
|
|
696
|
+
catch (refreshError) {
|
|
697
|
+
(0, runtime_1.emitNervesEvent)({
|
|
698
|
+
level: "warn",
|
|
699
|
+
component: "engine",
|
|
700
|
+
event: "engine.provider_retry_refresh_failed",
|
|
701
|
+
message: "provider credential refresh failed during retry",
|
|
702
|
+
meta: { provider: record.provider, model: record.model, reason: refreshError instanceof Error ? refreshError.message : String(refreshError) },
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
callbacks.onError(new Error(`${cause}, retrying in ${seconds}s (${record.attempt}/${maxAttempts})...`), "transient");
|
|
706
|
+
},
|
|
707
|
+
sleep: async (delayMs) => {
|
|
708
|
+
await waitForProviderRetry(delayMs, signal);
|
|
709
|
+
providerRuntime.resetTurnState(messages);
|
|
710
|
+
},
|
|
414
711
|
});
|
|
712
|
+
if (!attempt.ok) {
|
|
713
|
+
finishTerminalProviderError(attempt.error, attempt.classification);
|
|
714
|
+
continue;
|
|
715
|
+
}
|
|
716
|
+
const result = attempt.value;
|
|
415
717
|
// Track usage from the latest API call
|
|
416
718
|
if (result.usage)
|
|
417
719
|
lastUsage = result.usage;
|
|
418
|
-
retryCount = 0; // reset on success
|
|
419
720
|
// SHARED: build CC-format assistant message from TurnResult
|
|
420
721
|
const msg = {
|
|
421
722
|
role: "assistant",
|
|
@@ -434,28 +735,76 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
434
735
|
if (reasoningItems.length > 0) {
|
|
435
736
|
msg._reasoning_items = reasoningItems;
|
|
436
737
|
}
|
|
738
|
+
// Store thinking blocks (Anthropic) on the assistant message for round-tripping
|
|
739
|
+
const thinkingItems = result.outputItems.filter((item) => "type" in item && (item.type === "thinking" || item.type === "redacted_thinking"));
|
|
740
|
+
if (thinkingItems.length > 0) {
|
|
741
|
+
msg._thinking_blocks = thinkingItems;
|
|
742
|
+
}
|
|
743
|
+
// Phase annotation for Codex provider
|
|
744
|
+
const hasPhaseAnnotation = providerRuntime.capabilities.has("phase-annotation");
|
|
745
|
+
const isSoleSettle = result.toolCalls.length === 1 && result.toolCalls[0].name === "settle";
|
|
746
|
+
if (hasPhaseAnnotation) {
|
|
747
|
+
msg.phase = isSoleSettle ? "settle" : "commentary";
|
|
748
|
+
}
|
|
437
749
|
if (!result.toolCalls.length) {
|
|
438
750
|
// No tool calls — accept response as-is.
|
|
439
|
-
// (Kick detection disabled; tool_choice: required +
|
|
751
|
+
// (Kick detection disabled; tool_choice: required + settle
|
|
440
752
|
// is the primary loop control. See src/heart/kicks.ts to re-enable.)
|
|
441
753
|
messages.push(msg);
|
|
442
754
|
done = true;
|
|
443
755
|
}
|
|
444
756
|
else {
|
|
445
|
-
// Check for
|
|
446
|
-
|
|
447
|
-
|
|
757
|
+
// Check for settle sole call: intercept before tool execution
|
|
758
|
+
if (isSoleSettle) {
|
|
759
|
+
/* v8 ignore next -- defensive: JSON.parse catch for malformed settle args @preserve */
|
|
760
|
+
const settleArgs = (() => { try {
|
|
761
|
+
return JSON.parse(result.toolCalls[0].arguments);
|
|
762
|
+
}
|
|
763
|
+
catch {
|
|
764
|
+
return {};
|
|
765
|
+
} })();
|
|
766
|
+
callbacks.onToolStart("settle", settleArgs);
|
|
767
|
+
// Inner dialog attention queue gate: reject settle if items remain
|
|
768
|
+
const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
|
|
769
|
+
if (isInnerDialog && attentionQueue && attentionQueue.length > 0) {
|
|
770
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
|
|
771
|
+
callbacks.onClearText?.();
|
|
772
|
+
messages.push(msg);
|
|
773
|
+
const gateMessage = "you're holding thoughts someone is waiting for — surface them before you settle.";
|
|
774
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
|
|
775
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
|
|
776
|
+
continue;
|
|
777
|
+
}
|
|
448
778
|
// Extract answer from the tool call arguments.
|
|
449
779
|
// Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
|
|
450
|
-
const { answer, intent } =
|
|
780
|
+
const { answer, intent } = parseSettlePayload(result.toolCalls[0].arguments);
|
|
781
|
+
// Inner dialog settle: no CompletionMetadata, "(settled)" ack
|
|
782
|
+
if (isInnerDialog) {
|
|
783
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
|
|
784
|
+
messages.push(msg);
|
|
785
|
+
const settled = "(settled)";
|
|
786
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: settled });
|
|
787
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, settled);
|
|
788
|
+
outcome = "settled";
|
|
789
|
+
done = true;
|
|
790
|
+
continue;
|
|
791
|
+
}
|
|
792
|
+
const retryError = getSettleRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp, options?.delegationDecision, sawSendMessageSelf, sawPonder, sawQuerySession, options?.currentObligation ?? null, options?.activeWorkFrame?.inner?.job, sawExternalStateQuery);
|
|
793
|
+
const deliveredAnswer = answer;
|
|
451
794
|
const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
|
|
452
795
|
const validTerminalIntent = intent === "complete" || intent === "blocked";
|
|
453
|
-
const validClosure =
|
|
796
|
+
const validClosure = deliveredAnswer != null
|
|
797
|
+
&& !retryError
|
|
454
798
|
&& (!mustResolveBeforeHandoffActive || validDirectReply || validTerminalIntent);
|
|
455
799
|
if (validClosure) {
|
|
456
|
-
|
|
800
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
|
|
801
|
+
completion = {
|
|
802
|
+
answer: deliveredAnswer,
|
|
803
|
+
intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
|
|
804
|
+
};
|
|
805
|
+
if (result.settleStreamed) {
|
|
457
806
|
// The streaming layer already parsed and emitted the answer
|
|
458
|
-
// progressively via
|
|
807
|
+
// progressively via SettleParser. Skip clearing and
|
|
459
808
|
// re-emitting to avoid double-delivery.
|
|
460
809
|
}
|
|
461
810
|
else {
|
|
@@ -463,7 +812,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
463
812
|
callbacks.onClearText?.();
|
|
464
813
|
// Emit the answer through the callback pipeline so channels receive it.
|
|
465
814
|
// Never truncate -- channel adapters handle splitting long messages.
|
|
466
|
-
callbacks.onTextChunk(
|
|
815
|
+
callbacks.onTextChunk(deliveredAnswer);
|
|
467
816
|
}
|
|
468
817
|
messages.push(msg);
|
|
469
818
|
if (validDirectReply) {
|
|
@@ -475,32 +824,98 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
475
824
|
const delivered = "(delivered)";
|
|
476
825
|
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
|
|
477
826
|
providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
|
|
478
|
-
outcome = intent === "blocked" ? "blocked" : "
|
|
827
|
+
outcome = intent === "blocked" ? "blocked" : "settled";
|
|
479
828
|
done = true;
|
|
480
829
|
}
|
|
481
830
|
}
|
|
482
831
|
else {
|
|
483
|
-
// Answer is undefined -- the model's
|
|
832
|
+
// Answer is undefined -- the model's settle was incomplete or
|
|
484
833
|
// malformed. Clear any partial streamed text or noise, then push the
|
|
485
834
|
// assistant msg + error tool result and let the model try again.
|
|
835
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
|
|
486
836
|
callbacks.onClearText?.();
|
|
487
|
-
const retryError = getFinalAnswerRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp);
|
|
488
837
|
messages.push(msg);
|
|
489
|
-
|
|
490
|
-
|
|
838
|
+
const toolRetryMessage = retryError
|
|
839
|
+
?? "your settle was incomplete or malformed. call settle again with your complete response.";
|
|
840
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: toolRetryMessage });
|
|
841
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, toolRetryMessage);
|
|
491
842
|
}
|
|
492
843
|
continue;
|
|
493
844
|
}
|
|
845
|
+
// Check for observe sole call: intercept before tool execution
|
|
846
|
+
const isSoleObserve = result.toolCalls.length === 1 && result.toolCalls[0].name === "observe";
|
|
847
|
+
if (isSoleObserve) {
|
|
848
|
+
/* v8 ignore next -- defensive: JSON.parse catch for malformed observe args @preserve */
|
|
849
|
+
const observeArgs = (() => { try {
|
|
850
|
+
return JSON.parse(result.toolCalls[0].arguments);
|
|
851
|
+
}
|
|
852
|
+
catch {
|
|
853
|
+
return {};
|
|
854
|
+
} })();
|
|
855
|
+
let reason;
|
|
856
|
+
if (typeof observeArgs?.reason === "string")
|
|
857
|
+
reason = observeArgs.reason;
|
|
858
|
+
callbacks.onToolStart("observe", observeArgs);
|
|
859
|
+
(0, runtime_1.emitNervesEvent)({
|
|
860
|
+
component: "engine",
|
|
861
|
+
event: "engine.observe",
|
|
862
|
+
message: "agent observed without responding",
|
|
863
|
+
meta: { ...(reason ? { reason } : {}) },
|
|
864
|
+
});
|
|
865
|
+
callbacks.onToolEnd("observe", (0, tools_1.summarizeArgs)("observe", observeArgs), true);
|
|
866
|
+
messages.push(msg);
|
|
867
|
+
const silenced = "(silenced)";
|
|
868
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: silenced });
|
|
869
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, silenced);
|
|
870
|
+
outcome = "observed";
|
|
871
|
+
done = true;
|
|
872
|
+
continue;
|
|
873
|
+
}
|
|
874
|
+
// Check for rest sole call: intercept before tool execution
|
|
875
|
+
const isSoleRest = result.toolCalls.length === 1 && result.toolCalls[0].name === "rest";
|
|
876
|
+
if (isSoleRest) {
|
|
877
|
+
const restArgs = (() => { try {
|
|
878
|
+
return JSON.parse(result.toolCalls[0].arguments);
|
|
879
|
+
}
|
|
880
|
+
catch {
|
|
881
|
+
return {};
|
|
882
|
+
} })();
|
|
883
|
+
callbacks.onToolStart("rest", restArgs);
|
|
884
|
+
// Attention queue gate: reject rest if items remain
|
|
885
|
+
const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
|
|
886
|
+
if (attentionQueue && attentionQueue.length > 0) {
|
|
887
|
+
callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), false);
|
|
888
|
+
messages.push(msg);
|
|
889
|
+
const gateMessage = "you're holding thoughts someone is waiting for — surface them before you rest.";
|
|
890
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
|
|
891
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
|
|
892
|
+
continue;
|
|
893
|
+
}
|
|
894
|
+
callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), true);
|
|
895
|
+
messages.push(msg);
|
|
896
|
+
const ack = "(resting)";
|
|
897
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
|
|
898
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
|
|
899
|
+
(0, runtime_1.emitNervesEvent)({
|
|
900
|
+
component: "engine",
|
|
901
|
+
event: "engine.rested",
|
|
902
|
+
message: "resting until next heartbeat",
|
|
903
|
+
meta: { ...(typeof restArgs?.status === "string" ? { status: restArgs.status } : {}) },
|
|
904
|
+
});
|
|
905
|
+
outcome = "rested";
|
|
906
|
+
done = true;
|
|
907
|
+
continue;
|
|
908
|
+
}
|
|
494
909
|
messages.push(msg);
|
|
495
|
-
//
|
|
910
|
+
// Execute tools (sole-call tools in mixed calls are rejected inline)
|
|
496
911
|
for (const tc of result.toolCalls) {
|
|
497
912
|
if (signal?.aborted)
|
|
498
913
|
break;
|
|
499
|
-
//
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
messages.push({ role: "tool", tool_call_id: tc.id, content:
|
|
503
|
-
providerRuntime.appendToolOutput(tc.id,
|
|
914
|
+
// Reject sole-call tools when mixed with other tool calls
|
|
915
|
+
const soleCallRejection = SOLE_CALL_REJECTION[tc.name];
|
|
916
|
+
if (soleCallRejection) {
|
|
917
|
+
messages.push({ role: "tool", tool_call_id: tc.id, content: soleCallRejection });
|
|
918
|
+
providerRuntime.appendToolOutput(tc.id, soleCallRejection);
|
|
504
919
|
continue;
|
|
505
920
|
}
|
|
506
921
|
let args = {};
|
|
@@ -510,97 +925,195 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
510
925
|
catch {
|
|
511
926
|
/* ignore */
|
|
512
927
|
}
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
928
|
+
if (tc.name === "send_message" && args.friendId === "self") {
|
|
929
|
+
sawSendMessageSelf = true;
|
|
930
|
+
}
|
|
931
|
+
if (tc.name === "ponder") {
|
|
932
|
+
const parsedArgs = normalizeLegacyPonderArgs(parsePonderPayload(tc.arguments));
|
|
933
|
+
const argSummary = (0, tools_1.summarizeArgs)(tc.name, parsedArgs);
|
|
934
|
+
callbacks.onToolStart(tc.name, parsedArgs);
|
|
935
|
+
let toolResult;
|
|
936
|
+
let success = false;
|
|
937
|
+
try {
|
|
938
|
+
const action = parsedArgs.action ?? "create";
|
|
939
|
+
const currentSession = (augmentedToolContext ?? options?.toolContext)?.currentSession;
|
|
940
|
+
const currentOrigin = currentSession
|
|
941
|
+
? { friendId: currentSession.friendId, channel: currentSession.channel, key: currentSession.key }
|
|
942
|
+
: undefined;
|
|
943
|
+
const isInnerChannel = currentOrigin?.friendId === "self" && currentOrigin?.channel === "inner";
|
|
944
|
+
const successCriteria = parseSuccessCriteria(parsedArgs.success_criteria);
|
|
945
|
+
const payload = parsePacketPayload(parsedArgs.payload_json);
|
|
946
|
+
let packet;
|
|
947
|
+
let returnObligationId = null;
|
|
948
|
+
let resultAction = "created";
|
|
949
|
+
if (action === "create") {
|
|
950
|
+
const kind = parsedArgs.kind;
|
|
951
|
+
const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
|
|
952
|
+
const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
|
|
953
|
+
if (!kind || !objective || !successCriteria || !payload) {
|
|
954
|
+
throw new Error("ponder create requires kind, objective, success_criteria, and valid payload_json.");
|
|
955
|
+
}
|
|
956
|
+
const agentRoot = (0, identity_2.getAgentRoot)();
|
|
957
|
+
let relatedObligationId;
|
|
958
|
+
if (currentOrigin && !isInnerChannel) {
|
|
959
|
+
try {
|
|
960
|
+
const obligation = (0, obligations_1.createObligation)(agentRoot, {
|
|
961
|
+
origin: currentOrigin,
|
|
962
|
+
content: objective,
|
|
963
|
+
});
|
|
964
|
+
relatedObligationId = obligation.id;
|
|
965
|
+
}
|
|
966
|
+
catch {
|
|
967
|
+
relatedObligationId = undefined;
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
const frictionSignature = kind === "harness_friction" && typeof payload.frictionSignature === "string"
|
|
971
|
+
? payload.frictionSignature
|
|
972
|
+
: null;
|
|
973
|
+
const existing = frictionSignature && currentOrigin
|
|
974
|
+
? (0, packets_1.findHarnessFrictionPacket)(agentRoot, currentOrigin, frictionSignature)
|
|
975
|
+
: null;
|
|
976
|
+
if (existing) {
|
|
977
|
+
resultAction = "revised";
|
|
978
|
+
returnObligationId = existing.relatedReturnObligationId ?? null;
|
|
979
|
+
packet = existing.status === "drafting"
|
|
980
|
+
? (0, packets_1.revisePonderPacket)(agentRoot, existing.id, {
|
|
981
|
+
kind,
|
|
982
|
+
objective,
|
|
983
|
+
summary,
|
|
984
|
+
successCriteria,
|
|
985
|
+
payload,
|
|
986
|
+
})
|
|
987
|
+
: existing;
|
|
988
|
+
}
|
|
989
|
+
else {
|
|
990
|
+
returnObligationId = (0, obligations_1.generateObligationId)(Date.now());
|
|
991
|
+
packet = (0, packets_1.createPonderPacket)(agentRoot, {
|
|
992
|
+
kind,
|
|
993
|
+
objective,
|
|
994
|
+
summary,
|
|
995
|
+
successCriteria,
|
|
996
|
+
...(currentOrigin ? { origin: currentOrigin } : {}),
|
|
997
|
+
...(relatedObligationId ? { relatedObligationId } : {}),
|
|
998
|
+
relatedReturnObligationId: returnObligationId,
|
|
999
|
+
...(parsedArgs.follows_packet_id ? { followsPacketId: parsedArgs.follows_packet_id } : {}),
|
|
1000
|
+
payload,
|
|
1001
|
+
});
|
|
1002
|
+
(0, obligations_1.createReturnObligation)((0, identity_2.getAgentName)(), {
|
|
1003
|
+
id: returnObligationId,
|
|
1004
|
+
origin: currentOrigin ?? { friendId: "self", channel: "inner", key: "dialog" },
|
|
1005
|
+
status: "queued",
|
|
1006
|
+
delegatedContent: (summary || objective).length > 120 ? `${(summary || objective).slice(0, 117)}...` : (summary || objective),
|
|
1007
|
+
packetId: packet.id,
|
|
1008
|
+
createdAt: Date.now(),
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
else if (action === "revise") {
|
|
1013
|
+
const packetId = typeof parsedArgs.packet_id === "string" ? parsedArgs.packet_id.trim() : "";
|
|
1014
|
+
const kind = parsedArgs.kind;
|
|
1015
|
+
const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
|
|
1016
|
+
const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
|
|
1017
|
+
if (!packetId || !kind || !objective || !successCriteria || !payload) {
|
|
1018
|
+
throw new Error("ponder revise requires packet_id, kind, objective, success_criteria, and valid payload_json.");
|
|
1019
|
+
}
|
|
1020
|
+
packet = (0, packets_1.revisePonderPacket)((0, identity_2.getAgentRoot)(), packetId, {
|
|
1021
|
+
kind,
|
|
1022
|
+
objective,
|
|
1023
|
+
summary,
|
|
1024
|
+
successCriteria,
|
|
1025
|
+
payload,
|
|
1026
|
+
});
|
|
1027
|
+
returnObligationId = packet.relatedReturnObligationId ?? null;
|
|
1028
|
+
resultAction = "revised";
|
|
1029
|
+
}
|
|
1030
|
+
else {
|
|
1031
|
+
throw new Error("ponder requires action=create or revise.");
|
|
1032
|
+
}
|
|
1033
|
+
try {
|
|
1034
|
+
await (0, socket_client_1.requestInnerWake)((0, identity_2.getAgentName)());
|
|
1035
|
+
}
|
|
1036
|
+
catch { /* daemon may not be running */ }
|
|
1037
|
+
sawPonder = true;
|
|
1038
|
+
toolResult = buildPonderResult(packet, resultAction, returnObligationId);
|
|
1039
|
+
success = true;
|
|
1040
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1041
|
+
component: "engine",
|
|
1042
|
+
event: "engine.ponder_packet",
|
|
1043
|
+
message: "ponder packet touched",
|
|
1044
|
+
meta: {
|
|
1045
|
+
action: resultAction,
|
|
1046
|
+
packetId: packet.id,
|
|
1047
|
+
kind: packet.kind,
|
|
1048
|
+
status: packet.status,
|
|
1049
|
+
},
|
|
1050
|
+
});
|
|
519
1051
|
}
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
callbacks.onToolStart(tc.name, args);
|
|
523
|
-
callbacks.onToolEnd(tc.name, argSummary, false);
|
|
524
|
-
messages.push({ role: "tool", tool_call_id: tc.id, content: cancelled });
|
|
525
|
-
providerRuntime.appendToolOutput(tc.id, cancelled);
|
|
526
|
-
continue;
|
|
1052
|
+
catch (error) {
|
|
1053
|
+
toolResult = error instanceof Error ? error.message : String(error);
|
|
527
1054
|
}
|
|
1055
|
+
callbacks.onToolEnd(tc.name, argSummary, success);
|
|
1056
|
+
messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
|
|
1057
|
+
providerRuntime.appendToolOutput(tc.id, toolResult);
|
|
1058
|
+
continue;
|
|
1059
|
+
}
|
|
1060
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
1061
|
+
if (tc.name === "query_session")
|
|
1062
|
+
sawQuerySession = true;
|
|
1063
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
1064
|
+
if (tc.name === "bridge_manage")
|
|
1065
|
+
sawBridgeManage = true;
|
|
1066
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
1067
|
+
if (isExternalStateQuery(tc.name, args))
|
|
1068
|
+
sawExternalStateQuery = true;
|
|
1069
|
+
const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
|
|
1070
|
+
const toolLoop = (0, tool_loop_1.detectToolLoop)(toolLoopState, tc.name, args);
|
|
1071
|
+
if (toolLoop.stuck) {
|
|
1072
|
+
const rejection = `loop guard: ${toolLoop.message}`;
|
|
1073
|
+
callbacks.onToolStart(tc.name, args);
|
|
1074
|
+
callbacks.onToolEnd(tc.name, argSummary, false);
|
|
1075
|
+
messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
|
|
1076
|
+
providerRuntime.appendToolOutput(tc.id, rejection);
|
|
1077
|
+
continue;
|
|
528
1078
|
}
|
|
529
1079
|
callbacks.onToolStart(tc.name, args);
|
|
530
1080
|
let toolResult;
|
|
531
1081
|
let success;
|
|
532
1082
|
try {
|
|
533
1083
|
const execToolFn = options?.execTool ?? tools_1.execTool;
|
|
534
|
-
toolResult = await execToolFn(tc.name, args, options?.toolContext);
|
|
1084
|
+
toolResult = await execToolFn(tc.name, args, augmentedToolContext ?? options?.toolContext);
|
|
535
1085
|
success = true;
|
|
536
1086
|
}
|
|
537
1087
|
catch (e) {
|
|
538
1088
|
toolResult = `error: ${e}`;
|
|
539
1089
|
success = false;
|
|
540
1090
|
}
|
|
541
|
-
|
|
1091
|
+
toolResult = (0, tool_friction_1.rewriteToolResultForModel)(tc.name, toolResult, toolFrictionLedger);
|
|
1092
|
+
(0, tool_loop_1.recordToolOutcome)(toolLoopState, tc.name, args, toolResult, success);
|
|
1093
|
+
callbacks.onToolEnd(tc.name, (0, tools_1.buildToolResultSummary)(tc.name, args, toolResult, success), success);
|
|
542
1094
|
messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
|
|
543
1095
|
providerRuntime.appendToolOutput(tc.id, toolResult);
|
|
1096
|
+
callbacks.onToolResult?.(messages);
|
|
544
1097
|
}
|
|
545
1098
|
}
|
|
546
1099
|
}
|
|
547
1100
|
catch (e) {
|
|
548
1101
|
// Abort is not an error — just stop cleanly
|
|
549
|
-
if (signal?.aborted) {
|
|
1102
|
+
if (e instanceof provider_attempt_1.ProviderAttemptAbortError || signal?.aborted) {
|
|
550
1103
|
stripLastToolCalls(messages);
|
|
551
1104
|
outcome = "aborted";
|
|
552
1105
|
break;
|
|
553
1106
|
}
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
|
|
559
|
-
const trimmed = (0, context_1.trimMessages)(messages, maxTokens, contextMargin, maxTokens * 2);
|
|
560
|
-
messages.splice(0, messages.length, ...trimmed);
|
|
561
|
-
providerRuntime.resetTurnState(messages);
|
|
562
|
-
callbacks.onError(new Error("context trimmed, retrying..."), "transient");
|
|
563
|
-
continue;
|
|
1107
|
+
const errorForClassification = e instanceof Error ? e : /* v8 ignore next -- defensive @preserve */ new Error(String(e));
|
|
1108
|
+
let providerClassification;
|
|
1109
|
+
try {
|
|
1110
|
+
providerClassification = providerRuntime.classifyError(errorForClassification);
|
|
564
1111
|
}
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
const delay = RETRY_BASE_MS * Math.pow(2, retryCount - 1);
|
|
569
|
-
const cause = classifyTransientError(e);
|
|
570
|
-
callbacks.onError(new Error(`${cause}, retrying in ${delay / 1000}s (${retryCount}/${MAX_RETRIES})...`), "transient");
|
|
571
|
-
// Wait with abort support
|
|
572
|
-
const aborted = await new Promise((resolve) => {
|
|
573
|
-
const timer = setTimeout(() => resolve(false), delay);
|
|
574
|
-
if (signal) {
|
|
575
|
-
const onAbort = () => { clearTimeout(timer); resolve(true); };
|
|
576
|
-
if (signal.aborted) {
|
|
577
|
-
clearTimeout(timer);
|
|
578
|
-
resolve(true);
|
|
579
|
-
return;
|
|
580
|
-
}
|
|
581
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
582
|
-
}
|
|
583
|
-
});
|
|
584
|
-
if (aborted) {
|
|
585
|
-
stripLastToolCalls(messages);
|
|
586
|
-
outcome = "aborted";
|
|
587
|
-
break;
|
|
588
|
-
}
|
|
589
|
-
providerRuntime.resetTurnState(messages);
|
|
590
|
-
continue;
|
|
1112
|
+
catch {
|
|
1113
|
+
/* v8 ignore next -- defensive: classifyError should not throw @preserve */
|
|
1114
|
+
providerClassification = "unknown";
|
|
591
1115
|
}
|
|
592
|
-
|
|
593
|
-
(0, runtime_1.emitNervesEvent)({
|
|
594
|
-
level: "error",
|
|
595
|
-
event: "engine.error",
|
|
596
|
-
trace_id: traceId,
|
|
597
|
-
component: "engine",
|
|
598
|
-
message: e instanceof Error ? e.message : String(e),
|
|
599
|
-
meta: {},
|
|
600
|
-
});
|
|
601
|
-
stripLastToolCalls(messages);
|
|
602
|
-
outcome = "errored";
|
|
603
|
-
done = true;
|
|
1116
|
+
finishTerminalProviderError(errorForClassification, providerClassification);
|
|
604
1117
|
}
|
|
605
1118
|
}
|
|
606
1119
|
(0, runtime_1.emitNervesEvent)({
|
|
@@ -608,7 +1121,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
608
1121
|
trace_id: traceId,
|
|
609
1122
|
component: "engine",
|
|
610
1123
|
message: "runAgent turn completed",
|
|
611
|
-
meta: { done },
|
|
1124
|
+
meta: { done, sawPonder, sawQuerySession, sawBridgeManage },
|
|
612
1125
|
});
|
|
613
|
-
return {
|
|
1126
|
+
return {
|
|
1127
|
+
usage: lastUsage,
|
|
1128
|
+
outcome,
|
|
1129
|
+
completion,
|
|
1130
|
+
...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
|
|
1131
|
+
};
|
|
614
1132
|
}
|