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,1726 @@
1
+ import { parseMemoryRef } from '../core/memory.js';
2
+ import { TaskExecutionRejected } from '../personal-agent/task-loop.js';
3
+ import { taskGrantService } from '../personal-agent/tasks.js';
4
+ export { formatSeconds } from './service-state.js';
5
+ import { CodingProgressNarrationState } from './coding-progress-narration.js';
6
+ import { HostDelivery } from './host-delivery.js';
7
+ import { ProjectConfirmationFlow } from './project-confirmation-flow.js';
8
+ import { ProviderProjection } from './provider-projection.js';
9
+ import { Mutex, Signal, diagnosticName } from './service-state.js';
10
+ import { ToolContinuations } from './tool-continuations.js';
11
+ /**
12
+ * Coordinates provider event ordering, lifecycle and user-origin evidence.
13
+ * HostDelivery owns speech/acknowledgements; ToolContinuations owns admitted work;
14
+ * ProjectConfirmationFlow owns confirmation lifecycle; ProviderProjection owns presentation.
15
+ * Reconnect lock precedes delivery lock. Reconnect uses private deliveryPass, never
16
+ * the public recovery wrapper. Continuations run only after delivery lock release.
17
+ * Epoch checks remain at the original await boundaries because providers may reuse IDs.
18
+ */
19
+ import { randomUUID } from 'node:crypto';
20
+ import { createAgentControllerRegistry } from '../executors/agent-controller.js';
21
+ import { ApprovalHost } from '../core/approval.js';
22
+ import {} from '../core/events.js';
23
+ import {} from '../executors/coding/intake.js';
24
+ import { USER_PRIORITY } from '../core/memory.js';
25
+ import { codePointLengthLikePython } from '../text/python-text.js';
26
+ import {} from './evidence.js';
27
+ import { packRecoveryTurns, projectRecoveryTurns } from './history.js';
28
+ import { ItemDeliveryUncertainError } from './protocol.js';
29
+ import { MAX_HOST_FACT_CHARS, MAX_TRACKED_TOOL_CALLS, PROJECT_EXPIRY_STEP_TIMEOUT_S, callKey, hostFactIntent } from './service-state.js';
30
+ import {} from './session-state.js';
31
+ import { RealtimeDeliveryError } from './session.js';
32
+ import { UserOriginBindingLedger } from './user-origin-binding.js';
33
+ function sameAgentDescriptors(left, right) {
34
+ return left.length === right.length && left.every((descriptor, index) => {
35
+ const other = right[index];
36
+ return other?.name === descriptor.name
37
+ && descriptor.summary === other.summary
38
+ && descriptor.ownedChannels.length === other.ownedChannels.length
39
+ && descriptor.ownedChannels.every((channel, channelIndex) => channel === other.ownedChannels[channelIndex]);
40
+ });
41
+ }
42
+ /**
43
+ * How long `close` waits for a task that is not responding to its abort signal.
44
+ *
45
+ * Short: every loop here checks the signal at its next suspension point, so a task still running after
46
+ * this is stuck rather than slow, and waiting longer would only delay the diagnostic.
47
+ */
48
+ const SHUTDOWN_GRACE_MS = 250;
49
+ export class RealtimeService {
50
+ async setLanguage(language) { await this.#provider.setLanguage?.(language); }
51
+ playbackStarted(utteranceId, generationEpoch) { return this.#host.playbackStarted(utteranceId, generationEpoch); }
52
+ #confirmation;
53
+ get projectConfirmationBlockingForTest() { return this.#confirmation.projectConfirmationBlockingForTest; }
54
+ get confirmationClosingItemsForTest() { return this.#confirmation.confirmationClosingItemsForTest; }
55
+ get confirmationItemsForTest() { return this.#confirmation.confirmationItemsForTest; }
56
+ get confirmationResponsesForTest() { return this.#confirmation.confirmationResponsesForTest; }
57
+ #continuations;
58
+ get toolCallDispositionsForTest() { return this.#continuations.toolCallDispositionsForTest; }
59
+ driveContinuations() { return this.#continuations.driveContinuations(); }
60
+ toolCallAcceptances() { return this.#continuations.toolCallAcceptances(); }
61
+ #host;
62
+ get urgentOwnerForTest() { return this.#host.urgentOwnerForTest; }
63
+ seedUrgentOwnerForTest(input) { return this.#host.seedUrgentOwnerForTest(input); }
64
+ takeNextQueuedHostItem() { return this.#host.takeNextQueuedHostItem(); }
65
+ queuedHostItems() { return this.#host.queuedHostItems(); }
66
+ get armedPreemptPriority() { return this.#host.armedPreemptPriority; }
67
+ get pendingHostItemCount() { return this.#host.pendingHostItemCount; }
68
+ playbackDisconnected(options = {}) { return this.#host.playbackDisconnected(options); }
69
+ playbackStopped(utteranceId, generationEpoch, playedMs) { return this.#host.playbackStopped(utteranceId, generationEpoch, playedMs); }
70
+ playbackCleared(utteranceId, generationEpoch, playedMs) { return this.#host.playbackCleared(utteranceId, generationEpoch, playedMs); }
71
+ playbackDone(utteranceId, generationEpoch, playedMs) { return this.#host.playbackDone(utteranceId, generationEpoch, playedMs); }
72
+ taskRoutes() { return this.#agentRegistry.descriptors.map(item => item.name); }
73
+ taskTurnOrigin() { return this.#intakeUser?.origin_ref; }
74
+ async dispatchTask(grant, instruction) {
75
+ let tasks;
76
+ try {
77
+ tasks = taskGrantService(grant);
78
+ tasks.validateContinuation(grant);
79
+ }
80
+ catch {
81
+ throw new TaskExecutionRejected('task_continuation_stale');
82
+ }
83
+ const task = tasks.get(grant.fence.task_id);
84
+ const controller = task.execution_route ? this.#agentRegistry.controllers.get(task.execution_route) : undefined;
85
+ if (!controller)
86
+ throw new TaskExecutionRejected('task_executor_unavailable');
87
+ return controller.dispatch({ taskContext: grant, continuationGrant: grant, instruction, originalUserText: task.original_goal ?? task.goal, origin_ref: grant.origin_ref, sessionEpoch: this.session.sessionEpoch, acceptedUserInputRevision: 0, stillWanted: grant.stillWanted });
88
+ }
89
+ queueHostItem(intent, options = {}) {
90
+ const decision = intent.item.event_id.startsWith('approval:') || intent.item.event_id.startsWith('project-confirmation:');
91
+ if (decision && this.#proactiveRouting) {
92
+ if (!this.#proactiveRouting.local())
93
+ return;
94
+ const prior = options.stillWanted;
95
+ options = { ...options, stillWanted: () => this.#proactiveRouting.local() && (!prior || prior()) };
96
+ }
97
+ return this.#host.queueHostItem(intent, options);
98
+ }
99
+ #proactiveEvents = new Set();
100
+ isTaskContinuationResponse(responseId) { return this.session.responseHostItemIds(responseId).some(id => id.startsWith('task-response:')); }
101
+ isProactiveResponse(responseId) { return this.session.responseEventIds(responseId).some(id => this.#proactiveEvents.has(id) || id.startsWith('approval:') || id.startsWith('project-confirmation:')); }
102
+ #queueProactive(intent, options = {}, body = intent.item.content, admittedFeed = false, evidenceRefs = []) {
103
+ const route = this.#proactiveRouting;
104
+ if (!route) {
105
+ this.queueHostItem(intent, options);
106
+ return;
107
+ }
108
+ this.#proactiveEvents.add(intent.item.event_id);
109
+ if (this.#proactiveEvents.size > 2048)
110
+ this.#proactiveEvents.delete(this.#proactiveEvents.values().next().value);
111
+ const work = intent.item.source?.work_id;
112
+ const event = intent.item.event_id;
113
+ const notice = { event_id: event, kind: ((event.startsWith('progress:') || intent.item.kind === 'progress') ? 'task_progress' : event.startsWith('observation:') ? 'alert' : event.startsWith('suggestion:') ? 'suggestion' : 'task_result'), body, ...(work ? { work_id: work } : {}), priority: options.preemptiveAlert ? 100 : options.priority ?? 40, expires_in_ms: options.expiresAt == null ? null : Math.max(0, (options.expiresAt - this.#clock.now()) * 1000) };
114
+ const signal = this.#stop.signal;
115
+ notice.evidence_refs = evidenceRefs;
116
+ notice.valid = () => { if (signal.aborted)
117
+ return false; for (const ref of evidenceRefs) {
118
+ try {
119
+ const [channel, seq] = parseMemoryRef(ref);
120
+ if (!this.#runtime.memory?.channels.get(channel)?.items.some(item => item.seq === seq))
121
+ return false;
122
+ }
123
+ catch { /* Durable evidence is validated by the host. */ }
124
+ } if (options.stillWanted && !options.stillWanted())
125
+ return false; if (work && notice.kind === 'alert' && !this.#runtime.inFlightDelegate(work))
126
+ return false; if (options.owner) {
127
+ const state = this.session.delegateState(options.owner.delegate_id);
128
+ if (state !== 'running')
129
+ return false;
130
+ } return options.expiresAt == null || options.expiresAt > this.#clock.now(); };
131
+ if (!admittedFeed)
132
+ void route.publish(notice).catch(() => this.#onDiagnostic('[realtime-diagnostic] notification_admission_failed'));
133
+ if (!route.local()) {
134
+ void this.session.injectHostContext(intent.item).catch(() => this.#onDiagnostic('[realtime-diagnostic] notification_context_unavailable'));
135
+ return;
136
+ }
137
+ const prior = options.stillWanted;
138
+ this.queueHostItem(intent, { ...options, stillWanted: () => route.local() && (!prior || prior()) });
139
+ }
140
+ semanticAcknowledgementFor(responseId) { return this.#host.semanticAcknowledgementFor(responseId); }
141
+ #projection;
142
+ projectRuntimeEvent(event, currentConversation = true) {
143
+ this.#projection.projectRuntimeEvent(event, currentConversation);
144
+ }
145
+ onSuggestionSelected(suggestion, reason) {
146
+ this.#projection.onSuggestionSelected(suggestion, reason);
147
+ }
148
+ session;
149
+ #intake;
150
+ #intakeUser = null;
151
+ #localSpeechOnsetRevision = 0;
152
+ #lastLocalSpeechOnsetId = null;
153
+ #provider;
154
+ #runtime;
155
+ #clock;
156
+ #unsubscribeCodingProgress = null;
157
+ #codingProgressNarration;
158
+ #tools;
159
+ #providerSchemas;
160
+ #bridge;
161
+ #idFactory;
162
+ #onProviderTerminal;
163
+ #onExecutorState;
164
+ #captionScope = randomUUID();
165
+ #onCaption;
166
+ #onUserTranscriptAccepted;
167
+ #telemetry;
168
+ #onDiagnostic;
169
+ #controlledPreemptiveAlertReconnect;
170
+ #preemptiveAlertHistoryRecovery;
171
+ #preemptiveAlertHistoryPairs;
172
+ #approvalHost;
173
+ /** The coding-role executor's channel and label, resolved once from the registered manifests. */
174
+ #coding;
175
+ #agentRegistry;
176
+ #reconnectLock = new Mutex();
177
+ #pendingIngress = new Set();
178
+ #deliveryReady = new Signal();
179
+ /**
180
+ * The stop flag, as a real `AbortController`.
181
+ *
182
+ * Not a look-alike carrying only `aborted`: the runtime's `serve` registers an abort listener on
183
+ * whatever it is handed, so anything less than the real thing throws on the first `start()`.
184
+ * Replaced on each `start()` rather than reset, because an `AbortController` cannot be un-aborted.
185
+ */
186
+ #stop = new AbortController();
187
+ #unsubscribe = null;
188
+ #tasks = [];
189
+ #connected = false;
190
+ #providerFailed = false;
191
+ #clearingConversation = false;
192
+ #clearConversationOperation = null;
193
+ #conversationClearRevision = 0;
194
+ #audioStarted = new Set();
195
+ /** Exact revision-scoped join from provider user items to responses and Memory origins. */
196
+ #userOrigins = new UserOriginBindingLedger(MAX_TRACKED_TOOL_CALLS);
197
+ #unsubscribeExecutorApproval = null;
198
+ #awaitingUserOrigin = false;
199
+ #userOriginPreexistingResponseId = null;
200
+ #providerNotifications = new WeakSet();
201
+ #notifyProviderEvent(event) {
202
+ if (this.#providerNotifications.has(event))
203
+ return;
204
+ this.#providerNotifications.add(event);
205
+ this.#onProviderEvent?.(event);
206
+ }
207
+ #onProviderEvent;
208
+ #proactiveRouting;
209
+ constructor(options) {
210
+ this.#proactiveRouting = options.proactiveRouting;
211
+ this.#onProviderEvent = options.onProviderEvent;
212
+ // Preserve config capture order when custom controller factories invoke intake callbacks.
213
+ let commitProjectOperation = undefined;
214
+ let onProjectView = undefined;
215
+ let projectViewProvider = undefined;
216
+ let projectExpiryStepTimeoutMs = undefined;
217
+ const recovery = options.preemptiveAlertHistoryRecovery ?? 'none';
218
+ if (recovery !== 'none' && recovery !== 'packed') {
219
+ throw new TypeError('unknown preemptive-alert history recovery arm');
220
+ }
221
+ const pairs = options.preemptiveAlertHistoryPairs ?? 4;
222
+ // 1, 2, or 4 rather than any positive number: these are the arms the recovery experiment has,
223
+ // and an unlisted value would silently be a fifth arm nobody measured.
224
+ if (pairs !== 1 && pairs !== 2 && pairs !== 4) {
225
+ throw new TypeError('preemptive-alert history pair budget must be 1, 2, or 4');
226
+ }
227
+ this.#provider = options.provider;
228
+ this.#runtime = options.runtime;
229
+ this.#clock = options.runtime.clock;
230
+ this.#codingProgressNarration = options.runtime.codingProgressNarration ?? new CodingProgressNarrationState();
231
+ this.#subscribeCodingProgress();
232
+ this.#tools = options.tools;
233
+ // Deep-copied at construction: the provider is handed these on every connect, including after a
234
+ // reconnect, and a caller that mutated its own array afterwards would change what the model is
235
+ // told its tools are, mid-session.
236
+ this.#providerSchemas = structuredClone(options.providerSchemas ?? options.tools.schemas);
237
+ this.session = options.session;
238
+ this.#bridge = options.bridge;
239
+ this.#idFactory = options.idFactory ?? (() => `host_${randomHex()}`);
240
+ this.#onProviderTerminal = options.onProviderTerminal ?? noop;
241
+ this.#onExecutorState = options.onExecutorState ?? noop;
242
+ const onActiveWorkChanged = options.onActiveWorkChanged ?? noop;
243
+ this.#onCaption = options.onCaption;
244
+ this.#onUserTranscriptAccepted = options.onUserTranscriptAccepted;
245
+ this.#telemetry = options.telemetry;
246
+ this.#onDiagnostic = options.onDiagnostic ?? ((line) => {
247
+ console.log(line);
248
+ });
249
+ this.#controlledPreemptiveAlertReconnect = options.controlledPreemptiveAlertReconnect ?? false;
250
+ this.#preemptiveAlertHistoryRecovery = recovery;
251
+ this.#preemptiveAlertHistoryPairs = pairs;
252
+ const projectConfirmation = options.projectConfirmation;
253
+ const intake = options.intake === undefined ? undefined : {
254
+ ...options.intake,
255
+ clock: this.#clock,
256
+ record: (intake, kind, data) => {
257
+ if (kind === 'intake.failure' || kind === 'intake.timing')
258
+ this.#telemetry?.record(kind, {
259
+ intake_id: intake.intake_id, revision: intake.revision, ...data,
260
+ });
261
+ options.intake.record(intake, kind, data);
262
+ },
263
+ onStateChanged: () => this.#projection.publishExecutorState(),
264
+ idFactory: this.#idFactory,
265
+ dispatch: async (intake, stillWanted) => {
266
+ const result = await options.intake.dispatch(intake, stillWanted);
267
+ return this.#continuations.recordIntakeDispatch(intake, result);
268
+ },
269
+ diagnostic: code => this.#onDiagnostic(`[realtime-diagnostic] ${code}`),
270
+ invalidateProposal: () => this.#confirmation.invalidateProjectConfirmation('intake_amended'),
271
+ fact: (intake, text, kind) => {
272
+ this.queueHostItem(hostFactIntent({
273
+ kind: 'final', host_item_id: this.#idFactory(),
274
+ event_id: `intake:${intake.intake_id}:${intake.revision}:${kind ?? this.#idFactory()}`,
275
+ content: [...text].slice(0, MAX_HOST_FACT_CHARS).join(''),
276
+ }), { priority: USER_PRIORITY - 1, preemptive: false });
277
+ this.#deliveryReady.set();
278
+ },
279
+ prepare: intake => {
280
+ const proposal = this.#confirmation.prepareIntake(intake);
281
+ options.onIntakePrepared?.(intake, proposal);
282
+ return proposal;
283
+ },
284
+ };
285
+ this.#approvalHost = new ApprovalHost({
286
+ session: this.session, clock: this.#clock, idFactory: this.#idFactory,
287
+ controller: options.executorApproval, telemetry: this.#telemetry,
288
+ projectBlocking: () => projectConfirmation?.pending === true || projectConfirmation?.committing === true,
289
+ displayName: () => this.#coding?.display_name ?? '执行器',
290
+ queueHostItem: (intent, options) => this.queueHostItem(intent, options),
291
+ deliveryReady: () => this.#deliveryReady.set(),
292
+ reportDeliveryFailure: failure => this.#reportDeliveryFailure(failure),
293
+ retireProviderHostEventNow: eventId => this.#host.retireProviderHostEventNow(eventId),
294
+ retireProviderHostEvent: eventId => this.#host.retireProviderHostEvent(eventId),
295
+ removeQueuedPrompt: id => this.#host.removeQueuedExecutorApprovalPrompt(id),
296
+ releaseQuestion: id => this.#host.releaseExecutorApprovalQuestion(id),
297
+ });
298
+ this.#coding = null;
299
+ for (const adapter of options.runtime.executors.values()) {
300
+ if (adapter.manifest.roles.includes('coding')) {
301
+ this.#coding = { channel: adapter.manifest.name, display_name: adapter.manifest.display_name ?? adapter.manifest.name };
302
+ break;
303
+ }
304
+ }
305
+ this.#host = new HostDelivery({
306
+ session: this.session, runtime: this.#runtime, clock: this.#clock,
307
+ telemetry: this.#telemetry, approvalHost: this.#approvalHost,
308
+ controlledPreemptiveAlertReconnect: this.#controlledPreemptiveAlertReconnect,
309
+ clearingConversation: () => this.#clearingConversation,
310
+ stopped: () => this.#stop.signal.aborted,
311
+ providerFailed: () => this.#providerFailed,
312
+ wake: () => this.#deliveryReady.set(),
313
+ intakeFactEligible: (id, epoch) => this.#intake?.factEligible(id, epoch),
314
+ executorPriority: channel => this.#projection.executorPriority(channel),
315
+ executorDisplayName: channel => this.#projection.executorDisplayName(channel),
316
+ idFactory: this.#idFactory, onDiagnostic: this.#onDiagnostic,
317
+ reportDeliveryFailure: failure => this.#reportDeliveryFailure(failure),
318
+ responseCarriesPersonalRecall: responseId => this.#continuations.responseCarriesPersonalRecall(responseId),
319
+ originCanReferenceProof: key => this.#continuations.originCanReferenceProof(key),
320
+ originHasNonterminalReference: key => this.#continuations.originHasNonterminalReference(key),
321
+ });
322
+ this.#confirmation = new ProjectConfirmationFlow({
323
+ session: this.session, clock: this.#clock, projectConfirmation,
324
+ approvalHost: this.#approvalHost, coding: this.#coding, telemetry: this.#telemetry,
325
+ idFactory: this.#idFactory, onDiagnostic: this.#onDiagnostic,
326
+ intake: () => this.#intake,
327
+ get commitProjectOperation() { return commitProjectOperation; },
328
+ get onProjectView() { return onProjectView; },
329
+ get projectViewProvider() { return projectViewProvider; },
330
+ get projectExpiryStepTimeoutMs() { return projectExpiryStepTimeoutMs; },
331
+ userOrigins: {
332
+ itemForResponse: (epoch, response) => this.#userOrigins.itemForResponse(epoch, response),
333
+ revisionForItem: (epoch, item) => this.#userOrigins.revisionForItem(epoch, item),
334
+ hasOriginRef: (epoch, item) => this.#userOrigins.hasOriginRef(epoch, item),
335
+ bindRetryResponse: input => this.#userOrigins.bindRetryResponse(input),
336
+ },
337
+ bindResponseUserOrigin: (epoch, response) => this.#bindResponseUserOrigin(epoch, response),
338
+ failOriginTranscriptAndRefresh: (epoch, item) => {
339
+ this.#failUserOriginTranscript(epoch, item);
340
+ this.#awaitingUserOrigin = this.#userOrigins.hasUnboundRevision(epoch, this.session.userInputRevision);
341
+ if (!this.#awaitingUserOrigin)
342
+ this.#userOriginPreexistingResponseId = null;
343
+ },
344
+ continuations: {
345
+ takeDeferredForItem: item => this.#continuations.takeDeferredForItem(item),
346
+ takeConfirmationDeferredCalls: epoch => this.#continuations.takeConfirmationDeferredCalls(epoch),
347
+ abandonProjectConfirmationContinuation: (epoch, response) => this.#continuations.abandonProjectConfirmationContinuation(epoch, response),
348
+ releaseDeferredOriginCalls: (item, origin) => this.#continuations.releaseDeferredOriginCalls(item, origin),
349
+ },
350
+ reconnectProviderSession: options => this.#reconnectProviderSession(options),
351
+ deliveryPass: () => this.#deliveryPass(),
352
+ queueHostItem: (intent, options) => this.queueHostItem(intent, options),
353
+ wakeDelivery: () => this.#deliveryReady.set(),
354
+ reportDeliveryFailure: failure => this.#reportDeliveryFailure(failure),
355
+ stopSignal: () => this.#stop.signal,
356
+ conversationClearRevision: () => this.#conversationClearRevision,
357
+ clearingConversation: () => this.#clearingConversation,
358
+ });
359
+ const controllers = [...(options.agentControllers ?? [])];
360
+ if (options.agentControllerFactory !== undefined) {
361
+ const controller = options.agentControllerFactory.create({ intake });
362
+ this.#intake = controller.intake;
363
+ controllers.unshift(controller);
364
+ }
365
+ // Assembly factories may create controllers in a different order from the compiled roster.
366
+ controllers.sort((left, right) => options.tools.agent_descriptors.findIndex(value => value.name === left.descriptor.name)
367
+ - options.tools.agent_descriptors.findIndex(value => value.name === right.descriptor.name));
368
+ this.#agentRegistry = createAgentControllerRegistry({
369
+ controllers,
370
+ manifests: [...options.runtime.executors.values()].map(adapter => adapter.manifest),
371
+ });
372
+ if (!sameAgentDescriptors(this.#agentRegistry.descriptors, options.tools.agent_descriptors)) {
373
+ throw new TypeError('agent controller registry does not match compiled tool descriptors');
374
+ }
375
+ this.#continuations = new ToolContinuations({
376
+ ...(options.scheduleHost ? { scheduleHost: options.scheduleHost } : {}),
377
+ ...(options.scopedTool ? { scopedTool: options.scopedTool } : {}),
378
+ ...(options.validateScopedContext ? { validateScopedContext: options.validateScopedContext } : {}),
379
+ ...(options.taskHost ? { taskHost: options.taskHost } : {}),
380
+ session: this.session, host: this.#host, runtime: this.#runtime,
381
+ bridge: this.#bridge, tools: this.#tools, intake: this.#intake, approvalHost: this.#approvalHost,
382
+ coding: this.#coding, telemetry: this.#telemetry, idFactory: this.#idFactory,
383
+ executorPriority: channel => this.#projection.executorPriority(channel),
384
+ executorDisplayName: channel => this.#projection.executorDisplayName(channel),
385
+ publishExecutorState: () => this.#projection.publishExecutorState(),
386
+ queueHostItem: (intent, options) => this.queueHostItem(intent, options),
387
+ wakeDelivery: () => this.#deliveryReady.set(),
388
+ userOrigins: {
389
+ itemForResponse: (epoch, response) => this.#userOrigins.itemForResponse(epoch, response),
390
+ revisionForItem: (epoch, item) => this.#userOrigins.revisionForItem(epoch, item),
391
+ originRefForItem: (epoch, item) => this.#userOrigins.originRefForItem(epoch, item),
392
+ bindRetryResponse: input => this.#userOrigins.bindRetryResponse(input),
393
+ },
394
+ confirmTarget: event => this.#confirmation.confirmTarget(event),
395
+ isProjectConfirmationShadowItem: (epoch, item) => this.#confirmation.isProjectConfirmationShadowItem(epoch, item),
396
+ closeProjectConfirmationTool: event => this.#confirmation.closeProjectConfirmationTool(event),
397
+ handleProjectConfirmationDecision: (event, origin) => this.#confirmation.handleProjectConfirmationDecision(event, origin),
398
+ reconnectProviderSession: options => this.#reconnectProviderSession(options),
399
+ deliveryPass: () => this.#deliveryPass(),
400
+ recoverUncertainDelivery: failure => this.#recoverUncertainDelivery(failure),
401
+ reportDeliveryFailure: failure => this.#reportDeliveryFailure(failure),
402
+ awaitingUserOrigin: () => this.#awaitingUserOrigin,
403
+ userOriginPreexistingResponseId: () => this.#userOriginPreexistingResponseId,
404
+ discardedInputEpoch: () => this.#discardedInputEpoch,
405
+ stopSignal: () => this.#stop.signal,
406
+ intakeUser: () => this.#intakeUser,
407
+ currentUserTurn: (event, origin) => this.#currentUserTurn(event, origin),
408
+ agentController: name => this.#agentRegistry.controllers.get(name),
409
+ });
410
+ commitProjectOperation = options.commitProjectOperation;
411
+ onProjectView = options.onProjectView;
412
+ projectViewProvider = options.projectViewProvider;
413
+ projectExpiryStepTimeoutMs = options.projectExpiryStepTimeoutMs ?? PROJECT_EXPIRY_STEP_TIMEOUT_S * 1_000;
414
+ // Subscribed at construction: a proposal can expire before anything else happens, and the observer
415
+ // is the only notice of it.
416
+ this.#confirmation.subscribeExpiry();
417
+ this.#unsubscribeExecutorApproval = options.executorApproval?.observe(view => {
418
+ this.#approvalHost.syncExecutorApproval(view);
419
+ }) ?? null;
420
+ if (options.executorApproval !== undefined)
421
+ this.#approvalHost.syncExecutorApproval(options.executorApproval.view);
422
+ this.#projection = new ProviderProjection({
423
+ session: this.session, runtime: this.#runtime, clock: this.#clock, coding: this.#coding,
424
+ ...(options.taskHost ? { taskOwnsWork: (workId) => options.taskHost.tasks.list().some(task => task.work_ids.includes(workId)) } : {}),
425
+ codingProgressNarration: this.#codingProgressNarration,
426
+ generatePlan: options.intake?.settings.generate_plan !== false, telemetry: this.#telemetry,
427
+ idFactory: this.#idFactory,
428
+ queueHostItem: (intent, options, body, admittedFeed, evidenceRefs) => this.#queueProactive(intent, options, body, admittedFeed, evidenceRefs),
429
+ agentNameForChannel: channel => this.#agentRegistry.agentNameForChannel(channel),
430
+ clearingConversation: () => this.#clearingConversation,
431
+ onActiveWorkChanged,
432
+ onExecutorState: this.#onExecutorState,
433
+ preparing: () => this.#intake?.preparing === true,
434
+ onDiagnostic: this.#onDiagnostic,
435
+ resolveSyncResult: event => this.#continuations.resolveSyncResult(event),
436
+ expireSyncResult: event => this.#continuations.expireSyncResult(event),
437
+ hasSemanticAcknowledgement: id => this.#host.hasSemanticAcknowledgement(id),
438
+ fenceSemanticAcknowledgement: delegate => this.#host.fenceSemanticAcknowledgement(delegate),
439
+ retireDelegateHostEvents: delegate => this.#host.retireDelegateHostEvents(delegate),
440
+ rememberDelegateHostEvent: (delegate, event) => this.#host.rememberDelegateHostEvent(delegate, event),
441
+ rememberCodingProgressHostEvent: event => this.#host.rememberCodingProgressHostEvent(event),
442
+ coalesceCodingProgress: () => {
443
+ this.#host.coalesceCodingProgress();
444
+ },
445
+ });
446
+ }
447
+ get executorState() {
448
+ return this.#projection.executorState;
449
+ }
450
+ agentNameForChannel(channel) { return this.#agentRegistry.agentNameForChannel(channel); }
451
+ onProjectWorkspaceChanged(workspaceId) {
452
+ this.#intake?.workspaceChanged(workspaceId);
453
+ }
454
+ get stopped() {
455
+ return this.#stop.signal.aborted;
456
+ }
457
+ /** True from the synchronous clear fence until a blank provider epoch is fully ready. */
458
+ get clearingConversation() {
459
+ return this.#clearingConversation;
460
+ }
461
+ /** Clear the current conversation while leaving independently running executors alone. */
462
+ clearConversation() {
463
+ if (this.#clearConversationOperation !== null)
464
+ return this.#clearConversationOperation;
465
+ if (!this.#connected || this.stopped || this.#providerFailed) {
466
+ return Promise.reject(new Error('realtime service is not available for conversation clear'));
467
+ }
468
+ // Publish single-flight ownership before playback/confirmation callbacks can reenter clear.
469
+ const operation = Promise.resolve().then(() => this.#clearConversationAfterFence());
470
+ this.#clearConversationOperation = operation;
471
+ // Install every externally visible fence before returning the Promise. Old provider input and
472
+ // user authority must become unusable in the same synchronous turn as the clear request.
473
+ this.#conversationClearRevision += 1;
474
+ this.#clearingConversation = true;
475
+ this.#host.pauseForConversationClear();
476
+ const clearingGeneration = this.session.beginConversationClear();
477
+ if (clearingGeneration !== null)
478
+ this.#host.startPreemptiveAlertClearDeadline(clearingGeneration);
479
+ this.#intake?.cancel();
480
+ this.#intakeUser = null;
481
+ this.#host.releaseUrgentOwner();
482
+ this.#confirmation.invalidateProjectConfirmation('conversation_cleared');
483
+ do {
484
+ this.#approvalHost.invalidateExecutorApproval('conversation_cleared');
485
+ } while (this.#approvalHost.pending);
486
+ void operation.then(() => {
487
+ if (this.#clearConversationOperation !== operation)
488
+ return;
489
+ this.#clearConversationOperation = null;
490
+ this.#clearingConversation = false;
491
+ this.#host.resumeAfterConversationClear();
492
+ this.#deliveryReady.set();
493
+ }, failure => {
494
+ if (this.#clearConversationOperation !== operation)
495
+ return;
496
+ this.#clearConversationOperation = null;
497
+ this.#onDiagnostic(`[realtime-diagnostic] conversation_clear_failed type=${diagnosticName(failure)}`);
498
+ // A failed durable clear or replacement cannot leave a live service silently dropping input.
499
+ // Use the existing fatal lifecycle; a new service must reopen and revalidate its resources.
500
+ this.#taskFailed(this.#stop);
501
+ });
502
+ return operation;
503
+ }
504
+ async #clearConversationAfterFence() {
505
+ // Normal ingress stays concurrent: a newer user turn must be able to supersede a pending tool.
506
+ // The synchronous clear fence prevents new admissions while existing handlers settle.
507
+ await Promise.allSettled([...this.#pendingIngress]);
508
+ await this.#reconnectLock.run(async () => {
509
+ await this.#host.withDeliveryLock(async () => {
510
+ if (this.#runtime.clearConversation === undefined) {
511
+ throw new Error('runtime conversation clear is unavailable');
512
+ }
513
+ await this.#runtime.clearConversation();
514
+ this.#resetConversationLedgers();
515
+ await this.session.resetConversation({ tools: structuredClone(this.#providerSchemas) });
516
+ this.#userOrigins.beginEpoch(this.session.sessionEpoch);
517
+ this.#clearCaptions();
518
+ this.#projection.publishExecutorState();
519
+ });
520
+ });
521
+ }
522
+ #subscribeCodingProgress() {
523
+ if (this.#unsubscribeCodingProgress !== null)
524
+ return;
525
+ this.#unsubscribeCodingProgress = this.#codingProgressNarration.observe(() => {
526
+ this.#host.retireCodingProgress();
527
+ });
528
+ }
529
+ async connect() {
530
+ this.#subscribeCodingProgress();
531
+ if (this.#connected)
532
+ return;
533
+ await this.session.connect({ tools: structuredClone(this.#providerSchemas) });
534
+ if (Number.isInteger(this.session.sessionEpoch) && this.session.sessionEpoch >= 0) {
535
+ this.#userOrigins.beginEpoch(this.session.sessionEpoch);
536
+ }
537
+ this.#confirmation.syncProjectConfirmationIsolation();
538
+ this.#approvalHost.sync();
539
+ this.#unsubscribe = this.#runtime.observe((event, currentConversation = true) => {
540
+ this.projectRuntimeEvent(event, currentConversation);
541
+ });
542
+ this.#connected = true;
543
+ }
544
+ /**
545
+ * Start the three long-lived loops.
546
+ *
547
+ * Idempotent by design: `start` is called from more than one place during bring-up, and a second
548
+ * set of loops would consume the same provider stream twice.
549
+ */
550
+ async start() {
551
+ await this.connect();
552
+ if (this.#tasks.length > 0)
553
+ return;
554
+ // A fresh controller: an aborted one cannot be reused, and `start` after `close` has to work.
555
+ // Each guard is handed the controller it belongs to, so a task abandoned by an earlier close
556
+ // cannot report a failure against the run that replaced it.
557
+ const run = new AbortController();
558
+ this.#stop = run;
559
+ const signal = run.signal;
560
+ this.#tasks = [
561
+ this.#guardTask(this.#receiveLoop(signal), run),
562
+ this.#guardTask(this.#deliveryLoop(signal), run),
563
+ this.#guardTask(this.#runtime.serve(signal), run),
564
+ ];
565
+ }
566
+ /**
567
+ * Stop everything, and surface a provider close failure rather than swallowing it.
568
+ *
569
+ * The order matters. State that could authorize new work is cleared *before* awaiting anything, so
570
+ * a task still running during the await cannot act on it. The provider close is attempted even if
571
+ * that clearing threw, and its own failure is held and re-raised after every task has been
572
+ * cancelled -- a close that failed still has to leave the service stopped.
573
+ */
574
+ async close() {
575
+ this.#unsubscribeCodingProgress?.();
576
+ this.#unsubscribeCodingProgress = null;
577
+ this.#stop.abort();
578
+ this.#confirmation.invalidateProjectConfirmation('service_closed');
579
+ this.#approvalHost.invalidateExecutorApproval('service_closed');
580
+ this.#confirmation.unsubscribeExpiry();
581
+ if (this.#unsubscribeExecutorApproval !== null) {
582
+ this.#unsubscribeExecutorApproval();
583
+ this.#unsubscribeExecutorApproval = null;
584
+ }
585
+ this.#confirmation.discardPendingExpiries();
586
+ // The drain is shutdown-owned work. A promise cannot be cancelled, so its continuations check the
587
+ // signal instead -- and this waits, bounded, so a reconnect cannot land after `close` returned.
588
+ const draining = this.#confirmation.expiryDrain();
589
+ this.#host.close();
590
+ this.#deliveryReady.set();
591
+ if (this.#unsubscribe !== null) {
592
+ this.#unsubscribe();
593
+ this.#unsubscribe = null;
594
+ }
595
+ // Held rather than propagated immediately: a close that failed still has to leave every task
596
+ // cancelled and the service marked disconnected, so the failure is re-raised only after that.
597
+ let closeFailure = null;
598
+ let closeAbandoned = false;
599
+ try {
600
+ // Bounded like the loops are. A transport that never finishes closing would otherwise block
601
+ // application shutdown forever, which is exactly the failure mode a degraded transport has.
602
+ closeAbandoned = !await resolvedWithin(this.#provider.close(), SHUTDOWN_GRACE_MS);
603
+ }
604
+ catch (cause) {
605
+ closeFailure = { cause };
606
+ }
607
+ if (closeAbandoned) {
608
+ this.#onDiagnostic('[realtime-diagnostic] shutdown_provider_close_abandoned');
609
+ }
610
+ const backgroundTasks = [
611
+ ...this.#tasks,
612
+ ...this.#host.retirementTasks(),
613
+ ...this.#approvalHost.pendingTasks,
614
+ ...this.#host.acknowledgementReleaseTasks(),
615
+ ...this.#confirmation.carrierReleaseTasks(),
616
+ ];
617
+ const tasks = draining === null ? backgroundTasks : [...backgroundTasks, draining];
618
+ this.#tasks = [];
619
+ // Bounded. A promise cannot be cancelled from outside the way an asyncio task can, so a loop that
620
+ // ignores the abort would make `close` wait forever -- and a service that never finishes closing
621
+ // is worse than one that reports a task it could not stop. The loops all observe the signal, so
622
+ // reaching the timeout means one of them is genuinely stuck.
623
+ const abandoned = await settleWithin(tasks, SHUTDOWN_GRACE_MS);
624
+ this.#connected = false;
625
+ if (abandoned > 0) {
626
+ this.#onDiagnostic(`[realtime-diagnostic] shutdown_tasks_abandoned count=${abandoned}`);
627
+ }
628
+ if (closeFailure !== null)
629
+ throw asError(closeFailure.cause);
630
+ }
631
+ #inputController = new AbortController();
632
+ #inputReady = null;
633
+ #inputChanged = new Signal();
634
+ #discardedInputEpoch = -1;
635
+ /** Replace only the provider session; host work remains owned by the existing graph. */
636
+ detachTaskConversation() {
637
+ this.#conversationClearRevision++;
638
+ this.#intakeUser = null;
639
+ }
640
+ discardInputAudio() {
641
+ // A phone-owned provider may still be awaiting its first successful SDK handshake.
642
+ if (!this.#connected)
643
+ return Promise.resolve();
644
+ this.#inputController.abort();
645
+ this.#inputController = new AbortController();
646
+ this.#discardedInputEpoch = this.session.sessionEpoch;
647
+ // Serialize repeated disconnects, including one during a pending replacement. A failed
648
+ // replacement deliberately leaves this barrier rejected so subsequent input stays closed.
649
+ const previous = this.#inputReady;
650
+ const replace = async () => {
651
+ this.#discardedInputEpoch = this.session.sessionEpoch;
652
+ await this.#reconnectProviderSession({ reason: 'client_disconnect' });
653
+ };
654
+ const ready = previous === null ? replace() : previous.then(replace, replace);
655
+ this.#inputReady = ready;
656
+ this.#inputChanged.set();
657
+ void ready.catch(() => undefined);
658
+ return ready;
659
+ }
660
+ get inputCapabilities() { return [...(this.#provider.submitText ? ['text_input'] : []), ...(this.#provider.transcribeDraft ? ['dictation'] : [])]; }
661
+ async transcribeDraft(pcm, signal) {
662
+ if (!this.#provider.transcribeDraft)
663
+ throw new Error('dictation unavailable');
664
+ return this.#provider.transcribeDraft(pcm, AbortSignal.any([signal, this.#inputController.signal]));
665
+ }
666
+ async submitText(text) {
667
+ const controller = this.#inputController;
668
+ if (this.#inputReady !== null)
669
+ await this.#inputReady;
670
+ if (controller.signal.aborted || !this.#provider.submitText)
671
+ throw new Error('text input unavailable');
672
+ await this.#provider.submitText(text, controller.signal);
673
+ }
674
+ async sendAudio(pcm) {
675
+ if (this.#clearingConversation)
676
+ return;
677
+ const controller = this.#inputController;
678
+ if (this.#inputReady !== null)
679
+ await this.#inputReady;
680
+ if (controller.signal.aborted || this.#clearingConversation)
681
+ return;
682
+ await this.#provider.sendAudio(pcm, controller.signal);
683
+ }
684
+ async localSpeechOnset(speechId) {
685
+ if (this.#clearingConversation)
686
+ return;
687
+ if (speechId !== this.#lastLocalSpeechOnsetId) {
688
+ this.#lastLocalSpeechOnsetId = speechId;
689
+ this.#localSpeechOnsetRevision += 1;
690
+ }
691
+ this.#intake?.userInputStarted();
692
+ this.#approvalHost.noteExecutorApprovalOnsetBeforeContext();
693
+ const generation = this.session.currentGeneration;
694
+ if (generation !== null) {
695
+ const key = callKey(generation.session_epoch, generation.response_id);
696
+ this.#host.rememberLocalSpeechInterruption(key);
697
+ }
698
+ this.#approvalHost.releaseQuestionOnOnset();
699
+ await this.session.localSpeechOnset(speechId);
700
+ }
701
+ /** Settle the exact proposal shown by the renderer; the controller remains the sole authority. */
702
+ projectConfirmationDecision(proposalId, confirmed) {
703
+ return this.#trackIngress(() => this.#confirmation.projectConfirmationDecision(proposalId, confirmed));
704
+ }
705
+ /** Renderer clicks are direct local-user authority on the same one-shot controller as voice. */
706
+ executorApprovalDecision(approvalId, approved, scope) {
707
+ if (this.#clearingConversation)
708
+ return false;
709
+ return this.#approvalHost.executorApprovalDecision(approvalId, approved, scope);
710
+ }
711
+ async waitStopped() {
712
+ await Promise.allSettled(this.#tasks);
713
+ }
714
+ /**
715
+ * Deliver everything the floor currently allows.
716
+ *
717
+ * The public entry point. It exists to translate an uncertain delivery into a reconnect attempt;
718
+ * the reconnect path itself must call `#deliveryPass` instead, or it would re-enter here while
719
+ * holding the reconnect lock.
720
+ */
721
+ async flushHostItems() {
722
+ try {
723
+ await this.#deliveryPass();
724
+ }
725
+ catch (cause) {
726
+ if (cause instanceof ItemDeliveryUncertainError) {
727
+ await this.#recoverUncertainDelivery(cause);
728
+ return;
729
+ }
730
+ throw cause;
731
+ }
732
+ }
733
+ /**
734
+ * An injection whose outcome the provider never confirmed.
735
+ *
736
+ * Retried exactly once per item, and never for a recovery item -- a recovery injection is what a
737
+ * reconnect *is*, so retrying it through another reconnect would recurse. A second uncertainty for
738
+ * the same item means the transport cannot be trusted to report anything, and the service stops
739
+ * rather than guessing whether the model has seen a fact.
740
+ */
741
+ async #recoverUncertainDelivery(failure) {
742
+ if (failure.item_kind === 'recovery') {
743
+ this.#failUncertainDelivery();
744
+ return;
745
+ }
746
+ if (!this.#host.admitUncertainDeliveryRetry(failure.host_item_id)) {
747
+ this.#failUncertainDelivery();
748
+ return;
749
+ }
750
+ try {
751
+ const reconnected = await this.#reconnectProviderSession({
752
+ reason: 'uncertain_delivery',
753
+ expectedEpoch: failure.session_epoch,
754
+ });
755
+ if (!reconnected)
756
+ await this.#deliveryPass();
757
+ }
758
+ catch (cause) {
759
+ if (cause instanceof ItemDeliveryUncertainError) {
760
+ this.#failUncertainDelivery();
761
+ return;
762
+ }
763
+ throw cause;
764
+ }
765
+ }
766
+ #failUncertainDelivery() {
767
+ this.#onDiagnostic('[realtime-diagnostic] uncertain_delivery_exhausted');
768
+ this.#providerFailed = true;
769
+ this.#host.releaseFailedDelivery();
770
+ this.#stop.abort();
771
+ this.#deliveryReady.set();
772
+ }
773
+ /**
774
+ * One pass over the queue, under the delivery lock.
775
+ *
776
+ * The stale-hold release happens first and unconditionally: a user hold that has outlived its
777
+ * window blocks every delivery, so checking it after the floor test would let one abandoned hold
778
+ * stall the queue indefinitely.
779
+ *
780
+ * The continuation re-drive at the end is the subtle part. A preempt that was armed and is no
781
+ * longer armed means the thing blocking continuations has cleared, and nothing else will notice --
782
+ * so this pass has to hand off. It happens *outside* the lock because the continuation drive takes
783
+ * its own, and CP3 says the two are never held together.
784
+ */
785
+ async #deliveryPass() {
786
+ if (await this.#host.deliveryPass())
787
+ await this.driveContinuations();
788
+ }
789
+ /** Blank dead-epoch speculative text on both roles after a reconnect. */
790
+ #clearCaptions() {
791
+ this.session.resetCaptions();
792
+ if (this.#onCaption !== undefined) {
793
+ this.#onCaption({ role: 'assistant', text: '', final: true });
794
+ this.#onCaption({ role: 'user', text: '', final: true });
795
+ }
796
+ }
797
+ /** Drop every service projection that could make the fresh provider epoch describe old dialogue. */
798
+ #resetConversationLedgers() {
799
+ this.#host.resetDelivery();
800
+ this.#host.resetUncertainDeliveryRetries();
801
+ this.#continuations.resetCalls();
802
+ this.#host.resetAcknowledgements();
803
+ this.#audioStarted.clear();
804
+ this.#continuations.resetDeferredAndSync();
805
+ this.#confirmation.reset();
806
+ this.#projection.reset();
807
+ this.#host.resetOriginProofs();
808
+ this.#awaitingUserOrigin = false;
809
+ this.#userOriginPreexistingResponseId = null;
810
+ this.#intakeUser = null;
811
+ this.#localSpeechOnsetRevision = 0;
812
+ this.#lastLocalSpeechOnsetId = null;
813
+ this.#deliveryReady.clear();
814
+ }
815
+ /**
816
+ * Replace the provider session, and reconcile everything that referred to the old one.
817
+ *
818
+ * Ported from `_reconnect_provider_session`. The whole method runs under `#reconnectLock`, and the
819
+ * two things that look like implementation detail are both load-bearing:
820
+ *
821
+ * The source epoch is armed *before* the await, so a preemptive alert already waiting on the session's
822
+ * response-request lock can see that the provider identity advanced even if it runs before this
823
+ * resumes. Arming it after would let that alert act against a session that no longer exists.
824
+ *
825
+ * The tail calls the private `#deliveryPass` rather than the public `flushHostItems`. The public
826
+ * wrapper turns an uncertain delivery into a reconnect, and reconnecting while already holding the
827
+ * lock would deadlock. Confirmation uncertainty is meant to escape to the caller here.
828
+ *
829
+ * Returns false when the epoch moved while waiting for the lock: someone else already replaced the
830
+ * session, and doing it again would discard a *live* one.
831
+ */
832
+ async #reconnectProviderSession(options) {
833
+ const requestedEpoch = options.expectedEpoch ?? this.session.sessionEpoch;
834
+ this.#telemetry?.record('provider.reconnect', { reason: options.reason, outcome: 'started' });
835
+ try {
836
+ return await this.#reconnectLock.run(async () => {
837
+ if (this.session.sessionEpoch !== requestedEpoch) {
838
+ this.#telemetry?.record('provider.reconnect', {
839
+ reason: options.reason,
840
+ outcome: 'skipped_epoch',
841
+ });
842
+ return false;
843
+ }
844
+ const oldEpoch = this.session.sessionEpoch;
845
+ this.#confirmation.invalidateProjectConfirmation('provider_replaced');
846
+ this.#approvalHost.invalidateExecutorApproval('provider_replaced');
847
+ this.#host.beginReconnect(oldEpoch);
848
+ // Provider identity and session epoch must advance before queued host delivery resumes.
849
+ await this.session.reconnect({
850
+ tools: structuredClone(this.#providerSchemas),
851
+ withProviderTransition: work => this.#host.withDeliveryLock(work),
852
+ });
853
+ // Only if nothing cleared it while we were awaiting. A user who started speaking during the
854
+ // reconnect has already activated the new session, so demanding an activation would be wrong.
855
+ this.#host.finishReconnect(oldEpoch);
856
+ const retryOwner = this.#host.currentUrgentOwner;
857
+ // Every origin binding named items in a session that is gone. Keeping any of it would let a
858
+ // tool call cite evidence the new provider has never seen.
859
+ this.#awaitingUserOrigin = false;
860
+ this.#userOriginPreexistingResponseId = null;
861
+ this.#userOrigins.beginEpoch(this.session.sessionEpoch);
862
+ this.#continuations.clearDeferred();
863
+ this.#host.releaseUrgentHostResponseForEpoch(oldEpoch);
864
+ // An urgent item that was injected but never got a response is the one case worth retrying: it
865
+ // was delivered into a session that died before speaking it, so the user heard nothing. One that
866
+ // *did* get a response was taken up by the provider, and re-queueing would say it twice.
867
+ if (retryOwner?.session_epoch === oldEpoch && retryOwner.response_id === null) {
868
+ this.#host.requeueHostItem(retryOwner.queued);
869
+ }
870
+ this.#clearCaptions();
871
+ this.#audioStarted.clear();
872
+ this.#continuations.reconcileToolStateAfterReconnect(oldEpoch);
873
+ this.#host.reopenFailedSemanticAcknowledgements();
874
+ this.#host.reconcileSemanticAcknowledgementsAfterReconnect();
875
+ await this.driveContinuations();
876
+ await this.#deliveryPass();
877
+ this.#telemetry?.record('provider.reconnect', {
878
+ reason: options.reason,
879
+ outcome: 'completed',
880
+ });
881
+ return true;
882
+ });
883
+ }
884
+ catch (failure) {
885
+ this.#telemetry?.record('provider.reconnect', { reason: options.reason, outcome: 'failed' });
886
+ throw failure;
887
+ }
888
+ }
889
+ /** Live host preference: switching never stops or restarts executor work. */
890
+ setCodingProgressNarration(mode) { this.#codingProgressNarration.setMode(mode); }
891
+ /**
892
+ * Consume the provider stream until it ends or the service stops.
893
+ *
894
+ * The epoch filter is the first thing in the loop and it is not redundant with the session's own:
895
+ * `events()` already drops mismatched events, and dropping them again here is what makes a
896
+ * reconnect that happens *while* an event is in flight safe.
897
+ *
898
+ * The outer loop distinguishes three endings. A stopped service or a failed provider returns. An
899
+ * epoch that changed means a reconnect replaced the stream, so it re-subscribes. A stream that
900
+ * ended having yielded nothing is a provider that is simply gone.
901
+ */
902
+ async #receiveLoop(signal) {
903
+ while (!signal.aborted) {
904
+ const streamEpoch = this.session.sessionEpoch;
905
+ let received = false;
906
+ // The signal goes to the provider: at shutdown the stream is normally parked with nothing to
907
+ // say, and an iterator suspended in `await` cannot be stopped from out here.
908
+ for await (const event of this.#provider.events(signal)) {
909
+ if (signal.aborted)
910
+ return;
911
+ if (event.session_epoch <= this.#discardedInputEpoch)
912
+ continue;
913
+ if (event.session_epoch !== this.session.sessionEpoch)
914
+ continue;
915
+ received = true;
916
+ try {
917
+ await this.handleEvent(event);
918
+ this.#notifyProviderEvent(event);
919
+ }
920
+ catch (cause) {
921
+ if (event.kind === 'response_terminal')
922
+ this.#notifyProviderEvent(event);
923
+ if (cause instanceof ItemDeliveryUncertainError) {
924
+ await this.#recoverUncertainDelivery(cause);
925
+ }
926
+ else if (cause instanceof RealtimeDeliveryError) {
927
+ this.#reportDeliveryFailure(cause);
928
+ }
929
+ else {
930
+ throw cause;
931
+ }
932
+ }
933
+ if (this.#stop.signal.aborted)
934
+ return;
935
+ }
936
+ if (this.#stop.signal.aborted || this.#providerFailed)
937
+ return;
938
+ if (streamEpoch <= this.#discardedInputEpoch && this.#inputReady !== null) {
939
+ while (!signal.aborted) {
940
+ const ready = this.#inputReady;
941
+ try {
942
+ await ready;
943
+ if (ready === this.#inputReady)
944
+ break;
945
+ }
946
+ catch {
947
+ // Stay fail-closed until another remote disconnect requests a replacement.
948
+ this.#inputChanged.clear();
949
+ if (ready === this.#inputReady)
950
+ await this.#inputChanged.wait(signal);
951
+ }
952
+ }
953
+ if (this.#stop.signal.aborted)
954
+ return;
955
+ }
956
+ // Reconnect closes the old iterator before connect/observers publish the new session epoch.
957
+ // Join that transition before deciding an ended stream means the provider disappeared.
958
+ await this.#reconnectLock.run(() => Promise.resolve());
959
+ if (this.#stop.signal.aborted || this.#providerFailed)
960
+ return;
961
+ if (this.session.sessionEpoch !== streamEpoch)
962
+ continue;
963
+ if (!received)
964
+ return;
965
+ }
966
+ }
967
+ /**
968
+ * Deliver queued host items whenever something signals there may be work.
969
+ *
970
+ * A delivery failure is reported and the loop continues: one item the provider refused must not
971
+ * take down the loop that would deliver the next one.
972
+ */
973
+ async #deliveryLoop(signal) {
974
+ while (!signal.aborted) {
975
+ // Raced against the signal, not just checked after: the wait is where this loop spends almost
976
+ // all of its time, and a latch nobody sets again would hold it past shutdown.
977
+ await this.#deliveryReady.wait(signal);
978
+ this.#deliveryReady.clear();
979
+ if (signal.aborted)
980
+ return;
981
+ try {
982
+ await this.flushHostItems();
983
+ // R105: a sync resolution may have made a held batch ready. The drive is reentrancy-safe --
984
+ // it early-returns while a batch is requested or bound.
985
+ await this.driveContinuations();
986
+ }
987
+ catch (cause) {
988
+ if (cause instanceof RealtimeDeliveryError) {
989
+ this.#reportDeliveryFailure(cause);
990
+ }
991
+ else {
992
+ throw cause;
993
+ }
994
+ }
995
+ }
996
+ }
997
+ /**
998
+ * Ingest one provider event.
999
+ *
1000
+ * The shape is a sequence of `if isinstance` blocks in the oracle and stays one here, deliberately:
1001
+ * a single event can be several things at once to this layer -- a `ResponseStarted` binds a user
1002
+ * origin *and* a semantic acknowledgement *and* a continuation -- so a switch that ran one arm per
1003
+ * event would have to duplicate the shared tail.
1004
+ *
1005
+ * Two events never reach the session at all. A cancel rejection is routed by response ownership:
1006
+ * confirmation carriers recover their provider epoch, while every other rejection is the preemptive alert's to
1007
+ * arbitrate. A provider error is about the transport rather than the conversation.
1008
+ *
1009
+ * The tail is the part worth reading twice: after everything an event implies has been recorded,
1010
+ * continuations are driven (only if the session accepted it -- a rejected event changed nothing to
1011
+ * speak about) and then a delivery pass runs unconditionally, because the floor may have opened even
1012
+ * for an event the session refused.
1013
+ */
1014
+ handleEvent(event) {
1015
+ return this.#trackIngress(() => this.#handleEvent(event));
1016
+ }
1017
+ #trackIngress(action) {
1018
+ if (this.#clearingConversation)
1019
+ return Promise.resolve();
1020
+ // Register before invoking callbacks so a reentrant clear also joins this handler.
1021
+ const operation = Promise.resolve().then(async () => {
1022
+ if (!this.#clearingConversation)
1023
+ await action();
1024
+ });
1025
+ this.#pendingIngress.add(operation);
1026
+ void operation.then(() => { this.#pendingIngress.delete(operation); }, () => { this.#pendingIngress.delete(operation); });
1027
+ return operation;
1028
+ }
1029
+ async #handleEvent(event) {
1030
+ if (event.session_epoch <= this.#discardedInputEpoch)
1031
+ return;
1032
+ this.#confirmation.syncProjectConfirmationIsolation();
1033
+ if (event.kind === 'response_cancel_rejected') {
1034
+ if (this.#confirmation.responseIsQuarantined(event.session_epoch, event.response_id)) {
1035
+ await this.#confirmation.recoverProjectConfirmationCarrier(event.session_epoch, event.response_id, 'cancel_rejected');
1036
+ return;
1037
+ }
1038
+ // The provider kept speaking through a preemption. The preemptive-alert arbiter owns it, and it does not reach
1039
+ // the session at all: this is about the transport, not the conversation.
1040
+ await this.#handlePreemptiveAlertCancelRejected(event);
1041
+ return;
1042
+ }
1043
+ if (event.kind === 'provider_error') {
1044
+ this.#telemetry?.record('provider.error', { session_epoch: event.session_epoch, code: event.code, recoverable: event.recoverable });
1045
+ await this.session.accept(event);
1046
+ this.#onDiagnostic(`[realtime-diagnostic] provider_error code=${event.code} recoverable=${event.recoverable}`);
1047
+ if (event.recoverable) {
1048
+ await this.#reconnectProviderSession({
1049
+ reason: 'recoverable_provider_error',
1050
+ expectedEpoch: this.session.sessionEpoch,
1051
+ });
1052
+ this.#clearCaptions();
1053
+ }
1054
+ else {
1055
+ this.#providerFailed = true;
1056
+ this.#approvalHost.invalidateExecutorApproval('provider_failed');
1057
+ this.#host.releaseUrgentOwner();
1058
+ this.#host.releasePreemptionAfterFailure();
1059
+ this.#stop.abort();
1060
+ }
1061
+ return;
1062
+ }
1063
+ const approvalEvent = this.#approvalHost.beforeEvent(event);
1064
+ if (this.#telemetry !== undefined) {
1065
+ if (event.kind === 'response_audio_delta') {
1066
+ // First delta only: the metric is time-to-first-audio, and recording every delta would make
1067
+ // it a throughput counter instead.
1068
+ if (!this.#audioStarted.has(event.response_id)) {
1069
+ this.#audioStarted.add(event.response_id);
1070
+ this.#telemetry.record('provider.first_audio_delta', { session_epoch: event.session_epoch, response_id: event.response_id });
1071
+ }
1072
+ }
1073
+ else if (event.kind === 'response_terminal') {
1074
+ this.#audioStarted.delete(event.response_id);
1075
+ }
1076
+ }
1077
+ // Captured before `accept`, because a terminal is what *removes* the owner's response and the
1078
+ // release below needs to know which owner this terminal belonged to.
1079
+ const terminalOwner = event.kind === 'response_terminal'
1080
+ ? this.#host.urgentOwnerForResponse(event.session_epoch, event.response_id)
1081
+ : null;
1082
+ // A tool call in a turn that is meant to be waiting for a confirmation is refused before the
1083
+ // session sees it: letting it through would have the model acting inside the very turn whose answer
1084
+ // it is supposed to be waiting for.
1085
+ const confirmTarget = event.kind === 'tool_call_ready' ? this.#confirmation.confirmTarget(event) : null;
1086
+ const toolBinding = event.kind === 'tool_call_ready' ? this.#tools.bindings.get(event.name) : undefined;
1087
+ const stoppingTask = event.kind === 'tool_call_ready' && toolBinding?.kind === 'host' && (event.name === 'cancel' || (event.name === 'task' && event.arguments.operation === 'cancel'));
1088
+ const isConfirmationDecision = confirmTarget === 'project';
1089
+ const blockedConfirmationTool = event.kind === 'tool_call_ready'
1090
+ && this.#confirmation.blocksProjectConfirmationTool(event)
1091
+ && !isConfirmationDecision && !stoppingTask;
1092
+ const isExecutorApprovalDecision = confirmTarget === 'approval';
1093
+ const blockedExecutorApprovalTool = event.kind === 'tool_call_ready'
1094
+ && this.#approvalHost.blocksExecutorApprovalTool(event)
1095
+ && !isExecutorApprovalDecision && !stoppingTask;
1096
+ // An automatic provider may create the response that will emit the confirmation function before VAD reports
1097
+ // speech end. That response is an authorization carrier, not an audible assistant turn. Let it
1098
+ // acquire an origin while the user still owns the floor, but never bypass the one-shot fence for
1099
+ // a stale host-requested confirmation question.
1100
+ const { confirmationFencePendingAtStart, confirmationResponseStartsDuringSpeech } = this.#confirmation.beforeEvent(event);
1101
+ if ('response_id' in event && typeof event.response_id === 'string' && this.#proactiveRouting && !this.#proactiveRouting.local() && this.isProactiveResponse(event.response_id))
1102
+ this.session.suppressResponse(event.response_id);
1103
+ const accepted = blockedConfirmationTool || blockedExecutorApprovalTool
1104
+ ? false
1105
+ : await this.session.accept(event, {
1106
+ allowResponseStartDuringUserSpeech: confirmationResponseStartsDuringSpeech
1107
+ || approvalEvent.responseStartsDuringSpeech
1108
+ || approvalEvent.orphanedExecutorRetryCandidate,
1109
+ });
1110
+ const executorQuarantinedResponse = await this.#approvalHost.afterEventAccepted(event, accepted, approvalEvent);
1111
+ this.#confirmation.afterEventAccepted(event, accepted, confirmationFencePendingAtStart, confirmationResponseStartsDuringSpeech);
1112
+ if (event.kind === 'response_started' || event.kind === 'response_audio_delta') {
1113
+ this.#host.learnPreemptedResponse(event);
1114
+ this.#host.recordPreemptiveAlertCancelSent(event.response_id);
1115
+ }
1116
+ // Unconditional, and before the accepted-only work: a fence receipt is destructive to read, so it
1117
+ // has to be consumed on every event or a later one would see a stale interruption.
1118
+ this.#host.retireFencedPrestartUrgent();
1119
+ if (accepted && (event.kind === 'response_started' || event.kind === 'response_audio_delta')) {
1120
+ this.#host.bindUrgentHostResponse(event);
1121
+ this.#host.finishPreemptiveAlertFirstAudio(event);
1122
+ }
1123
+ if (event.kind === 'response_started' && accepted) {
1124
+ // Only for a response with no events yet: one that already has them has been bound, and
1125
+ // rebinding would take a second user turn for the same response.
1126
+ if (this.session.responseEventIds(event.response_id).length === 0) {
1127
+ this.#bindResponseUserOrigin(event.session_epoch, event.response_id);
1128
+ }
1129
+ this.#host.suppressCancelledSemanticAcknowledgement(event.response_id);
1130
+ this.#host.bindRequestedSemanticAcknowledgement(event.response_id);
1131
+ this.#continuations.bindContinuation(event.response_id);
1132
+ this.#continuations.bindToolContinuationOrigin(event.session_epoch, event.response_id);
1133
+ this.#confirmation.suppressShadowConfirmationResponse(event.session_epoch, event.response_id);
1134
+ }
1135
+ if (event.kind === 'response_started') {
1136
+ this.#telemetry?.record('provider.response_started', {
1137
+ session_epoch: event.session_epoch,
1138
+ response_id: event.response_id,
1139
+ accepted,
1140
+ user_input_revision: this.session.providerTurnUserInputRevision(event.response_id) ?? -1,
1141
+ item_id: this.#userOrigins.itemForResponse(event.session_epoch, event.response_id) ?? 'none',
1142
+ });
1143
+ }
1144
+ if (event.kind === 'user_speech_started' || event.kind === 'user_speech_ended') {
1145
+ this.#telemetry?.record(`provider.${event.kind}`, { session_epoch: event.session_epoch,
1146
+ speech_id: event.speech_id, item_id: event.provider_item_id, accepted });
1147
+ }
1148
+ else if (event.kind === 'user_transcript_final' || event.kind === 'user_transcript_failed') {
1149
+ this.#telemetry?.record(`provider.${event.kind}`, { session_epoch: event.session_epoch,
1150
+ item_id: event.item_id, accepted });
1151
+ }
1152
+ else if (event.kind === 'response_terminal') {
1153
+ this.#telemetry?.record('provider.response_terminal', { session_epoch: event.session_epoch,
1154
+ response_id: event.response_id, status: event.status, accepted });
1155
+ }
1156
+ if (this.#onCaption !== undefined) {
1157
+ const caption = this.session.captionFor(event, event.kind === 'user_transcript_final' ? { accepted } : undefined);
1158
+ if (caption !== null) {
1159
+ const sourceId = 'item_id' in event ? event.item_id : 'response_id' in event ? event.response_id : null;
1160
+ this.#onCaption({ ...caption, ...(typeof sourceId === 'string' ? { turn_id: `${this.#captionScope}:${event.session_epoch}:${caption.role}:${sourceId}` } : {}) });
1161
+ }
1162
+ }
1163
+ if (event.kind === 'user_speech_started' && accepted) {
1164
+ this.#intake?.userInputStarted();
1165
+ this.#host.acceptUserActivation(event.session_epoch);
1166
+ this.#host.revokePreemptiveReconnect();
1167
+ // An automatic provider may finish its function call before emitting this turn's transcript final. Do not let
1168
+ // that call bind to provider-authored placeholder text or the previous user turn.
1169
+ this.#awaitingUserOrigin = true;
1170
+ this.#userOriginPreexistingResponseId = this.session.activeProviderResponseId;
1171
+ if (event.provider_item_id !== null) {
1172
+ this.#rememberUnboundUserOrigin(event.session_epoch, this.session.userInputRevision, event.provider_item_id);
1173
+ }
1174
+ this.#approvalHost.noteExecutorApprovalOnsetBeforeContext();
1175
+ this.#approvalHost.releaseQuestionOnOnset();
1176
+ await this.#approvalHost.reserveExecutorApprovalItem(event.session_epoch, event.provider_item_id);
1177
+ this.#confirmation.reserveProjectConfirmation(event);
1178
+ }
1179
+ if (event.kind === 'user_speech_ended'
1180
+ && accepted
1181
+ && event.provider_item_id !== null) {
1182
+ this.#rememberUnboundUserOrigin(event.session_epoch, this.session.userInputRevision, event.provider_item_id);
1183
+ await this.#approvalHost.reserveExecutorApprovalItem(event.session_epoch, event.provider_item_id);
1184
+ await this.#approvalHost.maybeRequestFreshExecutorApprovalResponse();
1185
+ }
1186
+ if (event.kind === 'response_yielded' && accepted) {
1187
+ this.#audioStarted.delete(event.response_id);
1188
+ const generation = this.session.currentGeneration;
1189
+ if (generation?.response_id === event.response_id && generation.session_epoch === event.session_epoch) {
1190
+ this.#onProviderTerminal(generation);
1191
+ }
1192
+ this.#continuations.finishContinuation({ response_id: event.response_id, status: 'yielded' });
1193
+ this.#continuations.finishOrigin(event.response_id);
1194
+ // Notify lifecycle owners before a follow-up delivery can fail.
1195
+ this.#notifyProviderEvent(event);
1196
+ }
1197
+ if (event.kind === 'response_terminal' && accepted) {
1198
+ this.#approvalHost.noteTerminal(event);
1199
+ this.#host.recordPreemptiveAlertCancelTerminal(event);
1200
+ const generation = this.session.currentGeneration;
1201
+ if (generation !== null
1202
+ && generation.session_epoch === event.session_epoch
1203
+ && generation.response_id === event.response_id) {
1204
+ this.#onProviderTerminal(generation);
1205
+ }
1206
+ this.#host.finishSemanticAcknowledgement(event);
1207
+ this.#continuations.finishContinuation(event);
1208
+ this.#continuations.finishOrigin(event.response_id);
1209
+ // Notify lifecycle owners before a follow-up delivery can fail.
1210
+ this.#notifyProviderEvent(event);
1211
+ const itemId = this.#userOrigins.itemForResponse(event.session_epoch, event.response_id);
1212
+ if (event.status === 'completed' && itemId !== undefined
1213
+ && this.#userOrigins.revisionForItem(event.session_epoch, itemId) === this.session.userInputRevision
1214
+ && this.#intakeUser?.localOnsetRevision === this.#localSpeechOnsetRevision)
1215
+ this.#intake?.userResponseCompleted();
1216
+ await this.#confirmation.settleTerminal(event, itemId);
1217
+ await this.#approvalHost.settleTerminal(event);
1218
+ this.#confirmation.clearTerminalShadow(event.session_epoch, itemId);
1219
+ // Released only when the terminal is *not* the current generation: if it is, playback is still
1220
+ // running and the owner is what keeps the alert's audio attributable.
1221
+ if (generation?.session_epoch !== event.session_epoch
1222
+ || generation.response_id !== event.response_id) {
1223
+ this.#host.releaseUrgentHostResponse(terminalOwner);
1224
+ }
1225
+ this.#host.markPreemptiveAlertReplacementTerminal(terminalOwner);
1226
+ }
1227
+ if (event.kind === 'response_terminal' && executorQuarantinedResponse) {
1228
+ await this.#approvalHost.finishPendingExecutorApprovalResponseQuarantine(event.session_epoch, event.response_id);
1229
+ }
1230
+ if (event.kind === 'user_transcript_final') {
1231
+ if (accepted) {
1232
+ const localOnsetRevision = this.#localSpeechOnsetRevision;
1233
+ // A delayed final still belongs to its original VAD item, not a newer speech onset.
1234
+ const inputRevision = this.#userOrigins.revisionForItem(event.session_epoch, event.item_id)
1235
+ ?? this.session.userInputRevision;
1236
+ this.#host.acceptUserActivation(event.session_epoch);
1237
+ if (this.#userOrigins.revisionForItem(event.session_epoch, event.item_id) === undefined) {
1238
+ // Some realtime transports can deliver a final transcript without a preceding VAD item id.
1239
+ // `RealtimeSession.accept()` has already advanced the exact item as the current user turn;
1240
+ // mirror that accepted identity into the evidence ledger rather than dropping the transcript.
1241
+ this.#rememberUnboundUserOrigin(event.session_epoch, this.session.userInputRevision, event.item_id);
1242
+ }
1243
+ await this.#approvalHost.reserveExecutorApprovalItem(event.session_epoch, event.item_id);
1244
+ if (event.session_epoch <= this.#discardedInputEpoch)
1245
+ return;
1246
+ await this.#approvalHost.maybeRequestFreshExecutorApprovalResponse();
1247
+ if (event.session_epoch <= this.#discardedInputEpoch)
1248
+ return;
1249
+ const originRef = await this.#bridge.acceptUserTranscript(event.text);
1250
+ if (event.session_epoch <= this.#discardedInputEpoch)
1251
+ return;
1252
+ this.#notifyAcceptedUserTranscript({
1253
+ text: event.text, originRef, sessionEpoch: event.session_epoch, itemId: event.item_id, userInputRevision: inputRevision, ...(event.input_kind === 'text' ? { confirmed: true } : {}),
1254
+ });
1255
+ this.#rememberUserOriginRef(event.session_epoch, event.item_id, originRef);
1256
+ this.#intakeUser = { text: event.text, origin_ref: originRef, epoch: event.session_epoch, inputRevision, localOnsetRevision };
1257
+ this.#intake?.userInputEnded();
1258
+ this.#awaitingUserOrigin = this.#userOrigins.hasUnboundRevision(event.session_epoch, this.session.userInputRevision);
1259
+ if (!this.#awaitingUserOrigin)
1260
+ this.#userOriginPreexistingResponseId = null;
1261
+ await this.#confirmation.afterTranscriptFinal(event, originRef);
1262
+ }
1263
+ }
1264
+ else if (event.kind === 'user_transcript_failed') {
1265
+ if (accepted) {
1266
+ // Failed speech is neither cancellation nor authorization. Release an existing
1267
+ // proposal's speech hold; unfinished planning stays paused for a valid user turn.
1268
+ if (this.#userOrigins.revisionForItem(event.session_epoch, event.item_id) === this.session.userInputRevision) {
1269
+ this.#intake?.userInputFailed();
1270
+ }
1271
+ if (this.#userOrigins.revisionForItem(event.session_epoch, event.item_id) === undefined) {
1272
+ this.#rememberUnboundUserOrigin(event.session_epoch, this.session.userInputRevision, event.item_id);
1273
+ }
1274
+ await this.#approvalHost.reserveExecutorApprovalItem(event.session_epoch, event.item_id);
1275
+ await this.#approvalHost.maybeRequestFreshExecutorApprovalResponse();
1276
+ // The transcript will never arrive, so anything waiting on it is waiting forever. Released
1277
+ // with a null ref: the calls still need an answer, and the bridge refuses them for want of
1278
+ // evidence rather than this layer dropping them silently.
1279
+ this.#failUserOriginTranscript(event.session_epoch, event.item_id);
1280
+ this.#awaitingUserOrigin = this.#userOrigins.hasUnboundRevision(event.session_epoch, this.session.userInputRevision);
1281
+ if (!this.#awaitingUserOrigin)
1282
+ this.#userOriginPreexistingResponseId = null;
1283
+ await this.#confirmation.afterTranscriptFailed(event);
1284
+ }
1285
+ }
1286
+ else if (event.kind === 'tool_call_ready') {
1287
+ this.#telemetry?.record('tool.call', {
1288
+ name: this.#tools.bindings.get(event.name)?.logical_name ?? (event.name === 'confirm' ? 'confirm' : 'unknown'),
1289
+ call_id: event.call_id, outcome: accepted ? 'received' : 'rejected',
1290
+ });
1291
+ if (!accepted) {
1292
+ // Approval carriers suppress ordinary tools; stopping still passes the user-origin fences.
1293
+ if (stoppingTask && event.session_epoch === this.session.sessionEpoch && event.response_id !== null
1294
+ && this.session.providerTurnPhase(event.response_id) === 'active'
1295
+ && !this.session.providerTurnWasFenced(event.response_id)
1296
+ && this.#approvalHost.blocksExecutorApprovalTool(event)) {
1297
+ await this.#continuations.routeToolCall(event);
1298
+ return;
1299
+ }
1300
+ // A refused confirmation tool still owes the provider a terminal result, or the protocol stalls
1301
+ // waiting for one that will never come.
1302
+ if (blockedConfirmationTool)
1303
+ await this.#confirmation.closeProjectConfirmationTool(event);
1304
+ else if (blockedExecutorApprovalTool)
1305
+ await this.#approvalHost.closeExecutorApprovalCarrierTool(event);
1306
+ else if (isExecutorApprovalDecision
1307
+ && event.session_epoch === this.session.sessionEpoch) {
1308
+ await this.#approvalHost.handleExecutorApprovalDecision(event, {
1309
+ observedProviderResponseId: event.response_id,
1310
+ originItemId: null,
1311
+ originRef: null,
1312
+ });
1313
+ }
1314
+ return;
1315
+ }
1316
+ await this.#continuations.routeToolCall(event);
1317
+ }
1318
+ if (event.kind === 'user_transcript_final' || event.kind === 'user_transcript_failed') {
1319
+ await this.#confirmation.resumeProjectConfirmationCarrierRecoveryAfterUser();
1320
+ }
1321
+ if (event.kind === 'response_terminal') {
1322
+ if (!accepted)
1323
+ this.#notifyProviderEvent(event);
1324
+ this.#confirmation.clearTerminal(event);
1325
+ this.#approvalHost.clearTerminal(event);
1326
+ }
1327
+ if (accepted)
1328
+ await this.driveContinuations();
1329
+ await this.#deliveryPass();
1330
+ }
1331
+ #notifyAcceptedUserTranscript(turn) {
1332
+ const callback = this.#onUserTranscriptAccepted;
1333
+ if (callback === undefined)
1334
+ return;
1335
+ try {
1336
+ void Promise.resolve(callback(turn)).catch(() => {
1337
+ this.#onDiagnostic('[realtime-diagnostic] personal_memory_admission_failed');
1338
+ });
1339
+ }
1340
+ catch {
1341
+ this.#onDiagnostic('[realtime-diagnostic] personal_memory_admission_failed');
1342
+ }
1343
+ }
1344
+ /**
1345
+ * Wrap a loop so its failure stops the service instead of vanishing.
1346
+ *
1347
+ * An unobserved rejection in one of three long-lived loops is the worst outcome available: the
1348
+ * service would look alive while no longer consuming its provider. A loop that ends *at all*
1349
+ * without the service being asked to stop is treated as a failure for the same reason.
1350
+ */
1351
+ async #guardTask(task, run) {
1352
+ try {
1353
+ await task;
1354
+ if (!run.signal.aborted)
1355
+ this.#taskFailed(run);
1356
+ }
1357
+ catch (cause) {
1358
+ this.#onDiagnostic(`[realtime-diagnostic] task_failure type=${diagnosticName(cause)}`);
1359
+ this.#taskFailed(run);
1360
+ }
1361
+ }
1362
+ /**
1363
+ * Stop the service because one of its loops ended when it should not have.
1364
+ *
1365
+ * Scoped to the run that started the task, not to whatever run is current. A task abandoned by an
1366
+ * earlier `close` can still resolve later, and without this check it would read the *replacement*
1367
+ * controller, find it un-aborted, and take down a service that had already been restarted.
1368
+ */
1369
+ #taskFailed(run) {
1370
+ if (run !== this.#stop) {
1371
+ // From a run that is already over. Its outcome cannot bear on the current one.
1372
+ this.#onDiagnostic('[realtime-diagnostic] task_failure_from_previous_run');
1373
+ return;
1374
+ }
1375
+ this.#providerFailed = true;
1376
+ this.#approvalHost.invalidateExecutorApproval('task_failed');
1377
+ this.#host.releaseFailedDelivery();
1378
+ this.#stop.abort();
1379
+ this.#deliveryReady.set();
1380
+ }
1381
+ #reportDeliveryFailure(failure) {
1382
+ this.#onDiagnostic(`[realtime-diagnostic] delivery_failure type=${diagnosticName(failure)}`);
1383
+ }
1384
+ // ---------------------------------------------------------------------------------------------
1385
+ // Family H: binding a tool call to the user turn that justifies it.
1386
+ //
1387
+ // A tool proposal needs evidence, and the evidence is the user transcript of the turn the model was
1388
+ // responding to. The provider does not hand those over together -- An automatic provider can finish a function call
1389
+ // before emitting the turn's transcript final -- so the binding is built here from two streams that
1390
+ // arrive out of order. Getting it wrong does not fail loudly; it attaches a proposal to the
1391
+ // *previous* user turn, which is precisely the kind of citation the origin check exists to stop.
1392
+ // ---------------------------------------------------------------------------------------------
1393
+ /** Register one provider item against the exact user revision that introduced it. */
1394
+ #rememberUnboundUserOrigin(epoch, revision, itemId) {
1395
+ const registered = this.#userOrigins.registerUserItem({ epoch, revision, itemId });
1396
+ this.#telemetry?.record('user_origin.item_registered', {
1397
+ session_epoch: epoch,
1398
+ user_input_revision: revision,
1399
+ item_id: itemId,
1400
+ registered,
1401
+ });
1402
+ }
1403
+ /**
1404
+ * Claim only the user item from the revision this provider response captured at open.
1405
+ */
1406
+ #bindResponseUserOrigin(epoch, responseId) {
1407
+ if (epoch !== this.session.sessionEpoch) {
1408
+ this.#recordUserOriginResponseBinding(epoch, responseId, -1, 'epoch_mismatch', 'none');
1409
+ return false;
1410
+ }
1411
+ const revision = this.session.providerTurnUserInputRevision(responseId);
1412
+ if (revision === undefined) {
1413
+ this.#recordUserOriginResponseBinding(epoch, responseId, -1, 'revision_missing', 'none');
1414
+ return false;
1415
+ }
1416
+ const origin = this.session.providerResponseOrigin(responseId);
1417
+ if (origin !== undefined && (origin.kind !== 'user_item'
1418
+ || this.#userOrigins.revisionForItem(epoch, origin.item_id) !== revision
1419
+ || !this.session.responseMatchesUserItem(responseId, origin.item_id, revision))) {
1420
+ this.#recordUserOriginResponseBinding(epoch, responseId, revision, 'provider_origin_mismatch', 'none');
1421
+ return false;
1422
+ }
1423
+ const result = this.#userOrigins.bindResponse({ epoch, responseId, revision });
1424
+ this.#recordUserOriginResponseBinding(epoch, responseId, revision, result.status, result.status === 'bound' ? result.item_id : 'none');
1425
+ this.#awaitingUserOrigin = this.#userOrigins.hasUnboundRevision(epoch, this.session.userInputRevision);
1426
+ if (!this.#awaitingUserOrigin)
1427
+ this.#userOriginPreexistingResponseId = null;
1428
+ return result.status === 'bound';
1429
+ }
1430
+ #recordUserOriginResponseBinding(epoch, responseId, revision, status, itemId) {
1431
+ this.#telemetry?.record('user_origin.response_binding', {
1432
+ session_epoch: epoch,
1433
+ user_input_revision: revision,
1434
+ response_id: responseId,
1435
+ item_id: itemId,
1436
+ status,
1437
+ proposal_id: this.#confirmation.proposalId ?? 'none',
1438
+ proposal_origin_ref: this.#confirmation.proposalOriginRef ?? 'none',
1439
+ });
1440
+ }
1441
+ /** Record the Memory ref produced by the transcript for this exact provider item. */
1442
+ #rememberUserOriginRef(epoch, itemId, originRef) {
1443
+ const resolved = this.#userOrigins.resolveTranscript({ epoch, itemId, originRef });
1444
+ this.#telemetry?.record('user_origin.transcript_resolution', {
1445
+ session_epoch: epoch,
1446
+ user_input_revision: this.#userOrigins.revisionForItem(epoch, itemId) ?? -1,
1447
+ item_id: itemId,
1448
+ origin_ref: originRef,
1449
+ status: resolved ? 'resolved' : 'rejected',
1450
+ });
1451
+ }
1452
+ #failUserOriginTranscript(epoch, itemId) {
1453
+ const revision = this.#userOrigins.revisionForItem(epoch, itemId) ?? -1;
1454
+ const failed = this.#userOrigins.failTranscript(epoch, itemId);
1455
+ this.#telemetry?.record('user_origin.transcript_resolution', {
1456
+ session_epoch: epoch,
1457
+ user_input_revision: revision,
1458
+ item_id: itemId,
1459
+ origin_ref: 'none',
1460
+ status: failed ? 'failed' : 'missing',
1461
+ });
1462
+ return failed;
1463
+ }
1464
+ /** Same current-user fence for controller actions and direct external MCP effects. */
1465
+ #currentUserTurn(event, originRef) {
1466
+ const user = this.#intakeUser;
1467
+ if (event.session_epoch <= this.#discardedInputEpoch || originRef === null || user?.epoch !== event.session_epoch || originRef !== user.origin_ref
1468
+ || user.localOnsetRevision !== this.#localSpeechOnsetRevision || user.inputRevision !== this.session.userInputRevision)
1469
+ return null;
1470
+ const revision = this.session.userInputRevision;
1471
+ const localOnsetRevision = this.#localSpeechOnsetRevision;
1472
+ return { originRef, sessionEpoch: event.session_epoch, acceptedUserInputRevision: revision,
1473
+ stillWanted: () => event.session_epoch > this.#discardedInputEpoch
1474
+ && this.session.sessionEpoch === event.session_epoch
1475
+ && this.session.userInputRevision === revision
1476
+ && this.#localSpeechOnsetRevision === localOnsetRevision
1477
+ && this.#intakeUser?.origin_ref === originRef };
1478
+ }
1479
+ // Controlled provider replacement stays here; HostDelivery owns preemption state and deadlines.
1480
+ /**
1481
+ * The provider refused to cancel, so take the session away from it.
1482
+ *
1483
+ * The last resort. The provider was asked to stop, said it would not, and the alert is still waiting
1484
+ * -- so the whole provider session is replaced under the preemption rather than letting the old turn
1485
+ * run to completion. Gated behind the composition-owned reconnect option because it is a heavy remedy for a case
1486
+ * that should not happen.
1487
+ *
1488
+ * `#reconnectLock` before `#deliveryLock`, never the reverse: that order is fixed across this layer,
1489
+ * and every replacement path that holds both follows this order.
1490
+ *
1491
+ * Seven conditions have to hold before the permit is spent. Together they say: this rejection is
1492
+ * about *this* preemption, in the current session, for a turn that is still trying to cancel and has
1493
+ * not produced anything yet. Anything else and a reconnect would be discarding a session that is
1494
+ * working.
1495
+ */
1496
+ async #handlePreemptiveAlertCancelRejected(event) {
1497
+ if (!this.#controlledPreemptiveAlertReconnect)
1498
+ return;
1499
+ await this.#reconnectLock.run(async () => {
1500
+ await this.#host.withDeliveryLock(async () => {
1501
+ if (this.#preemptiveAlertHistoryRecovery !== 'none')
1502
+ await this.#runtime.flushMemory?.(true);
1503
+ const preemption = this.#host.currentPreemption;
1504
+ if (preemption?.session_epoch !== event.session_epoch
1505
+ || preemption.session_epoch !== this.session.sessionEpoch
1506
+ || preemption.old_response_id !== event.response_id
1507
+ || preemption.reconnect_permit_consumed
1508
+ || preemption.reconnect_disallowed
1509
+ || this.session.providerTurnPhase(event.response_id) !== 'cancel_requested'
1510
+ // A turn that has already produced events has said something to the user; replacing the
1511
+ // session under it would lose whatever that was.
1512
+ || this.session.responseEventIds(event.response_id).length > 0) {
1513
+ return;
1514
+ }
1515
+ const queued = this.#host.findQueuedEvent(preemption.event_id);
1516
+ const oldGeneration = preemption.old_generation;
1517
+ if (queued === undefined || oldGeneration === null)
1518
+ return;
1519
+ const spent = this.#host.spendReconnectPermit(preemption);
1520
+ if (spent.deadline_fired) {
1521
+ // The alert already fenced the retained renderer generation. Anchor its uncertainty bound
1522
+ // now, before a slow reconnect; ordinary deferred alerts never consume this permit.
1523
+ this.#host.startPreemptiveAlertClearDeadline(oldGeneration);
1524
+ }
1525
+ const oldEpoch = this.session.sessionEpoch;
1526
+ const history = this.#preemptiveAlertRecoveryHistory();
1527
+ try {
1528
+ const historyOutcome = await this.session.reconnectForPreemptiveAlert({
1529
+ tools: structuredClone(this.#providerSchemas),
1530
+ oldGeneration,
1531
+ confirmationTimeout: 0.5,
1532
+ history,
1533
+ historyMode: this.#preemptiveAlertHistoryRecovery,
1534
+ });
1535
+ this.#host.requireActivation();
1536
+ if (this.#preemptiveAlertHistoryRecovery !== 'none') {
1537
+ this.#telemetry?.record('guard.history_recovery', {
1538
+ arm: this.#preemptiveAlertHistoryRecovery,
1539
+ outcome: historyOutcome,
1540
+ item_count: history.length,
1541
+ pair_count: Math.floor(history.length / 2),
1542
+ character_count: history.reduce((total, turn) => total + codePointLengthLikePython(turn.text), 0),
1543
+ });
1544
+ }
1545
+ this.#awaitingUserOrigin = false;
1546
+ this.#userOriginPreexistingResponseId = null;
1547
+ this.#userOrigins.beginEpoch(this.session.sessionEpoch);
1548
+ this.#continuations.clearDeferred();
1549
+ this.#host.releaseUrgentHostResponseForEpoch(oldEpoch);
1550
+ this.#clearCaptions();
1551
+ this.#audioStarted.clear();
1552
+ this.#continuations.reconcileToolStateAfterReconnect(oldEpoch);
1553
+ this.#host.reopenFailedSemanticAcknowledgements();
1554
+ this.#host.reconcileSemanticAcknowledgementsAfterReconnect();
1555
+ const current = this.#host.currentPreemption;
1556
+ // The world may have moved while reconnecting: a replacement preemption, or a user who
1557
+ // started speaking and revoked the authority this was borrowing.
1558
+ if (current?.token !== spent.token)
1559
+ return;
1560
+ if (current.reconnect_aborted) {
1561
+ this.#host.clearPreemptiveAlert(current.token);
1562
+ return;
1563
+ }
1564
+ this.#host.adoptReconnectedPreemption(current);
1565
+ await this.#host.deliverCapturedPreemptiveAlertLocked(queued);
1566
+ }
1567
+ catch (failure) {
1568
+ this.#telemetry?.record('guard.history_recovery_failure', {
1569
+ arm: this.#preemptiveAlertHistoryRecovery,
1570
+ reason: diagnosticName(failure),
1571
+ });
1572
+ this.#onDiagnostic(`[realtime-diagnostic] preemptive_alert_reconnect_failure type=${diagnosticName(failure)}`);
1573
+ // A failed reconnect leaves no working provider and no way to speak the alert. Stopping is
1574
+ // the only honest outcome.
1575
+ this.#providerFailed = true;
1576
+ this.#stop.abort();
1577
+ this.#deliveryReady.set();
1578
+ }
1579
+ });
1580
+ });
1581
+ }
1582
+ /** Recent conversation to hand a replacement provider, so it does not start blank. */
1583
+ #preemptiveAlertRecoveryHistory() {
1584
+ if (this.#preemptiveAlertHistoryRecovery === 'none')
1585
+ return [];
1586
+ const channel = this.#runtime.memory?.channels.get('conversation');
1587
+ if (channel === undefined)
1588
+ return [];
1589
+ const history = projectRecoveryTurns(channel.items, { maxPairs: this.#preemptiveAlertHistoryPairs });
1590
+ if (this.#preemptiveAlertHistoryRecovery === 'packed')
1591
+ return packRecoveryTurns(history).turns;
1592
+ return history;
1593
+ }
1594
+ deliveryState() {
1595
+ return { ...this.#host.snapshot(), continuationOrder: this.#continuations.continuationOrder() };
1596
+ }
1597
+ /**
1598
+ * Drive the uncertain-delivery recovery directly.
1599
+ *
1600
+ * Exposed to test the bounded recovery policy independently of provider receive timing.
1601
+ */
1602
+ reportUncertainDeliveryForTest(failure) {
1603
+ return this.#recoverUncertainDelivery(failure);
1604
+ }
1605
+ /**
1606
+ * How many user items are waiting for a response to claim them.
1607
+ *
1608
+ * The evidence boundary is invisible from outside otherwise: a spent item wrongly re-queued only
1609
+ * shows up later, as a tool call admitted against a turn the user has moved past.
1610
+ */
1611
+ get unboundUserOriginCountForTest() {
1612
+ return this.#userOrigins.unboundCount;
1613
+ }
1614
+ /**
1615
+ * Drive a reconnect directly.
1616
+ *
1617
+ * The paths that normally reach it -- a recoverable provider error, an uncertain delivery, a full
1618
+ * refusal ledger -- each need their own setup, and the reconciliation this performs is worth testing
1619
+ * on its own rather than only through one of them.
1620
+ */
1621
+ reconnectForTest(expectedEpoch) {
1622
+ return this.#reconnectProviderSession({
1623
+ reason: 'test',
1624
+ ...(expectedEpoch === undefined ? {} : { expectedEpoch }),
1625
+ });
1626
+ }
1627
+ /** Drive invalidation directly, for the observer-failure case. */
1628
+ invalidateProjectConfirmationForTest(reason) {
1629
+ this.#confirmation.invalidateProjectConfirmation(reason);
1630
+ }
1631
+ /** Which response holds which user turn, in binding order. */
1632
+ get boundOriginsForTest() {
1633
+ return this.#userOrigins.boundResponses;
1634
+ }
1635
+ /** How many responses hold a user turn as their evidence. */
1636
+ get boundOriginCountForTest() {
1637
+ return this.#userOrigins.boundResponseCount;
1638
+ }
1639
+ /** What the provider was handed at connect. Exposed so the copy can be checked, not assumed. */
1640
+ get providerSchemasForTest() {
1641
+ return this.#providerSchemas;
1642
+ }
1643
+ /** Read-only compatibility configuration view. */
1644
+ get preemptiveAlertConfiguration() {
1645
+ return {
1646
+ controlledReconnect: this.#controlledPreemptiveAlertReconnect,
1647
+ historyRecovery: this.#preemptiveAlertHistoryRecovery,
1648
+ historyPairs: this.#preemptiveAlertHistoryPairs,
1649
+ };
1650
+ }
1651
+ /** Existing test compatibility views; production owners communicate through semantic methods. */
1652
+ get internals() {
1653
+ return {
1654
+ reconnectLock: this.#reconnectLock,
1655
+ bridge: this.#bridge,
1656
+ tools: this.#tools,
1657
+ runtime: this.#runtime,
1658
+ idFactory: this.#idFactory,
1659
+ setExecutorState: (state) => {
1660
+ this.#projection.setExecutorStateForTest(state);
1661
+ },
1662
+ };
1663
+ }
1664
+ }
1665
+ /**
1666
+ * Whether a promise settled inside the grace period.
1667
+ *
1668
+ * Rejections propagate -- a provider that refused to close reported something the caller has to see --
1669
+ * while a promise that never settles at all resolves to `false` so the caller can say so and move on.
1670
+ */
1671
+ async function resolvedWithin(work, graceMs) {
1672
+ let timer;
1673
+ const deadline = new Promise(resolve => {
1674
+ timer = setTimeout(() => resolve(false), graceMs);
1675
+ });
1676
+ try {
1677
+ return await Promise.race([work.then(() => true), deadline]);
1678
+ }
1679
+ finally {
1680
+ if (timer !== undefined)
1681
+ clearTimeout(timer);
1682
+ }
1683
+ }
1684
+ /**
1685
+ * Wait for every task, but not forever.
1686
+ *
1687
+ * Returns how many were still running when the grace period ran out. A JavaScript promise cannot be
1688
+ * cancelled the way an asyncio task can, so a loop that ignored its abort signal would make `close`
1689
+ * hang -- and a service that never finishes closing is worse than one that names a task it could not
1690
+ * stop. Every loop here observes the signal, so reaching the timeout means one is genuinely stuck.
1691
+ */
1692
+ async function settleWithin(tasks, graceMs) {
1693
+ if (tasks.length === 0)
1694
+ return 0;
1695
+ let outstanding = tasks.length;
1696
+ const settled = tasks.map(task => task.then(() => {
1697
+ outstanding -= 1;
1698
+ }, () => {
1699
+ outstanding -= 1;
1700
+ }));
1701
+ let timer;
1702
+ const deadline = new Promise(resolve => {
1703
+ timer = setTimeout(resolve, graceMs);
1704
+ });
1705
+ await Promise.race([Promise.all(settled), deadline]);
1706
+ if (timer !== undefined)
1707
+ clearTimeout(timer);
1708
+ return outstanding;
1709
+ }
1710
+ /** A callback that was not supplied. Named so two of them are not two anonymous empty functions. */
1711
+ function noop() {
1712
+ // Intentionally empty: an absent observer is not an error.
1713
+ }
1714
+ /** Wrap whatever was thrown so it can be re-thrown as an Error without losing the original. */
1715
+ function asError(cause) {
1716
+ if (cause instanceof Error)
1717
+ return cause;
1718
+ const wrapped = new Error(`provider close failed: ${String(cause)}`);
1719
+ wrapped.cause = cause;
1720
+ return wrapped;
1721
+ }
1722
+ function randomHex() {
1723
+ // 32 hex characters, matching the oracle's `uuid4().hex`.
1724
+ return randomUUID().replaceAll('-', '');
1725
+ }
1726
+ //# sourceMappingURL=service.js.map