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,1711 @@
|
|
|
1
|
+
import { USER_PRIORITY } from '../core/memory.js';
|
|
2
|
+
import { MAX_TRACKED_ORIGIN_DELIVERY_PROOFS, MAX_TRACKED_SEMANTIC_ACKNOWLEDGEMENTS, MAX_UNCERTAIN_DELIVERY_RETRIES, PREEMPTIVE_ALERT_CLEAR_ACK_DEADLINE_S, PREEMPTIVE_ALERT_DEADLINE_S, PREEMPT_MIN_PRIORITY, USER_HOLD_MAX_S, callKey, compareQueuedHostResponses, hostFactIntent, semanticAcknowledgement } from './service-state.js';
|
|
3
|
+
import { MAX_CONTINUATION_TASK_SUMMARY, MAX_PENDING_HOST_EVENTS } from './session-state.js';
|
|
4
|
+
import { RealtimeDeliveryError, ResponseRequestUncertainError } from './session.js';
|
|
5
|
+
import { Mutex, diagnosticName, isAbort } from './service-state.js';
|
|
6
|
+
export class HostDelivery {
|
|
7
|
+
/**
|
|
8
|
+
* What this turn was speaking *about*, when that is unambiguous.
|
|
9
|
+
*
|
|
10
|
+
* Only a single suggestion counts: a turn carrying two is answering neither one in particular, and
|
|
11
|
+
* attributing it to either would be a guess recorded as a fact.
|
|
12
|
+
*/
|
|
13
|
+
#playbackAttribution(responseId) {
|
|
14
|
+
const suggestionEvents = this.session.responseEventIds(responseId)
|
|
15
|
+
.filter(eventId => eventId.startsWith('suggestion:'));
|
|
16
|
+
if (suggestionEvents.length === 1) {
|
|
17
|
+
const suggestionId = suggestionEvents[0].slice('suggestion:'.length);
|
|
18
|
+
const suggestion = this.#ports.runtime.suggestionFor?.(suggestionId) ?? null;
|
|
19
|
+
if (suggestion !== null && suggestion.kind === 'selected_progress') {
|
|
20
|
+
const memoryRef = suggestion.evidence_refs[0];
|
|
21
|
+
if (memoryRef !== undefined) {
|
|
22
|
+
return { target: 'selected_progress', memory_ref: memoryRef };
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
if (this.#ports.responseCarriesPersonalRecall(responseId))
|
|
27
|
+
return { target: 'memory_recall' };
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
// ---------------------------------------------------------------------------------------------
|
|
31
|
+
// Family E: playback acknowledgement.
|
|
32
|
+
//
|
|
33
|
+
// The renderer is the only thing that knows whether audio actually reached a person. Everything here
|
|
34
|
+
// turns its reports into facts the rest of the system can rely on -- and refuses to turn them into
|
|
35
|
+
// more than that. "The renderer said it played 0 ms" is not evidence the user heard anything.
|
|
36
|
+
// ---------------------------------------------------------------------------------------------
|
|
37
|
+
playbackStarted(utteranceId, generationEpoch) {
|
|
38
|
+
// Read before the call, because starting playback is what makes it current.
|
|
39
|
+
const generation = this.session.currentGeneration;
|
|
40
|
+
const started = this.session.playbackStarted(utteranceId, generationEpoch);
|
|
41
|
+
if (started
|
|
42
|
+
&& generation !== null
|
|
43
|
+
&& generation.utterance_id === utteranceId
|
|
44
|
+
&& generation.generation_epoch === generationEpoch
|
|
45
|
+
&& this.#ports.telemetry !== undefined) {
|
|
46
|
+
this.#ports.telemetry.record('playback.started', { session_epoch: generation.session_epoch,
|
|
47
|
+
response_id: generation.response_id, utterance_id: utteranceId, generation_epoch: generationEpoch });
|
|
48
|
+
const attribution = this.#playbackAttribution(generation.response_id);
|
|
49
|
+
if (attribution !== null)
|
|
50
|
+
this.#ports.telemetry.record('playback.attribution', attribution);
|
|
51
|
+
}
|
|
52
|
+
return started;
|
|
53
|
+
}
|
|
54
|
+
semanticAcknowledgement(state) {
|
|
55
|
+
return this.#ensureSemanticAcknowledgement(state);
|
|
56
|
+
}
|
|
57
|
+
markOriginDelivered(state) {
|
|
58
|
+
const acknowledgement = this.#ensureSemanticAcknowledgement(state);
|
|
59
|
+
if (acknowledgement === null)
|
|
60
|
+
return false;
|
|
61
|
+
acknowledgement.origin_delivered = true;
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
settleBackgroundAcknowledgement(eventId) {
|
|
65
|
+
const acknowledgement = this.#semanticAcknowledgements.get(eventId) ?? null;
|
|
66
|
+
if (acknowledgement === null)
|
|
67
|
+
return;
|
|
68
|
+
if (acknowledgement.origin_delivered || acknowledgement.heard) {
|
|
69
|
+
acknowledgement.phase = 'delivered';
|
|
70
|
+
acknowledgement.response_id = null;
|
|
71
|
+
acknowledgement.response_session_epoch = null;
|
|
72
|
+
acknowledgement.binding = null;
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
this.#queueSemanticAcknowledgement(acknowledgement);
|
|
76
|
+
}
|
|
77
|
+
bindContinuationAcknowledgement(state, responseId) {
|
|
78
|
+
const acknowledgement = this.#ensureSemanticAcknowledgement(state);
|
|
79
|
+
if (acknowledgement?.phase === 'pending') {
|
|
80
|
+
acknowledgement.phase = 'bound';
|
|
81
|
+
acknowledgement.response_id = responseId;
|
|
82
|
+
acknowledgement.response_session_epoch = this.session.sessionEpoch;
|
|
83
|
+
// The continuation is carried by the tool output itself. That item is protocol state for the
|
|
84
|
+
// function call, not a provider-visible semantic acknowledgement fact, so the acknowledgement
|
|
85
|
+
// must never acquire authority to retire or reopen it.
|
|
86
|
+
acknowledgement.provider_event_id = null;
|
|
87
|
+
acknowledgement.binding = 'continuation';
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
originCanReferenceProof(sessionEpoch, responseId) {
|
|
91
|
+
for (const acknowledgement of this.#semanticAcknowledgements.values()) {
|
|
92
|
+
if (acknowledgement.origin_session_epoch === sessionEpoch
|
|
93
|
+
&& acknowledgement.origin_response_id === responseId) {
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
originHasNonterminalReference(sessionEpoch, responseId) {
|
|
100
|
+
for (const acknowledgement of this.#semanticAcknowledgements.values()) {
|
|
101
|
+
if (acknowledgement.origin_session_epoch === sessionEpoch
|
|
102
|
+
&& acknowledgement.origin_response_id === responseId
|
|
103
|
+
&& acknowledgement.phase !== 'delivered') {
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
/** Insertion-ordered, oldest evicted: a retry already attempted must not be attempted again. */
|
|
110
|
+
#uncertainDeliveryRetries = new Map();
|
|
111
|
+
resetUncertainDeliveryRetries() { this.#uncertainDeliveryRetries.clear(); }
|
|
112
|
+
admitUncertainDeliveryRetry(itemId) {
|
|
113
|
+
if (this.#uncertainDeliveryRetries.has(itemId))
|
|
114
|
+
return false;
|
|
115
|
+
this.#uncertainDeliveryRetries.delete(itemId);
|
|
116
|
+
this.#uncertainDeliveryRetries.set(itemId, null);
|
|
117
|
+
while (this.#uncertainDeliveryRetries.size > MAX_UNCERTAIN_DELIVERY_RETRIES) {
|
|
118
|
+
const oldest = this.#uncertainDeliveryRetries.keys().next();
|
|
119
|
+
if (oldest.done === true)
|
|
120
|
+
break;
|
|
121
|
+
this.#uncertainDeliveryRetries.delete(oldest.value);
|
|
122
|
+
}
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
async deliveryPass() {
|
|
126
|
+
let shouldRedriveContinuations = false;
|
|
127
|
+
await this.withDeliveryLock(async () => {
|
|
128
|
+
if (this.session.releaseStaleUserHold(USER_HOLD_MAX_S)) {
|
|
129
|
+
this.#ports.onDiagnostic('[realtime-diagnostic] floor_stale_hold_released');
|
|
130
|
+
}
|
|
131
|
+
if (this.#rendererHostDeliveryPaused)
|
|
132
|
+
return;
|
|
133
|
+
const eligiblePreemptWasArmed = this.hasEligiblePreempt();
|
|
134
|
+
await this.#maybePreemptLocked();
|
|
135
|
+
if (this.session.userResponseMode === 'requested') {
|
|
136
|
+
await this.session.requestPendingUserResponse();
|
|
137
|
+
}
|
|
138
|
+
await this.#flushHostItemsLocked();
|
|
139
|
+
if (this.#hostItems.length === 0 && !this.#ports.approvalHost.pending) {
|
|
140
|
+
await this.session.requestDeliveryRecovery();
|
|
141
|
+
}
|
|
142
|
+
shouldRedriveContinuations = eligiblePreemptWasArmed
|
|
143
|
+
&& (!this.hasEligiblePreempt())
|
|
144
|
+
&& this.session.foregroundIdle
|
|
145
|
+
&& this.session.floor.state !== 'user_speaking';
|
|
146
|
+
});
|
|
147
|
+
return shouldRedriveContinuations;
|
|
148
|
+
}
|
|
149
|
+
snapshot() {
|
|
150
|
+
const alert = this.#preemptiveAlert;
|
|
151
|
+
return {
|
|
152
|
+
sessionEpoch: this.session.sessionEpoch,
|
|
153
|
+
floor: this.session.floor.state,
|
|
154
|
+
providerIdle: this.session.providerIdle,
|
|
155
|
+
foregroundIdle: this.session.foregroundIdle,
|
|
156
|
+
rendererPaused: this.#rendererHostDeliveryPaused,
|
|
157
|
+
activeResponseId: this.session.activeProviderResponseId,
|
|
158
|
+
userResponseMode: this.session.userResponseMode,
|
|
159
|
+
urgentOwner: this.#urgentHostResponseOwner === null ? null : {
|
|
160
|
+
session_epoch: this.#urgentHostResponseOwner.session_epoch,
|
|
161
|
+
event_id: this.#urgentHostResponseOwner.event_id,
|
|
162
|
+
response_id: this.#urgentHostResponseOwner.response_id,
|
|
163
|
+
delivery_token: this.#urgentHostResponseOwner.delivery_token,
|
|
164
|
+
},
|
|
165
|
+
queuedEventIds: this.queuedHostItems().map(queued => queued.intent.item.event_id),
|
|
166
|
+
armedPreemptPriority: this.#pendingPreemptPriority,
|
|
167
|
+
preemptiveAlert: alert === null ? null : {
|
|
168
|
+
...alert,
|
|
169
|
+
old_generation: alert.old_generation === null ? null : { ...alert.old_generation }
|
|
170
|
+
},
|
|
171
|
+
epochNeedingActivation: this.#providerEpochNeedingActivation,
|
|
172
|
+
acknowledgementPhases: Object.fromEntries([...this.#semanticAcknowledgements.entries()]
|
|
173
|
+
.map(([eventId, acknowledgement]) => [eventId, acknowledgement.phase])),
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
withDeliveryLock(body) { return this.#deliveryLock.run(body); }
|
|
177
|
+
get rendererPaused() { return this.#rendererHostDeliveryPaused; }
|
|
178
|
+
get currentUrgentOwner() { return this.#urgentHostResponseOwner; }
|
|
179
|
+
get currentPreemption() { return this.#preemptiveAlert; }
|
|
180
|
+
releasePreemptionAfterFailure() { this.#preemptiveAlert = null; }
|
|
181
|
+
releaseUrgentOwner() { this.#urgentHostResponseOwner = null; }
|
|
182
|
+
resetOriginProofs() { this.#originDeliveryProofs.clear(); }
|
|
183
|
+
hasOriginDeliveryProof(key) { return this.#originDeliveryProofs.has(key); }
|
|
184
|
+
releaseAcknowledgementReservation() { this.#semanticAcknowledgementReservations -= 1; }
|
|
185
|
+
hasSemanticAcknowledgement(id) { return this.#semanticAcknowledgements.has(id); }
|
|
186
|
+
retirementTasks() { return [...this.#providerRetirementTasks]; }
|
|
187
|
+
acknowledgementReleaseTasks() { return [...this.#semanticAcknowledgementReleaseTasks]; }
|
|
188
|
+
acceptUserActivation(epoch) {
|
|
189
|
+
if (this.#providerEpochNeedingActivation === epoch)
|
|
190
|
+
this.#providerEpochNeedingActivation = null;
|
|
191
|
+
this.#providerReconnectSourceEpoch = null;
|
|
192
|
+
}
|
|
193
|
+
requireActivation() { this.#providerEpochNeedingActivation = this.session.sessionEpoch; }
|
|
194
|
+
findQueuedEvent(eventId) {
|
|
195
|
+
return this.#hostItems.find(candidate => candidate.intent.item.event_id === eventId);
|
|
196
|
+
}
|
|
197
|
+
spendReconnectPermit(preemption) {
|
|
198
|
+
const spent = { ...preemption, cancel_sent: true, reconnect_permit_consumed: true };
|
|
199
|
+
this.#preemptiveAlert = spent;
|
|
200
|
+
return spent;
|
|
201
|
+
}
|
|
202
|
+
adoptReconnectedPreemption(current) {
|
|
203
|
+
this.#preemptiveAlert = { ...current, session_epoch: this.session.sessionEpoch, old_response_id: null };
|
|
204
|
+
}
|
|
205
|
+
rememberLocalSpeechInterruption(key) {
|
|
206
|
+
this.#localSpeechInterruptedResponses.delete(key);
|
|
207
|
+
this.#localSpeechInterruptedResponses.set(key, null);
|
|
208
|
+
while (this.#localSpeechInterruptedResponses.size
|
|
209
|
+
> MAX_TRACKED_SEMANTIC_ACKNOWLEDGEMENTS) {
|
|
210
|
+
const oldest = this.#localSpeechInterruptedResponses.keys().next();
|
|
211
|
+
if (oldest.done)
|
|
212
|
+
break;
|
|
213
|
+
this.#localSpeechInterruptedResponses.delete(oldest.value);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
learnPreemptedResponse(event) {
|
|
217
|
+
const preemption = this.#preemptiveAlert;
|
|
218
|
+
// A turn that was still starting when the alert arrived has only now revealed its id, so the
|
|
219
|
+
// preemption learns which response it is cancelling here rather than at arbitration time.
|
|
220
|
+
if (preemption !== null
|
|
221
|
+
&& preemption.session_epoch === event.session_epoch
|
|
222
|
+
&& preemption.old_response_id === null
|
|
223
|
+
&& this.session.activeProviderResponseId === event.response_id
|
|
224
|
+
&& this.session.providerTurnPhase(event.response_id) === 'cancel_requested'
|
|
225
|
+
&& this.session.providerTurnWasFenced(event.response_id)) {
|
|
226
|
+
this.#preemptiveAlert = { ...preemption, old_response_id: event.response_id };
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
revokePreemptiveReconnect() {
|
|
230
|
+
const preemption = this.#preemptiveAlert;
|
|
231
|
+
if (preemption !== null) {
|
|
232
|
+
// The user speaking is the authority the preemption was borrowing. A permit not yet spent is
|
|
233
|
+
// now disallowed; one already spent means a reconnect is in flight and has to be abandoned.
|
|
234
|
+
this.#preemptiveAlert = {
|
|
235
|
+
...preemption,
|
|
236
|
+
reconnect_disallowed: !preemption.reconnect_permit_consumed,
|
|
237
|
+
reconnect_aborted: preemption.reconnect_permit_consumed,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
finishReconnect(oldEpoch) {
|
|
242
|
+
if (this.#providerReconnectSourceEpoch === oldEpoch) {
|
|
243
|
+
this.#providerEpochNeedingActivation = this.session.sessionEpoch;
|
|
244
|
+
this.#providerReconnectSourceEpoch = null;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
beginReconnect(oldEpoch) {
|
|
248
|
+
this.#preemptiveAlert = null;
|
|
249
|
+
this.#providerReconnectSourceEpoch = oldEpoch;
|
|
250
|
+
}
|
|
251
|
+
resetAcknowledgements() {
|
|
252
|
+
this.#semanticAcknowledgements.clear();
|
|
253
|
+
this.#semanticAcknowledgementReservations = 0;
|
|
254
|
+
this.#localSpeechInterruptedResponses.clear();
|
|
255
|
+
this.#delegateHostEvents.clear();
|
|
256
|
+
this.#providerRetirementEventIds.clear();
|
|
257
|
+
}
|
|
258
|
+
resetDelivery() {
|
|
259
|
+
for (const queued of this.#hostItems)
|
|
260
|
+
void this.#notDelivered(queued);
|
|
261
|
+
this.#hostItems.length = 0;
|
|
262
|
+
this.#hostItemSeq = 0;
|
|
263
|
+
this.#pendingPreemptPriority = null;
|
|
264
|
+
this.#urgentDeliveryToken += 1;
|
|
265
|
+
this.releaseUrgentOwner();
|
|
266
|
+
this.#providerEpochNeedingActivation = null;
|
|
267
|
+
this.#providerReconnectSourceEpoch = null;
|
|
268
|
+
this.#preemptiveAlertToken += 1;
|
|
269
|
+
this.#preemptiveAlertAbort?.abort();
|
|
270
|
+
this.#preemptiveAlertAbort = null;
|
|
271
|
+
this.#preemptiveAlert = null;
|
|
272
|
+
}
|
|
273
|
+
releaseFailedDelivery() {
|
|
274
|
+
this.#urgentHostResponseOwner = null;
|
|
275
|
+
this.#preemptiveAlert = null;
|
|
276
|
+
}
|
|
277
|
+
close() {
|
|
278
|
+
this.#providerEpochNeedingActivation = null;
|
|
279
|
+
this.#providerReconnectSourceEpoch = null;
|
|
280
|
+
this.#urgentHostResponseOwner = null;
|
|
281
|
+
this.#preemptiveAlert = null;
|
|
282
|
+
}
|
|
283
|
+
resumeAfterConversationClear() {
|
|
284
|
+
this.#rendererHostDeliveryPaused = false;
|
|
285
|
+
this.#rendererHostDeliveryBoundary = null;
|
|
286
|
+
}
|
|
287
|
+
pauseForConversationClear() {
|
|
288
|
+
this.#rendererHostDeliveryPaused = true;
|
|
289
|
+
this.#rendererHostDeliveryBoundary = {};
|
|
290
|
+
this.#preemptiveAlertToken += 1;
|
|
291
|
+
this.clearPreemptiveAlert();
|
|
292
|
+
for (const deadline of this.#preemptiveAlertClearDeadlines.values())
|
|
293
|
+
deadline.abort();
|
|
294
|
+
this.#preemptiveAlertClearDeadlines.clear();
|
|
295
|
+
}
|
|
296
|
+
retireCodingProgress() {
|
|
297
|
+
for (const eventId of this.#codingProgressHostEventIds)
|
|
298
|
+
this.retireProviderHostEvent(eventId);
|
|
299
|
+
const retained = this.#hostItems.filter(item => !this.#codingProgressQueued.has(item));
|
|
300
|
+
this.#hostItems.length = 0;
|
|
301
|
+
this.#hostItems.push(...retained.sort(compareQueuedHostResponses));
|
|
302
|
+
this.#codingProgressHostEventIds.clear();
|
|
303
|
+
}
|
|
304
|
+
coalesceCodingProgress() {
|
|
305
|
+
const retained = this.#hostItems.filter(item => !this.#codingProgressQueued.has(item)
|
|
306
|
+
|| this.#codingProgressHostEventIds.has(item.intent.item.event_id));
|
|
307
|
+
this.#hostItems.length = 0;
|
|
308
|
+
this.#hostItems.push(...retained.sort(compareQueuedHostResponses));
|
|
309
|
+
}
|
|
310
|
+
#ports;
|
|
311
|
+
constructor(ports) { this.#ports = ports; }
|
|
312
|
+
get session() { return this.#ports.session; }
|
|
313
|
+
#codingProgressQueued = new WeakSet();
|
|
314
|
+
#codingProgressHostEventIds = new Set();
|
|
315
|
+
/** A binary min-heap ordered by `compareQueuedHostResponses`, matching the oracle's `heapq`. */
|
|
316
|
+
#uncertainQueuedDeliveries = new WeakSet();
|
|
317
|
+
async #notDelivered(queued) { if (!this.#uncertainQueuedDeliveries.has(queued))
|
|
318
|
+
try {
|
|
319
|
+
await queued.onNotDelivered?.();
|
|
320
|
+
}
|
|
321
|
+
catch {
|
|
322
|
+
this.#ports.onDiagnostic('[realtime-diagnostic] hostitem_disposition_failed');
|
|
323
|
+
} }
|
|
324
|
+
#hostItems = [];
|
|
325
|
+
#hostItemSeq = 0;
|
|
326
|
+
#pendingPreemptPriority = null;
|
|
327
|
+
#urgentDeliveryToken = 0;
|
|
328
|
+
#urgentHostResponseOwner = null;
|
|
329
|
+
#providerEpochNeedingActivation = null;
|
|
330
|
+
#providerReconnectSourceEpoch = null;
|
|
331
|
+
#preemptiveAlertToken = 0;
|
|
332
|
+
#preemptiveAlert = null;
|
|
333
|
+
/** The in-flight cancel deadline for the current preemption, if one is armed. */
|
|
334
|
+
#preemptiveAlertAbort = null;
|
|
335
|
+
/** Per-generation waits for the renderer to confirm a clear, keyed `utterance:epoch`. */
|
|
336
|
+
#preemptiveAlertClearDeadlines = new Map();
|
|
337
|
+
#deliveryLock = new Mutex();
|
|
338
|
+
#rendererHostDeliveryPaused = false;
|
|
339
|
+
#rendererHostDeliveryBoundary = null;
|
|
340
|
+
#semanticAcknowledgements = new Map();
|
|
341
|
+
/** Responses whose renderer generation was fenced because the user locally took the floor. */
|
|
342
|
+
#localSpeechInterruptedResponses = new Map();
|
|
343
|
+
/** Provider-visible progress events and their owners, bounded in provider-ledger order. */
|
|
344
|
+
#delegateHostEvents = new Map();
|
|
345
|
+
/** Best-effort provider cleanup is observed so it cannot reject outside service ownership. */
|
|
346
|
+
#providerRetirementTasks = new Set();
|
|
347
|
+
#providerRetirementEventIds = new Set();
|
|
348
|
+
/** Exact standalone delegation acknowledgements superseded by their own terminal handoff. */
|
|
349
|
+
#semanticAcknowledgementReleaseTasks = new Set();
|
|
350
|
+
/**
|
|
351
|
+
* Slots promised to calls admitted but not yet acknowledged.
|
|
352
|
+
*
|
|
353
|
+
* Counted against the same bound as the acknowledgements themselves, so two calls admitted back to
|
|
354
|
+
* back cannot both be promised a slot only one of them can have.
|
|
355
|
+
*/
|
|
356
|
+
#semanticAcknowledgementReservations = 0;
|
|
357
|
+
/**
|
|
358
|
+
* `(epoch, response)` keys whose playback the user demonstrably heard.
|
|
359
|
+
*
|
|
360
|
+
* Proof rather than assumption: an acknowledgement is only suppressed as already-said when there is
|
|
361
|
+
* a record of the turn carrying it having actually been played.
|
|
362
|
+
*/
|
|
363
|
+
#originDeliveryProofs = new Map();
|
|
364
|
+
/** The acknowledgement bound to one provider response, if it is the one being spoken. */
|
|
365
|
+
semanticAcknowledgementFor(responseId) {
|
|
366
|
+
for (const current of this.#semanticAcknowledgements.values()) {
|
|
367
|
+
if (current.phase === 'bound' && current.response_id === responseId)
|
|
368
|
+
return current.event_id;
|
|
369
|
+
}
|
|
370
|
+
return null;
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Queue one host fact for delivery when the floor allows it.
|
|
374
|
+
*
|
|
375
|
+
* The priority is clamped below `USER_PRIORITY`: nothing the host says may outrank the user, and a
|
|
376
|
+
* caller that passes a higher number is expressing urgency rather than claiming precedence over the
|
|
377
|
+
* person in the room.
|
|
378
|
+
*/
|
|
379
|
+
queueHostItem(intent, options = {}) {
|
|
380
|
+
if (this.#ports.clearingConversation()) {
|
|
381
|
+
void options.onNotDelivered?.().catch(() => this.#ports.onDiagnostic('[realtime-diagnostic] hostitem_disposition_failed'));
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
const priority = options.priority ?? 50;
|
|
385
|
+
const preemptive = options.preemptive ?? false;
|
|
386
|
+
const preemptiveAlert = options.preemptiveAlert ?? false;
|
|
387
|
+
const effectivePriority = Math.min(priority, USER_PRIORITY - 1);
|
|
388
|
+
const preemptiveAlertDelegateId = options.preemptiveAlertDelegateId ?? null;
|
|
389
|
+
const preemptiveAlertActivation = preemptiveAlertDelegateId === null
|
|
390
|
+
? null
|
|
391
|
+
: {
|
|
392
|
+
delegate_id: preemptiveAlertDelegateId,
|
|
393
|
+
event_id: intent.item.event_id,
|
|
394
|
+
source_epoch: this.session.sessionEpoch,
|
|
395
|
+
};
|
|
396
|
+
this.#ports.telemetry?.record('hostitem.queued', { event_id: intent.item.event_id });
|
|
397
|
+
this.#hostItemSeq += 1;
|
|
398
|
+
const queued = {
|
|
399
|
+
...(options.stillWanted ? { stillWanted: options.stillWanted } : {}),
|
|
400
|
+
...(options.onNotDelivered ? { onNotDelivered: options.onNotDelivered } : {}),
|
|
401
|
+
sortKey: [-effectivePriority, preemptive ? -1 : 0, this.#hostItemSeq],
|
|
402
|
+
intent,
|
|
403
|
+
priority: effectivePriority,
|
|
404
|
+
preemptive,
|
|
405
|
+
preemptive_alert: preemptiveAlert,
|
|
406
|
+
seq: this.#hostItemSeq,
|
|
407
|
+
queued_at: this.#ports.clock.now(),
|
|
408
|
+
semantic_event_id: options.semanticEventId ?? null,
|
|
409
|
+
preemptive_alert_activation: preemptiveAlertActivation,
|
|
410
|
+
owner: options.owner ?? null,
|
|
411
|
+
expires_at: options.expiresAt ?? null,
|
|
412
|
+
};
|
|
413
|
+
if (this.#codingProgressHostEventIds.has(intent.item.event_id))
|
|
414
|
+
this.#codingProgressQueued.add(queued);
|
|
415
|
+
heapPush(this.#hostItems, queued);
|
|
416
|
+
if (preemptive)
|
|
417
|
+
this.#armPreempt(effectivePriority);
|
|
418
|
+
this.#ports.wake();
|
|
419
|
+
}
|
|
420
|
+
requeueHostItem(queued) {
|
|
421
|
+
this.#ports.telemetry?.record('hostitem.queued', { event_id: queued.intent.item.event_id });
|
|
422
|
+
heapPush(this.#hostItems, queued);
|
|
423
|
+
if (queued.preemptive)
|
|
424
|
+
this.#armPreempt(queued.priority);
|
|
425
|
+
this.#ports.wake();
|
|
426
|
+
}
|
|
427
|
+
#armPreempt(priority) {
|
|
428
|
+
const pending = this.#pendingPreemptPriority;
|
|
429
|
+
this.#pendingPreemptPriority = pending === null ? priority : Math.max(priority, pending);
|
|
430
|
+
}
|
|
431
|
+
/** Recompute the armed preempt priority from what is actually still queued. */
|
|
432
|
+
#recomputePreemptPriority() {
|
|
433
|
+
const priorities = this.#hostItems
|
|
434
|
+
.filter(candidate => candidate.preemptive)
|
|
435
|
+
.map(candidate => candidate.priority);
|
|
436
|
+
this.#pendingPreemptPriority = priorities.length === 0 ? null : Math.max(...priorities);
|
|
437
|
+
}
|
|
438
|
+
/** Generic urgent items need the legacy priority band; monitor alerts carry explicit policy authority. */
|
|
439
|
+
#preemptEligible(queued) {
|
|
440
|
+
return queued.preemptive && (queued.preemptive_alert || queued.priority >= PREEMPT_MIN_PRIORITY);
|
|
441
|
+
}
|
|
442
|
+
hasEligiblePreempt() {
|
|
443
|
+
return this.#hostItems.some(queued => this.#preemptEligible(queued));
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Arbitrate a preemptive host item against whatever the agent is saying.
|
|
447
|
+
*
|
|
448
|
+
* Every early return here is a reason *not* to interrupt, and they are checked before any preemptive alert
|
|
449
|
+
* state is touched so the ordinary path never reaches the unported arbitration.
|
|
450
|
+
*/
|
|
451
|
+
async #maybePreemptLocked() {
|
|
452
|
+
if (!this.hasEligiblePreempt())
|
|
453
|
+
return;
|
|
454
|
+
if (this.session.floor.state === 'user_speaking')
|
|
455
|
+
return;
|
|
456
|
+
if (this.session.foregroundIdle)
|
|
457
|
+
return;
|
|
458
|
+
if (this.#urgentHostResponseOwner !== null)
|
|
459
|
+
return;
|
|
460
|
+
if (this.#preemptiveAlert !== null)
|
|
461
|
+
return;
|
|
462
|
+
const queued = this.#hostItems
|
|
463
|
+
.filter(candidate => this.#preemptEligible(candidate))
|
|
464
|
+
.sort(compareQueuedHostResponses)
|
|
465
|
+
.at(0);
|
|
466
|
+
if (queued === undefined)
|
|
467
|
+
return;
|
|
468
|
+
this.#preemptiveAlertToken += 1;
|
|
469
|
+
const preemption = {
|
|
470
|
+
token: this.#preemptiveAlertToken,
|
|
471
|
+
session_epoch: this.session.sessionEpoch,
|
|
472
|
+
event_id: queued.intent.item.event_id,
|
|
473
|
+
old_response_id: this.session.activeProviderResponseId,
|
|
474
|
+
old_generation: this.session.currentGeneration,
|
|
475
|
+
queued_at: queued.queued_at,
|
|
476
|
+
cancel_sent: false,
|
|
477
|
+
deadline_fired: false,
|
|
478
|
+
replacement_terminal: false,
|
|
479
|
+
reconnect_permit_consumed: false,
|
|
480
|
+
reconnect_disallowed: false,
|
|
481
|
+
reconnect_aborted: false,
|
|
482
|
+
};
|
|
483
|
+
this.#preemptiveAlert = preemption;
|
|
484
|
+
// Armed before the await: the provider may never confirm the cancel, and the deadline is what
|
|
485
|
+
// stops the alert waiting behind a turn that will not stop.
|
|
486
|
+
const abort = new AbortController();
|
|
487
|
+
this.#preemptiveAlertAbort = abort;
|
|
488
|
+
void this.#firePreemptiveAlertDeadline(preemption);
|
|
489
|
+
this.#ports.telemetry?.record('guard.preempt_started', {});
|
|
490
|
+
let preempted;
|
|
491
|
+
try {
|
|
492
|
+
preempted = await this.session.hostPreempt();
|
|
493
|
+
}
|
|
494
|
+
catch (cause) {
|
|
495
|
+
// The preemption never happened, so its deadline must not fire against a session that is still
|
|
496
|
+
// speaking normally.
|
|
497
|
+
this.clearPreemptiveAlert(preemption.token);
|
|
498
|
+
throw cause;
|
|
499
|
+
}
|
|
500
|
+
if (!preempted) {
|
|
501
|
+
this.clearPreemptiveAlert(preemption.token);
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
// The session may have learned the response id only while preempting -- a turn that was still
|
|
505
|
+
// starting when the alert arrived.
|
|
506
|
+
const responseId = this.session.activeProviderResponseId;
|
|
507
|
+
const current = this.#preemptiveAlert;
|
|
508
|
+
if (responseId !== null
|
|
509
|
+
&& current !== null
|
|
510
|
+
&& current.token === preemption.token
|
|
511
|
+
&& this.session.providerTurnPhase(responseId) === 'cancel_requested') {
|
|
512
|
+
if (current.old_response_id === null) {
|
|
513
|
+
this.#preemptiveAlert = { ...current, old_response_id: responseId };
|
|
514
|
+
}
|
|
515
|
+
this.recordPreemptiveAlertCancelSent(responseId);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Deliver from the head of the queue while the floor allows it.
|
|
520
|
+
*
|
|
521
|
+
* Stops at the first item that cannot go now rather than scanning past it: the heap order *is* the
|
|
522
|
+
* delivery order, and skipping a blocked head to deliver a lower-priority item behind it would
|
|
523
|
+
* reorder what the user hears.
|
|
524
|
+
*/
|
|
525
|
+
async #flushHostItemsLocked() {
|
|
526
|
+
while (this.#hostItems.length > 0) {
|
|
527
|
+
const queued = this.#hostItems[0];
|
|
528
|
+
if (this.#executorApprovalBlocksSemanticAcknowledgement(queued))
|
|
529
|
+
break;
|
|
530
|
+
if (!this.#queuedHostItemEligible(queued)) {
|
|
531
|
+
heapPop(this.#hostItems);
|
|
532
|
+
await this.#notDelivered(queued);
|
|
533
|
+
if (queued.preemptive)
|
|
534
|
+
this.#recomputePreemptPriority();
|
|
535
|
+
continue;
|
|
536
|
+
}
|
|
537
|
+
const preemptiveOverlap = this.#preemptiveAlertOverlapAllowed(queued);
|
|
538
|
+
const ordinaryDelivery = this.session.foregroundIdle && this.session.floor.state === 'idle';
|
|
539
|
+
if (!preemptiveOverlap && !ordinaryDelivery)
|
|
540
|
+
break;
|
|
541
|
+
heapPop(this.#hostItems);
|
|
542
|
+
const userActivation = this.#preemptiveAlertActivationRequired(queued);
|
|
543
|
+
let eligibilityRevoked = false;
|
|
544
|
+
const responseAllowed = () => {
|
|
545
|
+
const eligible = this.#queuedHostItemEligible(queued);
|
|
546
|
+
if (!eligible)
|
|
547
|
+
eligibilityRevoked = true;
|
|
548
|
+
return eligible;
|
|
549
|
+
};
|
|
550
|
+
let delivery;
|
|
551
|
+
try {
|
|
552
|
+
if (userActivation) {
|
|
553
|
+
// A reconnected session will not speak until something user-shaped arrives, so a preemptive-alert fact
|
|
554
|
+
// crossing a reconnect has to carry that activation or it lands in a session that never
|
|
555
|
+
// responds.
|
|
556
|
+
delivery = await this.session.deliverHostResponse(queued.intent, {
|
|
557
|
+
responseAllowed,
|
|
558
|
+
asUserActivation: true,
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
else if (preemptiveOverlap) {
|
|
562
|
+
const preemption = this.#preemptiveAlert;
|
|
563
|
+
// Only a permit-consuming preemption gets a confirmation timeout: it is speaking into a
|
|
564
|
+
// session created for it, where waiting indefinitely would strand the alert.
|
|
565
|
+
const confirmationTimeout = preemption !== null
|
|
566
|
+
&& preemption.reconnect_permit_consumed
|
|
567
|
+
&& preemption.event_id === queued.intent.item.event_id
|
|
568
|
+
? 0.5
|
|
569
|
+
: null;
|
|
570
|
+
delivery = confirmationTimeout === null
|
|
571
|
+
? await this.session.deliverPreemptiveHostResponse(queued.intent, { responseAllowed })
|
|
572
|
+
: await this.session.deliverPreemptiveHostResponse(queued.intent, {
|
|
573
|
+
confirmationTimeout,
|
|
574
|
+
responseAllowed,
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
else {
|
|
578
|
+
delivery = await this.session.deliverHostResponse(queued.intent, { responseAllowed });
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
catch (cause) {
|
|
582
|
+
// Preserve the item after transport failure; a response may already have been requested.
|
|
583
|
+
// Later queue invalidation must not claim this uncertain delivery was never sent.
|
|
584
|
+
this.#uncertainQueuedDeliveries.add(queued);
|
|
585
|
+
if (!['task_continuation', 'scheduled_task'].includes(queued.intent.kind) || !(cause instanceof ResponseRequestUncertainError))
|
|
586
|
+
heapPush(this.#hostItems, queued);
|
|
587
|
+
else if (queued.preemptive)
|
|
588
|
+
this.#recomputePreemptPriority();
|
|
589
|
+
throw cause;
|
|
590
|
+
}
|
|
591
|
+
const delivered = delivery.accepted;
|
|
592
|
+
if (!delivered
|
|
593
|
+
&& eligibilityRevoked
|
|
594
|
+
&& delivery.injectionEpoch === this.session.sessionEpoch) {
|
|
595
|
+
await this.retireProviderHostEventNow(queued.intent.item.event_id);
|
|
596
|
+
await this.#notDelivered(queued);
|
|
597
|
+
}
|
|
598
|
+
if (delivered && userActivation) {
|
|
599
|
+
this.#providerEpochNeedingActivation = null;
|
|
600
|
+
this.#providerReconnectSourceEpoch = null;
|
|
601
|
+
}
|
|
602
|
+
if (queued.preemptive)
|
|
603
|
+
this.#recomputePreemptPriority();
|
|
604
|
+
if (delivered
|
|
605
|
+
&& queued.preemptive
|
|
606
|
+
&& !this.#ports.stopped()
|
|
607
|
+
&& !this.#ports.providerFailed()
|
|
608
|
+
&& delivery.injectionEpoch === this.session.sessionEpoch) {
|
|
609
|
+
// The owner is what makes the alert's audio attributable until it is played or cleared.
|
|
610
|
+
this.#urgentDeliveryToken += 1;
|
|
611
|
+
this.#urgentHostResponseOwner = {
|
|
612
|
+
delivery_token: this.#urgentDeliveryToken,
|
|
613
|
+
session_epoch: delivery.injectionEpoch,
|
|
614
|
+
event_id: queued.intent.item.event_id,
|
|
615
|
+
queued,
|
|
616
|
+
response_id: null,
|
|
617
|
+
generation: null,
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
if (delivered && queued.semantic_event_id !== null) {
|
|
621
|
+
const acknowledgement = this.#semanticAcknowledgements.get(queued.semantic_event_id);
|
|
622
|
+
if (acknowledgement?.phase === 'queued')
|
|
623
|
+
acknowledgement.phase = 'requested';
|
|
624
|
+
}
|
|
625
|
+
if (delivered) {
|
|
626
|
+
this.#ports.telemetry?.record('hostitem.injected', { event_id: queued.intent.item.event_id });
|
|
627
|
+
// One delivery per pass: the floor state this loop tested is now stale, and the next pass
|
|
628
|
+
// re-reads it rather than assuming the item just injected left the floor unchanged.
|
|
629
|
+
break;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
/** Revalidate lifecycle eligibility at the final provider boundary. */
|
|
634
|
+
#queuedHostItemEligible(queued) {
|
|
635
|
+
if (queued.stillWanted && !queued.stillWanted())
|
|
636
|
+
return false;
|
|
637
|
+
const eventId = queued.intent.item.event_id;
|
|
638
|
+
if (this.#codingProgressQueued.has(queued) && !this.#codingProgressHostEventIds.has(eventId))
|
|
639
|
+
return false;
|
|
640
|
+
if (eventId.startsWith('intake:') && this.#ports.intakeFactEligible(eventId, this.session.sessionEpoch) !== true)
|
|
641
|
+
return false;
|
|
642
|
+
if (eventId.startsWith('approval:') && !this.#ports.approvalHost.factEligible(eventId))
|
|
643
|
+
return false;
|
|
644
|
+
if (queued.semantic_event_id !== null) {
|
|
645
|
+
const acknowledgement = this.#semanticAcknowledgements.get(queued.semantic_event_id);
|
|
646
|
+
if (acknowledgement?.phase === 'cancelled'
|
|
647
|
+
|| acknowledgement?.phase === 'delivered')
|
|
648
|
+
return false;
|
|
649
|
+
}
|
|
650
|
+
if (queued.owner !== null) {
|
|
651
|
+
const state = this.session.delegateState(queued.owner.delegate_id);
|
|
652
|
+
if (state !== undefined && state !== 'running')
|
|
653
|
+
return false;
|
|
654
|
+
}
|
|
655
|
+
return queued.expires_at === null || this.#ports.clock.now() < queued.expires_at;
|
|
656
|
+
}
|
|
657
|
+
/** A pending permission question owns the foreground ahead of any generic startup receipt. */
|
|
658
|
+
#executorApprovalBlocksSemanticAcknowledgement(queued) {
|
|
659
|
+
return this.#ports.approvalHost.blocksSemanticAcknowledgement(queued.semantic_event_id);
|
|
660
|
+
}
|
|
661
|
+
/** Whether this queued item is the captured preemptive alert the current handoff is waiting to deliver. */
|
|
662
|
+
#preemptiveAlertOverlapAllowed(queued) {
|
|
663
|
+
const preemption = this.#preemptiveAlert;
|
|
664
|
+
return preemption !== null
|
|
665
|
+
&& queued.preemptive
|
|
666
|
+
&& queued.intent.item.event_id === preemption.event_id
|
|
667
|
+
&& preemption.session_epoch === this.session.sessionEpoch
|
|
668
|
+
&& this.session.providerIdle
|
|
669
|
+
&& this.session.floor.state !== 'user_speaking';
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Whether this item has to be injected as a user activation.
|
|
673
|
+
*
|
|
674
|
+
* A reconnected provider session will not speak until something user-shaped arrives, so a preemptive alert
|
|
675
|
+
* fact that crosses a reconnect has to carry that activation or it is delivered into a session
|
|
676
|
+
* that never responds.
|
|
677
|
+
*/
|
|
678
|
+
#preemptiveAlertActivationRequired(queued) {
|
|
679
|
+
const authority = queued.preemptive_alert_activation;
|
|
680
|
+
if (authority?.event_id !== queued.intent.item.event_id)
|
|
681
|
+
return false;
|
|
682
|
+
const authorized = queued.intent.item.event_id === `final:${authority.delegate_id}`
|
|
683
|
+
|| queued.intent.item.event_id.startsWith(`observation:${authority.delegate_id}:`);
|
|
684
|
+
if (!authorized)
|
|
685
|
+
return false;
|
|
686
|
+
return this.#providerEpochNeedingActivation === this.session.sessionEpoch
|
|
687
|
+
|| (this.#providerReconnectSourceEpoch !== null
|
|
688
|
+
&& this.#providerReconnectSourceEpoch !== this.session.sessionEpoch);
|
|
689
|
+
}
|
|
690
|
+
/** Queue one acknowledgement as a host fact, unless it is already queued or already said. */
|
|
691
|
+
#queueSemanticAcknowledgement(acknowledgement) {
|
|
692
|
+
if (acknowledgement.phase === 'requested'
|
|
693
|
+
|| acknowledgement.phase === 'bound'
|
|
694
|
+
|| acknowledgement.phase === 'delivered'
|
|
695
|
+
|| acknowledgement.phase === 'cancelled') {
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
if (this.#hostItems.some(queued => queued.semantic_event_id === acknowledgement.event_id)) {
|
|
699
|
+
// Already waiting its turn. Marked queued rather than queued again, so the user hears it once.
|
|
700
|
+
acknowledgement.phase = 'queued';
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
const priority = this.#ports.executorPriority(acknowledgement.channel);
|
|
704
|
+
acknowledgement.provider_event_id = acknowledgement.event_id;
|
|
705
|
+
this.queueHostItem({
|
|
706
|
+
kind: 'host_fact',
|
|
707
|
+
item: {
|
|
708
|
+
kind: 'progress',
|
|
709
|
+
host_item_id: this.#ports.idFactory(),
|
|
710
|
+
event_id: acknowledgement.event_id,
|
|
711
|
+
content: `${this.#ports.executorDisplayName(acknowledgement.channel)} 已提交,正在启动:${acknowledgement.summary}`,
|
|
712
|
+
call_id: null,
|
|
713
|
+
},
|
|
714
|
+
task_summary: null,
|
|
715
|
+
origin_spoken: false,
|
|
716
|
+
}, { semanticEventId: acknowledgement.event_id, priority });
|
|
717
|
+
acknowledgement.phase = 'queued';
|
|
718
|
+
}
|
|
719
|
+
/**
|
|
720
|
+
* Settle the acknowledgements the response that just ended was carrying.
|
|
721
|
+
*
|
|
722
|
+
* Provider completion is not audible delivery. A completed turn with a live renderer generation
|
|
723
|
+
* stays bound until playback reports what happened; one with no playable audio becomes a fallback.
|
|
724
|
+
* A failed fallback gets one bounded retry, while a failed continuation returns to its batch.
|
|
725
|
+
*
|
|
726
|
+
* An origin already proven delivered is delivered regardless of the status: the user heard it, and a
|
|
727
|
+
* retry would be the second telling.
|
|
728
|
+
*/
|
|
729
|
+
finishSemanticAcknowledgement(event) {
|
|
730
|
+
const bound = [...this.#semanticAcknowledgements.values()]
|
|
731
|
+
.filter(current => (current.phase === 'bound'
|
|
732
|
+
&& current.response_session_epoch === event.session_epoch
|
|
733
|
+
&& current.response_id === event.response_id));
|
|
734
|
+
for (const acknowledgement of bound) {
|
|
735
|
+
if (acknowledgement.origin_delivered || acknowledgement.heard) {
|
|
736
|
+
this.#markAcknowledgementDelivered(acknowledgement);
|
|
737
|
+
continue;
|
|
738
|
+
}
|
|
739
|
+
if (event.status === 'completed') {
|
|
740
|
+
const generation = this.session.currentGeneration;
|
|
741
|
+
if (generation?.session_epoch === event.session_epoch
|
|
742
|
+
&& generation.response_id === event.response_id)
|
|
743
|
+
continue;
|
|
744
|
+
// Only a standalone fallback owns its semantic event as a provider fact. Continuations leave
|
|
745
|
+
// `provider_event_id` null in `#bindContinuation`, so this equality is the explicit ownership
|
|
746
|
+
// boundary: preserve the injected fact, but return its response authority for another turn.
|
|
747
|
+
if (acknowledgement.provider_event_id === acknowledgement.event_id
|
|
748
|
+
&& !this.session.reopenHostResponse(acknowledgement.event_id)) {
|
|
749
|
+
this.#ports.onDiagnostic('[realtime-diagnostic] semantic_ack_reopen_failed');
|
|
750
|
+
continue;
|
|
751
|
+
}
|
|
752
|
+
acknowledgement.phase = 'pending';
|
|
753
|
+
acknowledgement.response_id = null;
|
|
754
|
+
acknowledgement.response_session_epoch = null;
|
|
755
|
+
acknowledgement.binding = null;
|
|
756
|
+
this.#queueSemanticAcknowledgement(acknowledgement);
|
|
757
|
+
}
|
|
758
|
+
else if (acknowledgement.binding === 'fallback') {
|
|
759
|
+
acknowledgement.phase = 'pending';
|
|
760
|
+
acknowledgement.response_id = null;
|
|
761
|
+
acknowledgement.response_session_epoch = null;
|
|
762
|
+
acknowledgement.binding = null;
|
|
763
|
+
if (event.status === 'failed') {
|
|
764
|
+
// One retry after a failure, and only one: a provider failing the same fact repeatedly would
|
|
765
|
+
// otherwise have the host queue it forever.
|
|
766
|
+
if (acknowledgement.failed_retry_consumed)
|
|
767
|
+
continue;
|
|
768
|
+
acknowledgement.failed_retry_consumed = true;
|
|
769
|
+
}
|
|
770
|
+
this.#queueSemanticAcknowledgement(acknowledgement);
|
|
771
|
+
}
|
|
772
|
+
else if (acknowledgement.binding === 'continuation') {
|
|
773
|
+
acknowledgement.phase = 'pending';
|
|
774
|
+
acknowledgement.response_id = null;
|
|
775
|
+
acknowledgement.response_session_epoch = null;
|
|
776
|
+
acknowledgement.binding = null;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
#markAcknowledgementDelivered(acknowledgement) {
|
|
781
|
+
acknowledgement.phase = 'delivered';
|
|
782
|
+
acknowledgement.response_id = null;
|
|
783
|
+
acknowledgement.response_session_epoch = null;
|
|
784
|
+
acknowledgement.binding = null;
|
|
785
|
+
}
|
|
786
|
+
/** Bind the one acknowledgement that asked for a turn to the response that will speak it. */
|
|
787
|
+
bindRequestedSemanticAcknowledgement(responseId) {
|
|
788
|
+
for (const acknowledgement of this.#semanticAcknowledgements.values()) {
|
|
789
|
+
if (acknowledgement.phase !== 'requested')
|
|
790
|
+
continue;
|
|
791
|
+
acknowledgement.phase = 'bound';
|
|
792
|
+
acknowledgement.response_id = responseId;
|
|
793
|
+
acknowledgement.response_session_epoch = this.session.sessionEpoch;
|
|
794
|
+
acknowledgement.provider_event_id = acknowledgement.event_id;
|
|
795
|
+
acknowledgement.binding = 'fallback';
|
|
796
|
+
return;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
suppressCancelledSemanticAcknowledgement(responseId) {
|
|
800
|
+
const eventIds = this.session.responseEventIds(responseId);
|
|
801
|
+
const acknowledgement = [...this.#semanticAcknowledgements.values()].find(current => (current.phase === 'cancelled' && eventIds.includes(current.event_id)));
|
|
802
|
+
return acknowledgement !== undefined && this.session.suppressResponse(responseId);
|
|
803
|
+
}
|
|
804
|
+
fenceSemanticAcknowledgement(delegateId) {
|
|
805
|
+
const acknowledgement = this.#semanticAcknowledgements.get(`background:${delegateId}`);
|
|
806
|
+
if (acknowledgement === undefined
|
|
807
|
+
|| acknowledgement.phase === 'delivered'
|
|
808
|
+
|| acknowledgement.phase === 'cancelled')
|
|
809
|
+
return false;
|
|
810
|
+
if (acknowledgement.origin_delivered
|
|
811
|
+
|| acknowledgement.heard
|
|
812
|
+
|| this.session.eventWasSpoken(acknowledgement.event_id)) {
|
|
813
|
+
if (acknowledgement.phase === 'bound'
|
|
814
|
+
&& acknowledgement.binding === 'fallback'
|
|
815
|
+
&& acknowledgement.response_id !== null
|
|
816
|
+
&& acknowledgement.response_session_epoch === this.session.sessionEpoch) {
|
|
817
|
+
this.#cancelSemanticAcknowledgementResponse(acknowledgement.response_session_epoch, acknowledgement.response_id);
|
|
818
|
+
}
|
|
819
|
+
this.#markAcknowledgementDelivered(acknowledgement);
|
|
820
|
+
this.#retireSemanticAcknowledgementHostEvent(acknowledgement);
|
|
821
|
+
return false;
|
|
822
|
+
}
|
|
823
|
+
if (acknowledgement.phase === 'bound') {
|
|
824
|
+
const responseId = acknowledgement.response_id;
|
|
825
|
+
if (responseId === null)
|
|
826
|
+
return false;
|
|
827
|
+
if (!this.session.suppressResponse(responseId)) {
|
|
828
|
+
if (acknowledgement.binding !== 'fallback'
|
|
829
|
+
|| acknowledgement.response_session_epoch !== this.session.sessionEpoch)
|
|
830
|
+
return false;
|
|
831
|
+
this.#cancelSemanticAcknowledgementResponse(acknowledgement.response_session_epoch, responseId);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
const retained = this.#hostItems.filter(queued => (queued.semantic_event_id !== acknowledgement.event_id));
|
|
835
|
+
if (retained.length !== this.#hostItems.length) {
|
|
836
|
+
retained.sort(compareQueuedHostResponses);
|
|
837
|
+
this.#hostItems.length = 0;
|
|
838
|
+
this.#hostItems.push(...retained);
|
|
839
|
+
}
|
|
840
|
+
acknowledgement.phase = 'cancelled';
|
|
841
|
+
acknowledgement.response_id = null;
|
|
842
|
+
acknowledgement.response_session_epoch = null;
|
|
843
|
+
acknowledgement.binding = null;
|
|
844
|
+
this.#retireSemanticAcknowledgementHostEvent(acknowledgement);
|
|
845
|
+
return true;
|
|
846
|
+
}
|
|
847
|
+
/** Cancel only the standalone acknowledgement that its own terminal handoff made obsolete. */
|
|
848
|
+
#cancelSemanticAcknowledgementResponse(sessionEpoch, responseId) {
|
|
849
|
+
const cancellation = (async () => {
|
|
850
|
+
if (sessionEpoch !== this.session.sessionEpoch)
|
|
851
|
+
return;
|
|
852
|
+
try {
|
|
853
|
+
await this.session.quarantineResponse(responseId);
|
|
854
|
+
}
|
|
855
|
+
catch (failure) {
|
|
856
|
+
this.#ports.reportDeliveryFailure(failure instanceof RealtimeDeliveryError
|
|
857
|
+
? failure
|
|
858
|
+
: new RealtimeDeliveryError(String(failure)));
|
|
859
|
+
}
|
|
860
|
+
finally {
|
|
861
|
+
this.#ports.wake();
|
|
862
|
+
}
|
|
863
|
+
})();
|
|
864
|
+
const task = cancellation.finally(() => {
|
|
865
|
+
this.#semanticAcknowledgementReleaseTasks.delete(task);
|
|
866
|
+
});
|
|
867
|
+
this.#semanticAcknowledgementReleaseTasks.add(task);
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* Re-queue acknowledgements whose turn died with the old session.
|
|
871
|
+
*
|
|
872
|
+
* One that was requested or bound to any response was never proven audible -- the turn carrying it
|
|
873
|
+
* belonged to a provider session that is gone -- so it goes back to pending and is queued again.
|
|
874
|
+
* Only an acknowledgement carrying renderer-backed `heard` proof stays delivered.
|
|
875
|
+
*/
|
|
876
|
+
reconcileSemanticAcknowledgementsAfterReconnect() {
|
|
877
|
+
for (const acknowledgement of this.#semanticAcknowledgements.values()) {
|
|
878
|
+
if (acknowledgement.heard) {
|
|
879
|
+
this.#markAcknowledgementDelivered(acknowledgement);
|
|
880
|
+
continue;
|
|
881
|
+
}
|
|
882
|
+
if (acknowledgement.phase === 'requested'
|
|
883
|
+
|| acknowledgement.phase === 'bound') {
|
|
884
|
+
if (acknowledgement.provider_event_id !== null) {
|
|
885
|
+
this.session.reopenHostEvent(acknowledgement.provider_event_id);
|
|
886
|
+
}
|
|
887
|
+
acknowledgement.phase = 'pending';
|
|
888
|
+
acknowledgement.response_id = null;
|
|
889
|
+
acknowledgement.response_session_epoch = null;
|
|
890
|
+
acknowledgement.binding = null;
|
|
891
|
+
}
|
|
892
|
+
if (acknowledgement.phase === 'pending' || acknowledgement.phase === 'queued') {
|
|
893
|
+
this.#queueSemanticAcknowledgement(acknowledgement);
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
/**
|
|
898
|
+
* Give a once-failed acknowledgement another chance after a reconnect.
|
|
899
|
+
*
|
|
900
|
+
* Its single retry was spent on a session that then died, which is not the same as having been tried
|
|
901
|
+
* and refused -- so the new session gets to attempt it once.
|
|
902
|
+
*/
|
|
903
|
+
reopenFailedSemanticAcknowledgements() {
|
|
904
|
+
for (const acknowledgement of this.#semanticAcknowledgements.values()) {
|
|
905
|
+
if (!acknowledgement.failed_retry_consumed)
|
|
906
|
+
continue;
|
|
907
|
+
if (acknowledgement.phase === 'pending') {
|
|
908
|
+
this.#queueSemanticAcknowledgement(acknowledgement);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
rememberCodingProgressHostEvent(eventId) {
|
|
913
|
+
this.#codingProgressHostEventIds.add(eventId);
|
|
914
|
+
while (this.#codingProgressHostEventIds.size > MAX_PENDING_HOST_EVENTS) {
|
|
915
|
+
this.#codingProgressHostEventIds.delete(this.#codingProgressHostEventIds.values().next().value);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
919
|
+
* The acknowledgement for one delegated call, creating it if the ledger has room.
|
|
920
|
+
*
|
|
921
|
+
* Returns null rather than evicting something live: an acknowledgement still waiting to be spoken
|
|
922
|
+
* is a promise to the user, and dropping one to make room for another would silently break it. Only
|
|
923
|
+
* terminal entries (delivered, or cancelled before speech) are reclaimed.
|
|
924
|
+
*/
|
|
925
|
+
#ensureSemanticAcknowledgement(state) {
|
|
926
|
+
const summary = state.acceptance.response_intent.task_summary;
|
|
927
|
+
const delegateId = state.acceptance.delegate_id;
|
|
928
|
+
if (delegateId === null || summary === null)
|
|
929
|
+
return null;
|
|
930
|
+
const eventId = `background:${delegateId}`;
|
|
931
|
+
const existing = this.#semanticAcknowledgements.get(eventId);
|
|
932
|
+
if (existing !== undefined) {
|
|
933
|
+
this.#semanticAcknowledgements.delete(eventId);
|
|
934
|
+
this.#semanticAcknowledgements.set(eventId, existing);
|
|
935
|
+
return existing;
|
|
936
|
+
}
|
|
937
|
+
while (this.#semanticAcknowledgements.size >= MAX_TRACKED_SEMANTIC_ACKNOWLEDGEMENTS) {
|
|
938
|
+
const deliveredId = [...this.#semanticAcknowledgements.entries()]
|
|
939
|
+
.find(([, current]) => (current.phase === 'delivered' || current.phase === 'cancelled'))?.[0];
|
|
940
|
+
if (deliveredId === undefined)
|
|
941
|
+
return null;
|
|
942
|
+
this.#semanticAcknowledgements.delete(deliveredId);
|
|
943
|
+
}
|
|
944
|
+
const channel = state.acceptance.executor;
|
|
945
|
+
if (channel === null)
|
|
946
|
+
return null;
|
|
947
|
+
const created = semanticAcknowledgement({
|
|
948
|
+
event_id: eventId,
|
|
949
|
+
delegate_id: delegateId,
|
|
950
|
+
summary: [...summary].slice(0, MAX_CONTINUATION_TASK_SUMMARY).join(''),
|
|
951
|
+
channel,
|
|
952
|
+
});
|
|
953
|
+
created.origin_session_epoch = state.provider_session_epoch;
|
|
954
|
+
created.origin_response_id = state.provider_response_id;
|
|
955
|
+
created.origin_user_input_revision = state.origin_user_input_revision;
|
|
956
|
+
this.#semanticAcknowledgements.set(eventId, created);
|
|
957
|
+
return created;
|
|
958
|
+
}
|
|
959
|
+
/**
|
|
960
|
+
* Hold a slot before admitting a call that will need one.
|
|
961
|
+
*
|
|
962
|
+
* The reservation counts against the same bound as the acknowledgements themselves, so two calls
|
|
963
|
+
* admitted back to back cannot both be promised a slot only one of them can have.
|
|
964
|
+
*/
|
|
965
|
+
reserveSemanticAcknowledgement() {
|
|
966
|
+
while (this.#semanticAcknowledgements.size + this.#semanticAcknowledgementReservations
|
|
967
|
+
>= MAX_TRACKED_SEMANTIC_ACKNOWLEDGEMENTS) {
|
|
968
|
+
const deliveredId = [...this.#semanticAcknowledgements.entries()]
|
|
969
|
+
.find(([, current]) => (current.phase === 'delivered' || current.phase === 'cancelled'))?.[0];
|
|
970
|
+
if (deliveredId === undefined)
|
|
971
|
+
return false;
|
|
972
|
+
this.#semanticAcknowledgements.delete(deliveredId);
|
|
973
|
+
}
|
|
974
|
+
this.#semanticAcknowledgementReservations += 1;
|
|
975
|
+
return true;
|
|
976
|
+
}
|
|
977
|
+
// ---------------------------------------------------------------------------------------------
|
|
978
|
+
// Approval transport: queue delivery and exact audible-response fencing.
|
|
979
|
+
/** Remove only the undelivered local queue entry; provider context has its own lifecycle. */
|
|
980
|
+
removeQueuedExecutorApprovalPrompt(approvalId) {
|
|
981
|
+
const prefix = `approval:${approvalId}:`;
|
|
982
|
+
const retained = this.#hostItems.filter(queued => (!queued.intent.item.event_id.startsWith(prefix)));
|
|
983
|
+
if (retained.length !== this.#hostItems.length) {
|
|
984
|
+
retained.sort(compareQueuedHostResponses);
|
|
985
|
+
this.#hostItems.length = 0;
|
|
986
|
+
this.#hostItems.push(...retained);
|
|
987
|
+
this.#recomputePreemptPriority();
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
/** Stop/fence only the exact spoken question response while preserving its provider host fact. */
|
|
991
|
+
releaseExecutorApprovalQuestion(approvalId) {
|
|
992
|
+
const prefix = `approval:${approvalId}:`;
|
|
993
|
+
const owner = this.#urgentHostResponseOwner;
|
|
994
|
+
if (owner?.event_id.startsWith(prefix) === true) {
|
|
995
|
+
if (owner.response_id === null) {
|
|
996
|
+
this.#ports.approvalHost.setResponseFencePending(this.session.armPendingResponseFence());
|
|
997
|
+
}
|
|
998
|
+
else {
|
|
999
|
+
this.session.suppressResponse(owner.response_id);
|
|
1000
|
+
this.#ports.approvalHost.cancelExecutorApprovalPromptResponse(owner.session_epoch, owner.response_id);
|
|
1001
|
+
}
|
|
1002
|
+
this.releaseUrgentHostResponse(owner);
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* The renderer finished playing a generation.
|
|
1007
|
+
*
|
|
1008
|
+
* The event ids are captured *before* completing, because completion is what clears the generation --
|
|
1009
|
+
* and the suggestion confirmations below need to know what it was carrying.
|
|
1010
|
+
*/
|
|
1011
|
+
playbackDone(utteranceId, generationEpoch, playedMs) {
|
|
1012
|
+
const generation = this.session.currentGeneration;
|
|
1013
|
+
const urgentOwner = this.#urgentOwnerForGeneration(utteranceId, generationEpoch);
|
|
1014
|
+
const eventIds = generation === null
|
|
1015
|
+
? []
|
|
1016
|
+
: this.session.responseEventIds(generation.response_id);
|
|
1017
|
+
const completion = this.session.completePlayback(utteranceId, generationEpoch, playedMs);
|
|
1018
|
+
if (completion === null)
|
|
1019
|
+
return false;
|
|
1020
|
+
this.#localSpeechInterruptedResponses.delete(callKey(completion.session_epoch, completion.response_id));
|
|
1021
|
+
this.#recordOriginDeliveryProof(completion);
|
|
1022
|
+
this.#recordSemanticAcknowledgementHeard(completion);
|
|
1023
|
+
this.#cancelPreemptiveAlertClearDeadline(utteranceId, generationEpoch);
|
|
1024
|
+
for (const eventId of eventIds) {
|
|
1025
|
+
// Confirmed only if it was actually spoken: a suggestion in a turn that was cut off has not been
|
|
1026
|
+
// offered, and marking it fired would stop it ever being offered again.
|
|
1027
|
+
if (eventId.startsWith('suggestion:') && this.session.eventWasSpoken(eventId)) {
|
|
1028
|
+
this.#ports.runtime.confirmSuggestionSpoken?.(eventId.slice('suggestion:'.length));
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
this.releaseUrgentHostResponse(urgentOwner);
|
|
1032
|
+
this.#ports.wake();
|
|
1033
|
+
return true;
|
|
1034
|
+
}
|
|
1035
|
+
/** The renderer dropped a generation on request. */
|
|
1036
|
+
playbackCleared(utteranceId, generationEpoch, playedMs) {
|
|
1037
|
+
const urgentOwner = this.#urgentOwnerForGeneration(utteranceId, generationEpoch);
|
|
1038
|
+
const completion = this.session.completePlaybackClear(utteranceId, generationEpoch, playedMs);
|
|
1039
|
+
if (completion === null)
|
|
1040
|
+
return false;
|
|
1041
|
+
const responseKey = callKey(completion.session_epoch, completion.response_id);
|
|
1042
|
+
const interruptedByLocalSpeech = this.#localSpeechInterruptedResponses.delete(responseKey);
|
|
1043
|
+
const audible = completion.played_ms === null
|
|
1044
|
+
? completion.started
|
|
1045
|
+
: completion.played_ms > 0;
|
|
1046
|
+
this.#reconcileAcknowledgementAfterPlaybackInterruption(completion.session_epoch, completion.response_id, interruptedByLocalSpeech && audible);
|
|
1047
|
+
// The acknowledgement arrived, so the deadline waiting for it has nothing left to retire.
|
|
1048
|
+
this.#cancelPreemptiveAlertClearDeadline(utteranceId, generationEpoch);
|
|
1049
|
+
this.releaseUrgentHostResponse(urgentOwner);
|
|
1050
|
+
this.#ports.wake();
|
|
1051
|
+
return true;
|
|
1052
|
+
}
|
|
1053
|
+
/** The renderer stopped playback without being asked -- a device change, or a closed window. */
|
|
1054
|
+
async playbackStopped(utteranceId, generationEpoch, playedMs) {
|
|
1055
|
+
const generation = this.session.currentGeneration;
|
|
1056
|
+
const urgentOwner = this.#urgentOwnerForGeneration(utteranceId, generationEpoch);
|
|
1057
|
+
const namesCurrentGeneration = generation !== null
|
|
1058
|
+
&& generation.utterance_id === utteranceId
|
|
1059
|
+
&& generation.generation_epoch === generationEpoch;
|
|
1060
|
+
const stopping = this.session.playbackStopped(utteranceId, generationEpoch, playedMs);
|
|
1061
|
+
// `RealtimeSession.playbackStopped` fences and clears the renderer generation synchronously,
|
|
1062
|
+
// then may wait for provider cancellation. Recover acknowledgement ownership before that wait:
|
|
1063
|
+
// a cascaded provider can emit `response_terminal(cancelled)` while the cancel promise is still
|
|
1064
|
+
// pending, and that terminal deliberately removes the old continuation binding.
|
|
1065
|
+
if (namesCurrentGeneration) {
|
|
1066
|
+
this.#localSpeechInterruptedResponses.delete(callKey(generation.session_epoch, generation.response_id));
|
|
1067
|
+
this.#reconcileAcknowledgementAfterPlaybackInterruption(generation.session_epoch, generation.response_id);
|
|
1068
|
+
}
|
|
1069
|
+
const stopped = await stopping;
|
|
1070
|
+
if (!stopped)
|
|
1071
|
+
return false;
|
|
1072
|
+
this.#cancelPreemptiveAlertClearDeadline(utteranceId, generationEpoch);
|
|
1073
|
+
this.releaseUrgentHostResponse(urgentOwner);
|
|
1074
|
+
this.#ports.wake();
|
|
1075
|
+
return true;
|
|
1076
|
+
}
|
|
1077
|
+
/** The renderer transport vanished, so no current or imminent response may keep speaking. */
|
|
1078
|
+
async playbackDisconnected(options = {}) {
|
|
1079
|
+
// Set before the first await so a concurrent host event cannot use the renderer boundary as a
|
|
1080
|
+
// chance to start speech that no authenticated renderer can play.
|
|
1081
|
+
const boundary = {};
|
|
1082
|
+
this.#rendererHostDeliveryBoundary = boundary;
|
|
1083
|
+
this.#rendererHostDeliveryPaused = true;
|
|
1084
|
+
try {
|
|
1085
|
+
const releasedUserHold = this.session.releaseRendererUserHold();
|
|
1086
|
+
const generation = this.session.currentGeneration;
|
|
1087
|
+
let fenced;
|
|
1088
|
+
if (generation !== null) {
|
|
1089
|
+
fenced = await this.playbackStopped(generation.utterance_id, generation.generation_epoch, null);
|
|
1090
|
+
}
|
|
1091
|
+
else {
|
|
1092
|
+
fenced = await this.session.rendererDisconnected();
|
|
1093
|
+
}
|
|
1094
|
+
return fenced || releasedUserHold;
|
|
1095
|
+
}
|
|
1096
|
+
finally {
|
|
1097
|
+
if (options.resumeDelivery === true
|
|
1098
|
+
&& this.#rendererHostDeliveryBoundary === boundary) {
|
|
1099
|
+
this.#rendererHostDeliveryPaused = false;
|
|
1100
|
+
this.#ports.wake();
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
/** Return an interrupted, unheard acknowledgement to the live delegate that still owns it. */
|
|
1105
|
+
#reconcileAcknowledgementAfterPlaybackInterruption(sessionEpoch, responseId, suppressReplay = false) {
|
|
1106
|
+
for (const acknowledgement of this.#semanticAcknowledgements.values()) {
|
|
1107
|
+
if (acknowledgement.phase !== 'bound'
|
|
1108
|
+
|| acknowledgement.response_session_epoch !== sessionEpoch
|
|
1109
|
+
|| acknowledgement.response_id !== responseId
|
|
1110
|
+
|| acknowledgement.heard)
|
|
1111
|
+
continue;
|
|
1112
|
+
if (suppressReplay) {
|
|
1113
|
+
// The renderer supplied audible evidence and local VAD says the user took the floor. The
|
|
1114
|
+
// acknowledgement was interrupted rather than fully heard, but replaying the same sentence
|
|
1115
|
+
// over the user's next turn is worse than retiring it. Device/window stops never enter here.
|
|
1116
|
+
acknowledgement.phase = 'cancelled';
|
|
1117
|
+
acknowledgement.response_id = null;
|
|
1118
|
+
acknowledgement.response_session_epoch = null;
|
|
1119
|
+
acknowledgement.binding = null;
|
|
1120
|
+
this.#retireSemanticAcknowledgementHostEvent(acknowledgement);
|
|
1121
|
+
continue;
|
|
1122
|
+
}
|
|
1123
|
+
if (this.session.delegateState(acknowledgement.delegate_id) !== 'running') {
|
|
1124
|
+
acknowledgement.phase = 'cancelled';
|
|
1125
|
+
acknowledgement.response_id = null;
|
|
1126
|
+
acknowledgement.response_session_epoch = null;
|
|
1127
|
+
acknowledgement.binding = null;
|
|
1128
|
+
this.#retireSemanticAcknowledgementHostEvent(acknowledgement);
|
|
1129
|
+
continue;
|
|
1130
|
+
}
|
|
1131
|
+
if (acknowledgement.provider_event_id === acknowledgement.event_id
|
|
1132
|
+
&& !this.session.reopenHostResponse(acknowledgement.event_id)) {
|
|
1133
|
+
this.#ports.onDiagnostic('[realtime-diagnostic] semantic_ack_reopen_failed');
|
|
1134
|
+
continue;
|
|
1135
|
+
}
|
|
1136
|
+
acknowledgement.phase = 'pending';
|
|
1137
|
+
acknowledgement.response_id = null;
|
|
1138
|
+
acknowledgement.response_session_epoch = null;
|
|
1139
|
+
acknowledgement.binding = null;
|
|
1140
|
+
this.#queueSemanticAcknowledgement(acknowledgement);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
/**
|
|
1144
|
+
* Record that a turn was audibly delivered, if it was.
|
|
1145
|
+
*
|
|
1146
|
+
* `played_ms > 0` when the renderer reported a duration, and otherwise whether it started at all.
|
|
1147
|
+
* Zero milliseconds is not audible: the renderer began and produced no sound, which is exactly the
|
|
1148
|
+
* case where assuming delivery would suppress an acknowledgement the user never heard.
|
|
1149
|
+
*
|
|
1150
|
+
* Only kept when something can still refer to it, and evicted oldest-first among the entries nothing
|
|
1151
|
+
* live points at -- so a bounded ledger never drops the proof a pending acknowledgement is waiting on.
|
|
1152
|
+
*/
|
|
1153
|
+
#recordOriginDeliveryProof(completion) {
|
|
1154
|
+
const audible = completion.played_ms === null
|
|
1155
|
+
? completion.started
|
|
1156
|
+
: completion.played_ms > 0;
|
|
1157
|
+
if (completion.disposition !== 'spoken' || !audible)
|
|
1158
|
+
return;
|
|
1159
|
+
const key = callKey(completion.session_epoch, completion.response_id);
|
|
1160
|
+
if (!this.#ports.originCanReferenceProof(key))
|
|
1161
|
+
return;
|
|
1162
|
+
this.#originDeliveryProofs.delete(key);
|
|
1163
|
+
this.#originDeliveryProofs.set(key, null);
|
|
1164
|
+
this.#pruneOriginDeliveryProofs();
|
|
1165
|
+
}
|
|
1166
|
+
/** Persist renderer-backed audibility for the acknowledgement bound to this exact provider turn. */
|
|
1167
|
+
#recordSemanticAcknowledgementHeard(completion) {
|
|
1168
|
+
const audible = completion.played_ms === null
|
|
1169
|
+
? completion.started
|
|
1170
|
+
: completion.played_ms > 0;
|
|
1171
|
+
if (completion.disposition !== 'spoken' || !audible)
|
|
1172
|
+
return;
|
|
1173
|
+
for (const acknowledgement of this.#semanticAcknowledgements.values()) {
|
|
1174
|
+
if (acknowledgement.phase !== 'bound'
|
|
1175
|
+
|| acknowledgement.response_session_epoch !== completion.session_epoch
|
|
1176
|
+
|| acknowledgement.response_id !== completion.response_id)
|
|
1177
|
+
continue;
|
|
1178
|
+
acknowledgement.heard = true;
|
|
1179
|
+
this.#markAcknowledgementDelivered(acknowledgement);
|
|
1180
|
+
this.#retireSemanticAcknowledgementHostEvent(acknowledgement);
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
rememberDelegateHostEvent(delegateId, eventId) {
|
|
1184
|
+
this.#delegateHostEvents.delete(eventId);
|
|
1185
|
+
this.#delegateHostEvents.set(eventId, delegateId);
|
|
1186
|
+
while (this.#delegateHostEvents.size > MAX_PENDING_HOST_EVENTS) {
|
|
1187
|
+
const oldest = this.#delegateHostEvents.keys().next();
|
|
1188
|
+
if (oldest.done)
|
|
1189
|
+
break;
|
|
1190
|
+
this.#delegateHostEvents.delete(oldest.value);
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
retireDelegateHostEvents(delegateId) {
|
|
1194
|
+
for (const [eventId, owner] of [...this.#delegateHostEvents]) {
|
|
1195
|
+
if (owner !== delegateId)
|
|
1196
|
+
continue;
|
|
1197
|
+
this.#delegateHostEvents.delete(eventId);
|
|
1198
|
+
this.#codingProgressHostEventIds.delete(eventId);
|
|
1199
|
+
this.retireProviderHostEvent(eventId);
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
#retireSemanticAcknowledgementHostEvent(acknowledgement) {
|
|
1203
|
+
const eventId = acknowledgement.provider_event_id;
|
|
1204
|
+
if (eventId !== null)
|
|
1205
|
+
this.retireProviderHostEvent(eventId);
|
|
1206
|
+
}
|
|
1207
|
+
/** Provider deletion is defense in depth; queue eligibility remains the correctness boundary. */
|
|
1208
|
+
retireProviderHostEvent(eventId) {
|
|
1209
|
+
if (this.#providerRetirementEventIds.has(eventId))
|
|
1210
|
+
return;
|
|
1211
|
+
this.#providerRetirementEventIds.add(eventId);
|
|
1212
|
+
const task = this.session.retireHostEvent(eventId)
|
|
1213
|
+
.then(() => undefined)
|
|
1214
|
+
.catch((failure) => {
|
|
1215
|
+
this.#ports.onDiagnostic(`[realtime-diagnostic] host_item_retire_failure type=${diagnosticName(failure)}`);
|
|
1216
|
+
})
|
|
1217
|
+
.finally(() => {
|
|
1218
|
+
this.#providerRetirementEventIds.delete(eventId);
|
|
1219
|
+
this.#providerRetirementTasks.delete(task);
|
|
1220
|
+
});
|
|
1221
|
+
this.#providerRetirementTasks.add(task);
|
|
1222
|
+
}
|
|
1223
|
+
/** Injection just completed, so perform a fresh lookup even if an earlier best-effort miss exists. */
|
|
1224
|
+
async retireProviderHostEventNow(eventId) {
|
|
1225
|
+
try {
|
|
1226
|
+
await this.session.retireHostEvent(eventId);
|
|
1227
|
+
}
|
|
1228
|
+
catch (failure) {
|
|
1229
|
+
this.#ports.onDiagnostic(`[realtime-diagnostic] host_item_retire_failure type=${diagnosticName(failure)}`);
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
/**
|
|
1233
|
+
* Keep the ledger bounded, evicting what nothing unfinished depends on.
|
|
1234
|
+
*
|
|
1235
|
+
* When *everything* is still referenced there is no safe choice, so the newest goes: the older
|
|
1236
|
+
* proofs have waited longer and are likelier to be the one something is about to ask for.
|
|
1237
|
+
*/
|
|
1238
|
+
#pruneOriginDeliveryProofs() {
|
|
1239
|
+
while (this.#originDeliveryProofs.size > MAX_TRACKED_ORIGIN_DELIVERY_PROOFS) {
|
|
1240
|
+
let evictable;
|
|
1241
|
+
for (const key of this.#originDeliveryProofs.keys()) {
|
|
1242
|
+
if (!this.#ports.originHasNonterminalReference(key)) {
|
|
1243
|
+
evictable = key;
|
|
1244
|
+
break;
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
if (evictable === undefined) {
|
|
1248
|
+
const newest = [...this.#originDeliveryProofs.keys()].at(-1);
|
|
1249
|
+
if (newest !== undefined)
|
|
1250
|
+
this.#originDeliveryProofs.delete(newest);
|
|
1251
|
+
return;
|
|
1252
|
+
}
|
|
1253
|
+
this.#originDeliveryProofs.delete(evictable);
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
/**
|
|
1257
|
+
* Deliver the exact preemptive alert captured before the reconnect, independent of heap order.
|
|
1258
|
+
*
|
|
1259
|
+
* Not through the ordinary flush: the item was chosen before the session was replaced, and re-running
|
|
1260
|
+
* the priority comparison now could deliver something else into a session that exists solely to
|
|
1261
|
+
* carry this one. Removed from the heap by identity and re-heapified, rather than popped.
|
|
1262
|
+
*/
|
|
1263
|
+
async deliverCapturedPreemptiveAlertLocked(queued) {
|
|
1264
|
+
const index = this.#hostItems.indexOf(queued);
|
|
1265
|
+
if (index === -1)
|
|
1266
|
+
return;
|
|
1267
|
+
this.#hostItems.splice(index, 1);
|
|
1268
|
+
this.#hostItems.sort(compareQueuedHostResponses);
|
|
1269
|
+
const userActivation = this.#preemptiveAlertActivationRequired(queued);
|
|
1270
|
+
let lifecycleRevoked = false;
|
|
1271
|
+
let delivery;
|
|
1272
|
+
try {
|
|
1273
|
+
delivery = await this.session.deliverPreemptiveHostResponse(queued.intent, {
|
|
1274
|
+
confirmationTimeout: 0.5,
|
|
1275
|
+
responseAllowed: () => {
|
|
1276
|
+
const eligible = this.#queuedHostItemEligible(queued);
|
|
1277
|
+
if (!eligible)
|
|
1278
|
+
lifecycleRevoked = true;
|
|
1279
|
+
return eligible && this.#preemptiveAlertResponseIsAllowed(queued.intent.item.event_id);
|
|
1280
|
+
},
|
|
1281
|
+
asUserActivation: userActivation,
|
|
1282
|
+
});
|
|
1283
|
+
}
|
|
1284
|
+
catch (cause) {
|
|
1285
|
+
this.requeueHostItem(queued);
|
|
1286
|
+
throw cause;
|
|
1287
|
+
}
|
|
1288
|
+
if (!delivery.accepted) {
|
|
1289
|
+
if (lifecycleRevoked) {
|
|
1290
|
+
if (delivery.injectionEpoch === this.session.sessionEpoch) {
|
|
1291
|
+
await this.retireProviderHostEventNow(queued.intent.item.event_id);
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
else {
|
|
1295
|
+
this.requeueHostItem(queued);
|
|
1296
|
+
}
|
|
1297
|
+
this.#recomputePreemptPriority();
|
|
1298
|
+
return;
|
|
1299
|
+
}
|
|
1300
|
+
if (userActivation) {
|
|
1301
|
+
this.#providerEpochNeedingActivation = null;
|
|
1302
|
+
this.#providerReconnectSourceEpoch = null;
|
|
1303
|
+
}
|
|
1304
|
+
this.#recomputePreemptPriority();
|
|
1305
|
+
if (queued.semantic_event_id !== null) {
|
|
1306
|
+
const acknowledgement = this.#semanticAcknowledgements.get(queued.semantic_event_id);
|
|
1307
|
+
if (acknowledgement?.phase === 'queued')
|
|
1308
|
+
acknowledgement.phase = 'requested';
|
|
1309
|
+
}
|
|
1310
|
+
if (!this.#ports.stopped()
|
|
1311
|
+
&& !this.#ports.providerFailed()
|
|
1312
|
+
&& delivery.injectionEpoch === this.session.sessionEpoch) {
|
|
1313
|
+
this.#urgentDeliveryToken += 1;
|
|
1314
|
+
this.#urgentHostResponseOwner = {
|
|
1315
|
+
delivery_token: this.#urgentDeliveryToken,
|
|
1316
|
+
session_epoch: delivery.injectionEpoch,
|
|
1317
|
+
event_id: queued.intent.item.event_id,
|
|
1318
|
+
queued,
|
|
1319
|
+
response_id: null,
|
|
1320
|
+
generation: null,
|
|
1321
|
+
};
|
|
1322
|
+
}
|
|
1323
|
+
this.#ports.telemetry?.record('hostitem.injected', { event_id: queued.intent.item.event_id });
|
|
1324
|
+
}
|
|
1325
|
+
/**
|
|
1326
|
+
* Whether the replacement turn may still speak.
|
|
1327
|
+
*
|
|
1328
|
+
* Checked at the moment the provider is about to create it, not when it was requested: a user who
|
|
1329
|
+
* started talking in between has revoked the authority, and an aborted reconnect means the session
|
|
1330
|
+
* this was for is gone.
|
|
1331
|
+
*/
|
|
1332
|
+
#preemptiveAlertResponseIsAllowed(eventId) {
|
|
1333
|
+
const preemption = this.#preemptiveAlert;
|
|
1334
|
+
return preemption !== null
|
|
1335
|
+
&& preemption.event_id === eventId
|
|
1336
|
+
&& !preemption.reconnect_aborted
|
|
1337
|
+
&& this.session.floor.state !== 'user_speaking';
|
|
1338
|
+
}
|
|
1339
|
+
/**
|
|
1340
|
+
* Bind the urgent item to the response now speaking it.
|
|
1341
|
+
*
|
|
1342
|
+
* The owner is created at delivery, before any response exists, so this is where it learns which one
|
|
1343
|
+
* it became. Matched by *event id within the response*, not by timing: another response could start
|
|
1344
|
+
* in the same instant, and binding to the wrong one would mean the alert is later considered spoken
|
|
1345
|
+
* when something else was.
|
|
1346
|
+
*/
|
|
1347
|
+
bindUrgentHostResponse(event) {
|
|
1348
|
+
const owner = this.#urgentHostResponseOwner;
|
|
1349
|
+
if (owner?.session_epoch !== event.session_epoch)
|
|
1350
|
+
return;
|
|
1351
|
+
let bound = owner;
|
|
1352
|
+
if (owner.response_id === null) {
|
|
1353
|
+
if (event.kind !== 'response_started')
|
|
1354
|
+
return;
|
|
1355
|
+
if (!this.session.responseEventIds(event.response_id).includes(owner.event_id))
|
|
1356
|
+
return;
|
|
1357
|
+
bound = { ...owner, response_id: event.response_id };
|
|
1358
|
+
}
|
|
1359
|
+
else if (owner.response_id !== event.response_id) {
|
|
1360
|
+
return;
|
|
1361
|
+
}
|
|
1362
|
+
const generation = this.session.currentGeneration;
|
|
1363
|
+
if (generation !== null
|
|
1364
|
+
&& generation.session_epoch === event.session_epoch
|
|
1365
|
+
&& generation.response_id === event.response_id) {
|
|
1366
|
+
bound = { ...bound, generation };
|
|
1367
|
+
}
|
|
1368
|
+
// The token guards against a replacement owner having appeared while this was being computed.
|
|
1369
|
+
if (this.#urgentHostResponseOwner?.delivery_token === bound.delivery_token) {
|
|
1370
|
+
this.#urgentHostResponseOwner = bound;
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
/**
|
|
1374
|
+
* The replacement is audibly speaking, so the preemption is over.
|
|
1375
|
+
*
|
|
1376
|
+
* This is the success path, and it is deliberately the *only* one that reports the switch latency:
|
|
1377
|
+
* the deadline path fires when the provider did not cooperate, and timing that would measure the
|
|
1378
|
+
* timeout rather than the handover.
|
|
1379
|
+
*/
|
|
1380
|
+
finishPreemptiveAlertFirstAudio(event) {
|
|
1381
|
+
const preemption = this.#preemptiveAlert;
|
|
1382
|
+
const owner = this.#urgentHostResponseOwner;
|
|
1383
|
+
const generation = this.session.currentGeneration;
|
|
1384
|
+
if (preemption === null
|
|
1385
|
+
|| owner === null
|
|
1386
|
+
|| generation === null
|
|
1387
|
+
|| preemption.event_id !== owner.event_id
|
|
1388
|
+
|| preemption.session_epoch !== event.session_epoch
|
|
1389
|
+
|| owner.response_id !== event.response_id
|
|
1390
|
+
|| generation.session_epoch !== event.session_epoch
|
|
1391
|
+
|| generation.response_id !== event.response_id) {
|
|
1392
|
+
return;
|
|
1393
|
+
}
|
|
1394
|
+
const token = preemption.token;
|
|
1395
|
+
this.clearPreemptiveAlert(token);
|
|
1396
|
+
if (this.#ports.controlledPreemptiveAlertReconnect
|
|
1397
|
+
&& preemption.reconnect_permit_consumed
|
|
1398
|
+
&& preemption.old_generation !== null) {
|
|
1399
|
+
this.startPreemptiveAlertClearDeadline(preemption.old_generation);
|
|
1400
|
+
}
|
|
1401
|
+
this.#ports.telemetry?.record('guard.first_audio_switch', {
|
|
1402
|
+
elapsed_ms: Math.max(0, Math.round((this.#ports.clock.now() - preemption.queued_at) * 1_000)),
|
|
1403
|
+
});
|
|
1404
|
+
}
|
|
1405
|
+
/**
|
|
1406
|
+
* Stop waiting for the provider to confirm the cancel.
|
|
1407
|
+
*
|
|
1408
|
+
* The provider was asked to stop and has not said it did. Past the deadline the host acts as though
|
|
1409
|
+
* it had -- the alternative is the user hearing the old turn continue while an urgent alert waits
|
|
1410
|
+
* behind it, which is the failure preemption exists to prevent.
|
|
1411
|
+
*/
|
|
1412
|
+
async #firePreemptiveAlertDeadline(preemption) {
|
|
1413
|
+
try {
|
|
1414
|
+
const delay = Math.max(0, preemption.queued_at + PREEMPTIVE_ALERT_DEADLINE_S - this.#ports.clock.now());
|
|
1415
|
+
await this.#ports.clock.sleep(delay, this.#preemptiveAlertAbort?.signal);
|
|
1416
|
+
const current = this.#preemptiveAlert;
|
|
1417
|
+
// Re-read, never trusted: the preemption this timer belongs to may have resolved, been replaced,
|
|
1418
|
+
// or already fired while this was sleeping.
|
|
1419
|
+
if (current?.token !== preemption.token || current.deadline_fired)
|
|
1420
|
+
return;
|
|
1421
|
+
if (current.reconnect_aborted) {
|
|
1422
|
+
this.clearPreemptiveAlert(current.token);
|
|
1423
|
+
return;
|
|
1424
|
+
}
|
|
1425
|
+
const controlledHandoff = current.reconnect_permit_consumed;
|
|
1426
|
+
const expired = controlledHandoff && current.old_generation !== null
|
|
1427
|
+
? this.session.alertPreemptiveAlertHandoff(current.old_generation)
|
|
1428
|
+
: this.session.expireHostPreempt(current.old_generation);
|
|
1429
|
+
if (!expired)
|
|
1430
|
+
return;
|
|
1431
|
+
this.#preemptiveAlert = { ...current, deadline_fired: true };
|
|
1432
|
+
if (this.#ports.controlledPreemptiveAlertReconnect
|
|
1433
|
+
&& current.reconnect_permit_consumed
|
|
1434
|
+
&& current.old_generation !== null) {
|
|
1435
|
+
this.startPreemptiveAlertClearDeadline(current.old_generation);
|
|
1436
|
+
}
|
|
1437
|
+
this.#ports.telemetry?.record('guard.alert_deadline_fired', {});
|
|
1438
|
+
// Both halves are done, so nothing is left to wait for.
|
|
1439
|
+
if (current.replacement_terminal)
|
|
1440
|
+
this.clearPreemptiveAlert(current.token);
|
|
1441
|
+
this.#ports.wake();
|
|
1442
|
+
}
|
|
1443
|
+
catch (failure) {
|
|
1444
|
+
if (isAbort(failure))
|
|
1445
|
+
return;
|
|
1446
|
+
this.#ports.onDiagnostic(`[realtime-diagnostic] preemptive_alert_failure type=${diagnosticName(failure)}`);
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
/**
|
|
1450
|
+
* End a preemption, cancelling its deadline.
|
|
1451
|
+
*
|
|
1452
|
+
* The token argument is how a caller says "only if this is still the one I mean" -- without it, a
|
|
1453
|
+
* late callback would clear a preemption that started after the one it belonged to.
|
|
1454
|
+
*/
|
|
1455
|
+
clearPreemptiveAlert(token) {
|
|
1456
|
+
const current = this.#preemptiveAlert;
|
|
1457
|
+
if (current === null || (token !== undefined && current.token !== token))
|
|
1458
|
+
return;
|
|
1459
|
+
this.#preemptiveAlert = null;
|
|
1460
|
+
const abort = this.#preemptiveAlertAbort;
|
|
1461
|
+
this.#preemptiveAlertAbort = null;
|
|
1462
|
+
abort?.abort();
|
|
1463
|
+
}
|
|
1464
|
+
/**
|
|
1465
|
+
* Wait for the renderer to confirm it dropped the cleared audio.
|
|
1466
|
+
*
|
|
1467
|
+
* Keyed by generation and idempotent: the clear can be re-sent, and a second deadline for the same
|
|
1468
|
+
* generation would retire it twice.
|
|
1469
|
+
*/
|
|
1470
|
+
startPreemptiveAlertClearDeadline(generation) {
|
|
1471
|
+
const key = `${generation.utterance_id}:${generation.generation_epoch}`;
|
|
1472
|
+
if (this.#preemptiveAlertClearDeadlines.has(key))
|
|
1473
|
+
return;
|
|
1474
|
+
const abort = new AbortController();
|
|
1475
|
+
this.#preemptiveAlertClearDeadlines.set(key, abort);
|
|
1476
|
+
void this.#retirePreemptiveAlertClearUnknown(generation, key, abort.signal);
|
|
1477
|
+
}
|
|
1478
|
+
/**
|
|
1479
|
+
* Give up on the renderer's clear acknowledgement.
|
|
1480
|
+
*
|
|
1481
|
+
* Retiring the generation as *unknown* rather than cleared is the honest answer: the host does not
|
|
1482
|
+
* know how much of it the user heard, and recording either extreme would be a claim it cannot
|
|
1483
|
+
* support.
|
|
1484
|
+
*/
|
|
1485
|
+
async #retirePreemptiveAlertClearUnknown(generation, key, signal) {
|
|
1486
|
+
try {
|
|
1487
|
+
await this.#ports.clock.sleep(PREEMPTIVE_ALERT_CLEAR_ACK_DEADLINE_S, signal);
|
|
1488
|
+
if (!this.session.retirePlaybackClearUnknown(generation))
|
|
1489
|
+
return;
|
|
1490
|
+
this.#ports.telemetry?.record('renderer_clear_unknown', {
|
|
1491
|
+
session_epoch: generation.session_epoch,
|
|
1492
|
+
generation_epoch: generation.generation_epoch,
|
|
1493
|
+
});
|
|
1494
|
+
this.#ports.wake();
|
|
1495
|
+
}
|
|
1496
|
+
catch (failure) {
|
|
1497
|
+
if (!isAbort(failure))
|
|
1498
|
+
throw failure;
|
|
1499
|
+
}
|
|
1500
|
+
finally {
|
|
1501
|
+
if (this.#preemptiveAlertClearDeadlines.get(key)?.signal === signal) {
|
|
1502
|
+
this.#preemptiveAlertClearDeadlines.delete(key);
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
#cancelPreemptiveAlertClearDeadline(utteranceId, generationEpoch) {
|
|
1507
|
+
const key = `${utteranceId}:${generationEpoch}`;
|
|
1508
|
+
const abort = this.#preemptiveAlertClearDeadlines.get(key);
|
|
1509
|
+
if (abort === undefined)
|
|
1510
|
+
return;
|
|
1511
|
+
this.#preemptiveAlertClearDeadlines.delete(key);
|
|
1512
|
+
abort.abort();
|
|
1513
|
+
}
|
|
1514
|
+
/** Record how the cancelled turn actually ended, which is the only measure of whether it worked. */
|
|
1515
|
+
recordPreemptiveAlertCancelTerminal(event) {
|
|
1516
|
+
const preemption = this.#preemptiveAlert;
|
|
1517
|
+
if (preemption?.session_epoch !== event.session_epoch
|
|
1518
|
+
|| preemption.old_response_id !== event.response_id) {
|
|
1519
|
+
return;
|
|
1520
|
+
}
|
|
1521
|
+
// Only a client-requested cancellation means the preemption did it. A turn that ended by itself in
|
|
1522
|
+
// the same moment looks identical from outside and is not the same event.
|
|
1523
|
+
const success = event.status === 'cancelled' && event.reason === 'client_cancelled';
|
|
1524
|
+
const reasonCategory = event.status === 'cancelled'
|
|
1525
|
+
? (success ? 'client_cancelled' : 'other_cancelled')
|
|
1526
|
+
: event.status;
|
|
1527
|
+
this.#ports.telemetry?.record('provider.cancel_terminal', {
|
|
1528
|
+
status: event.status,
|
|
1529
|
+
reason_category: reasonCategory,
|
|
1530
|
+
success,
|
|
1531
|
+
elapsed_ms: Math.max(0, Math.round((this.#ports.clock.now() - preemption.queued_at) * 1_000)),
|
|
1532
|
+
});
|
|
1533
|
+
}
|
|
1534
|
+
/** Note that the cancel actually reached the provider. Once per preemption. */
|
|
1535
|
+
recordPreemptiveAlertCancelSent(responseId) {
|
|
1536
|
+
const preemption = this.#preemptiveAlert;
|
|
1537
|
+
if (preemption?.session_epoch !== this.session.sessionEpoch
|
|
1538
|
+
|| preemption.old_response_id !== responseId
|
|
1539
|
+
|| preemption.cancel_sent) {
|
|
1540
|
+
return;
|
|
1541
|
+
}
|
|
1542
|
+
this.#preemptiveAlert = { ...preemption, cancel_sent: true };
|
|
1543
|
+
this.#ports.telemetry?.record('provider.cancel_sent', {
|
|
1544
|
+
elapsed_ms: Math.max(0, Math.round((this.#ports.clock.now() - preemption.queued_at) * 1_000)),
|
|
1545
|
+
});
|
|
1546
|
+
}
|
|
1547
|
+
/**
|
|
1548
|
+
* The replacement turn has ended.
|
|
1549
|
+
*
|
|
1550
|
+
* Half of the two-sided finish: the preemption is over when the replacement has finished *and* the
|
|
1551
|
+
* old turn has been dealt with. Whichever arrives second does the clearing.
|
|
1552
|
+
*/
|
|
1553
|
+
markPreemptiveAlertReplacementTerminal(owner) {
|
|
1554
|
+
const preemption = this.#preemptiveAlert;
|
|
1555
|
+
if (owner === null
|
|
1556
|
+
|| preemption?.event_id !== owner.event_id
|
|
1557
|
+
|| preemption.session_epoch !== owner.session_epoch) {
|
|
1558
|
+
return;
|
|
1559
|
+
}
|
|
1560
|
+
const marked = { ...preemption, replacement_terminal: true };
|
|
1561
|
+
this.#preemptiveAlert = marked;
|
|
1562
|
+
if (marked.deadline_fired)
|
|
1563
|
+
this.clearPreemptiveAlert(marked.token);
|
|
1564
|
+
}
|
|
1565
|
+
/**
|
|
1566
|
+
* Release an urgent item that was fenced before it ever started.
|
|
1567
|
+
*
|
|
1568
|
+
* A fence receipt naming it means the provider never began the response carrying it. Holding the
|
|
1569
|
+
* owner would block every later preemption behind one that is never going to speak.
|
|
1570
|
+
*/
|
|
1571
|
+
retireFencedPrestartUrgent() {
|
|
1572
|
+
const receipt = this.session.takeFenceInterruption();
|
|
1573
|
+
const owner = this.#urgentHostResponseOwner;
|
|
1574
|
+
if (receipt === null
|
|
1575
|
+
|| owner?.response_id !== null
|
|
1576
|
+
|| owner.session_epoch !== receipt.session_epoch
|
|
1577
|
+
|| !receipt.event_ids.includes(owner.event_id)) {
|
|
1578
|
+
return;
|
|
1579
|
+
}
|
|
1580
|
+
this.releaseUrgentHostResponse(owner);
|
|
1581
|
+
}
|
|
1582
|
+
urgentOwnerForResponse(sessionEpoch, responseId) {
|
|
1583
|
+
const owner = this.#urgentHostResponseOwner;
|
|
1584
|
+
if (owner?.session_epoch !== sessionEpoch || owner.response_id !== responseId)
|
|
1585
|
+
return null;
|
|
1586
|
+
return owner;
|
|
1587
|
+
}
|
|
1588
|
+
#urgentOwnerForGeneration(utteranceId, generationEpoch) {
|
|
1589
|
+
const generation = this.#urgentHostResponseOwner?.generation;
|
|
1590
|
+
if (generation?.utterance_id !== utteranceId
|
|
1591
|
+
|| generation.generation_epoch !== generationEpoch) {
|
|
1592
|
+
return null;
|
|
1593
|
+
}
|
|
1594
|
+
return this.#urgentHostResponseOwner;
|
|
1595
|
+
}
|
|
1596
|
+
/** Release this exact owner. The token is what stops a stale caller releasing its replacement. */
|
|
1597
|
+
releaseUrgentHostResponse(owner) {
|
|
1598
|
+
const current = this.#urgentHostResponseOwner;
|
|
1599
|
+
if (owner !== null
|
|
1600
|
+
&& current !== null
|
|
1601
|
+
&& current.delivery_token === owner.delivery_token) {
|
|
1602
|
+
this.#urgentHostResponseOwner = null;
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
releaseUrgentHostResponseForEpoch(sessionEpoch) {
|
|
1606
|
+
if (this.#urgentHostResponseOwner?.session_epoch === sessionEpoch) {
|
|
1607
|
+
this.#urgentHostResponseOwner = null;
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
/** Read-only views the tests and the desktop layer use. */
|
|
1611
|
+
get pendingHostItemCount() {
|
|
1612
|
+
return this.#hostItems.length;
|
|
1613
|
+
}
|
|
1614
|
+
get armedPreemptPriority() {
|
|
1615
|
+
return this.#pendingPreemptPriority;
|
|
1616
|
+
}
|
|
1617
|
+
/** The queued items in delivery order, for assertions. A copy: the heap is not the caller's. */
|
|
1618
|
+
queuedHostItems() {
|
|
1619
|
+
return [...this.#hostItems].sort(compareQueuedHostResponses);
|
|
1620
|
+
}
|
|
1621
|
+
/**
|
|
1622
|
+
* Take the next item the queue would deliver, without delivering it.
|
|
1623
|
+
*
|
|
1624
|
+
* The ordering is a contract the oracle pins, and the delivery path around it is not ported yet, so
|
|
1625
|
+
* the two have to be separable: this is how the ordering is exercised on its own. It keeps the
|
|
1626
|
+
* armed-preempt bookkeeping in step, which is the part a caller would otherwise get wrong.
|
|
1627
|
+
*/
|
|
1628
|
+
takeNextQueuedHostItem() {
|
|
1629
|
+
const queued = heapPop(this.#hostItems);
|
|
1630
|
+
if (queued?.preemptive === true)
|
|
1631
|
+
this.#recomputePreemptPriority();
|
|
1632
|
+
return queued;
|
|
1633
|
+
}
|
|
1634
|
+
/** Stand in for preemptive-alert delivery that would normally create an urgent owner. */
|
|
1635
|
+
seedUrgentOwnerForTest(input) {
|
|
1636
|
+
this.#urgentDeliveryToken += 1;
|
|
1637
|
+
this.#urgentHostResponseOwner = {
|
|
1638
|
+
delivery_token: this.#urgentDeliveryToken,
|
|
1639
|
+
session_epoch: input.sessionEpoch,
|
|
1640
|
+
event_id: input.eventId,
|
|
1641
|
+
queued: {
|
|
1642
|
+
sortKey: [-90, -1, 0],
|
|
1643
|
+
intent: hostFactIntent({
|
|
1644
|
+
kind: 'final',
|
|
1645
|
+
host_item_id: 'urgent-host-1',
|
|
1646
|
+
event_id: input.eventId,
|
|
1647
|
+
content: 'urgent',
|
|
1648
|
+
}),
|
|
1649
|
+
priority: 90,
|
|
1650
|
+
preemptive: true,
|
|
1651
|
+
preemptive_alert: false,
|
|
1652
|
+
seq: 0,
|
|
1653
|
+
queued_at: 0,
|
|
1654
|
+
semantic_event_id: null,
|
|
1655
|
+
preemptive_alert_activation: null,
|
|
1656
|
+
owner: null,
|
|
1657
|
+
expires_at: null,
|
|
1658
|
+
},
|
|
1659
|
+
response_id: input.responseId,
|
|
1660
|
+
generation: null,
|
|
1661
|
+
};
|
|
1662
|
+
}
|
|
1663
|
+
get urgentOwnerForTest() {
|
|
1664
|
+
return this.#urgentHostResponseOwner;
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
/**
|
|
1668
|
+
* A binary min-heap, matching the oracle's `heapq` sift order exactly.
|
|
1669
|
+
*
|
|
1670
|
+
* Not a sorted array: `heapq` is not a stable sort, and two items comparing equal can come out in an
|
|
1671
|
+
* order a sort would not produce. The comparison keys here are unique by construction (the sequence
|
|
1672
|
+
* number is the last field), so the orders coincide -- but implementing the same structure means that
|
|
1673
|
+
* remains true if a future key stops being unique.
|
|
1674
|
+
*/
|
|
1675
|
+
function heapPush(heap, item) {
|
|
1676
|
+
heap.push(item);
|
|
1677
|
+
let index = heap.length - 1;
|
|
1678
|
+
while (index > 0) {
|
|
1679
|
+
const parent = (index - 1) >> 1;
|
|
1680
|
+
if (compareHeap(heap[index], heap[parent]) >= 0)
|
|
1681
|
+
break;
|
|
1682
|
+
[heap[index], heap[parent]] = [heap[parent], heap[index]];
|
|
1683
|
+
index = parent;
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
function heapPop(heap) {
|
|
1687
|
+
const top = heap[0];
|
|
1688
|
+
const last = heap.pop();
|
|
1689
|
+
if (heap.length === 0 || last === undefined)
|
|
1690
|
+
return top;
|
|
1691
|
+
heap[0] = last;
|
|
1692
|
+
let index = 0;
|
|
1693
|
+
for (;;) {
|
|
1694
|
+
const left = index * 2 + 1;
|
|
1695
|
+
const right = left + 1;
|
|
1696
|
+
let smallest = index;
|
|
1697
|
+
if (left < heap.length && compareHeap(heap[left], heap[smallest]) < 0)
|
|
1698
|
+
smallest = left;
|
|
1699
|
+
if (right < heap.length && compareHeap(heap[right], heap[smallest]) < 0)
|
|
1700
|
+
smallest = right;
|
|
1701
|
+
if (smallest === index)
|
|
1702
|
+
break;
|
|
1703
|
+
[heap[index], heap[smallest]] = [heap[smallest], heap[index]];
|
|
1704
|
+
index = smallest;
|
|
1705
|
+
}
|
|
1706
|
+
return top;
|
|
1707
|
+
}
|
|
1708
|
+
function compareHeap(left, right) {
|
|
1709
|
+
return compareQueuedHostResponses(left, right);
|
|
1710
|
+
}
|
|
1711
|
+
//# sourceMappingURL=host-delivery.js.map
|