nova-personal-agent-server 0.4.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +674 -201
- package/README.md +12 -2
- package/bin/nova-space-host.mjs +4 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/cli.js +71 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/client.js +340 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/crypto.js +167 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/live.js +169 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/mailbox.js +217 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/media.js +320 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/pairing.js +13 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/protocol.js +50 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/security.js +305 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/server.js +477 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/source-address.js +58 -0
- package/node_modules/@nova-personal-agent/relay/package.json +1 -0
- package/package.json +13 -6
- package/runtime/dist/src/cascaded-text-provider.js +8 -3
- package/runtime/dist/src/composition/assembly.js +133 -35
- package/runtime/dist/src/composition/cascaded-realtime-assembly.js +114 -59
- package/runtime/dist/src/composition/production-composition.js +57 -21
- package/runtime/dist/src/composition/realtime-assembly.js +160 -52
- package/runtime/dist/src/composition/soul-context.js +22 -0
- package/runtime/dist/src/config/capability-registry.js +48 -3
- package/runtime/dist/src/config/cascaded-realtime-config.js +23 -10
- package/runtime/dist/src/config/config.js +541 -128
- package/runtime/dist/src/config/credential-rotation.js +26 -0
- package/runtime/dist/src/config/data-root.js +764 -0
- package/runtime/dist/src/config/diagnostics.js +3 -1
- package/runtime/dist/src/config/environment-contract.js +190 -188
- package/runtime/dist/src/config/model-routes.js +140 -0
- package/runtime/dist/src/config/voice-credentials.js +55 -0
- package/runtime/dist/src/connectors/composio/index.js +9 -0
- package/runtime/dist/src/connectors/feishu/index.js +258 -44
- package/runtime/dist/src/connectors/macos/mail.js +7 -3
- package/runtime/dist/src/connectors/macos/reader.js +3 -1
- package/runtime/dist/src/conversation-voice-provider.js +5 -2
- package/runtime/dist/src/core/causal-runtime.js +38 -3
- package/runtime/dist/src/core/context-view.js +7 -0
- package/runtime/dist/src/core/guards.js +32 -0
- package/runtime/dist/src/core/runtime.js +3 -0
- package/runtime/dist/src/core/schedule-tools.js +2 -2
- package/runtime/dist/src/core/source-processing-instructions.js +2 -2
- package/runtime/dist/src/core/source-processing-tools.js +3 -1
- package/runtime/dist/src/core/tool-schema.js +42 -7
- package/runtime/dist/src/desktop/desktop-camera.js +3 -5
- package/runtime/dist/src/desktop/desktop-control.js +41 -8
- package/runtime/dist/src/desktop/desktop-session.js +90 -19
- package/runtime/dist/src/desktop/desktop-wire.js +5 -7
- package/runtime/dist/src/desktop/startup-error.js +18 -16
- package/runtime/dist/src/desktop/workbench-acceptance.js +52 -14
- package/runtime/dist/src/desktop-entry.js +6 -2
- package/runtime/dist/src/desktop.js +5 -1
- package/runtime/dist/src/device/attempt.js +65 -0
- package/runtime/dist/src/device/authority.js +159 -0
- package/runtime/dist/src/device/gateway.js +87 -0
- package/runtime/dist/src/device/ledger.js +91 -0
- package/runtime/dist/src/device/ownership.js +92 -0
- package/runtime/dist/src/device/port.js +2 -0
- package/runtime/dist/src/device/schedule-ownership.js +103 -0
- package/runtime/dist/src/executors/acp/transport.js +2 -0
- package/runtime/dist/src/executors/browser.js +4 -3
- package/runtime/dist/src/executors/codex/adapter-project.js +58 -12
- package/runtime/dist/src/executors/codex/app-server-schema.js +12 -21
- package/runtime/dist/src/executors/codex/app-server-transport.js +32 -18
- package/runtime/dist/src/executors/codex/common.js +1 -1
- package/runtime/dist/src/executors/codex/contract.js +12 -16
- package/runtime/dist/src/executors/codex/credential-snapshot.js +1 -9
- package/runtime/dist/src/executors/codex/factory.js +54 -32
- package/runtime/dist/src/executors/codex/host-config.js +69 -20
- package/runtime/dist/src/executors/codex/launch-profile.js +3 -2
- package/runtime/dist/src/executors/codex/local-provider-credential.js +39 -0
- package/runtime/dist/src/executors/codex/process-owner.js +4 -6
- package/runtime/dist/src/executors/codex/production-host.js +33 -34
- package/runtime/dist/src/executors/codex/protocol.js +9 -14
- package/runtime/dist/src/executors/codex/session-title.js +6 -8
- package/runtime/dist/src/executors/codex/spawn-env.js +27 -6
- package/runtime/dist/src/executors/codex/turn-projection.js +12 -17
- package/runtime/dist/src/executors/codex/windows-guardian.js +4 -6
- package/runtime/dist/src/executors/coding/intake.js +12 -7
- package/runtime/dist/src/executors/computer-backend.js +18 -10
- package/runtime/dist/src/executors/computer-config.js +32 -0
- package/runtime/dist/src/executors/computer-device.js +68 -16
- package/runtime/dist/src/executors/computer-worker.js +18 -6
- package/runtime/dist/src/executors/computer.js +29 -56
- package/runtime/dist/src/executors/device-lock.js +14 -5
- package/runtime/dist/src/executors/gui-execution.js +2 -0
- package/runtime/dist/src/executors/index.js +0 -1
- package/runtime/dist/src/executors/mobile.js +9 -8
- package/runtime/dist/src/executors/native-process.js +4 -0
- package/runtime/dist/src/executors/search.js +3 -5
- package/runtime/dist/src/executors/task-resources.js +21 -0
- package/runtime/dist/src/executors/watcher.js +2 -4
- package/runtime/dist/src/experience/host.js +179 -0
- package/runtime/dist/src/index.js +2 -0
- package/runtime/dist/src/knowledge/assembly.js +3 -4
- package/runtime/dist/src/knowledge/embeddings.js +50 -34
- package/runtime/dist/src/knowledge/service.js +1 -0
- package/runtime/dist/src/knowledge/store-client.js +1 -6
- package/runtime/dist/src/knowledge/store-worker.js +1 -3
- package/runtime/dist/src/mem0/resource.js +25 -0
- package/runtime/dist/src/mem0/store-worker.js +234 -21
- package/runtime/dist/src/memory/consumer.js +31 -0
- package/runtime/dist/src/memory/engine-worker.js +210 -0
- package/runtime/dist/src/memory/entry.js +8 -1
- package/runtime/dist/src/memory/explicit-memory.js +20 -0
- package/runtime/dist/src/memory/factory.js +30 -15
- package/runtime/dist/src/memory/grounded-voicemem.js +10 -0
- package/runtime/dist/src/memory/ledger-recall-engine.js +86 -0
- package/runtime/dist/src/memory/prerecall-port.js +27 -0
- package/runtime/dist/src/memory/prerecall.js +1 -1
- package/runtime/dist/src/memory/production-engine.js +151 -0
- package/runtime/dist/src/memory/provenance.js +1 -0
- package/runtime/dist/src/memory/remote-personal-memory.js +3 -1
- package/runtime/dist/src/memory/retrieval.js +107 -22
- package/runtime/dist/src/memory/sensitivity.js +6 -2
- package/runtime/dist/src/memory/source-retrieval.js +11 -0
- package/runtime/dist/src/memory/tool-capabilities.js +46 -0
- package/runtime/dist/src/memory/voicemem-sdk/LICENSE +202 -0
- package/runtime/dist/src/memory/voicemem-sdk/NOTICE.md +97 -0
- package/runtime/dist/src/memory/voicemem-sdk/PATCH-NOTICE.md +23 -0
- package/runtime/dist/src/memory/voicemem-sdk/archive.js +12 -0
- package/runtime/dist/src/memory/voicemem-sdk/audio.js +111 -0
- package/runtime/dist/src/memory/voicemem-sdk/barge-in.js +59 -0
- package/runtime/dist/src/memory/voicemem-sdk/checkpoint.js +56 -0
- package/runtime/dist/src/memory/voicemem-sdk/cleanup.js +139 -0
- package/runtime/dist/src/memory/voicemem-sdk/dashscope-asr.js +254 -0
- package/runtime/dist/src/memory/voicemem-sdk/dashscope-tts.js +247 -0
- package/runtime/dist/src/memory/voicemem-sdk/evaluation.js +330 -0
- package/runtime/dist/src/memory/voicemem-sdk/extraction.js +220 -0
- package/runtime/dist/src/memory/voicemem-sdk/finetune-data.js +115 -0
- package/runtime/dist/src/memory/voicemem-sdk/finetune.js +170 -0
- package/runtime/dist/src/memory/voicemem-sdk/grounded-reply-preferences.js +81 -0
- package/runtime/dist/src/memory/voicemem-sdk/index.js +22 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-embedding.js +164 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-runtime.js +53 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-speaker.js +240 -0
- package/runtime/dist/src/memory/voicemem-sdk/memory.js +767 -0
- package/runtime/dist/src/memory/voicemem-sdk/model-json.js +14 -0
- package/runtime/dist/src/memory/voicemem-sdk/personamem.js +209 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/addenda.js +215 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/additive-extraction.js +478 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/index.js +32 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/update-memory.js +152 -0
- package/runtime/dist/src/memory/voicemem-sdk/providers.js +325 -0
- package/runtime/dist/src/memory/voicemem-sdk/ranking.js +65 -0
- package/runtime/dist/src/memory/voicemem-sdk/reaction.js +33 -0
- package/runtime/dist/src/memory/voicemem-sdk/realtime.js +215 -0
- package/runtime/dist/src/memory/voicemem-sdk/reply.js +68 -0
- package/runtime/dist/src/memory/voicemem-sdk/routing.js +209 -0
- package/runtime/dist/src/memory/voicemem-sdk/slots.js +61 -0
- package/runtime/dist/src/memory/voicemem-sdk/speaker-bindings.js +120 -0
- package/runtime/dist/src/memory/voicemem-sdk/speaker-profiles.js +327 -0
- package/runtime/dist/src/memory/voicemem-sdk/store.js +577 -0
- package/runtime/dist/src/memory/voicemem-sdk/stream.js +317 -0
- package/runtime/dist/src/memory/voicemem-sdk/subgraph.js +113 -0
- package/runtime/dist/src/memory/voicemem-sdk/summaries.js +56 -0
- package/runtime/dist/src/memory/voicemem-sdk/time.js +157 -0
- package/runtime/dist/src/memory/voicemem-sdk/types.js +2 -0
- package/runtime/dist/src/memory-ledger/store-client.js +235 -37
- package/runtime/dist/src/memory-ledger/store-worker.js +8 -5
- package/runtime/dist/src/memory-ledger/store.js +91 -1
- package/runtime/dist/src/memory-substrate/consolidation.js +23 -7
- package/runtime/dist/src/memory-substrate/diary.js +27 -0
- package/runtime/dist/src/memory-substrate/engine-outbox.js +107 -0
- package/runtime/dist/src/memory-substrate/explicit-memory.js +112 -0
- package/runtime/dist/src/memory-substrate/fact-fidelity.js +68 -0
- package/runtime/dist/src/memory-substrate/feishu-consent.js +41 -0
- package/runtime/dist/src/memory-substrate/file-authority.js +29 -6
- package/runtime/dist/src/memory-substrate/life-operations.js +35 -9
- package/runtime/dist/src/memory-substrate/markdown-repository.js +271 -65
- package/runtime/dist/src/memory-substrate/memory-documents.js +96 -0
- package/runtime/dist/src/memory-substrate/migration.js +2 -0
- package/runtime/dist/src/memory-substrate/purge.js +12 -2
- package/runtime/dist/src/memory-substrate/resource.js +514 -129
- package/runtime/dist/src/memory-substrate/retrieval.js +8 -5
- package/runtime/dist/src/memory-substrate/source-operations.js +9 -1
- package/runtime/dist/src/memory-substrate/source-processing.js +436 -40
- package/runtime/dist/src/memory-substrate/source-retrieval.js +28 -0
- package/runtime/dist/src/memory-substrate/source-state.js +8 -0
- package/runtime/dist/src/memory-substrate/space-source-input.js +90 -0
- package/runtime/dist/src/memory-substrate/store.js +125 -23
- package/runtime/dist/src/model/goal-checkin-writer.js +72 -0
- package/runtime/dist/src/model/goal-writer.js +80 -0
- package/runtime/dist/src/model/jev-client.js +24 -13
- package/runtime/dist/src/model/model-adapters.js +2 -3
- package/runtime/dist/src/model/model-catalog.js +80 -0
- package/runtime/dist/src/model/model-gateway.js +47 -18
- package/runtime/dist/src/model/model-purpose.js +3 -4
- package/runtime/dist/src/model/personal-writer.js +536 -44
- package/runtime/dist/src/model/proactivity.js +50 -6
- package/runtime/dist/src/model/responses-model-gateway.js +59 -0
- package/runtime/dist/src/model/task-verifier.js +3 -3
- package/runtime/dist/src/model/timeline-anchors.js +77 -0
- package/runtime/dist/src/model/timeline-perspective.js +13 -0
- package/runtime/dist/src/model/timeline-selection.js +182 -0
- package/runtime/dist/src/model/understanding-writer.js +27 -0
- package/runtime/dist/src/model/vision-capability.js +3 -1
- package/runtime/dist/src/model/workbench-writer.js +96 -0
- package/runtime/dist/src/news/feeds.js +6 -10
- package/runtime/dist/src/news/interests.js +23 -0
- package/runtime/dist/src/news/service.js +87 -31
- package/runtime/dist/src/news/sources.json +116 -0
- package/runtime/dist/src/notifications/adapters/space-relay.js +4 -0
- package/runtime/dist/src/notifications/content.js +41 -0
- package/runtime/dist/src/notifications/contracts.js +4 -2
- package/runtime/dist/src/notifications/feed.js +6 -2
- package/runtime/dist/src/notifications/service.js +27 -14
- package/runtime/dist/src/notifications/store.js +3 -1
- package/runtime/dist/src/personal-agent/app-context.js +39 -4
- package/runtime/dist/src/personal-agent/chat-failure.js +37 -0
- package/runtime/dist/src/personal-agent/computer-use/contract.js +42 -0
- package/runtime/dist/src/personal-agent/computer-use/session.js +280 -0
- package/runtime/dist/src/personal-agent/computer-use/skill.js +18 -0
- package/runtime/dist/src/personal-agent/computer-use/tools.js +15 -0
- package/runtime/dist/src/personal-agent/context-candidates.js +9 -13
- package/runtime/dist/src/personal-agent/context-dependencies.js +28 -0
- package/runtime/dist/src/personal-agent/contracts.js +24 -4
- package/runtime/dist/src/personal-agent/conversation-runtime.js +440 -42
- package/runtime/dist/src/personal-agent/conversation-tool-bridge.js +97 -0
- package/runtime/dist/src/personal-agent/conversation-tool-policy.js +22 -0
- package/runtime/dist/src/personal-agent/conversations.js +71 -15
- package/runtime/dist/src/personal-agent/daily-brief.js +5 -0
- package/runtime/dist/src/personal-agent/daily-workbench.js +558 -0
- package/runtime/dist/src/personal-agent/discovery-window.js +36 -0
- package/runtime/dist/src/personal-agent/goal-checkin.js +53 -0
- package/runtime/dist/src/personal-agent/host.js +2379 -223
- package/runtime/dist/src/personal-agent/identity-context.js +33 -0
- package/runtime/dist/src/personal-agent/life.js +129 -11
- package/runtime/dist/src/personal-agent/local-shell.js +181 -0
- package/runtime/dist/src/personal-agent/local-tools.js +234 -0
- package/runtime/dist/src/personal-agent/preferred-name-sync.js +35 -0
- package/runtime/dist/src/personal-agent/profile-warmup.js +100 -39
- package/runtime/dist/src/personal-agent/project-digests.js +7 -3
- package/runtime/dist/src/personal-agent/project-history.js +36 -0
- package/runtime/dist/src/personal-agent/reading-copies.js +183 -0
- package/runtime/dist/src/personal-agent/scheduled-tasks.js +50 -13
- package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +26 -10
- package/runtime/dist/src/personal-agent/source-processing-agent.js +239 -17
- package/runtime/dist/src/personal-agent/sources.js +9 -1
- package/runtime/dist/src/personal-agent/store.js +124 -14
- package/runtime/dist/src/personal-agent/task-loop.js +3 -0
- package/runtime/dist/src/personal-agent/tasks.js +16 -4
- package/runtime/dist/src/personal-agent/timeline-brief.js +462 -0
- package/runtime/dist/src/personal-agent/timeline-cache.js +191 -0
- package/runtime/dist/src/personal-agent/timeline-cluster.js +30 -0
- package/runtime/dist/src/personal-agent/timeline-inputs.js +47 -0
- package/runtime/dist/src/personal-agent/timeline-time.js +60 -0
- package/runtime/dist/src/personal-agent/understanding-products.js +49 -0
- package/runtime/dist/src/personal-agent/understanding.js +7 -22
- package/runtime/dist/src/personal-agent/workbench-context.js +17 -21
- package/runtime/dist/src/personal-agent/workbench-copy.js +124 -0
- package/runtime/dist/src/personal-agent/workbench-evidence.js +77 -0
- package/runtime/dist/src/personal-agent/workbench-instructions.js +21 -0
- package/runtime/dist/src/personal-agent/workbench-runtime.js +1006 -0
- package/runtime/dist/src/personal-agent/workbench-shell-class.js +304 -0
- package/runtime/dist/src/personal-agent/workbench-store.js +292 -0
- package/runtime/dist/src/personal-agent/workbench-temporal.js +66 -0
- package/runtime/dist/src/projects/project-native-resource.js +10 -8
- package/runtime/dist/src/projects/project-store.js +36 -4
- package/runtime/dist/src/realtime/bridge.js +77 -8
- package/runtime/dist/src/realtime/capabilities.js +19 -0
- package/runtime/dist/src/realtime/cascaded/adapter.js +180 -40
- package/runtime/dist/src/realtime/cascaded/ark-llm.js +150 -24
- package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +243 -83
- package/runtime/dist/src/realtime/cascaded/llm-stream-limits.js +18 -0
- package/runtime/dist/src/realtime/cascaded/llm.js +96 -0
- package/runtime/dist/src/realtime/cascaded/openai-compatible-speech.js +251 -0
- package/runtime/dist/src/realtime/cascaded/provider.js +8 -0
- package/runtime/dist/src/realtime/evidence.js +1 -1
- package/runtime/dist/src/realtime/frontend-instructions.js +76 -55
- package/runtime/dist/src/realtime/gemini.js +14 -3
- package/runtime/dist/src/realtime/host-delivery.js +37 -4
- package/runtime/dist/src/realtime/protocol.js +18 -3
- package/runtime/dist/src/realtime/provider-projection.js +4 -1
- package/runtime/dist/src/realtime/provider-session.js +73 -16
- package/runtime/dist/src/realtime/qwen-transport.js +35 -4
- package/runtime/dist/src/realtime/qwen.js +144 -9
- package/runtime/dist/src/realtime/service-state.js +0 -1
- package/runtime/dist/src/realtime/service.js +93 -7
- package/runtime/dist/src/realtime/session.js +39 -32
- package/runtime/dist/src/realtime/sglang-native.js +214 -0
- package/runtime/dist/src/realtime/system-prompts.en.js +14 -2
- package/runtime/dist/src/realtime/telemetry.js +6 -3
- package/runtime/dist/src/realtime/tool-continuations.js +84 -7
- package/runtime/dist/src/realtime/transport.js +17 -0
- package/runtime/dist/src/realtime/usage.js +33 -17
- package/runtime/dist/src/realtime/volcengine/ark.js +40 -15
- package/runtime/dist/src/realtime/volcengine/asr.js +2 -1
- package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +1 -7
- package/runtime/dist/src/realtime/volcengine/tts.js +2 -1
- package/runtime/dist/src/server/aoq-chat-server.js +1 -1
- package/runtime/dist/src/server/client-server.js +21 -0
- package/runtime/dist/src/server-entry.js +3 -0
- package/runtime/dist/src/space-host/admin-socket.js +115 -0
- package/runtime/dist/src/space-host/audio-owner.js +44 -0
- package/runtime/dist/src/space-host/cli.js +195 -0
- package/runtime/dist/src/space-host/config.js +247 -0
- package/runtime/dist/src/space-host/context-input.js +12 -0
- package/runtime/dist/src/space-host/contracts.js +10 -0
- package/runtime/dist/src/space-host/host-admin.js +114 -0
- package/runtime/dist/src/space-host/key-delivery.js +28 -0
- package/runtime/dist/src/space-host/mobile-tools.js +9 -0
- package/runtime/dist/src/space-host/model-settings.js +213 -0
- package/runtime/dist/src/space-host/projection.js +37 -0
- package/runtime/dist/src/space-host/push.js +137 -0
- package/runtime/dist/src/space-host/relay-transport.js +55 -0
- package/runtime/dist/src/space-host/service.js +841 -0
- package/runtime/dist/src/space-host/voice-crypto.js +240 -0
- package/runtime/dist/src/space-host/voice.js +600 -0
- package/runtime/dist/src/space-host/windows-secret-key.js +82 -0
- package/runtime/dist/src/storage/private-database.js +7 -10
- package/runtime/dist/src/text/unicode-normalize.js +5 -1
- package/runtime/dist/src/understanding/candidates.js +8 -10
- package/runtime/dist/src/understanding/fixture.js +1 -1
- package/runtime/dist/src/understanding/pipeline.js +4 -4
- package/runtime/dist/src/usage/context.js +23 -0
- package/runtime/dist/src/usage/index.js +4 -0
- package/runtime/dist/src/usage/ledger-worker.js +90 -0
- package/runtime/dist/src/usage/ledger.js +74 -0
- package/runtime/dist/src/usage/model-call.js +63 -0
- package/runtime/dist/src/usage/pricing.js +68 -0
- package/runtime/dist/src/usage/summary.js +69 -0
- package/runtime/dist/src/voicemem/store-client.js +104 -21
- package/runtime/dist/src/voicemem/store-worker.js +5 -8
- package/runtime/dist/src/voicemem/versioned-memory.js +1 -1
- package/src/command.mjs +8 -1
- package/runtime/dist/src/executors/autoglm.js +0 -376
|
@@ -2,27 +2,34 @@ import { selfHostedEndpoint } from '../../config/self-hosted.js';
|
|
|
2
2
|
import { committedConversationPairsSchema } from '../history.js';
|
|
3
3
|
import { translateSystemPrompt } from '../prompt-language.js';
|
|
4
4
|
import { cascadedNarrationInstructions } from './llm.js';
|
|
5
|
-
import { originalImageUrl } from './llm.js';
|
|
6
|
-
import {
|
|
7
|
-
import { reportUsage } from '../usage.js';
|
|
5
|
+
import { chatCompletionsOutputTokensField, modelOutputTokens, originalImageUrl, toolObservations, trimToolImages, isToolObservation, imageFreeMessage } from './llm.js';
|
|
6
|
+
import { beginModelUsage, mergeModelUsage } from '../../usage/model-call.js';
|
|
8
7
|
import { codePointLengthLikePython } from '../../text/python-text.js';
|
|
8
|
+
import { llmStreamLimits, llmToolCallLimit } from './llm-stream-limits.js';
|
|
9
9
|
import { MAX_CASCADED_LLM_HISTORY_CODEPOINTS, MAX_CASCADED_LLM_HISTORY_ITEMS, } from './llm.js';
|
|
10
|
+
import { rotatedCredential } from '../../config/credential-rotation.js';
|
|
10
11
|
export { MAX_CASCADED_LLM_HISTORY_CODEPOINTS, MAX_CASCADED_LLM_HISTORY_ITEMS } from './llm.js';
|
|
11
|
-
const MAX_LINE_BYTES = 256 * 1024;
|
|
12
12
|
const MAX_EVENT_BYTES = 512 * 1024;
|
|
13
|
-
|
|
14
|
-
const
|
|
13
|
+
/** Per-response bound for display-only thinking text; it never grows provider history. */
|
|
14
|
+
export const MAX_REASONING_CODEPOINTS = 65_536;
|
|
15
15
|
export class ChatCompletionsLlmFailure extends Error {
|
|
16
16
|
code;
|
|
17
17
|
statusCode;
|
|
18
|
-
|
|
18
|
+
detail;
|
|
19
|
+
constructor(code, statusCode = null, detail = null) {
|
|
19
20
|
super(`Chat Completions LLM ${code} failure`);
|
|
20
21
|
this.code = code;
|
|
21
22
|
this.statusCode = statusCode;
|
|
23
|
+
this.detail = detail;
|
|
22
24
|
this.name = 'ChatCompletionsLlmFailure';
|
|
23
25
|
}
|
|
24
26
|
}
|
|
27
|
+
/** Provider account codes the user can act on; the rest of an error body is never kept. */
|
|
28
|
+
const ACCOUNT_CODES = { Arrearage: 'quota', insufficient_quota: 'quota', InvalidApiKey: 'auth', invalid_api_key: 'auth' };
|
|
29
|
+
const MAX_ERROR_BODY_BYTES = 4096;
|
|
30
|
+
const ERROR_BODY_DEADLINE_MS = 1000;
|
|
25
31
|
function fail(code, statusCode = null) { return new ChatCompletionsLlmFailure(code, statusCode); }
|
|
32
|
+
function protocol(detail) { return new ChatCompletionsLlmFailure('protocol', null, detail); }
|
|
26
33
|
function object(value) { return value !== null && !Array.isArray(value) && typeof value === 'object'; }
|
|
27
34
|
function jsonObject(value) { return object(value); }
|
|
28
35
|
function id(value) { return typeof value === 'string' && value.length > 0; }
|
|
@@ -39,6 +46,38 @@ function message(input) { return input.kind === 'tool_result' ? { role: 'tool',
|
|
|
39
46
|
function schema(tool) { return { type: 'function', function: { name: tool.name, ...(tool.description === undefined ? {} : { description: tool.description }), parameters: copy(tool.parameters) } }; }
|
|
40
47
|
function size(units) { const all = units.flat(); return { items: all.length, codepoints: all.reduce((sum, item) => sum + codePointLengthLikePython(JSON.stringify(withoutImage(item))), 0) }; }
|
|
41
48
|
class Session {
|
|
49
|
+
#historyLimits = { items: MAX_CASCADED_LLM_HISTORY_ITEMS, codepoints: MAX_CASCADED_LLM_HISTORY_CODEPOINTS };
|
|
50
|
+
setHistoryLimits(limits) { if (this.#started || limits.items < 1 || limits.items > 2048 || limits.codepoints < 1 || limits.codepoints > 32 * 1024 * 1024)
|
|
51
|
+
throw fail('configuration'); this.#historyLimits = { ...limits }; }
|
|
52
|
+
checkpoint() { return structuredClone({ protocol: 'chat-completions', history: this.#history, pending: this.#unresolved }); }
|
|
53
|
+
restoreCheckpoint(checkpoint) {
|
|
54
|
+
if (this.#started || this.#closed || this.#seeded || !object(checkpoint) || checkpoint.protocol !== 'chat-completions' || !Array.isArray(checkpoint.history) || !(checkpoint.pending === null || Array.isArray(checkpoint.pending)))
|
|
55
|
+
throw fail('protocol');
|
|
56
|
+
const units = [...checkpoint.history, ...(checkpoint.pending === null ? [] : [checkpoint.pending])];
|
|
57
|
+
for (const unit of units) {
|
|
58
|
+
if (!Array.isArray(unit))
|
|
59
|
+
throw fail('protocol');
|
|
60
|
+
const outstanding = new Set();
|
|
61
|
+
for (const msg of unit) {
|
|
62
|
+
if (!object(msg) || typeof msg.role !== 'string' || !['system', 'user', 'assistant', 'tool'].includes(msg.role) || !(typeof msg.content === 'string' || msg.content === null || isToolObservation(msg) && Array.isArray(msg.content) && msg.content.every(part => object(part) && (part.type === 'text' && typeof part.text === 'string' || part.type === 'image_url' && object(part.image_url) && typeof part.image_url.url === 'string' && /^data:image\/(png|jpeg);base64,[A-Za-z0-9+/]+={0,2}$/u.test(part.image_url.url)))))
|
|
63
|
+
throw fail('protocol');
|
|
64
|
+
if (Array.isArray(msg.tool_calls))
|
|
65
|
+
for (const call of msg.tool_calls) {
|
|
66
|
+
if (!object(call) || !id(call.id) || !object(call.function) || !id(call.function.name) || typeof call.function.arguments !== 'string' || outstanding.has(call.id))
|
|
67
|
+
throw fail('protocol');
|
|
68
|
+
outstanding.add(call.id);
|
|
69
|
+
}
|
|
70
|
+
if (msg.role === 'tool' && (typeof msg.tool_call_id !== 'string' || !outstanding.delete(msg.tool_call_id)))
|
|
71
|
+
throw fail('protocol');
|
|
72
|
+
}
|
|
73
|
+
if (unit !== checkpoint.pending && outstanding.size)
|
|
74
|
+
throw fail('protocol');
|
|
75
|
+
}
|
|
76
|
+
this.#history = structuredClone(checkpoint.history);
|
|
77
|
+
this.#unresolved = structuredClone(checkpoint.pending);
|
|
78
|
+
this.#seeded = true;
|
|
79
|
+
trimToolImages([...this.#history.flat(), ...(this.#unresolved ?? [])]);
|
|
80
|
+
}
|
|
42
81
|
#provider;
|
|
43
82
|
#onUsage;
|
|
44
83
|
#endpoint;
|
|
@@ -49,18 +88,29 @@ class Session {
|
|
|
49
88
|
#idleTimeoutMs;
|
|
50
89
|
#closeTimeoutMs;
|
|
51
90
|
#active = new Set();
|
|
91
|
+
#streamLimits;
|
|
92
|
+
#toolCallLimit;
|
|
52
93
|
#started = false;
|
|
53
94
|
#seeded = false;
|
|
95
|
+
/** A provider that rejects the thinking flag is remembered so later rounds never ask again. */
|
|
96
|
+
#reasoningUnsupported = false;
|
|
54
97
|
#history = [];
|
|
55
98
|
#unresolved = null;
|
|
56
99
|
#closed = false;
|
|
57
100
|
#closePromise = null;
|
|
58
101
|
constructor(options, history) {
|
|
59
102
|
this.#provider = options.provider;
|
|
60
|
-
|
|
103
|
+
try {
|
|
104
|
+
this.#streamLimits = llmStreamLimits(options);
|
|
105
|
+
this.#toolCallLimit = llmToolCallLimit(options);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
throw fail('configuration');
|
|
109
|
+
}
|
|
110
|
+
this.#onUsage = options.onUsage;
|
|
61
111
|
if ((!options.apiKey && options.provider !== 'self-hosted') || !options.model || !options.instructions)
|
|
62
112
|
throw fail('configuration');
|
|
63
|
-
this.#endpoint = endpoint(
|
|
113
|
+
this.#endpoint = endpoint(['self-hosted', 'openai-compatible'].includes(options.provider) ? selfHostedEndpoint(options.baseUrl, 'http', options.provider === 'self-hosted' ? 'SELF_HOSTED_LLM_BASE_URL' : 'OPENAI_COMPATIBLE_BASE_URL') : options.baseUrl);
|
|
64
114
|
this.#apiKey = options.apiKey;
|
|
65
115
|
this.#model = options.model;
|
|
66
116
|
this.#instructions = options.instructions;
|
|
@@ -78,7 +128,8 @@ class Session {
|
|
|
78
128
|
if (input.signal.aborted)
|
|
79
129
|
throw fail('aborted');
|
|
80
130
|
this.#started = true;
|
|
81
|
-
const current = input.inputs
|
|
131
|
+
const current = wireMessages(input.inputs), unresolved = this.#unresolved;
|
|
132
|
+
trimToolImages([...this.#history.flat(), ...(unresolved ?? []), ...current]);
|
|
82
133
|
if (unresolved === null && input.inputs.some(item => item.kind === 'tool_result'))
|
|
83
134
|
throw fail('protocol');
|
|
84
135
|
if (unresolved !== null)
|
|
@@ -93,56 +144,92 @@ class Session {
|
|
|
93
144
|
// Tool-call/result pairs stay intact; the full turn is still recorded for the next user turn.
|
|
94
145
|
const context = factOnly
|
|
95
146
|
? [...(unresolved?.slice(-1) ?? []),
|
|
96
|
-
...input.inputs.filter(item => item.kind === 'host_activation' || item.kind === 'tool_result')
|
|
147
|
+
...wireMessages(input.inputs.filter(item => item.kind === 'host_activation' || item.kind === 'tool_result'))]
|
|
97
148
|
: [...this.#history.flat(), ...(unresolved ?? []), ...current];
|
|
98
149
|
// Self-hosted Qwen chat templates accept system messages only at the beginning.
|
|
99
150
|
const messages = this.#provider === 'self-hosted'
|
|
100
151
|
? [{ 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
152
|
: [{ role: 'system', content: systemContent }, ...context];
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
if (
|
|
112
|
-
|
|
113
|
-
|
|
153
|
+
const buildBody = (reasoning) => {
|
|
154
|
+
const value = { model: this.#model, messages: messages, stream: true, stream_options: { include_usage: true } };
|
|
155
|
+
// Disabled keeps the historical per-provider shape; supported providers may opt in.
|
|
156
|
+
if (this.#provider === 'deepseek')
|
|
157
|
+
value.thinking = { type: reasoning === 'enabled' ? 'enabled' : 'disabled' };
|
|
158
|
+
else if (this.#provider === 'qwen')
|
|
159
|
+
value.enable_thinking = reasoning === 'enabled';
|
|
160
|
+
else if (this.#provider === 'openai')
|
|
161
|
+
value.reasoning_effort = reasoning === 'enabled' ? 'low' : 'none';
|
|
162
|
+
if (input.tools.length > 0) {
|
|
163
|
+
value.tools = input.tools.map(schema);
|
|
164
|
+
if (this.#provider !== 'gemini')
|
|
165
|
+
value.parallel_tool_calls = this.#toolCallLimit > 1;
|
|
166
|
+
}
|
|
167
|
+
// Never leave the output ceiling to the provider default: the ceiling is what makes a
|
|
168
|
+
// truncated reply detectable and resumable instead of silently short.
|
|
169
|
+
value[chatCompletionsOutputTokensField(this.#provider)] = modelOutputTokens(this.#provider);
|
|
170
|
+
return value;
|
|
171
|
+
};
|
|
172
|
+
let reasoning = input.reasoning === 'enabled' && !this.#reasoningUnsupported ? 'enabled' : 'disabled';
|
|
114
173
|
const active = { completion: null, usageDeadline: null, controller: new AbortController(), reader: null, failureCode: null };
|
|
115
174
|
const stop = () => { active.failureCode ??= 'aborted'; active.controller.abort(); void this.#cancel(active.reader); };
|
|
116
175
|
input.signal.addEventListener('abort', stop, { once: true });
|
|
117
176
|
this.#active.add(active);
|
|
118
177
|
let responseId = null, terminal = false;
|
|
119
|
-
|
|
178
|
+
let finishUsage;
|
|
120
179
|
let usage;
|
|
121
180
|
let events;
|
|
181
|
+
const toolIndexes = new Set();
|
|
122
182
|
const captureUsage = (event) => {
|
|
123
183
|
if (object(event.usage))
|
|
124
|
-
usage = event.usage;
|
|
184
|
+
usage = mergeModelUsage(usage, event.usage);
|
|
125
185
|
};
|
|
126
186
|
try {
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
187
|
+
const request = (current) => this.#timed(this.#fetch(this.#endpoint, { method: 'POST', redirect: ['self-hosted', 'openai-compatible'].includes(this.#provider) ? 'error' : 'follow', headers: { ...(this.#apiKey ? { authorization: `Bearer ${rotatedCredential(this.#apiKey)}` } : {}), 'content-type': 'application/json', accept: 'text/event-stream' }, body: JSON.stringify(current), signal: active.controller.signal }), active);
|
|
188
|
+
const send = async () => {
|
|
189
|
+
try {
|
|
190
|
+
return await request(buildBody(reasoning));
|
|
191
|
+
}
|
|
192
|
+
catch (error) {
|
|
193
|
+
if (error instanceof ChatCompletionsLlmFailure)
|
|
194
|
+
throw error;
|
|
195
|
+
throw fail(input.signal.aborted ? 'aborted' : this.#closed ? 'closed' : 'network');
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
let response = await send();
|
|
199
|
+
// A provider that rejects the thinking flag itself must not kill the round: retry once without it.
|
|
200
|
+
if (!response.ok && (response.status === 400 || response.status === 422) && reasoning === 'enabled') {
|
|
201
|
+
this.#reasoningUnsupported = true;
|
|
202
|
+
reasoning = 'disabled';
|
|
203
|
+
try {
|
|
204
|
+
await response.body?.cancel();
|
|
205
|
+
}
|
|
206
|
+
catch { /* the abandoned body needs no reader */ }
|
|
207
|
+
response = await send();
|
|
139
208
|
}
|
|
209
|
+
finishUsage = beginModelUsage(this.#onUsage, this.#endpoint, this.#model, 'llm', this.#provider === 'self-hosted' || this.#provider === 'openai-compatible' ? 'custom' : this.#provider, this.#provider === 'qwen' ? reasoning : undefined);
|
|
210
|
+
if (!response.ok)
|
|
211
|
+
throw new ChatCompletionsLlmFailure('http', response.status, await this.#accountFailure(response, active));
|
|
140
212
|
if (response.body === null || !response.headers.get('content-type')?.toLowerCase().startsWith('text/event-stream')) {
|
|
141
213
|
await this.#cancel(response.body?.getReader() ?? null);
|
|
142
214
|
throw fail('protocol');
|
|
143
215
|
}
|
|
144
216
|
active.reader = response.body.getReader();
|
|
145
217
|
let started = false, text = '', sawText = false;
|
|
218
|
+
let reasoningCodepoints = 0, reasoningText = '';
|
|
219
|
+
// The provider-private reasoning copy is complete (DeepSeek requires the whole
|
|
220
|
+
// field back); only the UI event is bounded by MAX_REASONING_CODEPOINTS.
|
|
221
|
+
const reasoningDelta = (value) => {
|
|
222
|
+
if (typeof value !== 'string' || value === '')
|
|
223
|
+
return undefined;
|
|
224
|
+
reasoningText += value;
|
|
225
|
+
const left = MAX_REASONING_CODEPOINTS - reasoningCodepoints;
|
|
226
|
+
if (left <= 0)
|
|
227
|
+
return undefined;
|
|
228
|
+
const points = [...value];
|
|
229
|
+
const chunk = points.length <= left ? value : points.slice(0, left).join('');
|
|
230
|
+
reasoningCodepoints += Math.min(points.length, left);
|
|
231
|
+
return chunk;
|
|
232
|
+
};
|
|
146
233
|
const fragments = new Map();
|
|
147
234
|
events = this.#events(active)[Symbol.asyncIterator]();
|
|
148
235
|
while (true) {
|
|
@@ -153,20 +240,25 @@ class Session {
|
|
|
153
240
|
captureUsage(event);
|
|
154
241
|
if (event.id !== undefined) {
|
|
155
242
|
if (!id(event.id) || (responseId !== null && responseId !== event.id))
|
|
156
|
-
throw
|
|
243
|
+
throw protocol('response_id');
|
|
157
244
|
responseId ??= event.id;
|
|
158
245
|
}
|
|
159
246
|
if (!Array.isArray(event.choices))
|
|
160
247
|
continue;
|
|
161
248
|
for (const choice of event.choices) {
|
|
162
249
|
if (!object(choice) || !object(choice.delta))
|
|
163
|
-
throw
|
|
250
|
+
throw protocol('choice_delta');
|
|
164
251
|
const content = choice.delta.content, calls = choice.delta.tool_calls;
|
|
165
252
|
if (content !== undefined && content !== null && typeof content !== 'string')
|
|
166
|
-
throw
|
|
253
|
+
throw protocol('content_shape');
|
|
167
254
|
if (calls !== undefined && !Array.isArray(calls))
|
|
168
|
-
throw
|
|
169
|
-
|
|
255
|
+
throw protocol('tool_calls_shape');
|
|
256
|
+
// Only requested thinking is surfaced: a provider that volunteers reasoning while the
|
|
257
|
+
// feature is off must never leak it into Build.
|
|
258
|
+
const thinking = reasoning === 'enabled' ? reasoningDelta(choice.delta.reasoning_content) ?? reasoningDelta(choice.delta.reasoning) : undefined;
|
|
259
|
+
if (thinking !== undefined)
|
|
260
|
+
yield { kind: 'reasoning_delta', text: thinking };
|
|
261
|
+
if (!started && (((input.tools.length === 0 || input.previewText === true) && typeof content === 'string' && content !== '') || (choice.finish_reason !== undefined && choice.finish_reason !== null))) {
|
|
170
262
|
if (responseId === null)
|
|
171
263
|
throw fail('protocol');
|
|
172
264
|
started = true;
|
|
@@ -178,19 +270,24 @@ class Session {
|
|
|
178
270
|
text += content;
|
|
179
271
|
if (input.tools.length === 0)
|
|
180
272
|
yield { kind: 'text_delta', text: content };
|
|
273
|
+
else if (input.previewText === true)
|
|
274
|
+
yield { kind: 'text_preview', text: content };
|
|
181
275
|
}
|
|
182
|
-
for (const call of calls ?? [])
|
|
276
|
+
for (const call of calls ?? []) {
|
|
277
|
+
if (object(call) && typeof call.index === 'number' && Number.isSafeInteger(call.index))
|
|
278
|
+
toolIndexes.add(call.index);
|
|
183
279
|
this.#fragment(fragments, call);
|
|
280
|
+
}
|
|
184
281
|
if (choice.finish_reason !== undefined && choice.finish_reason !== null) {
|
|
185
282
|
if (typeof choice.finish_reason !== 'string' || responseId === null)
|
|
186
283
|
throw fail('protocol');
|
|
187
284
|
if (choice.finish_reason === 'stop') {
|
|
188
285
|
if (fragments.size > 0)
|
|
189
|
-
throw
|
|
286
|
+
throw protocol('tool_finish_reason');
|
|
190
287
|
// With tools enabled, wait for the response kind before publishing speech.
|
|
191
288
|
if (input.tools.length > 0 && text !== '')
|
|
192
289
|
yield { kind: 'text_delta', text };
|
|
193
|
-
this.#history.push([...(unresolved ?? []), ...current, { role: 'assistant', content: text }].map(withoutImage));
|
|
290
|
+
this.#history.push([...(unresolved ?? []), ...current, { role: 'assistant', content: text, ...(this.#provider === 'deepseek' && reasoningText !== '' ? { reasoning_content: reasoningText } : {}) }].map(item => isToolObservation(item) ? item : withoutImage(item)));
|
|
194
291
|
this.#unresolved = null;
|
|
195
292
|
terminal = true;
|
|
196
293
|
yield { kind: 'response_completed', response_id: responseId };
|
|
@@ -200,20 +297,35 @@ class Session {
|
|
|
200
297
|
if ((sawText && input.tools.length === 0) || fragments.size === 0)
|
|
201
298
|
throw fail('protocol');
|
|
202
299
|
const callsOut = this.#calls(fragments);
|
|
300
|
+
// Text-mode callers keep the narration that preceded the tool decision; voice still
|
|
301
|
+
// withholds it so the opening sentence never reaches TTS before the round resolves.
|
|
302
|
+
if (text !== '' && input.previewText === true)
|
|
303
|
+
yield { kind: 'text_delta', text };
|
|
203
304
|
for (const call of callsOut)
|
|
204
305
|
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 }];
|
|
306
|
+
this.#unresolved = [...(unresolved ?? []), ...current, { role: 'assistant', content: null, tool_calls: callsOut, ...(this.#provider === 'deepseek' && reasoningText !== '' ? { reasoning_content: reasoningText } : {}) }];
|
|
206
307
|
terminal = true;
|
|
207
308
|
yield { kind: 'response_completed', response_id: responseId };
|
|
208
309
|
return;
|
|
209
310
|
}
|
|
311
|
+
else if (choice.finish_reason === 'length') {
|
|
312
|
+
// The provider stopped at its output ceiling. Text it withheld for the tool decision
|
|
313
|
+
// is real narration: hand it to display-only consumers before reporting a limit
|
|
314
|
+
// failure the host can continue from.
|
|
315
|
+
if (text !== '' && input.tools.length > 0 && input.previewText === true)
|
|
316
|
+
yield { kind: 'text_delta', text };
|
|
317
|
+
throw new ChatCompletionsLlmFailure('output_limit', null, fragments.size > 0 ? 'tool_arguments' : 'length');
|
|
318
|
+
}
|
|
210
319
|
else
|
|
211
|
-
throw
|
|
320
|
+
throw protocol('finish_reason');
|
|
212
321
|
}
|
|
213
322
|
}
|
|
214
323
|
}
|
|
215
|
-
if (!terminal)
|
|
216
|
-
|
|
324
|
+
if (!terminal) {
|
|
325
|
+
if (!active.failureCode && !this.#closed && !input.signal.aborted)
|
|
326
|
+
throw protocol('incomplete_stream');
|
|
327
|
+
throw fail(active.failureCode ?? (this.#closed ? 'closed' : 'aborted'));
|
|
328
|
+
}
|
|
217
329
|
}
|
|
218
330
|
catch (error) {
|
|
219
331
|
if (terminal)
|
|
@@ -221,7 +333,7 @@ class Session {
|
|
|
221
333
|
const stable = error instanceof ChatCompletionsLlmFailure
|
|
222
334
|
? error : fail(active.failureCode ?? (this.#closed ? 'closed' : input.signal.aborted ? 'aborted' : 'network'));
|
|
223
335
|
if (responseId !== null && !terminal) {
|
|
224
|
-
yield { kind: 'response_failed', response_id: responseId, code: stable.code };
|
|
336
|
+
yield { kind: 'response_failed', response_id: responseId, code: stable.code, ...(stable.detail ? { detail: stable.detail } : {}), ...(stable.code === 'protocol' && this.#toolCallLimit > 1 ? { tool_call_count: toolIndexes.size } : {}) };
|
|
225
337
|
return;
|
|
226
338
|
}
|
|
227
339
|
throw stable;
|
|
@@ -230,7 +342,7 @@ class Session {
|
|
|
230
342
|
// Receipt of a matching tool result survives interruption of its narration.
|
|
231
343
|
// Preserve the resolved pair; the next user turn must not owe that result again.
|
|
232
344
|
if (!terminal && unresolved !== null) {
|
|
233
|
-
this.#history.push([...unresolved, ...current].map(withoutImage));
|
|
345
|
+
this.#history.push([...unresolved, ...current].map(item => isToolObservation(item) ? item : withoutImage(item)));
|
|
234
346
|
this.#unresolved = null;
|
|
235
347
|
}
|
|
236
348
|
const finish = async () => {
|
|
@@ -247,16 +359,7 @@ class Session {
|
|
|
247
359
|
}
|
|
248
360
|
catch { /* Metering cannot change a completed response. */ }
|
|
249
361
|
}
|
|
250
|
-
|
|
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
|
-
});
|
|
362
|
+
finishUsage?.(usage, terminal ? 'success' : input.signal.aborted ? 'cancelled' : 'error', responseId);
|
|
260
363
|
input.signal.removeEventListener('abort', stop);
|
|
261
364
|
await this.#cancel(active.reader);
|
|
262
365
|
this.#active.delete(active);
|
|
@@ -286,28 +389,32 @@ class Session {
|
|
|
286
389
|
this.#trim([]);
|
|
287
390
|
}
|
|
288
391
|
#fragment(fragments, value) {
|
|
289
|
-
if (!object(value) || typeof value.index !== 'number' || !Number.isSafeInteger(value.index) || value.index
|
|
290
|
-
throw
|
|
392
|
+
if (!object(value) || typeof value.index !== 'number' || !Number.isSafeInteger(value.index) || value.index < 0)
|
|
393
|
+
throw protocol('tool_index');
|
|
394
|
+
if (value.index >= this.#toolCallLimit)
|
|
395
|
+
throw protocol('tool_call_limit');
|
|
396
|
+
if (value.function !== undefined && !object(value.function))
|
|
397
|
+
throw protocol('tool_function_shape');
|
|
291
398
|
const index = value.index;
|
|
292
399
|
const found = fragments.get(index) ?? { id: null, name: '', arguments: '' };
|
|
293
400
|
// A null id on a later DashScope delta contributes no new identity; final validation still requires an id.
|
|
294
401
|
if (value.id !== undefined && value.id !== null && value.id !== '') {
|
|
295
402
|
if (!id(value.id) || (found.id !== null && found.id !== value.id))
|
|
296
|
-
throw
|
|
403
|
+
throw protocol('tool_identity');
|
|
297
404
|
found.id = value.id;
|
|
298
405
|
}
|
|
299
406
|
// DashScope may append arguments:null after complete JSON; that delta contributes no bytes.
|
|
300
407
|
const fn = value.function;
|
|
301
|
-
if (fn
|
|
408
|
+
if (object(fn)) {
|
|
302
409
|
if (fn.name !== undefined) {
|
|
303
410
|
if (typeof fn.name !== 'string')
|
|
304
|
-
throw
|
|
411
|
+
throw protocol('tool_name');
|
|
305
412
|
found.name += fn.name;
|
|
306
413
|
}
|
|
307
414
|
;
|
|
308
415
|
if (fn.arguments !== undefined && fn.arguments !== null) {
|
|
309
416
|
if (typeof fn.arguments !== 'string')
|
|
310
|
-
throw
|
|
417
|
+
throw protocol('tool_arguments_shape');
|
|
311
418
|
found.arguments += fn.arguments;
|
|
312
419
|
}
|
|
313
420
|
}
|
|
@@ -320,15 +427,26 @@ class Session {
|
|
|
320
427
|
}
|
|
321
428
|
fragments.set(index, found);
|
|
322
429
|
}
|
|
323
|
-
#calls(fragments) {
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
430
|
+
#calls(fragments) {
|
|
431
|
+
const ids = new Set();
|
|
432
|
+
return [...fragments.entries()].sort(([a], [b]) => a - b).map(([index, part], position) => {
|
|
433
|
+
if (index !== position)
|
|
434
|
+
throw protocol('tool_index');
|
|
435
|
+
if (!id(part.id) || !id(part.name) || ids.has(part.id))
|
|
436
|
+
throw protocol('tool_identity');
|
|
437
|
+
ids.add(part.id);
|
|
438
|
+
let args;
|
|
439
|
+
try {
|
|
440
|
+
args = JSON.parse(part.arguments);
|
|
441
|
+
}
|
|
442
|
+
catch {
|
|
443
|
+
throw protocol('tool_arguments_json');
|
|
444
|
+
}
|
|
445
|
+
if (!jsonObject(args))
|
|
446
|
+
throw protocol('tool_arguments_object');
|
|
447
|
+
return { id: part.id, type: 'function', ...(part.extra_content ? { extra_content: part.extra_content } : {}), function: { name: part.name, arguments: JSON.stringify(copy(args)) } };
|
|
448
|
+
});
|
|
327
449
|
}
|
|
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
450
|
#checkResults(inputs, unresolved) {
|
|
333
451
|
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
452
|
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'))
|
|
@@ -342,7 +460,7 @@ class Session {
|
|
|
342
460
|
}
|
|
343
461
|
#trim(unresolved) { while (true) {
|
|
344
462
|
const measured = size([...this.#history, unresolved]);
|
|
345
|
-
if (measured.items <=
|
|
463
|
+
if (measured.items <= this.#historyLimits.items && measured.codepoints <= this.#historyLimits.codepoints)
|
|
346
464
|
return;
|
|
347
465
|
if (this.#history.length === 0)
|
|
348
466
|
throw fail('overflow');
|
|
@@ -352,7 +470,7 @@ class Session {
|
|
|
352
470
|
const reader = active.reader, decoder = new TextDecoder('utf-8', { fatal: true });
|
|
353
471
|
let buffered = new Uint8Array(), total = 0, parts = [], partBytes = 0, count = 0;
|
|
354
472
|
const line = (raw) => { let bytes = raw; if (bytes.at(-1) === 13)
|
|
355
|
-
bytes = bytes.subarray(0, bytes.length - 1); if (bytes.length >
|
|
473
|
+
bytes = bytes.subarray(0, bytes.length - 1); if (bytes.length > this.#streamLimits.lineBytes)
|
|
356
474
|
throw fail('overflow'); let text; try {
|
|
357
475
|
text = decoder.decode(bytes);
|
|
358
476
|
}
|
|
@@ -363,12 +481,12 @@ class Session {
|
|
|
363
481
|
return null;
|
|
364
482
|
const part = text.slice(5).replace(/^ /u, '');
|
|
365
483
|
partBytes += new TextEncoder().encode(part).length + (parts.length === 0 ? 0 : 1);
|
|
366
|
-
if (partBytes >
|
|
484
|
+
if (partBytes > this.#streamLimits.eventBytes)
|
|
367
485
|
throw fail('overflow');
|
|
368
486
|
parts.push(part);
|
|
369
487
|
return null;
|
|
370
488
|
} ; if (parts.length === 0)
|
|
371
|
-
return null; count += 1; if (count >
|
|
489
|
+
return null; count += 1; if (count > this.#streamLimits.events)
|
|
372
490
|
throw fail('overflow'); const joined = parts.join('\n'); parts = []; partBytes = 0; if (joined === '[DONE]')
|
|
373
491
|
return 'done'; let parsed; try {
|
|
374
492
|
parsed = JSON.parse(joined);
|
|
@@ -402,7 +520,7 @@ class Session {
|
|
|
402
520
|
if (!(read.value instanceof Uint8Array))
|
|
403
521
|
throw fail('protocol');
|
|
404
522
|
total += read.value.length;
|
|
405
|
-
if (total >
|
|
523
|
+
if (total > this.#streamLimits.responseBytes)
|
|
406
524
|
throw fail('overflow');
|
|
407
525
|
const next = new Uint8Array(buffered.length + read.value.length);
|
|
408
526
|
next.set(buffered);
|
|
@@ -419,10 +537,48 @@ class Session {
|
|
|
419
537
|
newline = buffered.indexOf(10);
|
|
420
538
|
}
|
|
421
539
|
;
|
|
422
|
-
if (buffered.length >
|
|
540
|
+
if (buffered.length > this.#streamLimits.lineBytes)
|
|
423
541
|
throw fail('overflow');
|
|
424
542
|
}
|
|
425
543
|
}
|
|
544
|
+
/** Reads at most a small error body for an allowlisted account code, then the status. */
|
|
545
|
+
async #accountFailure(response, active) {
|
|
546
|
+
const reader = response.body?.getReader() ?? null;
|
|
547
|
+
let code, timer;
|
|
548
|
+
// One absolute budget for the whole body: a per-read idle timeout would let a trickling body hold the turn.
|
|
549
|
+
const expired = new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error('error body deadline')), ERROR_BODY_DEADLINE_MS); });
|
|
550
|
+
try {
|
|
551
|
+
const chunks = [];
|
|
552
|
+
let size = 0;
|
|
553
|
+
while (reader !== null && size <= MAX_ERROR_BODY_BYTES) {
|
|
554
|
+
const { done, value } = await Promise.race([this.#timed(reader.read(), active), expired]);
|
|
555
|
+
if (done)
|
|
556
|
+
break;
|
|
557
|
+
chunks.push(value);
|
|
558
|
+
size += value.byteLength;
|
|
559
|
+
}
|
|
560
|
+
if (size <= MAX_ERROR_BODY_BYTES) {
|
|
561
|
+
const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
562
|
+
code = body.error?.code ?? body.code;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
catch {
|
|
566
|
+
// A missing, slow or malformed body leaves only the status to classify.
|
|
567
|
+
}
|
|
568
|
+
finally {
|
|
569
|
+
clearTimeout(timer);
|
|
570
|
+
await this.#cancel(reader);
|
|
571
|
+
}
|
|
572
|
+
if (typeof code === 'string' && Object.hasOwn(ACCOUNT_CODES, code))
|
|
573
|
+
return ACCOUNT_CODES[code];
|
|
574
|
+
if (response.status === 401 || response.status === 403)
|
|
575
|
+
return 'auth';
|
|
576
|
+
if (response.status === 402)
|
|
577
|
+
return 'quota';
|
|
578
|
+
if (response.status === 429)
|
|
579
|
+
return 'rate_limited';
|
|
580
|
+
return null;
|
|
581
|
+
}
|
|
426
582
|
async #cancel(reader) {
|
|
427
583
|
if (reader === null)
|
|
428
584
|
return;
|
|
@@ -472,7 +628,11 @@ class Session {
|
|
|
472
628
|
}
|
|
473
629
|
}
|
|
474
630
|
export function createChatCompletionsLlmFactory(options) { return { open: input => new Session(options, input?.history) }; }
|
|
475
|
-
function withoutImage(message) {
|
|
476
|
-
|
|
631
|
+
function withoutImage(message) { return imageFreeMessage(message); }
|
|
632
|
+
function wireMessages(inputs) {
|
|
633
|
+
if (!inputs.some(input => input.kind === 'tool_result' && input.images?.length))
|
|
634
|
+
return inputs.map(message);
|
|
635
|
+
const results = inputs.filter(input => input.kind === 'tool_result'), other = inputs.filter(input => input.kind !== 'tool_result');
|
|
636
|
+
return [...results.map(message), ...toolObservations(results), ...other.map(message)];
|
|
477
637
|
}
|
|
478
638
|
//# sourceMappingURL=chat-completions-llm.js.map
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export const DEFAULT_LLM_STREAM_LIMITS = Object.freeze({ events: 4096, responseBytes: 8 * 1024 * 1024, eventBytes: 512 * 1024, lineBytes: 256 * 1024 });
|
|
2
|
+
// Local builds can produce large file arguments and many small streaming deltas.
|
|
3
|
+
// This bounds each model request; the complete agent loop has no wall-clock limit.
|
|
4
|
+
export const PLAN_LLM_TRANSPORT = Object.freeze({ maxToolCallsPerResponse: 24 });
|
|
5
|
+
export const BUILD_LLM_TRANSPORT = Object.freeze({ ...PLAN_LLM_TRANSPORT, maxToolCallsPerResponse: 64, idleTimeoutMs: 10 * 60 * 1000, streamLimits: Object.freeze({ events: 65536, responseBytes: 32 * 1024 * 1024, eventBytes: 8 * 1024 * 1024, lineBytes: 8 * 1024 * 1024 }) });
|
|
6
|
+
export function llmToolCallLimit(options) {
|
|
7
|
+
const limit = options.maxToolCallsPerResponse ?? 1;
|
|
8
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 64)
|
|
9
|
+
throw Error('invalid_llm_tool_call_limit');
|
|
10
|
+
return limit;
|
|
11
|
+
}
|
|
12
|
+
export function llmStreamLimits(options) {
|
|
13
|
+
const limits = { ...DEFAULT_LLM_STREAM_LIMITS, ...options.streamLimits };
|
|
14
|
+
if (Object.values(limits).some(value => !Number.isSafeInteger(value) || value <= 0))
|
|
15
|
+
throw Error('invalid_llm_stream_limits');
|
|
16
|
+
return limits;
|
|
17
|
+
}
|
|
18
|
+
//# sourceMappingURL=llm-stream-limits.js.map
|