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