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,517 @@
|
|
|
1
|
+
import { canonicalJson } from '../text/canonical-json.js';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { abortable } from '../core/camera-session.js';
|
|
4
|
+
import { frontendInstructions } from './frontend-instructions.js';
|
|
5
|
+
import { committedConversationPairsSchema, dispatchSourceContext } from './history.js';
|
|
6
|
+
import { ProviderResponseRejectedError, hostContextItemSchema, responseAdaptationContextSchema } from './protocol.js';
|
|
7
|
+
import { reportUsage } from './usage.js';
|
|
8
|
+
const MAX_QUEUE = 4096;
|
|
9
|
+
const MAX_PENDING = 128;
|
|
10
|
+
const MAX_TEXT = 4000;
|
|
11
|
+
const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
12
|
+
const failure = () => new Error('Gemini Live protocol or connection failed');
|
|
13
|
+
/** Native Live session. Host facts are staged locally, as in the cascaded adapter.
|
|
14
|
+
* Replaceable system context uses a fresh acknowledged setup; it never masquerades as user input.
|
|
15
|
+
* Internal transport replacement retains the host epoch but invalidates every old socket reader.
|
|
16
|
+
*/
|
|
17
|
+
export class GeminiLiveAdapter {
|
|
18
|
+
userResponseMode = 'automatic';
|
|
19
|
+
responseAdaptationMode = 'session_setup';
|
|
20
|
+
mediaCapability = { originalImageInput: false };
|
|
21
|
+
#options;
|
|
22
|
+
#id;
|
|
23
|
+
#epoch = 0;
|
|
24
|
+
#socket;
|
|
25
|
+
#controller = new AbortController();
|
|
26
|
+
#queue = [];
|
|
27
|
+
#wake;
|
|
28
|
+
#tail = Promise.resolve();
|
|
29
|
+
#tools = [];
|
|
30
|
+
#history = [];
|
|
31
|
+
#workspace;
|
|
32
|
+
#adaptation;
|
|
33
|
+
#pending = new Map();
|
|
34
|
+
#calls = new Map();
|
|
35
|
+
#response;
|
|
36
|
+
#completed = new Map();
|
|
37
|
+
#user;
|
|
38
|
+
#latestUser = '';
|
|
39
|
+
#nextOrigin;
|
|
40
|
+
#used = false;
|
|
41
|
+
#visibleResponses = new Map();
|
|
42
|
+
#audioUsed = false;
|
|
43
|
+
#allowToolContinuation = false;
|
|
44
|
+
#yieldedId;
|
|
45
|
+
#toolUser = '';
|
|
46
|
+
#usage;
|
|
47
|
+
constructor(options) {
|
|
48
|
+
this.#options = options;
|
|
49
|
+
this.#id = options.idFactory ?? randomUUID;
|
|
50
|
+
if (!options.apiKey || !options.model || !options.voice)
|
|
51
|
+
throw failure();
|
|
52
|
+
if (options.history)
|
|
53
|
+
this.#history = committedConversationPairsSchema.parse(options.history);
|
|
54
|
+
}
|
|
55
|
+
async connect(options) {
|
|
56
|
+
if (this.#socket)
|
|
57
|
+
throw failure();
|
|
58
|
+
this.#epoch++;
|
|
59
|
+
this.#controller = new AbortController();
|
|
60
|
+
this.#queue = [];
|
|
61
|
+
this.#tools = structuredClone(options.tools);
|
|
62
|
+
this.#visibleResponses.clear();
|
|
63
|
+
this.#nextOrigin = undefined;
|
|
64
|
+
this.#audioUsed = false;
|
|
65
|
+
this.#allowToolContinuation = false;
|
|
66
|
+
this.#yieldedId = undefined;
|
|
67
|
+
this.#toolUser = '';
|
|
68
|
+
this.#pending.clear();
|
|
69
|
+
this.#calls.clear();
|
|
70
|
+
this.#completed.clear();
|
|
71
|
+
this.#response = undefined;
|
|
72
|
+
this.#user = undefined;
|
|
73
|
+
this.#workspace = undefined;
|
|
74
|
+
this.#adaptation = undefined;
|
|
75
|
+
this.#used = false;
|
|
76
|
+
await this.#serial(() => this.#open(options.signal));
|
|
77
|
+
return { epoch: this.#epoch, provider_session_id: `gemini-${this.#epoch}-${this.#id()}` };
|
|
78
|
+
}
|
|
79
|
+
async restoreHistory(history, signal) {
|
|
80
|
+
if (this.#used)
|
|
81
|
+
throw failure();
|
|
82
|
+
this.#history = committedConversationPairsSchema.parse(history);
|
|
83
|
+
await this.#serial(() => this.#refresh(signal));
|
|
84
|
+
}
|
|
85
|
+
async setLanguage(language) {
|
|
86
|
+
if (language === this.#options.language)
|
|
87
|
+
return;
|
|
88
|
+
// Language changes require a new setup. Do not mutate other provider configuration.
|
|
89
|
+
this.#options = { ...this.#options, language: language ?? 'zh-CN' };
|
|
90
|
+
if (this.#socket)
|
|
91
|
+
await this.#serial(() => this.#refresh(this.#controller.signal));
|
|
92
|
+
}
|
|
93
|
+
async sendAudio(pcm, signal) {
|
|
94
|
+
if (!pcm.length || pcm.length % 2 || pcm.length > 65536)
|
|
95
|
+
throw failure();
|
|
96
|
+
const data = Buffer.from(pcm).toString('base64');
|
|
97
|
+
await this.#serial(async () => {
|
|
98
|
+
this.#used = true;
|
|
99
|
+
this.#audioUsed = true;
|
|
100
|
+
await this.#send({ realtimeInput: { audio: { mimeType: 'audio/pcm;rate=16000', data } } }, signal);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
async submitText(text, signal) {
|
|
104
|
+
if (!text.trim() || [...text].length > MAX_TEXT)
|
|
105
|
+
throw failure();
|
|
106
|
+
await this.#serial(async () => {
|
|
107
|
+
if (this.#response || this.#nextOrigin || this.#calls.size)
|
|
108
|
+
throw new Error('Gemini Live response is busy');
|
|
109
|
+
this.#used = true;
|
|
110
|
+
this.#latestUser = text;
|
|
111
|
+
const id = this.#id();
|
|
112
|
+
this.#emit({ kind: 'user_transcript_final', session_epoch: this.#epoch, item_id: id, text, input_kind: 'text' });
|
|
113
|
+
this.#nextOrigin = { kind: 'user_item', item_id: id };
|
|
114
|
+
await this.#send({ clientContent: { turns: [{ role: 'user', parts: [{ text }] }], turnComplete: true } }, signal);
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
injectHostItem(input, options) {
|
|
118
|
+
this.#assertLocal(options.signal);
|
|
119
|
+
const item = hostContextItemSchema.parse(input);
|
|
120
|
+
if (item.kind === 'workspace_context' || this.#pending.has(item.host_item_id) || this.#pending.size >= MAX_PENDING)
|
|
121
|
+
throw failure();
|
|
122
|
+
if (options.asUserActivation && item.kind !== 'progress' && item.kind !== 'final')
|
|
123
|
+
throw failure();
|
|
124
|
+
const id = `staged-${this.#id()}`;
|
|
125
|
+
this.#pending.set(item.host_item_id, { id, item: structuredClone(item) });
|
|
126
|
+
return Promise.resolve({ session_epoch: this.#epoch, host_item_id: item.host_item_id, provider_item_id: id, delivery: 'staged' });
|
|
127
|
+
}
|
|
128
|
+
retireHostItem(id, signal) {
|
|
129
|
+
this.#assertLocal(signal);
|
|
130
|
+
for (const [key, value] of this.#pending)
|
|
131
|
+
if (value.id === id)
|
|
132
|
+
this.#pending.delete(key);
|
|
133
|
+
return Promise.resolve();
|
|
134
|
+
}
|
|
135
|
+
async injectWorkspaceContext(input, options) {
|
|
136
|
+
const item = hostContextItemSchema.parse(input);
|
|
137
|
+
if (item.kind !== 'workspace_context' || item.session_epoch !== this.#epoch)
|
|
138
|
+
throw failure();
|
|
139
|
+
return this.#serial(async () => {
|
|
140
|
+
if (this.#workspace && item.revision <= this.#workspace.revision)
|
|
141
|
+
throw failure();
|
|
142
|
+
this.#workspace = structuredClone(item);
|
|
143
|
+
await this.#refresh(options.signal);
|
|
144
|
+
return { item, asUserActivation: false, delivery: { capability: 'refresh_session', delivered: true, session_epoch: this.#epoch, workspace_instance_id: item.workspace_instance_id, revision: item.revision, prior_provider_item_id: null, refresh_id: this.#id() } };
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
async replaceResponseAdaptation(input, signal) {
|
|
148
|
+
const context = responseAdaptationContextSchema.parse(input);
|
|
149
|
+
await this.#serial(async () => {
|
|
150
|
+
if (this.#adaptation && context.revision < this.#adaptation.revision)
|
|
151
|
+
throw failure();
|
|
152
|
+
const prior = this.#adaptation;
|
|
153
|
+
this.#adaptation = context;
|
|
154
|
+
if (JSON.stringify([prior?.content, prior?.user_sources]) === JSON.stringify([context.content, context.user_sources]))
|
|
155
|
+
return;
|
|
156
|
+
// Empty initial guidance has no server-visible effect.
|
|
157
|
+
if (!prior && !context.content && !context.user_sources?.length)
|
|
158
|
+
return;
|
|
159
|
+
await this.#refresh(signal);
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
async createResponse(intent, signal) {
|
|
163
|
+
await this.#serial(async () => {
|
|
164
|
+
this.#assert(signal);
|
|
165
|
+
const pending = this.#pending.get(intent.item.host_item_id);
|
|
166
|
+
if (!pending || canonicalJson(pending.item) !== canonicalJson(intent.item))
|
|
167
|
+
throw new ProviderResponseRejectedError('Host item is not staged on this connection');
|
|
168
|
+
if (this.#response || this.#nextOrigin)
|
|
169
|
+
throw new ProviderResponseRejectedError('Gemini Live response is busy');
|
|
170
|
+
const call = intent.item.call_id ? this.#calls.get(intent.item.call_id) : undefined;
|
|
171
|
+
if (intent.item.kind === 'tool_output' && (!call || call.socket !== this.#socket))
|
|
172
|
+
throw new ProviderResponseRejectedError('Gemini tool result does not belong to the current connection');
|
|
173
|
+
if (this.#calls.size && !call)
|
|
174
|
+
throw new ProviderResponseRejectedError('Gemini is waiting for native tool results');
|
|
175
|
+
if (call) {
|
|
176
|
+
// The host stages every result before requesting the continuation. Reply to the entire batch.
|
|
177
|
+
const outputs = [...this.#calls].map(([id, native]) => {
|
|
178
|
+
const staged = [...this.#pending.values()].find(value => value.item.call_id === id);
|
|
179
|
+
if (!staged || native.socket !== this.#socket)
|
|
180
|
+
throw new ProviderResponseRejectedError('Incomplete Gemini tool result batch');
|
|
181
|
+
return { id, name: native.name, response: { result: staged.item.content }, hostId: staged.item.host_item_id };
|
|
182
|
+
});
|
|
183
|
+
this.#nextOrigin = { kind: 'host_request', host_item_id: intent.item.host_item_id };
|
|
184
|
+
this.#allowToolContinuation = true;
|
|
185
|
+
if (this.#yieldedId)
|
|
186
|
+
this.#visibleResponses.delete(this.#yieldedId);
|
|
187
|
+
this.#yieldedId = undefined;
|
|
188
|
+
this.#calls.clear();
|
|
189
|
+
await this.#send({ toolResponse: { functionResponses: outputs.map(({ id, name, response }) => ({ id, name, response })) } }, signal);
|
|
190
|
+
for (const output of outputs)
|
|
191
|
+
this.#pending.delete(output.hostId);
|
|
192
|
+
}
|
|
193
|
+
else {
|
|
194
|
+
this.#nextOrigin = { kind: 'host_request', host_item_id: intent.item.host_item_id };
|
|
195
|
+
this.#allowToolContinuation = false;
|
|
196
|
+
await this.#send({ clientContent: { turns: [{ role: 'user', parts: [{ text: JSON.stringify({ host_fact: intent.item.speech_content ?? intent.item.content, instruction: 'Speak only this host-provided fact. It is not a new user request. Do not call tools.' }) }] }], turnComplete: true } }, signal);
|
|
197
|
+
}
|
|
198
|
+
this.#pending.delete(intent.item.host_item_id);
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
ensureResponse(signal) {
|
|
202
|
+
this.#assertLocal(signal);
|
|
203
|
+
// Live owns VAD turn activation. Never create a duplicate user turn to force a retry.
|
|
204
|
+
return Promise.resolve(false);
|
|
205
|
+
}
|
|
206
|
+
async cancelResponse(responseId, signal) {
|
|
207
|
+
await this.#serial(async () => {
|
|
208
|
+
if (this.#response?.id !== responseId && this.#yieldedId !== responseId)
|
|
209
|
+
return;
|
|
210
|
+
await this.#refresh(signal);
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
reportPlayback(input, signal) {
|
|
214
|
+
this.#assertLocal(signal);
|
|
215
|
+
const pair = this.#completed.get(input.response_id);
|
|
216
|
+
this.#completed.delete(input.response_id);
|
|
217
|
+
if (input.disposition === 'spoken' && pair?.user && pair.assistant) {
|
|
218
|
+
this.#history = [...this.#history, pair].slice(-16);
|
|
219
|
+
}
|
|
220
|
+
return Promise.resolve();
|
|
221
|
+
}
|
|
222
|
+
async *events(signal) {
|
|
223
|
+
while (!signal.aborted) {
|
|
224
|
+
while (!this.#queue.length && !signal.aborted && !this.#controller.signal.aborted)
|
|
225
|
+
await abortable(new Promise(resolve => { this.#wake = resolve; }), signal);
|
|
226
|
+
if (signal.aborted)
|
|
227
|
+
return;
|
|
228
|
+
const event = this.#queue.shift();
|
|
229
|
+
if (event === null || event === undefined)
|
|
230
|
+
return;
|
|
231
|
+
if (event.kind === 'response_started')
|
|
232
|
+
this.#visibleResponses.set(event.response_id, event.origin);
|
|
233
|
+
if (event.kind === 'response_terminal')
|
|
234
|
+
this.#visibleResponses.delete(event.response_id);
|
|
235
|
+
if (event.kind === 'tool_call_ready' && !this.#calls.has(event.call_id))
|
|
236
|
+
continue;
|
|
237
|
+
yield event;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
async close() {
|
|
241
|
+
this.#controller.abort();
|
|
242
|
+
const socket = this.#socket;
|
|
243
|
+
this.#socket = undefined;
|
|
244
|
+
this.#queue = [];
|
|
245
|
+
this.#queue.push(null);
|
|
246
|
+
this.#wake?.();
|
|
247
|
+
this.#wake = undefined;
|
|
248
|
+
if (socket)
|
|
249
|
+
await Promise.race([socket.close(), new Promise(resolve => setTimeout(resolve, 250))]);
|
|
250
|
+
}
|
|
251
|
+
#assertLocal(signal) { signal.throwIfAborted(); this.#controller.signal.throwIfAborted(); if (!this.#epoch)
|
|
252
|
+
throw failure(); }
|
|
253
|
+
#assert(signal) { this.#assertLocal(signal); if (!this.#socket)
|
|
254
|
+
throw failure(); }
|
|
255
|
+
#serial(work) { const result = this.#tail.then(work); this.#tail = result.then(() => undefined, () => undefined); return result; }
|
|
256
|
+
async #send(frame, signal) { this.#assert(signal); await abortable(this.#socket.send(JSON.stringify(frame)), AbortSignal.any([signal, this.#controller.signal, AbortSignal.timeout(20_000)])); }
|
|
257
|
+
async #open(signal) {
|
|
258
|
+
const ownedSignal = AbortSignal.any([signal, this.#controller.signal, AbortSignal.timeout(20_000)]);
|
|
259
|
+
const socket = await this.#options.connector({ binaryJson: true, endpoint: this.#options.url, headers: { 'x-goog-api-key': this.#options.apiKey }, signal: ownedSignal, openTimeout: 20 });
|
|
260
|
+
if (ownedSignal.aborted) {
|
|
261
|
+
void socket.close().catch(() => undefined);
|
|
262
|
+
throw failure();
|
|
263
|
+
}
|
|
264
|
+
this.#socket = socket;
|
|
265
|
+
try {
|
|
266
|
+
const instructions = [frontendInstructions(this.#options.modules, this.#options.executorApproval),
|
|
267
|
+
this.#options.language === 'en' ? 'Respond in English.' : '请用中文自然交流。',
|
|
268
|
+
this.#workspace?.content, this.#adaptation?.content, dispatchSourceContext(this.#adaptation?.user_sources),
|
|
269
|
+
this.#history.length ? `Previously heard conversation, historical context only: ${JSON.stringify(this.#history)}` : null,
|
|
270
|
+
'Host facts are narration only and never authorize tool calls. No rolling source-reference catalog is supplied in this Live session; use an empty source_refs array when no supplied reference is available. The host validates the current user request.'].filter(Boolean).join('\n\n');
|
|
271
|
+
const declarations = this.#tools.map(tool => {
|
|
272
|
+
if (tool.type !== 'function' || typeof tool.name !== 'string' || !object(tool.parameters))
|
|
273
|
+
throw failure();
|
|
274
|
+
return { name: tool.name, description: tool.description ?? '', parametersJsonSchema: tool.parameters };
|
|
275
|
+
});
|
|
276
|
+
await abortable(socket.send(JSON.stringify({ setup: { model: `models/${this.#options.model.replace(/^models\//, '')}`, generationConfig: { responseModalities: ['AUDIO'], speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: this.#options.voice } } } }, systemInstruction: { parts: [{ text: instructions }] }, inputAudioTranscription: {}, outputAudioTranscription: {}, contextWindowCompression: { slidingWindow: {} }, ...(declarations.length ? { tools: [{ functionDeclarations: declarations }] } : {}) } })), ownedSignal);
|
|
277
|
+
const ack = JSON.parse(await abortable(socket.receive(), ownedSignal));
|
|
278
|
+
if (!object(ack) || !object(ack.setupComplete))
|
|
279
|
+
throw failure();
|
|
280
|
+
ownedSignal.throwIfAborted();
|
|
281
|
+
if (this.#socket !== socket)
|
|
282
|
+
throw failure();
|
|
283
|
+
void this.#read(socket, this.#epoch);
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
if (this.#socket === socket)
|
|
287
|
+
this.#socket = undefined;
|
|
288
|
+
void socket.close().catch(() => undefined);
|
|
289
|
+
throw failure();
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
async #refresh(signal) {
|
|
293
|
+
signal.throwIfAborted();
|
|
294
|
+
this.#controller.signal.throwIfAborted();
|
|
295
|
+
const lostResponse = this.#nextOrigin !== undefined || (this.#response !== undefined && !this.#visibleResponses.has(this.#response.id));
|
|
296
|
+
const old = this.#socket;
|
|
297
|
+
this.#socket = undefined;
|
|
298
|
+
// Already consumed events need terminal cleanup; queued old events must never acquire authority.
|
|
299
|
+
this.#queue = [];
|
|
300
|
+
for (const [id, origin] of this.#visibleResponses)
|
|
301
|
+
this.#emit({ kind: 'response_terminal', session_epoch: this.#epoch, response_id: id, status: 'cancelled', reason: 'context_refresh', ...(origin ? { origin } : {}) });
|
|
302
|
+
this.#visibleResponses.clear();
|
|
303
|
+
this.#response = undefined;
|
|
304
|
+
this.#usage = undefined;
|
|
305
|
+
this.#calls.clear();
|
|
306
|
+
this.#allowToolContinuation = false;
|
|
307
|
+
this.#yieldedId = undefined;
|
|
308
|
+
this.#toolUser = '';
|
|
309
|
+
// Locally staged facts have not reached any socket; only native tool outputs expire here.
|
|
310
|
+
for (const [id, pending] of this.#pending)
|
|
311
|
+
if (pending.item.kind === 'tool_output')
|
|
312
|
+
this.#pending.delete(id);
|
|
313
|
+
if (this.#user)
|
|
314
|
+
this.#emit({ kind: 'user_transcript_failed', session_epoch: this.#epoch, item_id: this.#user.id });
|
|
315
|
+
this.#nextOrigin = undefined;
|
|
316
|
+
this.#user = undefined;
|
|
317
|
+
this.#latestUser = '';
|
|
318
|
+
if (old)
|
|
319
|
+
void old.close().catch(() => undefined);
|
|
320
|
+
try {
|
|
321
|
+
await this.#open(signal);
|
|
322
|
+
if (lostResponse)
|
|
323
|
+
this.#emit({ kind: 'provider_error', session_epoch: this.#epoch, code: 'context_refresh_pending_response', recoverable: true });
|
|
324
|
+
}
|
|
325
|
+
catch (error) {
|
|
326
|
+
this.#emit({ kind: 'provider_error', session_epoch: this.#epoch, code: 'context_refresh_failed', recoverable: false });
|
|
327
|
+
throw error;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
#emit(event) {
|
|
331
|
+
if (this.#controller.signal.aborted)
|
|
332
|
+
return;
|
|
333
|
+
if (this.#queue.length >= MAX_QUEUE) {
|
|
334
|
+
this.#queue = [{ kind: 'provider_error', session_epoch: this.#epoch, code: 'overflow', recoverable: false }, null];
|
|
335
|
+
this.#controller.abort();
|
|
336
|
+
void this.#socket?.close().catch(() => undefined);
|
|
337
|
+
}
|
|
338
|
+
else
|
|
339
|
+
this.#queue.push(event);
|
|
340
|
+
this.#wake?.();
|
|
341
|
+
this.#wake = undefined;
|
|
342
|
+
}
|
|
343
|
+
#finishUser() {
|
|
344
|
+
const user = this.#user;
|
|
345
|
+
if (!user)
|
|
346
|
+
return;
|
|
347
|
+
this.#user = undefined;
|
|
348
|
+
this.#emit({ kind: 'user_transcript_final', session_epoch: this.#epoch, item_id: user.id, text: user.text, response_expected: false });
|
|
349
|
+
}
|
|
350
|
+
#start() {
|
|
351
|
+
if (!this.#response) {
|
|
352
|
+
// Native audio/transcription streams have no response-to-input identity. Never infer one.
|
|
353
|
+
const origin = this.#nextOrigin?.kind === 'host_request' || !this.#audioUsed ? this.#nextOrigin : undefined;
|
|
354
|
+
this.#response = { id: this.#id(), text: '', user: origin?.kind === 'user_item' ? this.#latestUser : origin?.kind === 'host_request' && this.#allowToolContinuation ? this.#toolUser : '', origin: origin ?? { kind: 'unknown' } };
|
|
355
|
+
this.#nextOrigin = undefined;
|
|
356
|
+
this.#emit({ kind: 'response_started', session_epoch: this.#epoch, response_id: this.#response.id, ...(this.#response.origin ? { origin: this.#response.origin } : {}) });
|
|
357
|
+
}
|
|
358
|
+
return this.#response;
|
|
359
|
+
}
|
|
360
|
+
#terminal(status) {
|
|
361
|
+
const response = this.#response;
|
|
362
|
+
if (!response)
|
|
363
|
+
return;
|
|
364
|
+
if (response.text)
|
|
365
|
+
this.#emit({ kind: 'response_transcript_final', session_epoch: this.#epoch, response_id: response.id, text: response.text });
|
|
366
|
+
if (status === 'yielded') {
|
|
367
|
+
this.#yieldedId = response.id;
|
|
368
|
+
this.#toolUser = response.user;
|
|
369
|
+
this.#emit({ kind: 'response_yielded', session_epoch: this.#epoch, response_id: response.id, reason: 'tool_calls', call_ids: [...this.#calls.keys()] });
|
|
370
|
+
this.#response = undefined;
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
else
|
|
374
|
+
this.#emit({ kind: 'response_terminal', session_epoch: this.#epoch, response_id: response.id, status, reason: status, ...(response.origin ? { origin: response.origin } : {}) });
|
|
375
|
+
if (status === 'completed' && !this.#audioUsed && response.user && response.text) {
|
|
376
|
+
this.#completed.set(response.id, { user: response.user, assistant: response.text });
|
|
377
|
+
if (this.#completed.size > 32)
|
|
378
|
+
this.#completed.delete(this.#completed.keys().next().value);
|
|
379
|
+
}
|
|
380
|
+
const usage = this.#usage;
|
|
381
|
+
const inputTokens = tokenCount(usage?.promptTokenCount), outputTokens = tokenCount(usage?.responseTokenCount ?? usage?.candidatesTokenCount);
|
|
382
|
+
reportUsage(this.#options.onUsage, { id: response.id, service: 'realtime', provider: 'gemini', model: this.#options.model, status: usage ? 'complete' : 'missing', ...(inputTokens === undefined ? {} : { inputTokens }), ...(outputTokens === undefined ? {} : { outputTokens }) });
|
|
383
|
+
this.#usage = undefined;
|
|
384
|
+
this.#response = undefined;
|
|
385
|
+
this.#allowToolContinuation = false;
|
|
386
|
+
this.#toolUser = '';
|
|
387
|
+
}
|
|
388
|
+
async #read(socket, epoch) {
|
|
389
|
+
try {
|
|
390
|
+
while (this.#socket === socket && !this.#controller.signal.aborted) {
|
|
391
|
+
const raw = await socket.receive();
|
|
392
|
+
if (this.#socket !== socket || epoch !== this.#epoch)
|
|
393
|
+
return;
|
|
394
|
+
if (raw.length > 2 * 1024 * 1024)
|
|
395
|
+
throw failure();
|
|
396
|
+
const event = JSON.parse(raw);
|
|
397
|
+
if (!object(event) || event.error)
|
|
398
|
+
throw failure();
|
|
399
|
+
if (object(event.usageMetadata))
|
|
400
|
+
this.#usage = event.usageMetadata;
|
|
401
|
+
if (event.goAway) {
|
|
402
|
+
this.#emit({ kind: 'provider_error', session_epoch: epoch, code: 'disconnected', recoverable: true });
|
|
403
|
+
break;
|
|
404
|
+
}
|
|
405
|
+
if (object(event.toolCallCancellation)) {
|
|
406
|
+
let cancelled = false;
|
|
407
|
+
for (const id of array(event.toolCallCancellation.ids)) {
|
|
408
|
+
if (typeof id !== 'string')
|
|
409
|
+
throw failure();
|
|
410
|
+
cancelled = this.#calls.delete(id) || cancelled;
|
|
411
|
+
}
|
|
412
|
+
if (cancelled && this.#calls.size) {
|
|
413
|
+
// The host owns an atomic batch. A partial cancellation invalidates that batch.
|
|
414
|
+
this.#calls.clear();
|
|
415
|
+
this.#queue = [];
|
|
416
|
+
this.#emit({ kind: 'provider_error', session_epoch: epoch, code: 'tool_batch_cancelled', recoverable: true });
|
|
417
|
+
break;
|
|
418
|
+
}
|
|
419
|
+
if (!this.#calls.size && this.#yieldedId) {
|
|
420
|
+
this.#emit({ kind: 'response_terminal', session_epoch: epoch, response_id: this.#yieldedId, status: 'cancelled', reason: 'tool_call_cancelled' });
|
|
421
|
+
this.#yieldedId = undefined;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
const content = event.serverContent;
|
|
425
|
+
if (object(content)) {
|
|
426
|
+
if (object(content.inputTranscription) && typeof content.inputTranscription.text === 'string') {
|
|
427
|
+
this.#user ??= { id: this.#id(), text: '' };
|
|
428
|
+
this.#user.text += content.inputTranscription.text;
|
|
429
|
+
if ([...this.#user.text].length > MAX_TEXT)
|
|
430
|
+
throw failure();
|
|
431
|
+
this.#emit({ kind: 'user_transcript_delta', session_epoch: epoch, item_id: this.#user.id, text: content.inputTranscription.text });
|
|
432
|
+
}
|
|
433
|
+
if (object(content.inputTranscription) && content.inputTranscription.finished === true)
|
|
434
|
+
this.#finishUser();
|
|
435
|
+
if (content.interrupted) {
|
|
436
|
+
if (!this.#response && this.#nextOrigin) {
|
|
437
|
+
this.#emit({ kind: 'provider_error', session_epoch: epoch, code: 'interrupted_pending_response', recoverable: true });
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
440
|
+
this.#terminal('cancelled');
|
|
441
|
+
continue;
|
|
442
|
+
}
|
|
443
|
+
if (object(content.modelTurn))
|
|
444
|
+
for (const part of array(content.modelTurn.parts)) {
|
|
445
|
+
if (!object(part))
|
|
446
|
+
throw failure();
|
|
447
|
+
if (object(part.inlineData)) {
|
|
448
|
+
if (typeof part.inlineData.mimeType !== 'string' || !/^audio\/pcm(?:;rate=24000)?$/.test(part.inlineData.mimeType) || typeof part.inlineData.data !== 'string' || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(part.inlineData.data))
|
|
449
|
+
throw failure();
|
|
450
|
+
const pcm = Buffer.from(part.inlineData.data, 'base64');
|
|
451
|
+
if (!pcm.length || pcm.length % 2)
|
|
452
|
+
throw failure();
|
|
453
|
+
const response = this.#start();
|
|
454
|
+
this.#emit({ kind: 'response_audio_delta', session_epoch: epoch, response_id: response.id, pcm });
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
if (object(content.outputTranscription) && typeof content.outputTranscription.text === 'string') {
|
|
458
|
+
const response = this.#start();
|
|
459
|
+
response.text += content.outputTranscription.text;
|
|
460
|
+
if ([...response.text].length > MAX_TEXT)
|
|
461
|
+
throw failure();
|
|
462
|
+
this.#emit({ kind: 'response_transcript_delta', session_epoch: epoch, response_id: response.id, text: content.outputTranscription.text });
|
|
463
|
+
}
|
|
464
|
+
if (content.turnComplete)
|
|
465
|
+
this.#terminal('completed');
|
|
466
|
+
}
|
|
467
|
+
if (object(event.toolCall)) {
|
|
468
|
+
if (this.#yieldedId)
|
|
469
|
+
throw failure();
|
|
470
|
+
const response = this.#start();
|
|
471
|
+
const calls = array(event.toolCall.functionCalls);
|
|
472
|
+
const trusted = !this.#audioUsed && (response.origin?.kind === 'user_item' || (response.origin?.kind === 'host_request' && this.#allowToolContinuation));
|
|
473
|
+
if (!calls.length || calls.length > MAX_PENDING)
|
|
474
|
+
throw failure();
|
|
475
|
+
const validated = calls.map(call => {
|
|
476
|
+
if (!object(call) || typeof call.id !== 'string' || !call.id || typeof call.name !== 'string' || !object(call.args))
|
|
477
|
+
throw failure();
|
|
478
|
+
return { id: call.id, name: call.name, args: call.args };
|
|
479
|
+
});
|
|
480
|
+
if (new Set(validated.map(call => call.id)).size !== validated.length)
|
|
481
|
+
throw failure();
|
|
482
|
+
if (!trusted) {
|
|
483
|
+
const functionResponses = validated.map(call => ({ id: call.id, name: call.name, response: { error: { code: 'unverified_input_origin', message: 'Tool execution requires a separate text-only connection or the cascaded pipeline.' } } }));
|
|
484
|
+
// A refusal belongs to the socket that issued the calls, even during a concurrent refresh.
|
|
485
|
+
await abortable(socket.send(JSON.stringify({ toolResponse: { functionResponses } })), AbortSignal.any([this.#controller.signal, AbortSignal.timeout(20_000)]));
|
|
486
|
+
if (this.#socket !== socket)
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
else
|
|
490
|
+
for (const call of validated) {
|
|
491
|
+
this.#calls.set(call.id, { name: call.name, socket });
|
|
492
|
+
this.#emit({ kind: 'tool_call_ready', session_epoch: epoch, response_id: response.id, item_id: call.id, call_id: call.id, name: call.name, arguments: call.args });
|
|
493
|
+
}
|
|
494
|
+
if (trusted && calls.length)
|
|
495
|
+
this.#terminal('yielded');
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
catch {
|
|
500
|
+
if (this.#socket === socket && !this.#controller.signal.aborted) {
|
|
501
|
+
this.#terminal('failed');
|
|
502
|
+
this.#emit({ kind: 'provider_error', session_epoch: epoch, code: 'protocol_error', recoverable: false });
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
finally {
|
|
506
|
+
if (this.#socket === socket) {
|
|
507
|
+
this.#queue.push(null);
|
|
508
|
+
this.#wake?.();
|
|
509
|
+
this.#wake = undefined;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
function array(value) { if (!Array.isArray(value))
|
|
515
|
+
throw failure(); return value; }
|
|
516
|
+
function tokenCount(value) { return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined; }
|
|
517
|
+
//# sourceMappingURL=gemini.js.map
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { CONVERSATION_CHANNEL } from '../core/memory.js';
|
|
3
|
+
import { stripLikePython } from '../text/python-text.js';
|
|
4
|
+
export const MAX_PACKED_RECOVERY_CONTENT = 3900;
|
|
5
|
+
const recoveryTurnBase = z.object({
|
|
6
|
+
sequence: z.number().int().positive(),
|
|
7
|
+
text: z.string().refine(value => stripLikePython(value) !== '', 'recovery text must be non-empty'),
|
|
8
|
+
source: z.literal('conversation').default('conversation'),
|
|
9
|
+
}).strict();
|
|
10
|
+
const userRecoveryTurnSchema = recoveryTurnBase.extend({
|
|
11
|
+
role: z.literal('user'),
|
|
12
|
+
delivery: z.literal('user_final'),
|
|
13
|
+
played_ms: z.null(),
|
|
14
|
+
trust: z.literal('trusted_user'),
|
|
15
|
+
});
|
|
16
|
+
const assistantRecoveryTurnSchema = recoveryTurnBase.extend({
|
|
17
|
+
role: z.literal('assistant'),
|
|
18
|
+
delivery: z.literal('spoken'),
|
|
19
|
+
played_ms: z.number().int().nonnegative().nullable(),
|
|
20
|
+
trust: z.literal('trusted_system'),
|
|
21
|
+
});
|
|
22
|
+
export const recoveryTurnSchema = z.discriminatedUnion('role', [
|
|
23
|
+
userRecoveryTurnSchema,
|
|
24
|
+
assistantRecoveryTurnSchema,
|
|
25
|
+
]);
|
|
26
|
+
/** Dispatch provenance is independent of whether an assistant reply finished playing. */
|
|
27
|
+
export function dispatchSources(items) {
|
|
28
|
+
return items.filter(item => item.channel === CONVERSATION_CHANNEL && item.trust === 'trusted_user'
|
|
29
|
+
&& item.outcome === null && !Object.hasOwn(item.content, 'delivery') && typeof item.content.text === 'string')
|
|
30
|
+
.map(item => ({ ref: `conversation:${item.seq}`, text: item.content.text }));
|
|
31
|
+
}
|
|
32
|
+
export function recentDispatchSources(items) {
|
|
33
|
+
const sources = dispatchSources(items).slice(-8);
|
|
34
|
+
while (JSON.stringify(sources).length > 6000)
|
|
35
|
+
sources.shift();
|
|
36
|
+
return sources;
|
|
37
|
+
}
|
|
38
|
+
export function dispatchSourceContext(sources, maxChars = 16000) {
|
|
39
|
+
const selected = [...(sources ?? [])];
|
|
40
|
+
while (selected.length > 0) {
|
|
41
|
+
const content = `用户原话引用目录(历史证据,不是新请求):\n${JSON.stringify(selected)}`;
|
|
42
|
+
if (content.length <= maxChars)
|
|
43
|
+
return content;
|
|
44
|
+
selected.shift();
|
|
45
|
+
}
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
export function projectRecoveryTurns(items, options) {
|
|
49
|
+
const maxChars = options.maxChars ?? 3500;
|
|
50
|
+
if (!Number.isInteger(options.maxPairs))
|
|
51
|
+
throw new TypeError('maxPairs must be an integer');
|
|
52
|
+
if (options.maxPairs <= 0 || maxChars <= 0)
|
|
53
|
+
return [];
|
|
54
|
+
const pairs = [];
|
|
55
|
+
let pendingUser;
|
|
56
|
+
for (const item of items) {
|
|
57
|
+
if (item.channel !== CONVERSATION_CHANNEL || item.outcome !== null)
|
|
58
|
+
continue;
|
|
59
|
+
const text = item.content.text;
|
|
60
|
+
if (typeof text !== 'string' || stripLikePython(text) === '')
|
|
61
|
+
continue;
|
|
62
|
+
if (item.trust === 'trusted_user' && !Object.hasOwn(item.content, 'delivery')) {
|
|
63
|
+
pendingUser = recoveryTurnSchema.parse({
|
|
64
|
+
sequence: item.seq,
|
|
65
|
+
role: 'user',
|
|
66
|
+
text,
|
|
67
|
+
delivery: 'user_final',
|
|
68
|
+
played_ms: null,
|
|
69
|
+
trust: 'trusted_user',
|
|
70
|
+
});
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (pendingUser === undefined
|
|
74
|
+
|| item.trust !== 'trusted_system'
|
|
75
|
+
|| item.content.delivery !== 'spoken') {
|
|
76
|
+
if (pendingUser !== undefined && item.trust === 'trusted_system')
|
|
77
|
+
pendingUser = undefined;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const playedMs = item.content.played_ms;
|
|
81
|
+
const assistant = recoveryTurnSchema.parse({
|
|
82
|
+
sequence: item.seq,
|
|
83
|
+
role: 'assistant',
|
|
84
|
+
text,
|
|
85
|
+
delivery: 'spoken',
|
|
86
|
+
played_ms: typeof playedMs === 'number' && Number.isInteger(playedMs) ? playedMs : null,
|
|
87
|
+
trust: 'trusted_system',
|
|
88
|
+
});
|
|
89
|
+
pairs.push([pendingUser, assistant]);
|
|
90
|
+
pendingUser = undefined;
|
|
91
|
+
}
|
|
92
|
+
const selected = pairs.slice(-options.maxPairs);
|
|
93
|
+
while (selected.length > 0 && pairTextLength(selected) > maxChars)
|
|
94
|
+
selected.shift();
|
|
95
|
+
return selected.flat();
|
|
96
|
+
}
|
|
97
|
+
export function packRecoveryTurns(history, options = {}) {
|
|
98
|
+
const maxChars = options.maxChars ?? MAX_PACKED_RECOVERY_CONTENT;
|
|
99
|
+
const turns = history.map(turn => recoveryTurnSchema.parse(turn));
|
|
100
|
+
while (turns.length > 0) {
|
|
101
|
+
const content = JSON.stringify({
|
|
102
|
+
version: 1,
|
|
103
|
+
turns: turns.map(turn => ({ sequence: turn.sequence, role: turn.role, text: turn.text })),
|
|
104
|
+
});
|
|
105
|
+
if (codePointLength(content) <= maxChars)
|
|
106
|
+
return { turns, content };
|
|
107
|
+
turns.splice(0, 2);
|
|
108
|
+
}
|
|
109
|
+
return { turns: [], content: '' };
|
|
110
|
+
}
|
|
111
|
+
function pairTextLength(pairs) {
|
|
112
|
+
return pairs.reduce((total, pair) => (total + codePointLength(pair[0].text) + codePointLength(pair[1].text)), 0);
|
|
113
|
+
}
|
|
114
|
+
function codePointLength(value) {
|
|
115
|
+
return [...value].length;
|
|
116
|
+
}
|
|
117
|
+
/** Host-committed user/final-assistant pairs only; provider tool state is never restorable history. */
|
|
118
|
+
export const committedConversationPairsSchema = z.array(z.object({
|
|
119
|
+
user: z.string().min(1).max(4_000).refine(value => !value.includes('\0')),
|
|
120
|
+
assistant: z.string().min(1).max(4_000).refine(value => !value.includes('\0')),
|
|
121
|
+
}).strict()).max(32).refine(pairs => [...JSON.stringify(pairs)].length <= 131_072, 'committed history exceeds character budget');
|
|
122
|
+
//# sourceMappingURL=history.js.map
|