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