@ouro.bot/cli 0.1.0-alpha.83 → 0.1.0-alpha.831
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/LICENSE +21 -0
- package/README.md +154 -23
- 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-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/assets/bluebubbles-host +264 -0
- package/assets/sanctuary-host-launcher.sh +16 -0
- package/changelog.json +5308 -16
- package/deploy/unraid/Dockerfile +54 -0
- package/deploy/unraid/README.txt +2983 -0
- package/deploy/unraid/audit-container-spec.sh +4 -0
- package/deploy/unraid/container-runtime.json +1 -0
- package/deploy/unraid/docker-man-template-transaction.mjs +711 -0
- package/deploy/unraid/docker-man-template-xml.cjs +105 -0
- package/deploy/unraid/migrate-sanctuary-bundle.mjs +60 -0
- package/deploy/unraid/ouro-events/bootstrap-spool.sh +92 -0
- package/deploy/unraid/ouro-events/emit-event.mjs +310 -0
- package/deploy/unraid/ouro-events/emit-usenet-event.sh +54 -0
- package/deploy/unraid/ouro-events/install-usenet-guard.sh +435 -0
- package/deploy/unraid/ouro-events/usenet-health.sh +176 -0
- package/deploy/unraid/sanctuary-acceptance-adapter.sh +43 -0
- package/deploy/unraid/sanctuary-acceptance-contract.json +198 -0
- package/deploy/unraid/sanctuary-acceptance-harness.sh +23 -0
- package/deploy/unraid/sanctuary-authority-installation.json +36 -0
- package/deploy/unraid/sanctuary-authority-service.sh +30 -0
- package/deploy/unraid/sanctuary-deployment-target.mjs +710 -0
- package/deploy/unraid/sanctuary-safe-rename.py +24 -0
- package/deploy/unraid/sanctuary-unit16-host-broker.mjs +2084 -0
- package/deploy/unraid/sanctuary-unit16-run.sh +560 -0
- package/deploy/unraid/sanctuary-unit18-target-audit.sh +27 -0
- package/deploy/unraid/sanctuary.ouro/agent.json +66 -0
- package/deploy/unraid/sanctuary.ouro/arc/README.md +3 -0
- package/deploy/unraid/sanctuary.ouro/bundle-meta.json +5 -0
- package/deploy/unraid/sanctuary.ouro/habits/sanctuary-health.md +8 -0
- package/deploy/unraid/sanctuary.ouro/mcp/media-mcp.mjs +795 -0
- package/deploy/unraid/sanctuary.ouro/provider-readiness.json +11 -0
- package/deploy/unraid/sanctuary.ouro/psyche/ASPIRATIONS.md +5 -0
- package/deploy/unraid/sanctuary.ouro/psyche/IDENTITY.md +5 -0
- package/deploy/unraid/sanctuary.ouro/psyche/LORE.md +15 -0
- package/deploy/unraid/sanctuary.ouro/psyche/SOUL.md +25 -0
- package/deploy/unraid/sanctuary.ouro/psyche/TACIT.md +15 -0
- package/deploy/unraid/sanctuary.ouro/state/policy/steward.json +7 -0
- package/deploy/unraid/sanctuary.ouro/tool-profiles.json +135 -0
- package/deploy/unraid/sanctuary.xml +28 -0
- package/dist/a2a/card.js +57 -0
- package/dist/a2a/client.js +180 -0
- package/dist/a2a/config.js +50 -0
- package/dist/a2a/delegation-stores.js +56 -0
- package/dist/a2a/did-resolution.js +93 -0
- package/dist/a2a/identity.js +170 -0
- package/dist/a2a/inbound-share.js +107 -0
- package/dist/a2a/mission-result-wire.js +196 -0
- package/dist/a2a/onboarding.js +115 -0
- package/dist/a2a/pin-store.js +132 -0
- package/dist/a2a/seen-ledger.js +120 -0
- package/dist/a2a/server.js +604 -0
- package/dist/a2a/task-store.js +69 -0
- package/dist/a2a/transport.js +45 -0
- package/dist/a2a/types.js +3 -0
- package/dist/arc/attention-types.js +8 -0
- package/dist/arc/cares.js +360 -0
- package/dist/arc/episodes.js +118 -0
- package/dist/arc/evolution.js +490 -0
- package/dist/arc/flight-recorder.js +1034 -0
- package/dist/arc/intentions.js +134 -0
- package/dist/arc/json-store.js +117 -0
- package/dist/arc/obligations.js +386 -0
- package/dist/arc/packets.js +336 -0
- package/dist/arc/presence.js +185 -0
- package/dist/arc/task-lifecycle.js +57 -0
- package/dist/commerce/store.js +755 -0
- package/dist/commerce/types.js +3 -0
- package/dist/heart/active-work.js +798 -40
- package/dist/heart/agent-entry.js +252 -3
- package/dist/heart/approval-files.js +113 -0
- package/dist/heart/approval-store.js +960 -0
- 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/bluebubbles.js +156 -0
- package/dist/heart/attachments/sources/cli-local-file.js +78 -0
- package/dist/heart/attachments/sources/index.js +18 -0
- package/dist/heart/attachments/sources/telegram.js +71 -0
- package/dist/heart/attachments/store.js +132 -0
- package/dist/heart/attachments/types.js +93 -0
- package/dist/heart/auth/auth-flow.js +495 -0
- package/dist/heart/autonomy-budget.js +478 -0
- package/dist/heart/awaiting/await-alert.js +148 -0
- package/dist/heart/awaiting/await-expiry.js +143 -0
- package/dist/heart/awaiting/await-loader.js +91 -0
- package/dist/heart/awaiting/await-parser.js +149 -0
- package/dist/heart/awaiting/await-runtime-state.js +111 -0
- package/dist/heart/awaiting/await-scheduler.js +382 -0
- package/dist/heart/background-operations.js +281 -0
- package/dist/heart/bridges/manager.js +137 -17
- package/dist/heart/bridges/store.js +14 -2
- package/dist/heart/bundle-state.js +168 -0
- package/dist/heart/commitments.js +44 -18
- package/dist/heart/config-registry.js +331 -0
- package/dist/heart/config.js +174 -131
- package/dist/heart/context-loss-gauntlet.js +387 -0
- package/dist/heart/context-loss-sentinel.js +1157 -0
- package/dist/heart/core.js +2169 -581
- package/dist/heart/cross-chat-delivery.js +9 -22
- package/dist/heart/daemon/agent-config-check.js +451 -0
- package/dist/heart/daemon/agent-discovery.js +185 -3
- package/dist/heart/daemon/agent-service.js +542 -0
- package/dist/heart/daemon/agentic-repair.js +547 -0
- package/dist/heart/daemon/await-private-wake.js +59 -0
- package/dist/heart/daemon/bluebubbles-cli-integration.js +71 -0
- package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
- package/dist/heart/daemon/bluebubbles-host-protocol.js +433 -0
- package/dist/heart/daemon/bluebubbles-host.js +273 -0
- package/dist/heart/daemon/boot-sync-probe.js +197 -0
- package/dist/heart/daemon/cadence.js +180 -0
- package/dist/heart/daemon/cli-defaults.js +854 -0
- package/dist/heart/daemon/cli-desk.js +322 -0
- package/dist/heart/daemon/cli-exec.js +8822 -0
- package/dist/heart/daemon/cli-help.js +716 -0
- package/dist/heart/daemon/cli-parse.js +2771 -0
- package/dist/heart/daemon/cli-render-doctor.js +57 -0
- package/dist/heart/daemon/cli-render.js +777 -0
- package/dist/heart/daemon/cli-types.js +8 -0
- package/dist/heart/daemon/connect-bay.js +323 -0
- package/dist/heart/daemon/container-credential-bootstrap.js +273 -0
- package/dist/heart/daemon/container-healthcheck.js +112 -0
- package/dist/heart/daemon/container-runtime.js +97 -0
- package/dist/heart/daemon/container-spec-auditor-main.js +171 -0
- package/dist/heart/daemon/container-spec-auditor.js +229 -0
- package/dist/heart/daemon/daemon-bootstrap-startup.js +115 -0
- package/dist/heart/daemon/daemon-cli.js +29 -2349
- package/dist/heart/daemon/daemon-entry.js +930 -11
- package/dist/heart/daemon/daemon-health.js +186 -0
- package/dist/heart/daemon/daemon-rollup.js +57 -0
- package/dist/heart/daemon/daemon-runtime-sync.js +88 -13
- package/dist/heart/daemon/daemon-tombstone.js +236 -0
- package/dist/heart/daemon/daemon.js +2084 -105
- package/dist/heart/daemon/dns-workflow.js +394 -0
- package/dist/heart/daemon/doctor-types.js +8 -0
- package/dist/heart/daemon/doctor.js +1755 -0
- package/dist/heart/daemon/freshness.js +345 -0
- package/dist/heart/daemon/habit-private-wake.js +61 -0
- package/dist/heart/daemon/health-monitor.js +142 -11
- package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
- package/dist/heart/daemon/hooks/bundle-meta.js +135 -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 +78 -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 +79 -10
- package/dist/heart/daemon/logs-prune.js +132 -0
- package/dist/heart/daemon/mcp-canary.js +524 -0
- package/dist/heart/daemon/message-router.js +65 -5
- package/dist/heart/daemon/migrate-to-desk.js +848 -0
- package/dist/heart/daemon/os-cron-deps.js +135 -0
- package/dist/heart/daemon/os-cron.js +22 -14
- package/dist/heart/daemon/ouro-bot-entry.js +4 -2
- package/dist/heart/daemon/ouro-entry.js +3 -1
- package/dist/heart/daemon/plugin-cli.js +432 -0
- package/dist/heart/daemon/process-manager.js +733 -61
- package/dist/heart/daemon/provider-discovery.js +137 -0
- package/dist/heart/daemon/provider-ping-progress.js +83 -0
- package/dist/heart/daemon/prunable-bundle.js +144 -0
- package/dist/heart/daemon/pulse.js +511 -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 +47 -14
- package/dist/heart/daemon/runtime-metadata.js +2 -30
- package/dist/heart/daemon/runtime-mode.js +13 -2
- package/dist/heart/daemon/safe-mode.js +161 -0
- package/dist/heart/daemon/sanctuary-acceptance-adapter.js +2654 -0
- package/dist/heart/daemon/sanctuary-acceptance-harness.js +1830 -0
- package/dist/heart/daemon/sanctuary-acceptance-marker.js +267 -0
- package/dist/heart/daemon/sanctuary-acceptance-scenarios.js +955 -0
- package/dist/heart/daemon/sanctuary-authority-codec.js +86 -0
- package/dist/heart/daemon/sanctuary-authority-epoch.js +256 -0
- package/dist/heart/daemon/sanctuary-authority-installation.js +140 -0
- package/dist/heart/daemon/sanctuary-authority-ledger.js +241 -0
- package/dist/heart/daemon/sanctuary-authority-root-lifecycle.js +819 -0
- package/dist/heart/daemon/sanctuary-authority-vault-migration.js +79 -0
- package/dist/heart/daemon/sanctuary-bundle-migration.js +729 -0
- package/dist/heart/daemon/sanctuary-host-authority.js +1008 -0
- package/dist/heart/daemon/sanctuary-host-detached-supervisor.js +494 -0
- package/dist/heart/daemon/sanctuary-host-executor.js +670 -0
- package/dist/heart/daemon/sanctuary-host-linux-kernel.js +334 -0
- package/dist/heart/daemon/sanctuary-host-supervisor-entry.js +207 -0
- package/dist/heart/daemon/sanctuary-host-supervisor.js +95 -0
- package/dist/heart/daemon/sanctuary-package-management.js +103 -0
- package/dist/heart/daemon/sanctuary-scheduler-liveness.js +227 -0
- package/dist/heart/daemon/sanctuary-scheduler-origin.js +132 -0
- package/dist/heart/daemon/sanctuary-telegram-authority-entry.js +445 -0
- package/dist/heart/daemon/sanctuary-telegram-authority-gateway.js +585 -0
- package/dist/heart/daemon/sanctuary-telegram-authority-service.js +630 -0
- package/dist/heart/daemon/sense-manager.js +699 -48
- package/dist/heart/daemon/session-id-resolver.js +131 -0
- package/dist/heart/daemon/skill-management-installer.js +1 -1
- package/dist/heart/daemon/socket-client.js +180 -12
- package/dist/heart/daemon/stale-bundle-prune.js +113 -0
- package/dist/heart/daemon/startup-tui.js +339 -0
- package/dist/heart/daemon/supercronic-supervisor.js +282 -0
- package/dist/heart/daemon/task-scheduler.js +117 -39
- package/dist/heart/daemon/terminal-ui.js +499 -0
- package/dist/heart/daemon/thoughts.js +138 -54
- package/dist/heart/daemon/up-progress.js +366 -0
- package/dist/heart/daemon/vault-items.js +56 -0
- package/dist/heart/delegation.js +1 -4
- package/dist/heart/external-events/router.js +1430 -0
- package/dist/heart/frontend-approval-runtime.js +506 -0
- package/dist/heart/frontend-journal.js +215 -0
- package/dist/heart/frontend-session-service.js +237 -0
- package/dist/heart/frontend-socket-client.js +164 -0
- package/dist/heart/frontend-socket.js +400 -0
- package/dist/heart/habits/habit-cancel.js +810 -0
- package/dist/heart/habits/habit-lifecycle.js +1327 -0
- package/dist/heart/habits/habit-migration.js +194 -0
- package/dist/heart/habits/habit-parser.js +278 -0
- package/dist/heart/habits/habit-runtime-state.js +93 -0
- package/dist/heart/habits/habit-scheduler.js +653 -0
- package/dist/heart/habits/habit-session-summary.js +318 -0
- package/dist/heart/habits/habit-session.js +636 -0
- package/dist/heart/{daemon → hatch}/hatch-flow.js +55 -62
- 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 +53 -18
- package/dist/heart/identity.js +196 -59
- package/dist/heart/kept-notes.js +289 -0
- package/dist/heart/kicks.js +1 -1
- package/dist/heart/machine-identity.js +161 -0
- package/dist/heart/mail-import-discovery.js +356 -0
- package/dist/heart/mailbox/mailbox-http-hooks.js +98 -0
- package/dist/heart/mailbox/mailbox-http-response.js +7 -0
- package/dist/heart/mailbox/mailbox-http-routes.js +398 -0
- package/dist/heart/mailbox/mailbox-http-static.js +103 -0
- package/dist/heart/mailbox/mailbox-http-transport.js +129 -0
- package/dist/heart/mailbox/mailbox-http.js +99 -0
- package/dist/heart/mailbox/mailbox-read.js +39 -0
- package/dist/heart/mailbox/mailbox-types.js +27 -0
- package/dist/heart/mailbox/mailbox-view.js +197 -0
- package/dist/heart/mailbox/readers/agent-machine.js +428 -0
- package/dist/heart/mailbox/readers/continuity-readers.js +329 -0
- package/dist/heart/mailbox/readers/mail.js +375 -0
- package/dist/heart/mailbox/readers/runtime-readers.js +823 -0
- package/dist/heart/mailbox/readers/sessions.js +231 -0
- package/dist/heart/mailbox/readers/shared.js +111 -0
- package/dist/heart/mcp/mcp-server.js +696 -0
- package/dist/heart/migrate-config.js +100 -0
- package/dist/heart/model-capabilities.js +11 -0
- package/dist/heart/orientation-frame.js +345 -0
- package/dist/heart/platform.js +81 -0
- package/dist/heart/primitives.js +1 -1
- package/dist/heart/private-runtime/decision-renderer.js +158 -0
- package/dist/heart/private-runtime/index.js +18 -0
- package/dist/heart/private-runtime/ledger.js +221 -0
- package/dist/heart/private-runtime/policy.js +252 -0
- package/dist/heart/private-runtime/types.js +2 -0
- package/dist/heart/progress-story.js +1 -1
- package/dist/heart/provider-attempt.js +137 -0
- package/dist/heart/provider-binding-resolver.js +273 -0
- package/dist/heart/provider-credentials.js +449 -0
- package/dist/heart/provider-failover.js +311 -0
- package/dist/heart/provider-models.js +96 -0
- package/dist/heart/provider-ping.js +265 -0
- package/dist/heart/provider-readiness-cache.js +119 -0
- package/dist/heart/provider-visibility.js +188 -0
- package/dist/heart/providers/anthropic-token.js +131 -0
- package/dist/heart/providers/anthropic.js +173 -60
- package/dist/heart/providers/azure.js +23 -11
- package/dist/heart/providers/error-classification.js +127 -0
- package/dist/heart/providers/github-copilot.js +34 -38
- package/dist/heart/providers/minimax-vlm.js +189 -0
- package/dist/heart/providers/minimax.js +26 -8
- package/dist/heart/providers/openai-codex-token.js +349 -0
- package/dist/heart/providers/openai-codex.js +55 -40
- package/dist/heart/providers/openai-compatible.js +177 -0
- package/dist/heart/run-ledger.js +247 -0
- package/dist/heart/runtime-capability-check.js +170 -0
- package/dist/heart/runtime-credentials.js +607 -0
- package/dist/heart/runtime-cwd.js +87 -0
- package/dist/heart/sense-truth.js +22 -4
- package/dist/heart/session-activity.js +92 -24
- package/dist/heart/session-events.js +1504 -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-redaction-repair-cli-main.js +31 -0
- package/dist/heart/session-redaction-repair.js +552 -0
- package/dist/heart/session-stats-cli-main.js +5 -0
- package/dist/heart/session-stats.js +183 -0
- package/dist/heart/session-transcript.js +133 -0
- package/dist/heart/start-of-turn-packet.js +372 -0
- package/dist/heart/steward-policy.js +618 -0
- package/dist/heart/streaming.js +604 -207
- package/dist/heart/structured-output.js +196 -0
- package/dist/heart/sync-classification.js +176 -0
- package/dist/heart/sync.js +449 -0
- package/dist/heart/target-resolution.js +11 -7
- 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-approval.js +382 -0
- package/dist/heart/tool-description.js +155 -0
- package/dist/heart/tool-friction.js +55 -0
- package/dist/heart/tool-loop.js +200 -0
- package/dist/heart/turn-context.js +482 -0
- package/dist/heart/turn-execution-lease.js +30 -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 +432 -0
- package/dist/heart/versioning/ouro-recovery-launcher.js +76 -0
- package/dist/heart/versioning/ouro-version-manager.js +409 -0
- package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
- package/dist/heart/{daemon → versioning}/update-checker.js +6 -1
- package/dist/heart/versioning/update-hooks.js +154 -0
- package/dist/heart/versioning/version-intent.js +114 -0
- package/dist/heart/work-card.js +380 -0
- package/dist/mailbox-ui/assets/index-Cyv4mw3Y.js +1 -0
- package/dist/mailbox-ui/assets/index-Du_9G9WO.css +1 -0
- package/dist/mailbox-ui/assets/vendor-CcN1XpQ9.js +61 -0
- package/dist/mailbox-ui/index.html +16 -0
- package/dist/mailroom/attention.js +167 -0
- package/dist/mailroom/autonomy.js +209 -0
- package/dist/mailroom/blob-store.js +889 -0
- package/dist/mailroom/body-cache.js +61 -0
- package/dist/mailroom/cache-sync-cli.js +58 -0
- package/dist/mailroom/core.js +803 -0
- package/dist/mailroom/entry.js +160 -0
- package/dist/mailroom/file-store.js +568 -0
- package/dist/mailroom/hosted-cache-sync.js +384 -0
- package/dist/mailroom/mbox-import.js +393 -0
- package/dist/mailroom/migration.js +164 -0
- package/dist/mailroom/outbound.js +380 -0
- package/dist/mailroom/policy.js +263 -0
- package/dist/mailroom/reader.js +292 -0
- package/dist/mailroom/search-cache.js +513 -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 +24 -2
- package/dist/mind/context.js +309 -111
- package/dist/mind/desk-section.js +362 -0
- package/dist/mind/diary-integrity.js +60 -0
- package/dist/mind/{memory.js → diary.js} +68 -77
- package/dist/mind/embedding-provider.js +60 -0
- package/dist/mind/file-state.js +179 -0
- package/dist/mind/{associative-recall.js → note-search.js} +47 -58
- package/dist/mind/obligation-steering.js +199 -3
- package/dist/mind/pending.js +36 -10
- package/dist/mind/prompt-budget.js +479 -0
- package/dist/mind/prompt-refresh.js +3 -2
- package/dist/mind/prompt.js +1050 -189
- package/dist/mind/provenance-trust.js +26 -0
- package/dist/mind/record-paths.js +312 -0
- package/dist/mind/scrutiny.js +173 -0
- package/dist/mind/session-transaction.js +564 -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 +55 -35
- package/dist/nerves/coverage/source-scanner.js +4 -4
- package/dist/nerves/event-buffer.js +111 -0
- package/dist/nerves/index.js +293 -9
- 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 +159 -0
- package/dist/nerves/runtime.js +17 -1
- package/dist/repertoire/ado-client.js +15 -56
- package/dist/repertoire/ado-semantic.js +16 -10
- package/dist/repertoire/api-client.js +97 -0
- package/dist/repertoire/bitwarden-store.js +1045 -0
- package/dist/repertoire/bundle-templates.js +71 -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 +331 -0
- package/dist/repertoire/coding/feedback.js +174 -32
- package/dist/repertoire/coding/index.js +15 -3
- package/dist/repertoire/coding/manager.js +159 -10
- package/dist/repertoire/coding/spawner.js +58 -11
- package/dist/repertoire/coding/tools.js +221 -15
- package/dist/repertoire/coding/workbench-client.js +272 -0
- package/dist/repertoire/coding/workbench-manager.js +346 -0
- package/dist/repertoire/commerce-errors.js +109 -0
- package/dist/repertoire/commerce-self-test.js +156 -0
- package/dist/repertoire/credential-access.js +178 -0
- package/dist/repertoire/desk/classifier.js +362 -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 +811 -18
- package/dist/repertoire/mcp-client.js +44 -3
- package/dist/repertoire/mcp-manager.js +427 -139
- package/dist/repertoire/mcp-tools.js +124 -0
- package/dist/repertoire/plugin-mcp.js +175 -0
- package/dist/repertoire/plugins.js +253 -0
- package/dist/repertoire/relationship-authorization.js +322 -0
- package/dist/repertoire/shell-sessions.js +134 -0
- package/dist/repertoire/skills.js +48 -4
- package/dist/repertoire/stripe-client.js +131 -0
- package/dist/repertoire/tool-arguments.js +170 -0
- package/dist/repertoire/tool-results.js +29 -0
- package/dist/repertoire/tools-a2a.js +699 -0
- package/dist/repertoire/tools-attachments.js +322 -0
- package/dist/repertoire/tools-awaiting.js +575 -0
- package/dist/repertoire/tools-base.js +77 -1138
- package/dist/repertoire/tools-bluebubbles.js +2 -0
- package/dist/repertoire/tools-bridge.js +144 -0
- package/dist/repertoire/tools-bundle.js +993 -0
- package/dist/repertoire/tools-commerce.js +253 -0
- package/dist/repertoire/tools-config.js +186 -0
- package/dist/repertoire/tools-continuity.js +575 -0
- package/dist/repertoire/tools-credential.js +383 -0
- package/dist/repertoire/tools-evolution.js +527 -0
- package/dist/repertoire/tools-files.js +344 -0
- package/dist/repertoire/tools-flight.js +290 -0
- package/dist/repertoire/tools-flow.js +119 -0
- package/dist/repertoire/tools-github.js +3 -8
- package/dist/repertoire/tools-habits.js +103 -0
- package/dist/repertoire/tools-mail.js +1828 -0
- package/dist/repertoire/tools-notes.js +485 -0
- package/dist/repertoire/tools-obligations.js +182 -0
- package/dist/repertoire/tools-orientation.js +31 -0
- package/dist/repertoire/tools-record.js +482 -0
- package/dist/repertoire/tools-rsvp.js +139 -0
- package/dist/repertoire/tools-runtime.js +150 -0
- package/dist/repertoire/tools-sanctuary-host.js +202 -0
- package/dist/repertoire/tools-session.js +1133 -0
- package/dist/repertoire/tools-shell.js +149 -0
- package/dist/repertoire/tools-steward-policy.js +119 -0
- package/dist/repertoire/tools-stripe.js +224 -0
- package/dist/repertoire/tools-surface.js +369 -0
- package/dist/repertoire/tools-teams.js +12 -39
- package/dist/repertoire/tools-telegram-contacts.js +37 -0
- package/dist/repertoire/tools-travel.js +125 -0
- package/dist/repertoire/tools-trip.js +982 -0
- package/dist/repertoire/tools-unraid.js +531 -0
- package/dist/repertoire/tools-user-profile.js +146 -0
- package/dist/repertoire/tools-vault.js +40 -0
- package/dist/repertoire/tools-voice.js +145 -0
- package/dist/repertoire/tools.js +494 -148
- package/dist/repertoire/travel-api-client.js +360 -0
- package/dist/repertoire/unraid-client.js +155 -0
- package/dist/repertoire/unraid-restart.js +339 -0
- package/dist/repertoire/user-profile.js +131 -0
- package/dist/repertoire/vault-setup.js +246 -0
- package/dist/repertoire/vault-unlock.js +628 -0
- package/dist/rsvp/aisleplanner-client.js +354 -0
- package/dist/rsvp/cli.js +926 -0
- package/dist/rsvp/config.js +327 -0
- package/dist/rsvp/cutover.js +433 -0
- package/dist/rsvp/diagnostics.js +232 -0
- package/dist/rsvp/diff-renderer.js +176 -0
- package/dist/rsvp/habit-policy.js +110 -0
- package/dist/rsvp/habit-stage.js +123 -0
- package/dist/rsvp/incident-bundle.js +97 -0
- package/dist/rsvp/migration.js +204 -0
- package/dist/rsvp/native-habit-runner.js +630 -0
- package/dist/rsvp/outbound-state.js +628 -0
- package/dist/rsvp/query.js +118 -0
- package/dist/rsvp/replay.js +233 -0
- package/dist/rsvp/snapshot.js +232 -0
- package/dist/rsvp/spend-ledger.js +175 -0
- package/dist/scripts/claude-code-hook.js +41 -0
- package/dist/scripts/claude-code-stop-hook.js +47 -0
- package/dist/senses/a2a-entry.js +115 -0
- package/dist/senses/acp-server.js +386 -0
- package/dist/senses/attention-queue.js +186 -0
- package/dist/senses/await-turn-message.js +58 -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} +355 -40
- package/dist/senses/bluebubbles/context-packet.js +207 -0
- package/dist/senses/bluebubbles/context-smoke.js +144 -0
- package/dist/senses/bluebubbles/entry.js +90 -0
- package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +21 -3
- package/dist/senses/bluebubbles/index.js +3841 -0
- package/dist/senses/bluebubbles/latest-turn.js +311 -0
- package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +121 -71
- package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +159 -28
- package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +24 -13
- package/dist/senses/bluebubbles/outbound-state.js +308 -0
- package/dist/senses/bluebubbles/processed-log.js +133 -0
- package/dist/senses/bluebubbles/reaction-policy.js +47 -0
- package/dist/senses/bluebubbles/replay.js +284 -0
- package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +30 -2
- package/dist/senses/bluebubbles/semantic-receipts.js +1986 -0
- package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
- package/dist/senses/bluebubbles/webhook-registration.js +228 -0
- package/dist/senses/bluebubbles-meta-guard.js +39 -0
- 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 +241 -0
- package/dist/senses/cli/virtual-list.js +35 -0
- package/dist/senses/cli-entry.js +60 -8
- package/dist/senses/cli.js +604 -320
- package/dist/senses/commands.js +66 -3
- package/dist/senses/context-packet-ledger.js +371 -0
- package/dist/senses/context-packets.js +154 -0
- package/dist/senses/habit-lifecycle-guard.js +24 -0
- package/dist/senses/habit-turn-message.js +160 -0
- package/dist/senses/ingress-evidence.js +2 -0
- package/dist/senses/mail-entry.js +66 -0
- package/dist/senses/mail.js +524 -0
- package/dist/senses/pipeline.js +1115 -204
- package/dist/senses/private-runtime-worker.js +859 -0
- package/dist/senses/private-runtime.js +1517 -0
- package/dist/senses/proactive-content-guard.js +51 -0
- package/dist/senses/root-host-approval-port.js +345 -0
- package/dist/senses/root-host-approval-runtime.js +393 -0
- package/dist/senses/sanctuary-authority-resident.js +102 -0
- package/dist/senses/sanctuary-download-credit-presentation.js +31 -0
- package/dist/senses/sanctuary-full-visibility-contract.js +302 -0
- package/dist/senses/sanctuary-grounding.js +118 -0
- package/dist/senses/sanctuary-health-acceptance-probe-entry.js +12 -0
- package/dist/senses/sanctuary-health-acceptance-probe.js +774 -0
- package/dist/senses/sanctuary-health-runner.js +100 -0
- package/dist/senses/sanctuary-health.js +408 -0
- package/dist/senses/sanctuary-install-state-contract.js +126 -0
- package/dist/senses/sanctuary-interactive-control.js +410 -0
- package/dist/senses/sanctuary-media-catalog-contract.js +297 -0
- package/dist/senses/sanctuary-media-optimization.js +514 -0
- package/dist/senses/sanctuary-runtime.js +340 -0
- package/dist/senses/sanctuary-sab.js +85 -0
- package/dist/senses/sanctuary-storage-optimization-contract.js +32 -0
- package/dist/senses/shared-turn.js +772 -0
- package/dist/senses/surface-tool.js +109 -0
- package/dist/senses/teams-entry.js +60 -8
- package/dist/senses/teams.js +519 -218
- package/dist/senses/telegram-admission.js +718 -0
- package/dist/senses/telegram-approval-runtime.js +793 -0
- package/dist/senses/telegram-attachments.js +186 -0
- package/dist/senses/telegram-audit-ledger.js +220 -0
- package/dist/senses/telegram-authority-transport.js +231 -0
- package/dist/senses/telegram-client.js +1749 -0
- package/dist/senses/telegram-effect-adapter.js +896 -0
- package/dist/senses/telegram-entry.js +83 -0
- package/dist/senses/telegram.js +2324 -0
- package/dist/senses/trust-gate.js +104 -9
- package/dist/senses/voice/audio-playback.js +237 -0
- package/dist/senses/voice/audio-routing.js +119 -0
- package/dist/senses/voice/elevenlabs.js +202 -0
- package/dist/senses/voice/floor-control.js +431 -0
- package/dist/senses/voice/floor-controller.js +115 -0
- package/dist/senses/voice/golden-path.js +116 -0
- package/dist/senses/voice/index.js +29 -0
- package/dist/senses/voice/meeting.js +113 -0
- package/dist/senses/voice/outbound.js +190 -0
- package/dist/senses/voice/phone.js +33 -0
- package/dist/senses/voice/playback.js +139 -0
- package/dist/senses/voice/realtime-eval.js +496 -0
- package/dist/senses/voice/realtime-trace.js +531 -0
- package/dist/senses/voice/transcript.js +70 -0
- package/dist/senses/voice/turn.js +191 -0
- package/dist/senses/voice/twilio-phone-runtime.js +807 -0
- package/dist/senses/voice/twilio-phone.js +5031 -0
- package/dist/senses/voice/types.js +2 -0
- package/dist/senses/voice/whisper.js +161 -0
- package/dist/senses/voice-entry.js +81 -0
- package/dist/senses/voice-realtime-eval-command.js +99 -0
- package/dist/senses/voice-realtime-eval-entry.js +21 -0
- package/dist/senses/voice-twilio-entry.js +87 -0
- package/dist/trips/core.js +138 -0
- package/dist/trips/store.js +265 -0
- package/dist/util/frontmatter.js +69 -0
- package/npm-shrinkwrap.json +8138 -0
- package/package.json +72 -13
- package/skills/agent-commerce.md +113 -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 +99 -0
- package/skills/travel-planning.md +138 -0
- package/dist/heart/daemon/auth-flow.js +0 -430
- package/dist/heart/daemon/ouro-path-installer.js +0 -260
- package/dist/heart/daemon/ouro-version-manager.js +0 -171
- package/dist/heart/daemon/update-hooks.js +0 -138
- package/dist/heart/obligations.js +0 -191
- package/dist/heart/safe-workspace.js +0 -228
- package/dist/heart/session-recall.js +0 -116
- package/dist/mind/friends/channel.js +0 -84
- package/dist/mind/friends/group-context.js +0 -144
- package/dist/mind/friends/resolver.js +0 -84
- package/dist/mind/friends/store-file.js +0 -190
- package/dist/mind/friends/store.js +0 -4
- package/dist/mind/friends/tokens.js +0 -26
- package/dist/mind/friends/trust-explanation.js +0 -74
- package/dist/mind/friends/types.js +0 -29
- package/dist/repertoire/tasks/board.js +0 -134
- package/dist/repertoire/tasks/index.js +0 -224
- package/dist/repertoire/tasks/lifecycle.js +0 -80
- package/dist/repertoire/tasks/middleware.js +0 -65
- package/dist/repertoire/tasks/parser.js +0 -173
- package/dist/repertoire/tasks/scanner.js +0 -132
- package/dist/repertoire/tasks/transitions.js +0 -144
- package/dist/senses/bluebubbles-entry.js +0 -13
- package/dist/senses/bluebubbles.js +0 -1181
- package/dist/senses/debug-activity.js +0 -154
- package/dist/senses/inner-dialog-worker.js +0 -90
- package/dist/senses/inner-dialog.js +0 -525
- package/subagents/README.md +0 -7
- /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/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +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,85 +1,153 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.MAX_PROVIDER_ITERATIONS = void 0;
|
|
4
|
+
exports.validateToolCallBatchAtProductionBoundary = validateToolCallBatchAtProductionBoundary;
|
|
4
5
|
exports.createProviderRegistry = createProviderRegistry;
|
|
6
|
+
exports.getProviderRuntime = getProviderRuntime;
|
|
5
7
|
exports.resetProviderRuntime = resetProviderRuntime;
|
|
6
8
|
exports.getModel = getModel;
|
|
7
9
|
exports.getProvider = getProvider;
|
|
8
10
|
exports.createSummarize = createSummarize;
|
|
9
11
|
exports.getProviderDisplayLabel = getProviderDisplayLabel;
|
|
10
|
-
exports.
|
|
12
|
+
exports.createHabitCallbackBuffer = createHabitCallbackBuffer;
|
|
13
|
+
exports.resumeApprovalContinuation = resumeApprovalContinuation;
|
|
14
|
+
exports.isChatStyleChannel = isChatStyleChannel;
|
|
15
|
+
exports.buildPonderResult = buildPonderResult;
|
|
16
|
+
exports.isExternalStateQuery = isExternalStateQuery;
|
|
17
|
+
exports.getSettleRetryError = getSettleRetryError;
|
|
11
18
|
exports.stripLastToolCalls = stripLastToolCalls;
|
|
12
19
|
exports.repairOrphanedToolCalls = repairOrphanedToolCalls;
|
|
13
|
-
exports.isTransientError = isTransientError;
|
|
14
|
-
exports.classifyTransientError = classifyTransientError;
|
|
15
20
|
exports.runAgent = runAgent;
|
|
16
21
|
const config_1 = require("./config");
|
|
17
22
|
const identity_1 = require("./identity");
|
|
18
23
|
const tools_1 = require("../repertoire/tools");
|
|
19
|
-
const
|
|
24
|
+
const tool_arguments_1 = require("../repertoire/tool-arguments");
|
|
25
|
+
const session_events_1 = require("./session-events");
|
|
26
|
+
const tool_approval_1 = require("./tool-approval");
|
|
27
|
+
const friends_1 = require("@ouro.bot/friends");
|
|
28
|
+
const streaming_1 = require("./streaming");
|
|
20
29
|
const runtime_1 = require("../nerves/runtime");
|
|
30
|
+
function validateToolCallBatchAtProductionBoundary(calls, activeTools) {
|
|
31
|
+
const callIdCounts = new Map();
|
|
32
|
+
for (const call of calls)
|
|
33
|
+
callIdCounts.set(call.id, (callIdCounts.get(call.id) ?? 0) + 1);
|
|
34
|
+
return calls.map((call) => {
|
|
35
|
+
if (callIdCounts.get(call.id) !== 1)
|
|
36
|
+
return { call, error: "duplicate tool call id" };
|
|
37
|
+
const advertised = activeTools.find((tool) => tool.function.name === call.name);
|
|
38
|
+
if (!advertised || !advertised.function.parameters || typeof advertised.function.parameters !== "object")
|
|
39
|
+
return { call, error: "tool was not advertised with a valid argument schema" };
|
|
40
|
+
const validated = (0, tool_arguments_1.validateAdvertisedToolArguments)(call.arguments, advertised.function.parameters);
|
|
41
|
+
return validated.ok ? { call, advertised, validated: validated.value } : { call, error: validated.reason };
|
|
42
|
+
});
|
|
43
|
+
}
|
|
21
44
|
const context_1 = require("../mind/context");
|
|
45
|
+
const prompt_budget_1 = require("../mind/prompt-budget");
|
|
22
46
|
const prompt_1 = require("../mind/prompt");
|
|
23
|
-
const
|
|
47
|
+
const kept_notes_1 = require("./kept-notes");
|
|
48
|
+
const error_classification_1 = require("./providers/error-classification");
|
|
24
49
|
const anthropic_1 = require("./providers/anthropic");
|
|
25
50
|
const azure_1 = require("./providers/azure");
|
|
26
51
|
const minimax_1 = require("./providers/minimax");
|
|
27
52
|
const openai_codex_1 = require("./providers/openai-codex");
|
|
28
53
|
const github_copilot_1 = require("./providers/github-copilot");
|
|
29
|
-
const
|
|
54
|
+
const openai_compatible_1 = require("./providers/openai-compatible");
|
|
55
|
+
const orientation_frame_1 = require("./orientation-frame");
|
|
30
56
|
const identity_2 = require("./identity");
|
|
31
57
|
const socket_client_1 = require("./daemon/socket-client");
|
|
32
|
-
const obligations_1 = require("
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
+
const obligations_1 = require("../arc/obligations");
|
|
59
|
+
const tool_loop_1 = require("./tool-loop");
|
|
60
|
+
const packets_1 = require("../arc/packets");
|
|
61
|
+
const tool_friction_1 = require("./tool-friction");
|
|
62
|
+
const provider_models_1 = require("./provider-models");
|
|
63
|
+
const provider_credentials_1 = require("./provider-credentials");
|
|
64
|
+
const habit_session_1 = require("./habits/habit-session");
|
|
65
|
+
const provider_attempt_1 = require("./provider-attempt");
|
|
66
|
+
const openai_codex_token_1 = require("./providers/openai-codex-token");
|
|
67
|
+
// Cache only immutable provider construction inputs. ProviderRuntime owns
|
|
68
|
+
// mutable per-turn state (for example Responses nativeInput), so every caller
|
|
69
|
+
// must receive a fresh instance even when its binding fingerprint is unchanged.
|
|
70
|
+
const _providerRuntimeFactories = {
|
|
71
|
+
human: null,
|
|
72
|
+
agent: null,
|
|
73
|
+
};
|
|
74
|
+
function providerLaneForFacing(facing) {
|
|
75
|
+
return facing === "human" ? "outward" : "inner";
|
|
76
|
+
}
|
|
77
|
+
function resolveRuntimeProviderBinding(facing, owner) {
|
|
78
|
+
const lane = providerLaneForFacing(facing);
|
|
79
|
+
const config = (0, identity_1.loadAgentConfig)(owner);
|
|
80
|
+
const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
|
|
81
|
+
return { lane, provider: facingConfig.provider, model: facingConfig.model };
|
|
82
|
+
}
|
|
83
|
+
async function getProviderRuntimeFingerprint(facing, owner) {
|
|
84
|
+
const agentName = owner?.agentName ?? (0, identity_2.getAgentName)();
|
|
85
|
+
const binding = resolveRuntimeProviderBinding(facing, owner);
|
|
86
|
+
const credential = await (0, provider_credentials_1.readProviderCredentialRecord)(agentName, binding.provider);
|
|
87
|
+
if (!credential.ok) {
|
|
88
|
+
throw new Error([
|
|
89
|
+
`${binding.lane} provider ${binding.provider} (${binding.model}) has no credentials for ${agentName}.`,
|
|
90
|
+
credential.error,
|
|
91
|
+
`Run \`ouro auth --agent ${agentName} --provider ${binding.provider}\`.`,
|
|
92
|
+
].join("\n"));
|
|
93
|
+
}
|
|
94
|
+
let record = credential.record;
|
|
95
|
+
if (binding.provider === "openai-codex") {
|
|
96
|
+
const refresh = await (0, openai_codex_token_1.refreshOpenAICodexProviderCredentials)(agentName, {
|
|
97
|
+
record,
|
|
98
|
+
reason: "runtime-init",
|
|
99
|
+
});
|
|
100
|
+
if (refresh.ok) {
|
|
101
|
+
record = refresh.record;
|
|
58
102
|
}
|
|
59
|
-
/* v8 ignore stop */
|
|
60
103
|
}
|
|
104
|
+
return {
|
|
105
|
+
binding,
|
|
106
|
+
fingerprint: JSON.stringify({
|
|
107
|
+
...(owner ? { agentName: owner.agentName, agentRoot: owner.agentRoot } : {}),
|
|
108
|
+
lane: binding.lane,
|
|
109
|
+
provider: binding.provider,
|
|
110
|
+
model: binding.model,
|
|
111
|
+
credentialRevision: record.revision,
|
|
112
|
+
}),
|
|
113
|
+
credential: record,
|
|
114
|
+
};
|
|
61
115
|
}
|
|
62
116
|
function createProviderRegistry() {
|
|
63
|
-
const factories = {
|
|
64
|
-
azure: azure_1.createAzureProviderRuntime,
|
|
65
|
-
anthropic: anthropic_1.createAnthropicProviderRuntime,
|
|
66
|
-
minimax: minimax_1.createMinimaxProviderRuntime,
|
|
67
|
-
"openai-codex": openai_codex_1.createOpenAICodexProviderRuntime,
|
|
68
|
-
"github-copilot": github_copilot_1.createGithubCopilotProviderRuntime,
|
|
69
|
-
};
|
|
70
117
|
return {
|
|
71
|
-
resolve() {
|
|
72
|
-
const
|
|
73
|
-
|
|
118
|
+
resolve(provider, model, credential) {
|
|
119
|
+
const providerConfig = { ...credential.config, ...credential.credentials };
|
|
120
|
+
switch (provider) {
|
|
121
|
+
case "azure":
|
|
122
|
+
return (0, azure_1.createAzureProviderRuntime)(model, providerConfig);
|
|
123
|
+
case "anthropic":
|
|
124
|
+
return (0, anthropic_1.createAnthropicProviderRuntime)(model, providerConfig);
|
|
125
|
+
case "minimax":
|
|
126
|
+
return (0, minimax_1.createMinimaxProviderRuntime)(model, providerConfig);
|
|
127
|
+
case "openai-codex":
|
|
128
|
+
return (0, openai_codex_1.createOpenAICodexProviderRuntime)(model, providerConfig);
|
|
129
|
+
case "github-copilot":
|
|
130
|
+
return (0, github_copilot_1.createGithubCopilotProviderRuntime)(model, providerConfig);
|
|
131
|
+
case "openai-compatible":
|
|
132
|
+
case "openai-compatible-gemini":
|
|
133
|
+
return (0, openai_compatible_1.createOpenAICompatibleProviderRuntime)(provider, model, providerConfig);
|
|
134
|
+
}
|
|
74
135
|
},
|
|
75
136
|
};
|
|
76
137
|
}
|
|
77
|
-
function getProviderRuntime() {
|
|
138
|
+
async function getProviderRuntime(facing = "human", owner) {
|
|
139
|
+
const scope = owner ? { agentName: owner.agentName, agentRoot: owner.agentRoot } : undefined;
|
|
140
|
+
let runtime = null;
|
|
78
141
|
try {
|
|
79
|
-
const fingerprint = getProviderRuntimeFingerprint();
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
142
|
+
const { binding, fingerprint, credential } = await getProviderRuntimeFingerprint(facing, scope);
|
|
143
|
+
const cached = _providerRuntimeFactories[facing];
|
|
144
|
+
if (!cached || cached.fingerprint !== fingerprint) {
|
|
145
|
+
const create = () => createProviderRegistry().resolve(binding.provider, binding.model, credential);
|
|
146
|
+
runtime = create();
|
|
147
|
+
_providerRuntimeFactories[facing] = runtime ? { fingerprint, create } : null;
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
runtime = cached.create();
|
|
83
151
|
}
|
|
84
152
|
}
|
|
85
153
|
catch (error) {
|
|
@@ -89,43 +157,46 @@ function getProviderRuntime() {
|
|
|
89
157
|
event: "engine.provider_init_error",
|
|
90
158
|
component: "engine",
|
|
91
159
|
message: msg,
|
|
92
|
-
meta: {},
|
|
160
|
+
meta: { facing },
|
|
93
161
|
});
|
|
94
162
|
// eslint-disable-next-line no-console -- pre-boot guard: provider init failure
|
|
95
163
|
console.error(`\n[fatal] ${msg}\n`);
|
|
96
|
-
|
|
97
|
-
throw new Error("unreachable");
|
|
164
|
+
throw error instanceof Error ? error : new Error(msg);
|
|
98
165
|
}
|
|
99
|
-
if (!
|
|
166
|
+
if (!runtime) {
|
|
167
|
+
const msg = "provider runtime could not be initialized.";
|
|
100
168
|
(0, runtime_1.emitNervesEvent)({
|
|
101
169
|
level: "error",
|
|
102
170
|
event: "engine.provider_init_error",
|
|
103
171
|
component: "engine",
|
|
104
|
-
message:
|
|
105
|
-
meta: {},
|
|
172
|
+
message: msg,
|
|
173
|
+
meta: { facing },
|
|
106
174
|
});
|
|
107
|
-
|
|
108
|
-
|
|
175
|
+
// eslint-disable-next-line no-console -- pre-boot guard: provider init failure
|
|
176
|
+
console.error(`\n[fatal] ${msg}\n`);
|
|
177
|
+
throw new Error(msg);
|
|
109
178
|
}
|
|
110
|
-
|
|
179
|
+
// The shared tool loop supplies approval continuation to every provider adapter.
|
|
180
|
+
return { ...runtime, capabilities: new Set([...runtime.capabilities, "approval-continuation"]) };
|
|
111
181
|
}
|
|
112
182
|
/**
|
|
113
|
-
* Clear
|
|
114
|
-
* current config. Runtime
|
|
115
|
-
*
|
|
183
|
+
* Clear cached provider construction inputs so the next access re-reads them
|
|
184
|
+
* from current config. Runtime instances are always per-caller and are never
|
|
185
|
+
* shared across turns.
|
|
116
186
|
*/
|
|
117
187
|
function resetProviderRuntime() {
|
|
118
|
-
|
|
188
|
+
_providerRuntimeFactories.human = null;
|
|
189
|
+
_providerRuntimeFactories.agent = null;
|
|
119
190
|
}
|
|
120
|
-
function getModel() {
|
|
121
|
-
return
|
|
191
|
+
function getModel(facing = "human") {
|
|
192
|
+
return resolveRuntimeProviderBinding(facing).model;
|
|
122
193
|
}
|
|
123
|
-
function getProvider() {
|
|
124
|
-
return
|
|
194
|
+
function getProvider(facing = "human") {
|
|
195
|
+
return resolveRuntimeProviderBinding(facing).provider;
|
|
125
196
|
}
|
|
126
|
-
function createSummarize() {
|
|
197
|
+
function createSummarize(facing = "human") {
|
|
127
198
|
return async (transcript, instruction) => {
|
|
128
|
-
const runtime = getProviderRuntime();
|
|
199
|
+
const runtime = await getProviderRuntime(facing);
|
|
129
200
|
const client = runtime.client;
|
|
130
201
|
const response = await client.chat.completions.create({
|
|
131
202
|
model: runtime.model,
|
|
@@ -138,137 +209,593 @@ function createSummarize() {
|
|
|
138
209
|
return response.choices?.[0]?.message?.content ?? transcript;
|
|
139
210
|
};
|
|
140
211
|
}
|
|
141
|
-
function getProviderDisplayLabel() {
|
|
142
|
-
const
|
|
212
|
+
function getProviderDisplayLabel(facing = "human") {
|
|
213
|
+
const binding = resolveRuntimeProviderBinding(facing);
|
|
214
|
+
const provider = binding.provider;
|
|
215
|
+
const model = binding.model || "unknown";
|
|
143
216
|
const providerLabelBuilders = {
|
|
144
217
|
azure: () => {
|
|
145
|
-
|
|
146
|
-
return `azure openai (${config.deployment || "default"}, model: ${config.modelName || "unknown"})`;
|
|
218
|
+
return `azure openai (model: ${model})`;
|
|
147
219
|
},
|
|
148
|
-
anthropic: () => `anthropic (${
|
|
149
|
-
minimax: () => `minimax (${
|
|
150
|
-
"openai-codex": () => `openai codex (${
|
|
220
|
+
anthropic: () => `anthropic (${model})`,
|
|
221
|
+
minimax: () => `minimax (${model})`,
|
|
222
|
+
"openai-codex": () => `openai codex (${model})`,
|
|
151
223
|
/* v8 ignore next -- branch: tested via display label unit test @preserve */
|
|
152
|
-
"github-copilot": () => `github copilot (${
|
|
224
|
+
"github-copilot": () => `github copilot (${model})`,
|
|
225
|
+
"openai-compatible": () => `z.ai openai-compatible (${model})`,
|
|
226
|
+
"openai-compatible-gemini": () => `gemini openai-compatible (${model})`,
|
|
153
227
|
};
|
|
154
228
|
return providerLabelBuilders[provider]();
|
|
155
229
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
const
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
230
|
+
function createCallbackBuffer(callbacks, mode) {
|
|
231
|
+
const events = [];
|
|
232
|
+
const bufferedCallbacks = {
|
|
233
|
+
...callbacks,
|
|
234
|
+
onTextChunk: (text) => { events.push({ kind: "text", text }); },
|
|
235
|
+
onClearText: () => { events.push({ kind: "clear" }); },
|
|
236
|
+
flushNow: () => { events.push({ kind: "flush" }); },
|
|
237
|
+
};
|
|
238
|
+
if (mode === "all") {
|
|
239
|
+
bufferedCallbacks.onModelStreamStart = () => { events.push({ kind: "stream-start" }); };
|
|
240
|
+
bufferedCallbacks.onReasoningChunk = (text) => { events.push({ kind: "reasoning", text }); };
|
|
241
|
+
}
|
|
242
|
+
return {
|
|
243
|
+
callbacks: bufferedCallbacks,
|
|
244
|
+
async flush() {
|
|
245
|
+
for (const event of events.splice(0)) {
|
|
246
|
+
switch (event.kind) {
|
|
247
|
+
case "stream-start":
|
|
248
|
+
callbacks.onModelStreamStart();
|
|
249
|
+
break;
|
|
250
|
+
case "text":
|
|
251
|
+
callbacks.onTextChunk(event.text);
|
|
252
|
+
break;
|
|
253
|
+
case "reasoning":
|
|
254
|
+
callbacks.onReasoningChunk(event.text);
|
|
255
|
+
break;
|
|
256
|
+
case "clear":
|
|
257
|
+
callbacks.onClearText?.();
|
|
258
|
+
break;
|
|
259
|
+
case "flush":
|
|
260
|
+
await callbacks.flushNow?.();
|
|
261
|
+
break;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
},
|
|
265
|
+
discard() {
|
|
266
|
+
events.splice(0);
|
|
267
|
+
},
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
function createHabitCallbackBuffer(callbacks) {
|
|
271
|
+
return createCallbackBuffer(callbacks, "all");
|
|
272
|
+
}
|
|
273
|
+
function createFinalOnlyTextBuffer(callbacks) {
|
|
274
|
+
return createCallbackBuffer(callbacks, "text-only");
|
|
275
|
+
}
|
|
276
|
+
exports.MAX_PROVIDER_ITERATIONS = 8;
|
|
277
|
+
function continuationCallbacks(callbacks, text) {
|
|
278
|
+
const noop = () => undefined;
|
|
279
|
+
return {
|
|
280
|
+
onModelStart: callbacks.onModelStart ?? noop,
|
|
281
|
+
onModelStreamStart: callbacks.onModelStreamStart ?? noop,
|
|
282
|
+
onTextChunk: (chunk) => {
|
|
283
|
+
text.value += chunk;
|
|
284
|
+
callbacks.onTextChunk?.(chunk);
|
|
285
|
+
},
|
|
286
|
+
onReasoningChunk: callbacks.onReasoningChunk ?? noop,
|
|
287
|
+
onToolStart: callbacks.onToolStart ?? noop,
|
|
288
|
+
onToolEnd: callbacks.onToolEnd ?? noop,
|
|
289
|
+
onError: callbacks.onError ?? noop,
|
|
290
|
+
...(callbacks.onClearText ? { onClearText: callbacks.onClearText } : {}),
|
|
291
|
+
...(callbacks.flushNow ? { flushNow: callbacks.flushNow } : {}),
|
|
292
|
+
...(callbacks.settleOutputMode ? { settleOutputMode: callbacks.settleOutputMode } : {}),
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
async function resumeApprovalContinuation(options) {
|
|
296
|
+
const claim = options.claimContinuation();
|
|
297
|
+
if (!claim.claimed) {
|
|
298
|
+
if (claim.interruptedAfterAttempt) {
|
|
299
|
+
const notice = "the approval continuation was interrupted after provider work began; its outcome is indeterminate and it will not be retried automatically";
|
|
300
|
+
await options.deliver(notice);
|
|
301
|
+
(0, runtime_1.emitNervesEvent)({
|
|
302
|
+
level: "error",
|
|
303
|
+
component: "engine",
|
|
304
|
+
event: "engine.approval_continuation_indeterminate",
|
|
305
|
+
message: "approval continuation interrupted after provider attempt",
|
|
306
|
+
meta: { approvalId: options.record.approvalId, continuationState: claim.record.continuationState },
|
|
307
|
+
});
|
|
308
|
+
return { outcome: "terminal_notice", messages: structuredClone(options.sessionMessages) };
|
|
309
|
+
}
|
|
310
|
+
(0, runtime_1.emitNervesEvent)({
|
|
311
|
+
component: "engine",
|
|
312
|
+
event: "engine.approval_continuation_duplicate",
|
|
313
|
+
message: "approval continuation was already consumed",
|
|
314
|
+
meta: { approvalId: options.record.approvalId },
|
|
315
|
+
});
|
|
316
|
+
return { outcome: "already_continued", messages: structuredClone(options.sessionMessages) };
|
|
317
|
+
}
|
|
318
|
+
const materialized = (0, session_events_1.materializeApprovalTerminal)({
|
|
319
|
+
messages: options.sessionMessages,
|
|
320
|
+
checkpoint: options.checkpoint,
|
|
321
|
+
record: options.record,
|
|
322
|
+
currentSessionRevision: options.currentSessionRevision,
|
|
323
|
+
materializedApprovalIds: options.materializedApprovalIds,
|
|
324
|
+
});
|
|
325
|
+
const recoveredMaterialization = claim.record.continuationState === "materialized";
|
|
326
|
+
if (!recoveredMaterialization) {
|
|
327
|
+
await options.persist(materialized.messages);
|
|
328
|
+
await options.markContinuationMaterialized();
|
|
329
|
+
}
|
|
330
|
+
const currentOptions = options.revalidate ? await options.revalidate()
|
|
331
|
+
: options.runAgentOptions?.toolContext?.relationshipAuthorization ? null : options.runAgentOptions;
|
|
332
|
+
if (!materialized.resumeProvider || currentOptions === null) {
|
|
333
|
+
if (currentOptions === null)
|
|
334
|
+
(0, runtime_1.emitNervesEvent)({
|
|
335
|
+
level: "warn", component: "engine", event: "engine.approval_continuation_authority_block",
|
|
336
|
+
message: "approval continuation has no current relationship authority",
|
|
337
|
+
meta: { approvalId: options.record.approvalId, state: options.record.state },
|
|
338
|
+
});
|
|
339
|
+
const effect = options.record.state === "succeeded" ? "the approved action completed"
|
|
340
|
+
: options.record.state === "failed" ? "the approved action failed" : "the protected action was not executed";
|
|
341
|
+
await options.deliver(materialized.directNotice ?? `${effect}; current relationship access is unavailable, so no model continuation was run`);
|
|
342
|
+
await options.completeContinuation();
|
|
343
|
+
return { outcome: "terminal_notice", messages: materialized.messages };
|
|
344
|
+
}
|
|
345
|
+
const outward = { value: "" };
|
|
346
|
+
const callbacks = continuationCallbacks(options.callbacks, outward);
|
|
347
|
+
await options.markContinuationAttempted();
|
|
348
|
+
const result = await options.runAgent(materialized.messages, callbacks, options.channel, options.signal, currentOptions);
|
|
349
|
+
if (result.outcome === "suspended") {
|
|
350
|
+
await options.completeContinuation();
|
|
351
|
+
return { outcome: result.outcome, messages: materialized.messages, suspension: result.suspension };
|
|
352
|
+
}
|
|
353
|
+
await options.persist(materialized.messages, result);
|
|
354
|
+
if (outward.value)
|
|
355
|
+
await options.deliver(outward.value);
|
|
356
|
+
await options.completeContinuation();
|
|
357
|
+
(0, runtime_1.emitNervesEvent)({
|
|
358
|
+
component: "engine",
|
|
359
|
+
event: "engine.approval_continuation_completed",
|
|
360
|
+
message: "approval continuation completed through existing provider loop",
|
|
361
|
+
meta: { approvalId: options.record.approvalId, outcome: result.outcome },
|
|
362
|
+
});
|
|
363
|
+
return { outcome: result.outcome, messages: materialized.messages };
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Strip <think>...</think> blocks for the violation-detection check at the
|
|
367
|
+
* end of a streaming turn. Used to tell legitimate text-only responses
|
|
368
|
+
* apart from the MiniMax-M2.7 "only thinking, no tool call" violation
|
|
369
|
+
* shape. Mirrors the more thorough stripThinkBlocks helper in
|
|
370
|
+
* senses/shared-turn.ts (which is for operator-facing output) — kept
|
|
371
|
+
* inline here to avoid pulling senses/ into the core module's import graph.
|
|
372
|
+
*/
|
|
373
|
+
function stripThinkBlocksForViolationCheck(input) {
|
|
374
|
+
let out = input;
|
|
375
|
+
for (;;) {
|
|
376
|
+
const open = out.indexOf("<think>");
|
|
377
|
+
if (open === -1)
|
|
378
|
+
break;
|
|
379
|
+
const close = out.indexOf("</think>", open + "<think>".length);
|
|
380
|
+
if (close === -1) {
|
|
381
|
+
out = out.slice(0, open);
|
|
382
|
+
break;
|
|
383
|
+
}
|
|
384
|
+
out = out.slice(0, open) + out.slice(close + "</think>".length);
|
|
385
|
+
}
|
|
386
|
+
return out.trim();
|
|
387
|
+
}
|
|
388
|
+
function hasFreshPendingWork(options) {
|
|
389
|
+
const pendingMessages = options?.pendingMessages;
|
|
390
|
+
if (!Array.isArray(pendingMessages))
|
|
391
|
+
return false;
|
|
392
|
+
return pendingMessages.some((message) => typeof message?.content === "string"
|
|
393
|
+
&& message.content.trim().length > 0);
|
|
394
|
+
}
|
|
395
|
+
const HABIT_CONTROL_TOOLS = new Set(["rest", "ponder", "observe"]);
|
|
396
|
+
function highRiskExternalMutation(profile) {
|
|
397
|
+
if (profile.risk !== "high")
|
|
398
|
+
return null;
|
|
399
|
+
const mutates = typeof profile.mutates === "string" ? [profile.mutates] : [...profile.mutates];
|
|
400
|
+
return mutates.includes("external_side_effect") ? mutates.join(", ") : null;
|
|
401
|
+
}
|
|
402
|
+
function recordBlockedHabitSurfaceAttempts(habitSession, toolCalls, reason) {
|
|
403
|
+
if (toolCalls.some((call) => call.name !== "send_message" && call.name !== "surface")) {
|
|
404
|
+
habitSession?.recordError?.(`blocked habit tool batch: ${reason}`);
|
|
405
|
+
}
|
|
406
|
+
if (!habitSession?.recordSurfaceAttempt)
|
|
407
|
+
return;
|
|
408
|
+
for (const call of toolCalls) {
|
|
409
|
+
if (call.name !== "send_message" && call.name !== "surface")
|
|
410
|
+
continue;
|
|
411
|
+
// The canonical pre-batch schema gate guarantees object arguments here.
|
|
412
|
+
const args = JSON.parse(call.arguments);
|
|
413
|
+
habitSession.recordSurfaceAttempt({
|
|
414
|
+
recipient: String(args.friendId ?? args.delegationId ?? "unknown"),
|
|
415
|
+
channel: String(args.channel ?? call.name),
|
|
416
|
+
reason: "blocked",
|
|
417
|
+
result: "blocked",
|
|
418
|
+
rawStatus: "blocked",
|
|
419
|
+
error: reason,
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
async function habitToolBatchBlockReason(habitSession, toolCalls, delegatedOrigins, selection) {
|
|
424
|
+
if (!habitSession)
|
|
425
|
+
return null;
|
|
426
|
+
const granted = new Set(habitSession.toolPolicy.grantedTools);
|
|
427
|
+
const denied = new Set(habitSession.toolPolicy.deniedTools);
|
|
428
|
+
for (const call of toolCalls) {
|
|
429
|
+
if (denied.has(call.name))
|
|
430
|
+
return `habit tool '${call.name}' is denied by this habit session`;
|
|
431
|
+
if (HABIT_CONTROL_TOOLS.has(call.name))
|
|
432
|
+
continue;
|
|
433
|
+
if (!granted.has(call.name))
|
|
434
|
+
return `habit tool '${call.name}' was not granted to this habit session`;
|
|
435
|
+
// The canonical pre-batch schema gate guarantees object arguments here.
|
|
436
|
+
const args = JSON.parse(call.arguments);
|
|
437
|
+
const riskProfile = (0, tools_1.riskProfileForToolName)(call.name, args, selection);
|
|
438
|
+
if (!riskProfile)
|
|
439
|
+
return `habit tool '${call.name}' does not have a known executable risk profile`;
|
|
440
|
+
const externalMutation = highRiskExternalMutation(riskProfile);
|
|
441
|
+
if (externalMutation && call.name !== "send_message" && call.name !== "surface") {
|
|
442
|
+
return `habit tool '${call.name}' has high-risk executable mutation ${externalMutation}: ${riskProfile.reason}`;
|
|
443
|
+
}
|
|
444
|
+
if (call.name === "send_message" || call.name === "surface") {
|
|
445
|
+
const route = await (0, habit_session_1.resolveHabitReturnRoute)({
|
|
446
|
+
agentRoot: (0, identity_2.getAgentRoot)(),
|
|
447
|
+
envelope: habitSession.permissionEnvelope,
|
|
448
|
+
toolName: call.name,
|
|
449
|
+
args,
|
|
450
|
+
friendStore: habitSession.friendStore,
|
|
451
|
+
delegatedOrigins,
|
|
452
|
+
});
|
|
453
|
+
if (!route.allowed)
|
|
454
|
+
return route.reason;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
return null;
|
|
458
|
+
}
|
|
459
|
+
/** Channels that deliberately support mid-turn delivery expose `speak`.
|
|
460
|
+
* BlueBubbles is final-only: its adapter owns one accepted visibility boundary.
|
|
461
|
+
* The private runtime has `ponder`; MCP returns synchronously; mail is batch. */
|
|
462
|
+
function isChatStyleChannel(channel) {
|
|
463
|
+
return (0, friends_1.getChannelCapabilities)(channel).chatStyle;
|
|
464
|
+
}
|
|
465
|
+
function bindCurrentIngressEvidenceLocator(toolList, evidence) {
|
|
466
|
+
if (!evidence
|
|
467
|
+
|| evidence.schemaVersion !== 1
|
|
468
|
+
|| evidence.provider !== "bluebubbles"
|
|
469
|
+
|| !/^[a-f0-9]{64}$/.test(evidence.captureKeyHash))
|
|
470
|
+
return toolList;
|
|
471
|
+
const locator = `capture:${evidence.captureKeyHash}`;
|
|
472
|
+
return toolList.map((tool) => {
|
|
473
|
+
if (tool.function.name !== "habit_cancel")
|
|
474
|
+
return tool;
|
|
475
|
+
const parameters = tool.function.parameters;
|
|
476
|
+
const properties = parameters.properties;
|
|
477
|
+
return {
|
|
478
|
+
...tool,
|
|
479
|
+
function: {
|
|
480
|
+
...tool.function,
|
|
481
|
+
parameters: {
|
|
482
|
+
...parameters,
|
|
483
|
+
properties: {
|
|
484
|
+
...properties,
|
|
485
|
+
evidence: {
|
|
486
|
+
...properties.evidence,
|
|
487
|
+
enum: [locator],
|
|
488
|
+
},
|
|
489
|
+
},
|
|
490
|
+
},
|
|
491
|
+
},
|
|
492
|
+
};
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
// Sole-call tools must be the only tool call in a turn. When they appear
|
|
496
|
+
// alongside other tools, the sole-call tool is rejected with this message.
|
|
497
|
+
const SOLE_CALL_REJECTION = {
|
|
498
|
+
settle: "rejected: settle must be the only tool call. finish your work first, then call settle alone.",
|
|
499
|
+
observe: "rejected: observe must be the only tool call. call observe alone when you want to stay silent.",
|
|
500
|
+
rest: "rejected: rest must be the only tool call. finish your work first, then call rest alone.",
|
|
178
501
|
};
|
|
179
|
-
function
|
|
180
|
-
const
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
502
|
+
function parseSettlePayload(argumentsText) {
|
|
503
|
+
const parsed = JSON.parse(argumentsText);
|
|
504
|
+
// Provider finalization validates settle.answer as a string before this
|
|
505
|
+
// terminal handling path. Keep this parser focused on projection instead
|
|
506
|
+
// of carrying an unreachable second shape check.
|
|
507
|
+
const answer = parsed.answer;
|
|
508
|
+
const rawIntent = parsed.intent;
|
|
509
|
+
const intent = rawIntent === "complete" || rawIntent === "blocked" || rawIntent === "direct_reply"
|
|
510
|
+
? rawIntent
|
|
511
|
+
: undefined;
|
|
512
|
+
return { answer, intent };
|
|
513
|
+
}
|
|
514
|
+
function parsePonderPayload(argumentsText) {
|
|
515
|
+
// The canonical pre-batch schema gate guarantees a valid object payload.
|
|
516
|
+
return JSON.parse(argumentsText);
|
|
517
|
+
}
|
|
518
|
+
function parseSuccessCriteria(raw) {
|
|
519
|
+
if (typeof raw !== "string")
|
|
520
|
+
return null;
|
|
521
|
+
const criteria = raw
|
|
522
|
+
.split("\n")
|
|
523
|
+
.map((line) => line.replace(/^\s*[-*]\s*/, "").trim())
|
|
524
|
+
.filter((line) => line.length > 0);
|
|
525
|
+
return criteria.length > 0 ? criteria : null;
|
|
526
|
+
}
|
|
527
|
+
function parsePacketPayload(raw) {
|
|
528
|
+
if (typeof raw !== "string")
|
|
529
|
+
return null;
|
|
530
|
+
try {
|
|
531
|
+
const parsed = JSON.parse(raw);
|
|
532
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
|
533
|
+
? parsed
|
|
534
|
+
: null;
|
|
190
535
|
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
"",
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
"",
|
|
204
|
-
"
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
536
|
+
catch {
|
|
537
|
+
return null;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
function normalizeLegacyPonderArgs(parsed) {
|
|
541
|
+
if (typeof parsed.thought !== "string" || parsed.thought.trim().length === 0) {
|
|
542
|
+
return parsed;
|
|
543
|
+
}
|
|
544
|
+
return {
|
|
545
|
+
action: "create",
|
|
546
|
+
kind: "reflection",
|
|
547
|
+
objective: parsed.thought.trim(),
|
|
548
|
+
summary: typeof parsed.say === "string" ? parsed.say.trim() : "",
|
|
549
|
+
success_criteria: "- preserve the thread for later work",
|
|
550
|
+
payload_json: "{}",
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
function messageContentText(content) {
|
|
554
|
+
if (typeof content === "string")
|
|
555
|
+
return content;
|
|
556
|
+
if (!Array.isArray(content))
|
|
557
|
+
return "";
|
|
558
|
+
return content
|
|
559
|
+
.map((part) => {
|
|
560
|
+
if (typeof part === "string")
|
|
561
|
+
return part;
|
|
562
|
+
if (!part || typeof part !== "object")
|
|
563
|
+
return "";
|
|
564
|
+
const maybeText = part.text;
|
|
565
|
+
return typeof maybeText === "string" ? maybeText : "";
|
|
566
|
+
})
|
|
567
|
+
.filter(Boolean)
|
|
568
|
+
.join("\n");
|
|
569
|
+
}
|
|
570
|
+
function toolResultIndicatesFailure(content) {
|
|
571
|
+
const normalized = content.trim().toLowerCase();
|
|
572
|
+
return normalized.startsWith("error:")
|
|
573
|
+
|| normalized.startsWith("invalid tool arguments:")
|
|
574
|
+
|| normalized.startsWith("unknown:")
|
|
575
|
+
|| normalized.startsWith("relationship authorization required:")
|
|
576
|
+
|| normalized.startsWith("orientation hold:")
|
|
577
|
+
|| normalized.startsWith("commerce authority required:")
|
|
578
|
+
|| normalized.startsWith("blocked:")
|
|
579
|
+
|| normalized.startsWith("rejected:");
|
|
580
|
+
}
|
|
581
|
+
function requiredToolResultSucceeded(name, content, args, validate) {
|
|
582
|
+
if (toolResultIndicatesFailure(content))
|
|
583
|
+
return false;
|
|
584
|
+
return validate?.(name, content, args) ?? true;
|
|
585
|
+
}
|
|
586
|
+
function effectFingerprint(name, rawArguments, selection) {
|
|
587
|
+
let args;
|
|
212
588
|
try {
|
|
213
|
-
const parsed = JSON.parse(
|
|
214
|
-
if (typeof parsed
|
|
215
|
-
return
|
|
589
|
+
const parsed = JSON.parse(rawArguments);
|
|
590
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
591
|
+
return null;
|
|
592
|
+
args = { ...parsed };
|
|
593
|
+
}
|
|
594
|
+
catch {
|
|
595
|
+
return null;
|
|
596
|
+
}
|
|
597
|
+
const profile = (0, tools_1.riskProfileForToolName)(name, args, selection);
|
|
598
|
+
if (!profile || profile.mutates === "none")
|
|
599
|
+
return null;
|
|
600
|
+
delete args.expectedVersion;
|
|
601
|
+
return (0, tool_arguments_1.digestJson)({ name, args });
|
|
602
|
+
}
|
|
603
|
+
function historicalFailedEffectsForExactRepeatedRequest(messages, selection) {
|
|
604
|
+
const userRequests = [];
|
|
605
|
+
for (let index = 0; index < messages.length; index += 1) {
|
|
606
|
+
const message = messages[index];
|
|
607
|
+
if (message?.role !== "user")
|
|
608
|
+
continue;
|
|
609
|
+
const text = messageContentText(message.content).replace(/\s+/g, " ").trim();
|
|
610
|
+
if (!text)
|
|
611
|
+
continue;
|
|
612
|
+
userRequests.push({ index, text });
|
|
613
|
+
}
|
|
614
|
+
const current = userRequests.at(-1);
|
|
615
|
+
if (!current)
|
|
616
|
+
return [];
|
|
617
|
+
const prior = userRequests.slice(0, -1).find((request) => request.text === current.text);
|
|
618
|
+
if (!prior)
|
|
619
|
+
return [];
|
|
620
|
+
const effectsByCallId = new Map();
|
|
621
|
+
const failedEffects = new Map();
|
|
622
|
+
for (let index = prior.index + 1; index < current.index; index += 1) {
|
|
623
|
+
const message = messages[index];
|
|
624
|
+
if (message?.role === "assistant" && Array.isArray(message.tool_calls)) {
|
|
625
|
+
for (const call of message.tool_calls) {
|
|
626
|
+
if (call.type !== "function" || !call.id || !call.function.name)
|
|
627
|
+
continue;
|
|
628
|
+
const fingerprint = effectFingerprint(call.function.name, call.function.arguments, selection);
|
|
629
|
+
if (fingerprint)
|
|
630
|
+
effectsByCallId.set(call.id, { name: call.function.name, fingerprint });
|
|
631
|
+
}
|
|
632
|
+
continue;
|
|
633
|
+
}
|
|
634
|
+
if (message?.role !== "tool")
|
|
635
|
+
continue;
|
|
636
|
+
const content = messageContentText(message.content);
|
|
637
|
+
const effect = effectsByCallId.get(message.tool_call_id);
|
|
638
|
+
if (!effect)
|
|
639
|
+
continue;
|
|
640
|
+
if (toolResultIndicatesFailure(content)) {
|
|
641
|
+
failedEffects.set(effect.fingerprint, effect);
|
|
216
642
|
}
|
|
217
|
-
|
|
218
|
-
|
|
643
|
+
else {
|
|
644
|
+
failedEffects.delete(effect.fingerprint);
|
|
219
645
|
}
|
|
220
|
-
const answer = typeof parsed.answer === "string" ? parsed.answer : undefined;
|
|
221
|
-
const rawIntent = parsed.intent;
|
|
222
|
-
const intent = rawIntent === "complete" || rawIntent === "blocked" || rawIntent === "direct_reply"
|
|
223
|
-
? rawIntent
|
|
224
|
-
: undefined;
|
|
225
|
-
return { answer, intent };
|
|
226
646
|
}
|
|
227
|
-
|
|
228
|
-
|
|
647
|
+
return [...failedEffects.values()];
|
|
648
|
+
}
|
|
649
|
+
function latestUserMessageText(messages) {
|
|
650
|
+
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
|
651
|
+
const message = messages[i];
|
|
652
|
+
if (message?.role !== "user")
|
|
653
|
+
continue;
|
|
654
|
+
const text = messageContentText(message.content).trim();
|
|
655
|
+
if (text.length > 0)
|
|
656
|
+
return text;
|
|
229
657
|
}
|
|
658
|
+
return "";
|
|
230
659
|
}
|
|
231
|
-
function
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
660
|
+
function truncatePonderDelegatedContent(value) {
|
|
661
|
+
return value.length > 120 ? `${value.slice(0, 117)}...` : value;
|
|
662
|
+
}
|
|
663
|
+
function buildPonderDelegatedContent(input) {
|
|
664
|
+
const primary = (input.summary || input.objective).trim();
|
|
665
|
+
const sourceRequest = input.sourceRequest.trim();
|
|
666
|
+
if (!sourceRequest || sourceRequest === primary || sourceRequest === input.objective.trim()) {
|
|
667
|
+
return truncatePonderDelegatedContent(primary);
|
|
668
|
+
}
|
|
669
|
+
return truncatePonderDelegatedContent(`${primary}\nsource request: ${sourceRequest}`);
|
|
670
|
+
}
|
|
671
|
+
function looksLikePrivateReturnRequest(text) {
|
|
672
|
+
const normalized = text.toLowerCase();
|
|
673
|
+
return /\b(private|privately|private-attention|think|reflect|reflection)\b/.test(normalized)
|
|
674
|
+
&& /\b(return|bring back|come back|surface|report back)\b/.test(normalized);
|
|
675
|
+
}
|
|
676
|
+
function extractPrivateReturnHeldTokens(text) {
|
|
677
|
+
const tokens = new Set();
|
|
678
|
+
for (const match of text.matchAll(/\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+){2,}\b/g)) {
|
|
679
|
+
const token = match[0];
|
|
680
|
+
if (token.length >= 8)
|
|
681
|
+
tokens.add(token);
|
|
682
|
+
}
|
|
683
|
+
return [...tokens];
|
|
684
|
+
}
|
|
685
|
+
function privateReturnAckLeakError(answer, heldTokens) {
|
|
686
|
+
if (!answer || heldTokens.size === 0)
|
|
687
|
+
return null;
|
|
688
|
+
for (const token of heldTokens) {
|
|
689
|
+
if (answer.includes(token)) {
|
|
690
|
+
return "private return is queued; do not repeat private markers or requested private-return content in the outward acknowledgement. Say only that the private pass is queued and will return when ready.";
|
|
691
|
+
}
|
|
244
692
|
}
|
|
693
|
+
return null;
|
|
694
|
+
}
|
|
695
|
+
function claimsPrivateReturnQueued(answer) {
|
|
696
|
+
if (!answer)
|
|
697
|
+
return false;
|
|
698
|
+
const normalized = answer.toLowerCase();
|
|
699
|
+
return /\b(queued|queue|will return|return when|when .*complete|when .*completes|private pass|private runtime completes|inner dialog completes|later)\b/.test(normalized)
|
|
700
|
+
&& /\b(private|inner|return|queued|later)\b/.test(normalized);
|
|
701
|
+
}
|
|
702
|
+
function privateReturnMissingPonderError(input) {
|
|
703
|
+
if (input.sawPonder)
|
|
704
|
+
return null;
|
|
705
|
+
if (!looksLikePrivateReturnRequest(input.latestUserRequest))
|
|
706
|
+
return null;
|
|
707
|
+
if (!claimsPrivateReturnQueued(input.answer))
|
|
708
|
+
return null;
|
|
709
|
+
return "private-return acknowledgement claimed work was queued, but no ponder packet was created this turn. Call ponder(action=create, ...) first so the return has a packet, return obligation, and private-runtime wake; then settle with only a queued acknowledgement. If you cannot create the packet, ask a blocking clarification without saying it is queued.";
|
|
710
|
+
}
|
|
711
|
+
function activeReturnObligationId(agentName, obligationId) {
|
|
712
|
+
if (!obligationId)
|
|
713
|
+
return null;
|
|
714
|
+
const obligation = (0, obligations_1.readReturnObligation)(agentName, obligationId);
|
|
715
|
+
return obligation?.status === "queued" || obligation?.status === "running" ? obligationId : null;
|
|
716
|
+
}
|
|
717
|
+
function ponderReturnSessionId(packet) {
|
|
718
|
+
const origin = packet.origin;
|
|
719
|
+
if (!origin)
|
|
720
|
+
return "unknown/unknown/unknown";
|
|
721
|
+
return `${origin.friendId}/${origin.channel}/${origin.key}`;
|
|
722
|
+
}
|
|
723
|
+
function buildPonderReturnPrivateWakeOptions(input) {
|
|
724
|
+
const sessionId = ponderReturnSessionId(input.packet);
|
|
725
|
+
return {
|
|
726
|
+
reason: "ponder return obligation private attention",
|
|
727
|
+
triggerSource: "ponder-return-obligation",
|
|
728
|
+
budgetClass: "interactive",
|
|
729
|
+
idempotencyKey: `ponder-return:${input.agentName}:${input.returnObligationId}:${input.packet.id}:${sessionId}`,
|
|
730
|
+
originRefs: [
|
|
731
|
+
{ kind: "tool", id: "ponder" },
|
|
732
|
+
{ kind: "ponder-packet", id: input.packet.id },
|
|
733
|
+
{ kind: "return-obligation", id: input.returnObligationId },
|
|
734
|
+
{ kind: "session", id: sessionId },
|
|
735
|
+
],
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
function buildPonderResult(packet, action, returnObligationId) {
|
|
739
|
+
return JSON.stringify({
|
|
740
|
+
ok: true,
|
|
741
|
+
packet_id: packet.id,
|
|
742
|
+
action,
|
|
743
|
+
status: packet.status,
|
|
744
|
+
return_obligation_id: returnObligationId,
|
|
745
|
+
private_return_contract: returnObligationId
|
|
746
|
+
? "queued for private-runtime attention; do not present the requested private answer as complete in this same outward turn. if you answer now, only say the private pass is queued and will return when ready."
|
|
747
|
+
: null,
|
|
748
|
+
}, null, 2);
|
|
749
|
+
}
|
|
750
|
+
/** Returns true when a tool call queries external state (GitHub, npm registry). */
|
|
751
|
+
function isExternalStateQuery(toolName, args) {
|
|
752
|
+
if (toolName !== "shell")
|
|
753
|
+
return false;
|
|
754
|
+
const cmd = String(args.command ?? "");
|
|
755
|
+
return /\bgh\s+(pr|run|api|issue)\b/.test(cmd) || /\bnpm\s+(view|info|show)\b/.test(cmd);
|
|
756
|
+
}
|
|
757
|
+
function getSettleRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp, _delegationDecision, sawSendMessageSelf, sawPonder, _sawQuerySession, currentObligation, innerJob, _sawExternalStateQuery) {
|
|
758
|
+
// Delegation adherence removed: the delegation decision is surfaced in the
|
|
759
|
+
// system prompt as a suggestion. Hard-gating settle caused infinite
|
|
760
|
+
// rejection loops where the agent couldn't respond to the user at all.
|
|
761
|
+
// The agent is free to follow or ignore the delegation hint.
|
|
245
762
|
// 2. Pending obligation not addressed
|
|
246
|
-
if (innerJob?.obligationStatus === "pending" && !sawSendMessageSelf && !
|
|
247
|
-
return "you're still holding something from an earlier conversation -- someone is waiting for your answer. finish the thought first, or
|
|
763
|
+
if (innerJob?.obligationStatus === "pending" && !sawSendMessageSelf && !sawPonder) {
|
|
764
|
+
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.";
|
|
248
765
|
}
|
|
249
766
|
// 3. mustResolveBeforeHandoff + missing intent
|
|
250
767
|
if (mustResolveBeforeHandoff && !intent) {
|
|
251
|
-
return "your
|
|
768
|
+
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.";
|
|
252
769
|
}
|
|
253
770
|
// 4. mustResolveBeforeHandoff + direct_reply without follow-up
|
|
254
771
|
if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
|
|
255
|
-
return "your
|
|
772
|
+
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.";
|
|
773
|
+
}
|
|
774
|
+
// 5. mustResolveBeforeHandoff + complete while a live return loop is still active
|
|
775
|
+
if (mustResolveBeforeHandoff && intent === "complete" && currentObligation && !sawSteeringFollowUp) {
|
|
776
|
+
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.";
|
|
256
777
|
}
|
|
257
|
-
|
|
258
|
-
return "your final_answer was incomplete or malformed. call final_answer again with your complete response.";
|
|
778
|
+
return null;
|
|
259
779
|
}
|
|
260
|
-
|
|
261
|
-
var kicks_1 = require("./kicks");
|
|
262
|
-
Object.defineProperty(exports, "hasToolIntent", { enumerable: true, get: function () { return kicks_1.hasToolIntent; } });
|
|
263
|
-
function upsertSystemPrompt(messages, systemText) {
|
|
780
|
+
function upsertSystemPrompt(messages, systemText, protectedSystemMessages = []) {
|
|
264
781
|
const systemMessage = { role: "system", content: systemText };
|
|
265
|
-
|
|
782
|
+
const protectedMessages = new Set(protectedSystemMessages.filter((message) => message.role === "system"));
|
|
783
|
+
if (messages[0]?.role === "system" && !protectedMessages.has(messages[0])) {
|
|
266
784
|
messages[0] = systemMessage;
|
|
267
785
|
}
|
|
268
786
|
else {
|
|
269
787
|
messages.unshift(systemMessage);
|
|
270
788
|
}
|
|
271
789
|
}
|
|
790
|
+
/**
|
|
791
|
+
* A prompt refresh failure must not revive any generated text from an older
|
|
792
|
+
* turn or release. Even the nominally stable region contains actor-scoped trust,
|
|
793
|
+
* tool, and channel context, so it is not safe to reconstruct. Fail closed to a
|
|
794
|
+
* neutral base and put the freshly derived trigger first.
|
|
795
|
+
*/
|
|
796
|
+
function repairFallbackSystemPrompt(orientationFrame) {
|
|
797
|
+
return `${(0, orientation_frame_1.renderOrientationFrame)(orientationFrame)}\n\nYou are a helpful assistant.`;
|
|
798
|
+
}
|
|
272
799
|
// Remove orphan tool_calls from the last assistant message and any
|
|
273
800
|
// trailing tool-result messages that lack a matching tool_call.
|
|
274
801
|
// This keeps the conversation valid after an abort or tool-loop limit.
|
|
@@ -297,27 +824,39 @@ const TOOL_SCAN_BOUNDARY_ROLES = new Set(["assistant", "user"]);
|
|
|
297
824
|
// 1. If an assistant message has tool_calls but missing tool results, inject synthetic error results.
|
|
298
825
|
// 2. If a tool result's tool_call_id doesn't match any tool_calls in a preceding assistant message, remove it.
|
|
299
826
|
// This prevents 400 errors from the API after an aborted turn.
|
|
827
|
+
//
|
|
828
|
+
// Position-aware: a tool result is orphaned when its tool_call_id hasn't been
|
|
829
|
+
// defined by an assistant message AT THIS POSITION yet. MiniMax-M2.7 reuses
|
|
830
|
+
// canonical tool_call_ids across turns, so the global-set check that this
|
|
831
|
+
// function used previously kept misordered tool results that MiniMax then
|
|
832
|
+
// rejected with error 2013 ("tool result's tool id not found"). Walking
|
|
833
|
+
// in order matches what MiniMax actually enforces.
|
|
300
834
|
function repairOrphanedToolCalls(messages) {
|
|
301
|
-
// Pass 1:
|
|
302
|
-
|
|
303
|
-
|
|
835
|
+
// Pass 1: walk in order, accumulate seen tool_call_ids per-position, and
|
|
836
|
+
// mark tool results for removal if their id hasn't been defined yet.
|
|
837
|
+
const seenCallIds = new Set();
|
|
838
|
+
const removeIndices = [];
|
|
839
|
+
for (let i = 0; i < messages.length; i++) {
|
|
840
|
+
const msg = messages[i];
|
|
304
841
|
if (msg.role === "assistant") {
|
|
305
842
|
const asst = msg;
|
|
306
843
|
if (asst.tool_calls) {
|
|
307
844
|
for (const tc of asst.tool_calls)
|
|
308
|
-
|
|
845
|
+
seenCallIds.add(tc.id);
|
|
309
846
|
}
|
|
847
|
+
continue;
|
|
310
848
|
}
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
const toolMsg = messages[i];
|
|
316
|
-
if (!validCallIds.has(toolMsg.tool_call_id)) {
|
|
317
|
-
messages.splice(i, 1);
|
|
849
|
+
if (msg.role === "tool") {
|
|
850
|
+
const toolMsg = msg;
|
|
851
|
+
if (!seenCallIds.has(toolMsg.tool_call_id)) {
|
|
852
|
+
removeIndices.push(i);
|
|
318
853
|
}
|
|
319
854
|
}
|
|
320
855
|
}
|
|
856
|
+
// Splice from the end so earlier indices stay valid.
|
|
857
|
+
for (let i = removeIndices.length - 1; i >= 0; i--) {
|
|
858
|
+
messages.splice(removeIndices[i], 1);
|
|
859
|
+
}
|
|
321
860
|
// Pass 3: inject synthetic results for tool_calls missing their tool results
|
|
322
861
|
for (let i = 0; i < messages.length; i++) {
|
|
323
862
|
const msg = messages[i];
|
|
@@ -339,10 +878,13 @@ function repairOrphanedToolCalls(messages) {
|
|
|
339
878
|
}
|
|
340
879
|
const missing = asst.tool_calls.filter((tc) => !resultIds.has(tc.id));
|
|
341
880
|
if (missing.length > 0) {
|
|
881
|
+
// AX rule: the agent must see what happened. Don't say "interrupted"
|
|
882
|
+
// — that's vague. Tell them the result was lost, possible causes,
|
|
883
|
+
// and what to do next.
|
|
342
884
|
const syntheticResults = missing.map((tc) => ({
|
|
343
885
|
role: "tool",
|
|
344
886
|
tool_call_id: tc.id,
|
|
345
|
-
content: "error: tool call was
|
|
887
|
+
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.",
|
|
346
888
|
}));
|
|
347
889
|
let insertAt = i + 1;
|
|
348
890
|
while (insertAt < messages.length && messages[insertAt].role === "tool")
|
|
@@ -365,51 +907,83 @@ function isContextOverflow(err) {
|
|
|
365
907
|
return true;
|
|
366
908
|
return false;
|
|
367
909
|
}
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
910
|
+
const RETRY_LABELS = {
|
|
911
|
+
"auth-failure": "auth error",
|
|
912
|
+
"usage-limit": "usage limit",
|
|
913
|
+
"rate-limit": "rate limited",
|
|
914
|
+
"server-error": "server error",
|
|
915
|
+
"network-error": "network error",
|
|
916
|
+
"unknown": "error",
|
|
917
|
+
};
|
|
918
|
+
function waitForProviderRetry(delayMs, signal) {
|
|
919
|
+
if (!signal) {
|
|
920
|
+
return new Promise((resolve) => {
|
|
921
|
+
setTimeout(resolve, delayMs);
|
|
922
|
+
});
|
|
923
|
+
}
|
|
924
|
+
return new Promise((resolve, reject) => {
|
|
925
|
+
let timer;
|
|
926
|
+
const onAbort = () => {
|
|
927
|
+
clearTimeout(timer);
|
|
928
|
+
reject(new provider_attempt_1.ProviderAttemptAbortError());
|
|
929
|
+
};
|
|
930
|
+
timer = setTimeout(() => {
|
|
931
|
+
signal.removeEventListener("abort", onAbort);
|
|
932
|
+
resolve();
|
|
933
|
+
}, delayMs);
|
|
934
|
+
if (signal.aborted) {
|
|
935
|
+
onAbort();
|
|
936
|
+
return;
|
|
937
|
+
}
|
|
938
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
939
|
+
});
|
|
940
|
+
}
|
|
941
|
+
function buildAuthFailureGuidance(provider, model, agentName, detail) {
|
|
942
|
+
const mismatch = (0, provider_models_1.getProviderModelMismatchMessage)(provider, model);
|
|
943
|
+
const modelLabel = model
|
|
944
|
+
? mismatch
|
|
945
|
+
? `${provider} [configured model: ${model}]`
|
|
946
|
+
: `${provider} (${model})`
|
|
947
|
+
: provider;
|
|
948
|
+
const lines = [`${modelLabel} authentication failed.`];
|
|
949
|
+
const cleanDetail = detail.replace(/\s+/g, " ").trim();
|
|
950
|
+
if (cleanDetail)
|
|
951
|
+
lines.push(`provider detail: ${cleanDetail.length > 300 ? `${cleanDetail.slice(0, 297)}...` : cleanDetail}`);
|
|
952
|
+
lines.push("");
|
|
953
|
+
lines.push("To keep using this provider:");
|
|
954
|
+
lines.push(` 1. Run \`ouro auth --agent ${agentName} --provider ${provider}\``);
|
|
955
|
+
if (mismatch) {
|
|
956
|
+
const defaultModel = (0, provider_models_1.getDefaultModelForProvider)(provider);
|
|
957
|
+
lines.push("");
|
|
958
|
+
lines.push("Config warning:");
|
|
959
|
+
lines.push(` - ${mismatch}`);
|
|
960
|
+
lines.push(" - Repair the configured model with:");
|
|
961
|
+
lines.push(` \`ouro use --agent ${agentName} --lane outward --provider ${provider} --model ${defaultModel}\``);
|
|
962
|
+
lines.push(` \`ouro use --agent ${agentName} --lane inner --provider ${provider} --model ${defaultModel}\``);
|
|
963
|
+
}
|
|
964
|
+
lines.push("");
|
|
965
|
+
lines.push(`To use another configured provider instead, run \`ouro use --agent ${agentName} --lane <outward|inner> --provider <provider> --model <model>\`.`);
|
|
966
|
+
return lines.join("\n");
|
|
394
967
|
}
|
|
395
|
-
function classifyTransientError(err) {
|
|
396
|
-
if (!(err instanceof Error))
|
|
397
|
-
return "unknown error";
|
|
398
|
-
const status = err.status;
|
|
399
|
-
if (status === 429)
|
|
400
|
-
return "rate limited";
|
|
401
|
-
if (status === 401 || status === 403)
|
|
402
|
-
return "auth error";
|
|
403
|
-
if (status && status >= 500)
|
|
404
|
-
return "server error";
|
|
405
|
-
return "network error";
|
|
406
|
-
}
|
|
407
|
-
const MAX_RETRIES = 3;
|
|
408
|
-
const RETRY_BASE_MS = 2000;
|
|
409
968
|
async function runAgent(messages, callbacks, channel, signal, options) {
|
|
410
|
-
const
|
|
969
|
+
const generatedMessages = [];
|
|
970
|
+
let nextAttemptControls = [];
|
|
971
|
+
let rejectedAttempt = [];
|
|
972
|
+
const pushGenerated = (...next) => {
|
|
973
|
+
messages.push(...next);
|
|
974
|
+
generatedMessages.push(...structuredClone(next));
|
|
975
|
+
if (rejectedAttempt.length > 0) {
|
|
976
|
+
rejectedAttempt = [];
|
|
977
|
+
providerRuntime.resetTurnState(messages);
|
|
978
|
+
}
|
|
979
|
+
};
|
|
980
|
+
const facing = (0, friends_1.channelToFacing)(channel);
|
|
981
|
+
const owner = options?.toolContext?.agentName && options.toolContext.agentRoot
|
|
982
|
+
? { agentName: options.toolContext.agentName, agentRoot: options.toolContext.agentRoot }
|
|
983
|
+
: undefined;
|
|
984
|
+
let providerRuntime = options?.providerRuntimeOverride ?? await getProviderRuntime(facing, owner);
|
|
411
985
|
const provider = providerRuntime.id;
|
|
412
|
-
const toolChoiceRequired = options?.toolChoiceRequired ?? true;
|
|
986
|
+
const toolChoiceRequired = options?.hardDisableTools ? false : options?.toolChoiceRequired ?? true;
|
|
413
987
|
const traceId = options?.traceId;
|
|
414
988
|
(0, runtime_1.emitNervesEvent)({
|
|
415
989
|
event: "engine.turn_start",
|
|
@@ -428,24 +1002,88 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
428
1002
|
currentContext = { ...currentContext, friend: freshFriend };
|
|
429
1003
|
}
|
|
430
1004
|
}
|
|
1005
|
+
const turnOrientationFrame = options?.orientationFrame
|
|
1006
|
+
?? (channel ? (0, orientation_frame_1.buildOrientationFrame)({ channel, messages }) : undefined);
|
|
1007
|
+
if (options?.requiredPromptEvidence) {
|
|
1008
|
+
let structuralFloor;
|
|
1009
|
+
try {
|
|
1010
|
+
structuralFloor = (0, prompt_budget_1.assessRequiredPromptEvidenceBudget)({
|
|
1011
|
+
messages,
|
|
1012
|
+
requiredPromptEvidence: options.requiredPromptEvidence,
|
|
1013
|
+
provider: providerRuntime.id,
|
|
1014
|
+
model: providerRuntime.model,
|
|
1015
|
+
contextWindowTokens: (0, config_1.getContextConfig)().maxTokens,
|
|
1016
|
+
});
|
|
1017
|
+
}
|
|
1018
|
+
catch (error) {
|
|
1019
|
+
const invalidEvidenceError = error instanceof Error ? error : new Error(String(error));
|
|
1020
|
+
callbacks.onError(invalidEvidenceError, "terminal");
|
|
1021
|
+
options.captureGeneratedMessages?.([]);
|
|
1022
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1023
|
+
event: "engine.turn_end",
|
|
1024
|
+
trace_id: traceId,
|
|
1025
|
+
component: "engine",
|
|
1026
|
+
message: "runAgent turn completed",
|
|
1027
|
+
meta: { done: true, sawPonder: false, sawQuerySession: false, sawBridgeManage: false },
|
|
1028
|
+
});
|
|
1029
|
+
return {
|
|
1030
|
+
outcome: "errored",
|
|
1031
|
+
error: invalidEvidenceError,
|
|
1032
|
+
errorClassification: "unknown",
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
if (structuralFloor.status === "required_evidence_over_budget") {
|
|
1036
|
+
const budgetError = new Error(`required_evidence_over_budget: required current-turn evidence needs ${structuralFloor.estimatedTokens} tokens but the provider input limit is ${structuralFloor.budget.inputTokenLimit}`);
|
|
1037
|
+
callbacks.onError(budgetError, "terminal");
|
|
1038
|
+
options.captureGeneratedMessages?.([]);
|
|
1039
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1040
|
+
event: "engine.turn_end",
|
|
1041
|
+
trace_id: traceId,
|
|
1042
|
+
component: "engine",
|
|
1043
|
+
message: "runAgent turn completed",
|
|
1044
|
+
meta: { done: true, sawPonder: false, sawQuerySession: false, sawBridgeManage: false },
|
|
1045
|
+
});
|
|
1046
|
+
return {
|
|
1047
|
+
outcome: "errored",
|
|
1048
|
+
error: budgetError,
|
|
1049
|
+
errorClassification: "unknown",
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
431
1053
|
// Refresh system prompt at start of each turn when channel is provided.
|
|
432
|
-
// If refresh fails,
|
|
433
|
-
// so
|
|
1054
|
+
// If refresh fails, retain only a recognised stable prefix (or inject a
|
|
1055
|
+
// minimal safe fallback) so stale dynamic state cannot regain authority.
|
|
1056
|
+
let structuredSystemPrompt;
|
|
434
1057
|
if (channel) {
|
|
435
1058
|
try {
|
|
436
1059
|
const buildSystemOptions = {
|
|
437
1060
|
...options,
|
|
1061
|
+
relationshipContextScopes: options?.toolContext?.relationshipAuthorization?.authorizedContextScopes,
|
|
1062
|
+
relationshipProfileId: options?.toolContext?.relationshipAuthorization?.profileId,
|
|
1063
|
+
relationshipToolNames: options?.toolContext?.relationshipAuthorization?.advertisedToolNames,
|
|
1064
|
+
orientationFrame: turnOrientationFrame,
|
|
1065
|
+
resumePriorWork: options?.resumePriorWork === true,
|
|
438
1066
|
providerCapabilities: providerRuntime.capabilities,
|
|
439
1067
|
supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
|
|
440
1068
|
};
|
|
441
1069
|
const refreshed = await (0, prompt_1.buildSystem)(channel, buildSystemOptions, currentContext);
|
|
442
|
-
|
|
1070
|
+
structuredSystemPrompt = refreshed;
|
|
1071
|
+
upsertSystemPrompt(messages, (0, prompt_1.flattenSystemPrompt)(refreshed), [
|
|
1072
|
+
...(options?.promptOnlyEvidenceMessages ?? []),
|
|
1073
|
+
...(options?.requiredPromptEvidence?.verifiedPredecessorMessage
|
|
1074
|
+
? [options.requiredPromptEvidence.verifiedPredecessorMessage]
|
|
1075
|
+
: []),
|
|
1076
|
+
]);
|
|
443
1077
|
}
|
|
444
1078
|
catch (error) {
|
|
445
1079
|
const hadExistingSystemPrompt = messages[0]?.role === "system" && typeof messages[0].content === "string";
|
|
446
|
-
const
|
|
447
|
-
|
|
448
|
-
|
|
1080
|
+
const fallback = repairFallbackSystemPrompt(turnOrientationFrame);
|
|
1081
|
+
upsertSystemPrompt(messages, fallback, [
|
|
1082
|
+
...(options?.promptOnlyEvidenceMessages ?? []),
|
|
1083
|
+
...(options?.requiredPromptEvidence?.verifiedPredecessorMessage
|
|
1084
|
+
? [options.requiredPromptEvidence.verifiedPredecessorMessage]
|
|
1085
|
+
: []),
|
|
1086
|
+
]);
|
|
449
1087
|
(0, runtime_1.emitNervesEvent)({
|
|
450
1088
|
level: "warn",
|
|
451
1089
|
event: "mind.step_error",
|
|
@@ -460,424 +1098,1374 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
460
1098
|
});
|
|
461
1099
|
}
|
|
462
1100
|
}
|
|
463
|
-
|
|
1101
|
+
if (channel && options?.skipKeptNotes !== true) {
|
|
1102
|
+
await (0, kept_notes_1.injectKeptNotes)(messages, {
|
|
1103
|
+
channel,
|
|
1104
|
+
friend: currentContext?.friend,
|
|
1105
|
+
judge: async (input) => (0, kept_notes_1.createKeptNotesJudge)(await getProviderRuntime("agent", owner), signal)(input),
|
|
1106
|
+
signal,
|
|
1107
|
+
traceId,
|
|
1108
|
+
});
|
|
1109
|
+
}
|
|
464
1110
|
let done = false;
|
|
465
1111
|
let lastUsage;
|
|
466
1112
|
let overflowRetried = false;
|
|
467
|
-
let
|
|
468
|
-
let outcome = "complete";
|
|
1113
|
+
let outcome = "settled";
|
|
469
1114
|
let completion;
|
|
1115
|
+
let suspension;
|
|
1116
|
+
let terminalError;
|
|
1117
|
+
let terminalErrorClassification;
|
|
470
1118
|
let sawSteeringFollowUp = false;
|
|
471
1119
|
let mustResolveBeforeHandoffActive = options?.mustResolveBeforeHandoff === true;
|
|
472
1120
|
let currentReasoningEffort = "medium";
|
|
473
1121
|
let sawSendMessageSelf = false;
|
|
474
|
-
let
|
|
1122
|
+
let sawPonder = false;
|
|
475
1123
|
let sawQuerySession = false;
|
|
476
1124
|
let sawBridgeManage = false;
|
|
1125
|
+
let sawExternalStateQuery = false;
|
|
1126
|
+
const privateReturnHeldTokens = new Set();
|
|
1127
|
+
// Once-per-turn flag for the fresh-work rest gate. Without this, an agent
|
|
1128
|
+
// that called rest, was told "fresh work arrived", processed the items,
|
|
1129
|
+
// and called rest again would get the same message forever — the gate
|
|
1130
|
+
// condition is read from the turn-start snapshot of pendingMessages,
|
|
1131
|
+
// which doesn't update mid-turn. The agent only needs to be told once;
|
|
1132
|
+
// after that, repeated rest attempts mean they've acknowledged.
|
|
1133
|
+
let freshWorkGateFired = false;
|
|
1134
|
+
// Counter for no-tool-call violations. MiniMax reasoning models occasionally
|
|
1135
|
+
// emit only a <think>...</think> block and stop, without any tool call — even
|
|
1136
|
+
// when tool_choice is set to "required". Private-return requests also need
|
|
1137
|
+
// a hard no-tool guard: a text-only "queued" acknowledgement is false unless
|
|
1138
|
+
// a ponder packet created the return obligation in this turn.
|
|
1139
|
+
let noToolCallRetries = 0;
|
|
1140
|
+
const NO_TOOL_CALL_MAX_RETRIES = 2;
|
|
1141
|
+
let unresolvedHistoricalEffects = [];
|
|
1142
|
+
let historicalToolFailureRetries = 0;
|
|
1143
|
+
let providerIterations = 0;
|
|
1144
|
+
const requiredToolCallNames = [...new Set(options?.requiredToolCalls?.names ?? [])];
|
|
1145
|
+
const dispatchedRequiredToolCalls = new Set();
|
|
1146
|
+
const rejectAttempt = (assistant, controls) => {
|
|
1147
|
+
rejectedAttempt = [structuredClone(assistant)];
|
|
1148
|
+
nextAttemptControls = controls;
|
|
1149
|
+
};
|
|
1150
|
+
const rejectToolBatch = (assistant, reasons) => {
|
|
1151
|
+
rejectAttempt(assistant, assistant.tool_calls.map((call, index) => ({
|
|
1152
|
+
role: "tool", tool_call_id: call.id, content: reasons[index],
|
|
1153
|
+
})));
|
|
1154
|
+
};
|
|
1155
|
+
const pendingRequiredToolCalls = () => {
|
|
1156
|
+
const missing = requiredToolCallNames.filter((name) => !dispatchedRequiredToolCalls.has(name));
|
|
1157
|
+
return missing.length > 0
|
|
1158
|
+
? { missing, message: `${options.requiredToolCalls.retryMessage} Missing required tool calls: ${missing.join(", ")}.` }
|
|
1159
|
+
: null;
|
|
1160
|
+
};
|
|
1161
|
+
const queueRequiredCorrection = (assistant, message, limitContext) => {
|
|
1162
|
+
if (providerIterations >= exports.MAX_PROVIDER_ITERATIONS)
|
|
1163
|
+
throw new Error(`provider iteration limit exhausted at response ${exports.MAX_PROVIDER_ITERATIONS} ${limitContext}`);
|
|
1164
|
+
rejectAttempt(assistant, [{ role: "user", content: message }]);
|
|
1165
|
+
};
|
|
1166
|
+
const toolLoopState = (0, tool_loop_1.createToolLoopState)();
|
|
1167
|
+
const toolFrictionLedger = (0, tool_friction_1.createToolFrictionLedger)();
|
|
1168
|
+
const finishTerminalProviderError = (error, classification) => {
|
|
1169
|
+
terminalError = error;
|
|
1170
|
+
terminalErrorClassification = classification;
|
|
1171
|
+
/* v8 ignore start — auth-failure guidance: tested via provider error classification tests @preserve */
|
|
1172
|
+
if (terminalErrorClassification === "auth-failure") {
|
|
1173
|
+
const agentName = (0, identity_2.getAgentName)();
|
|
1174
|
+
const currentProvider = providerRuntime.id;
|
|
1175
|
+
callbacks.onError(new Error(buildAuthFailureGuidance(currentProvider, providerRuntime.model, agentName, terminalError.message)), "terminal");
|
|
1176
|
+
}
|
|
1177
|
+
else {
|
|
1178
|
+
callbacks.onError(terminalError, "terminal");
|
|
1179
|
+
}
|
|
1180
|
+
/* v8 ignore stop */
|
|
1181
|
+
const errorDetails = (0, error_classification_1.extractProviderErrorDetails)(terminalError);
|
|
1182
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1183
|
+
level: "error",
|
|
1184
|
+
event: "engine.error",
|
|
1185
|
+
trace_id: traceId,
|
|
1186
|
+
component: "engine",
|
|
1187
|
+
message: terminalError.message,
|
|
1188
|
+
meta: {
|
|
1189
|
+
provider: providerRuntime.id,
|
|
1190
|
+
model: providerRuntime.model,
|
|
1191
|
+
errorClassification: terminalErrorClassification,
|
|
1192
|
+
...(errorDetails.status !== undefined ? { httpStatus: errorDetails.status } : {}),
|
|
1193
|
+
...(errorDetails.bodyExcerpt ? { bodyExcerpt: errorDetails.bodyExcerpt } : {}),
|
|
1194
|
+
summary: (0, error_classification_1.summarizeProviderError)(terminalError, terminalErrorClassification, providerRuntime.id, providerRuntime.model),
|
|
1195
|
+
},
|
|
1196
|
+
});
|
|
1197
|
+
// Only legacy input can still contain unaccepted calls. Generated output
|
|
1198
|
+
// has crossed acceptance; a later provider failure cannot revoke effects.
|
|
1199
|
+
if (generatedMessages.length === 0)
|
|
1200
|
+
stripLastToolCalls(messages);
|
|
1201
|
+
outcome = "errored";
|
|
1202
|
+
done = true;
|
|
1203
|
+
};
|
|
477
1204
|
// Prevent MaxListenersExceeded warning — each iteration adds a listener
|
|
478
1205
|
try {
|
|
479
1206
|
require("events").setMaxListeners(50, signal);
|
|
480
1207
|
}
|
|
481
1208
|
catch { /* unsupported */ }
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
: baseTools;
|
|
503
|
-
const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
|
|
504
|
-
if (steeringFollowUps.length > 0) {
|
|
505
|
-
const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
|
|
506
|
-
if (hasSupersedingFollowUp) {
|
|
507
|
-
mustResolveBeforeHandoffActive = false;
|
|
508
|
-
options?.setMustResolveBeforeHandoff?.(false);
|
|
509
|
-
outcome = "superseded";
|
|
510
|
-
break;
|
|
511
|
-
}
|
|
512
|
-
if (steeringFollowUps.some((followUp) => followUp.effect === "set_no_handoff")) {
|
|
513
|
-
mustResolveBeforeHandoffActive = true;
|
|
514
|
-
options?.setMustResolveBeforeHandoff?.(true);
|
|
515
|
-
}
|
|
516
|
-
sawSteeringFollowUp = true;
|
|
517
|
-
for (const followUp of steeringFollowUps) {
|
|
518
|
-
messages.push({ role: "user", content: followUp.text });
|
|
519
|
-
}
|
|
520
|
-
providerRuntime.resetTurnState(messages);
|
|
521
|
-
}
|
|
522
|
-
// Yield so pending I/O (stdin Ctrl-C) can be processed between iterations
|
|
523
|
-
await new Promise((r) => setImmediate(r));
|
|
524
|
-
if (signal?.aborted) {
|
|
525
|
-
outcome = "aborted";
|
|
526
|
-
break;
|
|
527
|
-
}
|
|
528
|
-
try {
|
|
529
|
-
callbacks.onModelStart();
|
|
530
|
-
const result = await providerRuntime.streamTurn({
|
|
531
|
-
messages,
|
|
532
|
-
activeTools,
|
|
533
|
-
callbacks,
|
|
534
|
-
signal,
|
|
535
|
-
traceId,
|
|
536
|
-
toolChoiceRequired,
|
|
537
|
-
reasoningEffort: currentReasoningEffort,
|
|
1209
|
+
try {
|
|
1210
|
+
const toolPreferences = currentContext?.friend?.toolPreferences;
|
|
1211
|
+
const filterTrustedTools = (tools, selected) => tools.filter((tool) => !selected.engine.some((engine) => engine.function.name === tool.function.name)
|
|
1212
|
+
&& (channel !== "inner" || options?.toolProfile === "sanctuary-health-private" || !["send_message", "surface"].includes(tool.function.name)
|
|
1213
|
+
|| selected.ordinary.some((definition) => definition.tool.function.name === tool.function.name)));
|
|
1214
|
+
const selectCurrentTools = () => {
|
|
1215
|
+
if (options?.hardDisableTools)
|
|
1216
|
+
return Object.freeze({ ordinary: Object.freeze([]), engine: Object.freeze([]) });
|
|
1217
|
+
const selected = (0, tools_1.selectToolsForChannel)(channel ? (0, friends_1.getChannelCapabilities)(channel) : undefined, toolPreferences, currentContext, providerRuntime.capabilities, options?.mcpManager, providerRuntime.model, { ...options?.toolContext, ...(options?.habitSession ? { habitSession: options.habitSession } : {}) });
|
|
1218
|
+
const ordinary = options?.tools !== undefined && !options.toolContext?.relationshipAuthorization
|
|
1219
|
+
? filterTrustedTools(options.tools, selected).flatMap((tool) => {
|
|
1220
|
+
const definition = (0, tools_1.resolveToolDefinition)(tool.function.name, selected) ?? (0, tools_1.resolveToolDefinition)(tool.function.name);
|
|
1221
|
+
return definition ? [{ ...definition, tool }] : [];
|
|
1222
|
+
})
|
|
1223
|
+
: selected.ordinary;
|
|
1224
|
+
const bound = bindCurrentIngressEvidenceLocator(ordinary.map((definition) => definition.tool), options?.toolContext?.currentIngressEvidence);
|
|
1225
|
+
return Object.freeze({
|
|
1226
|
+
ordinary: Object.freeze(ordinary.map((definition, index) => definition.tool === bound[index]
|
|
1227
|
+
? definition : Object.freeze({ ...definition, tool: bound[index] }))),
|
|
1228
|
+
engine: selected.engine,
|
|
538
1229
|
});
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
role: "assistant",
|
|
546
|
-
};
|
|
547
|
-
if (result.content)
|
|
548
|
-
msg.content = result.content;
|
|
549
|
-
if (result.toolCalls.length)
|
|
550
|
-
msg.tool_calls = result.toolCalls.map((tc) => ({
|
|
551
|
-
id: tc.id,
|
|
552
|
-
type: "function",
|
|
553
|
-
function: { name: tc.name, arguments: tc.arguments },
|
|
554
|
-
}));
|
|
555
|
-
// Store reasoning items from the API response on the assistant message
|
|
556
|
-
// so they persist through session save/load and can be restored in toResponsesInput
|
|
557
|
-
const reasoningItems = result.outputItems.filter((item) => "type" in item && item.type === "reasoning");
|
|
558
|
-
if (reasoningItems.length > 0) {
|
|
559
|
-
msg._reasoning_items = reasoningItems;
|
|
1230
|
+
};
|
|
1231
|
+
let toolSelection = selectCurrentTools();
|
|
1232
|
+
const relationship = options?.toolContext?.relationshipAuthorization;
|
|
1233
|
+
if (!options?.hardDisableTools && options?.tools !== undefined) {
|
|
1234
|
+
if (relationship) {
|
|
1235
|
+
toolSelection = (0, tools_1.reduceToolSelection)(toolSelection, options.tools);
|
|
560
1236
|
}
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
1237
|
+
}
|
|
1238
|
+
const unboundBaseTools = !options?.hardDisableTools && !relationship && options?.tools
|
|
1239
|
+
? filterTrustedTools(options.tools, toolSelection)
|
|
1240
|
+
: toolSelection.ordinary.map((definition) => definition.tool);
|
|
1241
|
+
const relationshipToolNames = options?.toolContext?.relationshipAuthorization?.advertisedToolNames;
|
|
1242
|
+
const relationshipScopedTools = relationshipToolNames
|
|
1243
|
+
? unboundBaseTools.filter((tool) => relationshipToolNames.includes(tool.function.name))
|
|
1244
|
+
: unboundBaseTools;
|
|
1245
|
+
const baseTools = bindCurrentIngressEvidenceLocator(relationshipScopedTools, options?.toolContext?.currentIngressEvidence);
|
|
1246
|
+
// Augment tool context with reasoning effort controls from provider
|
|
1247
|
+
const baseToolContext = options?.toolContext
|
|
1248
|
+
?? { signin: async () => undefined, ...(turnOrientationFrame ? { orientationFrame: turnOrientationFrame } : {}) };
|
|
1249
|
+
const habitSession = options?.habitSession ?? baseToolContext?.habitSession;
|
|
1250
|
+
const augmentedToolContext = {
|
|
1251
|
+
...baseToolContext,
|
|
1252
|
+
supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
|
|
1253
|
+
setReasoningEffort: (level) => { currentReasoningEffort = level; },
|
|
1254
|
+
activeWorkFrame: options?.activeWorkFrame,
|
|
1255
|
+
orientationFrame: turnOrientationFrame ?? baseToolContext.orientationFrame,
|
|
1256
|
+
...(habitSession ? { habitSession } : {}),
|
|
1257
|
+
toolSelection,
|
|
1258
|
+
selectCurrentTools,
|
|
1259
|
+
};
|
|
1260
|
+
const trustedToolContext = options?.toolContext || turnOrientationFrame || habitSession ? augmentedToolContext : undefined;
|
|
1261
|
+
unresolvedHistoricalEffects = historicalFailedEffectsForExactRepeatedRequest(messages, toolSelection);
|
|
1262
|
+
// Rebase provider-owned turn state from canonical messages at user-turn start.
|
|
1263
|
+
// This prevents stale provider caches from replaying prior-turn context.
|
|
1264
|
+
providerRuntime.resetTurnState(messages);
|
|
1265
|
+
while (!done) {
|
|
1266
|
+
// Channel-based tool filtering:
|
|
1267
|
+
// - Private runtime: exclude send_message (delivery via surface), observe (no one to observe)
|
|
1268
|
+
// - All outward channels (1:1, group, reaction): observe available
|
|
1269
|
+
//
|
|
1270
|
+
// ponder, settle/rest, surface, and observe are always assembled based on channel context.
|
|
1271
|
+
// ponder is available in ALL channels (outer: think privately, inner: keep turning).
|
|
1272
|
+
// Private runtime gets restTool instead of settleTool (rest = end turn, gated by attention queue).
|
|
1273
|
+
// toolChoiceRequired only controls whether tool_choice: "required" is set in the API call.
|
|
1274
|
+
const isPrivateRuntimeChannel = channel === "inner";
|
|
1275
|
+
const unscopedOrdinaryActiveTools = [
|
|
1276
|
+
...baseTools,
|
|
1277
|
+
...toolSelection.engine,
|
|
1278
|
+
];
|
|
1279
|
+
const ordinaryActiveTools = relationshipToolNames
|
|
1280
|
+
? unscopedOrdinaryActiveTools.filter((tool) => relationshipToolNames.includes(tool.function.name))
|
|
1281
|
+
: unscopedOrdinaryActiveTools;
|
|
1282
|
+
const candidateActiveTools = options?.hardDisableTools
|
|
1283
|
+
? []
|
|
1284
|
+
: options?.toolProfile === "sanctuary-health-private"
|
|
1285
|
+
? (() => {
|
|
1286
|
+
const sendTools = baseTools.filter((tool) => tool.function.name === "send_message");
|
|
1287
|
+
if (channel !== "inner" || sendTools.length !== 1 || baseTools.length !== 1) {
|
|
1288
|
+
throw new Error("sanctuary-health-private requires inner channel with exactly one canonical send_message definition");
|
|
1289
|
+
}
|
|
1290
|
+
return [sendTools[0], tools_1.restTool];
|
|
1291
|
+
})()
|
|
1292
|
+
: ordinaryActiveTools;
|
|
1293
|
+
const candidateToolNames = new Set(candidateActiveTools.map((tool) => tool.function.name));
|
|
1294
|
+
const unadvertisedRequiredTool = requiredToolCallNames.find((name) => !candidateToolNames.has(name));
|
|
1295
|
+
if (unadvertisedRequiredTool) {
|
|
1296
|
+
(0, runtime_1.emitNervesEvent)({ level: "error", component: "engine", event: "engine.required_tool_unadvertised", message: "required tool is not advertised for the active channel", meta: { toolName: unadvertisedRequiredTool, channel: String(channel) } });
|
|
1297
|
+
throw new Error(`required tool is not advertised for this channel: ${unadvertisedRequiredTool}`);
|
|
565
1298
|
}
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
1299
|
+
const forcedHistoricalToolNames = new Set(unresolvedHistoricalEffects
|
|
1300
|
+
.map((effect) => effect.name)
|
|
1301
|
+
.filter((name) => candidateToolNames.has(name)));
|
|
1302
|
+
const forcingHistoricalEffect = forcedHistoricalToolNames.size > 0;
|
|
1303
|
+
const activeTools = forcingHistoricalEffect
|
|
1304
|
+
? candidateActiveTools.filter((tool) => forcedHistoricalToolNames.has(tool.function.name))
|
|
1305
|
+
: candidateActiveTools;
|
|
1306
|
+
const activeToolNames = new Set(activeTools.map((tool) => tool.function.name));
|
|
1307
|
+
const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
|
|
1308
|
+
if (steeringFollowUps.length > 0) {
|
|
1309
|
+
const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
|
|
1310
|
+
if (hasSupersedingFollowUp) {
|
|
1311
|
+
mustResolveBeforeHandoffActive = false;
|
|
1312
|
+
options?.setMustResolveBeforeHandoff?.(false);
|
|
1313
|
+
outcome = "superseded";
|
|
1314
|
+
break;
|
|
1315
|
+
}
|
|
1316
|
+
if (steeringFollowUps.some((followUp) => followUp.effect === "set_no_handoff")) {
|
|
1317
|
+
mustResolveBeforeHandoffActive = true;
|
|
1318
|
+
options?.setMustResolveBeforeHandoff?.(true);
|
|
1319
|
+
}
|
|
1320
|
+
sawSteeringFollowUp = true;
|
|
1321
|
+
for (const followUp of steeringFollowUps) {
|
|
1322
|
+
messages.push({ role: "user", content: followUp.text });
|
|
1323
|
+
}
|
|
1324
|
+
providerRuntime.resetTurnState(messages);
|
|
571
1325
|
}
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
done = true;
|
|
1326
|
+
// Yield so pending I/O (stdin Ctrl-C) can be processed between iterations
|
|
1327
|
+
await new Promise((r) => setImmediate(r));
|
|
1328
|
+
if (signal?.aborted) {
|
|
1329
|
+
outcome = "aborted";
|
|
1330
|
+
break;
|
|
578
1331
|
}
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
1332
|
+
try {
|
|
1333
|
+
const budgetOptions = {
|
|
1334
|
+
requiredPromptEvidence: options?.requiredPromptEvidence,
|
|
1335
|
+
provider: providerRuntime.id,
|
|
1336
|
+
model: providerRuntime.model,
|
|
1337
|
+
contextWindowTokens: (0, config_1.getContextConfig)().maxTokens,
|
|
1338
|
+
};
|
|
1339
|
+
const canonicalBudget = (0, prompt_budget_1.applyPromptBudget)({ ...budgetOptions, messages });
|
|
1340
|
+
const currentUserMessage = budgetOptions.requiredPromptEvidence?.currentUserMessage
|
|
1341
|
+
?? canonicalBudget.messages.findLast((message) => message.role === "user");
|
|
1342
|
+
// Keep retry controls attached to the genuine request, not to canonical history.
|
|
1343
|
+
let attemptMessages = rejectedAttempt.length > 0
|
|
1344
|
+
? [...(0, prompt_budget_1.applyPromptBudget)({
|
|
1345
|
+
...budgetOptions,
|
|
1346
|
+
requiredPromptEvidence: budgetOptions.requiredPromptEvidence ?? (currentUserMessage ? { currentUserMessage } : undefined),
|
|
1347
|
+
messages: [...canonicalBudget.messages, ...rejectedAttempt, ...nextAttemptControls],
|
|
1348
|
+
}).messages]
|
|
1349
|
+
: [...canonicalBudget.messages];
|
|
1350
|
+
if (rejectedAttempt.length > 0 || canonicalBudget.status !== "within_budget")
|
|
1351
|
+
providerRuntime.resetTurnState(attemptMessages);
|
|
1352
|
+
const turnCallbackBufferRef = { current: null };
|
|
1353
|
+
const callProviderTurn = async () => {
|
|
1354
|
+
callbacks.onModelStart();
|
|
1355
|
+
turnCallbackBufferRef.current = habitSession
|
|
1356
|
+
? createHabitCallbackBuffer(callbacks)
|
|
1357
|
+
: callbacks.settleOutputMode === "final_only" || relationship !== undefined
|
|
1358
|
+
? createFinalOnlyTextBuffer(callbacks)
|
|
1359
|
+
: null;
|
|
1360
|
+
try {
|
|
1361
|
+
return await providerRuntime.streamTurn({
|
|
1362
|
+
messages: attemptMessages,
|
|
1363
|
+
activeTools,
|
|
1364
|
+
callbacks: turnCallbackBufferRef.current?.callbacks ?? callbacks,
|
|
1365
|
+
signal,
|
|
1366
|
+
traceId,
|
|
1367
|
+
toolChoiceRequired: options?.hardDisableTools ? false : forcingHistoricalEffect || toolChoiceRequired,
|
|
1368
|
+
reasoningEffort: currentReasoningEffort,
|
|
1369
|
+
eagerSettleStreaming: true,
|
|
1370
|
+
systemPrompt: structuredSystemPrompt,
|
|
1371
|
+
});
|
|
1372
|
+
}
|
|
1373
|
+
catch (error) {
|
|
1374
|
+
turnCallbackBufferRef.current?.discard();
|
|
1375
|
+
turnCallbackBufferRef.current = null;
|
|
1376
|
+
if (signal?.aborted)
|
|
1377
|
+
throw new provider_attempt_1.ProviderAttemptAbortError();
|
|
1378
|
+
throw error;
|
|
1379
|
+
}
|
|
1380
|
+
};
|
|
1381
|
+
const callProviderTurnWithOverflowRecovery = async () => {
|
|
1382
|
+
try {
|
|
1383
|
+
return await callProviderTurn();
|
|
1384
|
+
}
|
|
1385
|
+
catch (error) {
|
|
1386
|
+
if (error instanceof provider_attempt_1.ProviderAttemptAbortError)
|
|
1387
|
+
throw error;
|
|
1388
|
+
if (isContextOverflow(error) && !overflowRetried) {
|
|
1389
|
+
overflowRetried = true;
|
|
1390
|
+
const protectedStart = currentUserMessage ? Math.max(0, attemptMessages.indexOf(currentUserMessage)) : 0;
|
|
1391
|
+
const currentAttempt = attemptMessages.slice(protectedStart);
|
|
1392
|
+
const overflowMessages = attemptMessages.slice(0, protectedStart).map((message) => message.role === "assistant" ? { ...message } : message);
|
|
1393
|
+
stripLastToolCalls(overflowMessages);
|
|
1394
|
+
overflowMessages.push(...currentAttempt);
|
|
1395
|
+
const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
|
|
1396
|
+
const trimmed = (0, context_1.trimMessages)(overflowMessages, maxTokens, contextMargin, maxTokens * 2);
|
|
1397
|
+
const requiredEvidence = options?.requiredPromptEvidence;
|
|
1398
|
+
const requiredMessages = new Set([
|
|
1399
|
+
...(requiredEvidence?.verifiedPredecessorMessage ? [requiredEvidence.verifiedPredecessorMessage] : []),
|
|
1400
|
+
...currentAttempt,
|
|
1401
|
+
]);
|
|
1402
|
+
const trimmedMessages = new Set(trimmed);
|
|
1403
|
+
attemptMessages = requiredMessages.size === 0
|
|
1404
|
+
? trimmed
|
|
1405
|
+
: overflowMessages.filter((message) => trimmedMessages.has(message) || requiredMessages.has(message));
|
|
1406
|
+
providerRuntime.resetTurnState(attemptMessages);
|
|
1407
|
+
callbacks.onError(new Error("context trimmed, retrying..."), "transient");
|
|
1408
|
+
return callProviderTurn();
|
|
598
1409
|
}
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
1410
|
+
throw error;
|
|
1411
|
+
}
|
|
1412
|
+
};
|
|
1413
|
+
const attempt = await (0, provider_attempt_1.runProviderAttempt)({
|
|
1414
|
+
operation: "turn",
|
|
1415
|
+
provider: providerRuntime.id,
|
|
1416
|
+
model: providerRuntime.model,
|
|
1417
|
+
run: callProviderTurnWithOverflowRecovery,
|
|
1418
|
+
classifyError: (error) => providerRuntime.classifyError(error),
|
|
1419
|
+
onRetry: async (record, maxAttempts) => {
|
|
1420
|
+
const delayMs = record.delayMs;
|
|
1421
|
+
const seconds = delayMs / 1000;
|
|
1422
|
+
const cause = RETRY_LABELS[record.classification];
|
|
1423
|
+
try {
|
|
1424
|
+
const agentName = owner?.agentName ?? (0, identity_2.getAgentName)();
|
|
1425
|
+
if (record.provider === "openai-codex" && record.classification === "auth-failure") {
|
|
1426
|
+
await (0, openai_codex_token_1.refreshOpenAICodexProviderCredentials)(agentName, {
|
|
1427
|
+
force: true,
|
|
1428
|
+
reason: "turn-auth-failure",
|
|
1429
|
+
});
|
|
1430
|
+
}
|
|
1431
|
+
await (0, provider_credentials_1.refreshProviderCredentialPool)(agentName, {
|
|
1432
|
+
preserveCachedOnFailure: true,
|
|
1433
|
+
providers: [record.provider],
|
|
1434
|
+
});
|
|
1435
|
+
_providerRuntimeFactories[facing] = null;
|
|
1436
|
+
providerRuntime = await getProviderRuntime(facing, owner);
|
|
1437
|
+
providerRuntime.resetTurnState(attemptMessages);
|
|
605
1438
|
}
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
1439
|
+
catch (refreshError) {
|
|
1440
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1441
|
+
level: "warn",
|
|
1442
|
+
component: "engine",
|
|
1443
|
+
event: "engine.provider_retry_refresh_failed",
|
|
1444
|
+
message: "provider credential refresh failed during retry",
|
|
1445
|
+
meta: { provider: record.provider, model: record.model, reason: refreshError instanceof Error ? refreshError.message : String(refreshError) },
|
|
1446
|
+
});
|
|
611
1447
|
}
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
1448
|
+
callbacks.onError(new Error(`${cause}, retrying in ${seconds}s (${record.attempt}/${maxAttempts})...`), "transient");
|
|
1449
|
+
},
|
|
1450
|
+
sleep: async (delayMs) => {
|
|
1451
|
+
await waitForProviderRetry(delayMs, signal);
|
|
1452
|
+
providerRuntime.resetTurnState(attemptMessages);
|
|
1453
|
+
},
|
|
1454
|
+
});
|
|
1455
|
+
if (!attempt.ok) {
|
|
1456
|
+
finishTerminalProviderError(attempt.error, attempt.classification);
|
|
1457
|
+
continue;
|
|
1458
|
+
}
|
|
1459
|
+
const result = attempt.value;
|
|
1460
|
+
nextAttemptControls = [];
|
|
1461
|
+
providerIterations += 1;
|
|
1462
|
+
if (providerIterations === exports.MAX_PROVIDER_ITERATIONS && result.toolCalls.length > 0) {
|
|
1463
|
+
throw new Error(`provider iteration limit exhausted at response ${exports.MAX_PROVIDER_ITERATIONS} before tool execution`);
|
|
1464
|
+
}
|
|
1465
|
+
const streamCallbackBuffer = turnCallbackBufferRef.current;
|
|
1466
|
+
turnCallbackBufferRef.current = null;
|
|
1467
|
+
if (result.settleFinalization && !result.settleFinalization.ok) {
|
|
1468
|
+
// A completed settle payload is terminal provider output, not a prompt
|
|
1469
|
+
// for another model turn. Retractable callbacks have already cleared;
|
|
1470
|
+
// core-owned callback buffers must be discarded before surfacing the exact
|
|
1471
|
+
// parser failure through the ordinary terminal-error path.
|
|
1472
|
+
streamCallbackBuffer?.discard();
|
|
1473
|
+
finishTerminalProviderError(new Error(result.settleFinalization.errorCode), "unknown");
|
|
1474
|
+
continue;
|
|
1475
|
+
}
|
|
1476
|
+
// Track usage from the latest API call
|
|
1477
|
+
if (result.usage)
|
|
1478
|
+
lastUsage = result.usage;
|
|
1479
|
+
// SHARED: build CC-format assistant message from TurnResult
|
|
1480
|
+
const msg = {
|
|
1481
|
+
role: "assistant",
|
|
1482
|
+
};
|
|
1483
|
+
// Persist assistant content WITHOUT inline <think>...</think> blocks.
|
|
1484
|
+
// Reasoning content already routed through onReasoningChunk for live
|
|
1485
|
+
// surfacing and persisted separately as `_reasoning_items` for
|
|
1486
|
+
// providers that support a reasoning channel; saving it inline AND
|
|
1487
|
+
// alongside tool_calls causes MiniMax to reject the replayed turn
|
|
1488
|
+
// with "tool result's tool id not found" (error code 2013) because
|
|
1489
|
+
// it can't reconcile reasoning-with-tools in the same assistant
|
|
1490
|
+
// message. Strip aggressively at persist so the next replay is
|
|
1491
|
+
// clean; preserve the original reasoning trace on the message via
|
|
1492
|
+
// `_inline_reasoning` so debug/audit paths can still see it.
|
|
1493
|
+
if (result.content) {
|
|
1494
|
+
const stripped = stripThinkBlocksForViolationCheck(result.content);
|
|
1495
|
+
if (stripped.length > 0)
|
|
1496
|
+
msg.content = stripped;
|
|
1497
|
+
if (stripped.length !== result.content.length) {
|
|
1498
|
+
msg._inline_reasoning = result.content;
|
|
1499
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1500
|
+
level: "info",
|
|
1501
|
+
component: "engine",
|
|
1502
|
+
event: "engine.inline_reasoning_stripped",
|
|
1503
|
+
message: "stripped inline <think> blocks from persisted assistant message; preserved on _inline_reasoning",
|
|
1504
|
+
meta: {
|
|
1505
|
+
provider: providerRuntime.id,
|
|
1506
|
+
model: providerRuntime.model,
|
|
1507
|
+
originalLength: result.content.length,
|
|
1508
|
+
strippedLength: stripped.length,
|
|
1509
|
+
},
|
|
1510
|
+
});
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
if (result.toolCalls.length)
|
|
1514
|
+
msg.tool_calls = result.toolCalls.map((tc) => ({
|
|
1515
|
+
id: tc.id,
|
|
1516
|
+
type: "function",
|
|
1517
|
+
function: { name: tc.name, arguments: tc.arguments },
|
|
1518
|
+
}));
|
|
1519
|
+
// Store reasoning items from the API response on the assistant message
|
|
1520
|
+
// so they persist through session save/load and can be restored in toResponsesInput
|
|
1521
|
+
const reasoningItems = result.outputItems.filter((item) => "type" in item && item.type === "reasoning");
|
|
1522
|
+
if (reasoningItems.length > 0) {
|
|
1523
|
+
msg._reasoning_items = reasoningItems;
|
|
1524
|
+
}
|
|
1525
|
+
// Store thinking blocks (Anthropic) on the assistant message for round-tripping
|
|
1526
|
+
const thinkingItems = result.outputItems.filter((item) => "type" in item && (item.type === "thinking" || item.type === "redacted_thinking"));
|
|
1527
|
+
if (thinkingItems.length > 0) {
|
|
1528
|
+
msg._thinking_blocks = thinkingItems;
|
|
1529
|
+
}
|
|
1530
|
+
// Phase annotation for Codex provider
|
|
1531
|
+
const hasPhaseAnnotation = providerRuntime.capabilities.has("phase-annotation");
|
|
1532
|
+
const isSoleSettle = result.toolCalls.length === 1 && result.toolCalls[0].name === "settle";
|
|
1533
|
+
if (hasPhaseAnnotation) {
|
|
1534
|
+
msg.phase = isSoleSettle ? "settle" : "commentary";
|
|
1535
|
+
}
|
|
1536
|
+
// Detect the MiniMax "only-thinking, no tool call" violation: no tool
|
|
1537
|
+
// calls returned, and the content is empty after stripping
|
|
1538
|
+
// <think>...</think> blocks. This is a narrow check — legitimate
|
|
1539
|
+
// content-only responses (text without think tags, or text outside
|
|
1540
|
+
// think tags) still flow through the original "no tool calls →
|
|
1541
|
+
// accept as-is" path so existing channels and tests are unaffected.
|
|
1542
|
+
const onlyThinkContent = !result.toolCalls.length
|
|
1543
|
+
&& typeof result.content === "string"
|
|
1544
|
+
&& stripThinkBlocksForViolationCheck(result.content).length === 0
|
|
1545
|
+
&& result.content.length > 0;
|
|
1546
|
+
const privateReturnTextAckRetryError = !result.toolCalls.length
|
|
1547
|
+
? privateReturnMissingPonderError({
|
|
1548
|
+
latestUserRequest: latestUserMessageText(messages),
|
|
1549
|
+
answer: stripThinkBlocksForViolationCheck(result.content),
|
|
1550
|
+
sawPonder,
|
|
1551
|
+
})
|
|
1552
|
+
: null;
|
|
1553
|
+
if (!result.toolCalls.length) {
|
|
1554
|
+
if (forcingHistoricalEffect) {
|
|
1555
|
+
streamCallbackBuffer?.discard();
|
|
1556
|
+
callbacks.onClearText?.();
|
|
1557
|
+
const retryableHistoricalTools = [...forcedHistoricalToolNames];
|
|
1558
|
+
if (historicalToolFailureRetries >= NO_TOOL_CALL_MAX_RETRIES) {
|
|
1559
|
+
const blockedAnswer = `I could not complete the unresolved ${retryableHistoricalTools.join(", ")} effect because the provider repeatedly returned no tool call. I did not treat the requested change as complete.`;
|
|
1560
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1561
|
+
level: "warn",
|
|
1562
|
+
component: "engine",
|
|
1563
|
+
event: "engine.historical_tool_failure_retry",
|
|
1564
|
+
message: "unresolved historical effect exhausted deterministic tool-call retries; failing closed",
|
|
1565
|
+
meta: { provider: providerRuntime.id, model: providerRuntime.model, toolNames: retryableHistoricalTools, cap: NO_TOOL_CALL_MAX_RETRIES },
|
|
1566
|
+
});
|
|
1567
|
+
pushGenerated({ role: "assistant", content: blockedAnswer });
|
|
1568
|
+
callbacks.onTextChunk(blockedAnswer);
|
|
1569
|
+
completion = { answer: blockedAnswer, intent: "blocked" };
|
|
1570
|
+
outcome = "blocked";
|
|
617
1571
|
done = true;
|
|
1572
|
+
continue;
|
|
618
1573
|
}
|
|
1574
|
+
historicalToolFailureRetries += 1;
|
|
1575
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1576
|
+
level: "warn",
|
|
1577
|
+
component: "engine",
|
|
1578
|
+
event: "engine.historical_tool_failure_retry",
|
|
1579
|
+
message: "unresolved historical effect returned no tool call; forcing another exact-effect attempt",
|
|
1580
|
+
meta: {
|
|
1581
|
+
provider: providerRuntime.id,
|
|
1582
|
+
model: providerRuntime.model,
|
|
1583
|
+
toolNames: retryableHistoricalTools,
|
|
1584
|
+
attempt: historicalToolFailureRetries,
|
|
1585
|
+
cap: NO_TOOL_CALL_MAX_RETRIES,
|
|
1586
|
+
},
|
|
1587
|
+
});
|
|
1588
|
+
rejectAttempt(msg, [{
|
|
1589
|
+
role: "user",
|
|
1590
|
+
content: `this exact request previously reached a tool that is advertised again now. Its unresolved historical effect is through ${retryableHistoricalTools.join(", ")}. Only that tool is available now. Read current state if needed, then retry the exact failed effect. Do not report completion until the effect succeeds.`,
|
|
1591
|
+
}]);
|
|
1592
|
+
continue;
|
|
619
1593
|
}
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
// assistant msg + error tool result and let the model try again.
|
|
1594
|
+
const requiredToolCallsGate = pendingRequiredToolCalls();
|
|
1595
|
+
if (requiredToolCallsGate) {
|
|
1596
|
+
streamCallbackBuffer?.discard();
|
|
624
1597
|
callbacks.onClearText?.();
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
1598
|
+
queueRequiredCorrection(msg, requiredToolCallsGate.message, "before required tool calls completed");
|
|
1599
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1600
|
+
level: "warn",
|
|
1601
|
+
component: "engine",
|
|
1602
|
+
event: "engine.required_tool_calls_pending",
|
|
1603
|
+
message: "terminal response rejected until required tool handlers dispatch",
|
|
1604
|
+
meta: { missingToolNames: requiredToolCallsGate.missing },
|
|
1605
|
+
});
|
|
1606
|
+
continue;
|
|
629
1607
|
}
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
1608
|
+
const requiredAnswerRejection = options?.requiredToolCalls?.validateTerminalAnswer?.(String(msg.content ?? ""));
|
|
1609
|
+
if (requiredAnswerRejection) {
|
|
1610
|
+
streamCallbackBuffer?.discard();
|
|
1611
|
+
callbacks.onClearText?.();
|
|
1612
|
+
queueRequiredCorrection(msg, requiredAnswerRejection, "before required terminal answer validation completed");
|
|
1613
|
+
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "engine", event: "engine.required_tool_answer_rejected", message: "unsupported terminal answer rejected after required reads", meta: { answerLength: String(msg.content ?? "").length } });
|
|
1614
|
+
continue;
|
|
1615
|
+
}
|
|
1616
|
+
if (privateReturnTextAckRetryError) {
|
|
1617
|
+
streamCallbackBuffer?.discard();
|
|
1618
|
+
callbacks.onClearText?.();
|
|
1619
|
+
if (noToolCallRetries < NO_TOOL_CALL_MAX_RETRIES) {
|
|
1620
|
+
noToolCallRetries++;
|
|
1621
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1622
|
+
level: "warn",
|
|
1623
|
+
component: "engine",
|
|
1624
|
+
event: "engine.no_tool_call_retry",
|
|
1625
|
+
message: "model returned a text-only private-return acknowledgement without ponder; retrying with corrective nudge",
|
|
1626
|
+
meta: {
|
|
1627
|
+
attempt: noToolCallRetries,
|
|
1628
|
+
cap: NO_TOOL_CALL_MAX_RETRIES,
|
|
1629
|
+
provider: providerRuntime.id,
|
|
1630
|
+
model: providerRuntime.model,
|
|
1631
|
+
reason: "private_return_missing_ponder",
|
|
1632
|
+
contentLength: result.content.length,
|
|
1633
|
+
},
|
|
1634
|
+
});
|
|
1635
|
+
rejectAttempt(msg, [{
|
|
1636
|
+
role: "user",
|
|
1637
|
+
content: `${privateReturnTextAckRetryError} Emit the ponder(action=create, ...) tool call now, or ask a blocking clarification without saying the private work is queued.`,
|
|
1638
|
+
}]);
|
|
1639
|
+
continue;
|
|
1640
|
+
}
|
|
1641
|
+
const blockedAnswer = "I could not start the private pass. No private-attention packet was created, so no return work was queued.";
|
|
1642
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1643
|
+
level: "error",
|
|
1644
|
+
component: "engine",
|
|
1645
|
+
event: "engine.private_return_missing_ponder_blocked",
|
|
1646
|
+
message: "private-return text acknowledgement skipped ponder through the retry cap; failing closed",
|
|
1647
|
+
meta: {
|
|
1648
|
+
cap: NO_TOOL_CALL_MAX_RETRIES,
|
|
1649
|
+
provider: providerRuntime.id,
|
|
1650
|
+
model: providerRuntime.model,
|
|
1651
|
+
contentLength: result.content.length,
|
|
1652
|
+
},
|
|
1653
|
+
});
|
|
1654
|
+
pushGenerated({ role: "assistant", content: blockedAnswer });
|
|
1655
|
+
callbacks.onTextChunk(blockedAnswer);
|
|
1656
|
+
completion = { answer: blockedAnswer, intent: "blocked" };
|
|
1657
|
+
outcome = "blocked";
|
|
1658
|
+
done = true;
|
|
1659
|
+
continue;
|
|
640
1660
|
}
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
1661
|
+
if (onlyThinkContent && toolChoiceRequired && noToolCallRetries < NO_TOOL_CALL_MAX_RETRIES) {
|
|
1662
|
+
streamCallbackBuffer?.discard();
|
|
1663
|
+
// Provider-level violation: tool_choice was required, model emitted
|
|
1664
|
+
// only a <think>...</think> block (or empty content) with no tool
|
|
1665
|
+
// call. Retry with a corrective nudge up to NO_TOOL_CALL_MAX_RETRIES
|
|
1666
|
+
// times. After cap, accept as-is (the readback path strips think
|
|
1667
|
+
// tags and surfaces a clear diagnostic).
|
|
1668
|
+
noToolCallRetries++;
|
|
1669
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1670
|
+
level: "warn",
|
|
1671
|
+
component: "engine",
|
|
1672
|
+
event: "engine.no_tool_call_retry",
|
|
1673
|
+
message: "model returned only <think> content with no tool call despite tool_choice=required; retrying with corrective nudge",
|
|
1674
|
+
meta: {
|
|
1675
|
+
attempt: noToolCallRetries,
|
|
1676
|
+
cap: NO_TOOL_CALL_MAX_RETRIES,
|
|
1677
|
+
provider: providerRuntime.id,
|
|
1678
|
+
model: providerRuntime.model,
|
|
1679
|
+
contentLength: result.content.length,
|
|
1680
|
+
},
|
|
1681
|
+
});
|
|
1682
|
+
rejectAttempt(msg, [{
|
|
1683
|
+
role: "user",
|
|
1684
|
+
content: isPrivateRuntimeChannel
|
|
1685
|
+
? augmentedToolContext?.noSend === true
|
|
1686
|
+
? "no tool was called this turn. this is an immutable no-send turn; call rest now without creating a continuation."
|
|
1687
|
+
: "no tool was called this turn. you must end every turn by calling rest (or surface, ponder, observe). emit the tool call now."
|
|
1688
|
+
: "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.",
|
|
1689
|
+
}]);
|
|
1690
|
+
continue;
|
|
1691
|
+
}
|
|
1692
|
+
// Legitimate text-only response, or cap reached — accept as-is.
|
|
1693
|
+
await streamCallbackBuffer?.flush();
|
|
1694
|
+
pushGenerated(msg);
|
|
653
1695
|
done = true;
|
|
654
|
-
continue;
|
|
655
1696
|
}
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
1697
|
+
else {
|
|
1698
|
+
// Reset the retry counter on any successful tool call.
|
|
1699
|
+
noToolCallRetries = 0;
|
|
1700
|
+
const preCallMessages = structuredClone(messages.filter((message) => message.role !== "system"));
|
|
1701
|
+
const validatedCalls = validateToolCallBatchAtProductionBoundary(result.toolCalls, activeTools);
|
|
1702
|
+
const invalidCall = validatedCalls.find((entry) => "error" in entry);
|
|
1703
|
+
if (invalidCall) {
|
|
1704
|
+
streamCallbackBuffer?.discard();
|
|
1705
|
+
const unadvertisedCall = validatedCalls.find((entry) => !activeToolNames.has(entry.call.name));
|
|
1706
|
+
const rejections = [];
|
|
1707
|
+
for (const entry of validatedCalls) {
|
|
1708
|
+
const detail = "error" in entry ? entry.error : "another call in this batch had invalid arguments";
|
|
1709
|
+
const rejection = unadvertisedCall
|
|
1710
|
+
? `rejected: ${entry.call.name} was not advertised for this channel; no handler was executed.`
|
|
1711
|
+
: `invalid tool arguments: ${detail}`;
|
|
1712
|
+
rejections.push(rejection);
|
|
1713
|
+
options?.toolBoundaryObserver?.({
|
|
1714
|
+
name: entry.call.name,
|
|
1715
|
+
reason: activeToolNames.has(entry.call.name) ? "invalid_arguments" : "profile_excluded",
|
|
1716
|
+
globallyResolvable: typeof (0, tools_1.resolveToolDefinition)(entry.call.name)?.handler === "function",
|
|
1717
|
+
invoked: false,
|
|
1718
|
+
sideEffect: false,
|
|
1719
|
+
});
|
|
1720
|
+
}
|
|
1721
|
+
rejectToolBatch(msg, rejections);
|
|
1722
|
+
if (unadvertisedCall) {
|
|
1723
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1724
|
+
level: "warn",
|
|
1725
|
+
component: "engine",
|
|
1726
|
+
event: "engine.unadvertised_tool_blocked",
|
|
1727
|
+
message: "blocked an unadvertised tool call before batch execution",
|
|
1728
|
+
meta: { channel: String(channel), toolName: unadvertisedCall.call.name },
|
|
1729
|
+
});
|
|
1730
|
+
}
|
|
1731
|
+
else {
|
|
1732
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1733
|
+
level: "warn",
|
|
1734
|
+
component: "engine",
|
|
1735
|
+
event: "engine.tool_arguments_rejected",
|
|
1736
|
+
message: "tool batch rejected before execution because arguments were invalid",
|
|
1737
|
+
meta: { toolCallId: invalidCall.call.id, toolName: invalidCall.call.name },
|
|
1738
|
+
});
|
|
1739
|
+
}
|
|
1740
|
+
continue;
|
|
1741
|
+
}
|
|
1742
|
+
const validCalls = validatedCalls;
|
|
1743
|
+
const validatedCallArguments = new Map(validCalls.map((entry) => [
|
|
1744
|
+
entry.call,
|
|
1745
|
+
entry.validated.arguments,
|
|
1746
|
+
]));
|
|
1747
|
+
const preflightRejections = new Map();
|
|
1748
|
+
for (const entry of validCalls) {
|
|
1749
|
+
if (!relationship && !toolSelection.engine.some((tool) => tool.function.name === entry.call.name))
|
|
1750
|
+
continue;
|
|
1751
|
+
const prepared = await (0, tools_1.preflightToolCall)(entry.call.name, validatedCallArguments.get(entry.call), augmentedToolContext);
|
|
1752
|
+
if (prepared.kind !== "ready")
|
|
1753
|
+
preflightRejections.set(entry.call.id, prepared.text);
|
|
1754
|
+
}
|
|
1755
|
+
if (preflightRejections.size > 0) {
|
|
1756
|
+
streamCallbackBuffer?.discard();
|
|
1757
|
+
rejectToolBatch(msg, result.toolCalls.map((call) => preflightRejections.get(call.id)
|
|
1758
|
+
?? "rejected: another call in this batch failed current authorization; no handler was executed."));
|
|
1759
|
+
continue;
|
|
1760
|
+
}
|
|
1761
|
+
const habitBlockReason = await habitToolBatchBlockReason(habitSession, result.toolCalls, augmentedToolContext?.delegatedOrigins, toolSelection);
|
|
1762
|
+
if (habitBlockReason) {
|
|
1763
|
+
streamCallbackBuffer?.discard();
|
|
1764
|
+
recordBlockedHabitSurfaceAttempts(habitSession, result.toolCalls, habitBlockReason);
|
|
1765
|
+
const blockedOutput = `blocked: ${habitBlockReason}. No tool side effects from this assistant message were executed.`;
|
|
1766
|
+
rejectToolBatch(msg, result.toolCalls.map(() => blockedOutput));
|
|
1767
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1768
|
+
level: "warn",
|
|
1769
|
+
component: "engine",
|
|
1770
|
+
event: "engine.habit_tool_batch_blocked",
|
|
1771
|
+
message: "habit tool batch blocked before side effects",
|
|
1772
|
+
meta: { reason: habitBlockReason, toolCalls: result.toolCalls.map((call) => call.name) },
|
|
1773
|
+
});
|
|
1774
|
+
continue;
|
|
662
1775
|
}
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
const content = typeof parsedArgs.content === "string" ? parsedArgs.content : "";
|
|
666
|
-
const answer = typeof parsedArgs.answer === "string" ? parsedArgs.answer : undefined;
|
|
667
|
-
const parsedMode = parsedArgs.mode === "reflect" || parsedArgs.mode === "plan" || parsedArgs.mode === "relay"
|
|
668
|
-
? parsedArgs.mode
|
|
1776
|
+
const soleViolation = result.toolCalls.length > 1
|
|
1777
|
+
? result.toolCalls.find((call) => SOLE_CALL_REJECTION[call.name] !== undefined || (0, tools_1.resolveToolDefinition)(call.name, toolSelection)?.terminalProjection?.requiresSoleCall === true)
|
|
669
1778
|
: undefined;
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
1779
|
+
if (soleViolation) {
|
|
1780
|
+
streamCallbackBuffer?.discard();
|
|
1781
|
+
const reason = SOLE_CALL_REJECTION[soleViolation.name] ?? `rejected: ${soleViolation.name} must be the only tool call.`;
|
|
1782
|
+
rejectToolBatch(msg, result.toolCalls.map(() => reason));
|
|
1783
|
+
continue;
|
|
675
1784
|
}
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
...(currentSession && !isInnerChannel ? {
|
|
697
|
-
delegatedFrom: {
|
|
698
|
-
friendId: currentSession.friendId,
|
|
699
|
-
channel: currentSession.channel,
|
|
700
|
-
key: currentSession.key,
|
|
701
|
-
},
|
|
702
|
-
obligationStatus: "pending",
|
|
703
|
-
} : {}),
|
|
704
|
-
};
|
|
705
|
-
(0, pending_1.queuePendingMessage)(pendingDir, envelope);
|
|
706
|
-
if (currentSession && !isInnerChannel) {
|
|
1785
|
+
const soleTerminalCall = result.toolCalls.length === 1
|
|
1786
|
+
? result.toolCalls[0]
|
|
1787
|
+
: null;
|
|
1788
|
+
const soleTerminalProjection = soleTerminalCall
|
|
1789
|
+
? (0, tools_1.resolveToolDefinition)(soleTerminalCall.name, toolSelection)?.terminalProjection
|
|
1790
|
+
: undefined;
|
|
1791
|
+
if (soleTerminalCall && soleTerminalProjection?.mode === "verbatim") {
|
|
1792
|
+
const terminalArgs = validatedCallArguments.get(soleTerminalCall);
|
|
1793
|
+
if (soleTerminalProjection.clearBufferedText
|
|
1794
|
+
|| callbacks.settleOutputMode === "final_only") {
|
|
1795
|
+
streamCallbackBuffer?.discard();
|
|
1796
|
+
}
|
|
1797
|
+
else {
|
|
1798
|
+
await streamCallbackBuffer?.flush();
|
|
1799
|
+
}
|
|
1800
|
+
if (soleTerminalProjection.clearBufferedText)
|
|
1801
|
+
callbacks.onClearText?.();
|
|
1802
|
+
callbacks.onToolStart(soleTerminalCall.name, terminalArgs);
|
|
1803
|
+
let terminalResult;
|
|
1804
|
+
let terminalSucceeded = false;
|
|
707
1805
|
try {
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
1806
|
+
if (options?.execTool && !relationship) {
|
|
1807
|
+
terminalResult = await options.execTool(soleTerminalCall.name, terminalArgs, trustedToolContext);
|
|
1808
|
+
terminalSucceeded = true;
|
|
1809
|
+
}
|
|
1810
|
+
else {
|
|
1811
|
+
const execution = await (0, tools_1.executeTool)(soleTerminalCall.name, terminalArgs, augmentedToolContext, options?.execTool);
|
|
1812
|
+
terminalResult = "error" in execution
|
|
1813
|
+
? `error: ${execution.error instanceof Error ? execution.error.message : String(execution.error)}`
|
|
1814
|
+
: execution.text;
|
|
1815
|
+
terminalSucceeded = execution.kind === "handler_succeeded";
|
|
1816
|
+
}
|
|
716
1817
|
}
|
|
717
|
-
catch {
|
|
718
|
-
|
|
1818
|
+
catch (error) {
|
|
1819
|
+
terminalResult = error instanceof Error ? `error: ${error.message}` : `error: ${String(error)}`;
|
|
719
1820
|
}
|
|
1821
|
+
callbacks.onToolEnd(soleTerminalCall.name, (0, tools_1.summarizeArgs)(soleTerminalCall.name, terminalArgs, toolSelection), terminalSucceeded);
|
|
1822
|
+
pushGenerated(msg);
|
|
1823
|
+
pushGenerated({ role: "tool", tool_call_id: soleTerminalCall.id, content: terminalResult });
|
|
1824
|
+
providerRuntime.appendToolOutput(soleTerminalCall.id, terminalResult);
|
|
1825
|
+
callbacks.onTextChunk(terminalResult);
|
|
1826
|
+
completion = { answer: terminalResult, intent: terminalSucceeded ? "complete" : "blocked" };
|
|
1827
|
+
outcome = terminalSucceeded ? "settled" : "blocked";
|
|
1828
|
+
done = true;
|
|
1829
|
+
continue;
|
|
720
1830
|
}
|
|
721
|
-
|
|
722
|
-
|
|
1831
|
+
// Check for settle sole call: intercept before tool execution
|
|
1832
|
+
if (isSoleSettle) {
|
|
1833
|
+
const settleArgs = validatedCallArguments.get(result.toolCalls[0]);
|
|
1834
|
+
callbacks.onToolStart("settle", settleArgs);
|
|
1835
|
+
const requiredToolCallsGate = pendingRequiredToolCalls();
|
|
1836
|
+
if (requiredToolCallsGate) {
|
|
1837
|
+
streamCallbackBuffer?.discard();
|
|
1838
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs, toolSelection), false);
|
|
1839
|
+
callbacks.onClearText?.();
|
|
1840
|
+
queueRequiredCorrection(msg, requiredToolCallsGate.message, "before required tool calls completed");
|
|
1841
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1842
|
+
level: "warn",
|
|
1843
|
+
component: "engine",
|
|
1844
|
+
event: "engine.required_tool_calls_pending",
|
|
1845
|
+
message: "settle rejected until required tool handlers dispatch",
|
|
1846
|
+
meta: { missingToolNames: requiredToolCallsGate.missing },
|
|
1847
|
+
});
|
|
1848
|
+
continue;
|
|
1849
|
+
}
|
|
1850
|
+
// Private-runtime attention queue gate: reject settle if items remain
|
|
1851
|
+
const attentionQueue = augmentedToolContext?.delegatedOrigins;
|
|
1852
|
+
if (isPrivateRuntimeChannel && attentionQueue && attentionQueue.length > 0) {
|
|
1853
|
+
streamCallbackBuffer?.discard();
|
|
1854
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs, toolSelection), false);
|
|
1855
|
+
callbacks.onClearText?.();
|
|
1856
|
+
const gateMessage = "current held-work frame still has unsurfaced items — return each listed item with surface(delegationId=...) before you settle. Older transcript claims are historical; only the current held-work frame is the gate.";
|
|
1857
|
+
rejectToolBatch(msg, [gateMessage]);
|
|
1858
|
+
continue;
|
|
1859
|
+
}
|
|
1860
|
+
// Extract answer from the tool call arguments.
|
|
1861
|
+
// Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
|
|
1862
|
+
const { answer, intent } = parseSettlePayload(result.toolCalls[0].arguments);
|
|
1863
|
+
const requiredAnswerRejection = options?.requiredToolCalls?.validateTerminalAnswer?.(answer);
|
|
1864
|
+
if (requiredAnswerRejection) {
|
|
1865
|
+
streamCallbackBuffer?.discard();
|
|
1866
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs, toolSelection), false);
|
|
1867
|
+
callbacks.onClearText?.();
|
|
1868
|
+
queueRequiredCorrection(msg, requiredAnswerRejection, "before required terminal answer validation completed");
|
|
1869
|
+
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "engine", event: "engine.required_tool_answer_rejected", message: "unsupported settle answer rejected after required reads", meta: { answerLength: answer.length } });
|
|
1870
|
+
continue;
|
|
1871
|
+
}
|
|
1872
|
+
// Private-runtime settle: no CompletionMetadata, "(settled)" ack
|
|
1873
|
+
if (isPrivateRuntimeChannel) {
|
|
1874
|
+
streamCallbackBuffer?.discard();
|
|
1875
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs, toolSelection), true);
|
|
1876
|
+
pushGenerated(msg);
|
|
1877
|
+
const settled = "(settled)";
|
|
1878
|
+
pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: settled });
|
|
1879
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, settled);
|
|
1880
|
+
outcome = "settled";
|
|
1881
|
+
done = true;
|
|
1882
|
+
continue;
|
|
1883
|
+
}
|
|
1884
|
+
// The provider finalizer has already established a top-level string
|
|
1885
|
+
// answer before ordinary settle handling reaches this point.
|
|
1886
|
+
const deliveredAnswer = answer;
|
|
1887
|
+
const retryError = privateReturnAckLeakError(deliveredAnswer, privateReturnHeldTokens)
|
|
1888
|
+
?? privateReturnMissingPonderError({
|
|
1889
|
+
latestUserRequest: latestUserMessageText(messages),
|
|
1890
|
+
answer: deliveredAnswer,
|
|
1891
|
+
sawPonder,
|
|
1892
|
+
})
|
|
1893
|
+
?? getSettleRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp, options?.delegationDecision, sawSendMessageSelf, sawPonder, sawQuerySession, options?.currentObligation ?? null, options?.activeWorkFrame?.inner?.job, sawExternalStateQuery);
|
|
1894
|
+
const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
|
|
1895
|
+
if (retryError === null) {
|
|
1896
|
+
try {
|
|
1897
|
+
if (!result.settleStreamed) {
|
|
1898
|
+
const acceptedOutputCallbacks = streamCallbackBuffer?.callbacks ?? callbacks;
|
|
1899
|
+
acceptedOutputCallbacks.onTextChunk(deliveredAnswer);
|
|
1900
|
+
}
|
|
1901
|
+
await streamCallbackBuffer?.flush();
|
|
1902
|
+
}
|
|
1903
|
+
catch (error) {
|
|
1904
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs, toolSelection), false);
|
|
1905
|
+
streamCallbackBuffer?.discard();
|
|
1906
|
+
finishTerminalProviderError(new streaming_1.SettleFinalizationCallbackError(error), "unknown");
|
|
1907
|
+
continue;
|
|
1908
|
+
}
|
|
1909
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs, toolSelection), true);
|
|
1910
|
+
completion = {
|
|
1911
|
+
answer: deliveredAnswer,
|
|
1912
|
+
intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
|
|
1913
|
+
};
|
|
1914
|
+
// Retractable owners already hold the validated answer. Final-only
|
|
1915
|
+
// owners receive it here, after every semantic continuation gate.
|
|
1916
|
+
pushGenerated(msg);
|
|
1917
|
+
if (validDirectReply) {
|
|
1918
|
+
const resumeWork = "direct reply delivered. resume the unresolved obligation now and keep working until you can finish or clearly report that you are blocked.";
|
|
1919
|
+
pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: resumeWork });
|
|
1920
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, resumeWork);
|
|
1921
|
+
}
|
|
1922
|
+
else {
|
|
1923
|
+
const delivered = "(delivered)";
|
|
1924
|
+
pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
|
|
1925
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
|
|
1926
|
+
outcome = intent === "blocked" ? "blocked" : "settled";
|
|
1927
|
+
done = true;
|
|
1928
|
+
}
|
|
1929
|
+
}
|
|
1930
|
+
else {
|
|
1931
|
+
// The payload is structurally final, but a semantic continuation
|
|
1932
|
+
// gate rejected it. Return that exact gate reason to the model.
|
|
1933
|
+
streamCallbackBuffer?.discard();
|
|
1934
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs, toolSelection), false);
|
|
1935
|
+
callbacks.onClearText?.();
|
|
1936
|
+
rejectToolBatch(msg, [retryError]);
|
|
1937
|
+
}
|
|
1938
|
+
continue;
|
|
723
1939
|
}
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
if (tc.name === "final_answer") {
|
|
747
|
-
const rejection = "rejected: final_answer must be the only tool call. Finish your work first, then call final_answer alone.";
|
|
748
|
-
messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
|
|
749
|
-
providerRuntime.appendToolOutput(tc.id, rejection);
|
|
1940
|
+
// Check for observe sole call: intercept before tool execution
|
|
1941
|
+
const isSoleObserve = result.toolCalls.length === 1 && result.toolCalls[0].name === "observe";
|
|
1942
|
+
if (isSoleObserve) {
|
|
1943
|
+
streamCallbackBuffer?.discard();
|
|
1944
|
+
const observeArgs = validatedCallArguments.get(result.toolCalls[0]);
|
|
1945
|
+
let reason;
|
|
1946
|
+
if (typeof observeArgs?.reason === "string")
|
|
1947
|
+
reason = observeArgs.reason;
|
|
1948
|
+
callbacks.onToolStart("observe", observeArgs);
|
|
1949
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1950
|
+
component: "engine",
|
|
1951
|
+
event: "engine.observe",
|
|
1952
|
+
message: "agent observed without responding",
|
|
1953
|
+
meta: { ...(reason ? { reason } : {}) },
|
|
1954
|
+
});
|
|
1955
|
+
callbacks.onToolEnd("observe", (0, tools_1.summarizeArgs)("observe", observeArgs, toolSelection), true);
|
|
1956
|
+
pushGenerated(msg);
|
|
1957
|
+
const silenced = "(silenced)";
|
|
1958
|
+
pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: silenced });
|
|
1959
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, silenced);
|
|
1960
|
+
outcome = "observed";
|
|
1961
|
+
done = true;
|
|
750
1962
|
continue;
|
|
751
1963
|
}
|
|
752
|
-
//
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
1964
|
+
// Check for rest sole call: intercept before tool execution
|
|
1965
|
+
const isSoleRest = result.toolCalls.length === 1 && result.toolCalls[0].name === "rest";
|
|
1966
|
+
if (isSoleRest) {
|
|
1967
|
+
streamCallbackBuffer?.discard();
|
|
1968
|
+
const restArgs = validatedCallArguments.get(result.toolCalls[0]);
|
|
1969
|
+
callbacks.onToolStart("rest", restArgs);
|
|
1970
|
+
// Attention queue gate: reject rest if items remain
|
|
1971
|
+
const attentionQueue = augmentedToolContext?.delegatedOrigins;
|
|
1972
|
+
if (attentionQueue && attentionQueue.length > 0) {
|
|
1973
|
+
callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs, toolSelection), false);
|
|
1974
|
+
const gateMessage = "current held-work frame still has unsurfaced items — return each listed item with surface(delegationId=...) before you rest. Older transcript claims are historical; only the current held-work frame is the gate.";
|
|
1975
|
+
rejectToolBatch(msg, [gateMessage]);
|
|
1976
|
+
continue;
|
|
1977
|
+
}
|
|
1978
|
+
if (hasFreshPendingWork(options) && !freshWorkGateFired) {
|
|
1979
|
+
freshWorkGateFired = true;
|
|
1980
|
+
callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs, toolSelection), false);
|
|
1981
|
+
const gateMessage = "fresh work arrived for me this turn — inspect the pending messages above and take the next concrete action before you rest.";
|
|
1982
|
+
rejectToolBatch(msg, [gateMessage]);
|
|
1983
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1984
|
+
level: "info",
|
|
1985
|
+
component: "engine",
|
|
1986
|
+
event: "engine.fresh_work_gate_fired",
|
|
1987
|
+
message: "rest deferred once because pending work arrived this turn; agent has been notified",
|
|
1988
|
+
meta: { pendingCount: options.pendingMessages.length },
|
|
1989
|
+
});
|
|
1990
|
+
continue;
|
|
1991
|
+
}
|
|
1992
|
+
callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs, toolSelection), true);
|
|
1993
|
+
pushGenerated(msg);
|
|
1994
|
+
const ack = "(resting)";
|
|
1995
|
+
pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
|
|
1996
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
|
|
1997
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1998
|
+
component: "engine",
|
|
1999
|
+
event: "engine.rested",
|
|
2000
|
+
message: "resting until next heartbeat",
|
|
2001
|
+
meta: { ...(typeof restArgs?.status === "string" ? { status: restArgs.status } : {}) },
|
|
2002
|
+
});
|
|
2003
|
+
outcome = "rested";
|
|
2004
|
+
done = true;
|
|
757
2005
|
continue;
|
|
758
2006
|
}
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
const
|
|
762
|
-
|
|
763
|
-
|
|
2007
|
+
const requiredDispatchRejections = new Map();
|
|
2008
|
+
for (const entry of validCalls) {
|
|
2009
|
+
const requiredArgs = entry.validated.arguments;
|
|
2010
|
+
const rejection = options?.requiredToolCalls?.validateToolCallBeforeDispatch?.(entry.call.name, requiredArgs);
|
|
2011
|
+
if (rejection)
|
|
2012
|
+
requiredDispatchRejections.set(entry.call.id, { name: entry.call.name, args: requiredArgs, message: rejection });
|
|
2013
|
+
}
|
|
2014
|
+
if (requiredDispatchRejections.size > 0) {
|
|
2015
|
+
streamCallbackBuffer?.discard();
|
|
2016
|
+
for (const rejection of requiredDispatchRejections.values()) {
|
|
2017
|
+
callbacks.onToolStart(rejection.name, rejection.args);
|
|
2018
|
+
callbacks.onToolEnd(rejection.name, (0, tools_1.summarizeArgs)(rejection.name, rejection.args, toolSelection), false);
|
|
2019
|
+
options?.toolBoundaryObserver?.({
|
|
2020
|
+
name: rejection.name, reason: "dependency_rejected",
|
|
2021
|
+
globallyResolvable: typeof (0, tools_1.resolveToolDefinition)(rejection.name)?.handler === "function",
|
|
2022
|
+
invoked: false, sideEffect: false,
|
|
2023
|
+
});
|
|
2024
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2025
|
+
level: "warn", component: "engine", event: "engine.required_tool_dispatch_rejected",
|
|
2026
|
+
message: "required tool dependency rejected before approval and handler dispatch",
|
|
2027
|
+
meta: { toolName: rejection.name },
|
|
2028
|
+
});
|
|
2029
|
+
}
|
|
2030
|
+
rejectToolBatch(msg, result.toolCalls.map((call) => requiredDispatchRejections.get(call.id)?.message
|
|
2031
|
+
?? "rejected: another call in this batch has an unsatisfied required dependency; no handler was executed."));
|
|
764
2032
|
continue;
|
|
765
2033
|
}
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
args =
|
|
2034
|
+
const executionRejections = new Map();
|
|
2035
|
+
for (const entry of validCalls) {
|
|
2036
|
+
const args = validatedCallArguments.get(entry.call);
|
|
2037
|
+
const fingerprint = effectFingerprint(entry.call.name, entry.call.arguments, toolSelection);
|
|
2038
|
+
if (forcingHistoricalEffect && fingerprint && !unresolvedHistoricalEffects.some((effect) => effect.fingerprint === fingerprint)) {
|
|
2039
|
+
executionRejections.set(entry.call.id, "rejected: this turn is retrying an unresolved historical effect, and these mutation arguments do not match it. Read current state or retry the exact failed effect.");
|
|
2040
|
+
}
|
|
2041
|
+
else if (entry.call.name === "send_message" && args.friendId === "self" && !isPrivateRuntimeChannel && looksLikePrivateReturnRequest(latestUserMessageText(messages))) {
|
|
2042
|
+
executionRejections.set(entry.call.id, "private-return requests must use ponder, not send_message(friendId=self). Create a typed ponder packet with the marker/source request preserved, then only acknowledge that the private pass is queued.");
|
|
2043
|
+
}
|
|
2044
|
+
else if (entry.call.name !== "speak" && entry.call.name !== "ponder") {
|
|
2045
|
+
const loop = (0, tool_loop_1.detectToolLoop)(toolLoopState, entry.call.name, args);
|
|
2046
|
+
if (loop.stuck)
|
|
2047
|
+
executionRejections.set(entry.call.id, `loop guard: ${loop.message}`);
|
|
2048
|
+
}
|
|
769
2049
|
}
|
|
770
|
-
|
|
771
|
-
|
|
2050
|
+
if (executionRejections.size > 0) {
|
|
2051
|
+
streamCallbackBuffer?.discard();
|
|
2052
|
+
for (const entry of validCalls) {
|
|
2053
|
+
if (!executionRejections.has(entry.call.id))
|
|
2054
|
+
continue;
|
|
2055
|
+
const args = validatedCallArguments.get(entry.call);
|
|
2056
|
+
callbacks.onToolStart(entry.call.name, args);
|
|
2057
|
+
callbacks.onToolEnd(entry.call.name, (0, tools_1.summarizeArgs)(entry.call.name, args, toolSelection), false);
|
|
2058
|
+
}
|
|
2059
|
+
rejectToolBatch(msg, result.toolCalls.map((call) => executionRejections.get(call.id)
|
|
2060
|
+
?? "rejected: another call in this batch was inadmissible; no handler was executed."));
|
|
2061
|
+
continue;
|
|
772
2062
|
}
|
|
773
|
-
|
|
774
|
-
|
|
2063
|
+
const approvalCalls = await Promise.all(validCalls.map(async (entry) => {
|
|
2064
|
+
const classification = await (0, tools_1.classifyApprovalForInvocation)(entry.call.name, entry.validated.arguments, augmentedToolContext);
|
|
2065
|
+
return {
|
|
2066
|
+
...entry,
|
|
2067
|
+
...classification,
|
|
2068
|
+
};
|
|
2069
|
+
}));
|
|
2070
|
+
const protectedCall = approvalCalls.find((entry) => entry.policy.kind === "required");
|
|
2071
|
+
if (protectedCall && result.toolCalls.length !== 1) {
|
|
2072
|
+
streamCallbackBuffer?.discard();
|
|
2073
|
+
rejectToolBatch(msg, result.toolCalls.map(() => "rejected: approval-eligible tool must be the sole call; no call in this batch was executed."));
|
|
2074
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2075
|
+
level: "warn",
|
|
2076
|
+
component: "engine",
|
|
2077
|
+
event: "engine.approval_mixed_batch_rejected",
|
|
2078
|
+
message: "protected tool batch rejected before every handler",
|
|
2079
|
+
meta: { toolCallCount: result.toolCalls.length, protectedToolName: protectedCall.call.name },
|
|
2080
|
+
});
|
|
2081
|
+
continue;
|
|
775
2082
|
}
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
}
|
|
789
|
-
if (decision !== "confirmed") {
|
|
790
|
-
const cancelled = "Action cancelled by user.";
|
|
791
|
-
callbacks.onToolStart(tc.name, args);
|
|
792
|
-
callbacks.onToolEnd(tc.name, argSummary, false);
|
|
793
|
-
messages.push({ role: "tool", tool_call_id: tc.id, content: cancelled });
|
|
794
|
-
providerRuntime.appendToolOutput(tc.id, cancelled);
|
|
2083
|
+
if (protectedCall && protectedCall.policy.kind === "required") {
|
|
2084
|
+
if (!options?.approvalCoordinator) {
|
|
2085
|
+
streamCallbackBuffer?.discard();
|
|
2086
|
+
const rejection = "rejected: this protected tool requires approval, but the approval coordinator is unavailable; the handler was not invoked.";
|
|
2087
|
+
rejectToolBatch(msg, [rejection]);
|
|
2088
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2089
|
+
level: "warn",
|
|
2090
|
+
component: "engine",
|
|
2091
|
+
event: "engine.approval_coordinator_unavailable",
|
|
2092
|
+
message: "protected tool failed closed before handler execution",
|
|
2093
|
+
meta: { toolName: protectedCall.call.name, toolCallId: protectedCall.call.id },
|
|
2094
|
+
});
|
|
795
2095
|
continue;
|
|
796
2096
|
}
|
|
2097
|
+
streamCallbackBuffer?.discard();
|
|
2098
|
+
const toolDigest = (0, tool_approval_1.digestApprovalToolDefinition)((0, tools_1.resolveToolDefinition)(protectedCall.call.name, toolSelection), protectedCall.validated.schemaDigest, protectedCall.policy.policyId);
|
|
2099
|
+
const policyDigest = (0, tool_arguments_1.digestJson)({
|
|
2100
|
+
policyId: protectedCall.policy.policyId,
|
|
2101
|
+
actionClass: protectedCall.policy.actionClass,
|
|
2102
|
+
classification: "required",
|
|
2103
|
+
});
|
|
2104
|
+
const committed = await options.approvalCoordinator.propose({
|
|
2105
|
+
toolCall: structuredClone(msg.tool_calls[0]),
|
|
2106
|
+
arguments: structuredClone(protectedCall.validated.arguments),
|
|
2107
|
+
preCallMessages,
|
|
2108
|
+
frozenAssistantMessage: structuredClone(msg),
|
|
2109
|
+
schemaDigest: protectedCall.validated.schemaDigest,
|
|
2110
|
+
toolDigest,
|
|
2111
|
+
policyDigest,
|
|
2112
|
+
policyId: protectedCall.policy.policyId,
|
|
2113
|
+
actionClass: protectedCall.policy.actionClass,
|
|
2114
|
+
liveToolContext: augmentedToolContext,
|
|
2115
|
+
});
|
|
2116
|
+
pushGenerated(msg);
|
|
2117
|
+
suspension = {
|
|
2118
|
+
approvalId: committed.approvalId,
|
|
2119
|
+
toolCallId: protectedCall.call.id,
|
|
2120
|
+
checkpointDigest: committed.checkpointDigest,
|
|
2121
|
+
suspendedSessionRevision: committed.suspendedSessionRevision,
|
|
2122
|
+
};
|
|
2123
|
+
outcome = "suspended";
|
|
2124
|
+
done = true;
|
|
2125
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2126
|
+
component: "engine",
|
|
2127
|
+
event: "engine.approval_turn_suspended",
|
|
2128
|
+
message: "agent turn suspended before protected tool execution",
|
|
2129
|
+
meta: { approvalId: committed.approvalId, toolCallId: protectedCall.call.id },
|
|
2130
|
+
});
|
|
2131
|
+
continue;
|
|
797
2132
|
}
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
2133
|
+
await streamCallbackBuffer?.flush();
|
|
2134
|
+
pushGenerated(msg);
|
|
2135
|
+
// Every pre-dispatch gate accepted the complete batch.
|
|
2136
|
+
for (const tc of result.toolCalls) {
|
|
2137
|
+
if (signal?.aborted)
|
|
2138
|
+
break;
|
|
2139
|
+
const args = validatedCallArguments.get(tc);
|
|
2140
|
+
const currentEffectFingerprint = effectFingerprint(tc.name, tc.arguments, toolSelection);
|
|
2141
|
+
if (tc.name === "send_message" && args.friendId === "self") {
|
|
2142
|
+
sawSendMessageSelf = true;
|
|
2143
|
+
}
|
|
2144
|
+
if (tc.name === "speak") {
|
|
2145
|
+
// The canonical pre-batch schema gate guarantees a required string.
|
|
2146
|
+
const speakArgs = JSON.parse(tc.arguments);
|
|
2147
|
+
const speakMessage = speakArgs.message;
|
|
2148
|
+
const argSummary = (0, tools_1.summarizeArgs)("speak", { message: speakMessage }, toolSelection);
|
|
2149
|
+
callbacks.onToolStart("speak", { message: speakMessage });
|
|
2150
|
+
if (speakMessage.trim().length === 0) {
|
|
2151
|
+
const err = "speak requires a non-empty `message` string.";
|
|
2152
|
+
callbacks.onToolEnd("speak", argSummary, false);
|
|
2153
|
+
pushGenerated({ role: "tool", tool_call_id: tc.id, content: err });
|
|
2154
|
+
providerRuntime.appendToolOutput(tc.id, err);
|
|
2155
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2156
|
+
level: "warn",
|
|
2157
|
+
component: "engine",
|
|
2158
|
+
event: "engine.speak_invalid",
|
|
2159
|
+
message: "speak rejected: missing or empty message",
|
|
2160
|
+
meta: {},
|
|
2161
|
+
});
|
|
2162
|
+
continue;
|
|
2163
|
+
}
|
|
2164
|
+
callbacks.onTextChunk(speakMessage);
|
|
2165
|
+
let speakDeliveryError = null;
|
|
2166
|
+
try {
|
|
2167
|
+
await callbacks.flushNow?.();
|
|
2168
|
+
}
|
|
2169
|
+
catch (err) {
|
|
2170
|
+
speakDeliveryError = err instanceof Error ? err : new Error(String(err));
|
|
2171
|
+
}
|
|
2172
|
+
if (speakDeliveryError) {
|
|
2173
|
+
callbacks.onToolEnd("speak", argSummary, false);
|
|
2174
|
+
const failMsg = `speak delivery failed: ${speakDeliveryError.message}. the message did not reach your friend; do not assume they saw it.`;
|
|
2175
|
+
pushGenerated({ role: "tool", tool_call_id: tc.id, content: failMsg });
|
|
2176
|
+
providerRuntime.appendToolOutput(tc.id, failMsg);
|
|
2177
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2178
|
+
level: "error",
|
|
2179
|
+
component: "engine",
|
|
2180
|
+
event: "engine.speak_delivery_failed",
|
|
2181
|
+
message: "speak delivery failed",
|
|
2182
|
+
meta: { error: speakDeliveryError.message, messageLength: speakMessage.length },
|
|
2183
|
+
});
|
|
2184
|
+
continue;
|
|
2185
|
+
}
|
|
2186
|
+
callbacks.onToolEnd("speak", argSummary, true);
|
|
2187
|
+
const ack = "(spoken)";
|
|
2188
|
+
pushGenerated({ role: "tool", tool_call_id: tc.id, content: ack });
|
|
2189
|
+
providerRuntime.appendToolOutput(tc.id, ack);
|
|
2190
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2191
|
+
component: "engine",
|
|
2192
|
+
event: "engine.speak",
|
|
2193
|
+
message: "agent spoke mid-turn",
|
|
2194
|
+
meta: { messageLength: speakMessage.length },
|
|
2195
|
+
});
|
|
2196
|
+
continue;
|
|
2197
|
+
}
|
|
2198
|
+
if (tc.name === "ponder") {
|
|
2199
|
+
const parsedArgs = normalizeLegacyPonderArgs(parsePonderPayload(tc.arguments));
|
|
2200
|
+
const argSummary = (0, tools_1.summarizeArgs)(tc.name, parsedArgs, toolSelection);
|
|
2201
|
+
callbacks.onToolStart(tc.name, parsedArgs);
|
|
2202
|
+
let toolResult;
|
|
2203
|
+
let success = false;
|
|
2204
|
+
try {
|
|
2205
|
+
const action = parsedArgs.action ?? "create";
|
|
2206
|
+
const currentSession = augmentedToolContext?.currentSession;
|
|
2207
|
+
const currentOrigin = currentSession
|
|
2208
|
+
? { friendId: currentSession.friendId, channel: currentSession.channel, key: currentSession.key }
|
|
2209
|
+
: undefined;
|
|
2210
|
+
const isInnerChannel = currentOrigin?.friendId === "self" && currentOrigin?.channel === "inner";
|
|
2211
|
+
const shouldCreateReturnObligation = !!currentOrigin && !isInnerChannel;
|
|
2212
|
+
const attentionQueue = augmentedToolContext?.delegatedOrigins ?? [];
|
|
2213
|
+
const successCriteria = parseSuccessCriteria(parsedArgs.success_criteria);
|
|
2214
|
+
const payload = parsePacketPayload(parsedArgs.payload_json);
|
|
2215
|
+
let packet;
|
|
2216
|
+
let returnObligationId = null;
|
|
2217
|
+
let resultAction = "created";
|
|
2218
|
+
let privateReturnSourceRequest = "";
|
|
2219
|
+
if (action === "create") {
|
|
2220
|
+
if (isInnerChannel && attentionQueue.length > 0) {
|
|
2221
|
+
throw new Error("private runtime already has held return work in the attention queue; surface the existing delegationId instead of creating a replacement ponder packet.");
|
|
2222
|
+
}
|
|
2223
|
+
const kind = parsedArgs.kind;
|
|
2224
|
+
const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
|
|
2225
|
+
const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
|
|
2226
|
+
const sourceRequest = currentOrigin && !isInnerChannel ? latestUserMessageText(messages) : "";
|
|
2227
|
+
privateReturnSourceRequest = sourceRequest;
|
|
2228
|
+
if (!kind || !objective || !successCriteria || !payload) {
|
|
2229
|
+
throw new Error("ponder create requires kind, objective, success_criteria, and valid payload_json.");
|
|
2230
|
+
}
|
|
2231
|
+
const packetPayload = sourceRequest
|
|
2232
|
+
? { ...payload, sourceRequest }
|
|
2233
|
+
: payload;
|
|
2234
|
+
const createLinkedReturnObligation = (id, packetId) => {
|
|
2235
|
+
(0, obligations_1.createReturnObligation)((0, identity_2.getAgentName)(), {
|
|
2236
|
+
id,
|
|
2237
|
+
origin: currentOrigin,
|
|
2238
|
+
status: "queued",
|
|
2239
|
+
delegatedContent: buildPonderDelegatedContent({ summary, objective, sourceRequest }),
|
|
2240
|
+
packetId,
|
|
2241
|
+
createdAt: Date.now(),
|
|
2242
|
+
});
|
|
2243
|
+
};
|
|
2244
|
+
const agentRoot = (0, identity_2.getAgentRoot)();
|
|
2245
|
+
let relatedObligationId;
|
|
2246
|
+
if (currentOrigin && !isInnerChannel) {
|
|
2247
|
+
try {
|
|
2248
|
+
const obligation = (0, obligations_1.createObligation)(agentRoot, {
|
|
2249
|
+
origin: currentOrigin,
|
|
2250
|
+
content: objective,
|
|
2251
|
+
});
|
|
2252
|
+
relatedObligationId = obligation.id;
|
|
2253
|
+
}
|
|
2254
|
+
catch {
|
|
2255
|
+
relatedObligationId = undefined;
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
const frictionSignature = kind === "harness_friction" && typeof packetPayload.frictionSignature === "string"
|
|
2259
|
+
? packetPayload.frictionSignature
|
|
2260
|
+
: null;
|
|
2261
|
+
const existing = frictionSignature && currentOrigin
|
|
2262
|
+
? (0, packets_1.findHarnessFrictionPacket)(agentRoot, currentOrigin, frictionSignature)
|
|
2263
|
+
: null;
|
|
2264
|
+
if (existing) {
|
|
2265
|
+
resultAction = "revised";
|
|
2266
|
+
const existingActiveReturnId = shouldCreateReturnObligation
|
|
2267
|
+
? activeReturnObligationId((0, identity_2.getAgentName)(), existing.relatedReturnObligationId)
|
|
2268
|
+
: null;
|
|
2269
|
+
returnObligationId = existingActiveReturnId
|
|
2270
|
+
?? (shouldCreateReturnObligation ? (0, obligations_1.generateObligationId)(Date.now()) : null);
|
|
2271
|
+
packet = existing.status === "drafting"
|
|
2272
|
+
? (0, packets_1.revisePonderPacket)(agentRoot, existing.id, {
|
|
2273
|
+
kind,
|
|
2274
|
+
objective,
|
|
2275
|
+
summary,
|
|
2276
|
+
successCriteria,
|
|
2277
|
+
payload: packetPayload,
|
|
2278
|
+
})
|
|
2279
|
+
: existing;
|
|
2280
|
+
if (returnObligationId && returnObligationId !== existing.relatedReturnObligationId) {
|
|
2281
|
+
packet = (0, packets_1.advancePonderPacket)(agentRoot, packet.id, { relatedReturnObligationId: returnObligationId });
|
|
2282
|
+
createLinkedReturnObligation(returnObligationId, packet.id);
|
|
2283
|
+
}
|
|
2284
|
+
}
|
|
2285
|
+
else {
|
|
2286
|
+
returnObligationId = shouldCreateReturnObligation ? (0, obligations_1.generateObligationId)(Date.now()) : null;
|
|
2287
|
+
packet = (0, packets_1.createPonderPacket)(agentRoot, {
|
|
2288
|
+
kind,
|
|
2289
|
+
objective,
|
|
2290
|
+
summary,
|
|
2291
|
+
successCriteria,
|
|
2292
|
+
...(currentOrigin ? { origin: currentOrigin } : {}),
|
|
2293
|
+
...(relatedObligationId ? { relatedObligationId } : {}),
|
|
2294
|
+
...(returnObligationId ? { relatedReturnObligationId: returnObligationId } : {}),
|
|
2295
|
+
...(parsedArgs.follows_packet_id ? { followsPacketId: parsedArgs.follows_packet_id } : {}),
|
|
2296
|
+
payload: packetPayload,
|
|
2297
|
+
});
|
|
2298
|
+
if (returnObligationId) {
|
|
2299
|
+
createLinkedReturnObligation(returnObligationId, packet.id);
|
|
2300
|
+
}
|
|
2301
|
+
}
|
|
2302
|
+
}
|
|
2303
|
+
else {
|
|
2304
|
+
const packetId = typeof parsedArgs.packet_id === "string" ? parsedArgs.packet_id.trim() : "";
|
|
2305
|
+
const kind = parsedArgs.kind;
|
|
2306
|
+
const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
|
|
2307
|
+
const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
|
|
2308
|
+
if (!packetId || !kind || !objective || !successCriteria || !payload) {
|
|
2309
|
+
throw new Error("ponder revise requires packet_id, kind, objective, success_criteria, and valid payload_json.");
|
|
2310
|
+
}
|
|
2311
|
+
packet = (0, packets_1.revisePonderPacket)((0, identity_2.getAgentRoot)(), packetId, {
|
|
2312
|
+
kind,
|
|
2313
|
+
objective,
|
|
2314
|
+
summary,
|
|
2315
|
+
successCriteria,
|
|
2316
|
+
payload,
|
|
2317
|
+
});
|
|
2318
|
+
returnObligationId = packet.relatedReturnObligationId
|
|
2319
|
+
&& !(packet.origin?.friendId === "self" && packet.origin.channel === "inner")
|
|
2320
|
+
? packet.relatedReturnObligationId
|
|
2321
|
+
: null;
|
|
2322
|
+
resultAction = "revised";
|
|
2323
|
+
}
|
|
2324
|
+
if (returnObligationId) {
|
|
2325
|
+
for (const token of extractPrivateReturnHeldTokens(privateReturnSourceRequest)) {
|
|
2326
|
+
privateReturnHeldTokens.add(token);
|
|
2327
|
+
}
|
|
2328
|
+
const agentName = (0, identity_2.getAgentName)();
|
|
2329
|
+
await (0, socket_client_1.requestPrivateWake)(agentName, augmentedToolContext?.daemonSocketPath, buildPonderReturnPrivateWakeOptions({ agentName, packet, returnObligationId })).catch(() => undefined);
|
|
2330
|
+
}
|
|
2331
|
+
sawPonder = true;
|
|
2332
|
+
toolResult = buildPonderResult(packet, resultAction, returnObligationId);
|
|
2333
|
+
success = true;
|
|
2334
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2335
|
+
component: "engine",
|
|
2336
|
+
event: "engine.ponder_packet",
|
|
2337
|
+
message: "ponder packet touched",
|
|
2338
|
+
meta: {
|
|
2339
|
+
action: resultAction,
|
|
2340
|
+
packetId: packet.id,
|
|
2341
|
+
kind: packet.kind,
|
|
2342
|
+
status: packet.status,
|
|
2343
|
+
},
|
|
2344
|
+
});
|
|
2345
|
+
}
|
|
2346
|
+
catch (error) {
|
|
2347
|
+
toolResult = error instanceof Error ? error.message : String(error);
|
|
2348
|
+
}
|
|
2349
|
+
callbacks.onToolEnd(tc.name, argSummary, success);
|
|
2350
|
+
pushGenerated({ role: "tool", tool_call_id: tc.id, content: toolResult });
|
|
2351
|
+
providerRuntime.appendToolOutput(tc.id, toolResult);
|
|
2352
|
+
continue;
|
|
2353
|
+
}
|
|
2354
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
2355
|
+
if (tc.name === "query_session")
|
|
2356
|
+
sawQuerySession = true;
|
|
2357
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
2358
|
+
if (tc.name === "bridge_manage")
|
|
2359
|
+
sawBridgeManage = true;
|
|
2360
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
2361
|
+
if (isExternalStateQuery(tc.name, args))
|
|
2362
|
+
sawExternalStateQuery = true;
|
|
2363
|
+
callbacks.onToolStart(tc.name, args);
|
|
2364
|
+
let toolResult;
|
|
2365
|
+
let success;
|
|
2366
|
+
let invoked = false;
|
|
2367
|
+
try {
|
|
2368
|
+
const routineActionSelection = approvalCalls.find((entry) => entry.call.id === tc.id)?.routineActionSelection;
|
|
2369
|
+
const executionToolContext = routineActionSelection && augmentedToolContext ? { ...augmentedToolContext, routineActionSelection } : augmentedToolContext;
|
|
2370
|
+
if (options?.execTool && !relationship) {
|
|
2371
|
+
invoked = true;
|
|
2372
|
+
toolResult = await options.execTool(tc.name, args, trustedToolContext);
|
|
2373
|
+
success = true;
|
|
2374
|
+
}
|
|
2375
|
+
else {
|
|
2376
|
+
const execution = await (0, tools_1.executeTool)(tc.name, args, executionToolContext, options?.execTool);
|
|
2377
|
+
invoked = execution.kind !== "rejected_before_handler";
|
|
2378
|
+
success = execution.kind === "handler_succeeded";
|
|
2379
|
+
toolResult = "error" in execution ? `error: ${execution.error}` : execution.text;
|
|
2380
|
+
}
|
|
2381
|
+
}
|
|
2382
|
+
catch (e) {
|
|
2383
|
+
toolResult = `error: ${e}`;
|
|
2384
|
+
success = false;
|
|
2385
|
+
}
|
|
2386
|
+
if (invoked && requiredToolCallNames.includes(tc.name) && !options?.requiredToolCalls?.requireSuccessfulResults)
|
|
2387
|
+
dispatchedRequiredToolCalls.add(tc.name);
|
|
2388
|
+
const modelResult = (0, tool_friction_1.rewriteToolResultForModel)(tc.name, toolResult, toolFrictionLedger);
|
|
2389
|
+
pushGenerated({ role: "tool", tool_call_id: tc.id, content: modelResult });
|
|
2390
|
+
providerRuntime.appendToolOutput(tc.id, modelResult);
|
|
2391
|
+
if (!success)
|
|
2392
|
+
augmentedToolContext?.habitSession?.recordError?.(toolResult);
|
|
2393
|
+
const validatedRequiredResult = success && requiredToolCallNames.includes(tc.name) && options?.requiredToolCalls?.requireSuccessfulResults
|
|
2394
|
+
? requiredToolResultSucceeded(tc.name, toolResult, args, options.requiredToolCalls.validateRequiredToolResult)
|
|
2395
|
+
: false;
|
|
2396
|
+
if (validatedRequiredResult) {
|
|
2397
|
+
dispatchedRequiredToolCalls.add(tc.name);
|
|
2398
|
+
for (const requiredName of options?.requiredToolCalls?.requiredToolCallsAfterResult?.(tc.name, args, toolResult) ?? []) {
|
|
2399
|
+
if (!candidateToolNames.has(requiredName)) {
|
|
2400
|
+
(0, runtime_1.emitNervesEvent)({ level: "error", component: "engine", event: "engine.required_tool_unadvertised", message: "dependent required tool is not advertised for the active channel", meta: { toolName: requiredName, channel: String(channel) } });
|
|
2401
|
+
throw new Error(`dependent required tool is not advertised for this channel: ${requiredName}`);
|
|
2402
|
+
}
|
|
2403
|
+
if (!requiredToolCallNames.includes(requiredName))
|
|
2404
|
+
requiredToolCallNames.push(requiredName);
|
|
2405
|
+
}
|
|
2406
|
+
}
|
|
2407
|
+
if (success && currentEffectFingerprint && !toolResultIndicatesFailure(toolResult)) {
|
|
2408
|
+
unresolvedHistoricalEffects = unresolvedHistoricalEffects.filter((effect) => effect.fingerprint !== currentEffectFingerprint);
|
|
2409
|
+
}
|
|
2410
|
+
const resolvedRiskProfile = (0, tools_1.resolveToolDefinition)(tc.name, toolSelection)?.riskProfile;
|
|
2411
|
+
const toolRiskProfile = typeof resolvedRiskProfile === "function" ? resolvedRiskProfile(args) : resolvedRiskProfile;
|
|
2412
|
+
options?.toolBoundaryObserver?.({
|
|
2413
|
+
name: tc.name,
|
|
2414
|
+
reason: "dispatched",
|
|
2415
|
+
globallyResolvable: typeof (0, tools_1.resolveToolDefinition)(tc.name, toolSelection)?.handler === "function",
|
|
2416
|
+
invoked,
|
|
2417
|
+
sideEffect: success && toolRiskProfile?.mutates !== "none",
|
|
2418
|
+
});
|
|
2419
|
+
(0, tool_loop_1.recordToolOutcome)(toolLoopState, tc.name, args, modelResult, success);
|
|
2420
|
+
callbacks.onToolEnd(tc.name, (0, tools_1.buildToolResultSummary)(tc.name, args, modelResult, success, toolSelection), success);
|
|
2421
|
+
callbacks.onToolResult?.(messages);
|
|
809
2422
|
}
|
|
810
|
-
callbacks.onToolEnd(tc.name, argSummary, success);
|
|
811
|
-
messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
|
|
812
|
-
providerRuntime.appendToolOutput(tc.id, toolResult);
|
|
813
2423
|
}
|
|
814
2424
|
}
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
outcome = "aborted";
|
|
821
|
-
break;
|
|
822
|
-
}
|
|
823
|
-
// Context overflow: trim aggressively and retry once
|
|
824
|
-
if (isContextOverflow(e) && !overflowRetried) {
|
|
825
|
-
overflowRetried = true;
|
|
826
|
-
stripLastToolCalls(messages);
|
|
827
|
-
const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
|
|
828
|
-
const trimmed = (0, context_1.trimMessages)(messages, maxTokens, contextMargin, maxTokens * 2);
|
|
829
|
-
messages.splice(0, messages.length, ...trimmed);
|
|
830
|
-
providerRuntime.resetTurnState(messages);
|
|
831
|
-
callbacks.onError(new Error("context trimmed, retrying..."), "transient");
|
|
832
|
-
continue;
|
|
833
|
-
}
|
|
834
|
-
// Transient errors: retry with exponential backoff
|
|
835
|
-
if (isTransientError(e) && retryCount < MAX_RETRIES) {
|
|
836
|
-
retryCount++;
|
|
837
|
-
const delay = RETRY_BASE_MS * Math.pow(2, retryCount - 1);
|
|
838
|
-
const cause = classifyTransientError(e);
|
|
839
|
-
callbacks.onError(new Error(`${cause}, retrying in ${delay / 1000}s (${retryCount}/${MAX_RETRIES})...`), "transient");
|
|
840
|
-
// Wait with abort support
|
|
841
|
-
const aborted = await new Promise((resolve) => {
|
|
842
|
-
const timer = setTimeout(() => resolve(false), delay);
|
|
843
|
-
if (signal) {
|
|
844
|
-
const onAbort = () => { clearTimeout(timer); resolve(true); };
|
|
845
|
-
if (signal.aborted) {
|
|
846
|
-
clearTimeout(timer);
|
|
847
|
-
resolve(true);
|
|
848
|
-
return;
|
|
849
|
-
}
|
|
850
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
851
|
-
}
|
|
852
|
-
});
|
|
853
|
-
if (aborted) {
|
|
854
|
-
stripLastToolCalls(messages);
|
|
2425
|
+
catch (e) {
|
|
2426
|
+
// Abort is not an error — just stop cleanly
|
|
2427
|
+
if (e instanceof provider_attempt_1.ProviderAttemptAbortError || signal?.aborted) {
|
|
2428
|
+
if (generatedMessages.length === 0)
|
|
2429
|
+
stripLastToolCalls(messages);
|
|
855
2430
|
outcome = "aborted";
|
|
856
2431
|
break;
|
|
857
2432
|
}
|
|
858
|
-
|
|
859
|
-
|
|
2433
|
+
const errorForClassification = e instanceof Error ? e : /* v8 ignore next -- defensive @preserve */ new Error(String(e));
|
|
2434
|
+
let providerClassification;
|
|
2435
|
+
try {
|
|
2436
|
+
providerClassification = providerRuntime.classifyError(errorForClassification);
|
|
2437
|
+
}
|
|
2438
|
+
catch {
|
|
2439
|
+
/* v8 ignore next -- defensive: classifyError should not throw @preserve */
|
|
2440
|
+
providerClassification = "unknown";
|
|
2441
|
+
}
|
|
2442
|
+
finishTerminalProviderError(errorForClassification, providerClassification);
|
|
860
2443
|
}
|
|
861
|
-
callbacks.onError(e instanceof Error ? e : new Error(String(e)), "terminal");
|
|
862
|
-
(0, runtime_1.emitNervesEvent)({
|
|
863
|
-
level: "error",
|
|
864
|
-
event: "engine.error",
|
|
865
|
-
trace_id: traceId,
|
|
866
|
-
component: "engine",
|
|
867
|
-
message: e instanceof Error ? e.message : String(e),
|
|
868
|
-
meta: {},
|
|
869
|
-
});
|
|
870
|
-
stripLastToolCalls(messages);
|
|
871
|
-
outcome = "errored";
|
|
872
|
-
done = true;
|
|
873
2444
|
}
|
|
874
2445
|
}
|
|
2446
|
+
catch (error) {
|
|
2447
|
+
if (!(error instanceof tools_1.ToolSelectionError))
|
|
2448
|
+
throw error;
|
|
2449
|
+
finishTerminalProviderError(error, "unknown");
|
|
2450
|
+
}
|
|
2451
|
+
finally {
|
|
2452
|
+
nextAttemptControls = [];
|
|
2453
|
+
rejectedAttempt = [];
|
|
2454
|
+
providerRuntime.resetTurnState(messages);
|
|
2455
|
+
}
|
|
2456
|
+
options?.captureGeneratedMessages?.(structuredClone(generatedMessages));
|
|
875
2457
|
(0, runtime_1.emitNervesEvent)({
|
|
876
2458
|
event: "engine.turn_end",
|
|
877
2459
|
trace_id: traceId,
|
|
878
2460
|
component: "engine",
|
|
879
2461
|
message: "runAgent turn completed",
|
|
880
|
-
meta: { done,
|
|
2462
|
+
meta: { done, sawPonder, sawQuerySession, sawBridgeManage },
|
|
881
2463
|
});
|
|
882
|
-
return {
|
|
2464
|
+
return {
|
|
2465
|
+
usage: lastUsage,
|
|
2466
|
+
outcome,
|
|
2467
|
+
completion,
|
|
2468
|
+
...(suspension ? { suspension } : {}),
|
|
2469
|
+
...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
|
|
2470
|
+
};
|
|
883
2471
|
}
|