nova-personal-agent-server 0.0.0-stage → 0.4.1

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,1092 @@
1
+ import { personalCommandSchema } from './personal-agent/contracts.js';
2
+ import { parsePromptLanguage } from './realtime/prompt-language.js';
3
+ export { VISION_MODELS, supportsVision } from './model/vision-capability.js';
4
+ export { describeMissingBlockingEnvironment } from './config/config.js';
5
+ import { taskActionSchema } from './desktop/desktop-tasks.js';
6
+ import { timingSafeEqual } from 'node:crypto';
7
+ import { createConnection } from 'node:net';
8
+ import { z } from 'zod';
9
+ import { WebSocket, WebSocketServer } from 'ws';
10
+ import { CAMERA_CAPTURE_TIMEOUT_MS, CAMERA_HEIGHT, CAMERA_PERMISSION_TIMEOUT_MS, CAMERA_WIDTH, MAX_CAMERA_LATE_RESPONSES, MAX_CAMERA_POSITION_MS, MAX_CAMERA_WIRE_BYTES, MAX_DESKTOP_INBOUND_BYTES, MAX_PENDING_CAMERA_REQUESTS, decodeCameraFrame, hasCameraFrameMagic, parseCameraError, parseCameraPermissionResult, serializeCameraCapture, serializeCameraPermissionRequest, } from './desktop/desktop-camera.js';
11
+ import { codePointLengthLikePython, stripLikePython } from './text/python-text.js';
12
+ import { MAX_BOARD_MESSAGE_BYTES, } from './realtime/memory-board.js';
13
+ export { inspectProjectNativeHostFromResources, loadProjectNativeHostFromResources, } from './projects/project-native-resource.js';
14
+ export { ManagedWorkspaceMaintenanceService, } from './projects/managed-workspace-maintenance.js';
15
+ import { DESKTOP_READY, MAX_DESKTOP_JSON_BYTES, MAX_DESKTOP_PCM_BYTES } from './desktop/desktop-wire.js';
16
+ export { MAX_DESKTOP_JSON_BYTES, MAX_DESKTOP_PCM_BYTES, WIRE_FRAME_TYPES } from './desktop/desktop-wire.js';
17
+ // Task detail includes up to 100 public events of 16,000 characters, plus receipts.
18
+ // Keep personal projections bounded independently of inbound/control text.
19
+ export const MAX_DESKTOP_PERSONAL_JSON_BYTES = 8 * 1024 * 1024;
20
+ export const MAX_DESKTOP_OUTBOUND_BINARY_BYTES = 8 * 1024 * 1024;
21
+ export const MAX_DESKTOP_PENDING_SENDS = 128;
22
+ export const MAX_DESKTOP_DEBUG_CONNECTIONS = 4;
23
+ export const DESKTOP_AUTH_TIMEOUT_MS = 3_000;
24
+ export const DESKTOP_CLOSE_GRACE_MS = 500;
25
+ export const DESKTOP_READY_TIMEOUT_MS = 5_000;
26
+ export const DESKTOP_DEBUG_PATH = '/debug-board';
27
+ const tokenPattern = /^[a-f0-9]{32}$/u;
28
+ const readyEndpointPattern = /^127\.0\.0\.1:([0-9]{1,5})$/u;
29
+ const identifierSchema = z.string()
30
+ .refine(value => codePointLengthLikePython(value) <= 256)
31
+ .refine(value => stripLikePython(value) !== '');
32
+ const renderTimestampSchema = z.number().finite().nonnegative().optional();
33
+ const playbackTelemetryCountSchema = z.number().int().nonnegative().max(4_294_967_295);
34
+ const playbackTelemetryQueueSchema = z.number().int().nonnegative().max(16_777_216);
35
+ const playbackTelemetryDurationSchema = z.number().finite().nonnegative().max(86_400_000);
36
+ const helloSchema = z.object({
37
+ type: z.literal('hello'),
38
+ token: z.string(),
39
+ });
40
+ const debugBoardRequestSchema = z.object({
41
+ type: z.literal('debug.board.request'),
42
+ request_id: identifierSchema,
43
+ board: z.literal('memory'),
44
+ detail: z.enum(['compact', 'full']),
45
+ channel: z.string().min(1).max(128).optional(),
46
+ before_seq: z.number().int().positive().optional(),
47
+ query: z.string().max(200).optional(),
48
+ }).strict().refine(value => (value.before_seq === undefined || value.channel !== undefined) && (value.query === undefined || value.channel === 'personal'));
49
+ export const playbackTelemetrySchema = z.object({
50
+ type: z.literal('playback.telemetry'),
51
+ utterance_id: identifierSchema,
52
+ generation_epoch: z.number().int().positive(),
53
+ final: z.boolean(),
54
+ window_ms: playbackTelemetryDurationSchema.int(),
55
+ queued_samples: playbackTelemetryQueueSchema,
56
+ queued_samples_max: playbackTelemetryQueueSchema,
57
+ underrun_samples: playbackTelemetryCountSchema,
58
+ underrun_callbacks: playbackTelemetryCountSchema,
59
+ max_consecutive_underrun_samples: playbackTelemetryCountSchema,
60
+ render_callbacks: playbackTelemetryCountSchema,
61
+ max_callback_us: z.number().int().nonnegative().max(60_000_000),
62
+ frame_gap_ms_max: playbackTelemetryDurationSchema,
63
+ pcm_near_silence_ms_max: playbackTelemetryDurationSchema.int(),
64
+ sequence_gaps: z.number().int().nonnegative().max(1_000_000),
65
+ rejected_frames: z.number().int().nonnegative().max(1_000_000),
66
+ stdin_buffered_bytes_max: playbackTelemetryQueueSchema,
67
+ stdin_backpressure_count: z.number().int().nonnegative().max(1_000_000),
68
+ stdin_drain_ms_max: playbackTelemetryDurationSchema,
69
+ }).strict();
70
+ export const connectionDiagnosticSchema = z.discriminatedUnion('phase', [
71
+ z.object({
72
+ type: z.literal('connection.diagnostic'),
73
+ phase: z.literal('closed'),
74
+ close_code: z.number().int().nonnegative().max(4_999),
75
+ reason: z.enum([
76
+ 'normal',
77
+ 'going_away',
78
+ 'protocol_error',
79
+ 'unsupported_data',
80
+ 'abnormal',
81
+ 'policy',
82
+ 'message_too_big',
83
+ 'internal_error',
84
+ 'protocol_rejected',
85
+ 'client_unavailable',
86
+ 'other',
87
+ ]),
88
+ }).strict(),
89
+ z.object({
90
+ type: z.literal('connection.diagnostic'),
91
+ phase: z.literal('reconnect_attempt'),
92
+ attempt: z.number().int().positive().max(1_000_000),
93
+ delay_ms: z.number().int().positive().max(60_000),
94
+ }).strict(),
95
+ z.object({
96
+ type: z.literal('connection.diagnostic'),
97
+ phase: z.literal('reconnect_result'),
98
+ attempt: z.number().int().nonnegative().max(1_000_000),
99
+ result: z.enum(['connected', 'open_failed']),
100
+ }).strict(),
101
+ ]);
102
+ const DEFAULT_BOOTSTRAP_TEXT_FRAMES = [
103
+ JSON.stringify({ type: DESKTOP_READY }),
104
+ ];
105
+ const ordinaryDesktopControlSchema = z.discriminatedUnion('type', [
106
+ personalCommandSchema,
107
+ z.object({ type: z.literal('input.audio'), conversation_id: identifierSchema.optional() }).strict(),
108
+ z.object({ type: z.literal('input.dictation'), conversation_id: identifierSchema.optional(), id: identifierSchema, action: z.enum(['start', 'finish', 'cancel']) }).strict(),
109
+ z.object({ type: z.literal('input.text'), source_todo: z.object({ id: z.string().min(1).max(512), version: z.number().int().nonnegative() }).strict().optional(), conversation_id: identifierSchema.optional(), request_id: z.string().min(1).max(128).optional(), input_instance_id: z.string().min(1).max(128).optional(), text: z.string().min(1).max(4000).refine(value => value.trim().length > 0) }).strict(),
110
+ z.object({
111
+ type: z.literal('speech.onset'),
112
+ speech_id: identifierSchema,
113
+ t_render_ms: renderTimestampSchema,
114
+ }),
115
+ z.object({
116
+ type: z.literal('playback.started'),
117
+ utterance_id: identifierSchema,
118
+ generation_epoch: z.number().int().positive(),
119
+ t_render_ms: renderTimestampSchema,
120
+ }),
121
+ ...['playback.stopped', 'playback.done', 'playback.cleared']
122
+ .map(type => z.object({
123
+ type: z.literal(type),
124
+ utterance_id: identifierSchema,
125
+ generation_epoch: z.number().int().positive(),
126
+ played_ms: z.number().int().nonnegative().optional(),
127
+ t_render_ms: renderTimestampSchema,
128
+ })),
129
+ z.object({
130
+ type: z.literal('project.confirmation_decision'), conversation_id: identifierSchema.optional(),
131
+ proposal_id: identifierSchema.refine(value => codePointLengthLikePython(value) <= 128),
132
+ confirmed: z.boolean(),
133
+ }).strict(),
134
+ z.object({
135
+ type: z.literal('executor.approval_decision'), conversation_id: identifierSchema.optional(),
136
+ executor: identifierSchema,
137
+ approval_id: identifierSchema.refine(value => codePointLengthLikePython(value) <= 128),
138
+ approved: z.boolean(),
139
+ scope: z.literal('session').optional(),
140
+ }).strict().refine(value => value.scope === undefined || value.approved),
141
+ z.object({
142
+ type: z.literal('clock.pong'),
143
+ ping_id: identifierSchema,
144
+ t_render_ms: z.number().finite().nonnegative(),
145
+ }),
146
+ playbackTelemetrySchema,
147
+ ]);
148
+ export const desktopControlSchema = z.union([
149
+ ordinaryDesktopControlSchema,
150
+ taskActionSchema,
151
+ z.object({ type: z.literal('coding.progress_narration'), mode: z.enum(['smart', 'continuous']) }).strict(),
152
+ connectionDiagnosticSchema,
153
+ ]);
154
+ export class DesktopProtocolError extends Error {
155
+ constructor(message) {
156
+ super(message);
157
+ this.name = 'DesktopProtocolError';
158
+ }
159
+ }
160
+ export class DesktopOutboundValidationError extends DesktopProtocolError {
161
+ constructor(message) {
162
+ super(message);
163
+ this.name = 'DesktopOutboundValidationError';
164
+ }
165
+ }
166
+ export class DesktopPersonalFrameTooLargeError extends DesktopOutboundValidationError {
167
+ frameType;
168
+ bytes;
169
+ requestId;
170
+ constructor(frameType, bytes, requestId) {
171
+ super('desktop personal frame is too large');
172
+ this.frameType = frameType;
173
+ this.bytes = bytes;
174
+ this.requestId = requestId;
175
+ this.name = 'DesktopPersonalFrameTooLargeError';
176
+ }
177
+ }
178
+ export class DesktopCameraError extends Error {
179
+ code;
180
+ constructor(code) {
181
+ super(code === 'invalid_request'
182
+ ? 'desktop camera capture request is invalid'
183
+ : 'desktop camera capture is unavailable');
184
+ this.code = code;
185
+ this.name = 'DesktopCameraError';
186
+ }
187
+ }
188
+ export class NodeDesktopServer {
189
+ #options;
190
+ #server;
191
+ #active;
192
+ #authenticated = false;
193
+ #pendingSends = [];
194
+ #currentSend;
195
+ #writerRunning = false;
196
+ #pendingSendCount = 0;
197
+ #stopping = false;
198
+ #closing;
199
+ #connectionGeneration = 0;
200
+ #cameraSequence = 0n;
201
+ #cameraPermissionSequence = 0n;
202
+ #pendingCamera = new Map();
203
+ #pendingCameraPermission;
204
+ #lateCameraIds = new Map();
205
+ #lateCameraOrder = [];
206
+ #debugSockets = new Set();
207
+ #inboundBytes = 0;
208
+ constructor(options) {
209
+ validateDesktopToken(options.token);
210
+ const timeout = options.authTimeoutMs ?? DESKTOP_AUTH_TIMEOUT_MS;
211
+ if (!Number.isFinite(timeout) || timeout <= 0) {
212
+ throw new DesktopProtocolError('desktop authentication timeout is invalid');
213
+ }
214
+ const closeGrace = options.closeGraceMs ?? DESKTOP_CLOSE_GRACE_MS;
215
+ if (!Number.isFinite(closeGrace) || closeGrace <= 0) {
216
+ throw new DesktopProtocolError('desktop close grace is invalid');
217
+ }
218
+ this.#options = {
219
+ ...options,
220
+ authTimeoutMs: timeout,
221
+ closeGraceMs: closeGrace,
222
+ bootstrapTextFrames: copyBootstrapTextFrames(options.bootstrapTextFrames),
223
+ };
224
+ }
225
+ async sendText(raw) {
226
+ if (!this.#canSend())
227
+ throw outboundUnavailableError();
228
+ validateOutboundText(raw);
229
+ return this.#enqueueSend(this.#active, raw);
230
+ }
231
+ async sendBinary(raw) {
232
+ if (!this.#canSend())
233
+ throw outboundUnavailableError();
234
+ validateOutboundBinary(raw);
235
+ // The caller may reuse its buffer after the Promise is returned. The queued
236
+ // frame must remain exactly the bytes accepted at this boundary.
237
+ return this.#enqueueSend(this.#active, new Uint8Array(raw));
238
+ }
239
+ captureCamera(request) {
240
+ validateCameraCaptureRequest(request);
241
+ if (!this.#canSend() || this.#pendingCamera.size >= MAX_PENDING_CAMERA_REQUESTS) {
242
+ return Promise.reject(cameraUnavailableError());
243
+ }
244
+ const socket = this.#active;
245
+ const generation = this.#connectionGeneration;
246
+ this.#cameraSequence += 1n;
247
+ const requestId = `camera-${this.#cameraSequence}`;
248
+ const raw = serializeCameraCapture(request.source === 'local'
249
+ ? { request_id: requestId, source: 'local', ...(request.sessionId === undefined ? {} : { session_id: request.sessionId, device_id: request.deviceId ?? '' }) }
250
+ : { request_id: requestId, source: 'file', position_ms: request.positionMs });
251
+ const pending = new PendingCameraCapture(requestId, socket, generation);
252
+ this.#pendingCamera.set(requestId, pending);
253
+ const timer = this.#options.cameraTimer ?? defaultCameraTimer;
254
+ pending.timerHandle = timer.set(CAMERA_CAPTURE_TIMEOUT_MS, () => {
255
+ if (this.#pendingCamera.get(requestId) !== pending)
256
+ return;
257
+ this.#pendingCamera.delete(requestId);
258
+ this.#rememberLateCameraId(pending);
259
+ pending.reject(cameraUnavailableError());
260
+ });
261
+ void this.#enqueueSend(socket, raw).catch(() => {
262
+ this.#rejectCameraCapture(pending, cameraUnavailableError());
263
+ });
264
+ return pending.promise;
265
+ }
266
+ releaseCamera(sessionId) {
267
+ if (!/^[a-zA-Z0-9-]{1,80}$/u.test(sessionId))
268
+ return Promise.reject(cameraUnavailableError());
269
+ if (!this.#canSend())
270
+ return Promise.resolve();
271
+ return this.#enqueueSend(this.#active, JSON.stringify({ type: 'camera.release', session_id: sessionId }));
272
+ }
273
+ requestCameraPermission() {
274
+ if (!this.#canSend() || this.#pendingCameraPermission !== undefined) {
275
+ return Promise.reject(cameraUnavailableError());
276
+ }
277
+ const socket = this.#active;
278
+ const generation = this.#connectionGeneration;
279
+ this.#cameraPermissionSequence += 1n;
280
+ const requestId = `camera-permission-${this.#cameraPermissionSequence}`;
281
+ const pending = new PendingCameraPermission(requestId, socket, generation);
282
+ this.#pendingCameraPermission = pending;
283
+ const timer = this.#options.cameraTimer ?? defaultCameraTimer;
284
+ pending.timerHandle = timer.set(CAMERA_PERMISSION_TIMEOUT_MS, () => {
285
+ if (this.#pendingCameraPermission !== pending)
286
+ return;
287
+ this.#pendingCameraPermission = undefined;
288
+ this.#rememberLateCameraId(pending);
289
+ pending.reject(cameraUnavailableError());
290
+ });
291
+ void this.#enqueueSend(socket, serializeCameraPermissionRequest({ request_id: requestId }))
292
+ .catch(() => this.#rejectCameraPermission(pending));
293
+ return pending.promise;
294
+ }
295
+ /** Retire only the client active when this call begins; a later reconnect is never its target. */
296
+ async disconnectClient() {
297
+ const active = this.#active;
298
+ if (active === undefined)
299
+ return;
300
+ this.#rejectSocketCameraCaptures(active);
301
+ await closeWebSocket(active, this.#options.closeGraceMs ?? DESKTOP_CLOSE_GRACE_MS);
302
+ this.#notifyDisconnected(active);
303
+ }
304
+ async start() {
305
+ if (this.#server !== undefined || this.#stopping) {
306
+ throw new Error('desktop server already started or stopped');
307
+ }
308
+ const server = new WebSocketServer({
309
+ host: '127.0.0.1',
310
+ port: 0,
311
+ maxPayload: MAX_CAMERA_WIRE_BYTES,
312
+ perMessageDeflate: false,
313
+ });
314
+ this.#server = server;
315
+ server.on('connection', (socket, request) => {
316
+ if (request.url === DESKTOP_DEBUG_PATH)
317
+ this.#acceptDebug(socket);
318
+ else if (request.url === '/')
319
+ this.#accept(socket);
320
+ else
321
+ socket.close(4004, 'desktop endpoint is unsupported');
322
+ });
323
+ await new Promise((resolve, reject) => {
324
+ server.once('listening', resolve);
325
+ server.once('error', reject);
326
+ });
327
+ const address = server.address();
328
+ if (address === null || typeof address === 'string') {
329
+ throw new Error('desktop loopback server did not bind');
330
+ }
331
+ return { token: this.#options.token, host: '127.0.0.1', port: address.port };
332
+ }
333
+ close() {
334
+ if (this.#closing !== undefined)
335
+ return this.#closing;
336
+ this.#stopping = true;
337
+ this.#closing = this.#close();
338
+ return this.#closing;
339
+ }
340
+ async #close() {
341
+ const server = this.#server;
342
+ this.#server = undefined;
343
+ const active = this.#active;
344
+ if (active !== undefined)
345
+ this.#rejectSocketCameraCaptures(active);
346
+ const activeClosed = active === undefined ? Promise.resolve() : closeWebSocket(active, this.#options.closeGraceMs ?? DESKTOP_CLOSE_GRACE_MS);
347
+ const debugClosed = [...this.#debugSockets].map(socket => closeWebSocket(socket, this.#options.closeGraceMs ?? DESKTOP_CLOSE_GRACE_MS));
348
+ if (server === undefined) {
349
+ await Promise.all([activeClosed, ...debugClosed]);
350
+ this.#notifyDisconnected(active);
351
+ return;
352
+ }
353
+ const serverClosed = new Promise((resolve, reject) => {
354
+ server.close(error => error === undefined ? resolve() : reject(error));
355
+ });
356
+ await Promise.all([activeClosed, ...debugClosed, serverClosed]);
357
+ this.#notifyDisconnected(active);
358
+ }
359
+ #acceptDebug(socket) {
360
+ if (this.#stopping
361
+ || this.#options.onDebugBoardRequest === undefined
362
+ || this.#debugSockets.size >= MAX_DESKTOP_DEBUG_CONNECTIONS) {
363
+ socket.close(4009, 'desktop debug client unavailable');
364
+ return;
365
+ }
366
+ this.#debugSockets.add(socket);
367
+ socket.on('error', error => { void error; });
368
+ let authenticated = false;
369
+ let requestStarted = false;
370
+ let terminal = false;
371
+ let inboundBytes = 0;
372
+ let processing = Promise.resolve();
373
+ const reject = () => {
374
+ if (terminal)
375
+ return;
376
+ terminal = true;
377
+ if (socket.readyState < WebSocket.CLOSING) {
378
+ socket.close(4003, 'desktop debug protocol rejected');
379
+ }
380
+ };
381
+ let phaseTimer = setTimeout(reject, this.#options.authTimeoutMs);
382
+ const resetPhaseTimer = () => {
383
+ clearTimeout(phaseTimer);
384
+ phaseTimer = setTimeout(reject, this.#options.authTimeoutMs);
385
+ };
386
+ socket.on('message', (data, isBinary) => {
387
+ const frameBytes = rawDataByteLength(data);
388
+ if (isBinary || inboundBytes + frameBytes > MAX_DESKTOP_JSON_BYTES) {
389
+ reject();
390
+ return;
391
+ }
392
+ inboundBytes += frameBytes;
393
+ processing = processing.then(async () => {
394
+ if (terminal)
395
+ return;
396
+ const raw = rawText(data);
397
+ if (!authenticated) {
398
+ authenticateDesktopFrame(raw, this.#options.token);
399
+ authenticated = true;
400
+ resetPhaseTimer();
401
+ return;
402
+ }
403
+ if (requestStarted)
404
+ throw new DesktopProtocolError('desktop debug request already started');
405
+ const request = parseDebugBoardRequest(raw);
406
+ requestStarted = true;
407
+ resetPhaseTimer();
408
+ const response = await this.#options.onDebugBoardRequest(request);
409
+ if (terminal)
410
+ return;
411
+ validateDebugBoardResponse(response, request);
412
+ await sendWebSocketFrame(socket, response);
413
+ if (terminal)
414
+ return;
415
+ terminal = true;
416
+ clearTimeout(phaseTimer);
417
+ if (socket.readyState < WebSocket.CLOSING)
418
+ socket.close(1000, 'debug complete');
419
+ }).catch(() => reject()).finally(() => {
420
+ inboundBytes -= frameBytes;
421
+ });
422
+ });
423
+ socket.once('close', () => {
424
+ terminal = true;
425
+ clearTimeout(phaseTimer);
426
+ this.#debugSockets.delete(socket);
427
+ });
428
+ }
429
+ #accept(socket) {
430
+ if (this.#active !== undefined || this.#stopping) {
431
+ socket.close(4009, 'desktop client already connected');
432
+ return;
433
+ }
434
+ this.#active = socket;
435
+ const generation = ++this.#connectionGeneration;
436
+ // `ws` reports protocol and max-payload failures through this event before
437
+ // closing the peer. The close code remains the renderer-visible verdict.
438
+ socket.on('error', error => { void error; });
439
+ let authenticated = false;
440
+ let controlsReady = false;
441
+ let rejected = false;
442
+ let processing = Promise.resolve();
443
+ const authTimer = setTimeout(() => socket.close(4003, 'desktop protocol rejected'), this.#options.authTimeoutMs);
444
+ socket.on('message', (data, isBinary) => {
445
+ const inboundBytes = rawDataByteLength(data);
446
+ if (this.#inboundBytes + inboundBytes > MAX_DESKTOP_INBOUND_BYTES) {
447
+ rejected = true;
448
+ socket.close(4003, 'desktop protocol rejected');
449
+ return;
450
+ }
451
+ this.#inboundBytes += inboundBytes;
452
+ // Personal commands include stopping voice and creating a text conversation. They
453
+ // must not wait for PCM delivery to a slow provider. Authentication and generation
454
+ // fences still run below; audio-routing controls retain their original queue order.
455
+ let personal = false;
456
+ if (controlsReady && !isBinary) {
457
+ try {
458
+ personal = parseDesktopControl(rawText(data)).type === 'personal.command';
459
+ }
460
+ catch { /* normal parser rejects below */ }
461
+ }
462
+ const operation = (personal ? Promise.resolve() : processing).then(async () => {
463
+ // One rejection is terminal. Without this latch a peer could keep
464
+ // guessing tokens on the same socket in the window before close settles.
465
+ if (rejected)
466
+ return;
467
+ // The callback may have waited behind an asynchronous operation from this peer.
468
+ // A newer authenticated socket must never inherit the old peer's queued authority.
469
+ if (this.#active !== socket || this.#connectionGeneration !== generation
470
+ || socket.readyState !== WebSocket.OPEN)
471
+ return;
472
+ if (!authenticated) {
473
+ if (isBinary)
474
+ throw new DesktopProtocolError('desktop authentication frame must be text');
475
+ authenticateDesktopFrame(rawText(data), this.#options.token);
476
+ const language = parsePromptLanguage(JSON.parse(rawText(data)).language);
477
+ authenticated = true;
478
+ this.#authenticated = true;
479
+ clearTimeout(authTimer);
480
+ for (const frame of this.#options.bootstrapTextFrames ?? []) {
481
+ await this.#enqueueSend(socket, frame);
482
+ }
483
+ if (this.#active !== socket || this.#connectionGeneration !== generation
484
+ || socket.readyState !== WebSocket.OPEN)
485
+ return;
486
+ await this.#options.onClientAuthenticated?.(language);
487
+ controlsReady = true;
488
+ return;
489
+ }
490
+ if (isBinary) {
491
+ const binary = rawBinaryBytes(data);
492
+ if (hasCameraFrameMagic(binary)) {
493
+ this.#receiveCameraFrame(socket, generation, binary);
494
+ return;
495
+ }
496
+ const pcm = validateAndCopyPcm(binary);
497
+ if (pcm.byteLength === 0 || pcm.byteLength % 2 !== 0) {
498
+ throw new DesktopProtocolError('desktop input must be aligned PCM16 bytes');
499
+ }
500
+ try {
501
+ await this.#options.onAudio?.(pcm);
502
+ }
503
+ catch {
504
+ // The renderer frame is already fully validated here. A provider can be temporarily
505
+ // unavailable while its session reconnects; that host-side delivery failure drops only
506
+ // this PCM frame and must not be reclassified as a renderer protocol violation.
507
+ }
508
+ return;
509
+ }
510
+ const raw = rawText(data);
511
+ const cameraError = maybeCameraError(raw);
512
+ if (cameraError !== undefined) {
513
+ this.#receiveCameraError(socket, generation, cameraError.request_id);
514
+ return;
515
+ }
516
+ const cameraPermission = maybeCameraPermissionResult(raw);
517
+ if (cameraPermission !== undefined) {
518
+ this.#receiveCameraPermission(socket, generation, cameraPermission.request_id, cameraPermission.status);
519
+ return;
520
+ }
521
+ const control = parseDesktopControl(raw);
522
+ try {
523
+ await this.#options.onControl?.(control);
524
+ }
525
+ catch {
526
+ // Control parsing succeeded, so a host-side failure (for example cancellation while the
527
+ // provider reconnects) is not evidence that the renderer violated the desktop protocol.
528
+ }
529
+ }).catch(() => {
530
+ rejected = true;
531
+ socket.close(4003, 'desktop protocol rejected');
532
+ }).finally(() => {
533
+ this.#inboundBytes -= inboundBytes;
534
+ });
535
+ if (!personal)
536
+ processing = operation;
537
+ });
538
+ socket.once('close', () => {
539
+ clearTimeout(authTimer);
540
+ this.#notifyDisconnected(socket);
541
+ });
542
+ }
543
+ #notifyDisconnected(socket) {
544
+ if (socket === undefined)
545
+ return;
546
+ this.#rejectSocketCameraCaptures(socket);
547
+ if (this.#active !== socket)
548
+ return;
549
+ this.#active = undefined;
550
+ this.#authenticated = false;
551
+ this.#rejectSocketSends(socket, outboundUnavailableError());
552
+ try {
553
+ this.#options.onClientDisconnect?.();
554
+ }
555
+ catch {
556
+ // Disconnect observation cannot own the socket writer or process lifetime.
557
+ }
558
+ }
559
+ #canSend() {
560
+ return !this.#stopping && this.#active !== undefined && this.#authenticated;
561
+ }
562
+ #enqueueSend(socket, raw) {
563
+ if (this.#pendingSendCount >= MAX_DESKTOP_PENDING_SENDS) {
564
+ return Promise.reject(new DesktopProtocolError('desktop outbound send queue is full'));
565
+ }
566
+ this.#pendingSendCount += 1;
567
+ const pending = new PendingDesktopSend(socket, raw);
568
+ this.#pendingSends.push(pending);
569
+ void this.#drainSends();
570
+ return pending.promise;
571
+ }
572
+ async #drainSends() {
573
+ if (this.#writerRunning)
574
+ return;
575
+ this.#writerRunning = true;
576
+ try {
577
+ while (this.#pendingSends.length > 0) {
578
+ const pending = this.#pendingSends.shift();
579
+ this.#currentSend = pending;
580
+ if (this.#active !== pending.socket || !this.#authenticated || this.#stopping) {
581
+ this.#settleSend(pending, outboundUnavailableError());
582
+ this.#currentSend = undefined;
583
+ continue;
584
+ }
585
+ try {
586
+ await sendWebSocketFrame(pending.socket, pending.raw);
587
+ this.#settleSend(pending);
588
+ }
589
+ catch {
590
+ this.#settleSend(pending, new DesktopProtocolError('desktop outbound send failed'));
591
+ this.#closeFailedSocket(pending.socket);
592
+ }
593
+ this.#currentSend = undefined;
594
+ }
595
+ }
596
+ finally {
597
+ this.#writerRunning = false;
598
+ if (this.#pendingSends.length > 0)
599
+ void this.#drainSends();
600
+ }
601
+ }
602
+ #settleSend(pending, error) {
603
+ if (pending.settled)
604
+ return;
605
+ pending.settled = true;
606
+ this.#pendingSendCount -= 1;
607
+ if (error === undefined)
608
+ pending.resolve();
609
+ else
610
+ pending.reject(error);
611
+ }
612
+ #rejectSocketSends(socket, error) {
613
+ if (this.#currentSend?.socket === socket)
614
+ this.#settleSend(this.#currentSend, error);
615
+ for (const pending of this.#pendingSends) {
616
+ if (pending.socket === socket)
617
+ this.#settleSend(pending, error);
618
+ }
619
+ }
620
+ #closeFailedSocket(socket) {
621
+ this.#notifyDisconnected(socket);
622
+ if (socket.readyState < WebSocket.CLOSING) {
623
+ socket.close(4003, 'desktop protocol rejected');
624
+ }
625
+ }
626
+ #receiveCameraFrame(socket, generation, raw) {
627
+ const frame = decodeCameraFrame(raw);
628
+ const pending = this.#ownedCameraCapture(frame.request_id, socket, generation);
629
+ if (pending === undefined)
630
+ return;
631
+ this.#settleCameraCapture(pending);
632
+ pending.resolve({
633
+ payload: new Uint8Array(frame.payload),
634
+ media_type: 'image/jpeg',
635
+ width: CAMERA_WIDTH,
636
+ height: CAMERA_HEIGHT,
637
+ });
638
+ }
639
+ #receiveCameraError(socket, generation, requestId) {
640
+ const pending = this.#ownedCameraCapture(requestId, socket, generation);
641
+ if (pending === undefined)
642
+ return;
643
+ this.#rejectCameraCapture(pending, cameraUnavailableError());
644
+ }
645
+ #ownedCameraCapture(requestId, socket, generation) {
646
+ const pending = this.#pendingCamera.get(requestId);
647
+ if (pending === undefined) {
648
+ const lateOwner = this.#lateCameraIds.get(requestId);
649
+ if (lateOwner !== undefined) {
650
+ if (lateOwner.socket === socket && lateOwner.generation === generation)
651
+ return undefined;
652
+ throw new DesktopProtocolError('desktop camera response has wrong owner');
653
+ }
654
+ throw new DesktopProtocolError('desktop camera response is unsolicited');
655
+ }
656
+ if (pending.socket !== socket || pending.generation !== generation) {
657
+ throw new DesktopProtocolError('desktop camera response has wrong owner');
658
+ }
659
+ return pending;
660
+ }
661
+ #settleCameraCapture(pending) {
662
+ if (this.#pendingCamera.get(pending.requestId) !== pending)
663
+ return;
664
+ this.#pendingCamera.delete(pending.requestId);
665
+ const timer = this.#options.cameraTimer ?? defaultCameraTimer;
666
+ if (pending.timerHandle !== undefined)
667
+ timer.clear(pending.timerHandle);
668
+ }
669
+ #rejectCameraCapture(pending, error) {
670
+ if (this.#pendingCamera.get(pending.requestId) !== pending)
671
+ return;
672
+ this.#settleCameraCapture(pending);
673
+ pending.reject(error);
674
+ }
675
+ #rejectSocketCameraCaptures(socket) {
676
+ for (const pending of [...this.#pendingCamera.values()]) {
677
+ if (pending.socket === socket)
678
+ this.#rejectCameraCapture(pending, cameraUnavailableError());
679
+ }
680
+ if (this.#pendingCameraPermission?.socket === socket) {
681
+ this.#rejectCameraPermission(this.#pendingCameraPermission);
682
+ }
683
+ }
684
+ #receiveCameraPermission(socket, generation, requestId, status) {
685
+ const pending = this.#pendingCameraPermission;
686
+ if (pending?.requestId !== requestId) {
687
+ const lateOwner = this.#lateCameraIds.get(requestId);
688
+ if (lateOwner?.socket === socket && lateOwner.generation === generation)
689
+ return;
690
+ throw new DesktopProtocolError('desktop camera permission response is unsolicited');
691
+ }
692
+ if (pending.socket !== socket || pending.generation !== generation) {
693
+ throw new DesktopProtocolError('desktop camera permission response has wrong owner');
694
+ }
695
+ this.#settleCameraPermission(pending);
696
+ pending.resolve(status);
697
+ }
698
+ #settleCameraPermission(pending) {
699
+ if (this.#pendingCameraPermission !== pending)
700
+ return;
701
+ this.#pendingCameraPermission = undefined;
702
+ const timer = this.#options.cameraTimer ?? defaultCameraTimer;
703
+ if (pending.timerHandle !== undefined)
704
+ timer.clear(pending.timerHandle);
705
+ }
706
+ #rejectCameraPermission(pending) {
707
+ if (this.#pendingCameraPermission !== pending)
708
+ return;
709
+ this.#settleCameraPermission(pending);
710
+ pending.reject(cameraUnavailableError());
711
+ }
712
+ #rememberLateCameraId(pending) {
713
+ this.#lateCameraIds.set(pending.requestId, {
714
+ socket: pending.socket,
715
+ generation: pending.generation,
716
+ });
717
+ this.#lateCameraOrder.push(pending.requestId);
718
+ while (this.#lateCameraOrder.length > MAX_CAMERA_LATE_RESPONSES) {
719
+ const oldest = this.#lateCameraOrder.shift();
720
+ if (oldest !== undefined)
721
+ this.#lateCameraIds.delete(oldest);
722
+ }
723
+ }
724
+ }
725
+ class PendingDesktopSend {
726
+ socket;
727
+ raw;
728
+ promise;
729
+ settled = false;
730
+ resolve;
731
+ reject;
732
+ constructor(socket, raw) {
733
+ this.socket = socket;
734
+ this.raw = raw;
735
+ let resolve;
736
+ let reject;
737
+ this.promise = new Promise((promiseResolve, promiseReject) => {
738
+ resolve = promiseResolve;
739
+ reject = promiseReject;
740
+ });
741
+ this.resolve = resolve;
742
+ this.reject = reject;
743
+ }
744
+ }
745
+ class PendingCameraCapture {
746
+ requestId;
747
+ socket;
748
+ generation;
749
+ promise;
750
+ resolve;
751
+ reject;
752
+ timerHandle;
753
+ constructor(requestId, socket, generation) {
754
+ this.requestId = requestId;
755
+ this.socket = socket;
756
+ this.generation = generation;
757
+ let resolve;
758
+ let reject;
759
+ this.promise = new Promise((promiseResolve, promiseReject) => {
760
+ resolve = promiseResolve;
761
+ reject = promiseReject;
762
+ });
763
+ this.resolve = resolve;
764
+ this.reject = reject;
765
+ }
766
+ }
767
+ class PendingCameraPermission {
768
+ requestId;
769
+ socket;
770
+ generation;
771
+ promise;
772
+ resolve;
773
+ reject;
774
+ timerHandle;
775
+ constructor(requestId, socket, generation) {
776
+ this.requestId = requestId;
777
+ this.socket = socket;
778
+ this.generation = generation;
779
+ let resolve;
780
+ let reject;
781
+ this.promise = new Promise((promiseResolve, promiseReject) => {
782
+ resolve = promiseResolve;
783
+ reject = promiseReject;
784
+ });
785
+ this.resolve = resolve;
786
+ this.reject = reject;
787
+ }
788
+ }
789
+ const defaultCameraTimer = {
790
+ set: (delayMs, callback) => setTimeout(callback, delayMs),
791
+ clear: handle => clearTimeout(handle),
792
+ };
793
+ export function validateDesktopToken(token) {
794
+ if (!tokenPattern.test(token)) {
795
+ throw new DesktopProtocolError('desktop token must be 128-bit lowercase hexadecimal');
796
+ }
797
+ }
798
+ function copyBootstrapTextFrames(frames) {
799
+ const copied = [...(frames ?? DEFAULT_BOOTSTRAP_TEXT_FRAMES)];
800
+ for (const frame of copied)
801
+ validateOutboundText(frame, 'desktop bootstrap frame');
802
+ return copied;
803
+ }
804
+ const personalOutboundEnvelopeSchema = z.discriminatedUnion('type', [
805
+ z.object({ type: z.literal('personal.state'), revision: z.number().int().nonnegative() }),
806
+ z.object({ type: z.literal('personal.result'), request_id: z.string().min(1).max(128), ok: z.boolean() }),
807
+ ]);
808
+ function validateOutboundText(raw, label = 'desktop outbound text frame') {
809
+ if (typeof raw !== 'string') {
810
+ throw new DesktopOutboundValidationError(`${label} is invalid`);
811
+ }
812
+ const bytes = Buffer.byteLength(raw, 'utf8');
813
+ if (bytes <= MAX_DESKTOP_JSON_BYTES)
814
+ return;
815
+ let value;
816
+ try {
817
+ value = JSON.parse(raw);
818
+ }
819
+ catch {
820
+ throw new DesktopOutboundValidationError(`${label} is too large`);
821
+ }
822
+ const envelope = personalOutboundEnvelopeSchema.safeParse(value);
823
+ if (!envelope.success)
824
+ throw new DesktopOutboundValidationError(`${label} is too large`);
825
+ if (bytes > MAX_DESKTOP_PERSONAL_JSON_BYTES) {
826
+ throw new DesktopPersonalFrameTooLargeError(envelope.data.type, bytes, envelope.data.type === 'personal.result' ? envelope.data.request_id : undefined);
827
+ }
828
+ }
829
+ function parseDebugBoardRequest(raw) {
830
+ let value;
831
+ try {
832
+ value = JSON.parse(raw);
833
+ }
834
+ catch {
835
+ throw new DesktopProtocolError('desktop debug request is invalid');
836
+ }
837
+ const parsed = debugBoardRequestSchema.safeParse(value);
838
+ if (!parsed.success)
839
+ throw new DesktopProtocolError('desktop debug request is invalid');
840
+ return parsed.data;
841
+ }
842
+ function validateDebugBoardResponse(raw, request) {
843
+ if (typeof raw !== 'string' || Buffer.byteLength(raw, 'utf8') > MAX_BOARD_MESSAGE_BYTES) {
844
+ throw new DesktopOutboundValidationError('desktop debug response is invalid');
845
+ }
846
+ let value;
847
+ try {
848
+ value = JSON.parse(raw);
849
+ }
850
+ catch {
851
+ throw new DesktopOutboundValidationError('desktop debug response is invalid');
852
+ }
853
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
854
+ throw new DesktopOutboundValidationError('desktop debug response is invalid');
855
+ }
856
+ const response = value;
857
+ const expectedType = 'memory.board';
858
+ if (response.type !== expectedType || response.request_id !== request.request_id) {
859
+ throw new DesktopOutboundValidationError('desktop debug response is invalid');
860
+ }
861
+ }
862
+ function validateOutboundBinary(raw) {
863
+ if (!(raw instanceof Uint8Array)) {
864
+ throw new DesktopProtocolError('desktop outbound binary frame is invalid');
865
+ }
866
+ if (raw.byteLength > MAX_DESKTOP_OUTBOUND_BINARY_BYTES) {
867
+ throw new DesktopProtocolError('desktop outbound binary frame is too large');
868
+ }
869
+ }
870
+ function outboundUnavailableError() {
871
+ return new DesktopProtocolError('desktop outbound send is unavailable');
872
+ }
873
+ function cameraUnavailableError() {
874
+ return new DesktopCameraError('capture_unavailable');
875
+ }
876
+ function validateCameraCaptureRequest(request) {
877
+ if (typeof request !== 'object' || request === null) {
878
+ throw new DesktopCameraError('invalid_request');
879
+ }
880
+ if (request.source === 'local') {
881
+ if (request.positionMs !== undefined)
882
+ throw new DesktopCameraError('invalid_request');
883
+ return;
884
+ }
885
+ if (request.source !== 'file'
886
+ || typeof request.positionMs !== 'number'
887
+ || !Number.isFinite(request.positionMs)
888
+ || !Number.isInteger(request.positionMs)
889
+ || request.positionMs < 0
890
+ || request.positionMs > MAX_CAMERA_POSITION_MS) {
891
+ throw new DesktopCameraError('invalid_request');
892
+ }
893
+ }
894
+ function maybeCameraError(raw) {
895
+ let value;
896
+ try {
897
+ value = JSON.parse(raw);
898
+ }
899
+ catch {
900
+ return undefined;
901
+ }
902
+ if (typeof value !== 'object' || value === null || Array.isArray(value)
903
+ || value.type !== 'camera.error')
904
+ return undefined;
905
+ return parseCameraError(raw);
906
+ }
907
+ function maybeCameraPermissionResult(raw) {
908
+ let value;
909
+ try {
910
+ value = JSON.parse(raw);
911
+ }
912
+ catch {
913
+ return undefined;
914
+ }
915
+ if (typeof value !== 'object' || value === null || Array.isArray(value)
916
+ || value.type !== 'camera.permission_result')
917
+ return undefined;
918
+ return parseCameraPermissionResult(raw);
919
+ }
920
+ function sendWebSocketFrame(socket, raw) {
921
+ return new Promise((resolve, reject) => {
922
+ socket.send(raw, { binary: typeof raw !== 'string' }, error => {
923
+ if (error == null)
924
+ resolve();
925
+ else
926
+ reject(error);
927
+ });
928
+ });
929
+ }
930
+ export function authenticateDesktopFrame(raw, expectedToken) {
931
+ validateDesktopToken(expectedToken);
932
+ const value = parseBoundedJson(raw);
933
+ const parsed = helloSchema.safeParse(value);
934
+ if (!parsed.success || !safeTokenEqual(parsed.data.token, expectedToken)) {
935
+ throw new DesktopProtocolError('desktop authentication failed');
936
+ }
937
+ }
938
+ export function parseDesktopControl(raw) {
939
+ const value = parseBoundedJson(raw);
940
+ const result = desktopControlSchema.safeParse(value);
941
+ if (!result.success) {
942
+ if (typeof value === 'object'
943
+ && value !== null
944
+ && !Array.isArray(value)) {
945
+ const type = value.type;
946
+ if (type === 'playback.telemetry')
947
+ return { type: 'playback.telemetry_rejected' };
948
+ }
949
+ throw new DesktopProtocolError('desktop control frame is unsupported');
950
+ }
951
+ return result.data;
952
+ }
953
+ export function parseReadyEndpoint(raw) {
954
+ const match = readyEndpointPattern.exec(stripLikePython(raw));
955
+ const port = match === null ? 0 : Number(match[1]);
956
+ if (port < 1 || port > 65_535) {
957
+ throw new DesktopProtocolError('desktop readiness endpoint is invalid');
958
+ }
959
+ return { host: '127.0.0.1', port };
960
+ }
961
+ export async function announceReadiness(endpoint, readiness, input = DESKTOP_READY_TIMEOUT_MS) {
962
+ const timeoutMs = typeof input === 'number' ? input : (input.timeoutMs ?? DESKTOP_READY_TIMEOUT_MS);
963
+ const signal = typeof input === 'number' ? undefined : input.signal;
964
+ validateDesktopToken(readiness.token);
965
+ if (readiness.host !== '127.0.0.1' || !Number.isInteger(readiness.port)
966
+ || readiness.port < 1 || readiness.port > 65_535) {
967
+ throw new DesktopProtocolError('desktop readiness payload is invalid');
968
+ }
969
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
970
+ throw new DesktopProtocolError('desktop readiness timeout is invalid');
971
+ }
972
+ if (signal?.aborted === true) {
973
+ throw new DesktopProtocolError('desktop readiness announcement cancelled');
974
+ }
975
+ const target = parseReadyEndpoint(endpoint);
976
+ const line = `${JSON.stringify(readiness)}\n`;
977
+ await new Promise((resolve, reject) => {
978
+ const socket = createConnection(target);
979
+ let settled = false;
980
+ let writeStarted = false;
981
+ const finish = (error) => {
982
+ if (settled)
983
+ return;
984
+ settled = true;
985
+ clearTimeout(timer);
986
+ signal?.removeEventListener('abort', onAbort);
987
+ if (error === undefined)
988
+ resolve();
989
+ else
990
+ reject(error);
991
+ };
992
+ const onAbort = () => {
993
+ // Once the whole line has been handed to Socket.end it cannot be reliably withdrawn. Keep
994
+ // observing that write: reporting "cancelled" after the parent may have accepted readiness
995
+ // would make the two processes disagree about whether startup committed.
996
+ if (writeStarted)
997
+ return;
998
+ socket.destroy();
999
+ finish(new DesktopProtocolError('desktop readiness announcement cancelled'));
1000
+ };
1001
+ // The commit point is the completion callback for this process's one line write, not a close from
1002
+ // the parent. The parent is allowed to hold its side open after it has accepted the complete line.
1003
+ const timer = setTimeout(() => {
1004
+ socket.destroy();
1005
+ finish(new DesktopProtocolError('desktop readiness announcement timed out'));
1006
+ }, timeoutMs);
1007
+ signal?.addEventListener('abort', onAbort, { once: true });
1008
+ if (signal?.aborted === true)
1009
+ onAbort();
1010
+ socket.once('error', error => finish(error));
1011
+ socket.once('connect', () => {
1012
+ if (signal?.aborted === true) {
1013
+ onAbort();
1014
+ return;
1015
+ }
1016
+ writeStarted = true;
1017
+ socket.end(line, () => {
1018
+ finish();
1019
+ socket.destroy();
1020
+ });
1021
+ });
1022
+ });
1023
+ }
1024
+ function parseBoundedJson(raw) {
1025
+ if (Buffer.byteLength(raw, 'utf8') > MAX_DESKTOP_JSON_BYTES) {
1026
+ throw new DesktopProtocolError('desktop control frame is too large');
1027
+ }
1028
+ try {
1029
+ return JSON.parse(raw);
1030
+ }
1031
+ catch {
1032
+ throw new DesktopProtocolError('desktop control frame is invalid JSON');
1033
+ }
1034
+ }
1035
+ function safeTokenEqual(candidate, expected) {
1036
+ const candidateBytes = Buffer.from(candidate, 'utf8');
1037
+ const expectedBytes = Buffer.from(expected, 'utf8');
1038
+ return candidateBytes.length === expectedBytes.length
1039
+ && timingSafeEqual(candidateBytes, expectedBytes);
1040
+ }
1041
+ function rawText(data) {
1042
+ return Buffer.isBuffer(data)
1043
+ ? data.toString('utf8')
1044
+ : Buffer.concat(Array.isArray(data) ? data : [Buffer.from(data)]).toString('utf8');
1045
+ }
1046
+ function rawDataByteLength(data) {
1047
+ if (Array.isArray(data))
1048
+ return data.reduce((total, chunk) => total + chunk.byteLength, 0);
1049
+ return data.byteLength;
1050
+ }
1051
+ function rawBinaryBytes(data) {
1052
+ const bytes = Buffer.isBuffer(data)
1053
+ ? data
1054
+ : Buffer.concat(Array.isArray(data) ? data : [Buffer.from(data)]);
1055
+ return new Uint8Array(bytes);
1056
+ }
1057
+ function validateAndCopyPcm(bytes) {
1058
+ if (bytes.byteLength > MAX_DESKTOP_PCM_BYTES) {
1059
+ throw new DesktopProtocolError('desktop input PCM frame is too large');
1060
+ }
1061
+ // Copy rather than view. `ws` allocates receive buffers from a shared pool, so
1062
+ // a view would alias bytes that a later frame overwrites, and the realtime
1063
+ // uplink holds PCM across await points before it reaches a provider.
1064
+ return new Uint8Array(bytes);
1065
+ }
1066
+ async function closeWebSocket(socket, graceMs) {
1067
+ if (socket.readyState === WebSocket.CLOSED)
1068
+ return;
1069
+ await new Promise(resolve => {
1070
+ let settled = false;
1071
+ const finish = () => {
1072
+ if (settled)
1073
+ return;
1074
+ settled = true;
1075
+ clearTimeout(timer);
1076
+ resolve();
1077
+ };
1078
+ socket.once('close', finish);
1079
+ const timer = setTimeout(() => {
1080
+ socket.terminate();
1081
+ finish();
1082
+ }, graceMs);
1083
+ if (socket.readyState < WebSocket.CLOSING)
1084
+ socket.close(1001, 'shutdown');
1085
+ });
1086
+ }
1087
+ export * from './config/capability-registry.js';
1088
+ export { probeMcpServer } from './executors/mcp-client.js';
1089
+ export { SensitiveContentPolicy } from './memory/sensitivity.js';
1090
+ export { FeishuConnector } from './connectors/feishu/index.js';
1091
+ export { probeAcceptanceGate, acceptanceRuntimeHash, allowAcceptanceLoopback, installAcceptanceGate, loadAcceptanceManifest, assertAcceptanceUrl, assertOriginalProfilePaths, acceptanceProfileHash, acceptanceManifest, acceptanceCounts, appendAcceptanceCounts } from './desktop/workbench-acceptance.js';
1092
+ //# sourceMappingURL=desktop.js.map