somora 2026.930.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (404) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +364 -0
  3. package/bin/node-version.d.mts +3 -0
  4. package/bin/node-version.mjs +45 -0
  5. package/bin/somora.mjs +77 -0
  6. package/config.example.yaml +896 -0
  7. package/docs/agents.md +677 -0
  8. package/docs/api.md +3194 -0
  9. package/docs/browser.md +317 -0
  10. package/docs/builder.md +331 -0
  11. package/docs/cache-strategy.md +373 -0
  12. package/docs/compaction.md +253 -0
  13. package/docs/display.md +154 -0
  14. package/docs/dream-phases.md +891 -0
  15. package/docs/files.md +387 -0
  16. package/docs/imagegen.md +366 -0
  17. package/docs/images/somora-hero.png +0 -0
  18. package/docs/images/somora-mobile-2026-05-23.png +0 -0
  19. package/docs/images/somora-tui-2026-05-23.png +0 -0
  20. package/docs/images/somora-web-2026-05-23.png +0 -0
  21. package/docs/index.md +178 -0
  22. package/docs/lsp.md +93 -0
  23. package/docs/mcp.md +332 -0
  24. package/docs/memory.md +407 -0
  25. package/docs/mobile.md +310 -0
  26. package/docs/models.md +379 -0
  27. package/docs/projects.md +425 -0
  28. package/docs/realtime-voice.md +293 -0
  29. package/docs/resources.md +230 -0
  30. package/docs/sampling.md +128 -0
  31. package/docs/security.md +189 -0
  32. package/docs/sentinel.md +295 -0
  33. package/docs/setup.md +1217 -0
  34. package/docs/skills.md +501 -0
  35. package/docs/team.md +189 -0
  36. package/docs/thinking.md +463 -0
  37. package/docs/tmux.md +399 -0
  38. package/docs/tools.md +117 -0
  39. package/docs/videogen.md +191 -0
  40. package/docs/voice.md +288 -0
  41. package/docs/web.md +893 -0
  42. package/docs/wiki.md +583 -0
  43. package/npm-shrinkwrap.json +5670 -0
  44. package/package.json +116 -0
  45. package/src/attachments/store.ts +196 -0
  46. package/src/browser/change-stream.ts +31 -0
  47. package/src/browser/display.ts +108 -0
  48. package/src/browser/policy.ts +121 -0
  49. package/src/browser/screencast.ts +374 -0
  50. package/src/browser/service.ts +1337 -0
  51. package/src/browser/session.ts +15 -0
  52. package/src/browser/snapshot.ts +40 -0
  53. package/src/cli/auth.ts +117 -0
  54. package/src/cli/codex.ts +41 -0
  55. package/src/cli/lsp.ts +71 -0
  56. package/src/cli/resolvers/clawhub.ts +400 -0
  57. package/src/cli/setup.ts +835 -0
  58. package/src/cli/skill.ts +619 -0
  59. package/src/cli/somora.ts +548 -0
  60. package/src/cli/systemd-unit.ts +72 -0
  61. package/src/cli/team.ts +148 -0
  62. package/src/cli/tui/activity-stream.ts +121 -0
  63. package/src/cli/tui/api.ts +479 -0
  64. package/src/cli/tui/app.tsx +1169 -0
  65. package/src/cli/tui/autocomplete.tsx +55 -0
  66. package/src/cli/tui/commands.ts +913 -0
  67. package/src/cli/tui/dream-glyphs.ts +22 -0
  68. package/src/cli/tui/footer.tsx +15 -0
  69. package/src/cli/tui/format.ts +28 -0
  70. package/src/cli/tui/header.tsx +279 -0
  71. package/src/cli/tui/index.tsx +120 -0
  72. package/src/cli/tui/markdown.tsx +63 -0
  73. package/src/cli/tui/sampling.ts +162 -0
  74. package/src/cli/tui/separator.tsx +13 -0
  75. package/src/cli/tui/state.ts +42 -0
  76. package/src/cli/tui/stream.ts +330 -0
  77. package/src/cli/tui/thinking-text.ts +54 -0
  78. package/src/cli/tui/turn-views.tsx +499 -0
  79. package/src/cli/tui/types.ts +410 -0
  80. package/src/cli/tui/work-queue.ts +161 -0
  81. package/src/cli/update-args.ts +55 -0
  82. package/src/cli/wiki.ts +406 -0
  83. package/src/compaction/index.ts +28 -0
  84. package/src/compaction/midturn.ts +210 -0
  85. package/src/compaction/policy.ts +154 -0
  86. package/src/compaction/summarize.ts +691 -0
  87. package/src/compaction/template.ts +90 -0
  88. package/src/compaction/types.ts +148 -0
  89. package/src/config/loader.ts +276 -0
  90. package/src/config/reload.ts +43 -0
  91. package/src/config/types.ts +2292 -0
  92. package/src/dream/deep-actions.ts +324 -0
  93. package/src/dream/deep-dispatcher.ts +237 -0
  94. package/src/dream/deep-llm.ts +388 -0
  95. package/src/dream/deep-prompts.ts +106 -0
  96. package/src/dream/deep-runner.ts +757 -0
  97. package/src/dream/deep-skip-cache.ts +199 -0
  98. package/src/dream/deep-worker.ts +229 -0
  99. package/src/dream/json-salvage.ts +34 -0
  100. package/src/dream/judge.ts +188 -0
  101. package/src/dream/loop-state.ts +286 -0
  102. package/src/dream/lucid-actions.ts +303 -0
  103. package/src/dream/lucid-batches.ts +94 -0
  104. package/src/dream/lucid-prompt.ts +82 -0
  105. package/src/dream/lucid-runner.ts +744 -0
  106. package/src/dream/lucid-storage.ts +277 -0
  107. package/src/dream/lucid-structure.ts +102 -0
  108. package/src/dream/lucid-types.ts +137 -0
  109. package/src/dream/lucid-worker.ts +224 -0
  110. package/src/dream/rem-dedup.ts +502 -0
  111. package/src/dream/rem-extract.ts +782 -0
  112. package/src/dream/rem-reset-run.ts +67 -0
  113. package/src/dream/rem-runner.ts +696 -0
  114. package/src/dream/rem-worker.ts +527 -0
  115. package/src/dream/review-window.ts +71 -0
  116. package/src/dream/scheduler-state.ts +129 -0
  117. package/src/dream/storage.ts +497 -0
  118. package/src/dream/types.ts +133 -0
  119. package/src/dream/wiki-context.ts +133 -0
  120. package/src/engine/a2a.ts +33 -0
  121. package/src/engine/availability.ts +63 -0
  122. package/src/engine/claude-cli.ts +969 -0
  123. package/src/engine/codex-app-server-client.ts +294 -0
  124. package/src/engine/codex-bin.ts +49 -0
  125. package/src/engine/codex-cli.ts +1014 -0
  126. package/src/engine/codex-dynamic-tools.ts +239 -0
  127. package/src/engine/codex-home.ts +63 -0
  128. package/src/engine/codex-thread-config.ts +74 -0
  129. package/src/engine/context-budget.ts +257 -0
  130. package/src/engine/engine-meta-labels.ts +211 -0
  131. package/src/engine/grok-cli.ts +941 -0
  132. package/src/engine/inline-think.ts +59 -0
  133. package/src/engine/model-availability.ts +105 -0
  134. package/src/engine/openai-compatible.ts +2464 -0
  135. package/src/engine/reasoning-retry.ts +83 -0
  136. package/src/engine/registry.ts +13 -0
  137. package/src/engine/replay.ts +195 -0
  138. package/src/engine/sampling.ts +90 -0
  139. package/src/engine/thinking-params.ts +264 -0
  140. package/src/engine/types.ts +269 -0
  141. package/src/engine/user-tag.ts +24 -0
  142. package/src/imagegen/aspect.ts +128 -0
  143. package/src/imagegen/generate.ts +642 -0
  144. package/src/imagegen/references.ts +75 -0
  145. package/src/imagegen/types.ts +154 -0
  146. package/src/lsp/client.ts +183 -0
  147. package/src/lsp/fake-server.helper.mjs +42 -0
  148. package/src/lsp/format.ts +29 -0
  149. package/src/lsp/index.ts +21 -0
  150. package/src/lsp/manager.ts +238 -0
  151. package/src/lsp/registry.ts +151 -0
  152. package/src/mcp/config.ts +117 -0
  153. package/src/mcp/hub/audit.ts +55 -0
  154. package/src/mcp/hub/bridge.ts +115 -0
  155. package/src/mcp/hub/catalog.ts +69 -0
  156. package/src/mcp/hub/credentials.ts +406 -0
  157. package/src/mcp/hub/env-expand.ts +14 -0
  158. package/src/mcp/hub/manager.ts +770 -0
  159. package/src/mcp/hub/normalize.ts +213 -0
  160. package/src/mcp/server.ts +368 -0
  161. package/src/mcp/tool-schema.ts +20 -0
  162. package/src/media/capabilities.ts +392 -0
  163. package/src/media/records.ts +175 -0
  164. package/src/media/store.ts +217 -0
  165. package/src/media/types.ts +69 -0
  166. package/src/memory/chunking.ts +168 -0
  167. package/src/memory/embeddings.ts +262 -0
  168. package/src/memory/index.ts +15 -0
  169. package/src/memory/inject.ts +197 -0
  170. package/src/memory/manager.ts +996 -0
  171. package/src/memory/registry.ts +176 -0
  172. package/src/memory/rescan.ts +101 -0
  173. package/src/memory/retrieval.ts +586 -0
  174. package/src/memory/shared-index.ts +372 -0
  175. package/src/memory/slug.ts +39 -0
  176. package/src/memory/storage.ts +385 -0
  177. package/src/memory/watcher.ts +134 -0
  178. package/src/multimodal/blocks.ts +101 -0
  179. package/src/multimodal/dimensions.ts +214 -0
  180. package/src/multimodal/load.ts +86 -0
  181. package/src/multimodal/mime.ts +135 -0
  182. package/src/multimodal/pdf-render.ts +80 -0
  183. package/src/multimodal/user-content.ts +266 -0
  184. package/src/persona/files.ts +144 -0
  185. package/src/persona/loader.ts +598 -0
  186. package/src/persona/skill-gating-store.ts +59 -0
  187. package/src/persona/tool-gating-store.ts +113 -0
  188. package/src/projects/focus.ts +186 -0
  189. package/src/projects/prompt-block.ts +106 -0
  190. package/src/projects/scheme.ts +107 -0
  191. package/src/projects/store.ts +144 -0
  192. package/src/projects/types.ts +73 -0
  193. package/src/sentinel/dispatcher.ts +97 -0
  194. package/src/sentinel/schedule.ts +271 -0
  195. package/src/sentinel/scheduler.ts +840 -0
  196. package/src/sentinel/store.ts +259 -0
  197. package/src/sentinel/types.ts +221 -0
  198. package/src/server/activity-stream.ts +160 -0
  199. package/src/server/ask-calls.ts +137 -0
  200. package/src/server/ask-wait-graph.ts +171 -0
  201. package/src/server/async-tasks.ts +199 -0
  202. package/src/server/builder-busy.ts +86 -0
  203. package/src/server/builder-prompt.ts +204 -0
  204. package/src/server/builder-questions.ts +117 -0
  205. package/src/server/builder-session.ts +249 -0
  206. package/src/server/chat-aborts.ts +83 -0
  207. package/src/server/claude-config-dir.ts +71 -0
  208. package/src/server/claude-credential-sync.ts +454 -0
  209. package/src/server/env-file.ts +100 -0
  210. package/src/server/env.ts +115 -0
  211. package/src/server/heal-session.ts +151 -0
  212. package/src/server/history-page.ts +46 -0
  213. package/src/server/index.ts +7244 -0
  214. package/src/server/lockfile.ts +89 -0
  215. package/src/server/logger.ts +67 -0
  216. package/src/server/logs.ts +187 -0
  217. package/src/server/loopback-fetch.ts +130 -0
  218. package/src/server/openai-client.ts +89 -0
  219. package/src/server/prompt-assembly.ts +334 -0
  220. package/src/server/restart-reconcile.ts +139 -0
  221. package/src/server/run-turn-fallback.ts +275 -0
  222. package/src/server/run-turn-types.ts +91 -0
  223. package/src/server/run-turn.ts +1474 -0
  224. package/src/server/sanitize-assistant-text.ts +112 -0
  225. package/src/server/session-export.ts +220 -0
  226. package/src/server/session-queue.ts +376 -0
  227. package/src/server/session-workdir.ts +49 -0
  228. package/src/server/sse-h2-safe.ts +61 -0
  229. package/src/server/sse-liveness.ts +162 -0
  230. package/src/server/sse-serializer.ts +161 -0
  231. package/src/server/start-turn.ts +249 -0
  232. package/src/server/steer-inbox.ts +107 -0
  233. package/src/server/tls-keeper.ts +153 -0
  234. package/src/server/tool-format.ts +167 -0
  235. package/src/server/turn-framing.ts +52 -0
  236. package/src/server/turn-origin-kind.ts +74 -0
  237. package/src/server/turn-origin.ts +40 -0
  238. package/src/server/work-ledger.ts +975 -0
  239. package/src/server/workspace.ts +114 -0
  240. package/src/setup/config-edit.ts +201 -0
  241. package/src/setup/presets.ts +71 -0
  242. package/src/setup/prompt.ts +163 -0
  243. package/src/setup/tailscale.ts +44 -0
  244. package/src/skills/bin-checks.ts +227 -0
  245. package/src/skills/bootstrap.ts +347 -0
  246. package/src/skills/env-scope.ts +175 -0
  247. package/src/skills/gating.ts +71 -0
  248. package/src/skills/lint.ts +202 -0
  249. package/src/skills/load.ts +368 -0
  250. package/src/skills/path-helpers.ts +102 -0
  251. package/src/skills/registry.ts +178 -0
  252. package/src/ssh/exec.ts +142 -0
  253. package/src/ssh/index.ts +12 -0
  254. package/src/ssh/known-hosts.ts +109 -0
  255. package/src/ssh/pool.ts +307 -0
  256. package/src/storage/sessions.ts +602 -0
  257. package/src/team/render.ts +149 -0
  258. package/src/team/resolve.ts +122 -0
  259. package/src/team/store.ts +124 -0
  260. package/src/team/types.ts +111 -0
  261. package/src/team/write.ts +95 -0
  262. package/src/testing/isolated-home.mts +46 -0
  263. package/src/tmux/attention-watcher.ts +272 -0
  264. package/src/tmux/attention.ts +336 -0
  265. package/src/tmux/list.ts +91 -0
  266. package/src/tmux/origin-store.ts +102 -0
  267. package/src/tmux/tui-markers.ts +267 -0
  268. package/src/tools/agents/ask-cancel.ts +94 -0
  269. package/src/tools/agents/ask-result.ts +235 -0
  270. package/src/tools/agents/ask.ts +704 -0
  271. package/src/tools/agents/builder-dispatch.ts +217 -0
  272. package/src/tools/agents/images.ts +104 -0
  273. package/src/tools/agents/index.ts +42 -0
  274. package/src/tools/agents/long-task-timeouts.ts +39 -0
  275. package/src/tools/agents/session-list.ts +136 -0
  276. package/src/tools/agents/session-model.ts +106 -0
  277. package/src/tools/agents/spawn.ts +845 -0
  278. package/src/tools/agents/status.ts +589 -0
  279. package/src/tools/browser/index.ts +6 -0
  280. package/src/tools/browser/ops.ts +145 -0
  281. package/src/tools/browser/tools.ts +184 -0
  282. package/src/tools/builder/short-descriptions.ts +80 -0
  283. package/src/tools/builder/tools.ts +222 -0
  284. package/src/tools/docs/index.ts +1 -0
  285. package/src/tools/docs/tools.ts +228 -0
  286. package/src/tools/dream/index.ts +11 -0
  287. package/src/tools/dream/tools.ts +1002 -0
  288. package/src/tools/exec/allowlist.ts +233 -0
  289. package/src/tools/exec/background-detach.helper.mts +27 -0
  290. package/src/tools/exec/blacklist.ts +336 -0
  291. package/src/tools/exec/concurrency.ts +150 -0
  292. package/src/tools/exec/fit-output.ts +82 -0
  293. package/src/tools/exec/index.ts +7 -0
  294. package/src/tools/exec/internal-env.ts +89 -0
  295. package/src/tools/exec/job-store.ts +403 -0
  296. package/src/tools/exec/local.ts +649 -0
  297. package/src/tools/exec/remote.ts +399 -0
  298. package/src/tools/exec/tools.ts +934 -0
  299. package/src/tools/file/analyze.ts +378 -0
  300. package/src/tools/file/index.ts +2 -0
  301. package/src/tools/file/local.ts +707 -0
  302. package/src/tools/file/lsp-hook.ts +72 -0
  303. package/src/tools/file/persona-guard.ts +61 -0
  304. package/src/tools/file/policy.ts +292 -0
  305. package/src/tools/file/read-format.ts +129 -0
  306. package/src/tools/file/remote.ts +680 -0
  307. package/src/tools/file/replace.ts +507 -0
  308. package/src/tools/file/search-window.ts +224 -0
  309. package/src/tools/file/tools.ts +658 -0
  310. package/src/tools/file/write-scope.ts +182 -0
  311. package/src/tools/gating.ts +106 -0
  312. package/src/tools/image/budget.ts +82 -0
  313. package/src/tools/image/index.ts +7 -0
  314. package/src/tools/image/tools.ts +601 -0
  315. package/src/tools/index.ts +99 -0
  316. package/src/tools/memory/index.ts +12 -0
  317. package/src/tools/memory/tools.ts +399 -0
  318. package/src/tools/projects/index.ts +1 -0
  319. package/src/tools/projects/tools.ts +643 -0
  320. package/src/tools/registry.ts +427 -0
  321. package/src/tools/resources/index.ts +8 -0
  322. package/src/tools/resources/tools.ts +176 -0
  323. package/src/tools/resources/visibility.ts +60 -0
  324. package/src/tools/sentinel/index.ts +1 -0
  325. package/src/tools/sentinel/tools.ts +592 -0
  326. package/src/tools/skill/index.ts +4 -0
  327. package/src/tools/skill/tools.ts +285 -0
  328. package/src/tools/time/index.ts +5 -0
  329. package/src/tools/time/tools.ts +123 -0
  330. package/src/tools/tmux/index.ts +1 -0
  331. package/src/tools/tmux/local.ts +277 -0
  332. package/src/tools/tmux/remote.ts +168 -0
  333. package/src/tools/tmux/tools.ts +1064 -0
  334. package/src/tools/tool-output.ts +97 -0
  335. package/src/tools/types.ts +227 -0
  336. package/src/tools/video/index.ts +1 -0
  337. package/src/tools/video/tools.ts +425 -0
  338. package/src/tools/web/fetch.ts +337 -0
  339. package/src/tools/web/index.ts +4 -0
  340. package/src/tools/web/tools.ts +186 -0
  341. package/src/tools/wiki/index.ts +1 -0
  342. package/src/tools/wiki/tools.ts +445 -0
  343. package/src/tts/cache-gc.ts +128 -0
  344. package/src/tts/prepare-for-tts.ts +114 -0
  345. package/src/tts/service.ts +332 -0
  346. package/src/types/events.ts +695 -0
  347. package/src/types/turn-origin.ts +53 -0
  348. package/src/version.ts +21 -0
  349. package/src/videogen/dialects.ts +222 -0
  350. package/src/videogen/generate.ts +484 -0
  351. package/src/videogen/jobs.ts +178 -0
  352. package/src/videogen/runner.ts +125 -0
  353. package/src/videogen/wake.ts +119 -0
  354. package/src/voice/realtime/call.ts +948 -0
  355. package/src/voice/realtime/consult.ts +293 -0
  356. package/src/voice/realtime/fake-provider.ts +134 -0
  357. package/src/voice/realtime/manager.ts +384 -0
  358. package/src/voice/realtime/openai-provider.ts +471 -0
  359. package/src/voice/realtime/persona.ts +227 -0
  360. package/src/voice/realtime/session-match.ts +116 -0
  361. package/src/voice/realtime/types.ts +182 -0
  362. package/src/wiki/conflict.ts +113 -0
  363. package/src/wiki/explorer.ts +578 -0
  364. package/src/wiki/index-builder.ts +172 -0
  365. package/src/wiki/language.ts +134 -0
  366. package/src/wiki/log-builder.ts +150 -0
  367. package/src/wiki/map.ts +258 -0
  368. package/src/wiki/migration/analyze.ts +304 -0
  369. package/src/wiki/migration/execute.ts +689 -0
  370. package/src/wiki/migration/refine.ts +402 -0
  371. package/src/wiki/migration/store.ts +100 -0
  372. package/src/wiki/move-page.ts +57 -0
  373. package/src/wiki/structure-file.ts +192 -0
  374. package/src/wiki/taxonomy.ts +140 -0
  375. package/src/wiki/templates.ts +163 -0
  376. package/src/wiki/types.ts +133 -0
  377. package/templates/skills/README.md +24 -0
  378. package/templates/skills/_templates/api-wrapper/SKILL.md +26 -0
  379. package/templates/skills/_templates/cli-wrapper/BOOTSTRAP.md +32 -0
  380. package/templates/skills/_templates/cli-wrapper/SKILL.md +24 -0
  381. package/templates/skills/_templates/default/SKILL.md +25 -0
  382. package/templates/skills/builder-handover/SKILL.md +96 -0
  383. package/templates/skills/builder-handover/assets/ORDER.md +12 -0
  384. package/templates/skills/skill-author/SKILL.md +110 -0
  385. package/tsconfig.json +22 -0
  386. package/web/dist/assets/index-BaVv6pB2.js +631 -0
  387. package/web/dist/assets/index-BaVv6pB2.js.map +1 -0
  388. package/web/dist/assets/index-V3FV3Z25.css +32 -0
  389. package/web/dist/favicon.svg +8 -0
  390. package/web/dist/index.html +20 -0
  391. package/web/package.json +36 -0
  392. package/web/tsconfig.json +25 -0
  393. package/web-mobile/dist/apple-touch-icon.png +0 -0
  394. package/web-mobile/dist/assets/index-BqKt7IMx.css +1 -0
  395. package/web-mobile/dist/assets/index-X_vRr6cd.js +88 -0
  396. package/web-mobile/dist/assets/index-X_vRr6cd.js.map +1 -0
  397. package/web-mobile/dist/favicon.svg +8 -0
  398. package/web-mobile/dist/icon-192.png +0 -0
  399. package/web-mobile/dist/icon-512.png +0 -0
  400. package/web-mobile/dist/index.html +27 -0
  401. package/web-mobile/dist/manifest.webmanifest +32 -0
  402. package/web-mobile/dist/service-worker.js +90 -0
  403. package/web-mobile/package.json +28 -0
  404. package/web-mobile/tsconfig.json +25 -0
@@ -0,0 +1,948 @@
1
+ // One voice call: a standing conversation bound to one agent and one
2
+ // session, in which a second model does the talking and the real agent
3
+ // does the knowing.
4
+ //
5
+ // The state machine lives here, deliberately free of any provider and
6
+ // of the HTTP server, so it can be driven by a fake provider in a test
7
+ // and by a real one in production without a second implementation.
8
+ //
9
+ // Design: private/realtime-voice-design.md
10
+
11
+ import { randomUUID } from 'node:crypto';
12
+ import type { Persona } from '../../persona/loader.ts';
13
+ import type { NormalizedEvent } from '../../types/events.ts';
14
+ import {
15
+ CONSULT_TOOL_NAME,
16
+ RESULT_TOOL_NAME,
17
+ parseResultArgs,
18
+ resultToolSpec,
19
+ STATUS_TOOL_NAME,
20
+ SWITCH_TOOL_NAME,
21
+ consultToolSpec,
22
+ parseConsultArgs,
23
+ parseSwitchArgs,
24
+ renderConsultTurn,
25
+ statusToolSpec,
26
+ switchToolSpec,
27
+ } from './consult.ts';
28
+ import { languageName, buildVoiceInstructions } from './persona.ts';
29
+ import { normalizeSpokenName } from './session-match.ts';
30
+ import type { RealtimeEvent, RealtimeProvider, RealtimeSession } from './types.ts';
31
+
32
+ /** How much of the conversation the call keeps in memory. */
33
+ /** An announcement waits for this much quiet from the caller … */
34
+ const ANNOUNCE_PAUSE_MS = 1_500;
35
+ /** … but not forever. */
36
+ const ANNOUNCE_MAX_WAIT_MS = 60_000;
37
+ const TRANSCRIPT_MEMORY = 24;
38
+ /** How much of it travels with a question to the agent. Six lines is
39
+ * about two exchanges: enough for "and how long does that take", short
40
+ * enough that it does not dominate the session it is written into. */
41
+ const CONSULT_TRANSCRIPT_LINES = 6;
42
+
43
+ export type VoiceCallState =
44
+ | 'connecting'
45
+ | 'listening'
46
+ | 'consulting'
47
+ | 'speaking'
48
+ | 'closed';
49
+
50
+ export interface VoiceCallTarget {
51
+ agent: string;
52
+ /** Resolved session id, never a slug — resolution happens before the
53
+ * call starts so a typo cannot become a new conversation. */
54
+ session: string;
55
+ /** For display and for the instructions. */
56
+ slug: string;
57
+ }
58
+
59
+ export interface ConsultResult {
60
+ text: string;
61
+ outcome?: string;
62
+ /** For correlating a spoken answer with the turn it came from. */
63
+ turnId?: string;
64
+ /**
65
+ * The turn did not finish inside the call's patience, or the session
66
+ * was busy with older work. The answer is a status, not a result —
67
+ * the work keeps running and lands in the session either way.
68
+ */
69
+ pending?: boolean;
70
+ /** Phase 2 (2026-09-13): `answered` came back inside the patience;
71
+ * `handed_over` means the work goes on under `consultId` and the
72
+ * answer is delivered to the call when it lands. */
73
+ state?: 'answered' | 'handed_over';
74
+ consultId?: string;
75
+ /** Place in the session's queue at hand-over (0 = already running). */
76
+ position?: number;
77
+ }
78
+
79
+ /** What a handed-over consult looks like when the voice asks for it. */
80
+ export interface ConsultLookup {
81
+ state: 'pending' | 'done' | 'failed';
82
+ text?: string;
83
+ error?: string;
84
+ position?: number;
85
+ }
86
+
87
+ /** A finished consult, brought to the call by the work ledger. */
88
+ export interface ConsultDelivery {
89
+ consultId: string;
90
+ state: 'done' | 'failed';
91
+ text?: string;
92
+ error?: string;
93
+ /** Work the consult started finished after its answer (work-ledger
94
+ * maybeFollowUp): read out as a follow-up, even though the consult
95
+ * itself was already delivered. */
96
+ followUp?: boolean;
97
+ }
98
+
99
+ export interface SessionWorkStatus {
100
+ busy: boolean;
101
+ /** How long the current work has been running. */
102
+ sinceMs?: number;
103
+ /** Anything waiting behind it. */
104
+ queued?: number;
105
+ }
106
+
107
+ export interface VoiceCallDeps {
108
+ provider: RealtimeProvider;
109
+ /** Runs ONE turn in the bound session, as `from_system: 'voice'`.
110
+ * `prefix` is scaffolding the model sees and the record does not. */
111
+ runConsult(args: { agent: string; session: string; text: string; prefix?: string; callId?: string }): Promise<ConsultResult>;
112
+ /**
113
+ * Persists into the bound session's history AND puts it on the live
114
+ * stream.
115
+ *
116
+ * Both, or the chat window tells two different stories: during a call
117
+ * it showed only what the consult turn published, and a reload then
118
+ * added what had been on disk all along (Rene, 2026-09-12: "es war
119
+ * vorher anders gerendert … erst nach einem browser reload so").
120
+ * Whatever is written is published.
121
+ *
122
+ * Used for the handover note only. Everything the call says and hears
123
+ * stays in the call; what a session records is the question that
124
+ * reached the agent and the answer it gave.
125
+ */
126
+ appendEvent(agent: string, session: string, ev: NormalizedEvent): Promise<void>;
127
+ /** Is the bound session busy, and for how long? Must not wait. */
128
+ sessionStatus?(agent: string, session: string): Promise<SessionWorkStatus>;
129
+ /** A handed-over consult by id — reading it counts as fetched. */
130
+ consultResult?(consultId: string): Promise<ConsultLookup | null>;
131
+ /** The call read (or announced) a consult; no second delivery. */
132
+ markConsultFetched?(consultId: string): Promise<void>;
133
+ /** Agents this call may be handed over to. Empty = switching off. */
134
+ callableAgents?: readonly string[];
135
+ /** Everything a call needs to continue as another agent. Rejects with
136
+ * a message the voice can say when the target does not exist. */
137
+ resolveTarget?(agent: string, sessionRef: string | undefined): Promise<{
138
+ persona: Persona;
139
+ target: VoiceCallTarget;
140
+ cfg: VoiceCallConfig;
141
+ }>;
142
+ /**
143
+ * Every provider event, as the call processes it.
144
+ *
145
+ * There is exactly ONE consumer of the provider's event stream — this
146
+ * class. An async generator hands each event to whoever asks first,
147
+ * so a second reader (the route forwarding frames to the browser)
148
+ * does not mirror the stream, it STEALS half of it. Measured through
149
+ * the deployed server on 2026-09-11: the call machine got the tool
150
+ * call and ran the turn while the browser saw neither transcript nor
151
+ * audio. Anything that needs to watch a call subscribes here.
152
+ */
153
+ onEvent?(ev: RealtimeEvent, snapshot: VoiceCallSnapshot): void;
154
+ /**
155
+ * The call's own state, whenever it changes.
156
+ *
157
+ * Separate from `onEvent` because the interesting states are the ones
158
+ * NO provider event announces: "asking the agent" begins when somora
159
+ * decides to run a turn and ends when the turn returns. A watcher
160
+ * that only mirrors provider events sees connecting → listening →
161
+ * speaking and never learns why the pause in the middle happened
162
+ * (measured through the deployed server, 2026-09-11).
163
+ */
164
+ onState?(snapshot: VoiceCallSnapshot): void;
165
+ log?(entry: Record<string, unknown>): void;
166
+ now?(): number;
167
+ }
168
+
169
+ export interface VoiceCallConfig {
170
+ model: string;
171
+ voice: string;
172
+ language: string;
173
+ consultPolicy: 'auto' | 'substantive' | 'always';
174
+ maxCallMinutes: number;
175
+ /** Interruption sensitivity, from config. */
176
+ turnDetection?: { threshold: number; prefixPaddingMs: number; silenceDurationMs: number };
177
+ /** Hand-written character from VOICE.md, when there is one. */
178
+ personaOverride?: string;
179
+ }
180
+
181
+ export interface VoiceCallSnapshot {
182
+ id: string;
183
+ target: VoiceCallTarget;
184
+ state: VoiceCallState;
185
+ startedAt: number;
186
+ /** Consults asked and answered — the number that says whether the
187
+ * voice self is actually delegating. */
188
+ consults: number;
189
+ /** Sentences the caller has said in this call. Counted, not kept:
190
+ * the session records the questions that reached the agent. */
191
+ spokenTurns: number;
192
+ /** Set while a handover is in flight: who the call is moving to.
193
+ * `target` still names the agent that is talking until the new one
194
+ * is actually on the line. */
195
+ handoverTo?: string;
196
+ lastError?: string;
197
+ }
198
+
199
+ export class VoiceCall {
200
+ readonly id = randomUUID();
201
+ private state: VoiceCallState = 'connecting';
202
+ private session: RealtimeSession | undefined;
203
+ /** Set by the switch tool; the run loop picks it up when the old
204
+ * provider session ends. */
205
+ private pendingSwitch: { agent: string; session?: string } | undefined;
206
+ /**
207
+ * The conversation itself — kept here and nowhere else.
208
+ *
209
+ * Spoken sentences used to be appended into the agent's session as
210
+ * user messages, and what the voice said back as a meta row. That
211
+ * made three different readers stumble: the CLI engines drop a user
212
+ * turn that never got an answer, REM and recall saw every question
213
+ * twice (once as said, once as asked), and a sentence written outside
214
+ * the session lock could land inside a running turn and break its
215
+ * pair. Rene, 2026-09-12: "es ist viel viel wartbarer code".
216
+ *
217
+ * What a session records now is exactly what A2A records: the
218
+ * question this call put to the agent, and the agent's answer. The
219
+ * talking around it lives for the length of the call, the way
220
+ * OpenClaw keeps it on its call object.
221
+ */
222
+ private transcript: Array<{ role: 'caller' | 'voice'; text: string }> = [];
223
+ /** Consults that came back handed over: what was asked, when, and
224
+ * for whom — a result for a previous agent is not read out as this
225
+ * one's after a switch. */
226
+ private openConsults = new Map<string, { question: string; startedAt: number; agent: string; fetched: boolean }>();
227
+ /** A result that landed before the hand-over was recorded (the turn
228
+ * finished in the same tick the patience ran out). */
229
+ private earlyDeliveries = new Map<string, ConsultDelivery>();
230
+ /** When the caller last said something — an announcement waits for a
231
+ * pause. */
232
+ private lastHeardAt = 0;
233
+ /**
234
+ * Who the window is showing. Lags `target` across a handover.
235
+ *
236
+ * The old agent's last sentence is still in the browser's playback
237
+ * queue when the new provider session opens. Announcing the new name
238
+ * at that moment makes lisa finish her sentence under hans's name and
239
+ * colour (Rene, 2026-09-12: "es spricht aber noch Lisa"). The call
240
+ * says who is on the line only once that is true; the browser adds
241
+ * its own queue to the same question.
242
+ */
243
+ private announced: VoiceCallTarget;
244
+ /**
245
+ * Targets that could not be reached, and what to say about them.
246
+ *
247
+ * Every switch attempt ends the provider session so the next voice can
248
+ * start, so a target that does not resolve costs a restart. Asking for
249
+ * the same impossible thing twice must not cost a second one — the
250
+ * answer is already known and goes straight back to the model.
251
+ */
252
+ private unreachable = new Map<string, string>();
253
+ private consults = 0;
254
+ private spokenTurns = 0;
255
+ private lastError: string | undefined;
256
+ private readonly startedAt: number;
257
+ private deadlineTimer: NodeJS.Timeout | undefined;
258
+
259
+ constructor(
260
+ private target: VoiceCallTarget,
261
+ private persona: Persona,
262
+ private cfg: VoiceCallConfig,
263
+ private readonly deps: VoiceCallDeps,
264
+ ) {
265
+ this.startedAt = this.now();
266
+ this.announced = { ...target };
267
+ }
268
+
269
+ private now(): number {
270
+ return this.deps.now ? this.deps.now() : Date.now();
271
+ }
272
+
273
+ private setState(next: VoiceCallState): void {
274
+ if (this.state === next) return;
275
+ this.state = next;
276
+ this.deps.onState?.(this.snapshot());
277
+ }
278
+
279
+ /**
280
+ * Where this call may be moved: any agent the operator allowed —
281
+ * INCLUDING the one already on the line.
282
+ *
283
+ * Filtering itself out made a whole dimension unreachable: an agent
284
+ * has many sessions, and "put me into your cerebrocraft session" was
285
+ * impossible while the tool only offered other agents (Rene,
286
+ * 2026-09-12). Same agent plus a different session is a move like any
287
+ * other; the voice stays the same, the conversation does not.
288
+ */
289
+ private switchable(): string[] {
290
+ return [...(this.deps.callableAgents ?? [])];
291
+ }
292
+
293
+ /**
294
+ * Is this name just the session the call is already in?
295
+ *
296
+ * The voice self knows which session it sits in, and on a handover it
297
+ * passes that name along unless something stops it — which is how
298
+ * asking for naxon landed in naxon's "cerebrocraft", because lisa had
299
+ * been in hers (Rene, 2026-09-12: "es muss nicht immer zwingend der
300
+ * fall sein das der andere agent überhaupt eine session hat die so
301
+ * benannt ist"). Nobody said that name, so it is not a wish.
302
+ *
303
+ * Anything ELSE the model passes did not come from itself, so it came
304
+ * from the caller and is taken at face value. An earlier version
305
+ * checked the name against the transcript instead and threw away a
306
+ * real wish: speech recognition wrote the session differently than the
307
+ * model did, and the two never matched.
308
+ */
309
+ private isOwnSessionName(name: string): boolean {
310
+ return normalizeSpokenName(name) === normalizeSpokenName(this.target.slug);
311
+ }
312
+
313
+ private log(entry: Record<string, unknown>): void {
314
+ this.deps.log?.({ call: this.id, agent: this.target.agent, session: this.target.session, ...entry });
315
+ }
316
+
317
+ snapshot(): VoiceCallSnapshot {
318
+ const moving = this.announced.agent !== this.target.agent || this.announced.slug !== this.target.slug;
319
+ return {
320
+ id: this.id,
321
+ target: this.announced,
322
+ ...(moving ? { handoverTo: this.target.agent } : {}),
323
+ state: this.state,
324
+ startedAt: this.startedAt,
325
+ consults: this.consults,
326
+ spokenTurns: this.spokenTurns,
327
+ ...(this.lastError ? { lastError: this.lastError } : {}),
328
+ };
329
+ }
330
+
331
+ /** Open the provider session. The audio itself flows browser ↔
332
+ * provider; what comes back here is the control channel. */
333
+ async start(): Promise<RealtimeSession> {
334
+ const instructions = buildVoiceInstructions({
335
+ persona: this.persona,
336
+ consultPolicy: this.cfg.consultPolicy,
337
+ language: this.cfg.language,
338
+ consultToolName: CONSULT_TOOL_NAME,
339
+ sessionSlug: this.target.slug,
340
+ ...(this.cfg.personaOverride ? { override: this.cfg.personaOverride } : {}),
341
+ // The instruction names the OTHERS — "ask for someone else" reads
342
+ // oddly with your own name in the list. The tool spec carries the
343
+ // full list, own name included, because moving to another session
344
+ // of yourself goes through the same call.
345
+ ...(this.switchable().filter((a) => a !== this.target.agent).length > 0
346
+ ? { switchTo: this.switchable().filter((a) => a !== this.target.agent) }
347
+ : {}),
348
+ });
349
+ this.log({
350
+ msg: 'voice.call_start',
351
+ model: this.cfg.model,
352
+ voice: this.cfg.voice,
353
+ instructionChars: instructions.chars,
354
+ personaSource: this.cfg.personaOverride ? 'VOICE.md' : 'derived',
355
+ });
356
+ this.session = await this.deps.provider.open({
357
+ model: this.cfg.model,
358
+ voice: this.cfg.voice,
359
+ instructions: instructions.text,
360
+ language: this.cfg.language,
361
+ ...(this.cfg.turnDetection ? { turnDetection: this.cfg.turnDetection } : {}),
362
+ tools: [
363
+ consultToolSpec(this.persona.name),
364
+ statusToolSpec(),
365
+ resultToolSpec(),
366
+ ...(this.switchable().length > 0 ? [switchToolSpec(this.switchable(), this.target.agent)] : []),
367
+ ],
368
+ });
369
+ // The meter runs while nobody speaks, so the cap is wall-clock and
370
+ // enforced here rather than left to whoever forgets the tab.
371
+ //
372
+ // Measured from the START of the call, not of this session: start()
373
+ // runs again on every move. Re-arming it with the full budget would
374
+ // make a handover a way to talk for as long as you like, and leaving
375
+ // the old timer in place left one ticking per move.
376
+ this.clearDeadline();
377
+ const budgetLeft = Math.max(0, this.cfg.maxCallMinutes * 60_000 - (this.now() - this.startedAt));
378
+ this.deadlineTimer = setTimeout(
379
+ () => void this.close('call time limit reached'),
380
+ budgetLeft,
381
+ );
382
+ this.deadlineTimer.unref?.();
383
+ return this.session;
384
+ }
385
+
386
+ /** Drive the call. Ends when the provider session ends. */
387
+ async *run(): AsyncGenerator<VoiceCallSnapshot> {
388
+ // The loop outlives a single provider session: handing the call to
389
+ // another agent means a new voice, and a voice cannot be changed
390
+ // once a session has spoken (measured 2026-09-11). So the call
391
+ // stays, the session underneath is replaced.
392
+ while (true) {
393
+ const session = this.session ?? (await this.start());
394
+ const ended = yield* this.pump(session);
395
+ if (!this.pendingSwitch) {
396
+ if (ended) return;
397
+ continue;
398
+ }
399
+ const request = this.pendingSwitch;
400
+ this.pendingSwitch = undefined;
401
+ const ok = await this.performSwitch(request);
402
+ yield this.snapshot();
403
+ if (!ok) return;
404
+ }
405
+ }
406
+
407
+ /** One provider session's worth of events. Returns true when the call
408
+ * is over, false when it ended to make room for a switch. */
409
+ private async *pump(session: RealtimeSession): AsyncGenerator<VoiceCallSnapshot, boolean> {
410
+ for await (const ev of session.events()) {
411
+ // Mirror first, act second: a watcher must see the event even if
412
+ // handling it throws.
413
+ this.deps.onEvent?.(ev, this.snapshot());
414
+ switch (ev.kind) {
415
+ case 'ready':
416
+ // The new session is live, so the new name is now the honest
417
+ // one. Announced here rather than when the switch was decided.
418
+ this.announced = { ...this.target };
419
+ this.setState('listening');
420
+ this.deps.onState?.(this.snapshot());
421
+ yield this.snapshot();
422
+ break;
423
+ case 'model_speech':
424
+ this.setState(ev.phase === 'start' ? 'speaking' : 'listening');
425
+ yield this.snapshot();
426
+ break;
427
+ case 'user_transcript':
428
+ this.lastHeardAt = this.now();
429
+ if (ev.final && ev.text.trim().length > 0) {
430
+ this.remember('caller', ev.text.trim());
431
+ yield this.snapshot();
432
+ }
433
+ break;
434
+ case 'model_transcript':
435
+ if (ev.final && ev.text.trim().length > 0) {
436
+ this.remember('voice', ev.text.trim());
437
+ }
438
+ break;
439
+ case 'tool_call':
440
+ // Not awaited: a consult can take the whole patience, and the
441
+ // call must keep hearing the caller, honouring barge-in and
442
+ // taking the next question meanwhile (birdseye L10). The
443
+ // handler answers the tool call when it is done.
444
+ void this.handleToolCall(session, ev.callId, ev.name, ev.args).catch((err) => {
445
+ this.log({ msg: 'voice.tool_failed', tool: ev.name, err: (err as Error).message });
446
+ });
447
+ yield this.snapshot();
448
+ break;
449
+ case 'interrupted':
450
+ this.setState('listening');
451
+ this.log({ msg: 'voice.interrupted' });
452
+ yield this.snapshot();
453
+ break;
454
+ case 'error':
455
+ this.lastError = ev.message;
456
+ this.log({ msg: 'voice.error', err: ev.message, fatal: ev.fatal });
457
+ yield this.snapshot();
458
+ if (ev.fatal) {
459
+ await this.close(`provider error: ${ev.message}`);
460
+ return true;
461
+ }
462
+ break;
463
+ case 'closed':
464
+ if (this.pendingSwitch) return false;
465
+ this.setState('closed');
466
+ this.clearDeadline();
467
+ this.log({ msg: 'voice.call_end', reason: ev.reason, consults: this.consults, spokenTurns: this.spokenTurns });
468
+ yield this.snapshot();
469
+ return true;
470
+ default:
471
+ break;
472
+ }
473
+ }
474
+ if (this.pendingSwitch) return false;
475
+ this.setState('closed');
476
+ this.clearDeadline();
477
+ yield this.snapshot();
478
+ return true;
479
+ }
480
+
481
+ /**
482
+ * Continue the same call somewhere else: another agent, or another
483
+ * session of the agent already on the line.
484
+ *
485
+ * A failure here used to end the call. It must not: the caller asked
486
+ * for a session that may not exist, and being hung up on for a typo
487
+ * is the worst possible answer. The call comes back as the agent it
488
+ * was and says so.
489
+ */
490
+ private async performSwitch(request: { agent: string; session?: string }): Promise<boolean> {
491
+ const from = { ...this.target };
492
+ const fromPersona = this.persona;
493
+ const fromCfg = this.cfg;
494
+ const wanted = request.session;
495
+ // Carried over rather than asked for: dropped, so the caller lands
496
+ // in the other agent's main session.
497
+ const inherited = wanted !== undefined && request.agent !== this.target.agent && this.isOwnSessionName(wanted);
498
+ const session = inherited ? undefined : wanted;
499
+ if (inherited) {
500
+ this.log({ msg: 'voice.switch_session_dropped', to: request.agent, session: wanted });
501
+ }
502
+ try {
503
+ const next = await this.deps.resolveTarget!(request.agent, session);
504
+ await this.session?.close('handed over').catch(() => {});
505
+ this.session = undefined;
506
+ this.target = next.target;
507
+ this.persona = next.persona;
508
+ this.cfg = next.cfg;
509
+ this.setState('connecting');
510
+ this.deps.onState?.(this.snapshot());
511
+ await this.start();
512
+ this.log({ msg: 'voice.switched', from: `${from.agent}/${from.slug}`, to: `${this.target.agent}/${this.target.slug}` });
513
+ const moved = from.agent !== this.target.agent;
514
+ // A line in both places, so reading either conversation later
515
+ // shows where it went and where it came from. Moving between two
516
+ // sessions of the SAME agent writes the same pair — the agent is
517
+ // one, the conversations are two.
518
+ await this.note(
519
+ from.agent,
520
+ from.session,
521
+ moved
522
+ ? `[voice] handed this call over to ${this.target.agent} (session "${this.target.slug}")`
523
+ : `[voice] this call moved to the "${this.target.slug}" session`,
524
+ );
525
+ await this.note(
526
+ this.target.agent,
527
+ this.target.session,
528
+ moved
529
+ ? `[voice] took this call over from ${from.agent} (session "${from.slug}")`
530
+ : `[voice] this call came over from the "${from.slug}" session`,
531
+ );
532
+ return true;
533
+ } catch (err) {
534
+ this.lastError = (err as Error).message;
535
+ this.unreachable.set(`${request.agent}/${request.session ?? 'main'}`, this.lastError);
536
+ this.log({ msg: 'voice.switch_failed', to: request.agent, session: request.session ?? 'main', err: this.lastError });
537
+ // Back to where we were. The old provider session is already
538
+ // closing (the switch tool ends it so the new voice can start),
539
+ // so this opens a fresh one for the same agent.
540
+ try {
541
+ this.target = from;
542
+ this.persona = fromPersona;
543
+ this.cfg = fromCfg;
544
+ this.announced = { ...from };
545
+ this.setState('connecting');
546
+ const recovered = await this.start();
547
+ // The reason is the useful part: "there is main and cerebrocraft"
548
+ // is what lets the caller pick, where "that did not work" makes
549
+ // them guess again.
550
+ void recovered
551
+ .speak?.(
552
+ 'Say ONE short sentence, in the language of this conversation: the move did not work and they are ' +
553
+ `still with you. Put this into your own words, briefly: ${this.lastError ?? 'the target could not be reached'}`,
554
+ )
555
+ .catch(() => {});
556
+ this.log({ msg: 'voice.switch_recovered', agent: from.agent, session: from.slug });
557
+ return true;
558
+ } catch (recoveryErr) {
559
+ this.log({ msg: 'voice.switch_recovery_failed', err: (recoveryErr as Error).message });
560
+ this.setState('closed');
561
+ this.clearDeadline();
562
+ return false;
563
+ }
564
+ }
565
+ }
566
+
567
+ /**
568
+ * Come back on the line as the agent we already are.
569
+ *
570
+ * The switch tool ends its own provider session so the next voice can
571
+ * start, so "nothing to move to" is not a no-op: there is no session
572
+ * left to talk through. This opens a fresh one for the same target and
573
+ * has the voice say that the caller is still here.
574
+ */
575
+ private async stayPut(reason: string): Promise<boolean> {
576
+ this.log({ msg: 'voice.switch_stayed', agent: this.target.agent, session: this.target.slug, reason });
577
+ try {
578
+ this.announced = { ...this.target };
579
+ this.setState('connecting');
580
+ const recovered = await this.start();
581
+ void recovered
582
+ .speak?.(
583
+ 'Say ONE short sentence that they are still with you and ask which session they meant. Keep it under ten words.',
584
+ )
585
+ .catch(() => {});
586
+ return true;
587
+ } catch (err) {
588
+ this.log({ msg: 'voice.stay_failed', err: (err as Error).message });
589
+ this.setState('closed');
590
+ this.clearDeadline();
591
+ return false;
592
+ }
593
+ }
594
+
595
+ /**
596
+ * Microphone audio for whatever session the call is on RIGHT NOW.
597
+ *
598
+ * After a handover the provider session is a different object. The
599
+ * route used to hold the one it was given at the start, so once the
600
+ * call continued as another agent the microphone was still feeding a
601
+ * closed session: the window switched to lisa, lisa heard nothing,
602
+ * and the call had to be restarted (Rene, 2026-09-12). Anything that
603
+ * talks to the provider goes through the call, never around it.
604
+ */
605
+ async sendAudio(chunk: { base64: string; rateHz: number }): Promise<void> {
606
+ await this.session?.sendAudio?.(chunk);
607
+ }
608
+
609
+ async interrupt(): Promise<void> {
610
+ await this.session?.interrupt();
611
+ }
612
+
613
+ /**
614
+ * An answer that came back inside the patience goes to the talking
615
+ * model as a tool result. Handed the raw text, the small local model
616
+ * treated "shortened for the ear" as "leave it out": asked for the
617
+ * team structure, hans answered with 1239 characters and the voice
618
+ * spoke 25 (Rene, 2026-09-13). The hand-over announcement always
619
+ * carried an instruction; the quick path now does too — English,
620
+ * naming the call's language and the persona's sentence budget, the
621
+ * wording still the model's.
622
+ */
623
+ private frameAnswer(text: string): string {
624
+ const sentences = this.persona.voice?.maxSpokenSentences ?? 4;
625
+ return (
626
+ `The agent answered. Tell the user the substance of this answer in ${languageName(this.cfg.language)}, ` +
627
+ `in at most ${sentences} sentences: the names, facts and numbers in it, as the agent gave them, ` +
628
+ 'without reading lists or paths aloud. Never replace it with saying that you have it, that it is ' +
629
+ 'done, or that it is in the chat.\n' +
630
+ text
631
+ );
632
+ }
633
+
634
+ private async note(agent: string, session: string, text: string): Promise<void> {
635
+ await this.deps.appendEvent(agent, session, {
636
+ kind: 'engine_meta',
637
+ ts: this.now(),
638
+ engine: 'voice',
639
+ itemType: 'voice_handover',
640
+ payload: { text },
641
+ } as NormalizedEvent);
642
+ }
643
+
644
+ private async handleToolCall(session: RealtimeSession, callId: string, name: string, rawArgs: string): Promise<void> {
645
+ if (name === STATUS_TOOL_NAME) {
646
+ const status = (await this.deps.sessionStatus?.(this.target.agent, this.target.session)) ?? { busy: false };
647
+ const minutes = status.sinceMs ? Math.max(1, Math.round(status.sinceMs / 60_000)) : 0;
648
+ const own: string[] = [];
649
+ for (const [id, c] of this.openConsults) {
650
+ if (c.fetched) continue;
651
+ const look = await this.deps.consultResult?.(id).catch(() => null);
652
+ if (look?.state === 'done' || look?.state === 'failed') {
653
+ // Reading it here counts as fetched: it is answered on this line.
654
+ c.fetched = true;
655
+ own.push(`your request "${c.question.slice(0, 80)}" is finished — answer: ${look.state === 'done' ? (look.text ?? '') : `could not: ${look.error ?? 'unknown error'}`}`);
656
+ } else if (look) {
657
+ own.push(`your request "${c.question.slice(0, 80)}" is still ${look.position ? `waiting (position ${look.position})` : 'running'}`);
658
+ }
659
+ }
660
+ const base = status.busy
661
+ ? `still working on something you started ${minutes} minute(s) ago${status.queued ? `, ${status.queued} waiting behind it` : ''} — say so, and offer to look again in a moment`
662
+ : 'nothing running right now';
663
+ await session.sendToolResult(callId, own.length > 0 ? `${base}; ${own.join('; ')}` : base);
664
+ return;
665
+ }
666
+ if (name === RESULT_TOOL_NAME) {
667
+ const parsed = parseResultArgs(rawArgs);
668
+ if (!parsed.ok) {
669
+ await session.sendToolResult(callId, parsed.error);
670
+ return;
671
+ }
672
+ const open = this.openConsults.get(parsed.consultId);
673
+ const look = await this.deps.consultResult?.(parsed.consultId).catch(() => null);
674
+ if (!look) {
675
+ await session.sendToolResult(callId, 'nothing was handed over under that id — say so');
676
+ return;
677
+ }
678
+ if (look.state === 'pending') {
679
+ await session.sendToolResult(callId, `still working on it${look.position ? ` (position ${look.position} in the queue)` : ''} — say so, do not invent an answer`);
680
+ return;
681
+ }
682
+ if (open) open.fetched = true;
683
+ this.log({ msg: 'voice.consult_fetched', consultId: parsed.consultId, state: look.state });
684
+ await session.sendToolResult(
685
+ callId,
686
+ look.state === 'done'
687
+ ? (look.text?.trim() ? this.frameAnswer(look.text.trim()) : 'no answer this time — say so, do not invent one')
688
+ : `the agent could not answer: ${look.error ?? 'unknown error'}`,
689
+ );
690
+ return;
691
+ }
692
+ if (name === SWITCH_TOOL_NAME) {
693
+ const parsed = parseSwitchArgs(rawArgs);
694
+ if (!parsed.ok) {
695
+ await session.sendToolResult(callId, parsed.error);
696
+ return;
697
+ }
698
+ const allowed = this.switchable();
699
+ if (!allowed.includes(parsed.args.agent)) {
700
+ await session.sendToolResult(
701
+ callId,
702
+ `${parsed.args.agent} cannot be reached by voice — say so. Available: ${allowed.join(', ') || 'nobody else'}`,
703
+ );
704
+ return;
705
+ }
706
+ const request = parsed.args;
707
+ // Already tried and already impossible: answer from memory rather
708
+ // than tearing the line down again.
709
+ const known = this.unreachable.get(`${request.agent}/${request.session ?? 'main'}`);
710
+ if (known) {
711
+ await session.sendToolResult(callId, known);
712
+ return;
713
+ }
714
+ // Asking to go where you already are is a model slip, not a wish.
715
+ // Caught here because it is the one case decidable on the spot,
716
+ // and tearing a session down for it would be an audible pause for
717
+ // nothing.
718
+ const staying =
719
+ request.agent === this.target.agent &&
720
+ (request.session === undefined
721
+ ? this.target.slug === 'main'
722
+ : request.session === this.target.slug);
723
+ if (staying) {
724
+ await session.sendToolResult(
725
+ callId,
726
+ 'that is the conversation you are already in — say so, and ask which session they mean',
727
+ );
728
+ return;
729
+ }
730
+ // Answer BEFORE the session goes away: the tool result has to
731
+ // reach the model that asked, not its successor.
732
+ await session.sendToolResult(
733
+ callId,
734
+ request.agent === this.target.agent
735
+ ? `moving you into the "${request.session ?? 'main'}" session now`
736
+ : `putting them through to ${request.agent} now`,
737
+ );
738
+ this.pendingSwitch = request;
739
+ this.log({ msg: 'voice.switch_requested', to: request.agent, session: request.session ?? 'main' });
740
+ // Give the sentence a moment to be spoken, then end this session;
741
+ // the run loop opens the next one.
742
+ setTimeout(() => void session.close('handing over').catch(() => {}), 2_500).unref?.();
743
+ return;
744
+ }
745
+ if (name !== CONSULT_TOOL_NAME) {
746
+ // The voice self only ever gets the tools we hand it. Anything
747
+ // else is a provider or prompt bug, and answering it with an
748
+ // error keeps the conversation alive instead of wedging it.
749
+ this.log({ msg: 'voice.unknown_tool', tool: name });
750
+ await session.sendToolResult(callId, `unknown tool '${name}' — you only have ${CONSULT_TOOL_NAME}`);
751
+ return;
752
+ }
753
+ const parsed = parseConsultArgs(rawArgs);
754
+ if (!parsed.ok) {
755
+ this.log({ msg: 'voice.consult_bad_args', err: parsed.error });
756
+ await session.sendToolResult(callId, parsed.error);
757
+ return;
758
+ }
759
+ this.setState('consulting');
760
+ this.consults += 1;
761
+ const startedAt = this.now();
762
+ const turn = renderConsultTurn(parsed.args, 'the user', this.recentTranscript());
763
+ this.log({ msg: 'voice.consult_start', question: parsed.args.question.slice(0, 160) });
764
+ // Fill the silence from here rather than asking the model to
765
+ // announce its own lookup: told to do that, it announced and never
766
+ // called (both models, 2026-09-11).
767
+ void session
768
+ .speak?.('Say ONE short sentence that you are looking it up right now. Nothing else, no promises about what you will find.')
769
+ .catch(() => {});
770
+ try {
771
+ const result = await this.deps.runConsult({
772
+ agent: this.target.agent,
773
+ session: this.target.session,
774
+ text: turn.text,
775
+ prefix: turn.prefix,
776
+ callId: this.id,
777
+ });
778
+ if (result.state === 'handed_over' && result.consultId) {
779
+ const id = result.consultId;
780
+ this.openConsults.set(id, { question: parsed.args.question, startedAt, agent: this.target.agent, fetched: false });
781
+ this.log({ msg: 'voice.consult_handed_over', consultId: id, position: result.position ?? 0, ms: this.now() - startedAt });
782
+ if (this.state !== 'closed' && session === this.session) {
783
+ await session.sendToolResult(
784
+ callId,
785
+ `handed over (consult ${id}${result.position ? `, position ${result.position} in the queue` : ''}). ` +
786
+ 'Tell the user you passed it on and keep talking. The answer is read out to them when it ' +
787
+ `arrives; if they ask whether it is done, ${RESULT_TOOL_NAME} fetches it.`,
788
+ );
789
+ }
790
+ const early = this.earlyDeliveries.get(id);
791
+ if (early) {
792
+ this.earlyDeliveries.delete(id);
793
+ void this.deliver(early);
794
+ }
795
+ return;
796
+ }
797
+ const answer = result.text.trim();
798
+ this.log({
799
+ msg: 'voice.consult_done',
800
+ ms: this.now() - startedAt,
801
+ outcome: result.outcome ?? null,
802
+ pending: result.pending ?? false,
803
+ chars: answer.length,
804
+ });
805
+ // The session may be gone or replaced by the time a long answer
806
+ // lands: never write into a closed line or the successor's.
807
+ if (this.state === 'closed' || session !== this.session) {
808
+ this.log({ msg: 'voice.consult_answer_after_session', ms: this.now() - startedAt });
809
+ return;
810
+ }
811
+ await session.sendToolResult(
812
+ callId,
813
+ answer.length > 0
814
+ ? this.frameAnswer(answer)
815
+ : `no answer this time — say so, do not invent one`,
816
+ );
817
+ } catch (err) {
818
+ const message = (err as Error).message;
819
+ this.lastError = message;
820
+ this.log({ msg: 'voice.consult_failed', err: message });
821
+ // The failure is told to the voice self so it can say something
822
+ // true ("I could not reach him"), rather than being swallowed
823
+ // into a silence the user has to interpret.
824
+ await session.sendToolResult(callId, `asking ${this.persona.name} failed: ${message}`);
825
+ } finally {
826
+ this.setState('listening');
827
+ }
828
+ }
829
+
830
+ /**
831
+ * A handed-over consult finished. Read it out — once, on this line,
832
+ * for the agent that was asked, at a pause in the conversation.
833
+ * Anything else stays in the agent's chat where it landed.
834
+ */
835
+ async deliver(res: ConsultDelivery): Promise<void> {
836
+ const open = this.openConsults.get(res.consultId);
837
+ if (res.followUp) {
838
+ if (!open) {
839
+ this.log({ msg: 'voice.consult_delivery_skipped', consultId: res.consultId, reason: 'follow-up for a consult this call does not know' });
840
+ return;
841
+ }
842
+ if (this.state === 'closed' || !this.session) {
843
+ this.log({ msg: 'voice.consult_delivery_skipped', consultId: res.consultId, reason: 'call closed' });
844
+ return;
845
+ }
846
+ if (open.agent !== this.target.agent) {
847
+ this.log({ msg: 'voice.consult_delivery_skipped', consultId: res.consultId, reason: 'call moved to another agent' });
848
+ return;
849
+ }
850
+ await this.announce(open.question, res);
851
+ return;
852
+ }
853
+ if (!open) {
854
+ // Finished before the hand-over was recorded: keep it for a moment.
855
+ this.earlyDeliveries.set(res.consultId, res);
856
+ setTimeout(() => this.earlyDeliveries.delete(res.consultId), 30_000).unref?.();
857
+ return;
858
+ }
859
+ if (open.fetched) return;
860
+ if (this.state === 'closed' || !this.session) {
861
+ this.log({ msg: 'voice.consult_delivery_skipped', consultId: res.consultId, reason: 'call closed' });
862
+ return;
863
+ }
864
+ if (open.agent !== this.target.agent) {
865
+ this.log({ msg: 'voice.consult_delivery_skipped', consultId: res.consultId, reason: 'call moved to another agent' });
866
+ return;
867
+ }
868
+ open.fetched = true;
869
+ await this.deps.markConsultFetched?.(res.consultId).catch(() => {});
870
+ await this.announce(open.question, res);
871
+ }
872
+
873
+ /** Wait for a pause (the model not speaking, the caller quiet for a
874
+ * moment), then have the model read the answer. Never a fixed
875
+ * sentence: the instruction is English, names the call's language,
876
+ * and the wording is the model's (Rene, 2026-09-13). */
877
+ private async announce(question: string, res: ConsultDelivery): Promise<void> {
878
+ const deadline = this.now() + ANNOUNCE_MAX_WAIT_MS;
879
+ while (this.now() < deadline) {
880
+ if (this.state === 'closed') return;
881
+ const quiet = this.state === 'listening' && this.now() - this.lastHeardAt >= ANNOUNCE_PAUSE_MS;
882
+ if (quiet) break;
883
+ await new Promise((r) => setTimeout(r, 250));
884
+ }
885
+ if (this.state === 'closed' || !this.session) return;
886
+ const body = res.state === 'done'
887
+ ? (res.text?.trim() || 'the agent had no answer')
888
+ : `the agent could not answer: ${res.error ?? 'unknown error'}`;
889
+ const instruction = res.followUp
890
+ ? `The agent has a follow-up on the question the user asked earlier about "${question.slice(0, 120)}": ` +
891
+ 'work it had started for that question has now finished. ' +
892
+ `Start by saying, in ${this.cfg.language}, that this is a follow-up to that earlier question, ` +
893
+ 'then give it as it is. Do not add anything else.\n' +
894
+ body
895
+ : `Read the user the answer to the question they asked earlier about "${question.slice(0, 120)}". ` +
896
+ `Start by saying, in ${this.cfg.language}, that this is the answer to that earlier question, ` +
897
+ 'then give the answer as it is. Do not add anything else.\n' +
898
+ body;
899
+ try {
900
+ // deliver: the model may be mid-sentence (its own "still working"
901
+ // after a status check); the announcement is kept for the pause
902
+ // instead of dropped like a filler (2026-09-13, hans counting to
903
+ // forty went silent while the log said announced).
904
+ await this.session.speak?.(instruction, { deliver: true });
905
+ this.log({ msg: 'voice.consult_announced', consultId: res.consultId, state: res.state, chars: body.length, ...(res.followUp ? { followUp: true } : {}) });
906
+ } catch (err) {
907
+ this.log({ msg: 'voice.consult_announce_failed', consultId: res.consultId, err: (err as Error).message });
908
+ }
909
+ }
910
+
911
+ /**
912
+ * One line of the conversation, held for the length of the call.
913
+ *
914
+ * Nothing here reaches disk. Its one job is to give the agent the
915
+ * couple of sentences around a question: asked "what time is it", the
916
+ * agent otherwise has no idea what the caller was talking about.
917
+ * OpenClaw hands its consulting agent the last twelve lines for the
918
+ * same reason.
919
+ */
920
+ private remember(role: 'caller' | 'voice', text: string): void {
921
+ if (role === 'caller') this.spokenTurns += 1;
922
+ this.transcript.push({ role, text });
923
+ if (this.transcript.length > TRANSCRIPT_MEMORY) {
924
+ this.transcript.splice(0, this.transcript.length - TRANSCRIPT_MEMORY);
925
+ }
926
+ }
927
+
928
+ /** The tail of the conversation that travels with a question. Short
929
+ * on purpose: it is written into the agent's session, so it is part
930
+ * of the record and part of every later context. */
931
+ private recentTranscript(): Array<{ role: 'caller' | 'voice'; text: string }> {
932
+ return this.transcript.slice(-CONSULT_TRANSCRIPT_LINES);
933
+ }
934
+
935
+ private clearDeadline(): void {
936
+ if (this.deadlineTimer) clearTimeout(this.deadlineTimer);
937
+ this.deadlineTimer = undefined;
938
+ }
939
+
940
+ async close(reason: string): Promise<void> {
941
+ this.clearDeadline();
942
+ if (this.state !== 'closed') {
943
+ this.state = 'closed';
944
+ await this.session?.close(reason).catch(() => {});
945
+ this.log({ msg: 'voice.call_closed', reason, consults: this.consults, spokenTurns: this.spokenTurns });
946
+ }
947
+ }
948
+ }