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,478 @@
|
|
|
1
|
+
import { selfHostedEndpoint } from '../../config/self-hosted.js';
|
|
2
|
+
import { committedConversationPairsSchema } from '../history.js';
|
|
3
|
+
import { translateSystemPrompt } from '../prompt-language.js';
|
|
4
|
+
import { cascadedNarrationInstructions } from './llm.js';
|
|
5
|
+
import { originalImageUrl } from './llm.js';
|
|
6
|
+
import { randomUUID } from 'node:crypto';
|
|
7
|
+
import { reportUsage } from '../usage.js';
|
|
8
|
+
import { codePointLengthLikePython } from '../../text/python-text.js';
|
|
9
|
+
import { MAX_CASCADED_LLM_HISTORY_CODEPOINTS, MAX_CASCADED_LLM_HISTORY_ITEMS, } from './llm.js';
|
|
10
|
+
export { MAX_CASCADED_LLM_HISTORY_CODEPOINTS, MAX_CASCADED_LLM_HISTORY_ITEMS } from './llm.js';
|
|
11
|
+
const MAX_LINE_BYTES = 256 * 1024;
|
|
12
|
+
const MAX_EVENT_BYTES = 512 * 1024;
|
|
13
|
+
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
14
|
+
const MAX_EVENTS = 4096;
|
|
15
|
+
export class ChatCompletionsLlmFailure extends Error {
|
|
16
|
+
code;
|
|
17
|
+
statusCode;
|
|
18
|
+
constructor(code, statusCode = null) {
|
|
19
|
+
super(`Chat Completions LLM ${code} failure`);
|
|
20
|
+
this.code = code;
|
|
21
|
+
this.statusCode = statusCode;
|
|
22
|
+
this.name = 'ChatCompletionsLlmFailure';
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function fail(code, statusCode = null) { return new ChatCompletionsLlmFailure(code, statusCode); }
|
|
26
|
+
function object(value) { return value !== null && !Array.isArray(value) && typeof value === 'object'; }
|
|
27
|
+
function jsonObject(value) { return object(value); }
|
|
28
|
+
function id(value) { return typeof value === 'string' && value.length > 0; }
|
|
29
|
+
function copy(value) { return structuredClone(value); }
|
|
30
|
+
function endpoint(baseUrl) { try {
|
|
31
|
+
const url = new URL(baseUrl);
|
|
32
|
+
url.pathname = `${url.pathname.replace(/\/+$/u, '')}/chat/completions`;
|
|
33
|
+
return url.toString();
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
throw fail('configuration');
|
|
37
|
+
} }
|
|
38
|
+
function message(input) { return input.kind === 'tool_result' ? { role: 'tool', content: JSON.stringify(copy(input.output)), tool_call_id: input.call_id } : { role: input.kind === 'user_text' || input.kind === 'host_activation' || input.kind === 'host_task' ? 'user' : 'system', content: input.kind === 'user_text' ? (input.image ? [{ type: 'text', text: input.text }, { type: 'image_url', image_url: { url: originalImageUrl(input.image) } }] : input.text) : input.kind === 'host_activation' ? JSON.stringify({ text_to_say: input.content }) : input.kind === 'host_task' ? JSON.stringify({ host_scheduled_task: input.content, authority: 'host_schedule_run_not_a_user_message' }) : input.content }; }
|
|
39
|
+
function schema(tool) { return { type: 'function', function: { name: tool.name, ...(tool.description === undefined ? {} : { description: tool.description }), parameters: copy(tool.parameters) } }; }
|
|
40
|
+
function size(units) { const all = units.flat(); return { items: all.length, codepoints: all.reduce((sum, item) => sum + codePointLengthLikePython(JSON.stringify(withoutImage(item))), 0) }; }
|
|
41
|
+
class Session {
|
|
42
|
+
#provider;
|
|
43
|
+
#onUsage;
|
|
44
|
+
#endpoint;
|
|
45
|
+
#apiKey;
|
|
46
|
+
#model;
|
|
47
|
+
#instructions;
|
|
48
|
+
#fetch;
|
|
49
|
+
#idleTimeoutMs;
|
|
50
|
+
#closeTimeoutMs;
|
|
51
|
+
#active = new Set();
|
|
52
|
+
#started = false;
|
|
53
|
+
#seeded = false;
|
|
54
|
+
#history = [];
|
|
55
|
+
#unresolved = null;
|
|
56
|
+
#closed = false;
|
|
57
|
+
#closePromise = null;
|
|
58
|
+
constructor(options, history) {
|
|
59
|
+
this.#provider = options.provider;
|
|
60
|
+
this.#onUsage = options.provider === 'self-hosted' ? undefined : options.onUsage;
|
|
61
|
+
if ((!options.apiKey && options.provider !== 'self-hosted') || !options.model || !options.instructions)
|
|
62
|
+
throw fail('configuration');
|
|
63
|
+
this.#endpoint = endpoint(options.provider === 'self-hosted' ? selfHostedEndpoint(options.baseUrl, 'http', 'SELF_HOSTED_LLM_BASE_URL') : options.baseUrl);
|
|
64
|
+
this.#apiKey = options.apiKey;
|
|
65
|
+
this.#model = options.model;
|
|
66
|
+
this.#instructions = options.instructions;
|
|
67
|
+
this.#fetch = options.fetchImpl ?? globalThis.fetch;
|
|
68
|
+
this.#idleTimeoutMs = options.idleTimeoutMs ?? 30_000;
|
|
69
|
+
this.#closeTimeoutMs = options.closeTimeoutMs ?? 1_000;
|
|
70
|
+
if (history !== undefined)
|
|
71
|
+
this.#seed(history);
|
|
72
|
+
if (!Number.isFinite(this.#idleTimeoutMs) || this.#idleTimeoutMs <= 0 || !Number.isFinite(this.#closeTimeoutMs) || this.#closeTimeoutMs <= 0)
|
|
73
|
+
throw fail('configuration');
|
|
74
|
+
}
|
|
75
|
+
async *stream(input) {
|
|
76
|
+
if (this.#closed)
|
|
77
|
+
throw fail('closed');
|
|
78
|
+
if (input.signal.aborted)
|
|
79
|
+
throw fail('aborted');
|
|
80
|
+
this.#started = true;
|
|
81
|
+
const current = input.inputs.map(message), unresolved = this.#unresolved;
|
|
82
|
+
if (unresolved === null && input.inputs.some(item => item.kind === 'tool_result'))
|
|
83
|
+
throw fail('protocol');
|
|
84
|
+
if (unresolved !== null)
|
|
85
|
+
this.#checkResults(input.inputs, unresolved);
|
|
86
|
+
this.#trim(unresolved ?? []);
|
|
87
|
+
const factOnly = input.inputs.some(item => item.kind === 'host_activation');
|
|
88
|
+
const systemContent = [factOnly ? cascadedNarrationInstructions(input.language) : translateSystemPrompt(this.#instructions, input.language),
|
|
89
|
+
factOnly ? null : input.workspaceContext, input.responseAdaptation]
|
|
90
|
+
.filter((item) => item !== null && item !== undefined)
|
|
91
|
+
.join('\n\n');
|
|
92
|
+
// Narration reads its own fact, not an unfinished question from a prior conversation turn.
|
|
93
|
+
// Tool-call/result pairs stay intact; the full turn is still recorded for the next user turn.
|
|
94
|
+
const context = factOnly
|
|
95
|
+
? [...(unresolved?.slice(-1) ?? []),
|
|
96
|
+
...input.inputs.filter(item => item.kind === 'host_activation' || item.kind === 'tool_result').map(message)]
|
|
97
|
+
: [...this.#history.flat(), ...(unresolved ?? []), ...current];
|
|
98
|
+
// Self-hosted Qwen chat templates accept system messages only at the beginning.
|
|
99
|
+
const messages = this.#provider === 'self-hosted'
|
|
100
|
+
? [{ role: 'system', content: [systemContent, ...context.filter(item => item.role === 'system').map(item => typeof item.content === 'string' ? item.content : '')].join('\n\n') }, ...context.filter(item => item.role !== 'system')]
|
|
101
|
+
: [{ role: 'system', content: systemContent }, ...context];
|
|
102
|
+
const body = { model: this.#model, messages: messages, stream: true, stream_options: { include_usage: true } };
|
|
103
|
+
if (this.#provider === 'deepseek')
|
|
104
|
+
body.thinking = { type: 'disabled' };
|
|
105
|
+
else if (this.#provider === 'qwen')
|
|
106
|
+
body.enable_thinking = false;
|
|
107
|
+
else if (this.#provider === 'openai')
|
|
108
|
+
body.reasoning_effort = 'none';
|
|
109
|
+
if (input.tools.length > 0) {
|
|
110
|
+
body.tools = input.tools.map(schema);
|
|
111
|
+
if (this.#provider !== 'gemini')
|
|
112
|
+
body.parallel_tool_calls = false;
|
|
113
|
+
}
|
|
114
|
+
const active = { completion: null, usageDeadline: null, controller: new AbortController(), reader: null, failureCode: null };
|
|
115
|
+
const stop = () => { active.failureCode ??= 'aborted'; active.controller.abort(); void this.#cancel(active.reader); };
|
|
116
|
+
input.signal.addEventListener('abort', stop, { once: true });
|
|
117
|
+
this.#active.add(active);
|
|
118
|
+
let responseId = null, terminal = false;
|
|
119
|
+
const usageId = randomUUID();
|
|
120
|
+
let usage;
|
|
121
|
+
let events;
|
|
122
|
+
const captureUsage = (event) => {
|
|
123
|
+
if (object(event.usage))
|
|
124
|
+
usage = event.usage;
|
|
125
|
+
};
|
|
126
|
+
try {
|
|
127
|
+
let response;
|
|
128
|
+
try {
|
|
129
|
+
response = await this.#timed(this.#fetch(this.#endpoint, { method: 'POST', redirect: this.#provider === 'self-hosted' ? 'error' : 'follow', headers: { ...(this.#apiKey ? { authorization: `Bearer ${this.#apiKey}` } : {}), 'content-type': 'application/json', accept: 'text/event-stream' }, body: JSON.stringify(body), signal: active.controller.signal }), active);
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
if (error instanceof ChatCompletionsLlmFailure)
|
|
133
|
+
throw error;
|
|
134
|
+
throw fail(input.signal.aborted ? 'aborted' : this.#closed ? 'closed' : 'network');
|
|
135
|
+
}
|
|
136
|
+
if (!response.ok) {
|
|
137
|
+
await this.#cancel(response.body?.getReader() ?? null);
|
|
138
|
+
throw fail('http', response.status);
|
|
139
|
+
}
|
|
140
|
+
if (response.body === null || !response.headers.get('content-type')?.toLowerCase().startsWith('text/event-stream')) {
|
|
141
|
+
await this.#cancel(response.body?.getReader() ?? null);
|
|
142
|
+
throw fail('protocol');
|
|
143
|
+
}
|
|
144
|
+
active.reader = response.body.getReader();
|
|
145
|
+
let started = false, text = '', sawText = false;
|
|
146
|
+
const fragments = new Map();
|
|
147
|
+
events = this.#events(active)[Symbol.asyncIterator]();
|
|
148
|
+
while (true) {
|
|
149
|
+
const next = await events.next();
|
|
150
|
+
if (next.done)
|
|
151
|
+
break;
|
|
152
|
+
const event = next.value;
|
|
153
|
+
captureUsage(event);
|
|
154
|
+
if (event.id !== undefined) {
|
|
155
|
+
if (!id(event.id) || (responseId !== null && responseId !== event.id))
|
|
156
|
+
throw fail('protocol');
|
|
157
|
+
responseId ??= event.id;
|
|
158
|
+
}
|
|
159
|
+
if (!Array.isArray(event.choices))
|
|
160
|
+
continue;
|
|
161
|
+
for (const choice of event.choices) {
|
|
162
|
+
if (!object(choice) || !object(choice.delta))
|
|
163
|
+
throw fail('protocol');
|
|
164
|
+
const content = choice.delta.content, calls = choice.delta.tool_calls;
|
|
165
|
+
if (content !== undefined && content !== null && typeof content !== 'string')
|
|
166
|
+
throw fail('protocol');
|
|
167
|
+
if (calls !== undefined && !Array.isArray(calls))
|
|
168
|
+
throw fail('protocol');
|
|
169
|
+
if (!started && ((input.tools.length === 0 && typeof content === 'string' && content !== '') || (choice.finish_reason !== undefined && choice.finish_reason !== null))) {
|
|
170
|
+
if (responseId === null)
|
|
171
|
+
throw fail('protocol');
|
|
172
|
+
started = true;
|
|
173
|
+
yield { kind: 'response_started', response_id: responseId };
|
|
174
|
+
}
|
|
175
|
+
if (typeof content === 'string' && content !== '')
|
|
176
|
+
sawText = true;
|
|
177
|
+
if (typeof content === 'string' && content !== '') {
|
|
178
|
+
text += content;
|
|
179
|
+
if (input.tools.length === 0)
|
|
180
|
+
yield { kind: 'text_delta', text: content };
|
|
181
|
+
}
|
|
182
|
+
for (const call of calls ?? [])
|
|
183
|
+
this.#fragment(fragments, call);
|
|
184
|
+
if (choice.finish_reason !== undefined && choice.finish_reason !== null) {
|
|
185
|
+
if (typeof choice.finish_reason !== 'string' || responseId === null)
|
|
186
|
+
throw fail('protocol');
|
|
187
|
+
if (choice.finish_reason === 'stop') {
|
|
188
|
+
if (fragments.size > 0)
|
|
189
|
+
throw fail('protocol');
|
|
190
|
+
// With tools enabled, wait for the response kind before publishing speech.
|
|
191
|
+
if (input.tools.length > 0 && text !== '')
|
|
192
|
+
yield { kind: 'text_delta', text };
|
|
193
|
+
this.#history.push([...(unresolved ?? []), ...current, { role: 'assistant', content: text }].map(withoutImage));
|
|
194
|
+
this.#unresolved = null;
|
|
195
|
+
terminal = true;
|
|
196
|
+
yield { kind: 'response_completed', response_id: responseId };
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
else if (choice.finish_reason === 'tool_calls') {
|
|
200
|
+
if ((sawText && input.tools.length === 0) || fragments.size === 0)
|
|
201
|
+
throw fail('protocol');
|
|
202
|
+
const callsOut = this.#calls(fragments);
|
|
203
|
+
for (const call of callsOut)
|
|
204
|
+
yield { kind: 'tool_call', item_id: call.id, call_id: call.id, name: call.function.name, arguments: JSON.parse(call.function.arguments) };
|
|
205
|
+
this.#unresolved = [...(unresolved ?? []), ...current, { role: 'assistant', content: null, tool_calls: callsOut }];
|
|
206
|
+
terminal = true;
|
|
207
|
+
yield { kind: 'response_completed', response_id: responseId };
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
else
|
|
211
|
+
throw fail('protocol');
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (!terminal)
|
|
216
|
+
throw fail(active.failureCode ?? (this.#closed ? 'closed' : input.signal.aborted ? 'aborted' : 'protocol'));
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
if (terminal)
|
|
220
|
+
return;
|
|
221
|
+
const stable = error instanceof ChatCompletionsLlmFailure
|
|
222
|
+
? error : fail(active.failureCode ?? (this.#closed ? 'closed' : input.signal.aborted ? 'aborted' : 'network'));
|
|
223
|
+
if (responseId !== null && !terminal) {
|
|
224
|
+
yield { kind: 'response_failed', response_id: responseId, code: stable.code };
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
throw stable;
|
|
228
|
+
}
|
|
229
|
+
finally {
|
|
230
|
+
// Receipt of a matching tool result survives interruption of its narration.
|
|
231
|
+
// Preserve the resolved pair; the next user turn must not owe that result again.
|
|
232
|
+
if (!terminal && unresolved !== null) {
|
|
233
|
+
this.#history.push([...unresolved, ...current].map(withoutImage));
|
|
234
|
+
this.#unresolved = null;
|
|
235
|
+
}
|
|
236
|
+
const finish = async () => {
|
|
237
|
+
// Metering outlives semantic ownership; the next voice turn must not wait for this tail.
|
|
238
|
+
if (terminal && this.#onUsage !== undefined && events !== undefined && !active.controller.signal.aborted) {
|
|
239
|
+
active.usageDeadline = Date.now() + Math.min(this.#closeTimeoutMs, 1000);
|
|
240
|
+
try {
|
|
241
|
+
while (true) {
|
|
242
|
+
const next = await events.next();
|
|
243
|
+
if (next.done)
|
|
244
|
+
break;
|
|
245
|
+
captureUsage(next.value);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
catch { /* Metering cannot change a completed response. */ }
|
|
249
|
+
}
|
|
250
|
+
const details = object(usage?.prompt_tokens_details) ? usage.prompt_tokens_details : {};
|
|
251
|
+
const outputDetails = object(usage?.completion_tokens_details) ? usage.completion_tokens_details : {};
|
|
252
|
+
reportUsage(this.#onUsage, {
|
|
253
|
+
id: usageId, service: 'llm', provider: this.#provider, model: this.#model,
|
|
254
|
+
status: terminal && usage !== undefined ? 'complete' : 'missing',
|
|
255
|
+
...(terminal && usage !== undefined ? {
|
|
256
|
+
inputTokens: usage.prompt_tokens, outputTokens: usage.completion_tokens,
|
|
257
|
+
cachedTokens: this.#provider === 'deepseek' ? usage.prompt_cache_hit_tokens : details.cached_tokens, reasoningTokens: outputDetails.reasoning_tokens,
|
|
258
|
+
} : {}),
|
|
259
|
+
});
|
|
260
|
+
input.signal.removeEventListener('abort', stop);
|
|
261
|
+
await this.#cancel(active.reader);
|
|
262
|
+
this.#active.delete(active);
|
|
263
|
+
};
|
|
264
|
+
if (terminal && this.#onUsage !== undefined)
|
|
265
|
+
active.completion = finish();
|
|
266
|
+
else
|
|
267
|
+
await finish();
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
restoreHistory(history, signal) {
|
|
271
|
+
try {
|
|
272
|
+
signal.throwIfAborted();
|
|
273
|
+
if (this.#closed || this.#started || this.#seeded)
|
|
274
|
+
throw fail('protocol');
|
|
275
|
+
this.#seed(history);
|
|
276
|
+
return Promise.resolve();
|
|
277
|
+
}
|
|
278
|
+
catch (error) {
|
|
279
|
+
return Promise.reject(error instanceof Error ? error : fail('protocol'));
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
#seed(history) {
|
|
283
|
+
const pairs = committedConversationPairsSchema.parse(history);
|
|
284
|
+
this.#history = pairs.map(pair => [{ role: 'user', content: pair.user }, { role: 'assistant', content: pair.assistant }]);
|
|
285
|
+
this.#seeded = true;
|
|
286
|
+
this.#trim([]);
|
|
287
|
+
}
|
|
288
|
+
#fragment(fragments, value) {
|
|
289
|
+
if (!object(value) || typeof value.index !== 'number' || !Number.isSafeInteger(value.index) || value.index !== 0 || (value.function !== undefined && !object(value.function)))
|
|
290
|
+
throw fail('protocol');
|
|
291
|
+
const index = value.index;
|
|
292
|
+
const found = fragments.get(index) ?? { id: null, name: '', arguments: '' };
|
|
293
|
+
// A null id on a later DashScope delta contributes no new identity; final validation still requires an id.
|
|
294
|
+
if (value.id !== undefined && value.id !== null && value.id !== '') {
|
|
295
|
+
if (!id(value.id) || (found.id !== null && found.id !== value.id))
|
|
296
|
+
throw fail('protocol');
|
|
297
|
+
found.id = value.id;
|
|
298
|
+
}
|
|
299
|
+
// DashScope may append arguments:null after complete JSON; that delta contributes no bytes.
|
|
300
|
+
const fn = value.function;
|
|
301
|
+
if (fn !== undefined) {
|
|
302
|
+
if (fn.name !== undefined) {
|
|
303
|
+
if (typeof fn.name !== 'string')
|
|
304
|
+
throw fail('protocol');
|
|
305
|
+
found.name += fn.name;
|
|
306
|
+
}
|
|
307
|
+
;
|
|
308
|
+
if (fn.arguments !== undefined && fn.arguments !== null) {
|
|
309
|
+
if (typeof fn.arguments !== 'string')
|
|
310
|
+
throw fail('protocol');
|
|
311
|
+
found.arguments += fn.arguments;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
if (this.#provider === 'gemini' && value.extra_content !== undefined) {
|
|
315
|
+
if (!jsonObject(value.extra_content) || JSON.stringify(value.extra_content).length > MAX_EVENT_BYTES)
|
|
316
|
+
throw fail('protocol');
|
|
317
|
+
if (found.extra_content && JSON.stringify(found.extra_content) !== JSON.stringify(value.extra_content))
|
|
318
|
+
throw fail('protocol');
|
|
319
|
+
found.extra_content = structuredClone(value.extra_content);
|
|
320
|
+
}
|
|
321
|
+
fragments.set(index, found);
|
|
322
|
+
}
|
|
323
|
+
#calls(fragments) { if (fragments.size !== 1 || !fragments.has(0))
|
|
324
|
+
throw fail('protocol'); return [...fragments.entries()].map(([, part]) => { if (!id(part.id) || !id(part.name))
|
|
325
|
+
throw fail('protocol'); let args; try {
|
|
326
|
+
args = JSON.parse(part.arguments);
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
throw fail('protocol');
|
|
330
|
+
} ; if (!jsonObject(args))
|
|
331
|
+
throw fail('protocol'); return { id: part.id, type: 'function', ...(part.extra_content ? { extra_content: part.extra_content } : {}), function: { name: part.name, arguments: JSON.stringify(copy(args)) } }; }); }
|
|
332
|
+
#checkResults(inputs, unresolved) {
|
|
333
|
+
const calls = (unresolved.at(-1)?.tool_calls ?? []).map(item => item.id).sort(), results = inputs.filter((item) => item.kind === 'tool_result').map(item => item.call_id).sort();
|
|
334
|
+
if (calls.length === 0 || calls.length !== results.length || calls.some((call, index) => call !== results[index]) || inputs.slice(0, results.length).some(item => item.kind !== 'tool_result'))
|
|
335
|
+
throw fail('protocol');
|
|
336
|
+
}
|
|
337
|
+
abandonPendingResponse() {
|
|
338
|
+
if (this.#closed)
|
|
339
|
+
return Promise.reject(fail('closed'));
|
|
340
|
+
this.#unresolved = null;
|
|
341
|
+
return Promise.resolve();
|
|
342
|
+
}
|
|
343
|
+
#trim(unresolved) { while (true) {
|
|
344
|
+
const measured = size([...this.#history, unresolved]);
|
|
345
|
+
if (measured.items <= MAX_CASCADED_LLM_HISTORY_ITEMS && measured.codepoints <= MAX_CASCADED_LLM_HISTORY_CODEPOINTS)
|
|
346
|
+
return;
|
|
347
|
+
if (this.#history.length === 0)
|
|
348
|
+
throw fail('overflow');
|
|
349
|
+
this.#history.shift();
|
|
350
|
+
} }
|
|
351
|
+
async *#events(active) {
|
|
352
|
+
const reader = active.reader, decoder = new TextDecoder('utf-8', { fatal: true });
|
|
353
|
+
let buffered = new Uint8Array(), total = 0, parts = [], partBytes = 0, count = 0;
|
|
354
|
+
const line = (raw) => { let bytes = raw; if (bytes.at(-1) === 13)
|
|
355
|
+
bytes = bytes.subarray(0, bytes.length - 1); if (bytes.length > MAX_LINE_BYTES)
|
|
356
|
+
throw fail('overflow'); let text; try {
|
|
357
|
+
text = decoder.decode(bytes);
|
|
358
|
+
}
|
|
359
|
+
catch {
|
|
360
|
+
throw fail('protocol');
|
|
361
|
+
} ; if (text !== '') {
|
|
362
|
+
if (text.startsWith(':') || !text.startsWith('data:'))
|
|
363
|
+
return null;
|
|
364
|
+
const part = text.slice(5).replace(/^ /u, '');
|
|
365
|
+
partBytes += new TextEncoder().encode(part).length + (parts.length === 0 ? 0 : 1);
|
|
366
|
+
if (partBytes > MAX_EVENT_BYTES)
|
|
367
|
+
throw fail('overflow');
|
|
368
|
+
parts.push(part);
|
|
369
|
+
return null;
|
|
370
|
+
} ; if (parts.length === 0)
|
|
371
|
+
return null; count += 1; if (count > MAX_EVENTS)
|
|
372
|
+
throw fail('overflow'); const joined = parts.join('\n'); parts = []; partBytes = 0; if (joined === '[DONE]')
|
|
373
|
+
return 'done'; let parsed; try {
|
|
374
|
+
parsed = JSON.parse(joined);
|
|
375
|
+
}
|
|
376
|
+
catch {
|
|
377
|
+
throw fail('protocol');
|
|
378
|
+
} ; if (!object(parsed))
|
|
379
|
+
throw fail('protocol'); return parsed; };
|
|
380
|
+
while (true) {
|
|
381
|
+
let read;
|
|
382
|
+
try {
|
|
383
|
+
read = await this.#timed(reader.read(), active);
|
|
384
|
+
}
|
|
385
|
+
catch (error) {
|
|
386
|
+
if (error instanceof ChatCompletionsLlmFailure)
|
|
387
|
+
throw error;
|
|
388
|
+
throw fail(active.controller.signal.aborted ? this.#closed ? 'closed' : 'aborted' : 'network');
|
|
389
|
+
}
|
|
390
|
+
if (read.done) {
|
|
391
|
+
if (buffered.length > 0) {
|
|
392
|
+
const event = line(buffered);
|
|
393
|
+
if (event !== null && event !== 'done')
|
|
394
|
+
yield event;
|
|
395
|
+
}
|
|
396
|
+
;
|
|
397
|
+
const event = line(new Uint8Array());
|
|
398
|
+
if (event !== null && event !== 'done')
|
|
399
|
+
yield event;
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
if (!(read.value instanceof Uint8Array))
|
|
403
|
+
throw fail('protocol');
|
|
404
|
+
total += read.value.length;
|
|
405
|
+
if (total > MAX_RESPONSE_BYTES)
|
|
406
|
+
throw fail('overflow');
|
|
407
|
+
const next = new Uint8Array(buffered.length + read.value.length);
|
|
408
|
+
next.set(buffered);
|
|
409
|
+
next.set(read.value, buffered.length);
|
|
410
|
+
buffered = next;
|
|
411
|
+
let newline = buffered.indexOf(10);
|
|
412
|
+
while (newline >= 0) {
|
|
413
|
+
const event = line(buffered.subarray(0, newline));
|
|
414
|
+
buffered = buffered.slice(newline + 1);
|
|
415
|
+
if (event === 'done')
|
|
416
|
+
return;
|
|
417
|
+
if (event !== null)
|
|
418
|
+
yield event;
|
|
419
|
+
newline = buffered.indexOf(10);
|
|
420
|
+
}
|
|
421
|
+
;
|
|
422
|
+
if (buffered.length > MAX_LINE_BYTES)
|
|
423
|
+
throw fail('overflow');
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
async #cancel(reader) {
|
|
427
|
+
if (reader === null)
|
|
428
|
+
return;
|
|
429
|
+
let timer;
|
|
430
|
+
try {
|
|
431
|
+
await Promise.race([
|
|
432
|
+
reader.cancel().catch(() => undefined),
|
|
433
|
+
new Promise(resolve => { timer = setTimeout(resolve, this.#closeTimeoutMs); }),
|
|
434
|
+
]);
|
|
435
|
+
}
|
|
436
|
+
finally {
|
|
437
|
+
if (timer !== undefined)
|
|
438
|
+
clearTimeout(timer);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
async #timed(promise, active) { let timer; try {
|
|
442
|
+
return await Promise.race([promise, new Promise((_resolve, reject) => { timer = setTimeout(() => { active.failureCode ??= 'timeout'; active.controller.abort(); void this.#cancel(active.reader); reject(fail('timeout')); }, active.usageDeadline === null ? this.#idleTimeoutMs : Math.max(1, Math.min(this.#idleTimeoutMs, active.usageDeadline - Date.now()))); })]);
|
|
443
|
+
}
|
|
444
|
+
finally {
|
|
445
|
+
if (timer !== undefined)
|
|
446
|
+
clearTimeout(timer);
|
|
447
|
+
} }
|
|
448
|
+
close() {
|
|
449
|
+
if (this.#closePromise !== null)
|
|
450
|
+
return this.#closePromise;
|
|
451
|
+
this.#closed = true;
|
|
452
|
+
const cancellations = [...this.#active].map(async (active) => {
|
|
453
|
+
active.failureCode ??= 'closed';
|
|
454
|
+
active.controller.abort();
|
|
455
|
+
await this.#cancel(active.reader);
|
|
456
|
+
await active.completion;
|
|
457
|
+
});
|
|
458
|
+
this.#closePromise = (async () => {
|
|
459
|
+
let timer;
|
|
460
|
+
try {
|
|
461
|
+
await Promise.race([
|
|
462
|
+
Promise.allSettled(cancellations),
|
|
463
|
+
new Promise(resolve => { timer = setTimeout(resolve, this.#closeTimeoutMs); }),
|
|
464
|
+
]);
|
|
465
|
+
}
|
|
466
|
+
finally {
|
|
467
|
+
if (timer !== undefined)
|
|
468
|
+
clearTimeout(timer);
|
|
469
|
+
}
|
|
470
|
+
})();
|
|
471
|
+
return this.#closePromise;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
export function createChatCompletionsLlmFactory(options) { return { open: input => new Session(options, input?.history) }; }
|
|
475
|
+
function withoutImage(message) {
|
|
476
|
+
return Array.isArray(message.content) ? { ...message, content: message.content.filter(part => part.type === 'text').map(part => typeof part.text === 'string' ? part.text : '').join('\n') } : message;
|
|
477
|
+
}
|
|
478
|
+
//# sourceMappingURL=chat-completions-llm.js.map
|