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,2106 @@
1
+ import { randomUUID, createHash } from 'node:crypto';
2
+ import { DesktopTasks, executorTasksSchema, taskActionResultSchema, taskActionSchema, openTaskDirectory, } from './desktop-tasks.js';
3
+ import { EXECUTOR_RESULT, EXECUTOR_RESULTS_RESET, DESKTOP_ACTIVITY, CLOCK_PING, CAPTION, PLAYBACK_TERMINAL, DesktopProtocolError as DesktopWireProtocolError, captionMessage, executorApprovalMessage, projectStateMessage, executorStateMessage, decodeAudioFrame, encodeAudioFrame, playbackAlertMessage, playbackClearMessage, playbackTerminalMessage, parseJsonWithIntegerFields, validateInputPcm, DESKTOP_READY, deliveryToEvent, } from './desktop-wire.js';
4
+ import {} from '../core/clock.js';
5
+ import { connectionDiagnosticSchema, playbackTelemetrySchema, DesktopOutboundValidationError, DesktopPersonalFrameTooLargeError, MAX_DESKTOP_PERSONAL_JSON_BYTES, DesktopProtocolError, NodeDesktopServer, parseReadyEndpoint, validateDesktopToken, } from '../desktop.js';
6
+ import {} from '../realtime/playback.js';
7
+ import {} from '../realtime/session-state.js';
8
+ import {} from '../realtime/service-state.js';
9
+ import {} from '../core/approval-port.js';
10
+ import {} from '../realtime/telemetry.js';
11
+ import { DictationError, pcmLevel } from '../realtime/dictation.js';
12
+ import { codePointLengthLikePython, stripLikePython } from '../text/python-text.js';
13
+ import { executorProgressSchema, executorResultSchema, projectExecutorEvent, projectExecutorSuggestion, } from './desktop-progress.js';
14
+ import { executorWithRole } from '../executors/coding-executor.js';
15
+ import { memoryBoardMessage } from '../realtime/memory-board.js';
16
+ import {} from './desktop-camera.js';
17
+ import {} from '../composition/realtime-assembly.js';
18
+ import {} from '../projects/project-confirmation.js';
19
+ import {} from '../core/suggestions.js';
20
+ export const DEFAULT_MAX_OUTBOUND_FRAMES = 128;
21
+ export class DesktopSocketBridge {
22
+ #token;
23
+ #service;
24
+ #stop;
25
+ #maxOutboundFrames;
26
+ #clock;
27
+ #telemetry;
28
+ #onOutboundAvailable;
29
+ /** Audio, captions, terminals. Bounded; a non-droppable overflow stops the transport. */
30
+ #outbound = [];
31
+ /** Clears and alerts. Drained before `#outbound` so a clear overtakes the audio it cancels. */
32
+ #preemptOutbound = [];
33
+ /** Single-slot: only the latest state matters, and a backlog of stale ones is worse than none. */
34
+ #executorOutbound = null;
35
+ #executor;
36
+ #projectOutbound = null;
37
+ #approvalOutbound = null;
38
+ #progressMode;
39
+ #progressSummaries = new Map();
40
+ // ponytail: 64 session entries; refuse new tracking when every slot is live.
41
+ #results = new Map();
42
+ #resultReplay = [];
43
+ tasks;
44
+ #tasksOutbound = null;
45
+ /**
46
+ * The highest generation the renderer has been told to clear.
47
+ *
48
+ * Anything at or below it is audio for a turn the agent has abandoned. Monotonic, because a clear for
49
+ * an older generation arriving late must not un-fence a newer one.
50
+ */
51
+ #fencedGenerationEpoch = 0;
52
+ #latestPlaybackGenerationEpoch = 0;
53
+ #captionSequence = 0;
54
+ #latestAssistantCaptionSequence = 0;
55
+ /** Assistant captions at or below this belong to a cleared turn. */
56
+ #fencedAssistantCaptionSequence = 0;
57
+ #inputInstanceId = randomUUID();
58
+ #textReceipts = new Map();
59
+ #draftInput = false;
60
+ #dictation;
61
+ #claimed = false;
62
+ #authenticated = false;
63
+ #everAuthenticated = false;
64
+ #executorState;
65
+ #lastExecutorStateSent = null;
66
+ #projectView;
67
+ #lastProjectViewSent = null;
68
+ #approvalExecutor;
69
+ #approvalView;
70
+ #lastApprovalViewSent = null;
71
+ #uplinkFrames = 0;
72
+ #uplinkBytes = 0;
73
+ #uplinkFlushedAt;
74
+ #pingSent = new Map();
75
+ #firstFrameSeen = null;
76
+ #playbackTelemetryRejected = 0;
77
+ #conversationService;
78
+ #voiceService;
79
+ #ownsAudio;
80
+ #voiceConversation;
81
+ #sendConversationAudio;
82
+ #submitConversationText;
83
+ #validateConversationInput;
84
+ constructor(options) {
85
+ this.#conversationService = options.conversationService;
86
+ this.#voiceService = options.voiceService;
87
+ this.#ownsAudio = options.ownsAudio ?? (() => true);
88
+ this.#sendConversationAudio = options.sendConversationAudio;
89
+ this.#submitConversationText = options.submitConversationText;
90
+ this.#validateConversationInput = options.validateConversationInput;
91
+ // 128 bits of hex, exactly. A shorter token is a weaker one, and a longer one means the caller is
92
+ // passing something other than what this expects.
93
+ if (options.token.length !== 32 || !/^[0-9a-fA-F]+$/u.test(options.token)) {
94
+ throw new TypeError('desktop token must be 128-bit hexadecimal');
95
+ }
96
+ this.#token = options.token;
97
+ this.#service = options.service;
98
+ this.#stop = options.stop;
99
+ this.#maxOutboundFrames = options.maxOutboundFrames ?? DEFAULT_MAX_OUTBOUND_FRAMES;
100
+ this.#clock = options.clock;
101
+ // Telemetry needs a clock to be worth anything: every sample it takes is a duration.
102
+ this.#telemetry = options.clock === undefined ? undefined : options.telemetry;
103
+ this.#onOutboundAvailable = options.onOutboundAvailable;
104
+ this.#executorState = options.service.executorState;
105
+ this.#projectView = options.projectView ?? null;
106
+ this.#approvalView = options.approvalView ?? null;
107
+ this.#approvalExecutor = options.approvalView?.executorIdentity ?? options.executor ?? null;
108
+ this.#progressMode = options.progressBubbles ?? 'milestones';
109
+ this.#executor = options.executor ?? null;
110
+ this.tasks = new DesktopTasks(this.#executor?.executor ?? null);
111
+ if (this.#projectView !== null)
112
+ this.tasks.project(this.#projectView);
113
+ this.#uplinkFlushedAt = options.clock?.now() ?? 0;
114
+ }
115
+ // -----------------------------------------------------------------------------------------------
116
+ // Outbound: what the runtime hands the renderer.
117
+ // -----------------------------------------------------------------------------------------------
118
+ onAudioFrame(frame) {
119
+ this.#latestPlaybackGenerationEpoch = Math.max(this.#latestPlaybackGenerationEpoch, frame.generation_epoch);
120
+ if (frame.generation_epoch <= this.#fencedGenerationEpoch)
121
+ return;
122
+ const sent = this.#enqueue(encodeAudioFrame(frame));
123
+ if (!sent || this.#telemetry === undefined || frame.sequence !== 0)
124
+ return;
125
+ // First frame of a generation only: the metric is time-to-first-audio, and a re-sent sequence zero
126
+ // for the same generation is the transport retrying rather than a new turn starting.
127
+ const key = `${frame.utterance_id}:${frame.generation_epoch}`;
128
+ if (this.#firstFrameSeen === key)
129
+ return;
130
+ this.#firstFrameSeen = key;
131
+ this.#telemetry.record('playback.first_frame_enqueued', {
132
+ utterance_id: frame.utterance_id,
133
+ generation_epoch: frame.generation_epoch,
134
+ });
135
+ }
136
+ /**
137
+ * Tell the renderer to drop a generation's audio.
138
+ *
139
+ * Raises the fence before enqueueing, so anything already waiting behind this in the audio queue is
140
+ * recognised as stale when the sender reaches it. Enqueued on the preempt queue, because a clear that
141
+ * waited behind the audio it cancels is not a clear.
142
+ */
143
+ onAudioClear(utteranceId, generationEpoch) {
144
+ this.#fencedGenerationEpoch = Math.max(this.#fencedGenerationEpoch, generationEpoch);
145
+ this.#fencedAssistantCaptionSequence = Math.max(this.#fencedAssistantCaptionSequence, this.#latestAssistantCaptionSequence);
146
+ const sent = this.#enqueuePreempt(playbackClearMessage(utteranceId, generationEpoch));
147
+ if (sent) {
148
+ this.#telemetry?.record('playback.clear_sent', {
149
+ utterance_id: utteranceId,
150
+ generation_epoch: generationEpoch,
151
+ });
152
+ }
153
+ }
154
+ /**
155
+ * Tell the renderer playback stalled.
156
+ *
157
+ * Fences the same way a clear does even when the alert carries no generation: an alert means the
158
+ * agent's audio is not reaching the user, and continuing to send it would be sending sound nobody
159
+ * hears into a turn that has already gone wrong.
160
+ */
161
+ onAudioAlert(utteranceId, generationEpoch) {
162
+ const message = playbackAlertMessage(utteranceId, generationEpoch);
163
+ if (generationEpoch !== null) {
164
+ this.#fencedGenerationEpoch = Math.max(this.#fencedGenerationEpoch, generationEpoch);
165
+ }
166
+ this.#fencedAssistantCaptionSequence = Math.max(this.#fencedAssistantCaptionSequence, this.#latestAssistantCaptionSequence);
167
+ const sent = this.#enqueuePreempt(message);
168
+ if (sent) {
169
+ this.#telemetry?.record('renderer.alert_tone_sent', {
170
+ generation_qualified: generationEpoch !== null,
171
+ });
172
+ }
173
+ }
174
+ onAudioTerminal(utteranceId, generationEpoch) {
175
+ this.#latestPlaybackGenerationEpoch = Math.max(this.#latestPlaybackGenerationEpoch, generationEpoch);
176
+ this.#enqueue(playbackTerminalMessage(utteranceId, generationEpoch));
177
+ }
178
+ /**
179
+ * The Codex state changed.
180
+ *
181
+ * Validated eagerly so a bad state is a caller error here rather than a malformed frame later. An
182
+ * in-flight send is cancelled: the renderer wants the *current* state, and finishing a send of the
183
+ * previous one first would show something already untrue.
184
+ */
185
+ onExecutorState(state) {
186
+ if (this.#executor !== null)
187
+ executorStateMessage(state, this.#executor);
188
+ if (state === this.#executorState)
189
+ return;
190
+ this.#executorState = state;
191
+ this.#syncExecutorStateDelivery();
192
+ }
193
+ onActivity(idle) {
194
+ if (this.#authenticated)
195
+ this.#enqueue(JSON.stringify({ type: DESKTOP_ACTIVITY, idle }), { droppable: true });
196
+ }
197
+ onProjectView(view) {
198
+ projectStateMessage(view);
199
+ if (sameProjectView(view, this.#projectView))
200
+ return;
201
+ this.#projectView = view;
202
+ this.tasks.project(view);
203
+ this.#syncTasks();
204
+ for (const entry of view.roster ?? [])
205
+ for (const work of entry.running) {
206
+ const retained = this.#results.get(work.work_id);
207
+ if (retained?.result === null) {
208
+ retained.project = entry.name;
209
+ retained.title = work.title;
210
+ }
211
+ }
212
+ this.#syncProjectDelivery();
213
+ }
214
+ onExecutorApproval(view) {
215
+ const identity = view.executorIdentity ?? (view.pending_approval ? this.#executor : this.#approvalExecutor);
216
+ if (identity !== null)
217
+ executorApprovalMessage(view, this.#clock?.now() ?? 0, identity);
218
+ this.#approvalExecutor = identity;
219
+ if (sameApprovalView(view, this.#approvalView))
220
+ return;
221
+ this.#telemetry?.record('approval.desktop_view', {
222
+ pending: view.pending_approval,
223
+ approval_id: view.pending_approval_id ?? null,
224
+ connected: this.#authenticated,
225
+ executor_available: this.#executor !== null,
226
+ });
227
+ this.#approvalView = view;
228
+ this.#syncApprovalDelivery();
229
+ }
230
+ /**
231
+ * Transcript text, speculative or final.
232
+ *
233
+ * Droppable, and the only thing here that is: a lost caption is a cosmetic gap, while a lost audio
234
+ * frame leaves the renderer's playback state wrong in a way it cannot detect.
235
+ */
236
+ onCaption(frame) {
237
+ this.#captionSequence += 1;
238
+ if (frame.role === 'assistant') {
239
+ this.#latestAssistantCaptionSequence = this.#captionSequence;
240
+ }
241
+ this.#enqueue(captionMessage(frame, this.#captionSequence), { droppable: !frame.final || frame.full_text === undefined });
242
+ }
243
+ onExecutorProgress(input, result) {
244
+ const frame = executorProgressSchema.parse(input);
245
+ const revision = this.tasks.snapshot().revision;
246
+ this.tasks.progress(frame);
247
+ if (this.#projectView !== null)
248
+ this.tasks.project(this.#projectView);
249
+ if (this.tasks.snapshot().revision !== revision)
250
+ this.#syncTasks();
251
+ if (result !== undefined) {
252
+ const parsed = executorResultSchema.parse({ type: EXECUTOR_RESULT, work_id: frame.delegate_id, result });
253
+ const previous = this.#results.get(frame.delegate_id);
254
+ const project = this.#projectView?.roster?.find(entry => entry.running.some(work => work.work_id === frame.delegate_id));
255
+ const title = frame.title ?? project?.running.find(work => work.work_id === frame.delegate_id)?.title ?? previous?.title;
256
+ const projectName = frame.project ?? project?.name ?? previous?.project;
257
+ const retained = { ...(projectName === undefined ? {} : { project: projectName }), ...(title === undefined ? {} : { title }) };
258
+ const enriched = parsed.result === null ? null : { ...parsed.result, ...retained };
259
+ // Validate metadata too before changing retained state; serialization stays one bounded work per frame.
260
+ const wire = executorResultSchema.parse({ type: EXECUTOR_RESULT, work_id: frame.delegate_id, result: enriched });
261
+ if (Buffer.byteLength(JSON.stringify(wire)) > MAX_DESKTOP_JSON_BYTES)
262
+ throw new DesktopWireProtocolError('desktop result frame is too large');
263
+ const oldestFinished = [...this.#results].find(([, entry]) => entry.result !== null)?.[0];
264
+ if (previous === undefined && this.#results.size >= 64 && oldestFinished === undefined) {
265
+ this.#telemetry?.record('desktop.result_retention_full', {});
266
+ }
267
+ else {
268
+ if (previous === undefined && this.#results.size >= 64)
269
+ this.#results.delete(oldestFinished);
270
+ this.#results.set(frame.delegate_id, { result: wire.result, ...retained });
271
+ this.#replayResults();
272
+ }
273
+ }
274
+ if (result !== undefined && result !== null)
275
+ this.#progressSummaries.delete(frame.delegate_id);
276
+ if (this.#progressMode === 'off' || this.#progressMode === 'milestones' && frame.level === 'detail')
277
+ return;
278
+ if (frame.level === 'detail') {
279
+ if (this.#progressSummaries.get(frame.delegate_id) === frame.summary)
280
+ return;
281
+ if (this.#progressSummaries.size >= 64)
282
+ this.#progressSummaries.delete(this.#progressSummaries.keys().next().value);
283
+ this.#progressSummaries.set(frame.delegate_id, frame.summary);
284
+ }
285
+ this.#enqueue(JSON.stringify(frame), { droppable: true });
286
+ }
287
+ // -----------------------------------------------------------------------------------------------
288
+ // Connection ownership.
289
+ // -----------------------------------------------------------------------------------------------
290
+ /** One renderer at a time. A second connection is refused rather than replacing the first. */
291
+ claim() {
292
+ if (this.#claimed)
293
+ return false;
294
+ this.#claimed = true;
295
+ return true;
296
+ }
297
+ release() {
298
+ this.#cancelDictation();
299
+ this.#draftInput = false;
300
+ this.#voiceConversation = undefined;
301
+ this.#claimed = false;
302
+ this.#authenticated = false;
303
+ this.#fencedGenerationEpoch = Math.max(this.#fencedGenerationEpoch, this.#latestPlaybackGenerationEpoch);
304
+ this.#outbound.length = 0;
305
+ this.#preemptOutbound.length = 0;
306
+ this.#pingSent.clear();
307
+ this.#firstFrameSeen = null;
308
+ this.#fencePlaybackForConnectionBoundary();
309
+ // The next renderer has been told nothing, so both latches reset -- otherwise it would never
310
+ // receive the current state, having "already been sent" it.
311
+ this.#lastExecutorStateSent = null;
312
+ this.#lastProjectViewSent = null;
313
+ this.#lastApprovalViewSent = null;
314
+ this.#executorOutbound = null;
315
+ this.#projectOutbound = null;
316
+ this.#approvalOutbound = null;
317
+ this.#progressSummaries.clear();
318
+ this.#resultReplay = [];
319
+ this.#tasksOutbound = null;
320
+ }
321
+ /** Mark the connection authenticated, which is what unblocks the single-slot queues. */
322
+ onPersonalFrame(frame) { if (this.#authenticated)
323
+ this.#enqueue(JSON.stringify(frame)); }
324
+ markAuthenticated() {
325
+ if (this.#everAuthenticated) {
326
+ this.#fencePlaybackForConnectionBoundary({ resumeDelivery: true });
327
+ }
328
+ this.#authenticated = true;
329
+ this.#everAuthenticated = true;
330
+ if (this.#service.inputCapabilities !== undefined)
331
+ this.onPersonalFrame({ type: 'desktop.capabilities', capabilities: this.#service.inputCapabilities, input_instance_id: this.#inputInstanceId });
332
+ this.#syncExecutorStateDelivery();
333
+ this.#syncProjectDelivery();
334
+ this.#syncApprovalDelivery();
335
+ this.#syncTasks();
336
+ if (this.#results.size > 0)
337
+ this.#replayResults();
338
+ }
339
+ #syncTasks() {
340
+ this.#tasksOutbound = JSON.stringify(executorTasksSchema.parse(this.tasks.snapshot()));
341
+ if (this.#authenticated)
342
+ this.#onOutboundAvailable?.();
343
+ }
344
+ onTaskActionResult(result) {
345
+ if (this.#authenticated)
346
+ this.#enqueue(JSON.stringify(taskActionResultSchema.parse(result)));
347
+ }
348
+ #replayResults() {
349
+ // A fresh snapshot also removes evicted entries from a connected renderer. Never aggregate 64 results into one frame.
350
+ this.#resultReplay = [JSON.stringify({ type: EXECUTOR_RESULTS_RESET }), ...[...this.#results].map(([work_id, entry]) => JSON.stringify({ type: EXECUTOR_RESULT, work_id, result: entry.result }))];
351
+ if (this.#authenticated)
352
+ this.#onOutboundAvailable?.();
353
+ }
354
+ #fencePlaybackForConnectionBoundary(options = {}) {
355
+ if (!this.#ownsAudio())
356
+ return;
357
+ void (this.#voiceService?.() ?? this.#service).playbackDisconnected(options).catch(() => {
358
+ this.#telemetry?.record('desktop.playback_disconnect_failed', {});
359
+ });
360
+ }
361
+ // -----------------------------------------------------------------------------------------------
362
+ // Inbound: what the renderer tells the runtime.
363
+ // -----------------------------------------------------------------------------------------------
364
+ /**
365
+ * Handle one frame from the renderer.
366
+ *
367
+ * Binary is microphone PCM and text is control. Before authentication only one text frame is
368
+ * accepted, and only if it authenticates -- so nothing reaches the runtime on an unproven connection.
369
+ */
370
+ async receive(raw, options) {
371
+ if (!options.authenticated) {
372
+ if (typeof raw !== 'string') {
373
+ throw new DesktopWireProtocolError('desktop authentication frame must be text');
374
+ }
375
+ parseClientMessage(raw, { expectedToken: this.#token, authenticated: false });
376
+ return true;
377
+ }
378
+ if (typeof raw !== 'string') {
379
+ await this.receiveAudio(raw);
380
+ return true;
381
+ }
382
+ const command = parseClientMessage(raw, { expectedToken: this.#token, authenticated: true });
383
+ await this.#receiveCommand(command);
384
+ return true;
385
+ }
386
+ async receiveAudio(raw) {
387
+ this.#recordUplink(raw.length);
388
+ const pcm = validateInputPcm(raw);
389
+ if (this.#dictation) {
390
+ const draft = this.#dictation;
391
+ if (draft.finishing)
392
+ return;
393
+ if (draft.size + pcm.length > 16000 * 2 * 60) {
394
+ this.#cancelDictation();
395
+ throw new Error('dictation too long');
396
+ }
397
+ draft.chunks.push(pcm.slice());
398
+ draft.size += pcm.length;
399
+ return;
400
+ }
401
+ if (!this.#draftInput) {
402
+ this.#validateConversationInput?.('audio', this.#voiceConversation);
403
+ if (this.#voiceConversation) {
404
+ if (!this.#sendConversationAudio)
405
+ throw Error('voice_unavailable');
406
+ await this.#sendConversationAudio(this.#voiceConversation, pcm);
407
+ }
408
+ else
409
+ await this.#service.sendAudio(pcm);
410
+ }
411
+ }
412
+ async receiveControl(control) {
413
+ if (control.type === 'input.audio') {
414
+ this.#validateConversationInput?.('audio', control.conversation_id);
415
+ this.#voiceConversation = control.conversation_id;
416
+ if (this.#dictation)
417
+ throw new Error('dictation active');
418
+ this.#draftInput = false;
419
+ return;
420
+ }
421
+ if (control.type === 'input.dictation') {
422
+ if (control.action === 'start')
423
+ this.#validateConversationInput?.('dictation', control.conversation_id);
424
+ this.#dictationControl(control.id, control.action, control.conversation_id);
425
+ return;
426
+ }
427
+ if (control.type === 'input.text') {
428
+ const submit = async () => {
429
+ if (this.#dictation)
430
+ throw new Error('dictation active');
431
+ if (control.conversation_id) {
432
+ if (!this.#submitConversationText)
433
+ throw Error('conversation_runtime_unavailable');
434
+ await this.#submitConversationText(control.conversation_id, control.text, control.request_id, control.source_todo);
435
+ return;
436
+ }
437
+ if (!this.#service.submitText)
438
+ throw new Error('text input unavailable');
439
+ await this.#service.submitText(control.text);
440
+ };
441
+ if (control.request_id === undefined) {
442
+ await submit();
443
+ return;
444
+ }
445
+ const id = control.request_id;
446
+ const result = (ok, error) => ({ type: 'input.text_result', request_id: id, ok, ...(control.conversation_id ? { conversation_id: control.conversation_id } : {}), ...(error === undefined ? {} : { error }) });
447
+ let receipt;
448
+ const hash = createHash('sha256').update(JSON.stringify([control.conversation_id ?? null, control.text, control.source_todo ?? null])).digest('hex');
449
+ const prior = this.#textReceipts.get(id);
450
+ if (control.input_instance_id !== undefined && control.input_instance_id !== this.#inputInstanceId)
451
+ receipt = result(false, 'outcome_unknown');
452
+ else if (prior)
453
+ receipt = prior.hash === hash ? await prior.result : result(false, 'request_id_conflict');
454
+ else if (this.#textReceipts.size >= 256)
455
+ receipt = result(false, 'request_capacity');
456
+ else {
457
+ // Record before calling the provider. Reconnect retries share this exact operation.
458
+ const operation = Promise.resolve().then(submit).then(() => result(true), () => result(false, 'submission_failed'));
459
+ this.#textReceipts.set(id, { hash, result: operation });
460
+ receipt = await operation;
461
+ }
462
+ if (this.#authenticated)
463
+ this.#enqueue(JSON.stringify(receipt));
464
+ return;
465
+ }
466
+ await this.#receiveCommand(commandFromControl(control));
467
+ }
468
+ #cancelDictation() {
469
+ if (!this.#dictation)
470
+ return;
471
+ clearTimeout(this.#dictation.timer);
472
+ this.#dictation.controller.abort();
473
+ this.#dictation = undefined;
474
+ }
475
+ #dictationControl(id, action, conversationId) {
476
+ if (action === 'cancel') {
477
+ if (this.#dictation?.id === id)
478
+ this.#cancelDictation();
479
+ return;
480
+ }
481
+ if (!this.#service.transcribeDraft)
482
+ throw new Error('dictation unavailable');
483
+ if (action === 'start') {
484
+ this.#draftInput = true;
485
+ if (this.#dictation)
486
+ throw new Error('dictation active');
487
+ const controller = new AbortController();
488
+ const timer = setTimeout(() => { if (this.#dictation?.controller === controller)
489
+ this.#cancelDictation(); }, 90000);
490
+ this.#dictation = { id, ...(conversationId ? { conversationId } : {}), chunks: [], size: 0, finishing: false, controller, timer };
491
+ return;
492
+ }
493
+ const draft = this.#dictation;
494
+ if (draft?.id !== id || draft.finishing)
495
+ throw new Error('stale dictation');
496
+ draft.finishing = true;
497
+ const pcm = Buffer.concat(draft.chunks);
498
+ draft.chunks = [];
499
+ void this.#service.transcribeDraft(pcm, AbortSignal.any([draft.controller.signal, AbortSignal.timeout(30000)]))
500
+ .then(text => { if (this.#dictation === draft)
501
+ this.#enqueue(JSON.stringify({ type: 'input.transcription', id, ...(draft.conversationId ? { conversation_id: draft.conversationId } : {}), text })); })
502
+ .catch((error) => {
503
+ if (this.#dictation !== draft)
504
+ return;
505
+ const level = pcmLevel(pcm);
506
+ try {
507
+ this.#telemetry?.record('dictation.failed', { bytes: pcm.length, peak: level.peak, rms: level.rms, error: (error instanceof Error ? error.message : String(error)).replace(/[\r\n]/gu, ' ').slice(0, 200) });
508
+ }
509
+ catch { /* the failure frame below must reach the client even when the telemetry disk cannot be written */ }
510
+ this.#enqueue(JSON.stringify({ type: 'input.transcription', id, ...(draft.conversationId ? { conversation_id: draft.conversationId } : {}), error: error instanceof DictationError ? error.code : 'recognition_failed' }));
511
+ })
512
+ .finally(() => { if (this.#dictation === draft)
513
+ this.#cancelDictation(); });
514
+ }
515
+ async #receiveCommand(command) {
516
+ if (['speech_onset', 'playback_started', 'playback_stopped', 'playback_done', 'playback_cleared'].includes(command.kind) && !this.#ownsAudio())
517
+ return;
518
+ if (this.#telemetry !== undefined
519
+ && command.kind !== 'playback_telemetry'
520
+ && command.kind !== 'playback_telemetry_rejected'
521
+ && command.kind !== 'connection_diagnostic') {
522
+ this.#telemetry.record('renderer.ack', { kind: command.kind, ...command.payload });
523
+ }
524
+ switch (command.kind) {
525
+ case 'connection_diagnostic': {
526
+ const { phase, ...payload } = command.payload;
527
+ const kind = phase === 'closed'
528
+ ? 'desktop.connection_closed'
529
+ : phase === 'reconnect_attempt'
530
+ ? 'desktop.reconnect_attempt'
531
+ : 'desktop.reconnect_result';
532
+ this.#telemetry?.record(kind, payload);
533
+ return;
534
+ }
535
+ case 'playback_telemetry_rejected':
536
+ this.#playbackTelemetryRejected += 1;
537
+ this.#telemetry?.record('playback.telemetry_rejected', {
538
+ count: this.#playbackTelemetryRejected,
539
+ });
540
+ return;
541
+ case 'playback_telemetry':
542
+ this.#telemetry?.record('playback.native', command.payload);
543
+ return;
544
+ case 'clock_pong':
545
+ this.#recordSyncSample(String(command.payload.ping_id), Number(command.payload.t_render_ms));
546
+ return;
547
+ case 'speech_onset':
548
+ await (this.#voiceService?.() ?? this.#service).localSpeechOnset(String(command.payload.speech_id));
549
+ return;
550
+ case 'playback_started':
551
+ (this.#voiceService?.() ?? this.#service).playbackStarted(String(command.payload.utterance_id), Number(command.payload.generation_epoch));
552
+ return;
553
+ case 'playback_done':
554
+ (this.#voiceService?.() ?? this.#service).playbackDone(String(command.payload.utterance_id), Number(command.payload.generation_epoch), optionalPlayedMs(command.payload));
555
+ return;
556
+ case 'playback_stopped':
557
+ await (this.#voiceService?.() ?? this.#service).playbackStopped(String(command.payload.utterance_id), Number(command.payload.generation_epoch), optionalPlayedMs(command.payload));
558
+ return;
559
+ case 'playback_cleared':
560
+ (this.#voiceService?.() ?? this.#service).playbackCleared(String(command.payload.utterance_id), Number(command.payload.generation_epoch), optionalPlayedMs(command.payload));
561
+ return;
562
+ case 'project_confirmation_decision': {
563
+ const proposalId = command.payload.proposal_id;
564
+ if (typeof proposalId !== 'string')
565
+ return;
566
+ const target = typeof command.payload.conversation_id === 'string' ? this.#conversationService?.(command.payload.conversation_id) : this.#service;
567
+ if (!target)
568
+ return;
569
+ await target.projectConfirmationDecision(proposalId, command.payload.confirmed === true);
570
+ return;
571
+ }
572
+ case 'executor_approval_decision': {
573
+ const approvalId = command.payload.approval_id;
574
+ // A decision names its executor; one that names another executor is not ours to relay.
575
+ // Conversation-owned coding approvals keep the fixed executor even after a phone approval was shown,
576
+ // but a decision naming the coding executor never answers the phone approval on the main surface.
577
+ const executor = command.payload.executor;
578
+ const shown = this.#approvalView;
579
+ const answersOther = shown?.pending_approval === true && shown.pending_approval_id === approvalId
580
+ && shown.executorIdentity !== undefined && shown.executorIdentity.executor !== executor;
581
+ if (typeof approvalId !== 'string' || answersOther
582
+ || (executor !== this.#approvalExecutor?.executor && executor !== this.#executor?.executor))
583
+ return;
584
+ const target = typeof command.payload.conversation_id === 'string' ? this.#conversationService?.(command.payload.conversation_id) : this.#service;
585
+ if (!target)
586
+ return;
587
+ target.executorApprovalDecision(approvalId, command.payload.approved === true, command.payload.scope === 'session' ? 'session' : undefined);
588
+ return;
589
+ }
590
+ default:
591
+ return;
592
+ }
593
+ }
594
+ // -----------------------------------------------------------------------------------------------
595
+ // The send side.
596
+ // -----------------------------------------------------------------------------------------------
597
+ /**
598
+ * Take the next frame the renderer should receive, in priority order.
599
+ *
600
+ * Preempt before audio, then the two single-slot queues. Audio at or below the fence is dropped here
601
+ * rather than at enqueue time, because the fence can rise *after* a frame is queued -- which is the
602
+ * common case, since a clear is exactly what raises it.
603
+ */
604
+ takeNextFrame() {
605
+ return this.takeNextDelivery()?.frame ?? null;
606
+ }
607
+ /** Take the next frame together with the failure policy the sender must apply. */
608
+ takeNextDelivery() {
609
+ const preempt = this.#preemptOutbound.shift();
610
+ if (preempt !== undefined)
611
+ return preempt;
612
+ for (;;) {
613
+ const delivery = this.#outbound.shift();
614
+ if (delivery === undefined)
615
+ break;
616
+ if (!this.#isFencedPlaybackMessage(delivery.frame))
617
+ return delivery;
618
+ }
619
+ if (this.#executorOutbound !== null) {
620
+ const state = this.#executorOutbound;
621
+ this.#executorOutbound = null;
622
+ if (state !== this.#lastExecutorStateSent) {
623
+ this.#lastExecutorStateSent = state;
624
+ this.#syncExecutorStateDelivery();
625
+ if (this.#executor !== null)
626
+ return { frame: executorStateMessage(state, this.#executor), policy: 'latest' };
627
+ }
628
+ }
629
+ if (this.#projectOutbound !== null) {
630
+ const view = this.#projectOutbound;
631
+ this.#projectOutbound = null;
632
+ if (!sameProjectView(view, this.#lastProjectViewSent)) {
633
+ this.#lastProjectViewSent = view;
634
+ this.#syncProjectDelivery();
635
+ return { frame: projectStateMessage(view), policy: 'latest' };
636
+ }
637
+ }
638
+ if (this.#approvalOutbound !== null) {
639
+ const view = this.#approvalOutbound;
640
+ this.#approvalOutbound = null;
641
+ if (!sameApprovalView(view, this.#lastApprovalViewSent)) {
642
+ this.#lastApprovalViewSent = view;
643
+ this.#syncApprovalDelivery();
644
+ if (this.#approvalExecutor !== null) {
645
+ return { frame: executorApprovalMessage(view, this.#clock?.now() ?? 0, this.#approvalExecutor), policy: 'latest' };
646
+ }
647
+ }
648
+ }
649
+ if (this.#authenticated && this.#tasksOutbound !== null) {
650
+ const frame = this.#tasksOutbound;
651
+ this.#tasksOutbound = null;
652
+ return { frame, policy: 'latest' };
653
+ }
654
+ if (this.#authenticated && this.#resultReplay.length > 0) {
655
+ return { frame: this.#resultReplay.shift(), policy: 'latest' };
656
+ }
657
+ return null;
658
+ }
659
+ /**
660
+ * Whether this frame belongs to a turn the renderer has been told to drop.
661
+ *
662
+ * Cheap prefix test first: only two message shapes can be fenced, and parsing every caption to find
663
+ * out would be work on the hot path. Audio is checked by decoding its header, which is the only place
664
+ * its generation is written.
665
+ */
666
+ #isFencedPlaybackMessage(value) {
667
+ if (typeof value !== 'string') {
668
+ return decodeAudioFrame(value).generation_epoch <= this.#fencedGenerationEpoch;
669
+ }
670
+ if (!value.startsWith(`{"type":"${CAPTION}"`)
671
+ && !value.startsWith(`{"type":"${PLAYBACK_TERMINAL}"`)) {
672
+ return false;
673
+ }
674
+ let payload;
675
+ try {
676
+ payload = JSON.parse(value);
677
+ }
678
+ catch {
679
+ return false;
680
+ }
681
+ if (!isPlainObject(payload))
682
+ return false;
683
+ if (payload.type === 'caption') {
684
+ const sequence = payload.sequence;
685
+ // Only the assistant's: a user caption describes what the *user* said, which a fence about the
686
+ // agent's audio says nothing about.
687
+ return payload.role === 'assistant'
688
+ && typeof sequence === 'number'
689
+ && Number.isInteger(sequence)
690
+ && sequence <= this.#fencedAssistantCaptionSequence;
691
+ }
692
+ if (payload.type !== 'playback.terminal')
693
+ return false;
694
+ const generationEpoch = payload.generation_epoch;
695
+ return typeof generationEpoch === 'number'
696
+ && Number.isInteger(generationEpoch)
697
+ && generationEpoch <= this.#fencedGenerationEpoch;
698
+ }
699
+ #enqueue(value, options = {}) {
700
+ if (this.#everAuthenticated && !this.#authenticated)
701
+ return false;
702
+ if (this.#outbound.length >= this.#maxOutboundFrames) {
703
+ if (options.droppable !== true) {
704
+ const droppableIndex = this.#outbound.findIndex(delivery => delivery.policy === 'droppable');
705
+ if (droppableIndex >= 0)
706
+ this.#outbound.splice(droppableIndex, 1);
707
+ }
708
+ }
709
+ if (this.#outbound.length >= this.#maxOutboundFrames) {
710
+ // A dropped non-droppable frame leaves the renderer's picture of playback wrong in a way it
711
+ // cannot detect, so the transport stops rather than continuing to look healthy.
712
+ if (options.droppable !== true)
713
+ this.#stop.abort();
714
+ return false;
715
+ }
716
+ this.#outbound.push({ frame: value, policy: options.droppable === true ? 'droppable' : 'required' });
717
+ this.#onOutboundAvailable?.();
718
+ return true;
719
+ }
720
+ #enqueuePreempt(value) {
721
+ if (this.#everAuthenticated && !this.#authenticated)
722
+ return false;
723
+ if (this.#preemptOutbound.length >= this.#maxOutboundFrames) {
724
+ // Never droppable. A clear that does not arrive means the user keeps hearing an abandoned turn.
725
+ this.#stop.abort();
726
+ return false;
727
+ }
728
+ this.#preemptOutbound.push({ frame: value, policy: 'required' });
729
+ this.#onOutboundAvailable?.();
730
+ return true;
731
+ }
732
+ /** Re-arm the single slot if the renderer's state is still behind. */
733
+ #syncExecutorStateDelivery() {
734
+ const next = this.#authenticated && this.#executorState !== this.#lastExecutorStateSent
735
+ ? this.#executorState
736
+ : null;
737
+ if (next === this.#executorOutbound)
738
+ return;
739
+ this.#executorOutbound = next;
740
+ if (next !== null)
741
+ this.#onOutboundAvailable?.();
742
+ }
743
+ #syncProjectDelivery() {
744
+ const next = (this.#authenticated
745
+ && this.#projectView !== null
746
+ && !sameProjectView(this.#projectView, this.#lastProjectViewSent)) ? this.#projectView : null;
747
+ if (sameProjectView(next, this.#projectOutbound))
748
+ return;
749
+ this.#projectOutbound = next;
750
+ if (next !== null)
751
+ this.#onOutboundAvailable?.();
752
+ }
753
+ #syncApprovalDelivery() {
754
+ const next = (this.#authenticated
755
+ && this.#approvalView !== null
756
+ && !sameApprovalView(this.#approvalView, this.#lastApprovalViewSent)) ? this.#approvalView : null;
757
+ if (sameApprovalView(next, this.#approvalOutbound))
758
+ return;
759
+ this.#approvalOutbound = next;
760
+ if (next !== null)
761
+ this.#onOutboundAvailable?.();
762
+ }
763
+ // -----------------------------------------------------------------------------------------------
764
+ // Clock synchronisation and uplink accounting.
765
+ // -----------------------------------------------------------------------------------------------
766
+ registerPing(pingId) {
767
+ if (this.#clock !== undefined)
768
+ this.#pingSent.set(pingId, this.#clock.now());
769
+ }
770
+ /**
771
+ * Arm a round of clock pings.
772
+ *
773
+ * Several rather than one: a single round trip is dominated by whatever the renderer happened to be
774
+ * doing, and the useful figure is the minimum across a handful.
775
+ */
776
+ sendClockPings(count = 5) {
777
+ if (this.#clock === undefined || this.#telemetry === undefined)
778
+ return [];
779
+ const ids = [];
780
+ for (let index = 0; index < count; index += 1) {
781
+ const pingId = `ping-${index}`;
782
+ if (this.#enqueue(`{"type":"${CLOCK_PING}","ping_id":"${pingId}"}`, { droppable: true })) {
783
+ this.registerPing(pingId);
784
+ ids.push(pingId);
785
+ }
786
+ }
787
+ return ids;
788
+ }
789
+ #recordSyncSample(pingId, renderMs) {
790
+ const sentAt = this.#pingSent.get(pingId);
791
+ if (sentAt === undefined || this.#clock === undefined || this.#telemetry === undefined)
792
+ return;
793
+ this.#pingSent.delete(pingId);
794
+ const roundTrip = Math.max(0, this.#clock.now() - sentAt);
795
+ this.#telemetry.record('renderer.clock_sync', {
796
+ ping_id: pingId,
797
+ round_trip_ms: roundTrip * 1_000,
798
+ t_render_ms: renderMs,
799
+ });
800
+ }
801
+ #recordUplink(size) {
802
+ this.#uplinkFrames += 1;
803
+ this.#uplinkBytes += size;
804
+ }
805
+ /** Report accumulated uplink volume, once a second at most. */
806
+ flushUplink() {
807
+ if (this.#clock === undefined || this.#telemetry === undefined)
808
+ return;
809
+ if (this.#uplinkFrames === 0)
810
+ return;
811
+ const now = this.#clock.now();
812
+ if (now - this.#uplinkFlushedAt < 1)
813
+ return;
814
+ this.#telemetry.record('renderer.uplink', {
815
+ frames: this.#uplinkFrames,
816
+ bytes: this.#uplinkBytes,
817
+ elapsed: now - this.#uplinkFlushedAt,
818
+ });
819
+ this.#uplinkFrames = 0;
820
+ this.#uplinkBytes = 0;
821
+ this.#uplinkFlushedAt = now;
822
+ }
823
+ /** Read-only views, for assertions. */
824
+ get pendingCounts() {
825
+ return {
826
+ outbound: this.#outbound.length,
827
+ preempt: this.#preemptOutbound.length,
828
+ executor: this.#executorOutbound !== null,
829
+ project: this.#projectOutbound !== null,
830
+ approval: this.#approvalOutbound !== null,
831
+ };
832
+ }
833
+ get fencedGenerationEpoch() {
834
+ return this.#fencedGenerationEpoch;
835
+ }
836
+ }
837
+ /**
838
+ * Parse one renderer control frame.
839
+ *
840
+ * The size bound is checked on the *encoded* bytes before parsing, because a frame's cost is its
841
+ * length and the parse is what this is protecting.
842
+ */
843
+ export function parseClientMessage(raw, options) {
844
+ if (new TextEncoder().encode(raw).length > MAX_DESKTOP_JSON_BYTES) {
845
+ throw new DesktopWireProtocolError('desktop control frame is too large');
846
+ }
847
+ let preliminary;
848
+ try {
849
+ preliminary = JSON.parse(raw);
850
+ }
851
+ catch {
852
+ throw new DesktopWireProtocolError('desktop control frame is invalid JSON');
853
+ }
854
+ if (options.authenticated
855
+ && isPlainObject(preliminary)
856
+ && preliminary.type === 'playback.telemetry') {
857
+ try {
858
+ const telemetryValue = parseJsonWithIntegerFields(raw, [
859
+ 'generation_epoch',
860
+ 'window_ms',
861
+ 'queued_samples',
862
+ 'queued_samples_max',
863
+ 'underrun_samples',
864
+ 'underrun_callbacks',
865
+ 'max_consecutive_underrun_samples',
866
+ 'render_callbacks',
867
+ 'max_callback_us',
868
+ 'pcm_near_silence_ms_max',
869
+ 'sequence_gaps',
870
+ 'rejected_frames',
871
+ 'stdin_buffered_bytes_max',
872
+ 'stdin_backpressure_count',
873
+ ], () => new DesktopWireProtocolError('desktop playback telemetry is invalid'));
874
+ const result = playbackTelemetrySchema.safeParse(telemetryValue);
875
+ if (!result.success)
876
+ return { kind: 'playback_telemetry_rejected', payload: {} };
877
+ const { type, ...payload } = result.data;
878
+ void type;
879
+ return { kind: 'playback_telemetry', payload };
880
+ }
881
+ catch {
882
+ return { kind: 'playback_telemetry_rejected', payload: {} };
883
+ }
884
+ }
885
+ let value;
886
+ try {
887
+ // Only the fields the oracle type-checks as `int`. `t_render_ms` is deliberately absent: it accepts
888
+ // an int or a float there and coerces with `float()`, so both spellings are legal input.
889
+ value = parseJsonWithIntegerFields(raw, [
890
+ 'generation_epoch',
891
+ 'played_ms',
892
+ 'window_ms',
893
+ 'queued_samples',
894
+ 'queued_samples_max',
895
+ 'underrun_samples',
896
+ 'underrun_callbacks',
897
+ 'max_consecutive_underrun_samples',
898
+ 'render_callbacks',
899
+ 'max_callback_us',
900
+ 'pcm_near_silence_ms_max',
901
+ 'sequence_gaps',
902
+ 'rejected_frames',
903
+ 'stdin_buffered_bytes_max',
904
+ 'stdin_backpressure_count',
905
+ 'close_code',
906
+ 'attempt',
907
+ 'delay_ms',
908
+ ], field => new DesktopWireProtocolError(field === 'generation_epoch'
909
+ ? 'desktop playback generation is invalid'
910
+ : 'desktop playback played_ms is invalid'));
911
+ }
912
+ catch (cause) {
913
+ if (cause instanceof DesktopWireProtocolError)
914
+ throw cause;
915
+ throw new DesktopWireProtocolError('desktop control frame is invalid JSON');
916
+ }
917
+ if (!isPlainObject(value) || typeof value.type !== 'string') {
918
+ throw new DesktopWireProtocolError('desktop control frame has no type');
919
+ }
920
+ if (!options.authenticated) {
921
+ const token = value.token;
922
+ if (value.type !== 'hello'
923
+ || typeof token !== 'string'
924
+ || !constantTimeEqual(token, options.expectedToken)) {
925
+ throw new DesktopWireProtocolError('desktop authentication failed');
926
+ }
927
+ return { kind: 'authenticated', payload: {} };
928
+ }
929
+ const kind = value.type;
930
+ if (kind === 'speech.onset') {
931
+ const payload = { speech_id: readIdentifier(value, 'speech_id') };
932
+ readRenderTimestamp(value, payload);
933
+ return { kind: 'speech_onset', payload };
934
+ }
935
+ if (kind === 'playback.started'
936
+ || kind === 'playback.stopped'
937
+ || kind === 'playback.done'
938
+ || kind === 'playback.cleared') {
939
+ const utteranceId = readIdentifier(value, 'utterance_id');
940
+ const generationEpoch = value.generation_epoch;
941
+ if (typeof generationEpoch !== 'number'
942
+ || !Number.isInteger(generationEpoch)
943
+ || generationEpoch < 1) {
944
+ throw new DesktopWireProtocolError('desktop playback generation is invalid');
945
+ }
946
+ const payload = {
947
+ utterance_id: utteranceId,
948
+ generation_epoch: generationEpoch,
949
+ };
950
+ // `started` carries no duration: nothing has played yet, so a value there would be a claim about
951
+ // audio the renderer has not delivered.
952
+ if (kind !== 'playback.started') {
953
+ const playedMs = value.played_ms;
954
+ if (playedMs !== null && playedMs !== undefined) {
955
+ if (typeof playedMs !== 'number' || !Number.isInteger(playedMs) || playedMs < 0) {
956
+ throw new DesktopWireProtocolError('desktop playback played_ms is invalid');
957
+ }
958
+ payload.played_ms = playedMs;
959
+ }
960
+ }
961
+ readRenderTimestamp(value, payload);
962
+ return {
963
+ kind: kind.replace('.', '_'),
964
+ payload,
965
+ };
966
+ }
967
+ if (kind === 'project.confirmation_decision') {
968
+ if (Object.keys(value).sort().join(',') !== 'confirmed,proposal_id,type') {
969
+ throw new DesktopWireProtocolError('desktop control frame type is unsupported');
970
+ }
971
+ if (typeof value.confirmed !== 'boolean') {
972
+ throw new DesktopWireProtocolError('desktop project confirmation decision is invalid');
973
+ }
974
+ const proposalId = readIdentifier(value, 'proposal_id');
975
+ if (codePointLengthLikePython(proposalId) > 128) {
976
+ throw new DesktopWireProtocolError('desktop project confirmation decision is invalid');
977
+ }
978
+ return {
979
+ kind: 'project_confirmation_decision',
980
+ payload: { proposal_id: proposalId, confirmed: value.confirmed },
981
+ };
982
+ }
983
+ if (kind === 'executor.approval_decision') {
984
+ if (Object.keys(value).sort().join(',') !== (value.scope === undefined ? 'approval_id,approved,executor,type' : 'approval_id,approved,executor,scope,type')) {
985
+ throw new DesktopWireProtocolError('desktop control frame type is unsupported');
986
+ }
987
+ if (typeof value.approved !== 'boolean' || value.scope !== undefined && (value.scope !== 'session' || !value.approved)) {
988
+ throw new DesktopWireProtocolError('desktop executor approval decision is invalid');
989
+ }
990
+ const executor = readIdentifier(value, 'executor');
991
+ const approvalId = readIdentifier(value, 'approval_id');
992
+ if (codePointLengthLikePython(approvalId) > 128) {
993
+ throw new DesktopWireProtocolError('desktop executor approval decision is invalid');
994
+ }
995
+ return {
996
+ kind: 'executor_approval_decision',
997
+ payload: { executor, approval_id: approvalId, approved: value.approved, ...(value.scope === undefined ? {} : { scope: value.scope }) },
998
+ };
999
+ }
1000
+ if (kind === 'clock.pong') {
1001
+ const timestamp = value.t_render_ms;
1002
+ if (typeof timestamp !== 'number' || !Number.isFinite(timestamp) || timestamp < 0) {
1003
+ throw new DesktopWireProtocolError('desktop t_render_ms is invalid');
1004
+ }
1005
+ return {
1006
+ kind: 'clock_pong',
1007
+ payload: { ping_id: readIdentifier(value, 'ping_id'), t_render_ms: timestamp },
1008
+ };
1009
+ }
1010
+ if (kind === 'connection.diagnostic') {
1011
+ const result = connectionDiagnosticSchema.safeParse(value);
1012
+ if (!result.success) {
1013
+ throw new DesktopWireProtocolError('desktop connection diagnostic is invalid');
1014
+ }
1015
+ const { type, ...payload } = result.data;
1016
+ void type;
1017
+ return { kind: 'connection_diagnostic', payload };
1018
+ }
1019
+ throw new DesktopWireProtocolError('desktop control frame type is unsupported');
1020
+ }
1021
+ function commandFromControl(control) {
1022
+ switch (control.type) {
1023
+ case 'personal.command':
1024
+ case 'executor.task_action':
1025
+ case 'coding.progress_narration':
1026
+ throw new DesktopWireProtocolError('desktop host control requires authenticated transport');
1027
+ case 'speech.onset':
1028
+ return {
1029
+ kind: 'speech_onset',
1030
+ payload: withRenderTimestamp({ speech_id: control.speech_id }, control.t_render_ms),
1031
+ };
1032
+ case 'playback.started':
1033
+ return {
1034
+ kind: 'playback_started',
1035
+ payload: withRenderTimestamp({
1036
+ utterance_id: control.utterance_id,
1037
+ generation_epoch: control.generation_epoch,
1038
+ }, control.t_render_ms),
1039
+ };
1040
+ case 'playback.stopped':
1041
+ case 'playback.done':
1042
+ case 'playback.cleared': {
1043
+ const payload = withRenderTimestamp({
1044
+ utterance_id: control.utterance_id,
1045
+ generation_epoch: control.generation_epoch,
1046
+ }, control.t_render_ms);
1047
+ if (control.played_ms !== undefined)
1048
+ payload.played_ms = control.played_ms;
1049
+ return { kind: control.type.replace('.', '_'), payload };
1050
+ }
1051
+ case 'project.confirmation_decision':
1052
+ return {
1053
+ kind: 'project_confirmation_decision',
1054
+ payload: { proposal_id: control.proposal_id, confirmed: control.confirmed, ...(control.conversation_id ? { conversation_id: control.conversation_id } : {}) },
1055
+ };
1056
+ case 'executor.approval_decision':
1057
+ return {
1058
+ kind: 'executor_approval_decision',
1059
+ payload: { ...(control.conversation_id ? { conversation_id: control.conversation_id } : {}), executor: control.executor, approval_id: control.approval_id, approved: control.approved, ...(control.scope === undefined ? {} : { scope: control.scope }) },
1060
+ };
1061
+ case 'clock.pong':
1062
+ return {
1063
+ kind: 'clock_pong',
1064
+ payload: { ping_id: control.ping_id, t_render_ms: control.t_render_ms },
1065
+ };
1066
+ case 'connection.diagnostic': {
1067
+ const { type, ...payload } = control;
1068
+ void type;
1069
+ return { kind: 'connection_diagnostic', payload };
1070
+ }
1071
+ case 'playback.telemetry': {
1072
+ const { type, ...payload } = control;
1073
+ void type;
1074
+ return { kind: 'playback_telemetry', payload };
1075
+ }
1076
+ case 'playback.telemetry_rejected':
1077
+ return { kind: 'playback_telemetry_rejected', payload: {} };
1078
+ }
1079
+ }
1080
+ function withRenderTimestamp(payload, timestamp) {
1081
+ if (timestamp !== undefined)
1082
+ payload.t_render_ms = timestamp;
1083
+ return payload;
1084
+ }
1085
+ const MAX_DESKTOP_JSON_BYTES = 16 * 1_024;
1086
+ function readRenderTimestamp(value, payload) {
1087
+ const timestamp = value.t_render_ms;
1088
+ if (timestamp === undefined || timestamp === null)
1089
+ return;
1090
+ if (typeof timestamp !== 'number' || !Number.isFinite(timestamp) || timestamp < 0) {
1091
+ throw new DesktopWireProtocolError('desktop t_render_ms is invalid');
1092
+ }
1093
+ payload.t_render_ms = timestamp;
1094
+ }
1095
+ function readIdentifier(value, field) {
1096
+ const candidate = value[field];
1097
+ if (typeof candidate !== 'string'
1098
+ || stripLikePython(candidate) === ''
1099
+ || codePointLengthLikePython(candidate) > 256) {
1100
+ throw new DesktopWireProtocolError(`desktop ${field} is invalid`);
1101
+ }
1102
+ return candidate;
1103
+ }
1104
+ function optionalPlayedMs(payload) {
1105
+ const value = payload.played_ms;
1106
+ return value === undefined ? null : Number(value);
1107
+ }
1108
+ function sameProjectView(left, right) {
1109
+ if (left === null || right === null)
1110
+ return left === right;
1111
+ return left.workspace_display_name === right.workspace_display_name
1112
+ && left.session_title === right.session_title
1113
+ && left.pending_confirmation === right.pending_confirmation
1114
+ && left.pending_confirmation_busy === right.pending_confirmation_busy
1115
+ && left.pending_confirmation_id === right.pending_confirmation_id
1116
+ && (left.pending_action ?? null) === (right.pending_action ?? null)
1117
+ && (left.pending_workspace_display_name ?? null)
1118
+ === (right.pending_workspace_display_name ?? null)
1119
+ && (left.pending_session_title ?? null) === (right.pending_session_title ?? null)
1120
+ && (left.pending_expires_in_seconds ?? null) === (right.pending_expires_in_seconds ?? null)
1121
+ // Store-ordered and plain data, so the serialisation is a stable identity (spec 08 roster).
1122
+ && JSON.stringify(left.roster ?? []) === JSON.stringify(right.roster ?? []);
1123
+ }
1124
+ function sameApprovalView(left, right) {
1125
+ if (left === null || right === null)
1126
+ return left === right;
1127
+ return left.pending_approval === right.pending_approval
1128
+ && left.pending_approval_busy === right.pending_approval_busy
1129
+ && left.pending_approval_id === right.pending_approval_id
1130
+ && left.executorIdentity?.executor === right.executorIdentity?.executor
1131
+ && left.executorIdentity?.display_name === right.executorIdentity?.display_name
1132
+ && left.kind === right.kind
1133
+ && left.operation_summary === right.operation_summary
1134
+ && left.expires_at === right.expires_at
1135
+ && (left.held ?? false) === (right.held ?? false)
1136
+ && JSON.stringify(left.allowed_decisions) === JSON.stringify(right.allowed_decisions)
1137
+ && JSON.stringify(left.local_detail) === JSON.stringify(right.local_detail);
1138
+ }
1139
+ function isPlainObject(value) {
1140
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
1141
+ }
1142
+ /**
1143
+ * Compare two strings without leaking their contents through timing.
1144
+ *
1145
+ * The length is compared first and returns early, which is not a leak: the token's length is fixed and
1146
+ * public. What must not leak is *where* a wrong token first differs.
1147
+ */
1148
+ function constantTimeEqual(candidate, expected) {
1149
+ if (candidate.length !== expected.length)
1150
+ return false;
1151
+ let difference = 0;
1152
+ for (let index = 0; index < candidate.length; index += 1) {
1153
+ difference |= candidate.charCodeAt(index) ^ expected.charCodeAt(index);
1154
+ }
1155
+ return difference === 0;
1156
+ }
1157
+ const READY_FRAME = JSON.stringify({ type: DESKTOP_READY });
1158
+ /**
1159
+ * Owns the narrow connection-generation boundary between desktop policy and the socket writer.
1160
+ * Realtime service/provider construction intentionally lives elsewhere.
1161
+ */
1162
+ export class DesktopRealtime {
1163
+ bridge;
1164
+ server;
1165
+ serverOptions;
1166
+ #stop;
1167
+ #transportFailure;
1168
+ #onConnectionReleased;
1169
+ #telemetry;
1170
+ #discardInputAudio;
1171
+ #generation = 0;
1172
+ #activeGeneration = null;
1173
+ #drainRequested = false;
1174
+ #draining = false;
1175
+ constructor(options) {
1176
+ const { createServer, transportFailure, onConnectionReleased, memoryBoard, ...bridgeOptions } = options;
1177
+ this.#discardInputAudio = transportFailure === 'disconnect'
1178
+ ? async () => { if (options.ownsAudio?.() !== false)
1179
+ await (options.voiceService?.() ?? options.service).discardInputAudio?.(); } : undefined;
1180
+ this.#stop = options.stop;
1181
+ this.#transportFailure = transportFailure ?? 'abort';
1182
+ this.#onConnectionReleased = onConnectionReleased;
1183
+ this.#telemetry = options.telemetry;
1184
+ this.bridge = new DesktopSocketBridge({
1185
+ ...bridgeOptions,
1186
+ ...(transportFailure === 'disconnect' ? { stop: { abort: () => {
1187
+ const generation = this.#activeGeneration;
1188
+ if (generation === null)
1189
+ this.bridge.release();
1190
+ else
1191
+ void this.#disconnect(generation);
1192
+ } } } : {}),
1193
+ onOutboundAvailable: () => this.#requestDrain(),
1194
+ });
1195
+ this.serverOptions = {
1196
+ token: options.token,
1197
+ bootstrapTextFrames: [READY_FRAME],
1198
+ onClientAuthenticated: async (language) => {
1199
+ this.#authenticated();
1200
+ if (!options.preserveLanguage)
1201
+ await options.service.setLanguage?.(language);
1202
+ },
1203
+ onClientDisconnect: media => this.#disconnected(media?.hadProviderAttachment ?? true),
1204
+ onDebugBoardRequest: request => {
1205
+ if (memoryBoard === undefined)
1206
+ throw new DesktopProtocolError('desktop memory board is unavailable');
1207
+ return memoryBoard(request.request_id, request.detail, request);
1208
+ },
1209
+ onAudio: pcm => this.bridge.receiveAudio(pcm),
1210
+ onControl: async (control, context) => {
1211
+ const generation = this.#activeGeneration;
1212
+ if (generation === null)
1213
+ throw new DesktopProtocolError('desktop control is unauthenticated');
1214
+ if (control.type === 'personal.command') {
1215
+ const result = options.personalCommand ? await options.personalCommand(control, context ?? (transportFailure === 'disconnect' ? undefined : { client_id: 'desktop:local' })) : { type: 'personal.result', request_id: control.request_id, ok: false, error: 'unavailable' };
1216
+ if (this.#activeGeneration === generation) {
1217
+ this.bridge.onPersonalFrame(result);
1218
+ // Inspector reads must not publish state and trigger another inspector read.
1219
+ if (options.personalSnapshot && !['tasks.get', 'tasks.list'].includes(control.method))
1220
+ this.bridge.onPersonalFrame(options.personalSnapshot());
1221
+ }
1222
+ return;
1223
+ }
1224
+ if (control.type === 'coding.progress_narration') {
1225
+ options.service.setCodingProgressNarration?.(control.mode);
1226
+ return;
1227
+ }
1228
+ if (control.type !== 'executor.task_action')
1229
+ return this.bridge.receiveControl(control);
1230
+ const request = taskActionSchema.parse(control);
1231
+ // Folder resolution and native launch must not hold the serialized PCM input queue.
1232
+ void (async () => {
1233
+ let status = 'unavailable';
1234
+ try {
1235
+ if (this.bridge.tasks.has(request.work_id, request.executor) && options.taskPort !== undefined) {
1236
+ if (request.action === 'cancel')
1237
+ status = this.bridge.tasks.isRunning(request.work_id) ? options.taskPort.cancelTask(request.work_id) : 'not_running';
1238
+ else {
1239
+ const path = await options.taskPort.taskDirectory(request.work_id);
1240
+ if (this.#activeGeneration !== generation)
1241
+ return;
1242
+ if (path !== null) {
1243
+ await (options.openTaskDirectory ?? (target => openTaskDirectory(target, undefined, process.platform, () => this.#activeGeneration === generation)))(path);
1244
+ status = 'opened';
1245
+ }
1246
+ }
1247
+ }
1248
+ }
1249
+ catch {
1250
+ status = 'failed';
1251
+ }
1252
+ if (this.#activeGeneration === generation)
1253
+ this.bridge.onTaskActionResult({ type: 'executor.task_action_result', request_id: request.request_id, work_id: request.work_id, action: request.action, status });
1254
+ })();
1255
+ },
1256
+ };
1257
+ this.server = (createServer ?? (serverOptions => new NodeDesktopServer(serverOptions)))(this.serverOptions);
1258
+ }
1259
+ #authenticated() {
1260
+ if (!this.bridge.claim()) {
1261
+ throw new DesktopProtocolError('desktop bridge connection is unavailable');
1262
+ }
1263
+ this.#activeGeneration = ++this.#generation;
1264
+ this.bridge.markAuthenticated();
1265
+ this.#requestDrain();
1266
+ }
1267
+ #disconnected(hadProviderAttachment) {
1268
+ const generation = this.#activeGeneration;
1269
+ if (generation !== null)
1270
+ this.#release(generation, hadProviderAttachment);
1271
+ }
1272
+ #release(generation, hadProviderAttachment = true) {
1273
+ if (this.#activeGeneration !== generation)
1274
+ return;
1275
+ this.#activeGeneration = null;
1276
+ this.#generation += 1;
1277
+ if (hadProviderAttachment)
1278
+ void this.#discardInputAudio?.().catch(() => {
1279
+ this.#telemetry?.record('remote.input_reset_failed', {});
1280
+ });
1281
+ this.bridge.release();
1282
+ this.#onConnectionReleased?.();
1283
+ }
1284
+ #requestDrain() {
1285
+ this.#drainRequested = true;
1286
+ if (this.#activeGeneration !== null && !this.#draining)
1287
+ void this.#drain();
1288
+ }
1289
+ async #drain() {
1290
+ if (this.#draining)
1291
+ return;
1292
+ this.#draining = true;
1293
+ try {
1294
+ while (this.#activeGeneration !== null && this.#drainRequested) {
1295
+ this.#drainRequested = false;
1296
+ for (;;) {
1297
+ const generation = this.#activeGeneration;
1298
+ if (generation === null)
1299
+ break;
1300
+ const delivery = this.bridge.takeNextDelivery();
1301
+ if (delivery === null)
1302
+ break;
1303
+ try {
1304
+ await this.#send(delivery);
1305
+ }
1306
+ catch (error) {
1307
+ if (this.#activeGeneration !== generation)
1308
+ break;
1309
+ if (error instanceof DesktopPersonalFrameTooLargeError) {
1310
+ this.#telemetry?.record('desktop.personal_frame_rejected', {
1311
+ frame_type: error.frameType, bytes: error.bytes, limit: MAX_DESKTOP_PERSONAL_JSON_BYTES,
1312
+ });
1313
+ try {
1314
+ // A command may already have committed. Reject its response without replaying it.
1315
+ await this.server.sendText(JSON.stringify(error.frameType === 'personal.result'
1316
+ ? { type: 'personal.result', request_id: error.requestId, ok: false, error: 'personal_frame_too_large', input_status: 'unknown' }
1317
+ : { type: 'personal.error', error: 'personal_frame_too_large' }));
1318
+ continue;
1319
+ }
1320
+ catch { /* A failed error delivery still follows the transport failure policy. */ }
1321
+ if (this.#activeGeneration !== generation)
1322
+ break;
1323
+ }
1324
+ if (delivery.policy === 'required' && this.#transportFailure === 'abort')
1325
+ this.#stop.abort();
1326
+ else if (delivery.policy !== 'required' && error instanceof DesktopOutboundValidationError) {
1327
+ this.#telemetry?.record('desktop.outbound_validation_dropped', {
1328
+ policy: delivery.policy,
1329
+ frame_kind: typeof delivery.frame === 'string' ? 'text' : 'binary',
1330
+ });
1331
+ continue;
1332
+ }
1333
+ else {
1334
+ await this.#disconnect(generation);
1335
+ }
1336
+ break;
1337
+ }
1338
+ if (this.#activeGeneration !== generation)
1339
+ break;
1340
+ }
1341
+ }
1342
+ }
1343
+ finally {
1344
+ this.#draining = false;
1345
+ if (this.#activeGeneration !== null && this.#drainRequested)
1346
+ void this.#drain();
1347
+ }
1348
+ }
1349
+ async #disconnect(generation) {
1350
+ if (this.#activeGeneration !== generation)
1351
+ return;
1352
+ try {
1353
+ const disconnect = this.server.disconnectClient();
1354
+ if (this.#transportFailure === 'disconnect')
1355
+ this.#release(generation);
1356
+ await disconnect;
1357
+ this.#release(generation);
1358
+ }
1359
+ catch {
1360
+ this.#release(generation);
1361
+ this.#telemetry?.record('desktop.transport_disconnect_failed', {});
1362
+ }
1363
+ }
1364
+ #send(delivery) {
1365
+ return typeof delivery.frame === 'string'
1366
+ ? this.server.sendText(delivery.frame)
1367
+ : this.server.sendBinary(delivery.frame);
1368
+ }
1369
+ }
1370
+ export const DESKTOP_OWNER_SHUTDOWN_GRACE_MS = 1_000;
1371
+ /** Build the circular desktop callback graph without exposing a half-built bridge. */
1372
+ export function buildDesktopRealtimeComposition(options) {
1373
+ validateDesktopToken(options.token);
1374
+ const holder = {};
1375
+ let phone;
1376
+ let audioOwner = null;
1377
+ let audioClosing = 0;
1378
+ const voiceOperations = new Map();
1379
+ const audioBridge = () => audioClosing ? undefined : audioOwner === 'phone' ? phone?.bridge : holder.desktop?.bridge;
1380
+ const publishPersonal = (frame) => { holder.desktop?.bridge.onPersonalFrame(frame); phone?.bridge.onPersonalFrame(frame); };
1381
+ const presentation = new Map();
1382
+ const effectivePresentation = () => [...presentation.values()].includes('workbench') ? 'workbench' : [...presentation.values()].includes('orb') ? 'orb' : 'background';
1383
+ const claimAudio = (side) => {
1384
+ if (audioClosing || (audioOwner !== null && audioOwner !== side))
1385
+ throw Error('voice_not_owned');
1386
+ audioOwner = side;
1387
+ };
1388
+ const command = async (side, value, context) => {
1389
+ const input = value;
1390
+ const params = input.params ?? {};
1391
+ const priorOwner = audioOwner;
1392
+ if (input.method === 'conversations.voice') {
1393
+ if (params.enabled === true) {
1394
+ try {
1395
+ claimAudio(side);
1396
+ }
1397
+ catch {
1398
+ return { type: 'personal.result', request_id: input.request_id, ok: false, error: 'voice_not_owned' };
1399
+ }
1400
+ }
1401
+ else if (audioOwner !== side)
1402
+ return { type: 'personal.result', request_id: input.request_id, ok: false, error: 'voice_not_owned' };
1403
+ }
1404
+ let commandContext = context;
1405
+ if (input.method === 'presentation.set' && ['background', 'workbench', 'orb'].includes(String(params.mode))) {
1406
+ presentation.set(side, params.mode);
1407
+ commandContext = { ...context, client_id: context?.client_id ?? (side === 'phone' ? 'remote:master' : 'desktop:local'), presentation_mode: effectivePresentation() };
1408
+ }
1409
+ let operation;
1410
+ try {
1411
+ operation = requireRealtime().personalAgent.command(input, commandContext);
1412
+ if (input.method === 'conversations.voice')
1413
+ voiceOperations.set(side, operation);
1414
+ const result = await operation;
1415
+ // Orb PCM has no explicit conversations.voice stop. Leaving orb releases that
1416
+ // implicit owner and drains its audio independently of phone visibility.
1417
+ if (input.method === 'presentation.set' && result.ok &&
1418
+ side === 'desktop' && params.mode !== 'orb' && audioOwner === side &&
1419
+ requireRealtime().personalAgent.conversationSnapshot().voice_id === null) {
1420
+ audioClosing++;
1421
+ try {
1422
+ await requireRealtime().service.discardInputAudio?.();
1423
+ await requireRealtime().service.playbackDisconnected({ resumeDelivery: true });
1424
+ if (audioOwner === side)
1425
+ audioOwner = null;
1426
+ }
1427
+ catch {
1428
+ // Failed draining must retain ownership: retry or disconnect before
1429
+ // routing another device's audio through potentially stale playback.
1430
+ return { type: 'personal.result', request_id: input.request_id, ok: false, error: 'audio_release_failed' };
1431
+ }
1432
+ finally {
1433
+ audioClosing--;
1434
+ }
1435
+ }
1436
+ if (input.method === 'conversations.voice') {
1437
+ if (!result.ok)
1438
+ audioOwner = priorOwner;
1439
+ else if (params.enabled === false)
1440
+ audioOwner = null;
1441
+ }
1442
+ return result;
1443
+ }
1444
+ catch (error) {
1445
+ if (input.method === 'conversations.voice')
1446
+ audioOwner = priorOwner;
1447
+ throw error;
1448
+ }
1449
+ finally {
1450
+ if (operation && voiceOperations.get(side) === operation)
1451
+ voiceOperations.delete(side);
1452
+ }
1453
+ };
1454
+ const requireDesktop = () => {
1455
+ if (holder.desktop === undefined) {
1456
+ throw new Error('desktop realtime bridge is unavailable during construction');
1457
+ }
1458
+ return holder.desktop;
1459
+ };
1460
+ const requireRealtime = () => {
1461
+ if (holder.realtime === undefined) {
1462
+ throw new Error('desktop realtime runtime is unavailable during construction');
1463
+ }
1464
+ return holder.realtime;
1465
+ };
1466
+ const cameraTransport = {
1467
+ captureCamera(request) {
1468
+ let server;
1469
+ try {
1470
+ server = requireDesktop().server;
1471
+ }
1472
+ catch (error) {
1473
+ return Promise.reject(error instanceof Error
1474
+ ? error
1475
+ : new Error('desktop realtime bridge is unavailable during construction'));
1476
+ }
1477
+ if (!isCameraCaptureTransport(server)) {
1478
+ return Promise.reject(new Error('desktop camera transport is unavailable'));
1479
+ }
1480
+ return server.captureCamera(request);
1481
+ },
1482
+ async releaseCamera(sessionId) {
1483
+ const server = requireDesktop().server;
1484
+ if (isCameraCaptureTransport(server))
1485
+ await server.releaseCamera?.(sessionId);
1486
+ },
1487
+ requestCameraPermission() {
1488
+ let server;
1489
+ try {
1490
+ server = requireDesktop().server;
1491
+ }
1492
+ catch (error) {
1493
+ return Promise.reject(error instanceof Error
1494
+ ? error
1495
+ : new Error('desktop realtime bridge is unavailable during construction'));
1496
+ }
1497
+ if (!isCameraPermissionTransport(server)) {
1498
+ return Promise.reject(new Error('desktop camera permission transport is unavailable'));
1499
+ }
1500
+ return server.requestCameraPermission();
1501
+ },
1502
+ };
1503
+ const realtime = options.buildRealtime({
1504
+ onExecutorSuggestion: suggestion => {
1505
+ const progress = projectExecutorSuggestion(suggestion, requireRealtime().runtime.clock.now());
1506
+ if (progress !== null)
1507
+ requireDesktop().bridge.onExecutorProgress(progress);
1508
+ },
1509
+ onAudioFrame: frame => { requireDesktop(); audioBridge()?.onAudioFrame(frame); },
1510
+ onAudioClear: (utteranceId, generationEpoch) => {
1511
+ audioBridge()?.onAudioClear(utteranceId, generationEpoch);
1512
+ },
1513
+ onAudioAlert: (utteranceId, generationEpoch) => {
1514
+ audioBridge()?.onAudioAlert(utteranceId, generationEpoch);
1515
+ },
1516
+ onAudioTerminal: (utteranceId, generationEpoch) => {
1517
+ audioBridge()?.onAudioTerminal(utteranceId, generationEpoch);
1518
+ },
1519
+ onDelivery: completion => {
1520
+ const current = requireRealtime();
1521
+ if (current.service.clearingConversation || completion.session_epoch !== current.session.sessionEpoch)
1522
+ return;
1523
+ const payload = deliveryToEvent(completion);
1524
+ if (payload !== null)
1525
+ current.runtime.post({ kind: 'assistant_spoken', payload });
1526
+ },
1527
+ onCaption: frame => requireDesktop().bridge.onCaption(frame),
1528
+ onExecutorState: state => requireDesktop().bridge.onExecutorState(state),
1529
+ onProjectView: view => requireDesktop().bridge.onProjectView(view),
1530
+ }, cameraTransport);
1531
+ holder.realtime = realtime;
1532
+ const endpointOptions = (side) => ({
1533
+ token: options.token,
1534
+ ownsAudio: () => !audioClosing && (audioOwner === side || (side === 'desktop' && audioOwner === null)),
1535
+ ...(options.transportFailure === undefined ? {} : { transportFailure: options.transportFailure }),
1536
+ service: realtime.service,
1537
+ conversationService: id => realtime.personalAgent.conversationService(id),
1538
+ voiceService: () => realtime.personalAgent.voiceService(),
1539
+ sendConversationAudio: (id, pcm) => realtime.personalAgent.sendConversationAudio(id, pcm),
1540
+ submitConversationText: (id, text, requestId, sourceTodo) => realtime.personalAgent.submitConversationText(id, text, requestId, sourceTodo),
1541
+ validateConversationInput: (kind, id) => { if (presentation.get(side) === 'background' || realtime.personalAgent.presentationMode === 'background')
1542
+ throw Error('presentation_hidden'); const state = realtime.personalAgent.conversationSnapshot(); if (id !== undefined && !state.items.some(item => item.id === id))
1543
+ throw Error('conversation_not_found'); if (kind === 'audio' && ((id !== undefined && state.voice_id !== id) || (id === undefined && state.voice_id !== null)))
1544
+ throw Error('voice_not_owned'); if (kind === 'dictation' && state.voice_id !== null)
1545
+ throw Error('voice_active'); if (kind === 'audio') {
1546
+ if (side === 'desktop' && id === undefined && presentation.get(side) === 'workbench')
1547
+ throw Error('voice_not_owned');
1548
+ if (side === 'phone' && id === undefined)
1549
+ throw Error('conversation_required');
1550
+ claimAudio(side);
1551
+ } },
1552
+ personalCommand: (input, context) => command(side, input, context),
1553
+ personalSnapshot: () => realtime.personalAgent.snapshot(),
1554
+ onConnectionReleased: () => {
1555
+ const hadPresentation = presentation.delete(side);
1556
+ if (audioOwner === side && (realtime.personalAgent.conversationSnapshot().voice_id !== null || voiceOperations.has(side))) {
1557
+ audioClosing++;
1558
+ let released = false;
1559
+ void (async () => {
1560
+ await voiceOperations.get(side)?.catch(() => { });
1561
+ const id = realtime.personalAgent.conversationSnapshot().voice_id;
1562
+ if (id) {
1563
+ const result = await realtime.personalAgent.command({ type: 'personal.command', request_id: randomUUID(), method: 'conversations.voice', params: { id, enabled: false } });
1564
+ if (!result.ok)
1565
+ throw Error('voice_release_failed');
1566
+ }
1567
+ released = true;
1568
+ })().catch(() => { }).finally(() => { if (released && audioOwner === side)
1569
+ audioOwner = null; audioClosing--; });
1570
+ }
1571
+ else if (audioOwner === side)
1572
+ audioOwner = null;
1573
+ if (hadPresentation && presentation.size === 0 && realtime.personalAgent.presentationMode !== null)
1574
+ void realtime.personalAgent.disconnectPresentation().catch(() => { });
1575
+ else if (presentation.size > 0)
1576
+ void realtime.personalAgent.command({ type: 'personal.command', request_id: randomUUID(), method: 'presentation.set', params: { mode: 'background' } }, { client_id: side === 'phone' ? 'remote:master' : 'desktop:local', can_takeover: false, presentation_mode: effectivePresentation() });
1577
+ },
1578
+ executor: codingExecutorIdentity(realtime) ?? options.approvalExecutor ?? null,
1579
+ ...(() => {
1580
+ const adapter = [...realtime.runtime.executors.values()].find(adapter => adapter.manifest.roles.includes('coding'));
1581
+ const port = adapter?.taskPort;
1582
+ return port === undefined ? {} : { taskPort: port };
1583
+ })(),
1584
+ stop: options.stop,
1585
+ memoryBoard: async (requestId, detail, page) => {
1586
+ if (page?.channel === 'personal') {
1587
+ const personal = await realtime.inspectPersonalMemory({ query: page.query ?? '', ...(page.before_seq === undefined ? {} : { before: page.before_seq }) });
1588
+ return JSON.stringify({ type: 'memory.board', request_id: requestId, channels: [], diagnostics: { version: 1, records: [] }, personal });
1589
+ }
1590
+ await realtime.runtime.flushMemory(true);
1591
+ return memoryBoardMessage(requestId, realtime.runtime.memory, options.telemetry?.diagnostics?.(), { ...page, conversationEpoch: realtime.runtime.core.conversationEpoch, ...(detail === undefined ? {} : { detail }) });
1592
+ },
1593
+ clock: realtime.runtime.clock,
1594
+ ...(options.progressBubbles === undefined ? {} : { progressBubbles: options.progressBubbles }),
1595
+ ...(options.telemetry === undefined ? {} : { telemetry: options.telemetry }),
1596
+ ...(options.projectView === undefined ? {} : { projectView: options.projectView }),
1597
+ ...(options.approvalView === undefined ? {} : { approvalView: options.approvalView }),
1598
+ ...(options.createServer === undefined ? {} : { createServer: options.createServer }),
1599
+ });
1600
+ const desktop = new DesktopRealtime(endpointOptions('desktop'));
1601
+ holder.desktop = desktop;
1602
+ const createPhone = (phoneOptions) => {
1603
+ // The caller closes the previous endpoint before creating its replacement.
1604
+ phone = new DesktopRealtime({ ...endpointOptions('phone'), ...phoneOptions, transportFailure: 'disconnect', preserveLanguage: true });
1605
+ return phone;
1606
+ };
1607
+ const unsubscribePersonal = realtime.personalAgent.subscribe(() => publishPersonal(realtime.personalAgent.snapshot()));
1608
+ options.stop.signal.addEventListener('abort', unsubscribePersonal, { once: true });
1609
+ startDesktopActivityHeartbeat(realtime.service, idle => desktop.bridge.onActivity(idle), options.stop.signal);
1610
+ const unsubscribeProgress = realtime.runtime.observe((event, currentConversation) => {
1611
+ if (currentConversation === false)
1612
+ return;
1613
+ const projected = projectExecutorEvent(event, realtime.runtime, channel => realtime.service.agentNameForChannel(channel), undefined, id => realtime.service.session.delegateRecord(id));
1614
+ if (projected !== null)
1615
+ desktop.bridge.onExecutorProgress(projected.progress, projected.result);
1616
+ });
1617
+ if (options.stop.signal.aborted)
1618
+ unsubscribeProgress();
1619
+ else
1620
+ options.stop.signal.addEventListener('abort', unsubscribeProgress, { once: true });
1621
+ const prepareLegacyPhoneVoice = async () => {
1622
+ const context = { client_id: 'remote:master', can_takeover: false };
1623
+ const id = realtime.personalAgent.conversationSnapshot().selected_id;
1624
+ for (const input of [
1625
+ { method: 'presentation.set', params: { mode: 'workbench' } },
1626
+ { method: 'conversations.voice', params: { id, enabled: true } },
1627
+ ]) {
1628
+ const result = await command('phone', { type: 'personal.command', request_id: randomUUID(), ...input }, context);
1629
+ if (!result.ok)
1630
+ throw Error('legacy_voice_unavailable');
1631
+ }
1632
+ return id;
1633
+ };
1634
+ return { realtime, desktop, createPhone, audioBridge, publishPersonal, prepareLegacyPhoneVoice };
1635
+ }
1636
+ /** Best-effort presence must never take down the owning realtime service. */
1637
+ export function startDesktopActivityHeartbeat(service, publish, signal) {
1638
+ const timer = setInterval(() => {
1639
+ if (signal.aborted)
1640
+ return;
1641
+ let idle = false;
1642
+ try {
1643
+ const session = service.session;
1644
+ idle = session.foregroundIdle && session.floor.state === 'idle'
1645
+ && session.snapshot().active_delegates.length === 0
1646
+ && service.executorState === 'idle';
1647
+ }
1648
+ catch { /* Unavailable session state conservatively means busy. */ }
1649
+ try {
1650
+ publish(idle);
1651
+ }
1652
+ catch { /* A dropped presence frame is retried next tick. */ }
1653
+ }, 1000);
1654
+ timer.unref();
1655
+ if (signal.aborted)
1656
+ clearInterval(timer);
1657
+ else
1658
+ signal.addEventListener('abort', () => clearInterval(timer), { once: true });
1659
+ return timer;
1660
+ }
1661
+ /** The frame identity of the configured coding executor, or `null` when there is none. */
1662
+ export function codingExecutorIdentity(realtime) {
1663
+ const manifest = executorWithRole([...realtime.runtime.executors.values()].map(adapter => adapter.manifest), 'coding');
1664
+ if (manifest === null)
1665
+ return null;
1666
+ const publicName = realtime.service.agentNameForChannel(manifest.name) ?? manifest.name;
1667
+ return { executor: publicName, display_name: publicName };
1668
+ }
1669
+ function isCameraCaptureTransport(server) {
1670
+ return 'captureCamera' in server && typeof server.captureCamera === 'function';
1671
+ }
1672
+ function isCameraPermissionTransport(server) {
1673
+ return 'requestCameraPermission' in server
1674
+ && typeof server.requestCameraPermission === 'function';
1675
+ }
1676
+ /** One idempotent lifecycle owner around the already-constructed realtime and socket graphs. */
1677
+ export class RealtimeDesktopService {
1678
+ #realtime;
1679
+ #desktop;
1680
+ #readyEndpoint;
1681
+ #stop;
1682
+ #announce;
1683
+ #closeAuxiliary;
1684
+ #cleanupGraceMs;
1685
+ #listenBeforeRealtime;
1686
+ #onDiagnostic;
1687
+ #runOperation = null;
1688
+ #cleanupOperation = null;
1689
+ constructor(options) {
1690
+ const grace = options.cleanupGraceMs ?? DESKTOP_OWNER_SHUTDOWN_GRACE_MS;
1691
+ if (!Number.isFinite(grace) || grace <= 0) {
1692
+ throw new TypeError('desktop cleanup grace must be positive and finite');
1693
+ }
1694
+ this.#listenBeforeRealtime = options.listenBeforeRealtime ?? false;
1695
+ this.#realtime = options.realtime;
1696
+ this.#desktop = options.desktop;
1697
+ this.#readyEndpoint = options.readyEndpoint;
1698
+ this.#stop = options.stop;
1699
+ this.#announce = options.announce;
1700
+ this.#closeAuxiliary = options.closeAuxiliary ?? noop;
1701
+ this.#cleanupGraceMs = grace;
1702
+ this.#onDiagnostic = options.onDiagnostic ?? noopDiagnostic;
1703
+ }
1704
+ run() {
1705
+ if (this.#runOperation !== null)
1706
+ return this.#runOperation;
1707
+ const operation = this.#runFresh();
1708
+ this.#runOperation = operation;
1709
+ return operation;
1710
+ }
1711
+ async stop() {
1712
+ this.#stop.abort();
1713
+ const outcome = await this.#ensureCleanup();
1714
+ if (outcome.firstFailure !== null)
1715
+ throw outcome.firstFailure.error;
1716
+ }
1717
+ async #runFresh() {
1718
+ let primaryFailure = null;
1719
+ try {
1720
+ const external = this.#externalStopMonitor();
1721
+ if (this.#listenBeforeRealtime && !this.#stop.signal.aborted) {
1722
+ const listening = await this.#runPhase(this.#listen(), external, 'desktop_server_start_abandoned', isReadinessCancellation);
1723
+ if (listening.kind === 'rejected')
1724
+ throw listening.error;
1725
+ if (listening.kind === 'terminal')
1726
+ return await this.#finish(listening.cause);
1727
+ }
1728
+ if (!this.#stop.signal.aborted) {
1729
+ const start = await this.#runPhase(this.#realtime.start(), external, 'desktop_realtime_start_abandoned');
1730
+ if (start.kind === 'rejected')
1731
+ primaryFailure = { error: start.error };
1732
+ if (start.kind === 'terminal')
1733
+ return await this.#finish(start.cause);
1734
+ }
1735
+ if (primaryFailure === null && !this.#stop.signal.aborted) {
1736
+ const terminal = this.#armTerminalMonitor(external);
1737
+ // Promise callbacks for an already-settled waitStopped run before this continuation. This
1738
+ // fence is what keeps a dead service from briefly advertising a live desktop listener.
1739
+ await Promise.resolve();
1740
+ const early = terminal.current();
1741
+ if (early !== undefined)
1742
+ return await this.#finish(early);
1743
+ if (!this.#listenBeforeRealtime) {
1744
+ const listener = await this.#runPhase(this.#desktop.server.start(), terminal, 'desktop_server_start_abandoned');
1745
+ if (listener.kind === 'rejected')
1746
+ primaryFailure = { error: listener.error };
1747
+ if (listener.kind === 'terminal')
1748
+ return await this.#finish(listener.cause);
1749
+ if (listener.kind === 'resolved') {
1750
+ const announcement = await this.#runPhase(this.#announce(this.#readyEndpoint, listener.value, this.#stop.signal), terminal, 'desktop_readiness_announcement_abandoned', isReadinessCancellation);
1751
+ if (announcement.kind === 'rejected')
1752
+ primaryFailure = { error: announcement.error };
1753
+ if (announcement.kind === 'terminal')
1754
+ return await this.#finish(announcement.cause);
1755
+ }
1756
+ }
1757
+ if (primaryFailure === null)
1758
+ return await this.#finish(await terminal.promise);
1759
+ }
1760
+ }
1761
+ catch (error) {
1762
+ primaryFailure = { error };
1763
+ }
1764
+ this.#stop.abort();
1765
+ const cleanup = await this.#ensureCleanup();
1766
+ if (primaryFailure !== null)
1767
+ throw primaryFailure.error;
1768
+ if (cleanup.firstFailure !== null)
1769
+ throw cleanup.firstFailure.error;
1770
+ }
1771
+ async #listen() {
1772
+ const readiness = await this.#desktop.server.start();
1773
+ if (!this.#stop.signal.aborted)
1774
+ await this.#announce(this.#readyEndpoint, readiness, this.#stop.signal);
1775
+ }
1776
+ #externalStopMonitor() {
1777
+ let current;
1778
+ const promise = new Promise(resolve => {
1779
+ if (this.#stop.signal.aborted) {
1780
+ current = { kind: 'external', error: null };
1781
+ resolve(current);
1782
+ return;
1783
+ }
1784
+ const onAbort = () => {
1785
+ current = { kind: 'external', error: null };
1786
+ resolve(current);
1787
+ };
1788
+ this.#stop.signal.addEventListener('abort', onAbort, { once: true });
1789
+ });
1790
+ return { promise, current: () => current };
1791
+ }
1792
+ #armTerminalMonitor(external) {
1793
+ let current = external.current();
1794
+ const remember = (cause) => {
1795
+ current ??= external.current() ?? cause;
1796
+ return current;
1797
+ };
1798
+ let service;
1799
+ try {
1800
+ service = this.#realtime.service.waitStopped().then(() => remember({ kind: 'service', error: null }), (error) => remember({ kind: 'service', error: { value: error } }));
1801
+ }
1802
+ catch (error) {
1803
+ service = Promise.resolve(remember({ kind: 'service', error: { value: error } }));
1804
+ }
1805
+ const promise = Promise.race([external.promise, service]).then(cause => {
1806
+ current = cause;
1807
+ this.#stop.abort();
1808
+ void this.#ensureCleanup();
1809
+ return cause;
1810
+ });
1811
+ return { promise, current: () => current ?? external.current() };
1812
+ }
1813
+ async #runPhase(work, terminal, abandonedDiagnostic, terminalWinsConcurrentRejection) {
1814
+ const outcome = work.then(value => ({ kind: 'resolved', value }), (error) => ({ kind: 'rejected', error }));
1815
+ const raced = await Promise.race([
1816
+ outcome,
1817
+ terminal.promise.then(cause => ({ kind: 'terminal', cause })),
1818
+ ]);
1819
+ if (raced.kind === 'rejected'
1820
+ && terminalWinsConcurrentRejection?.(raced.error) === true) {
1821
+ const cause = terminal.current();
1822
+ if (cause !== undefined)
1823
+ return { kind: 'terminal', cause };
1824
+ }
1825
+ if (raced.kind !== 'terminal')
1826
+ return raced;
1827
+ await this.#settlePhaseWithinGrace(outcome, abandonedDiagnostic);
1828
+ return raced;
1829
+ }
1830
+ async #settlePhaseWithinGrace(outcome, diagnostic) {
1831
+ let timer;
1832
+ const deadline = new Promise(resolve => {
1833
+ timer = setTimeout(() => resolve('abandoned'), this.#cleanupGraceMs);
1834
+ });
1835
+ const result = await Promise.race([outcome.then(() => 'settled'), deadline]);
1836
+ if (timer !== undefined)
1837
+ clearTimeout(timer);
1838
+ if (result === 'abandoned')
1839
+ this.#emitDiagnostic(diagnostic);
1840
+ }
1841
+ async #finish(cause) {
1842
+ const cleanup = await this.#ensureCleanup();
1843
+ if (cause.kind === 'service' && cause.error !== null)
1844
+ throw cause.error.value;
1845
+ if (cleanup.firstFailure !== null)
1846
+ throw cleanup.firstFailure.error;
1847
+ }
1848
+ #ensureCleanup() {
1849
+ if (this.#cleanupOperation !== null)
1850
+ return this.#cleanupOperation;
1851
+ this.#cleanupOperation = this.#cleanup();
1852
+ return this.#cleanupOperation;
1853
+ }
1854
+ async #cleanup() {
1855
+ let firstFailure = null;
1856
+ const server = await this.#cleanupWithinGrace(() => this.#desktop.server.close(), 'desktop_server_close_abandoned');
1857
+ if (server.kind === 'rejected')
1858
+ firstFailure = { error: server.error };
1859
+ const realtime = await settleCleanup(() => this.#realtime.stop());
1860
+ if (firstFailure === null && realtime.kind === 'rejected') {
1861
+ firstFailure = { error: realtime.error };
1862
+ }
1863
+ const auxiliary = await this.#cleanupWithinGrace(() => this.#closeAuxiliary(), 'desktop_auxiliary_close_abandoned');
1864
+ if (firstFailure === null && auxiliary.kind === 'rejected') {
1865
+ firstFailure = { error: auxiliary.error };
1866
+ }
1867
+ return { firstFailure };
1868
+ }
1869
+ async #cleanupWithinGrace(cleanup, diagnostic) {
1870
+ const settled = settleCleanup(cleanup);
1871
+ let timer;
1872
+ const deadline = new Promise(resolve => {
1873
+ timer = setTimeout(() => resolve({ kind: 'abandoned' }), this.#cleanupGraceMs);
1874
+ });
1875
+ const result = await Promise.race([settled, deadline]);
1876
+ if (timer !== undefined)
1877
+ clearTimeout(timer);
1878
+ if (result.kind === 'abandoned') {
1879
+ this.#emitDiagnostic(diagnostic);
1880
+ }
1881
+ return result;
1882
+ }
1883
+ #emitDiagnostic(diagnostic) {
1884
+ try {
1885
+ this.#onDiagnostic(`[runtime-diagnostic] ${diagnostic}`);
1886
+ }
1887
+ catch {
1888
+ // Diagnostic observers do not own shutdown progress.
1889
+ }
1890
+ }
1891
+ }
1892
+ async function settleCleanup(cleanup) {
1893
+ try {
1894
+ await cleanup();
1895
+ return { kind: 'resolved' };
1896
+ }
1897
+ catch (error) {
1898
+ return { kind: 'rejected', error };
1899
+ }
1900
+ }
1901
+ /** Run the production entry without leaking configuration or dependency errors to stderr. */
1902
+ export async function runDesktopEntry(options) {
1903
+ let ownership = null;
1904
+ try {
1905
+ ownership = new DesktopConstructionLedger(options.cleanupGraceMs ?? DESKTOP_OWNER_SHUTDOWN_GRACE_MS, options.onDiagnostic);
1906
+ validateDesktopToken(options.token);
1907
+ if (options.readyEndpoint !== undefined)
1908
+ parseReadyEndpoint(options.readyEndpoint);
1909
+ const constructed = await options.construct(ownership);
1910
+ const owner = new RealtimeDesktopService({
1911
+ ...(options.listenBeforeRealtime === undefined ? {} : { listenBeforeRealtime: options.listenBeforeRealtime }),
1912
+ realtime: constructed.realtime,
1913
+ desktop: constructed.desktop,
1914
+ readyEndpoint: options.readyEndpoint ?? '',
1915
+ stop: options.stop,
1916
+ announce: options.announce,
1917
+ ...(constructed.closeAuxiliary === undefined
1918
+ ? {}
1919
+ : { closeAuxiliary: constructed.closeAuxiliary }),
1920
+ ...(options.cleanupGraceMs === undefined ? {} : { cleanupGraceMs: options.cleanupGraceMs }),
1921
+ onDiagnostic: options.onDiagnostic,
1922
+ });
1923
+ ownership.commit();
1924
+ await owner.run();
1925
+ return 0;
1926
+ }
1927
+ catch (error) {
1928
+ await ownership?.rollback();
1929
+ try {
1930
+ options.onStartupFailure?.(error);
1931
+ options.onDiagnostic(`[runtime-diagnostic] ${desktopEntryFailureCode(error)}`);
1932
+ }
1933
+ catch {
1934
+ // A diagnostic sink must not convert a bounded entry failure into an unhandled rejection.
1935
+ }
1936
+ return 2;
1937
+ }
1938
+ }
1939
+ function desktopEntryFailureCode(error) {
1940
+ if (error !== null && typeof error === 'object') {
1941
+ const value = error;
1942
+ if (value.message === 'personal_store_locked')
1943
+ return 'personal_store_locked';
1944
+ if (['EACCES', 'EPERM', 'EROFS'].includes(String(value.code)))
1945
+ return 'filesystem_permissions';
1946
+ if (['state_permissions', 'state_busy', 'state_lock_failed', 'personal_store_locked', 'workspace_not_found', 'workspace_invalid'].includes(String(value.code)))
1947
+ return String(value.code);
1948
+ if (value.code === 'frontbrain_tool_budget_exceeded')
1949
+ return 'configuration_required';
1950
+ if (value.code === 'credential_missing')
1951
+ return 'authentication_failed';
1952
+ if (new Set([
1953
+ 'binary_missing', 'spawn_failed', 'codex_host_unavailable',
1954
+ 'codex_project_host_unsupported', 'backend_unavailable',
1955
+ ]).has(String(value.code)))
1956
+ return 'backend_unavailable';
1957
+ // Every configuration error class (core, camera, any executor's host config) ends in this suffix.
1958
+ if (typeof value.name === 'string' && value.name.endsWith('ConfigurationError'))
1959
+ return 'configuration_required';
1960
+ }
1961
+ return 'assembly_failed';
1962
+ }
1963
+ class DesktopConstructionLedger {
1964
+ #cleanups = [];
1965
+ #cleanupGraceMs;
1966
+ #onDiagnostic;
1967
+ #sealed = false;
1968
+ #rollbackOperation = null;
1969
+ constructor(cleanupGraceMs, onDiagnostic) {
1970
+ if (!Number.isFinite(cleanupGraceMs) || cleanupGraceMs <= 0) {
1971
+ throw new TypeError('desktop cleanup grace must be positive and finite');
1972
+ }
1973
+ this.#cleanupGraceMs = cleanupGraceMs;
1974
+ this.#onDiagnostic = onDiagnostic;
1975
+ }
1976
+ own(cleanup) {
1977
+ if (this.#sealed || typeof cleanup !== 'function') {
1978
+ throw new TypeError('desktop construction ownership is closed');
1979
+ }
1980
+ const entry = { cleanup, active: true };
1981
+ this.#cleanups.push(entry);
1982
+ return () => { entry.active = false; };
1983
+ }
1984
+ commit() {
1985
+ this.#sealed = true;
1986
+ for (const entry of this.#cleanups)
1987
+ entry.active = false;
1988
+ }
1989
+ rollback() {
1990
+ if (this.#rollbackOperation !== null)
1991
+ return this.#rollbackOperation;
1992
+ if (this.#sealed)
1993
+ return Promise.resolve();
1994
+ this.#sealed = true;
1995
+ this.#rollbackOperation = this.#rollbackFresh();
1996
+ return this.#rollbackOperation;
1997
+ }
1998
+ async #rollbackFresh() {
1999
+ for (let index = this.#cleanups.length - 1; index >= 0; index -= 1) {
2000
+ const entry = this.#cleanups[index];
2001
+ if (!entry.active)
2002
+ continue;
2003
+ entry.active = false;
2004
+ const result = await this.#cleanupWithinGrace(entry.cleanup);
2005
+ if (result.kind === 'rejected') {
2006
+ this.#emitDiagnostic('desktop_construction_cleanup_failed');
2007
+ }
2008
+ else if (result.kind === 'abandoned') {
2009
+ this.#emitDiagnostic('desktop_construction_cleanup_abandoned');
2010
+ }
2011
+ }
2012
+ }
2013
+ async #cleanupWithinGrace(cleanup) {
2014
+ const settled = settleCleanup(cleanup);
2015
+ let timer;
2016
+ const deadline = new Promise(resolve => {
2017
+ timer = setTimeout(() => resolve({ kind: 'abandoned' }), this.#cleanupGraceMs);
2018
+ });
2019
+ const result = await Promise.race([settled, deadline]);
2020
+ if (timer !== undefined)
2021
+ clearTimeout(timer);
2022
+ return result;
2023
+ }
2024
+ #emitDiagnostic(diagnostic) {
2025
+ try {
2026
+ this.#onDiagnostic(`[runtime-diagnostic] ${diagnostic}`);
2027
+ }
2028
+ catch {
2029
+ // Construction rollback remains all-attempted when diagnostics fail.
2030
+ }
2031
+ }
2032
+ }
2033
+ /** Bind every host termination path to one abort owner and make the bindings explicitly releasable. */
2034
+ export function installDesktopStopSources(options) {
2035
+ const removers = [];
2036
+ let resumedStdin = false;
2037
+ let disposed = false;
2038
+ const requestStop = () => options.stop.abort();
2039
+ const bind = (source, method, event, listener) => {
2040
+ source[method](event, listener);
2041
+ removers.push(() => removeEventListener(source, event, listener));
2042
+ };
2043
+ bind(options.processEvents, 'once', 'SIGINT', requestStop);
2044
+ bind(options.processEvents, 'once', 'SIGTERM', requestStop);
2045
+ if (options.parentPort === undefined) {
2046
+ bind(options.processEvents, 'once', 'disconnect', requestStop);
2047
+ bind(options.stdin, 'once', 'end', requestStop);
2048
+ options.stdin.resume();
2049
+ resumedStdin = true;
2050
+ }
2051
+ else {
2052
+ const onMessage = (event) => {
2053
+ if (isDesktopShutdownMessage(event))
2054
+ requestStop();
2055
+ };
2056
+ bind(options.parentPort, 'on', 'message', onMessage);
2057
+ bind(options.parentPort, 'once', 'close', requestStop);
2058
+ options.parentPort.start?.();
2059
+ }
2060
+ return {
2061
+ dispose: () => {
2062
+ if (disposed)
2063
+ return;
2064
+ disposed = true;
2065
+ for (const remove of removers.splice(0).reverse())
2066
+ remove();
2067
+ if (resumedStdin)
2068
+ options.stdin.pause?.();
2069
+ },
2070
+ };
2071
+ }
2072
+ /** Entry wrapper that cannot leave a resumed stdin or process listener behind after any exit. */
2073
+ export async function runDesktopEntryWithStopSources(options, sources) {
2074
+ const binding = installDesktopStopSources({ ...sources, stop: options.stop });
2075
+ try {
2076
+ return await runDesktopEntry(options);
2077
+ }
2078
+ finally {
2079
+ binding.dispose();
2080
+ }
2081
+ }
2082
+ /** Accept both Electron MessageEvent wrappers and utility-process direct payloads. */
2083
+ export function isDesktopShutdownMessage(event) {
2084
+ const message = isObject(event) && 'data' in event ? event.data : event;
2085
+ return isObject(message) && message.type === 'nova.shutdown';
2086
+ }
2087
+ function isObject(value) {
2088
+ return value !== null && typeof value === 'object';
2089
+ }
2090
+ function isReadinessCancellation(error) {
2091
+ return error instanceof DesktopProtocolError
2092
+ && error.message === 'desktop readiness announcement cancelled';
2093
+ }
2094
+ function removeEventListener(source, event, listener) {
2095
+ if (source.off !== undefined)
2096
+ source.off(event, listener);
2097
+ else
2098
+ source.removeListener?.(event, listener);
2099
+ }
2100
+ function noop() {
2101
+ // Default auxiliary cleanup and settled-signal disposer.
2102
+ }
2103
+ function noopDiagnostic(_line) {
2104
+ void _line;
2105
+ }
2106
+ //# sourceMappingURL=desktop-session.js.map