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,8 @@
|
|
|
1
|
+
/** Raised by a transport when the peer closed; mapped to a recoverable disconnect. */
|
|
2
|
+
export class RealtimeSocketClosedError extends Error {
|
|
3
|
+
constructor(message = 'realtime socket closed') {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = 'RealtimeSocketClosedError';
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
//# sourceMappingURL=transport.js.map
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
const meters = ['inputTokens', 'outputTokens', 'inputTextTokens', 'inputAudioTokens',
|
|
2
|
+
'outputTextTokens', 'outputAudioTokens', 'cachedTokens', 'reasoningTokens',
|
|
3
|
+
'audioDurationMs', 'characters'];
|
|
4
|
+
export function reportUsage(reporter, report) {
|
|
5
|
+
if (reporter === undefined)
|
|
6
|
+
return;
|
|
7
|
+
if (!['qwen', 'stepfun', 'ark', 'deepseek', 'volcengine', 'openai', 'gemini'].includes(report.provider)
|
|
8
|
+
|| !['llm', 'realtime', 'asr', 'tts'].includes(report.service)
|
|
9
|
+
|| typeof report.id !== 'string' || !report.id || report.id.length > 256
|
|
10
|
+
|| typeof report.model !== 'string' || !report.model || report.model.length > 256)
|
|
11
|
+
return;
|
|
12
|
+
const counts = {};
|
|
13
|
+
let complete = report.status === 'complete';
|
|
14
|
+
for (const key of meters) {
|
|
15
|
+
const value = report[key];
|
|
16
|
+
if (value === undefined || value === null)
|
|
17
|
+
continue;
|
|
18
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
19
|
+
complete = false;
|
|
20
|
+
else
|
|
21
|
+
counts[key] = value;
|
|
22
|
+
}
|
|
23
|
+
const required = report.service === 'asr' ? ['audioDurationMs']
|
|
24
|
+
: report.service === 'tts' ? ['characters'] : ['inputTokens', 'outputTokens'];
|
|
25
|
+
if (required.some(key => counts[key] === undefined))
|
|
26
|
+
complete = false;
|
|
27
|
+
try {
|
|
28
|
+
reporter(Object.freeze({ id: report.id, service: report.service, provider: report.provider,
|
|
29
|
+
model: report.model, status: complete ? 'complete' : 'missing', ...counts,
|
|
30
|
+
...(report.pricingRegion === undefined ? {} : { pricingRegion: report.pricingRegion }),
|
|
31
|
+
...(report.outputModality === undefined ? {} : { outputModality: report.outputModality }),
|
|
32
|
+
}));
|
|
33
|
+
}
|
|
34
|
+
catch { /* A closed UI/IPC channel cannot change generation or cancellation. */ }
|
|
35
|
+
}
|
|
36
|
+
/** Pricing is tied to the selected host endpoint, never inferred from a model name alone. */
|
|
37
|
+
export function usageReporterForEndpoint(reporter, endpoint) {
|
|
38
|
+
if (reporter === undefined)
|
|
39
|
+
return undefined;
|
|
40
|
+
let pricingRegion = 'unknown';
|
|
41
|
+
try {
|
|
42
|
+
const url = new URL(endpoint);
|
|
43
|
+
if (url.username === '' && url.password === '' && (!url.port || url.port === '443')
|
|
44
|
+
&& ['https:', 'wss:'].includes(url.protocol)) {
|
|
45
|
+
if (['dashscope.aliyuncs.com', 'ark.cn-beijing.volces.com', 'openspeech.bytedance.com'].includes(url.hostname)
|
|
46
|
+
|| /^[a-zA-Z0-9-]+\.cn-beijing\.maas\.aliyuncs\.com$/u.test(url.hostname))
|
|
47
|
+
pricingRegion = 'cn-beijing';
|
|
48
|
+
else if (url.hostname === 'dashscope-intl.aliyuncs.com')
|
|
49
|
+
pricingRegion = 'singapore';
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
catch { /* Custom/invalid endpoints have no known public price. */ }
|
|
53
|
+
return report => reportUsage(reporter, { ...report, pricingRegion });
|
|
54
|
+
}
|
|
55
|
+
//# sourceMappingURL=usage.js.map
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { callKey } from './service-state.js';
|
|
2
|
+
/**
|
|
3
|
+
* Bounded causal join between one provider user item, its response and its Memory origin.
|
|
4
|
+
*
|
|
5
|
+
* Provider ids are reusable after reconnect, so every lookup is epoch-scoped. Responses bind by
|
|
6
|
+
* the exact user-input revision captured when their provider turn opened; an orphaned earlier item
|
|
7
|
+
* can therefore age out, but can never be shifted onto a later response.
|
|
8
|
+
*/
|
|
9
|
+
export class UserOriginBindingLedger {
|
|
10
|
+
#limit;
|
|
11
|
+
#epoch = 0;
|
|
12
|
+
#itemsByRevision = new Map();
|
|
13
|
+
#itemRevisionKeys = new Map();
|
|
14
|
+
#responseItems = new Map();
|
|
15
|
+
constructor(limit) {
|
|
16
|
+
if (!Number.isInteger(limit) || limit <= 0)
|
|
17
|
+
throw new RangeError('limit must be positive');
|
|
18
|
+
this.#limit = limit;
|
|
19
|
+
}
|
|
20
|
+
beginEpoch(epoch) {
|
|
21
|
+
if (!Number.isInteger(epoch) || epoch < 0)
|
|
22
|
+
throw new RangeError('epoch must be non-negative');
|
|
23
|
+
this.#epoch = epoch;
|
|
24
|
+
this.#itemsByRevision.clear();
|
|
25
|
+
this.#itemRevisionKeys.clear();
|
|
26
|
+
this.#responseItems.clear();
|
|
27
|
+
}
|
|
28
|
+
registerUserItem(input) {
|
|
29
|
+
if (input.epoch !== this.#epoch
|
|
30
|
+
|| !Number.isInteger(input.revision)
|
|
31
|
+
|| input.revision <= 0
|
|
32
|
+
|| input.itemId === '')
|
|
33
|
+
return false;
|
|
34
|
+
const itemKey = callKey(input.epoch, input.itemId);
|
|
35
|
+
const knownRevisionKey = this.#itemRevisionKeys.get(itemKey);
|
|
36
|
+
const revisionKey = callKey(input.epoch, String(input.revision));
|
|
37
|
+
if (knownRevisionKey !== undefined)
|
|
38
|
+
return knownRevisionKey === revisionKey;
|
|
39
|
+
if (this.#itemsByRevision.has(revisionKey))
|
|
40
|
+
return false;
|
|
41
|
+
this.#itemsByRevision.set(revisionKey, {
|
|
42
|
+
epoch: input.epoch,
|
|
43
|
+
revision: input.revision,
|
|
44
|
+
item_id: input.itemId,
|
|
45
|
+
origin_ref: null,
|
|
46
|
+
transcript_failed: false,
|
|
47
|
+
claimed: false,
|
|
48
|
+
});
|
|
49
|
+
this.#itemRevisionKeys.set(itemKey, revisionKey);
|
|
50
|
+
this.#pruneItems();
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
bindResponse(input) {
|
|
54
|
+
if (input.epoch !== this.#epoch) {
|
|
55
|
+
return { status: 'epoch_mismatch', revision: input.revision };
|
|
56
|
+
}
|
|
57
|
+
const responseKey = callKey(input.epoch, input.responseId);
|
|
58
|
+
const existingItemId = this.#responseItems.get(responseKey);
|
|
59
|
+
if (existingItemId !== undefined) {
|
|
60
|
+
const item = this.#itemFor(input.epoch, existingItemId);
|
|
61
|
+
return item === undefined
|
|
62
|
+
? { status: 'missing_item', revision: input.revision }
|
|
63
|
+
: { status: 'bound', item_id: item.item_id, revision: item.revision };
|
|
64
|
+
}
|
|
65
|
+
const item = this.#itemsByRevision.get(callKey(input.epoch, String(input.revision)));
|
|
66
|
+
if (item === undefined || item.transcript_failed) {
|
|
67
|
+
return { status: 'missing_item', revision: input.revision };
|
|
68
|
+
}
|
|
69
|
+
if (item.claimed)
|
|
70
|
+
return { status: 'item_already_claimed', revision: input.revision };
|
|
71
|
+
item.claimed = true;
|
|
72
|
+
this.#rememberResponse(responseKey, item.item_id);
|
|
73
|
+
return { status: 'bound', item_id: item.item_id, revision: item.revision };
|
|
74
|
+
}
|
|
75
|
+
/** A bounded retry may reuse only the exact reserved item, never another revision's item. */
|
|
76
|
+
bindRetryResponse(input) {
|
|
77
|
+
if (input.epoch !== this.#epoch)
|
|
78
|
+
return false;
|
|
79
|
+
const item = this.#itemFor(input.epoch, input.itemId);
|
|
80
|
+
if (item === undefined || item.transcript_failed || item.origin_ref === null)
|
|
81
|
+
return false;
|
|
82
|
+
const responseKey = callKey(input.epoch, input.responseId);
|
|
83
|
+
const existing = this.#responseItems.get(responseKey);
|
|
84
|
+
if (existing !== undefined)
|
|
85
|
+
return existing === input.itemId;
|
|
86
|
+
this.#rememberResponse(responseKey, input.itemId);
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
resolveTranscript(input) {
|
|
90
|
+
const item = this.#itemFor(input.epoch, input.itemId);
|
|
91
|
+
if (item === undefined || item.transcript_failed || input.originRef === '')
|
|
92
|
+
return false;
|
|
93
|
+
item.origin_ref = input.originRef;
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
failTranscript(epoch, itemId) {
|
|
97
|
+
const item = this.#itemFor(epoch, itemId);
|
|
98
|
+
if (item === undefined)
|
|
99
|
+
return false;
|
|
100
|
+
item.transcript_failed = true;
|
|
101
|
+
item.origin_ref = null;
|
|
102
|
+
for (const [responseKey, boundItemId] of [...this.#responseItems]) {
|
|
103
|
+
if (boundItemId === itemId)
|
|
104
|
+
this.#responseItems.delete(responseKey);
|
|
105
|
+
}
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
itemForResponse(epoch, responseId) {
|
|
109
|
+
if (epoch !== this.#epoch)
|
|
110
|
+
return undefined;
|
|
111
|
+
return this.#responseItems.get(callKey(epoch, responseId));
|
|
112
|
+
}
|
|
113
|
+
originRefForItem(epoch, itemId) {
|
|
114
|
+
const item = this.#itemFor(epoch, itemId);
|
|
115
|
+
return item?.origin_ref ?? undefined;
|
|
116
|
+
}
|
|
117
|
+
revisionForItem(epoch, itemId) {
|
|
118
|
+
return this.#itemFor(epoch, itemId)?.revision;
|
|
119
|
+
}
|
|
120
|
+
hasOriginRef(epoch, itemId) {
|
|
121
|
+
return this.originRefForItem(epoch, itemId) !== undefined;
|
|
122
|
+
}
|
|
123
|
+
hasUnboundRevision(epoch, revision) {
|
|
124
|
+
if (epoch !== this.#epoch)
|
|
125
|
+
return false;
|
|
126
|
+
const item = this.#itemsByRevision.get(callKey(epoch, String(revision)));
|
|
127
|
+
return item !== undefined && !item.claimed && !item.transcript_failed;
|
|
128
|
+
}
|
|
129
|
+
get unboundCount() {
|
|
130
|
+
let count = 0;
|
|
131
|
+
for (const item of this.#itemsByRevision.values()) {
|
|
132
|
+
if (!item.claimed && !item.transcript_failed)
|
|
133
|
+
count += 1;
|
|
134
|
+
}
|
|
135
|
+
return count;
|
|
136
|
+
}
|
|
137
|
+
get boundResponses() {
|
|
138
|
+
return [...this.#responseItems.entries()];
|
|
139
|
+
}
|
|
140
|
+
get boundResponseCount() {
|
|
141
|
+
return this.#responseItems.size;
|
|
142
|
+
}
|
|
143
|
+
#itemFor(epoch, itemId) {
|
|
144
|
+
if (epoch !== this.#epoch)
|
|
145
|
+
return undefined;
|
|
146
|
+
const revisionKey = this.#itemRevisionKeys.get(callKey(epoch, itemId));
|
|
147
|
+
return revisionKey === undefined ? undefined : this.#itemsByRevision.get(revisionKey);
|
|
148
|
+
}
|
|
149
|
+
#rememberResponse(responseKey, itemId) {
|
|
150
|
+
this.#responseItems.set(responseKey, itemId);
|
|
151
|
+
while (this.#responseItems.size > this.#limit) {
|
|
152
|
+
const oldest = this.#responseItems.keys().next();
|
|
153
|
+
if (oldest.done)
|
|
154
|
+
break;
|
|
155
|
+
this.#responseItems.delete(oldest.value);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
#pruneItems() {
|
|
159
|
+
while (this.#itemsByRevision.size > this.#limit) {
|
|
160
|
+
const oldest = this.#itemsByRevision.entries().next();
|
|
161
|
+
if (oldest.done)
|
|
162
|
+
break;
|
|
163
|
+
const [revisionKey, item] = oldest.value;
|
|
164
|
+
this.#itemsByRevision.delete(revisionKey);
|
|
165
|
+
this.#itemRevisionKeys.delete(callKey(item.epoch, item.item_id));
|
|
166
|
+
for (const [responseKey, itemId] of [...this.#responseItems]) {
|
|
167
|
+
if (itemId === item.item_id)
|
|
168
|
+
this.#responseItems.delete(responseKey);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
//# sourceMappingURL=user-origin-binding.js.map
|
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
import { translateSystemPrompt } from '../prompt-language.js';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { reportUsage } from '../usage.js';
|
|
4
|
+
import { jsonValueSchema } from '../../core/events.js';
|
|
5
|
+
import { codePointLengthLikePython, stripLikePython } from '../../text/python-text.js';
|
|
6
|
+
import { MAX_REALTIME_TEXT } from '../protocol.js';
|
|
7
|
+
export const MAX_ARK_REQUEST_BYTES = 4 * 1_024 * 1_024;
|
|
8
|
+
export const MAX_ARK_SSE_LINE_BYTES = 256 * 1_024;
|
|
9
|
+
export const MAX_ARK_SSE_EVENT_BYTES = 512 * 1_024;
|
|
10
|
+
export const MAX_ARK_RESPONSE_BYTES = 8 * 1_024 * 1_024;
|
|
11
|
+
export const MAX_ARK_EVENTS = 4_096;
|
|
12
|
+
export const DEFAULT_ARK_IDLE_TIMEOUT_MS = 30_000;
|
|
13
|
+
export const DEFAULT_ARK_CLOSE_TIMEOUT_MS = 1_000;
|
|
14
|
+
export class ArkResponsesFailure extends Error {
|
|
15
|
+
code;
|
|
16
|
+
statusCode;
|
|
17
|
+
constructor(code, statusCode = null) {
|
|
18
|
+
super(`Ark Responses ${code} failure`);
|
|
19
|
+
this.name = 'ArkResponsesFailure';
|
|
20
|
+
this.code = code;
|
|
21
|
+
this.statusCode = statusCode;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function validIdentifier(value) {
|
|
25
|
+
return typeof value === 'string'
|
|
26
|
+
&& stripLikePython(value) !== ''
|
|
27
|
+
&& codePointLengthLikePython(value) <= MAX_REALTIME_TEXT;
|
|
28
|
+
}
|
|
29
|
+
function isJsonObject(value) {
|
|
30
|
+
return value !== null && !Array.isArray(value) && typeof value === 'object'
|
|
31
|
+
&& jsonValueSchema.safeParse(value).success;
|
|
32
|
+
}
|
|
33
|
+
function copyJsonValue(value) {
|
|
34
|
+
if (Array.isArray(value))
|
|
35
|
+
return value.map(copyJsonValue);
|
|
36
|
+
if (value !== null && typeof value === 'object') {
|
|
37
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, copyJsonValue(item)]));
|
|
38
|
+
}
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
function copyJsonObject(value) {
|
|
42
|
+
return copyJsonValue(value);
|
|
43
|
+
}
|
|
44
|
+
function copyJsonObjects(values) {
|
|
45
|
+
if (!Array.isArray(values))
|
|
46
|
+
throw new ArkResponsesFailure('protocol');
|
|
47
|
+
return values.map(value => {
|
|
48
|
+
if (!isJsonObject(value))
|
|
49
|
+
throw new ArkResponsesFailure('protocol');
|
|
50
|
+
return copyJsonObject(value);
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
function resolveResponsesEndpoint(baseUrl) {
|
|
54
|
+
try {
|
|
55
|
+
const endpoint = new URL(baseUrl);
|
|
56
|
+
endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, '')}/responses`;
|
|
57
|
+
return endpoint.toString();
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
throw new ArkResponsesFailure('configuration');
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function abortActive(active, code) {
|
|
64
|
+
active.failureCode ??= code;
|
|
65
|
+
active.controller.abort();
|
|
66
|
+
void active.reader?.cancel().catch(() => undefined);
|
|
67
|
+
}
|
|
68
|
+
async function boundedWait(promise, active, timeoutMs) {
|
|
69
|
+
let timer;
|
|
70
|
+
try {
|
|
71
|
+
const timed = new Promise((_resolve, reject) => {
|
|
72
|
+
timer = setTimeout(() => {
|
|
73
|
+
abortActive(active, 'timeout');
|
|
74
|
+
reject(new ArkResponsesFailure('timeout'));
|
|
75
|
+
}, timeoutMs);
|
|
76
|
+
});
|
|
77
|
+
const value = await Promise.race([promise, timed]);
|
|
78
|
+
if (active.failureCode !== null)
|
|
79
|
+
throw new ArkResponsesFailure(active.failureCode);
|
|
80
|
+
return value;
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
if (timer !== undefined)
|
|
84
|
+
clearTimeout(timer);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function concatBytes(left, right) {
|
|
88
|
+
const combined = new Uint8Array(left.byteLength + right.byteLength);
|
|
89
|
+
combined.set(left);
|
|
90
|
+
combined.set(right, left.byteLength);
|
|
91
|
+
return combined;
|
|
92
|
+
}
|
|
93
|
+
function copyReadableChunk(value) {
|
|
94
|
+
if (!(value instanceof Uint8Array))
|
|
95
|
+
throw new ArkResponsesFailure('protocol');
|
|
96
|
+
const copied = new Uint8Array(value.byteLength);
|
|
97
|
+
copied.set(value);
|
|
98
|
+
return copied;
|
|
99
|
+
}
|
|
100
|
+
function normalizeProviderEvent(value) {
|
|
101
|
+
const type = value.type;
|
|
102
|
+
if (typeof type !== 'string')
|
|
103
|
+
throw new ArkResponsesFailure('protocol');
|
|
104
|
+
if (type === 'response.output_text.delta') {
|
|
105
|
+
const delta = value.delta;
|
|
106
|
+
if (typeof delta !== 'string' || codePointLengthLikePython(delta) > MAX_REALTIME_TEXT) {
|
|
107
|
+
throw new ArkResponsesFailure('protocol');
|
|
108
|
+
}
|
|
109
|
+
return { kind: 'text_delta', text: delta };
|
|
110
|
+
}
|
|
111
|
+
if (type === 'response.output_item.done') {
|
|
112
|
+
const item = value.item;
|
|
113
|
+
if (!isJsonObject(item))
|
|
114
|
+
throw new ArkResponsesFailure('protocol');
|
|
115
|
+
if (item.type !== 'function_call')
|
|
116
|
+
return null;
|
|
117
|
+
if (!validIdentifier(item.id) || !validIdentifier(item.call_id)
|
|
118
|
+
|| !validIdentifier(item.name) || typeof item.arguments !== 'string') {
|
|
119
|
+
throw new ArkResponsesFailure('protocol');
|
|
120
|
+
}
|
|
121
|
+
let argumentsValue;
|
|
122
|
+
try {
|
|
123
|
+
argumentsValue = JSON.parse(item.arguments);
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
throw new ArkResponsesFailure('protocol');
|
|
127
|
+
}
|
|
128
|
+
if (!isJsonObject(argumentsValue))
|
|
129
|
+
throw new ArkResponsesFailure('protocol');
|
|
130
|
+
return {
|
|
131
|
+
kind: 'tool_call',
|
|
132
|
+
item_id: item.id,
|
|
133
|
+
call_id: item.call_id,
|
|
134
|
+
name: item.name,
|
|
135
|
+
arguments: copyJsonObject(argumentsValue),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
if (type === 'response.created' || type === 'response.completed'
|
|
139
|
+
|| type === 'response.failed' || type === 'response.incomplete') {
|
|
140
|
+
const response = value.response;
|
|
141
|
+
if (!isJsonObject(response) || !validIdentifier(response.id)) {
|
|
142
|
+
throw new ArkResponsesFailure('protocol');
|
|
143
|
+
}
|
|
144
|
+
if (type === 'response.created') {
|
|
145
|
+
return { kind: 'response_started', response_id: response.id };
|
|
146
|
+
}
|
|
147
|
+
if (type === 'response.completed') {
|
|
148
|
+
return { kind: 'response_completed', response_id: response.id };
|
|
149
|
+
}
|
|
150
|
+
return {
|
|
151
|
+
kind: 'response_failed',
|
|
152
|
+
response_id: response.id,
|
|
153
|
+
code: type === 'response.failed' ? 'failed' : 'incomplete',
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
class FetchArkResponsesGateway {
|
|
159
|
+
#onUsage;
|
|
160
|
+
#endpoint;
|
|
161
|
+
#apiKey;
|
|
162
|
+
#model;
|
|
163
|
+
#instructions;
|
|
164
|
+
#fetch;
|
|
165
|
+
#idleTimeoutMs;
|
|
166
|
+
#closeTimeoutMs;
|
|
167
|
+
#active = new Set();
|
|
168
|
+
#closed = false;
|
|
169
|
+
#closePromise = null;
|
|
170
|
+
constructor(options) {
|
|
171
|
+
this.#onUsage = options.onUsage;
|
|
172
|
+
this.#endpoint = resolveResponsesEndpoint(options.baseUrl);
|
|
173
|
+
this.#apiKey = options.apiKey;
|
|
174
|
+
this.#model = options.model;
|
|
175
|
+
this.#instructions = options.instructions;
|
|
176
|
+
this.#fetch = options.fetchImpl ?? globalThis.fetch;
|
|
177
|
+
this.#idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_ARK_IDLE_TIMEOUT_MS;
|
|
178
|
+
this.#closeTimeoutMs = options.closeTimeoutMs ?? DEFAULT_ARK_CLOSE_TIMEOUT_MS;
|
|
179
|
+
if (!Number.isFinite(this.#idleTimeoutMs) || this.#idleTimeoutMs <= 0
|
|
180
|
+
|| !Number.isFinite(this.#closeTimeoutMs) || this.#closeTimeoutMs <= 0) {
|
|
181
|
+
throw new ArkResponsesFailure('configuration');
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
async *stream(input) {
|
|
185
|
+
if (this.#closed)
|
|
186
|
+
throw new ArkResponsesFailure('closed');
|
|
187
|
+
if (input.signal?.aborted === true)
|
|
188
|
+
throw new ArkResponsesFailure('aborted');
|
|
189
|
+
const inputItems = copyJsonObjects(input.inputItems);
|
|
190
|
+
const tools = copyJsonObjects(input.tools);
|
|
191
|
+
if (input.previousResponseId !== null && !validIdentifier(input.previousResponseId)) {
|
|
192
|
+
throw new ArkResponsesFailure('protocol');
|
|
193
|
+
}
|
|
194
|
+
const body = JSON.stringify({
|
|
195
|
+
model: this.#model,
|
|
196
|
+
instructions: [translateSystemPrompt(this.#instructions, input.language), input.workspaceContext, input.responseAdaptation]
|
|
197
|
+
.filter((item) => item !== null && item !== undefined)
|
|
198
|
+
.join('\n\n'),
|
|
199
|
+
input: inputItems,
|
|
200
|
+
tools,
|
|
201
|
+
parallel_tool_calls: false,
|
|
202
|
+
store: true,
|
|
203
|
+
stream: true,
|
|
204
|
+
thinking: { type: 'disabled' },
|
|
205
|
+
...(input.previousResponseId === null
|
|
206
|
+
? {}
|
|
207
|
+
: { previous_response_id: input.previousResponseId }),
|
|
208
|
+
});
|
|
209
|
+
if (new TextEncoder().encode(body).byteLength > MAX_ARK_REQUEST_BYTES) {
|
|
210
|
+
throw new ArkResponsesFailure('overflow');
|
|
211
|
+
}
|
|
212
|
+
let resolveDone = () => undefined;
|
|
213
|
+
const active = {
|
|
214
|
+
controller: new AbortController(),
|
|
215
|
+
reader: null,
|
|
216
|
+
failureCode: null,
|
|
217
|
+
done: new Promise(resolve => { resolveDone = resolve; }),
|
|
218
|
+
resolveDone: () => resolveDone(),
|
|
219
|
+
};
|
|
220
|
+
const onCallerAbort = () => abortActive(active, 'aborted');
|
|
221
|
+
input.signal?.addEventListener('abort', onCallerAbort, { once: true });
|
|
222
|
+
this.#active.add(active);
|
|
223
|
+
const usageId = randomUUID();
|
|
224
|
+
let usageReported = false;
|
|
225
|
+
try {
|
|
226
|
+
let response;
|
|
227
|
+
try {
|
|
228
|
+
response = await boundedWait(this.#fetch(this.#endpoint, {
|
|
229
|
+
method: 'POST',
|
|
230
|
+
headers: {
|
|
231
|
+
authorization: `Bearer ${this.#apiKey}`,
|
|
232
|
+
'content-type': 'application/json',
|
|
233
|
+
accept: 'text/event-stream',
|
|
234
|
+
},
|
|
235
|
+
body,
|
|
236
|
+
signal: active.controller.signal,
|
|
237
|
+
}), active, this.#idleTimeoutMs);
|
|
238
|
+
}
|
|
239
|
+
catch (error) {
|
|
240
|
+
if (error instanceof ArkResponsesFailure)
|
|
241
|
+
throw error;
|
|
242
|
+
if (active.failureCode !== null)
|
|
243
|
+
throw new ArkResponsesFailure(active.failureCode);
|
|
244
|
+
throw new ArkResponsesFailure('network');
|
|
245
|
+
}
|
|
246
|
+
if (response.status < 200 || response.status >= 300) {
|
|
247
|
+
await response.body?.cancel().catch(() => undefined);
|
|
248
|
+
throw new ArkResponsesFailure('http', response.status);
|
|
249
|
+
}
|
|
250
|
+
if (response.body === null
|
|
251
|
+
|| !response.headers.get('content-type')?.toLowerCase().startsWith('text/event-stream')) {
|
|
252
|
+
await response.body?.cancel().catch(() => undefined);
|
|
253
|
+
throw new ArkResponsesFailure('protocol');
|
|
254
|
+
}
|
|
255
|
+
const reader = response.body.getReader();
|
|
256
|
+
active.reader = reader;
|
|
257
|
+
let buffered = new Uint8Array(0);
|
|
258
|
+
let aggregateBytes = 0;
|
|
259
|
+
let dataLines = [];
|
|
260
|
+
let dataBytes = 0;
|
|
261
|
+
let dispatchedEvents = 0;
|
|
262
|
+
let terminal = false;
|
|
263
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
264
|
+
const handleLine = (bytes) => {
|
|
265
|
+
let lineBytes = bytes;
|
|
266
|
+
if (lineBytes.byteLength > 0 && lineBytes[lineBytes.byteLength - 1] === 13) {
|
|
267
|
+
lineBytes = lineBytes.subarray(0, lineBytes.byteLength - 1);
|
|
268
|
+
}
|
|
269
|
+
if (lineBytes.byteLength > MAX_ARK_SSE_LINE_BYTES) {
|
|
270
|
+
throw new ArkResponsesFailure('overflow');
|
|
271
|
+
}
|
|
272
|
+
let line;
|
|
273
|
+
try {
|
|
274
|
+
line = decoder.decode(lineBytes);
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
throw new ArkResponsesFailure('protocol');
|
|
278
|
+
}
|
|
279
|
+
if (line !== '') {
|
|
280
|
+
if (line.startsWith(':'))
|
|
281
|
+
return null;
|
|
282
|
+
const separator = line.indexOf(':');
|
|
283
|
+
const field = separator < 0 ? line : line.slice(0, separator);
|
|
284
|
+
let fieldValue = separator < 0 ? '' : line.slice(separator + 1);
|
|
285
|
+
if (fieldValue.startsWith(' '))
|
|
286
|
+
fieldValue = fieldValue.slice(1);
|
|
287
|
+
if (field === 'data') {
|
|
288
|
+
const encoded = new TextEncoder().encode(fieldValue);
|
|
289
|
+
dataBytes += encoded.byteLength + (dataLines.length === 0 ? 0 : 1);
|
|
290
|
+
if (dataBytes > MAX_ARK_SSE_EVENT_BYTES) {
|
|
291
|
+
throw new ArkResponsesFailure('overflow');
|
|
292
|
+
}
|
|
293
|
+
dataLines.push(fieldValue);
|
|
294
|
+
}
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
if (dataLines.length === 0)
|
|
298
|
+
return null;
|
|
299
|
+
dispatchedEvents += 1;
|
|
300
|
+
if (dispatchedEvents > MAX_ARK_EVENTS)
|
|
301
|
+
throw new ArkResponsesFailure('overflow');
|
|
302
|
+
const data = dataLines.join('\n');
|
|
303
|
+
dataLines = [];
|
|
304
|
+
dataBytes = 0;
|
|
305
|
+
let parsed;
|
|
306
|
+
try {
|
|
307
|
+
parsed = JSON.parse(data);
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
throw new ArkResponsesFailure('protocol');
|
|
311
|
+
}
|
|
312
|
+
if (!isJsonObject(parsed))
|
|
313
|
+
throw new ArkResponsesFailure('protocol');
|
|
314
|
+
const event = normalizeProviderEvent(parsed);
|
|
315
|
+
if (event?.kind === 'response_completed' || event?.kind === 'response_failed') {
|
|
316
|
+
const response = isJsonObject(parsed.response) ? parsed.response : {};
|
|
317
|
+
const usage = event.kind === 'response_completed' && isJsonObject(response.usage) ? response.usage : undefined;
|
|
318
|
+
const details = isJsonObject(usage?.input_tokens_details) ? usage.input_tokens_details : {};
|
|
319
|
+
const outputDetails = isJsonObject(usage?.output_tokens_details) ? usage.output_tokens_details : {};
|
|
320
|
+
reportUsage(this.#onUsage, {
|
|
321
|
+
id: usageId, service: 'llm', provider: 'ark', model: this.#model,
|
|
322
|
+
status: usage === undefined ? 'missing' : 'complete',
|
|
323
|
+
...(usage === undefined ? {} : { inputTokens: usage.input_tokens, outputTokens: usage.output_tokens,
|
|
324
|
+
cachedTokens: details.cached_tokens, reasoningTokens: outputDetails.reasoning_tokens }),
|
|
325
|
+
});
|
|
326
|
+
usageReported = true;
|
|
327
|
+
}
|
|
328
|
+
return event;
|
|
329
|
+
};
|
|
330
|
+
while (!terminal) {
|
|
331
|
+
const result = await (async () => {
|
|
332
|
+
try {
|
|
333
|
+
return await boundedWait(reader.read(), active, this.#idleTimeoutMs);
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
if (error instanceof ArkResponsesFailure)
|
|
337
|
+
throw error;
|
|
338
|
+
if (active.failureCode !== null)
|
|
339
|
+
throw new ArkResponsesFailure(active.failureCode);
|
|
340
|
+
throw new ArkResponsesFailure('network');
|
|
341
|
+
}
|
|
342
|
+
})();
|
|
343
|
+
if (result.done) {
|
|
344
|
+
if (buffered.byteLength > 0) {
|
|
345
|
+
const event = handleLine(buffered);
|
|
346
|
+
if (event !== null) {
|
|
347
|
+
yield event;
|
|
348
|
+
terminal = event.kind === 'response_completed' || event.kind === 'response_failed';
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
const finalEvent = handleLine(new Uint8Array(0));
|
|
352
|
+
if (finalEvent !== null) {
|
|
353
|
+
yield finalEvent;
|
|
354
|
+
terminal = finalEvent.kind === 'response_completed' || finalEvent.kind === 'response_failed';
|
|
355
|
+
}
|
|
356
|
+
if (!terminal)
|
|
357
|
+
throw new ArkResponsesFailure('protocol');
|
|
358
|
+
break;
|
|
359
|
+
}
|
|
360
|
+
const chunk = copyReadableChunk(result.value);
|
|
361
|
+
aggregateBytes += chunk.byteLength;
|
|
362
|
+
if (aggregateBytes > MAX_ARK_RESPONSE_BYTES)
|
|
363
|
+
throw new ArkResponsesFailure('overflow');
|
|
364
|
+
buffered = concatBytes(buffered, chunk);
|
|
365
|
+
let newline = buffered.indexOf(10);
|
|
366
|
+
while (newline >= 0) {
|
|
367
|
+
const event = handleLine(buffered.subarray(0, newline));
|
|
368
|
+
buffered = buffered.slice(newline + 1);
|
|
369
|
+
if (event !== null) {
|
|
370
|
+
yield event;
|
|
371
|
+
terminal = event.kind === 'response_completed' || event.kind === 'response_failed';
|
|
372
|
+
if (terminal)
|
|
373
|
+
break;
|
|
374
|
+
}
|
|
375
|
+
newline = buffered.indexOf(10);
|
|
376
|
+
}
|
|
377
|
+
if (buffered.byteLength > MAX_ARK_SSE_LINE_BYTES) {
|
|
378
|
+
throw new ArkResponsesFailure('overflow');
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
catch (error) {
|
|
383
|
+
if (error instanceof ArkResponsesFailure)
|
|
384
|
+
throw error;
|
|
385
|
+
if (active.failureCode !== null)
|
|
386
|
+
throw new ArkResponsesFailure(active.failureCode);
|
|
387
|
+
throw new ArkResponsesFailure('protocol');
|
|
388
|
+
}
|
|
389
|
+
finally {
|
|
390
|
+
if (!usageReported)
|
|
391
|
+
reportUsage(this.#onUsage, {
|
|
392
|
+
id: usageId, service: 'llm', provider: 'ark', model: this.#model, status: 'missing',
|
|
393
|
+
});
|
|
394
|
+
input.signal?.removeEventListener('abort', onCallerAbort);
|
|
395
|
+
try {
|
|
396
|
+
await active.reader?.cancel();
|
|
397
|
+
}
|
|
398
|
+
catch {
|
|
399
|
+
// Reader cleanup is best effort; the stable operation result was already selected above.
|
|
400
|
+
}
|
|
401
|
+
this.#active.delete(active);
|
|
402
|
+
active.resolveDone();
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
close() {
|
|
406
|
+
if (this.#closePromise !== null)
|
|
407
|
+
return this.#closePromise;
|
|
408
|
+
this.#closed = true;
|
|
409
|
+
const active = [...this.#active];
|
|
410
|
+
for (const item of active)
|
|
411
|
+
abortActive(item, 'closed');
|
|
412
|
+
this.#closePromise = (async () => {
|
|
413
|
+
let timer;
|
|
414
|
+
await Promise.race([
|
|
415
|
+
Promise.allSettled(active.map(item => item.done)),
|
|
416
|
+
new Promise(resolve => { timer = setTimeout(resolve, this.#closeTimeoutMs); }),
|
|
417
|
+
]);
|
|
418
|
+
if (timer !== undefined)
|
|
419
|
+
clearTimeout(timer);
|
|
420
|
+
this.#active.clear();
|
|
421
|
+
})();
|
|
422
|
+
return this.#closePromise;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
export function createFetchArkResponsesGateway(options) {
|
|
426
|
+
return new FetchArkResponsesGateway(options);
|
|
427
|
+
}
|
|
428
|
+
//# sourceMappingURL=ark.js.map
|