nova-personal-agent-server 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +30 -2
- package/bin/novapersonal-server.mjs +4 -0
- package/package.json +61 -4
- package/resources/endpointing/volcengine-v1/LICENSE.silero-vad.txt +21 -0
- package/resources/endpointing/volcengine-v1/MANIFEST.json +31 -0
- package/resources/endpointing/volcengine-v1/silence-16k-s16le.pcm +0 -0
- package/resources/endpointing/volcengine-v1/speech-16k-s16le.pcm +0 -0
- package/resources/native/codex-sandbox-probe +0 -0
- package/resources/native/project-native/nova_project_native.node +0 -0
- package/resources/native-resources-v1.json +1 -0
- package/runtime/dist/eval/demos.js +156 -0
- package/runtime/dist/eval/fixture-host.js +385 -0
- package/runtime/dist/eval/fixtures.js +319 -0
- package/runtime/dist/eval/realtime/session-fixtures.js +474 -0
- package/runtime/dist/eval/scorecard.js +285 -0
- package/runtime/dist/eval/sim.js +43 -0
- package/runtime/dist/src/cascaded-text-provider.js +31 -0
- package/runtime/dist/src/cli.js +96 -0
- package/runtime/dist/src/composition/assembly.js +352 -0
- package/runtime/dist/src/composition/cascaded-realtime-assembly.js +455 -0
- package/runtime/dist/src/composition/production-composition.js +389 -0
- package/runtime/dist/src/composition/realtime-assembly.js +1330 -0
- package/runtime/dist/src/config/capability-registry.js +315 -0
- package/runtime/dist/src/config/cascaded-realtime-config.js +146 -0
- package/runtime/dist/src/config/coding-backends.js +8 -0
- package/runtime/dist/src/config/coding-profiles.js +98 -0
- package/runtime/dist/src/config/config.js +857 -0
- package/runtime/dist/src/config/diagnostics.js +139 -0
- package/runtime/dist/src/config/environment-contract.js +202 -0
- package/runtime/dist/src/config/self-hosted.js +23 -0
- package/runtime/dist/src/connectors/composio/client.js +195 -0
- package/runtime/dist/src/connectors/composio/google.js +208 -0
- package/runtime/dist/src/connectors/composio/index.js +334 -0
- package/runtime/dist/src/connectors/feishu/cli.js +220 -0
- package/runtime/dist/src/connectors/feishu/index.js +980 -0
- package/runtime/dist/src/connectors/macos/calendar.js +35 -0
- package/runtime/dist/src/connectors/macos/mail.js +32 -0
- package/runtime/dist/src/connectors/macos/reader.js +62 -0
- package/runtime/dist/src/conversation-voice-provider.js +41 -0
- package/runtime/dist/src/core/approval-port.js +9 -0
- package/runtime/dist/src/core/approval.js +1328 -0
- package/runtime/dist/src/core/calls.js +35 -0
- package/runtime/dist/src/core/camera-session.js +32 -0
- package/runtime/dist/src/core/causal-runtime.js +650 -0
- package/runtime/dist/src/core/clock.js +139 -0
- package/runtime/dist/src/core/context-view.js +156 -0
- package/runtime/dist/src/core/effects.js +62 -0
- package/runtime/dist/src/core/events.js +217 -0
- package/runtime/dist/src/core/executor-diagnostic.js +9 -0
- package/runtime/dist/src/core/ids.js +32 -0
- package/runtime/dist/src/core/media-store.js +104 -0
- package/runtime/dist/src/core/memory.js +296 -0
- package/runtime/dist/src/core/pending-decision.js +64 -0
- package/runtime/dist/src/core/ports.js +125 -0
- package/runtime/dist/src/core/runtime.js +1459 -0
- package/runtime/dist/src/core/schedule-tools.js +15 -0
- package/runtime/dist/src/core/sims.js +186 -0
- package/runtime/dist/src/core/slots.js +97 -0
- package/runtime/dist/src/core/source-processing-instructions.js +3 -0
- package/runtime/dist/src/core/source-processing-tools.js +12 -0
- package/runtime/dist/src/core/suggestions.js +143 -0
- package/runtime/dist/src/core/task-tools.js +22 -0
- package/runtime/dist/src/core/tool-schema.js +212 -0
- package/runtime/dist/src/core/trace.js +34 -0
- package/runtime/dist/src/core/work-tools.js +94 -0
- package/runtime/dist/src/desktop/desktop-camera-source.js +31 -0
- package/runtime/dist/src/desktop/desktop-camera.js +281 -0
- package/runtime/dist/src/desktop/desktop-control.js +140 -0
- package/runtime/dist/src/desktop/desktop-progress.js +162 -0
- package/runtime/dist/src/desktop/desktop-session.js +2106 -0
- package/runtime/dist/src/desktop/desktop-tasks.js +80 -0
- package/runtime/dist/src/desktop/desktop-wire.js +605 -0
- package/runtime/dist/src/desktop/phone-desktop-entry.js +17 -0
- package/runtime/dist/src/desktop/startup-error.js +18 -0
- package/runtime/dist/src/desktop/workbench-acceptance.js +262 -0
- package/runtime/dist/src/desktop-entry.js +106 -0
- package/runtime/dist/src/desktop.js +1092 -0
- package/runtime/dist/src/executors/acp/backends.js +105 -0
- package/runtime/dist/src/executors/acp/mcp.js +81 -0
- package/runtime/dist/src/executors/acp/preflight.js +14 -0
- package/runtime/dist/src/executors/acp/process-owner.js +112 -0
- package/runtime/dist/src/executors/acp/transport.js +760 -0
- package/runtime/dist/src/executors/acp/windows-launch.js +68 -0
- package/runtime/dist/src/executors/agent-controller.js +244 -0
- package/runtime/dist/src/executors/autoglm.js +376 -0
- package/runtime/dist/src/executors/browser-device.js +102 -0
- package/runtime/dist/src/executors/browser.js +61 -0
- package/runtime/dist/src/executors/camera.js +101 -0
- package/runtime/dist/src/executors/chromium-frame-source.js +173 -0
- package/runtime/dist/src/executors/codex/adapter-live.js +292 -0
- package/runtime/dist/src/executors/codex/adapter-project.js +1306 -0
- package/runtime/dist/src/executors/codex/app-server-schema.js +712 -0
- package/runtime/dist/src/executors/codex/app-server-transport.js +1798 -0
- package/runtime/dist/src/executors/codex/approval-protocol.js +439 -0
- package/runtime/dist/src/executors/codex/common.js +655 -0
- package/runtime/dist/src/executors/codex/contract.js +581 -0
- package/runtime/dist/src/executors/codex/controller.js +141 -0
- package/runtime/dist/src/executors/codex/credential-snapshot.js +195 -0
- package/runtime/dist/src/executors/codex/factory.js +463 -0
- package/runtime/dist/src/executors/codex/host-config.js +238 -0
- package/runtime/dist/src/executors/codex/host.js +17 -0
- package/runtime/dist/src/executors/codex/index.js +19 -0
- package/runtime/dist/src/executors/codex/launch-profile.js +37 -0
- package/runtime/dist/src/executors/codex/local-sessions.js +119 -0
- package/runtime/dist/src/executors/codex/managed-mcp.js +196 -0
- package/runtime/dist/src/executors/codex/process-owner.js +398 -0
- package/runtime/dist/src/executors/codex/production-host.js +887 -0
- package/runtime/dist/src/executors/codex/progress-instructions.js +10 -0
- package/runtime/dist/src/executors/codex/protocol.js +581 -0
- package/runtime/dist/src/executors/codex/safe-json.js +87 -0
- package/runtime/dist/src/executors/codex/session-title.js +61 -0
- package/runtime/dist/src/executors/codex/shared-home.js +29 -0
- package/runtime/dist/src/executors/codex/spawn-env.js +162 -0
- package/runtime/dist/src/executors/codex/turn-projection.js +435 -0
- package/runtime/dist/src/executors/codex/version.js +38 -0
- package/runtime/dist/src/executors/codex/windows-guardian.js +716 -0
- package/runtime/dist/src/executors/coding/intake-model.js +103 -0
- package/runtime/dist/src/executors/coding/intake.js +824 -0
- package/runtime/dist/src/executors/coding/json-completion.js +14 -0
- package/runtime/dist/src/executors/coding/target-resolution.js +61 -0
- package/runtime/dist/src/executors/coding/work-order.js +50 -0
- package/runtime/dist/src/executors/coding-executor.js +23 -0
- package/runtime/dist/src/executors/computer-backend.js +188 -0
- package/runtime/dist/src/executors/computer-device.js +187 -0
- package/runtime/dist/src/executors/computer-worker.js +125 -0
- package/runtime/dist/src/executors/computer.js +100 -0
- package/runtime/dist/src/executors/device-lock.js +127 -0
- package/runtime/dist/src/executors/frame-source.js +29 -0
- package/runtime/dist/src/executors/gui-evidence.js +30 -0
- package/runtime/dist/src/executors/gui-execution.js +237 -0
- package/runtime/dist/src/executors/gui-runner.js +88 -0
- package/runtime/dist/src/executors/host-executor-capability.js +12 -0
- package/runtime/dist/src/executors/index.js +13 -0
- package/runtime/dist/src/executors/mcp-client.js +198 -0
- package/runtime/dist/src/executors/mcp.js +210 -0
- package/runtime/dist/src/executors/mobile-android.js +180 -0
- package/runtime/dist/src/executors/mobile-ios.js +303 -0
- package/runtime/dist/src/executors/mobile.js +78 -0
- package/runtime/dist/src/executors/search-mcp.js +146 -0
- package/runtime/dist/src/executors/search.js +524 -0
- package/runtime/dist/src/executors/task-resources.js +38 -0
- package/runtime/dist/src/executors/vision/assess.js +296 -0
- package/runtime/dist/src/executors/vision/controller-core.js +373 -0
- package/runtime/dist/src/executors/vision/controller.js +164 -0
- package/runtime/dist/src/executors/vision/lifecycle.js +69 -0
- package/runtime/dist/src/executors/vision.js +5 -0
- package/runtime/dist/src/executors/watcher.js +718 -0
- package/runtime/dist/src/http/bounded-response.js +37 -0
- package/runtime/dist/src/index.js +56 -0
- package/runtime/dist/src/knowledge/assembly.js +60 -0
- package/runtime/dist/src/knowledge/documents.js +520 -0
- package/runtime/dist/src/knowledge/embeddings.js +201 -0
- package/runtime/dist/src/knowledge/mcp.js +218 -0
- package/runtime/dist/src/knowledge/parse-worker.js +122 -0
- package/runtime/dist/src/knowledge/references.js +51 -0
- package/runtime/dist/src/knowledge/service.js +526 -0
- package/runtime/dist/src/knowledge/store-client.js +185 -0
- package/runtime/dist/src/knowledge/store-worker.js +843 -0
- package/runtime/dist/src/knowledge/types.js +2 -0
- package/runtime/dist/src/mcp/http-server.js +177 -0
- package/runtime/dist/src/mem0/resource.js +35 -0
- package/runtime/dist/src/mem0/store-worker.js +330 -0
- package/runtime/dist/src/memory/blackboard-session.js +205 -0
- package/runtime/dist/src/memory/blackboard-store.js +194 -0
- package/runtime/dist/src/memory/blackboard-worker.js +369 -0
- package/runtime/dist/src/memory/entry.js +39 -0
- package/runtime/dist/src/memory/factory.js +20 -0
- package/runtime/dist/src/memory/personal-memory-inspection.js +18 -0
- package/runtime/dist/src/memory/personal-memory.js +10 -0
- package/runtime/dist/src/memory/prerecall.js +20 -0
- package/runtime/dist/src/memory/provenance.js +17 -0
- package/runtime/dist/src/memory/remote-personal-memory.js +194 -0
- package/runtime/dist/src/memory/retrieval.js +235 -0
- package/runtime/dist/src/memory/sensitivity.js +261 -0
- package/runtime/dist/src/memory-ledger/models.js +98 -0
- package/runtime/dist/src/memory-ledger/store-client.js +210 -0
- package/runtime/dist/src/memory-ledger/store-worker.js +130 -0
- package/runtime/dist/src/memory-ledger/store.js +597 -0
- package/runtime/dist/src/memory-substrate/candidates.js +16 -0
- package/runtime/dist/src/memory-substrate/consolidation.js +124 -0
- package/runtime/dist/src/memory-substrate/file-authority.js +111 -0
- package/runtime/dist/src/memory-substrate/life-operations.js +280 -0
- package/runtime/dist/src/memory-substrate/markdown-repository.js +610 -0
- package/runtime/dist/src/memory-substrate/migration.js +87 -0
- package/runtime/dist/src/memory-substrate/profile-source-input.js +9 -0
- package/runtime/dist/src/memory-substrate/purge.js +398 -0
- package/runtime/dist/src/memory-substrate/resolution.js +32 -0
- package/runtime/dist/src/memory-substrate/resource.js +867 -0
- package/runtime/dist/src/memory-substrate/retrieval.js +85 -0
- package/runtime/dist/src/memory-substrate/source-operations.js +306 -0
- package/runtime/dist/src/memory-substrate/source-processing.js +326 -0
- package/runtime/dist/src/memory-substrate/source-state.js +93 -0
- package/runtime/dist/src/memory-substrate/store.js +534 -0
- package/runtime/dist/src/memory-substrate/workspace-projections.js +106 -0
- package/runtime/dist/src/memory-substrate/workspace.js +21 -0
- package/runtime/dist/src/model/jev-client.js +25 -0
- package/runtime/dist/src/model/model-adapters.js +64 -0
- package/runtime/dist/src/model/model-gateway.js +399 -0
- package/runtime/dist/src/model/model-lane.js +34 -0
- package/runtime/dist/src/model/model-purpose.js +5 -0
- package/runtime/dist/src/model/personal-writer.js +361 -0
- package/runtime/dist/src/model/proactivity.js +72 -0
- package/runtime/dist/src/model/prompting.js +279 -0
- package/runtime/dist/src/model/task-verifier.js +217 -0
- package/runtime/dist/src/model/vision-capability.js +10 -0
- package/runtime/dist/src/news/feeds.js +114 -0
- package/runtime/dist/src/news/jev-ranking.js +25 -0
- package/runtime/dist/src/news/ranking.js +26 -0
- package/runtime/dist/src/news/service.js +262 -0
- package/runtime/dist/src/notifications/adapters/feishu.js +10 -0
- package/runtime/dist/src/notifications/adapters/nova.js +15 -0
- package/runtime/dist/src/notifications/content.js +15 -0
- package/runtime/dist/src/notifications/contracts.js +9 -0
- package/runtime/dist/src/notifications/feed.js +8 -0
- package/runtime/dist/src/notifications/service.js +412 -0
- package/runtime/dist/src/notifications/store.js +4 -0
- package/runtime/dist/src/personal-agent/app-context.js +113 -0
- package/runtime/dist/src/personal-agent/approval-scope.js +8 -0
- package/runtime/dist/src/personal-agent/coding-targets.js +82 -0
- package/runtime/dist/src/personal-agent/context-candidates.js +94 -0
- package/runtime/dist/src/personal-agent/contracts.js +32 -0
- package/runtime/dist/src/personal-agent/conversation-runtime.js +536 -0
- package/runtime/dist/src/personal-agent/conversations.js +187 -0
- package/runtime/dist/src/personal-agent/daily-brief.js +53 -0
- package/runtime/dist/src/personal-agent/host.js +2403 -0
- package/runtime/dist/src/personal-agent/intake-task.js +37 -0
- package/runtime/dist/src/personal-agent/life.js +260 -0
- package/runtime/dist/src/personal-agent/memory-overview.js +19 -0
- package/runtime/dist/src/personal-agent/profile-sources.js +34 -0
- package/runtime/dist/src/personal-agent/profile-warmup.js +244 -0
- package/runtime/dist/src/personal-agent/project-digests.js +242 -0
- package/runtime/dist/src/personal-agent/sampling.js +20 -0
- package/runtime/dist/src/personal-agent/schedule-agent.js +60 -0
- package/runtime/dist/src/personal-agent/schedule-api.js +61 -0
- package/runtime/dist/src/personal-agent/schedule-presets.js +13 -0
- package/runtime/dist/src/personal-agent/schedule-reference.js +3 -0
- package/runtime/dist/src/personal-agent/scheduled-response-scope.js +38 -0
- package/runtime/dist/src/personal-agent/scheduled-run-authority.js +44 -0
- package/runtime/dist/src/personal-agent/scheduled-tasks.js +280 -0
- package/runtime/dist/src/personal-agent/scheduled-time.js +99 -0
- package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +109 -0
- package/runtime/dist/src/personal-agent/source-priority.js +142 -0
- package/runtime/dist/src/personal-agent/source-processing-agent.js +158 -0
- package/runtime/dist/src/personal-agent/source-walk.js +25 -0
- package/runtime/dist/src/personal-agent/sources.js +1484 -0
- package/runtime/dist/src/personal-agent/store-lock-worker.js +17 -0
- package/runtime/dist/src/personal-agent/store.js +146 -0
- package/runtime/dist/src/personal-agent/task-loop.js +163 -0
- package/runtime/dist/src/personal-agent/tasks.js +920 -0
- package/runtime/dist/src/personal-agent/turn-deadline.js +55 -0
- package/runtime/dist/src/personal-agent/understanding.js +160 -0
- package/runtime/dist/src/personal-agent/workbench-context.js +239 -0
- package/runtime/dist/src/projects/confirmed-project-capability.js +60 -0
- package/runtime/dist/src/projects/host-paths.js +133 -0
- package/runtime/dist/src/projects/managed-workspace-maintenance.js +351 -0
- package/runtime/dist/src/projects/project-confirmation.js +486 -0
- package/runtime/dist/src/projects/project-native-resource.js +284 -0
- package/runtime/dist/src/projects/project-node-files.js +169 -0
- package/runtime/dist/src/projects/project-root-file.js +16 -0
- package/runtime/dist/src/projects/project-state.js +504 -0
- package/runtime/dist/src/projects/project-store-files.js +1271 -0
- package/runtime/dist/src/projects/project-store.js +1345 -0
- package/runtime/dist/src/realtime/aoq.js +141 -0
- package/runtime/dist/src/realtime/bridge.js +652 -0
- package/runtime/dist/src/realtime/cascaded/adapter.js +1669 -0
- package/runtime/dist/src/realtime/cascaded/ark-llm.js +219 -0
- package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +478 -0
- package/runtime/dist/src/realtime/cascaded/gemini-speech.js +232 -0
- package/runtime/dist/src/realtime/cascaded/llm.js +37 -0
- package/runtime/dist/src/realtime/cascaded/ports.js +2 -0
- package/runtime/dist/src/realtime/cascaded/provider.js +216 -0
- package/runtime/dist/src/realtime/cascaded/qwen-llm.js +7 -0
- package/runtime/dist/src/realtime/cascaded/self-hosted-asr.js +110 -0
- package/runtime/dist/src/realtime/cascaded/self-hosted-tts.js +137 -0
- package/runtime/dist/src/realtime/cascaded/transcribe.js +42 -0
- package/runtime/dist/src/realtime/coding-progress-narration.js +28 -0
- package/runtime/dist/src/realtime/confirmation-turn-isolation.js +586 -0
- package/runtime/dist/src/realtime/dictation.js +28 -0
- package/runtime/dist/src/realtime/evidence.js +276 -0
- package/runtime/dist/src/realtime/floor.js +43 -0
- package/runtime/dist/src/realtime/frontend-instructions.js +195 -0
- package/runtime/dist/src/realtime/gemini.js +517 -0
- package/runtime/dist/src/realtime/history.js +122 -0
- package/runtime/dist/src/realtime/host-delivery.js +1711 -0
- package/runtime/dist/src/realtime/integrated-wire-profile.js +128 -0
- package/runtime/dist/src/realtime/memory-board.js +105 -0
- package/runtime/dist/src/realtime/openai-wire-profile.js +46 -0
- package/runtime/dist/src/realtime/playback.js +242 -0
- package/runtime/dist/src/realtime/project-confirmation-flow.js +1428 -0
- package/runtime/dist/src/realtime/prompt-language.js +17 -0
- package/runtime/dist/src/realtime/protocol.js +428 -0
- package/runtime/dist/src/realtime/provider-projection.js +526 -0
- package/runtime/dist/src/realtime/provider-session.js +491 -0
- package/runtime/dist/src/realtime/qwen-transport.js +144 -0
- package/runtime/dist/src/realtime/qwen.js +1377 -0
- package/runtime/dist/src/realtime/recall.js +341 -0
- package/runtime/dist/src/realtime/service-ports.js +8 -0
- package/runtime/dist/src/realtime/service-state.js +259 -0
- package/runtime/dist/src/realtime/service.js +1726 -0
- package/runtime/dist/src/realtime/session-state.js +684 -0
- package/runtime/dist/src/realtime/session.js +1976 -0
- package/runtime/dist/src/realtime/speech-prep.js +63 -0
- package/runtime/dist/src/realtime/streaming-speech.js +120 -0
- package/runtime/dist/src/realtime/system-prompts.en.js +136 -0
- package/runtime/dist/src/realtime/telemetry.js +144 -0
- package/runtime/dist/src/realtime/tool-continuations.js +1510 -0
- package/runtime/dist/src/realtime/transport.js +8 -0
- package/runtime/dist/src/realtime/usage.js +55 -0
- package/runtime/dist/src/realtime/user-origin-binding.js +173 -0
- package/runtime/dist/src/realtime/volcengine/ark.js +428 -0
- package/runtime/dist/src/realtime/volcengine/asr.js +573 -0
- package/runtime/dist/src/realtime/volcengine/audio.js +39 -0
- package/runtime/dist/src/realtime/volcengine/endpointing-capability.js +834 -0
- package/runtime/dist/src/realtime/volcengine/livekit-endpointing.js +714 -0
- package/runtime/dist/src/realtime/volcengine/local-eot-executor.js +33 -0
- package/runtime/dist/src/realtime/volcengine/protocol.js +247 -0
- package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +237 -0
- package/runtime/dist/src/realtime/volcengine/tts.js +444 -0
- package/runtime/dist/src/realtime/volcengine/websocket.js +293 -0
- package/runtime/dist/src/server/aoq-chat-server.js +497 -0
- package/runtime/dist/src/server/client-pairing.js +192 -0
- package/runtime/dist/src/server/client-protocol.js +87 -0
- package/runtime/dist/src/server/client-server.js +312 -0
- package/runtime/dist/src/server/server-config.js +72 -0
- package/runtime/dist/src/server-entry.js +135 -0
- package/runtime/dist/src/storage/bounded-json.js +63 -0
- package/runtime/dist/src/storage/native-file-lock.js +8 -0
- package/runtime/dist/src/storage/native-resource-snapshot.js +41 -0
- package/runtime/dist/src/storage/private-database.js +120 -0
- package/runtime/dist/src/text/canonical-json.js +60 -0
- package/runtime/dist/src/text/python-number.js +18 -0
- package/runtime/dist/src/text/python-text.js +92 -0
- package/runtime/dist/src/text/unicode-casefold.js +29 -0
- package/runtime/dist/src/text/unicode-normalize.js +138 -0
- package/runtime/dist/src/text/unicode-tables.js +210 -0
- package/runtime/dist/src/understanding/candidates.js +77 -0
- package/runtime/dist/src/understanding/fixture.js +7 -0
- package/runtime/dist/src/understanding/jev.js +20 -0
- package/runtime/dist/src/understanding/pipeline.js +38 -0
- package/runtime/dist/src/voicemem/store-client.js +476 -0
- package/runtime/dist/src/voicemem/store-worker.js +380 -0
- package/runtime/dist/src/voicemem/versioned-memory.js +170 -0
- package/runtime/scripts/pair-device.mjs +109 -0
- package/src/command.mjs +48 -0
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
import { translateSystemPrompt } from '../realtime/prompt-language.js';
|
|
2
|
+
/** AOQ credential/data broker; Runtime ownership is supplied through hooks, never constructed here. */
|
|
3
|
+
import { randomUUID, timingSafeEqual } from 'node:crypto';
|
|
4
|
+
import { performance } from 'node:perf_hooks';
|
|
5
|
+
import { WebSocket, WebSocketServer } from 'ws';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
const MAX_JSON_BYTES = 16 * 1024;
|
|
8
|
+
const MAX_RESPONSE_BYTES = 64 * 1024;
|
|
9
|
+
const MAX_BUFFERED_BYTES = 256 * 1024;
|
|
10
|
+
const TRANSPORT = 'qwen_aoq_chat_v1';
|
|
11
|
+
const RUNTIME_TRANSPORT = 'qwen_aoq_runtime_v1';
|
|
12
|
+
const MAX_EVENT_BYTES = 64 * 1024;
|
|
13
|
+
const MAX_ENVELOPE_BYTES = 128 * 1024;
|
|
14
|
+
const hostEvents = new Set(['session.update', 'conversation.item.create', 'conversation.item.delete',
|
|
15
|
+
'conversation.item.truncate', 'input_audio_buffer.clear', 'response.create', 'response.cancel']);
|
|
16
|
+
const providerEvents = new Set(['session.created', 'session.updated', 'error',
|
|
17
|
+
'input_audio_buffer.speech_started', 'input_audio_buffer.speech_stopped', 'input_audio_buffer.committed', 'input_audio_buffer.cleared',
|
|
18
|
+
'conversation.item.created', 'conversation.item.deleted', 'conversation.item.truncated',
|
|
19
|
+
'conversation.item.input_audio_transcription.completed', 'conversation.item.input_audio_transcription.failed',
|
|
20
|
+
// Qwen-Audio ASR metadata only: the adapter deliberately ignores partial/ambient text.
|
|
21
|
+
'conversation.item.input_audio_transcription.delta', 'conversation.item.ambient_audio_transcription.delta',
|
|
22
|
+
'conversation.item.ambient_audio_transcription.completed',
|
|
23
|
+
'response.created', 'response.done', 'response.output_item.added', 'response.output_item.done',
|
|
24
|
+
'response.content_part.added', 'response.content_part.done', 'response.audio_transcript.delta', 'response.audio_transcript.done',
|
|
25
|
+
'response.output_audio_transcript.delta', 'response.output_audio_transcript.done', 'response.text.delta', 'response.text.done',
|
|
26
|
+
'response.output_text.delta', 'response.output_text.done',
|
|
27
|
+
'response.function_call_arguments.delta', 'response.function_call_arguments.done', 'response.audio.done']);
|
|
28
|
+
const eventEnvelope = z.object({ type: z.literal('aoq.event'), connection_id: z.uuid(),
|
|
29
|
+
sequence: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER), event: z.record(z.string(), z.unknown()) }).strict();
|
|
30
|
+
function validateEvent(event, allowed) {
|
|
31
|
+
if (!event || Array.isArray(event) || typeof event.type !== 'string' || !allowed.has(event.type))
|
|
32
|
+
throw new Error('invalid AOQ event');
|
|
33
|
+
const raw = JSON.stringify(event);
|
|
34
|
+
if (Buffer.byteLength(raw) > MAX_EVENT_BYTES)
|
|
35
|
+
throw new Error('AOQ event too large');
|
|
36
|
+
// Validate the JSON tree without recursive descent or accepting audio payloads in nested items.
|
|
37
|
+
const pending = [event];
|
|
38
|
+
while (pending.length) {
|
|
39
|
+
const value = pending.pop();
|
|
40
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean')
|
|
41
|
+
continue;
|
|
42
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
43
|
+
continue;
|
|
44
|
+
if (typeof value !== 'object' || (Object.getPrototypeOf(value) !== Object.prototype && !Array.isArray(value)))
|
|
45
|
+
throw new Error('invalid AOQ JSON');
|
|
46
|
+
for (const [key, child] of Object.entries(value)) {
|
|
47
|
+
if (['audio', 'base64', 'pcm', 'audio_delta'].includes(key))
|
|
48
|
+
throw new Error('AOQ audio payload rejected');
|
|
49
|
+
pending.push(child);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return raw;
|
|
53
|
+
}
|
|
54
|
+
const text = z.string().trim().min(1).max(8192);
|
|
55
|
+
const allocationSchema = z.object({
|
|
56
|
+
aoqTokenForClient: text, sid: text, clientRelayCertFingerprint: text,
|
|
57
|
+
clientRelayEndpoints: z.array(z.object({ endpoint: text.max(253), port: z.number().int().min(1).max(65535),
|
|
58
|
+
route_index: z.number().int().nonnegative().optional() })).min(1).max(8),
|
|
59
|
+
extraInfo: z.object({ workspaceIdHash: text }),
|
|
60
|
+
sidExpiresInSecs: z.number().positive().max(2_147_483),
|
|
61
|
+
});
|
|
62
|
+
const helloSchema = z.object({ type: z.literal('hello'), token: z.string(), language: z.enum(['zh-CN', 'en']).optional() });
|
|
63
|
+
const mediaSchema = z.object({ protocol_version: z.literal(1),
|
|
64
|
+
media: z.object({ transports: z.array(z.string()).max(32) }) });
|
|
65
|
+
const connectSchema = z.object({ type: z.literal('aoq.connect'), connection_id: z.uuid(), request_id: z.uuid() }).strict();
|
|
66
|
+
/** Beijing workspace hosts only; callers cannot supply a URL, port, path or redirect. */
|
|
67
|
+
export function aoqCredentialURL(host) {
|
|
68
|
+
if (!/^llm-[a-z0-9]+\.cn-beijing\.maas\.aliyuncs\.com$/u.test(host))
|
|
69
|
+
throw new Error('invalid_aoq_api_host');
|
|
70
|
+
return `https://${host}/api/v1/webrtc/realtime?model=qwen-audio-3.0-realtime-plus`;
|
|
71
|
+
}
|
|
72
|
+
/** Only the official top-level allocation is accepted; errors never retain upstream text. */
|
|
73
|
+
export async function issueAoqCredential(apiKey, signal, apiHost, fetcher = fetch) {
|
|
74
|
+
const controller = new AbortController();
|
|
75
|
+
const abort = () => controller.abort();
|
|
76
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
77
|
+
if (signal.aborted)
|
|
78
|
+
abort();
|
|
79
|
+
const timeout = setTimeout(abort, 8000);
|
|
80
|
+
let reader;
|
|
81
|
+
try {
|
|
82
|
+
if (!apiKey.trim())
|
|
83
|
+
throw new Error();
|
|
84
|
+
const response = await fetcher(aoqCredentialURL(apiHost), {
|
|
85
|
+
method: 'POST', body: '{}', redirect: 'error', signal: controller.signal,
|
|
86
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}`, 'x-dashscope-rtc-transport': 'moq' },
|
|
87
|
+
});
|
|
88
|
+
reader = response.body?.getReader();
|
|
89
|
+
if (!response.ok || response.redirected || !reader || Number(response.headers.get('content-length')) > MAX_RESPONSE_BYTES)
|
|
90
|
+
throw new Error();
|
|
91
|
+
const chunks = [];
|
|
92
|
+
let size = 0;
|
|
93
|
+
while (true) {
|
|
94
|
+
const { value, done } = await reader.read();
|
|
95
|
+
if (done)
|
|
96
|
+
break;
|
|
97
|
+
size += value.byteLength;
|
|
98
|
+
if (size > MAX_RESPONSE_BYTES)
|
|
99
|
+
throw new Error();
|
|
100
|
+
chunks.push(value);
|
|
101
|
+
}
|
|
102
|
+
controller.signal.throwIfAborted();
|
|
103
|
+
return allocationSchema.parse(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
throw new Error('credential_unavailable');
|
|
107
|
+
}
|
|
108
|
+
finally {
|
|
109
|
+
clearTimeout(timeout);
|
|
110
|
+
signal.removeEventListener('abort', abort);
|
|
111
|
+
controller.abort();
|
|
112
|
+
void reader?.cancel().catch(() => { });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
export class AoqChatServer {
|
|
116
|
+
#options;
|
|
117
|
+
#Commands;
|
|
118
|
+
#instanceId = randomUUID();
|
|
119
|
+
#server;
|
|
120
|
+
#active;
|
|
121
|
+
#closed = false;
|
|
122
|
+
// ponytail: process-local, shared-token rolling budget; use shared storage if deploying multiple brokers.
|
|
123
|
+
#attempts = [];
|
|
124
|
+
constructor(options) {
|
|
125
|
+
if (!/^[a-f0-9]{32}$/u.test(options.token) || !Number.isInteger(options.port) || options.port < 0 || options.port > 65535) {
|
|
126
|
+
throw new Error('invalid AOQ server configuration');
|
|
127
|
+
}
|
|
128
|
+
for (const ms of [options.authTimeoutMs ?? 3000, options.credentialTimeoutMs ?? 8000, options.heartbeatMs ?? 15000]) {
|
|
129
|
+
if (!Number.isFinite(ms) || ms <= 0 || ms > 2_147_483_647)
|
|
130
|
+
throw new Error('invalid AOQ timeout');
|
|
131
|
+
}
|
|
132
|
+
if (options.voice !== undefined && !/^[a-zA-Z0-9_-]{1,64}$/u.test(options.voice))
|
|
133
|
+
throw new Error('invalid AOQ voice');
|
|
134
|
+
if (options.runtime && options.runtime.token !== options.token)
|
|
135
|
+
throw new Error('AOQ runtime token mismatch');
|
|
136
|
+
this.#options = options;
|
|
137
|
+
}
|
|
138
|
+
async start() {
|
|
139
|
+
if (this.#server || this.#closed)
|
|
140
|
+
throw new Error('AOQ server already started or stopped');
|
|
141
|
+
if (this.#options.runtime)
|
|
142
|
+
this.#Commands = (await import('./client-protocol.js')).ClientCommands;
|
|
143
|
+
if (this.#server || this.#closed)
|
|
144
|
+
throw new Error('AOQ server already started or stopped');
|
|
145
|
+
const server = new WebSocketServer({ host: '127.0.0.1', port: this.#options.port,
|
|
146
|
+
maxPayload: this.#options.runtime ? MAX_ENVELOPE_BYTES : MAX_JSON_BYTES - 1, perMessageDeflate: false });
|
|
147
|
+
this.#server = server;
|
|
148
|
+
server.on('connection', (socket, request) => {
|
|
149
|
+
socket.on('error', () => { socket.terminate(); });
|
|
150
|
+
if (!this.#closed && this.#options.pairing?.handle(socket, request.url))
|
|
151
|
+
return;
|
|
152
|
+
if (request.url !== '/client/v1') {
|
|
153
|
+
this.#closeSocket(socket, 4004);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
if (this.#active || this.#closed) {
|
|
157
|
+
this.#closeSocket(socket, 4009);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
this.#accept(socket);
|
|
161
|
+
});
|
|
162
|
+
await new Promise((resolve, reject) => {
|
|
163
|
+
server.once('listening', resolve);
|
|
164
|
+
server.once('error', reject);
|
|
165
|
+
});
|
|
166
|
+
server.on('error', () => { });
|
|
167
|
+
const address = server.address();
|
|
168
|
+
if (!address || typeof address === 'string')
|
|
169
|
+
throw new Error('AOQ server did not bind');
|
|
170
|
+
return { token: this.#options.token, host: '127.0.0.1', port: address.port };
|
|
171
|
+
}
|
|
172
|
+
async close() {
|
|
173
|
+
this.#closed = true;
|
|
174
|
+
if (this.#active)
|
|
175
|
+
this.#release(this.#active);
|
|
176
|
+
const server = this.#server;
|
|
177
|
+
this.#server = undefined;
|
|
178
|
+
if (!server)
|
|
179
|
+
return;
|
|
180
|
+
for (const socket of server.clients)
|
|
181
|
+
socket.terminate();
|
|
182
|
+
await new Promise(resolve => server.close(() => resolve()));
|
|
183
|
+
}
|
|
184
|
+
async sendText(raw) {
|
|
185
|
+
const c = this.#active;
|
|
186
|
+
if (!this.#options.runtime || !c?.authenticated)
|
|
187
|
+
throw new Error('AOQ runtime unavailable');
|
|
188
|
+
if (Buffer.byteLength(raw) >= MAX_JSON_BYTES)
|
|
189
|
+
throw new Error('AOQ desktop frame too large');
|
|
190
|
+
const frame = z.object({ type: z.string().min(1) }).parse(JSON.parse(raw));
|
|
191
|
+
if (frame.type.startsWith('aoq.') || frame.type === 'hello' || frame.type === 'client.command'
|
|
192
|
+
|| hostEvents.has(frame.type) || providerEvents.has(frame.type))
|
|
193
|
+
throw new Error('invalid AOQ desktop frame');
|
|
194
|
+
await this.#write(c, raw, MAX_JSON_BYTES - 1);
|
|
195
|
+
}
|
|
196
|
+
sendBinary(raw) {
|
|
197
|
+
void raw;
|
|
198
|
+
return Promise.reject(new Error('AOQ binary transport is unavailable'));
|
|
199
|
+
}
|
|
200
|
+
disconnectClient() {
|
|
201
|
+
const c = this.#active;
|
|
202
|
+
if (c) {
|
|
203
|
+
this.#release(c);
|
|
204
|
+
c.socket.terminate();
|
|
205
|
+
}
|
|
206
|
+
return Promise.resolve();
|
|
207
|
+
}
|
|
208
|
+
#release(c) {
|
|
209
|
+
if (this.#active !== c)
|
|
210
|
+
return;
|
|
211
|
+
this.#active = undefined;
|
|
212
|
+
clearTimeout(c.authTimer);
|
|
213
|
+
clearTimeout(c.credentialTimer);
|
|
214
|
+
clearInterval(c.heartbeat);
|
|
215
|
+
const runtime = this.#options.runtime;
|
|
216
|
+
// Fence the desktop epoch before releasing the provider, even when a hook throws.
|
|
217
|
+
if (c.authenticated) {
|
|
218
|
+
try {
|
|
219
|
+
void Promise.resolve(runtime?.onClientDisconnect?.({ hadProviderAttachment: c.providerConnected })).catch(() => { });
|
|
220
|
+
}
|
|
221
|
+
catch { /* Continue owned cleanup. */ }
|
|
222
|
+
}
|
|
223
|
+
if (c.providerConnected) {
|
|
224
|
+
c.providerConnected = false;
|
|
225
|
+
try {
|
|
226
|
+
void Promise.resolve(runtime?.onProviderDisconnect(c.id)).catch(() => { });
|
|
227
|
+
}
|
|
228
|
+
catch { /* Never leak hook errors. */ }
|
|
229
|
+
}
|
|
230
|
+
c.abort.abort();
|
|
231
|
+
}
|
|
232
|
+
#closeSocket(socket, code) {
|
|
233
|
+
socket.close(code, 'AOQ connection closed');
|
|
234
|
+
const grace = setTimeout(() => socket.terminate(), 500);
|
|
235
|
+
grace.unref();
|
|
236
|
+
socket.once('close', () => clearTimeout(grace));
|
|
237
|
+
}
|
|
238
|
+
#reject(c, code = c.authenticated ? 1002 : 4003, reason = 'invalid_message', eventType = 'unknown') {
|
|
239
|
+
if (this.#active !== c)
|
|
240
|
+
return;
|
|
241
|
+
if (code === 1002 || code === 4003) {
|
|
242
|
+
const safeType = typeof eventType === 'string' && /^[a-z_.]{1,80}$/u.test(eventType) ? eventType : 'unknown';
|
|
243
|
+
try {
|
|
244
|
+
this.#options.onDiagnostic?.(`[runtime-diagnostic] aoq_protocol_rejected type=${safeType} reason=${reason}`);
|
|
245
|
+
}
|
|
246
|
+
catch { /* Diagnostics cannot prevent cleanup. */ }
|
|
247
|
+
}
|
|
248
|
+
this.#release(c);
|
|
249
|
+
this.#closeSocket(c.socket, code);
|
|
250
|
+
}
|
|
251
|
+
#unavailable(c) {
|
|
252
|
+
if (this.#active !== c)
|
|
253
|
+
return;
|
|
254
|
+
this.#send(c, { type: 'aoq.error', code: 'credential_unavailable' });
|
|
255
|
+
this.#reject(c, 4008);
|
|
256
|
+
}
|
|
257
|
+
#send(c, frame) {
|
|
258
|
+
if (this.#active !== c || c.socket.readyState !== WebSocket.OPEN)
|
|
259
|
+
return false;
|
|
260
|
+
void this.#write(c, JSON.stringify(frame), MAX_JSON_BYTES - 1).catch(() => this.#reject(c));
|
|
261
|
+
return this.#active === c;
|
|
262
|
+
}
|
|
263
|
+
async #write(c, raw, maxBytes) {
|
|
264
|
+
if (this.#active !== c || c.socket.readyState !== WebSocket.OPEN)
|
|
265
|
+
throw new Error('AOQ connection unavailable');
|
|
266
|
+
const size = Buffer.byteLength(raw);
|
|
267
|
+
if (size > maxBytes || c.pendingSendBytes + size > MAX_BUFFERED_BYTES
|
|
268
|
+
|| c.socket.bufferedAmount + size > MAX_BUFFERED_BYTES || c.pendingSends >= 128) {
|
|
269
|
+
this.#reject(c, 4008);
|
|
270
|
+
throw new Error('AOQ send queue full');
|
|
271
|
+
}
|
|
272
|
+
c.pendingSends++;
|
|
273
|
+
c.pendingSendBytes += size;
|
|
274
|
+
try {
|
|
275
|
+
await new Promise((resolve, reject) => c.socket.send(raw, error => error ? reject(new Error('AOQ send failed')) : resolve()));
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
this.#reject(c);
|
|
279
|
+
throw new Error('AOQ send failed');
|
|
280
|
+
}
|
|
281
|
+
finally {
|
|
282
|
+
c.pendingSends--;
|
|
283
|
+
c.pendingSendBytes -= size;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
async #sendProvider(c, event) {
|
|
287
|
+
if (this.#active !== c || !c.providerConnected || !Number.isSafeInteger(c.outboundSequence + 1))
|
|
288
|
+
throw new Error('AOQ provider unavailable');
|
|
289
|
+
const rawEvent = validateEvent(event, hostEvents);
|
|
290
|
+
const raw = `{"type":"aoq.command","connection_id":${JSON.stringify(c.id)},"sequence":${++c.outboundSequence},"event":${rawEvent}}`;
|
|
291
|
+
await this.#write(c, raw, MAX_ENVELOPE_BYTES);
|
|
292
|
+
}
|
|
293
|
+
#control(c, raw) {
|
|
294
|
+
const size = Buffer.byteLength(raw);
|
|
295
|
+
if (++c.pendingControls > 128 || (c.pendingControlBytes += size) > MAX_BUFFERED_BYTES) {
|
|
296
|
+
this.#reject(c, 4008);
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
c.controlLane = c.controlLane.then(async () => {
|
|
300
|
+
await c.authentication;
|
|
301
|
+
if (this.#active !== c || !c.commands)
|
|
302
|
+
return;
|
|
303
|
+
const result = await c.commands.receive(raw, control => {
|
|
304
|
+
if (this.#active !== c || !this.#options.runtime?.onControl)
|
|
305
|
+
throw new Error('AOQ control unavailable');
|
|
306
|
+
return this.#options.runtime.onControl(control);
|
|
307
|
+
});
|
|
308
|
+
if (this.#active !== c)
|
|
309
|
+
return;
|
|
310
|
+
await this.#write(c, JSON.stringify(result), MAX_JSON_BYTES - 1);
|
|
311
|
+
if (c.commands.full)
|
|
312
|
+
this.#reject(c, 4008);
|
|
313
|
+
}).catch(() => this.#reject(c)).finally(() => { c.pendingControls--; c.pendingControlBytes -= size; });
|
|
314
|
+
}
|
|
315
|
+
#accept(socket) {
|
|
316
|
+
const id = randomUUID();
|
|
317
|
+
const c = { socket, id, abort: new AbortController(),
|
|
318
|
+
...(this.#Commands ? { commands: new this.#Commands(id) } : {}),
|
|
319
|
+
controlLane: Promise.resolve(), pendingControls: 0, pendingControlBytes: 0, pendingSendBytes: 0,
|
|
320
|
+
allocated: false, providerConnected: false, inboundSequence: 0, outboundSequence: 0,
|
|
321
|
+
authenticated: false, requested: false, alive: true, pendingSends: 0, burstMessages: 0, burstBytes: 0 };
|
|
322
|
+
this.#active = c;
|
|
323
|
+
c.authTimer = setTimeout(() => this.#reject(c, 4003, 'auth_timeout'), this.#options.authTimeoutMs ?? 3000);
|
|
324
|
+
socket.once('close', () => this.#release(c));
|
|
325
|
+
socket.on('pong', () => { c.alive = true; });
|
|
326
|
+
c.heartbeat = setInterval(() => {
|
|
327
|
+
if (!c.alive) {
|
|
328
|
+
this.#release(c);
|
|
329
|
+
socket.terminate();
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
c.alive = false;
|
|
333
|
+
socket.ping();
|
|
334
|
+
}, this.#options.heartbeatMs ?? 15000);
|
|
335
|
+
socket.on('message', (data, binary) => {
|
|
336
|
+
if (this.#active !== c)
|
|
337
|
+
return;
|
|
338
|
+
const bytes = Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
|
|
339
|
+
c.burstBytes += bytes.byteLength;
|
|
340
|
+
c.burstMessages++;
|
|
341
|
+
// Parse synchronously; never queue frames behind an in-flight HTTP allocation.
|
|
342
|
+
if (c.burstMessages === 1)
|
|
343
|
+
queueMicrotask(() => { c.burstMessages = 0; c.burstBytes = 0; });
|
|
344
|
+
if (binary || bytes.byteLength > (this.#options.runtime ? MAX_ENVELOPE_BYTES : MAX_JSON_BYTES - 1) || c.burstBytes > MAX_BUFFERED_BYTES || c.burstMessages > 128) {
|
|
345
|
+
this.#reject(c, undefined, binary ? 'binary_rejected' : 'input_limit');
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
let rejectionReason = 'invalid_json';
|
|
349
|
+
let eventType = 'unknown';
|
|
350
|
+
try {
|
|
351
|
+
const raw = bytes.toString('utf8');
|
|
352
|
+
const frame = JSON.parse(raw);
|
|
353
|
+
rejectionReason = 'invalid_envelope';
|
|
354
|
+
const type = z.object({ type: z.string() }).parse(frame).type;
|
|
355
|
+
eventType = type;
|
|
356
|
+
if (bytes.byteLength >= MAX_JSON_BYTES && !(this.#options.runtime && c.authenticated && type === 'aoq.event')) {
|
|
357
|
+
this.#reject(c, undefined, 'input_limit', type);
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
if (!c.authenticated) {
|
|
361
|
+
rejectionReason = 'authentication_failed';
|
|
362
|
+
const hello = helloSchema.parse(frame);
|
|
363
|
+
const provided = Buffer.from(hello.token);
|
|
364
|
+
const expected = Buffer.from(this.#options.token);
|
|
365
|
+
if (!(this.#options.pairing ? this.#options.pairing.accepts(hello.token) : provided.length === expected.length && timingSafeEqual(provided, expected))) {
|
|
366
|
+
this.#reject(c, 4003, 'authentication_failed', type);
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
const media = mediaSchema.safeParse(frame);
|
|
370
|
+
const runtime = this.#options.runtime;
|
|
371
|
+
const transport = runtime ? RUNTIME_TRANSPORT : TRANSPORT;
|
|
372
|
+
if (!media.success || !media.data.media.transports.includes(transport)) {
|
|
373
|
+
this.#reject(c, 4006);
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
if (hello.language !== undefined)
|
|
377
|
+
c.language = hello.language;
|
|
378
|
+
c.authenticated = true;
|
|
379
|
+
if (this.#options.pairing) {
|
|
380
|
+
const untrack = this.#options.pairing.track(hello.token, () => this.#reject(c, 4003, 'device_revoked'));
|
|
381
|
+
socket.once('close', untrack);
|
|
382
|
+
}
|
|
383
|
+
clearTimeout(c.authTimer);
|
|
384
|
+
this.#send(c, { type: 'client.ready', protocol_version: 1, server_instance_id: this.#instanceId, connection_id: c.id,
|
|
385
|
+
input_audio: { encoding: 'pcm_s16le', sample_rate: 16000, channels: 1 },
|
|
386
|
+
output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 }, capabilities: runtime ? ['audio', 'captions', 'projects', 'executor'] : ['audio', 'captions'],
|
|
387
|
+
media: { transport, path: 'direct', audio_owner: 'aoq_sdk', pipeline: 'integrated', mode: runtime ? 'runtime' : 'chat_only' } });
|
|
388
|
+
c.authentication = Promise.resolve(runtime?.onClientAuthenticated?.(hello.language));
|
|
389
|
+
void c.authentication.catch(() => this.#reject(c));
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (this.#options.runtime && type === 'aoq.event') {
|
|
393
|
+
rejectionReason = 'invalid_event_envelope';
|
|
394
|
+
const envelope = eventEnvelope.parse(frame);
|
|
395
|
+
eventType = envelope.event.type;
|
|
396
|
+
if (!c.allocated) {
|
|
397
|
+
this.#reject(c, 1002, 'not_allocated', eventType);
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
if (envelope.connection_id !== c.id) {
|
|
401
|
+
this.#reject(c, 1002, 'connection_mismatch', eventType);
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
if (envelope.sequence !== c.inboundSequence + 1) {
|
|
405
|
+
this.#reject(c, 1002, 'event_sequence', eventType);
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
if (typeof eventType !== 'string' || !providerEvents.has(eventType)) {
|
|
409
|
+
this.#reject(c, 1002, 'unsupported_event', eventType);
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
rejectionReason = 'invalid_event_payload';
|
|
413
|
+
validateEvent(envelope.event, providerEvents);
|
|
414
|
+
c.inboundSequence = envelope.sequence;
|
|
415
|
+
rejectionReason = 'provider_hook_failed';
|
|
416
|
+
void Promise.resolve(this.#options.runtime.onProviderEvent(c.id, envelope.event)).catch(() => this.#reject(c));
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
if (this.#options.runtime && type === 'client.command') {
|
|
420
|
+
this.#control(c, raw);
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
rejectionReason = 'invalid_connect';
|
|
424
|
+
const request = connectSchema.parse(frame);
|
|
425
|
+
if (request.connection_id !== c.id) {
|
|
426
|
+
this.#reject(c);
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
if (c.requested) {
|
|
430
|
+
this.#unavailable(c);
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
c.requested = true;
|
|
434
|
+
const now = (this.#options.now ?? (() => performance.now()))();
|
|
435
|
+
this.#attempts = this.#attempts.filter(time => now - time < 60_000);
|
|
436
|
+
if (this.#attempts.length >= 6) {
|
|
437
|
+
this.#unavailable(c);
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
this.#attempts.push(now);
|
|
441
|
+
c.credentialTimer = setTimeout(() => this.#unavailable(c), this.#options.credentialTimeoutMs ?? 8000);
|
|
442
|
+
void this.#allocate(c, request.request_id, now);
|
|
443
|
+
}
|
|
444
|
+
catch {
|
|
445
|
+
this.#reject(c, undefined, rejectionReason, eventType);
|
|
446
|
+
}
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
async #allocate(c, requestId, started) {
|
|
450
|
+
try {
|
|
451
|
+
// Issue the credential in parallel with the language hook so credentialTimeoutMs keeps
|
|
452
|
+
// covering issuance alone, then settle the hook before the provider attaches or
|
|
453
|
+
// instructions render -- c.language itself is already assigned synchronously at hello.
|
|
454
|
+
const credential = this.#options.issueCredential(c.abort.signal);
|
|
455
|
+
const result = allocationSchema.parse(await credential);
|
|
456
|
+
if (this.#active !== c || c.abort.signal.aborted)
|
|
457
|
+
return;
|
|
458
|
+
clearTimeout(c.credentialTimer);
|
|
459
|
+
await c.authentication;
|
|
460
|
+
if (this.#active !== c || c.abort.signal.aborted)
|
|
461
|
+
return;
|
|
462
|
+
const { sidExpiresInSecs, clientRelayEndpoints, ...fields } = result;
|
|
463
|
+
const credentials = { ...fields, clientRelayEndpoints: clientRelayEndpoints.map(({ endpoint, port, route_index }, index) => ({
|
|
464
|
+
endpoint, port, routeIndex: route_index ?? index,
|
|
465
|
+
})) };
|
|
466
|
+
const remaining = sidExpiresInSecs * 1000 - ((this.#options.now ?? (() => performance.now()))() - started);
|
|
467
|
+
if (remaining <= 0) {
|
|
468
|
+
this.#unavailable(c);
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
const frame = { type: 'aoq.credentials', connection_id: c.id, request_id: requestId, credentials,
|
|
472
|
+
...(this.#options.runtime ? { mode: 'runtime' } : { session: { modalities: ['text', 'audio'], voice: this.#options.voice ?? 'longanqian',
|
|
473
|
+
input_audio_format: 'pcm', output_audio_format: 'pcm',
|
|
474
|
+
instructions: translateSystemPrompt('你是Nova,一个自然、友好的语音聊天助手。仅进行纯聊天,不执行主机工具,不操作文件、终端、项目或设备,也不声称已执行这些操作。', c.language ?? this.#options.language),
|
|
475
|
+
turn_detection: { type: 'smart_turn' } } }) };
|
|
476
|
+
if (Buffer.byteLength(JSON.stringify(frame)) >= MAX_JSON_BYTES) {
|
|
477
|
+
this.#unavailable(c);
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
if (this.#options.runtime) {
|
|
481
|
+
c.providerConnected = true;
|
|
482
|
+
void Promise.resolve(this.#options.runtime.onProviderConnect({ id: c.id, send: event => this.#sendProvider(c, event),
|
|
483
|
+
disconnect: () => { if (this.#active === c)
|
|
484
|
+
this.#reject(c, 4008); } })).catch(() => this.#unavailable(c));
|
|
485
|
+
}
|
|
486
|
+
if (!this.#send(c, frame))
|
|
487
|
+
return;
|
|
488
|
+
c.allocated = true;
|
|
489
|
+
// sidExpiresInSecs is not documented as a broker-enforced active-call deadline.
|
|
490
|
+
// The SDK/upstream owns post-connect expiry; never truncate a live call here.
|
|
491
|
+
}
|
|
492
|
+
catch {
|
|
493
|
+
this.#unavailable(c);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
//# sourceMappingURL=aoq-chat-server.js.map
|