@ouro.bot/cli 0.1.0-alpha.75 → 0.1.0-alpha.750
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 +4812 -16
- package/deploy/unraid/Dockerfile +48 -0
- package/deploy/unraid/README.txt +2373 -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 +178 -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 +16 -0
- package/dist/heart/attachments/store.js +103 -0
- package/dist/heart/attachments/types.js +93 -0
- package/dist/heart/auth/auth-flow.js +495 -0
- package/dist/heart/autonomy-budget.js +477 -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 +1761 -456
- 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 -2144
- 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 +1050 -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 +379 -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 +317 -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 +507 -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 +88 -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 +460 -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 +371 -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-layout.js +100 -0
- package/dist/senses/cli.js +621 -321
- 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 +774 -0
- package/dist/senses/private-runtime.js +1459 -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-runtime.js +240 -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 +695 -0
- package/dist/senses/telegram-approval-runtime.js +566 -0
- package/dist/senses/telegram-audit-ledger.js +220 -0
- package/dist/senses/telegram-client.js +1635 -0
- package/dist/senses/telegram-effect-adapter.js +787 -0
- package/dist/senses/telegram-entry.js +83 -0
- package/dist/senses/telegram.js +1914 -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,510 @@ 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
|
-
Object.defineProperty(exports, "toResponsesTools", { enumerable: true, get: function () { return streaming_1.toResponsesTools; } });
|
|
167
|
-
// Re-export prompt functions for backward compat
|
|
168
|
-
var prompt_2 = require("../mind/prompt");
|
|
169
|
-
Object.defineProperty(exports, "buildSystem", { enumerable: true, get: function () { return prompt_2.buildSystem; } });
|
|
170
|
-
const DELEGATION_REASON_PROSE_HANDOFF = {
|
|
171
|
-
explicit_reflection: "something in the conversation called for reflection",
|
|
172
|
-
cross_session: "this touches other conversations",
|
|
173
|
-
bridge_state: "there's shared work spanning sessions",
|
|
174
|
-
task_state: "there are active tasks that relate to this",
|
|
175
|
-
non_fast_path_tool: "this needs tools beyond a simple reply",
|
|
176
|
-
unresolved_obligation: "there's an unresolved commitment from an earlier conversation",
|
|
177
|
-
};
|
|
178
|
-
function buildGoInwardHandoffPacket(params) {
|
|
179
|
-
const reasons = params.delegationDecision?.reasons ?? [];
|
|
180
|
-
const reasonProse = reasons.length > 0
|
|
181
|
-
? reasons.map((r) => DELEGATION_REASON_PROSE_HANDOFF[r]).join("; ")
|
|
182
|
-
: "this felt like it needed more thought";
|
|
183
|
-
const returnAddress = params.currentSession
|
|
184
|
-
? `${params.currentSession.friendId}/${params.currentSession.channel}/${params.currentSession.key}`
|
|
185
|
-
: "no specific return -- just thinking";
|
|
186
|
-
let obligationLine;
|
|
187
|
-
if (params.outwardClosureRequired && params.currentSession) {
|
|
188
|
-
obligationLine = `i need to come back to ${params.currentSession.friendId} with something`;
|
|
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 }); };
|
|
189
237
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
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) };
|
|
215
305
|
}
|
|
216
|
-
|
|
217
|
-
|
|
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;
|
|
218
369
|
}
|
|
219
|
-
|
|
220
|
-
const rawIntent = parsed.intent;
|
|
221
|
-
const intent = rawIntent === "complete" || rawIntent === "blocked" || rawIntent === "direct_reply"
|
|
222
|
-
? rawIntent
|
|
223
|
-
: undefined;
|
|
224
|
-
return { answer, intent };
|
|
370
|
+
out = out.slice(0, open) + out.slice(close + "</think>".length);
|
|
225
371
|
}
|
|
226
|
-
|
|
227
|
-
|
|
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
|
+
});
|
|
228
407
|
}
|
|
229
408
|
}
|
|
230
|
-
function
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
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
|
+
},
|
|
240
477
|
},
|
|
241
|
-
}
|
|
242
|
-
|
|
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.",
|
|
487
|
+
};
|
|
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;
|
|
521
|
+
}
|
|
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
|
+
}
|
|
560
|
+
function latestUserMessageText(messages) {
|
|
561
|
+
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
|
562
|
+
const message = messages[i];
|
|
563
|
+
if (message?.role !== "user")
|
|
564
|
+
continue;
|
|
565
|
+
const text = messageContentText(message.content).trim();
|
|
566
|
+
if (isHarnessCorrectiveUserText(text))
|
|
567
|
+
continue;
|
|
568
|
+
if (text.length > 0)
|
|
569
|
+
return text;
|
|
243
570
|
}
|
|
571
|
+
return "";
|
|
572
|
+
}
|
|
573
|
+
function truncatePonderDelegatedContent(value) {
|
|
574
|
+
return value.length > 120 ? `${value.slice(0, 117)}...` : value;
|
|
575
|
+
}
|
|
576
|
+
function buildPonderDelegatedContent(input) {
|
|
577
|
+
const primary = (input.summary || input.objective).trim();
|
|
578
|
+
const sourceRequest = input.sourceRequest.trim();
|
|
579
|
+
if (!sourceRequest || sourceRequest === primary || sourceRequest === input.objective.trim()) {
|
|
580
|
+
return truncatePonderDelegatedContent(primary);
|
|
581
|
+
}
|
|
582
|
+
return truncatePonderDelegatedContent(`${primary}\nsource request: ${sourceRequest}`);
|
|
583
|
+
}
|
|
584
|
+
function looksLikePrivateReturnRequest(text) {
|
|
585
|
+
const normalized = text.toLowerCase();
|
|
586
|
+
return /\b(private|privately|private-attention|think|reflect|reflection)\b/.test(normalized)
|
|
587
|
+
&& /\b(return|bring back|come back|surface|report back)\b/.test(normalized);
|
|
588
|
+
}
|
|
589
|
+
function extractPrivateReturnHeldTokens(text) {
|
|
590
|
+
const tokens = new Set();
|
|
591
|
+
for (const match of text.matchAll(/\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+){2,}\b/g)) {
|
|
592
|
+
const token = match[0];
|
|
593
|
+
if (token.length >= 8)
|
|
594
|
+
tokens.add(token);
|
|
595
|
+
}
|
|
596
|
+
return [...tokens];
|
|
597
|
+
}
|
|
598
|
+
function privateReturnAckLeakError(answer, heldTokens) {
|
|
599
|
+
if (!answer || heldTokens.size === 0)
|
|
600
|
+
return null;
|
|
601
|
+
for (const token of heldTokens) {
|
|
602
|
+
if (answer.includes(token)) {
|
|
603
|
+
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.";
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
return null;
|
|
607
|
+
}
|
|
608
|
+
function claimsPrivateReturnQueued(answer) {
|
|
609
|
+
if (!answer)
|
|
610
|
+
return false;
|
|
611
|
+
const normalized = answer.toLowerCase();
|
|
612
|
+
return /\b(queued|queue|will return|return when|when .*complete|when .*completes|private pass|private runtime completes|inner dialog completes|later)\b/.test(normalized)
|
|
613
|
+
&& /\b(private|inner|return|queued|later)\b/.test(normalized);
|
|
614
|
+
}
|
|
615
|
+
function privateReturnMissingPonderError(input) {
|
|
616
|
+
if (input.sawPonder)
|
|
617
|
+
return null;
|
|
618
|
+
if (!looksLikePrivateReturnRequest(input.latestUserRequest))
|
|
619
|
+
return null;
|
|
620
|
+
if (!claimsPrivateReturnQueued(input.answer))
|
|
621
|
+
return null;
|
|
622
|
+
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.";
|
|
623
|
+
}
|
|
624
|
+
function activeReturnObligationId(agentName, obligationId) {
|
|
625
|
+
if (!obligationId)
|
|
626
|
+
return null;
|
|
627
|
+
const obligation = (0, obligations_1.readReturnObligation)(agentName, obligationId);
|
|
628
|
+
return obligation?.status === "queued" || obligation?.status === "running" ? obligationId : null;
|
|
629
|
+
}
|
|
630
|
+
function ponderReturnSessionId(packet) {
|
|
631
|
+
const origin = packet.origin;
|
|
632
|
+
if (!origin)
|
|
633
|
+
return "unknown/unknown/unknown";
|
|
634
|
+
return `${origin.friendId}/${origin.channel}/${origin.key}`;
|
|
635
|
+
}
|
|
636
|
+
function buildPonderReturnPrivateWakeOptions(input) {
|
|
637
|
+
const sessionId = ponderReturnSessionId(input.packet);
|
|
638
|
+
return {
|
|
639
|
+
reason: "ponder return obligation private attention",
|
|
640
|
+
triggerSource: "ponder-return-obligation",
|
|
641
|
+
budgetClass: "interactive",
|
|
642
|
+
idempotencyKey: `ponder-return:${input.agentName}:${input.returnObligationId}:${input.packet.id}:${sessionId}`,
|
|
643
|
+
originRefs: [
|
|
644
|
+
{ kind: "tool", id: "ponder" },
|
|
645
|
+
{ kind: "ponder-packet", id: input.packet.id },
|
|
646
|
+
{ kind: "return-obligation", id: input.returnObligationId },
|
|
647
|
+
{ kind: "session", id: sessionId },
|
|
648
|
+
],
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
function buildPonderResult(packet, action, returnObligationId) {
|
|
652
|
+
return JSON.stringify({
|
|
653
|
+
ok: true,
|
|
654
|
+
packet_id: packet.id,
|
|
655
|
+
action,
|
|
656
|
+
status: packet.status,
|
|
657
|
+
return_obligation_id: returnObligationId,
|
|
658
|
+
private_return_contract: returnObligationId
|
|
659
|
+
? "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."
|
|
660
|
+
: null,
|
|
661
|
+
}, null, 2);
|
|
662
|
+
}
|
|
663
|
+
/** Returns true when a tool call queries external state (GitHub, npm registry). */
|
|
664
|
+
function isExternalStateQuery(toolName, args) {
|
|
665
|
+
if (toolName !== "shell")
|
|
666
|
+
return false;
|
|
667
|
+
const cmd = String(args.command ?? "");
|
|
668
|
+
return /\bgh\s+(pr|run|api|issue)\b/.test(cmd) || /\bnpm\s+(view|info|show)\b/.test(cmd);
|
|
669
|
+
}
|
|
670
|
+
function getSettleRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp, _delegationDecision, sawSendMessageSelf, sawPonder, _sawQuerySession, currentObligation, innerJob, _sawExternalStateQuery) {
|
|
671
|
+
// Delegation adherence removed: the delegation decision is surfaced in the
|
|
672
|
+
// system prompt as a suggestion. Hard-gating settle caused infinite
|
|
673
|
+
// rejection loops where the agent couldn't respond to the user at all.
|
|
674
|
+
// The agent is free to follow or ignore the delegation hint.
|
|
244
675
|
// 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
|
|
676
|
+
if (innerJob?.obligationStatus === "pending" && !sawSendMessageSelf && !sawPonder) {
|
|
677
|
+
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
678
|
}
|
|
248
679
|
// 3. mustResolveBeforeHandoff + missing intent
|
|
249
680
|
if (mustResolveBeforeHandoff && !intent) {
|
|
250
|
-
return "your
|
|
681
|
+
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
682
|
}
|
|
252
683
|
// 4. mustResolveBeforeHandoff + direct_reply without follow-up
|
|
253
684
|
if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
|
|
254
|
-
return "your
|
|
685
|
+
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.";
|
|
686
|
+
}
|
|
687
|
+
// 5. mustResolveBeforeHandoff + complete while a live return loop is still active
|
|
688
|
+
if (mustResolveBeforeHandoff && intent === "complete" && currentObligation && !sawSteeringFollowUp) {
|
|
689
|
+
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
690
|
}
|
|
256
|
-
|
|
257
|
-
return "your final_answer was incomplete or malformed. call final_answer again with your complete response.";
|
|
691
|
+
return null;
|
|
258
692
|
}
|
|
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) {
|
|
693
|
+
function upsertSystemPrompt(messages, systemText, protectedSystemMessages = []) {
|
|
263
694
|
const systemMessage = { role: "system", content: systemText };
|
|
264
|
-
|
|
695
|
+
const protectedMessages = new Set(protectedSystemMessages.filter((message) => message.role === "system"));
|
|
696
|
+
if (messages[0]?.role === "system" && !protectedMessages.has(messages[0])) {
|
|
265
697
|
messages[0] = systemMessage;
|
|
266
698
|
}
|
|
267
699
|
else {
|
|
268
700
|
messages.unshift(systemMessage);
|
|
269
701
|
}
|
|
270
702
|
}
|
|
703
|
+
/**
|
|
704
|
+
* A prompt refresh failure must not revive any generated text from an older
|
|
705
|
+
* turn or release. Even the nominally stable region contains actor-scoped trust,
|
|
706
|
+
* tool, and channel context, so it is not safe to reconstruct. Fail closed to a
|
|
707
|
+
* neutral base and put the freshly derived trigger first.
|
|
708
|
+
*/
|
|
709
|
+
function repairFallbackSystemPrompt(orientationFrame) {
|
|
710
|
+
return `${(0, orientation_frame_1.renderOrientationFrame)(orientationFrame)}\n\nYou are a helpful assistant.`;
|
|
711
|
+
}
|
|
271
712
|
// Remove orphan tool_calls from the last assistant message and any
|
|
272
713
|
// trailing tool-result messages that lack a matching tool_call.
|
|
273
714
|
// This keeps the conversation valid after an abort or tool-loop limit.
|
|
@@ -296,27 +737,39 @@ const TOOL_SCAN_BOUNDARY_ROLES = new Set(["assistant", "user"]);
|
|
|
296
737
|
// 1. If an assistant message has tool_calls but missing tool results, inject synthetic error results.
|
|
297
738
|
// 2. If a tool result's tool_call_id doesn't match any tool_calls in a preceding assistant message, remove it.
|
|
298
739
|
// This prevents 400 errors from the API after an aborted turn.
|
|
740
|
+
//
|
|
741
|
+
// Position-aware: a tool result is orphaned when its tool_call_id hasn't been
|
|
742
|
+
// defined by an assistant message AT THIS POSITION yet. MiniMax-M2.7 reuses
|
|
743
|
+
// canonical tool_call_ids across turns, so the global-set check that this
|
|
744
|
+
// function used previously kept misordered tool results that MiniMax then
|
|
745
|
+
// rejected with error 2013 ("tool result's tool id not found"). Walking
|
|
746
|
+
// in order matches what MiniMax actually enforces.
|
|
299
747
|
function repairOrphanedToolCalls(messages) {
|
|
300
|
-
// Pass 1:
|
|
301
|
-
|
|
302
|
-
|
|
748
|
+
// Pass 1: walk in order, accumulate seen tool_call_ids per-position, and
|
|
749
|
+
// mark tool results for removal if their id hasn't been defined yet.
|
|
750
|
+
const seenCallIds = new Set();
|
|
751
|
+
const removeIndices = [];
|
|
752
|
+
for (let i = 0; i < messages.length; i++) {
|
|
753
|
+
const msg = messages[i];
|
|
303
754
|
if (msg.role === "assistant") {
|
|
304
755
|
const asst = msg;
|
|
305
756
|
if (asst.tool_calls) {
|
|
306
757
|
for (const tc of asst.tool_calls)
|
|
307
|
-
|
|
758
|
+
seenCallIds.add(tc.id);
|
|
308
759
|
}
|
|
760
|
+
continue;
|
|
309
761
|
}
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
const toolMsg = messages[i];
|
|
315
|
-
if (!validCallIds.has(toolMsg.tool_call_id)) {
|
|
316
|
-
messages.splice(i, 1);
|
|
762
|
+
if (msg.role === "tool") {
|
|
763
|
+
const toolMsg = msg;
|
|
764
|
+
if (!seenCallIds.has(toolMsg.tool_call_id)) {
|
|
765
|
+
removeIndices.push(i);
|
|
317
766
|
}
|
|
318
767
|
}
|
|
319
768
|
}
|
|
769
|
+
// Splice from the end so earlier indices stay valid.
|
|
770
|
+
for (let i = removeIndices.length - 1; i >= 0; i--) {
|
|
771
|
+
messages.splice(removeIndices[i], 1);
|
|
772
|
+
}
|
|
320
773
|
// Pass 3: inject synthetic results for tool_calls missing their tool results
|
|
321
774
|
for (let i = 0; i < messages.length; i++) {
|
|
322
775
|
const msg = messages[i];
|
|
@@ -338,10 +791,13 @@ function repairOrphanedToolCalls(messages) {
|
|
|
338
791
|
}
|
|
339
792
|
const missing = asst.tool_calls.filter((tc) => !resultIds.has(tc.id));
|
|
340
793
|
if (missing.length > 0) {
|
|
794
|
+
// AX rule: the agent must see what happened. Don't say "interrupted"
|
|
795
|
+
// — that's vague. Tell them the result was lost, possible causes,
|
|
796
|
+
// and what to do next.
|
|
341
797
|
const syntheticResults = missing.map((tc) => ({
|
|
342
798
|
role: "tool",
|
|
343
799
|
tool_call_id: tc.id,
|
|
344
|
-
content: "error: tool call was
|
|
800
|
+
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
801
|
}));
|
|
346
802
|
let insertAt = i + 1;
|
|
347
803
|
while (insertAt < messages.length && messages[insertAt].role === "tool")
|
|
@@ -364,49 +820,72 @@ function isContextOverflow(err) {
|
|
|
364
820
|
return true;
|
|
365
821
|
return false;
|
|
366
822
|
}
|
|
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
|
-
|
|
823
|
+
const RETRY_LABELS = {
|
|
824
|
+
"auth-failure": "auth error",
|
|
825
|
+
"usage-limit": "usage limit",
|
|
826
|
+
"rate-limit": "rate limited",
|
|
827
|
+
"server-error": "server error",
|
|
828
|
+
"network-error": "network error",
|
|
829
|
+
"unknown": "error",
|
|
830
|
+
};
|
|
831
|
+
function waitForProviderRetry(delayMs, signal) {
|
|
832
|
+
if (!signal) {
|
|
833
|
+
return new Promise((resolve) => {
|
|
834
|
+
setTimeout(resolve, delayMs);
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
return new Promise((resolve, reject) => {
|
|
838
|
+
let timer;
|
|
839
|
+
const onAbort = () => {
|
|
840
|
+
clearTimeout(timer);
|
|
841
|
+
reject(new provider_attempt_1.ProviderAttemptAbortError());
|
|
842
|
+
};
|
|
843
|
+
timer = setTimeout(() => {
|
|
844
|
+
signal.removeEventListener("abort", onAbort);
|
|
845
|
+
resolve();
|
|
846
|
+
}, delayMs);
|
|
847
|
+
if (signal.aborted) {
|
|
848
|
+
onAbort();
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
function buildAuthFailureGuidance(provider, model, agentName, detail) {
|
|
855
|
+
const mismatch = (0, provider_models_1.getProviderModelMismatchMessage)(provider, model);
|
|
856
|
+
const modelLabel = model
|
|
857
|
+
? mismatch
|
|
858
|
+
? `${provider} [configured model: ${model}]`
|
|
859
|
+
: `${provider} (${model})`
|
|
860
|
+
: provider;
|
|
861
|
+
const lines = [`${modelLabel} authentication failed.`];
|
|
862
|
+
const cleanDetail = detail.replace(/\s+/g, " ").trim();
|
|
863
|
+
if (cleanDetail)
|
|
864
|
+
lines.push(`provider detail: ${cleanDetail.length > 300 ? `${cleanDetail.slice(0, 297)}...` : cleanDetail}`);
|
|
865
|
+
lines.push("");
|
|
866
|
+
lines.push("To keep using this provider:");
|
|
867
|
+
lines.push(` 1. Run \`ouro auth --agent ${agentName} --provider ${provider}\``);
|
|
868
|
+
if (mismatch) {
|
|
869
|
+
const defaultModel = (0, provider_models_1.getDefaultModelForProvider)(provider);
|
|
870
|
+
lines.push("");
|
|
871
|
+
lines.push("Config warning:");
|
|
872
|
+
lines.push(` - ${mismatch}`);
|
|
873
|
+
lines.push(" - Repair the configured model with:");
|
|
874
|
+
lines.push(` \`ouro use --agent ${agentName} --lane outward --provider ${provider} --model ${defaultModel}\``);
|
|
875
|
+
lines.push(` \`ouro use --agent ${agentName} --lane inner --provider ${provider} --model ${defaultModel}\``);
|
|
876
|
+
}
|
|
877
|
+
lines.push("");
|
|
878
|
+
lines.push(`To use another configured provider instead, run \`ouro use --agent ${agentName} --lane <outward|inner> --provider <provider> --model <model>\`.`);
|
|
879
|
+
return lines.join("\n");
|
|
393
880
|
}
|
|
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
881
|
async function runAgent(messages, callbacks, channel, signal, options) {
|
|
409
|
-
const
|
|
882
|
+
const generatedMessages = [];
|
|
883
|
+
const pushGenerated = (...next) => {
|
|
884
|
+
messages.push(...next);
|
|
885
|
+
generatedMessages.push(...structuredClone(next));
|
|
886
|
+
};
|
|
887
|
+
const facing = (0, friends_1.channelToFacing)(channel);
|
|
888
|
+
let providerRuntime = options?.providerRuntimeOverride ?? await getProviderRuntime(facing);
|
|
410
889
|
const provider = providerRuntime.id;
|
|
411
890
|
const toolChoiceRequired = options?.toolChoiceRequired ?? true;
|
|
412
891
|
const traceId = options?.traceId;
|
|
@@ -427,24 +906,88 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
427
906
|
currentContext = { ...currentContext, friend: freshFriend };
|
|
428
907
|
}
|
|
429
908
|
}
|
|
909
|
+
const turnOrientationFrame = options?.orientationFrame
|
|
910
|
+
?? (channel ? (0, orientation_frame_1.buildOrientationFrame)({ channel, messages }) : undefined);
|
|
911
|
+
if (options?.requiredPromptEvidence) {
|
|
912
|
+
let structuralFloor;
|
|
913
|
+
try {
|
|
914
|
+
structuralFloor = (0, prompt_budget_1.assessRequiredPromptEvidenceBudget)({
|
|
915
|
+
messages,
|
|
916
|
+
requiredPromptEvidence: options.requiredPromptEvidence,
|
|
917
|
+
provider: providerRuntime.id,
|
|
918
|
+
model: providerRuntime.model,
|
|
919
|
+
contextWindowTokens: (0, config_1.getContextConfig)().maxTokens,
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
catch (error) {
|
|
923
|
+
const invalidEvidenceError = error instanceof Error ? error : new Error(String(error));
|
|
924
|
+
callbacks.onError(invalidEvidenceError, "terminal");
|
|
925
|
+
options.captureGeneratedMessages?.([]);
|
|
926
|
+
(0, runtime_1.emitNervesEvent)({
|
|
927
|
+
event: "engine.turn_end",
|
|
928
|
+
trace_id: traceId,
|
|
929
|
+
component: "engine",
|
|
930
|
+
message: "runAgent turn completed",
|
|
931
|
+
meta: { done: true, sawPonder: false, sawQuerySession: false, sawBridgeManage: false },
|
|
932
|
+
});
|
|
933
|
+
return {
|
|
934
|
+
outcome: "errored",
|
|
935
|
+
error: invalidEvidenceError,
|
|
936
|
+
errorClassification: "unknown",
|
|
937
|
+
};
|
|
938
|
+
}
|
|
939
|
+
if (structuralFloor.status === "required_evidence_over_budget") {
|
|
940
|
+
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}`);
|
|
941
|
+
callbacks.onError(budgetError, "terminal");
|
|
942
|
+
options.captureGeneratedMessages?.([]);
|
|
943
|
+
(0, runtime_1.emitNervesEvent)({
|
|
944
|
+
event: "engine.turn_end",
|
|
945
|
+
trace_id: traceId,
|
|
946
|
+
component: "engine",
|
|
947
|
+
message: "runAgent turn completed",
|
|
948
|
+
meta: { done: true, sawPonder: false, sawQuerySession: false, sawBridgeManage: false },
|
|
949
|
+
});
|
|
950
|
+
return {
|
|
951
|
+
outcome: "errored",
|
|
952
|
+
error: budgetError,
|
|
953
|
+
errorClassification: "unknown",
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
}
|
|
430
957
|
// Refresh system prompt at start of each turn when channel is provided.
|
|
431
|
-
// If refresh fails,
|
|
432
|
-
// so
|
|
958
|
+
// If refresh fails, retain only a recognised stable prefix (or inject a
|
|
959
|
+
// minimal safe fallback) so stale dynamic state cannot regain authority.
|
|
960
|
+
let structuredSystemPrompt;
|
|
433
961
|
if (channel) {
|
|
434
962
|
try {
|
|
435
963
|
const buildSystemOptions = {
|
|
436
964
|
...options,
|
|
965
|
+
relationshipContextScopes: options?.toolContext?.relationshipAuthorization?.authorizedContextScopes,
|
|
966
|
+
relationshipProfileId: options?.toolContext?.relationshipAuthorization?.profileId,
|
|
967
|
+
relationshipToolNames: options?.toolContext?.relationshipAuthorization?.advertisedToolNames,
|
|
968
|
+
orientationFrame: turnOrientationFrame,
|
|
969
|
+
resumePriorWork: options?.resumePriorWork === true,
|
|
437
970
|
providerCapabilities: providerRuntime.capabilities,
|
|
438
971
|
supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
|
|
439
972
|
};
|
|
440
973
|
const refreshed = await (0, prompt_1.buildSystem)(channel, buildSystemOptions, currentContext);
|
|
441
|
-
|
|
974
|
+
structuredSystemPrompt = refreshed;
|
|
975
|
+
upsertSystemPrompt(messages, (0, prompt_1.flattenSystemPrompt)(refreshed), [
|
|
976
|
+
...(options?.promptOnlyEvidenceMessages ?? []),
|
|
977
|
+
...(options?.requiredPromptEvidence?.verifiedPredecessorMessage
|
|
978
|
+
? [options.requiredPromptEvidence.verifiedPredecessorMessage]
|
|
979
|
+
: []),
|
|
980
|
+
]);
|
|
442
981
|
}
|
|
443
982
|
catch (error) {
|
|
444
983
|
const hadExistingSystemPrompt = messages[0]?.role === "system" && typeof messages[0].content === "string";
|
|
445
|
-
const
|
|
446
|
-
|
|
447
|
-
|
|
984
|
+
const fallback = repairFallbackSystemPrompt(turnOrientationFrame);
|
|
985
|
+
upsertSystemPrompt(messages, fallback, [
|
|
986
|
+
...(options?.promptOnlyEvidenceMessages ?? []),
|
|
987
|
+
...(options?.requiredPromptEvidence?.verifiedPredecessorMessage
|
|
988
|
+
? [options.requiredPromptEvidence.verifiedPredecessorMessage]
|
|
989
|
+
: []),
|
|
990
|
+
]);
|
|
448
991
|
(0, runtime_1.emitNervesEvent)({
|
|
449
992
|
level: "warn",
|
|
450
993
|
event: "mind.step_error",
|
|
@@ -459,46 +1002,160 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
459
1002
|
});
|
|
460
1003
|
}
|
|
461
1004
|
}
|
|
462
|
-
|
|
1005
|
+
if (channel && options?.skipKeptNotes !== true) {
|
|
1006
|
+
await (0, kept_notes_1.injectKeptNotes)(messages, {
|
|
1007
|
+
channel,
|
|
1008
|
+
friend: currentContext?.friend,
|
|
1009
|
+
judge: async (input) => (0, kept_notes_1.createKeptNotesJudge)(await getProviderRuntime("agent"), signal)(input),
|
|
1010
|
+
signal,
|
|
1011
|
+
traceId,
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
463
1014
|
let done = false;
|
|
464
1015
|
let lastUsage;
|
|
465
1016
|
let overflowRetried = false;
|
|
466
|
-
let
|
|
467
|
-
let outcome = "complete";
|
|
1017
|
+
let outcome = "settled";
|
|
468
1018
|
let completion;
|
|
1019
|
+
let suspension;
|
|
1020
|
+
let terminalError;
|
|
1021
|
+
let terminalErrorClassification;
|
|
469
1022
|
let sawSteeringFollowUp = false;
|
|
470
1023
|
let mustResolveBeforeHandoffActive = options?.mustResolveBeforeHandoff === true;
|
|
471
1024
|
let currentReasoningEffort = "medium";
|
|
472
1025
|
let sawSendMessageSelf = false;
|
|
473
|
-
let
|
|
1026
|
+
let sawPonder = false;
|
|
474
1027
|
let sawQuerySession = false;
|
|
475
1028
|
let sawBridgeManage = false;
|
|
1029
|
+
let sawExternalStateQuery = false;
|
|
1030
|
+
const privateReturnHeldTokens = new Set();
|
|
1031
|
+
// Once-per-turn flag for the fresh-work rest gate. Without this, an agent
|
|
1032
|
+
// that called rest, was told "fresh work arrived", processed the items,
|
|
1033
|
+
// and called rest again would get the same message forever — the gate
|
|
1034
|
+
// condition is read from the turn-start snapshot of pendingMessages,
|
|
1035
|
+
// which doesn't update mid-turn. The agent only needs to be told once;
|
|
1036
|
+
// after that, repeated rest attempts mean they've acknowledged.
|
|
1037
|
+
let freshWorkGateFired = false;
|
|
1038
|
+
// Counter for no-tool-call violations. MiniMax reasoning models occasionally
|
|
1039
|
+
// emit only a <think>...</think> block and stop, without any tool call — even
|
|
1040
|
+
// when tool_choice is set to "required". Private-return requests also need
|
|
1041
|
+
// a hard no-tool guard: a text-only "queued" acknowledgement is false unless
|
|
1042
|
+
// a ponder packet created the return obligation in this turn.
|
|
1043
|
+
let noToolCallRetries = 0;
|
|
1044
|
+
const NO_TOOL_CALL_MAX_RETRIES = 2;
|
|
1045
|
+
let providerIterations = 0;
|
|
1046
|
+
const toolLoopState = (0, tool_loop_1.createToolLoopState)();
|
|
1047
|
+
const toolFrictionLedger = (0, tool_friction_1.createToolFrictionLedger)();
|
|
1048
|
+
const finishTerminalProviderError = (error, classification) => {
|
|
1049
|
+
terminalError = error;
|
|
1050
|
+
terminalErrorClassification = classification;
|
|
1051
|
+
/* v8 ignore start — auth-failure guidance: tested via provider error classification tests @preserve */
|
|
1052
|
+
if (terminalErrorClassification === "auth-failure") {
|
|
1053
|
+
const agentName = (0, identity_2.getAgentName)();
|
|
1054
|
+
const currentProvider = providerRuntime.id;
|
|
1055
|
+
callbacks.onError(new Error(buildAuthFailureGuidance(currentProvider, providerRuntime.model, agentName, terminalError.message)), "terminal");
|
|
1056
|
+
}
|
|
1057
|
+
else {
|
|
1058
|
+
callbacks.onError(terminalError, "terminal");
|
|
1059
|
+
}
|
|
1060
|
+
/* v8 ignore stop */
|
|
1061
|
+
const errorDetails = (0, error_classification_1.extractProviderErrorDetails)(terminalError);
|
|
1062
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1063
|
+
level: "error",
|
|
1064
|
+
event: "engine.error",
|
|
1065
|
+
trace_id: traceId,
|
|
1066
|
+
component: "engine",
|
|
1067
|
+
message: terminalError.message,
|
|
1068
|
+
meta: {
|
|
1069
|
+
provider: providerRuntime.id,
|
|
1070
|
+
model: providerRuntime.model,
|
|
1071
|
+
errorClassification: terminalErrorClassification,
|
|
1072
|
+
...(errorDetails.status !== undefined ? { httpStatus: errorDetails.status } : {}),
|
|
1073
|
+
...(errorDetails.bodyExcerpt ? { bodyExcerpt: errorDetails.bodyExcerpt } : {}),
|
|
1074
|
+
summary: (0, error_classification_1.summarizeProviderError)(terminalError, terminalErrorClassification, providerRuntime.id, providerRuntime.model),
|
|
1075
|
+
},
|
|
1076
|
+
});
|
|
1077
|
+
stripLastToolCalls(messages);
|
|
1078
|
+
stripLastToolCalls(generatedMessages);
|
|
1079
|
+
outcome = "errored";
|
|
1080
|
+
done = true;
|
|
1081
|
+
};
|
|
476
1082
|
// Prevent MaxListenersExceeded warning — each iteration adds a listener
|
|
477
1083
|
try {
|
|
478
1084
|
require("events").setMaxListeners(50, signal);
|
|
479
1085
|
}
|
|
480
1086
|
catch { /* unsupported */ }
|
|
481
1087
|
const toolPreferences = currentContext?.friend?.toolPreferences;
|
|
482
|
-
const
|
|
1088
|
+
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);
|
|
1089
|
+
const relationshipToolNames = options?.toolContext?.relationshipAuthorization?.advertisedToolNames;
|
|
1090
|
+
const relationshipScopedTools = relationshipToolNames
|
|
1091
|
+
? unboundBaseTools.filter((tool) => relationshipToolNames.includes(tool.function.name))
|
|
1092
|
+
: unboundBaseTools;
|
|
1093
|
+
const baseTools = bindCurrentIngressEvidenceLocator(relationshipScopedTools, options?.toolContext?.currentIngressEvidence);
|
|
483
1094
|
// Augment tool context with reasoning effort controls from provider
|
|
484
|
-
const
|
|
1095
|
+
const baseToolContext = options?.toolContext
|
|
1096
|
+
?? (turnOrientationFrame ? { signin: async () => undefined, orientationFrame: turnOrientationFrame } : undefined);
|
|
1097
|
+
const habitSession = options?.habitSession ?? baseToolContext?.habitSession;
|
|
1098
|
+
const augmentedToolContext = baseToolContext
|
|
485
1099
|
? {
|
|
486
|
-
...
|
|
1100
|
+
...baseToolContext,
|
|
487
1101
|
supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
|
|
488
1102
|
setReasoningEffort: (level) => { currentReasoningEffort = level; },
|
|
1103
|
+
activeWorkFrame: options?.activeWorkFrame,
|
|
1104
|
+
orientationFrame: turnOrientationFrame ?? baseToolContext.orientationFrame,
|
|
1105
|
+
...(habitSession ? { habitSession } : {}),
|
|
489
1106
|
}
|
|
490
|
-
:
|
|
1107
|
+
: habitSession
|
|
1108
|
+
? {
|
|
1109
|
+
signin: async () => undefined,
|
|
1110
|
+
habitSession,
|
|
1111
|
+
supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
|
|
1112
|
+
setReasoningEffort: (level) => { currentReasoningEffort = level; },
|
|
1113
|
+
}
|
|
1114
|
+
: undefined;
|
|
491
1115
|
// Rebase provider-owned turn state from canonical messages at user-turn start.
|
|
492
1116
|
// This prevents stale provider caches from replaying prior-turn context.
|
|
493
1117
|
providerRuntime.resetTurnState(messages);
|
|
494
1118
|
while (!done) {
|
|
495
|
-
//
|
|
496
|
-
//
|
|
497
|
-
//
|
|
498
|
-
//
|
|
499
|
-
|
|
500
|
-
|
|
1119
|
+
// Channel-based tool filtering:
|
|
1120
|
+
// - Private runtime: exclude send_message (delivery via surface), observe (no one to observe)
|
|
1121
|
+
// - All outward channels (1:1, group, reaction): observe available
|
|
1122
|
+
//
|
|
1123
|
+
// ponder, settle/rest, surface, and observe are always assembled based on channel context.
|
|
1124
|
+
// ponder is available in ALL channels (outer: think privately, inner: keep turning).
|
|
1125
|
+
// Private runtime gets restTool instead of settleTool (rest = end turn, gated by attention queue).
|
|
1126
|
+
// toolChoiceRequired only controls whether tool_choice: "required" is set in the API call.
|
|
1127
|
+
const isPrivateRuntimeChannel = channel === "inner";
|
|
1128
|
+
const privateRuntimeHabitCanSendMessage = isPrivateRuntimeChannel
|
|
1129
|
+
&& habitSession?.toolPolicy.outwardMessagingAllowed === true
|
|
1130
|
+
&& habitSession.toolPolicy.grantedTools.includes("send_message");
|
|
1131
|
+
const privateRuntimeHabitCanSurface = isPrivateRuntimeChannel
|
|
1132
|
+
&& (!habitSession || (habitSession.toolPolicy.outwardMessagingAllowed === true
|
|
1133
|
+
&& habitSession.toolPolicy.grantedTools.includes("surface")));
|
|
1134
|
+
const filteredBaseTools = isPrivateRuntimeChannel
|
|
1135
|
+
? baseTools.filter((t) => privateRuntimeHabitCanSendMessage || t.function.name !== "send_message")
|
|
501
1136
|
: baseTools;
|
|
1137
|
+
const unscopedOrdinaryActiveTools = [
|
|
1138
|
+
...filteredBaseTools,
|
|
1139
|
+
...(augmentedToolContext?.noSend === true ? [] : [tools_1.ponderTool]),
|
|
1140
|
+
...(isPrivateRuntimeChannel && privateRuntimeHabitCanSurface ? [tools_2.surfaceToolDef] : []),
|
|
1141
|
+
...(isPrivateRuntimeChannel ? [tools_1.restTool] : []),
|
|
1142
|
+
...(!isPrivateRuntimeChannel ? [tools_1.observeTool] : []),
|
|
1143
|
+
...(!isPrivateRuntimeChannel ? [tools_1.settleTool] : []),
|
|
1144
|
+
...(isChatStyleChannel(channel ?? "") ? [tools_1.speakTool] : []),
|
|
1145
|
+
];
|
|
1146
|
+
const ordinaryActiveTools = relationshipToolNames
|
|
1147
|
+
? unscopedOrdinaryActiveTools.filter((tool) => relationshipToolNames.includes(tool.function.name))
|
|
1148
|
+
: unscopedOrdinaryActiveTools;
|
|
1149
|
+
const activeTools = options?.toolProfile === "sanctuary-health-private"
|
|
1150
|
+
? (() => {
|
|
1151
|
+
const sendTools = baseTools.filter((tool) => tool.function.name === "send_message");
|
|
1152
|
+
if (channel !== "inner" || sendTools.length !== 1 || baseTools.length !== 1) {
|
|
1153
|
+
throw new Error("sanctuary-health-private requires inner channel with exactly one canonical send_message definition");
|
|
1154
|
+
}
|
|
1155
|
+
return [sendTools[0], tools_1.restTool];
|
|
1156
|
+
})()
|
|
1157
|
+
: ordinaryActiveTools;
|
|
1158
|
+
const activeToolNames = new Set(activeTools.map((tool) => tool.function.name));
|
|
502
1159
|
const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
|
|
503
1160
|
if (steeringFollowUps.length > 0) {
|
|
504
1161
|
const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
|
|
@@ -525,26 +1182,174 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
525
1182
|
break;
|
|
526
1183
|
}
|
|
527
1184
|
try {
|
|
528
|
-
|
|
529
|
-
const
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
1185
|
+
const turnCallbackBufferRef = { current: null };
|
|
1186
|
+
const callProviderTurn = async () => {
|
|
1187
|
+
callbacks.onModelStart();
|
|
1188
|
+
turnCallbackBufferRef.current = habitSession
|
|
1189
|
+
? createHabitCallbackBuffer(callbacks)
|
|
1190
|
+
: callbacks.settleOutputMode === "final_only"
|
|
1191
|
+
? createFinalOnlyTextBuffer(callbacks)
|
|
1192
|
+
: null;
|
|
1193
|
+
try {
|
|
1194
|
+
const promptBudget = (0, prompt_budget_1.applyPromptBudget)({
|
|
1195
|
+
messages,
|
|
1196
|
+
requiredPromptEvidence: options?.requiredPromptEvidence,
|
|
1197
|
+
provider: providerRuntime.id,
|
|
1198
|
+
model: providerRuntime.model,
|
|
1199
|
+
contextWindowTokens: (0, config_1.getContextConfig)().maxTokens,
|
|
1200
|
+
});
|
|
1201
|
+
if (promptBudget.status !== "within_budget") {
|
|
1202
|
+
messages.splice(0, messages.length, ...promptBudget.messages);
|
|
1203
|
+
providerRuntime.resetTurnState(messages);
|
|
1204
|
+
}
|
|
1205
|
+
return await providerRuntime.streamTurn({
|
|
1206
|
+
messages,
|
|
1207
|
+
activeTools,
|
|
1208
|
+
callbacks: turnCallbackBufferRef.current?.callbacks ?? callbacks,
|
|
1209
|
+
signal,
|
|
1210
|
+
traceId,
|
|
1211
|
+
toolChoiceRequired,
|
|
1212
|
+
reasoningEffort: currentReasoningEffort,
|
|
1213
|
+
eagerSettleStreaming: true,
|
|
1214
|
+
systemPrompt: structuredSystemPrompt,
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
catch (error) {
|
|
1218
|
+
turnCallbackBufferRef.current?.discard();
|
|
1219
|
+
turnCallbackBufferRef.current = null;
|
|
1220
|
+
if (signal?.aborted)
|
|
1221
|
+
throw new provider_attempt_1.ProviderAttemptAbortError();
|
|
1222
|
+
throw error;
|
|
1223
|
+
}
|
|
1224
|
+
};
|
|
1225
|
+
const callProviderTurnWithOverflowRecovery = async () => {
|
|
1226
|
+
try {
|
|
1227
|
+
return await callProviderTurn();
|
|
1228
|
+
}
|
|
1229
|
+
catch (error) {
|
|
1230
|
+
if (error instanceof provider_attempt_1.ProviderAttemptAbortError)
|
|
1231
|
+
throw error;
|
|
1232
|
+
if (isContextOverflow(error) && !overflowRetried) {
|
|
1233
|
+
overflowRetried = true;
|
|
1234
|
+
stripLastToolCalls(messages);
|
|
1235
|
+
stripLastToolCalls(generatedMessages);
|
|
1236
|
+
const { maxTokens, contextMargin } = (0, config_1.getContextConfig)();
|
|
1237
|
+
const trimmed = (0, context_1.trimMessages)(messages, maxTokens, contextMargin, maxTokens * 2);
|
|
1238
|
+
const requiredEvidence = options?.requiredPromptEvidence;
|
|
1239
|
+
const requiredMessages = new Set([
|
|
1240
|
+
...(requiredEvidence?.verifiedPredecessorMessage ? [requiredEvidence.verifiedPredecessorMessage] : []),
|
|
1241
|
+
...(requiredEvidence?.currentUserMessage ? [requiredEvidence.currentUserMessage] : []),
|
|
1242
|
+
]);
|
|
1243
|
+
const trimmedMessages = new Set(trimmed);
|
|
1244
|
+
const overflowRetryMessages = requiredMessages.size === 0
|
|
1245
|
+
? trimmed
|
|
1246
|
+
: messages.filter((message) => trimmedMessages.has(message) || requiredMessages.has(message));
|
|
1247
|
+
messages.splice(0, messages.length, ...overflowRetryMessages);
|
|
1248
|
+
providerRuntime.resetTurnState(messages);
|
|
1249
|
+
callbacks.onError(new Error("context trimmed, retrying..."), "transient");
|
|
1250
|
+
return callProviderTurn();
|
|
1251
|
+
}
|
|
1252
|
+
throw error;
|
|
1253
|
+
}
|
|
1254
|
+
};
|
|
1255
|
+
const attempt = await (0, provider_attempt_1.runProviderAttempt)({
|
|
1256
|
+
operation: "turn",
|
|
1257
|
+
provider: providerRuntime.id,
|
|
1258
|
+
model: providerRuntime.model,
|
|
1259
|
+
run: callProviderTurnWithOverflowRecovery,
|
|
1260
|
+
classifyError: (error) => providerRuntime.classifyError(error),
|
|
1261
|
+
onRetry: async (record, maxAttempts) => {
|
|
1262
|
+
const delayMs = record.delayMs;
|
|
1263
|
+
const seconds = delayMs / 1000;
|
|
1264
|
+
const cause = RETRY_LABELS[record.classification];
|
|
1265
|
+
try {
|
|
1266
|
+
if (record.provider === "openai-codex" && record.classification === "auth-failure") {
|
|
1267
|
+
await (0, openai_codex_token_1.refreshOpenAICodexProviderCredentials)((0, identity_2.getAgentName)(), {
|
|
1268
|
+
force: true,
|
|
1269
|
+
reason: "turn-auth-failure",
|
|
1270
|
+
});
|
|
1271
|
+
}
|
|
1272
|
+
await (0, provider_credentials_1.refreshProviderCredentialPool)((0, identity_2.getAgentName)(), {
|
|
1273
|
+
preserveCachedOnFailure: true,
|
|
1274
|
+
providers: [record.provider],
|
|
1275
|
+
});
|
|
1276
|
+
_providerRuntimeFactories[facing] = null;
|
|
1277
|
+
providerRuntime = await getProviderRuntime(facing);
|
|
1278
|
+
providerRuntime.resetTurnState(messages);
|
|
1279
|
+
}
|
|
1280
|
+
catch (refreshError) {
|
|
1281
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1282
|
+
level: "warn",
|
|
1283
|
+
component: "engine",
|
|
1284
|
+
event: "engine.provider_retry_refresh_failed",
|
|
1285
|
+
message: "provider credential refresh failed during retry",
|
|
1286
|
+
meta: { provider: record.provider, model: record.model, reason: refreshError instanceof Error ? refreshError.message : String(refreshError) },
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
callbacks.onError(new Error(`${cause}, retrying in ${seconds}s (${record.attempt}/${maxAttempts})...`), "transient");
|
|
1290
|
+
},
|
|
1291
|
+
sleep: async (delayMs) => {
|
|
1292
|
+
await waitForProviderRetry(delayMs, signal);
|
|
1293
|
+
providerRuntime.resetTurnState(messages);
|
|
1294
|
+
},
|
|
537
1295
|
});
|
|
1296
|
+
if (!attempt.ok) {
|
|
1297
|
+
finishTerminalProviderError(attempt.error, attempt.classification);
|
|
1298
|
+
continue;
|
|
1299
|
+
}
|
|
1300
|
+
const result = attempt.value;
|
|
1301
|
+
providerIterations += 1;
|
|
1302
|
+
if (providerIterations === exports.MAX_PROVIDER_ITERATIONS && result.toolCalls.length > 0) {
|
|
1303
|
+
throw new Error(`provider iteration limit exhausted at response ${exports.MAX_PROVIDER_ITERATIONS} before tool execution`);
|
|
1304
|
+
}
|
|
1305
|
+
const streamCallbackBuffer = turnCallbackBufferRef.current;
|
|
1306
|
+
turnCallbackBufferRef.current = null;
|
|
1307
|
+
if (result.settleFinalization && !result.settleFinalization.ok) {
|
|
1308
|
+
// A completed settle payload is terminal provider output, not a prompt
|
|
1309
|
+
// for another model turn. Retractable callbacks have already cleared;
|
|
1310
|
+
// core-owned callback buffers must be discarded before surfacing the exact
|
|
1311
|
+
// parser failure through the ordinary terminal-error path.
|
|
1312
|
+
streamCallbackBuffer?.discard();
|
|
1313
|
+
finishTerminalProviderError(new Error(result.settleFinalization.errorCode), "unknown");
|
|
1314
|
+
continue;
|
|
1315
|
+
}
|
|
538
1316
|
// Track usage from the latest API call
|
|
539
1317
|
if (result.usage)
|
|
540
1318
|
lastUsage = result.usage;
|
|
541
|
-
retryCount = 0; // reset on success
|
|
542
1319
|
// SHARED: build CC-format assistant message from TurnResult
|
|
543
1320
|
const msg = {
|
|
544
1321
|
role: "assistant",
|
|
545
1322
|
};
|
|
546
|
-
|
|
547
|
-
|
|
1323
|
+
// Persist assistant content WITHOUT inline <think>...</think> blocks.
|
|
1324
|
+
// Reasoning content already routed through onReasoningChunk for live
|
|
1325
|
+
// surfacing and persisted separately as `_reasoning_items` for
|
|
1326
|
+
// providers that support a reasoning channel; saving it inline AND
|
|
1327
|
+
// alongside tool_calls causes MiniMax to reject the replayed turn
|
|
1328
|
+
// with "tool result's tool id not found" (error code 2013) because
|
|
1329
|
+
// it can't reconcile reasoning-with-tools in the same assistant
|
|
1330
|
+
// message. Strip aggressively at persist so the next replay is
|
|
1331
|
+
// clean; preserve the original reasoning trace on the message via
|
|
1332
|
+
// `_inline_reasoning` so debug/audit paths can still see it.
|
|
1333
|
+
if (result.content) {
|
|
1334
|
+
const stripped = stripThinkBlocksForViolationCheck(result.content);
|
|
1335
|
+
if (stripped.length > 0)
|
|
1336
|
+
msg.content = stripped;
|
|
1337
|
+
if (stripped.length !== result.content.length) {
|
|
1338
|
+
msg._inline_reasoning = result.content;
|
|
1339
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1340
|
+
level: "info",
|
|
1341
|
+
component: "engine",
|
|
1342
|
+
event: "engine.inline_reasoning_stripped",
|
|
1343
|
+
message: "stripped inline <think> blocks from persisted assistant message; preserved on _inline_reasoning",
|
|
1344
|
+
meta: {
|
|
1345
|
+
provider: providerRuntime.id,
|
|
1346
|
+
model: providerRuntime.model,
|
|
1347
|
+
originalLength: result.content.length,
|
|
1348
|
+
strippedLength: stripped.length,
|
|
1349
|
+
},
|
|
1350
|
+
});
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
548
1353
|
if (result.toolCalls.length)
|
|
549
1354
|
msg.tool_calls = result.toolCalls.map((tc) => ({
|
|
550
1355
|
id: tc.id,
|
|
@@ -564,198 +1369,718 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
564
1369
|
}
|
|
565
1370
|
// Phase annotation for Codex provider
|
|
566
1371
|
const hasPhaseAnnotation = providerRuntime.capabilities.has("phase-annotation");
|
|
567
|
-
const
|
|
1372
|
+
const isSoleSettle = result.toolCalls.length === 1 && result.toolCalls[0].name === "settle";
|
|
568
1373
|
if (hasPhaseAnnotation) {
|
|
569
|
-
msg.phase =
|
|
1374
|
+
msg.phase = isSoleSettle ? "settle" : "commentary";
|
|
570
1375
|
}
|
|
1376
|
+
// Detect the MiniMax "only-thinking, no tool call" violation: no tool
|
|
1377
|
+
// calls returned, and the content is empty after stripping
|
|
1378
|
+
// <think>...</think> blocks. This is a narrow check — legitimate
|
|
1379
|
+
// content-only responses (text without think tags, or text outside
|
|
1380
|
+
// think tags) still flow through the original "no tool calls →
|
|
1381
|
+
// accept as-is" path so existing channels and tests are unaffected.
|
|
1382
|
+
const onlyThinkContent = !result.toolCalls.length
|
|
1383
|
+
&& typeof result.content === "string"
|
|
1384
|
+
&& stripThinkBlocksForViolationCheck(result.content).length === 0
|
|
1385
|
+
&& result.content.length > 0;
|
|
1386
|
+
const privateReturnTextAckRetryError = !result.toolCalls.length
|
|
1387
|
+
? privateReturnMissingPonderError({
|
|
1388
|
+
latestUserRequest: latestUserMessageText(messages),
|
|
1389
|
+
answer: stripThinkBlocksForViolationCheck(result.content),
|
|
1390
|
+
sawPonder,
|
|
1391
|
+
})
|
|
1392
|
+
: null;
|
|
571
1393
|
if (!result.toolCalls.length) {
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
1394
|
+
if (privateReturnTextAckRetryError) {
|
|
1395
|
+
streamCallbackBuffer?.discard();
|
|
1396
|
+
callbacks.onClearText?.();
|
|
1397
|
+
if (noToolCallRetries < NO_TOOL_CALL_MAX_RETRIES) {
|
|
1398
|
+
noToolCallRetries++;
|
|
1399
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1400
|
+
level: "warn",
|
|
1401
|
+
component: "engine",
|
|
1402
|
+
event: "engine.no_tool_call_retry",
|
|
1403
|
+
message: "model returned a text-only private-return acknowledgement without ponder; retrying with corrective nudge",
|
|
1404
|
+
meta: {
|
|
1405
|
+
attempt: noToolCallRetries,
|
|
1406
|
+
cap: NO_TOOL_CALL_MAX_RETRIES,
|
|
1407
|
+
provider: providerRuntime.id,
|
|
1408
|
+
model: providerRuntime.model,
|
|
1409
|
+
reason: "private_return_missing_ponder",
|
|
1410
|
+
contentLength: result.content.length,
|
|
1411
|
+
},
|
|
1412
|
+
});
|
|
1413
|
+
pushGenerated(msg);
|
|
1414
|
+
messages.push({
|
|
1415
|
+
role: "user",
|
|
1416
|
+
content: `${privateReturnTextAckRetryError} Emit the ponder(action=create, ...) tool call now, or ask a blocking clarification without saying the private work is queued.`,
|
|
1417
|
+
});
|
|
1418
|
+
continue;
|
|
1419
|
+
}
|
|
1420
|
+
const blockedAnswer = "I could not start the private pass. No private-attention packet was created, so no return work was queued.";
|
|
1421
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1422
|
+
level: "error",
|
|
1423
|
+
component: "engine",
|
|
1424
|
+
event: "engine.private_return_missing_ponder_blocked",
|
|
1425
|
+
message: "private-return text acknowledgement skipped ponder through the retry cap; failing closed",
|
|
1426
|
+
meta: {
|
|
1427
|
+
cap: NO_TOOL_CALL_MAX_RETRIES,
|
|
1428
|
+
provider: providerRuntime.id,
|
|
1429
|
+
model: providerRuntime.model,
|
|
1430
|
+
contentLength: result.content.length,
|
|
1431
|
+
},
|
|
1432
|
+
});
|
|
1433
|
+
msg.content = blockedAnswer;
|
|
1434
|
+
pushGenerated(msg);
|
|
1435
|
+
callbacks.onTextChunk(blockedAnswer);
|
|
1436
|
+
completion = { answer: blockedAnswer, intent: "blocked" };
|
|
1437
|
+
outcome = "blocked";
|
|
1438
|
+
done = true;
|
|
1439
|
+
continue;
|
|
1440
|
+
}
|
|
1441
|
+
if (onlyThinkContent && toolChoiceRequired && noToolCallRetries < NO_TOOL_CALL_MAX_RETRIES) {
|
|
1442
|
+
streamCallbackBuffer?.discard();
|
|
1443
|
+
// Provider-level violation: tool_choice was required, model emitted
|
|
1444
|
+
// only a <think>...</think> block (or empty content) with no tool
|
|
1445
|
+
// call. Retry with a corrective nudge up to NO_TOOL_CALL_MAX_RETRIES
|
|
1446
|
+
// times. After cap, accept as-is (the readback path strips think
|
|
1447
|
+
// tags and surfaces a clear diagnostic).
|
|
1448
|
+
noToolCallRetries++;
|
|
1449
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1450
|
+
level: "warn",
|
|
1451
|
+
component: "engine",
|
|
1452
|
+
event: "engine.no_tool_call_retry",
|
|
1453
|
+
message: "model returned only <think> content with no tool call despite tool_choice=required; retrying with corrective nudge",
|
|
1454
|
+
meta: {
|
|
1455
|
+
attempt: noToolCallRetries,
|
|
1456
|
+
cap: NO_TOOL_CALL_MAX_RETRIES,
|
|
1457
|
+
provider: providerRuntime.id,
|
|
1458
|
+
model: providerRuntime.model,
|
|
1459
|
+
contentLength: result.content.length,
|
|
1460
|
+
},
|
|
1461
|
+
});
|
|
1462
|
+
pushGenerated(msg);
|
|
1463
|
+
messages.push({
|
|
1464
|
+
role: "user",
|
|
1465
|
+
content: isPrivateRuntimeChannel
|
|
1466
|
+
? augmentedToolContext?.noSend === true
|
|
1467
|
+
? "no tool was called this turn. this is an immutable no-send turn; call rest now without creating a continuation."
|
|
1468
|
+
: "no tool was called this turn. you must end every turn by calling rest (or surface, ponder, observe). emit the tool call now."
|
|
1469
|
+
: "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.",
|
|
1470
|
+
});
|
|
1471
|
+
continue;
|
|
1472
|
+
}
|
|
1473
|
+
// Legitimate text-only response, or cap reached — accept as-is.
|
|
1474
|
+
await streamCallbackBuffer?.flush();
|
|
1475
|
+
pushGenerated(msg);
|
|
576
1476
|
done = true;
|
|
577
1477
|
}
|
|
578
1478
|
else {
|
|
579
|
-
//
|
|
580
|
-
|
|
1479
|
+
// Reset the retry counter on any successful tool call.
|
|
1480
|
+
noToolCallRetries = 0;
|
|
1481
|
+
const preCallMessages = structuredClone(messages.filter((message) => message.role !== "system"));
|
|
1482
|
+
const validatedCalls = validateToolCallBatchAtProductionBoundary(result.toolCalls, activeTools);
|
|
1483
|
+
const invalidCall = validatedCalls.find((entry) => "error" in entry);
|
|
1484
|
+
if (invalidCall) {
|
|
1485
|
+
await streamCallbackBuffer?.flush();
|
|
1486
|
+
pushGenerated(msg);
|
|
1487
|
+
const unadvertisedCall = validatedCalls.find((entry) => !activeToolNames.has(entry.call.name));
|
|
1488
|
+
for (const entry of validatedCalls) {
|
|
1489
|
+
const detail = "error" in entry ? entry.error : "another call in this batch had invalid arguments";
|
|
1490
|
+
const rejection = unadvertisedCall
|
|
1491
|
+
? `rejected: ${entry.call.name} was not advertised for this channel; no handler was executed.`
|
|
1492
|
+
: `invalid tool arguments: ${detail}`;
|
|
1493
|
+
pushGenerated({ role: "tool", tool_call_id: entry.call.id, content: rejection });
|
|
1494
|
+
providerRuntime.appendToolOutput(entry.call.id, rejection);
|
|
1495
|
+
options?.toolBoundaryObserver?.({
|
|
1496
|
+
name: entry.call.name,
|
|
1497
|
+
reason: activeToolNames.has(entry.call.name) ? "invalid_arguments" : "profile_excluded",
|
|
1498
|
+
globallyResolvable: typeof (0, tools_1.resolveToolDefinition)(entry.call.name)?.handler === "function",
|
|
1499
|
+
invoked: false,
|
|
1500
|
+
sideEffect: false,
|
|
1501
|
+
});
|
|
1502
|
+
}
|
|
1503
|
+
if (unadvertisedCall) {
|
|
1504
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1505
|
+
level: "warn",
|
|
1506
|
+
component: "engine",
|
|
1507
|
+
event: "engine.unadvertised_tool_blocked",
|
|
1508
|
+
message: "blocked an unadvertised tool call before batch execution",
|
|
1509
|
+
meta: { channel: String(channel), toolName: unadvertisedCall.call.name },
|
|
1510
|
+
});
|
|
1511
|
+
}
|
|
1512
|
+
else {
|
|
1513
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1514
|
+
level: "warn",
|
|
1515
|
+
component: "engine",
|
|
1516
|
+
event: "engine.tool_arguments_rejected",
|
|
1517
|
+
message: "tool batch rejected before execution because arguments were invalid",
|
|
1518
|
+
meta: { toolCallId: invalidCall.call.id, toolName: invalidCall.call.name },
|
|
1519
|
+
});
|
|
1520
|
+
}
|
|
1521
|
+
continue;
|
|
1522
|
+
}
|
|
1523
|
+
const validCalls = validatedCalls;
|
|
1524
|
+
const validatedCallArguments = new Map(validCalls.map((entry) => [
|
|
1525
|
+
entry.call,
|
|
1526
|
+
entry.validated.arguments,
|
|
1527
|
+
]));
|
|
1528
|
+
const habitBlockReason = await habitToolBatchBlockReason(habitSession, result.toolCalls, augmentedToolContext?.delegatedOrigins);
|
|
1529
|
+
if (habitBlockReason) {
|
|
1530
|
+
streamCallbackBuffer?.discard();
|
|
1531
|
+
recordBlockedHabitSurfaceAttempts(habitSession, result.toolCalls, habitBlockReason);
|
|
1532
|
+
pushGenerated(msg);
|
|
1533
|
+
const blockedOutput = `blocked: ${habitBlockReason}. No tool side effects from this assistant message were executed.`;
|
|
1534
|
+
for (const call of result.toolCalls) {
|
|
1535
|
+
pushGenerated({ role: "tool", tool_call_id: call.id, content: blockedOutput });
|
|
1536
|
+
providerRuntime.appendToolOutput(call.id, blockedOutput);
|
|
1537
|
+
}
|
|
1538
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1539
|
+
level: "warn",
|
|
1540
|
+
component: "engine",
|
|
1541
|
+
event: "engine.habit_tool_batch_blocked",
|
|
1542
|
+
message: "habit tool batch blocked before side effects",
|
|
1543
|
+
meta: { reason: habitBlockReason, toolCalls: result.toolCalls.map((call) => call.name) },
|
|
1544
|
+
});
|
|
1545
|
+
continue;
|
|
1546
|
+
}
|
|
1547
|
+
const soleTerminalCall = result.toolCalls.length === 1
|
|
1548
|
+
? result.toolCalls[0]
|
|
1549
|
+
: null;
|
|
1550
|
+
const soleTerminalProjection = soleTerminalCall
|
|
1551
|
+
? (0, tools_1.resolveToolDefinition)(soleTerminalCall.name)?.terminalProjection
|
|
1552
|
+
: undefined;
|
|
1553
|
+
if (soleTerminalCall && soleTerminalProjection?.mode === "verbatim") {
|
|
1554
|
+
const terminalArgs = validatedCallArguments.get(soleTerminalCall);
|
|
1555
|
+
if (soleTerminalProjection.clearBufferedText
|
|
1556
|
+
|| callbacks.settleOutputMode === "final_only") {
|
|
1557
|
+
streamCallbackBuffer?.discard();
|
|
1558
|
+
}
|
|
1559
|
+
else {
|
|
1560
|
+
await streamCallbackBuffer?.flush();
|
|
1561
|
+
}
|
|
1562
|
+
if (soleTerminalProjection.clearBufferedText)
|
|
1563
|
+
callbacks.onClearText?.();
|
|
1564
|
+
callbacks.onToolStart(soleTerminalCall.name, terminalArgs);
|
|
1565
|
+
let terminalResult;
|
|
1566
|
+
try {
|
|
1567
|
+
const execToolFn = options?.execTool ?? tools_1.execTool;
|
|
1568
|
+
terminalResult = await execToolFn(soleTerminalCall.name, terminalArgs, augmentedToolContext);
|
|
1569
|
+
}
|
|
1570
|
+
catch (error) {
|
|
1571
|
+
callbacks.onToolEnd(soleTerminalCall.name, (0, tools_1.summarizeArgs)(soleTerminalCall.name, terminalArgs), false);
|
|
1572
|
+
pushGenerated(msg);
|
|
1573
|
+
const failure = error instanceof Error ? `error: ${error.message}` : `error: ${String(error)}`;
|
|
1574
|
+
pushGenerated({ role: "tool", tool_call_id: soleTerminalCall.id, content: failure });
|
|
1575
|
+
providerRuntime.appendToolOutput(soleTerminalCall.id, failure);
|
|
1576
|
+
callbacks.onTextChunk(failure);
|
|
1577
|
+
completion = { answer: failure, intent: "blocked" };
|
|
1578
|
+
outcome = "blocked";
|
|
1579
|
+
done = true;
|
|
1580
|
+
continue;
|
|
1581
|
+
}
|
|
1582
|
+
callbacks.onToolEnd(soleTerminalCall.name, (0, tools_1.summarizeArgs)(soleTerminalCall.name, terminalArgs), true);
|
|
1583
|
+
pushGenerated(msg);
|
|
1584
|
+
pushGenerated({ role: "tool", tool_call_id: soleTerminalCall.id, content: terminalResult });
|
|
1585
|
+
providerRuntime.appendToolOutput(soleTerminalCall.id, terminalResult);
|
|
1586
|
+
callbacks.onTextChunk(terminalResult);
|
|
1587
|
+
completion = { answer: terminalResult, intent: "complete" };
|
|
1588
|
+
outcome = "settled";
|
|
1589
|
+
done = true;
|
|
1590
|
+
continue;
|
|
1591
|
+
}
|
|
1592
|
+
// Check for settle sole call: intercept before tool execution
|
|
1593
|
+
if (isSoleSettle) {
|
|
1594
|
+
const settleArgs = validatedCallArguments.get(result.toolCalls[0]);
|
|
1595
|
+
callbacks.onToolStart("settle", settleArgs);
|
|
1596
|
+
// Private-runtime attention queue gate: reject settle if items remain
|
|
1597
|
+
const attentionQueue = augmentedToolContext?.delegatedOrigins;
|
|
1598
|
+
if (isPrivateRuntimeChannel && attentionQueue && attentionQueue.length > 0) {
|
|
1599
|
+
streamCallbackBuffer?.discard();
|
|
1600
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
|
|
1601
|
+
callbacks.onClearText?.();
|
|
1602
|
+
pushGenerated(msg);
|
|
1603
|
+
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.";
|
|
1604
|
+
pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
|
|
1605
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
|
|
1606
|
+
continue;
|
|
1607
|
+
}
|
|
581
1608
|
// Extract answer from the tool call arguments.
|
|
582
1609
|
// Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
|
|
583
|
-
const { answer, intent } =
|
|
1610
|
+
const { answer, intent } = parseSettlePayload(result.toolCalls[0].arguments);
|
|
1611
|
+
// Private-runtime settle: no CompletionMetadata, "(settled)" ack
|
|
1612
|
+
if (isPrivateRuntimeChannel) {
|
|
1613
|
+
streamCallbackBuffer?.discard();
|
|
1614
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
|
|
1615
|
+
pushGenerated(msg);
|
|
1616
|
+
const settled = "(settled)";
|
|
1617
|
+
pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: settled });
|
|
1618
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, settled);
|
|
1619
|
+
outcome = "settled";
|
|
1620
|
+
done = true;
|
|
1621
|
+
continue;
|
|
1622
|
+
}
|
|
1623
|
+
// The provider finalizer has already established a top-level string
|
|
1624
|
+
// answer before ordinary settle handling reaches this point.
|
|
1625
|
+
const deliveredAnswer = answer;
|
|
1626
|
+
const retryError = privateReturnAckLeakError(deliveredAnswer, privateReturnHeldTokens)
|
|
1627
|
+
?? privateReturnMissingPonderError({
|
|
1628
|
+
latestUserRequest: latestUserMessageText(messages),
|
|
1629
|
+
answer: deliveredAnswer,
|
|
1630
|
+
sawPonder,
|
|
1631
|
+
})
|
|
1632
|
+
?? getSettleRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp, options?.delegationDecision, sawSendMessageSelf, sawPonder, sawQuerySession, options?.currentObligation ?? null, options?.activeWorkFrame?.inner?.job, sawExternalStateQuery);
|
|
584
1633
|
const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
1634
|
+
if (retryError === null) {
|
|
1635
|
+
try {
|
|
1636
|
+
if (!result.settleStreamed) {
|
|
1637
|
+
const acceptedOutputCallbacks = streamCallbackBuffer?.callbacks ?? callbacks;
|
|
1638
|
+
acceptedOutputCallbacks.onTextChunk(deliveredAnswer);
|
|
1639
|
+
}
|
|
1640
|
+
await streamCallbackBuffer?.flush();
|
|
1641
|
+
}
|
|
1642
|
+
catch (error) {
|
|
1643
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
|
|
1644
|
+
streamCallbackBuffer?.discard();
|
|
1645
|
+
finishTerminalProviderError(new streaming_1.SettleFinalizationCallbackError(error), "unknown");
|
|
1646
|
+
continue;
|
|
1647
|
+
}
|
|
1648
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
|
|
589
1649
|
completion = {
|
|
590
|
-
answer,
|
|
1650
|
+
answer: deliveredAnswer,
|
|
591
1651
|
intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
|
|
592
1652
|
};
|
|
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);
|
|
1653
|
+
// Retractable owners already hold the validated answer. Final-only
|
|
1654
|
+
// owners receive it here, after every semantic continuation gate.
|
|
1655
|
+
pushGenerated(msg);
|
|
606
1656
|
if (validDirectReply) {
|
|
607
1657
|
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
|
-
|
|
1658
|
+
pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: resumeWork });
|
|
609
1659
|
providerRuntime.appendToolOutput(result.toolCalls[0].id, resumeWork);
|
|
610
1660
|
}
|
|
611
1661
|
else {
|
|
612
1662
|
const delivered = "(delivered)";
|
|
613
|
-
|
|
1663
|
+
pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
|
|
614
1664
|
providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
|
|
615
|
-
outcome = intent === "blocked" ? "blocked" : "
|
|
1665
|
+
outcome = intent === "blocked" ? "blocked" : "settled";
|
|
616
1666
|
done = true;
|
|
617
1667
|
}
|
|
618
1668
|
}
|
|
619
1669
|
else {
|
|
620
|
-
//
|
|
621
|
-
//
|
|
622
|
-
|
|
1670
|
+
// The payload is structurally final, but a semantic continuation
|
|
1671
|
+
// gate rejected it. Return that exact gate reason to the model.
|
|
1672
|
+
streamCallbackBuffer?.discard();
|
|
1673
|
+
callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
|
|
623
1674
|
callbacks.onClearText?.();
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
providerRuntime.appendToolOutput(result.toolCalls[0].id,
|
|
1675
|
+
pushGenerated(msg);
|
|
1676
|
+
const toolRetryMessage = retryError;
|
|
1677
|
+
pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: toolRetryMessage });
|
|
1678
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, toolRetryMessage);
|
|
628
1679
|
}
|
|
629
1680
|
continue;
|
|
630
1681
|
}
|
|
631
|
-
// Check for
|
|
632
|
-
const
|
|
633
|
-
if (
|
|
1682
|
+
// Check for observe sole call: intercept before tool execution
|
|
1683
|
+
const isSoleObserve = result.toolCalls.length === 1 && result.toolCalls[0].name === "observe";
|
|
1684
|
+
if (isSoleObserve) {
|
|
1685
|
+
streamCallbackBuffer?.discard();
|
|
1686
|
+
const observeArgs = validatedCallArguments.get(result.toolCalls[0]);
|
|
634
1687
|
let reason;
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
reason = parsed.reason;
|
|
639
|
-
}
|
|
640
|
-
catch { /* ignore */ }
|
|
1688
|
+
if (typeof observeArgs?.reason === "string")
|
|
1689
|
+
reason = observeArgs.reason;
|
|
1690
|
+
callbacks.onToolStart("observe", observeArgs);
|
|
641
1691
|
(0, runtime_1.emitNervesEvent)({
|
|
642
1692
|
component: "engine",
|
|
643
|
-
event: "engine.
|
|
644
|
-
message: "agent
|
|
1693
|
+
event: "engine.observe",
|
|
1694
|
+
message: "agent observed without responding",
|
|
645
1695
|
meta: { ...(reason ? { reason } : {}) },
|
|
646
1696
|
});
|
|
647
|
-
|
|
1697
|
+
callbacks.onToolEnd("observe", (0, tools_1.summarizeArgs)("observe", observeArgs), true);
|
|
1698
|
+
pushGenerated(msg);
|
|
648
1699
|
const silenced = "(silenced)";
|
|
649
|
-
|
|
1700
|
+
pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: silenced });
|
|
650
1701
|
providerRuntime.appendToolOutput(result.toolCalls[0].id, silenced);
|
|
651
|
-
outcome = "
|
|
1702
|
+
outcome = "observed";
|
|
652
1703
|
done = true;
|
|
653
1704
|
continue;
|
|
654
1705
|
}
|
|
655
|
-
// Check for
|
|
656
|
-
const
|
|
657
|
-
if (
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
1706
|
+
// Check for rest sole call: intercept before tool execution
|
|
1707
|
+
const isSoleRest = result.toolCalls.length === 1 && result.toolCalls[0].name === "rest";
|
|
1708
|
+
if (isSoleRest) {
|
|
1709
|
+
streamCallbackBuffer?.discard();
|
|
1710
|
+
const restArgs = validatedCallArguments.get(result.toolCalls[0]);
|
|
1711
|
+
callbacks.onToolStart("rest", restArgs);
|
|
1712
|
+
// Attention queue gate: reject rest if items remain
|
|
1713
|
+
const attentionQueue = augmentedToolContext?.delegatedOrigins;
|
|
1714
|
+
if (attentionQueue && attentionQueue.length > 0) {
|
|
1715
|
+
callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), false);
|
|
1716
|
+
pushGenerated(msg);
|
|
1717
|
+
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.";
|
|
1718
|
+
pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
|
|
1719
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
|
|
1720
|
+
continue;
|
|
661
1721
|
}
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
1722
|
+
if (hasFreshPendingWork(options) && !freshWorkGateFired) {
|
|
1723
|
+
freshWorkGateFired = true;
|
|
1724
|
+
callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), false);
|
|
1725
|
+
pushGenerated(msg);
|
|
1726
|
+
const gateMessage = "fresh work arrived for me this turn — inspect the pending messages above and take the next concrete action before you rest.";
|
|
1727
|
+
pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
|
|
1728
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
|
|
1729
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1730
|
+
level: "info",
|
|
1731
|
+
component: "engine",
|
|
1732
|
+
event: "engine.fresh_work_gate_fired",
|
|
1733
|
+
message: "rest deferred once because pending work arrived this turn; agent has been notified",
|
|
1734
|
+
meta: { pendingCount: options.pendingMessages.length },
|
|
1735
|
+
});
|
|
1736
|
+
continue;
|
|
674
1737
|
}
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
1738
|
+
callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), true);
|
|
1739
|
+
pushGenerated(msg);
|
|
1740
|
+
const ack = "(resting)";
|
|
1741
|
+
pushGenerated({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
|
|
1742
|
+
providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
|
|
1743
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1744
|
+
component: "engine",
|
|
1745
|
+
event: "engine.rested",
|
|
1746
|
+
message: "resting until next heartbeat",
|
|
1747
|
+
meta: { ...(typeof restArgs?.status === "string" ? { status: restArgs.status } : {}) },
|
|
683
1748
|
});
|
|
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
|
-
} : {}),
|
|
1749
|
+
outcome = "rested";
|
|
1750
|
+
done = true;
|
|
1751
|
+
continue;
|
|
1752
|
+
}
|
|
1753
|
+
const approvalCalls = await Promise.all(validCalls.map(async (entry) => {
|
|
1754
|
+
const classification = await (0, tools_1.classifyApprovalForInvocation)(entry.call.name, entry.validated.arguments, augmentedToolContext);
|
|
1755
|
+
return {
|
|
1756
|
+
...entry,
|
|
1757
|
+
...classification,
|
|
703
1758
|
};
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
1759
|
+
}));
|
|
1760
|
+
const protectedCall = approvalCalls.find((entry) => entry.policy.kind === "required");
|
|
1761
|
+
if (protectedCall && result.toolCalls.length !== 1) {
|
|
1762
|
+
streamCallbackBuffer?.discard();
|
|
1763
|
+
pushGenerated(msg);
|
|
1764
|
+
for (const call of result.toolCalls) {
|
|
1765
|
+
const rejection = "rejected: approval-eligible tool must be the sole call; no call in this batch was executed.";
|
|
1766
|
+
pushGenerated({ role: "tool", tool_call_id: call.id, content: rejection });
|
|
1767
|
+
providerRuntime.appendToolOutput(call.id, rejection);
|
|
707
1768
|
}
|
|
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
1769
|
(0, runtime_1.emitNervesEvent)({
|
|
1770
|
+
level: "warn",
|
|
715
1771
|
component: "engine",
|
|
716
|
-
event: "engine.
|
|
717
|
-
message: "
|
|
718
|
-
meta: {
|
|
1772
|
+
event: "engine.approval_mixed_batch_rejected",
|
|
1773
|
+
message: "protected tool batch rejected before every handler",
|
|
1774
|
+
meta: { toolCallCount: result.toolCalls.length, protectedToolName: protectedCall.call.name },
|
|
719
1775
|
});
|
|
720
|
-
|
|
1776
|
+
continue;
|
|
1777
|
+
}
|
|
1778
|
+
if (protectedCall && protectedCall.policy.kind === "required") {
|
|
1779
|
+
if (!options?.approvalCoordinator) {
|
|
1780
|
+
streamCallbackBuffer?.discard();
|
|
1781
|
+
pushGenerated(msg);
|
|
1782
|
+
const rejection = "rejected: this protected tool requires approval, but the approval coordinator is unavailable; the handler was not invoked.";
|
|
1783
|
+
pushGenerated({ role: "tool", tool_call_id: protectedCall.call.id, content: rejection });
|
|
1784
|
+
providerRuntime.appendToolOutput(protectedCall.call.id, rejection);
|
|
1785
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1786
|
+
level: "warn",
|
|
1787
|
+
component: "engine",
|
|
1788
|
+
event: "engine.approval_coordinator_unavailable",
|
|
1789
|
+
message: "protected tool failed closed before handler execution",
|
|
1790
|
+
meta: { toolName: protectedCall.call.name, toolCallId: protectedCall.call.id },
|
|
1791
|
+
});
|
|
1792
|
+
continue;
|
|
1793
|
+
}
|
|
1794
|
+
streamCallbackBuffer?.discard();
|
|
1795
|
+
pushGenerated(msg);
|
|
1796
|
+
const toolDigest = (0, tool_arguments_1.digestJson)({
|
|
1797
|
+
name: protectedCall.call.name,
|
|
1798
|
+
schemaDigest: protectedCall.validated.schemaDigest,
|
|
1799
|
+
policyId: protectedCall.policy.policyId,
|
|
1800
|
+
});
|
|
1801
|
+
const policyDigest = (0, tool_arguments_1.digestJson)({
|
|
1802
|
+
policyId: protectedCall.policy.policyId,
|
|
1803
|
+
actionClass: protectedCall.policy.actionClass,
|
|
1804
|
+
classification: "required",
|
|
1805
|
+
});
|
|
1806
|
+
const committed = await options.approvalCoordinator.propose({
|
|
1807
|
+
toolCall: structuredClone(msg.tool_calls[0]),
|
|
1808
|
+
arguments: structuredClone(protectedCall.validated.arguments),
|
|
1809
|
+
preCallMessages,
|
|
1810
|
+
frozenAssistantMessage: structuredClone(msg),
|
|
1811
|
+
schemaDigest: protectedCall.validated.schemaDigest,
|
|
1812
|
+
toolDigest,
|
|
1813
|
+
policyDigest,
|
|
1814
|
+
policyId: protectedCall.policy.policyId,
|
|
1815
|
+
actionClass: protectedCall.policy.actionClass,
|
|
1816
|
+
});
|
|
1817
|
+
suspension = {
|
|
1818
|
+
approvalId: committed.approvalId,
|
|
1819
|
+
toolCallId: protectedCall.call.id,
|
|
1820
|
+
checkpointDigest: committed.checkpointDigest,
|
|
1821
|
+
suspendedSessionRevision: committed.suspendedSessionRevision,
|
|
1822
|
+
};
|
|
1823
|
+
outcome = "suspended";
|
|
721
1824
|
done = true;
|
|
1825
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1826
|
+
component: "engine",
|
|
1827
|
+
event: "engine.approval_turn_suspended",
|
|
1828
|
+
message: "agent turn suspended before protected tool execution",
|
|
1829
|
+
meta: { approvalId: committed.approvalId, toolCallId: protectedCall.call.id },
|
|
1830
|
+
});
|
|
722
1831
|
continue;
|
|
723
1832
|
}
|
|
724
|
-
|
|
725
|
-
|
|
1833
|
+
const containsSoleCallOnlyViolation = result.toolCalls.length > 1
|
|
1834
|
+
&& result.toolCalls.some((call) => {
|
|
1835
|
+
const terminalProjection = (0, tools_1.resolveToolDefinition)(call.name)?.terminalProjection;
|
|
1836
|
+
return SOLE_CALL_REJECTION[call.name] !== undefined
|
|
1837
|
+
|| terminalProjection?.requiresSoleCall === true;
|
|
1838
|
+
});
|
|
1839
|
+
if (callbacks.settleOutputMode === "final_only" && containsSoleCallOnlyViolation) {
|
|
1840
|
+
streamCallbackBuffer?.discard();
|
|
1841
|
+
}
|
|
1842
|
+
else {
|
|
1843
|
+
await streamCallbackBuffer?.flush();
|
|
1844
|
+
}
|
|
1845
|
+
pushGenerated(msg);
|
|
1846
|
+
// Execute tools (sole-call tools in mixed calls are rejected inline)
|
|
726
1847
|
for (const tc of result.toolCalls) {
|
|
727
1848
|
if (signal?.aborted)
|
|
728
1849
|
break;
|
|
729
|
-
//
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
1850
|
+
// Reject sole-call tools when mixed with other tool calls
|
|
1851
|
+
const terminalProjection = (0, tools_1.resolveToolDefinition)(tc.name)?.terminalProjection;
|
|
1852
|
+
const soleCallRejection = SOLE_CALL_REJECTION[tc.name]
|
|
1853
|
+
?? (terminalProjection?.requiresSoleCall
|
|
1854
|
+
? `rejected: ${tc.name} must be the only tool call.`
|
|
1855
|
+
: undefined);
|
|
1856
|
+
if (soleCallRejection) {
|
|
1857
|
+
pushGenerated({ role: "tool", tool_call_id: tc.id, content: soleCallRejection });
|
|
1858
|
+
providerRuntime.appendToolOutput(tc.id, soleCallRejection);
|
|
734
1859
|
continue;
|
|
735
1860
|
}
|
|
736
|
-
|
|
737
|
-
if (tc.name === "
|
|
738
|
-
const
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
1861
|
+
const args = validatedCallArguments.get(tc);
|
|
1862
|
+
if (tc.name === "send_message" && args.friendId === "self") {
|
|
1863
|
+
const latestUserText = latestUserMessageText(messages);
|
|
1864
|
+
if (!isPrivateRuntimeChannel && looksLikePrivateReturnRequest(latestUserText)) {
|
|
1865
|
+
const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
|
|
1866
|
+
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.";
|
|
1867
|
+
callbacks.onToolStart(tc.name, args);
|
|
1868
|
+
callbacks.onToolEnd(tc.name, argSummary, false);
|
|
1869
|
+
pushGenerated({ role: "tool", tool_call_id: tc.id, content: rejection });
|
|
1870
|
+
providerRuntime.appendToolOutput(tc.id, rejection);
|
|
1871
|
+
continue;
|
|
1872
|
+
}
|
|
1873
|
+
sawSendMessageSelf = true;
|
|
742
1874
|
}
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
const
|
|
746
|
-
|
|
747
|
-
|
|
1875
|
+
if (tc.name === "speak") {
|
|
1876
|
+
// The canonical pre-batch schema gate guarantees a required string.
|
|
1877
|
+
const speakArgs = JSON.parse(tc.arguments);
|
|
1878
|
+
const speakMessage = speakArgs.message;
|
|
1879
|
+
const argSummary = (0, tools_1.summarizeArgs)("speak", { message: speakMessage });
|
|
1880
|
+
callbacks.onToolStart("speak", { message: speakMessage });
|
|
1881
|
+
if (speakMessage.trim().length === 0) {
|
|
1882
|
+
const err = "speak requires a non-empty `message` string.";
|
|
1883
|
+
callbacks.onToolEnd("speak", argSummary, false);
|
|
1884
|
+
pushGenerated({ role: "tool", tool_call_id: tc.id, content: err });
|
|
1885
|
+
providerRuntime.appendToolOutput(tc.id, err);
|
|
1886
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1887
|
+
level: "warn",
|
|
1888
|
+
component: "engine",
|
|
1889
|
+
event: "engine.speak_invalid",
|
|
1890
|
+
message: "speak rejected: missing or empty message",
|
|
1891
|
+
meta: {},
|
|
1892
|
+
});
|
|
1893
|
+
continue;
|
|
1894
|
+
}
|
|
1895
|
+
callbacks.onTextChunk(speakMessage);
|
|
1896
|
+
let speakDeliveryError = null;
|
|
1897
|
+
try {
|
|
1898
|
+
await callbacks.flushNow?.();
|
|
1899
|
+
}
|
|
1900
|
+
catch (err) {
|
|
1901
|
+
speakDeliveryError = err instanceof Error ? err : new Error(String(err));
|
|
1902
|
+
}
|
|
1903
|
+
if (speakDeliveryError) {
|
|
1904
|
+
callbacks.onToolEnd("speak", argSummary, false);
|
|
1905
|
+
const failMsg = `speak delivery failed: ${speakDeliveryError.message}. the message did not reach your friend; do not assume they saw it.`;
|
|
1906
|
+
pushGenerated({ role: "tool", tool_call_id: tc.id, content: failMsg });
|
|
1907
|
+
providerRuntime.appendToolOutput(tc.id, failMsg);
|
|
1908
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1909
|
+
level: "error",
|
|
1910
|
+
component: "engine",
|
|
1911
|
+
event: "engine.speak_delivery_failed",
|
|
1912
|
+
message: "speak delivery failed",
|
|
1913
|
+
meta: { error: speakDeliveryError.message, messageLength: speakMessage.length },
|
|
1914
|
+
});
|
|
1915
|
+
continue;
|
|
1916
|
+
}
|
|
1917
|
+
callbacks.onToolEnd("speak", argSummary, true);
|
|
1918
|
+
const ack = "(spoken)";
|
|
1919
|
+
pushGenerated({ role: "tool", tool_call_id: tc.id, content: ack });
|
|
1920
|
+
providerRuntime.appendToolOutput(tc.id, ack);
|
|
1921
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1922
|
+
component: "engine",
|
|
1923
|
+
event: "engine.speak",
|
|
1924
|
+
message: "agent spoke mid-turn",
|
|
1925
|
+
meta: { messageLength: speakMessage.length },
|
|
1926
|
+
});
|
|
748
1927
|
continue;
|
|
749
1928
|
}
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
1929
|
+
if (tc.name === "ponder") {
|
|
1930
|
+
const parsedArgs = normalizeLegacyPonderArgs(parsePonderPayload(tc.arguments));
|
|
1931
|
+
const argSummary = (0, tools_1.summarizeArgs)(tc.name, parsedArgs);
|
|
1932
|
+
callbacks.onToolStart(tc.name, parsedArgs);
|
|
1933
|
+
let toolResult;
|
|
1934
|
+
let success = false;
|
|
1935
|
+
try {
|
|
1936
|
+
const action = parsedArgs.action ?? "create";
|
|
1937
|
+
const currentSession = augmentedToolContext?.currentSession;
|
|
1938
|
+
const currentOrigin = currentSession
|
|
1939
|
+
? { friendId: currentSession.friendId, channel: currentSession.channel, key: currentSession.key }
|
|
1940
|
+
: undefined;
|
|
1941
|
+
const isInnerChannel = currentOrigin?.friendId === "self" && currentOrigin?.channel === "inner";
|
|
1942
|
+
const shouldCreateReturnObligation = !!currentOrigin && !isInnerChannel;
|
|
1943
|
+
const attentionQueue = augmentedToolContext?.delegatedOrigins ?? [];
|
|
1944
|
+
const successCriteria = parseSuccessCriteria(parsedArgs.success_criteria);
|
|
1945
|
+
const payload = parsePacketPayload(parsedArgs.payload_json);
|
|
1946
|
+
let packet;
|
|
1947
|
+
let returnObligationId = null;
|
|
1948
|
+
let resultAction = "created";
|
|
1949
|
+
let privateReturnSourceRequest = "";
|
|
1950
|
+
if (action === "create") {
|
|
1951
|
+
if (isInnerChannel && attentionQueue.length > 0) {
|
|
1952
|
+
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.");
|
|
1953
|
+
}
|
|
1954
|
+
const kind = parsedArgs.kind;
|
|
1955
|
+
const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
|
|
1956
|
+
const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
|
|
1957
|
+
const sourceRequest = currentOrigin && !isInnerChannel ? latestUserMessageText(messages) : "";
|
|
1958
|
+
privateReturnSourceRequest = sourceRequest;
|
|
1959
|
+
if (!kind || !objective || !successCriteria || !payload) {
|
|
1960
|
+
throw new Error("ponder create requires kind, objective, success_criteria, and valid payload_json.");
|
|
1961
|
+
}
|
|
1962
|
+
const packetPayload = sourceRequest
|
|
1963
|
+
? { ...payload, sourceRequest }
|
|
1964
|
+
: payload;
|
|
1965
|
+
const createLinkedReturnObligation = (id, packetId) => {
|
|
1966
|
+
(0, obligations_1.createReturnObligation)((0, identity_2.getAgentName)(), {
|
|
1967
|
+
id,
|
|
1968
|
+
origin: currentOrigin,
|
|
1969
|
+
status: "queued",
|
|
1970
|
+
delegatedContent: buildPonderDelegatedContent({ summary, objective, sourceRequest }),
|
|
1971
|
+
packetId,
|
|
1972
|
+
createdAt: Date.now(),
|
|
1973
|
+
});
|
|
1974
|
+
};
|
|
1975
|
+
const agentRoot = (0, identity_2.getAgentRoot)();
|
|
1976
|
+
let relatedObligationId;
|
|
1977
|
+
if (currentOrigin && !isInnerChannel) {
|
|
1978
|
+
try {
|
|
1979
|
+
const obligation = (0, obligations_1.createObligation)(agentRoot, {
|
|
1980
|
+
origin: currentOrigin,
|
|
1981
|
+
content: objective,
|
|
1982
|
+
});
|
|
1983
|
+
relatedObligationId = obligation.id;
|
|
1984
|
+
}
|
|
1985
|
+
catch {
|
|
1986
|
+
relatedObligationId = undefined;
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
const frictionSignature = kind === "harness_friction" && typeof packetPayload.frictionSignature === "string"
|
|
1990
|
+
? packetPayload.frictionSignature
|
|
1991
|
+
: null;
|
|
1992
|
+
const existing = frictionSignature && currentOrigin
|
|
1993
|
+
? (0, packets_1.findHarnessFrictionPacket)(agentRoot, currentOrigin, frictionSignature)
|
|
1994
|
+
: null;
|
|
1995
|
+
if (existing) {
|
|
1996
|
+
resultAction = "revised";
|
|
1997
|
+
const existingActiveReturnId = shouldCreateReturnObligation
|
|
1998
|
+
? activeReturnObligationId((0, identity_2.getAgentName)(), existing.relatedReturnObligationId)
|
|
1999
|
+
: null;
|
|
2000
|
+
returnObligationId = existingActiveReturnId
|
|
2001
|
+
?? (shouldCreateReturnObligation ? (0, obligations_1.generateObligationId)(Date.now()) : null);
|
|
2002
|
+
packet = existing.status === "drafting"
|
|
2003
|
+
? (0, packets_1.revisePonderPacket)(agentRoot, existing.id, {
|
|
2004
|
+
kind,
|
|
2005
|
+
objective,
|
|
2006
|
+
summary,
|
|
2007
|
+
successCriteria,
|
|
2008
|
+
payload: packetPayload,
|
|
2009
|
+
})
|
|
2010
|
+
: existing;
|
|
2011
|
+
if (returnObligationId && returnObligationId !== existing.relatedReturnObligationId) {
|
|
2012
|
+
packet = (0, packets_1.advancePonderPacket)(agentRoot, packet.id, { relatedReturnObligationId: returnObligationId });
|
|
2013
|
+
createLinkedReturnObligation(returnObligationId, packet.id);
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
else {
|
|
2017
|
+
returnObligationId = shouldCreateReturnObligation ? (0, obligations_1.generateObligationId)(Date.now()) : null;
|
|
2018
|
+
packet = (0, packets_1.createPonderPacket)(agentRoot, {
|
|
2019
|
+
kind,
|
|
2020
|
+
objective,
|
|
2021
|
+
summary,
|
|
2022
|
+
successCriteria,
|
|
2023
|
+
...(currentOrigin ? { origin: currentOrigin } : {}),
|
|
2024
|
+
...(relatedObligationId ? { relatedObligationId } : {}),
|
|
2025
|
+
...(returnObligationId ? { relatedReturnObligationId: returnObligationId } : {}),
|
|
2026
|
+
...(parsedArgs.follows_packet_id ? { followsPacketId: parsedArgs.follows_packet_id } : {}),
|
|
2027
|
+
payload: packetPayload,
|
|
2028
|
+
});
|
|
2029
|
+
if (returnObligationId) {
|
|
2030
|
+
createLinkedReturnObligation(returnObligationId, packet.id);
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
else {
|
|
2035
|
+
const packetId = typeof parsedArgs.packet_id === "string" ? parsedArgs.packet_id.trim() : "";
|
|
2036
|
+
const kind = parsedArgs.kind;
|
|
2037
|
+
const objective = typeof parsedArgs.objective === "string" ? parsedArgs.objective.trim() : "";
|
|
2038
|
+
const summary = typeof parsedArgs.summary === "string" ? parsedArgs.summary.trim() : "";
|
|
2039
|
+
if (!packetId || !kind || !objective || !successCriteria || !payload) {
|
|
2040
|
+
throw new Error("ponder revise requires packet_id, kind, objective, success_criteria, and valid payload_json.");
|
|
2041
|
+
}
|
|
2042
|
+
packet = (0, packets_1.revisePonderPacket)((0, identity_2.getAgentRoot)(), packetId, {
|
|
2043
|
+
kind,
|
|
2044
|
+
objective,
|
|
2045
|
+
summary,
|
|
2046
|
+
successCriteria,
|
|
2047
|
+
payload,
|
|
2048
|
+
});
|
|
2049
|
+
returnObligationId = packet.relatedReturnObligationId
|
|
2050
|
+
&& !(packet.origin?.friendId === "self" && packet.origin.channel === "inner")
|
|
2051
|
+
? packet.relatedReturnObligationId
|
|
2052
|
+
: null;
|
|
2053
|
+
resultAction = "revised";
|
|
2054
|
+
}
|
|
2055
|
+
if (returnObligationId) {
|
|
2056
|
+
for (const token of extractPrivateReturnHeldTokens(privateReturnSourceRequest)) {
|
|
2057
|
+
privateReturnHeldTokens.add(token);
|
|
2058
|
+
}
|
|
2059
|
+
const agentName = (0, identity_2.getAgentName)();
|
|
2060
|
+
await (0, socket_client_1.requestPrivateWake)(agentName, augmentedToolContext?.daemonSocketPath, buildPonderReturnPrivateWakeOptions({ agentName, packet, returnObligationId })).catch(() => undefined);
|
|
2061
|
+
}
|
|
2062
|
+
sawPonder = true;
|
|
2063
|
+
toolResult = buildPonderResult(packet, resultAction, returnObligationId);
|
|
2064
|
+
success = true;
|
|
2065
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2066
|
+
component: "engine",
|
|
2067
|
+
event: "engine.ponder_packet",
|
|
2068
|
+
message: "ponder packet touched",
|
|
2069
|
+
meta: {
|
|
2070
|
+
action: resultAction,
|
|
2071
|
+
packetId: packet.id,
|
|
2072
|
+
kind: packet.kind,
|
|
2073
|
+
status: packet.status,
|
|
2074
|
+
},
|
|
2075
|
+
});
|
|
2076
|
+
}
|
|
2077
|
+
catch (error) {
|
|
2078
|
+
toolResult = error instanceof Error ? error.message : String(error);
|
|
2079
|
+
}
|
|
2080
|
+
callbacks.onToolEnd(tc.name, argSummary, success);
|
|
2081
|
+
pushGenerated({ role: "tool", tool_call_id: tc.id, content: toolResult });
|
|
2082
|
+
providerRuntime.appendToolOutput(tc.id, toolResult);
|
|
2083
|
+
continue;
|
|
759
2084
|
}
|
|
760
2085
|
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
761
2086
|
if (tc.name === "query_session")
|
|
@@ -763,105 +2088,85 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
763
2088
|
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
764
2089
|
if (tc.name === "bridge_manage")
|
|
765
2090
|
sawBridgeManage = true;
|
|
2091
|
+
/* v8 ignore next -- flag tested via truth-check integration tests @preserve */
|
|
2092
|
+
if (isExternalStateQuery(tc.name, args))
|
|
2093
|
+
sawExternalStateQuery = true;
|
|
766
2094
|
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
|
-
}
|
|
2095
|
+
const toolLoop = (0, tool_loop_1.detectToolLoop)(toolLoopState, tc.name, args);
|
|
2096
|
+
if (toolLoop.stuck) {
|
|
2097
|
+
const rejection = `loop guard: ${toolLoop.message}`;
|
|
2098
|
+
callbacks.onToolStart(tc.name, args);
|
|
2099
|
+
callbacks.onToolEnd(tc.name, argSummary, false);
|
|
2100
|
+
pushGenerated({ role: "tool", tool_call_id: tc.id, content: rejection });
|
|
2101
|
+
providerRuntime.appendToolOutput(tc.id, rejection);
|
|
2102
|
+
continue;
|
|
781
2103
|
}
|
|
782
2104
|
callbacks.onToolStart(tc.name, args);
|
|
783
2105
|
let toolResult;
|
|
784
2106
|
let success;
|
|
785
2107
|
try {
|
|
786
2108
|
const execToolFn = options?.execTool ?? tools_1.execTool;
|
|
787
|
-
|
|
2109
|
+
const routineActionSelection = approvalCalls.find((entry) => entry.call.id === tc.id)?.routineActionSelection;
|
|
2110
|
+
const executionToolContext = routineActionSelection && augmentedToolContext ? { ...augmentedToolContext, routineActionSelection } : augmentedToolContext;
|
|
2111
|
+
toolResult = await execToolFn(tc.name, args, executionToolContext);
|
|
788
2112
|
success = true;
|
|
789
2113
|
}
|
|
790
2114
|
catch (e) {
|
|
791
2115
|
toolResult = `error: ${e}`;
|
|
792
2116
|
success = false;
|
|
2117
|
+
augmentedToolContext?.habitSession?.recordError?.(toolResult);
|
|
793
2118
|
}
|
|
794
|
-
|
|
795
|
-
|
|
2119
|
+
const resolvedRiskProfile = (0, tools_1.resolveToolDefinition)(tc.name)?.riskProfile;
|
|
2120
|
+
const toolRiskProfile = typeof resolvedRiskProfile === "function" ? resolvedRiskProfile(args) : resolvedRiskProfile;
|
|
2121
|
+
options?.toolBoundaryObserver?.({
|
|
2122
|
+
name: tc.name,
|
|
2123
|
+
reason: "dispatched",
|
|
2124
|
+
globallyResolvable: typeof (0, tools_1.resolveToolDefinition)(tc.name)?.handler === "function",
|
|
2125
|
+
invoked: true,
|
|
2126
|
+
sideEffect: success && toolRiskProfile?.mutates !== "none",
|
|
2127
|
+
});
|
|
2128
|
+
toolResult = (0, tool_friction_1.rewriteToolResultForModel)(tc.name, toolResult, toolFrictionLedger);
|
|
2129
|
+
(0, tool_loop_1.recordToolOutcome)(toolLoopState, tc.name, args, toolResult, success);
|
|
2130
|
+
callbacks.onToolEnd(tc.name, (0, tools_1.buildToolResultSummary)(tc.name, args, toolResult, success), success);
|
|
2131
|
+
pushGenerated({ role: "tool", tool_call_id: tc.id, content: toolResult });
|
|
796
2132
|
providerRuntime.appendToolOutput(tc.id, toolResult);
|
|
2133
|
+
callbacks.onToolResult?.(messages);
|
|
797
2134
|
}
|
|
798
2135
|
}
|
|
799
2136
|
}
|
|
800
2137
|
catch (e) {
|
|
801
2138
|
// Abort is not an error — just stop cleanly
|
|
802
|
-
if (signal?.aborted) {
|
|
2139
|
+
if (e instanceof provider_attempt_1.ProviderAttemptAbortError || signal?.aborted) {
|
|
803
2140
|
stripLastToolCalls(messages);
|
|
2141
|
+
stripLastToolCalls(generatedMessages);
|
|
804
2142
|
outcome = "aborted";
|
|
805
2143
|
break;
|
|
806
2144
|
}
|
|
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;
|
|
2145
|
+
const errorForClassification = e instanceof Error ? e : /* v8 ignore next -- defensive @preserve */ new Error(String(e));
|
|
2146
|
+
let providerClassification;
|
|
2147
|
+
try {
|
|
2148
|
+
providerClassification = providerRuntime.classifyError(errorForClassification);
|
|
817
2149
|
}
|
|
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;
|
|
2150
|
+
catch {
|
|
2151
|
+
/* v8 ignore next -- defensive: classifyError should not throw @preserve */
|
|
2152
|
+
providerClassification = "unknown";
|
|
844
2153
|
}
|
|
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;
|
|
2154
|
+
finishTerminalProviderError(errorForClassification, providerClassification);
|
|
857
2155
|
}
|
|
858
2156
|
}
|
|
2157
|
+
options?.captureGeneratedMessages?.(structuredClone(generatedMessages));
|
|
859
2158
|
(0, runtime_1.emitNervesEvent)({
|
|
860
2159
|
event: "engine.turn_end",
|
|
861
2160
|
trace_id: traceId,
|
|
862
2161
|
component: "engine",
|
|
863
2162
|
message: "runAgent turn completed",
|
|
864
|
-
meta: { done,
|
|
2163
|
+
meta: { done, sawPonder, sawQuerySession, sawBridgeManage },
|
|
865
2164
|
});
|
|
866
|
-
return {
|
|
2165
|
+
return {
|
|
2166
|
+
usage: lastUsage,
|
|
2167
|
+
outcome,
|
|
2168
|
+
completion,
|
|
2169
|
+
...(suspension ? { suspension } : {}),
|
|
2170
|
+
...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
|
|
2171
|
+
};
|
|
867
2172
|
}
|