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