@ouro.bot/cli 0.1.0-alpha.55 → 0.1.0-alpha.551
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 +3561 -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 +479 -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 +114 -118
- package/dist/heart/core.js +925 -246
- 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 +665 -0
- package/dist/heart/daemon/cli-exec.js +7565 -0
- package/dist/heart/daemon/cli-help.js +498 -0
- package/dist/heart/daemon/cli-parse.js +1590 -0
- package/dist/heart/daemon/cli-render-doctor.js +57 -0
- package/dist/heart/daemon/cli-render.js +775 -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 -1672
- package/dist/heart/daemon/daemon-entry.js +417 -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 +87 -13
- package/dist/heart/daemon/daemon-tombstone.js +236 -0
- package/dist/heart/daemon/daemon.js +796 -71
- package/dist/heart/daemon/dns-workflow.js +394 -0
- package/dist/heart/daemon/doctor-types.js +8 -0
- package/dist/heart/daemon/doctor.js +844 -0
- package/dist/heart/daemon/drift-detection.js +146 -0
- package/dist/heart/daemon/health-monitor.js +122 -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 +37 -8
- package/dist/heart/daemon/log-tailer.js +82 -12
- package/dist/heart/daemon/logs-prune.js +110 -0
- package/dist/heart/daemon/mcp-canary.js +297 -0
- package/dist/heart/daemon/message-router.js +2 -2
- package/dist/heart/daemon/os-cron-deps.js +135 -0
- package/dist/heart/daemon/os-cron.js +14 -12
- 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 +3 -31
- package/dist/heart/daemon/safe-mode.js +161 -0
- package/dist/heart/daemon/sense-manager.js +353 -38
- 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 +158 -11
- 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 +200 -51
- 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 +683 -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/runtime-cwd.js +87 -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 +6 -5
- package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
- package/dist/heart/versioning/ouro-path-installer.js +426 -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 +6 -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 +674 -0
- package/dist/mailroom/body-cache.js +61 -0
- package/dist/mailroom/core.js +720 -0
- package/dist/mailroom/entry.js +160 -0
- package/dist/mailroom/file-store.js +430 -0
- package/dist/mailroom/mbox-import.js +383 -0
- package/dist/mailroom/outbound.js +380 -0
- package/dist/mailroom/policy.js +263 -0
- package/dist/mailroom/reader.js +233 -0
- package/dist/mailroom/search-cache.js +256 -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} +62 -75
- 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 +995 -123
- 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 +295 -0
- package/dist/repertoire/mcp-manager.js +362 -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 +1857 -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 +604 -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/active-turns.js +216 -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 +2305 -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 +133 -0
- package/dist/senses/bluebubbles/replay.js +137 -0
- package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +30 -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,71 +1,114 @@
|
|
|
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
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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 };
|
|
47
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 };
|
|
48
63
|
}
|
|
49
|
-
function
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
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,
|
|
55
84
|
};
|
|
85
|
+
}
|
|
86
|
+
function createProviderRegistry() {
|
|
56
87
|
return {
|
|
57
|
-
resolve() {
|
|
58
|
-
const
|
|
59
|
-
|
|
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
|
+
}
|
|
60
102
|
},
|
|
61
103
|
};
|
|
62
104
|
}
|
|
63
|
-
function getProviderRuntime() {
|
|
105
|
+
async function getProviderRuntime(facing = "human") {
|
|
64
106
|
try {
|
|
65
|
-
const fingerprint = getProviderRuntimeFingerprint();
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
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;
|
|
69
112
|
}
|
|
70
113
|
}
|
|
71
114
|
catch (error) {
|
|
@@ -75,25 +118,26 @@ function getProviderRuntime() {
|
|
|
75
118
|
event: "engine.provider_init_error",
|
|
76
119
|
component: "engine",
|
|
77
120
|
message: msg,
|
|
78
|
-
meta: {},
|
|
121
|
+
meta: { facing },
|
|
79
122
|
});
|
|
80
123
|
// eslint-disable-next-line no-console -- pre-boot guard: provider init failure
|
|
81
124
|
console.error(`\n[fatal] ${msg}\n`);
|
|
82
|
-
|
|
83
|
-
throw new Error("unreachable");
|
|
125
|
+
throw error instanceof Error ? error : new Error(msg);
|
|
84
126
|
}
|
|
85
|
-
if (!
|
|
127
|
+
if (!_providerRuntimes[facing]) {
|
|
128
|
+
const msg = "provider runtime could not be initialized.";
|
|
86
129
|
(0, runtime_1.emitNervesEvent)({
|
|
87
130
|
level: "error",
|
|
88
131
|
event: "engine.provider_init_error",
|
|
89
132
|
component: "engine",
|
|
90
|
-
message:
|
|
91
|
-
meta: {},
|
|
133
|
+
message: msg,
|
|
134
|
+
meta: { facing },
|
|
92
135
|
});
|
|
93
|
-
|
|
94
|
-
|
|
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);
|
|
95
139
|
}
|
|
96
|
-
return
|
|
140
|
+
return _providerRuntimes[facing].runtime;
|
|
97
141
|
}
|
|
98
142
|
/**
|
|
99
143
|
* Clear the cached provider runtime so the next access re-creates it from
|
|
@@ -101,17 +145,18 @@ function getProviderRuntime() {
|
|
|
101
145
|
* provider fingerprint changes on disk.
|
|
102
146
|
*/
|
|
103
147
|
function resetProviderRuntime() {
|
|
104
|
-
|
|
148
|
+
_providerRuntimes.human = null;
|
|
149
|
+
_providerRuntimes.agent = null;
|
|
105
150
|
}
|
|
106
|
-
function getModel() {
|
|
107
|
-
return
|
|
151
|
+
function getModel(facing = "human") {
|
|
152
|
+
return resolveRuntimeProviderBinding(facing).model;
|
|
108
153
|
}
|
|
109
|
-
function getProvider() {
|
|
110
|
-
return
|
|
154
|
+
function getProvider(facing = "human") {
|
|
155
|
+
return resolveRuntimeProviderBinding(facing).provider;
|
|
111
156
|
}
|
|
112
|
-
function createSummarize() {
|
|
157
|
+
function createSummarize(facing = "human") {
|
|
113
158
|
return async (transcript, instruction) => {
|
|
114
|
-
const runtime = getProviderRuntime();
|
|
159
|
+
const runtime = await getProviderRuntime(facing);
|
|
115
160
|
const client = runtime.client;
|
|
116
161
|
const response = await client.chat.completions.create({
|
|
117
162
|
model: runtime.model,
|
|
@@ -124,35 +169,66 @@ function createSummarize() {
|
|
|
124
169
|
return response.choices?.[0]?.message?.content ?? transcript;
|
|
125
170
|
};
|
|
126
171
|
}
|
|
127
|
-
function getProviderDisplayLabel() {
|
|
128
|
-
const
|
|
172
|
+
function getProviderDisplayLabel(facing = "human") {
|
|
173
|
+
const binding = resolveRuntimeProviderBinding(facing);
|
|
174
|
+
const provider = binding.provider;
|
|
175
|
+
const model = binding.model || "unknown";
|
|
129
176
|
const providerLabelBuilders = {
|
|
130
177
|
azure: () => {
|
|
131
|
-
|
|
132
|
-
return `azure openai (${config.deployment || "default"}, model: ${config.modelName || "unknown"})`;
|
|
178
|
+
return `azure openai (model: ${model})`;
|
|
133
179
|
},
|
|
134
|
-
anthropic: () => `anthropic (${
|
|
135
|
-
minimax: () => `minimax (${
|
|
136
|
-
"openai-codex": () => `openai codex (${
|
|
180
|
+
anthropic: () => `anthropic (${model})`,
|
|
181
|
+
minimax: () => `minimax (${model})`,
|
|
182
|
+
"openai-codex": () => `openai codex (${model})`,
|
|
183
|
+
/* v8 ignore next -- branch: tested via display label unit test @preserve */
|
|
184
|
+
"github-copilot": () => `github copilot (${model})`,
|
|
137
185
|
};
|
|
138
186
|
return providerLabelBuilders[provider]();
|
|
139
187
|
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
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);
|
|
217
|
+
}
|
|
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) {
|
|
156
232
|
try {
|
|
157
233
|
const parsed = JSON.parse(argumentsText);
|
|
158
234
|
if (typeof parsed === "string") {
|
|
@@ -172,18 +248,93 @@ function parseFinalAnswerPayload(argumentsText) {
|
|
|
172
248
|
return {};
|
|
173
249
|
}
|
|
174
250
|
}
|
|
175
|
-
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
|
|
176
321
|
if (mustResolveBeforeHandoff && !intent) {
|
|
177
|
-
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.";
|
|
178
323
|
}
|
|
324
|
+
// 4. mustResolveBeforeHandoff + direct_reply without follow-up
|
|
179
325
|
if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
|
|
180
|
-
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.";
|
|
327
|
+
}
|
|
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.";
|
|
181
335
|
}
|
|
182
|
-
return
|
|
336
|
+
return null;
|
|
183
337
|
}
|
|
184
|
-
// Re-export kick utilities for backward compat
|
|
185
|
-
var kicks_1 = require("./kicks");
|
|
186
|
-
Object.defineProperty(exports, "hasToolIntent", { enumerable: true, get: function () { return kicks_1.hasToolIntent; } });
|
|
187
338
|
function upsertSystemPrompt(messages, systemText) {
|
|
188
339
|
const systemMessage = { role: "system", content: systemText };
|
|
189
340
|
if (messages[0]?.role === "system") {
|
|
@@ -221,27 +372,39 @@ const TOOL_SCAN_BOUNDARY_ROLES = new Set(["assistant", "user"]);
|
|
|
221
372
|
// 1. If an assistant message has tool_calls but missing tool results, inject synthetic error results.
|
|
222
373
|
// 2. If a tool result's tool_call_id doesn't match any tool_calls in a preceding assistant message, remove it.
|
|
223
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.
|
|
224
382
|
function repairOrphanedToolCalls(messages) {
|
|
225
|
-
// Pass 1:
|
|
226
|
-
|
|
227
|
-
|
|
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];
|
|
228
389
|
if (msg.role === "assistant") {
|
|
229
390
|
const asst = msg;
|
|
230
391
|
if (asst.tool_calls) {
|
|
231
392
|
for (const tc of asst.tool_calls)
|
|
232
|
-
|
|
393
|
+
seenCallIds.add(tc.id);
|
|
233
394
|
}
|
|
395
|
+
continue;
|
|
234
396
|
}
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
const toolMsg = messages[i];
|
|
240
|
-
if (!validCallIds.has(toolMsg.tool_call_id)) {
|
|
241
|
-
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);
|
|
242
401
|
}
|
|
243
402
|
}
|
|
244
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
|
+
}
|
|
245
408
|
// Pass 3: inject synthetic results for tool_calls missing their tool results
|
|
246
409
|
for (let i = 0; i < messages.length; i++) {
|
|
247
410
|
const msg = messages[i];
|
|
@@ -263,10 +426,13 @@ function repairOrphanedToolCalls(messages) {
|
|
|
263
426
|
}
|
|
264
427
|
const missing = asst.tool_calls.filter((tc) => !resultIds.has(tc.id));
|
|
265
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.
|
|
266
432
|
const syntheticResults = missing.map((tc) => ({
|
|
267
433
|
role: "tool",
|
|
268
434
|
tool_call_id: tc.id,
|
|
269
|
-
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.",
|
|
270
436
|
}));
|
|
271
437
|
let insertAt = i + 1;
|
|
272
438
|
while (insertAt < messages.length && messages[insertAt].role === "tool")
|
|
@@ -289,49 +455,67 @@ function isContextOverflow(err) {
|
|
|
289
455
|
return true;
|
|
290
456
|
return false;
|
|
291
457
|
}
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
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
|
+
});
|
|
318
488
|
}
|
|
319
|
-
function
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
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");
|
|
330
515
|
}
|
|
331
|
-
const MAX_RETRIES = 3;
|
|
332
|
-
const RETRY_BASE_MS = 2000;
|
|
333
516
|
async function runAgent(messages, callbacks, channel, signal, options) {
|
|
334
|
-
const
|
|
517
|
+
const facing = (0, channel_1.channelToFacing)(channel);
|
|
518
|
+
let providerRuntime = await getProviderRuntime(facing);
|
|
335
519
|
const provider = providerRuntime.id;
|
|
336
520
|
const toolChoiceRequired = options?.toolChoiceRequired ?? true;
|
|
337
521
|
const traceId = options?.traceId;
|
|
@@ -355,6 +539,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
355
539
|
// Refresh system prompt at start of each turn when channel is provided.
|
|
356
540
|
// If refresh fails, keep existing system prompt (or inject a minimal safe fallback)
|
|
357
541
|
// so turn execution remains consistent and non-fatal.
|
|
542
|
+
let structuredSystemPrompt;
|
|
358
543
|
if (channel) {
|
|
359
544
|
try {
|
|
360
545
|
const buildSystemOptions = {
|
|
@@ -363,7 +548,8 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
363
548
|
supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
|
|
364
549
|
};
|
|
365
550
|
const refreshed = await (0, prompt_1.buildSystem)(channel, buildSystemOptions, currentContext);
|
|
366
|
-
|
|
551
|
+
structuredSystemPrompt = refreshed;
|
|
552
|
+
upsertSystemPrompt(messages, (0, prompt_1.flattenSystemPrompt)(refreshed));
|
|
367
553
|
}
|
|
368
554
|
catch (error) {
|
|
369
555
|
const hadExistingSystemPrompt = messages[0]?.role === "system" && typeof messages[0].content === "string";
|
|
@@ -384,40 +570,120 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
384
570
|
});
|
|
385
571
|
}
|
|
386
572
|
}
|
|
387
|
-
|
|
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
|
+
}
|
|
388
582
|
let done = false;
|
|
389
583
|
let lastUsage;
|
|
390
584
|
let overflowRetried = false;
|
|
391
|
-
let
|
|
392
|
-
let outcome = "complete";
|
|
585
|
+
let outcome = "settled";
|
|
393
586
|
let completion;
|
|
587
|
+
let terminalError;
|
|
588
|
+
let terminalErrorClassification;
|
|
394
589
|
let sawSteeringFollowUp = false;
|
|
395
590
|
let mustResolveBeforeHandoffActive = options?.mustResolveBeforeHandoff === true;
|
|
396
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
|
+
};
|
|
397
647
|
// Prevent MaxListenersExceeded warning — each iteration adds a listener
|
|
398
648
|
try {
|
|
399
649
|
require("events").setMaxListeners(50, signal);
|
|
400
650
|
}
|
|
401
651
|
catch { /* unsupported */ }
|
|
402
652
|
const toolPreferences = currentContext?.friend?.toolPreferences;
|
|
403
|
-
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);
|
|
404
654
|
// Augment tool context with reasoning effort controls from provider
|
|
405
655
|
const augmentedToolContext = options?.toolContext
|
|
406
656
|
? {
|
|
407
657
|
...options.toolContext,
|
|
408
658
|
supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
|
|
409
659
|
setReasoningEffort: (level) => { currentReasoningEffort = level; },
|
|
660
|
+
activeWorkFrame: options?.activeWorkFrame,
|
|
410
661
|
}
|
|
411
662
|
: undefined;
|
|
412
663
|
// Rebase provider-owned turn state from canonical messages at user-turn start.
|
|
413
664
|
// This prevents stale provider caches from replaying prior-turn context.
|
|
414
665
|
providerRuntime.resetTurnState(messages);
|
|
415
666
|
while (!done) {
|
|
416
|
-
//
|
|
417
|
-
//
|
|
418
|
-
//
|
|
419
|
-
//
|
|
420
|
-
|
|
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
|
+
];
|
|
421
687
|
const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
|
|
422
688
|
if (steeringFollowUps.length > 0) {
|
|
423
689
|
const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
|
|
@@ -444,26 +710,124 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
444
710
|
break;
|
|
445
711
|
}
|
|
446
712
|
try {
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
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
|
+
},
|
|
456
788
|
});
|
|
789
|
+
if (!attempt.ok) {
|
|
790
|
+
finishTerminalProviderError(attempt.error, attempt.classification);
|
|
791
|
+
continue;
|
|
792
|
+
}
|
|
793
|
+
const result = attempt.value;
|
|
457
794
|
// Track usage from the latest API call
|
|
458
795
|
if (result.usage)
|
|
459
796
|
lastUsage = result.usage;
|
|
460
|
-
retryCount = 0; // reset on success
|
|
461
797
|
// SHARED: build CC-format assistant message from TurnResult
|
|
462
798
|
const msg = {
|
|
463
799
|
role: "assistant",
|
|
464
800
|
};
|
|
465
|
-
|
|
466
|
-
|
|
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
|
+
}
|
|
467
831
|
if (result.toolCalls.length)
|
|
468
832
|
msg.tool_calls = result.toolCalls.map((tc) => ({
|
|
469
833
|
id: tc.id,
|
|
@@ -483,35 +847,108 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
483
847
|
}
|
|
484
848
|
// Phase annotation for Codex provider
|
|
485
849
|
const hasPhaseAnnotation = providerRuntime.capabilities.has("phase-annotation");
|
|
486
|
-
const
|
|
850
|
+
const isSoleSettle = result.toolCalls.length === 1 && result.toolCalls[0].name === "settle";
|
|
487
851
|
if (hasPhaseAnnotation) {
|
|
488
|
-
msg.phase =
|
|
852
|
+
msg.phase = isSoleSettle ? "settle" : "commentary";
|
|
489
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;
|
|
490
864
|
if (!result.toolCalls.length) {
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
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.
|
|
494
895
|
messages.push(msg);
|
|
495
896
|
done = true;
|
|
496
897
|
}
|
|
497
898
|
else {
|
|
498
|
-
//
|
|
499
|
-
|
|
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
|
+
}
|
|
500
922
|
// Extract answer from the tool call arguments.
|
|
501
923
|
// Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
|
|
502
|
-
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;
|
|
503
938
|
const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
|
|
504
939
|
const validTerminalIntent = intent === "complete" || intent === "blocked";
|
|
505
|
-
const validClosure =
|
|
940
|
+
const validClosure = deliveredAnswer != null
|
|
941
|
+
&& !retryError
|
|
506
942
|
&& (!mustResolveBeforeHandoffActive || validDirectReply || validTerminalIntent);
|
|
507
943
|
if (validClosure) {
|
|
944
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
|
|
508
945
|
completion = {
|
|
509
|
-
answer,
|
|
946
|
+
answer: deliveredAnswer,
|
|
510
947
|
intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
|
|
511
948
|
};
|
|
512
|
-
if (result.
|
|
949
|
+
if (result.settleStreamed) {
|
|
513
950
|
// The streaming layer already parsed and emitted the answer
|
|
514
|
-
// progressively via
|
|
951
|
+
// progressively via SettleParser. Skip clearing and
|
|
515
952
|
// re-emitting to avoid double-delivery.
|
|
516
953
|
}
|
|
517
954
|
else {
|
|
@@ -519,7 +956,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
519
956
|
callbacks.onClearText?.();
|
|
520
957
|
// Emit the answer through the callback pipeline so channels receive it.
|
|
521
958
|
// Never truncate -- channel adapters handle splitting long messages.
|
|
522
|
-
callbacks.onTextChunk(
|
|
959
|
+
callbacks.onTextChunk(deliveredAnswer);
|
|
523
960
|
}
|
|
524
961
|
messages.push(msg);
|
|
525
962
|
if (validDirectReply) {
|
|
@@ -531,32 +968,114 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
531
968
|
const delivered = "(delivered)";
|
|
532
969
|
messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
|
|
533
970
|
providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
|
|
534
|
-
outcome = intent === "blocked" ? "blocked" : "
|
|
971
|
+
outcome = intent === "blocked" ? "blocked" : "settled";
|
|
535
972
|
done = true;
|
|
536
973
|
}
|
|
537
974
|
}
|
|
538
975
|
else {
|
|
539
|
-
// Answer is undefined -- the model's
|
|
976
|
+
// Answer is undefined -- the model's settle was incomplete or
|
|
540
977
|
// malformed. Clear any partial streamed text or noise, then push the
|
|
541
978
|
// assistant msg + error tool result and let the model try again.
|
|
979
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
|
|
542
980
|
callbacks.onClearText?.();
|
|
543
|
-
const retryError = getFinalAnswerRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp);
|
|
544
981
|
messages.push(msg);
|
|
545
|
-
|
|
546
|
-
|
|
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);
|
|
547
986
|
}
|
|
548
987
|
continue;
|
|
549
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;
|
|
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;
|
|
1067
|
+
continue;
|
|
1068
|
+
}
|
|
550
1069
|
messages.push(msg);
|
|
551
|
-
//
|
|
1070
|
+
// Execute tools (sole-call tools in mixed calls are rejected inline)
|
|
552
1071
|
for (const tc of result.toolCalls) {
|
|
553
1072
|
if (signal?.aborted)
|
|
554
1073
|
break;
|
|
555
|
-
//
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
messages.push({ role: "tool", tool_call_id: tc.id, content:
|
|
559
|
-
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);
|
|
560
1079
|
continue;
|
|
561
1080
|
}
|
|
562
1081
|
let args = {};
|
|
@@ -566,21 +1085,213 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
566
1085
|
catch {
|
|
567
1086
|
/* ignore */
|
|
568
1087
|
}
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
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);
|
|
575
1095
|
}
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
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
|
+
});
|
|
582
1112
|
continue;
|
|
583
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));
|
|
1121
|
+
}
|
|
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
|
+
});
|
|
1134
|
+
continue;
|
|
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;
|
|
584
1295
|
}
|
|
585
1296
|
callbacks.onToolStart(tc.name, args);
|
|
586
1297
|
let toolResult;
|
|
@@ -594,69 +1305,32 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
594
1305
|
toolResult = `error: ${e}`;
|
|
595
1306
|
success = false;
|
|
596
1307
|
}
|
|
597
|
-
|
|
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);
|
|
598
1311
|
messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
|
|
599
1312
|
providerRuntime.appendToolOutput(tc.id, toolResult);
|
|
1313
|
+
callbacks.onToolResult?.(messages);
|
|
600
1314
|
}
|
|
601
1315
|
}
|
|
602
1316
|
}
|
|
603
1317
|
catch (e) {
|
|
604
1318
|
// Abort is not an error — just stop cleanly
|
|
605
|
-
if (signal?.aborted) {
|
|
1319
|
+
if (e instanceof provider_attempt_1.ProviderAttemptAbortError || signal?.aborted) {
|
|
606
1320
|
stripLastToolCalls(messages);
|
|
607
1321
|
outcome = "aborted";
|
|
608
1322
|
break;
|
|
609
1323
|
}
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
|
|
615
|
-
const trimmed = (0, context_1.trimMessages)(messages, maxTokens, contextMargin, maxTokens * 2);
|
|
616
|
-
messages.splice(0, messages.length, ...trimmed);
|
|
617
|
-
providerRuntime.resetTurnState(messages);
|
|
618
|
-
callbacks.onError(new Error("context trimmed, retrying..."), "transient");
|
|
619
|
-
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);
|
|
620
1328
|
}
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
const delay = RETRY_BASE_MS * Math.pow(2, retryCount - 1);
|
|
625
|
-
const cause = classifyTransientError(e);
|
|
626
|
-
callbacks.onError(new Error(`${cause}, retrying in ${delay / 1000}s (${retryCount}/${MAX_RETRIES})...`), "transient");
|
|
627
|
-
// Wait with abort support
|
|
628
|
-
const aborted = await new Promise((resolve) => {
|
|
629
|
-
const timer = setTimeout(() => resolve(false), delay);
|
|
630
|
-
if (signal) {
|
|
631
|
-
const onAbort = () => { clearTimeout(timer); resolve(true); };
|
|
632
|
-
if (signal.aborted) {
|
|
633
|
-
clearTimeout(timer);
|
|
634
|
-
resolve(true);
|
|
635
|
-
return;
|
|
636
|
-
}
|
|
637
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
638
|
-
}
|
|
639
|
-
});
|
|
640
|
-
if (aborted) {
|
|
641
|
-
stripLastToolCalls(messages);
|
|
642
|
-
outcome = "aborted";
|
|
643
|
-
break;
|
|
644
|
-
}
|
|
645
|
-
providerRuntime.resetTurnState(messages);
|
|
646
|
-
continue;
|
|
1329
|
+
catch {
|
|
1330
|
+
/* v8 ignore next -- defensive: classifyError should not throw @preserve */
|
|
1331
|
+
providerClassification = "unknown";
|
|
647
1332
|
}
|
|
648
|
-
|
|
649
|
-
(0, runtime_1.emitNervesEvent)({
|
|
650
|
-
level: "error",
|
|
651
|
-
event: "engine.error",
|
|
652
|
-
trace_id: traceId,
|
|
653
|
-
component: "engine",
|
|
654
|
-
message: e instanceof Error ? e.message : String(e),
|
|
655
|
-
meta: {},
|
|
656
|
-
});
|
|
657
|
-
stripLastToolCalls(messages);
|
|
658
|
-
outcome = "errored";
|
|
659
|
-
done = true;
|
|
1333
|
+
finishTerminalProviderError(errorForClassification, providerClassification);
|
|
660
1334
|
}
|
|
661
1335
|
}
|
|
662
1336
|
(0, runtime_1.emitNervesEvent)({
|
|
@@ -664,7 +1338,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
664
1338
|
trace_id: traceId,
|
|
665
1339
|
component: "engine",
|
|
666
1340
|
message: "runAgent turn completed",
|
|
667
|
-
meta: { done },
|
|
1341
|
+
meta: { done, sawPonder, sawQuerySession, sawBridgeManage },
|
|
668
1342
|
});
|
|
669
|
-
return {
|
|
1343
|
+
return {
|
|
1344
|
+
usage: lastUsage,
|
|
1345
|
+
outcome,
|
|
1346
|
+
completion,
|
|
1347
|
+
...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
|
|
1348
|
+
};
|
|
670
1349
|
}
|