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