nova-personal-agent-server 0.0.0-stage → 0.4.1
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,714 @@
|
|
|
1
|
+
import { ReadableStream } from 'node:stream/web';
|
|
2
|
+
import { ConfigurationError } from '../../config/config.js';
|
|
3
|
+
import { volcengineInputPcm } from './audio.js';
|
|
4
|
+
const SAMPLE_RATE = 16_000;
|
|
5
|
+
const BYTES_PER_SAMPLE = 2;
|
|
6
|
+
const FRAME_SAMPLES = 512;
|
|
7
|
+
const PREDICTION_TIMEOUT_SECONDS = 1.25;
|
|
8
|
+
const CLEANUP_TIMEOUT_MS = 1_000;
|
|
9
|
+
const TIMING_LIMITS = Object.freeze([
|
|
10
|
+
['vadPreRollMs', 0, 2_000, 'VOLCENGINE_VAD_PRE_ROLL_MS'],
|
|
11
|
+
['vadMinSpeechMs', 1, 10_000, 'VOLCENGINE_VAD_MIN_SPEECH_MS'],
|
|
12
|
+
['vadSilenceEndMs', 1, 10_000, 'VOLCENGINE_VAD_SILENCE_END_MS'],
|
|
13
|
+
['vadSpeechPadMs', 0, 2_000, 'VOLCENGINE_VAD_SPEECH_PAD_MS'],
|
|
14
|
+
['vadMaxUtteranceMs', 1, 60_000, 'VOLCENGINE_VAD_MAX_UTTERANCE_MS'],
|
|
15
|
+
]);
|
|
16
|
+
export class LiveKitVolcEndpointing {
|
|
17
|
+
#telemetry;
|
|
18
|
+
#surface;
|
|
19
|
+
#executor;
|
|
20
|
+
#config;
|
|
21
|
+
#clock;
|
|
22
|
+
#deactivationThreshold;
|
|
23
|
+
#speechPadSamples;
|
|
24
|
+
#maximumUtteranceSamples;
|
|
25
|
+
#retainedSampleLimit;
|
|
26
|
+
#token = 0;
|
|
27
|
+
#cursor = 0;
|
|
28
|
+
#partial = new Uint8Array();
|
|
29
|
+
#rotationReplay = new Uint8Array();
|
|
30
|
+
#records = [];
|
|
31
|
+
#utterance = null;
|
|
32
|
+
#events = [];
|
|
33
|
+
#epoch = null;
|
|
34
|
+
#tail = Promise.resolve();
|
|
35
|
+
#closePromise = null;
|
|
36
|
+
#closed = false;
|
|
37
|
+
constructor(options) {
|
|
38
|
+
validateConfig(options.config);
|
|
39
|
+
this.#telemetry = options.telemetry;
|
|
40
|
+
this.#surface = options.surface;
|
|
41
|
+
this.#executor = options.executor;
|
|
42
|
+
this.#config = Object.freeze({ ...options.config });
|
|
43
|
+
this.#clock = options.clock ?? REAL_CLOCK;
|
|
44
|
+
this.#deactivationThreshold = Math.max(options.config.vadThreshold - 0.15, 0.01);
|
|
45
|
+
this.#speechPadSamples = samplesForMilliseconds(options.config.vadSpeechPadMs);
|
|
46
|
+
this.#maximumUtteranceSamples = samplesForMilliseconds(options.config.vadMaxUtteranceMs);
|
|
47
|
+
this.#retainedSampleLimit = this.#maximumUtteranceSamples
|
|
48
|
+
+ samplesForMilliseconds(options.config.vadPreRollMs) + FRAME_SAMPLES;
|
|
49
|
+
}
|
|
50
|
+
feed(pcm, signal) {
|
|
51
|
+
if (this.#closed)
|
|
52
|
+
return Promise.reject(new Error('LiveKit endpointing is closed'));
|
|
53
|
+
let owned;
|
|
54
|
+
try {
|
|
55
|
+
owned = volcengineInputPcm(pcm).pcm;
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
return Promise.reject(error instanceof Error ? error : new RangeError('invalid input PCM'));
|
|
59
|
+
}
|
|
60
|
+
const result = this.#tail.then(async () => {
|
|
61
|
+
if (this.#closed)
|
|
62
|
+
throw new Error('LiveKit endpointing is closed');
|
|
63
|
+
throwIfAborted(signal);
|
|
64
|
+
let epoch = this.#epoch ?? this.#createEpoch();
|
|
65
|
+
try {
|
|
66
|
+
if (epoch.handlerTask !== null)
|
|
67
|
+
await epoch.handlerTask;
|
|
68
|
+
if (epoch.failure !== null)
|
|
69
|
+
await this.#failEpoch(epoch);
|
|
70
|
+
const available = this.#partial.byteLength === 0 ? owned : joinBytes([this.#partial, owned]);
|
|
71
|
+
const completeBytes = available.byteLength - (available.byteLength % (FRAME_SAMPLES * 2));
|
|
72
|
+
const frameInputs = [];
|
|
73
|
+
for (let offset = 0; offset < completeBytes; offset += FRAME_SAMPLES * 2) {
|
|
74
|
+
frameInputs.push(available.slice(offset, offset + FRAME_SAMPLES * 2));
|
|
75
|
+
}
|
|
76
|
+
this.#partial = available.slice(completeBytes);
|
|
77
|
+
for (const input of frameInputs) {
|
|
78
|
+
for (const frame of this.#writeFrames(epoch, input)) {
|
|
79
|
+
throwIfAborted(signal);
|
|
80
|
+
this.#acceptFrame(epoch, frame);
|
|
81
|
+
await epoch.producer.enqueue(frame, AbortSignal.any([signal, epoch.controller.signal]));
|
|
82
|
+
await this.#waitForVadPosition(epoch, this.#cursor, signal);
|
|
83
|
+
if (epoch.handlerTask !== null)
|
|
84
|
+
await epoch.handlerTask;
|
|
85
|
+
if (epoch.controller.signal.aborted || !this.#isCurrent(epoch)) {
|
|
86
|
+
throw abortReason(epoch.controller.signal);
|
|
87
|
+
}
|
|
88
|
+
if (epoch.failure !== null)
|
|
89
|
+
await this.#failEpoch(epoch);
|
|
90
|
+
if (epoch.rotateRequested)
|
|
91
|
+
epoch = await this.#rotateEpoch(epoch, signal);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (epoch.handlerTask !== null)
|
|
95
|
+
await epoch.handlerTask;
|
|
96
|
+
if (epoch.failure !== null)
|
|
97
|
+
await this.#failEpoch(epoch);
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
if (!signal.aborted && epoch.failure !== null && this.#epoch === epoch) {
|
|
101
|
+
await this.#failEpoch(epoch);
|
|
102
|
+
}
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
const events = this.#events.map(copyEndpointEvent);
|
|
106
|
+
this.#events = [];
|
|
107
|
+
return Object.freeze(events);
|
|
108
|
+
});
|
|
109
|
+
this.#tail = result.then(() => undefined, () => undefined);
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
reset() {
|
|
113
|
+
if (this.#closed)
|
|
114
|
+
return Promise.resolve();
|
|
115
|
+
const admitted = this.#epoch;
|
|
116
|
+
admitted?.controller.abort();
|
|
117
|
+
this.#token += 1;
|
|
118
|
+
const operation = this.#tail.then(async () => {
|
|
119
|
+
const old = this.#epoch ?? admitted;
|
|
120
|
+
this.#epoch = null;
|
|
121
|
+
this.#clearAudioState();
|
|
122
|
+
if (old !== null)
|
|
123
|
+
await this.#closeEpoch(old);
|
|
124
|
+
if (!this.#closed)
|
|
125
|
+
this.#createEpoch();
|
|
126
|
+
});
|
|
127
|
+
this.#tail = operation.then(() => undefined, () => undefined);
|
|
128
|
+
return operation;
|
|
129
|
+
}
|
|
130
|
+
close() {
|
|
131
|
+
if (this.#closePromise !== null)
|
|
132
|
+
return this.#closePromise;
|
|
133
|
+
this.#closed = true;
|
|
134
|
+
const admitted = this.#epoch;
|
|
135
|
+
admitted?.controller.abort();
|
|
136
|
+
this.#token += 1;
|
|
137
|
+
this.#closePromise = this.#tail.then(async () => {
|
|
138
|
+
const old = this.#epoch ?? admitted;
|
|
139
|
+
this.#epoch = null;
|
|
140
|
+
this.#clearAudioState();
|
|
141
|
+
if (old !== null)
|
|
142
|
+
await this.#closeEpoch(old);
|
|
143
|
+
});
|
|
144
|
+
return this.#closePromise;
|
|
145
|
+
}
|
|
146
|
+
#createEpoch() {
|
|
147
|
+
const token = ++this.#token;
|
|
148
|
+
const vad = new this.#surface.inference.VAD({
|
|
149
|
+
model: 'silero', minSpeechDuration: this.#config.vadMinSpeechMs,
|
|
150
|
+
minSilenceDuration: this.#config.vadSilenceEndMs,
|
|
151
|
+
prefixPaddingDuration: this.#config.vadPreRollMs,
|
|
152
|
+
maxBufferedSpeech: this.#config.vadMaxUtteranceMs,
|
|
153
|
+
activationThreshold: this.#config.vadThreshold,
|
|
154
|
+
deactivationThreshold: this.#deactivationThreshold,
|
|
155
|
+
});
|
|
156
|
+
const vadStream = vad.stream();
|
|
157
|
+
const detector = new this.#surface.inference.TurnDetector({
|
|
158
|
+
version: 'v1-mini', sampleRate: 16_000, executor: this.#executor,
|
|
159
|
+
});
|
|
160
|
+
const turnStream = detector.stream();
|
|
161
|
+
const producer = new OwnedFrameProducer();
|
|
162
|
+
vadStream.updateInputStream(producer.stream);
|
|
163
|
+
const epoch = {
|
|
164
|
+
token, controller: new AbortController(), vad, vadStream, detector, turnStream,
|
|
165
|
+
byteStream: new this.#surface.AudioByteStream(16_000, 1, 512), producer,
|
|
166
|
+
framingPartial: new Uint8Array(),
|
|
167
|
+
readerTask: Promise.resolve(), handlerTask: null, vadCursor: 0, pendingBoundaryPosition: null,
|
|
168
|
+
progressWaiters: new Set(), rotateRequested: false, failure: null,
|
|
169
|
+
};
|
|
170
|
+
epoch.readerTask = this.#readVad(epoch);
|
|
171
|
+
void epoch.readerTask.catch(() => undefined);
|
|
172
|
+
this.#epoch = epoch;
|
|
173
|
+
return epoch;
|
|
174
|
+
}
|
|
175
|
+
#acceptFrame(epoch, frame) {
|
|
176
|
+
const pcm = audioFrameBytes(frame);
|
|
177
|
+
const start = this.#cursor;
|
|
178
|
+
this.#cursor += frame.samplesPerChannel;
|
|
179
|
+
this.#records.push({ start, end: this.#cursor, pcm });
|
|
180
|
+
epoch.turnStream.pushAudio(frame);
|
|
181
|
+
this.#pruneRecords();
|
|
182
|
+
}
|
|
183
|
+
#writeFrames(epoch, input) {
|
|
184
|
+
const available = epoch.framingPartial.byteLength === 0
|
|
185
|
+
? input : joinBytes([epoch.framingPartial, input]);
|
|
186
|
+
const completeBytes = available.byteLength - (available.byteLength % (FRAME_SAMPLES * 2));
|
|
187
|
+
epoch.framingPartial = available.slice(completeBytes);
|
|
188
|
+
const frames = [];
|
|
189
|
+
for (let offset = 0; offset < completeBytes; offset += FRAME_SAMPLES * 2) {
|
|
190
|
+
const output = epoch.byteStream.write(available.slice(offset, offset + FRAME_SAMPLES * 2));
|
|
191
|
+
if (output.length !== 1)
|
|
192
|
+
throw new Error('LiveKit byte stream frame invariant failed');
|
|
193
|
+
frames.push(output[0]);
|
|
194
|
+
}
|
|
195
|
+
return frames;
|
|
196
|
+
}
|
|
197
|
+
async #readVad(epoch) {
|
|
198
|
+
try {
|
|
199
|
+
for await (const event of epoch.vadStream) {
|
|
200
|
+
if (!this.#isCurrent(epoch))
|
|
201
|
+
return;
|
|
202
|
+
const publicEvent = event;
|
|
203
|
+
const task = this.#handleVadEvent(epoch, publicEvent);
|
|
204
|
+
epoch.handlerTask = task;
|
|
205
|
+
await task;
|
|
206
|
+
if (epoch.handlerTask === task)
|
|
207
|
+
epoch.handlerTask = null;
|
|
208
|
+
this.#noteVadProgress(epoch, eventPosition(publicEvent));
|
|
209
|
+
}
|
|
210
|
+
if (this.#isCurrent(epoch) && !epoch.controller.signal.aborted) {
|
|
211
|
+
epoch.failure = new Error('LiveKit endpointing reader ended');
|
|
212
|
+
this.#rejectProgress(epoch, epoch.failure);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
if (this.#isCurrent(epoch) && !epoch.controller.signal.aborted) {
|
|
217
|
+
epoch.failure = new Error('LiveKit endpointing failed');
|
|
218
|
+
this.#rejectProgress(epoch, epoch.failure);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
async #handleVadEvent(epoch, event) {
|
|
223
|
+
const position = eventPosition(event);
|
|
224
|
+
// LiveKit 1.6.4 emits END frames as a view into its speech buffer, then
|
|
225
|
+
// immediately slides that buffer to retain pre-roll. By the time the async
|
|
226
|
+
// reader receives END, those bytes have changed. END needs only timing;
|
|
227
|
+
// all output audio comes from our owned ring and validated inference frames.
|
|
228
|
+
if (event.type === this.#surface.VADEventType.END_OF_SPEECH) {
|
|
229
|
+
await this.#endOfSpeech(epoch, event, position);
|
|
230
|
+
if (epoch.pendingBoundaryPosition === position)
|
|
231
|
+
epoch.pendingBoundaryPosition = null;
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
const frameRange = this.#validateEventFrames(event, position);
|
|
235
|
+
if (event.type === this.#surface.VADEventType.START_OF_SPEECH) {
|
|
236
|
+
this.#startSpeech(event, frameRange.start, position);
|
|
237
|
+
if (epoch.pendingBoundaryPosition === position)
|
|
238
|
+
epoch.pendingBoundaryPosition = null;
|
|
239
|
+
}
|
|
240
|
+
else if (event.type === this.#surface.VADEventType.INFERENCE_DONE) {
|
|
241
|
+
if (this.#expectsStartEvent(event) || this.#expectsEndEvent(event)) {
|
|
242
|
+
epoch.pendingBoundaryPosition = position;
|
|
243
|
+
}
|
|
244
|
+
this.#inferenceDone(event, position);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
#startSpeech(event, frameStart, position) {
|
|
248
|
+
const current = this.#utterance;
|
|
249
|
+
if (current === null) {
|
|
250
|
+
const duration = samplesForMilliseconds(requiredMilliseconds(event.speechDuration));
|
|
251
|
+
const firstSpeech = Math.max(frameStart, position - duration);
|
|
252
|
+
this.#emitAudio('speech_start', frameStart, position);
|
|
253
|
+
this.#utterance = { phase: 'active', firstSpeech, outputCursor: position, lastSpeech: position };
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
if (current.phase !== 'extension')
|
|
257
|
+
return;
|
|
258
|
+
if (position > current.outputCursor) {
|
|
259
|
+
this.#emitAudio('speech_audio', current.outputCursor, position);
|
|
260
|
+
}
|
|
261
|
+
current.phase = 'active';
|
|
262
|
+
current.outputCursor = position;
|
|
263
|
+
current.lastSpeech = position;
|
|
264
|
+
this.#forceAtCaps(position);
|
|
265
|
+
}
|
|
266
|
+
#inferenceDone(event, position) {
|
|
267
|
+
const current = this.#utterance;
|
|
268
|
+
if (current === null)
|
|
269
|
+
return;
|
|
270
|
+
if (!finiteProbability(event.probability))
|
|
271
|
+
throw new Error('invalid VAD probability');
|
|
272
|
+
if (current.phase === 'active' && event.probability > this.#deactivationThreshold) {
|
|
273
|
+
// Preserve low-probability speech and pauses between accepted frames.
|
|
274
|
+
this.#emitAudio('speech_audio', current.outputCursor, position);
|
|
275
|
+
current.outputCursor = Math.max(current.outputCursor, position);
|
|
276
|
+
current.lastSpeech = position;
|
|
277
|
+
}
|
|
278
|
+
this.#forceAtCaps(position);
|
|
279
|
+
}
|
|
280
|
+
#expectsEndEvent(event) {
|
|
281
|
+
const accumulated = event.rawAccumulatedSilence;
|
|
282
|
+
return event.speaking === true
|
|
283
|
+
&& typeof accumulated === 'number' && Number.isFinite(accumulated) && accumulated >= 0
|
|
284
|
+
&& event.probability <= this.#deactivationThreshold
|
|
285
|
+
&& accumulated + (FRAME_SAMPLES / (SAMPLE_RATE / 1_000)) >= this.#config.vadSilenceEndMs;
|
|
286
|
+
}
|
|
287
|
+
#expectsStartEvent(event) {
|
|
288
|
+
const accumulated = event.rawAccumulatedSpeech;
|
|
289
|
+
return event.speaking === false
|
|
290
|
+
&& typeof accumulated === 'number' && Number.isFinite(accumulated) && accumulated >= 0
|
|
291
|
+
&& event.probability >= this.#config.vadThreshold
|
|
292
|
+
&& accumulated + (FRAME_SAMPLES / (SAMPLE_RATE / 1_000)) >= this.#config.vadMinSpeechMs;
|
|
293
|
+
}
|
|
294
|
+
async #endOfSpeech(epoch, event, position) {
|
|
295
|
+
const current = this.#utterance;
|
|
296
|
+
if (current?.phase !== 'active')
|
|
297
|
+
return;
|
|
298
|
+
const silence = requiredMilliseconds(event.silenceDuration);
|
|
299
|
+
current.lastSpeech = Math.min(current.lastSpeech, position - samplesForMilliseconds(silence));
|
|
300
|
+
const predictionStarted = performance.now();
|
|
301
|
+
const threshold = await this.#predictionThreshold(epoch);
|
|
302
|
+
if (!this.#isCurrent(epoch) || this.#utterance !== current)
|
|
303
|
+
return;
|
|
304
|
+
this.#telemetry?.record('volcengine.endpointing.decision', {
|
|
305
|
+
probability: threshold.probability, threshold: threshold.unlikely, silence_ms: silence,
|
|
306
|
+
inference_ms: performance.now() - predictionStarted,
|
|
307
|
+
decision: threshold.probability >= threshold.unlikely ? 'commit' : 'extend',
|
|
308
|
+
});
|
|
309
|
+
if (threshold.probability >= threshold.unlikely)
|
|
310
|
+
this.#commitEnd(position);
|
|
311
|
+
else {
|
|
312
|
+
current.phase = 'extension';
|
|
313
|
+
this.#forceAtCaps(position);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
async #predictionThreshold(epoch) {
|
|
317
|
+
const [value, unlikely] = await withDeadline(Promise.all([
|
|
318
|
+
Promise.resolve(epoch.turnStream.predict().await),
|
|
319
|
+
epoch.detector.unlikelyThreshold('zh'),
|
|
320
|
+
]), this.#clock, epoch.controller.signal);
|
|
321
|
+
if (!finiteProbability(value.endOfTurnProbability) || !finiteProbability(unlikely)) {
|
|
322
|
+
throw new Error('invalid EOT result');
|
|
323
|
+
}
|
|
324
|
+
return { probability: value.endOfTurnProbability, unlikely };
|
|
325
|
+
}
|
|
326
|
+
#forceAtCaps(position) {
|
|
327
|
+
const current = this.#utterance;
|
|
328
|
+
if (current === null)
|
|
329
|
+
return;
|
|
330
|
+
const maximumReached = position - current.firstSpeech >= this.#maximumUtteranceSamples;
|
|
331
|
+
const extensionReached = current.phase === 'extension'
|
|
332
|
+
&& position - current.lastSpeech >= samplesForMilliseconds(this.#config.maxSilenceMs ?? 2500);
|
|
333
|
+
if (maximumReached || extensionReached)
|
|
334
|
+
this.#commitEnd(position);
|
|
335
|
+
}
|
|
336
|
+
#commitEnd(position) {
|
|
337
|
+
const current = this.#utterance;
|
|
338
|
+
if (current === null)
|
|
339
|
+
return;
|
|
340
|
+
const padEnd = Math.min(position, current.outputCursor + this.#speechPadSamples);
|
|
341
|
+
if (padEnd > current.outputCursor) {
|
|
342
|
+
this.#emitAudio('speech_audio', current.outputCursor, padEnd);
|
|
343
|
+
}
|
|
344
|
+
this.#events.push({ kind: 'speech_end', commit: true });
|
|
345
|
+
const preRollBytes = samplesForMilliseconds(this.#config.vadPreRollMs) * BYTES_PER_SAMPLE;
|
|
346
|
+
const remainder = this.#slice(padEnd, position);
|
|
347
|
+
this.#rotationReplay = remainder.slice(Math.max(0, remainder.byteLength - preRollBytes));
|
|
348
|
+
this.#utterance = null;
|
|
349
|
+
if (this.#epoch !== null)
|
|
350
|
+
this.#epoch.rotateRequested = true;
|
|
351
|
+
this.#pruneRecords();
|
|
352
|
+
}
|
|
353
|
+
#emitAudio(kind, start, end) {
|
|
354
|
+
// All paths (pre-roll, active speech, resumed pauses, tail) share the wire limit.
|
|
355
|
+
for (let offset = start; offset < end; offset += 32_000) {
|
|
356
|
+
this.#events.push({ kind: offset === start ? kind : 'speech_audio',
|
|
357
|
+
pcm: this.#slice(offset, Math.min(end, offset + 32_000)) });
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
#validateEventFrames(event, position) {
|
|
361
|
+
let samples = 0;
|
|
362
|
+
const bytes = [];
|
|
363
|
+
for (const frame of event.frames) {
|
|
364
|
+
bytes.push(audioFrameBytes(frame));
|
|
365
|
+
samples += frame.samplesPerChannel;
|
|
366
|
+
}
|
|
367
|
+
if (samples <= 0 || samples > this.#retainedSampleLimit)
|
|
368
|
+
throw new Error('invalid VAD frames');
|
|
369
|
+
const start = position - samples;
|
|
370
|
+
if (start < 0 || !equalBytes(this.#slice(start, position), joinBytes(bytes))) {
|
|
371
|
+
throw new Error('VAD frame cursor mismatch');
|
|
372
|
+
}
|
|
373
|
+
return { start };
|
|
374
|
+
}
|
|
375
|
+
#slice(start, end) {
|
|
376
|
+
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start) {
|
|
377
|
+
throw new Error('invalid endpointing cursor');
|
|
378
|
+
}
|
|
379
|
+
const result = new Uint8Array((end - start) * BYTES_PER_SAMPLE);
|
|
380
|
+
let copied = 0;
|
|
381
|
+
for (const record of this.#records) {
|
|
382
|
+
if (record.end <= start || record.start >= end)
|
|
383
|
+
continue;
|
|
384
|
+
const from = Math.max(start, record.start);
|
|
385
|
+
const to = Math.min(end, record.end);
|
|
386
|
+
const sourceStart = (from - record.start) * BYTES_PER_SAMPLE;
|
|
387
|
+
const sourceEnd = (to - record.start) * BYTES_PER_SAMPLE;
|
|
388
|
+
result.set(record.pcm.subarray(sourceStart, sourceEnd), copied);
|
|
389
|
+
copied += sourceEnd - sourceStart;
|
|
390
|
+
}
|
|
391
|
+
if (copied !== result.byteLength)
|
|
392
|
+
throw new Error('endpointing audio is outside retained ring');
|
|
393
|
+
return result;
|
|
394
|
+
}
|
|
395
|
+
#pruneRecords() {
|
|
396
|
+
const configuredPreRoll = samplesForMilliseconds(this.#config.vadPreRollMs);
|
|
397
|
+
const candidate = samplesForMilliseconds(this.#config.vadMinSpeechMs);
|
|
398
|
+
const floor = this.#utterance === null
|
|
399
|
+
? Math.max(0, this.#cursor - configuredPreRoll - candidate - FRAME_SAMPLES)
|
|
400
|
+
: Math.max(0, this.#cursor - this.#retainedSampleLimit);
|
|
401
|
+
while (this.#records[0] !== undefined && this.#records[0].end <= floor)
|
|
402
|
+
this.#records.shift();
|
|
403
|
+
}
|
|
404
|
+
async #failEpoch(epoch) {
|
|
405
|
+
if (this.#epoch === epoch)
|
|
406
|
+
this.#epoch = null;
|
|
407
|
+
this.#token += 1;
|
|
408
|
+
this.#clearAudioState();
|
|
409
|
+
await this.#closeEpoch(epoch).catch(() => undefined);
|
|
410
|
+
throw new Error('LiveKit endpointing failed');
|
|
411
|
+
}
|
|
412
|
+
async #rotateEpoch(epoch, signal) {
|
|
413
|
+
const replay = joinBytes([this.#rotationReplay, epoch.framingPartial]);
|
|
414
|
+
this.#rotationReplay = new Uint8Array();
|
|
415
|
+
if (this.#epoch === epoch)
|
|
416
|
+
this.#epoch = null;
|
|
417
|
+
const rotationToken = ++this.#token;
|
|
418
|
+
this.#cursor = 0;
|
|
419
|
+
this.#records = [];
|
|
420
|
+
this.#utterance = null;
|
|
421
|
+
await this.#closeEpoch(epoch);
|
|
422
|
+
if (this.#closed || this.#token !== rotationToken)
|
|
423
|
+
throw rotationAborted();
|
|
424
|
+
const fresh = this.#createEpoch();
|
|
425
|
+
for (const frame of this.#writeFrames(fresh, replay)) {
|
|
426
|
+
this.#acceptFrame(fresh, frame);
|
|
427
|
+
await fresh.producer.enqueue(frame, AbortSignal.any([signal, fresh.controller.signal]));
|
|
428
|
+
await this.#waitForVadPosition(fresh, this.#cursor, signal);
|
|
429
|
+
if (fresh.handlerTask !== null)
|
|
430
|
+
await fresh.handlerTask;
|
|
431
|
+
if (fresh.failure !== null)
|
|
432
|
+
await this.#failEpoch(fresh);
|
|
433
|
+
}
|
|
434
|
+
return fresh;
|
|
435
|
+
}
|
|
436
|
+
#waitForVadPosition(epoch, position, signal) {
|
|
437
|
+
if (epoch.failure !== null)
|
|
438
|
+
return Promise.reject(epoch.failure);
|
|
439
|
+
if (epoch.vadCursor >= position
|
|
440
|
+
&& (epoch.pendingBoundaryPosition === null || position < epoch.pendingBoundaryPosition)) {
|
|
441
|
+
return Promise.resolve();
|
|
442
|
+
}
|
|
443
|
+
const combined = AbortSignal.any([signal, epoch.controller.signal]);
|
|
444
|
+
return new Promise((resolve, reject) => {
|
|
445
|
+
const aborted = () => {
|
|
446
|
+
epoch.progressWaiters.delete(waiter);
|
|
447
|
+
reject(abortReason(combined));
|
|
448
|
+
};
|
|
449
|
+
const waiter = {
|
|
450
|
+
position,
|
|
451
|
+
resolve: () => { combined.removeEventListener('abort', aborted); resolve(); },
|
|
452
|
+
reject: error => { combined.removeEventListener('abort', aborted); reject(error); },
|
|
453
|
+
};
|
|
454
|
+
if (combined.aborted) {
|
|
455
|
+
aborted();
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
epoch.progressWaiters.add(waiter);
|
|
459
|
+
combined.addEventListener('abort', aborted, { once: true });
|
|
460
|
+
if (epoch.failure !== null) {
|
|
461
|
+
epoch.progressWaiters.delete(waiter);
|
|
462
|
+
waiter.reject(epoch.failure);
|
|
463
|
+
}
|
|
464
|
+
else if (combined.aborted)
|
|
465
|
+
aborted();
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
#noteVadProgress(epoch, position) {
|
|
469
|
+
epoch.vadCursor = Math.max(epoch.vadCursor, position);
|
|
470
|
+
setImmediate(() => {
|
|
471
|
+
for (const waiter of [...epoch.progressWaiters]) {
|
|
472
|
+
if (waiter.position > epoch.vadCursor)
|
|
473
|
+
continue;
|
|
474
|
+
if (epoch.pendingBoundaryPosition !== null
|
|
475
|
+
&& waiter.position >= epoch.pendingBoundaryPosition)
|
|
476
|
+
continue;
|
|
477
|
+
epoch.progressWaiters.delete(waiter);
|
|
478
|
+
waiter.resolve();
|
|
479
|
+
}
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
#rejectProgress(epoch, error) {
|
|
483
|
+
for (const waiter of epoch.progressWaiters)
|
|
484
|
+
waiter.reject(error);
|
|
485
|
+
epoch.progressWaiters.clear();
|
|
486
|
+
}
|
|
487
|
+
async #closeEpoch(epoch) {
|
|
488
|
+
epoch.controller.abort();
|
|
489
|
+
this.#rejectProgress(epoch, abortReason(epoch.controller.signal));
|
|
490
|
+
let failed = false;
|
|
491
|
+
for (const operation of [
|
|
492
|
+
() => epoch.producer.close(), () => epoch.vadStream.flush(),
|
|
493
|
+
() => epoch.vadStream.close(),
|
|
494
|
+
]) {
|
|
495
|
+
try {
|
|
496
|
+
operation();
|
|
497
|
+
}
|
|
498
|
+
catch {
|
|
499
|
+
failed = true;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
const eotCleanup = (async () => {
|
|
503
|
+
let successful = await callOutcome(() => epoch.turnStream.aclose());
|
|
504
|
+
successful = await callOutcome(() => epoch.detector.aclose()) && successful;
|
|
505
|
+
return successful;
|
|
506
|
+
})();
|
|
507
|
+
const tasks = [outcome(epoch.readerTask), eotCleanup, callOutcome(() => epoch.vad.close())];
|
|
508
|
+
const settled = await settleWithin(Promise.all(tasks), CLEANUP_TIMEOUT_MS);
|
|
509
|
+
failed = !settled || failed;
|
|
510
|
+
if (settled)
|
|
511
|
+
failed = (await Promise.all(tasks)).some(success => !success) || failed;
|
|
512
|
+
if (failed)
|
|
513
|
+
throw new Error('LiveKit endpointing cleanup failed');
|
|
514
|
+
}
|
|
515
|
+
#isCurrent(epoch) {
|
|
516
|
+
return this.#epoch === epoch && epoch.token === this.#token && !epoch.controller.signal.aborted;
|
|
517
|
+
}
|
|
518
|
+
#clearAudioState() {
|
|
519
|
+
this.#cursor = 0;
|
|
520
|
+
this.#partial = new Uint8Array();
|
|
521
|
+
this.#rotationReplay = new Uint8Array();
|
|
522
|
+
this.#records = [];
|
|
523
|
+
this.#utterance = null;
|
|
524
|
+
this.#events = [];
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
class OwnedFrameProducer {
|
|
528
|
+
stream;
|
|
529
|
+
#controller = null;
|
|
530
|
+
#capacityWaiter = null;
|
|
531
|
+
#closed = false;
|
|
532
|
+
constructor() {
|
|
533
|
+
this.stream = new ReadableStream({
|
|
534
|
+
start: controller => { this.#controller = controller; },
|
|
535
|
+
pull: () => {
|
|
536
|
+
this.#capacityWaiter?.();
|
|
537
|
+
this.#capacityWaiter = null;
|
|
538
|
+
},
|
|
539
|
+
}, { highWaterMark: 1 });
|
|
540
|
+
}
|
|
541
|
+
async enqueue(frame, signal) {
|
|
542
|
+
if (this.#closed || this.#controller === null)
|
|
543
|
+
throw new Error('VAD input is closed');
|
|
544
|
+
while ((this.#controller.desiredSize ?? 0) <= 0) {
|
|
545
|
+
await new Promise((resolve, reject) => {
|
|
546
|
+
const aborted = () => {
|
|
547
|
+
this.#capacityWaiter = null;
|
|
548
|
+
reject(abortReason(signal));
|
|
549
|
+
};
|
|
550
|
+
this.#capacityWaiter = () => {
|
|
551
|
+
signal.removeEventListener('abort', aborted);
|
|
552
|
+
resolve();
|
|
553
|
+
};
|
|
554
|
+
if (signal.aborted) {
|
|
555
|
+
aborted();
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
signal.addEventListener('abort', aborted, { once: true });
|
|
559
|
+
});
|
|
560
|
+
if (this.#closed)
|
|
561
|
+
throw new Error('VAD input is closed');
|
|
562
|
+
}
|
|
563
|
+
this.#controller.enqueue(frame);
|
|
564
|
+
await yieldToReaders();
|
|
565
|
+
}
|
|
566
|
+
close() {
|
|
567
|
+
if (this.#closed)
|
|
568
|
+
return;
|
|
569
|
+
this.#closed = true;
|
|
570
|
+
this.#capacityWaiter?.();
|
|
571
|
+
this.#capacityWaiter = null;
|
|
572
|
+
this.#controller?.close();
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
function validateConfig(config) {
|
|
576
|
+
if (config.maxSilenceMs !== undefined && (!Number.isSafeInteger(config.maxSilenceMs) || config.maxSilenceMs < 300 || config.maxSilenceMs > 2500))
|
|
577
|
+
throw new ConfigurationError('invalid endpointing maxSilenceMs');
|
|
578
|
+
if (!Number.isFinite(config.vadThreshold) || config.vadThreshold <= 0 || config.vadThreshold > 1) {
|
|
579
|
+
throw new ConfigurationError('invalid configuration: VOLCENGINE_VAD_THRESHOLD');
|
|
580
|
+
}
|
|
581
|
+
for (const [field, minimum, maximum, variable] of TIMING_LIMITS) {
|
|
582
|
+
const value = config[field];
|
|
583
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
|
|
584
|
+
throw new ConfigurationError(`invalid configuration: ${variable}`);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
if (config.vadMaxUtteranceMs < config.vadMinSpeechMs) {
|
|
588
|
+
throw new ConfigurationError('invalid configuration: VOLCENGINE_VAD_MAX_UTTERANCE_MS');
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
function eventPosition(event) {
|
|
592
|
+
if (!Number.isSafeInteger(event.samplesIndex) || event.samplesIndex < 0) {
|
|
593
|
+
throw new Error('invalid VAD sample index');
|
|
594
|
+
}
|
|
595
|
+
return event.samplesIndex;
|
|
596
|
+
}
|
|
597
|
+
function requiredMilliseconds(value) {
|
|
598
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
|
|
599
|
+
throw new Error('invalid VAD duration');
|
|
600
|
+
}
|
|
601
|
+
return value;
|
|
602
|
+
}
|
|
603
|
+
function audioFrameBytes(frame) {
|
|
604
|
+
if (frame.sampleRate !== SAMPLE_RATE || frame.channels !== 1
|
|
605
|
+
|| !Number.isSafeInteger(frame.samplesPerChannel) || frame.samplesPerChannel <= 0
|
|
606
|
+
|| frame.samplesPerChannel !== frame.data.length) {
|
|
607
|
+
throw new Error('invalid LiveKit audio frame format');
|
|
608
|
+
}
|
|
609
|
+
const pcm = new Uint8Array(frame.data.length * BYTES_PER_SAMPLE);
|
|
610
|
+
const view = new DataView(pcm.buffer);
|
|
611
|
+
frame.data.forEach((sample, index) => view.setInt16(index * BYTES_PER_SAMPLE, sample, true));
|
|
612
|
+
return pcm;
|
|
613
|
+
}
|
|
614
|
+
function copyEndpointEvent(event) {
|
|
615
|
+
return event.kind === 'speech_end' ? { ...event } : { ...event, pcm: event.pcm.slice() };
|
|
616
|
+
}
|
|
617
|
+
function samplesForMilliseconds(milliseconds) {
|
|
618
|
+
return milliseconds * (SAMPLE_RATE / 1_000);
|
|
619
|
+
}
|
|
620
|
+
function finiteProbability(value) {
|
|
621
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1;
|
|
622
|
+
}
|
|
623
|
+
function equalBytes(left, right) {
|
|
624
|
+
return left.byteLength === right.byteLength && left.every((value, index) => value === right[index]);
|
|
625
|
+
}
|
|
626
|
+
function joinBytes(parts) {
|
|
627
|
+
const result = new Uint8Array(parts.reduce((total, part) => total + part.byteLength, 0));
|
|
628
|
+
let offset = 0;
|
|
629
|
+
for (const part of parts) {
|
|
630
|
+
result.set(part, offset);
|
|
631
|
+
offset += part.byteLength;
|
|
632
|
+
}
|
|
633
|
+
return result;
|
|
634
|
+
}
|
|
635
|
+
async function withDeadline(promise, clock, signal) {
|
|
636
|
+
const timerController = new AbortController();
|
|
637
|
+
const timer = clock.sleep(PREDICTION_TIMEOUT_SECONDS, timerController.signal).then(() => {
|
|
638
|
+
throw new Error('LiveKit endpointing prediction timeout');
|
|
639
|
+
});
|
|
640
|
+
timer.catch(() => undefined);
|
|
641
|
+
try {
|
|
642
|
+
return await Promise.race([promise, timer, abortPromise(signal)]);
|
|
643
|
+
}
|
|
644
|
+
finally {
|
|
645
|
+
timerController.abort();
|
|
646
|
+
await timer.catch(() => undefined);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
function abortPromise(signal) {
|
|
650
|
+
if (signal.aborted)
|
|
651
|
+
return Promise.reject(abortReason(signal));
|
|
652
|
+
return new Promise((_resolve, reject) => {
|
|
653
|
+
signal.addEventListener('abort', () => reject(abortReason(signal)), { once: true });
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
function throwIfAborted(signal) { if (signal.aborted)
|
|
657
|
+
throw abortReason(signal); }
|
|
658
|
+
function abortReason(signal) {
|
|
659
|
+
return signal.reason instanceof Error
|
|
660
|
+
? signal.reason : new DOMException('This operation was aborted', 'AbortError');
|
|
661
|
+
}
|
|
662
|
+
function rotationAborted() {
|
|
663
|
+
return new DOMException('Endpointing rotation was aborted', 'AbortError');
|
|
664
|
+
}
|
|
665
|
+
function callOutcome(operation) {
|
|
666
|
+
try {
|
|
667
|
+
return outcome(operation());
|
|
668
|
+
}
|
|
669
|
+
catch {
|
|
670
|
+
return Promise.resolve(false);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
function outcome(promise) {
|
|
674
|
+
return promise.then(() => true, () => false);
|
|
675
|
+
}
|
|
676
|
+
async function settleWithin(promise, milliseconds) {
|
|
677
|
+
promise.catch(() => undefined);
|
|
678
|
+
let timer;
|
|
679
|
+
try {
|
|
680
|
+
return await Promise.race([
|
|
681
|
+
promise.then(() => true, () => false),
|
|
682
|
+
new Promise(resolve => { timer = setTimeout(() => resolve(false), milliseconds); }),
|
|
683
|
+
]);
|
|
684
|
+
}
|
|
685
|
+
finally {
|
|
686
|
+
if (timer !== undefined)
|
|
687
|
+
clearTimeout(timer);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
function yieldToReaders() { return new Promise(resolve => setImmediate(resolve)); }
|
|
691
|
+
const REAL_CLOCK = Object.freeze({
|
|
692
|
+
now: () => performance.now() / 1_000,
|
|
693
|
+
sleep: (duration, signal) => new Promise((resolve, reject) => {
|
|
694
|
+
if (!Number.isFinite(duration) || duration < 0) {
|
|
695
|
+
reject(new RangeError('invalid delay'));
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
if (signal?.aborted === true) {
|
|
699
|
+
reject(abortReason(signal));
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
const aborted = () => {
|
|
703
|
+
clearTimeout(timer);
|
|
704
|
+
reject(signal === undefined ? new Error('aborted') : abortReason(signal));
|
|
705
|
+
};
|
|
706
|
+
const timer = setTimeout(() => {
|
|
707
|
+
signal?.removeEventListener('abort', aborted);
|
|
708
|
+
resolve();
|
|
709
|
+
}, duration * 1_000);
|
|
710
|
+
timer.unref();
|
|
711
|
+
signal?.addEventListener('abort', aborted, { once: true });
|
|
712
|
+
}),
|
|
713
|
+
});
|
|
714
|
+
//# sourceMappingURL=livekit-endpointing.js.map
|