@ouro.bot/cli 0.1.0-alpha.53 → 0.1.0-alpha.530
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 +133 -19
- package/RepairGuide.ouro/agent.json +5 -0
- package/RepairGuide.ouro/psyche/IDENTITY.md +19 -0
- package/RepairGuide.ouro/psyche/SOUL.md +55 -0
- package/RepairGuide.ouro/skills/diagnose-bootstrap-drift.md +54 -0
- package/RepairGuide.ouro/skills/diagnose-broken-remote.md +63 -0
- package/RepairGuide.ouro/skills/diagnose-stacked-typed-issues.md +35 -0
- package/RepairGuide.ouro/skills/diagnose-sync-blocked.md +54 -0
- package/RepairGuide.ouro/skills/diagnose-vault-expired.md +60 -0
- package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +4 -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 +3427 -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 +837 -26
- 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 +427 -0
- package/dist/heart/background-operations.js +281 -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 +119 -129
- package/dist/heart/core.js +948 -243
- package/dist/heart/cross-chat-delivery.js +3 -18
- package/dist/heart/daemon/agent-config-check.js +512 -0
- package/dist/heart/daemon/agent-discovery.js +102 -3
- package/dist/heart/daemon/agent-service.js +522 -0
- package/dist/heart/daemon/agentic-repair.js +554 -0
- package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
- package/dist/heart/daemon/boot-sync-probe.js +197 -0
- package/dist/heart/daemon/cadence.js +70 -0
- package/dist/heart/daemon/cli-defaults.js +643 -0
- package/dist/heart/daemon/cli-exec.js +7544 -0
- package/dist/heart/daemon/cli-help.js +498 -0
- package/dist/heart/daemon/cli-parse.js +1561 -0
- package/dist/heart/daemon/cli-render-doctor.js +57 -0
- package/dist/heart/daemon/cli-render.js +728 -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 -1650
- package/dist/heart/daemon/daemon-entry.js +384 -2
- package/dist/heart/daemon/daemon-health.js +183 -0
- package/dist/heart/daemon/daemon-rollup.js +58 -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 +798 -69
- package/dist/heart/daemon/dns-workflow.js +394 -0
- package/dist/heart/daemon/doctor-types.js +8 -0
- package/dist/heart/daemon/doctor.js +837 -0
- package/dist/heart/daemon/drift-detection.js +146 -0
- package/dist/heart/daemon/health-monitor.js +117 -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 +102 -0
- package/dist/heart/daemon/interactive-repair.js +394 -0
- package/dist/heart/daemon/launchd.js +22 -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 +375 -33
- 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/safe-mode.js +161 -0
- package/dist/heart/daemon/sense-manager.js +341 -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 +330 -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 +162 -17
- package/dist/heart/daemon/up-progress.js +366 -0
- package/dist/heart/daemon/vault-items.js +56 -0
- package/dist/heart/delegation.js +1 -1
- 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 +6 -8
- 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 +205 -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/mail-import-discovery.js +353 -0
- package/dist/heart/mailbox/mailbox-http-hooks.js +66 -0
- package/dist/heart/mailbox/mailbox-http-response.js +7 -0
- package/dist/heart/mailbox/mailbox-http-routes.js +246 -0
- package/dist/heart/mailbox/mailbox-http-static.js +103 -0
- package/dist/heart/mailbox/mailbox-http-transport.js +116 -0
- package/dist/heart/mailbox/mailbox-http.js +99 -0
- package/dist/heart/mailbox/mailbox-read.js +31 -0
- package/dist/heart/mailbox/mailbox-types.js +27 -0
- package/dist/heart/mailbox/mailbox-view.js +195 -0
- package/dist/heart/mailbox/readers/agent-machine.js +382 -0
- package/dist/heart/mailbox/readers/continuity-readers.js +338 -0
- package/dist/heart/mailbox/readers/mail.js +362 -0
- package/dist/heart/mailbox/readers/runtime-readers.js +651 -0
- package/dist/heart/mailbox/readers/sessions.js +232 -0
- package/dist/heart/mailbox/readers/shared.js +111 -0
- package/dist/heart/mcp/mcp-server.js +653 -0
- package/dist/heart/migrate-config.js +100 -0
- package/dist/heart/model-capabilities.js +19 -0
- package/dist/heart/platform.js +81 -0
- package/dist/heart/provider-attempt.js +134 -0
- package/dist/heart/provider-binding-resolver.js +255 -0
- package/dist/heart/provider-credentials.js +425 -0
- package/dist/heart/provider-failover.js +301 -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 +139 -52
- package/dist/heart/providers/azure.js +97 -13
- package/dist/heart/providers/error-classification.js +127 -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 +26 -8
- package/dist/heart/providers/openai-codex.js +55 -40
- package/dist/heart/runtime-capability-check.js +170 -0
- package/dist/heart/runtime-credentials.js +367 -0
- package/dist/heart/sense-truth.js +11 -4
- package/dist/heart/session-activity.js +43 -22
- package/dist/heart/session-events.js +1149 -0
- package/dist/heart/session-playback-cli-main.js +5 -0
- package/dist/heart/session-playback-cli.js +36 -0
- package/dist/heart/session-playback.js +231 -0
- package/dist/heart/session-stats-cli-main.js +5 -0
- package/dist/heart/session-stats.js +182 -0
- package/dist/heart/session-transcript.js +243 -0
- package/dist/heart/start-of-turn-packet.js +345 -0
- package/dist/heart/streaming.js +44 -27
- package/dist/heart/sync-classification.js +176 -0
- package/dist/heart/sync.js +449 -0
- package/dist/heart/target-resolution.js +9 -5
- package/dist/heart/tempo.js +93 -0
- package/dist/heart/temporal-view.js +41 -0
- package/dist/heart/timeouts.js +101 -0
- package/dist/heart/tool-activity-callbacks.js +59 -0
- package/dist/heart/tool-description.js +139 -0
- package/dist/heart/tool-friction.js +55 -0
- package/dist/heart/tool-loop.js +200 -0
- package/dist/heart/turn-context.js +381 -0
- 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/mailbox-ui/assets/index-BPr5vNuM.css +1 -0
- package/dist/mailbox-ui/assets/index-Cm51CY9W.js +61 -0
- package/dist/mailbox-ui/index.html +15 -0
- package/dist/mailroom/attention.js +167 -0
- package/dist/mailroom/autonomy.js +209 -0
- package/dist/mailroom/blob-store.js +606 -0
- package/dist/mailroom/body-cache.js +61 -0
- package/dist/mailroom/core.js +672 -0
- package/dist/mailroom/entry.js +160 -0
- package/dist/mailroom/file-store.js +426 -0
- package/dist/mailroom/mbox-import.js +382 -0
- package/dist/mailroom/outbound.js +380 -0
- package/dist/mailroom/policy.js +263 -0
- package/dist/mailroom/reader.js +228 -0
- package/dist/mailroom/search-cache.js +182 -0
- package/dist/mailroom/search-relevance.js +319 -0
- package/dist/mailroom/smtp-ingress.js +176 -0
- package/dist/mailroom/source-state.js +176 -0
- package/dist/mailroom/thread.js +109 -0
- package/dist/mailroom/travel-extract.js +89 -0
- package/dist/mind/bundle-manifest.js +7 -1
- package/dist/mind/context.js +165 -101
- 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/resolver.js +54 -2
- package/dist/mind/friends/store-file.js +39 -3
- 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 +4 -0
- package/dist/mind/prompt-refresh.js +3 -2
- package/dist/mind/prompt.js +942 -122
- 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 +139 -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/review/cli-main.js +5 -0
- package/dist/nerves/review/cli.js +156 -0
- package/dist/nerves/review/core.js +152 -0
- package/dist/nerves/runtime.js +5 -1
- 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 +816 -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 +31 -5
- package/dist/repertoire/tasks/fix.js +182 -0
- package/dist/repertoire/tasks/index.js +16 -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 +47 -1075
- package/dist/repertoire/tools-bluebubbles.js +1 -0
- package/dist/repertoire/tools-bridge.js +142 -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 +119 -0
- package/dist/repertoire/tools-github.js +1 -7
- package/dist/repertoire/tools-mail.js +1477 -0
- package/dist/repertoire/tools-notes.js +421 -0
- package/dist/repertoire/tools-session.js +750 -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-trip.js +422 -0
- package/dist/repertoire/tools-user-profile.js +144 -0
- package/dist/repertoire/tools-vault.js +40 -0
- package/dist/repertoire/tools.js +108 -100
- 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 +77 -0
- package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +20 -3
- package/dist/senses/bluebubbles/index.js +2236 -0
- 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/processed-log.js +111 -0
- package/dist/senses/bluebubbles/replay.js +129 -0
- package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +16 -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 +607 -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 +85 -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 +520 -209
- package/dist/senses/commands.js +66 -3
- package/dist/senses/habit-turn-message.js +108 -0
- package/dist/senses/inner-dialog-worker.js +175 -21
- package/dist/senses/inner-dialog.js +330 -27
- package/dist/senses/mail-entry.js +66 -0
- package/dist/senses/mail.js +379 -0
- package/dist/senses/pipeline.js +569 -182
- package/dist/senses/proactive-content-guard.js +51 -0
- package/dist/senses/shared-turn.js +248 -0
- package/dist/senses/surface-tool.js +68 -0
- package/dist/senses/teams-entry.js +60 -8
- package/dist/senses/teams.js +387 -98
- package/dist/senses/trust-gate.js +100 -5
- package/dist/trips/core.js +138 -0
- package/dist/trips/store.js +146 -0
- package/package.json +38 -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/heart/session-recall.js +0 -116
- package/dist/mind/associative-recall.js +0 -209
- package/dist/senses/bluebubbles-entry.js +0 -13
- package/dist/senses/bluebubbles.js +0 -1177
- package/dist/senses/debug-activity.js +0 -148
- 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,162 @@
|
|
|
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.isChatStyleChannel = isChatStyleChannel;
|
|
10
|
+
exports.isExternalStateQuery = isExternalStateQuery;
|
|
11
|
+
exports.getSettleRetryError = getSettleRetryError;
|
|
10
12
|
exports.stripLastToolCalls = stripLastToolCalls;
|
|
11
13
|
exports.repairOrphanedToolCalls = repairOrphanedToolCalls;
|
|
12
|
-
exports.isTransientError = isTransientError;
|
|
13
|
-
exports.classifyTransientError = classifyTransientError;
|
|
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
|
+
const tools_2 = require("../repertoire/tools");
|
|
19
20
|
const runtime_1 = require("../nerves/runtime");
|
|
20
21
|
const context_1 = require("../mind/context");
|
|
21
22
|
const prompt_1 = require("../mind/prompt");
|
|
22
|
-
const
|
|
23
|
+
const kept_notes_1 = require("./kept-notes");
|
|
24
|
+
const error_classification_1 = require("./providers/error-classification");
|
|
23
25
|
const anthropic_1 = require("./providers/anthropic");
|
|
24
26
|
const azure_1 = require("./providers/azure");
|
|
25
27
|
const minimax_1 = require("./providers/minimax");
|
|
26
28
|
const openai_codex_1 = require("./providers/openai-codex");
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
29
|
+
const github_copilot_1 = require("./providers/github-copilot");
|
|
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 packets_1 = require("../arc/packets");
|
|
35
|
+
const tool_friction_1 = require("./tool-friction");
|
|
36
|
+
const provider_models_1 = require("./provider-models");
|
|
37
|
+
const provider_credentials_1 = require("./provider-credentials");
|
|
38
|
+
const provider_state_1 = require("./provider-state");
|
|
39
|
+
const provider_attempt_1 = require("./provider-attempt");
|
|
40
|
+
const _providerRuntimes = {
|
|
41
|
+
human: null,
|
|
42
|
+
agent: null,
|
|
43
|
+
};
|
|
44
|
+
function providerLaneForFacing(facing) {
|
|
45
|
+
return facing === "human" ? "outward" : "inner";
|
|
46
|
+
}
|
|
47
|
+
function resolveRuntimeProviderBinding(facing) {
|
|
48
|
+
const agentName = (0, identity_2.getAgentName)();
|
|
49
|
+
const lane = providerLaneForFacing(facing);
|
|
50
|
+
const stateResult = (0, provider_state_1.readProviderState)((0, identity_2.getAgentRoot)(agentName));
|
|
51
|
+
if (stateResult.ok) {
|
|
52
|
+
const binding = stateResult.state.lanes[lane];
|
|
53
|
+
return { lane, provider: binding.provider, model: binding.model };
|
|
54
|
+
}
|
|
55
|
+
if (stateResult.reason === "invalid") {
|
|
56
|
+
throw new Error(`provider state for ${agentName} is invalid at ${stateResult.statePath}: ${stateResult.error}`);
|
|
57
|
+
}
|
|
58
|
+
// First-run and SerpentGuide bootstrap path. Daemon startup normally
|
|
59
|
+
// bootstraps state/providers.json from agent.json before model calls.
|
|
60
|
+
const config = (0, identity_1.loadAgentConfig)();
|
|
61
|
+
const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
|
|
62
|
+
return { lane, provider: facingConfig.provider, model: facingConfig.model };
|
|
63
|
+
}
|
|
64
|
+
async function getProviderRuntimeFingerprint(facing) {
|
|
65
|
+
const agentName = (0, identity_2.getAgentName)();
|
|
66
|
+
const binding = resolveRuntimeProviderBinding(facing);
|
|
67
|
+
const credential = await (0, provider_credentials_1.readProviderCredentialRecord)(agentName, binding.provider);
|
|
68
|
+
if (!credential.ok) {
|
|
69
|
+
throw new Error([
|
|
70
|
+
`${binding.lane} provider ${binding.provider} (${binding.model}) has no credentials for ${agentName}.`,
|
|
71
|
+
credential.error,
|
|
72
|
+
`Run \`ouro auth --agent ${agentName} --provider ${binding.provider}\`.`,
|
|
73
|
+
].join("\n"));
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
binding,
|
|
77
|
+
fingerprint: JSON.stringify({
|
|
78
|
+
lane: binding.lane,
|
|
79
|
+
provider: binding.provider,
|
|
80
|
+
model: binding.model,
|
|
81
|
+
credentialRevision: credential.record.revision,
|
|
82
|
+
}),
|
|
83
|
+
credential: credential.record,
|
|
34
84
|
};
|
|
85
|
+
}
|
|
86
|
+
function createProviderRegistry() {
|
|
35
87
|
return {
|
|
36
|
-
resolve() {
|
|
37
|
-
const
|
|
38
|
-
|
|
88
|
+
resolve(provider, model, credential) {
|
|
89
|
+
const providerConfig = { ...credential.config, ...credential.credentials };
|
|
90
|
+
switch (provider) {
|
|
91
|
+
case "azure":
|
|
92
|
+
return (0, azure_1.createAzureProviderRuntime)(model, providerConfig);
|
|
93
|
+
case "anthropic":
|
|
94
|
+
return (0, anthropic_1.createAnthropicProviderRuntime)(model, providerConfig);
|
|
95
|
+
case "minimax":
|
|
96
|
+
return (0, minimax_1.createMinimaxProviderRuntime)(model, providerConfig);
|
|
97
|
+
case "openai-codex":
|
|
98
|
+
return (0, openai_codex_1.createOpenAICodexProviderRuntime)(model, providerConfig);
|
|
99
|
+
case "github-copilot":
|
|
100
|
+
return (0, github_copilot_1.createGithubCopilotProviderRuntime)(model, providerConfig);
|
|
101
|
+
}
|
|
39
102
|
},
|
|
40
103
|
};
|
|
41
104
|
}
|
|
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");
|
|
105
|
+
async function getProviderRuntime(facing = "human") {
|
|
106
|
+
try {
|
|
107
|
+
const { binding, fingerprint, credential } = await getProviderRuntimeFingerprint(facing);
|
|
108
|
+
const cached = _providerRuntimes[facing];
|
|
109
|
+
if (!cached || cached.fingerprint !== fingerprint) {
|
|
110
|
+
const runtime = createProviderRegistry().resolve(binding.provider, binding.model, credential);
|
|
111
|
+
_providerRuntimes[facing] = runtime ? { fingerprint, runtime } : null;
|
|
71
112
|
}
|
|
72
113
|
}
|
|
73
|
-
|
|
114
|
+
catch (error) {
|
|
115
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
116
|
+
(0, runtime_1.emitNervesEvent)({
|
|
117
|
+
level: "error",
|
|
118
|
+
event: "engine.provider_init_error",
|
|
119
|
+
component: "engine",
|
|
120
|
+
message: msg,
|
|
121
|
+
meta: { facing },
|
|
122
|
+
});
|
|
123
|
+
// eslint-disable-next-line no-console -- pre-boot guard: provider init failure
|
|
124
|
+
console.error(`\n[fatal] ${msg}\n`);
|
|
125
|
+
throw error instanceof Error ? error : new Error(msg);
|
|
126
|
+
}
|
|
127
|
+
if (!_providerRuntimes[facing]) {
|
|
128
|
+
const msg = "provider runtime could not be initialized.";
|
|
129
|
+
(0, runtime_1.emitNervesEvent)({
|
|
130
|
+
level: "error",
|
|
131
|
+
event: "engine.provider_init_error",
|
|
132
|
+
component: "engine",
|
|
133
|
+
message: msg,
|
|
134
|
+
meta: { facing },
|
|
135
|
+
});
|
|
136
|
+
// eslint-disable-next-line no-console -- pre-boot guard: provider init failure
|
|
137
|
+
console.error(`\n[fatal] ${msg}\n`);
|
|
138
|
+
throw new Error(msg);
|
|
139
|
+
}
|
|
140
|
+
return _providerRuntimes[facing].runtime;
|
|
74
141
|
}
|
|
75
142
|
/**
|
|
76
|
-
* Clear the cached provider runtime so the next
|
|
77
|
-
*
|
|
78
|
-
*
|
|
143
|
+
* Clear the cached provider runtime so the next access re-creates it from
|
|
144
|
+
* current config. Runtime access also auto-refreshes when the selected
|
|
145
|
+
* provider fingerprint changes on disk.
|
|
79
146
|
*/
|
|
80
147
|
function resetProviderRuntime() {
|
|
81
|
-
|
|
148
|
+
_providerRuntimes.human = null;
|
|
149
|
+
_providerRuntimes.agent = null;
|
|
82
150
|
}
|
|
83
|
-
function getModel() {
|
|
84
|
-
return
|
|
151
|
+
function getModel(facing = "human") {
|
|
152
|
+
return resolveRuntimeProviderBinding(facing).model;
|
|
85
153
|
}
|
|
86
|
-
function getProvider() {
|
|
87
|
-
return
|
|
154
|
+
function getProvider(facing = "human") {
|
|
155
|
+
return resolveRuntimeProviderBinding(facing).provider;
|
|
88
156
|
}
|
|
89
|
-
function createSummarize() {
|
|
157
|
+
function createSummarize(facing = "human") {
|
|
90
158
|
return async (transcript, instruction) => {
|
|
91
|
-
const runtime = getProviderRuntime();
|
|
159
|
+
const runtime = await getProviderRuntime(facing);
|
|
92
160
|
const client = runtime.client;
|
|
93
161
|
const response = await client.chat.completions.create({
|
|
94
162
|
model: runtime.model,
|
|
@@ -101,32 +169,66 @@ function createSummarize() {
|
|
|
101
169
|
return response.choices?.[0]?.message?.content ?? transcript;
|
|
102
170
|
};
|
|
103
171
|
}
|
|
104
|
-
function getProviderDisplayLabel() {
|
|
105
|
-
const
|
|
172
|
+
function getProviderDisplayLabel(facing = "human") {
|
|
173
|
+
const binding = resolveRuntimeProviderBinding(facing);
|
|
174
|
+
const provider = binding.provider;
|
|
175
|
+
const model = binding.model || "unknown";
|
|
106
176
|
const providerLabelBuilders = {
|
|
107
|
-
azure: () =>
|
|
177
|
+
azure: () => {
|
|
178
|
+
return `azure openai (model: ${model})`;
|
|
179
|
+
},
|
|
108
180
|
anthropic: () => `anthropic (${model})`,
|
|
109
181
|
minimax: () => `minimax (${model})`,
|
|
110
182
|
"openai-codex": () => `openai codex (${model})`,
|
|
183
|
+
/* v8 ignore next -- branch: tested via display label unit test @preserve */
|
|
184
|
+
"github-copilot": () => `github copilot (${model})`,
|
|
111
185
|
};
|
|
112
|
-
return providerLabelBuilders[
|
|
186
|
+
return providerLabelBuilders[provider]();
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Strip <think>...</think> blocks for the violation-detection check at the
|
|
190
|
+
* end of a streaming turn. Used to tell legitimate text-only responses
|
|
191
|
+
* apart from the MiniMax-M2.7 "only thinking, no tool call" violation
|
|
192
|
+
* shape. Mirrors the more thorough stripThinkBlocks helper in
|
|
193
|
+
* senses/shared-turn.ts (which is for operator-facing output) — kept
|
|
194
|
+
* inline here to avoid pulling senses/ into the core module's import graph.
|
|
195
|
+
*/
|
|
196
|
+
function stripThinkBlocksForViolationCheck(input) {
|
|
197
|
+
let out = input;
|
|
198
|
+
for (;;) {
|
|
199
|
+
const open = out.indexOf("<think>");
|
|
200
|
+
if (open === -1)
|
|
201
|
+
break;
|
|
202
|
+
const close = out.indexOf("</think>", open + "<think>".length);
|
|
203
|
+
if (close === -1) {
|
|
204
|
+
out = out.slice(0, open);
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
out = out.slice(0, open) + out.slice(close + "</think>".length);
|
|
208
|
+
}
|
|
209
|
+
return out.trim();
|
|
210
|
+
}
|
|
211
|
+
function hasFreshPendingWork(options) {
|
|
212
|
+
const pendingMessages = options?.pendingMessages;
|
|
213
|
+
if (!Array.isArray(pendingMessages))
|
|
214
|
+
return false;
|
|
215
|
+
return pendingMessages.some((message) => typeof message?.content === "string"
|
|
216
|
+
&& message.content.trim().length > 0);
|
|
113
217
|
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
//
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
Object.defineProperty(exports, "buildSystem", { enumerable: true, get: function () { return prompt_2.buildSystem; } });
|
|
129
|
-
function parseFinalAnswerPayload(argumentsText) {
|
|
218
|
+
/** Chat-style channels expose the `speak` tool — outer human-conversation channels
|
|
219
|
+
* where mid-turn delivery is meaningful. Inner dialog has `ponder`. MCP returns
|
|
220
|
+
* synchronously. Mail is batch. Anything else (unknown channel) treats as non-chat. */
|
|
221
|
+
function isChatStyleChannel(channel) {
|
|
222
|
+
return channel === "cli" || channel === "teams" || channel === "bluebubbles";
|
|
223
|
+
}
|
|
224
|
+
// Sole-call tools must be the only tool call in a turn. When they appear
|
|
225
|
+
// alongside other tools, the sole-call tool is rejected with this message.
|
|
226
|
+
const SOLE_CALL_REJECTION = {
|
|
227
|
+
settle: "rejected: settle must be the only tool call. finish your work first, then call settle alone.",
|
|
228
|
+
observe: "rejected: observe must be the only tool call. call observe alone when you want to stay silent.",
|
|
229
|
+
rest: "rejected: rest must be the only tool call. finish your work first, then call rest alone.",
|
|
230
|
+
};
|
|
231
|
+
function parseSettlePayload(argumentsText) {
|
|
130
232
|
try {
|
|
131
233
|
const parsed = JSON.parse(argumentsText);
|
|
132
234
|
if (typeof parsed === "string") {
|
|
@@ -146,18 +248,93 @@ function parseFinalAnswerPayload(argumentsText) {
|
|
|
146
248
|
return {};
|
|
147
249
|
}
|
|
148
250
|
}
|
|
149
|
-
function
|
|
251
|
+
function parsePonderPayload(argumentsText) {
|
|
252
|
+
try {
|
|
253
|
+
const parsed = JSON.parse(argumentsText);
|
|
254
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
255
|
+
}
|
|
256
|
+
catch {
|
|
257
|
+
return {};
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
function parseSuccessCriteria(raw) {
|
|
261
|
+
if (typeof raw !== "string")
|
|
262
|
+
return null;
|
|
263
|
+
const criteria = raw
|
|
264
|
+
.split("\n")
|
|
265
|
+
.map((line) => line.replace(/^\s*[-*]\s*/, "").trim())
|
|
266
|
+
.filter((line) => line.length > 0);
|
|
267
|
+
return criteria.length > 0 ? criteria : null;
|
|
268
|
+
}
|
|
269
|
+
function parsePacketPayload(raw) {
|
|
270
|
+
if (typeof raw !== "string")
|
|
271
|
+
return null;
|
|
272
|
+
try {
|
|
273
|
+
const parsed = JSON.parse(raw);
|
|
274
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
|
275
|
+
? parsed
|
|
276
|
+
: null;
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
function normalizeLegacyPonderArgs(parsed) {
|
|
283
|
+
if (typeof parsed.thought !== "string" || parsed.thought.trim().length === 0) {
|
|
284
|
+
return parsed;
|
|
285
|
+
}
|
|
286
|
+
return {
|
|
287
|
+
action: "create",
|
|
288
|
+
kind: "reflection",
|
|
289
|
+
objective: parsed.thought.trim(),
|
|
290
|
+
summary: typeof parsed.say === "string" ? parsed.say.trim() : "",
|
|
291
|
+
success_criteria: "- preserve the thread for later work",
|
|
292
|
+
payload_json: "{}",
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
function buildPonderResult(packet, action, returnObligationId) {
|
|
296
|
+
return JSON.stringify({
|
|
297
|
+
ok: true,
|
|
298
|
+
packet_id: packet.id,
|
|
299
|
+
action,
|
|
300
|
+
status: packet.status,
|
|
301
|
+
return_obligation_id: returnObligationId,
|
|
302
|
+
}, null, 2);
|
|
303
|
+
}
|
|
304
|
+
/** Returns true when a tool call queries external state (GitHub, npm registry). */
|
|
305
|
+
function isExternalStateQuery(toolName, args) {
|
|
306
|
+
if (toolName !== "shell")
|
|
307
|
+
return false;
|
|
308
|
+
const cmd = String(args.command ?? "");
|
|
309
|
+
return /\bgh\s+(pr|run|api|issue)\b/.test(cmd) || /\bnpm\s+(view|info|show)\b/.test(cmd);
|
|
310
|
+
}
|
|
311
|
+
function getSettleRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp, _delegationDecision, sawSendMessageSelf, sawPonder, _sawQuerySession, currentObligation, innerJob, sawExternalStateQuery) {
|
|
312
|
+
// Delegation adherence removed: the delegation decision is surfaced in the
|
|
313
|
+
// system prompt as a suggestion. Hard-gating settle caused infinite
|
|
314
|
+
// rejection loops where the agent couldn't respond to the user at all.
|
|
315
|
+
// The agent is free to follow or ignore the delegation hint.
|
|
316
|
+
// 2. Pending obligation not addressed
|
|
317
|
+
if (innerJob?.obligationStatus === "pending" && !sawSendMessageSelf && !sawPonder) {
|
|
318
|
+
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.";
|
|
319
|
+
}
|
|
320
|
+
// 3. mustResolveBeforeHandoff + missing intent
|
|
150
321
|
if (mustResolveBeforeHandoff && !intent) {
|
|
151
|
-
return "your
|
|
322
|
+
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
323
|
}
|
|
324
|
+
// 4. mustResolveBeforeHandoff + direct_reply without follow-up
|
|
153
325
|
if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
|
|
154
|
-
return "your
|
|
326
|
+
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.";
|
|
155
327
|
}
|
|
156
|
-
|
|
328
|
+
// 5. mustResolveBeforeHandoff + complete while a live return loop is still active
|
|
329
|
+
if (mustResolveBeforeHandoff && intent === "complete" && currentObligation && !sawSteeringFollowUp) {
|
|
330
|
+
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.";
|
|
331
|
+
}
|
|
332
|
+
// 6. External-state grounding: obligation + complete requires fresh external verification
|
|
333
|
+
if (intent === "complete" && currentObligation && !sawExternalStateQuery && !sawSteeringFollowUp) {
|
|
334
|
+
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.";
|
|
335
|
+
}
|
|
336
|
+
return null;
|
|
157
337
|
}
|
|
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
338
|
function upsertSystemPrompt(messages, systemText) {
|
|
162
339
|
const systemMessage = { role: "system", content: systemText };
|
|
163
340
|
if (messages[0]?.role === "system") {
|
|
@@ -195,27 +372,39 @@ const TOOL_SCAN_BOUNDARY_ROLES = new Set(["assistant", "user"]);
|
|
|
195
372
|
// 1. If an assistant message has tool_calls but missing tool results, inject synthetic error results.
|
|
196
373
|
// 2. If a tool result's tool_call_id doesn't match any tool_calls in a preceding assistant message, remove it.
|
|
197
374
|
// This prevents 400 errors from the API after an aborted turn.
|
|
375
|
+
//
|
|
376
|
+
// Position-aware: a tool result is orphaned when its tool_call_id hasn't been
|
|
377
|
+
// defined by an assistant message AT THIS POSITION yet. MiniMax-M2.7 reuses
|
|
378
|
+
// canonical tool_call_ids across turns, so the global-set check that this
|
|
379
|
+
// function used previously kept misordered tool results that MiniMax then
|
|
380
|
+
// rejected with error 2013 ("tool result's tool id not found"). Walking
|
|
381
|
+
// in order matches what MiniMax actually enforces.
|
|
198
382
|
function repairOrphanedToolCalls(messages) {
|
|
199
|
-
// Pass 1:
|
|
200
|
-
|
|
201
|
-
|
|
383
|
+
// Pass 1: walk in order, accumulate seen tool_call_ids per-position, and
|
|
384
|
+
// mark tool results for removal if their id hasn't been defined yet.
|
|
385
|
+
const seenCallIds = new Set();
|
|
386
|
+
const removeIndices = [];
|
|
387
|
+
for (let i = 0; i < messages.length; i++) {
|
|
388
|
+
const msg = messages[i];
|
|
202
389
|
if (msg.role === "assistant") {
|
|
203
390
|
const asst = msg;
|
|
204
391
|
if (asst.tool_calls) {
|
|
205
392
|
for (const tc of asst.tool_calls)
|
|
206
|
-
|
|
393
|
+
seenCallIds.add(tc.id);
|
|
207
394
|
}
|
|
395
|
+
continue;
|
|
208
396
|
}
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
const toolMsg = messages[i];
|
|
214
|
-
if (!validCallIds.has(toolMsg.tool_call_id)) {
|
|
215
|
-
messages.splice(i, 1);
|
|
397
|
+
if (msg.role === "tool") {
|
|
398
|
+
const toolMsg = msg;
|
|
399
|
+
if (!seenCallIds.has(toolMsg.tool_call_id)) {
|
|
400
|
+
removeIndices.push(i);
|
|
216
401
|
}
|
|
217
402
|
}
|
|
218
403
|
}
|
|
404
|
+
// Splice from the end so earlier indices stay valid.
|
|
405
|
+
for (let i = removeIndices.length - 1; i >= 0; i--) {
|
|
406
|
+
messages.splice(removeIndices[i], 1);
|
|
407
|
+
}
|
|
219
408
|
// Pass 3: inject synthetic results for tool_calls missing their tool results
|
|
220
409
|
for (let i = 0; i < messages.length; i++) {
|
|
221
410
|
const msg = messages[i];
|
|
@@ -237,10 +426,13 @@ function repairOrphanedToolCalls(messages) {
|
|
|
237
426
|
}
|
|
238
427
|
const missing = asst.tool_calls.filter((tc) => !resultIds.has(tc.id));
|
|
239
428
|
if (missing.length > 0) {
|
|
429
|
+
// AX rule: the agent must see what happened. Don't say "interrupted"
|
|
430
|
+
// — that's vague. Tell them the result was lost, possible causes,
|
|
431
|
+
// and what to do next.
|
|
240
432
|
const syntheticResults = missing.map((tc) => ({
|
|
241
433
|
role: "tool",
|
|
242
434
|
tool_call_id: tc.id,
|
|
243
|
-
content: "error: tool call was
|
|
435
|
+
content: "error: this tool call's result was lost — the previous turn ended before the tool finished (provider rejection, daemon interrupt, or the tool itself errored). if the work needs to be done, retry the tool call now.",
|
|
244
436
|
}));
|
|
245
437
|
let insertAt = i + 1;
|
|
246
438
|
while (insertAt < messages.length && messages[insertAt].role === "tool")
|
|
@@ -263,49 +455,67 @@ function isContextOverflow(err) {
|
|
|
263
455
|
return true;
|
|
264
456
|
return false;
|
|
265
457
|
}
|
|
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
|
-
|
|
458
|
+
const RETRY_LABELS = {
|
|
459
|
+
"auth-failure": "auth error",
|
|
460
|
+
"usage-limit": "usage limit",
|
|
461
|
+
"rate-limit": "rate limited",
|
|
462
|
+
"server-error": "server error",
|
|
463
|
+
"network-error": "network error",
|
|
464
|
+
"unknown": "error",
|
|
465
|
+
};
|
|
466
|
+
function waitForProviderRetry(delayMs, signal) {
|
|
467
|
+
if (!signal) {
|
|
468
|
+
return new Promise((resolve) => {
|
|
469
|
+
setTimeout(resolve, delayMs);
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
return new Promise((resolve, reject) => {
|
|
473
|
+
let timer;
|
|
474
|
+
const onAbort = () => {
|
|
475
|
+
clearTimeout(timer);
|
|
476
|
+
reject(new provider_attempt_1.ProviderAttemptAbortError());
|
|
477
|
+
};
|
|
478
|
+
timer = setTimeout(() => {
|
|
479
|
+
signal.removeEventListener("abort", onAbort);
|
|
480
|
+
resolve();
|
|
481
|
+
}, delayMs);
|
|
482
|
+
if (signal.aborted) {
|
|
483
|
+
onAbort();
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
487
|
+
});
|
|
292
488
|
}
|
|
293
|
-
function
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
489
|
+
function buildAuthFailureGuidance(provider, model, agentName, detail) {
|
|
490
|
+
const mismatch = (0, provider_models_1.getProviderModelMismatchMessage)(provider, model);
|
|
491
|
+
const modelLabel = model
|
|
492
|
+
? mismatch
|
|
493
|
+
? `${provider} [configured model: ${model}]`
|
|
494
|
+
: `${provider} (${model})`
|
|
495
|
+
: provider;
|
|
496
|
+
const lines = [`${modelLabel} authentication failed.`];
|
|
497
|
+
const cleanDetail = detail.replace(/\s+/g, " ").trim();
|
|
498
|
+
if (cleanDetail)
|
|
499
|
+
lines.push(`provider detail: ${cleanDetail.length > 300 ? `${cleanDetail.slice(0, 297)}...` : cleanDetail}`);
|
|
500
|
+
lines.push("");
|
|
501
|
+
lines.push("To keep using this provider:");
|
|
502
|
+
lines.push(` 1. Run \`ouro auth --agent ${agentName} --provider ${provider}\``);
|
|
503
|
+
if (mismatch) {
|
|
504
|
+
const defaultModel = (0, provider_models_1.getDefaultModelForProvider)(provider);
|
|
505
|
+
lines.push("");
|
|
506
|
+
lines.push("Config warning:");
|
|
507
|
+
lines.push(` - ${mismatch}`);
|
|
508
|
+
lines.push(" - Repair the configured model with:");
|
|
509
|
+
lines.push(` \`ouro config model --agent ${agentName} --facing human ${defaultModel}\``);
|
|
510
|
+
lines.push(` \`ouro config model --agent ${agentName} --facing agent ${defaultModel}\``);
|
|
511
|
+
}
|
|
512
|
+
lines.push("");
|
|
513
|
+
lines.push(`To use another configured provider instead, run \`ouro auth switch --agent ${agentName} --provider <provider>\`.`);
|
|
514
|
+
return lines.join("\n");
|
|
304
515
|
}
|
|
305
|
-
const MAX_RETRIES = 3;
|
|
306
|
-
const RETRY_BASE_MS = 2000;
|
|
307
516
|
async function runAgent(messages, callbacks, channel, signal, options) {
|
|
308
|
-
const
|
|
517
|
+
const facing = (0, channel_1.channelToFacing)(channel);
|
|
518
|
+
let providerRuntime = await getProviderRuntime(facing);
|
|
309
519
|
const provider = providerRuntime.id;
|
|
310
520
|
const toolChoiceRequired = options?.toolChoiceRequired ?? true;
|
|
311
521
|
const traceId = options?.traceId;
|
|
@@ -329,6 +539,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
329
539
|
// Refresh system prompt at start of each turn when channel is provided.
|
|
330
540
|
// If refresh fails, keep existing system prompt (or inject a minimal safe fallback)
|
|
331
541
|
// so turn execution remains consistent and non-fatal.
|
|
542
|
+
let structuredSystemPrompt;
|
|
332
543
|
if (channel) {
|
|
333
544
|
try {
|
|
334
545
|
const buildSystemOptions = {
|
|
@@ -337,7 +548,8 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
337
548
|
supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
|
|
338
549
|
};
|
|
339
550
|
const refreshed = await (0, prompt_1.buildSystem)(channel, buildSystemOptions, currentContext);
|
|
340
|
-
|
|
551
|
+
structuredSystemPrompt = refreshed;
|
|
552
|
+
upsertSystemPrompt(messages, (0, prompt_1.flattenSystemPrompt)(refreshed));
|
|
341
553
|
}
|
|
342
554
|
catch (error) {
|
|
343
555
|
const hadExistingSystemPrompt = messages[0]?.role === "system" && typeof messages[0].content === "string";
|
|
@@ -358,40 +570,120 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
358
570
|
});
|
|
359
571
|
}
|
|
360
572
|
}
|
|
361
|
-
|
|
573
|
+
if (channel) {
|
|
574
|
+
await (0, kept_notes_1.injectKeptNotes)(messages, {
|
|
575
|
+
channel,
|
|
576
|
+
friend: currentContext?.friend,
|
|
577
|
+
judge: async (input) => (0, kept_notes_1.createKeptNotesJudge)(await getProviderRuntime("agent"), signal)(input),
|
|
578
|
+
signal,
|
|
579
|
+
traceId,
|
|
580
|
+
});
|
|
581
|
+
}
|
|
362
582
|
let done = false;
|
|
363
583
|
let lastUsage;
|
|
364
584
|
let overflowRetried = false;
|
|
365
|
-
let
|
|
366
|
-
let outcome = "complete";
|
|
585
|
+
let outcome = "settled";
|
|
367
586
|
let completion;
|
|
587
|
+
let terminalError;
|
|
588
|
+
let terminalErrorClassification;
|
|
368
589
|
let sawSteeringFollowUp = false;
|
|
369
590
|
let mustResolveBeforeHandoffActive = options?.mustResolveBeforeHandoff === true;
|
|
370
591
|
let currentReasoningEffort = "medium";
|
|
592
|
+
let sawSendMessageSelf = false;
|
|
593
|
+
let sawPonder = false;
|
|
594
|
+
let sawQuerySession = false;
|
|
595
|
+
let sawBridgeManage = false;
|
|
596
|
+
let sawExternalStateQuery = false;
|
|
597
|
+
// Once-per-turn flag for the fresh-work rest gate. Without this, an agent
|
|
598
|
+
// that called rest, was told "fresh work arrived", processed the items,
|
|
599
|
+
// and called rest again would get the same message forever — the gate
|
|
600
|
+
// condition is read from the turn-start snapshot of pendingMessages,
|
|
601
|
+
// which doesn't update mid-turn. The agent only needs to be told once;
|
|
602
|
+
// after that, repeated rest attempts mean they've acknowledged.
|
|
603
|
+
let freshWorkGateFired = false;
|
|
604
|
+
// Counter for "no tool call returned despite tool_choice=required" violations.
|
|
605
|
+
// MiniMax reasoning models occasionally emit only a <think>...</think>
|
|
606
|
+
// block and stop, without any tool call — even when tool_choice is set to
|
|
607
|
+
// "required". This is a provider-level violation; the harness retries with
|
|
608
|
+
// a corrective nudge up to a small cap rather than silently accepting an
|
|
609
|
+
// empty turn.
|
|
610
|
+
let noToolCallRetries = 0;
|
|
611
|
+
const NO_TOOL_CALL_MAX_RETRIES = 2;
|
|
612
|
+
const toolLoopState = (0, tool_loop_1.createToolLoopState)();
|
|
613
|
+
const toolFrictionLedger = (0, tool_friction_1.createToolFrictionLedger)();
|
|
614
|
+
const finishTerminalProviderError = (error, classification) => {
|
|
615
|
+
terminalError = error;
|
|
616
|
+
terminalErrorClassification = classification;
|
|
617
|
+
/* v8 ignore start — auth-failure guidance: tested via provider error classification tests @preserve */
|
|
618
|
+
if (terminalErrorClassification === "auth-failure") {
|
|
619
|
+
const agentName = (0, identity_2.getAgentName)();
|
|
620
|
+
const currentProvider = providerRuntime.id;
|
|
621
|
+
callbacks.onError(new Error(buildAuthFailureGuidance(currentProvider, providerRuntime.model, agentName, terminalError.message)), "terminal");
|
|
622
|
+
}
|
|
623
|
+
else {
|
|
624
|
+
callbacks.onError(terminalError, "terminal");
|
|
625
|
+
}
|
|
626
|
+
/* v8 ignore stop */
|
|
627
|
+
const errorDetails = (0, error_classification_1.extractProviderErrorDetails)(terminalError);
|
|
628
|
+
(0, runtime_1.emitNervesEvent)({
|
|
629
|
+
level: "error",
|
|
630
|
+
event: "engine.error",
|
|
631
|
+
trace_id: traceId,
|
|
632
|
+
component: "engine",
|
|
633
|
+
message: terminalError.message,
|
|
634
|
+
meta: {
|
|
635
|
+
provider: providerRuntime.id,
|
|
636
|
+
model: providerRuntime.model,
|
|
637
|
+
errorClassification: terminalErrorClassification,
|
|
638
|
+
...(errorDetails.status !== undefined ? { httpStatus: errorDetails.status } : {}),
|
|
639
|
+
...(errorDetails.bodyExcerpt ? { bodyExcerpt: errorDetails.bodyExcerpt } : {}),
|
|
640
|
+
summary: (0, error_classification_1.summarizeProviderError)(terminalError, terminalErrorClassification, providerRuntime.id, providerRuntime.model),
|
|
641
|
+
},
|
|
642
|
+
});
|
|
643
|
+
stripLastToolCalls(messages);
|
|
644
|
+
outcome = "errored";
|
|
645
|
+
done = true;
|
|
646
|
+
};
|
|
371
647
|
// Prevent MaxListenersExceeded warning — each iteration adds a listener
|
|
372
648
|
try {
|
|
373
649
|
require("events").setMaxListeners(50, signal);
|
|
374
650
|
}
|
|
375
651
|
catch { /* unsupported */ }
|
|
376
652
|
const toolPreferences = currentContext?.friend?.toolPreferences;
|
|
377
|
-
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);
|
|
653
|
+
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);
|
|
378
654
|
// Augment tool context with reasoning effort controls from provider
|
|
379
655
|
const augmentedToolContext = options?.toolContext
|
|
380
656
|
? {
|
|
381
657
|
...options.toolContext,
|
|
382
658
|
supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
|
|
383
659
|
setReasoningEffort: (level) => { currentReasoningEffort = level; },
|
|
660
|
+
activeWorkFrame: options?.activeWorkFrame,
|
|
384
661
|
}
|
|
385
662
|
: undefined;
|
|
386
663
|
// Rebase provider-owned turn state from canonical messages at user-turn start.
|
|
387
664
|
// This prevents stale provider caches from replaying prior-turn context.
|
|
388
665
|
providerRuntime.resetTurnState(messages);
|
|
389
666
|
while (!done) {
|
|
390
|
-
//
|
|
391
|
-
//
|
|
392
|
-
//
|
|
393
|
-
//
|
|
394
|
-
|
|
667
|
+
// Channel-based tool filtering:
|
|
668
|
+
// - Inner dialog: exclude send_message (delivery via surface), observe (no one to observe)
|
|
669
|
+
// - All outward channels (1:1, group, reaction): observe available
|
|
670
|
+
//
|
|
671
|
+
// ponder, settle/rest, surface, and observe are always assembled based on channel context.
|
|
672
|
+
// ponder is available in ALL channels (outer: think privately, inner: keep turning).
|
|
673
|
+
// Inner dialog gets restTool instead of settleTool (rest = end turn, gated by attention queue).
|
|
674
|
+
// toolChoiceRequired only controls whether tool_choice: "required" is set in the API call.
|
|
675
|
+
const isInnerDialog = channel === "inner";
|
|
676
|
+
const filteredBaseTools = isInnerDialog
|
|
677
|
+
? baseTools.filter((t) => t.function.name !== "send_message")
|
|
678
|
+
: baseTools;
|
|
679
|
+
const activeTools = [
|
|
680
|
+
...filteredBaseTools,
|
|
681
|
+
tools_1.ponderTool,
|
|
682
|
+
...(isInnerDialog ? [tools_2.surfaceToolDef, tools_1.restTool] : []),
|
|
683
|
+
...(!isInnerDialog ? [tools_1.observeTool] : []),
|
|
684
|
+
...(!isInnerDialog ? [tools_1.settleTool] : []),
|
|
685
|
+
...(isChatStyleChannel(channel ?? "") ? [tools_1.speakTool] : []),
|
|
686
|
+
];
|
|
395
687
|
const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
|
|
396
688
|
if (steeringFollowUps.length > 0) {
|
|
397
689
|
const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
|
|
@@ -418,26 +710,124 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
418
710
|
break;
|
|
419
711
|
}
|
|
420
712
|
try {
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
713
|
+
const callProviderTurn = async () => {
|
|
714
|
+
callbacks.onModelStart();
|
|
715
|
+
try {
|
|
716
|
+
return await providerRuntime.streamTurn({
|
|
717
|
+
messages,
|
|
718
|
+
activeTools,
|
|
719
|
+
callbacks,
|
|
720
|
+
signal,
|
|
721
|
+
traceId,
|
|
722
|
+
toolChoiceRequired,
|
|
723
|
+
reasoningEffort: currentReasoningEffort,
|
|
724
|
+
eagerSettleStreaming: true,
|
|
725
|
+
systemPrompt: structuredSystemPrompt,
|
|
726
|
+
});
|
|
727
|
+
}
|
|
728
|
+
catch (error) {
|
|
729
|
+
if (signal?.aborted)
|
|
730
|
+
throw new provider_attempt_1.ProviderAttemptAbortError();
|
|
731
|
+
throw error;
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
const callProviderTurnWithOverflowRecovery = async () => {
|
|
735
|
+
try {
|
|
736
|
+
return await callProviderTurn();
|
|
737
|
+
}
|
|
738
|
+
catch (error) {
|
|
739
|
+
if (error instanceof provider_attempt_1.ProviderAttemptAbortError)
|
|
740
|
+
throw error;
|
|
741
|
+
if (isContextOverflow(error) && !overflowRetried) {
|
|
742
|
+
overflowRetried = true;
|
|
743
|
+
stripLastToolCalls(messages);
|
|
744
|
+
const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
|
|
745
|
+
const trimmed = (0, context_1.trimMessages)(messages, maxTokens, contextMargin, maxTokens * 2);
|
|
746
|
+
messages.splice(0, messages.length, ...trimmed);
|
|
747
|
+
providerRuntime.resetTurnState(messages);
|
|
748
|
+
callbacks.onError(new Error("context trimmed, retrying..."), "transient");
|
|
749
|
+
return callProviderTurn();
|
|
750
|
+
}
|
|
751
|
+
throw error;
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
const attempt = await (0, provider_attempt_1.runProviderAttempt)({
|
|
755
|
+
operation: "turn",
|
|
756
|
+
provider: providerRuntime.id,
|
|
757
|
+
model: providerRuntime.model,
|
|
758
|
+
run: callProviderTurnWithOverflowRecovery,
|
|
759
|
+
classifyError: (error) => providerRuntime.classifyError(error),
|
|
760
|
+
onRetry: async (record, maxAttempts) => {
|
|
761
|
+
const delayMs = record.delayMs;
|
|
762
|
+
const seconds = delayMs / 1000;
|
|
763
|
+
const cause = RETRY_LABELS[record.classification];
|
|
764
|
+
try {
|
|
765
|
+
await (0, provider_credentials_1.refreshProviderCredentialPool)((0, identity_2.getAgentName)(), {
|
|
766
|
+
preserveCachedOnFailure: true,
|
|
767
|
+
providers: [record.provider],
|
|
768
|
+
});
|
|
769
|
+
_providerRuntimes[facing] = null;
|
|
770
|
+
providerRuntime = await getProviderRuntime(facing);
|
|
771
|
+
providerRuntime.resetTurnState(messages);
|
|
772
|
+
}
|
|
773
|
+
catch (refreshError) {
|
|
774
|
+
(0, runtime_1.emitNervesEvent)({
|
|
775
|
+
level: "warn",
|
|
776
|
+
component: "engine",
|
|
777
|
+
event: "engine.provider_retry_refresh_failed",
|
|
778
|
+
message: "provider credential refresh failed during retry",
|
|
779
|
+
meta: { provider: record.provider, model: record.model, reason: refreshError instanceof Error ? refreshError.message : String(refreshError) },
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
callbacks.onError(new Error(`${cause}, retrying in ${seconds}s (${record.attempt}/${maxAttempts})...`), "transient");
|
|
783
|
+
},
|
|
784
|
+
sleep: async (delayMs) => {
|
|
785
|
+
await waitForProviderRetry(delayMs, signal);
|
|
786
|
+
providerRuntime.resetTurnState(messages);
|
|
787
|
+
},
|
|
430
788
|
});
|
|
789
|
+
if (!attempt.ok) {
|
|
790
|
+
finishTerminalProviderError(attempt.error, attempt.classification);
|
|
791
|
+
continue;
|
|
792
|
+
}
|
|
793
|
+
const result = attempt.value;
|
|
431
794
|
// Track usage from the latest API call
|
|
432
795
|
if (result.usage)
|
|
433
796
|
lastUsage = result.usage;
|
|
434
|
-
retryCount = 0; // reset on success
|
|
435
797
|
// SHARED: build CC-format assistant message from TurnResult
|
|
436
798
|
const msg = {
|
|
437
799
|
role: "assistant",
|
|
438
800
|
};
|
|
439
|
-
|
|
440
|
-
|
|
801
|
+
// Persist assistant content WITHOUT inline <think>...</think> blocks.
|
|
802
|
+
// Reasoning content already routed through onReasoningChunk for live
|
|
803
|
+
// surfacing and persisted separately as `_reasoning_items` for
|
|
804
|
+
// providers that support a reasoning channel; saving it inline AND
|
|
805
|
+
// alongside tool_calls causes MiniMax to reject the replayed turn
|
|
806
|
+
// with "tool result's tool id not found" (error code 2013) because
|
|
807
|
+
// it can't reconcile reasoning-with-tools in the same assistant
|
|
808
|
+
// message. Strip aggressively at persist so the next replay is
|
|
809
|
+
// clean; preserve the original reasoning trace on the message via
|
|
810
|
+
// `_inline_reasoning` so debug/audit paths can still see it.
|
|
811
|
+
if (result.content) {
|
|
812
|
+
const stripped = stripThinkBlocksForViolationCheck(result.content);
|
|
813
|
+
if (stripped.length > 0)
|
|
814
|
+
msg.content = stripped;
|
|
815
|
+
if (stripped.length !== result.content.length) {
|
|
816
|
+
msg._inline_reasoning = result.content;
|
|
817
|
+
(0, runtime_1.emitNervesEvent)({
|
|
818
|
+
level: "info",
|
|
819
|
+
component: "engine",
|
|
820
|
+
event: "engine.inline_reasoning_stripped",
|
|
821
|
+
message: "stripped inline <think> blocks from persisted assistant message; preserved on _inline_reasoning",
|
|
822
|
+
meta: {
|
|
823
|
+
provider: providerRuntime.id,
|
|
824
|
+
model: providerRuntime.model,
|
|
825
|
+
originalLength: result.content.length,
|
|
826
|
+
strippedLength: stripped.length,
|
|
827
|
+
},
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
}
|
|
441
831
|
if (result.toolCalls.length)
|
|
442
832
|
msg.tool_calls = result.toolCalls.map((tc) => ({
|
|
443
833
|
id: tc.id,
|
|
@@ -457,35 +847,108 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
457
847
|
}
|
|
458
848
|
// Phase annotation for Codex provider
|
|
459
849
|
const hasPhaseAnnotation = providerRuntime.capabilities.has("phase-annotation");
|
|
460
|
-
const
|
|
850
|
+
const isSoleSettle = result.toolCalls.length === 1 && result.toolCalls[0].name === "settle";
|
|
461
851
|
if (hasPhaseAnnotation) {
|
|
462
|
-
msg.phase =
|
|
852
|
+
msg.phase = isSoleSettle ? "settle" : "commentary";
|
|
463
853
|
}
|
|
854
|
+
// Detect the MiniMax "only-thinking, no tool call" violation: no tool
|
|
855
|
+
// calls returned, and the content is empty after stripping
|
|
856
|
+
// <think>...</think> blocks. This is a narrow check — legitimate
|
|
857
|
+
// content-only responses (text without think tags, or text outside
|
|
858
|
+
// think tags) still flow through the original "no tool calls →
|
|
859
|
+
// accept as-is" path so existing channels and tests are unaffected.
|
|
860
|
+
const onlyThinkContent = !result.toolCalls.length
|
|
861
|
+
&& typeof result.content === "string"
|
|
862
|
+
&& stripThinkBlocksForViolationCheck(result.content).length === 0
|
|
863
|
+
&& result.content.length > 0;
|
|
464
864
|
if (!result.toolCalls.length) {
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
865
|
+
if (onlyThinkContent && toolChoiceRequired && noToolCallRetries < NO_TOOL_CALL_MAX_RETRIES) {
|
|
866
|
+
// Provider-level violation: tool_choice was required, model emitted
|
|
867
|
+
// only a <think>...</think> block (or empty content) with no tool
|
|
868
|
+
// call. Retry with a corrective nudge up to NO_TOOL_CALL_MAX_RETRIES
|
|
869
|
+
// times. After cap, accept as-is (the readback path strips think
|
|
870
|
+
// tags and surfaces a clear diagnostic).
|
|
871
|
+
noToolCallRetries++;
|
|
872
|
+
(0, runtime_1.emitNervesEvent)({
|
|
873
|
+
level: "warn",
|
|
874
|
+
component: "engine",
|
|
875
|
+
event: "engine.no_tool_call_retry",
|
|
876
|
+
message: "model returned only <think> content with no tool call despite tool_choice=required; retrying with corrective nudge",
|
|
877
|
+
meta: {
|
|
878
|
+
attempt: noToolCallRetries,
|
|
879
|
+
cap: NO_TOOL_CALL_MAX_RETRIES,
|
|
880
|
+
provider: providerRuntime.id,
|
|
881
|
+
model: providerRuntime.model,
|
|
882
|
+
contentLength: result.content.length,
|
|
883
|
+
},
|
|
884
|
+
});
|
|
885
|
+
messages.push(msg);
|
|
886
|
+
messages.push({
|
|
887
|
+
role: "user",
|
|
888
|
+
content: isInnerDialog
|
|
889
|
+
? "no tool was called this turn. you must end every turn by calling rest (or surface, ponder, observe). emit the tool call now."
|
|
890
|
+
: "no tool was called this turn. you must end every turn by calling settle with your answer (or ponder/observe). emit the tool call now.",
|
|
891
|
+
});
|
|
892
|
+
continue;
|
|
893
|
+
}
|
|
894
|
+
// Legitimate text-only response, or cap reached — accept as-is.
|
|
468
895
|
messages.push(msg);
|
|
469
896
|
done = true;
|
|
470
897
|
}
|
|
471
898
|
else {
|
|
472
|
-
//
|
|
473
|
-
|
|
899
|
+
// Reset the retry counter on any successful tool call.
|
|
900
|
+
noToolCallRetries = 0;
|
|
901
|
+
// Check for settle sole call: intercept before tool execution
|
|
902
|
+
if (isSoleSettle) {
|
|
903
|
+
/* v8 ignore next -- defensive: JSON.parse catch for malformed settle args @preserve */
|
|
904
|
+
const settleArgs = (() => { try {
|
|
905
|
+
return JSON.parse(result.toolCalls[0].arguments);
|
|
906
|
+
}
|
|
907
|
+
catch {
|
|
908
|
+
return {};
|
|
909
|
+
} })();
|
|
910
|
+
callbacks.onToolStart("settle", settleArgs);
|
|
911
|
+
// Inner dialog attention queue gate: reject settle if items remain
|
|
912
|
+
const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
|
|
913
|
+
if (isInnerDialog && attentionQueue && attentionQueue.length > 0) {
|
|
914
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
|
|
915
|
+
callbacks.onClearText?.();
|
|
916
|
+
messages.push(msg);
|
|
917
|
+
const gateMessage = "you're holding thoughts someone is waiting for — surface them before you settle.";
|
|
918
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
|
|
919
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
|
|
920
|
+
continue;
|
|
921
|
+
}
|
|
474
922
|
// Extract answer from the tool call arguments.
|
|
475
923
|
// Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
|
|
476
|
-
const { answer, intent } =
|
|
924
|
+
const { answer, intent } = parseSettlePayload(result.toolCalls[0].arguments);
|
|
925
|
+
// Inner dialog settle: no CompletionMetadata, "(settled)" ack
|
|
926
|
+
if (isInnerDialog) {
|
|
927
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
|
|
928
|
+
messages.push(msg);
|
|
929
|
+
const settled = "(settled)";
|
|
930
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: settled });
|
|
931
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, settled);
|
|
932
|
+
outcome = "settled";
|
|
933
|
+
done = true;
|
|
934
|
+
continue;
|
|
935
|
+
}
|
|
936
|
+
const retryError = getSettleRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp, options?.delegationDecision, sawSendMessageSelf, sawPonder, sawQuerySession, options?.currentObligation ?? null, options?.activeWorkFrame?.inner?.job, sawExternalStateQuery);
|
|
937
|
+
const deliveredAnswer = answer;
|
|
477
938
|
const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
|
|
478
939
|
const validTerminalIntent = intent === "complete" || intent === "blocked";
|
|
479
|
-
const validClosure =
|
|
940
|
+
const validClosure = deliveredAnswer != null
|
|
941
|
+
&& !retryError
|
|
480
942
|
&& (!mustResolveBeforeHandoffActive || validDirectReply || validTerminalIntent);
|
|
481
943
|
if (validClosure) {
|
|
944
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
|
|
482
945
|
completion = {
|
|
483
|
-
answer,
|
|
946
|
+
answer: deliveredAnswer,
|
|
484
947
|
intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
|
|
485
948
|
};
|
|
486
|
-
if (result.
|
|
949
|
+
if (result.settleStreamed) {
|
|
487
950
|
// The streaming layer already parsed and emitted the answer
|
|
488
|
-
// progressively via
|
|
951
|
+
// progressively via SettleParser. Skip clearing and
|
|
489
952
|
// re-emitting to avoid double-delivery.
|
|
490
953
|
}
|
|
491
954
|
else {
|
|
@@ -493,7 +956,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
493
956
|
callbacks.onClearText?.();
|
|
494
957
|
// Emit the answer through the callback pipeline so channels receive it.
|
|
495
958
|
// Never truncate -- channel adapters handle splitting long messages.
|
|
496
|
-
callbacks.onTextChunk(
|
|
959
|
+
callbacks.onTextChunk(deliveredAnswer);
|
|
497
960
|
}
|
|
498
961
|
messages.push(msg);
|
|
499
962
|
if (validDirectReply) {
|
|
@@ -505,32 +968,114 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
505
968
|
const delivered = "(delivered)";
|
|
506
969
|
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
|
|
507
970
|
providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
|
|
508
|
-
outcome = intent === "blocked" ? "blocked" : "
|
|
971
|
+
outcome = intent === "blocked" ? "blocked" : "settled";
|
|
509
972
|
done = true;
|
|
510
973
|
}
|
|
511
974
|
}
|
|
512
975
|
else {
|
|
513
|
-
// Answer is undefined -- the model's
|
|
976
|
+
// Answer is undefined -- the model's settle was incomplete or
|
|
514
977
|
// malformed. Clear any partial streamed text or noise, then push the
|
|
515
978
|
// assistant msg + error tool result and let the model try again.
|
|
979
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
|
|
516
980
|
callbacks.onClearText?.();
|
|
517
|
-
const retryError = getFinalAnswerRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp);
|
|
518
981
|
messages.push(msg);
|
|
519
|
-
|
|
520
|
-
|
|
982
|
+
const toolRetryMessage = retryError
|
|
983
|
+
?? "your settle was incomplete or malformed. call settle again with your complete response.";
|
|
984
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: toolRetryMessage });
|
|
985
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, toolRetryMessage);
|
|
986
|
+
}
|
|
987
|
+
continue;
|
|
988
|
+
}
|
|
989
|
+
// Check for observe sole call: intercept before tool execution
|
|
990
|
+
const isSoleObserve = result.toolCalls.length === 1 && result.toolCalls[0].name === "observe";
|
|
991
|
+
if (isSoleObserve) {
|
|
992
|
+
/* v8 ignore next -- defensive: JSON.parse catch for malformed observe args @preserve */
|
|
993
|
+
const observeArgs = (() => { try {
|
|
994
|
+
return JSON.parse(result.toolCalls[0].arguments);
|
|
995
|
+
}
|
|
996
|
+
catch {
|
|
997
|
+
return {};
|
|
998
|
+
} })();
|
|
999
|
+
let reason;
|
|
1000
|
+
if (typeof observeArgs?.reason === "string")
|
|
1001
|
+
reason = observeArgs.reason;
|
|
1002
|
+
callbacks.onToolStart("observe", observeArgs);
|
|
1003
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1004
|
+
component: "engine",
|
|
1005
|
+
event: "engine.observe",
|
|
1006
|
+
message: "agent observed without responding",
|
|
1007
|
+
meta: { ...(reason ? { reason } : {}) },
|
|
1008
|
+
});
|
|
1009
|
+
callbacks.onToolEnd("observe", (0, tools_1.summarizeArgs)("observe", observeArgs), true);
|
|
1010
|
+
messages.push(msg);
|
|
1011
|
+
const silenced = "(silenced)";
|
|
1012
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: silenced });
|
|
1013
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, silenced);
|
|
1014
|
+
outcome = "observed";
|
|
1015
|
+
done = true;
|
|
1016
|
+
continue;
|
|
1017
|
+
}
|
|
1018
|
+
// Check for rest sole call: intercept before tool execution
|
|
1019
|
+
const isSoleRest = result.toolCalls.length === 1 && result.toolCalls[0].name === "rest";
|
|
1020
|
+
if (isSoleRest) {
|
|
1021
|
+
const restArgs = (() => { try {
|
|
1022
|
+
return JSON.parse(result.toolCalls[0].arguments);
|
|
1023
|
+
}
|
|
1024
|
+
catch {
|
|
1025
|
+
return {};
|
|
1026
|
+
} })();
|
|
1027
|
+
callbacks.onToolStart("rest", restArgs);
|
|
1028
|
+
// Attention queue gate: reject rest if items remain
|
|
1029
|
+
const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
|
|
1030
|
+
if (attentionQueue && attentionQueue.length > 0) {
|
|
1031
|
+
callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), false);
|
|
1032
|
+
messages.push(msg);
|
|
1033
|
+
const gateMessage = "you're holding thoughts someone is waiting for — surface them before you rest.";
|
|
1034
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
|
|
1035
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
|
|
1036
|
+
continue;
|
|
1037
|
+
}
|
|
1038
|
+
if (hasFreshPendingWork(options) && !freshWorkGateFired) {
|
|
1039
|
+
freshWorkGateFired = true;
|
|
1040
|
+
callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), false);
|
|
1041
|
+
messages.push(msg);
|
|
1042
|
+
const gateMessage = "fresh work arrived for me this turn — inspect the pending messages above and take the next concrete action before you rest.";
|
|
1043
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
|
|
1044
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
|
|
1045
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1046
|
+
level: "info",
|
|
1047
|
+
component: "engine",
|
|
1048
|
+
event: "engine.fresh_work_gate_fired",
|
|
1049
|
+
message: "rest deferred once because pending work arrived this turn; agent has been notified",
|
|
1050
|
+
meta: { pendingCount: options.pendingMessages.length },
|
|
1051
|
+
});
|
|
1052
|
+
continue;
|
|
521
1053
|
}
|
|
1054
|
+
callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), true);
|
|
1055
|
+
messages.push(msg);
|
|
1056
|
+
const ack = "(resting)";
|
|
1057
|
+
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
|
|
1058
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
|
|
1059
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1060
|
+
component: "engine",
|
|
1061
|
+
event: "engine.rested",
|
|
1062
|
+
message: "resting until next heartbeat",
|
|
1063
|
+
meta: { ...(typeof restArgs?.status === "string" ? { status: restArgs.status } : {}) },
|
|
1064
|
+
});
|
|
1065
|
+
outcome = "rested";
|
|
1066
|
+
done = true;
|
|
522
1067
|
continue;
|
|
523
1068
|
}
|
|
524
1069
|
messages.push(msg);
|
|
525
|
-
//
|
|
1070
|
+
// Execute tools (sole-call tools in mixed calls are rejected inline)
|
|
526
1071
|
for (const tc of result.toolCalls) {
|
|
527
1072
|
if (signal?.aborted)
|
|
528
1073
|
break;
|
|
529
|
-
//
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
messages.push({ role: "tool", tool_call_id: tc.id, content:
|
|
533
|
-
providerRuntime.appendToolOutput(tc.id,
|
|
1074
|
+
// Reject sole-call tools when mixed with other tool calls
|
|
1075
|
+
const soleCallRejection = SOLE_CALL_REJECTION[tc.name];
|
|
1076
|
+
if (soleCallRejection) {
|
|
1077
|
+
messages.push({ role: "tool", tool_call_id: tc.id, content: soleCallRejection });
|
|
1078
|
+
providerRuntime.appendToolOutput(tc.id, soleCallRejection);
|
|
534
1079
|
continue;
|
|
535
1080
|
}
|
|
536
1081
|
let args = {};
|
|
@@ -540,21 +1085,213 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
540
1085
|
catch {
|
|
541
1086
|
/* ignore */
|
|
542
1087
|
}
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
1088
|
+
if (tc.name === "send_message" && args.friendId === "self") {
|
|
1089
|
+
sawSendMessageSelf = true;
|
|
1090
|
+
}
|
|
1091
|
+
if (tc.name === "speak") {
|
|
1092
|
+
let speakArgs = {};
|
|
1093
|
+
try {
|
|
1094
|
+
speakArgs = JSON.parse(tc.arguments);
|
|
1095
|
+
}
|
|
1096
|
+
catch { /* malformed */ }
|
|
1097
|
+
const speakMessage = typeof speakArgs.message === "string" ? speakArgs.message : "";
|
|
1098
|
+
const argSummary = (0, tools_1.summarizeArgs)("speak", { message: speakMessage });
|
|
1099
|
+
callbacks.onToolStart("speak", { message: speakMessage });
|
|
1100
|
+
if (speakMessage.trim().length === 0) {
|
|
1101
|
+
const err = "speak requires a non-empty `message` string.";
|
|
1102
|
+
callbacks.onToolEnd("speak", argSummary, false);
|
|
1103
|
+
messages.push({ role: "tool", tool_call_id: tc.id, content: err });
|
|
1104
|
+
providerRuntime.appendToolOutput(tc.id, err);
|
|
1105
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1106
|
+
level: "warn",
|
|
1107
|
+
component: "engine",
|
|
1108
|
+
event: "engine.speak_invalid",
|
|
1109
|
+
message: "speak rejected: missing or empty message",
|
|
1110
|
+
meta: {},
|
|
1111
|
+
});
|
|
1112
|
+
continue;
|
|
1113
|
+
}
|
|
1114
|
+
callbacks.onTextChunk(speakMessage);
|
|
1115
|
+
let speakDeliveryError = null;
|
|
1116
|
+
try {
|
|
1117
|
+
await callbacks.flushNow?.();
|
|
1118
|
+
}
|
|
1119
|
+
catch (err) {
|
|
1120
|
+
speakDeliveryError = err instanceof Error ? err : new Error(String(err));
|
|
549
1121
|
}
|
|
550
|
-
if (
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
1122
|
+
if (speakDeliveryError) {
|
|
1123
|
+
callbacks.onToolEnd("speak", argSummary, false);
|
|
1124
|
+
const failMsg = `speak delivery failed: ${speakDeliveryError.message}. the message did not reach your friend; do not assume they saw it.`;
|
|
1125
|
+
messages.push({ role: "tool", tool_call_id: tc.id, content: failMsg });
|
|
1126
|
+
providerRuntime.appendToolOutput(tc.id, failMsg);
|
|
1127
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1128
|
+
level: "error",
|
|
1129
|
+
component: "engine",
|
|
1130
|
+
event: "engine.speak_delivery_failed",
|
|
1131
|
+
message: "speak delivery failed",
|
|
1132
|
+
meta: { error: speakDeliveryError.message, messageLength: speakMessage.length },
|
|
1133
|
+
});
|
|
556
1134
|
continue;
|
|
557
1135
|
}
|
|
1136
|
+
callbacks.onToolEnd("speak", argSummary, true);
|
|
1137
|
+
const ack = "(spoken)";
|
|
1138
|
+
messages.push({ role: "tool", tool_call_id: tc.id, content: ack });
|
|
1139
|
+
providerRuntime.appendToolOutput(tc.id, ack);
|
|
1140
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1141
|
+
component: "engine",
|
|
1142
|
+
event: "engine.speak",
|
|
1143
|
+
message: "agent spoke mid-turn",
|
|
1144
|
+
meta: { messageLength: speakMessage.length },
|
|
1145
|
+
});
|
|
1146
|
+
continue;
|
|
1147
|
+
}
|
|
1148
|
+
if (tc.name === "ponder") {
|
|
1149
|
+
const parsedArgs = normalizeLegacyPonderArgs(parsePonderPayload(tc.arguments));
|
|
1150
|
+
const argSummary = (0, tools_1.summarizeArgs)(tc.name, parsedArgs);
|
|
1151
|
+
callbacks.onToolStart(tc.name, parsedArgs);
|
|
1152
|
+
let toolResult;
|
|
1153
|
+
let success = false;
|
|
1154
|
+
try {
|
|
1155
|
+
const action = parsedArgs.action ?? "create";
|
|
1156
|
+
const currentSession = (augmentedToolContext ?? options?.toolContext)?.currentSession;
|
|
1157
|
+
const currentOrigin = currentSession
|
|
1158
|
+
? { friendId: currentSession.friendId, channel: currentSession.channel, key: currentSession.key }
|
|
1159
|
+
: undefined;
|
|
1160
|
+
const isInnerChannel = currentOrigin?.friendId === "self" && currentOrigin?.channel === "inner";
|
|
1161
|
+
const successCriteria = parseSuccessCriteria(parsedArgs.success_criteria);
|
|
1162
|
+
const payload = parsePacketPayload(parsedArgs.payload_json);
|
|
1163
|
+
let packet;
|
|
1164
|
+
let returnObligationId = null;
|
|
1165
|
+
let resultAction = "created";
|
|
1166
|
+
if (action === "create") {
|
|
1167
|
+
const kind = parsedArgs.kind;
|
|
1168
|
+
const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
|
|
1169
|
+
const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
|
|
1170
|
+
if (!kind || !objective || !successCriteria || !payload) {
|
|
1171
|
+
throw new Error("ponder create requires kind, objective, success_criteria, and valid payload_json.");
|
|
1172
|
+
}
|
|
1173
|
+
const agentRoot = (0, identity_2.getAgentRoot)();
|
|
1174
|
+
let relatedObligationId;
|
|
1175
|
+
if (currentOrigin && !isInnerChannel) {
|
|
1176
|
+
try {
|
|
1177
|
+
const obligation = (0, obligations_1.createObligation)(agentRoot, {
|
|
1178
|
+
origin: currentOrigin,
|
|
1179
|
+
content: objective,
|
|
1180
|
+
});
|
|
1181
|
+
relatedObligationId = obligation.id;
|
|
1182
|
+
}
|
|
1183
|
+
catch {
|
|
1184
|
+
relatedObligationId = undefined;
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
const frictionSignature = kind === "harness_friction" && typeof payload.frictionSignature === "string"
|
|
1188
|
+
? payload.frictionSignature
|
|
1189
|
+
: null;
|
|
1190
|
+
const existing = frictionSignature && currentOrigin
|
|
1191
|
+
? (0, packets_1.findHarnessFrictionPacket)(agentRoot, currentOrigin, frictionSignature)
|
|
1192
|
+
: null;
|
|
1193
|
+
if (existing) {
|
|
1194
|
+
resultAction = "revised";
|
|
1195
|
+
returnObligationId = existing.relatedReturnObligationId ?? null;
|
|
1196
|
+
packet = existing.status === "drafting"
|
|
1197
|
+
? (0, packets_1.revisePonderPacket)(agentRoot, existing.id, {
|
|
1198
|
+
kind,
|
|
1199
|
+
objective,
|
|
1200
|
+
summary,
|
|
1201
|
+
successCriteria,
|
|
1202
|
+
payload,
|
|
1203
|
+
})
|
|
1204
|
+
: existing;
|
|
1205
|
+
}
|
|
1206
|
+
else {
|
|
1207
|
+
returnObligationId = (0, obligations_1.generateObligationId)(Date.now());
|
|
1208
|
+
packet = (0, packets_1.createPonderPacket)(agentRoot, {
|
|
1209
|
+
kind,
|
|
1210
|
+
objective,
|
|
1211
|
+
summary,
|
|
1212
|
+
successCriteria,
|
|
1213
|
+
...(currentOrigin ? { origin: currentOrigin } : {}),
|
|
1214
|
+
...(relatedObligationId ? { relatedObligationId } : {}),
|
|
1215
|
+
relatedReturnObligationId: returnObligationId,
|
|
1216
|
+
...(parsedArgs.follows_packet_id ? { followsPacketId: parsedArgs.follows_packet_id } : {}),
|
|
1217
|
+
payload,
|
|
1218
|
+
});
|
|
1219
|
+
(0, obligations_1.createReturnObligation)((0, identity_2.getAgentName)(), {
|
|
1220
|
+
id: returnObligationId,
|
|
1221
|
+
origin: currentOrigin ?? { friendId: "self", channel: "inner", key: "dialog" },
|
|
1222
|
+
status: "queued",
|
|
1223
|
+
delegatedContent: (summary || objective).length > 120 ? `${(summary || objective).slice(0, 117)}...` : (summary || objective),
|
|
1224
|
+
packetId: packet.id,
|
|
1225
|
+
createdAt: Date.now(),
|
|
1226
|
+
});
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
else if (action === "revise") {
|
|
1230
|
+
const packetId = typeof parsedArgs.packet_id === "string" ? parsedArgs.packet_id.trim() : "";
|
|
1231
|
+
const kind = parsedArgs.kind;
|
|
1232
|
+
const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
|
|
1233
|
+
const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
|
|
1234
|
+
if (!packetId || !kind || !objective || !successCriteria || !payload) {
|
|
1235
|
+
throw new Error("ponder revise requires packet_id, kind, objective, success_criteria, and valid payload_json.");
|
|
1236
|
+
}
|
|
1237
|
+
packet = (0, packets_1.revisePonderPacket)((0, identity_2.getAgentRoot)(), packetId, {
|
|
1238
|
+
kind,
|
|
1239
|
+
objective,
|
|
1240
|
+
summary,
|
|
1241
|
+
successCriteria,
|
|
1242
|
+
payload,
|
|
1243
|
+
});
|
|
1244
|
+
returnObligationId = packet.relatedReturnObligationId ?? null;
|
|
1245
|
+
resultAction = "revised";
|
|
1246
|
+
}
|
|
1247
|
+
else {
|
|
1248
|
+
throw new Error("ponder requires action=create or revise.");
|
|
1249
|
+
}
|
|
1250
|
+
try {
|
|
1251
|
+
await (0, socket_client_1.requestInnerWake)((0, identity_2.getAgentName)());
|
|
1252
|
+
}
|
|
1253
|
+
catch { /* daemon may not be running */ }
|
|
1254
|
+
sawPonder = true;
|
|
1255
|
+
toolResult = buildPonderResult(packet, resultAction, returnObligationId);
|
|
1256
|
+
success = true;
|
|
1257
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1258
|
+
component: "engine",
|
|
1259
|
+
event: "engine.ponder_packet",
|
|
1260
|
+
message: "ponder packet touched",
|
|
1261
|
+
meta: {
|
|
1262
|
+
action: resultAction,
|
|
1263
|
+
packetId: packet.id,
|
|
1264
|
+
kind: packet.kind,
|
|
1265
|
+
status: packet.status,
|
|
1266
|
+
},
|
|
1267
|
+
});
|
|
1268
|
+
}
|
|
1269
|
+
catch (error) {
|
|
1270
|
+
toolResult = error instanceof Error ? error.message : String(error);
|
|
1271
|
+
}
|
|
1272
|
+
callbacks.onToolEnd(tc.name, argSummary, success);
|
|
1273
|
+
messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
|
|
1274
|
+
providerRuntime.appendToolOutput(tc.id, toolResult);
|
|
1275
|
+
continue;
|
|
1276
|
+
}
|
|
1277
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
1278
|
+
if (tc.name === "query_session")
|
|
1279
|
+
sawQuerySession = true;
|
|
1280
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
1281
|
+
if (tc.name === "bridge_manage")
|
|
1282
|
+
sawBridgeManage = true;
|
|
1283
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
1284
|
+
if (isExternalStateQuery(tc.name, args))
|
|
1285
|
+
sawExternalStateQuery = true;
|
|
1286
|
+
const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
|
|
1287
|
+
const toolLoop = (0, tool_loop_1.detectToolLoop)(toolLoopState, tc.name, args);
|
|
1288
|
+
if (toolLoop.stuck) {
|
|
1289
|
+
const rejection = `loop guard: ${toolLoop.message}`;
|
|
1290
|
+
callbacks.onToolStart(tc.name, args);
|
|
1291
|
+
callbacks.onToolEnd(tc.name, argSummary, false);
|
|
1292
|
+
messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
|
|
1293
|
+
providerRuntime.appendToolOutput(tc.id, rejection);
|
|
1294
|
+
continue;
|
|
558
1295
|
}
|
|
559
1296
|
callbacks.onToolStart(tc.name, args);
|
|
560
1297
|
let toolResult;
|
|
@@ -568,69 +1305,32 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
568
1305
|
toolResult = `error: ${e}`;
|
|
569
1306
|
success = false;
|
|
570
1307
|
}
|
|
571
|
-
|
|
1308
|
+
toolResult = (0, tool_friction_1.rewriteToolResultForModel)(tc.name, toolResult, toolFrictionLedger);
|
|
1309
|
+
(0, tool_loop_1.recordToolOutcome)(toolLoopState, tc.name, args, toolResult, success);
|
|
1310
|
+
callbacks.onToolEnd(tc.name, (0, tools_1.buildToolResultSummary)(tc.name, args, toolResult, success), success);
|
|
572
1311
|
messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
|
|
573
1312
|
providerRuntime.appendToolOutput(tc.id, toolResult);
|
|
1313
|
+
callbacks.onToolResult?.(messages);
|
|
574
1314
|
}
|
|
575
1315
|
}
|
|
576
1316
|
}
|
|
577
1317
|
catch (e) {
|
|
578
1318
|
// Abort is not an error — just stop cleanly
|
|
579
|
-
if (signal?.aborted) {
|
|
1319
|
+
if (e instanceof provider_attempt_1.ProviderAttemptAbortError || signal?.aborted) {
|
|
580
1320
|
stripLastToolCalls(messages);
|
|
581
1321
|
outcome = "aborted";
|
|
582
1322
|
break;
|
|
583
1323
|
}
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
|
|
589
|
-
const trimmed = (0, context_1.trimMessages)(messages, maxTokens, contextMargin, maxTokens * 2);
|
|
590
|
-
messages.splice(0, messages.length, ...trimmed);
|
|
591
|
-
providerRuntime.resetTurnState(messages);
|
|
592
|
-
callbacks.onError(new Error("context trimmed, retrying..."), "transient");
|
|
593
|
-
continue;
|
|
1324
|
+
const errorForClassification = e instanceof Error ? e : /* v8 ignore next -- defensive @preserve */ new Error(String(e));
|
|
1325
|
+
let providerClassification;
|
|
1326
|
+
try {
|
|
1327
|
+
providerClassification = providerRuntime.classifyError(errorForClassification);
|
|
594
1328
|
}
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
const delay = RETRY_BASE_MS * Math.pow(2, retryCount - 1);
|
|
599
|
-
const cause = classifyTransientError(e);
|
|
600
|
-
callbacks.onError(new Error(`${cause}, retrying in ${delay / 1000}s (${retryCount}/${MAX_RETRIES})...`), "transient");
|
|
601
|
-
// Wait with abort support
|
|
602
|
-
const aborted = await new Promise((resolve) => {
|
|
603
|
-
const timer = setTimeout(() => resolve(false), delay);
|
|
604
|
-
if (signal) {
|
|
605
|
-
const onAbort = () => { clearTimeout(timer); resolve(true); };
|
|
606
|
-
if (signal.aborted) {
|
|
607
|
-
clearTimeout(timer);
|
|
608
|
-
resolve(true);
|
|
609
|
-
return;
|
|
610
|
-
}
|
|
611
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
612
|
-
}
|
|
613
|
-
});
|
|
614
|
-
if (aborted) {
|
|
615
|
-
stripLastToolCalls(messages);
|
|
616
|
-
outcome = "aborted";
|
|
617
|
-
break;
|
|
618
|
-
}
|
|
619
|
-
providerRuntime.resetTurnState(messages);
|
|
620
|
-
continue;
|
|
1329
|
+
catch {
|
|
1330
|
+
/* v8 ignore next -- defensive: classifyError should not throw @preserve */
|
|
1331
|
+
providerClassification = "unknown";
|
|
621
1332
|
}
|
|
622
|
-
|
|
623
|
-
(0, runtime_1.emitNervesEvent)({
|
|
624
|
-
level: "error",
|
|
625
|
-
event: "engine.error",
|
|
626
|
-
trace_id: traceId,
|
|
627
|
-
component: "engine",
|
|
628
|
-
message: e instanceof Error ? e.message : String(e),
|
|
629
|
-
meta: {},
|
|
630
|
-
});
|
|
631
|
-
stripLastToolCalls(messages);
|
|
632
|
-
outcome = "errored";
|
|
633
|
-
done = true;
|
|
1333
|
+
finishTerminalProviderError(errorForClassification, providerClassification);
|
|
634
1334
|
}
|
|
635
1335
|
}
|
|
636
1336
|
(0, runtime_1.emitNervesEvent)({
|
|
@@ -638,7 +1338,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
638
1338
|
trace_id: traceId,
|
|
639
1339
|
component: "engine",
|
|
640
1340
|
message: "runAgent turn completed",
|
|
641
|
-
meta: { done },
|
|
1341
|
+
meta: { done, sawPonder, sawQuerySession, sawBridgeManage },
|
|
642
1342
|
});
|
|
643
|
-
return {
|
|
1343
|
+
return {
|
|
1344
|
+
usage: lastUsage,
|
|
1345
|
+
outcome,
|
|
1346
|
+
completion,
|
|
1347
|
+
...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
|
|
1348
|
+
};
|
|
644
1349
|
}
|