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