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.
Files changed (345) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +30 -2
  3. package/bin/novapersonal-server.mjs +4 -0
  4. package/package.json +61 -4
  5. package/resources/endpointing/volcengine-v1/LICENSE.silero-vad.txt +21 -0
  6. package/resources/endpointing/volcengine-v1/MANIFEST.json +31 -0
  7. package/resources/endpointing/volcengine-v1/silence-16k-s16le.pcm +0 -0
  8. package/resources/endpointing/volcengine-v1/speech-16k-s16le.pcm +0 -0
  9. package/resources/native/codex-sandbox-probe +0 -0
  10. package/resources/native/project-native/nova_project_native.node +0 -0
  11. package/resources/native-resources-v1.json +1 -0
  12. package/runtime/dist/eval/demos.js +156 -0
  13. package/runtime/dist/eval/fixture-host.js +385 -0
  14. package/runtime/dist/eval/fixtures.js +319 -0
  15. package/runtime/dist/eval/realtime/session-fixtures.js +474 -0
  16. package/runtime/dist/eval/scorecard.js +285 -0
  17. package/runtime/dist/eval/sim.js +43 -0
  18. package/runtime/dist/src/cascaded-text-provider.js +31 -0
  19. package/runtime/dist/src/cli.js +96 -0
  20. package/runtime/dist/src/composition/assembly.js +352 -0
  21. package/runtime/dist/src/composition/cascaded-realtime-assembly.js +455 -0
  22. package/runtime/dist/src/composition/production-composition.js +389 -0
  23. package/runtime/dist/src/composition/realtime-assembly.js +1330 -0
  24. package/runtime/dist/src/config/capability-registry.js +315 -0
  25. package/runtime/dist/src/config/cascaded-realtime-config.js +146 -0
  26. package/runtime/dist/src/config/coding-backends.js +8 -0
  27. package/runtime/dist/src/config/coding-profiles.js +98 -0
  28. package/runtime/dist/src/config/config.js +857 -0
  29. package/runtime/dist/src/config/diagnostics.js +139 -0
  30. package/runtime/dist/src/config/environment-contract.js +202 -0
  31. package/runtime/dist/src/config/self-hosted.js +23 -0
  32. package/runtime/dist/src/connectors/composio/client.js +195 -0
  33. package/runtime/dist/src/connectors/composio/google.js +208 -0
  34. package/runtime/dist/src/connectors/composio/index.js +334 -0
  35. package/runtime/dist/src/connectors/feishu/cli.js +220 -0
  36. package/runtime/dist/src/connectors/feishu/index.js +980 -0
  37. package/runtime/dist/src/connectors/macos/calendar.js +35 -0
  38. package/runtime/dist/src/connectors/macos/mail.js +32 -0
  39. package/runtime/dist/src/connectors/macos/reader.js +62 -0
  40. package/runtime/dist/src/conversation-voice-provider.js +41 -0
  41. package/runtime/dist/src/core/approval-port.js +9 -0
  42. package/runtime/dist/src/core/approval.js +1328 -0
  43. package/runtime/dist/src/core/calls.js +35 -0
  44. package/runtime/dist/src/core/camera-session.js +32 -0
  45. package/runtime/dist/src/core/causal-runtime.js +650 -0
  46. package/runtime/dist/src/core/clock.js +139 -0
  47. package/runtime/dist/src/core/context-view.js +156 -0
  48. package/runtime/dist/src/core/effects.js +62 -0
  49. package/runtime/dist/src/core/events.js +217 -0
  50. package/runtime/dist/src/core/executor-diagnostic.js +9 -0
  51. package/runtime/dist/src/core/ids.js +32 -0
  52. package/runtime/dist/src/core/media-store.js +104 -0
  53. package/runtime/dist/src/core/memory.js +296 -0
  54. package/runtime/dist/src/core/pending-decision.js +64 -0
  55. package/runtime/dist/src/core/ports.js +125 -0
  56. package/runtime/dist/src/core/runtime.js +1459 -0
  57. package/runtime/dist/src/core/schedule-tools.js +15 -0
  58. package/runtime/dist/src/core/sims.js +186 -0
  59. package/runtime/dist/src/core/slots.js +97 -0
  60. package/runtime/dist/src/core/source-processing-instructions.js +3 -0
  61. package/runtime/dist/src/core/source-processing-tools.js +12 -0
  62. package/runtime/dist/src/core/suggestions.js +143 -0
  63. package/runtime/dist/src/core/task-tools.js +22 -0
  64. package/runtime/dist/src/core/tool-schema.js +212 -0
  65. package/runtime/dist/src/core/trace.js +34 -0
  66. package/runtime/dist/src/core/work-tools.js +94 -0
  67. package/runtime/dist/src/desktop/desktop-camera-source.js +31 -0
  68. package/runtime/dist/src/desktop/desktop-camera.js +281 -0
  69. package/runtime/dist/src/desktop/desktop-control.js +140 -0
  70. package/runtime/dist/src/desktop/desktop-progress.js +162 -0
  71. package/runtime/dist/src/desktop/desktop-session.js +2106 -0
  72. package/runtime/dist/src/desktop/desktop-tasks.js +80 -0
  73. package/runtime/dist/src/desktop/desktop-wire.js +605 -0
  74. package/runtime/dist/src/desktop/phone-desktop-entry.js +17 -0
  75. package/runtime/dist/src/desktop/startup-error.js +18 -0
  76. package/runtime/dist/src/desktop/workbench-acceptance.js +262 -0
  77. package/runtime/dist/src/desktop-entry.js +106 -0
  78. package/runtime/dist/src/desktop.js +1092 -0
  79. package/runtime/dist/src/executors/acp/backends.js +105 -0
  80. package/runtime/dist/src/executors/acp/mcp.js +81 -0
  81. package/runtime/dist/src/executors/acp/preflight.js +14 -0
  82. package/runtime/dist/src/executors/acp/process-owner.js +112 -0
  83. package/runtime/dist/src/executors/acp/transport.js +760 -0
  84. package/runtime/dist/src/executors/acp/windows-launch.js +68 -0
  85. package/runtime/dist/src/executors/agent-controller.js +244 -0
  86. package/runtime/dist/src/executors/autoglm.js +376 -0
  87. package/runtime/dist/src/executors/browser-device.js +102 -0
  88. package/runtime/dist/src/executors/browser.js +61 -0
  89. package/runtime/dist/src/executors/camera.js +101 -0
  90. package/runtime/dist/src/executors/chromium-frame-source.js +173 -0
  91. package/runtime/dist/src/executors/codex/adapter-live.js +292 -0
  92. package/runtime/dist/src/executors/codex/adapter-project.js +1306 -0
  93. package/runtime/dist/src/executors/codex/app-server-schema.js +712 -0
  94. package/runtime/dist/src/executors/codex/app-server-transport.js +1798 -0
  95. package/runtime/dist/src/executors/codex/approval-protocol.js +439 -0
  96. package/runtime/dist/src/executors/codex/common.js +655 -0
  97. package/runtime/dist/src/executors/codex/contract.js +581 -0
  98. package/runtime/dist/src/executors/codex/controller.js +141 -0
  99. package/runtime/dist/src/executors/codex/credential-snapshot.js +195 -0
  100. package/runtime/dist/src/executors/codex/factory.js +463 -0
  101. package/runtime/dist/src/executors/codex/host-config.js +238 -0
  102. package/runtime/dist/src/executors/codex/host.js +17 -0
  103. package/runtime/dist/src/executors/codex/index.js +19 -0
  104. package/runtime/dist/src/executors/codex/launch-profile.js +37 -0
  105. package/runtime/dist/src/executors/codex/local-sessions.js +119 -0
  106. package/runtime/dist/src/executors/codex/managed-mcp.js +196 -0
  107. package/runtime/dist/src/executors/codex/process-owner.js +398 -0
  108. package/runtime/dist/src/executors/codex/production-host.js +887 -0
  109. package/runtime/dist/src/executors/codex/progress-instructions.js +10 -0
  110. package/runtime/dist/src/executors/codex/protocol.js +581 -0
  111. package/runtime/dist/src/executors/codex/safe-json.js +87 -0
  112. package/runtime/dist/src/executors/codex/session-title.js +61 -0
  113. package/runtime/dist/src/executors/codex/shared-home.js +29 -0
  114. package/runtime/dist/src/executors/codex/spawn-env.js +162 -0
  115. package/runtime/dist/src/executors/codex/turn-projection.js +435 -0
  116. package/runtime/dist/src/executors/codex/version.js +38 -0
  117. package/runtime/dist/src/executors/codex/windows-guardian.js +716 -0
  118. package/runtime/dist/src/executors/coding/intake-model.js +103 -0
  119. package/runtime/dist/src/executors/coding/intake.js +824 -0
  120. package/runtime/dist/src/executors/coding/json-completion.js +14 -0
  121. package/runtime/dist/src/executors/coding/target-resolution.js +61 -0
  122. package/runtime/dist/src/executors/coding/work-order.js +50 -0
  123. package/runtime/dist/src/executors/coding-executor.js +23 -0
  124. package/runtime/dist/src/executors/computer-backend.js +188 -0
  125. package/runtime/dist/src/executors/computer-device.js +187 -0
  126. package/runtime/dist/src/executors/computer-worker.js +125 -0
  127. package/runtime/dist/src/executors/computer.js +100 -0
  128. package/runtime/dist/src/executors/device-lock.js +127 -0
  129. package/runtime/dist/src/executors/frame-source.js +29 -0
  130. package/runtime/dist/src/executors/gui-evidence.js +30 -0
  131. package/runtime/dist/src/executors/gui-execution.js +237 -0
  132. package/runtime/dist/src/executors/gui-runner.js +88 -0
  133. package/runtime/dist/src/executors/host-executor-capability.js +12 -0
  134. package/runtime/dist/src/executors/index.js +13 -0
  135. package/runtime/dist/src/executors/mcp-client.js +198 -0
  136. package/runtime/dist/src/executors/mcp.js +210 -0
  137. package/runtime/dist/src/executors/mobile-android.js +180 -0
  138. package/runtime/dist/src/executors/mobile-ios.js +303 -0
  139. package/runtime/dist/src/executors/mobile.js +78 -0
  140. package/runtime/dist/src/executors/search-mcp.js +146 -0
  141. package/runtime/dist/src/executors/search.js +524 -0
  142. package/runtime/dist/src/executors/task-resources.js +38 -0
  143. package/runtime/dist/src/executors/vision/assess.js +296 -0
  144. package/runtime/dist/src/executors/vision/controller-core.js +373 -0
  145. package/runtime/dist/src/executors/vision/controller.js +164 -0
  146. package/runtime/dist/src/executors/vision/lifecycle.js +69 -0
  147. package/runtime/dist/src/executors/vision.js +5 -0
  148. package/runtime/dist/src/executors/watcher.js +718 -0
  149. package/runtime/dist/src/http/bounded-response.js +37 -0
  150. package/runtime/dist/src/index.js +56 -0
  151. package/runtime/dist/src/knowledge/assembly.js +60 -0
  152. package/runtime/dist/src/knowledge/documents.js +520 -0
  153. package/runtime/dist/src/knowledge/embeddings.js +201 -0
  154. package/runtime/dist/src/knowledge/mcp.js +218 -0
  155. package/runtime/dist/src/knowledge/parse-worker.js +122 -0
  156. package/runtime/dist/src/knowledge/references.js +51 -0
  157. package/runtime/dist/src/knowledge/service.js +526 -0
  158. package/runtime/dist/src/knowledge/store-client.js +185 -0
  159. package/runtime/dist/src/knowledge/store-worker.js +843 -0
  160. package/runtime/dist/src/knowledge/types.js +2 -0
  161. package/runtime/dist/src/mcp/http-server.js +177 -0
  162. package/runtime/dist/src/mem0/resource.js +35 -0
  163. package/runtime/dist/src/mem0/store-worker.js +330 -0
  164. package/runtime/dist/src/memory/blackboard-session.js +205 -0
  165. package/runtime/dist/src/memory/blackboard-store.js +194 -0
  166. package/runtime/dist/src/memory/blackboard-worker.js +369 -0
  167. package/runtime/dist/src/memory/entry.js +39 -0
  168. package/runtime/dist/src/memory/factory.js +20 -0
  169. package/runtime/dist/src/memory/personal-memory-inspection.js +18 -0
  170. package/runtime/dist/src/memory/personal-memory.js +10 -0
  171. package/runtime/dist/src/memory/prerecall.js +20 -0
  172. package/runtime/dist/src/memory/provenance.js +17 -0
  173. package/runtime/dist/src/memory/remote-personal-memory.js +194 -0
  174. package/runtime/dist/src/memory/retrieval.js +235 -0
  175. package/runtime/dist/src/memory/sensitivity.js +261 -0
  176. package/runtime/dist/src/memory-ledger/models.js +98 -0
  177. package/runtime/dist/src/memory-ledger/store-client.js +210 -0
  178. package/runtime/dist/src/memory-ledger/store-worker.js +130 -0
  179. package/runtime/dist/src/memory-ledger/store.js +597 -0
  180. package/runtime/dist/src/memory-substrate/candidates.js +16 -0
  181. package/runtime/dist/src/memory-substrate/consolidation.js +124 -0
  182. package/runtime/dist/src/memory-substrate/file-authority.js +111 -0
  183. package/runtime/dist/src/memory-substrate/life-operations.js +280 -0
  184. package/runtime/dist/src/memory-substrate/markdown-repository.js +610 -0
  185. package/runtime/dist/src/memory-substrate/migration.js +87 -0
  186. package/runtime/dist/src/memory-substrate/profile-source-input.js +9 -0
  187. package/runtime/dist/src/memory-substrate/purge.js +398 -0
  188. package/runtime/dist/src/memory-substrate/resolution.js +32 -0
  189. package/runtime/dist/src/memory-substrate/resource.js +867 -0
  190. package/runtime/dist/src/memory-substrate/retrieval.js +85 -0
  191. package/runtime/dist/src/memory-substrate/source-operations.js +306 -0
  192. package/runtime/dist/src/memory-substrate/source-processing.js +326 -0
  193. package/runtime/dist/src/memory-substrate/source-state.js +93 -0
  194. package/runtime/dist/src/memory-substrate/store.js +534 -0
  195. package/runtime/dist/src/memory-substrate/workspace-projections.js +106 -0
  196. package/runtime/dist/src/memory-substrate/workspace.js +21 -0
  197. package/runtime/dist/src/model/jev-client.js +25 -0
  198. package/runtime/dist/src/model/model-adapters.js +64 -0
  199. package/runtime/dist/src/model/model-gateway.js +399 -0
  200. package/runtime/dist/src/model/model-lane.js +34 -0
  201. package/runtime/dist/src/model/model-purpose.js +5 -0
  202. package/runtime/dist/src/model/personal-writer.js +361 -0
  203. package/runtime/dist/src/model/proactivity.js +72 -0
  204. package/runtime/dist/src/model/prompting.js +279 -0
  205. package/runtime/dist/src/model/task-verifier.js +217 -0
  206. package/runtime/dist/src/model/vision-capability.js +10 -0
  207. package/runtime/dist/src/news/feeds.js +114 -0
  208. package/runtime/dist/src/news/jev-ranking.js +25 -0
  209. package/runtime/dist/src/news/ranking.js +26 -0
  210. package/runtime/dist/src/news/service.js +262 -0
  211. package/runtime/dist/src/notifications/adapters/feishu.js +10 -0
  212. package/runtime/dist/src/notifications/adapters/nova.js +15 -0
  213. package/runtime/dist/src/notifications/content.js +15 -0
  214. package/runtime/dist/src/notifications/contracts.js +9 -0
  215. package/runtime/dist/src/notifications/feed.js +8 -0
  216. package/runtime/dist/src/notifications/service.js +412 -0
  217. package/runtime/dist/src/notifications/store.js +4 -0
  218. package/runtime/dist/src/personal-agent/app-context.js +113 -0
  219. package/runtime/dist/src/personal-agent/approval-scope.js +8 -0
  220. package/runtime/dist/src/personal-agent/coding-targets.js +82 -0
  221. package/runtime/dist/src/personal-agent/context-candidates.js +94 -0
  222. package/runtime/dist/src/personal-agent/contracts.js +32 -0
  223. package/runtime/dist/src/personal-agent/conversation-runtime.js +536 -0
  224. package/runtime/dist/src/personal-agent/conversations.js +187 -0
  225. package/runtime/dist/src/personal-agent/daily-brief.js +53 -0
  226. package/runtime/dist/src/personal-agent/host.js +2403 -0
  227. package/runtime/dist/src/personal-agent/intake-task.js +37 -0
  228. package/runtime/dist/src/personal-agent/life.js +260 -0
  229. package/runtime/dist/src/personal-agent/memory-overview.js +19 -0
  230. package/runtime/dist/src/personal-agent/profile-sources.js +34 -0
  231. package/runtime/dist/src/personal-agent/profile-warmup.js +244 -0
  232. package/runtime/dist/src/personal-agent/project-digests.js +242 -0
  233. package/runtime/dist/src/personal-agent/sampling.js +20 -0
  234. package/runtime/dist/src/personal-agent/schedule-agent.js +60 -0
  235. package/runtime/dist/src/personal-agent/schedule-api.js +61 -0
  236. package/runtime/dist/src/personal-agent/schedule-presets.js +13 -0
  237. package/runtime/dist/src/personal-agent/schedule-reference.js +3 -0
  238. package/runtime/dist/src/personal-agent/scheduled-response-scope.js +38 -0
  239. package/runtime/dist/src/personal-agent/scheduled-run-authority.js +44 -0
  240. package/runtime/dist/src/personal-agent/scheduled-tasks.js +280 -0
  241. package/runtime/dist/src/personal-agent/scheduled-time.js +99 -0
  242. package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +109 -0
  243. package/runtime/dist/src/personal-agent/source-priority.js +142 -0
  244. package/runtime/dist/src/personal-agent/source-processing-agent.js +158 -0
  245. package/runtime/dist/src/personal-agent/source-walk.js +25 -0
  246. package/runtime/dist/src/personal-agent/sources.js +1484 -0
  247. package/runtime/dist/src/personal-agent/store-lock-worker.js +17 -0
  248. package/runtime/dist/src/personal-agent/store.js +146 -0
  249. package/runtime/dist/src/personal-agent/task-loop.js +163 -0
  250. package/runtime/dist/src/personal-agent/tasks.js +920 -0
  251. package/runtime/dist/src/personal-agent/turn-deadline.js +55 -0
  252. package/runtime/dist/src/personal-agent/understanding.js +160 -0
  253. package/runtime/dist/src/personal-agent/workbench-context.js +239 -0
  254. package/runtime/dist/src/projects/confirmed-project-capability.js +60 -0
  255. package/runtime/dist/src/projects/host-paths.js +133 -0
  256. package/runtime/dist/src/projects/managed-workspace-maintenance.js +351 -0
  257. package/runtime/dist/src/projects/project-confirmation.js +486 -0
  258. package/runtime/dist/src/projects/project-native-resource.js +284 -0
  259. package/runtime/dist/src/projects/project-node-files.js +169 -0
  260. package/runtime/dist/src/projects/project-root-file.js +16 -0
  261. package/runtime/dist/src/projects/project-state.js +504 -0
  262. package/runtime/dist/src/projects/project-store-files.js +1271 -0
  263. package/runtime/dist/src/projects/project-store.js +1345 -0
  264. package/runtime/dist/src/realtime/aoq.js +141 -0
  265. package/runtime/dist/src/realtime/bridge.js +652 -0
  266. package/runtime/dist/src/realtime/cascaded/adapter.js +1669 -0
  267. package/runtime/dist/src/realtime/cascaded/ark-llm.js +219 -0
  268. package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +478 -0
  269. package/runtime/dist/src/realtime/cascaded/gemini-speech.js +232 -0
  270. package/runtime/dist/src/realtime/cascaded/llm.js +37 -0
  271. package/runtime/dist/src/realtime/cascaded/ports.js +2 -0
  272. package/runtime/dist/src/realtime/cascaded/provider.js +216 -0
  273. package/runtime/dist/src/realtime/cascaded/qwen-llm.js +7 -0
  274. package/runtime/dist/src/realtime/cascaded/self-hosted-asr.js +110 -0
  275. package/runtime/dist/src/realtime/cascaded/self-hosted-tts.js +137 -0
  276. package/runtime/dist/src/realtime/cascaded/transcribe.js +42 -0
  277. package/runtime/dist/src/realtime/coding-progress-narration.js +28 -0
  278. package/runtime/dist/src/realtime/confirmation-turn-isolation.js +586 -0
  279. package/runtime/dist/src/realtime/dictation.js +28 -0
  280. package/runtime/dist/src/realtime/evidence.js +276 -0
  281. package/runtime/dist/src/realtime/floor.js +43 -0
  282. package/runtime/dist/src/realtime/frontend-instructions.js +195 -0
  283. package/runtime/dist/src/realtime/gemini.js +517 -0
  284. package/runtime/dist/src/realtime/history.js +122 -0
  285. package/runtime/dist/src/realtime/host-delivery.js +1711 -0
  286. package/runtime/dist/src/realtime/integrated-wire-profile.js +128 -0
  287. package/runtime/dist/src/realtime/memory-board.js +105 -0
  288. package/runtime/dist/src/realtime/openai-wire-profile.js +46 -0
  289. package/runtime/dist/src/realtime/playback.js +242 -0
  290. package/runtime/dist/src/realtime/project-confirmation-flow.js +1428 -0
  291. package/runtime/dist/src/realtime/prompt-language.js +17 -0
  292. package/runtime/dist/src/realtime/protocol.js +428 -0
  293. package/runtime/dist/src/realtime/provider-projection.js +526 -0
  294. package/runtime/dist/src/realtime/provider-session.js +491 -0
  295. package/runtime/dist/src/realtime/qwen-transport.js +144 -0
  296. package/runtime/dist/src/realtime/qwen.js +1377 -0
  297. package/runtime/dist/src/realtime/recall.js +341 -0
  298. package/runtime/dist/src/realtime/service-ports.js +8 -0
  299. package/runtime/dist/src/realtime/service-state.js +259 -0
  300. package/runtime/dist/src/realtime/service.js +1726 -0
  301. package/runtime/dist/src/realtime/session-state.js +684 -0
  302. package/runtime/dist/src/realtime/session.js +1976 -0
  303. package/runtime/dist/src/realtime/speech-prep.js +63 -0
  304. package/runtime/dist/src/realtime/streaming-speech.js +120 -0
  305. package/runtime/dist/src/realtime/system-prompts.en.js +136 -0
  306. package/runtime/dist/src/realtime/telemetry.js +144 -0
  307. package/runtime/dist/src/realtime/tool-continuations.js +1510 -0
  308. package/runtime/dist/src/realtime/transport.js +8 -0
  309. package/runtime/dist/src/realtime/usage.js +55 -0
  310. package/runtime/dist/src/realtime/user-origin-binding.js +173 -0
  311. package/runtime/dist/src/realtime/volcengine/ark.js +428 -0
  312. package/runtime/dist/src/realtime/volcengine/asr.js +573 -0
  313. package/runtime/dist/src/realtime/volcengine/audio.js +39 -0
  314. package/runtime/dist/src/realtime/volcengine/endpointing-capability.js +834 -0
  315. package/runtime/dist/src/realtime/volcengine/livekit-endpointing.js +714 -0
  316. package/runtime/dist/src/realtime/volcengine/local-eot-executor.js +33 -0
  317. package/runtime/dist/src/realtime/volcengine/protocol.js +247 -0
  318. package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +237 -0
  319. package/runtime/dist/src/realtime/volcengine/tts.js +444 -0
  320. package/runtime/dist/src/realtime/volcengine/websocket.js +293 -0
  321. package/runtime/dist/src/server/aoq-chat-server.js +497 -0
  322. package/runtime/dist/src/server/client-pairing.js +192 -0
  323. package/runtime/dist/src/server/client-protocol.js +87 -0
  324. package/runtime/dist/src/server/client-server.js +312 -0
  325. package/runtime/dist/src/server/server-config.js +72 -0
  326. package/runtime/dist/src/server-entry.js +135 -0
  327. package/runtime/dist/src/storage/bounded-json.js +63 -0
  328. package/runtime/dist/src/storage/native-file-lock.js +8 -0
  329. package/runtime/dist/src/storage/native-resource-snapshot.js +41 -0
  330. package/runtime/dist/src/storage/private-database.js +120 -0
  331. package/runtime/dist/src/text/canonical-json.js +60 -0
  332. package/runtime/dist/src/text/python-number.js +18 -0
  333. package/runtime/dist/src/text/python-text.js +92 -0
  334. package/runtime/dist/src/text/unicode-casefold.js +29 -0
  335. package/runtime/dist/src/text/unicode-normalize.js +138 -0
  336. package/runtime/dist/src/text/unicode-tables.js +210 -0
  337. package/runtime/dist/src/understanding/candidates.js +77 -0
  338. package/runtime/dist/src/understanding/fixture.js +7 -0
  339. package/runtime/dist/src/understanding/jev.js +20 -0
  340. package/runtime/dist/src/understanding/pipeline.js +38 -0
  341. package/runtime/dist/src/voicemem/store-client.js +476 -0
  342. package/runtime/dist/src/voicemem/store-worker.js +380 -0
  343. package/runtime/dist/src/voicemem/versioned-memory.js +170 -0
  344. package/runtime/scripts/pair-device.mjs +109 -0
  345. package/src/command.mjs +48 -0
@@ -0,0 +1,1669 @@
1
+ import { committedConversationPairsSchema } from '../history.js';
2
+ import { abortable } from '../../core/camera-session.js';
3
+ import { dispatchSourceContext } from '../history.js';
4
+ import { cascadedResponseGuidance, validateOriginalImage, TASK_CONTINUATION_INSTRUCTIONS, SCHEDULED_TASK_INSTRUCTIONS } from './llm.js';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { jsonValueSchema } from '../../core/events.js';
7
+ import { codePointLengthLikePython, stripLikePython } from '../../text/python-text.js';
8
+ import { MAX_REALTIME_PCM_BYTES, MAX_REALTIME_TEXT, hostContextItemSchema, hostResponseIntentSchema, realtimeIdentifierSchema, realtimeProviderEventSchema, responseAdaptationContextSchema, workspaceContextInjectionSchema, } from '../protocol.js';
9
+ import { NullTelemetry } from '../telemetry.js';
10
+ import { StreamingSpeech } from '../streaming-speech.js';
11
+ export const MAX_CASCADED_EVENT_QUEUE = 4_096;
12
+ export const MAX_CASCADED_QUEUED_AUDIO_BYTES = 16 * 1_024 * 1_024;
13
+ export const MAX_CASCADED_PENDING_HOST_ITEMS = 256;
14
+ export const MAX_CASCADED_CONSUMED_HOST_ITEMS = 256;
15
+ export const MAX_CASCADED_ABANDONED_TOOL_CALLS = 256;
16
+ export const DEFAULT_CASCADED_SETTLE_MS = 1_000;
17
+ export const CASCADED_PREEMPTIVE_ALERT_POLICY = Object.freeze({
18
+ controlledPreemptiveAlertReconnect: false,
19
+ preemptiveAlertHistoryRecovery: 'none',
20
+ preemptiveAlertHistoryPairs: 4,
21
+ });
22
+ export class CascadedRealtimeError extends Error {
23
+ code;
24
+ constructor(code) {
25
+ super(`Cascaded realtime ${code} failure`);
26
+ this.name = 'CascadedRealtimeError';
27
+ this.code = code;
28
+ }
29
+ }
30
+ class MixedResponseFailure extends Error {
31
+ }
32
+ class TtsResponseFailure extends Error {
33
+ }
34
+ const TTS_BOUNDARIES = new Set([...`,。!?;:,.!?;:\n`]);
35
+ class TextChunker {
36
+ #softLimit = 18;
37
+ #hardLimit = 48;
38
+ #pending = [];
39
+ #first = true;
40
+ push(text) {
41
+ const delta = [...text];
42
+ if (delta.length > MAX_REALTIME_TEXT)
43
+ throw new RangeError('TTS text delta is too large');
44
+ this.#pending.push(...delta);
45
+ const chunks = [];
46
+ while (this.#pending.length > 0) {
47
+ const boundary = this.#flushBoundary();
48
+ if (boundary === null && this.#pending.length < this.#hardLimit)
49
+ break;
50
+ const end = boundary === null ? this.#hardLimit : Math.min(boundary, this.#hardLimit);
51
+ chunks.push(this.#pending.slice(0, end).join(''));
52
+ this.#pending = this.#pending.slice(end);
53
+ this.#first = false;
54
+ }
55
+ return chunks;
56
+ }
57
+ finish() {
58
+ if (this.#pending.length === 0)
59
+ return [];
60
+ const pending = this.#pending.join('');
61
+ this.#pending = [];
62
+ this.#first = false;
63
+ return [pending];
64
+ }
65
+ #flushBoundary() {
66
+ for (let index = 0; index < this.#pending.length; index += 1) {
67
+ if (!TTS_BOUNDARIES.has(this.#pending[index]))
68
+ continue;
69
+ const end = index + 1;
70
+ if (this.#first || end >= this.#softLimit)
71
+ return end;
72
+ }
73
+ return null;
74
+ }
75
+ }
76
+ class BoundedEventQueue {
77
+ #items = [];
78
+ #audioBytes = 0;
79
+ #claimed = false;
80
+ #closed = false;
81
+ #overflowEvent = null;
82
+ #waiter = null;
83
+ claim() {
84
+ if (this.#claimed)
85
+ throw new CascadedRealtimeError('state');
86
+ this.#claimed = true;
87
+ }
88
+ enqueue(event) {
89
+ if (this.#closed)
90
+ return false;
91
+ const owned = cloneEvent(event);
92
+ if (this.#waiter !== null) {
93
+ const waiter = this.#waiter;
94
+ waiter(owned);
95
+ return true;
96
+ }
97
+ const audioBytes = owned.kind === 'response_audio_delta' ? owned.pcm.byteLength : 0;
98
+ if (this.#items.length >= MAX_CASCADED_EVENT_QUEUE
99
+ || this.#audioBytes + audioBytes > MAX_CASCADED_QUEUED_AUDIO_BYTES)
100
+ return false;
101
+ this.#items.push(owned);
102
+ this.#audioBytes += audioBytes;
103
+ return true;
104
+ }
105
+ overflow(event) {
106
+ if (this.#overflowEvent !== null || this.#closed)
107
+ return;
108
+ this.#overflowEvent = cloneEvent(event);
109
+ this.#closed = true;
110
+ this.#wakeTerminalIfReady();
111
+ }
112
+ close() {
113
+ this.#closed = true;
114
+ this.#wakeTerminalIfReady();
115
+ }
116
+ take(signal) {
117
+ if (this.#items.length > 0) {
118
+ const event = this.#items.shift();
119
+ if (event.kind === 'response_audio_delta')
120
+ this.#audioBytes -= event.pcm.byteLength;
121
+ return Promise.resolve(cloneEvent(event));
122
+ }
123
+ if (this.#overflowEvent !== null) {
124
+ const event = this.#overflowEvent;
125
+ this.#overflowEvent = null;
126
+ return Promise.resolve(cloneEvent(event));
127
+ }
128
+ if (this.#closed || signal.aborted)
129
+ return Promise.resolve(null);
130
+ if (this.#waiter !== null)
131
+ return Promise.reject(new CascadedRealtimeError('state'));
132
+ return new Promise(resolve => {
133
+ const onAbort = () => finish(null);
134
+ const finish = (event) => {
135
+ if (this.#waiter !== finish)
136
+ return;
137
+ this.#waiter = null;
138
+ signal.removeEventListener('abort', onAbort);
139
+ resolve(event === null ? null : cloneEvent(event));
140
+ };
141
+ this.#waiter = finish;
142
+ signal.addEventListener('abort', onAbort, { once: true });
143
+ });
144
+ }
145
+ #wakeTerminalIfReady() {
146
+ if (this.#waiter === null || this.#items.length > 0)
147
+ return;
148
+ const waiter = this.#waiter;
149
+ if (this.#overflowEvent !== null) {
150
+ const event = this.#overflowEvent;
151
+ this.#overflowEvent = null;
152
+ waiter(event);
153
+ }
154
+ else
155
+ waiter(null);
156
+ }
157
+ }
158
+ export class CascadedRealtimeAdapter {
159
+ userResponseMode = 'requested';
160
+ #scheduledTask;
161
+ #textOnly;
162
+ #initialHistory;
163
+ #endpointing;
164
+ #asrClient;
165
+ #ttsClient;
166
+ #defaultLanguage;
167
+ #language;
168
+ #llm;
169
+ #llmFactory;
170
+ #prerecall;
171
+ #captureFrame;
172
+ #telemetry;
173
+ #idFactory;
174
+ #settleTimeoutMs;
175
+ #epoch;
176
+ #state = 'new';
177
+ #owner = null;
178
+ #audioTail = Promise.resolve();
179
+ #asrTail = Promise.resolve();
180
+ #queuedAsrBytes = 0;
181
+ #queuedAsrOperations = 0;
182
+ #closePromise = null;
183
+ #legacyLlmUsed = false;
184
+ #legacyLlmClosePromise = null;
185
+ setLanguage(language = this.#defaultLanguage) { this.#language = language; return Promise.resolve(); }
186
+ constructor(options) {
187
+ this.#scheduledTask = options.scheduledTask === true;
188
+ this.#textOnly = options.textOnly === true;
189
+ this.#initialHistory = options.history === undefined ? undefined : committedConversationPairsSchema.parse(options.history);
190
+ if (!this.#textOnly && (!options.endpointing || !options.asr || !options.tts))
191
+ throw new CascadedRealtimeError('configuration');
192
+ this.#endpointing = this.#textOnly ? undefined : options.endpointing;
193
+ this.#asrClient = this.#textOnly ? undefined : options.asr;
194
+ this.#ttsClient = this.#textOnly ? undefined : options.tts;
195
+ this.#defaultLanguage = options.language ?? 'zh-CN';
196
+ this.#language = this.#defaultLanguage;
197
+ this.#llm = options.llm;
198
+ this.#llmFactory = options.llmFactory;
199
+ this.#prerecall = options.prerecall;
200
+ this.#captureFrame = options.captureFrame;
201
+ this.#telemetry = options.telemetry ?? new NullTelemetry();
202
+ this.#idFactory = options.idFactory ?? randomUUID;
203
+ this.#settleTimeoutMs = options.settleTimeoutMs ?? DEFAULT_CASCADED_SETTLE_MS;
204
+ this.#epoch = options.initialEpoch ?? 0;
205
+ if (!Number.isSafeInteger(this.#settleTimeoutMs) || this.#settleTimeoutMs <= 0) {
206
+ throw new CascadedRealtimeError('configuration');
207
+ }
208
+ if (!Number.isSafeInteger(this.#epoch) || this.#epoch < 0) {
209
+ throw new CascadedRealtimeError('configuration');
210
+ }
211
+ }
212
+ async connect(options) {
213
+ if (this.#state !== 'new' && this.#state !== 'disconnected') {
214
+ throw new CascadedRealtimeError('state');
215
+ }
216
+ throwIfAborted(options.signal);
217
+ this.#state = 'connecting';
218
+ this.#closePromise = null;
219
+ this.#audioTail = Promise.resolve();
220
+ this.#asrTail = Promise.resolve();
221
+ this.#queuedAsrBytes = 0;
222
+ this.#queuedAsrOperations = 0;
223
+ const epoch = this.#epoch + 1;
224
+ let owner = null;
225
+ try {
226
+ const tools = options.tools.map(schema => cascadedToolSchema(structuredClone(schema)));
227
+ const sessionId = this.#freshId();
228
+ const llm = this.#openLlm();
229
+ owner = {
230
+ epoch,
231
+ historyRestoring: false,
232
+ sessionId,
233
+ controller: new AbortController(),
234
+ queue: new BoundedEventQueue(),
235
+ llm,
236
+ llmClosePromise: null,
237
+ tools: Object.freeze(tools.map(tool => Object.freeze(structuredClone(tool)))),
238
+ pending: new Map(),
239
+ consumed: new Map(),
240
+ abandonedCalls: new Map(),
241
+ workspaceContext: null,
242
+ prerecall: null,
243
+ responseAdaptation: null,
244
+ consumptionGeneration: 0,
245
+ responseSequence: 0,
246
+ pendingToolCallId: null,
247
+ responseStartBarrier: null,
248
+ userInput: null,
249
+ asr: null,
250
+ response: null,
251
+ standbyTts: null,
252
+ revoked: false,
253
+ };
254
+ this.#owner = owner;
255
+ if (this.#initialHistory !== undefined) {
256
+ if (!llm.restoreHistory)
257
+ throw new CascadedRealtimeError('configuration');
258
+ await llm.restoreHistory(this.#initialHistory, options.signal);
259
+ }
260
+ await this.#endpointing?.reset();
261
+ throwIfAborted(options.signal);
262
+ if (this.#owner !== owner || owner.revoked)
263
+ throw new CascadedRealtimeError('state');
264
+ this.#epoch = epoch;
265
+ this.#state = 'connected';
266
+ this.#warmStandbyTts(owner);
267
+ this.#record('volcengine.session.connected', { epoch });
268
+ return { epoch, provider_session_id: sessionId };
269
+ }
270
+ catch (error) {
271
+ if (owner !== null) {
272
+ const failedOwner = owner;
273
+ await safeCallWithin(() => this.#closeLlm(failedOwner), this.#settleTimeoutMs);
274
+ }
275
+ if (this.#owner?.epoch === epoch)
276
+ this.#owner = null;
277
+ this.#finishConnectFailure();
278
+ if (error instanceof CascadedRealtimeError)
279
+ throw error;
280
+ throwIfAborted(options.signal);
281
+ throw new CascadedRealtimeError('configuration');
282
+ }
283
+ }
284
+ async restoreHistory(history, signal) {
285
+ const owner = this.#requiredOwner();
286
+ if (owner.userInput !== null || owner.response !== null || owner.asr !== null || owner.pending.size || owner.consumed.size || owner.responseSequence)
287
+ throw new CascadedRealtimeError('state');
288
+ if (!owner.llm.restoreHistory)
289
+ throw new CascadedRealtimeError('configuration');
290
+ owner.historyRestoring = true;
291
+ try {
292
+ await owner.llm.restoreHistory(committedConversationPairsSchema.parse(history), combineSignals(signal, owner.controller.signal));
293
+ }
294
+ finally {
295
+ owner.historyRestoring = false;
296
+ }
297
+ }
298
+ submitText(text, signal) {
299
+ if (typeof text !== 'string' || !text.trim() || text.length > 4000)
300
+ return Promise.reject(new CascadedRealtimeError('configuration'));
301
+ const owner = this.#requiredOwner();
302
+ const operation = this.#audioTail.then(async () => {
303
+ throwIfAborted(combineSignals(owner.controller.signal, signal));
304
+ if (!this.#isCurrent(owner) || owner.asr !== null || this.#queuedAsrOperations > 0)
305
+ throw new CascadedRealtimeError('state');
306
+ this.#warmStandbyTts(owner);
307
+ const speechId = this.#freshId(), itemId = this.#freshId();
308
+ await this.#emit(owner, { kind: 'user_speech_started', session_epoch: owner.epoch, speech_id: speechId, provider_item_id: itemId });
309
+ await this.#emit(owner, { kind: 'user_speech_ended', session_epoch: owner.epoch, speech_id: speechId, provider_item_id: itemId });
310
+ owner.userInput = { itemId, text, submitted: false };
311
+ await this.#emit(owner, { kind: 'user_transcript_final', session_epoch: owner.epoch, item_id: itemId, text, input_kind: 'text' });
312
+ });
313
+ this.#audioTail = operation.catch(() => undefined);
314
+ return operation;
315
+ }
316
+ sendAudio(pcm, signal) {
317
+ if (this.#textOnly)
318
+ return Promise.reject(new CascadedRealtimeError('configuration'));
319
+ let owned;
320
+ try {
321
+ owned = inputPcm(pcm);
322
+ }
323
+ catch {
324
+ return Promise.reject(new CascadedRealtimeError('configuration'));
325
+ }
326
+ let owner;
327
+ try {
328
+ owner = this.#requiredOwner();
329
+ }
330
+ catch (error) {
331
+ return Promise.reject(error instanceof Error ? error : new CascadedRealtimeError('state'));
332
+ }
333
+ const operation = this.#audioTail.then(async () => {
334
+ const combined = combineSignals(owner.controller.signal, signal);
335
+ throwIfAborted(combined);
336
+ let decisions;
337
+ try {
338
+ decisions = await this.#endpointing.feed(owned.slice(), combined);
339
+ }
340
+ catch {
341
+ throwIfAborted(combined);
342
+ await this.#emit(owner, {
343
+ kind: 'provider_error', session_epoch: owner.epoch,
344
+ code: 'volcengine_vad_failed', recoverable: true,
345
+ });
346
+ await Promise.resolve(this.#endpointing?.reset()).catch(() => undefined);
347
+ return;
348
+ }
349
+ // Endpointing must keep consuming live microphone frames during a slow network open.
350
+ // ASR writes retain their own order, including the final packet.
351
+ decisions = decisions.map(decision => 'pcm' in decision
352
+ ? { ...decision, pcm: copyEndpointPcm(decision.pcm) } : { ...decision });
353
+ if (decisions.some(decision => decision.kind === 'speech_end')) {
354
+ this.#record('volcengine.vad.local_end', { epoch: owner.epoch });
355
+ try {
356
+ await this.#endpointing.reset();
357
+ }
358
+ catch {
359
+ throwIfAborted(combined);
360
+ await this.#emit(owner, { kind: 'provider_error', session_epoch: owner.epoch,
361
+ code: 'volcengine_vad_failed', recoverable: true });
362
+ }
363
+ }
364
+ const bytes = decisions.reduce((sum, decision) => sum + ('pcm' in decision ? decision.pcm.byteLength : 0), 0);
365
+ this.#queuedAsrBytes += bytes;
366
+ if (decisions.length > 0)
367
+ this.#queuedAsrOperations++;
368
+ const queuedAt = performance.now();
369
+ const throttled = this.#queuedAsrBytes > 320_000;
370
+ const sending = this.#asrTail.then(async () => {
371
+ if (decisions.length > 0)
372
+ this.#record('cascaded.asr.audio_queue', { epoch: owner.epoch, wait_ms: performance.now() - queuedAt, bytes });
373
+ for (const decision of decisions) {
374
+ if (!this.#isCurrent(owner))
375
+ return;
376
+ if (decision.kind === 'speech_start') {
377
+ await this.#startAsr(owner, decision.pcm, combined);
378
+ }
379
+ else if (decision.kind === 'speech_audio') {
380
+ await this.#appendAsr(owner, decision.pcm, combined);
381
+ }
382
+ else if (decision.kind === 'speech_end') {
383
+ if (typeof decision.commit !== 'boolean') {
384
+ await this.#failAsr(owner, 'cascaded_asr_finish');
385
+ }
386
+ else
387
+ await this.#stopAsr(owner, decision.commit, combined);
388
+ }
389
+ else {
390
+ await this.#emit(owner, {
391
+ kind: 'provider_error', session_epoch: owner.epoch,
392
+ code: 'volcengine_vad_failed', recoverable: true,
393
+ });
394
+ }
395
+ }
396
+ }).finally(() => {
397
+ if (this.#owner === owner) {
398
+ this.#queuedAsrBytes -= bytes;
399
+ if (decisions.length > 0)
400
+ this.#queuedAsrOperations--;
401
+ }
402
+ });
403
+ this.#asrTail = sending.catch(() => undefined);
404
+ return { sending, throttled };
405
+ });
406
+ this.#audioTail = operation.then(() => undefined, () => undefined);
407
+ return operation.then(result => result?.throttled ? result.sending : undefined);
408
+ }
409
+ replaceResponseAdaptation(context, signal) {
410
+ try {
411
+ const owner = this.#requiredOwner();
412
+ throwIfAborted(combineSignals(owner.controller.signal, signal));
413
+ context = responseAdaptationContextSchema.parse(context);
414
+ const prior = owner.responseAdaptation;
415
+ if (prior !== null && context.revision < prior.revision)
416
+ return Promise.resolve();
417
+ if (prior !== null && JSON.stringify(context) === JSON.stringify(prior))
418
+ return Promise.resolve();
419
+ owner.responseAdaptation = context;
420
+ return Promise.resolve();
421
+ }
422
+ catch (error) {
423
+ return Promise.reject(error instanceof Error ? error : new CascadedRealtimeError('configuration'));
424
+ }
425
+ }
426
+ async injectHostItem(input, options) {
427
+ void options.confirmationTimeout;
428
+ const owner = this.#requiredOwner();
429
+ throwIfAborted(combineSignals(owner.controller.signal, options.signal));
430
+ let item;
431
+ try {
432
+ item = hostContextItemSchema.parse(input);
433
+ }
434
+ catch {
435
+ throw new CascadedRealtimeError('configuration');
436
+ }
437
+ if (item.kind === 'workspace_context')
438
+ throw new CascadedRealtimeError('configuration');
439
+ if (options.asUserActivation && item.kind !== 'progress' && item.kind !== 'final') {
440
+ throw new CascadedRealtimeError('configuration');
441
+ }
442
+ if (owner.pending.has(item.host_item_id) || owner.consumed.has(item.host_item_id)) {
443
+ throw new CascadedRealtimeError('duplicate_host_item');
444
+ }
445
+ if (owner.pending.size >= MAX_CASCADED_PENDING_HOST_ITEMS) {
446
+ throw new CascadedRealtimeError('pending_host_items_full');
447
+ }
448
+ const providerItemId = this.#freshId();
449
+ owner.pending.set(item.host_item_id, {
450
+ providerItemId,
451
+ item: structuredClone(item),
452
+ input: hostInput(item, options.asUserActivation),
453
+ });
454
+ return await Promise.resolve({
455
+ session_epoch: owner.epoch,
456
+ host_item_id: item.host_item_id,
457
+ provider_item_id: providerItemId,
458
+ });
459
+ }
460
+ retireHostItem(providerItemId, signal) {
461
+ const owner = this.#requiredOwner();
462
+ throwIfAborted(combineSignals(owner.controller.signal, signal));
463
+ for (const [id, pending] of owner.pending) {
464
+ if (pending.providerItemId === providerItemId)
465
+ owner.pending.delete(id);
466
+ }
467
+ return Promise.resolve();
468
+ }
469
+ async injectWorkspaceContext(input, options) {
470
+ void options.confirmationTimeout;
471
+ const owner = this.#requiredOwner();
472
+ throwIfAborted(combineSignals(owner.controller.signal, options.signal));
473
+ let item;
474
+ try {
475
+ item = hostContextItemSchema.parse(input);
476
+ }
477
+ catch {
478
+ throw new CascadedRealtimeError('configuration');
479
+ }
480
+ if (item.kind !== 'workspace_context' || item.session_epoch !== owner.epoch) {
481
+ throw new CascadedRealtimeError('configuration');
482
+ }
483
+ const prior = owner.workspaceContext;
484
+ if (prior !== null && JSON.stringify(prior.item) === JSON.stringify(item)) {
485
+ return await Promise.resolve(structuredClone(prior.record));
486
+ }
487
+ if (prior !== null
488
+ && prior.item.workspace_instance_id === item.workspace_instance_id
489
+ && (item.revision ?? -1) <= (prior.item.revision ?? -1)) {
490
+ throw new CascadedRealtimeError('configuration');
491
+ }
492
+ const providerItemId = this.#freshId();
493
+ const record = workspaceContextInjectionSchema.parse({
494
+ item,
495
+ asUserActivation: false,
496
+ delivery: {
497
+ capability: 'replace_provider_item', delivered: true,
498
+ session_epoch: item.session_epoch,
499
+ workspace_instance_id: item.workspace_instance_id,
500
+ revision: item.revision,
501
+ prior_provider_item_id: prior?.providerItemId ?? null,
502
+ provider_item_id: providerItemId,
503
+ superseded_provider_item_id: prior?.providerItemId ?? null,
504
+ },
505
+ });
506
+ owner.workspaceContext = {
507
+ item: structuredClone(item), providerItemId, record: structuredClone(record),
508
+ };
509
+ return await Promise.resolve(structuredClone(record));
510
+ }
511
+ async createResponse(input, signal) {
512
+ const owner = this.#requiredOwner();
513
+ throwIfAborted(combineSignals(owner.controller.signal, signal));
514
+ let intent;
515
+ try {
516
+ intent = hostResponseIntentSchema.parse(input);
517
+ }
518
+ catch {
519
+ throw new CascadedRealtimeError('configuration');
520
+ }
521
+ await this.#serializeResponseStart(owner, async () => {
522
+ throwIfAborted(combineSignals(owner.controller.signal, signal));
523
+ if (owner.response !== null)
524
+ throw new CascadedRealtimeError('response_active');
525
+ if (intent.item.kind === 'tool_output' && intent.item.call_id !== null
526
+ && owner.abandonedCalls.has(intent.item.call_id)) {
527
+ owner.abandonedCalls.delete(intent.item.call_id);
528
+ owner.pending.delete(intent.item.host_item_id);
529
+ this.#startSilentResponse(owner, { kind: 'host_request', host_item_id: intent.item.host_item_id });
530
+ await Promise.resolve();
531
+ return;
532
+ }
533
+ if (owner.consumed.delete(intent.item.host_item_id)) {
534
+ this.#startSilentResponse(owner, { kind: 'host_request', host_item_id: intent.item.host_item_id });
535
+ await Promise.resolve();
536
+ return;
537
+ }
538
+ const { inputs, hostIds } = this.#selectResponseInputs(owner, intent);
539
+ if (inputs.length === 0)
540
+ throw new CascadedRealtimeError('missing_host_input');
541
+ await this.#resolvePendingToolCall(owner, inputs);
542
+ if (!this.#isCurrent(owner))
543
+ throw new CascadedRealtimeError('state');
544
+ throwIfAborted(combineSignals(owner.controller.signal, signal));
545
+ for (const id of hostIds)
546
+ owner.pending.delete(id);
547
+ this.#startResponse(owner, inputs, { kind: 'host_request', host_item_id: intent.item.host_item_id }, intent.item.kind === 'tool_output' || intent.kind === 'scheduled_task', intent.kind === 'task_continuation' ? 'content' : intent.kind === 'scheduled_task' ? 'scheduled' : undefined);
548
+ await Promise.resolve();
549
+ });
550
+ }
551
+ async cancelResponse(responseId, signal) {
552
+ const owner = this.#requiredOwner();
553
+ throwIfAborted(combineSignals(owner.controller.signal, signal));
554
+ if (!realtimeIdentifierSchema.safeParse(responseId).success) {
555
+ throw new CascadedRealtimeError('configuration');
556
+ }
557
+ const response = owner.response;
558
+ if (response?.id !== responseId || response.terminal) {
559
+ await this.#emit(owner, {
560
+ kind: 'response_cancel_rejected',
561
+ session_epoch: owner.epoch,
562
+ response_id: responseId,
563
+ cancel_request_id: this.#freshId(),
564
+ reason: 'no_active_response',
565
+ });
566
+ return;
567
+ }
568
+ this.#record('volcengine.response.cancel', { epoch: owner.epoch });
569
+ response.controller.abort();
570
+ if (!await settleWithin(response.task, this.#settleTimeoutMs)) {
571
+ // The LLM/TTS did not relinquish ownership. Reusing this epoch would overlap inference.
572
+ await this.#emitTerminal(owner, response, 'failed', 'cancel_timeout');
573
+ await this.#emit(owner, { kind: 'provider_error', session_epoch: owner.epoch,
574
+ code: 'cascaded_cancel_timeout', recoverable: false });
575
+ await this.#disconnectOwner(owner);
576
+ }
577
+ }
578
+ async *events(signal) {
579
+ const owner = this.#requiredOwner();
580
+ owner.queue.claim();
581
+ while (!signal.aborted) {
582
+ const event = await owner.queue.take(signal);
583
+ if (event === null)
584
+ return;
585
+ yield cloneEvent(event);
586
+ }
587
+ }
588
+ close() {
589
+ if (this.#closePromise !== null)
590
+ return this.#closePromise;
591
+ if (this.#state === 'new' || this.#state === 'disconnected') {
592
+ this.#state = 'disconnected';
593
+ this.#closePromise = (async () => {
594
+ if (!(await safeCallWithin(() => this.#closeUnusedLegacyLlm(), this.#settleTimeoutMs))) {
595
+ throw new CascadedRealtimeError('closed');
596
+ }
597
+ })();
598
+ return this.#closePromise;
599
+ }
600
+ this.#state = 'closing';
601
+ const owner = this.#owner;
602
+ const audioTail = this.#audioTail;
603
+ const asrTail = this.#asrTail;
604
+ this.#closePromise = (async () => {
605
+ let failed = false;
606
+ if (owner !== null) {
607
+ owner.revoked = true;
608
+ this.#emitClosingTerminal(owner);
609
+ owner.controller.abort();
610
+ failed = !(await settleWithin(audioTail, this.#settleTimeoutMs)) || failed;
611
+ failed = !(await settleWithin(asrTail, this.#settleTimeoutMs)) || failed;
612
+ failed = !(await this.#cleanupOwner(owner)) || failed;
613
+ owner.queue.close();
614
+ this.#record('volcengine.session.closed', { epoch: owner.epoch });
615
+ }
616
+ if (this.#owner === owner)
617
+ this.#owner = null;
618
+ this.#state = 'disconnected';
619
+ if (failed)
620
+ throw new CascadedRealtimeError('closed');
621
+ })();
622
+ return this.#closePromise;
623
+ }
624
+ #emitClosingTerminal(owner) {
625
+ const active = owner.response;
626
+ if (active?.id == null || active.terminal)
627
+ return;
628
+ active.terminal = true;
629
+ const terminal = realtimeProviderEventSchema.parse({
630
+ kind: 'response_terminal', session_epoch: owner.epoch,
631
+ response_id: active.id,
632
+ ...(active.origin.kind === 'user_item' ? { origin: active.origin } : {}), status: 'cancelled', reason: 'cancelled',
633
+ });
634
+ if (!owner.queue.enqueue(terminal)) {
635
+ owner.queue.overflow({
636
+ kind: 'provider_error', session_epoch: owner.epoch,
637
+ code: 'volcengine_event_overflow', recoverable: false,
638
+ });
639
+ }
640
+ this.#record('volcengine.response.terminal', { status: 'cancelled' });
641
+ }
642
+ async #startAsr(owner, pcm, signal) {
643
+ if (owner.asr !== null)
644
+ await this.#discardAsr(owner);
645
+ this.#warmStandbyTts(owner);
646
+ const speechId = this.#freshId();
647
+ const itemId = this.#freshId();
648
+ await this.#emit(owner, {
649
+ kind: 'user_speech_started', session_epoch: owner.epoch,
650
+ speech_id: speechId, provider_item_id: itemId,
651
+ });
652
+ let session;
653
+ try {
654
+ this.#record('cascaded.asr.connect', { epoch: owner.epoch });
655
+ session = await this.#asrClient.open(signal);
656
+ this.#record('cascaded.asr.connected', { epoch: owner.epoch, item_id: itemId });
657
+ }
658
+ catch {
659
+ if (!this.#isCurrent(owner))
660
+ return;
661
+ await this.#emit(owner, {
662
+ kind: 'user_speech_ended', session_epoch: owner.epoch,
663
+ speech_id: speechId, provider_item_id: itemId,
664
+ });
665
+ await this.#emit(owner, {
666
+ kind: 'provider_error', session_epoch: owner.epoch,
667
+ code: 'cascaded_asr_start', recoverable: true,
668
+ });
669
+ await this.#emit(owner, {
670
+ kind: 'user_transcript_failed', session_epoch: owner.epoch, item_id: itemId,
671
+ });
672
+ return;
673
+ }
674
+ if (!this.#isCurrent(owner)) {
675
+ await safeCallWithin(() => session.close(), this.#settleTimeoutMs);
676
+ return;
677
+ }
678
+ const controller = new AbortController();
679
+ const active = {
680
+ session, controller, speechId, itemId,
681
+ task: Promise.resolve(), speechEnded: false, failed: false,
682
+ };
683
+ owner.asr = active;
684
+ active.task = this.#consumeAsr(owner, active);
685
+ void active.task.catch(() => undefined);
686
+ try {
687
+ await session.append(pcm, combineSignals(signal, controller.signal));
688
+ }
689
+ catch {
690
+ await this.#failAsr(owner, 'cascaded_asr_append');
691
+ return;
692
+ }
693
+ this.#record('volcengine.vad.start', { epoch: owner.epoch });
694
+ }
695
+ async #appendAsr(owner, pcm, signal) {
696
+ const active = owner.asr;
697
+ if (active === null)
698
+ return;
699
+ try {
700
+ await active.session.append(pcm, combineSignals(signal, active.controller.signal));
701
+ }
702
+ catch {
703
+ await this.#failAsr(owner, 'cascaded_asr_append');
704
+ }
705
+ }
706
+ async #stopAsr(owner, commit, signal) {
707
+ const active = owner.asr;
708
+ if (active === null) {
709
+ return;
710
+ }
711
+ if (!active.speechEnded) {
712
+ active.speechEnded = true;
713
+ await this.#emit(owner, {
714
+ kind: 'user_speech_ended', session_epoch: owner.epoch,
715
+ speech_id: active.speechId, provider_item_id: active.itemId,
716
+ });
717
+ }
718
+ this.#record('volcengine.vad.end', { epoch: owner.epoch, commit });
719
+ if (active.failed) {
720
+ if (owner.asr === active)
721
+ owner.asr = null;
722
+ return;
723
+ }
724
+ if (!commit) {
725
+ await this.#discardAsr(owner);
726
+ return;
727
+ }
728
+ try {
729
+ await active.session.finish(combineSignals(signal, active.controller.signal));
730
+ }
731
+ catch {
732
+ await this.#emit(owner, {
733
+ kind: 'provider_error', session_epoch: owner.epoch,
734
+ code: 'cascaded_asr_finish', recoverable: true,
735
+ });
736
+ await this.#emit(owner, {
737
+ kind: 'user_transcript_failed', session_epoch: owner.epoch, item_id: active.itemId,
738
+ });
739
+ await this.#discardAsr(owner);
740
+ }
741
+ }
742
+ async #consumeAsr(owner, active) {
743
+ let finalSeen = false;
744
+ try {
745
+ for await (const transcript of active.session.events(combineSignals(owner.controller.signal, active.controller.signal))) {
746
+ if (!this.#isCurrent(owner) || owner.asr !== active)
747
+ return;
748
+ if (typeof transcript.text !== 'string' || typeof transcript.final !== 'boolean') {
749
+ throw new Error('invalid ASR event');
750
+ }
751
+ if ([...transcript.text].length > MAX_REALTIME_TEXT) {
752
+ throw new Error('ASR transcript is too large');
753
+ }
754
+ if (transcript.final) {
755
+ finalSeen = true;
756
+ this.#record('cascaded.asr.final', { epoch: owner.epoch });
757
+ if (stripLikePython(transcript.text) === '') {
758
+ await this.#emit(owner, {
759
+ kind: 'user_transcript_failed', session_epoch: owner.epoch, item_id: active.itemId,
760
+ });
761
+ }
762
+ else {
763
+ owner.userInput = { itemId: active.itemId, text: transcript.text, submitted: false };
764
+ await this.#emit(owner, {
765
+ kind: 'user_transcript_final', session_epoch: owner.epoch,
766
+ item_id: active.itemId, text: transcript.text,
767
+ });
768
+ }
769
+ return;
770
+ }
771
+ else {
772
+ this.#record('cascaded.asr.partial', { epoch: owner.epoch });
773
+ if (transcript.text.length >= 6)
774
+ void this.#prepareRecall(owner, active.itemId, transcript.text);
775
+ await this.#emit(owner, {
776
+ kind: 'user_transcript_delta', session_epoch: owner.epoch,
777
+ item_id: active.itemId, text: transcript.text,
778
+ ...(transcript.replace === true ? { replace: true } : {}),
779
+ });
780
+ }
781
+ }
782
+ if (!finalSeen && !active.controller.signal.aborted && !owner.controller.signal.aborted) {
783
+ throw new Error('ASR stream ended without final transcript');
784
+ }
785
+ }
786
+ catch {
787
+ if (this.#isCurrent(owner) && owner.asr === active
788
+ && !active.controller.signal.aborted && !owner.controller.signal.aborted) {
789
+ active.failed = true;
790
+ await this.#emit(owner, {
791
+ kind: 'provider_error', session_epoch: owner.epoch,
792
+ code: 'cascaded_asr_receive', recoverable: true,
793
+ });
794
+ await this.#emit(owner, {
795
+ kind: 'user_transcript_failed', session_epoch: owner.epoch, item_id: active.itemId,
796
+ });
797
+ }
798
+ }
799
+ finally {
800
+ await active.session.close().catch(() => undefined);
801
+ if (owner.asr === active && (active.speechEnded || active.controller.signal.aborted)) {
802
+ owner.asr = null;
803
+ }
804
+ }
805
+ }
806
+ async #failAsr(owner, code) {
807
+ const active = owner.asr;
808
+ if (active === null)
809
+ return;
810
+ if (!active.speechEnded) {
811
+ active.speechEnded = true;
812
+ await this.#emit(owner, {
813
+ kind: 'user_speech_ended', session_epoch: owner.epoch,
814
+ speech_id: active.speechId, provider_item_id: active.itemId,
815
+ });
816
+ }
817
+ await this.#emit(owner, {
818
+ kind: 'provider_error', session_epoch: owner.epoch, code, recoverable: true,
819
+ });
820
+ await this.#emit(owner, {
821
+ kind: 'user_transcript_failed', session_epoch: owner.epoch, item_id: active.itemId,
822
+ });
823
+ await this.#discardAsr(owner);
824
+ }
825
+ async #discardAsr(owner) {
826
+ const active = owner.asr;
827
+ if (active === null)
828
+ return;
829
+ owner.asr = null;
830
+ active.controller.abort();
831
+ await active.session.close().catch(() => undefined);
832
+ await settleWithin(active.task, this.#settleTimeoutMs);
833
+ }
834
+ async ensureResponse(signal, userItemId, requestId) {
835
+ const owner = this.#requiredOwner();
836
+ if (userItemId !== undefined && !realtimeIdentifierSchema.safeParse(userItemId).success) {
837
+ throw new CascadedRealtimeError('configuration');
838
+ }
839
+ if (requestId !== undefined && !realtimeIdentifierSchema.safeParse(requestId).success) {
840
+ throw new CascadedRealtimeError('configuration');
841
+ }
842
+ return this.#serializeResponseStart(owner, async () => {
843
+ throwIfAborted(combineSignals(owner.controller.signal, signal));
844
+ const input = owner.userInput;
845
+ if (owner.response !== null || input === null
846
+ || (userItemId !== undefined && input.itemId !== userItemId))
847
+ return false;
848
+ const { inputs, hostIds } = this.#selectResponseInputs(owner, null);
849
+ await this.#resolvePendingToolCall(owner, inputs);
850
+ if (!this.#isCurrent(owner))
851
+ throw new CascadedRealtimeError('state');
852
+ throwIfAborted(combineSignals(owner.controller.signal, signal));
853
+ if (owner.userInput !== input)
854
+ return false;
855
+ this.#markConsumed(owner, hostIds);
856
+ // A retry continues the same conversation; appending the transcript again invents a user turn.
857
+ if (!input.submitted)
858
+ inputs.push({ kind: 'user_text', text: input.text });
859
+ this.#startResponse(owner, inputs, { kind: 'user_item', item_id: input.itemId,
860
+ ...(requestId === undefined ? {} : { request_id: requestId }) });
861
+ return true;
862
+ });
863
+ }
864
+ #startResponse(owner, inputs, origin, allowTools = true, taskContinuation) {
865
+ const controller = new AbortController();
866
+ const active = {
867
+ controller, origin, id: `cascaded-response-${owner.epoch}-${++owner.responseSequence}`,
868
+ task: Promise.resolve(), terminal: false, tts: null,
869
+ };
870
+ owner.response = active;
871
+ active.task = Promise.resolve().then(() => this.#runResponse(owner, active, inputs, allowTools, taskContinuation));
872
+ void active.task.catch(() => undefined);
873
+ }
874
+ #startSilentResponse(owner, origin) {
875
+ const controller = new AbortController();
876
+ const active = {
877
+ controller, origin, id: null, task: Promise.resolve(), terminal: false, tts: null,
878
+ };
879
+ owner.response = active;
880
+ active.task = Promise.resolve().then(async () => {
881
+ const responseId = this.#freshId();
882
+ active.id = responseId;
883
+ try {
884
+ await this.#emit(owner, {
885
+ kind: 'response_started', session_epoch: owner.epoch, response_id: responseId, origin: active.origin,
886
+ });
887
+ await this.#emitTerminal(owner, active, 'completed', 'completed');
888
+ }
889
+ finally {
890
+ if (owner.response === active)
891
+ owner.response = null;
892
+ }
893
+ });
894
+ void active.task.catch(() => undefined);
895
+ }
896
+ #prepareRecall(owner, itemId, query) {
897
+ if (!this.#prerecall)
898
+ return Promise.resolve(null);
899
+ if (owner.prerecall?.query === query && owner.prerecall.itemId === itemId)
900
+ return owner.prerecall.result;
901
+ owner.prerecall?.controller.abort();
902
+ const controller = new AbortController();
903
+ const signal = AbortSignal.any([owner.controller.signal, controller.signal, AbortSignal.timeout(250)]);
904
+ const started = performance.now();
905
+ const result = abortable(this.#prerecall(query, signal), signal).catch(() => null).then(content => {
906
+ this.#record('memory.prerecall.completed', { duration_ms: performance.now() - started, injected: false });
907
+ return signal.aborted ? null : content;
908
+ });
909
+ owner.prerecall = { query, itemId, controller, result };
910
+ return result;
911
+ }
912
+ async #runResponse(owner, active, inputs, allowTools, taskContinuation) {
913
+ const language = this.#language;
914
+ let llmResponseId = null;
915
+ let llmFailureCode = null;
916
+ let textSeen = false;
917
+ let toolSeen = false;
918
+ let pendingTool = null;
919
+ const transcript = [];
920
+ let transcriptLength = 0;
921
+ const chunker = new TextChunker();
922
+ const speech = new StreamingSpeech();
923
+ const signal = combineSignals(owner.controller.signal, active.controller.signal);
924
+ let continuationResetFailed = false;
925
+ try {
926
+ if (active.id === null)
927
+ throw new Error('missing admitted response identity');
928
+ // Admission belongs to this adapter, independent of when a remote LLM sends its first byte.
929
+ await this.#emit(owner, { kind: 'response_started', session_epoch: owner.epoch,
930
+ response_id: active.id, origin: active.origin });
931
+ throwIfAborted(signal);
932
+ let visualInputs = inputs;
933
+ if (this.#captureFrame && inputs.some(item => item.kind === 'user_text')) {
934
+ try {
935
+ this.#record('cascaded.vision.requested', { epoch: owner.epoch, response_id: active.id });
936
+ const image = await this.#captureFrame(signal);
937
+ this.#record('cascaded.vision.completed', { epoch: owner.epoch, response_id: active.id });
938
+ validateOriginalImage(image);
939
+ throwIfAborted(signal);
940
+ if (!this.#isCurrent(owner) || owner.response !== active)
941
+ return;
942
+ visualInputs = inputs.map(item => item.kind === 'user_text' ? { ...item, image } : item);
943
+ }
944
+ catch {
945
+ throwIfAborted(signal);
946
+ visualInputs = inputs.map(item => item.kind === 'user_text' ? { ...item, text: item.text + '\n[主机状态:本轮摄像头取帧失败。请明确告诉用户本轮未取得画面,不要假装看到了。]' } : item);
947
+ }
948
+ }
949
+ const userText = inputs.find(item => item.kind === 'user_text');
950
+ let memoryContext = null;
951
+ if (userText?.kind === 'user_text' && this.#prerecall) {
952
+ const consumeSignal = AbortSignal.any([signal, AbortSignal.timeout(250)]);
953
+ const prepared = await abortable(this.#prepareRecall(owner, owner.userInput?.itemId ?? active.id, userText.text), consumeSignal).catch(() => null);
954
+ if (prepared) {
955
+ memoryContext = await abortable(prepared(consumeSignal), consumeSignal).catch(() => null);
956
+ }
957
+ throwIfAborted(signal);
958
+ if (!this.#isCurrent(owner) || owner.response !== active)
959
+ return;
960
+ this.#record('memory.prerecall.injected', { injected: memoryContext !== null });
961
+ }
962
+ this.#record('cascaded.llm.requested', { epoch: owner.epoch, response_id: active.id });
963
+ this.#warmStandbyTts(owner);
964
+ for await (const event of owner.llm.stream({
965
+ language,
966
+ inputs: visualInputs.map(item => structuredClone(item)),
967
+ tools: allowTools ? owner.tools.map(tool => structuredClone(tool)) : [],
968
+ workspaceContext: allowTools ? owner.workspaceContext?.item.content ?? null : null,
969
+ responseAdaptation: [allowTools ? owner.responseAdaptation?.content : null, allowTools ? memoryContext : null,
970
+ allowTools ? [...owner.pending.values()].filter(pending => pending.item.speech_content !== undefined)
971
+ .map(pending => pending.item.content).join('\n') : null,
972
+ allowTools ? dispatchSourceContext(owner.responseAdaptation?.user_sources) : null,
973
+ taskContinuation === 'content' ? TASK_CONTINUATION_INSTRUCTIONS : taskContinuation === 'scheduled' || this.#scheduledTask ? SCHEDULED_TASK_INSTRUCTIONS : cascadedResponseGuidance(allowTools, language),
974
+ ].filter(Boolean).join('\n'),
975
+ signal,
976
+ })) {
977
+ throwIfAborted(signal);
978
+ if (!this.#isCurrent(owner) || owner.response !== active)
979
+ return;
980
+ if (event.kind === 'response_started') {
981
+ if (llmResponseId !== null)
982
+ throw new Error('duplicate LLM response identity');
983
+ llmResponseId = event.response_id;
984
+ this.#record('cascaded.llm.started', { epoch: owner.epoch, response_id: active.id });
985
+ }
986
+ else if (event.kind === 'text_delta') {
987
+ if (toolSeen)
988
+ throw new MixedResponseFailure();
989
+ if (llmResponseId === null)
990
+ throw new Error('LLM text before identity');
991
+ if (!this.#textOnly && active.tts === null) {
992
+ active.tts = this.#newTtsState(active.id, signal);
993
+ const standby = owner.standbyTts;
994
+ if (standby !== null) {
995
+ owner.standbyTts = null;
996
+ clearTimeout(standby.timer);
997
+ active.tts.openId = standby.state.openId;
998
+ this.#record('cascaded.tts.prewarm.claimed', { epoch: owner.epoch,
999
+ response_id: active.id, open_id: standby.state.openId });
1000
+ active.tts.controller = standby.state.controller;
1001
+ active.tts.openPromise = standby.state.openPromise;
1002
+ const controller = active.tts.controller;
1003
+ signal.addEventListener('abort', () => controller.abort(), { once: true, signal: controller.signal });
1004
+ }
1005
+ else
1006
+ this.#prewarmTts(owner, active.tts);
1007
+ }
1008
+ textSeen = true;
1009
+ transcriptLength += [...event.text].length;
1010
+ if (transcriptLength > MAX_REALTIME_TEXT)
1011
+ throw new Error('LLM response text overflow');
1012
+ transcript.push(event.text);
1013
+ if (transcriptLength === [...event.text].length) {
1014
+ this.#record('cascaded.llm.first_text', { epoch: owner.epoch, response_id: active.id });
1015
+ }
1016
+ await this.#emit(owner, {
1017
+ kind: 'response_transcript_delta', session_epoch: owner.epoch,
1018
+ response_id: active.id, text: event.text,
1019
+ });
1020
+ if (active.tts !== null)
1021
+ for (const chunk of chunker.push(speech.push(event.text))) {
1022
+ await this.#sendTtsText(owner, active.tts, chunk);
1023
+ }
1024
+ }
1025
+ else if (event.kind === 'tool_call') {
1026
+ if (textSeen || toolSeen)
1027
+ throw new MixedResponseFailure();
1028
+ if (llmResponseId === null)
1029
+ throw new Error('LLM tool before identity');
1030
+ toolSeen = true;
1031
+ pendingTool = event;
1032
+ owner.pendingToolCallId = event.call_id;
1033
+ this.#record('cascaded.llm.tool_call', { epoch: owner.epoch, response_id: active.id });
1034
+ }
1035
+ else if (event.kind === 'response_failed') {
1036
+ if (llmResponseId !== null && event.response_id !== llmResponseId)
1037
+ throw new Error('LLM failure identity mismatch');
1038
+ llmFailureCode = event.code;
1039
+ throw new Error('LLM stable provider failure');
1040
+ }
1041
+ else {
1042
+ if (llmResponseId === null || event.response_id !== llmResponseId) {
1043
+ throw new Error('LLM terminal identity mismatch');
1044
+ }
1045
+ if (textSeen) {
1046
+ if (!this.#textOnly) {
1047
+ if (active.tts === null)
1048
+ throw new Error('missing TTS state');
1049
+ for (const chunk of chunker.push(speech.finish())) {
1050
+ await this.#sendTtsText(owner, active.tts, chunk);
1051
+ }
1052
+ for (const chunk of chunker.finish()) {
1053
+ await this.#sendTtsText(owner, active.tts, chunk);
1054
+ }
1055
+ await this.#finishTts(owner, active);
1056
+ }
1057
+ await this.#emit(owner, {
1058
+ kind: 'response_transcript_final', session_epoch: owner.epoch,
1059
+ response_id: active.id, text: transcript.join(''),
1060
+ });
1061
+ }
1062
+ else {
1063
+ await this.#cancelTts(owner, active);
1064
+ if (pendingTool !== null) {
1065
+ await this.#emit(owner, {
1066
+ kind: 'tool_call_ready', session_epoch: owner.epoch,
1067
+ call_id: pendingTool.call_id, item_id: pendingTool.item_id,
1068
+ name: pendingTool.name, arguments: structuredClone(pendingTool.arguments),
1069
+ response_id: active.id,
1070
+ });
1071
+ }
1072
+ }
1073
+ if (active.origin.kind === 'user_item' && owner.userInput?.itemId === active.origin.item_id) {
1074
+ owner.userInput.submitted = true;
1075
+ }
1076
+ await this.#emitTerminal(owner, active, 'completed', 'completed');
1077
+ return;
1078
+ }
1079
+ }
1080
+ throw new Error('LLM stream ended without terminal');
1081
+ }
1082
+ catch (error) {
1083
+ if (owner.pendingToolCallId !== null) {
1084
+ continuationResetFailed = !(await this.#abandonPendingToolCall(owner));
1085
+ }
1086
+ if (active.controller.signal.aborted || owner.controller.signal.aborted) {
1087
+ await this.#cancelTts(owner, active);
1088
+ if (active.id !== null && !active.terminal) {
1089
+ await this.#emitTerminal(owner, active, 'cancelled', 'cancelled');
1090
+ }
1091
+ }
1092
+ else if (error instanceof MixedResponseFailure) {
1093
+ await this.#cancelTts(owner, active);
1094
+ await this.#emit(owner, {
1095
+ kind: 'provider_error', session_epoch: owner.epoch,
1096
+ code: 'cascaded_mixed_text_tool', recoverable: false,
1097
+ });
1098
+ if (active.id !== null)
1099
+ await this.#emitTerminal(owner, active, 'failed', 'mixed_output');
1100
+ }
1101
+ else {
1102
+ await this.#cancelTts(owner, active);
1103
+ const ttsFailure = error instanceof TtsResponseFailure;
1104
+ const rawCode = llmFailureCode ?? (error instanceof Error && 'code' in error ? error.code : null);
1105
+ const code = typeof rawCode === 'string'
1106
+ && ['configuration', 'aborted', 'timeout', 'protocol', 'overflow', 'closed', 'network', 'http'].includes(rawCode)
1107
+ ? rawCode : 'unknown';
1108
+ this.#record('cascaded.response.failed', { component: ttsFailure ? 'tts' : 'llm', code });
1109
+ await this.#emit(owner, {
1110
+ kind: 'provider_error', session_epoch: owner.epoch,
1111
+ code: ttsFailure ? 'cascaded_tts_receive' : 'cascaded_response_failed',
1112
+ recoverable: true,
1113
+ });
1114
+ active.id ??= this.#freshId();
1115
+ await this.#emitTerminal(owner, active, 'failed', ttsFailure ? 'tts_failure' : 'provider_failure');
1116
+ }
1117
+ }
1118
+ finally {
1119
+ if (owner.response === active)
1120
+ owner.response = null;
1121
+ if (continuationResetFailed && this.#isCurrent(owner)) {
1122
+ await this.#disconnectOwner(owner);
1123
+ }
1124
+ }
1125
+ }
1126
+ #newTtsState(responseId, responseSignal) {
1127
+ return {
1128
+ responseId,
1129
+ responseSignal,
1130
+ controller: new AbortController(),
1131
+ openId: null,
1132
+ openPromise: null,
1133
+ session: null,
1134
+ receiveTask: null,
1135
+ texts: [],
1136
+ audioEmitted: false,
1137
+ retryUsed: false,
1138
+ firstTextRecorded: false,
1139
+ };
1140
+ }
1141
+ #warmStandbyTts(owner) {
1142
+ if (this.#textOnly || !this.#isCurrent(owner) || owner.standbyTts !== null)
1143
+ return;
1144
+ const state = this.#newTtsState('', owner.controller.signal);
1145
+ const timer = setTimeout(() => {
1146
+ if (owner.standbyTts?.state !== state)
1147
+ return;
1148
+ owner.standbyTts = null;
1149
+ void this.#releaseTtsState(state, true);
1150
+ }, 30_000);
1151
+ timer.unref();
1152
+ owner.standbyTts = { state, timer };
1153
+ this.#prewarmTts(owner, state);
1154
+ }
1155
+ #prewarmTts(owner, state) {
1156
+ if (state.openPromise !== null || state.session !== null)
1157
+ return;
1158
+ const openId = randomUUID();
1159
+ state.openId = openId;
1160
+ const started = performance.now();
1161
+ const payload = { epoch: owner.epoch, open_id: openId,
1162
+ ...(state.responseId ? { response_id: state.responseId } : {}) };
1163
+ this.#record('cascaded.tts.prewarm', payload);
1164
+ state.openPromise = Promise.resolve().then(() => this.#ttsClient.open(combineSignals(state.responseSignal, state.controller.signal))).then(session => {
1165
+ this.#record('cascaded.tts.prewarm.ready', { ...payload, duration_ms: performance.now() - started });
1166
+ return session;
1167
+ }, error => {
1168
+ this.#record('cascaded.tts.prewarm.failed', { ...payload, duration_ms: performance.now() - started });
1169
+ throw error;
1170
+ });
1171
+ void state.openPromise.catch(() => undefined);
1172
+ }
1173
+ async #ensureTts(owner, state) {
1174
+ if (state.session !== null)
1175
+ return state.session;
1176
+ const signal = combineSignals(state.responseSignal, state.controller.signal);
1177
+ throwIfAborted(signal);
1178
+ const prewarm = state.openPromise;
1179
+ let session;
1180
+ if (prewarm !== null) {
1181
+ try {
1182
+ session = await prewarm;
1183
+ }
1184
+ catch {
1185
+ throwIfAborted(signal);
1186
+ state.openPromise = this.#ttsClient.open(signal);
1187
+ session = await state.openPromise;
1188
+ }
1189
+ }
1190
+ else {
1191
+ state.openPromise = this.#ttsClient.open(signal);
1192
+ session = await state.openPromise;
1193
+ }
1194
+ // Keep pending opens owned until release can cancel even a late provider result.
1195
+ throwIfAborted(signal);
1196
+ state.openPromise = null;
1197
+ state.session = session;
1198
+ state.receiveTask = this.#consumeTts(owner, state, session);
1199
+ void state.receiveTask.catch(() => undefined);
1200
+ return session;
1201
+ }
1202
+ async #sendTtsText(owner, state, text) {
1203
+ state.texts.push(text);
1204
+ try {
1205
+ const session = await this.#ensureTts(owner, state);
1206
+ if (!state.firstTextRecorded) {
1207
+ state.firstTextRecorded = true;
1208
+ this.#record('cascaded.tts.first_text', { epoch: owner.epoch, response_id: state.responseId });
1209
+ }
1210
+ await session.sendText(text, combineSignals(state.responseSignal, state.controller.signal));
1211
+ }
1212
+ catch {
1213
+ try {
1214
+ if (await this.#retryTts(owner, state))
1215
+ return;
1216
+ }
1217
+ catch {
1218
+ // The stable TTS category below owns every open/send/replay detail.
1219
+ }
1220
+ throw new TtsResponseFailure();
1221
+ }
1222
+ }
1223
+ async #consumeTts(owner, state, session) {
1224
+ for await (const event of session.events(combineSignals(state.responseSignal, state.controller.signal))) {
1225
+ if (!this.#isCurrent(owner) || state.session !== session)
1226
+ return;
1227
+ const pcm = new Uint8Array(event.pcm);
1228
+ if (pcm.byteLength === 0 || pcm.byteLength % 2 !== 0)
1229
+ throw new TtsResponseFailure();
1230
+ if (!state.audioEmitted) {
1231
+ state.audioEmitted = true;
1232
+ this.#record('cascaded.tts.first_audio', { epoch: owner.epoch, response_id: state.responseId });
1233
+ }
1234
+ await this.#emit(owner, {
1235
+ kind: 'response_audio_delta', session_epoch: owner.epoch,
1236
+ response_id: state.responseId, pcm,
1237
+ });
1238
+ }
1239
+ // A closed prewarmed session is not proof that submitted speech was synthesized.
1240
+ if (!state.audioEmitted && !state.controller.signal.aborted)
1241
+ throw new TtsResponseFailure();
1242
+ }
1243
+ async #retryTts(owner, state) {
1244
+ if (state.audioEmitted || state.retryUsed || state.responseSignal.aborted)
1245
+ return false;
1246
+ state.retryUsed = true;
1247
+ this.#record('cascaded.tts.reconnect', { epoch: owner.epoch });
1248
+ await this.#releaseTtsState(state, true);
1249
+ state.controller = new AbortController();
1250
+ const session = await this.#ensureTts(owner, state);
1251
+ for (const text of state.texts) {
1252
+ await session.sendText(text, combineSignals(state.responseSignal, state.controller.signal));
1253
+ }
1254
+ return true;
1255
+ }
1256
+ async #finishTts(owner, active) {
1257
+ const state = active.tts;
1258
+ if (state === null)
1259
+ return;
1260
+ if (state.texts.length === 0) {
1261
+ await this.#cancelTts(owner, active);
1262
+ return;
1263
+ }
1264
+ try {
1265
+ const session = await this.#ensureTts(owner, state);
1266
+ await session.finish(combineSignals(state.responseSignal, state.controller.signal));
1267
+ if (state.receiveTask !== null)
1268
+ await state.receiveTask;
1269
+ }
1270
+ catch {
1271
+ try {
1272
+ if (!await this.#retryTts(owner, state))
1273
+ throw new TtsResponseFailure();
1274
+ if (state.session === null)
1275
+ throw new TtsResponseFailure();
1276
+ await state.session.finish(combineSignals(state.responseSignal, state.controller.signal));
1277
+ if (state.receiveTask !== null)
1278
+ await state.receiveTask;
1279
+ }
1280
+ catch {
1281
+ throw new TtsResponseFailure();
1282
+ }
1283
+ }
1284
+ finally {
1285
+ await this.#releaseTtsState(state, false);
1286
+ active.tts = null;
1287
+ }
1288
+ }
1289
+ async #cancelTts(owner, active) {
1290
+ const state = active.tts;
1291
+ if (state === null)
1292
+ return true;
1293
+ const hadResource = state.openPromise !== null || state.session !== null || state.receiveTask !== null;
1294
+ active.tts = null;
1295
+ const successful = await this.#releaseTtsState(state, true);
1296
+ if (hadResource)
1297
+ this.#record('cascaded.tts.cancel', { epoch: owner.epoch });
1298
+ return successful;
1299
+ }
1300
+ async #releaseTtsState(state, cancel) {
1301
+ let successful = true;
1302
+ const open = state.openPromise;
1303
+ state.openPromise = null;
1304
+ state.controller.abort();
1305
+ let session = state.session;
1306
+ state.session = null;
1307
+ if (open !== null) {
1308
+ const openSettled = await settleWithin(open, this.#settleTimeoutMs);
1309
+ if (openSettled) {
1310
+ try {
1311
+ session ??= await open;
1312
+ }
1313
+ catch {
1314
+ // A failed prewarm owns no provider resource.
1315
+ }
1316
+ }
1317
+ else {
1318
+ successful = false;
1319
+ void open.then(async (late) => {
1320
+ await safeCallWithin(() => late.cancel(), this.#settleTimeoutMs);
1321
+ await safeCallWithin(() => late.close(), this.#settleTimeoutMs);
1322
+ }, () => undefined);
1323
+ }
1324
+ }
1325
+ if (cancel && session !== null) {
1326
+ successful = await safeCallWithin(() => session.cancel(), this.#settleTimeoutMs) && successful;
1327
+ }
1328
+ const receive = state.receiveTask;
1329
+ state.receiveTask = null;
1330
+ if (receive !== null) {
1331
+ successful = await settleWithin(receive, this.#settleTimeoutMs) && successful;
1332
+ }
1333
+ if (session !== null) {
1334
+ successful = await safeCallWithin(() => session.close(), this.#settleTimeoutMs) && successful;
1335
+ }
1336
+ return successful;
1337
+ }
1338
+ async #emitTerminal(owner, active, status, reason) {
1339
+ if (active.terminal || active.id === null)
1340
+ return;
1341
+ active.terminal = true;
1342
+ await this.#emit(owner, {
1343
+ kind: 'response_terminal', session_epoch: owner.epoch,
1344
+ response_id: active.id,
1345
+ ...(active.origin.kind === 'user_item' ? { origin: active.origin } : {}), status, reason,
1346
+ });
1347
+ this.#record('volcengine.response.terminal', { status });
1348
+ }
1349
+ #selectResponseInputs(owner, intent) {
1350
+ const inputs = [];
1351
+ const hostIds = [];
1352
+ if (intent !== null && !owner.pending.has(intent.item.host_item_id))
1353
+ return { inputs, hostIds };
1354
+ for (const [hostId, pending] of owner.pending) {
1355
+ const include = pending.item.kind === 'recovery' || pending.item.kind === 'dialogue_context'
1356
+ || pending.item.kind === 'tool_output' || hostId === intent?.item.host_item_id;
1357
+ if (!include)
1358
+ continue;
1359
+ const input = intent?.kind === 'scheduled_task' && hostId === intent.item.host_item_id ? { kind: 'host_task', content: pending.item.content } : intent?.kind === 'host_fact' && hostId === intent.item.host_item_id
1360
+ && (pending.item.kind === 'progress' || pending.item.kind === 'final')
1361
+ ? hostInput(pending.item, true) : structuredClone(pending.input);
1362
+ if (input.kind === 'tool_result')
1363
+ inputs.unshift(input);
1364
+ else
1365
+ inputs.push(input);
1366
+ if (pending.item.speech_content === undefined)
1367
+ hostIds.push(hostId);
1368
+ }
1369
+ return { inputs, hostIds };
1370
+ }
1371
+ #markConsumed(owner, hostIds) {
1372
+ if (hostIds.length === 0)
1373
+ return;
1374
+ owner.consumptionGeneration += 1;
1375
+ for (const hostId of hostIds) {
1376
+ owner.pending.delete(hostId);
1377
+ owner.consumed.delete(hostId);
1378
+ owner.consumed.set(hostId, owner.consumptionGeneration);
1379
+ }
1380
+ while (owner.consumed.size > MAX_CASCADED_CONSUMED_HOST_ITEMS) {
1381
+ const oldest = owner.consumed.keys().next().value;
1382
+ if (oldest === undefined)
1383
+ break;
1384
+ owner.consumed.delete(oldest);
1385
+ }
1386
+ }
1387
+ async #resolvePendingToolCall(owner, inputs) {
1388
+ const callId = owner.pendingToolCallId;
1389
+ if (callId === null)
1390
+ return;
1391
+ if (inputs.some(input => input.kind === 'tool_result' && input.call_id === callId)) {
1392
+ owner.pendingToolCallId = null;
1393
+ return;
1394
+ }
1395
+ if (!(await this.#abandonPendingToolCall(owner))) {
1396
+ await this.#disconnectOwner(owner);
1397
+ throw new CascadedRealtimeError('closed');
1398
+ }
1399
+ }
1400
+ async #abandonPendingToolCall(owner) {
1401
+ const callId = owner.pendingToolCallId;
1402
+ if (callId === null)
1403
+ return true;
1404
+ owner.pendingToolCallId = null;
1405
+ owner.abandonedCalls.delete(callId);
1406
+ owner.abandonedCalls.set(callId, null);
1407
+ while (owner.abandonedCalls.size > MAX_CASCADED_ABANDONED_TOOL_CALLS) {
1408
+ const oldest = owner.abandonedCalls.keys().next().value;
1409
+ if (oldest === undefined)
1410
+ break;
1411
+ owner.abandonedCalls.delete(oldest);
1412
+ }
1413
+ return await safeCallWithin(() => owner.llm.abandonPendingResponse(), this.#settleTimeoutMs);
1414
+ }
1415
+ async #disconnectOwner(owner) {
1416
+ owner.revoked = true;
1417
+ owner.controller.abort();
1418
+ await this.#cleanupOwner(owner);
1419
+ owner.queue.close();
1420
+ if (this.#owner === owner)
1421
+ this.#owner = null;
1422
+ this.#state = 'disconnected';
1423
+ }
1424
+ async #serializeResponseStart(owner, operation) {
1425
+ const previous = owner.responseStartBarrier;
1426
+ let release;
1427
+ const barrier = new Promise(resolve => { release = resolve; });
1428
+ owner.responseStartBarrier = barrier;
1429
+ if (previous !== null)
1430
+ await previous;
1431
+ try {
1432
+ // Terminal is observable before the response task finishes releasing its ownership.
1433
+ if (owner.response?.terminal && !await settleWithin(owner.response.task, this.#settleTimeoutMs)) {
1434
+ throw new CascadedRealtimeError('response_active');
1435
+ }
1436
+ if (!this.#isCurrent(owner))
1437
+ throw new CascadedRealtimeError('state');
1438
+ return await operation();
1439
+ }
1440
+ finally {
1441
+ release?.();
1442
+ if (owner.responseStartBarrier === barrier)
1443
+ owner.responseStartBarrier = null;
1444
+ }
1445
+ }
1446
+ #emit(owner, event) {
1447
+ if (!this.#isCurrent(owner))
1448
+ return Promise.resolve();
1449
+ let parsed;
1450
+ try {
1451
+ parsed = realtimeProviderEventSchema.parse(event);
1452
+ }
1453
+ catch {
1454
+ parsed = {
1455
+ kind: 'provider_error', session_epoch: owner.epoch,
1456
+ code: 'volcengine_event_invalid', recoverable: false,
1457
+ };
1458
+ }
1459
+ if (owner.queue.enqueue(parsed))
1460
+ return Promise.resolve();
1461
+ owner.queue.overflow({
1462
+ kind: 'provider_error', session_epoch: owner.epoch,
1463
+ code: 'volcengine_event_overflow', recoverable: false,
1464
+ });
1465
+ owner.revoked = true;
1466
+ owner.controller.abort();
1467
+ void this.#cleanupOwner(owner).catch(() => undefined);
1468
+ return Promise.resolve();
1469
+ }
1470
+ async #cleanupOwner(owner) {
1471
+ let successful = true;
1472
+ const standby = owner.standbyTts;
1473
+ owner.standbyTts = null;
1474
+ if (standby !== null) {
1475
+ clearTimeout(standby.timer);
1476
+ successful = await this.#releaseTtsState(standby.state, true) && successful;
1477
+ }
1478
+ const response = owner.response;
1479
+ if (response !== null) {
1480
+ response.controller.abort();
1481
+ successful = await settleWithin(response.task, this.#settleTimeoutMs) && successful;
1482
+ successful = await this.#cancelTts(owner, response) && successful;
1483
+ if (owner.response === response)
1484
+ owner.response = null;
1485
+ }
1486
+ const asr = owner.asr;
1487
+ if (asr !== null) {
1488
+ asr.controller.abort();
1489
+ successful = await safeCallWithin(() => asr.session.close(), this.#settleTimeoutMs) && successful;
1490
+ successful = await settleWithin(asr.task, this.#settleTimeoutMs) && successful;
1491
+ if (owner.asr === asr)
1492
+ owner.asr = null;
1493
+ }
1494
+ successful = await this.#abandonPendingToolCall(owner) && successful;
1495
+ successful = await safeCallWithin(() => this.#closeLlm(owner), this.#settleTimeoutMs) && successful;
1496
+ successful = await safeCallWithin(async () => { await this.#endpointing?.reset(); }, this.#settleTimeoutMs) && successful;
1497
+ return successful;
1498
+ }
1499
+ #openLlm() {
1500
+ if (!this.#legacyLlmUsed) {
1501
+ this.#legacyLlmUsed = true;
1502
+ return this.#llm;
1503
+ }
1504
+ if (this.#llmFactory !== undefined)
1505
+ return this.#llmFactory.open();
1506
+ throw new CascadedRealtimeError('state');
1507
+ }
1508
+ #closeLlm(owner) {
1509
+ owner.llmClosePromise ??= Promise.resolve().then(() => owner.llm.close());
1510
+ return owner.llmClosePromise;
1511
+ }
1512
+ #closeUnusedLegacyLlm() {
1513
+ if (this.#legacyLlmUsed)
1514
+ return Promise.resolve();
1515
+ this.#legacyLlmClosePromise ??= Promise.resolve().then(() => this.#llm.close());
1516
+ return this.#legacyLlmClosePromise;
1517
+ }
1518
+ #requiredOwner() {
1519
+ const owner = this.#owner;
1520
+ if (this.#state !== 'connected' || owner === null || owner.revoked || owner.historyRestoring) {
1521
+ throw new CascadedRealtimeError('state');
1522
+ }
1523
+ return owner;
1524
+ }
1525
+ #finishConnectFailure() {
1526
+ if (this.#state !== 'closing')
1527
+ this.#state = 'disconnected';
1528
+ }
1529
+ #isCurrent(owner) {
1530
+ return this.#owner === owner && !owner.revoked;
1531
+ }
1532
+ #freshId() {
1533
+ let value;
1534
+ try {
1535
+ value = this.#idFactory();
1536
+ }
1537
+ catch {
1538
+ throw new CascadedRealtimeError('configuration');
1539
+ }
1540
+ const parsed = realtimeIdentifierSchema.safeParse(value);
1541
+ if (!parsed.success)
1542
+ throw new CascadedRealtimeError('configuration');
1543
+ return parsed.data;
1544
+ }
1545
+ #record(kind, payload) {
1546
+ this.#telemetry.record(kind, payload);
1547
+ }
1548
+ }
1549
+ function hostInput(item, asUserActivation) {
1550
+ if (item.kind === 'tool_output') {
1551
+ let output;
1552
+ try {
1553
+ output = JSON.parse(item.content);
1554
+ }
1555
+ catch {
1556
+ // Tool output is evidence, not a command: plain text is a valid JSON string value.
1557
+ output = item.content;
1558
+ }
1559
+ const parsed = jsonValueSchema.safeParse(output);
1560
+ if (!parsed.success || item.call_id === null)
1561
+ throw new CascadedRealtimeError('configuration');
1562
+ return { kind: 'tool_result', call_id: item.call_id, output: structuredClone(parsed.data) };
1563
+ }
1564
+ const labels = {
1565
+ progress: '任务进度事实',
1566
+ final: '任务结果事实',
1567
+ recovery: '恢复摘要',
1568
+ scheduled_task: '定时任务委托',
1569
+ dialogue_context: '只读历史对话',
1570
+ };
1571
+ const content = asUserActivation
1572
+ ? item.speech_content ?? item.content
1573
+ : `Nova Personal Agent ${labels[item.kind]}:${item.content}`;
1574
+ return item.kind === 'dialogue_context'
1575
+ ? { kind: 'packed_history', content }
1576
+ : { kind: asUserActivation ? 'host_activation' : 'host_context', content };
1577
+ }
1578
+ function cascadedToolSchema(schema) {
1579
+ const functionObject = schema.function;
1580
+ if (schema.type !== 'function' || !jsonObject(functionObject)) {
1581
+ throw new CascadedRealtimeError('configuration');
1582
+ }
1583
+ const name = functionObject.name;
1584
+ const parameters = functionObject.parameters;
1585
+ if (!validIdentifier(name) || !jsonObject(parameters)) {
1586
+ throw new CascadedRealtimeError('configuration');
1587
+ }
1588
+ const description = functionObject.description;
1589
+ if (description !== undefined && typeof description !== 'string') {
1590
+ throw new CascadedRealtimeError('configuration');
1591
+ }
1592
+ return {
1593
+ name,
1594
+ ...(description !== undefined && stripLikePython(description) !== '' ? { description } : {}),
1595
+ parameters: structuredClone(parameters),
1596
+ };
1597
+ }
1598
+ function validIdentifier(value) {
1599
+ return typeof value === 'string' && stripLikePython(value) !== ''
1600
+ && codePointLengthLikePython(value) <= MAX_REALTIME_TEXT;
1601
+ }
1602
+ function jsonObject(value) {
1603
+ return value !== null && !Array.isArray(value) && typeof value === 'object'
1604
+ && jsonValueSchema.safeParse(value).success;
1605
+ }
1606
+ function copyEndpointPcm(value) {
1607
+ try {
1608
+ return inputPcm(value);
1609
+ }
1610
+ catch {
1611
+ throw new CascadedRealtimeError('configuration');
1612
+ }
1613
+ }
1614
+ function inputPcm(value) {
1615
+ if (!(value instanceof Uint8Array) || value.byteLength === 0 || value.byteLength % 2 !== 0
1616
+ || value.byteLength > MAX_REALTIME_PCM_BYTES) {
1617
+ throw new RangeError('PCM must be non-empty aligned bounded PCM16 bytes');
1618
+ }
1619
+ return value.slice();
1620
+ }
1621
+ function cloneEvent(event) {
1622
+ if (event.kind !== 'response_audio_delta')
1623
+ return structuredClone(event);
1624
+ return { ...event, pcm: event.pcm.slice() };
1625
+ }
1626
+ function combineSignals(first, second) {
1627
+ return first === second ? first : AbortSignal.any([first, second]);
1628
+ }
1629
+ function throwIfAborted(signal) {
1630
+ if (!signal.aborted)
1631
+ return;
1632
+ if (signal.reason instanceof Error)
1633
+ throw signal.reason;
1634
+ throw new DOMException('This operation was aborted', 'AbortError');
1635
+ }
1636
+ async function settleWithin(task, timeoutMs) {
1637
+ let timer;
1638
+ try {
1639
+ return await Promise.race([
1640
+ task.then(() => true, () => true),
1641
+ new Promise(resolve => { timer = setTimeout(() => resolve(false), timeoutMs); }),
1642
+ ]);
1643
+ }
1644
+ finally {
1645
+ if (timer !== undefined)
1646
+ clearTimeout(timer);
1647
+ }
1648
+ }
1649
+ async function safeCallWithin(operation, timeoutMs) {
1650
+ let task;
1651
+ try {
1652
+ task = operation();
1653
+ }
1654
+ catch {
1655
+ return false;
1656
+ }
1657
+ let timer;
1658
+ try {
1659
+ return await Promise.race([
1660
+ task.then(() => true, () => false),
1661
+ new Promise(resolve => { timer = setTimeout(() => resolve(false), timeoutMs); }),
1662
+ ]);
1663
+ }
1664
+ finally {
1665
+ if (timer !== undefined)
1666
+ clearTimeout(timer);
1667
+ }
1668
+ }
1669
+ //# sourceMappingURL=adapter.js.map