nova-personal-agent-server 0.4.0 → 1.0.2
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 +674 -201
- package/README.md +12 -2
- package/bin/nova-space-host.mjs +4 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/cli.js +71 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/client.js +340 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/crypto.js +167 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/live.js +169 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/mailbox.js +217 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/media.js +320 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/pairing.js +13 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/protocol.js +50 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/security.js +305 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/server.js +477 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/source-address.js +58 -0
- package/node_modules/@nova-personal-agent/relay/package.json +1 -0
- package/package.json +13 -6
- package/runtime/dist/src/cascaded-text-provider.js +8 -3
- package/runtime/dist/src/composition/assembly.js +133 -35
- package/runtime/dist/src/composition/cascaded-realtime-assembly.js +114 -59
- package/runtime/dist/src/composition/production-composition.js +57 -21
- package/runtime/dist/src/composition/realtime-assembly.js +160 -52
- package/runtime/dist/src/composition/soul-context.js +22 -0
- package/runtime/dist/src/config/capability-registry.js +48 -3
- package/runtime/dist/src/config/cascaded-realtime-config.js +23 -10
- package/runtime/dist/src/config/config.js +541 -128
- package/runtime/dist/src/config/credential-rotation.js +26 -0
- package/runtime/dist/src/config/data-root.js +764 -0
- package/runtime/dist/src/config/diagnostics.js +3 -1
- package/runtime/dist/src/config/environment-contract.js +190 -188
- package/runtime/dist/src/config/model-routes.js +140 -0
- package/runtime/dist/src/config/voice-credentials.js +55 -0
- package/runtime/dist/src/connectors/composio/index.js +9 -0
- package/runtime/dist/src/connectors/feishu/index.js +258 -44
- package/runtime/dist/src/connectors/macos/mail.js +7 -3
- package/runtime/dist/src/connectors/macos/reader.js +3 -1
- package/runtime/dist/src/conversation-voice-provider.js +5 -2
- package/runtime/dist/src/core/causal-runtime.js +38 -3
- package/runtime/dist/src/core/context-view.js +7 -0
- package/runtime/dist/src/core/guards.js +32 -0
- package/runtime/dist/src/core/runtime.js +3 -0
- package/runtime/dist/src/core/schedule-tools.js +2 -2
- package/runtime/dist/src/core/source-processing-instructions.js +2 -2
- package/runtime/dist/src/core/source-processing-tools.js +3 -1
- package/runtime/dist/src/core/tool-schema.js +42 -7
- package/runtime/dist/src/desktop/desktop-camera.js +3 -5
- package/runtime/dist/src/desktop/desktop-control.js +41 -8
- package/runtime/dist/src/desktop/desktop-session.js +90 -19
- package/runtime/dist/src/desktop/desktop-wire.js +5 -7
- package/runtime/dist/src/desktop/startup-error.js +18 -16
- package/runtime/dist/src/desktop/workbench-acceptance.js +52 -14
- package/runtime/dist/src/desktop-entry.js +6 -2
- package/runtime/dist/src/desktop.js +5 -1
- package/runtime/dist/src/device/attempt.js +65 -0
- package/runtime/dist/src/device/authority.js +159 -0
- package/runtime/dist/src/device/gateway.js +87 -0
- package/runtime/dist/src/device/ledger.js +91 -0
- package/runtime/dist/src/device/ownership.js +92 -0
- package/runtime/dist/src/device/port.js +2 -0
- package/runtime/dist/src/device/schedule-ownership.js +103 -0
- package/runtime/dist/src/executors/acp/transport.js +2 -0
- package/runtime/dist/src/executors/browser.js +4 -3
- package/runtime/dist/src/executors/codex/adapter-project.js +58 -12
- package/runtime/dist/src/executors/codex/app-server-schema.js +12 -21
- package/runtime/dist/src/executors/codex/app-server-transport.js +32 -18
- package/runtime/dist/src/executors/codex/common.js +1 -1
- package/runtime/dist/src/executors/codex/contract.js +12 -16
- package/runtime/dist/src/executors/codex/credential-snapshot.js +1 -9
- package/runtime/dist/src/executors/codex/factory.js +54 -32
- package/runtime/dist/src/executors/codex/host-config.js +69 -20
- package/runtime/dist/src/executors/codex/launch-profile.js +3 -2
- package/runtime/dist/src/executors/codex/local-provider-credential.js +39 -0
- package/runtime/dist/src/executors/codex/process-owner.js +4 -6
- package/runtime/dist/src/executors/codex/production-host.js +33 -34
- package/runtime/dist/src/executors/codex/protocol.js +9 -14
- package/runtime/dist/src/executors/codex/session-title.js +6 -8
- package/runtime/dist/src/executors/codex/spawn-env.js +27 -6
- package/runtime/dist/src/executors/codex/turn-projection.js +12 -17
- package/runtime/dist/src/executors/codex/windows-guardian.js +4 -6
- package/runtime/dist/src/executors/coding/intake.js +12 -7
- package/runtime/dist/src/executors/computer-backend.js +18 -10
- package/runtime/dist/src/executors/computer-config.js +32 -0
- package/runtime/dist/src/executors/computer-device.js +68 -16
- package/runtime/dist/src/executors/computer-worker.js +18 -6
- package/runtime/dist/src/executors/computer.js +29 -56
- package/runtime/dist/src/executors/device-lock.js +14 -5
- package/runtime/dist/src/executors/gui-execution.js +2 -0
- package/runtime/dist/src/executors/index.js +0 -1
- package/runtime/dist/src/executors/mobile.js +9 -8
- package/runtime/dist/src/executors/native-process.js +4 -0
- package/runtime/dist/src/executors/search.js +3 -5
- package/runtime/dist/src/executors/task-resources.js +21 -0
- package/runtime/dist/src/executors/watcher.js +2 -4
- package/runtime/dist/src/experience/host.js +179 -0
- package/runtime/dist/src/index.js +2 -0
- package/runtime/dist/src/knowledge/assembly.js +3 -4
- package/runtime/dist/src/knowledge/embeddings.js +50 -34
- package/runtime/dist/src/knowledge/service.js +1 -0
- package/runtime/dist/src/knowledge/store-client.js +1 -6
- package/runtime/dist/src/knowledge/store-worker.js +1 -3
- package/runtime/dist/src/mem0/resource.js +25 -0
- package/runtime/dist/src/mem0/store-worker.js +234 -21
- package/runtime/dist/src/memory/consumer.js +31 -0
- package/runtime/dist/src/memory/engine-worker.js +210 -0
- package/runtime/dist/src/memory/entry.js +8 -1
- package/runtime/dist/src/memory/explicit-memory.js +20 -0
- package/runtime/dist/src/memory/factory.js +30 -15
- package/runtime/dist/src/memory/grounded-voicemem.js +10 -0
- package/runtime/dist/src/memory/ledger-recall-engine.js +86 -0
- package/runtime/dist/src/memory/prerecall-port.js +27 -0
- package/runtime/dist/src/memory/prerecall.js +1 -1
- package/runtime/dist/src/memory/production-engine.js +151 -0
- package/runtime/dist/src/memory/provenance.js +1 -0
- package/runtime/dist/src/memory/remote-personal-memory.js +3 -1
- package/runtime/dist/src/memory/retrieval.js +107 -22
- package/runtime/dist/src/memory/sensitivity.js +6 -2
- package/runtime/dist/src/memory/source-retrieval.js +11 -0
- package/runtime/dist/src/memory/tool-capabilities.js +46 -0
- package/runtime/dist/src/memory/voicemem-sdk/LICENSE +202 -0
- package/runtime/dist/src/memory/voicemem-sdk/NOTICE.md +97 -0
- package/runtime/dist/src/memory/voicemem-sdk/PATCH-NOTICE.md +23 -0
- package/runtime/dist/src/memory/voicemem-sdk/archive.js +12 -0
- package/runtime/dist/src/memory/voicemem-sdk/audio.js +111 -0
- package/runtime/dist/src/memory/voicemem-sdk/barge-in.js +59 -0
- package/runtime/dist/src/memory/voicemem-sdk/checkpoint.js +56 -0
- package/runtime/dist/src/memory/voicemem-sdk/cleanup.js +139 -0
- package/runtime/dist/src/memory/voicemem-sdk/dashscope-asr.js +254 -0
- package/runtime/dist/src/memory/voicemem-sdk/dashscope-tts.js +247 -0
- package/runtime/dist/src/memory/voicemem-sdk/evaluation.js +330 -0
- package/runtime/dist/src/memory/voicemem-sdk/extraction.js +220 -0
- package/runtime/dist/src/memory/voicemem-sdk/finetune-data.js +115 -0
- package/runtime/dist/src/memory/voicemem-sdk/finetune.js +170 -0
- package/runtime/dist/src/memory/voicemem-sdk/grounded-reply-preferences.js +81 -0
- package/runtime/dist/src/memory/voicemem-sdk/index.js +22 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-embedding.js +164 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-runtime.js +53 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-speaker.js +240 -0
- package/runtime/dist/src/memory/voicemem-sdk/memory.js +767 -0
- package/runtime/dist/src/memory/voicemem-sdk/model-json.js +14 -0
- package/runtime/dist/src/memory/voicemem-sdk/personamem.js +209 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/addenda.js +215 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/additive-extraction.js +478 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/index.js +32 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/update-memory.js +152 -0
- package/runtime/dist/src/memory/voicemem-sdk/providers.js +325 -0
- package/runtime/dist/src/memory/voicemem-sdk/ranking.js +65 -0
- package/runtime/dist/src/memory/voicemem-sdk/reaction.js +33 -0
- package/runtime/dist/src/memory/voicemem-sdk/realtime.js +215 -0
- package/runtime/dist/src/memory/voicemem-sdk/reply.js +68 -0
- package/runtime/dist/src/memory/voicemem-sdk/routing.js +209 -0
- package/runtime/dist/src/memory/voicemem-sdk/slots.js +61 -0
- package/runtime/dist/src/memory/voicemem-sdk/speaker-bindings.js +120 -0
- package/runtime/dist/src/memory/voicemem-sdk/speaker-profiles.js +327 -0
- package/runtime/dist/src/memory/voicemem-sdk/store.js +577 -0
- package/runtime/dist/src/memory/voicemem-sdk/stream.js +317 -0
- package/runtime/dist/src/memory/voicemem-sdk/subgraph.js +113 -0
- package/runtime/dist/src/memory/voicemem-sdk/summaries.js +56 -0
- package/runtime/dist/src/memory/voicemem-sdk/time.js +157 -0
- package/runtime/dist/src/memory/voicemem-sdk/types.js +2 -0
- package/runtime/dist/src/memory-ledger/store-client.js +235 -37
- package/runtime/dist/src/memory-ledger/store-worker.js +8 -5
- package/runtime/dist/src/memory-ledger/store.js +91 -1
- package/runtime/dist/src/memory-substrate/consolidation.js +23 -7
- package/runtime/dist/src/memory-substrate/diary.js +27 -0
- package/runtime/dist/src/memory-substrate/engine-outbox.js +107 -0
- package/runtime/dist/src/memory-substrate/explicit-memory.js +112 -0
- package/runtime/dist/src/memory-substrate/fact-fidelity.js +68 -0
- package/runtime/dist/src/memory-substrate/feishu-consent.js +41 -0
- package/runtime/dist/src/memory-substrate/file-authority.js +29 -6
- package/runtime/dist/src/memory-substrate/life-operations.js +35 -9
- package/runtime/dist/src/memory-substrate/markdown-repository.js +271 -65
- package/runtime/dist/src/memory-substrate/memory-documents.js +96 -0
- package/runtime/dist/src/memory-substrate/migration.js +2 -0
- package/runtime/dist/src/memory-substrate/purge.js +12 -2
- package/runtime/dist/src/memory-substrate/resource.js +514 -129
- package/runtime/dist/src/memory-substrate/retrieval.js +8 -5
- package/runtime/dist/src/memory-substrate/source-operations.js +9 -1
- package/runtime/dist/src/memory-substrate/source-processing.js +436 -40
- package/runtime/dist/src/memory-substrate/source-retrieval.js +28 -0
- package/runtime/dist/src/memory-substrate/source-state.js +8 -0
- package/runtime/dist/src/memory-substrate/space-source-input.js +90 -0
- package/runtime/dist/src/memory-substrate/store.js +125 -23
- package/runtime/dist/src/model/goal-checkin-writer.js +72 -0
- package/runtime/dist/src/model/goal-writer.js +80 -0
- package/runtime/dist/src/model/jev-client.js +24 -13
- package/runtime/dist/src/model/model-adapters.js +2 -3
- package/runtime/dist/src/model/model-catalog.js +80 -0
- package/runtime/dist/src/model/model-gateway.js +47 -18
- package/runtime/dist/src/model/model-purpose.js +3 -4
- package/runtime/dist/src/model/personal-writer.js +536 -44
- package/runtime/dist/src/model/proactivity.js +50 -6
- package/runtime/dist/src/model/responses-model-gateway.js +59 -0
- package/runtime/dist/src/model/task-verifier.js +3 -3
- package/runtime/dist/src/model/timeline-anchors.js +77 -0
- package/runtime/dist/src/model/timeline-perspective.js +13 -0
- package/runtime/dist/src/model/timeline-selection.js +182 -0
- package/runtime/dist/src/model/understanding-writer.js +27 -0
- package/runtime/dist/src/model/vision-capability.js +3 -1
- package/runtime/dist/src/model/workbench-writer.js +96 -0
- package/runtime/dist/src/news/feeds.js +6 -10
- package/runtime/dist/src/news/interests.js +23 -0
- package/runtime/dist/src/news/service.js +87 -31
- package/runtime/dist/src/news/sources.json +116 -0
- package/runtime/dist/src/notifications/adapters/space-relay.js +4 -0
- package/runtime/dist/src/notifications/content.js +41 -0
- package/runtime/dist/src/notifications/contracts.js +4 -2
- package/runtime/dist/src/notifications/feed.js +6 -2
- package/runtime/dist/src/notifications/service.js +27 -14
- package/runtime/dist/src/notifications/store.js +3 -1
- package/runtime/dist/src/personal-agent/app-context.js +39 -4
- package/runtime/dist/src/personal-agent/chat-failure.js +37 -0
- package/runtime/dist/src/personal-agent/computer-use/contract.js +42 -0
- package/runtime/dist/src/personal-agent/computer-use/session.js +280 -0
- package/runtime/dist/src/personal-agent/computer-use/skill.js +18 -0
- package/runtime/dist/src/personal-agent/computer-use/tools.js +15 -0
- package/runtime/dist/src/personal-agent/context-candidates.js +9 -13
- package/runtime/dist/src/personal-agent/context-dependencies.js +28 -0
- package/runtime/dist/src/personal-agent/contracts.js +24 -4
- package/runtime/dist/src/personal-agent/conversation-runtime.js +440 -42
- package/runtime/dist/src/personal-agent/conversation-tool-bridge.js +97 -0
- package/runtime/dist/src/personal-agent/conversation-tool-policy.js +22 -0
- package/runtime/dist/src/personal-agent/conversations.js +71 -15
- package/runtime/dist/src/personal-agent/daily-brief.js +5 -0
- package/runtime/dist/src/personal-agent/daily-workbench.js +558 -0
- package/runtime/dist/src/personal-agent/discovery-window.js +36 -0
- package/runtime/dist/src/personal-agent/goal-checkin.js +53 -0
- package/runtime/dist/src/personal-agent/host.js +2379 -223
- package/runtime/dist/src/personal-agent/identity-context.js +33 -0
- package/runtime/dist/src/personal-agent/life.js +129 -11
- package/runtime/dist/src/personal-agent/local-shell.js +181 -0
- package/runtime/dist/src/personal-agent/local-tools.js +234 -0
- package/runtime/dist/src/personal-agent/preferred-name-sync.js +35 -0
- package/runtime/dist/src/personal-agent/profile-warmup.js +100 -39
- package/runtime/dist/src/personal-agent/project-digests.js +7 -3
- package/runtime/dist/src/personal-agent/project-history.js +36 -0
- package/runtime/dist/src/personal-agent/reading-copies.js +183 -0
- package/runtime/dist/src/personal-agent/scheduled-tasks.js +50 -13
- package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +26 -10
- package/runtime/dist/src/personal-agent/source-processing-agent.js +239 -17
- package/runtime/dist/src/personal-agent/sources.js +9 -1
- package/runtime/dist/src/personal-agent/store.js +124 -14
- package/runtime/dist/src/personal-agent/task-loop.js +3 -0
- package/runtime/dist/src/personal-agent/tasks.js +16 -4
- package/runtime/dist/src/personal-agent/timeline-brief.js +462 -0
- package/runtime/dist/src/personal-agent/timeline-cache.js +191 -0
- package/runtime/dist/src/personal-agent/timeline-cluster.js +30 -0
- package/runtime/dist/src/personal-agent/timeline-inputs.js +47 -0
- package/runtime/dist/src/personal-agent/timeline-time.js +60 -0
- package/runtime/dist/src/personal-agent/understanding-products.js +49 -0
- package/runtime/dist/src/personal-agent/understanding.js +7 -22
- package/runtime/dist/src/personal-agent/workbench-context.js +17 -21
- package/runtime/dist/src/personal-agent/workbench-copy.js +124 -0
- package/runtime/dist/src/personal-agent/workbench-evidence.js +77 -0
- package/runtime/dist/src/personal-agent/workbench-instructions.js +21 -0
- package/runtime/dist/src/personal-agent/workbench-runtime.js +1006 -0
- package/runtime/dist/src/personal-agent/workbench-shell-class.js +304 -0
- package/runtime/dist/src/personal-agent/workbench-store.js +292 -0
- package/runtime/dist/src/personal-agent/workbench-temporal.js +66 -0
- package/runtime/dist/src/projects/project-native-resource.js +10 -8
- package/runtime/dist/src/projects/project-store.js +36 -4
- package/runtime/dist/src/realtime/bridge.js +77 -8
- package/runtime/dist/src/realtime/capabilities.js +19 -0
- package/runtime/dist/src/realtime/cascaded/adapter.js +180 -40
- package/runtime/dist/src/realtime/cascaded/ark-llm.js +150 -24
- package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +243 -83
- package/runtime/dist/src/realtime/cascaded/llm-stream-limits.js +18 -0
- package/runtime/dist/src/realtime/cascaded/llm.js +96 -0
- package/runtime/dist/src/realtime/cascaded/openai-compatible-speech.js +251 -0
- package/runtime/dist/src/realtime/cascaded/provider.js +8 -0
- package/runtime/dist/src/realtime/evidence.js +1 -1
- package/runtime/dist/src/realtime/frontend-instructions.js +76 -55
- package/runtime/dist/src/realtime/gemini.js +14 -3
- package/runtime/dist/src/realtime/host-delivery.js +37 -4
- package/runtime/dist/src/realtime/protocol.js +18 -3
- package/runtime/dist/src/realtime/provider-projection.js +4 -1
- package/runtime/dist/src/realtime/provider-session.js +73 -16
- package/runtime/dist/src/realtime/qwen-transport.js +35 -4
- package/runtime/dist/src/realtime/qwen.js +144 -9
- package/runtime/dist/src/realtime/service-state.js +0 -1
- package/runtime/dist/src/realtime/service.js +93 -7
- package/runtime/dist/src/realtime/session.js +39 -32
- package/runtime/dist/src/realtime/sglang-native.js +214 -0
- package/runtime/dist/src/realtime/system-prompts.en.js +14 -2
- package/runtime/dist/src/realtime/telemetry.js +6 -3
- package/runtime/dist/src/realtime/tool-continuations.js +84 -7
- package/runtime/dist/src/realtime/transport.js +17 -0
- package/runtime/dist/src/realtime/usage.js +33 -17
- package/runtime/dist/src/realtime/volcengine/ark.js +40 -15
- package/runtime/dist/src/realtime/volcengine/asr.js +2 -1
- package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +1 -7
- package/runtime/dist/src/realtime/volcengine/tts.js +2 -1
- package/runtime/dist/src/server/aoq-chat-server.js +1 -1
- package/runtime/dist/src/server/client-server.js +21 -0
- package/runtime/dist/src/server-entry.js +3 -0
- package/runtime/dist/src/space-host/admin-socket.js +115 -0
- package/runtime/dist/src/space-host/audio-owner.js +44 -0
- package/runtime/dist/src/space-host/cli.js +195 -0
- package/runtime/dist/src/space-host/config.js +247 -0
- package/runtime/dist/src/space-host/context-input.js +12 -0
- package/runtime/dist/src/space-host/contracts.js +10 -0
- package/runtime/dist/src/space-host/host-admin.js +114 -0
- package/runtime/dist/src/space-host/key-delivery.js +28 -0
- package/runtime/dist/src/space-host/mobile-tools.js +9 -0
- package/runtime/dist/src/space-host/model-settings.js +213 -0
- package/runtime/dist/src/space-host/projection.js +37 -0
- package/runtime/dist/src/space-host/push.js +137 -0
- package/runtime/dist/src/space-host/relay-transport.js +55 -0
- package/runtime/dist/src/space-host/service.js +841 -0
- package/runtime/dist/src/space-host/voice-crypto.js +240 -0
- package/runtime/dist/src/space-host/voice.js +600 -0
- package/runtime/dist/src/space-host/windows-secret-key.js +82 -0
- package/runtime/dist/src/storage/private-database.js +7 -10
- package/runtime/dist/src/text/unicode-normalize.js +5 -1
- package/runtime/dist/src/understanding/candidates.js +8 -10
- package/runtime/dist/src/understanding/fixture.js +1 -1
- package/runtime/dist/src/understanding/pipeline.js +4 -4
- package/runtime/dist/src/usage/context.js +23 -0
- package/runtime/dist/src/usage/index.js +4 -0
- package/runtime/dist/src/usage/ledger-worker.js +90 -0
- package/runtime/dist/src/usage/ledger.js +74 -0
- package/runtime/dist/src/usage/model-call.js +63 -0
- package/runtime/dist/src/usage/pricing.js +68 -0
- package/runtime/dist/src/usage/summary.js +69 -0
- package/runtime/dist/src/voicemem/store-client.js +104 -21
- package/runtime/dist/src/voicemem/store-worker.js +5 -8
- package/runtime/dist/src/voicemem/versioned-memory.js +1 -1
- package/src/command.mjs +8 -1
- package/runtime/dist/src/executors/autoglm.js +0 -376
|
@@ -0,0 +1,600 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { AUDIO_PREFIX_BYTES, decodeAudio, decodeControl, deriveCallKeys, encodeAudio, encodeControl, FRAME_AUDIO, FRAME_CONTROL, FRAME_HEADER_BYTES, FRAME_KEEPALIVE, FRAME_TAG_BYTES, FrameReceiver, FrameSender, generateEphemeral, startHash } from './voice-crypto.js';
|
|
4
|
+
export const VOICE_CODEC = 'pcm16', VOICE_FRAME_MS = 40;
|
|
5
|
+
/** 40 ms of 24 kHz mono PCM16. */
|
|
6
|
+
export const DOWNLINK_PACKET_BYTES = 1920;
|
|
7
|
+
const DOWNLINK_BYTES_PER_MS = 48;
|
|
8
|
+
/** Uplink is 16 kHz mono PCM16. The mic backlog toward the provider is bounded (§5). */
|
|
9
|
+
const UPLINK_BYTES_PER_MS = 32;
|
|
10
|
+
/** Largest sealed audio frame either direction sends at 40 ms (§2, §3): a relay must carry it. */
|
|
11
|
+
export const VOICE_MAX_AUDIO_FRAME_BYTES = FRAME_HEADER_BYTES + AUDIO_PREFIX_BYTES + Math.max(DOWNLINK_PACKET_BYTES, UPLINK_BYTES_PER_MS * VOICE_FRAME_MS) + FRAME_TAG_BYTES;
|
|
12
|
+
export const UPLINK_MAX_QUEUED_MS = 500, UPLINK_MAX_QUEUED_FRAMES = 16;
|
|
13
|
+
export const VOICE_CAPABILITY = 'voice.v1';
|
|
14
|
+
/** Playback receipts waiting behind a slow one (e.g. playback.stopped awaiting provider cancellation). */
|
|
15
|
+
export const VOICE_MAX_PENDING_RECEIPTS = 16;
|
|
16
|
+
const RECEIPT_TYPES = new Set(['playback.started', 'playback.done', 'playback.cleared', 'playback.stopped']);
|
|
17
|
+
/** Best-effort sends: a lost keepalive, clear or goodbye is covered by leases, deadlines and relay teardown. */
|
|
18
|
+
const ignore = () => undefined;
|
|
19
|
+
const b64 = z.string().regex(/^[A-Za-z0-9_-]{43}$/);
|
|
20
|
+
export const voiceStartSchema = z.object({
|
|
21
|
+
conversation_id: z.string().min(1).max(128), voice_mode: z.string().max(32).optional(), eph: b64, nonce: b64,
|
|
22
|
+
offers: z.object({ codecs: z.array(z.string().max(32)).min(1).max(8), frame_ms: z.array(z.number().int().positive().max(1000)).min(1).max(8) }).strict(),
|
|
23
|
+
deadline: z.number().int().nonnegative(),
|
|
24
|
+
}).strict();
|
|
25
|
+
export const voiceStopSchema = z.object({ op_id: z.string().min(1).max(128) }).strict();
|
|
26
|
+
/** Authorization order from §4: policy (with owner rules), chat-only conversation, chat voice mode. */
|
|
27
|
+
export function authorizeVoice(input) {
|
|
28
|
+
if (input.policy === 'off')
|
|
29
|
+
throw Error('voice_disabled');
|
|
30
|
+
if (input.policy === 'owner') {
|
|
31
|
+
if (input.owner === undefined)
|
|
32
|
+
throw Error('owner_unassigned');
|
|
33
|
+
if (input.owner !== input.sender)
|
|
34
|
+
throw Error('owner_required');
|
|
35
|
+
}
|
|
36
|
+
input.requireChat(input.conversationId);
|
|
37
|
+
if (input.voiceMode !== undefined && input.voiceMode !== 'chat')
|
|
38
|
+
throw Error('voice_mode_unavailable');
|
|
39
|
+
}
|
|
40
|
+
export class SpaceVoiceCall {
|
|
41
|
+
controller;
|
|
42
|
+
device;
|
|
43
|
+
opId;
|
|
44
|
+
conversationId;
|
|
45
|
+
voiceMode;
|
|
46
|
+
session;
|
|
47
|
+
hash;
|
|
48
|
+
endReason;
|
|
49
|
+
state = 'joining';
|
|
50
|
+
started;
|
|
51
|
+
#socket;
|
|
52
|
+
#sender;
|
|
53
|
+
#receiver;
|
|
54
|
+
#lease;
|
|
55
|
+
#voiceStarted = false;
|
|
56
|
+
#remoteSet = false;
|
|
57
|
+
#timers = new Set();
|
|
58
|
+
#lastHeard;
|
|
59
|
+
#queue = [];
|
|
60
|
+
#queuedMs = 0;
|
|
61
|
+
#budgetMs;
|
|
62
|
+
#budgetAt;
|
|
63
|
+
#pumping = false;
|
|
64
|
+
#pace;
|
|
65
|
+
#gens = new Map();
|
|
66
|
+
#nextGen = 0;
|
|
67
|
+
#startSent = new Set();
|
|
68
|
+
#uplink = [];
|
|
69
|
+
#uplinkBytes = 0;
|
|
70
|
+
#uplinkPump;
|
|
71
|
+
#starting;
|
|
72
|
+
#activating = false;
|
|
73
|
+
/** Only playback receipts are ordered here; audio, keepalive and end never wait behind it. Bounded. */
|
|
74
|
+
#receipts = Promise.resolve();
|
|
75
|
+
#pendingReceipts = 0;
|
|
76
|
+
#ending;
|
|
77
|
+
#endSignal;
|
|
78
|
+
#signalEnd;
|
|
79
|
+
constructor(controller, device, opId, conversationId, voiceMode, session, hash, keys, endReason = {}) {
|
|
80
|
+
this.controller = controller;
|
|
81
|
+
this.device = device;
|
|
82
|
+
this.opId = opId;
|
|
83
|
+
this.conversationId = conversationId;
|
|
84
|
+
this.voiceMode = voiceMode;
|
|
85
|
+
this.session = session;
|
|
86
|
+
this.hash = hash;
|
|
87
|
+
this.endReason = endReason;
|
|
88
|
+
this.#endSignal = new Promise(resolve => { this.#signalEnd = resolve; });
|
|
89
|
+
this.#sender = new FrameSender(keys.down);
|
|
90
|
+
this.#receiver = new FrameReceiver(keys.up);
|
|
91
|
+
keys.up.fill(0);
|
|
92
|
+
keys.down.fill(0);
|
|
93
|
+
this.started = controller.now();
|
|
94
|
+
this.#lastHeard = this.started;
|
|
95
|
+
this.#budgetMs = controller.timing.leadMs;
|
|
96
|
+
this.#budgetAt = this.started;
|
|
97
|
+
}
|
|
98
|
+
set lease(value) { this.#lease = value; }
|
|
99
|
+
get lease() { return this.#lease; }
|
|
100
|
+
get voiceStarted() { return this.#voiceStarted; }
|
|
101
|
+
/**
|
|
102
|
+
* Reserve the relay session and join the Host leg. The accept is published only after this
|
|
103
|
+
* resolves, so a fast Client never meets an unknown session (§1). Throws the end reason.
|
|
104
|
+
*/
|
|
105
|
+
async prepare() {
|
|
106
|
+
const c = this.controller;
|
|
107
|
+
this.#timer(() => { if (this.state === 'joining')
|
|
108
|
+
void this.end('join_timeout'); }, c.timing.joinTimeoutMs);
|
|
109
|
+
const ended = this.#endSignal.then(() => undefined);
|
|
110
|
+
try {
|
|
111
|
+
await Promise.race([c.options.media.reserve(this.session, this.device, c.timing.maxSessionMinutes * 60_000), ended]);
|
|
112
|
+
if (this.state !== 'joining')
|
|
113
|
+
throw Error(this.endReason.value ?? 'voice_ended');
|
|
114
|
+
const connecting = c.options.media.connect(this.session);
|
|
115
|
+
const socket = await Promise.race([connecting, ended]);
|
|
116
|
+
if (!socket || this.state !== 'joining') {
|
|
117
|
+
void connecting.then(late => { late.close(); }, ignore);
|
|
118
|
+
throw Error(this.endReason.value ?? 'voice_ended');
|
|
119
|
+
}
|
|
120
|
+
this.#socket = socket;
|
|
121
|
+
socket.onClose(() => { void this.end('transport_lost'); });
|
|
122
|
+
socket.onFrame(frame => { try {
|
|
123
|
+
this.#receive(frame);
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
c.options.onError?.(error);
|
|
127
|
+
void this.end('protocol_error');
|
|
128
|
+
} });
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
if (this.state === 'joining') {
|
|
132
|
+
c.options.onError?.(error);
|
|
133
|
+
await this.end('relay_media_unavailable');
|
|
134
|
+
}
|
|
135
|
+
throw Error(this.endReason.value ?? 'relay_media_unavailable');
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/** Cheap per-frame work runs synchronously on arrival, in order: open, liveness, uplink, end. */
|
|
139
|
+
#receive(frame) {
|
|
140
|
+
if (this.state === 'ending' || this.state === 'ended')
|
|
141
|
+
return;
|
|
142
|
+
let opened;
|
|
143
|
+
try {
|
|
144
|
+
opened = this.#receiver.open(frame);
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
if (error instanceof Error && error.message === 'voice_crypto_failed')
|
|
148
|
+
void this.end('voice_crypto_failed');
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (!opened)
|
|
152
|
+
return;
|
|
153
|
+
this.#lastHeard = this.controller.now();
|
|
154
|
+
if (this.state === 'joining') {
|
|
155
|
+
if (opened.type !== FRAME_CONTROL)
|
|
156
|
+
return;
|
|
157
|
+
const body = decodeControl(opened.plaintext);
|
|
158
|
+
if (body.type === 'end') {
|
|
159
|
+
void this.end('stopped');
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
if (body.type !== 'ready' || body.start_hash !== this.hash.toString('base64url')) {
|
|
163
|
+
void this.end('protocol_error');
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
// The Host's ready is the Client's go signal: it is sent only once the provider is up.
|
|
167
|
+
// Exactly one activation; a stuck startVoice cannot hold later frames.
|
|
168
|
+
if (this.#activating)
|
|
169
|
+
return;
|
|
170
|
+
this.#activating = true;
|
|
171
|
+
void this.#activate().catch(error => { this.controller.options.onError?.(error); void this.end('protocol_error'); });
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (opened.type === FRAME_KEEPALIVE)
|
|
175
|
+
return;
|
|
176
|
+
if (opened.type === FRAME_AUDIO) {
|
|
177
|
+
if (this.state !== 'active')
|
|
178
|
+
return;
|
|
179
|
+
const pcm = Buffer.from(decodeAudio(opened.plaintext).pcm);
|
|
180
|
+
this.#uplink.push(pcm);
|
|
181
|
+
this.#uplinkBytes += pcm.length;
|
|
182
|
+
// Realtime: shed the oldest mic audio rather than build latency behind a slow provider.
|
|
183
|
+
while (this.#uplink.length > UPLINK_MAX_QUEUED_FRAMES || this.#uplinkBytes > UPLINK_MAX_QUEUED_MS * UPLINK_BYTES_PER_MS) {
|
|
184
|
+
this.#uplinkBytes -= this.#uplink.shift().length;
|
|
185
|
+
}
|
|
186
|
+
this.#uplinkPump ??= this.#pumpUplink().finally(() => { this.#uplinkPump = undefined; });
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const body = decodeControl(opened.plaintext);
|
|
190
|
+
if (body.type === 'end') {
|
|
191
|
+
void this.end('stopped');
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
// Anything but a playback receipt (a duplicate ready, unknown types) is ignored here and takes no slot.
|
|
195
|
+
if (typeof body.type !== 'string' || !RECEIPT_TYPES.has(body.type))
|
|
196
|
+
return;
|
|
197
|
+
// Receipts stay ordered (a slow playback.stopped must land before a later cleared), but bounded.
|
|
198
|
+
if (this.#pendingReceipts >= VOICE_MAX_PENDING_RECEIPTS) {
|
|
199
|
+
void this.end('protocol_error');
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
this.#pendingReceipts++;
|
|
203
|
+
this.#receipts = this.#receipts.then(() => this.#control(body)).catch(error => { this.controller.options.onError?.(error); void this.end('protocol_error'); }).finally(() => { this.#pendingReceipts--; });
|
|
204
|
+
}
|
|
205
|
+
get uplinkQueuedMs() { return this.#uplinkBytes / UPLINK_BYTES_PER_MS; }
|
|
206
|
+
async #pumpUplink() {
|
|
207
|
+
const c = this.controller, host = c.options.host;
|
|
208
|
+
while (this.state === 'active' && this.#uplink.length) {
|
|
209
|
+
const pcm = this.#uplink.shift();
|
|
210
|
+
this.#uplinkBytes -= pcm.length;
|
|
211
|
+
let stalled;
|
|
212
|
+
const stall = new Promise(resolve => { stalled = setTimeout(() => resolve('stalled'), c.timing.providerStallMs); stalled.unref?.(); });
|
|
213
|
+
try {
|
|
214
|
+
const sent = host.sendAudio(this.conversationId, pcm).then(() => 'sent', (error) => { c.options.onError?.(error); return 'sent'; });
|
|
215
|
+
if (await Promise.race([sent, stall]) === 'stalled') {
|
|
216
|
+
void this.end('provider_stalled');
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
finally {
|
|
221
|
+
clearTimeout(stalled);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/** Only after an authenticated ready does provider work start (§4 step 4). */
|
|
226
|
+
async #activate() {
|
|
227
|
+
const host = this.controller.options.host;
|
|
228
|
+
if (this.state !== 'joining' || this.#lease === undefined || !host.arbiter.owns(this.#lease))
|
|
229
|
+
return;
|
|
230
|
+
try {
|
|
231
|
+
// Membership, policy, chat-only and mode may have changed during the join: re-check at admission.
|
|
232
|
+
this.controller.authorize(this);
|
|
233
|
+
host.setRemoteVoice(this.conversationId);
|
|
234
|
+
this.#remoteSet = true;
|
|
235
|
+
this.#starting = host.startVoice(this.conversationId).then(() => { this.#voiceStarted = true; });
|
|
236
|
+
await this.#starting;
|
|
237
|
+
}
|
|
238
|
+
catch (error) {
|
|
239
|
+
this.controller.options.onError?.(error);
|
|
240
|
+
await this.end(error instanceof Error && /^[a-z_]{1,64}$/.test(error.message) ? error.message : 'voice_unavailable');
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (this.state !== 'joining') {
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
this.state = 'active';
|
|
247
|
+
try {
|
|
248
|
+
await this.#send(FRAME_CONTROL, encodeControl({ type: 'ready', start_hash: this.hash.toString('base64url') }));
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
await this.end('transport_lost');
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
const keepalive = () => {
|
|
255
|
+
if (this.state !== 'active')
|
|
256
|
+
return;
|
|
257
|
+
void this.#send(FRAME_KEEPALIVE, new Uint8Array(0)).catch(ignore);
|
|
258
|
+
if (this.controller.now() - this.#lastHeard >= this.controller.timing.idleMs) {
|
|
259
|
+
void this.end('idle');
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
this.#timer(keepalive, this.controller.timing.keepaliveMs);
|
|
263
|
+
};
|
|
264
|
+
this.#timer(keepalive, this.controller.timing.keepaliveMs);
|
|
265
|
+
this.#timer(() => { void this.end('max_duration'); }, this.controller.timing.maxSessionMinutes * 60_000);
|
|
266
|
+
}
|
|
267
|
+
async #control(body) {
|
|
268
|
+
if (this.state !== 'active')
|
|
269
|
+
return;
|
|
270
|
+
const receipts = this.controller.options.host.receipts();
|
|
271
|
+
const utterance = typeof body.utterance_id === 'string' ? body.utterance_id : undefined, epoch = typeof body.generation_epoch === 'number' ? body.generation_epoch : undefined;
|
|
272
|
+
if (!receipts || utterance === undefined || epoch === undefined || ![...this.#gens.values()].some(g => g.utterance_id === utterance && g.generation_epoch === epoch))
|
|
273
|
+
return;
|
|
274
|
+
const played = typeof body.played_ms === 'number' && Number.isSafeInteger(body.played_ms) && body.played_ms >= 0 ? body.played_ms : null;
|
|
275
|
+
if (body.type === 'playback.started')
|
|
276
|
+
receipts.playbackStarted(utterance, epoch);
|
|
277
|
+
else if (body.type === 'playback.done')
|
|
278
|
+
receipts.playbackDone(utterance, epoch, played);
|
|
279
|
+
else if (body.type === 'playback.cleared')
|
|
280
|
+
receipts.playbackCleared(utterance, epoch, played);
|
|
281
|
+
// A loss fence (§3) is an interrupted playback truncated at the confirmed contiguous prefix.
|
|
282
|
+
else if (body.type === 'playback.stopped')
|
|
283
|
+
await receipts.playbackStopped(utterance, epoch, played);
|
|
284
|
+
}
|
|
285
|
+
// ---- downlink (SpaceVoiceBridge sink) ----
|
|
286
|
+
audioFrame(frame) {
|
|
287
|
+
if (this.state !== 'active')
|
|
288
|
+
return;
|
|
289
|
+
const key = `${frame.generation_epoch}:${frame.utterance_id}`;
|
|
290
|
+
let gen = this.#gens.get(key);
|
|
291
|
+
if (!gen) {
|
|
292
|
+
gen = { gen: this.#nextGen++ & 0xffff, utterance_id: frame.utterance_id, generation_epoch: frame.generation_epoch, nativeSeq: 0, sampleOffset: 0, fenced: false };
|
|
293
|
+
this.#gens.set(key, gen);
|
|
294
|
+
this.#startSent.delete(gen.gen);
|
|
295
|
+
while (this.#gens.size > 64) {
|
|
296
|
+
const oldest = this.#gens.keys().next().value;
|
|
297
|
+
this.#startSent.delete(this.#gens.get(oldest).gen);
|
|
298
|
+
this.#gens.delete(oldest);
|
|
299
|
+
}
|
|
300
|
+
this.#enqueue({ kind: 'control', gen: gen.gen, body: { type: 'playback.start', gen: gen.gen, utterance_id: gen.utterance_id, generation_epoch: gen.generation_epoch } });
|
|
301
|
+
}
|
|
302
|
+
if (gen.fenced)
|
|
303
|
+
return;
|
|
304
|
+
// Re-chunk Host frames (up to 64 KiB) into ≤40 ms packets with contiguous native sequence numbers.
|
|
305
|
+
for (let offset = 0; offset < frame.pcm.length; offset += DOWNLINK_PACKET_BYTES) {
|
|
306
|
+
const pcm = frame.pcm.subarray(offset, Math.min(frame.pcm.length, offset + DOWNLINK_PACKET_BYTES));
|
|
307
|
+
const plaintext = encodeAudio({ gen: gen.gen, nativeSeq: gen.nativeSeq++, sampleOffset: gen.sampleOffset, pcm });
|
|
308
|
+
gen.sampleOffset += pcm.length / 2;
|
|
309
|
+
const ms = pcm.length / DOWNLINK_BYTES_PER_MS;
|
|
310
|
+
this.#enqueue({ kind: 'audio', gen: gen.gen, plaintext, ms });
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
audioClear(utteranceId, generationEpoch) {
|
|
314
|
+
if (this.state !== 'active')
|
|
315
|
+
return;
|
|
316
|
+
const gen = this.#gens.get(`${generationEpoch}:${utteranceId}`);
|
|
317
|
+
if (gen) {
|
|
318
|
+
gen.fenced = true;
|
|
319
|
+
this.#drop(gen.gen);
|
|
320
|
+
// Dropped before playback.start left the Host: the Client never heard of it, so the Host
|
|
321
|
+
// records the clear itself (nothing was played) and sends nothing (§3).
|
|
322
|
+
if (!this.#startSent.has(gen.gen)) {
|
|
323
|
+
this.controller.options.host.receipts()?.playbackCleared(utteranceId, generationEpoch, 0);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
// A clear overtakes queued (unwritten) audio; bytes already written cannot be recalled (§5).
|
|
328
|
+
void this.#send(FRAME_CONTROL, encodeControl({ type: 'playback.clear', utterance_id: utteranceId, generation_epoch: generationEpoch })).catch(ignore);
|
|
329
|
+
}
|
|
330
|
+
audioTerminal(utteranceId, generationEpoch) {
|
|
331
|
+
if (this.state !== 'active')
|
|
332
|
+
return;
|
|
333
|
+
const gen = this.#gens.get(`${generationEpoch}:${utteranceId}`);
|
|
334
|
+
if (!gen || gen.fenced)
|
|
335
|
+
return;
|
|
336
|
+
// The relay may deliver control ahead of queued audio, so terminal names its end position:
|
|
337
|
+
// the Client finalizes only after the contiguous prefix up to it, else applies the loss fence (§3).
|
|
338
|
+
this.#enqueue({ kind: 'control', gen: gen.gen, body: { type: 'playback.terminal', utterance_id: utteranceId, generation_epoch: generationEpoch,
|
|
339
|
+
last_native_seq: gen.nativeSeq > 0 ? gen.nativeSeq - 1 : null, end_offset: gen.sampleOffset } });
|
|
340
|
+
}
|
|
341
|
+
audioAlert(utteranceId, generationEpoch) {
|
|
342
|
+
if (this.state !== 'active')
|
|
343
|
+
return;
|
|
344
|
+
void this.#send(FRAME_CONTROL, encodeControl({ type: 'playback.alert', utterance_id: utteranceId, generation_epoch: generationEpoch })).catch(ignore);
|
|
345
|
+
}
|
|
346
|
+
get queuedAudioMs() { return this.#queuedMs; }
|
|
347
|
+
#enqueue(item) {
|
|
348
|
+
if (item.kind === 'audio') {
|
|
349
|
+
this.#queuedMs += item.ms;
|
|
350
|
+
if (this.#queuedMs > this.controller.timing.maxQueuedAudioMs) {
|
|
351
|
+
void this.end('downlink_overflow');
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
this.#queue.push(item);
|
|
356
|
+
this.#schedule(0);
|
|
357
|
+
}
|
|
358
|
+
#drop(gen) { this.#queue = this.#queue.filter(item => { if (item.gen !== gen)
|
|
359
|
+
return true; if (item.kind === 'audio')
|
|
360
|
+
this.#queuedMs -= item.ms; return false; }); }
|
|
361
|
+
#schedule(delay) { if (this.#pace || this.#pumping)
|
|
362
|
+
return; this.#pace = setTimeout(() => { this.#pace = undefined; void this.#pump(); }, delay); this.#pace.unref?.(); }
|
|
363
|
+
/** ≤ paceFactor × realtime with ≤ leadMs lead: a token budget in milliseconds of audio. */
|
|
364
|
+
async #pump() {
|
|
365
|
+
if (this.state !== 'active' || this.#pumping)
|
|
366
|
+
return;
|
|
367
|
+
this.#pumping = true;
|
|
368
|
+
try {
|
|
369
|
+
while (this.state === 'active' && this.#queue.length) {
|
|
370
|
+
const now = this.controller.now(), t = this.controller.timing;
|
|
371
|
+
this.#budgetMs = Math.min(t.leadMs, this.#budgetMs + (now - this.#budgetAt) * t.paceFactor);
|
|
372
|
+
this.#budgetAt = now;
|
|
373
|
+
const item = this.#queue[0];
|
|
374
|
+
if (item.kind === 'audio' && this.#budgetMs < item.ms)
|
|
375
|
+
break;
|
|
376
|
+
this.#queue.shift();
|
|
377
|
+
// Once shifted it is written (or the socket fails): the Client may now know this generation.
|
|
378
|
+
if (item.kind === 'control' && item.body.type === 'playback.start' && item.gen !== null)
|
|
379
|
+
this.#startSent.add(item.gen);
|
|
380
|
+
if (item.kind === 'audio') {
|
|
381
|
+
this.#budgetMs -= item.ms;
|
|
382
|
+
this.#queuedMs -= item.ms;
|
|
383
|
+
await this.#send(FRAME_AUDIO, item.plaintext);
|
|
384
|
+
}
|
|
385
|
+
else
|
|
386
|
+
await this.#send(FRAME_CONTROL, encodeControl(item.body));
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
catch {
|
|
390
|
+
void this.end('transport_lost');
|
|
391
|
+
}
|
|
392
|
+
finally {
|
|
393
|
+
this.#pumping = false;
|
|
394
|
+
}
|
|
395
|
+
if (this.state === 'active' && this.#queue.length)
|
|
396
|
+
this.#schedule(this.controller.timing.tickMs);
|
|
397
|
+
}
|
|
398
|
+
async #send(type, plaintext) {
|
|
399
|
+
const socket = this.#socket;
|
|
400
|
+
if (!socket)
|
|
401
|
+
throw Error('media_closed');
|
|
402
|
+
// The sequence number is consumed even if the write then fails.
|
|
403
|
+
const frame = this.#sender.seal(type, plaintext);
|
|
404
|
+
await socket.send(frame);
|
|
405
|
+
}
|
|
406
|
+
/** Fence first (state, queues, sink), then clean up provider, owner, socket and keys (§4 teardown). */
|
|
407
|
+
end(reason) {
|
|
408
|
+
if (this.#ending)
|
|
409
|
+
return this.#ending;
|
|
410
|
+
this.endReason.value = reason;
|
|
411
|
+
const wasActive = this.state === 'active';
|
|
412
|
+
this.state = 'ending';
|
|
413
|
+
this.#signalEnd();
|
|
414
|
+
this.#uplink = [];
|
|
415
|
+
this.#uplinkBytes = 0;
|
|
416
|
+
for (const timer of this.#timers)
|
|
417
|
+
clearTimeout(timer);
|
|
418
|
+
this.#timers.clear();
|
|
419
|
+
if (this.#pace)
|
|
420
|
+
clearTimeout(this.#pace);
|
|
421
|
+
this.#pace = undefined;
|
|
422
|
+
this.#queue = [];
|
|
423
|
+
this.#queuedMs = 0;
|
|
424
|
+
this.#ending = (async () => {
|
|
425
|
+
const c = this.controller, host = c.options.host;
|
|
426
|
+
if (this.#socket && wasActive)
|
|
427
|
+
await this.#send(FRAME_CONTROL, encodeControl({ type: 'voice.ended', reason })).catch(ignore);
|
|
428
|
+
// A start still in flight is awaited only briefly: a stuck startVoice must not hold the lease.
|
|
429
|
+
// These bounded teardown waits stay ref'd so an ending call finishes even when nothing else keeps the process alive.
|
|
430
|
+
// If it comes up later, the provider it started is stopped then.
|
|
431
|
+
if (this.#starting && !this.#voiceStarted) {
|
|
432
|
+
let timer;
|
|
433
|
+
const settled = await Promise.race([this.#starting.then(() => true, () => true), new Promise(resolve => { timer = setTimeout(() => resolve(false), c.timing.providerStallMs); })]);
|
|
434
|
+
clearTimeout(timer);
|
|
435
|
+
if (!settled) {
|
|
436
|
+
const conversation = this.conversationId;
|
|
437
|
+
void this.#starting.then(async () => {
|
|
438
|
+
// Stop it while the Host voice is still this conversation and no other call has itself
|
|
439
|
+
// started voice; a joining successor then finds voice clear. An owner that is not one of this
|
|
440
|
+
// controller's calls (the desktop, or a call under a controller re-created by pairing) is left alone.
|
|
441
|
+
if (host.voiceConversationId() === conversation && !c.voiceStartedByAnyCall() && (host.arbiter.current === null || c.ownsCurrentLease()))
|
|
442
|
+
await host.stopVoice(conversation);
|
|
443
|
+
}, ignore).catch(error => c.options.onError?.(error));
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
if (this.#voiceStarted && this.#lease !== undefined && (host.arbiter.owns(this.#lease) || host.arbiter.current === null)) {
|
|
447
|
+
// Never wait indefinitely on a stalled provider write.
|
|
448
|
+
if (this.#uplinkPump) {
|
|
449
|
+
let timer;
|
|
450
|
+
await Promise.race([this.#uplinkPump.catch(ignore), new Promise(resolve => { timer = setTimeout(resolve, c.timing.providerStallMs); })]);
|
|
451
|
+
clearTimeout(timer);
|
|
452
|
+
}
|
|
453
|
+
await host.stopVoice(this.conversationId).catch(error => c.options.onError?.(error));
|
|
454
|
+
}
|
|
455
|
+
if (this.#remoteSet)
|
|
456
|
+
host.setRemoteVoice(null);
|
|
457
|
+
if (this.#lease !== undefined)
|
|
458
|
+
host.arbiter.release(this.#lease);
|
|
459
|
+
try {
|
|
460
|
+
this.#socket?.close();
|
|
461
|
+
}
|
|
462
|
+
catch { /* closing an already-closed socket */ }
|
|
463
|
+
this.#sender.destroy();
|
|
464
|
+
this.#receiver.destroy();
|
|
465
|
+
this.state = 'ended';
|
|
466
|
+
c.forget(this);
|
|
467
|
+
await c.options.notify(this.device, { type: 'voice.ended', op_id: this.opId, session: this.session, reason }).catch(ignore);
|
|
468
|
+
})();
|
|
469
|
+
return this.#ending;
|
|
470
|
+
}
|
|
471
|
+
#timer(run, ms) { const timer = setTimeout(() => { this.#timers.delete(timer); run(); }, ms); timer.unref?.(); this.#timers.add(timer); }
|
|
472
|
+
}
|
|
473
|
+
export class SpaceVoiceController {
|
|
474
|
+
options;
|
|
475
|
+
timing;
|
|
476
|
+
#calls = new Map();
|
|
477
|
+
#media;
|
|
478
|
+
#closed = false;
|
|
479
|
+
#probedAt;
|
|
480
|
+
#probe;
|
|
481
|
+
constructor(options) {
|
|
482
|
+
this.options = options;
|
|
483
|
+
this.timing = { joinTimeoutMs: options.joinTimeoutMs ?? 15_000, idleMs: options.idleMs ?? 20_000, keepaliveMs: options.keepaliveMs ?? 5_000, leadMs: options.leadMs ?? 1_000,
|
|
484
|
+
paceFactor: options.paceFactor ?? 1.25, tickMs: options.tickMs ?? 20, maxSessionMinutes: options.maxSessionMinutes ?? 60, maxQueuedAudioMs: options.maxQueuedAudioMs ?? 120_000, providerStallMs: options.providerStallMs ?? 2_000, capabilityRetryMs: options.capabilityRetryMs ?? 30_000 };
|
|
485
|
+
}
|
|
486
|
+
now() { return this.options.now?.() ?? Date.now(); }
|
|
487
|
+
/** Capability hint for one recipient: only hides or shows the call button (§8). */
|
|
488
|
+
available(device) {
|
|
489
|
+
if (this.#closed || !this.#media?.codecs.includes(VOICE_CODEC))
|
|
490
|
+
return false;
|
|
491
|
+
const policy = this.options.policy(), owner = this.options.owner();
|
|
492
|
+
return policy === 'members' || policy === 'owner' && owner !== undefined && owner === device;
|
|
493
|
+
}
|
|
494
|
+
/** Single-flight: concurrent callers share one probe. */
|
|
495
|
+
refreshCapability() {
|
|
496
|
+
return this.#probe ??= this.#probeCapability().finally(() => { this.#probe = undefined; });
|
|
497
|
+
}
|
|
498
|
+
async #probeCapability() {
|
|
499
|
+
this.#probedAt = this.now();
|
|
500
|
+
let next;
|
|
501
|
+
try {
|
|
502
|
+
const media = (await this.options.media.capabilities()).media;
|
|
503
|
+
// pcm16 is advertised and admitted only on a relay that can carry its largest packet.
|
|
504
|
+
next = media && (media.maxFrameBytes ?? 0) >= VOICE_MAX_AUDIO_FRAME_BYTES ? media : null;
|
|
505
|
+
}
|
|
506
|
+
catch (error) {
|
|
507
|
+
// Only an authoritative answer (media:null, which also covers a 404) disables voice; a transient
|
|
508
|
+
// failure keeps the last known value and the next start asks again.
|
|
509
|
+
this.options.onError?.(error);
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
// Compare against the value actually replaced, at assignment time.
|
|
513
|
+
const previous = this.#media;
|
|
514
|
+
this.#media = next;
|
|
515
|
+
if (JSON.stringify(previous ?? null) !== JSON.stringify(next))
|
|
516
|
+
this.options.onAvailabilityChanged?.();
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Background recovery while media is not known to be available: at most one probe per
|
|
520
|
+
* capabilityRetryMs. A flip fires onAvailabilityChanged so the snapshot advertises voice.v1.
|
|
521
|
+
*/
|
|
522
|
+
async refreshIfUnavailable() {
|
|
523
|
+
if (this.#closed || this.#media?.codecs.includes(VOICE_CODEC))
|
|
524
|
+
return;
|
|
525
|
+
if (this.#probedAt !== undefined && this.now() - this.#probedAt < this.timing.capabilityRetryMs)
|
|
526
|
+
return;
|
|
527
|
+
await this.refreshCapability();
|
|
528
|
+
}
|
|
529
|
+
call(device) { return this.#calls.get(device); }
|
|
530
|
+
voiceStartedByAnyCall() { return [...this.#calls.values()].some(call => call.voiceStarted); }
|
|
531
|
+
/** True when the Host audio lease is held by one of this controller's own calls. */
|
|
532
|
+
ownsCurrentLease() { const device = this.options.host.arbiter.spaceDevice; const lease = device === undefined ? undefined : this.#calls.get(device)?.lease; return lease !== undefined && this.options.host.arbiter.owns(lease); }
|
|
533
|
+
/** Full §4 authorization for a call, used again at provider admission. Throws a stable code. */
|
|
534
|
+
authorize(call) {
|
|
535
|
+
if (this.#closed)
|
|
536
|
+
throw Error('voice_unavailable');
|
|
537
|
+
if (this.options.member && !this.options.member(call.device))
|
|
538
|
+
throw Error('sender_not_paired');
|
|
539
|
+
authorizeVoice({ policy: this.options.policy(), owner: this.options.owner(), sender: call.device, conversationId: call.conversationId, voiceMode: call.voiceMode, requireChat: id => this.options.host.requireChat(id) });
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* Authorize, reserve the owner slot and derive keys. `raw` is the exact decrypted intent the
|
|
543
|
+
* Client sealed; its canonical hash binds the accept. Throws a stable code on refusal.
|
|
544
|
+
*/
|
|
545
|
+
async begin(sender, raw, now = this.now()) {
|
|
546
|
+
if (this.#closed)
|
|
547
|
+
throw Error('voice_unavailable');
|
|
548
|
+
const parsed = voiceStartSchema.safeParse(raw.input);
|
|
549
|
+
if (!parsed.success || typeof raw.op_id !== 'string')
|
|
550
|
+
throw Error('invalid_voice_start');
|
|
551
|
+
const opId = raw.op_id, input = parsed.data;
|
|
552
|
+
if (typeof raw.expires_at !== 'number' || typeof raw.created_at !== 'number' || raw.expires_at - raw.created_at > 15_000 || input.deadline > raw.expires_at)
|
|
553
|
+
throw Error('voice_deadline_required');
|
|
554
|
+
if (raw.expires_at <= now)
|
|
555
|
+
throw Error('expired');
|
|
556
|
+
const host = this.options.host;
|
|
557
|
+
this.authorize({ device: sender, conversationId: input.conversation_id, voiceMode: input.voice_mode });
|
|
558
|
+
if (!input.offers.codecs.includes(VOICE_CODEC) || !input.offers.frame_ms.includes(VOICE_FRAME_MS))
|
|
559
|
+
throw Error('codec_unavailable');
|
|
560
|
+
// Ask the relay again whenever media is not known to be available: a relay may enable it later.
|
|
561
|
+
if (!this.#media?.codecs.includes(VOICE_CODEC))
|
|
562
|
+
await this.refreshCapability();
|
|
563
|
+
if (!this.#media?.codecs.includes(VOICE_CODEC))
|
|
564
|
+
throw Error('relay_media_unavailable');
|
|
565
|
+
return host.arbiter.serial(async () => {
|
|
566
|
+
// A device's second start replaces only its own call.
|
|
567
|
+
await this.#calls.get(sender)?.end('replaced');
|
|
568
|
+
if (host.arbiter.current || host.voiceConversationId() !== null)
|
|
569
|
+
throw Error('voice_active');
|
|
570
|
+
const own = generateEphemeral(), session = randomBytes(18).toString('base64url');
|
|
571
|
+
const hash = startHash({ start: raw, space: this.options.space, epoch: this.options.epoch, client: sender, host: this.options.hostDevice });
|
|
572
|
+
const keys = deriveCallKeys({ own, peer: input.eph, contentKey: this.options.contentKey, startHash: hash, ephC: input.eph, ephH: own.publicKey, session, codec: VOICE_CODEC, frameMs: VOICE_FRAME_MS });
|
|
573
|
+
const call = new SpaceVoiceCall(this, sender, opId, input.conversation_id, input.voice_mode, session, hash, keys);
|
|
574
|
+
call.lease = host.arbiter.claim(`space:${sender}`, reason => call.end(reason));
|
|
575
|
+
this.#calls.set(sender, call);
|
|
576
|
+
return { call, accept: { type: 'voice.accept', op_id: opId, start_hash: hash.toString('base64url'), session, eph: own.publicKey, selected: { codec: VOICE_CODEC, frame_ms: VOICE_FRAME_MS }, call_deadline: now + this.timing.maxSessionMinutes * 60_000 } };
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
/** voice.stop: ends the sender's call only if it is the one started by `opId`. */
|
|
580
|
+
async stop(sender, opId) { const call = this.#calls.get(sender); if (call?.opId !== opId)
|
|
581
|
+
return false; await call.end('stopped'); return true; }
|
|
582
|
+
/** Policy or owner changes re-evaluate every active call. */
|
|
583
|
+
async policyChanged() {
|
|
584
|
+
const policy = this.options.policy(), owner = this.options.owner();
|
|
585
|
+
await Promise.all([...this.#calls.values()].filter(call => policy === 'off' || policy === 'owner' && owner !== call.device).map(call => call.end('policy_changed')));
|
|
586
|
+
this.options.onAvailabilityChanged?.();
|
|
587
|
+
}
|
|
588
|
+
async closeAll(reason) { this.#closed = true; await Promise.all([...this.#calls.values()].map(call => call.end(reason))); }
|
|
589
|
+
forget(call) { if (this.#calls.get(call.device) === call)
|
|
590
|
+
this.#calls.delete(call.device); }
|
|
591
|
+
/** SpaceVoiceBridge: the audio sink the Host routes to while a Space call owns audio. */
|
|
592
|
+
sink = {
|
|
593
|
+
onAudioFrame: (frame) => { this.#owning()?.audioFrame(frame); },
|
|
594
|
+
onAudioClear: (utteranceId, generationEpoch) => { this.#owning()?.audioClear(utteranceId, generationEpoch); },
|
|
595
|
+
onAudioAlert: (utteranceId, generationEpoch) => { this.#owning()?.audioAlert(utteranceId, generationEpoch); },
|
|
596
|
+
onAudioTerminal: (utteranceId, generationEpoch) => { this.#owning()?.audioTerminal(utteranceId, generationEpoch); },
|
|
597
|
+
};
|
|
598
|
+
#owning() { const device = this.options.host.arbiter.spaceDevice; const call = device === undefined ? undefined : this.#calls.get(device); return call?.lease !== undefined && this.options.host.arbiter.owns(call.lease) ? call : undefined; }
|
|
599
|
+
}
|
|
600
|
+
//# sourceMappingURL=voice.js.map
|