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,1976 @@
1
+ /**
2
+ * The realtime session: one provider conversation, reduced.
3
+ *
4
+ * Ported from `src/nova_personal_agent/realtime/session.py`. The state half lives in
5
+ * `session-state.ts`; this file is the decisions. `accept` is the centre of it -- a reducer over
6
+ * normalized provider events whose guards decide, for each event, whether it may take the provider
7
+ * slot, reach the renderer, or count as user input at all.
8
+ *
9
+ * Two ideas run through every guard. **Authority** is the right to be heard: a response earns it by
10
+ * taking the provider slot and loses it to a fence, and holding the slot is not the same as holding
11
+ * authority. **Epoch** scopes provider-allocated identity: a reconnect starts a new one, and an id
12
+ * from the old session must never satisfy a check in the new one.
13
+ *
14
+ * Every guard here is pinned by a scenario in `tests/fixtures/realtime/session/v1/`, exported from the
15
+ * Python oracle. When changing one, delete it and confirm a named scenario goes red; a guard no
16
+ * scenario distinguishes is either dead or a hole in the fixture set.
17
+ */
18
+ import { Floor } from './floor.js';
19
+ import { USER_PRIORITY } from '../core/memory.js';
20
+ import { codePointLengthLikePython } from '../text/python-text.js';
21
+ import { packRecoveryTurns } from './history.js';
22
+ import { ItemDeliveryUncertainError, ProviderResponseRejectedError, MAX_REALTIME_TEXT, hostFact, } from './protocol.js';
23
+ import { MAX_CONTINUATION_TASK_SUMMARY, RealtimeSessionState, truncateCaption as truncateCaptionText, } from './session-state.js';
24
+ /** A host response the session asked for and could not deliver. */
25
+ export class RealtimeDeliveryError extends Error {
26
+ }
27
+ /** The response request may have reached the provider before its acknowledgement failed. */
28
+ export class ResponseRequestUncertainError extends RealtimeDeliveryError {
29
+ }
30
+ export class RealtimeSession {
31
+ #state = new RealtimeSessionState();
32
+ #provider;
33
+ #playback;
34
+ #idFactory;
35
+ #clock;
36
+ #onSpoken;
37
+ #onDelivery;
38
+ #onDiagnostic;
39
+ #floor = new Floor();
40
+ #userHoldSince = null;
41
+ #awaitingUserResponse = false;
42
+ #pendingUserResponse = null;
43
+ #latestUserResponse = null;
44
+ #userResponseRequest = null;
45
+ #userResponseSequence = 0;
46
+ #fenceNextResponse = false;
47
+ #fenceInterruption = null;
48
+ #providerReplacementRevision = 0;
49
+ #replacementEpoch;
50
+ #providerResponseId = null;
51
+ #yielded = null;
52
+ #hostPreemptResponseId = null;
53
+ #hostPreemptPending = false;
54
+ #providerTranscript = '';
55
+ #preemptiveAlertHandoffGeneration = null;
56
+ /** The generation a preemptive-alert handoff may retain: only the most recent one can be handed off. */
57
+ #lastOpenedGeneration = null;
58
+ #responseItems = new Map();
59
+ #deliveredWorkVersions = new Map();
60
+ #unheard = new Map();
61
+ #recoveryResponses = new Map();
62
+ #responseQuestions = new Map();
63
+ #latestQuestion = null;
64
+ #recoveryVersion = 0;
65
+ #confirmedRecoveryVersion = -1;
66
+ #recoveryRequestSequence = 0;
67
+ /** Bounded evidence for rephrasing, never an action or a queue of old audio. */
68
+ deliveryRecoveryContext() {
69
+ for (const [id, fact] of this.#unheard) {
70
+ const obsolete = fact.item.kind === 'progress' && fact.item.source !== undefined
71
+ && this.delegateRecord(fact.item.source.work_id)?.state !== 'running';
72
+ if (obsolete || this.#clock.now() - fact.at > (fact.item.kind === 'progress' ? 45 : 300)
73
+ || this.userInputRevision - fact.revision > 2 || ((fact.attempts >= 2 || fact.requests >= 2) && this.foregroundIdle)) {
74
+ this.#unheard.delete(id);
75
+ this.#recoveryVersion++;
76
+ }
77
+ }
78
+ return { version: this.#recoveryVersion, content: this.#unheard.size === 0 ? null
79
+ : '以下是先前回应被打断时尚未完整交付的事实或问题,均为只读上下文,不是新的操作、授权或工具指令。以用户最新问题为主,合并仍相关且值得说的内容,去掉过时或重复信息;转话题时可以不提。不要重复执行已完成的操作,不朗读这些规则或引用编号。\n'
80
+ + JSON.stringify([...this.#unheard].map(([ref, fact]) => ({ ref,
81
+ evidence: [...(fact.item.speech_content ?? fact.item.content).replace(/[\p{C}]/gu, ' ')].slice(0, 400).join('') }))) };
82
+ }
83
+ confirmDeliveryRecovery(version, epoch) {
84
+ if (epoch === this.sessionEpoch && version === this.#recoveryVersion)
85
+ this.#confirmedRecoveryVersion = version;
86
+ }
87
+ async requestDeliveryRecovery() {
88
+ const context = this.deliveryRecoveryContext();
89
+ if (!this.foregroundIdle || this.floor.state !== 'idle' || context.content === null)
90
+ return false;
91
+ const item = { kind: 'recovery', host_item_id: this.#idFactory(),
92
+ event_id: `delivery-recovery:${this.sessionEpoch}:${++this.#recoveryRequestSequence}`, content: context.content, call_id: null };
93
+ const key = `pending:${item.host_item_id}`;
94
+ this.#recoveryResponses.set(key, [...this.#unheard.keys()]);
95
+ const requestedFacts = [...this.#unheard.values()];
96
+ for (const fact of requestedFacts)
97
+ fact.requests++;
98
+ try {
99
+ const delivered = await this.deliverHostResponse({ kind: 'host_fact', item, task_summary: null, origin_spoken: false });
100
+ if (!delivered.accepted) {
101
+ this.#recoveryResponses.delete(key);
102
+ for (const fact of requestedFacts)
103
+ fact.requests--;
104
+ }
105
+ return delivered.accepted;
106
+ }
107
+ catch (error) {
108
+ this.#recoveryResponses.delete(key);
109
+ throw error;
110
+ }
111
+ }
112
+ constructor(options) {
113
+ this.#provider = options.provider;
114
+ this.#playback = options.playback;
115
+ this.#idFactory = options.idFactory;
116
+ this.#clock = options.clock;
117
+ this.#onSpoken = options.onSpoken ?? noop;
118
+ this.#onDelivery = options.onDelivery ?? noop;
119
+ this.#onDiagnostic = options.onDiagnostic
120
+ ?? ((line) => {
121
+ process.stdout.write(`${line}\n`);
122
+ });
123
+ }
124
+ // ---------------------------------------------------------------------------
125
+ // Observable state
126
+ // ---------------------------------------------------------------------------
127
+ get floor() {
128
+ return this.#floor;
129
+ }
130
+ get sessionEpoch() {
131
+ return this.#state.sessionEpoch;
132
+ }
133
+ get userResponseMode() {
134
+ return this.#provider.userResponseMode ?? 'automatic';
135
+ }
136
+ get userInputRevision() {
137
+ return this.#state.userInputRevision;
138
+ }
139
+ get activeProviderResponseId() {
140
+ return this.#providerResponseId;
141
+ }
142
+ get currentGeneration() {
143
+ return this.#playback.current;
144
+ }
145
+ /** No provider inference is outstanding, whatever the renderer is still playing. */
146
+ get providerIdle() {
147
+ return (this.#yielded === null
148
+ && this.#state.pendingResponseCount === 0
149
+ && !this.#awaitingUserResponse
150
+ && this.#pendingUserResponse === null
151
+ && this.#userResponseRequest === null
152
+ && this.#providerResponseId === null);
153
+ }
154
+ /** Provider idle *and* nothing audible, which is what a non-preemptive host item waits for. */
155
+ get foregroundIdle() {
156
+ return (this.providerIdle
157
+ && this.#playback.current === null
158
+ && !this.#playback.hasUnreportedFence);
159
+ }
160
+ providerTurnPhase(responseId) {
161
+ return this.#state.providerTurnPhase(responseId);
162
+ }
163
+ providerTurnUserInputRevision(responseId) {
164
+ return this.#state.providerTurnUserInputRevision(responseId);
165
+ }
166
+ providerResponseOrigin(responseId) {
167
+ return this.#state.providerTurn(responseId)?.origin;
168
+ }
169
+ responseMatchesUserItem(responseId, itemId, revision) {
170
+ const turn = this.#state.providerTurn(responseId);
171
+ if (turn === undefined)
172
+ return this.#provider.userResponseMode !== 'requested';
173
+ if (turn.origin === undefined)
174
+ return true;
175
+ return turn.origin.kind === 'user_item'
176
+ && turn.origin.item_id === itemId
177
+ && turn.user_input_revision === revision;
178
+ }
179
+ providerTurnWasFenced(responseId) {
180
+ return this.#state.providerTurnWasFenced(responseId);
181
+ }
182
+ /** Settle the current user-response debt when this exact response answered its revision. */
183
+ settleUserResponse(responseId) {
184
+ if (!this.#awaitingUserResponse)
185
+ return false;
186
+ const revision = this.#state.providerTurnUserInputRevision(responseId);
187
+ if (revision === undefined || revision !== this.userInputRevision)
188
+ return false;
189
+ this.#awaitingUserResponse = false;
190
+ return true;
191
+ }
192
+ responseIsToolContinuation(responseId) {
193
+ const items = this.#responseItems.get(this.#turnKey(responseId));
194
+ return items !== undefined && items.length > 0 && items.every(item => item.kind === 'tool_output');
195
+ }
196
+ responseHostItemIds(responseId) {
197
+ return (this.#responseItems.get(this.#turnKey(responseId)) ?? []).map(item => item.host_item_id);
198
+ }
199
+ responseToolCallIds(responseId) {
200
+ return (this.#responseItems.get(this.#turnKey(responseId)) ?? []).flatMap(item => item.kind === 'tool_output' && item.call_id ? [item.call_id] : []);
201
+ }
202
+ responseEventIds(responseId) {
203
+ return (this.#responseItems.get(this.#turnKey(responseId)) ?? []).map(item => item.event_id);
204
+ }
205
+ responseHasSpoken(responseId) {
206
+ return responseId !== null && responseId === this.#spokenResponseId;
207
+ }
208
+ /**
209
+ * Give the host sole speech ownership of a provider response before it emits audio.
210
+ *
211
+ * Once a generation exists, provider audio has already crossed the attribution boundary even if
212
+ * the renderer has not acknowledged it yet. Refuse the transfer in that case rather than creating
213
+ * two competing owners for one turn.
214
+ */
215
+ suppressResponse(responseId) {
216
+ const generation = this.#playback.current;
217
+ if (this.responseHasSpoken(responseId)
218
+ || (generation !== null && generation.response_id === responseId))
219
+ return false;
220
+ this.#state.suppressResponse(responseId);
221
+ return true;
222
+ }
223
+ /** Revoke a response that belongs to a host-settled decision, even before its id is known. */
224
+ async quarantineActiveOrAwaitingResponse() {
225
+ return this.#fenceAndCancelActiveResponse();
226
+ }
227
+ /** Fence and cancel one exact response without ever consuming or cancelling a newer turn. */
228
+ async quarantineResponse(responseId) {
229
+ if (responseId === '')
230
+ throw new TypeError('responseId must be a non-empty string');
231
+ return this.#fenceAndCancelActiveResponse(responseId);
232
+ }
233
+ eventWasSpoken(eventId) {
234
+ return this.#state.eventWasSpoken(eventId);
235
+ }
236
+ hostEventIsDeduplicated(eventId) {
237
+ return this.#state.hostEventIsDeduplicated(eventId);
238
+ }
239
+ snapshot() {
240
+ return this.#state.snapshot();
241
+ }
242
+ get userCaption() {
243
+ return this.#state.userCaption;
244
+ }
245
+ get assistantCaption() {
246
+ return this.#state.assistantCaption;
247
+ }
248
+ #spokenResponseId = null;
249
+ /**
250
+ * Take the fence interruption, if any. Reading it clears it.
251
+ *
252
+ * A fence takes a host response away before it was heard; the caller has to learn that exactly
253
+ * once so it can re-queue the events, which is why this is destructive.
254
+ */
255
+ takeFenceInterruption() {
256
+ const interruption = this.#fenceInterruption;
257
+ this.#fenceInterruption = null;
258
+ return interruption;
259
+ }
260
+ /**
261
+ * Fence the next provider response before it can own playback.
262
+ *
263
+ * Repeated arming is deliberately idempotent, so one interruption cannot consume several
264
+ * responses. Confirmation uses the narrower pending-only wrapper below.
265
+ */
266
+ armNextResponseFence() {
267
+ if (this.#fenceNextResponse)
268
+ return;
269
+ if (this.#state.pendingResponseCount > 0)
270
+ this.#markHeadPendingFenced();
271
+ this.#fenceNextResponse = true;
272
+ this.#state.advanceSnapshot();
273
+ }
274
+ /** Fence an already-requested host response, without consuming the user's next response. */
275
+ armPendingResponseFence() {
276
+ if (this.#fenceNextResponse)
277
+ return true;
278
+ if (this.#state.pendingResponseCount === 0)
279
+ return false;
280
+ this.#markHeadPendingFenced();
281
+ this.#fenceNextResponse = true;
282
+ this.#state.advanceSnapshot();
283
+ return true;
284
+ }
285
+ // ---------------------------------------------------------------------------
286
+ // Provider session lifecycle
287
+ // ---------------------------------------------------------------------------
288
+ async connect(options) {
289
+ const identity = await this.#provider.connect({ tools: options.tools });
290
+ // The epoch must strictly increase; a provider that reuses one would let old ids satisfy
291
+ // dedup checks in the new session.
292
+ this.#state.beginEpoch(identity.epoch);
293
+ }
294
+ /**
295
+ * Replace the provider session, giving up everything the old one authorized.
296
+ *
297
+ * A reconnect is not a resume. Every provider-allocated identity dies with the epoch, so the
298
+ * new session is told what happened in a recovery item rather than being expected to remember.
299
+ * A response that never happened has its host event answer withdrawn, because it must be
300
+ * answerable again -- whereas one that completed stays answered, since the user heard it.
301
+ */
302
+ async reconnect(options) {
303
+ this.#preemptiveAlertHandoffGeneration = null;
304
+ const interruptedResponseIds = [];
305
+ const generation = this.#playback.fenceCurrent();
306
+ if (generation !== null && generation.session_epoch === this.sessionEpoch) {
307
+ interruptedResponseIds.push(generation.response_id);
308
+ }
309
+ if (this.#providerResponseId !== null
310
+ && !interruptedResponseIds.includes(this.#providerResponseId)) {
311
+ interruptedResponseIds.push(this.#providerResponseId);
312
+ }
313
+ for (const responseId of interruptedResponseIds) {
314
+ this.#markLocallyFenced(responseId);
315
+ this.#markResponseInterrupted(responseId);
316
+ this.#finishResponseAuthority(responseId);
317
+ }
318
+ this.#state.revokeRetainedSuggestionInjections();
319
+ this.#abandonPendingResponses();
320
+ this.#resetForNewProviderSession();
321
+ // A reconnect must not inherit an orphaned floor hold from the old epoch.
322
+ this.#floor = new Floor();
323
+ this.#userHoldSince = null;
324
+ const replace = async () => {
325
+ const identity = await this.#replaceProviderSession(options.tools);
326
+ this.#state.beginEpoch(identity.epoch);
327
+ };
328
+ if (options.withProviderTransition === undefined)
329
+ await replace();
330
+ else
331
+ await options.withProviderTransition(replace);
332
+ await this.#injectRecoveryItem(null);
333
+ this.#state.advanceSnapshot();
334
+ }
335
+ /** Immediately stop renderer authority while durable conversation clear is still pending. */
336
+ beginConversationClear() {
337
+ return this.#playback.fenceCurrent();
338
+ }
339
+ /** Start a blank conversation in a fresh provider epoch, without replaying the old snapshot. */
340
+ async resetConversation(options) {
341
+ this.#playback.fenceCurrent();
342
+ this.#preemptiveAlertHandoffGeneration = null;
343
+ this.#lastOpenedGeneration = null;
344
+ this.#state.resetConversation();
345
+ this.#responseItems.clear();
346
+ this.#unheard.clear();
347
+ this.#deliveredWorkVersions.clear();
348
+ this.#recoveryResponses.clear();
349
+ this.#responseQuestions.clear();
350
+ this.#latestQuestion = null;
351
+ this.#recoveryVersion++;
352
+ this.#confirmedRecoveryVersion = -1;
353
+ this.#resetForNewProviderSession();
354
+ this.#floor = new Floor();
355
+ this.#userHoldSince = null;
356
+ const identity = await this.#replaceProviderSession(options.tools);
357
+ this.#state.beginEpoch(identity.epoch);
358
+ }
359
+ /**
360
+ * Replace provider authority while retaining one exact renderer generation.
361
+ *
362
+ * This is the preemptive-alert handoff: the provider session underneath the user is replaced while the
363
+ * audio they are hearing keeps playing, so there is no gap. The retained generation is the one
364
+ * thing that survives, which is why it is validated three ways before anything is given up.
365
+ */
366
+ async reconnectForPreemptiveAlert(options) {
367
+ const { oldGeneration } = options;
368
+ const historyMode = options.historyMode ?? 'none';
369
+ const confirmationTimeout = options.confirmationTimeout ?? null;
370
+ // Checked before any state is touched: this method closes the provider session, so a caller
371
+ // whose input is malformed must get an error rather than an irreversible handoff. The type
372
+ // annotation is not enough -- a value reaching here from JSON is unchecked at runtime.
373
+ if (historyMode !== 'none' && historyMode !== 'packed') {
374
+ throw new TypeError(`unknown preemptive-alert history recovery arm: ${String(historyMode)}`);
375
+ }
376
+ if (oldGeneration.session_epoch !== this.sessionEpoch) {
377
+ throw new TypeError('preemptive-alert handoff generation must belong to the current session');
378
+ }
379
+ if (this.#lastOpenedGeneration === null
380
+ || !sameGeneration(oldGeneration, this.#lastOpenedGeneration)) {
381
+ throw new TypeError('preemptive-alert handoff requires a known playback generation');
382
+ }
383
+ const current = this.#playback.current;
384
+ if (current !== null && !sameGeneration(current, oldGeneration)) {
385
+ throw new TypeError('preemptive-alert handoff generation must be current');
386
+ }
387
+ const oldEpoch = this.sessionEpoch;
388
+ const responseIds = [oldGeneration.response_id];
389
+ if (this.#providerResponseId !== null
390
+ && !responseIds.includes(this.#providerResponseId)) {
391
+ responseIds.push(this.#providerResponseId);
392
+ }
393
+ for (const responseId of responseIds) {
394
+ const turn = this.#state.providerTurn(responseId, oldEpoch);
395
+ if (turn !== undefined) {
396
+ turn.defer_playback_fence = false;
397
+ if (turn.phase !== 'completed' && turn.phase !== 'cancelled' && turn.phase !== 'failed') {
398
+ turn.locally_fenced = true;
399
+ turn.phase = 'cancelled';
400
+ }
401
+ }
402
+ this.#markResponseInterrupted(responseId, oldEpoch);
403
+ this.#finishResponseAuthority(responseId, oldEpoch);
404
+ }
405
+ // The retained generation is interrupted from the provider's point of view even though the
406
+ // renderer is still playing it: no more audio is coming for it.
407
+ this.#playback.markProviderTerminal({
408
+ sessionEpoch: oldEpoch,
409
+ responseId: oldGeneration.response_id,
410
+ disposition: 'interrupted',
411
+ });
412
+ this.#state.revokeRetainedSuggestionInjections();
413
+ this.#abandonPendingResponses();
414
+ this.#resetForNewProviderSession();
415
+ // Unlike a plain reconnect, an agent_speaking floor for the retained utterance survives: it is
416
+ // still speaking, and blanking it would let something else claim the floor mid-word.
417
+ if (!(this.#floor.state === 'agent_speaking'
418
+ && this.#floor.utteranceId === oldGeneration.utterance_id)) {
419
+ this.#floor = new Floor();
420
+ }
421
+ this.#userHoldSince = null;
422
+ this.#preemptiveAlertHandoffGeneration = oldGeneration;
423
+ const identity = await this.#replaceProviderSession(options.tools);
424
+ this.#state.beginEpoch(identity.epoch);
425
+ let outcome = 'none';
426
+ if (historyMode !== 'none')
427
+ outcome = 'empty';
428
+ const history = options.history ?? [];
429
+ if (historyMode === 'packed' && history.length > 0) {
430
+ const { content: packedContent } = packRecoveryTurns(history);
431
+ if (packedContent === '') {
432
+ // History existed and none of it fit, which is not the same as there being none.
433
+ outcome = 'degraded';
434
+ }
435
+ else {
436
+ const historyItemId = this.#idFactory();
437
+ try {
438
+ await this.#provider.injectHostItem({
439
+ kind: 'dialogue_context',
440
+ host_item_id: historyItemId,
441
+ event_id: `${historyItemId}-event`,
442
+ content: packedContent,
443
+ call_id: null,
444
+ }, { confirmationTimeout });
445
+ outcome = 'packed';
446
+ }
447
+ catch (cause) {
448
+ // Uncertain and failed are different answers: uncertain means it may have arrived, so
449
+ // the caller must not assume the new session is missing it.
450
+ outcome = cause instanceof ItemDeliveryUncertainError ? 'uncertain' : 'degraded';
451
+ }
452
+ }
453
+ }
454
+ await this.#injectRecoveryItem(confirmationTimeout);
455
+ this.#state.advanceSnapshot();
456
+ return outcome;
457
+ }
458
+ async #replaceProviderSession(tools) {
459
+ this.#providerReplacementRevision++;
460
+ this.#replacementEpoch = null;
461
+ const identity = this.#provider.reconnect !== undefined
462
+ ? await this.#provider.reconnect(tools)
463
+ : await (async () => { await this.#provider.close(); return this.#provider.connect({ tools }); })();
464
+ // Keep delivery fenced until the caller publishes this identity into the host state.
465
+ this.#replacementEpoch = identity.epoch;
466
+ return identity;
467
+ }
468
+ /** The fields that belong to one provider session and none other. */
469
+ #resetForNewProviderSession() {
470
+ this.#yielded = null;
471
+ this.#confirmedRecoveryVersion = -1;
472
+ this.#recoveryResponses.clear();
473
+ this.#responseQuestions.clear();
474
+ this.#awaitingUserResponse = false;
475
+ this.#pendingUserResponse = null;
476
+ this.#latestUserResponse = null;
477
+ this.#userResponseRequest = null;
478
+ this.#fenceNextResponse = false;
479
+ this.#fenceInterruption = null;
480
+ this.#providerResponseId = null;
481
+ this.#hostPreemptResponseId = null;
482
+ this.#hostPreemptPending = false;
483
+ this.#spokenResponseId = null;
484
+ this.#state.clearSuppressedResponses();
485
+ this.#providerTranscript = '';
486
+ this.#state.clearPremapAudio();
487
+ }
488
+ /** Tell the new session what the old one had been doing. */
489
+ async #injectRecoveryItem(confirmationTimeout) {
490
+ const hostItemId = this.#idFactory();
491
+ const recovery = {
492
+ kind: 'recovery',
493
+ host_item_id: hostItemId,
494
+ event_id: `${hostItemId}-event`,
495
+ content: recoveryContent(this.snapshot()),
496
+ call_id: null,
497
+ };
498
+ const identity = confirmationTimeout === null
499
+ ? await this.#provider.injectHostItem(recovery)
500
+ : await this.#provider.injectHostItem(recovery, { confirmationTimeout });
501
+ if (identity.session_epoch !== this.sessionEpoch) {
502
+ throw new TypeError('recovery confirmation identity mismatch');
503
+ }
504
+ }
505
+ /**
506
+ * Give up every queued response.
507
+ *
508
+ * Their host events lose both their answer and their injection, because a response that never
509
+ * happened must be answerable again in the new session.
510
+ */
511
+ #abandonPendingResponses() {
512
+ for (const pending of this.#state.pendingResponses) {
513
+ for (const intent of pending.intents) {
514
+ this.#recoveryResponses.delete(`pending:${intent.item.host_item_id}`);
515
+ this.#state.releaseRespondedEvent(intent.item.event_id);
516
+ this.#state.releaseInjectedEvent(intent.item.event_id);
517
+ }
518
+ }
519
+ this.#state.clearPendingResponses();
520
+ }
521
+ // ---------------------------------------------------------------------------
522
+ // Host delivery
523
+ // ---------------------------------------------------------------------------
524
+ async deliverHostItem(item) {
525
+ const delivery = await this.deliverHostResponse(hostFact(item));
526
+ return delivery.accepted;
527
+ }
528
+ async deliverHostResponse(intent, options = {}) {
529
+ return this.#deliverHostResponse(intent, {
530
+ allowPlaybackOverlap: false,
531
+ confirmationTimeout: null,
532
+ asUserActivation: options.asUserActivation ?? false,
533
+ ...(options.responseAllowed === undefined ? {} : { responseAllowed: options.responseAllowed }),
534
+ });
535
+ }
536
+ /**
537
+ * Deliver a response that may talk over playback.
538
+ *
539
+ * A preemptive item waits only for the provider, not for the renderer, because the whole point is
540
+ * to interrupt. `responseAllowed` is re-checked after injection, since injecting is awaited and
541
+ * the reason for the response can expire while it is in flight.
542
+ */
543
+ async deliverPreemptiveHostResponse(intent, options = {}) {
544
+ return this.#deliverHostResponse(intent, {
545
+ allowPlaybackOverlap: true,
546
+ confirmationTimeout: options.confirmationTimeout ?? null,
547
+ asUserActivation: options.asUserActivation ?? false,
548
+ ...(options.responseAllowed === undefined ? {} : { responseAllowed: options.responseAllowed }),
549
+ });
550
+ }
551
+ async #deliverHostResponse(intent, options) {
552
+ const item = intent.item;
553
+ if (this.#state.hostEventIsDeduplicated(item.event_id)) {
554
+ return { accepted: false, injectionEpoch: null };
555
+ }
556
+ const ready = options.allowPlaybackOverlap ? this.providerIdle : this.foregroundIdle;
557
+ if (!ready)
558
+ throw new RealtimeDeliveryError('foreground became busy before host delivery');
559
+ let injectionEpoch = this.#state.injectedEventEpoch(item.event_id) ?? null;
560
+ if (item.kind === 'tool_output') {
561
+ if (injectionEpoch === null) {
562
+ throw new TypeError('tool output must be confirmed before response');
563
+ }
564
+ // A tool output from a previous epoch no longer refers to this conversation, unless it is a
565
+ // delegation acknowledgement, which narrates work that outlived the reconnect.
566
+ if (injectionEpoch !== this.sessionEpoch && intent.kind !== 'delegation_acknowledgement') {
567
+ return { accepted: false, injectionEpoch };
568
+ }
569
+ }
570
+ else if (injectionEpoch !== null && injectionEpoch !== this.sessionEpoch) {
571
+ return { accepted: false, injectionEpoch };
572
+ }
573
+ else if (injectionEpoch === null) {
574
+ await this.#injectHostItem(item, {
575
+ confirmationTimeout: options.confirmationTimeout,
576
+ asUserActivation: options.asUserActivation,
577
+ });
578
+ injectionEpoch = this.#state.injectedEventEpoch(item.event_id) ?? null;
579
+ }
580
+ if (options.responseAllowed !== undefined && !options.responseAllowed()) {
581
+ return { accepted: false, injectionEpoch };
582
+ }
583
+ await this.#createResponse(intent, [intent]);
584
+ return { accepted: true, injectionEpoch };
585
+ }
586
+ async injectToolOutput(item) {
587
+ if (item.kind !== 'tool_output') {
588
+ throw new TypeError('only tool output can bypass host response gating');
589
+ }
590
+ return this.#injectHostItem(item, { confirmationTimeout: null, asUserActivation: false });
591
+ }
592
+ async injectHostContext(item) {
593
+ if (item.kind === 'tool_output') {
594
+ throw new TypeError('tool output requires injectToolOutput');
595
+ }
596
+ if (item.kind === 'workspace_context') {
597
+ throw new TypeError('workspace context requires its dedicated delivery path');
598
+ }
599
+ return this.#injectHostItem(item, { confirmationTimeout: null, asUserActivation: false });
600
+ }
601
+ /** Delivery passes may only start a queued input once; explicit approval retries use the port below. */
602
+ async requestPendingUserResponse() {
603
+ if (this.#pendingUserResponse === null)
604
+ return false;
605
+ return this.requestUserResponse();
606
+ }
607
+ /** Request one normal provider response for the user turn that already reached transcript final. */
608
+ async requestUserResponse() {
609
+ if (this.#provider.ensureResponse === undefined
610
+ || this.#userResponseRequest !== null
611
+ || this.#providerResponseId !== null
612
+ || this.#yielded !== null
613
+ || this.#state.pendingResponseCount > 0
614
+ || this.#floor.state === 'user_speaking'
615
+ || this.#playback.current !== null
616
+ || this.#playback.hasUnreportedFence)
617
+ return false;
618
+ const pending = this.#pendingUserResponse;
619
+ const target = pending ?? this.#latestUserResponse;
620
+ if (this.#provider.userResponseMode === 'requested' && target === null)
621
+ return false;
622
+ const request = { itemId: target?.itemId ?? null, revision: target?.revision ?? this.userInputRevision,
623
+ requestId: `user-response-${this.sessionEpoch}-${++this.#userResponseSequence}`, armedHere: false };
624
+ this.#userResponseRequest = request;
625
+ this.#awaitingUserResponse = true;
626
+ if (this.#pendingUserResponse === pending)
627
+ this.#pendingUserResponse = null;
628
+ try {
629
+ const admitted = await this.#provider.ensureResponse(request.itemId ?? undefined, undefined, request.requestId);
630
+ if (admitted === false && this.#userResponseRequest === request) {
631
+ this.#userResponseRequest = null;
632
+ this.#awaitingUserResponse = false;
633
+ // false proves this request never owned a generation. Its pre-start fence has no target.
634
+ if (request.armedHere)
635
+ this.#fenceNextResponse = false;
636
+ if (pending !== null && this.userInputRevision === pending.revision) {
637
+ this.#pendingUserResponse ??= pending;
638
+ }
639
+ }
640
+ return admitted !== false;
641
+ }
642
+ catch (cause) {
643
+ if (this.#userResponseRequest === request) {
644
+ this.#userResponseRequest = null;
645
+ this.#awaitingUserResponse = false;
646
+ if (pending !== null && this.userInputRevision === pending.revision) {
647
+ this.#pendingUserResponse ??= pending;
648
+ }
649
+ }
650
+ throw new RealtimeDeliveryError(`user response request failed: ${String(cause)}`);
651
+ }
652
+ }
653
+ /** Retire one exact provider-visible host item without weakening the answered-event ledger. */
654
+ async retireHostEvent(eventId) {
655
+ const identity = this.#state.injectedProviderItem(eventId);
656
+ if (identity?.epoch !== this.sessionEpoch)
657
+ return false;
658
+ if (this.#provider.retireHostItem === undefined)
659
+ return false;
660
+ let retired;
661
+ try {
662
+ retired = await this.#provider.retireHostItem(identity.provider_item_id);
663
+ }
664
+ catch (cause) {
665
+ throw new RealtimeDeliveryError(`host item retirement failed: ${String(cause)}`);
666
+ }
667
+ if (!retired)
668
+ return false;
669
+ return this.#state.releaseInjectedProviderItem(eventId, identity);
670
+ }
671
+ /** Return an un-heard event's delivery authority after its provider session has been replaced. */
672
+ reopenHostEvent(eventId) {
673
+ const responded = this.#state.releaseRespondedEvent(eventId);
674
+ const injected = this.#state.releaseInjectedEvent(eventId);
675
+ return responded || injected;
676
+ }
677
+ /** Reuse one still-injected provider fact after renderer playback was interrupted. */
678
+ reopenHostResponse(eventId) {
679
+ if (this.#state.injectedEventEpoch(eventId) !== this.sessionEpoch)
680
+ return false;
681
+ this.#state.releaseRespondedEvent(eventId);
682
+ return true;
683
+ }
684
+ async #injectHostItem(item, options) {
685
+ if (this.#replacementEpoch !== undefined && this.#replacementEpoch !== this.sessionEpoch) {
686
+ throw new RealtimeDeliveryError('provider session replacement is pending');
687
+ }
688
+ const replacementRevision = this.#providerReplacementRevision;
689
+ const epoch = this.sessionEpoch;
690
+ if (this.#state.injectedEventEpoch(item.event_id) !== undefined)
691
+ return false;
692
+ let identity;
693
+ try {
694
+ identity = options.asUserActivation
695
+ ? await this.#provider.injectHostItem(item, {
696
+ confirmationTimeout: options.confirmationTimeout,
697
+ asUserActivation: true,
698
+ })
699
+ : options.confirmationTimeout === null
700
+ ? await this.#provider.injectHostItem(item)
701
+ : await this.#provider.injectHostItem(item, {
702
+ confirmationTimeout: options.confirmationTimeout,
703
+ });
704
+ }
705
+ catch (cause) {
706
+ // An uncertain delivery is not a failure: the item may have arrived, so the caller must not
707
+ // retry it as though it had not.
708
+ if (cause instanceof ItemDeliveryUncertainError)
709
+ throw cause;
710
+ throw new RealtimeDeliveryError(`host item injection failed: ${String(cause)}`);
711
+ }
712
+ // Late acknowledgements from an abandoned provider are transient delivery failures,
713
+ // not malformed identities in the new session. Never publish them into its ledger.
714
+ if (replacementRevision !== this.#providerReplacementRevision || epoch !== this.sessionEpoch) {
715
+ throw new RealtimeDeliveryError('provider session changed during host item injection');
716
+ }
717
+ if (identity.session_epoch !== this.sessionEpoch
718
+ || identity.host_item_id !== item.host_item_id) {
719
+ throw new TypeError('host item confirmation identity mismatch');
720
+ }
721
+ this.#state.recordInjectedEvent(item.event_id, identity.provider_item_id);
722
+ return true;
723
+ }
724
+ async #createResponse(intent, intents) {
725
+ const pending = { intents: [...intents], provider_intent: intent, user_input_revision: this.userInputRevision };
726
+ // A provider may publish its start before the command promise resolves. Register ownership first.
727
+ this.#state.queuePendingResponse(pending);
728
+ const eventIds = intents.map(candidate => candidate.item.event_id);
729
+ try {
730
+ await this.#provider.createResponse(intent);
731
+ }
732
+ catch (cause) {
733
+ this.#state.discardPendingResponse(pending);
734
+ if (cause instanceof ProviderResponseRejectedError)
735
+ throw cause;
736
+ throw new ResponseRequestUncertainError(`response request failed: ${String(cause)}`);
737
+ }
738
+ for (const eventId of eventIds)
739
+ this.#state.markEventResponded(eventId);
740
+ this.#state.pruneHostEventLedgers(eventIds);
741
+ }
742
+ // ---------------------------------------------------------------------------
743
+ // The reducer
744
+ // ---------------------------------------------------------------------------
745
+ /**
746
+ * Reduce one normalized provider event. `true` means the session acted on it.
747
+ *
748
+ * The return value is the contract: a refusal is a decision, not an omission. Several guards
749
+ * differ *only* in the boolean they return, which is why the fixtures record it per step.
750
+ */
751
+ async accept(event, options = {}) {
752
+ // An event from another provider session describes a world this session no longer has.
753
+ if (event.session_epoch !== this.sessionEpoch)
754
+ return false;
755
+ switch (event.kind) {
756
+ case 'tool_call_ready':
757
+ return this.#acceptToolCall(event.response_id);
758
+ case 'response_started':
759
+ return this.#acceptResponseStarted(event.response_id, event.origin, options.allowResponseStartDuringUserSpeech === true);
760
+ case 'response_audio_delta':
761
+ return this.#acceptAudioDelta(event.response_id, event.pcm);
762
+ case 'response_transcript_final':
763
+ return this.#acceptTranscriptFinal(event.response_id, event.text);
764
+ case 'response_yielded': {
765
+ const turn = this.#state.providerTurn(event.response_id);
766
+ if (this.#providerResponseId !== event.response_id || turn?.phase !== 'active' || turn.locally_fenced)
767
+ return false;
768
+ const accepted = this.#acceptTerminal(event.response_id, 'yielded', event.session_epoch);
769
+ if (accepted)
770
+ this.#yielded = { responseId: event.response_id, callIds: event.call_ids };
771
+ return accepted;
772
+ }
773
+ case 'response_terminal':
774
+ return this.#acceptTerminal(event.response_id, event.status, event.session_epoch, event.origin);
775
+ case 'user_speech_started':
776
+ return this.#acceptSpeechStarted(event.speech_id, event.provider_item_id);
777
+ case 'user_speech_ended':
778
+ return this.#acceptSpeechEnded(event.speech_id, event.provider_item_id);
779
+ case 'user_transcript_final':
780
+ // Admit transcript-only input before comparing revisions; speech identities deduplicate here.
781
+ this.#state.acceptUserTurn(event.item_id);
782
+ this.#latestQuestion = { id: event.item_id, text: event.text };
783
+ if (this.#providerResponseId !== null
784
+ && this.providerTurnUserInputRevision(this.#providerResponseId) === this.userInputRevision
785
+ && !this.#responseItems.has(this.#turnKey(this.#providerResponseId))) {
786
+ this.#responseQuestions.set(this.#turnKey(this.#providerResponseId), this.#latestQuestion);
787
+ }
788
+ return this.#acceptTranscriptTerminal(event.item_id, event.kind, event.response_expected !== false);
789
+ case 'user_transcript_failed':
790
+ return this.#acceptTranscriptTerminal(event.item_id, event.kind);
791
+ case 'provider_error':
792
+ if (!event.recoverable)
793
+ this.#releaseUserResponseRequest();
794
+ return false;
795
+ default:
796
+ // Deltas, confirmations and cancel rejections are not this reducer's to
797
+ // act on. Transcript deltas belong to `captionFor`; the rest belong to the layer above.
798
+ return false;
799
+ }
800
+ }
801
+ #acceptToolCall(eventResponseId) {
802
+ const responseId = eventResponseId ?? this.#providerResponseId;
803
+ // Only session-owned request items can identify a scheduled activation. The scoped tool
804
+ // runtime still validates its run authority and read-only policy before any read.
805
+ const scheduled = responseId !== null && this.#responseItems.get(this.#turnKey(responseId))?.some(item => item.kind === 'scheduled_task') === true;
806
+ if (this.#provider.userResponseMode === 'requested' && responseId === null)
807
+ return false;
808
+ if (responseId !== null) {
809
+ const turn = this.#state.providerTurn(responseId);
810
+ if (this.#provider.userResponseMode === 'requested' && turn?.origin === undefined)
811
+ return false;
812
+ if (turn !== undefined && (turn.locally_fenced || turn.phase !== 'active'))
813
+ return false;
814
+ if (turn?.origin?.kind === 'unknown')
815
+ return false;
816
+ if (turn?.origin?.kind === 'host_request' && !scheduled && !this.responseIsToolContinuation(responseId))
817
+ return false;
818
+ }
819
+ if (responseId !== null && this.#responseItems.has(this.#turnKey(responseId))
820
+ && !scheduled && !this.responseIsToolContinuation(responseId)) {
821
+ // Host factual narration cannot propose tools. Continuations still need host authorization.
822
+ return false;
823
+ }
824
+ return true;
825
+ }
826
+ async #acceptResponseStarted(responseId, origin, allowDuringUserSpeech) {
827
+ const requested = this.#userResponseRequest;
828
+ let turn = this.#state.providerTurn(responseId);
829
+ const matchesRequest = this.#matchesUserResponseRequest(origin);
830
+ if (matchesRequest || (this.#provider.userResponseMode !== 'requested' && origin === undefined)) {
831
+ this.#userResponseRequest = null;
832
+ this.#awaitingUserResponse = false;
833
+ }
834
+ if (turn !== undefined && (turn.locally_fenced || turn.phase !== 'active'))
835
+ return false;
836
+ const knownUserResponse = origin?.kind === 'user_item' && turn?.origin?.kind === 'user_item'
837
+ && origin.item_id === turn.origin.item_id && origin.request_id === turn.origin.request_id;
838
+ if (this.#provider.userResponseMode === 'requested'
839
+ && origin?.kind !== 'host_request' && !matchesRequest && !knownUserResponse) {
840
+ this.#markLocallyFenced(responseId);
841
+ if (this.#state.premapResponseId === responseId)
842
+ this.#state.clearPremapAudio();
843
+ this.#onDiagnostic('[realtime-diagnostic] unmatched_user_response_request');
844
+ await this.#provider.cancelResponse(responseId);
845
+ return false;
846
+ }
847
+ if (turn !== undefined && this.#fenceNextResponse) {
848
+ // An active recorded turn must not coexist with an armed pre-start fence: the known entry
849
+ // was closed at the oversized-delta gate. A provider protocol violation that recreates the
850
+ // shape is rejected loudly rather than killing the session.
851
+ this.#onDiagnostic('[realtime-diagnostic] armed_fence_turn_conflict');
852
+ turn.locally_fenced = true;
853
+ turn.phase = 'cancel_requested';
854
+ if (this.#state.premapResponseId === responseId)
855
+ this.#state.clearPremapAudio();
856
+ this.#state.advanceSnapshot();
857
+ await this.#provider.cancelResponse(responseId);
858
+ return false;
859
+ }
860
+ // The user holds the floor, so the queued host utterance loses its turn rather than talking
861
+ // over them.
862
+ if (this.#floor.state === 'user_speaking' && !allowDuringUserSpeech) {
863
+ await this.#fencePendingResponse(responseId);
864
+ return false;
865
+ }
866
+ if (turn === undefined && this.#fenceNextResponse) {
867
+ await this.#fencePendingResponse(responseId);
868
+ return false;
869
+ }
870
+ if (this.#providerResponseId !== null) {
871
+ // Another response owns the slot. Fence the newcomer so a provider that reuses the id later
872
+ // cannot reclaim a turn this session already gave up on.
873
+ if (this.#providerResponseId !== responseId)
874
+ this.#markLocallyFenced(responseId);
875
+ return false;
876
+ }
877
+ const premapOwner = this.#state.premapResponseId;
878
+ if (premapOwner !== null && premapOwner !== responseId) {
879
+ // The buffer belongs to one response at a time; adopting another's audio would lose which
880
+ // is which, so it is discarded rather than replayed into the wrong generation.
881
+ this.#state.clearPremapAudio();
882
+ return false;
883
+ }
884
+ turn ??= this.#state.openProviderTurn(responseId, requested !== null && matchesRequest
885
+ ? requested.revision : this.userInputRevision);
886
+ if (turn.origin === undefined && origin !== undefined)
887
+ turn.origin = origin;
888
+ this.#providerResponseId = responseId;
889
+ this.#spokenResponseId = null;
890
+ this.#providerTranscript = '';
891
+ const pending = origin === undefined
892
+ ? this.#state.popPendingResponse()
893
+ : origin.kind === 'host_request'
894
+ ? this.#state.takePendingResponse(origin.host_item_id)
895
+ : undefined;
896
+ if (pending !== undefined) {
897
+ this.#responseItems.set(this.#turnKey(responseId), pending.intents.map(intent => intent.item));
898
+ if (pending.provider_intent.origin_spoken
899
+ && pending.user_input_revision === this.userInputRevision) {
900
+ // Provider instructions are advisory. The host's played-origin proof owns audible
901
+ // acknowledgement -- but only for the world that response answers, which is why the
902
+ // revision has to still match.
903
+ this.#state.suppressResponse(responseId);
904
+ }
905
+ }
906
+ const recovery = pending?.provider_intent.item.event_id.startsWith('delivery-recovery:') === true;
907
+ if (pending === undefined || pending.provider_intent.kind === 'tool_result' || recovery) {
908
+ this.deliveryRecoveryContext();
909
+ if (recovery && pending !== undefined) {
910
+ const key = `pending:${pending.provider_intent.item.host_item_id}`;
911
+ this.#recoveryResponses.set(this.#turnKey(responseId), this.#recoveryResponses.get(key) ?? []);
912
+ this.#recoveryResponses.delete(key);
913
+ }
914
+ else if (this.#confirmedRecoveryVersion === this.#recoveryVersion && this.#unheard.size > 0) {
915
+ this.#recoveryResponses.set(this.#turnKey(responseId), [...this.#unheard.keys()]);
916
+ }
917
+ if (pending === undefined && this.#latestQuestion) {
918
+ this.#responseQuestions.set(this.#turnKey(responseId), this.#latestQuestion);
919
+ while (this.#responseQuestions.size > 32)
920
+ this.#responseQuestions.delete(this.#responseQuestions.keys().next().value);
921
+ }
922
+ }
923
+ const buffered = this.#state.premapAudio;
924
+ if (buffered.length > 0
925
+ && !this.#state.responseIsSuppressed(responseId)
926
+ && this.#openAudioResponse(responseId)) {
927
+ for (const pcm of buffered) {
928
+ this.#playback.pushAudio({
929
+ sessionEpoch: this.sessionEpoch,
930
+ responseId,
931
+ pcm,
932
+ });
933
+ }
934
+ }
935
+ this.#state.clearPremapAudio();
936
+ return true;
937
+ }
938
+ async #acceptAudioDelta(responseId, pcm) {
939
+ const head = this.#state.headPendingResponse;
940
+ const suppressPending = this.#providerResponseId === null
941
+ && head !== undefined
942
+ && head.provider_intent.origin_spoken
943
+ && head.user_input_revision === this.userInputRevision;
944
+ if (this.#state.responseIsSuppressed(responseId) || suppressPending) {
945
+ // Recorded rather than merely refused: the suppression has to outlive this delta so every
946
+ // later frame from the same response is refused too.
947
+ this.#state.suppressResponse(responseId);
948
+ return false;
949
+ }
950
+ if (this.#floor.state === 'user_speaking') {
951
+ if (this.#state.pendingResponseCount > 0)
952
+ await this.#fencePendingResponse(responseId);
953
+ return false;
954
+ }
955
+ let turn = this.#state.providerTurn(responseId);
956
+ if (turn === undefined) {
957
+ if (this.#fenceNextResponse) {
958
+ await this.#fencePendingResponse(responseId);
959
+ return false;
960
+ }
961
+ // Nothing pending means no intent for this audio to belong to, so there is nothing to
962
+ // buffer it against.
963
+ if (this.#state.pendingResponseCount === 0)
964
+ return false;
965
+ const premapOwner = this.#state.premapResponseId;
966
+ if (premapOwner !== null && premapOwner !== responseId)
967
+ return false;
968
+ // Checked here as well as below, and the two are not redundant: this one refuses without
969
+ // recording a turn at all, so an oversized first delta leaves no trace of the response.
970
+ if (this.#state.premapAudioWouldExceed(pcm.byteLength)) {
971
+ this.#state.clearPremapAudio();
972
+ return false;
973
+ }
974
+ turn = this.#state.openProviderTurn(responseId);
975
+ }
976
+ if (turn.locally_fenced || turn.phase !== 'active')
977
+ return false;
978
+ if (this.#playback.pushAudio({ sessionEpoch: this.sessionEpoch, responseId, pcm }))
979
+ return true;
980
+ if (this.#providerResponseId === responseId) {
981
+ if (!this.#openAudioResponse(responseId))
982
+ return false;
983
+ return this.#playback.pushAudio({ sessionEpoch: this.sessionEpoch, responseId, pcm });
984
+ }
985
+ if (this.#state.premapAudioWouldExceed(pcm.byteLength)) {
986
+ // Over budget means the buffered audio is unusable, not that this one delta is: a gap in
987
+ // the middle would be worse than starting over.
988
+ this.#state.clearPremapAudio();
989
+ return false;
990
+ }
991
+ this.#state.bufferPremapAudio(responseId, pcm);
992
+ return true;
993
+ }
994
+ #acceptTranscriptFinal(responseId, text) {
995
+ if (this.#state.responseIsSuppressed(responseId))
996
+ return false;
997
+ if (this.#playback.setTranscript({ sessionEpoch: this.sessionEpoch, responseId, text })) {
998
+ return true;
999
+ }
1000
+ const turn = this.#state.providerTurn(responseId);
1001
+ if (turn !== undefined && (turn.locally_fenced || turn.phase !== 'active'))
1002
+ return false;
1003
+ if (this.#providerResponseId === responseId) {
1004
+ // Cached for the generation this response has not opened yet. Holding the slot is not
1005
+ // authority, which is why the fence check above still applies to a slot owner.
1006
+ this.#providerTranscript = text;
1007
+ return true;
1008
+ }
1009
+ // A transcript the session cannot attribute is not evidence about anything.
1010
+ return false;
1011
+ }
1012
+ #matchesUserResponseRequest(origin) {
1013
+ const request = this.#userResponseRequest;
1014
+ return request !== null && origin?.kind === 'user_item' && origin.item_id === request.itemId
1015
+ && (this.#provider.userResponseMode !== 'requested' || origin.request_id === request.requestId);
1016
+ }
1017
+ #releaseUserResponseRequest() {
1018
+ const request = this.#userResponseRequest;
1019
+ if (request === null)
1020
+ return;
1021
+ if (request.armedHere)
1022
+ this.#fenceNextResponse = false;
1023
+ this.#userResponseRequest = null;
1024
+ this.#awaitingUserResponse = false;
1025
+ }
1026
+ #acceptTerminal(responseId, status, eventEpoch, origin) {
1027
+ const turn = this.#state.providerTurn(responseId);
1028
+ if (turn === undefined) {
1029
+ if (this.#matchesUserResponseRequest(origin)) {
1030
+ const ended = this.#state.openProviderTurn(responseId, this.#userResponseRequest.revision);
1031
+ ended.origin = origin;
1032
+ ended.phase = status;
1033
+ this.#releaseUserResponseRequest();
1034
+ return true;
1035
+ }
1036
+ // A pre-start fence has no provider response id to cancel. If its first observable event is
1037
+ // a terminal, it consumes the one-shot fence and releases the fenced pending's inference
1038
+ // slot. Without an armed fence an unknown terminal must not touch a live pending response.
1039
+ if (this.#fenceNextResponse && this.#userResponseRequest?.armedHere !== true) {
1040
+ this.#fenceNextResponse = false;
1041
+ this.#state.popPendingResponse();
1042
+ }
1043
+ return false;
1044
+ }
1045
+ // Audio may have created a fenced turn before its start event. Its exact request still
1046
+ // needs settlement, even if the provider proceeds directly to a terminal.
1047
+ if (this.#matchesUserResponseRequest(origin))
1048
+ this.#releaseUserResponseRequest();
1049
+ if ((turn.phase === 'yielded' && status === 'yielded') || turn.phase === 'completed' || turn.phase === 'cancelled' || turn.phase === 'failed') {
1050
+ // Applied once. A retransmission must not deliver the utterance twice, and a contradictory
1051
+ // status arriving later must not reopen a decided turn.
1052
+ return false;
1053
+ }
1054
+ // An unrelated/quarantined terminal cannot disarm the outstanding request's pre-start fence.
1055
+ if (this.#userResponseRequest === null)
1056
+ this.#awaitingUserResponse = false;
1057
+ if (this.#yielded?.responseId === responseId && status !== 'yielded')
1058
+ this.#yielded = null;
1059
+ turn.phase = status;
1060
+ if (this.#providerResponseId === responseId) {
1061
+ this.#providerResponseId = null;
1062
+ this.#providerTranscript = '';
1063
+ }
1064
+ if (this.#state.premapResponseId === responseId)
1065
+ this.#state.clearPremapAudio();
1066
+ if (status === 'completed' || status === 'yielded') {
1067
+ if (this.#playback.current?.response_id !== responseId) {
1068
+ this.#recoveryResponses.delete(this.#turnKey(responseId));
1069
+ this.#responseQuestions.delete(this.#turnKey(responseId));
1070
+ }
1071
+ if (this.#state.responseIsSuppressed(responseId)) {
1072
+ this.#state.releaseSuppressedResponse(responseId);
1073
+ this.#finishResponseAuthority(responseId);
1074
+ return true;
1075
+ }
1076
+ this.#playback.markProviderTerminal({ sessionEpoch: this.sessionEpoch, responseId });
1077
+ return true;
1078
+ }
1079
+ this.#state.releaseSuppressedResponse(responseId);
1080
+ this.#markResponseInterrupted(responseId);
1081
+ const current = this.#playback.current;
1082
+ if (turn.defer_playback_fence) {
1083
+ // A host preempt deferred the renderer fence, so the audio already queued keeps playing and
1084
+ // reports back rather than being cut mid-word.
1085
+ if (current !== null
1086
+ && current.session_epoch === eventEpoch
1087
+ && current.response_id === responseId) {
1088
+ this.#playback.markProviderTerminal({
1089
+ sessionEpoch: this.sessionEpoch,
1090
+ responseId,
1091
+ disposition: 'interrupted',
1092
+ });
1093
+ }
1094
+ else if (!this.responseHasSpoken(responseId)) {
1095
+ this.#finishResponseAuthority(responseId);
1096
+ }
1097
+ this.#state.advanceSnapshot();
1098
+ return true;
1099
+ }
1100
+ if (current?.session_epoch !== eventEpoch || current.response_id !== responseId) {
1101
+ if (!this.responseHasSpoken(responseId))
1102
+ this.#finishResponseAuthority(responseId);
1103
+ return true;
1104
+ }
1105
+ const generation = this.#playback.fenceCurrent();
1106
+ if (generation !== null) {
1107
+ this.#markLocallyFenced(generation.response_id);
1108
+ this.#markResponseInterrupted(generation.response_id);
1109
+ this.#state.advanceSnapshot();
1110
+ }
1111
+ return true;
1112
+ }
1113
+ #acceptSpeechStarted(speechId, providerItemId) {
1114
+ // Floor only. Fencing the renderer here would mark the origin turn locally fenced and suppress
1115
+ // dispatch of a tool call still owned by that response: a user barge-in is not an abandonment
1116
+ // of tool protocol state. The local onset detector is the renderer barge-in path.
1117
+ this.#floor = this.#floor.onUserSpeakStart(speechId);
1118
+ this.#state.acceptUserTurn(providerItemId ?? `speech:${speechId}`);
1119
+ this.#userHoldSince = this.#clock.now();
1120
+ return true;
1121
+ }
1122
+ #acceptSpeechEnded(speechId, providerItemId) {
1123
+ const before = this.#floor;
1124
+ this.#floor = this.#floor.onUserSpeakEnd(speechId);
1125
+ if (providerItemId !== null) {
1126
+ // The provider reveals the turn's real item id here. Renaming rather than recording a second
1127
+ // turn is what stops the same utterance counting twice.
1128
+ this.#state.replaceUserTurnIdentity(`speech:${speechId}`, providerItemId);
1129
+ }
1130
+ if (this.#floor.state !== 'user_speaking')
1131
+ this.#userHoldSince = null;
1132
+ // Only the speech that took the floor can release it, so a mismatched id changes nothing.
1133
+ return this.#floor !== before;
1134
+ }
1135
+ async #acceptTranscriptTerminal(itemId, kind, responseExpected = true) {
1136
+ if (!this.#state.acceptUserTranscriptTerminal(itemId))
1137
+ return false;
1138
+ this.#state.acceptUserTurn(itemId);
1139
+ if (kind === 'user_transcript_failed')
1140
+ return true;
1141
+ this.#latestUserResponse = { itemId, revision: this.userInputRevision };
1142
+ if (this.#provider.userResponseMode === 'requested') {
1143
+ this.#pendingUserResponse = this.#latestUserResponse;
1144
+ // Queued input is not in-flight inference: only existing provider/playback work is revoked.
1145
+ await this.#fenceAndCancelActiveResponse();
1146
+ return true;
1147
+ }
1148
+ // A final transcript is a question the provider owes an answer to, so the session is no longer
1149
+ // idle even though no response has started.
1150
+ if (responseExpected)
1151
+ this.#awaitingUserResponse = true;
1152
+ return true;
1153
+ }
1154
+ // ---------------------------------------------------------------------------
1155
+ // Barge-in and preempt
1156
+ // ---------------------------------------------------------------------------
1157
+ /**
1158
+ * The local energy detector heard the user.
1159
+ *
1160
+ * This is a barge-in signal only: it fences the audible renderer and cancels active provider
1161
+ * inference, but never takes the user_speaking floor. Floor ownership belongs to provider VAD
1162
+ * alone -- a local random id would overwrite the provider speech id, and the matching provider
1163
+ * end could then no longer release the floor.
1164
+ */
1165
+ async localSpeechOnset(speechId) {
1166
+ // The id is accepted and discarded, exactly as the oracle does: callers have one to give, and
1167
+ // taking it keeps them from inventing a floor identity this path must not own.
1168
+ void speechId;
1169
+ this.#hostPreemptPending = false;
1170
+ await this.#fenceAndCancelActiveResponse();
1171
+ }
1172
+ /**
1173
+ * The host wants the floor for something more important.
1174
+ *
1175
+ * Cancelling the provider and fencing the renderer are separate decisions here. When a response
1176
+ * is generating, its audio already queued is left playing (`defer_playback_fence`) so the user
1177
+ * hears a finished clause rather than a cut word; the fence lands when its terminal arrives.
1178
+ */
1179
+ async hostPreempt() {
1180
+ if (this.#floor.state === 'user_speaking')
1181
+ return false;
1182
+ const responseId = this.#providerResponseId;
1183
+ const generation = this.#playback.current;
1184
+ if (responseId !== null
1185
+ && generation !== null
1186
+ && generation.session_epoch !== this.sessionEpoch
1187
+ && generation.response_id === responseId) {
1188
+ // A generation from an older epoch that happens to share this response id is not this
1189
+ // response's audio, and preempting on that coincidence would fence the wrong utterance.
1190
+ return false;
1191
+ }
1192
+ if (responseId !== null) {
1193
+ const turn = this.#state.openProviderTurn(responseId);
1194
+ if (turn.phase === 'cancel_requested')
1195
+ return false;
1196
+ turn.phase = 'cancel_requested';
1197
+ turn.defer_playback_fence = true;
1198
+ this.#hostPreemptResponseId = responseId;
1199
+ await this.#provider.cancelResponse(responseId);
1200
+ return true;
1201
+ }
1202
+ if (generation !== null && generation.session_epoch === this.sessionEpoch) {
1203
+ const turn = this.#state.providerTurn(generation.response_id);
1204
+ if (turn !== undefined && !turn.defer_playback_fence) {
1205
+ turn.defer_playback_fence = true;
1206
+ this.#hostPreemptResponseId = generation.response_id;
1207
+ return true;
1208
+ }
1209
+ }
1210
+ const preempted = await this.#fenceAndCancelActiveResponse();
1211
+ if (preempted && this.#fenceNextResponse)
1212
+ this.#hostPreemptPending = true;
1213
+ return preempted;
1214
+ }
1215
+ /**
1216
+ * Fence whatever is audible and cancel whatever is generating.
1217
+ *
1218
+ * Five cases, and which one applies turns on how far the response has got. Note what this does
1219
+ * *not* do: the cancelled response keeps the provider slot until its own terminal arrives, so a
1220
+ * second `response.create` cannot go out while this cancellation is in flight.
1221
+ */
1222
+ async #fenceAndCancelActiveResponse(expectedResponseId = null) {
1223
+ const currentGeneration = this.#playback.current;
1224
+ const generationMatches = currentGeneration !== null
1225
+ && (expectedResponseId === null
1226
+ || (currentGeneration.session_epoch === this.sessionEpoch
1227
+ && currentGeneration.response_id === expectedResponseId));
1228
+ const generation = generationMatches ? this.#playback.fenceCurrent() : null;
1229
+ const fenced = generation !== null;
1230
+ const generationOwnsProvider = generation !== null
1231
+ && generation.session_epoch === this.sessionEpoch;
1232
+ if (generation !== null && generationOwnsProvider) {
1233
+ this.#markLocallyFenced(generation.response_id);
1234
+ this.#markResponseInterrupted(generation.response_id);
1235
+ this.#state.advanceSnapshot();
1236
+ }
1237
+ const activeResponseId = this.#providerResponseId;
1238
+ if (activeResponseId !== null) {
1239
+ if (expectedResponseId !== null && activeResponseId !== expectedResponseId)
1240
+ return fenced;
1241
+ // A generation from an older epoch that shares this response id is not this response's
1242
+ // audio; fencing it was right, cancelling on that coincidence would not be.
1243
+ if (generation !== null
1244
+ && !generationOwnsProvider
1245
+ && generation.response_id === activeResponseId) {
1246
+ return fenced;
1247
+ }
1248
+ const turn = this.#state.openProviderTurn(activeResponseId);
1249
+ if (turn.phase === 'cancel_requested') {
1250
+ // Already cancelled, by a host preempt that deferred the renderer fence. The fence has now
1251
+ // happened, so the deferral is spent and must not fence a later generation.
1252
+ turn.defer_playback_fence = false;
1253
+ if (this.#hostPreemptResponseId === activeResponseId)
1254
+ this.#hostPreemptResponseId = null;
1255
+ return expectedResponseId === null ? fenced : true;
1256
+ }
1257
+ turn.locally_fenced = true;
1258
+ turn.phase = 'cancel_requested';
1259
+ // Its own generation was already marked interrupted above; marking twice would be wrong only
1260
+ // in the snapshot count, which is exactly what the goldens compare.
1261
+ if (generation === null
1262
+ || !generationOwnsProvider
1263
+ || generation.response_id !== activeResponseId) {
1264
+ this.#markResponseInterrupted(activeResponseId);
1265
+ this.#state.advanceSnapshot();
1266
+ }
1267
+ await this.#provider.cancelResponse(activeResponseId);
1268
+ return true;
1269
+ }
1270
+ const premapResponseId = this.#state.premapResponseId;
1271
+ if (expectedResponseId !== null && premapResponseId !== expectedResponseId)
1272
+ return fenced;
1273
+ if (premapResponseId === null) {
1274
+ // `response.create` may already be in flight with no provider response id yet. Arm a
1275
+ // one-shot fence so the next unowned start or pre-map delta is fenced instead of played.
1276
+ // The fenced pending stays queued: it still owns the one inference slot, so no second
1277
+ // create can go out until a consumption event pops it.
1278
+ if (expectedResponseId === null
1279
+ && this.#state.pendingResponseCount > 0
1280
+ && !this.#fenceNextResponse) {
1281
+ this.#fenceNextResponse = true;
1282
+ this.#markHeadPendingFenced();
1283
+ this.#state.advanceSnapshot();
1284
+ return true;
1285
+ }
1286
+ if (expectedResponseId === null && this.#awaitingUserResponse && !this.#fenceNextResponse) {
1287
+ this.#fenceNextResponse = true;
1288
+ if (this.#userResponseRequest !== null)
1289
+ this.#userResponseRequest.armedHere = true;
1290
+ this.#state.advanceSnapshot();
1291
+ return true;
1292
+ }
1293
+ return fenced;
1294
+ }
1295
+ // Audio arrived before the start, so the response is known by the buffer alone. It takes the
1296
+ // provider slot here so its terminal has something to close.
1297
+ const turn = this.#state.openProviderTurn(premapResponseId);
1298
+ turn.locally_fenced = true;
1299
+ turn.phase = 'cancel_requested';
1300
+ this.#providerResponseId = premapResponseId;
1301
+ this.#abandonPendingResponse();
1302
+ this.#state.clearPremapAudio();
1303
+ this.#state.advanceSnapshot();
1304
+ await this.#provider.cancelResponse(premapResponseId);
1305
+ return true;
1306
+ }
1307
+ /**
1308
+ * Fence a response before it owns a playback generation.
1309
+ *
1310
+ * The fenced response keeps the provider slot until its own terminal: releasing it early would
1311
+ * let a preemptive alert open a second inference while this cancellation is still in flight.
1312
+ */
1313
+ async #fencePendingResponse(responseId) {
1314
+ const armed = this.#fenceNextResponse;
1315
+ this.#fenceNextResponse = false;
1316
+ const turn = this.#state.openProviderTurn(responseId);
1317
+ turn.locally_fenced = true;
1318
+ turn.phase = 'cancel_requested';
1319
+ this.#providerResponseId = responseId;
1320
+ if (this.#hostPreemptPending) {
1321
+ this.#hostPreemptResponseId = responseId;
1322
+ turn.defer_playback_fence = true;
1323
+ }
1324
+ if (armed) {
1325
+ // Arming already emitted the receipt for this pending; consuming it only releases the slot.
1326
+ this.#state.popPendingResponse();
1327
+ }
1328
+ else {
1329
+ this.#abandonPendingResponse();
1330
+ }
1331
+ this.#state.clearPremapAudio();
1332
+ this.#state.advanceSnapshot();
1333
+ await this.#provider.cancelResponse(responseId);
1334
+ }
1335
+ #markHeadPendingFenced() {
1336
+ const pending = this.#state.headPendingResponse;
1337
+ if (pending === undefined)
1338
+ return [];
1339
+ const items = pending.intents.map(intent => intent.item);
1340
+ for (const item of items)
1341
+ this.#recoveryResponses.delete(`pending:${item.host_item_id}`);
1342
+ const eventIds = items.map(item => item.event_id);
1343
+ for (const eventId of eventIds)
1344
+ this.#state.markEventInterrupted(eventId);
1345
+ this.#releaseSuggestionEventAuthority(items);
1346
+ this.#fenceInterruption = { session_epoch: this.sessionEpoch, event_ids: eventIds };
1347
+ return eventIds;
1348
+ }
1349
+ #abandonPendingResponse() {
1350
+ const eventIds = this.#markHeadPendingFenced();
1351
+ this.#state.popPendingResponse();
1352
+ return eventIds;
1353
+ }
1354
+ /**
1355
+ * Spend a deferred preempt fence, now that the audio it was waiting on is done.
1356
+ *
1357
+ * `hostPreempt` deferred fencing the renderer so a clause could finish. This is where that debt
1358
+ * is settled: pass the generation the preempt was aimed at, or `null` when the preempt never got
1359
+ * one because the response had not yet opened playback.
1360
+ */
1361
+ expireHostPreempt(generation) {
1362
+ const responseId = this.#hostPreemptResponseId;
1363
+ if (responseId === null) {
1364
+ // No response was preempted, so the only thing left to settle is a pending pre-start preempt,
1365
+ // and only when there is nothing audible to wait for.
1366
+ if (generation !== null || !this.#hostPreemptPending)
1367
+ return false;
1368
+ this.#hostPreemptPending = false;
1369
+ if (this.#playback.current === null)
1370
+ this.#playback.fenceCurrent({ alert: true });
1371
+ this.#state.advanceSnapshot();
1372
+ return true;
1373
+ }
1374
+ const turn = this.#state.providerTurn(responseId);
1375
+ if (turn?.defer_playback_fence !== true)
1376
+ return false;
1377
+ turn.defer_playback_fence = false;
1378
+ this.#hostPreemptResponseId = null;
1379
+ const current = this.#playback.current;
1380
+ let fenced = null;
1381
+ if (generation !== null && current !== null && sameGeneration(current, generation)) {
1382
+ // Alert-fenced, not silently fenced: the user was interrupted mid-utterance and the renderer
1383
+ // has to say so rather than just stopping.
1384
+ fenced = this.#playback.fenceCurrent({ alert: true });
1385
+ }
1386
+ else if (generation === null && this.#hostPreemptPending && current === null) {
1387
+ this.#playback.fenceCurrent({ alert: true });
1388
+ }
1389
+ this.#hostPreemptPending = false;
1390
+ if (fenced !== null && fenced.session_epoch === this.sessionEpoch) {
1391
+ this.#markLocallyFenced(fenced.response_id);
1392
+ }
1393
+ this.#markResponseInterrupted(responseId);
1394
+ this.#state.advanceSnapshot();
1395
+ return true;
1396
+ }
1397
+ /** Alert-fence the exact renderer generation retained for a preemptive-alert handoff. */
1398
+ alertPreemptiveAlertHandoff(generation) {
1399
+ // Reached with nothing current once the retained audio finishes: the generation is retired
1400
+ // while the handoff is still recorded, so a mismatched one would otherwise take the
1401
+ // nothing-is-playing branch and consume a handoff it does not name.
1402
+ if (this.#preemptiveAlertHandoffGeneration === null
1403
+ || !sameGeneration(this.#preemptiveAlertHandoffGeneration, generation)) {
1404
+ return false;
1405
+ }
1406
+ const current = this.#playback.current;
1407
+ if (current !== null && sameGeneration(current, generation)) {
1408
+ if (!this.#playback.alertFenceGeneration(generation))
1409
+ return false;
1410
+ }
1411
+ else if (current === null) {
1412
+ this.#playback.fenceCurrent({ alert: true });
1413
+ }
1414
+ else {
1415
+ // Something else is playing, so this generation is no longer the one to alert about.
1416
+ return false;
1417
+ }
1418
+ this.#preemptiveAlertHandoffGeneration = null;
1419
+ this.#floor = this.#floor.onSpeakEnd(generation.utterance_id);
1420
+ this.#state.advanceSnapshot();
1421
+ return true;
1422
+ }
1423
+ /**
1424
+ * Release an exactly-identified fenced generation without inventing delivery evidence.
1425
+ *
1426
+ * The renderer reported a clear for a generation the session cannot account for. Retiring it frees
1427
+ * the slot; what it must not do is produce a completion, because nobody knows whether or how much
1428
+ * of it was heard.
1429
+ */
1430
+ retirePlaybackClearUnknown(generation) {
1431
+ if (!this.#playback.retireClearUnknown(generation))
1432
+ return false;
1433
+ if (this.#preemptiveAlertHandoffGeneration !== null
1434
+ && sameGeneration(this.#preemptiveAlertHandoffGeneration, generation)) {
1435
+ this.#preemptiveAlertHandoffGeneration = null;
1436
+ }
1437
+ this.#floor = this.#floor.onSpeakEnd(generation.utterance_id);
1438
+ this.#state.advanceSnapshot();
1439
+ return true;
1440
+ }
1441
+ // ---------------------------------------------------------------------------
1442
+ // Playback acknowledgement
1443
+ // ---------------------------------------------------------------------------
1444
+ playbackStarted(utteranceId, generationEpoch) {
1445
+ const started = this.#playback.markStarted(utteranceId, generationEpoch);
1446
+ // Floor reflects audibility, so the grant lands on actual playback start; a start ack racing
1447
+ // barge-in must never take the user's floor.
1448
+ if (started && this.#floor.state === 'idle') {
1449
+ this.#floor = this.#floor.onSpeakStart(utteranceId, USER_PRIORITY);
1450
+ }
1451
+ return started;
1452
+ }
1453
+ #reportDelivery(completion) {
1454
+ void this.#provider.reportPlayback?.(completion).catch(() => undefined);
1455
+ this.#onDelivery(completion);
1456
+ }
1457
+ playbackDone(utteranceId, generationEpoch, playedMs = null) {
1458
+ return this.completePlayback(utteranceId, generationEpoch, playedMs) !== null;
1459
+ }
1460
+ completePlayback(utteranceId, generationEpoch, playedMs = null) {
1461
+ const completion = this.#playback.ackDone(utteranceId, generationEpoch, playedMs);
1462
+ if (completion === null)
1463
+ return null;
1464
+ if (completion.disposition !== 'spoken') {
1465
+ this.#releaseInterruptedSuggestionAuthority(completion.response_id, completion.session_epoch);
1466
+ this.#finishResponseAuthority(completion.response_id, completion.session_epoch);
1467
+ this.#reportDelivery(completion);
1468
+ this.#floor = this.#floor.onSpeakEnd(utteranceId);
1469
+ this.#state.advanceSnapshot();
1470
+ return completion;
1471
+ }
1472
+ const items = this.#responseItems.get(this.#turnKey(completion.response_id, completion.session_epoch)) ?? [];
1473
+ // This records completed audio delivery, not independently verified semantic coverage.
1474
+ for (const id of this.#recoveryResponses.get(this.#turnKey(completion.response_id, completion.session_epoch)) ?? []) {
1475
+ if (this.#unheard.delete(id))
1476
+ this.#recoveryVersion++;
1477
+ }
1478
+ for (const item of items) {
1479
+ this.#supersedeUnheard(item, true);
1480
+ this.#state.markEventSpoken(item.event_id);
1481
+ // It was heard, so there is nothing left to re-offer.
1482
+ this.#state.releaseRetainedSuggestionInjection(item.event_id);
1483
+ }
1484
+ const answered = this.#responseQuestions.get(this.#turnKey(completion.response_id, completion.session_epoch));
1485
+ if (answered && this.#latestQuestion?.id === answered.id)
1486
+ this.#latestQuestion = null;
1487
+ this.#finishResponseAuthority(completion.response_id, completion.session_epoch);
1488
+ this.#onSpoken(completion.text);
1489
+ this.#reportDelivery(completion);
1490
+ this.#floor = this.#floor.onSpeakEnd(utteranceId);
1491
+ this.#state.advanceSnapshot();
1492
+ return completion;
1493
+ }
1494
+ playbackCleared(utteranceId, generationEpoch, playedMs = null) {
1495
+ return this.completePlaybackClear(utteranceId, generationEpoch, playedMs) !== null;
1496
+ }
1497
+ completePlaybackClear(utteranceId, generationEpoch, playedMs = null) {
1498
+ const completion = this.#playback.recordCleared(utteranceId, generationEpoch, playedMs);
1499
+ if (completion === null)
1500
+ return null;
1501
+ this.#releaseInterruptedSuggestionAuthority(completion.response_id, completion.session_epoch);
1502
+ this.#finishResponseAuthority(completion.response_id, completion.session_epoch);
1503
+ this.#reportDelivery(completion);
1504
+ this.#floor = this.#floor.onSpeakEnd(utteranceId);
1505
+ return completion;
1506
+ }
1507
+ /**
1508
+ * The renderer stopped playing on its own account.
1509
+ *
1510
+ * Distinct from `playbackCleared`, which acknowledges a stop the session asked for. Here the
1511
+ * renderer decided, so the session has to catch up: fence the generation, record the partial
1512
+ * delivery, release the floor, and -- the part that matters -- cancel the provider if it is still
1513
+ * generating for this response. Without that last step audio would keep arriving for something
1514
+ * nobody is playing.
1515
+ */
1516
+ async playbackStopped(utteranceId, generationEpoch, playedMs = null) {
1517
+ const current = this.#playback.current;
1518
+ // Only the generation actually on the renderer can be stopped by it; a stale report names one
1519
+ // that has already been replaced.
1520
+ if (current?.utterance_id !== utteranceId
1521
+ || current.generation_epoch !== generationEpoch) {
1522
+ return false;
1523
+ }
1524
+ const generation = this.#playback.fenceCurrent();
1525
+ if (generation === null)
1526
+ return false;
1527
+ if (generation.session_epoch === this.sessionEpoch) {
1528
+ this.#markLocallyFenced(generation.response_id);
1529
+ this.#markResponseInterrupted(generation.response_id);
1530
+ this.#state.advanceSnapshot();
1531
+ }
1532
+ const completion = this.#playback.recordCleared(utteranceId, generationEpoch, playedMs);
1533
+ if (completion !== null) {
1534
+ this.#finishResponseAuthority(completion.response_id, completion.session_epoch);
1535
+ this.#reportDelivery(completion);
1536
+ }
1537
+ this.#floor = this.#floor.onSpeakEnd(utteranceId);
1538
+ if (generation.session_epoch === this.sessionEpoch
1539
+ && this.#providerResponseId === generation.response_id) {
1540
+ this.#state.openProviderTurn(generation.response_id).phase = 'cancel_requested';
1541
+ await this.#provider.cancelResponse(generation.response_id);
1542
+ }
1543
+ return true;
1544
+ }
1545
+ /** Fence or pre-arm cancellation when the renderer connection disappears. */
1546
+ async rendererDisconnected() {
1547
+ return this.#fenceAndCancelActiveResponse();
1548
+ }
1549
+ /** Release the exact provider VAD hold whose PCM source disappeared with the renderer. */
1550
+ releaseRendererUserHold() {
1551
+ const speechId = this.#floor.userSpeechId;
1552
+ if (speechId === null)
1553
+ return false;
1554
+ return this.#acceptSpeechEnded(speechId, null);
1555
+ }
1556
+ // ---------------------------------------------------------------------------
1557
+ // Delegates
1558
+ // ---------------------------------------------------------------------------
1559
+ /**
1560
+ * Record or update one delegate's session view.
1561
+ *
1562
+ * The session holds this because a reconnect has to tell the new provider what work is still
1563
+ * running; without it the recovery item would claim no active work and the model would lose the
1564
+ * context for anything it is asked about next.
1565
+ */
1566
+ registerDelegate(delegateId, update) {
1567
+ this.#state.registerDelegate(delegateId, update);
1568
+ }
1569
+ delegateRecord(delegateId) {
1570
+ return this.#state.delegateRecord(delegateId);
1571
+ }
1572
+ delegateState(delegateId) {
1573
+ return this.#state.delegateState(delegateId);
1574
+ }
1575
+ // ---------------------------------------------------------------------------
1576
+ // Captions
1577
+ // ---------------------------------------------------------------------------
1578
+ /**
1579
+ * Project a transcript event into the display-only caption channel.
1580
+ *
1581
+ * Captions carry the session's truth policy -- epoch checks, fences, response authorization --
1582
+ * but are never session state: a caption is revisable evidence for the UI, not input to Floor,
1583
+ * Memory, or delivery. `accepted` carries the session's verdict for the events whose
1584
+ * authorization lives in `accept` rather than in per-response tracking.
1585
+ */
1586
+ captionFor(event, options = {}) {
1587
+ if (event.session_epoch !== this.sessionEpoch)
1588
+ return null;
1589
+ const accepted = options.accepted ?? null;
1590
+ switch (event.kind) {
1591
+ case 'user_transcript_delta':
1592
+ if (event.replace)
1593
+ this.#state.resetUserCaptionTarget();
1594
+ this.#state.trackUserCaption(event.item_id);
1595
+ return { ...this.#state.appendCaption({ role: 'user', text: event.text, final: false }), message_id: `user:${this.sessionEpoch}:${event.item_id}` };
1596
+ case 'user_transcript_final': {
1597
+ // A final the reducer refused is not the user's turn, so it must not reach the display.
1598
+ if (accepted === false)
1599
+ return null;
1600
+ this.#state.resetUserCaptionTarget();
1601
+ return { role: 'user', text: truncateCaptionText(event.text), final: true, full_text: event.text, message_id: `user:${this.sessionEpoch}:${event.item_id}` };
1602
+ }
1603
+ case 'response_transcript_delta': {
1604
+ if (!this.#captionAuthorized(event.response_id))
1605
+ return null;
1606
+ this.#state.trackAssistantCaption(event.response_id);
1607
+ return { ...this.#state.appendCaption({ role: 'assistant', text: event.text, final: false }), message_id: `assistant:${this.sessionEpoch}:${event.response_id}`,
1608
+ ...this.#captionSource(event.response_id) };
1609
+ }
1610
+ case 'response_transcript_final': {
1611
+ if (!this.#captionAuthorized(event.response_id))
1612
+ return null;
1613
+ this.#state.resetAssistantCaptionTarget();
1614
+ return { role: 'assistant', text: truncateCaptionText(event.text), final: true, full_text: event.text, message_id: `assistant:${this.sessionEpoch}:${event.response_id}`,
1615
+ ...this.#captionSource(event.response_id) };
1616
+ }
1617
+ default:
1618
+ return null;
1619
+ }
1620
+ }
1621
+ #captionSource(responseId) {
1622
+ const items = this.#responseItems.get(this.#turnKey(responseId)) ?? [];
1623
+ const source = items[0]?.source;
1624
+ // A mixed response cannot truthfully be attributed to one task.
1625
+ return source !== undefined && items.every(item => item.source?.work_id === source.work_id
1626
+ && item.source?.executor === source.executor) ? source : undefined;
1627
+ }
1628
+ /** Only a response the session actually owns may put speculative text on screen. */
1629
+ #captionAuthorized(responseId) {
1630
+ if (this.#state.responseIsSuppressed(responseId))
1631
+ return false;
1632
+ if (this.#state.providerTurn(responseId)?.locally_fenced === true)
1633
+ return false;
1634
+ if (this.#providerResponseId === responseId
1635
+ || this.#state.premapResponseId === responseId) {
1636
+ return true;
1637
+ }
1638
+ if (this.#responseItems.has(this.#turnKey(responseId)))
1639
+ return true;
1640
+ const current = this.#playback.current;
1641
+ return (current !== null
1642
+ && current.session_epoch === this.sessionEpoch
1643
+ && current.response_id === responseId);
1644
+ }
1645
+ /** Drop speculative accumulators; the caller blanks the display. */
1646
+ resetCaptions() {
1647
+ this.#state.clearCaptions();
1648
+ }
1649
+ // ---------------------------------------------------------------------------
1650
+ // Tool continuation
1651
+ // ---------------------------------------------------------------------------
1652
+ /**
1653
+ * Ask the provider to narrate one or more finished tool calls.
1654
+ *
1655
+ * `retryable` rather than a refusal when the provider or renderer is busy: the provider contract permits one
1656
+ * inference at a time, and a continuation's audio would fence pre-tool-call speech that is still
1657
+ * audible, so the caller is told to come back rather than told no.
1658
+ */
1659
+ async requestToolContinuation(intents, options = {}) {
1660
+ if (intents.length === 0)
1661
+ throw new TypeError('tool continuation requires at least one intent');
1662
+ const yielded = this.#yielded;
1663
+ if (yielded) {
1664
+ const ids = intents.map(intent => intent.item.call_id);
1665
+ if (ids.some(id => id === null || !yielded.callIds.includes(id)))
1666
+ return 'rejected';
1667
+ if (yielded.callIds.some(id => !ids.includes(id)))
1668
+ return 'retryable';
1669
+ }
1670
+ if (this.#state.pendingResponseCount > 0
1671
+ || this.#providerResponseId !== null
1672
+ || this.#playback.current !== null
1673
+ || this.#playback.hasUnreportedFence) {
1674
+ return 'retryable';
1675
+ }
1676
+ for (const intent of intents) {
1677
+ const item = intent.item;
1678
+ if (item.kind !== 'tool_output') {
1679
+ throw new TypeError('tool continuation requires tool output');
1680
+ }
1681
+ if (this.#state.hostEventIsDeduplicated(item.event_id))
1682
+ return 'rejected';
1683
+ const injectedEpoch = this.#state.injectedEventEpoch(item.event_id);
1684
+ if (injectedEpoch === undefined) {
1685
+ throw new TypeError('tool output must be confirmed before continuation');
1686
+ }
1687
+ // Work that outlived a reconnect can still be narrated; a plain tool result cannot, because
1688
+ // the conversation it belonged to is gone.
1689
+ if (injectedEpoch !== this.sessionEpoch && intent.kind !== 'delegation_acknowledgement') {
1690
+ return 'rejected';
1691
+ }
1692
+ }
1693
+ const providerIntent = this.#mergeContinuationIntents(intents, options.originSpoken ?? false);
1694
+ try {
1695
+ await this.#createResponse(providerIntent, intents);
1696
+ }
1697
+ catch (error) {
1698
+ if (error instanceof ProviderResponseRejectedError) {
1699
+ if (yielded && this.#yielded === yielded)
1700
+ await this.#provider.cancelResponse(yielded.responseId);
1701
+ return 'rejected';
1702
+ }
1703
+ throw error;
1704
+ }
1705
+ if (this.#yielded === yielded)
1706
+ this.#yielded = null;
1707
+ return 'requested';
1708
+ }
1709
+ #mergeContinuationIntents(intents, originSpoken) {
1710
+ const acknowledgements = intents.filter(intent => intent.kind === 'delegation_acknowledgement');
1711
+ if (acknowledgements.length > 0) {
1712
+ const summary = [...acknowledgements.map(intent => intent.task_summary ?? '')]
1713
+ .join(';')
1714
+ .slice(0, MAX_CONTINUATION_TASK_SUMMARY);
1715
+ return {
1716
+ kind: 'delegation_acknowledgement',
1717
+ item: acknowledgements[0].item,
1718
+ task_summary: summary,
1719
+ // One voiced confirmation cannot stand in for every task in a batch, nor for any
1720
+ // synchronous result sharing it.
1721
+ origin_spoken: originSpoken && intents.length === 1,
1722
+ };
1723
+ }
1724
+ // A batch with no acknowledgement is a plain tool result, and the caller guaranteed there
1725
+ // is one by construction: every intent is tool output and none is an acknowledgement.
1726
+ return intents.find(intent => intent.kind === 'tool_result');
1727
+ }
1728
+ // ---------------------------------------------------------------------------
1729
+ // The user-hold deadline
1730
+ // ---------------------------------------------------------------------------
1731
+ /**
1732
+ * Release a user floor hold whose provider speech-end never arrived.
1733
+ *
1734
+ * Checked at each host-item delivery attempt. The deadline is measured from when the speech
1735
+ * started, not from when this is asked, so repeated asking cannot postpone it.
1736
+ */
1737
+ /**
1738
+ * Sleep on the injected clock until the active user hold turns stale.
1739
+ *
1740
+ * Returns false at once when no hold is active. The small margin past the deadline keeps the
1741
+ * release comparison strict on a real clock, where waking exactly on it would race.
1742
+ */
1743
+ async waitForStaleHold(maxHoldSeconds) {
1744
+ if (this.#floor.state !== 'user_speaking' || this.#userHoldSince === null)
1745
+ return false;
1746
+ const remaining = this.#userHoldSince + maxHoldSeconds - this.#clock.now();
1747
+ // Past the deadline, not on it: `releaseStaleUserHold` compares strictly, so a wake at exactly
1748
+ // the deadline would find the hold not yet stale and the caller would spin.
1749
+ if (remaining > 0)
1750
+ await this.#clock.sleep(remaining + 0.05);
1751
+ return true;
1752
+ }
1753
+ releaseStaleUserHold(maxHoldSeconds) {
1754
+ if (this.#floor.state !== 'user_speaking' || this.#userHoldSince === null)
1755
+ return false;
1756
+ if (this.#clock.now() - this.#userHoldSince <= maxHoldSeconds)
1757
+ return false;
1758
+ this.#floor = new Floor();
1759
+ this.#userHoldSince = null;
1760
+ return true;
1761
+ }
1762
+ // ---------------------------------------------------------------------------
1763
+ // Authority bookkeeping
1764
+ // ---------------------------------------------------------------------------
1765
+ #markLocallyFenced(responseId) {
1766
+ this.#state.openProviderTurn(responseId).locally_fenced = true;
1767
+ }
1768
+ #markResponseInterrupted(responseId, sessionEpoch) {
1769
+ const epoch = sessionEpoch ?? this.sessionEpoch;
1770
+ const items = this.#responseItems.get(this.#turnKey(responseId, epoch)) ?? [];
1771
+ if (epoch === this.sessionEpoch)
1772
+ this.#retainUnheard(responseId, items);
1773
+ for (const item of items)
1774
+ this.#state.markEventInterrupted(item.event_id);
1775
+ this.#releaseSuggestionEventAuthority(items, epoch);
1776
+ }
1777
+ #releaseInterruptedSuggestionAuthority(responseId, sessionEpoch) {
1778
+ const epoch = sessionEpoch ?? this.sessionEpoch;
1779
+ if (epoch === this.sessionEpoch)
1780
+ this.#retainUnheard(responseId, this.#responseItems.get(this.#turnKey(responseId, epoch)) ?? []);
1781
+ this.#releaseSuggestionEventAuthority(this.#responseItems.get(this.#turnKey(responseId, epoch)) ?? [], epoch);
1782
+ }
1783
+ /**
1784
+ * Give a suggestion back its right to be offered again.
1785
+ *
1786
+ * An interrupted suggestion never reached the user, so treating it as answered would lose it
1787
+ * silently. Its injection is retained for the rest of the epoch so it is not injected twice.
1788
+ */
1789
+ #releaseSuggestionEventAuthority(items, sessionEpoch) {
1790
+ const epoch = sessionEpoch ?? this.sessionEpoch;
1791
+ for (const item of items) {
1792
+ if (!item.event_id.startsWith('suggestion:'))
1793
+ continue;
1794
+ this.#state.releaseRespondedEvent(item.event_id);
1795
+ if (this.#state.injectedEventEpoch(item.event_id) === epoch) {
1796
+ this.#state.retainSuggestionInjection(item.event_id);
1797
+ }
1798
+ }
1799
+ }
1800
+ /** A delivered response loses caption authority and its item bookkeeping. */
1801
+ #finishResponseAuthority(responseId, sessionEpoch) {
1802
+ const epoch = sessionEpoch ?? this.sessionEpoch;
1803
+ this.#responseItems.delete(this.#turnKey(responseId, epoch));
1804
+ this.#recoveryResponses.delete(this.#turnKey(responseId, epoch));
1805
+ this.#responseQuestions.delete(this.#turnKey(responseId, epoch));
1806
+ if (epoch === this.sessionEpoch)
1807
+ this.#state.clearAssistantCaptionFor(responseId);
1808
+ }
1809
+ #supersedeUnheard(item, delivered) {
1810
+ const source = item.source;
1811
+ if (source?.event_seq === undefined)
1812
+ return;
1813
+ if (delivered) {
1814
+ const version = Math.max(source.event_seq, this.#deliveredWorkVersions.get(source.work_id) ?? -1);
1815
+ this.#deliveredWorkVersions.delete(source.work_id);
1816
+ this.#deliveredWorkVersions.set(source.work_id, version);
1817
+ // ponytail: retain 64 recently heard work versions; expand only if delayed ACKs span more work.
1818
+ while (this.#deliveredWorkVersions.size > 64)
1819
+ this.#deliveredWorkVersions.delete(this.#deliveredWorkVersions.keys().next().value);
1820
+ }
1821
+ for (const [id, prior] of this.#unheard) {
1822
+ if (prior.item.source?.work_id === source.work_id && prior.item.source.event_seq !== undefined
1823
+ && prior.item.source.event_seq <= source.event_seq) {
1824
+ this.#unheard.delete(id);
1825
+ this.#recoveryVersion++;
1826
+ }
1827
+ }
1828
+ }
1829
+ #retainUnheard(responseId, items) {
1830
+ const facts = items.filter(item => (item.kind === 'progress' || item.kind === 'final' || (item.kind === 'tool_output' && item.recovery_eligible === true))
1831
+ && !/^(approval:|intake:|suggestion:|ack:|background:)/u.test(item.event_id));
1832
+ const question = this.#responseQuestions.get(this.#turnKey(responseId));
1833
+ if (items.length === 0 && question && this.responseHasSpoken(responseId)) {
1834
+ facts.push({ kind: 'recovery', host_item_id: `unheard:${responseId}`,
1835
+ event_id: `unheard-user:${this.sessionEpoch}:${question.id}`, call_id: null,
1836
+ content: `先前的问题尚未完整回答:${question.text}` });
1837
+ }
1838
+ for (const item of facts) {
1839
+ if (this.#unheard.has(item.event_id))
1840
+ continue;
1841
+ const source = item.source;
1842
+ if (source?.event_seq !== undefined && (this.#deliveredWorkVersions.get(source.work_id) ?? -1) >= source.event_seq)
1843
+ continue;
1844
+ if (source?.event_seq !== undefined && [...this.#unheard.values()].some(prior => prior.item.source?.work_id === source.work_id && (prior.item.source.event_seq ?? -1) > source.event_seq))
1845
+ continue;
1846
+ this.#supersedeUnheard(item, false);
1847
+ this.#unheard.set(item.event_id, { item: { ...item, content: [...item.content].slice(0, 900).join('') },
1848
+ revision: this.userInputRevision, at: this.#clock.now(), attempts: 0, requests: 0 });
1849
+ while (this.#unheard.size > 3)
1850
+ this.#unheard.delete(this.#unheard.keys().next().value);
1851
+ this.#recoveryVersion++;
1852
+ }
1853
+ }
1854
+ /**
1855
+ * Give a response a renderer generation, fencing whatever held one before.
1856
+ *
1857
+ * Called at the first audio that has somewhere to go. Doing it here rather than at
1858
+ * `response_started` means a response that never produces audio never takes the renderer.
1859
+ */
1860
+ #openAudioResponse(responseId) {
1861
+ const turn = this.#state.providerTurn(responseId);
1862
+ if (this.#floor.state === 'user_speaking'
1863
+ || turn === undefined
1864
+ || turn.locally_fenced
1865
+ || turn.phase !== 'active') {
1866
+ return false;
1867
+ }
1868
+ let current = this.#playback.current;
1869
+ const handoff = this.#preemptiveAlertHandoffGeneration;
1870
+ if (handoff !== null) {
1871
+ if (current !== null && sameGeneration(current, handoff)) {
1872
+ // The preemptive alert's retained generation becomes this response's, so the user hears no seam.
1873
+ if (!this.#playback.switchGeneration(handoff))
1874
+ return false;
1875
+ this.#floor = this.#floor.onSpeakEnd(handoff.utterance_id);
1876
+ }
1877
+ else if (current !== null) {
1878
+ return false;
1879
+ }
1880
+ this.#preemptiveAlertHandoffGeneration = null;
1881
+ current = null;
1882
+ }
1883
+ if (current !== null
1884
+ && (current.session_epoch !== this.sessionEpoch || current.response_id !== responseId)) {
1885
+ const generation = this.#playback.fenceCurrent();
1886
+ if (generation !== null && generation.session_epoch === this.sessionEpoch) {
1887
+ const previous = this.#state.providerTurn(generation.response_id);
1888
+ if (previous !== undefined)
1889
+ previous.defer_playback_fence = false;
1890
+ this.#markLocallyFenced(generation.response_id);
1891
+ this.#markResponseInterrupted(generation.response_id);
1892
+ this.#state.advanceSnapshot();
1893
+ }
1894
+ }
1895
+ const preemptedResponseId = this.#hostPreemptResponseId;
1896
+ if (preemptedResponseId !== null && preemptedResponseId !== responseId) {
1897
+ const previous = this.#state.providerTurn(preemptedResponseId);
1898
+ if (previous !== undefined)
1899
+ previous.defer_playback_fence = false;
1900
+ this.#hostPreemptResponseId = null;
1901
+ }
1902
+ this.#hostPreemptPending = false;
1903
+ this.#lastOpenedGeneration = this.#playback.openResponse({
1904
+ sessionEpoch: this.sessionEpoch,
1905
+ responseId,
1906
+ });
1907
+ for (const id of this.#recoveryResponses.get(this.#turnKey(responseId)) ?? []) {
1908
+ const fact = this.#unheard.get(id);
1909
+ if (fact)
1910
+ fact.attempts++;
1911
+ }
1912
+ this.#spokenResponseId = responseId;
1913
+ if (this.#providerTranscript !== '') {
1914
+ // A transcript that arrived before the generation existed still belongs to it.
1915
+ this.#playback.setTranscript({
1916
+ sessionEpoch: this.sessionEpoch,
1917
+ responseId,
1918
+ text: this.#providerTranscript,
1919
+ });
1920
+ }
1921
+ return true;
1922
+ }
1923
+ #turnKey(responseId, sessionEpoch) {
1924
+ return `${sessionEpoch ?? this.#state.sessionEpoch}:${responseId}`;
1925
+ }
1926
+ }
1927
+ /**
1928
+ * What the new provider session is told about the old one.
1929
+ *
1930
+ * Counts and active work only: a recovery item is context, not a transcript, and the packed history
1931
+ * is a separate item precisely so this one stays small enough to always fit.
1932
+ */
1933
+ function recoveryContent(snapshot) {
1934
+ const header = [
1935
+ `snapshot_version=${snapshot.version}`,
1936
+ `active_work_count=${snapshot.active_delegates.length}`,
1937
+ ];
1938
+ const footer = [
1939
+ `spoken_progress_count=${snapshot.spoken_event_ids.length}`,
1940
+ `interrupted_progress_count=${snapshot.interrupted_event_ids.length}`,
1941
+ ];
1942
+ const activeWork = [];
1943
+ for (const [index, [, record]] of snapshot.active_delegates.entries()) {
1944
+ let line = `active_work_channel=${record.channel};`
1945
+ + `active_work=${record.summary.slice(0, MAX_CONTINUATION_TASK_SUMMARY)};`
1946
+ + ` state=${record.state}`;
1947
+ if (record.progress_summary !== null && record.progress_summary !== '') {
1948
+ line += `; progress=${record.progress_summary.slice(0, 120)}`;
1949
+ }
1950
+ const remaining = snapshot.active_delegates.length - index - 1;
1951
+ const trial = [...header, ...activeWork, line];
1952
+ // The omission notice has to fit too, or dropping a line could make the content longer.
1953
+ if (remaining > 0)
1954
+ trial.push(`active_work_omitted=${remaining}`);
1955
+ if (codePointLengthLikePython([...trial, ...footer].join('\n')) > MAX_REALTIME_TEXT)
1956
+ break;
1957
+ activeWork.push(line);
1958
+ }
1959
+ const omitted = snapshot.active_delegates.length - activeWork.length;
1960
+ const parts = [...header, ...activeWork];
1961
+ if (omitted > 0)
1962
+ parts.push(`active_work_omitted=${omitted}`);
1963
+ return [...parts, ...footer].join('\n');
1964
+ }
1965
+ /** A no-op default for the optional callbacks, shared rather than allocated twice. */
1966
+ function noop() {
1967
+ // Intentionally empty: a caller that wants nothing to happen gets nothing.
1968
+ }
1969
+ function sameGeneration(left, right) {
1970
+ return (left.session_epoch === right.session_epoch
1971
+ && left.generation_epoch === right.generation_epoch
1972
+ && left.generation_id === right.generation_id
1973
+ && left.utterance_id === right.utterance_id
1974
+ && left.response_id === right.response_id);
1975
+ }
1976
+ //# sourceMappingURL=session.js.map