nova-personal-agent-server 0.0.0-stage → 0.4.0
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 +201 -0
- package/README.md +30 -2
- package/bin/novapersonal-server.mjs +4 -0
- package/package.json +61 -4
- package/resources/endpointing/volcengine-v1/LICENSE.silero-vad.txt +21 -0
- package/resources/endpointing/volcengine-v1/MANIFEST.json +31 -0
- package/resources/endpointing/volcengine-v1/silence-16k-s16le.pcm +0 -0
- package/resources/endpointing/volcengine-v1/speech-16k-s16le.pcm +0 -0
- package/resources/native/codex-sandbox-probe +0 -0
- package/resources/native/project-native/nova_project_native.node +0 -0
- package/resources/native-resources-v1.json +1 -0
- package/runtime/dist/eval/demos.js +156 -0
- package/runtime/dist/eval/fixture-host.js +385 -0
- package/runtime/dist/eval/fixtures.js +319 -0
- package/runtime/dist/eval/realtime/session-fixtures.js +474 -0
- package/runtime/dist/eval/scorecard.js +285 -0
- package/runtime/dist/eval/sim.js +43 -0
- package/runtime/dist/src/cascaded-text-provider.js +31 -0
- package/runtime/dist/src/cli.js +96 -0
- package/runtime/dist/src/composition/assembly.js +352 -0
- package/runtime/dist/src/composition/cascaded-realtime-assembly.js +455 -0
- package/runtime/dist/src/composition/production-composition.js +389 -0
- package/runtime/dist/src/composition/realtime-assembly.js +1330 -0
- package/runtime/dist/src/config/capability-registry.js +315 -0
- package/runtime/dist/src/config/cascaded-realtime-config.js +146 -0
- package/runtime/dist/src/config/coding-backends.js +8 -0
- package/runtime/dist/src/config/coding-profiles.js +98 -0
- package/runtime/dist/src/config/config.js +857 -0
- package/runtime/dist/src/config/diagnostics.js +139 -0
- package/runtime/dist/src/config/environment-contract.js +202 -0
- package/runtime/dist/src/config/self-hosted.js +23 -0
- package/runtime/dist/src/connectors/composio/client.js +195 -0
- package/runtime/dist/src/connectors/composio/google.js +208 -0
- package/runtime/dist/src/connectors/composio/index.js +334 -0
- package/runtime/dist/src/connectors/feishu/cli.js +220 -0
- package/runtime/dist/src/connectors/feishu/index.js +980 -0
- package/runtime/dist/src/connectors/macos/calendar.js +35 -0
- package/runtime/dist/src/connectors/macos/mail.js +32 -0
- package/runtime/dist/src/connectors/macos/reader.js +62 -0
- package/runtime/dist/src/conversation-voice-provider.js +41 -0
- package/runtime/dist/src/core/approval-port.js +9 -0
- package/runtime/dist/src/core/approval.js +1328 -0
- package/runtime/dist/src/core/calls.js +35 -0
- package/runtime/dist/src/core/camera-session.js +32 -0
- package/runtime/dist/src/core/causal-runtime.js +650 -0
- package/runtime/dist/src/core/clock.js +139 -0
- package/runtime/dist/src/core/context-view.js +156 -0
- package/runtime/dist/src/core/effects.js +62 -0
- package/runtime/dist/src/core/events.js +217 -0
- package/runtime/dist/src/core/executor-diagnostic.js +9 -0
- package/runtime/dist/src/core/ids.js +32 -0
- package/runtime/dist/src/core/media-store.js +104 -0
- package/runtime/dist/src/core/memory.js +296 -0
- package/runtime/dist/src/core/pending-decision.js +64 -0
- package/runtime/dist/src/core/ports.js +125 -0
- package/runtime/dist/src/core/runtime.js +1459 -0
- package/runtime/dist/src/core/schedule-tools.js +15 -0
- package/runtime/dist/src/core/sims.js +186 -0
- package/runtime/dist/src/core/slots.js +97 -0
- package/runtime/dist/src/core/source-processing-instructions.js +3 -0
- package/runtime/dist/src/core/source-processing-tools.js +12 -0
- package/runtime/dist/src/core/suggestions.js +143 -0
- package/runtime/dist/src/core/task-tools.js +22 -0
- package/runtime/dist/src/core/tool-schema.js +212 -0
- package/runtime/dist/src/core/trace.js +34 -0
- package/runtime/dist/src/core/work-tools.js +94 -0
- package/runtime/dist/src/desktop/desktop-camera-source.js +31 -0
- package/runtime/dist/src/desktop/desktop-camera.js +281 -0
- package/runtime/dist/src/desktop/desktop-control.js +140 -0
- package/runtime/dist/src/desktop/desktop-progress.js +162 -0
- package/runtime/dist/src/desktop/desktop-session.js +2106 -0
- package/runtime/dist/src/desktop/desktop-tasks.js +80 -0
- package/runtime/dist/src/desktop/desktop-wire.js +605 -0
- package/runtime/dist/src/desktop/phone-desktop-entry.js +17 -0
- package/runtime/dist/src/desktop/startup-error.js +18 -0
- package/runtime/dist/src/desktop/workbench-acceptance.js +262 -0
- package/runtime/dist/src/desktop-entry.js +106 -0
- package/runtime/dist/src/desktop.js +1092 -0
- package/runtime/dist/src/executors/acp/backends.js +105 -0
- package/runtime/dist/src/executors/acp/mcp.js +81 -0
- package/runtime/dist/src/executors/acp/preflight.js +14 -0
- package/runtime/dist/src/executors/acp/process-owner.js +112 -0
- package/runtime/dist/src/executors/acp/transport.js +760 -0
- package/runtime/dist/src/executors/acp/windows-launch.js +68 -0
- package/runtime/dist/src/executors/agent-controller.js +244 -0
- package/runtime/dist/src/executors/autoglm.js +376 -0
- package/runtime/dist/src/executors/browser-device.js +102 -0
- package/runtime/dist/src/executors/browser.js +61 -0
- package/runtime/dist/src/executors/camera.js +101 -0
- package/runtime/dist/src/executors/chromium-frame-source.js +173 -0
- package/runtime/dist/src/executors/codex/adapter-live.js +292 -0
- package/runtime/dist/src/executors/codex/adapter-project.js +1306 -0
- package/runtime/dist/src/executors/codex/app-server-schema.js +712 -0
- package/runtime/dist/src/executors/codex/app-server-transport.js +1798 -0
- package/runtime/dist/src/executors/codex/approval-protocol.js +439 -0
- package/runtime/dist/src/executors/codex/common.js +655 -0
- package/runtime/dist/src/executors/codex/contract.js +581 -0
- package/runtime/dist/src/executors/codex/controller.js +141 -0
- package/runtime/dist/src/executors/codex/credential-snapshot.js +195 -0
- package/runtime/dist/src/executors/codex/factory.js +463 -0
- package/runtime/dist/src/executors/codex/host-config.js +238 -0
- package/runtime/dist/src/executors/codex/host.js +17 -0
- package/runtime/dist/src/executors/codex/index.js +19 -0
- package/runtime/dist/src/executors/codex/launch-profile.js +37 -0
- package/runtime/dist/src/executors/codex/local-sessions.js +119 -0
- package/runtime/dist/src/executors/codex/managed-mcp.js +196 -0
- package/runtime/dist/src/executors/codex/process-owner.js +398 -0
- package/runtime/dist/src/executors/codex/production-host.js +887 -0
- package/runtime/dist/src/executors/codex/progress-instructions.js +10 -0
- package/runtime/dist/src/executors/codex/protocol.js +581 -0
- package/runtime/dist/src/executors/codex/safe-json.js +87 -0
- package/runtime/dist/src/executors/codex/session-title.js +61 -0
- package/runtime/dist/src/executors/codex/shared-home.js +29 -0
- package/runtime/dist/src/executors/codex/spawn-env.js +162 -0
- package/runtime/dist/src/executors/codex/turn-projection.js +435 -0
- package/runtime/dist/src/executors/codex/version.js +38 -0
- package/runtime/dist/src/executors/codex/windows-guardian.js +716 -0
- package/runtime/dist/src/executors/coding/intake-model.js +103 -0
- package/runtime/dist/src/executors/coding/intake.js +824 -0
- package/runtime/dist/src/executors/coding/json-completion.js +14 -0
- package/runtime/dist/src/executors/coding/target-resolution.js +61 -0
- package/runtime/dist/src/executors/coding/work-order.js +50 -0
- package/runtime/dist/src/executors/coding-executor.js +23 -0
- package/runtime/dist/src/executors/computer-backend.js +188 -0
- package/runtime/dist/src/executors/computer-device.js +187 -0
- package/runtime/dist/src/executors/computer-worker.js +125 -0
- package/runtime/dist/src/executors/computer.js +100 -0
- package/runtime/dist/src/executors/device-lock.js +127 -0
- package/runtime/dist/src/executors/frame-source.js +29 -0
- package/runtime/dist/src/executors/gui-evidence.js +30 -0
- package/runtime/dist/src/executors/gui-execution.js +237 -0
- package/runtime/dist/src/executors/gui-runner.js +88 -0
- package/runtime/dist/src/executors/host-executor-capability.js +12 -0
- package/runtime/dist/src/executors/index.js +13 -0
- package/runtime/dist/src/executors/mcp-client.js +198 -0
- package/runtime/dist/src/executors/mcp.js +210 -0
- package/runtime/dist/src/executors/mobile-android.js +180 -0
- package/runtime/dist/src/executors/mobile-ios.js +303 -0
- package/runtime/dist/src/executors/mobile.js +78 -0
- package/runtime/dist/src/executors/search-mcp.js +146 -0
- package/runtime/dist/src/executors/search.js +524 -0
- package/runtime/dist/src/executors/task-resources.js +38 -0
- package/runtime/dist/src/executors/vision/assess.js +296 -0
- package/runtime/dist/src/executors/vision/controller-core.js +373 -0
- package/runtime/dist/src/executors/vision/controller.js +164 -0
- package/runtime/dist/src/executors/vision/lifecycle.js +69 -0
- package/runtime/dist/src/executors/vision.js +5 -0
- package/runtime/dist/src/executors/watcher.js +718 -0
- package/runtime/dist/src/http/bounded-response.js +37 -0
- package/runtime/dist/src/index.js +56 -0
- package/runtime/dist/src/knowledge/assembly.js +60 -0
- package/runtime/dist/src/knowledge/documents.js +520 -0
- package/runtime/dist/src/knowledge/embeddings.js +201 -0
- package/runtime/dist/src/knowledge/mcp.js +218 -0
- package/runtime/dist/src/knowledge/parse-worker.js +122 -0
- package/runtime/dist/src/knowledge/references.js +51 -0
- package/runtime/dist/src/knowledge/service.js +526 -0
- package/runtime/dist/src/knowledge/store-client.js +185 -0
- package/runtime/dist/src/knowledge/store-worker.js +843 -0
- package/runtime/dist/src/knowledge/types.js +2 -0
- package/runtime/dist/src/mcp/http-server.js +177 -0
- package/runtime/dist/src/mem0/resource.js +35 -0
- package/runtime/dist/src/mem0/store-worker.js +330 -0
- package/runtime/dist/src/memory/blackboard-session.js +205 -0
- package/runtime/dist/src/memory/blackboard-store.js +194 -0
- package/runtime/dist/src/memory/blackboard-worker.js +369 -0
- package/runtime/dist/src/memory/entry.js +39 -0
- package/runtime/dist/src/memory/factory.js +20 -0
- package/runtime/dist/src/memory/personal-memory-inspection.js +18 -0
- package/runtime/dist/src/memory/personal-memory.js +10 -0
- package/runtime/dist/src/memory/prerecall.js +20 -0
- package/runtime/dist/src/memory/provenance.js +17 -0
- package/runtime/dist/src/memory/remote-personal-memory.js +194 -0
- package/runtime/dist/src/memory/retrieval.js +235 -0
- package/runtime/dist/src/memory/sensitivity.js +261 -0
- package/runtime/dist/src/memory-ledger/models.js +98 -0
- package/runtime/dist/src/memory-ledger/store-client.js +210 -0
- package/runtime/dist/src/memory-ledger/store-worker.js +130 -0
- package/runtime/dist/src/memory-ledger/store.js +597 -0
- package/runtime/dist/src/memory-substrate/candidates.js +16 -0
- package/runtime/dist/src/memory-substrate/consolidation.js +124 -0
- package/runtime/dist/src/memory-substrate/file-authority.js +111 -0
- package/runtime/dist/src/memory-substrate/life-operations.js +280 -0
- package/runtime/dist/src/memory-substrate/markdown-repository.js +610 -0
- package/runtime/dist/src/memory-substrate/migration.js +87 -0
- package/runtime/dist/src/memory-substrate/profile-source-input.js +9 -0
- package/runtime/dist/src/memory-substrate/purge.js +398 -0
- package/runtime/dist/src/memory-substrate/resolution.js +32 -0
- package/runtime/dist/src/memory-substrate/resource.js +867 -0
- package/runtime/dist/src/memory-substrate/retrieval.js +85 -0
- package/runtime/dist/src/memory-substrate/source-operations.js +306 -0
- package/runtime/dist/src/memory-substrate/source-processing.js +326 -0
- package/runtime/dist/src/memory-substrate/source-state.js +93 -0
- package/runtime/dist/src/memory-substrate/store.js +534 -0
- package/runtime/dist/src/memory-substrate/workspace-projections.js +106 -0
- package/runtime/dist/src/memory-substrate/workspace.js +21 -0
- package/runtime/dist/src/model/jev-client.js +25 -0
- package/runtime/dist/src/model/model-adapters.js +64 -0
- package/runtime/dist/src/model/model-gateway.js +399 -0
- package/runtime/dist/src/model/model-lane.js +34 -0
- package/runtime/dist/src/model/model-purpose.js +5 -0
- package/runtime/dist/src/model/personal-writer.js +361 -0
- package/runtime/dist/src/model/proactivity.js +72 -0
- package/runtime/dist/src/model/prompting.js +279 -0
- package/runtime/dist/src/model/task-verifier.js +217 -0
- package/runtime/dist/src/model/vision-capability.js +10 -0
- package/runtime/dist/src/news/feeds.js +114 -0
- package/runtime/dist/src/news/jev-ranking.js +25 -0
- package/runtime/dist/src/news/ranking.js +26 -0
- package/runtime/dist/src/news/service.js +262 -0
- package/runtime/dist/src/notifications/adapters/feishu.js +10 -0
- package/runtime/dist/src/notifications/adapters/nova.js +15 -0
- package/runtime/dist/src/notifications/content.js +15 -0
- package/runtime/dist/src/notifications/contracts.js +9 -0
- package/runtime/dist/src/notifications/feed.js +8 -0
- package/runtime/dist/src/notifications/service.js +412 -0
- package/runtime/dist/src/notifications/store.js +4 -0
- package/runtime/dist/src/personal-agent/app-context.js +113 -0
- package/runtime/dist/src/personal-agent/approval-scope.js +8 -0
- package/runtime/dist/src/personal-agent/coding-targets.js +82 -0
- package/runtime/dist/src/personal-agent/context-candidates.js +94 -0
- package/runtime/dist/src/personal-agent/contracts.js +32 -0
- package/runtime/dist/src/personal-agent/conversation-runtime.js +536 -0
- package/runtime/dist/src/personal-agent/conversations.js +187 -0
- package/runtime/dist/src/personal-agent/daily-brief.js +53 -0
- package/runtime/dist/src/personal-agent/host.js +2403 -0
- package/runtime/dist/src/personal-agent/intake-task.js +37 -0
- package/runtime/dist/src/personal-agent/life.js +260 -0
- package/runtime/dist/src/personal-agent/memory-overview.js +19 -0
- package/runtime/dist/src/personal-agent/profile-sources.js +34 -0
- package/runtime/dist/src/personal-agent/profile-warmup.js +244 -0
- package/runtime/dist/src/personal-agent/project-digests.js +242 -0
- package/runtime/dist/src/personal-agent/sampling.js +20 -0
- package/runtime/dist/src/personal-agent/schedule-agent.js +60 -0
- package/runtime/dist/src/personal-agent/schedule-api.js +61 -0
- package/runtime/dist/src/personal-agent/schedule-presets.js +13 -0
- package/runtime/dist/src/personal-agent/schedule-reference.js +3 -0
- package/runtime/dist/src/personal-agent/scheduled-response-scope.js +38 -0
- package/runtime/dist/src/personal-agent/scheduled-run-authority.js +44 -0
- package/runtime/dist/src/personal-agent/scheduled-tasks.js +280 -0
- package/runtime/dist/src/personal-agent/scheduled-time.js +99 -0
- package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +109 -0
- package/runtime/dist/src/personal-agent/source-priority.js +142 -0
- package/runtime/dist/src/personal-agent/source-processing-agent.js +158 -0
- package/runtime/dist/src/personal-agent/source-walk.js +25 -0
- package/runtime/dist/src/personal-agent/sources.js +1484 -0
- package/runtime/dist/src/personal-agent/store-lock-worker.js +17 -0
- package/runtime/dist/src/personal-agent/store.js +146 -0
- package/runtime/dist/src/personal-agent/task-loop.js +163 -0
- package/runtime/dist/src/personal-agent/tasks.js +920 -0
- package/runtime/dist/src/personal-agent/turn-deadline.js +55 -0
- package/runtime/dist/src/personal-agent/understanding.js +160 -0
- package/runtime/dist/src/personal-agent/workbench-context.js +239 -0
- package/runtime/dist/src/projects/confirmed-project-capability.js +60 -0
- package/runtime/dist/src/projects/host-paths.js +133 -0
- package/runtime/dist/src/projects/managed-workspace-maintenance.js +351 -0
- package/runtime/dist/src/projects/project-confirmation.js +486 -0
- package/runtime/dist/src/projects/project-native-resource.js +284 -0
- package/runtime/dist/src/projects/project-node-files.js +169 -0
- package/runtime/dist/src/projects/project-root-file.js +16 -0
- package/runtime/dist/src/projects/project-state.js +504 -0
- package/runtime/dist/src/projects/project-store-files.js +1271 -0
- package/runtime/dist/src/projects/project-store.js +1345 -0
- package/runtime/dist/src/realtime/aoq.js +141 -0
- package/runtime/dist/src/realtime/bridge.js +652 -0
- package/runtime/dist/src/realtime/cascaded/adapter.js +1669 -0
- package/runtime/dist/src/realtime/cascaded/ark-llm.js +219 -0
- package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +478 -0
- package/runtime/dist/src/realtime/cascaded/gemini-speech.js +232 -0
- package/runtime/dist/src/realtime/cascaded/llm.js +37 -0
- package/runtime/dist/src/realtime/cascaded/ports.js +2 -0
- package/runtime/dist/src/realtime/cascaded/provider.js +216 -0
- package/runtime/dist/src/realtime/cascaded/qwen-llm.js +7 -0
- package/runtime/dist/src/realtime/cascaded/self-hosted-asr.js +110 -0
- package/runtime/dist/src/realtime/cascaded/self-hosted-tts.js +137 -0
- package/runtime/dist/src/realtime/cascaded/transcribe.js +42 -0
- package/runtime/dist/src/realtime/coding-progress-narration.js +28 -0
- package/runtime/dist/src/realtime/confirmation-turn-isolation.js +586 -0
- package/runtime/dist/src/realtime/dictation.js +28 -0
- package/runtime/dist/src/realtime/evidence.js +276 -0
- package/runtime/dist/src/realtime/floor.js +43 -0
- package/runtime/dist/src/realtime/frontend-instructions.js +195 -0
- package/runtime/dist/src/realtime/gemini.js +517 -0
- package/runtime/dist/src/realtime/history.js +122 -0
- package/runtime/dist/src/realtime/host-delivery.js +1711 -0
- package/runtime/dist/src/realtime/integrated-wire-profile.js +128 -0
- package/runtime/dist/src/realtime/memory-board.js +105 -0
- package/runtime/dist/src/realtime/openai-wire-profile.js +46 -0
- package/runtime/dist/src/realtime/playback.js +242 -0
- package/runtime/dist/src/realtime/project-confirmation-flow.js +1428 -0
- package/runtime/dist/src/realtime/prompt-language.js +17 -0
- package/runtime/dist/src/realtime/protocol.js +428 -0
- package/runtime/dist/src/realtime/provider-projection.js +526 -0
- package/runtime/dist/src/realtime/provider-session.js +491 -0
- package/runtime/dist/src/realtime/qwen-transport.js +144 -0
- package/runtime/dist/src/realtime/qwen.js +1377 -0
- package/runtime/dist/src/realtime/recall.js +341 -0
- package/runtime/dist/src/realtime/service-ports.js +8 -0
- package/runtime/dist/src/realtime/service-state.js +259 -0
- package/runtime/dist/src/realtime/service.js +1726 -0
- package/runtime/dist/src/realtime/session-state.js +684 -0
- package/runtime/dist/src/realtime/session.js +1976 -0
- package/runtime/dist/src/realtime/speech-prep.js +63 -0
- package/runtime/dist/src/realtime/streaming-speech.js +120 -0
- package/runtime/dist/src/realtime/system-prompts.en.js +136 -0
- package/runtime/dist/src/realtime/telemetry.js +144 -0
- package/runtime/dist/src/realtime/tool-continuations.js +1510 -0
- package/runtime/dist/src/realtime/transport.js +8 -0
- package/runtime/dist/src/realtime/usage.js +55 -0
- package/runtime/dist/src/realtime/user-origin-binding.js +173 -0
- package/runtime/dist/src/realtime/volcengine/ark.js +428 -0
- package/runtime/dist/src/realtime/volcengine/asr.js +573 -0
- package/runtime/dist/src/realtime/volcengine/audio.js +39 -0
- package/runtime/dist/src/realtime/volcengine/endpointing-capability.js +834 -0
- package/runtime/dist/src/realtime/volcengine/livekit-endpointing.js +714 -0
- package/runtime/dist/src/realtime/volcengine/local-eot-executor.js +33 -0
- package/runtime/dist/src/realtime/volcengine/protocol.js +247 -0
- package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +237 -0
- package/runtime/dist/src/realtime/volcengine/tts.js +444 -0
- package/runtime/dist/src/realtime/volcengine/websocket.js +293 -0
- package/runtime/dist/src/server/aoq-chat-server.js +497 -0
- package/runtime/dist/src/server/client-pairing.js +192 -0
- package/runtime/dist/src/server/client-protocol.js +87 -0
- package/runtime/dist/src/server/client-server.js +312 -0
- package/runtime/dist/src/server/server-config.js +72 -0
- package/runtime/dist/src/server-entry.js +135 -0
- package/runtime/dist/src/storage/bounded-json.js +63 -0
- package/runtime/dist/src/storage/native-file-lock.js +8 -0
- package/runtime/dist/src/storage/native-resource-snapshot.js +41 -0
- package/runtime/dist/src/storage/private-database.js +120 -0
- package/runtime/dist/src/text/canonical-json.js +60 -0
- package/runtime/dist/src/text/python-number.js +18 -0
- package/runtime/dist/src/text/python-text.js +92 -0
- package/runtime/dist/src/text/unicode-casefold.js +29 -0
- package/runtime/dist/src/text/unicode-normalize.js +138 -0
- package/runtime/dist/src/text/unicode-tables.js +210 -0
- package/runtime/dist/src/understanding/candidates.js +77 -0
- package/runtime/dist/src/understanding/fixture.js +7 -0
- package/runtime/dist/src/understanding/jev.js +20 -0
- package/runtime/dist/src/understanding/pipeline.js +38 -0
- package/runtime/dist/src/voicemem/store-client.js +476 -0
- package/runtime/dist/src/voicemem/store-worker.js +380 -0
- package/runtime/dist/src/voicemem/versioned-memory.js +170 -0
- package/runtime/scripts/pair-device.mjs +109 -0
- package/src/command.mjs +48 -0
|
@@ -0,0 +1,1510 @@
|
|
|
1
|
+
import { scheduledToolResult } from '../personal-agent/scheduled-tool-runtime.js';
|
|
2
|
+
import { dispatchSources, projectRecoveryTurns, recentDispatchSources } from './history.js';
|
|
3
|
+
import { taskToolArguments } from '../core/task-tools.js';
|
|
4
|
+
import { parseAgentActionResult } from '../executors/agent-controller.js';
|
|
5
|
+
import { canonicalJson } from '../text/canonical-json.js';
|
|
6
|
+
import {} from '../core/events.js';
|
|
7
|
+
import {} from '../executors/coding/intake.js';
|
|
8
|
+
import { codePointLengthLikePython, stripLikePython } from '../text/python-text.js';
|
|
9
|
+
import { CANCEL_TOOL, CONFIRM_TOOL, DISPATCH_TOOL } from '../core/work-tools.js';
|
|
10
|
+
import { requiresSynchronousResult } from './bridge.js';
|
|
11
|
+
import {} from './evidence.js';
|
|
12
|
+
import { ItemDeliveryUncertainError } from './protocol.js';
|
|
13
|
+
import { MAX_HOST_FACT_CHARS, MAX_LATE_SYNC_RESULTS, MAX_PENDING_TOOL_REFUSALS, MAX_TRACKED_TOOL_CALLS, Mutex, SYNC_RESULT_SNIPPET_CHARS, SYNC_RESULT_TITLE_CHARS, callKey, continuationBatch, hostFactIntent, isAbort, parseCallKey, toolCallState } from './service-state.js';
|
|
14
|
+
import { MAX_CONTINUATION_TASK_SUMMARY } from './session-state.js';
|
|
15
|
+
import { RealtimeDeliveryError } from './session.js';
|
|
16
|
+
const UNKNOWN_CONFIRMATION_TOOL_RESULT = JSON.stringify({ code: 'unknown_confirmation', state: 'refused' });
|
|
17
|
+
export class ToolContinuations {
|
|
18
|
+
recordIntakeDispatch(intake, result) {
|
|
19
|
+
if (result.accepted && result.delegate_id !== null && result.delegate_id !== undefined) {
|
|
20
|
+
const title = intake.title ?? intake.target?.session_title;
|
|
21
|
+
this.session.registerDelegate(result.delegate_id, {
|
|
22
|
+
summary: intake.slots.goal.note.slice(0, 240),
|
|
23
|
+
state: 'running',
|
|
24
|
+
channel: this.#ports.coding?.channel ?? 'coding',
|
|
25
|
+
...(intake.target === null ? {} : { project: intake.target.workspace_display_name }),
|
|
26
|
+
...(title === undefined || title === null ? {} : { title }),
|
|
27
|
+
});
|
|
28
|
+
this.#ports.telemetry?.record('executor.dispatch', { delegate_id: result.delegate_id });
|
|
29
|
+
this.#ports.publishExecutorState();
|
|
30
|
+
}
|
|
31
|
+
return result;
|
|
32
|
+
}
|
|
33
|
+
resetCalls() {
|
|
34
|
+
this.#toolCalls.clear();
|
|
35
|
+
this.#overflowToolCalls.clear();
|
|
36
|
+
this.#continuationBatches.clear();
|
|
37
|
+
this.#continuationFifo.length = 0;
|
|
38
|
+
}
|
|
39
|
+
resetDeferredAndSync() {
|
|
40
|
+
this.#originDeferredToolCalls.length = 0;
|
|
41
|
+
this.#pendingSync.clear();
|
|
42
|
+
this.#lateSync.clear();
|
|
43
|
+
}
|
|
44
|
+
clearDeferred() { this.#originDeferredToolCalls.length = 0; }
|
|
45
|
+
takeDeferredForItem(itemId) {
|
|
46
|
+
const matching = [];
|
|
47
|
+
const retained = [];
|
|
48
|
+
for (const call of this.#originDeferredToolCalls) {
|
|
49
|
+
(call.user_item_id === itemId ? matching : retained).push(call);
|
|
50
|
+
}
|
|
51
|
+
this.#originDeferredToolCalls.length = 0;
|
|
52
|
+
this.#originDeferredToolCalls.push(...retained);
|
|
53
|
+
return matching;
|
|
54
|
+
}
|
|
55
|
+
continuationOrder() { return [...this.#continuationFifo]; }
|
|
56
|
+
responseCarriesPersonalRecall(responseId) {
|
|
57
|
+
for (const state of this.#toolCalls.values()) {
|
|
58
|
+
if (state.logical_name === 'memory.recall'
|
|
59
|
+
&& state.acceptance.inline_fulfilled
|
|
60
|
+
&& state.continuation_response_id === responseId) {
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
#ports;
|
|
67
|
+
constructor(ports) { this.#ports = ports; }
|
|
68
|
+
get session() { return this.#ports.session; }
|
|
69
|
+
/**
|
|
70
|
+
* CP3: serializes the continuation pass across its two entry points -- provider events and the
|
|
71
|
+
* delivery loop. Never held together with the delivery lock.
|
|
72
|
+
*/
|
|
73
|
+
#continuationDriveLock = new Mutex();
|
|
74
|
+
#toolCalls = new Map();
|
|
75
|
+
#overflowToolCalls = new Map();
|
|
76
|
+
#continuationBatches = new Map();
|
|
77
|
+
#continuationFifo = [];
|
|
78
|
+
/** Tool calls waiting for the transcript that would justify them. */
|
|
79
|
+
#originDeferredToolCalls = [];
|
|
80
|
+
/** R105: delegate id -> the call key waiting on its synchronous result. */
|
|
81
|
+
#pendingSync = new Map();
|
|
82
|
+
/** A timed-out sync call whose first real late handoff should become one host fact. */
|
|
83
|
+
#lateSync = new Map();
|
|
84
|
+
/** What the host told the provider about each live tool call, in admission order. */
|
|
85
|
+
toolCallAcceptances() {
|
|
86
|
+
return [...this.#toolCalls.entries()].map(([key, state]) => {
|
|
87
|
+
const separator = key.indexOf(':');
|
|
88
|
+
return {
|
|
89
|
+
session_epoch: Number(key.slice(0, separator)),
|
|
90
|
+
call_id: key.slice(separator + 1),
|
|
91
|
+
provider_response_id: state.provider_response_id,
|
|
92
|
+
acceptance: state.acceptance,
|
|
93
|
+
};
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* CP3: both the provider stream and the delivery loop drive continuations.
|
|
98
|
+
*
|
|
99
|
+
* The phase check inside cannot stop a second entrant on its own, because the pass awaits the
|
|
100
|
+
* provider partway through -- so the whole pass is serialized instead.
|
|
101
|
+
*/
|
|
102
|
+
async driveContinuations() {
|
|
103
|
+
await this.#continuationDriveLock.run(async () => {
|
|
104
|
+
await this.#driveContinuationsLocked();
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Whether a continuation may be requested right now.
|
|
109
|
+
*
|
|
110
|
+
* Two reasons not to. The user speaking outranks anything the agent wants to say. And an armed
|
|
111
|
+
* preemption means something urgent is about to interrupt, so starting a turn now would produce one
|
|
112
|
+
* that is immediately cut off.
|
|
113
|
+
*/
|
|
114
|
+
#continuationRequestIsBlocked() {
|
|
115
|
+
return this.#ports.host.rendererPaused
|
|
116
|
+
|| this.session.floor.state === 'user_speaking'
|
|
117
|
+
|| (this.#ports.host.hasEligiblePreempt());
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Give the model a turn to speak about finished tool work, one batch at a time.
|
|
121
|
+
*
|
|
122
|
+
* Strictly FIFO and strictly one in flight. The FIFO is why the agent narrates work in the order it
|
|
123
|
+
* was asked for rather than the order it finished; the single-flight check is why it does not talk
|
|
124
|
+
* over itself. Both are enforced by looking only at the head of the queue -- a batch that is not
|
|
125
|
+
* ready blocks the ones behind it deliberately, because speaking about later work first would
|
|
126
|
+
* describe a sequence the user did not ask for.
|
|
127
|
+
*
|
|
128
|
+
* Every `return` here leaves the batch where it is, to be retried when something changes. Every
|
|
129
|
+
* `continue` has popped a batch that will never speak.
|
|
130
|
+
*/
|
|
131
|
+
#discardScopedBatch(batch) {
|
|
132
|
+
batch.phase = 'abandoned';
|
|
133
|
+
for (const key of batch.call_keys) {
|
|
134
|
+
const state = this.#toolCallState(key);
|
|
135
|
+
if (state) {
|
|
136
|
+
state.continuation = 'terminal';
|
|
137
|
+
state.final_disposition = 'abandoned';
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async #driveContinuationsLocked() {
|
|
142
|
+
if (this.#ports.host.hasEligiblePreempt()) {
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
// One turn in flight at a time. Checked across all batches rather than just the head, because a
|
|
146
|
+
// batch can still be speaking after its own key left the front of the queue.
|
|
147
|
+
for (const batch of this.#continuationBatches.values()) {
|
|
148
|
+
if (batch.phase === 'requested' || batch.phase === 'bound')
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
while (this.#continuationFifo.length > 0) {
|
|
152
|
+
const head = this.#continuationFifo[0];
|
|
153
|
+
const batch = this.#continuationBatches.get(head);
|
|
154
|
+
if (batch === undefined) {
|
|
155
|
+
this.#continuationFifo.shift();
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
if (batch.phase === 'terminal' || batch.phase === 'abandoned') {
|
|
159
|
+
this.#continuationFifo.shift();
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
if (batch.phase !== 'ready')
|
|
163
|
+
return;
|
|
164
|
+
const abandoning = batch.origin_status === 'cancelled' || batch.origin_status === 'failed';
|
|
165
|
+
if (!abandoning) {
|
|
166
|
+
// R105: a sync member is still awaiting its Handoff or Deadline. The batch stays unready
|
|
167
|
+
// without popping or requesting -- speaking now would describe a result that does not exist.
|
|
168
|
+
for (const key of batch.call_keys) {
|
|
169
|
+
if (this.#toolCallState(key)?.sync === 'pending')
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (this.#ports.validateScopedContext && !await this.#ports.validateScopedContext()) {
|
|
174
|
+
this.#discardScopedBatch(batch);
|
|
175
|
+
this.#continuationFifo.shift();
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
// The provider is holding a slot for every tool result in this batch. They are injected before
|
|
179
|
+
// the turn is requested, and before the abandon path too: an abandoned batch still owes the
|
|
180
|
+
// provider its results, or the protocol stalls waiting for them.
|
|
181
|
+
const intents = [];
|
|
182
|
+
for (const key of batch.call_keys) {
|
|
183
|
+
const state = this.#toolCallState(key);
|
|
184
|
+
if (state === undefined)
|
|
185
|
+
continue;
|
|
186
|
+
if (state.output === 'pending') {
|
|
187
|
+
await this.session.injectToolOutput(state.acceptance.host_item);
|
|
188
|
+
state.output = 'confirmed';
|
|
189
|
+
}
|
|
190
|
+
if (state.acceptance.continuation === 'deferred' && batch.origin_status !== 'yielded') {
|
|
191
|
+
state.continuation = 'terminal';
|
|
192
|
+
state.final_disposition = 'completed';
|
|
193
|
+
}
|
|
194
|
+
else
|
|
195
|
+
intents.push(state.acceptance.response_intent);
|
|
196
|
+
}
|
|
197
|
+
if (abandoning) {
|
|
198
|
+
this.#abandonBatch(batch);
|
|
199
|
+
this.#continuationFifo.shift();
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
if (intents.length === 0) {
|
|
203
|
+
// Internal receipts settle without generating speech; their results remain provider context.
|
|
204
|
+
batch.phase = 'terminal';
|
|
205
|
+
this.#continuationFifo.shift();
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
if (this.#continuationRequestIsBlocked())
|
|
209
|
+
return;
|
|
210
|
+
if (this.#ports.validateScopedContext && !await this.#ports.validateScopedContext()) {
|
|
211
|
+
this.#discardScopedBatch(batch);
|
|
212
|
+
this.#continuationFifo.shift();
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const requestResult = await this.session.requestToolContinuation(intents, {
|
|
216
|
+
originSpoken: this.#batchOriginWasDelivered(batch),
|
|
217
|
+
});
|
|
218
|
+
// Retryable means the provider could not take it *now*: the batch keeps its place and the next
|
|
219
|
+
// pass tries again. Rejected means it never will.
|
|
220
|
+
if (requestResult === 'retryable')
|
|
221
|
+
return;
|
|
222
|
+
if (requestResult === 'rejected') {
|
|
223
|
+
this.#abandonBatch(batch);
|
|
224
|
+
this.#continuationFifo.shift();
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
batch.phase = 'requested';
|
|
228
|
+
for (const key of batch.call_keys) {
|
|
229
|
+
const state = this.#toolCallState(key);
|
|
230
|
+
if (state !== undefined)
|
|
231
|
+
state.continuation = 'requested';
|
|
232
|
+
}
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Give up on a batch, and settle what each member is owed.
|
|
238
|
+
*
|
|
239
|
+
* The final disposition distinguishes three things a caller cares about: work that was never
|
|
240
|
+
* dispatched is `superseded`, work the bridge refused is `refused`, and work that ran but will not
|
|
241
|
+
* be spoken about is `abandoned` -- and only that last kind gets a background acknowledgement,
|
|
242
|
+
* because it is the only one where something actually happened that the user has not heard about.
|
|
243
|
+
*/
|
|
244
|
+
#abandonBatch(batch) {
|
|
245
|
+
for (const key of batch.call_keys) {
|
|
246
|
+
const state = this.#toolCallState(key);
|
|
247
|
+
if (state === undefined)
|
|
248
|
+
continue;
|
|
249
|
+
state.continuation = 'abandoned';
|
|
250
|
+
if (state.sync === 'pending') {
|
|
251
|
+
// R105: an abandoned batch converts the pending sync wait to the announce path; the result
|
|
252
|
+
// becomes a host fact instead of part of a turn that is no longer happening.
|
|
253
|
+
state.sync = 'announce';
|
|
254
|
+
}
|
|
255
|
+
else if (state.sync === 'resolved') {
|
|
256
|
+
// CP3: resolved while collecting. The output injection above landed in a dead turn and no
|
|
257
|
+
// continuation will speak it, so it is downgraded to one announce host fact.
|
|
258
|
+
this.#announceResolvedSyncState(state);
|
|
259
|
+
}
|
|
260
|
+
if (state.dispatch === 'not_dispatched') {
|
|
261
|
+
state.final_disposition = 'superseded';
|
|
262
|
+
}
|
|
263
|
+
else if (!state.acceptance.accepted) {
|
|
264
|
+
state.final_disposition = 'refused';
|
|
265
|
+
}
|
|
266
|
+
else {
|
|
267
|
+
state.final_disposition = 'abandoned';
|
|
268
|
+
this.#queueBackgroundAcknowledgement(state);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
batch.phase = 'abandoned';
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Whether the user has already heard the acknowledgement this batch would repeat.
|
|
275
|
+
*
|
|
276
|
+
* Only meaningful for a single-call batch: with more than one there is no single origin to have been
|
|
277
|
+
* delivered. The revision check is what makes it safe -- a proof from before the user spoke again
|
|
278
|
+
* says nothing about whether they have heard about *this* turn.
|
|
279
|
+
*/
|
|
280
|
+
#batchOriginWasDelivered(batch) {
|
|
281
|
+
if (batch.call_keys.length !== 1)
|
|
282
|
+
return false;
|
|
283
|
+
const state = this.#toolCallState(batch.call_keys[0]);
|
|
284
|
+
if (state === undefined || !this.#refreshOriginDelivery(state, batch))
|
|
285
|
+
return false;
|
|
286
|
+
const acknowledgement = this.#ports.host.semanticAcknowledgement(state);
|
|
287
|
+
return acknowledgement !== null
|
|
288
|
+
&& acknowledgement.origin_delivered
|
|
289
|
+
&& acknowledgement.origin_user_input_revision === this.session.userInputRevision;
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Mark an acknowledgement as already spoken, if there is proof its turn was played.
|
|
293
|
+
*
|
|
294
|
+
* A proof only counts for a lone asynchronous call: with several in a batch, or with a synchronous
|
|
295
|
+
* result, the turn that played was not the acknowledgement.
|
|
296
|
+
*/
|
|
297
|
+
#refreshOriginDelivery(state, batch) {
|
|
298
|
+
const key = callKey(state.provider_session_epoch, state.provider_response_id);
|
|
299
|
+
const resolved = batch ?? this.#continuationBatches.get(key);
|
|
300
|
+
const singleAsync = resolved?.call_keys.length === 1
|
|
301
|
+
&& this.#toolCallState(resolved.call_keys[0]) === state
|
|
302
|
+
&& state.acceptance.response_intent.kind === 'delegation_acknowledgement';
|
|
303
|
+
if (!singleAsync || !this.#ports.host.hasOriginDeliveryProof(key))
|
|
304
|
+
return false;
|
|
305
|
+
return this.#ports.host.markOriginDelivered(state);
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Queue the acknowledgement for work that ran but will not be spoken about in its own turn.
|
|
309
|
+
*
|
|
310
|
+
* If the user already heard it, it is marked delivered instead of queued: saying it twice is worse
|
|
311
|
+
* than not saying it again.
|
|
312
|
+
*/
|
|
313
|
+
#queueBackgroundAcknowledgement(state) {
|
|
314
|
+
const acknowledgement = this.#ports.host.semanticAcknowledgement(state);
|
|
315
|
+
if (acknowledgement === null)
|
|
316
|
+
return;
|
|
317
|
+
this.#refreshOriginDelivery(state);
|
|
318
|
+
this.#ports.host.settleBackgroundAcknowledgement(acknowledgement.event_id);
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* CP3: a resolved-but-undelivered sync result of an abandoned batch keeps its compact view.
|
|
322
|
+
*
|
|
323
|
+
* Requeued as the one announce host fact, rather than discarded: the work ran and produced a result
|
|
324
|
+
* the model was going to ground itself on, and losing it silently is worse than saying it plainly.
|
|
325
|
+
*/
|
|
326
|
+
#announceResolvedSyncState(state) {
|
|
327
|
+
const delegateId = state.acceptance.delegate_id;
|
|
328
|
+
if (delegateId === null)
|
|
329
|
+
return;
|
|
330
|
+
state.sync = 'announce';
|
|
331
|
+
this.#ports.queueHostItem({
|
|
332
|
+
kind: 'host_fact',
|
|
333
|
+
item: {
|
|
334
|
+
kind: 'final',
|
|
335
|
+
host_item_id: this.#ports.idFactory(),
|
|
336
|
+
event_id: `sync:${delegateId}`,
|
|
337
|
+
content: state.acceptance.host_item.content,
|
|
338
|
+
call_id: null,
|
|
339
|
+
},
|
|
340
|
+
task_summary: null,
|
|
341
|
+
origin_spoken: false,
|
|
342
|
+
}, { priority: this.#ports.executorPriority(state.acceptance.executor) });
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Settle every tool call that belonged to the dead epoch.
|
|
346
|
+
*
|
|
347
|
+
* The dead epoch cannot receive a continuation, so nothing in it will ever be spoken about in its own
|
|
348
|
+
* turn. Each call therefore gets a final disposition here rather than waiting for a terminal that
|
|
349
|
+
* cannot arrive -- and the ones that actually ran get a background acknowledgement, because the work
|
|
350
|
+
* happened and the user has not heard about it.
|
|
351
|
+
*/
|
|
352
|
+
reconcileToolStateAfterReconnect(oldEpoch) {
|
|
353
|
+
for (const callKeyValue of this.#pendingSync.values()) {
|
|
354
|
+
if (parseCallKey(callKeyValue).sessionEpoch !== oldEpoch)
|
|
355
|
+
continue;
|
|
356
|
+
const state = this.#toolCallState(callKeyValue);
|
|
357
|
+
// R105: the dead epoch cannot receive a continuation; the result, when it arrives, becomes a
|
|
358
|
+
// host fact in the new epoch.
|
|
359
|
+
if (state?.sync === 'pending')
|
|
360
|
+
state.sync = 'announce';
|
|
361
|
+
}
|
|
362
|
+
for (const [batchKey, batch] of this.#continuationBatches.entries()) {
|
|
363
|
+
if (parseCallKey(batchKey).sessionEpoch !== oldEpoch)
|
|
364
|
+
continue;
|
|
365
|
+
for (const key of batch.call_keys) {
|
|
366
|
+
const state = this.#toolCallState(key);
|
|
367
|
+
if (state === undefined)
|
|
368
|
+
continue;
|
|
369
|
+
// Captured before the disposition is written, because that is what decides whether anything
|
|
370
|
+
// actually ran -- and only work that ran is worth telling the user about.
|
|
371
|
+
const needsSemanticAcknowledgement = state.dispatch === 'dispatched'
|
|
372
|
+
&& state.acceptance.accepted;
|
|
373
|
+
if (state.continuation !== 'terminal') {
|
|
374
|
+
state.continuation = 'abandoned';
|
|
375
|
+
state.continuation_response_id = null;
|
|
376
|
+
if (state.sync === 'resolved') {
|
|
377
|
+
// CP3: resolved but its continuation never became terminal. Re-delivered as one announce
|
|
378
|
+
// host fact in the new epoch, matching the at-least-once posture of the acknowledgements.
|
|
379
|
+
this.#announceResolvedSyncState(state);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
if (state.final_disposition === null) {
|
|
383
|
+
if (state.dispatch === 'not_dispatched') {
|
|
384
|
+
state.final_disposition = 'superseded';
|
|
385
|
+
}
|
|
386
|
+
else if (!state.acceptance.accepted) {
|
|
387
|
+
state.final_disposition = 'refused';
|
|
388
|
+
}
|
|
389
|
+
else {
|
|
390
|
+
state.final_disposition = 'abandoned';
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
if (needsSemanticAcknowledgement)
|
|
394
|
+
this.#queueBackgroundAcknowledgement(state);
|
|
395
|
+
}
|
|
396
|
+
// A batch already terminal was spoken before the session died, so it keeps that.
|
|
397
|
+
if (batch.phase !== 'terminal') {
|
|
398
|
+
batch.phase = 'abandoned';
|
|
399
|
+
batch.continuation_response_id = null;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
const surviving = this.#continuationFifo
|
|
403
|
+
.filter(key => parseCallKey(key).sessionEpoch !== oldEpoch);
|
|
404
|
+
this.#continuationFifo.length = 0;
|
|
405
|
+
this.#continuationFifo.push(...surviving);
|
|
406
|
+
}
|
|
407
|
+
/** Resolve a synchronous tool result before ordinary channel projection can consume it. */
|
|
408
|
+
resolveSyncResult(event) {
|
|
409
|
+
const callKeyValue = this.#pendingSync.get(event.payload.delegate_id);
|
|
410
|
+
if (callKeyValue === undefined) {
|
|
411
|
+
if (!this.#lateSync.has(event.payload.delegate_id))
|
|
412
|
+
return false;
|
|
413
|
+
this.#lateSync.delete(event.payload.delegate_id);
|
|
414
|
+
this.#queueSyncAnnouncement(event);
|
|
415
|
+
return true;
|
|
416
|
+
}
|
|
417
|
+
this.#pendingSync.delete(event.payload.delegate_id);
|
|
418
|
+
const state = this.#toolCallState(callKeyValue);
|
|
419
|
+
if (state === undefined) {
|
|
420
|
+
this.#queueSyncAnnouncement(event);
|
|
421
|
+
return true;
|
|
422
|
+
}
|
|
423
|
+
if (state.sync === 'pending') {
|
|
424
|
+
this.#confirmSyncOutput(state, this.#syncResultContent(event));
|
|
425
|
+
state.sync = 'resolved';
|
|
426
|
+
this.#ports.wakeDelivery();
|
|
427
|
+
}
|
|
428
|
+
else if (state.sync === 'announce') {
|
|
429
|
+
this.#queueSyncAnnouncement(event);
|
|
430
|
+
}
|
|
431
|
+
return true;
|
|
432
|
+
}
|
|
433
|
+
/** Resolve a synchronous timeout without narrating it; one real late handoff may still be announced. */
|
|
434
|
+
expireSyncResult(event) {
|
|
435
|
+
const callKeyValue = this.#pendingSync.get(event.payload.delegate_id);
|
|
436
|
+
if (callKeyValue === undefined)
|
|
437
|
+
return false;
|
|
438
|
+
this.#pendingSync.delete(event.payload.delegate_id);
|
|
439
|
+
const state = this.#toolCallState(callKeyValue);
|
|
440
|
+
if (state !== undefined) {
|
|
441
|
+
if (state.sync === 'pending') {
|
|
442
|
+
this.#confirmSyncOutput(state, '{"state":"timeout"}');
|
|
443
|
+
this.#ports.wakeDelivery();
|
|
444
|
+
}
|
|
445
|
+
else if (state.sync !== 'announce') {
|
|
446
|
+
return true;
|
|
447
|
+
}
|
|
448
|
+
state.sync = 'announce';
|
|
449
|
+
}
|
|
450
|
+
this.#lateSync.delete(event.payload.delegate_id);
|
|
451
|
+
this.#lateSync.set(event.payload.delegate_id, callKeyValue);
|
|
452
|
+
while (this.#lateSync.size > MAX_LATE_SYNC_RESULTS) {
|
|
453
|
+
const oldest = this.#lateSync.keys().next();
|
|
454
|
+
if (oldest.done)
|
|
455
|
+
break;
|
|
456
|
+
this.#lateSync.delete(oldest.value);
|
|
457
|
+
}
|
|
458
|
+
return true;
|
|
459
|
+
}
|
|
460
|
+
#confirmSyncOutput(state, content) {
|
|
461
|
+
const previous = state.acceptance.host_item;
|
|
462
|
+
if (previous.call_id === null)
|
|
463
|
+
return;
|
|
464
|
+
const hostItem = { ...previous, content, recovery_eligible: true };
|
|
465
|
+
state.acceptance = {
|
|
466
|
+
...state.acceptance,
|
|
467
|
+
host_item: hostItem,
|
|
468
|
+
response_intent: {
|
|
469
|
+
kind: 'tool_result', item: hostItem, task_summary: null, origin_spoken: false,
|
|
470
|
+
},
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
#queueSyncAnnouncement(event) {
|
|
474
|
+
this.#ports.queueHostItem(hostFactIntent({
|
|
475
|
+
kind: 'final',
|
|
476
|
+
host_item_id: this.#ports.idFactory(),
|
|
477
|
+
event_id: `sync:${event.payload.delegate_id}`,
|
|
478
|
+
content: this.#syncResultContent(event),
|
|
479
|
+
}), { priority: this.#ports.executorPriority(event.payload.channel) });
|
|
480
|
+
}
|
|
481
|
+
/** Compact, closed sync result for the model; status remains intact and private refs stay excluded. */
|
|
482
|
+
#syncResultContent(event) {
|
|
483
|
+
const content = event.payload.content;
|
|
484
|
+
if (event.payload.channel === 'search' && event.payload.outcome === 'ok') {
|
|
485
|
+
const results = Array.isArray(content.results)
|
|
486
|
+
? content.results.flatMap(raw => {
|
|
487
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
|
|
488
|
+
return [];
|
|
489
|
+
const title = typeof raw.title === 'string'
|
|
490
|
+
? [...raw.title].slice(0, SYNC_RESULT_TITLE_CHARS).join('')
|
|
491
|
+
: '';
|
|
492
|
+
const snippet = typeof raw.snippet === 'string'
|
|
493
|
+
? [...raw.snippet].slice(0, SYNC_RESULT_SNIPPET_CHARS).join('')
|
|
494
|
+
: '';
|
|
495
|
+
let source = '';
|
|
496
|
+
if (typeof raw.canonical_url === 'string') {
|
|
497
|
+
try {
|
|
498
|
+
source = new URL(raw.canonical_url).hostname;
|
|
499
|
+
}
|
|
500
|
+
catch { /* invalid source stays empty */ }
|
|
501
|
+
}
|
|
502
|
+
return [{ title, snippet, source }];
|
|
503
|
+
})
|
|
504
|
+
: [];
|
|
505
|
+
const query = typeof content.query === 'string'
|
|
506
|
+
? [...content.query].slice(0, 512).join('')
|
|
507
|
+
: null;
|
|
508
|
+
let encoded = JSON.stringify({ state: 'ok', query, results });
|
|
509
|
+
while ([...encoded].length > MAX_HOST_FACT_CHARS && results.length > 0) {
|
|
510
|
+
const longest = Math.max(...results.map(result => [...result.snippet].length));
|
|
511
|
+
if (longest > 50) {
|
|
512
|
+
for (const result of results) {
|
|
513
|
+
result.snippet = [...result.snippet].slice(0, Math.max(50, Math.floor(longest / 2))).join('');
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
else
|
|
517
|
+
results.pop();
|
|
518
|
+
encoded = JSON.stringify({ state: 'ok', query, results });
|
|
519
|
+
}
|
|
520
|
+
return encoded;
|
|
521
|
+
}
|
|
522
|
+
const encoded = JSON.stringify({ state: event.payload.outcome, content });
|
|
523
|
+
return [...encoded].length <= MAX_HOST_FACT_CHARS
|
|
524
|
+
? encoded
|
|
525
|
+
: JSON.stringify({ state: event.payload.outcome, error: 'result_too_large' });
|
|
526
|
+
}
|
|
527
|
+
async routeToolCall(event) {
|
|
528
|
+
const activeResponseId = this.session.activeProviderResponseId;
|
|
529
|
+
const observedResponseId = event.response_id ?? activeResponseId;
|
|
530
|
+
const evidence = observedResponseId === null ? undefined : this.session.providerResponseOrigin(observedResponseId);
|
|
531
|
+
const boundItem = observedResponseId === null ? undefined
|
|
532
|
+
: this.#ports.userOrigins.itemForResponse(event.session_epoch, observedResponseId);
|
|
533
|
+
const toolContinuation = observedResponseId !== null && evidence?.kind === 'host_request'
|
|
534
|
+
&& this.session.responseIsToolContinuation(observedResponseId)
|
|
535
|
+
&& boundItem !== undefined
|
|
536
|
+
&& this.#ports.userOrigins.revisionForItem(event.session_epoch, boundItem) === this.session.userInputRevision
|
|
537
|
+
&& this.session.providerTurnUserInputRevision(observedResponseId) === this.session.userInputRevision;
|
|
538
|
+
if (evidence !== undefined && !toolContinuation && (evidence.kind !== 'user_item' || boundItem !== evidence.item_id)) {
|
|
539
|
+
// Explicit evidence may be rejected, but cannot fall back to the next arriving transcript.
|
|
540
|
+
await this.#handleBoundToolCall(event, {
|
|
541
|
+
observedProviderResponseId: observedResponseId, originItemId: null, originRef: null,
|
|
542
|
+
});
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
const confirmTarget = this.#ports.confirmTarget(event);
|
|
546
|
+
if (confirmTarget === 'approval') {
|
|
547
|
+
await this.#ports.approvalHost.routeExecutorApprovalCall(event, observedResponseId);
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
const originItemId = observedResponseId === null
|
|
551
|
+
? undefined
|
|
552
|
+
: this.#ports.userOrigins.itemForResponse(event.session_epoch, observedResponseId);
|
|
553
|
+
if (originItemId !== undefined
|
|
554
|
+
&& this.#ports.isProjectConfirmationShadowItem(event.session_epoch, originItemId)) {
|
|
555
|
+
await this.#ports.closeProjectConfirmationTool(event);
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
if (originItemId !== undefined) {
|
|
559
|
+
const originRef = this.#ports.userOrigins.originRefForItem(event.session_epoch, originItemId);
|
|
560
|
+
if (originRef !== undefined) {
|
|
561
|
+
await this.#handleBoundToolCall(event, {
|
|
562
|
+
observedProviderResponseId: observedResponseId,
|
|
563
|
+
originItemId,
|
|
564
|
+
originRef,
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
else if (this.#originDeferredToolCalls.length >= MAX_PENDING_TOOL_REFUSALS) {
|
|
568
|
+
await this.#ports.reconnectProviderSession({
|
|
569
|
+
reason: 'origin_resolution_overflow',
|
|
570
|
+
expectedEpoch: this.session.sessionEpoch,
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
else {
|
|
574
|
+
this.#originDeferredToolCalls.push({
|
|
575
|
+
event,
|
|
576
|
+
response_id: observedResponseId,
|
|
577
|
+
user_item_id: originItemId,
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
if (confirmTarget === 'project') {
|
|
583
|
+
await this.#ports.handleProjectConfirmationDecision(event, {
|
|
584
|
+
observedProviderResponseId: observedResponseId,
|
|
585
|
+
originItemId: null,
|
|
586
|
+
originRef: null,
|
|
587
|
+
});
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
if (this.#ports.awaitingUserOrigin()) {
|
|
591
|
+
// Whether the response this call names is the one the in-flight user turn will answer. If it is
|
|
592
|
+
// not -- a different response, a finished one, or one already fenced -- the call is not waiting
|
|
593
|
+
// on that turn and holding it back would delay it for evidence it was never going to get.
|
|
594
|
+
const originIsActive = observedResponseId !== null
|
|
595
|
+
&& activeResponseId === observedResponseId
|
|
596
|
+
&& this.session.providerTurnPhase(observedResponseId) === 'active'
|
|
597
|
+
&& !this.session.providerTurnWasFenced(observedResponseId);
|
|
598
|
+
if (observedResponseId === this.#ports.userOriginPreexistingResponseId()) {
|
|
599
|
+
// The response was already running when the user started speaking, so it cannot be answering
|
|
600
|
+
// them: handle it now with whatever evidence it has.
|
|
601
|
+
await this.#handleToolCall(event);
|
|
602
|
+
}
|
|
603
|
+
else if (!originIsActive) {
|
|
604
|
+
await this.#handleToolCall(event);
|
|
605
|
+
}
|
|
606
|
+
else if (this.#originDeferredToolCalls.length >= MAX_PENDING_TOOL_REFUSALS) {
|
|
607
|
+
await this.#ports.reconnectProviderSession({
|
|
608
|
+
reason: 'origin_binding_overflow',
|
|
609
|
+
expectedEpoch: this.session.sessionEpoch,
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
else {
|
|
613
|
+
// Non-null by construction: `originIsActive` above required it.
|
|
614
|
+
this.#originDeferredToolCalls.push({
|
|
615
|
+
event,
|
|
616
|
+
response_id: observedResponseId,
|
|
617
|
+
user_item_id: null,
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
await this.#handleToolCall(event);
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Run the tool calls that were waiting for this transcript.
|
|
626
|
+
*
|
|
627
|
+
* Two kinds of waiter. One names the user item it needs, and is released when that item arrives.
|
|
628
|
+
* The other could not be keyed at all -- it arrived before any item was known -- and those are
|
|
629
|
+
* released as a batch, all from the same response, but only if no keyed waiter matched: a keyed
|
|
630
|
+
* match means the transcript belongs to a specific call, and releasing the unkeyed batch alongside
|
|
631
|
+
* it would hand them evidence that is not theirs.
|
|
632
|
+
*
|
|
633
|
+
* The epoch is re-read each iteration. Handling one call can reconnect, and every remaining call
|
|
634
|
+
* belongs to a session that no longer exists.
|
|
635
|
+
*/
|
|
636
|
+
async releaseDeferredOriginCalls(itemId, originRef) {
|
|
637
|
+
const releaseEpoch = this.session.sessionEpoch;
|
|
638
|
+
const deferred = [...this.#originDeferredToolCalls];
|
|
639
|
+
this.#originDeferredToolCalls.length = 0;
|
|
640
|
+
const hasKeyedMatch = deferred.some(entry => entry.user_item_id === itemId);
|
|
641
|
+
const unkeyedResponseId = hasKeyedMatch
|
|
642
|
+
? null
|
|
643
|
+
: deferred.find(entry => entry.user_item_id === null)?.response_id ?? null;
|
|
644
|
+
for (const entry of deferred) {
|
|
645
|
+
if (this.session.sessionEpoch !== releaseEpoch)
|
|
646
|
+
return;
|
|
647
|
+
const matchesKeyed = entry.user_item_id === itemId;
|
|
648
|
+
const matchesUnkeyedBatch = entry.user_item_id === null
|
|
649
|
+
&& entry.response_id === unkeyedResponseId;
|
|
650
|
+
if (!matchesKeyed && !matchesUnkeyedBatch) {
|
|
651
|
+
this.#originDeferredToolCalls.push(entry);
|
|
652
|
+
continue;
|
|
653
|
+
}
|
|
654
|
+
await this.#handleBoundToolCall(entry.event, {
|
|
655
|
+
observedProviderResponseId: entry.response_id,
|
|
656
|
+
originItemId: entry.user_item_id,
|
|
657
|
+
originRef,
|
|
658
|
+
});
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
async #handleBoundToolCall(event, origin) {
|
|
662
|
+
const confirmTarget = this.#ports.confirmTarget(event);
|
|
663
|
+
if (confirmTarget === 'project') {
|
|
664
|
+
await this.#ports.handleProjectConfirmationDecision(event, origin);
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
if (confirmTarget === 'approval') {
|
|
668
|
+
await this.#ports.approvalHost.handleExecutorApprovalDecision(event, origin);
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
await this.#handleToolCall(event, {
|
|
672
|
+
observedProviderResponseId: origin.observedProviderResponseId,
|
|
673
|
+
originRef: origin.originRef,
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
/** Where a batch's originating response ended up, collapsed to the four states a batch tracks. */
|
|
677
|
+
#originStatus(responseId) {
|
|
678
|
+
const phase = this.session.providerTurnPhase(responseId);
|
|
679
|
+
// `cancel_requested` is still active: the cancel has been asked for, not observed, and treating
|
|
680
|
+
// it as cancelled would abandon a batch whose response may yet complete normally.
|
|
681
|
+
if (phase === 'active' || phase === 'cancel_requested')
|
|
682
|
+
return 'active';
|
|
683
|
+
if (phase === 'yielded')
|
|
684
|
+
return 'yielded';
|
|
685
|
+
if (phase === 'failed')
|
|
686
|
+
return 'failed';
|
|
687
|
+
if (phase === 'cancelled' || this.session.providerTurnWasFenced(responseId))
|
|
688
|
+
return 'cancelled';
|
|
689
|
+
return 'completed';
|
|
690
|
+
}
|
|
691
|
+
// ---------------------------------------------------------------------------------------------
|
|
692
|
+
// Family J: admitting one tool call.
|
|
693
|
+
// ---------------------------------------------------------------------------------------------
|
|
694
|
+
#toolCallState(key) {
|
|
695
|
+
return this.#toolCalls.get(key) ?? this.#overflowToolCalls.get(key);
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* Admit one tool call, or record why it could not be.
|
|
699
|
+
*
|
|
700
|
+
* The long branch is first-sighting; the short one at the end handles a repeat of a call already
|
|
701
|
+
* known. Three things can stop an admission and they are genuinely different: *superseded* means
|
|
702
|
+
* the turn that proposed it is gone, so running it would act on an intention the user has moved
|
|
703
|
+
* past; *over capacity* means the ledgers are full and admitting more would grow without bound;
|
|
704
|
+
* and a bridge refusal means the proposal itself was not admissible.
|
|
705
|
+
*/
|
|
706
|
+
async #handleToolCall(call, options = {}) {
|
|
707
|
+
const event = call;
|
|
708
|
+
// A hidden agent op named by the provider was never offered to it and cannot be reached through
|
|
709
|
+
// a host rewrite. Controllers are the only path from a public agent name to a hidden channel.
|
|
710
|
+
const hidden = this.#ports.tools.hidden.has(call.name);
|
|
711
|
+
const key = callKey(event.session_epoch, event.call_id);
|
|
712
|
+
const existing = this.#toolCallState(key);
|
|
713
|
+
if (existing !== undefined) {
|
|
714
|
+
// A repeat. Touch it so the LRU keeps it, and finish the one piece of work a repeat can carry:
|
|
715
|
+
// a superseded call whose output was never confirmed still owes the provider a result.
|
|
716
|
+
const ledger = this.#toolCalls.has(key) ? this.#toolCalls : this.#overflowToolCalls;
|
|
717
|
+
ledger.delete(key);
|
|
718
|
+
ledger.set(key, existing);
|
|
719
|
+
if (existing.observation === 'superseded'
|
|
720
|
+
&& existing.continuation === 'abandoned'
|
|
721
|
+
&& existing.output === 'pending') {
|
|
722
|
+
await this.#confirmSupersededOutput(existing);
|
|
723
|
+
}
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
const observedProviderResponseId = options.observedProviderResponseId ?? null;
|
|
727
|
+
const originRef = options.originRef ?? null;
|
|
728
|
+
const activeResponseId = this.session.activeProviderResponseId;
|
|
729
|
+
// The item id is the last resort: a call with no response at all still needs a batch key, and its
|
|
730
|
+
// own item is the only identifier that is certainly unique.
|
|
731
|
+
const providerResponseId = observedProviderResponseId
|
|
732
|
+
?? event.response_id
|
|
733
|
+
?? activeResponseId
|
|
734
|
+
?? event.item_id;
|
|
735
|
+
const originUserInputRevision = this.session.providerTurnUserInputRevision(providerResponseId)
|
|
736
|
+
?? this.session.userInputRevision;
|
|
737
|
+
const originPhase = this.session.providerTurnPhase(providerResponseId);
|
|
738
|
+
const hasProviderOrigin = event.response_id !== null || activeResponseId !== null;
|
|
739
|
+
// Two different questions. When the caller already resolved which response this belongs to, the
|
|
740
|
+
// only thing left to ask is whether that response survived. When it did not, the call has to be
|
|
741
|
+
// matched against the provider's current turn first -- and a call naming a response that is not
|
|
742
|
+
// the active one is describing a turn that has already been replaced.
|
|
743
|
+
const superseded = observedProviderResponseId !== null
|
|
744
|
+
? (originPhase === 'cancelled'
|
|
745
|
+
|| originPhase === 'failed'
|
|
746
|
+
|| this.session.providerTurnWasFenced(providerResponseId))
|
|
747
|
+
: ((event.response_id === null && activeResponseId === null)
|
|
748
|
+
|| (event.response_id !== null
|
|
749
|
+
&& activeResponseId !== null
|
|
750
|
+
&& activeResponseId !== event.response_id)
|
|
751
|
+
|| (hasProviderOrigin
|
|
752
|
+
&& ((originPhase !== null && originPhase !== 'active')
|
|
753
|
+
|| this.session.providerTurnWasFenced(providerResponseId))));
|
|
754
|
+
if (this.#toolCalls.size >= MAX_TRACKED_TOOL_CALLS
|
|
755
|
+
|| this.#overflowToolCalls.size >= MAX_PENDING_TOOL_REFUSALS) {
|
|
756
|
+
this.#pruneTerminalToolState();
|
|
757
|
+
}
|
|
758
|
+
const callOverCapacity = this.#toolCalls.size >= MAX_TRACKED_TOOL_CALLS;
|
|
759
|
+
const binding = hidden ? undefined : this.#ports.tools.bindings.get(event.name);
|
|
760
|
+
const personalRecall = binding?.kind === 'query'
|
|
761
|
+
&& (event.name === 'memory__evidence' || (event.name === 'memory__recall' && event.arguments.source !== 'session'));
|
|
762
|
+
const noIntakeAgentDispatch = !hidden
|
|
763
|
+
&& event.name === DISPATCH_TOOL
|
|
764
|
+
&& this.#ports.intake === undefined
|
|
765
|
+
&& this.#agentExecutorName(event.arguments.executor) !== null;
|
|
766
|
+
// A delegated call will eventually need to be spoken about, so its acknowledgement slot is
|
|
767
|
+
// reserved *before* admission -- admitting work the agent could never mention is worse than
|
|
768
|
+
// refusing it.
|
|
769
|
+
const synchronousDelegateCall = binding?.kind === 'delegate'
|
|
770
|
+
&& typeof binding.executor === 'string'
|
|
771
|
+
&& typeof binding.op === 'string'
|
|
772
|
+
&& requiresSynchronousResult(this.#ports.runtime.executors.get(binding.executor), binding.op, event.arguments, binding.sync_result === true);
|
|
773
|
+
const requiresSemanticAcknowledgement = !superseded
|
|
774
|
+
&& (binding?.kind === 'delegate' || noIntakeAgentDispatch)
|
|
775
|
+
&& !synchronousDelegateCall;
|
|
776
|
+
let semanticReserved = false;
|
|
777
|
+
if (!callOverCapacity && requiresSemanticAcknowledgement) {
|
|
778
|
+
semanticReserved = this.#ports.host.reserveSemanticAcknowledgement();
|
|
779
|
+
}
|
|
780
|
+
const overCapacity = callOverCapacity
|
|
781
|
+
|| (requiresSemanticAcknowledgement && !semanticReserved);
|
|
782
|
+
if (overCapacity && this.#overflowToolCalls.size >= MAX_PENDING_TOOL_REFUSALS) {
|
|
783
|
+
// Both ledgers full of refusals the provider has not acknowledged. The session is no longer
|
|
784
|
+
// tracking reality, and reconnecting is the only way back to a state that can be reasoned about.
|
|
785
|
+
await this.#ports.reconnectProviderSession({
|
|
786
|
+
reason: 'refusal_ledger_overflow',
|
|
787
|
+
expectedEpoch: this.session.sessionEpoch,
|
|
788
|
+
});
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
let acceptance;
|
|
792
|
+
if (superseded) {
|
|
793
|
+
acceptance = this.#supersededAcceptance(event);
|
|
794
|
+
}
|
|
795
|
+
else if (overCapacity) {
|
|
796
|
+
acceptance = this.#overCapacityAcceptance(event);
|
|
797
|
+
}
|
|
798
|
+
else if (hidden) {
|
|
799
|
+
acceptance = this.#refusalAcceptance(event, 'unknown_tool', '{"code":"unknown_tool","state":"refused"}');
|
|
800
|
+
}
|
|
801
|
+
else if (this.#ports.scopedTool) {
|
|
802
|
+
acceptance = await this.#ports.scopedTool(event);
|
|
803
|
+
}
|
|
804
|
+
else if (personalRecall) {
|
|
805
|
+
// Classification does not start the read. The serialized receive loop installs its ledger first.
|
|
806
|
+
acceptance = await this.#ports.bridge.acceptToolCall(event, { originRef });
|
|
807
|
+
if (acceptance.code === 'async_tool') {
|
|
808
|
+
const state = toolCallState({
|
|
809
|
+
acceptance,
|
|
810
|
+
logical_name: binding?.logical_name ?? null,
|
|
811
|
+
provider_response_id: providerResponseId,
|
|
812
|
+
provider_session_epoch: event.session_epoch,
|
|
813
|
+
origin_user_input_revision: originUserInputRevision,
|
|
814
|
+
observation: 'observed',
|
|
815
|
+
dispatch: 'fulfilled',
|
|
816
|
+
sync: 'pending',
|
|
817
|
+
});
|
|
818
|
+
this.#toolCalls.set(key, state);
|
|
819
|
+
const batchKey = callKey(event.session_epoch, providerResponseId);
|
|
820
|
+
let batch = this.#continuationBatches.get(batchKey);
|
|
821
|
+
if (batch === undefined) {
|
|
822
|
+
batch = continuationBatch(providerResponseId);
|
|
823
|
+
this.#continuationBatches.set(batchKey, batch);
|
|
824
|
+
this.#continuationFifo.push(batchKey);
|
|
825
|
+
}
|
|
826
|
+
batch.call_keys.push(key);
|
|
827
|
+
const originStatus = this.#originStatus(providerResponseId);
|
|
828
|
+
if (originStatus !== 'active') {
|
|
829
|
+
batch.origin_status = originStatus;
|
|
830
|
+
batch.phase = 'ready';
|
|
831
|
+
}
|
|
832
|
+
void this.#resolvePersonalRecall({
|
|
833
|
+
event,
|
|
834
|
+
key,
|
|
835
|
+
state,
|
|
836
|
+
originRef,
|
|
837
|
+
originUserInputRevision,
|
|
838
|
+
providerResponseId,
|
|
839
|
+
}).catch(failure => {
|
|
840
|
+
if (!isAbort(failure)) {
|
|
841
|
+
this.#ports.reportDeliveryFailure(failure instanceof RealtimeDeliveryError
|
|
842
|
+
? failure
|
|
843
|
+
: new RealtimeDeliveryError(String(failure)));
|
|
844
|
+
}
|
|
845
|
+
});
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
else {
|
|
850
|
+
try {
|
|
851
|
+
const userTurn = this.#ports.currentUserTurn(event, originRef);
|
|
852
|
+
const intercepted = await this.#interceptHost(event, originRef);
|
|
853
|
+
if (event.session_epoch <= this.#ports.discardedInputEpoch()) {
|
|
854
|
+
if (semanticReserved)
|
|
855
|
+
this.#ports.host.releaseAcknowledgementReservation();
|
|
856
|
+
return;
|
|
857
|
+
}
|
|
858
|
+
acceptance = intercepted
|
|
859
|
+
?? await this.#ports.bridge.acceptToolCall(event, { originRef, ...(userTurn === null ? {} : { userTurn }) });
|
|
860
|
+
if (event.session_epoch <= this.#ports.discardedInputEpoch()) {
|
|
861
|
+
if (semanticReserved)
|
|
862
|
+
this.#ports.host.releaseAcknowledgementReservation();
|
|
863
|
+
return;
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
catch (cause) {
|
|
867
|
+
// The reservation was taken on the assumption the admission would happen. It did not, and a
|
|
868
|
+
// reservation nobody releases is a slot permanently unavailable to every later call.
|
|
869
|
+
if (semanticReserved)
|
|
870
|
+
this.#ports.host.releaseAcknowledgementReservation();
|
|
871
|
+
throw cause;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
this.#recordToolAdmission({
|
|
875
|
+
callId: event.call_id,
|
|
876
|
+
logicalName: binding?.logical_name ?? null,
|
|
877
|
+
acceptance,
|
|
878
|
+
superseded,
|
|
879
|
+
});
|
|
880
|
+
const state = toolCallState({
|
|
881
|
+
acceptance,
|
|
882
|
+
logical_name: binding?.logical_name ?? null,
|
|
883
|
+
provider_response_id: providerResponseId,
|
|
884
|
+
provider_session_epoch: event.session_epoch,
|
|
885
|
+
origin_user_input_revision: originUserInputRevision,
|
|
886
|
+
observation: superseded ? 'superseded' : 'observed',
|
|
887
|
+
dispatch: superseded
|
|
888
|
+
? 'not_dispatched'
|
|
889
|
+
: overCapacity
|
|
890
|
+
? 'rejected'
|
|
891
|
+
: acceptance.inline_fulfilled
|
|
892
|
+
? 'fulfilled'
|
|
893
|
+
: acceptance.accepted
|
|
894
|
+
? 'dispatched'
|
|
895
|
+
: 'rejected',
|
|
896
|
+
});
|
|
897
|
+
if (acceptance.inline_fulfilled && acceptance.telemetry !== null) {
|
|
898
|
+
this.#ports.telemetry?.record('memory.recall', acceptance.telemetry);
|
|
899
|
+
}
|
|
900
|
+
if (acceptance.sync_result && acceptance.accepted && acceptance.delegate_id !== null) {
|
|
901
|
+
state.sync = 'pending';
|
|
902
|
+
this.#pendingSync.set(acceptance.delegate_id, key);
|
|
903
|
+
}
|
|
904
|
+
if (semanticReserved) {
|
|
905
|
+
try {
|
|
906
|
+
if (acceptance.accepted
|
|
907
|
+
&& acceptance.delegate_id !== null
|
|
908
|
+
&& !acceptance.sync_result) {
|
|
909
|
+
if (this.#ports.host.semanticAcknowledgement(state) === null) {
|
|
910
|
+
throw new Error('reserved semantic acknowledgement is unavailable');
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
finally {
|
|
915
|
+
this.#ports.host.releaseAcknowledgementReservation();
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
if (overCapacity) {
|
|
919
|
+
this.#overflowToolCalls.set(key, state);
|
|
920
|
+
}
|
|
921
|
+
else {
|
|
922
|
+
this.#toolCalls.set(key, state);
|
|
923
|
+
}
|
|
924
|
+
const batchKey = callKey(event.session_epoch, providerResponseId);
|
|
925
|
+
let batch = this.#continuationBatches.get(batchKey);
|
|
926
|
+
if (superseded
|
|
927
|
+
&& batch !== undefined
|
|
928
|
+
&& (batch.phase === 'requested'
|
|
929
|
+
|| batch.phase === 'bound'
|
|
930
|
+
|| batch.phase === 'terminal'
|
|
931
|
+
|| batch.phase === 'abandoned')) {
|
|
932
|
+
// The batch has already spoken or given up. A superseded latecomer cannot join it, and the only
|
|
933
|
+
// thing left owed is the tool result the provider is still holding a slot for.
|
|
934
|
+
state.continuation = 'abandoned';
|
|
935
|
+
await this.#confirmSupersededOutput(state);
|
|
936
|
+
return;
|
|
937
|
+
}
|
|
938
|
+
if (batch === undefined) {
|
|
939
|
+
batch = continuationBatch(providerResponseId);
|
|
940
|
+
this.#continuationBatches.set(batchKey, batch);
|
|
941
|
+
this.#continuationFifo.push(batchKey);
|
|
942
|
+
}
|
|
943
|
+
batch.call_keys.push(key);
|
|
944
|
+
const originStatus = this.#originStatus(providerResponseId);
|
|
945
|
+
if (superseded) {
|
|
946
|
+
batch.origin_status = 'cancelled';
|
|
947
|
+
// A cancel that has been requested but not observed leaves the batch collecting: the response
|
|
948
|
+
// may still deliver more calls, and closing the batch now would strand them.
|
|
949
|
+
if (originPhase !== 'cancel_requested')
|
|
950
|
+
batch.phase = 'ready';
|
|
951
|
+
}
|
|
952
|
+
else if (originStatus !== 'active') {
|
|
953
|
+
batch.origin_status = originStatus;
|
|
954
|
+
batch.phase = 'ready';
|
|
955
|
+
}
|
|
956
|
+
if (acceptance.accepted
|
|
957
|
+
&& acceptance.delegate_id !== null
|
|
958
|
+
&& acceptance.executor !== null
|
|
959
|
+
&& !acceptance.sync_result) {
|
|
960
|
+
const summary = acceptance.response_intent.task_summary;
|
|
961
|
+
const display = typeof summary === 'string' && stripLikePython(summary) !== ''
|
|
962
|
+
? summary
|
|
963
|
+
: `${this.#ports.executorDisplayName(acceptance.executor)} background task`;
|
|
964
|
+
this.session.registerDelegate(acceptance.delegate_id, {
|
|
965
|
+
summary: [...stripLikePython(display)].slice(0, MAX_CONTINUATION_TASK_SUMMARY).join(''),
|
|
966
|
+
state: 'running',
|
|
967
|
+
channel: acceptance.executor,
|
|
968
|
+
});
|
|
969
|
+
if (acceptance.executor === this.#ports.coding?.channel) {
|
|
970
|
+
this.#ports.telemetry?.record('executor.dispatch', { delegate_id: acceptance.delegate_id });
|
|
971
|
+
}
|
|
972
|
+
this.#ports.publishExecutorState();
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
async #resolvePersonalRecall(input) {
|
|
976
|
+
const acceptance = await this.#ports.bridge.acceptPersonalMemoryRecall(input.event, { originRef: input.originRef, signal: this.#ports.stopSignal() });
|
|
977
|
+
// A replacement session or shutdown cannot receive this old provider call. Its ledger was already
|
|
978
|
+
// reconciled, so the late read has no provider-facing work left to do.
|
|
979
|
+
if (this.#ports.stopSignal().aborted
|
|
980
|
+
|| this.session.sessionEpoch !== input.event.session_epoch
|
|
981
|
+
|| this.#toolCallState(input.key) !== input.state
|
|
982
|
+
|| input.state.final_disposition !== null)
|
|
983
|
+
return;
|
|
984
|
+
const superseded = this.session.userInputRevision !== input.originUserInputRevision
|
|
985
|
+
|| this.session.providerTurnWasFenced(input.providerResponseId);
|
|
986
|
+
input.state.acceptance = superseded ? this.#supersededAcceptance(input.event) : acceptance;
|
|
987
|
+
input.state.observation = superseded ? 'superseded' : 'observed';
|
|
988
|
+
input.state.dispatch = superseded
|
|
989
|
+
? 'not_dispatched'
|
|
990
|
+
: acceptance.inline_fulfilled
|
|
991
|
+
? 'fulfilled'
|
|
992
|
+
: 'rejected';
|
|
993
|
+
input.state.sync = 'none';
|
|
994
|
+
this.#recordToolAdmission({
|
|
995
|
+
callId: input.event.call_id,
|
|
996
|
+
logicalName: input.state.logical_name,
|
|
997
|
+
acceptance: input.state.acceptance,
|
|
998
|
+
superseded,
|
|
999
|
+
});
|
|
1000
|
+
if (input.state.acceptance.inline_fulfilled && input.state.acceptance.telemetry !== null) {
|
|
1001
|
+
this.#ports.telemetry?.record('memory.recall', input.state.acceptance.telemetry);
|
|
1002
|
+
}
|
|
1003
|
+
const batch = this.#continuationBatches.get(callKey(input.event.session_epoch, input.providerResponseId));
|
|
1004
|
+
if (superseded && batch !== undefined) {
|
|
1005
|
+
batch.origin_status = 'cancelled';
|
|
1006
|
+
batch.phase = 'ready';
|
|
1007
|
+
}
|
|
1008
|
+
try {
|
|
1009
|
+
await this.driveContinuations();
|
|
1010
|
+
await this.#ports.deliveryPass();
|
|
1011
|
+
}
|
|
1012
|
+
catch (cause) {
|
|
1013
|
+
if (cause instanceof ItemDeliveryUncertainError) {
|
|
1014
|
+
await this.#ports.recoverUncertainDelivery(cause);
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
if (cause instanceof RealtimeDeliveryError) {
|
|
1018
|
+
this.#ports.reportDeliveryFailure(cause);
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
throw cause;
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
/**
|
|
1025
|
+
* Drop everything that has reached a terminal state.
|
|
1026
|
+
*
|
|
1027
|
+
* Called when a ledger is about to overflow rather than on a timer: what makes an entry droppable
|
|
1028
|
+
* is that nothing can still refer to it, and that is a property of its state, not its age.
|
|
1029
|
+
*/
|
|
1030
|
+
#pruneTerminalToolState() {
|
|
1031
|
+
for (const ledger of [this.#toolCalls, this.#overflowToolCalls]) {
|
|
1032
|
+
for (const [key, state] of [...ledger.entries()]) {
|
|
1033
|
+
if (state.final_disposition !== null)
|
|
1034
|
+
ledger.delete(key);
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
for (const [key, batch] of [...this.#continuationBatches.entries()]) {
|
|
1038
|
+
if (batch.phase === 'terminal' || batch.phase === 'abandoned') {
|
|
1039
|
+
this.#continuationBatches.delete(key);
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
const surviving = this.#continuationFifo.filter(key => this.#continuationBatches.has(key));
|
|
1043
|
+
this.#continuationFifo.length = 0;
|
|
1044
|
+
this.#continuationFifo.push(...surviving);
|
|
1045
|
+
}
|
|
1046
|
+
#supersededAcceptance(event) {
|
|
1047
|
+
return this.#refusalAcceptance(event, 'superseded', '{"state":"superseded"}');
|
|
1048
|
+
}
|
|
1049
|
+
#overCapacityAcceptance(event) {
|
|
1050
|
+
return this.#refusalAcceptance(event, 'over_capacity', '{"code":"over_capacity","state":"refused"}');
|
|
1051
|
+
}
|
|
1052
|
+
/** A refusal the service authors itself, rather than one the bridge produced. */
|
|
1053
|
+
#refusalAcceptance(event, code, content) {
|
|
1054
|
+
const hostItem = {
|
|
1055
|
+
kind: 'tool_output',
|
|
1056
|
+
host_item_id: this.#ports.idFactory(),
|
|
1057
|
+
event_id: this.#ports.idFactory(),
|
|
1058
|
+
call_id: event.call_id,
|
|
1059
|
+
content,
|
|
1060
|
+
};
|
|
1061
|
+
return {
|
|
1062
|
+
accepted: false,
|
|
1063
|
+
code,
|
|
1064
|
+
host_item: hostItem,
|
|
1065
|
+
response_intent: { kind: 'tool_result', item: hostItem, task_summary: null, origin_spoken: false },
|
|
1066
|
+
delegate_id: null,
|
|
1067
|
+
sync_result: false,
|
|
1068
|
+
executor: null,
|
|
1069
|
+
op: null,
|
|
1070
|
+
inline_fulfilled: false,
|
|
1071
|
+
telemetry: null,
|
|
1072
|
+
};
|
|
1073
|
+
}
|
|
1074
|
+
/** The `executor` argument names a registered host controller, or nothing. */
|
|
1075
|
+
#agentExecutorName(value) {
|
|
1076
|
+
return typeof value === 'string' && this.#ports.agentController(value) !== undefined ? value : null;
|
|
1077
|
+
}
|
|
1078
|
+
/**
|
|
1079
|
+
* The host tools. A controller receives the fenced public request and returns structured facts;
|
|
1080
|
+
* RealtimeService alone maps those facts to provider-facing result language.
|
|
1081
|
+
*/
|
|
1082
|
+
async #interceptHost(event, originRef) {
|
|
1083
|
+
if (event.name === CONFIRM_TOOL) {
|
|
1084
|
+
return this.#refusalAcceptance(event, 'unknown_confirmation', UNKNOWN_CONFIRMATION_TOOL_RESULT);
|
|
1085
|
+
}
|
|
1086
|
+
if (this.#ports.taskHost?.isCurrent?.() === false)
|
|
1087
|
+
return this.#refusalAcceptance(event, 'superseded', '{"code":"superseded"}');
|
|
1088
|
+
if (event.name === 'schedule') {
|
|
1089
|
+
const user = this.#ports.intakeUser(), authority = this.#ports.currentUserTurn(event, originRef), host = this.#ports.scheduleHost;
|
|
1090
|
+
if (!host)
|
|
1091
|
+
return this.#refusalAcceptance(event, 'unsupported_tool', '{"code":"unsupported_tool"}');
|
|
1092
|
+
if (!authority || !user || event.session_epoch <= this.#ports.discardedInputEpoch() || user.epoch !== event.session_epoch || originRef !== user.origin_ref)
|
|
1093
|
+
return this.#refusalAcceptance(event, 'missing_origin_ref', '{"code":"missing_origin_ref"}');
|
|
1094
|
+
const args = { ...event.arguments };
|
|
1095
|
+
delete args.origin_ref;
|
|
1096
|
+
try {
|
|
1097
|
+
const result = await host.invoke(args, { request_id: event.session_epoch + ':' + event.call_id, origin_ref: user.origin_ref, sources: dispatchSources(this.#ports.runtime.memory?.channels.get('conversation')?.items ?? []), stillWanted: authority.stillWanted });
|
|
1098
|
+
return scheduledToolResult(event, result);
|
|
1099
|
+
}
|
|
1100
|
+
catch (error) {
|
|
1101
|
+
const code = error instanceof Error ? error.message : 'schedule_failed';
|
|
1102
|
+
return scheduledToolResult(event, { code, state: 'refused' }, code, false);
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
if (event.name === 'task') {
|
|
1106
|
+
const host = this.#ports.taskHost, user = this.#ports.intakeUser();
|
|
1107
|
+
const authority = this.#ports.currentUserTurn(event, originRef);
|
|
1108
|
+
if (!host)
|
|
1109
|
+
return this.#refusalAcceptance(event, 'unsupported_tool', '{"code":"unsupported_tool"}');
|
|
1110
|
+
if (!authority || !user || event.session_epoch <= this.#ports.discardedInputEpoch() || user.epoch !== event.session_epoch || originRef !== user.origin_ref)
|
|
1111
|
+
return this.#refusalAcceptance(event, 'missing_origin_ref', '{"code":"missing_origin_ref"}');
|
|
1112
|
+
const taskArguments = { ...event.arguments };
|
|
1113
|
+
delete taskArguments.origin_ref;
|
|
1114
|
+
const parsed = taskToolArguments.safeParse(taskArguments);
|
|
1115
|
+
if (!parsed.success)
|
|
1116
|
+
return this.#refusalAcceptance(event, 'invalid_params', '{"code":"invalid_params"}');
|
|
1117
|
+
const args = parsed.data, sources = dispatchSources(this.#ports.runtime.memory?.channels.get('conversation')?.items ?? []);
|
|
1118
|
+
if (args.source_refs.some(ref => !sources.some(source => source.ref === ref)))
|
|
1119
|
+
return this.#refusalAcceptance(event, 'invalid_source_refs', '{"code":"invalid_source_refs"}');
|
|
1120
|
+
if (!authority.stillWanted())
|
|
1121
|
+
return this.#refusalAcceptance(event, 'superseded', '{"code":"superseded"}');
|
|
1122
|
+
try {
|
|
1123
|
+
let task;
|
|
1124
|
+
if (args.operation === 'declare') {
|
|
1125
|
+
const todo = args.link_source_todo ? host.sourceTodo?.(user.origin_ref) : undefined;
|
|
1126
|
+
if (args.link_source_todo && !todo)
|
|
1127
|
+
throw Error('source_todo_unavailable');
|
|
1128
|
+
task = await host.tasks.delegate(event.call_id, { conversation_id: host.conversation_id, ...(host.conversation_generation === undefined ? {} : { conversation_generation: host.conversation_generation }), goal: args.goal, acceptance: args.acceptance, origin_ref: user.origin_ref, ...(todo ? { todo_ref: todo } : {}) });
|
|
1129
|
+
}
|
|
1130
|
+
else {
|
|
1131
|
+
task = host.tasks.get(args.task_id);
|
|
1132
|
+
if (task.conversation_id !== host.conversation_id)
|
|
1133
|
+
throw Error('task_not_owned');
|
|
1134
|
+
if (args.operation === 'cancel' && (task.conversation_generation ?? 0) !== (host.conversation_generation ?? 0))
|
|
1135
|
+
throw Error('task_not_owned');
|
|
1136
|
+
const fence = { task_id: task.id, control_revision: task.control_revision, goal_revision: task.goal_revision };
|
|
1137
|
+
if (args.operation === 'revise')
|
|
1138
|
+
task = await host.tasks.reviseGoal(event.call_id, fence, { kind: 'nova' }, args.goal, args.acceptance);
|
|
1139
|
+
else if (args.operation === 'return') {
|
|
1140
|
+
task = await host.tasks.returnFromUserOrigin(event.call_id, fence, { conversation_id: host.conversation_id, conversation_generation: host.conversation_generation ?? 0, origin_ref: user.origin_ref }, () => authority.stillWanted() && (host.isCurrent?.() ?? true));
|
|
1141
|
+
void host.wake?.(task.id);
|
|
1142
|
+
}
|
|
1143
|
+
else if (args.operation === 'continue') {
|
|
1144
|
+
task = await host.tasks.continue(event.call_id, fence, { kind: 'nova' });
|
|
1145
|
+
void host.wake?.(task.id);
|
|
1146
|
+
}
|
|
1147
|
+
else if (args.operation === 'cancel') {
|
|
1148
|
+
if (!host.cancel)
|
|
1149
|
+
throw Error('task_execution_unavailable');
|
|
1150
|
+
await host.cancel(event.call_id, fence);
|
|
1151
|
+
}
|
|
1152
|
+
else
|
|
1153
|
+
throw Error('task_execution_unavailable');
|
|
1154
|
+
}
|
|
1155
|
+
return { ...this.#refusalAcceptance(event, 'accepted', canonicalJson({ code: 'accepted', task_id: task.id })), accepted: true, inline_fulfilled: true };
|
|
1156
|
+
}
|
|
1157
|
+
catch (error) {
|
|
1158
|
+
const code = error instanceof Error ? error.message : 'task_failed';
|
|
1159
|
+
return this.#refusalAcceptance(event, code, canonicalJson({ code }));
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
if (event.name !== DISPATCH_TOOL && event.name !== CANCEL_TOOL)
|
|
1163
|
+
return null;
|
|
1164
|
+
const executor = this.#agentExecutorName(event.arguments.executor);
|
|
1165
|
+
const raw = event.arguments.instruction;
|
|
1166
|
+
const instruction = typeof raw === 'string' ? stripLikePython(raw) : null;
|
|
1167
|
+
const instructionValid = event.name === CANCEL_TOOL && raw === undefined
|
|
1168
|
+
? true
|
|
1169
|
+
: instruction !== null && instruction !== '' && codePointLengthLikePython(instruction) <= 4000;
|
|
1170
|
+
if (executor === null || !instructionValid) {
|
|
1171
|
+
return this.#refusalAcceptance(event, 'invalid_params', '{"code":"invalid_params"}');
|
|
1172
|
+
}
|
|
1173
|
+
// Both act on the user's behalf, so both need the current user turn as origin: a spontaneous
|
|
1174
|
+
// `cancel` would stop work nobody asked to stop.
|
|
1175
|
+
const user = this.#ports.intakeUser();
|
|
1176
|
+
if (event.session_epoch <= this.#ports.discardedInputEpoch() || originRef === null || user?.epoch !== event.session_epoch || originRef !== user.origin_ref) {
|
|
1177
|
+
return this.#refusalAcceptance(event, 'missing_origin_ref', '{"code":"missing_origin_ref"}');
|
|
1178
|
+
}
|
|
1179
|
+
const conversationItems = this.#ports.runtime.memory?.channels.get('conversation')?.items ?? [];
|
|
1180
|
+
const conversationContext = projectRecoveryTurns(conversationItems, { maxPairs: 8, maxChars: 8000 }).map(({ role, text, sequence }) => ({ role, text, sequence }));
|
|
1181
|
+
const sources = dispatchSources(conversationItems);
|
|
1182
|
+
const sourceRefs = event.arguments.source_refs ?? [];
|
|
1183
|
+
if (event.name === DISPATCH_TOOL && ('source_quotes' in event.arguments || !Array.isArray(sourceRefs)
|
|
1184
|
+
|| sourceRefs.length > 8 || sourceRefs.some(ref => typeof ref !== 'string' || !sources.some(source => source.ref === ref)))) {
|
|
1185
|
+
return this.#refusalAcceptance(event, 'invalid_source_refs', canonicalJson({
|
|
1186
|
+
code: 'invalid_source_refs', parameter: 'source_refs',
|
|
1187
|
+
message: '任务尚未提交。source_refs 必须选择用户原话引用目录中的 ref。', sources: recentDispatchSources(conversationItems),
|
|
1188
|
+
}));
|
|
1189
|
+
}
|
|
1190
|
+
const sourceQuotes = sources.filter(source => sourceRefs.includes(source.ref)).map(source => source.text);
|
|
1191
|
+
const controller = this.#ports.agentController(executor);
|
|
1192
|
+
if (controller === undefined)
|
|
1193
|
+
return this.#refusalAcceptance(event, 'unsupported_tool', '{"code":"unsupported_tool"}');
|
|
1194
|
+
// A user turn that supersedes an async controller operation makes its result informational only;
|
|
1195
|
+
// the controller must re-check this fence before it changes executor state.
|
|
1196
|
+
const authority = this.#ports.currentUserTurn(event, originRef);
|
|
1197
|
+
if (authority === null)
|
|
1198
|
+
return this.#refusalAcceptance(event, 'superseded', '{"code":"superseded"}');
|
|
1199
|
+
const revision = authority.acceptedUserInputRevision;
|
|
1200
|
+
if (event.name === CANCEL_TOOL && this.#ports.taskHost) {
|
|
1201
|
+
const host = this.#ports.taskHost;
|
|
1202
|
+
if (host.isCurrent?.() === false)
|
|
1203
|
+
return this.#refusalAcceptance(event, 'task_frontend_stale', '{"code":"task_frontend_stale"}');
|
|
1204
|
+
const candidates = host.tasks.list().filter(task => task.conversation_id === host.conversation_id
|
|
1205
|
+
&& (task.conversation_generation ?? 0) === (host.conversation_generation ?? 0) && task.execution_route === executor
|
|
1206
|
+
&& task.phase !== 'completed' && task.phase !== 'cancelled');
|
|
1207
|
+
const selected = event.arguments.task_id === undefined ? candidates.length === 1 ? candidates[0] : undefined
|
|
1208
|
+
: candidates.find(task => task.id === event.arguments.task_id);
|
|
1209
|
+
if (selected) {
|
|
1210
|
+
if (!host.cancel)
|
|
1211
|
+
return this.#refusalAcceptance(event, 'task_execution_unavailable', '{"code":"task_execution_unavailable"}');
|
|
1212
|
+
try {
|
|
1213
|
+
await host.cancel(event.call_id, { task_id: selected.id, control_revision: selected.control_revision, goal_revision: selected.goal_revision });
|
|
1214
|
+
}
|
|
1215
|
+
catch {
|
|
1216
|
+
return this.#refusalAcceptance(event, 'task_cancel_unconfirmed', '{"code":"task_cancel_unconfirmed"}');
|
|
1217
|
+
}
|
|
1218
|
+
return { ...this.#refusalAcceptance(event, 'accepted', canonicalJson({ code: 'accepted', task_id: selected.id })), accepted: true, inline_fulfilled: true };
|
|
1219
|
+
}
|
|
1220
|
+
if (event.arguments.task_id !== undefined || candidates.length > 1)
|
|
1221
|
+
return this.#refusalAcceptance(event, 'ambiguous_task', canonicalJson({ code: 'ambiguous_task', task_ids: candidates.map(task => task.id) }));
|
|
1222
|
+
return this.#refusalAcceptance(event, 'not_running', '{"code":"not_running"}');
|
|
1223
|
+
}
|
|
1224
|
+
let taskContext;
|
|
1225
|
+
if (event.name === DISPATCH_TOOL && event.arguments.task_id !== undefined) {
|
|
1226
|
+
try {
|
|
1227
|
+
const host = this.#ports.taskHost;
|
|
1228
|
+
if (!host || typeof event.arguments.task_id !== 'string')
|
|
1229
|
+
throw Error('invalid_task');
|
|
1230
|
+
const task = host.tasks.get(event.arguments.task_id);
|
|
1231
|
+
if (task.conversation_id !== host.conversation_id)
|
|
1232
|
+
throw Error('task_not_owned');
|
|
1233
|
+
taskContext = host.tasks.continuationContext({ task_id: task.id, control_revision: task.control_revision, goal_revision: task.goal_revision });
|
|
1234
|
+
await host.tasks.setRoute(taskContext.fence, executor);
|
|
1235
|
+
}
|
|
1236
|
+
catch (error) {
|
|
1237
|
+
const code = error instanceof Error ? error.message : 'invalid_task';
|
|
1238
|
+
return this.#refusalAcceptance(event, code, canonicalJson({ code }));
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
const fence = () => authority.stillWanted() && (taskContext?.stillWanted() ?? true);
|
|
1242
|
+
const rawResult = event.name === DISPATCH_TOOL
|
|
1243
|
+
? await controller.dispatch({
|
|
1244
|
+
...(taskContext ? { taskContext } : {}),
|
|
1245
|
+
instruction: instruction, originalUserText: user.text, input_origin_ref: user.origin_ref, origin_ref: taskContext?.origin_ref ?? user.origin_ref,
|
|
1246
|
+
conversationContext, sourceQuotes,
|
|
1247
|
+
sessionEpoch: event.session_epoch, acceptedUserInputRevision: revision, stillWanted: fence,
|
|
1248
|
+
})
|
|
1249
|
+
: await controller.cancel({
|
|
1250
|
+
...(instruction === null ? {} : { instruction }), originalUserText: user.text, origin_ref: user.origin_ref,
|
|
1251
|
+
sessionEpoch: event.session_epoch, acceptedUserInputRevision: revision, stillWanted: fence,
|
|
1252
|
+
});
|
|
1253
|
+
const result = parseAgentActionResult(rawResult);
|
|
1254
|
+
if (result === null) {
|
|
1255
|
+
return this.#refusalAcceptance(event, 'controller_result_invalid', canonicalJson({ code: 'controller_result_invalid' }));
|
|
1256
|
+
}
|
|
1257
|
+
if (result.code === 'delegated') {
|
|
1258
|
+
if (!controller.descriptor.ownedChannels.includes(result.detail.channel)) {
|
|
1259
|
+
return this.#refusalAcceptance(event, 'controller_result_invalid', canonicalJson({ code: 'controller_result_invalid' }));
|
|
1260
|
+
}
|
|
1261
|
+
return this.#controllerDelegationAcceptance(event, result, instruction);
|
|
1262
|
+
}
|
|
1263
|
+
if (result.code === 'monitor_stop_requested'
|
|
1264
|
+
&& !controller.descriptor.ownedChannels.includes(result.detail.channel)) {
|
|
1265
|
+
return this.#refusalAcceptance(event, 'controller_result_invalid', canonicalJson({ code: 'controller_result_invalid' }));
|
|
1266
|
+
}
|
|
1267
|
+
const acceptance = this.#refusalAcceptance(event, result.code, this.#agentActionContent(result));
|
|
1268
|
+
return result.accepted ? { ...acceptance, accepted: true, inline_fulfilled: true,
|
|
1269
|
+
...(result.code === 'intake_opened' || result.code === 'intake_in_progress'
|
|
1270
|
+
? { continuation: 'deferred' } : {}),
|
|
1271
|
+
} : acceptance;
|
|
1272
|
+
}
|
|
1273
|
+
#agentActionContent(result) {
|
|
1274
|
+
switch (result.code) {
|
|
1275
|
+
case 'intake_opened':
|
|
1276
|
+
case 'intake_in_progress':
|
|
1277
|
+
if (result.detail.state === 'dispatch_unknown')
|
|
1278
|
+
return canonicalJson({
|
|
1279
|
+
code: result.code, execution_started: null,
|
|
1280
|
+
message: '派单结果暂时无法确认,任务可能已开始。先核实执行状态,不要重复派单。',
|
|
1281
|
+
});
|
|
1282
|
+
return canonicalJson({
|
|
1283
|
+
code: result.code,
|
|
1284
|
+
execution_started: false,
|
|
1285
|
+
});
|
|
1286
|
+
case 'intake_cancelled':
|
|
1287
|
+
return canonicalJson({ code: result.code, message: '待执行任务已取消,尚未启动。' });
|
|
1288
|
+
case 'cancelled':
|
|
1289
|
+
return canonicalJson({
|
|
1290
|
+
code: result.code,
|
|
1291
|
+
message: 'code=cancelled:已请求停止任务,稍后有终态事实。',
|
|
1292
|
+
});
|
|
1293
|
+
case 'ambiguous_work':
|
|
1294
|
+
return canonicalJson({
|
|
1295
|
+
code: result.code,
|
|
1296
|
+
running_count: result.detail.running.length,
|
|
1297
|
+
message: 'code=ambiguous_work:有多个任务正在执行,请说明要停止哪一个。',
|
|
1298
|
+
});
|
|
1299
|
+
case 'not_running':
|
|
1300
|
+
return canonicalJson({ code: result.code, message: 'code=not_running:当前没有正在执行的任务。' });
|
|
1301
|
+
case 'busy':
|
|
1302
|
+
return canonicalJson({ code: result.code, message: '当前已有一个监控任务在运行。' });
|
|
1303
|
+
case 'clarification_required':
|
|
1304
|
+
return canonicalJson({ code: result.code, message: '请完整重述需要监控的画面条件、提醒要求和时长。' });
|
|
1305
|
+
case 'assessment_unavailable':
|
|
1306
|
+
return canonicalJson({ code: result.code, message: '暂时无法判断监控请求。' });
|
|
1307
|
+
case 'monitor_stop_requested':
|
|
1308
|
+
return canonicalJson({ code: result.code, message: '已请求停止监控。' });
|
|
1309
|
+
case 'accepted':
|
|
1310
|
+
case 'delegated':
|
|
1311
|
+
case 'unsupported_tool':
|
|
1312
|
+
case 'superseded':
|
|
1313
|
+
case 'runtime_rejected':
|
|
1314
|
+
return canonicalJson({ code: result.code });
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
#controllerDelegationAcceptance(event, result, instruction) {
|
|
1318
|
+
const hostItem = {
|
|
1319
|
+
kind: 'tool_output', host_item_id: this.#ports.idFactory(), event_id: this.#ports.idFactory(),
|
|
1320
|
+
call_id: event.call_id, content: canonicalJson({ state: 'accepted' }),
|
|
1321
|
+
};
|
|
1322
|
+
return {
|
|
1323
|
+
accepted: true,
|
|
1324
|
+
code: 'accepted',
|
|
1325
|
+
host_item: hostItem,
|
|
1326
|
+
response_intent: {
|
|
1327
|
+
kind: 'delegation_acknowledgement', item: hostItem,
|
|
1328
|
+
task_summary: [...stripLikePython(instruction)].slice(0, MAX_CONTINUATION_TASK_SUMMARY).join(''),
|
|
1329
|
+
origin_spoken: false,
|
|
1330
|
+
},
|
|
1331
|
+
delegate_id: result.delegate_id,
|
|
1332
|
+
sync_result: false,
|
|
1333
|
+
executor: result.detail.channel,
|
|
1334
|
+
op: result.detail.op,
|
|
1335
|
+
inline_fulfilled: false,
|
|
1336
|
+
telemetry: null,
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
#recordToolAdmission(input) {
|
|
1340
|
+
if (this.#ports.telemetry === undefined || input.logicalName === null)
|
|
1341
|
+
return;
|
|
1342
|
+
const outcome = input.superseded
|
|
1343
|
+
? 'superseded'
|
|
1344
|
+
: !input.acceptance.accepted
|
|
1345
|
+
? 'rejected'
|
|
1346
|
+
: input.acceptance.inline_fulfilled
|
|
1347
|
+
? 'inline'
|
|
1348
|
+
: input.acceptance.sync_result
|
|
1349
|
+
? 'sync'
|
|
1350
|
+
: 'delegated';
|
|
1351
|
+
this.#ports.telemetry.record('tool.admission', {
|
|
1352
|
+
logical_name: input.logicalName, call_id: input.callId,
|
|
1353
|
+
delegate_id: input.acceptance.delegate_id, outcome, code: input.acceptance.code,
|
|
1354
|
+
});
|
|
1355
|
+
}
|
|
1356
|
+
/** Give the provider the result it is holding a slot for, once. */
|
|
1357
|
+
async #confirmSupersededOutput(state) {
|
|
1358
|
+
if (state.output === 'confirmed')
|
|
1359
|
+
return;
|
|
1360
|
+
await this.session.injectToolOutput(state.acceptance.host_item);
|
|
1361
|
+
state.output = 'confirmed';
|
|
1362
|
+
state.final_disposition = 'superseded';
|
|
1363
|
+
}
|
|
1364
|
+
// ---------------------------------------------------------------------------------------------
|
|
1365
|
+
// Family M: batching tool results into one turn.
|
|
1366
|
+
// ---------------------------------------------------------------------------------------------
|
|
1367
|
+
/** A tool continuation inherits evidence only from its confirmed outputs in the current turn. */
|
|
1368
|
+
bindToolContinuationOrigin(epoch, responseId) {
|
|
1369
|
+
if (epoch !== this.session.sessionEpoch || !this.session.responseIsToolContinuation(responseId))
|
|
1370
|
+
return;
|
|
1371
|
+
const revision = this.session.providerTurnUserInputRevision(responseId);
|
|
1372
|
+
if (revision !== this.session.userInputRevision)
|
|
1373
|
+
return;
|
|
1374
|
+
let itemId;
|
|
1375
|
+
// ponytail: bounded ledger scan; index event ids if large continuation batches become common.
|
|
1376
|
+
for (const eventId of this.session.responseEventIds(responseId)) {
|
|
1377
|
+
const state = [...this.#toolCalls.values(), ...this.#overflowToolCalls.values()].find(current => (current.acceptance.host_item.event_id === eventId
|
|
1378
|
+
&& current.provider_session_epoch === epoch
|
|
1379
|
+
&& current.output === 'confirmed'
|
|
1380
|
+
&& current.continuation !== 'abandoned'
|
|
1381
|
+
&& current.observation !== 'superseded'));
|
|
1382
|
+
if (state?.origin_user_input_revision !== revision)
|
|
1383
|
+
return;
|
|
1384
|
+
const sourceItem = this.#ports.userOrigins.itemForResponse(epoch, state.provider_response_id);
|
|
1385
|
+
if (sourceItem === undefined || this.#ports.userOrigins.revisionForItem(epoch, sourceItem) !== revision
|
|
1386
|
+
|| (itemId !== undefined && itemId !== sourceItem))
|
|
1387
|
+
return;
|
|
1388
|
+
itemId = sourceItem;
|
|
1389
|
+
}
|
|
1390
|
+
if (itemId !== undefined)
|
|
1391
|
+
this.#ports.userOrigins.bindRetryResponse({ epoch, responseId, itemId });
|
|
1392
|
+
}
|
|
1393
|
+
/** Bind the head batch to the response that will speak it. */
|
|
1394
|
+
bindContinuation(responseId) {
|
|
1395
|
+
const head = this.#continuationFifo[0];
|
|
1396
|
+
if (head === undefined)
|
|
1397
|
+
return;
|
|
1398
|
+
const batch = this.#continuationBatches.get(head);
|
|
1399
|
+
if (batch?.phase !== 'requested')
|
|
1400
|
+
return;
|
|
1401
|
+
batch.phase = 'bound';
|
|
1402
|
+
batch.continuation_response_id = responseId;
|
|
1403
|
+
for (const key of batch.call_keys) {
|
|
1404
|
+
const state = this.#toolCallState(key);
|
|
1405
|
+
if (state === undefined)
|
|
1406
|
+
continue;
|
|
1407
|
+
state.continuation = 'bound';
|
|
1408
|
+
state.continuation_response_id = responseId;
|
|
1409
|
+
this.#ports.host.bindContinuationAcknowledgement(state, responseId);
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
/**
|
|
1413
|
+
* Close the head batch when the response that was speaking it ends.
|
|
1414
|
+
*
|
|
1415
|
+
* Only the head, and only if this is the response it was bound to: a terminal for some other
|
|
1416
|
+
* response says nothing about whether this batch was spoken.
|
|
1417
|
+
*/
|
|
1418
|
+
finishContinuation(event) {
|
|
1419
|
+
const head = this.#continuationFifo[0];
|
|
1420
|
+
if (head === undefined)
|
|
1421
|
+
return;
|
|
1422
|
+
const batch = this.#continuationBatches.get(head);
|
|
1423
|
+
if (batch === undefined)
|
|
1424
|
+
return;
|
|
1425
|
+
if (batch.phase !== 'bound' || batch.continuation_response_id !== event.response_id)
|
|
1426
|
+
return;
|
|
1427
|
+
batch.phase = 'terminal';
|
|
1428
|
+
for (const key of batch.call_keys) {
|
|
1429
|
+
const state = this.#toolCallState(key);
|
|
1430
|
+
if (state === undefined)
|
|
1431
|
+
continue;
|
|
1432
|
+
state.continuation = 'terminal';
|
|
1433
|
+
state.final_disposition = !state.acceptance.accepted
|
|
1434
|
+
? 'refused'
|
|
1435
|
+
: event.status === 'completed' || event.status === 'yielded'
|
|
1436
|
+
? 'completed'
|
|
1437
|
+
: 'abandoned';
|
|
1438
|
+
}
|
|
1439
|
+
this.#continuationFifo.shift();
|
|
1440
|
+
}
|
|
1441
|
+
/** A collecting batch whose originating response has ended is ready to speak. */
|
|
1442
|
+
finishOrigin(responseId) {
|
|
1443
|
+
const batch = this.#continuationBatches.get(callKey(this.session.sessionEpoch, responseId));
|
|
1444
|
+
if (batch?.phase !== 'collecting' && batch?.phase !== 'ready')
|
|
1445
|
+
return;
|
|
1446
|
+
batch.origin_status = this.#originStatus(responseId);
|
|
1447
|
+
batch.phase = 'ready';
|
|
1448
|
+
}
|
|
1449
|
+
abandonProjectConfirmationContinuation(sessionEpoch, responseId) {
|
|
1450
|
+
const batch = this.#continuationBatches.get(callKey(sessionEpoch, responseId));
|
|
1451
|
+
if (batch === undefined)
|
|
1452
|
+
return;
|
|
1453
|
+
batch.origin_status = 'cancelled';
|
|
1454
|
+
batch.phase = 'ready';
|
|
1455
|
+
}
|
|
1456
|
+
/** Take the deferred calls belonging to one epoch, leaving the rest queued in order. */
|
|
1457
|
+
takeConfirmationDeferredCalls(sourceEpoch) {
|
|
1458
|
+
const matching = [];
|
|
1459
|
+
const retained = [];
|
|
1460
|
+
for (const deferred of this.#originDeferredToolCalls) {
|
|
1461
|
+
(deferred.event.session_epoch === sourceEpoch ? matching : retained).push(deferred);
|
|
1462
|
+
}
|
|
1463
|
+
this.#originDeferredToolCalls.length = 0;
|
|
1464
|
+
this.#originDeferredToolCalls.push(...retained);
|
|
1465
|
+
return matching;
|
|
1466
|
+
}
|
|
1467
|
+
/** Whether anything at all refers to this turn. A proof nothing can cite is not worth keeping. */
|
|
1468
|
+
originCanReferenceProof(key) {
|
|
1469
|
+
const { sessionEpoch, id: responseId } = parseCallKey(key);
|
|
1470
|
+
if (this.#originDeferredToolCalls.some(deferred => (deferred.event.session_epoch === sessionEpoch && deferred.response_id === responseId))) {
|
|
1471
|
+
return true;
|
|
1472
|
+
}
|
|
1473
|
+
for (const ledger of [this.#toolCalls, this.#overflowToolCalls]) {
|
|
1474
|
+
for (const state of ledger.values()) {
|
|
1475
|
+
if (state.provider_session_epoch === sessionEpoch
|
|
1476
|
+
&& state.provider_response_id === responseId) {
|
|
1477
|
+
return true;
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
if (this.#continuationBatches.has(key))
|
|
1482
|
+
return true;
|
|
1483
|
+
return this.#ports.host.originCanReferenceProof(sessionEpoch, responseId);
|
|
1484
|
+
}
|
|
1485
|
+
/** Whether anything *unfinished* refers to it, which is what makes it unsafe to evict. */
|
|
1486
|
+
originHasNonterminalReference(key) {
|
|
1487
|
+
const { sessionEpoch, id: responseId } = parseCallKey(key);
|
|
1488
|
+
if (this.#originDeferredToolCalls.some(deferred => (deferred.event.session_epoch === sessionEpoch && deferred.response_id === responseId))) {
|
|
1489
|
+
return true;
|
|
1490
|
+
}
|
|
1491
|
+
for (const ledger of [this.#toolCalls, this.#overflowToolCalls]) {
|
|
1492
|
+
for (const state of ledger.values()) {
|
|
1493
|
+
if (state.provider_session_epoch === sessionEpoch
|
|
1494
|
+
&& state.provider_response_id === responseId
|
|
1495
|
+
&& state.final_disposition === null) {
|
|
1496
|
+
return true;
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
const batch = this.#continuationBatches.get(key);
|
|
1501
|
+
if (batch !== undefined && batch.phase !== 'terminal' && batch.phase !== 'abandoned')
|
|
1502
|
+
return true;
|
|
1503
|
+
return this.#ports.host.originHasNonterminalReference(sessionEpoch, responseId);
|
|
1504
|
+
}
|
|
1505
|
+
/** Each tracked tool call's final disposition, in admission order. */
|
|
1506
|
+
get toolCallDispositionsForTest() {
|
|
1507
|
+
return [...this.#toolCalls.values()].map(state => state.final_disposition);
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
//# sourceMappingURL=tool-continuations.js.map
|