@elizaos/plugin-local-inference 2.0.0-beta.1 → 2.0.11-beta.7

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 (676) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +83 -0
  3. package/package.json +81 -15
  4. package/src/actions/generate-media.d.ts +59 -0
  5. package/src/actions/generate-media.d.ts.map +1 -0
  6. package/src/actions/generate-media.ts +647 -0
  7. package/src/actions/identify-speaker.d.ts +23 -0
  8. package/src/actions/identify-speaker.d.ts.map +1 -0
  9. package/src/actions/identify-speaker.ts +171 -0
  10. package/src/adapters/capacitor-llama/__tests__/compat-behavior.test.ts +218 -0
  11. package/src/adapters/capacitor-llama/__tests__/index.test.ts +68 -0
  12. package/src/adapters/capacitor-llama/__tests__/structured-output.test.ts +215 -0
  13. package/src/adapters/capacitor-llama/__tests__/text-streaming.test.ts +174 -0
  14. package/src/adapters/capacitor-llama/environment.ts +71 -0
  15. package/src/adapters/capacitor-llama/index.browser.ts +83 -0
  16. package/src/adapters/capacitor-llama/index.ts +807 -0
  17. package/src/adapters/capacitor-llama/loader.ts +109 -0
  18. package/src/adapters/capacitor-llama/structured-output.ts +165 -0
  19. package/src/adapters/capacitor-llama/text-streaming.ts +227 -0
  20. package/src/adapters/capacitor-llama/types.ts +374 -0
  21. package/src/backends/apple-foundation.ts +127 -0
  22. package/src/index.d.ts +7 -0
  23. package/src/index.d.ts.map +1 -0
  24. package/src/index.ts +54 -0
  25. package/src/local-inference-routes.d.ts +38 -0
  26. package/src/local-inference-routes.d.ts.map +1 -0
  27. package/src/local-inference-routes.test.ts +344 -0
  28. package/src/local-inference-routes.ts +1543 -0
  29. package/src/provider.d.ts +21 -0
  30. package/src/provider.d.ts.map +1 -0
  31. package/src/provider.ts +1171 -0
  32. package/src/routes/compat-helpers.d.ts +18 -0
  33. package/src/routes/compat-helpers.d.ts.map +1 -0
  34. package/src/routes/compat-helpers.ts +274 -0
  35. package/src/routes/family-member-route.d.ts +62 -0
  36. package/src/routes/family-member-route.d.ts.map +1 -0
  37. package/src/routes/family-member-route.ts +353 -0
  38. package/src/routes/index.d.ts +19 -0
  39. package/src/routes/index.d.ts.map +1 -0
  40. package/src/routes/index.ts +60 -0
  41. package/src/routes/live-diarization-route.d.ts +26 -0
  42. package/src/routes/live-diarization-route.d.ts.map +1 -0
  43. package/src/routes/live-diarization-route.test.ts +213 -0
  44. package/src/routes/live-diarization-route.ts +122 -0
  45. package/src/routes/local-inference-asr-route.d.ts +4 -0
  46. package/src/routes/local-inference-asr-route.d.ts.map +1 -0
  47. package/src/routes/local-inference-asr-route.test.ts +190 -0
  48. package/src/routes/local-inference-asr-route.ts +213 -0
  49. package/src/routes/local-inference-compat-routes.d.ts +16 -0
  50. package/src/routes/local-inference-compat-routes.d.ts.map +1 -0
  51. package/src/routes/local-inference-compat-routes.test.ts +423 -0
  52. package/src/routes/local-inference-compat-routes.ts +782 -0
  53. package/src/routes/local-inference-tts-route.d.ts +7 -0
  54. package/src/routes/local-inference-tts-route.d.ts.map +1 -0
  55. package/src/routes/local-inference-tts-route.test.ts +179 -0
  56. package/src/routes/local-inference-tts-route.ts +230 -0
  57. package/src/routes/voice-first-run-routes.d.ts +62 -0
  58. package/src/routes/voice-first-run-routes.d.ts.map +1 -0
  59. package/src/routes/voice-first-run-routes.ts +524 -0
  60. package/src/routes/voice-models-routes.d.ts +62 -0
  61. package/src/routes/voice-models-routes.d.ts.map +1 -0
  62. package/src/routes/voice-models-routes.ts +554 -0
  63. package/src/routes/voice-profile-plugin-routes.d.ts +19 -0
  64. package/src/routes/voice-profile-plugin-routes.d.ts.map +1 -0
  65. package/src/routes/voice-profile-plugin-routes.ts +138 -0
  66. package/src/routes/voice-profiles-management-routes.d.ts +52 -0
  67. package/src/routes/voice-profiles-management-routes.d.ts.map +1 -0
  68. package/src/routes/voice-profiles-management-routes.ts +476 -0
  69. package/src/routes/voice-speaker-profile-routes.d.ts +57 -0
  70. package/src/routes/voice-speaker-profile-routes.d.ts.map +1 -0
  71. package/src/routes/voice-speaker-profile-routes.ts +199 -0
  72. package/src/runtime/aosp-llama-loader-selection.test.ts +80 -0
  73. package/src/runtime/capacitor-llama.d.ts +25 -0
  74. package/src/runtime/embedding-manager-support.d.ts +77 -0
  75. package/src/runtime/embedding-manager-support.d.ts.map +1 -0
  76. package/src/runtime/embedding-manager-support.ts +497 -0
  77. package/src/runtime/embedding-presets.d.ts +16 -0
  78. package/src/runtime/embedding-presets.d.ts.map +1 -0
  79. package/src/runtime/embedding-presets.ts +81 -0
  80. package/src/runtime/embedding-warmup-policy.d.ts +14 -0
  81. package/src/runtime/embedding-warmup-policy.d.ts.map +1 -0
  82. package/src/runtime/embedding-warmup-policy.test.ts +53 -0
  83. package/src/runtime/embedding-warmup-policy.ts +48 -0
  84. package/src/runtime/ensure-local-inference-handler.d.ts +53 -0
  85. package/src/runtime/ensure-local-inference-handler.d.ts.map +1 -0
  86. package/src/runtime/ensure-local-inference-handler.test.ts +528 -0
  87. package/src/runtime/ensure-local-inference-handler.ts +1398 -0
  88. package/src/runtime/index.d.ts +14 -0
  89. package/src/runtime/index.d.ts.map +1 -0
  90. package/src/runtime/index.ts +27 -0
  91. package/src/runtime/mobile-local-inference-gate.d.ts +31 -0
  92. package/src/runtime/mobile-local-inference-gate.d.ts.map +1 -0
  93. package/src/runtime/mobile-local-inference-gate.test.ts +69 -0
  94. package/src/runtime/mobile-local-inference-gate.ts +44 -0
  95. package/src/runtime/voice-entity-binding.d.ts +103 -0
  96. package/src/runtime/voice-entity-binding.d.ts.map +1 -0
  97. package/src/runtime/voice-entity-binding.transcript.test.ts +69 -0
  98. package/src/runtime/voice-entity-binding.ts +328 -0
  99. package/src/services/README.md +71 -0
  100. package/src/services/__tests__/backend-selector.test.ts +101 -0
  101. package/src/services/__tests__/checkpoint-manager.test.ts +376 -0
  102. package/src/services/__tests__/gpu-autotune.test.ts +400 -0
  103. package/src/services/__tests__/llm-streaming-binding.test.ts +85 -0
  104. package/src/services/__tests__/planner-grammar.test.ts +372 -0
  105. package/src/services/__tests__/runtime-target.test.ts +176 -0
  106. package/src/services/active-model-switch-rollback.test.ts +183 -0
  107. package/src/services/active-model.d.ts +282 -0
  108. package/src/services/active-model.d.ts.map +1 -0
  109. package/src/services/active-model.ts +1213 -0
  110. package/src/services/asr/errors.d.ts +21 -0
  111. package/src/services/asr/errors.d.ts.map +1 -0
  112. package/src/services/asr/errors.ts +50 -0
  113. package/src/services/asr/hash.d.ts +28 -0
  114. package/src/services/asr/hash.d.ts.map +1 -0
  115. package/src/services/asr/hash.ts +49 -0
  116. package/src/services/asr/index.d.ts +76 -0
  117. package/src/services/asr/index.d.ts.map +1 -0
  118. package/src/services/asr/index.ts +178 -0
  119. package/src/services/asr/types.d.ts +91 -0
  120. package/src/services/asr/types.d.ts.map +1 -0
  121. package/src/services/asr/types.ts +95 -0
  122. package/src/services/assignments.d.ts +71 -0
  123. package/src/services/assignments.d.ts.map +1 -0
  124. package/src/services/assignments.test.ts +80 -0
  125. package/src/services/assignments.ts +230 -0
  126. package/src/services/backend-selector.ts +95 -0
  127. package/src/services/backend.d.ts +346 -0
  128. package/src/services/backend.d.ts.map +1 -0
  129. package/src/services/backend.ts +612 -0
  130. package/src/services/bundled-models.d.ts +34 -0
  131. package/src/services/bundled-models.d.ts.map +1 -0
  132. package/src/services/bundled-models.ts +129 -0
  133. package/src/services/cache-bridge.d.ts +206 -0
  134. package/src/services/cache-bridge.d.ts.map +1 -0
  135. package/src/services/cache-bridge.test.ts +516 -0
  136. package/src/services/cache-bridge.ts +423 -0
  137. package/src/services/catalog.d.ts +10 -0
  138. package/src/services/catalog.d.ts.map +1 -0
  139. package/src/services/catalog.test.ts +240 -0
  140. package/src/services/catalog.ts +27 -0
  141. package/src/services/checkpoint-client.d.ts +109 -0
  142. package/src/services/checkpoint-client.d.ts.map +1 -0
  143. package/src/services/checkpoint-client.ts +258 -0
  144. package/src/services/checkpoint-manager.ts +474 -0
  145. package/src/services/cloud-fallback.d.ts +102 -0
  146. package/src/services/cloud-fallback.d.ts.map +1 -0
  147. package/src/services/cloud-fallback.ts +230 -0
  148. package/src/services/conversation-registry.d.ts +142 -0
  149. package/src/services/conversation-registry.d.ts.map +1 -0
  150. package/src/services/conversation-registry.test.ts +235 -0
  151. package/src/services/conversation-registry.ts +264 -0
  152. package/src/services/desktop-fused-ffi-backend-runtime.d.ts +92 -0
  153. package/src/services/desktop-fused-ffi-backend-runtime.d.ts.map +1 -0
  154. package/src/services/desktop-fused-ffi-backend-runtime.ts +333 -0
  155. package/src/services/device-bridge.d.ts +188 -0
  156. package/src/services/device-bridge.d.ts.map +1 -0
  157. package/src/services/device-bridge.ts +1237 -0
  158. package/src/services/device-resource-metrics.d.ts +149 -0
  159. package/src/services/device-resource-metrics.d.ts.map +1 -0
  160. package/src/services/device-resource-metrics.test.ts +98 -0
  161. package/src/services/device-resource-metrics.ts +346 -0
  162. package/src/services/device-tier.d.ts +115 -0
  163. package/src/services/device-tier.d.ts.map +1 -0
  164. package/src/services/device-tier.test.ts +371 -0
  165. package/src/services/device-tier.ts +410 -0
  166. package/src/services/downloader.d.ts +82 -0
  167. package/src/services/downloader.d.ts.map +1 -0
  168. package/src/services/downloader.test.ts +724 -0
  169. package/src/services/downloader.ts +899 -0
  170. package/src/services/engine-direct-bundle.test.ts +58 -0
  171. package/src/services/engine-streaming.test.ts +80 -0
  172. package/src/services/engine.d.ts +534 -0
  173. package/src/services/engine.d.ts.map +1 -0
  174. package/src/services/engine.ts +1891 -0
  175. package/src/services/ensure-local-artifacts.integration.test.ts +273 -0
  176. package/src/services/ensure-local-artifacts.test.ts +368 -0
  177. package/src/services/ensure-local-artifacts.ts +351 -0
  178. package/src/services/external-scanner.d.ts +17 -0
  179. package/src/services/external-scanner.d.ts.map +1 -0
  180. package/src/services/external-scanner.ts +312 -0
  181. package/src/services/ffi-llm-mock.ts +354 -0
  182. package/src/services/ffi-llm-streaming-abi.ts +442 -0
  183. package/src/services/ffi-streaming-backend.d.ts +180 -0
  184. package/src/services/ffi-streaming-backend.d.ts.map +1 -0
  185. package/src/services/ffi-streaming-backend.ts +382 -0
  186. package/src/services/ffi-streaming-runner.d.ts +122 -0
  187. package/src/services/ffi-streaming-runner.d.ts.map +1 -0
  188. package/src/services/ffi-streaming-runner.test.ts +60 -0
  189. package/src/services/ffi-streaming-runner.ts +354 -0
  190. package/src/services/ffi-unload-ordering.test.ts +162 -0
  191. package/src/services/gpu-autotune.ts +534 -0
  192. package/src/services/gpu-detect.ts +139 -0
  193. package/src/services/handler-registry.d.ts +72 -0
  194. package/src/services/handler-registry.d.ts.map +1 -0
  195. package/src/services/handler-registry.ts +240 -0
  196. package/src/services/hardware.d.ts +63 -0
  197. package/src/services/hardware.d.ts.map +1 -0
  198. package/src/services/hardware.test.ts +183 -0
  199. package/src/services/hardware.ts +404 -0
  200. package/src/services/hf-search.d.ts +26 -0
  201. package/src/services/hf-search.d.ts.map +1 -0
  202. package/src/services/hf-search.test.ts +69 -0
  203. package/src/services/hf-search.ts +420 -0
  204. package/src/services/image-description-runtime.d.ts +14 -0
  205. package/src/services/image-description-runtime.d.ts.map +1 -0
  206. package/src/services/image-description-runtime.test.ts +61 -0
  207. package/src/services/image-description-runtime.ts +118 -0
  208. package/src/services/imagegen/aosp-unavailable.d.ts +134 -0
  209. package/src/services/imagegen/aosp-unavailable.d.ts.map +1 -0
  210. package/src/services/imagegen/aosp-unavailable.ts +229 -0
  211. package/src/services/imagegen/backend-selector.d.ts +118 -0
  212. package/src/services/imagegen/backend-selector.d.ts.map +1 -0
  213. package/src/services/imagegen/backend-selector.ts +281 -0
  214. package/src/services/imagegen/coreml-unavailable.d.ts +105 -0
  215. package/src/services/imagegen/coreml-unavailable.d.ts.map +1 -0
  216. package/src/services/imagegen/coreml-unavailable.ts +237 -0
  217. package/src/services/imagegen/errors.d.ts +16 -0
  218. package/src/services/imagegen/errors.d.ts.map +1 -0
  219. package/src/services/imagegen/errors.ts +40 -0
  220. package/src/services/imagegen/index.d.ts +58 -0
  221. package/src/services/imagegen/index.d.ts.map +1 -0
  222. package/src/services/imagegen/index.ts +144 -0
  223. package/src/services/imagegen/mflux.d.ts +74 -0
  224. package/src/services/imagegen/mflux.d.ts.map +1 -0
  225. package/src/services/imagegen/mflux.ts +313 -0
  226. package/src/services/imagegen/sd-cpp.d.ts +180 -0
  227. package/src/services/imagegen/sd-cpp.d.ts.map +1 -0
  228. package/src/services/imagegen/sd-cpp.ts +718 -0
  229. package/src/services/imagegen/tensorrt-unavailable.d.ts +83 -0
  230. package/src/services/imagegen/tensorrt-unavailable.d.ts.map +1 -0
  231. package/src/services/imagegen/tensorrt-unavailable.ts +295 -0
  232. package/src/services/imagegen/types.d.ts +181 -0
  233. package/src/services/imagegen/types.d.ts.map +1 -0
  234. package/src/services/imagegen/types.ts +193 -0
  235. package/src/services/index.d.ts +30 -0
  236. package/src/services/index.d.ts.map +1 -0
  237. package/src/services/index.ts +225 -0
  238. package/src/services/inference-capabilities.d.ts +132 -0
  239. package/src/services/inference-capabilities.d.ts.map +1 -0
  240. package/src/services/inference-capabilities.test.ts +75 -0
  241. package/src/services/inference-capabilities.ts +204 -0
  242. package/src/services/inference-telemetry.d.ts +59 -0
  243. package/src/services/inference-telemetry.d.ts.map +1 -0
  244. package/src/services/inference-telemetry.ts +143 -0
  245. package/src/services/ios-llama-streaming.ts +248 -0
  246. package/src/services/kv-spill.d.ts +189 -0
  247. package/src/services/kv-spill.d.ts.map +1 -0
  248. package/src/services/kv-spill.test.ts +222 -0
  249. package/src/services/kv-spill.ts +356 -0
  250. package/src/services/latency-trace.d.ts +346 -0
  251. package/src/services/latency-trace.d.ts.map +1 -0
  252. package/src/services/latency-trace.test.ts +266 -0
  253. package/src/services/latency-trace.ts +844 -0
  254. package/src/services/llama-server-metrics.ts +304 -0
  255. package/src/services/llm-streaming-binding.d.ts +96 -0
  256. package/src/services/llm-streaming-binding.d.ts.map +1 -0
  257. package/src/services/llm-streaming-binding.ts +136 -0
  258. package/src/services/load-args.d.ts +82 -0
  259. package/src/services/load-args.d.ts.map +1 -0
  260. package/src/services/load-args.ts +81 -0
  261. package/src/services/manifest/eliza-1.manifest.v1.json +708 -0
  262. package/src/services/manifest/index.d.ts +4 -0
  263. package/src/services/manifest/index.d.ts.map +1 -0
  264. package/src/services/manifest/index.ts +66 -0
  265. package/src/services/manifest/manifest.test.ts +693 -0
  266. package/src/services/manifest/schema.d.ts +715 -0
  267. package/src/services/manifest/schema.d.ts.map +1 -0
  268. package/src/services/manifest/schema.ts +655 -0
  269. package/src/services/manifest/types.d.ts +30 -0
  270. package/src/services/manifest/types.d.ts.map +1 -0
  271. package/src/services/manifest/types.ts +55 -0
  272. package/src/services/manifest/validator.d.ts +66 -0
  273. package/src/services/manifest/validator.d.ts.map +1 -0
  274. package/src/services/manifest/validator.ts +569 -0
  275. package/src/services/memory-arbiter.d.ts +343 -0
  276. package/src/services/memory-arbiter.d.ts.map +1 -0
  277. package/src/services/memory-arbiter.test.ts +419 -0
  278. package/src/services/memory-arbiter.ts +1000 -0
  279. package/src/services/memory-monitor.d.ts +119 -0
  280. package/src/services/memory-monitor.d.ts.map +1 -0
  281. package/src/services/memory-monitor.test.ts +208 -0
  282. package/src/services/memory-monitor.ts +296 -0
  283. package/src/services/memory-pressure.d.ts +127 -0
  284. package/src/services/memory-pressure.d.ts.map +1 -0
  285. package/src/services/memory-pressure.ts +413 -0
  286. package/src/services/mtp-doctor.d.ts +13 -0
  287. package/src/services/mtp-doctor.d.ts.map +1 -0
  288. package/src/services/mtp-doctor.ts +78 -0
  289. package/src/services/network-policy.d.ts +127 -0
  290. package/src/services/network-policy.d.ts.map +1 -0
  291. package/src/services/network-policy.ts +346 -0
  292. package/src/services/paths.d.ts +6 -0
  293. package/src/services/paths.d.ts.map +1 -0
  294. package/src/services/paths.ts +25 -0
  295. package/src/services/planner-skeleton.d.ts +124 -0
  296. package/src/services/planner-skeleton.d.ts.map +1 -0
  297. package/src/services/planner-skeleton.ts +175 -0
  298. package/src/services/providers.d.ts +38 -0
  299. package/src/services/providers.d.ts.map +1 -0
  300. package/src/services/providers.ts +507 -0
  301. package/src/services/ram-budget-cache.test.ts +163 -0
  302. package/src/services/ram-budget.d.ts +110 -0
  303. package/src/services/ram-budget.d.ts.map +1 -0
  304. package/src/services/ram-budget.ts +0 -0
  305. package/src/services/readiness.d.ts +9 -0
  306. package/src/services/readiness.d.ts.map +1 -0
  307. package/src/services/readiness.test.ts +87 -0
  308. package/src/services/readiness.ts +238 -0
  309. package/src/services/recommendation.d.ts +111 -0
  310. package/src/services/recommendation.d.ts.map +1 -0
  311. package/src/services/recommendation.ts +672 -0
  312. package/src/services/registry.d.ts +35 -0
  313. package/src/services/registry.d.ts.map +1 -0
  314. package/src/services/registry.ts +151 -0
  315. package/src/services/router-handler.d.ts +92 -0
  316. package/src/services/router-handler.d.ts.map +1 -0
  317. package/src/services/router-handler.test.ts +45 -0
  318. package/src/services/router-handler.ts +376 -0
  319. package/src/services/routing-policy.d.ts +55 -0
  320. package/src/services/routing-policy.d.ts.map +1 -0
  321. package/src/services/routing-policy.ts +228 -0
  322. package/src/services/routing-preferences.d.ts +8 -0
  323. package/src/services/routing-preferences.d.ts.map +1 -0
  324. package/src/services/routing-preferences.ts +15 -0
  325. package/src/services/runtime-target.d.ts +98 -0
  326. package/src/services/runtime-target.d.ts.map +1 -0
  327. package/src/services/runtime-target.ts +154 -0
  328. package/src/services/service.d.ts +128 -0
  329. package/src/services/service.d.ts.map +1 -0
  330. package/src/services/service.test.ts +223 -0
  331. package/src/services/service.ts +735 -0
  332. package/src/services/session-pool.d.ts +72 -0
  333. package/src/services/session-pool.d.ts.map +1 -0
  334. package/src/services/session-pool.ts +153 -0
  335. package/src/services/structured-output/deterministic-repair.d.ts +23 -0
  336. package/src/services/structured-output/deterministic-repair.d.ts.map +1 -0
  337. package/src/services/structured-output/deterministic-repair.test.ts +169 -0
  338. package/src/services/structured-output/deterministic-repair.ts +443 -0
  339. package/src/services/structured-output/index.ts +4 -0
  340. package/src/services/structured-output.d.ts +311 -0
  341. package/src/services/structured-output.d.ts.map +1 -0
  342. package/src/services/structured-output.test.ts +483 -0
  343. package/src/services/structured-output.ts +712 -0
  344. package/src/services/transcription-priority.test.ts +211 -0
  345. package/src/services/tts/errors.ts +46 -0
  346. package/src/services/tts/index.ts +214 -0
  347. package/src/services/tts/tts-audio-cache.ts +235 -0
  348. package/src/services/tts/types.ts +157 -0
  349. package/src/services/types.d.ts +19 -0
  350. package/src/services/types.d.ts.map +1 -0
  351. package/src/services/types.ts +55 -0
  352. package/src/services/verify-on-device.d.ts +34 -0
  353. package/src/services/verify-on-device.d.ts.map +1 -0
  354. package/src/services/verify-on-device.test.ts +87 -0
  355. package/src/services/verify-on-device.ts +127 -0
  356. package/src/services/verify.d.ts +8 -0
  357. package/src/services/verify.d.ts.map +1 -0
  358. package/src/services/verify.ts +13 -0
  359. package/src/services/vision/aosp-unavailable.d.ts +115 -0
  360. package/src/services/vision/aosp-unavailable.d.ts.map +1 -0
  361. package/src/services/vision/aosp-unavailable.ts +163 -0
  362. package/src/services/vision/capacitor-llama.d.ts +99 -0
  363. package/src/services/vision/capacitor-llama.d.ts.map +1 -0
  364. package/src/services/vision/capacitor-llama.ts +255 -0
  365. package/src/services/vision/cloud-fallback.d.ts +47 -0
  366. package/src/services/vision/cloud-fallback.d.ts.map +1 -0
  367. package/src/services/vision/cloud-fallback.test.ts +243 -0
  368. package/src/services/vision/cloud-fallback.ts +268 -0
  369. package/src/services/vision/fallback-chain.test.ts +86 -0
  370. package/src/services/vision/hash.d.ts +71 -0
  371. package/src/services/vision/hash.d.ts.map +1 -0
  372. package/src/services/vision/hash.ts +157 -0
  373. package/src/services/vision/index.d.ts +95 -0
  374. package/src/services/vision/index.d.ts.map +1 -0
  375. package/src/services/vision/index.ts +251 -0
  376. package/src/services/vision/llama-server.d.ts +73 -0
  377. package/src/services/vision/llama-server.d.ts.map +1 -0
  378. package/src/services/vision/llama-server.ts +177 -0
  379. package/src/services/vision/types.d.ts +153 -0
  380. package/src/services/vision/types.d.ts.map +1 -0
  381. package/src/services/vision/types.ts +154 -0
  382. package/src/services/vision/vast-fallback.d.ts +18 -0
  383. package/src/services/vision/vast-fallback.d.ts.map +1 -0
  384. package/src/services/vision/vast-fallback.ts +127 -0
  385. package/src/services/vision-embedding-cache.d.ts +98 -0
  386. package/src/services/vision-embedding-cache.d.ts.map +1 -0
  387. package/src/services/vision-embedding-cache.ts +189 -0
  388. package/src/services/voice/VOICE_WORKBENCH.md +88 -0
  389. package/src/services/voice/__test-helpers__/fake-ffi.ts +92 -0
  390. package/src/services/voice/__test-helpers__/synthetic-speech.ts +124 -0
  391. package/src/services/voice/__tests__/checkpoint-manager.test.ts +241 -0
  392. package/src/services/voice/__tests__/checkpoint-policy.test.ts +270 -0
  393. package/src/services/voice/__tests__/eager-context-builder.test.ts +257 -0
  394. package/src/services/voice/__tests__/eliza1-eot-scorer.test.ts +288 -0
  395. package/src/services/voice/__tests__/eot-classifier.test.ts +431 -0
  396. package/src/services/voice/__tests__/optimistic-rollback.test.ts +312 -0
  397. package/src/services/voice/__tests__/prefill-client.test.ts +266 -0
  398. package/src/services/voice/__tests__/prefix-preserving-queue.test.ts +208 -0
  399. package/src/services/voice/__tests__/streaming-asr.test.ts +450 -0
  400. package/src/services/voice/__tests__/streaming-transcriber.test.ts +339 -0
  401. package/src/services/voice/__tests__/turn-detector-resolver.test.ts +197 -0
  402. package/src/services/voice/__tests__/voice-state-machine-prefill.test.ts +275 -0
  403. package/src/services/voice/__tests__/voice-state-machine.test.ts +354 -0
  404. package/src/services/voice/audio-frame-consumer.d.ts +212 -0
  405. package/src/services/voice/audio-frame-consumer.d.ts.map +1 -0
  406. package/src/services/voice/audio-frame-consumer.test.ts +343 -0
  407. package/src/services/voice/audio-frame-consumer.ts +491 -0
  408. package/src/services/voice/barge-in.d.ts +112 -0
  409. package/src/services/voice/barge-in.d.ts.map +1 -0
  410. package/src/services/voice/barge-in.test.ts +244 -0
  411. package/src/services/voice/barge-in.ts +336 -0
  412. package/src/services/voice/cancellation-coordinator.d.ts +127 -0
  413. package/src/services/voice/cancellation-coordinator.d.ts.map +1 -0
  414. package/src/services/voice/cancellation-coordinator.test.ts +196 -0
  415. package/src/services/voice/cancellation-coordinator.ts +269 -0
  416. package/src/services/voice/checkpoint-manager.d.ts +199 -0
  417. package/src/services/voice/checkpoint-manager.d.ts.map +1 -0
  418. package/src/services/voice/checkpoint-manager.ts +401 -0
  419. package/src/services/voice/checkpoint-policy.ts +336 -0
  420. package/src/services/voice/composite-eot-classifier.test.ts +59 -0
  421. package/src/services/voice/e2e-harness.test.ts +182 -0
  422. package/src/services/voice/e2e-harness.ts +743 -0
  423. package/src/services/voice/eager-context-builder.d.ts +170 -0
  424. package/src/services/voice/eager-context-builder.d.ts.map +1 -0
  425. package/src/services/voice/eager-context-builder.ts +262 -0
  426. package/src/services/voice/eliza1-eot-scorer.d.ts +124 -0
  427. package/src/services/voice/eliza1-eot-scorer.d.ts.map +1 -0
  428. package/src/services/voice/eliza1-eot-scorer.ts +242 -0
  429. package/src/services/voice/embedding-server.ts +200 -0
  430. package/src/services/voice/embedding.d.ts +133 -0
  431. package/src/services/voice/embedding.d.ts.map +1 -0
  432. package/src/services/voice/embedding.test.ts +148 -0
  433. package/src/services/voice/embedding.ts +244 -0
  434. package/src/services/voice/emotion-attribution.d.ts +68 -0
  435. package/src/services/voice/emotion-attribution.d.ts.map +1 -0
  436. package/src/services/voice/emotion-attribution.test.ts +129 -0
  437. package/src/services/voice/emotion-attribution.ts +361 -0
  438. package/src/services/voice/engine-bridge-cancellation.test.ts +422 -0
  439. package/src/services/voice/engine-bridge.d.ts +746 -0
  440. package/src/services/voice/engine-bridge.d.ts.map +1 -0
  441. package/src/services/voice/engine-bridge.test.ts +384 -0
  442. package/src/services/voice/engine-bridge.ts +2226 -0
  443. package/src/services/voice/eot-classifier-ggml.d.ts +179 -0
  444. package/src/services/voice/eot-classifier-ggml.d.ts.map +1 -0
  445. package/src/services/voice/eot-classifier-ggml.ts +566 -0
  446. package/src/services/voice/eot-classifier.d.ts +214 -0
  447. package/src/services/voice/eot-classifier.d.ts.map +1 -0
  448. package/src/services/voice/eot-classifier.ts +533 -0
  449. package/src/services/voice/errors.d.ts +20 -0
  450. package/src/services/voice/errors.d.ts.map +1 -0
  451. package/src/services/voice/errors.ts +32 -0
  452. package/src/services/voice/expressive-tags.d.ts +158 -0
  453. package/src/services/voice/expressive-tags.d.ts.map +1 -0
  454. package/src/services/voice/expressive-tags.ts +405 -0
  455. package/src/services/voice/ffi-bindings.d.ts +636 -0
  456. package/src/services/voice/ffi-bindings.d.ts.map +1 -0
  457. package/src/services/voice/ffi-bindings.test.ts +671 -0
  458. package/src/services/voice/ffi-bindings.ts +3050 -0
  459. package/src/services/voice/first-line-cache.d.ts +181 -0
  460. package/src/services/voice/first-line-cache.d.ts.map +1 -0
  461. package/src/services/voice/first-line-cache.ts +725 -0
  462. package/src/services/voice/fused-eot-scorer.d.ts +51 -0
  463. package/src/services/voice/fused-eot-scorer.d.ts.map +1 -0
  464. package/src/services/voice/fused-eot-scorer.ts +135 -0
  465. package/src/services/voice/index.d.ts +91 -0
  466. package/src/services/voice/index.d.ts.map +1 -0
  467. package/src/services/voice/index.ts +481 -0
  468. package/src/services/voice/kokoro/__tests__/kokoro-backend.test.ts +151 -0
  469. package/src/services/voice/kokoro/__tests__/kokoro-engine-bridge.real.test.ts +151 -0
  470. package/src/services/voice/kokoro/__tests__/kokoro-engine-bridge.test.ts +60 -0
  471. package/src/services/voice/kokoro/__tests__/kokoro-engine-discovery.test.ts +277 -0
  472. package/src/services/voice/kokoro/__tests__/kokoro-ffi-runtime.test.ts +235 -0
  473. package/src/services/voice/kokoro/__tests__/kokoro-runtime.test.ts +95 -0
  474. package/src/services/voice/kokoro/__tests__/phonemizer.test.ts +53 -0
  475. package/src/services/voice/kokoro/__tests__/runtime-selection.test.ts +231 -0
  476. package/src/services/voice/kokoro/__tests__/voices.test.ts +57 -0
  477. package/src/services/voice/kokoro/index.ts +79 -0
  478. package/src/services/voice/kokoro/kokoro-backend.d.ts +72 -0
  479. package/src/services/voice/kokoro/kokoro-backend.d.ts.map +1 -0
  480. package/src/services/voice/kokoro/kokoro-backend.ts +207 -0
  481. package/src/services/voice/kokoro/kokoro-engine-discovery.d.ts +58 -0
  482. package/src/services/voice/kokoro/kokoro-engine-discovery.d.ts.map +1 -0
  483. package/src/services/voice/kokoro/kokoro-engine-discovery.ts +177 -0
  484. package/src/services/voice/kokoro/kokoro-ffi-runtime.d.ts +75 -0
  485. package/src/services/voice/kokoro/kokoro-ffi-runtime.d.ts.map +1 -0
  486. package/src/services/voice/kokoro/kokoro-ffi-runtime.ts +233 -0
  487. package/src/services/voice/kokoro/kokoro-runtime.d.ts +100 -0
  488. package/src/services/voice/kokoro/kokoro-runtime.d.ts.map +1 -0
  489. package/src/services/voice/kokoro/kokoro-runtime.ts +170 -0
  490. package/src/services/voice/kokoro/phoneme-stream.ts +123 -0
  491. package/src/services/voice/kokoro/phonemizer.d.ts +50 -0
  492. package/src/services/voice/kokoro/phonemizer.d.ts.map +1 -0
  493. package/src/services/voice/kokoro/phonemizer.ts +344 -0
  494. package/src/services/voice/kokoro/pick-runtime.d.ts +61 -0
  495. package/src/services/voice/kokoro/pick-runtime.d.ts.map +1 -0
  496. package/src/services/voice/kokoro/pick-runtime.test.ts +91 -0
  497. package/src/services/voice/kokoro/pick-runtime.ts +130 -0
  498. package/src/services/voice/kokoro/runtime-selection.d.ts +92 -0
  499. package/src/services/voice/kokoro/runtime-selection.d.ts.map +1 -0
  500. package/src/services/voice/kokoro/runtime-selection.ts +237 -0
  501. package/src/services/voice/kokoro/types.d.ts +82 -0
  502. package/src/services/voice/kokoro/types.d.ts.map +1 -0
  503. package/src/services/voice/kokoro/types.ts +95 -0
  504. package/src/services/voice/kokoro/voice-presets.d.ts +23 -0
  505. package/src/services/voice/kokoro/voice-presets.d.ts.map +1 -0
  506. package/src/services/voice/kokoro/voice-presets.ts +129 -0
  507. package/src/services/voice/kokoro/voices.d.ts +30 -0
  508. package/src/services/voice/kokoro/voices.d.ts.map +1 -0
  509. package/src/services/voice/kokoro/voices.ts +64 -0
  510. package/src/services/voice/lifecycle.d.ts +135 -0
  511. package/src/services/voice/lifecycle.d.ts.map +1 -0
  512. package/src/services/voice/lifecycle.test.ts +315 -0
  513. package/src/services/voice/lifecycle.ts +301 -0
  514. package/src/services/voice/live-diarization-session.d.ts +96 -0
  515. package/src/services/voice/live-diarization-session.d.ts.map +1 -0
  516. package/src/services/voice/live-diarization-session.ts +289 -0
  517. package/src/services/voice/mic-source.d.ts +136 -0
  518. package/src/services/voice/mic-source.d.ts.map +1 -0
  519. package/src/services/voice/mic-source.test.ts +210 -0
  520. package/src/services/voice/mic-source.ts +503 -0
  521. package/src/services/voice/optimistic-policy.d.ts +109 -0
  522. package/src/services/voice/optimistic-policy.d.ts.map +1 -0
  523. package/src/services/voice/optimistic-policy.test.ts +101 -0
  524. package/src/services/voice/optimistic-policy.ts +192 -0
  525. package/src/services/voice/optimistic-rollback.ts +343 -0
  526. package/src/services/voice/partial-stabilizer.d.ts +73 -0
  527. package/src/services/voice/partial-stabilizer.d.ts.map +1 -0
  528. package/src/services/voice/partial-stabilizer.test.ts +68 -0
  529. package/src/services/voice/partial-stabilizer.ts +140 -0
  530. package/src/services/voice/phoneme-tokenizer.d.ts +49 -0
  531. package/src/services/voice/phoneme-tokenizer.d.ts.map +1 -0
  532. package/src/services/voice/phoneme-tokenizer.ts +158 -0
  533. package/src/services/voice/phrase-cache.d.ts +76 -0
  534. package/src/services/voice/phrase-cache.d.ts.map +1 -0
  535. package/src/services/voice/phrase-cache.test.ts +242 -0
  536. package/src/services/voice/phrase-cache.ts +186 -0
  537. package/src/services/voice/phrase-chunker.d.ts +62 -0
  538. package/src/services/voice/phrase-chunker.d.ts.map +1 -0
  539. package/src/services/voice/phrase-chunker.test.ts +239 -0
  540. package/src/services/voice/phrase-chunker.ts +281 -0
  541. package/src/services/voice/pipeline-impls.d.ts +151 -0
  542. package/src/services/voice/pipeline-impls.d.ts.map +1 -0
  543. package/src/services/voice/pipeline-impls.l6.test.ts +110 -0
  544. package/src/services/voice/pipeline-impls.test.ts +292 -0
  545. package/src/services/voice/pipeline-impls.ts +315 -0
  546. package/src/services/voice/pipeline.d.ts +216 -0
  547. package/src/services/voice/pipeline.d.ts.map +1 -0
  548. package/src/services/voice/pipeline.ts +505 -0
  549. package/src/services/voice/prefill-client.d.ts +123 -0
  550. package/src/services/voice/prefill-client.d.ts.map +1 -0
  551. package/src/services/voice/prefill-client.ts +316 -0
  552. package/src/services/voice/prefix-preserving-queue.d.ts +113 -0
  553. package/src/services/voice/prefix-preserving-queue.d.ts.map +1 -0
  554. package/src/services/voice/prefix-preserving-queue.ts +162 -0
  555. package/src/services/voice/profile-store.d.ts +248 -0
  556. package/src/services/voice/profile-store.d.ts.map +1 -0
  557. package/src/services/voice/profile-store.ts +887 -0
  558. package/src/services/voice/ring-buffer.d.ts +40 -0
  559. package/src/services/voice/ring-buffer.d.ts.map +1 -0
  560. package/src/services/voice/ring-buffer.ts +105 -0
  561. package/src/services/voice/rollback-queue.d.ts +24 -0
  562. package/src/services/voice/rollback-queue.d.ts.map +1 -0
  563. package/src/services/voice/rollback-queue.ts +74 -0
  564. package/src/services/voice/samantha-preset-placeholder.d.ts +67 -0
  565. package/src/services/voice/samantha-preset-placeholder.d.ts.map +1 -0
  566. package/src/services/voice/samantha-preset-placeholder.test.ts +97 -0
  567. package/src/services/voice/samantha-preset-placeholder.ts +148 -0
  568. package/src/services/voice/samantha-preset-regenerator.d.ts +87 -0
  569. package/src/services/voice/samantha-preset-regenerator.d.ts.map +1 -0
  570. package/src/services/voice/samantha-preset-regenerator.ts +393 -0
  571. package/src/services/voice/scheduler.d.ts +146 -0
  572. package/src/services/voice/scheduler.d.ts.map +1 -0
  573. package/src/services/voice/scheduler.t2.test.ts +141 -0
  574. package/src/services/voice/scheduler.ts +927 -0
  575. package/src/services/voice/shared-resources.d.ts +190 -0
  576. package/src/services/voice/shared-resources.d.ts.map +1 -0
  577. package/src/services/voice/shared-resources.ts +320 -0
  578. package/src/services/voice/speaker/attribution-pipeline.d.ts +74 -0
  579. package/src/services/voice/speaker/attribution-pipeline.d.ts.map +1 -0
  580. package/src/services/voice/speaker/attribution-pipeline.ts +386 -0
  581. package/src/services/voice/speaker/diarizer-fused.d.ts +59 -0
  582. package/src/services/voice/speaker/diarizer-fused.d.ts.map +1 -0
  583. package/src/services/voice/speaker/diarizer-fused.real.test.ts +100 -0
  584. package/src/services/voice/speaker/diarizer-fused.ts +154 -0
  585. package/src/services/voice/speaker/diarizer.d.ts +75 -0
  586. package/src/services/voice/speaker/diarizer.d.ts.map +1 -0
  587. package/src/services/voice/speaker/diarizer.ts +218 -0
  588. package/src/services/voice/speaker/encoder-fused.d.ts +60 -0
  589. package/src/services/voice/speaker/encoder-fused.d.ts.map +1 -0
  590. package/src/services/voice/speaker/encoder-fused.real.test.ts +113 -0
  591. package/src/services/voice/speaker/encoder-fused.ts +138 -0
  592. package/src/services/voice/speaker/encoder-ggml.d.ts +33 -0
  593. package/src/services/voice/speaker/encoder-ggml.d.ts.map +1 -0
  594. package/src/services/voice/speaker/encoder-ggml.ts +79 -0
  595. package/src/services/voice/speaker/encoder.d.ts +37 -0
  596. package/src/services/voice/speaker/encoder.d.ts.map +1 -0
  597. package/src/services/voice/speaker/encoder.ts +105 -0
  598. package/src/services/voice/speaker-imprint.d.ts +83 -0
  599. package/src/services/voice/speaker-imprint.d.ts.map +1 -0
  600. package/src/services/voice/speaker-imprint.test.ts +185 -0
  601. package/src/services/voice/speaker-imprint.ts +312 -0
  602. package/src/services/voice/speaker-preset-cache.d.ts +77 -0
  603. package/src/services/voice/speaker-preset-cache.d.ts.map +1 -0
  604. package/src/services/voice/speaker-preset-cache.test.ts +154 -0
  605. package/src/services/voice/speaker-preset-cache.ts +195 -0
  606. package/src/services/voice/streaming-asr/streaming-pipeline-adapter.ts +292 -0
  607. package/src/services/voice/system-audio-sink.d.ts +73 -0
  608. package/src/services/voice/system-audio-sink.d.ts.map +1 -0
  609. package/src/services/voice/system-audio-sink.test.ts +29 -0
  610. package/src/services/voice/system-audio-sink.ts +366 -0
  611. package/src/services/voice/transcriber.d.ts +244 -0
  612. package/src/services/voice/transcriber.d.ts.map +1 -0
  613. package/src/services/voice/transcriber.test.ts +392 -0
  614. package/src/services/voice/transcriber.ts +704 -0
  615. package/src/services/voice/turn-controller.d.ts +183 -0
  616. package/src/services/voice/turn-controller.d.ts.map +1 -0
  617. package/src/services/voice/turn-controller.test.ts +575 -0
  618. package/src/services/voice/turn-controller.ts +596 -0
  619. package/src/services/voice/types.d.ts +643 -0
  620. package/src/services/voice/types.d.ts.map +1 -0
  621. package/src/services/voice/types.ts +699 -0
  622. package/src/services/voice/vad.d.ts +282 -0
  623. package/src/services/voice/vad.d.ts.map +1 -0
  624. package/src/services/voice/vad.test.ts +480 -0
  625. package/src/services/voice/vad.ts +827 -0
  626. package/src/services/voice/vad.v1-v4.test.ts +222 -0
  627. package/src/services/voice/voice-budget.d.ts +241 -0
  628. package/src/services/voice/voice-budget.d.ts.map +1 -0
  629. package/src/services/voice/voice-budget.test.ts +420 -0
  630. package/src/services/voice/voice-budget.ts +656 -0
  631. package/src/services/voice/voice-duet.test.ts +375 -0
  632. package/src/services/voice/voice-emotion-classifier.d.ts +95 -0
  633. package/src/services/voice/voice-emotion-classifier.d.ts.map +1 -0
  634. package/src/services/voice/voice-emotion-classifier.test.ts +210 -0
  635. package/src/services/voice/voice-emotion-classifier.ts +273 -0
  636. package/src/services/voice/voice-preset-format.d.ts +158 -0
  637. package/src/services/voice/voice-preset-format.d.ts.map +1 -0
  638. package/src/services/voice/voice-preset-format.ts +700 -0
  639. package/src/services/voice/voice-preset-generator.test.ts +89 -0
  640. package/src/services/voice/voice-profile-artifact.d.ts +116 -0
  641. package/src/services/voice/voice-profile-artifact.d.ts.map +1 -0
  642. package/src/services/voice/voice-profile-artifact.test.ts +138 -0
  643. package/src/services/voice/voice-profile-artifact.ts +518 -0
  644. package/src/services/voice/voice-profile-routes.d.ts +83 -0
  645. package/src/services/voice/voice-profile-routes.d.ts.map +1 -0
  646. package/src/services/voice/voice-profile-routes.test.ts +429 -0
  647. package/src/services/voice/voice-profile-routes.ts +425 -0
  648. package/src/services/voice/voice-scenario.ts +154 -0
  649. package/src/services/voice/voice-settings.d.ts +82 -0
  650. package/src/services/voice/voice-settings.d.ts.map +1 -0
  651. package/src/services/voice/voice-settings.ts +172 -0
  652. package/src/services/voice/voice-state-machine.d.ts +364 -0
  653. package/src/services/voice/voice-state-machine.d.ts.map +1 -0
  654. package/src/services/voice/voice-state-machine.ts +727 -0
  655. package/src/services/voice/voice-workbench-report.test.ts +168 -0
  656. package/src/services/voice/voice-workbench-report.ts +326 -0
  657. package/src/services/voice/voice-workbench.test.ts +158 -0
  658. package/src/services/voice/voice.test.ts +1070 -0
  659. package/src/services/voice/wake-word-ggml.d.ts +101 -0
  660. package/src/services/voice/wake-word-ggml.d.ts.map +1 -0
  661. package/src/services/voice/wake-word-ggml.ts +320 -0
  662. package/src/services/voice/wake-word.d.ts +255 -0
  663. package/src/services/voice/wake-word.d.ts.map +1 -0
  664. package/src/services/voice/wake-word.test.ts +298 -0
  665. package/src/services/voice/wake-word.ts +554 -0
  666. package/src/services/voice/wrap-with-first-line-cache.d.ts +70 -0
  667. package/src/services/voice/wrap-with-first-line-cache.d.ts.map +1 -0
  668. package/src/services/voice/wrap-with-first-line-cache.ts +267 -0
  669. package/src/services/voice-model-updater.d.ts +240 -0
  670. package/src/services/voice-model-updater.d.ts.map +1 -0
  671. package/src/services/voice-model-updater.ts +724 -0
  672. package/src/services/voice-prewarm.d.ts +3 -0
  673. package/src/services/voice-prewarm.d.ts.map +1 -0
  674. package/src/services/voice-prewarm.ts +51 -0
  675. package/dist/index.d.ts +0 -37
  676. package/dist/index.js +0 -1098
@@ -0,0 +1,1891 @@
1
+ /**
2
+ * Standalone llama.cpp engine.
3
+ *
4
+ * Fronts the in-process FFI backend (fused `libelizainference`, or the
5
+ * libllama + eliza-llama-shim fallback) via the `BackendDispatcher`. At most
6
+ * one model is loaded at a time — model swap is unload-then-load so we never
7
+ * double-allocate VRAM.
8
+ *
9
+ * Two consumption paths:
10
+ * 1. The Model Hub UI calls `load()` / `unload()` to make "Activate" work.
11
+ * 2. The agent runtime calls `generate()` via the registered
12
+ * `ModelType.TEXT_SMALL` / `TEXT_LARGE` handlers (see
13
+ * `ensure-local-inference-handler.ts`).
14
+ */
15
+
16
+ import path from "node:path";
17
+ import {
18
+ logger,
19
+ type ResponseSkeleton,
20
+ ResponseSkeletonStreamExtractor,
21
+ } from "@elizaos/core";
22
+ import { isMobilePlatform } from "@elizaos/shared";
23
+ import type { LocalInferenceLoadArgs } from "./active-model";
24
+ import { readEffectiveAssignments } from "./assignments";
25
+ import type {
26
+ GenerateArgs as BackendGenerateArgs,
27
+ BackendPlan,
28
+ LocalGenerateWithUsageResult,
29
+ LocalRuntimeLoadConfig,
30
+ } from "./backend";
31
+ import { BackendDispatcher } from "./backend";
32
+ import {
33
+ ELIZA_1_PLACEHOLDER_IDS,
34
+ type Eliza1TierId,
35
+ findCatalogModel,
36
+ } from "./catalog";
37
+ import {
38
+ type ConversationHandle,
39
+ conversationRegistry,
40
+ } from "./conversation-registry";
41
+ import { desktopFusedFfiBackendRuntime } from "./desktop-fused-ffi-backend-runtime";
42
+ import { FfiStreamingBackend } from "./ffi-streaming-backend";
43
+ import { MemoryMonitor } from "./memory-monitor";
44
+ import { listInstalledModels } from "./registry";
45
+ import { resolveDefaultPoolSize } from "./session-pool";
46
+ import type { InstalledModel } from "./types";
47
+ import type { CoordinatorRuntime } from "./voice/cancellation-coordinator";
48
+ import {
49
+ createKokoroSpeakerPreset,
50
+ createKokoroTtsBackend,
51
+ EngineVoiceBridge,
52
+ type EngineVoiceBridgeOptions,
53
+ isOmniVoiceBundleAvailable,
54
+ VoiceStartupError,
55
+ } from "./voice/engine-bridge";
56
+ import { resolveKokoroEngineConfig } from "./voice/kokoro/kokoro-engine-discovery";
57
+ import {
58
+ readVoiceBackendModeFromEnv,
59
+ selectVoiceBackend,
60
+ type VoiceBackendChoice,
61
+ } from "./voice/kokoro/runtime-selection";
62
+ import type { VoicePipelineEvents } from "./voice/pipeline";
63
+ import { type MtpTextRunner, mtpTextRunner } from "./voice/pipeline-impls";
64
+ import {
65
+ createEvictableModelRole,
66
+ SharedResourceRegistry,
67
+ } from "./voice/shared-resources";
68
+ import type {
69
+ RejectedTokenRange,
70
+ TextToken,
71
+ TranscriptionAudio,
72
+ VerifierStreamEvent,
73
+ } from "./voice/types";
74
+
75
+ /**
76
+ * Default MTP draft window per round for voice turns. Small (≤8) so a
77
+ * rollback is cheap (AGENTS.md §4 — "small chunk = low latency cost on
78
+ * rollback"). Overridable per call via `runVoiceTurn({ maxDraftTokens })`.
79
+ */
80
+ const DEFAULT_VOICE_MAX_DRAFT_TOKENS = 8;
81
+ export interface LocalUsageBlock {
82
+ [key: string]: unknown;
83
+ input_tokens: number;
84
+ output_tokens: number;
85
+ cache_creation_input_tokens: number;
86
+ cache_read_input_tokens: number;
87
+ mtp_drafted_tokens?: number;
88
+ mtp_accepted_tokens?: number;
89
+ mtp_acceptance_rate?: number;
90
+ cache_hit_rate?: number;
91
+ }
92
+ const DEFAULT_VOICE_SKELETON_STREAM_FIELDS = new Set([
93
+ "replyText",
94
+ "text",
95
+ "messageToUser",
96
+ ]);
97
+
98
+ function resolveVoiceSkeletonStreamFields(
99
+ skeleton: ResponseSkeleton | undefined,
100
+ ): string[] {
101
+ if (!skeleton) return [];
102
+ const fields: string[] = [];
103
+ const seen = new Set<string>();
104
+ for (const span of skeleton.spans) {
105
+ const key = span.key;
106
+ if (
107
+ span.kind === "free-string" &&
108
+ key &&
109
+ DEFAULT_VOICE_SKELETON_STREAM_FIELDS.has(key) &&
110
+ !seen.has(key)
111
+ ) {
112
+ seen.add(key);
113
+ fields.push(key);
114
+ }
115
+ }
116
+ return fields;
117
+ }
118
+
119
+ function skeletonHasFreeStringKey(
120
+ skeleton: ResponseSkeleton | undefined,
121
+ key: string,
122
+ ): boolean {
123
+ return (
124
+ skeleton?.spans.some(
125
+ (span) => span.kind === "free-string" && span.key === key,
126
+ ) ?? false
127
+ );
128
+ }
129
+
130
+ /**
131
+ * Idle-unload timeout (J3). After this long with no `useModel` activity
132
+ * (text generation, embeddings, voice turns) the engine unloads the active
133
+ * text model so its weights are reclaimed when the agent is quiet; the next
134
+ * `useModel` lazy-reloads via the runtime handler. `0` disables it. Default
135
+ * 15 minutes. Override via `ELIZA_LOCAL_IDLE_UNLOAD_MS`.
136
+ */
137
+ const DEFAULT_IDLE_UNLOAD_MS = 15 * 60 * 1000;
138
+ /** How often the idle-unload timer checks the activity clock. */
139
+ const IDLE_UNLOAD_CHECK_INTERVAL_MS = 60 * 1000;
140
+
141
+ export function resolveIdleUnloadMs(): number {
142
+ const raw = process.env.ELIZA_LOCAL_IDLE_UNLOAD_MS?.trim();
143
+ if (raw === undefined) return DEFAULT_IDLE_UNLOAD_MS;
144
+ const parsed = Number.parseInt(raw, 10);
145
+ if (!Number.isFinite(parsed) || parsed < 0) return DEFAULT_IDLE_UNLOAD_MS;
146
+ return parsed;
147
+ }
148
+
149
+ /**
150
+ * Cap on how many speculative voice responses the turn-controller (W9) may
151
+ * have in flight at once — derived from the running server's slot count
152
+ * (each speculative response needs a slot's KV) but never more than half of
153
+ * them (the other half stays available for confirmed turns + tool calls).
154
+ * Floors at 1. Override via `ELIZA_LOCAL_MAX_SPECULATIVE_RESPONSES`.
155
+ */
156
+ export function resolveMaxConcurrentSpeculativeResponses(
157
+ parallelSlots: number,
158
+ ): number {
159
+ const raw = process.env.ELIZA_LOCAL_MAX_SPECULATIVE_RESPONSES?.trim();
160
+ if (raw) {
161
+ const parsed = Number.parseInt(raw, 10);
162
+ if (Number.isFinite(parsed) && parsed >= 1) return parsed;
163
+ }
164
+ return Math.max(1, Math.floor(parallelSlots / 2));
165
+ }
166
+
167
+ // Re-export of backend.ts's canonical GenerateArgs shape, including the
168
+ // optional `cacheKey` for prefix reuse via the session pool.
169
+ export type GenerateArgs = BackendGenerateArgs;
170
+
171
+ /**
172
+ * Resolve the active Eliza-1 bundle (root dir + tier id) from an
173
+ * `InstalledModel`, or `null` when the model is not an Eliza-1 bundle. An
174
+ * Eliza-1 InstalledModel carries `bundleRoot` and an `eliza-1-<tier>` id
175
+ * (the catalog seed ids). Drives the local-embedding route.
176
+ */
177
+ interface ActiveEliza1Bundle {
178
+ root: string;
179
+ tierId: Eliza1TierId;
180
+ voiceBackends?: ReadonlyArray<VoiceBackendChoice>;
181
+ }
182
+
183
+ function resolveActiveEliza1Bundle(
184
+ target: InstalledModel | undefined,
185
+ catalog: ReturnType<typeof findCatalogModel>,
186
+ ): ActiveEliza1Bundle | null {
187
+ if (!target?.bundleRoot) return null;
188
+ if (!ELIZA_1_PLACEHOLDER_IDS.has(target.id)) return null;
189
+ return {
190
+ root: target.bundleRoot,
191
+ tierId: target.id as Eliza1TierId,
192
+ voiceBackends: catalog?.voiceBackends,
193
+ };
194
+ }
195
+
196
+ function resolveDirectEliza1Bundle(
197
+ args: LocalInferenceLoadArgs | undefined,
198
+ catalog: ReturnType<typeof findCatalogModel>,
199
+ ): ActiveEliza1Bundle | null {
200
+ if (!args?.modelId || !ELIZA_1_PLACEHOLDER_IDS.has(args.modelId)) return null;
201
+ return {
202
+ root: path.dirname(path.dirname(args.modelPath)),
203
+ tierId: args.modelId as Eliza1TierId,
204
+ voiceBackends: catalog?.voiceBackends,
205
+ };
206
+ }
207
+
208
+ /**
209
+ * Project a fully-resolved `LocalInferenceLoadArgs` onto the subset that
210
+ * the dispatcher cares about. Keeps `BackendLoadOverrides` framework-free
211
+ * (no dependency on active-model.ts here) so backend.ts and engine.ts stay
212
+ * cycle-free.
213
+ */
214
+ function toBackendLoadOverrides(
215
+ args: LocalInferenceLoadArgs,
216
+ ): BackendPlan["overrides"] {
217
+ const overrides: BackendPlan["overrides"] = {};
218
+ if (args.contextSize !== undefined) overrides.contextSize = args.contextSize;
219
+ if (args.cacheTypeK !== undefined) overrides.cacheTypeK = args.cacheTypeK;
220
+ if (args.cacheTypeV !== undefined) overrides.cacheTypeV = args.cacheTypeV;
221
+ if (args.gpuLayers !== undefined) overrides.gpuLayers = args.gpuLayers;
222
+ if (args.kvOffload !== undefined) overrides.kvOffload = args.kvOffload;
223
+ if (args.flashAttention !== undefined) {
224
+ overrides.flashAttention = args.flashAttention;
225
+ }
226
+ if (args.mmap !== undefined) overrides.mmap = args.mmap;
227
+ if (args.mlock !== undefined) overrides.mlock = args.mlock;
228
+ if (args.useGpu !== undefined) overrides.useGpu = args.useGpu;
229
+ if (args.mmprojPath !== undefined) overrides.mmprojPath = args.mmprojPath;
230
+ if (args.draftModelPath !== undefined) {
231
+ overrides.draftModelPath = args.draftModelPath;
232
+ }
233
+ if (args.modelId?.startsWith("eliza-1-")) {
234
+ const bundleRoot = path.dirname(path.dirname(args.modelPath));
235
+ overrides.bundleRoot = bundleRoot;
236
+ overrides.manifestPath = path.join(bundleRoot, "eliza-1.manifest.json");
237
+ }
238
+ return overrides;
239
+ }
240
+
241
+ /**
242
+ * Public engine facade.
243
+ *
244
+ * Pre-existing API: `load(modelPath)`, `unload()`, `generate(args)`,
245
+ * plus the activity probes used by router/handler/active-model code. The
246
+ * implementation now sits behind the backend dispatcher; the
247
+ * shape is preserved so callers (active-model, router-handler, the agent
248
+ * runtime handler) keep working unchanged.
249
+ *
250
+ * MTP now lives in the normal optimized llama.cpp backend path. The
251
+ * dispatcher's decision tree picks `llama-cpp` when a kernel is required
252
+ * or when the catalog prefers optimized llama.cpp.
253
+ */
254
+ export class LocalInferenceEngine {
255
+ /**
256
+ * In-process FFI backend — the sole text runtime, served by the FUSED
257
+ * `libelizainference` (`desktop-fused-ffi-backend-runtime.ts`). Text gen,
258
+ * same-file MTP speculative decoding, KV-cache quant, native tokenization,
259
+ * and vision-describe all run through the one fused lib the voice subsystem
260
+ * already loads (ABI v9). libllama has been retired: a fused lib that is
261
+ * absent or lacks the v9 capabilities is a loud `LocalInferenceUnavailable`
262
+ * error, never a silent fallback. There is no server fallback for Eliza-1.
263
+ */
264
+ private readonly ffiBackend = new FfiStreamingBackend(
265
+ desktopFusedFfiBackendRuntime,
266
+ );
267
+ private readonly dispatcher = new BackendDispatcher(
268
+ this.ffiBackend,
269
+ () => desktopFusedFfiBackendRuntime.supported(),
270
+ () => null,
271
+ );
272
+ /**
273
+ * Active voice-streaming bridge (`EngineVoiceBridge`). Only set when an
274
+ * Eliza-1 bundle has been activated AND `startVoice()` has succeeded —
275
+ * see `packages/inference/AGENTS.md` §3 + §4. The engine never lazily
276
+ * stands up a voice session: callers either start it explicitly or get
277
+ * a hard error.
278
+ */
279
+ private voiceBridge: EngineVoiceBridge | null = null;
280
+ private voiceReadyPromise: Promise<EngineVoiceBridge> | null = null;
281
+
282
+ /**
283
+ * The general onload/offload coordinator (W10 / J5). One registry per
284
+ * engine: text + voice both ref-count their shared resources against it,
285
+ * and every resident model role registers an `EvictableModelRole` here so
286
+ * the `MemoryMonitor` can walk them ascending-priority under RAM pressure.
287
+ * The voice bridge gets this passed in (see `startVoice`) so it doesn't
288
+ * spin up a private one.
289
+ */
290
+ private readonly sharedResources = new SharedResourceRegistry({
291
+ logger: {
292
+ debug: (m) => console.debug(m),
293
+ warn: (m) => console.warn(m),
294
+ info: (m) => console.info(m),
295
+ },
296
+ });
297
+
298
+ /**
299
+ * RAM-pressure monitor (J2). Started when a model loads, stopped when the
300
+ * engine unloads. Evicts the lowest-priority resident role when free RAM
301
+ * crosses the low-water line.
302
+ */
303
+ private readonly memoryMonitor = new MemoryMonitor({
304
+ registry: this.sharedResources,
305
+ logger: {
306
+ info: (m) => console.info(m),
307
+ warn: (m) => console.warn(m),
308
+ debug: (m) => console.debug(m),
309
+ },
310
+ });
311
+
312
+ /** Wall-clock ms of the last `useModel`-style activity. */
313
+ private lastActivityMs = Date.now();
314
+ /** Idle-unload timer (J3); null when disabled or no model loaded. */
315
+ private idleUnloadTimer: NodeJS.Timeout | null = null;
316
+ /** Evictable text-target role id registered on `sharedResources`, or null. */
317
+ private textTargetRoleId: string | null = null;
318
+ /** Evictable drafter role id registered on `sharedResources`, or null. */
319
+
320
+ /**
321
+ * The active Eliza-1 bundle (root dir + tier id), resolved at `load()`
322
+ * from the InstalledModel path/id. `null` when the loaded model is not an
323
+ * Eliza-1 bundle (a user-installed custom). Drives bundle-relative voice
324
+ * resolution — the Kokoro TTS root and the per-tier EOT turn-detector
325
+ * revision.
326
+ */
327
+ private activeEliza1Bundle: ActiveEliza1Bundle | null = null;
328
+
329
+ /**
330
+ * The general onload/offload coordinator for this engine. Exposed so the
331
+ * voice lifecycle, the embedding route, and any other resident model role
332
+ * can register an `EvictableModelRole` against the same registry the
333
+ * `MemoryMonitor` walks under pressure.
334
+ */
335
+ getSharedResources(): SharedResourceRegistry {
336
+ return this.sharedResources;
337
+ }
338
+
339
+ /** The RAM-pressure monitor. Exposed for diagnostics / tests. */
340
+ getMemoryMonitor(): MemoryMonitor {
341
+ return this.memoryMonitor;
342
+ }
343
+
344
+ /** Record `useModel`-style activity so the idle-unload timer stays armed. */
345
+ private markActivity(): void {
346
+ this.lastActivityMs = Date.now();
347
+ }
348
+
349
+ /**
350
+ * Once a model is resident: register the text target as an evictable role,
351
+ * start the memory monitor, and arm the idle-unload timer. Idempotent.
352
+ */
353
+ private startBackgroundManagement(): void {
354
+ this.markActivity();
355
+ this.registerResidentRoles();
356
+ if (!this.memoryMonitor.isRunning()) this.memoryMonitor.start();
357
+ this.armIdleUnloadTimer();
358
+ }
359
+
360
+ /** Stop the memory monitor + idle timer and deregister evictable roles. */
361
+ private async stopBackgroundManagement(): Promise<void> {
362
+ if (this.idleUnloadTimer) {
363
+ clearInterval(this.idleUnloadTimer);
364
+ this.idleUnloadTimer = null;
365
+ }
366
+ this.memoryMonitor.stop();
367
+ await this.deregisterResidentRoles();
368
+ }
369
+
370
+ private registerResidentRoles(): void {
371
+ if (this.textTargetRoleId === null) {
372
+ const role = createEvictableModelRole({
373
+ role: "text-target",
374
+ isResident: () => this.hasLoadedModel(),
375
+ evict: async () => {
376
+ // Last thing to go. Evicting the text target = unload it; the
377
+ // next `useModel` lazy-reloads via the runtime handler.
378
+ await this.unload();
379
+ },
380
+ });
381
+ this.sharedResources.acquire(role);
382
+ this.textTargetRoleId = role.id;
383
+ }
384
+ }
385
+
386
+ private async deregisterResidentRoles(): Promise<void> {
387
+ const ids = [this.textTargetRoleId].filter(
388
+ (id): id is string => id !== null,
389
+ );
390
+ this.textTargetRoleId = null;
391
+ for (const id of ids) {
392
+ try {
393
+ await this.sharedResources.release(id);
394
+ } catch {
395
+ // Already released (e.g. unload→release ran twice) — fine.
396
+ }
397
+ }
398
+ }
399
+
400
+ private armIdleUnloadTimer(): void {
401
+ if (this.idleUnloadTimer) return;
402
+ const idleMs = resolveIdleUnloadMs();
403
+ if (idleMs <= 0) return;
404
+ const timer = setInterval(() => {
405
+ if (!this.hasLoadedModel()) return;
406
+ if (Date.now() - this.lastActivityMs < idleMs) return;
407
+ console.info(
408
+ `[local-inference] No useModel activity for >${Math.round(idleMs / 1000)}s — unloading the active text model to reclaim RAM. It will reload on the next request.`,
409
+ );
410
+ void this.unload().catch((err) => {
411
+ console.warn(
412
+ `[local-inference] idle-unload failed: ${err instanceof Error ? err.message : String(err)}`,
413
+ );
414
+ });
415
+ }, IDLE_UNLOAD_CHECK_INTERVAL_MS);
416
+ timer.unref();
417
+ this.idleUnloadTimer = timer;
418
+ }
419
+
420
+ /**
421
+ * Cap on concurrent speculative voice responses (W9 / J4): derived from
422
+ * the running server's slot count (each speculative response needs a KV
423
+ * slot), never more than half of them, floored at 1. The voice
424
+ * turn-controller reads this before kicking a speculative response.
425
+ */
426
+ maxConcurrentSpeculativeResponses(): number {
427
+ return resolveMaxConcurrentSpeculativeResponses(this.activeParallel());
428
+ }
429
+
430
+ /**
431
+ * Auto-tune the running server's `--parallel` (J4): when the conversation
432
+ * high-water mark has outgrown the configured slot count AND there's RAM
433
+ * headroom for the extra KV slots, resize/restart llama.cpp with the larger
434
+ * value so new conversations get their own slot instead of thrashing.
435
+ * Returns `true` when a resize was performed. No-op when the FFI backend
436
+ * isn't loaded. Best-effort: a failed restart leaves the old `--parallel`
437
+ * in place and logs.
438
+ */
439
+ async maybeAutoResizeParallel(): Promise<boolean> {
440
+ if (this.activeBackendId() !== "llama-cpp") return false;
441
+ if (!this.dispatcher.hasLoadedModel()) return false;
442
+ const running = this.dispatcher.parallelSlots();
443
+ const recommended = conversationRegistry.recommendedParallel(running);
444
+ if (recommended <= running) return false;
445
+ // Only grow when free RAM is comfortably above the low-water line —
446
+ // adding KV slots under pressure would just trigger the monitor.
447
+ const sample = await this.memoryMonitor.sample();
448
+ if (this.memoryMonitor.isUnderPressure(sample)) {
449
+ console.warn(
450
+ `[local-inference] Conversation high-water mark wants --parallel ${recommended} (running ${running}) but RAM is tight (free ${sample.effectiveFreeMb} MB) — not resizing. Slot thrashing may occur; consider a smaller tier or more RAM.`,
451
+ );
452
+ return false;
453
+ }
454
+ try {
455
+ const resized = await this.dispatcher.resizeParallel(recommended);
456
+ if (resized) {
457
+ console.info(
458
+ `[local-inference] Resized llama.cpp --parallel ${running} → ${recommended} (conversation high-water mark grew).`,
459
+ );
460
+ }
461
+ return resized;
462
+ } catch (err) {
463
+ console.warn(
464
+ `[local-inference] --parallel resize to ${recommended} failed: ${err instanceof Error ? err.message : String(err)}`,
465
+ );
466
+ return false;
467
+ }
468
+ }
469
+
470
+ async available(): Promise<boolean> {
471
+ return this.dispatcher.available();
472
+ }
473
+
474
+ currentModelPath(): string | null {
475
+ return this.dispatcher.currentModelPath();
476
+ }
477
+
478
+ hasLoadedModel(): boolean {
479
+ return this.dispatcher.hasLoadedModel();
480
+ }
481
+
482
+ activeBackendId(): "capacitor-llama" | "llama-cpp" | null {
483
+ return this.dispatcher.activeBackendId();
484
+ }
485
+
486
+ currentRuntimeLoadConfig(): LocalRuntimeLoadConfig | null {
487
+ if (this.activeBackendId() !== "llama-cpp") return null;
488
+ return this.dispatcher.currentRuntimeLoadConfig();
489
+ }
490
+
491
+ async unload(): Promise<void> {
492
+ // Stop the memory monitor + idle timer and deregister evictable roles
493
+ // before anything else — they reference the model that's about to go.
494
+ await this.stopBackgroundManagement();
495
+ this.activeEliza1Bundle = null;
496
+ const bridge = this.voiceBridge;
497
+ if (bridge) {
498
+ // Drop voice resources before tearing down text. Disarm is a
499
+ // no-op when the lifecycle is already in voice-off, so this is
500
+ // safe even if the caller never called startVoice().
501
+ try {
502
+ await bridge.disarm();
503
+ await bridge.settle();
504
+ } finally {
505
+ bridge.dispose();
506
+ if (this.voiceBridge === bridge) this.voiceBridge = null;
507
+ }
508
+ }
509
+ await this.dispatcher.unload();
510
+ }
511
+
512
+ async load(
513
+ modelPath: string,
514
+ resolved?: LocalInferenceLoadArgs,
515
+ ): Promise<void> {
516
+ const installed = await listInstalledModels();
517
+ const target = installed.find((m) => m.path === modelPath);
518
+ const modelId = target?.id ?? resolved?.modelId;
519
+ const catalog = modelId ? findCatalogModel(modelId) : undefined;
520
+
521
+ // Resolve the active Eliza-1 bundle (root + tier) so voice setup can
522
+ // find the bundle-relative Kokoro TTS root and the per-tier EOT
523
+ // turn-detector revision. An Eliza-1 InstalledModel carries a
524
+ // `bundleRoot` and an `eliza-1-<tier>` id. Reset on every load — a
525
+ // non-Eliza-1 model clears it.
526
+ this.activeEliza1Bundle =
527
+ resolveActiveEliza1Bundle(target, catalog) ??
528
+ resolveDirectEliza1Bundle(resolved, catalog);
529
+
530
+ // Resolved args (when provided) carry the merged catalog defaults +
531
+ // per-load overrides from the active-model coordinator. Project them
532
+ // onto the dispatcher-level overrides shape — engine.load is also
533
+ // called directly by legacy callers that pass only a `modelPath`,
534
+ // in which case `resolved` is undefined and we keep the historical
535
+ // behaviour of trusting catalog defaults inside the backend.
536
+ const overrides = resolved ? toBackendLoadOverrides(resolved) : undefined;
537
+
538
+ const plan: BackendPlan = {
539
+ modelPath,
540
+ modelId,
541
+ catalog,
542
+ overrides,
543
+ };
544
+
545
+ // The in-process FFI runtime (fused libelizainference, or the
546
+ // libllama + eliza-llama-shim fallback) is the sole text backend. A
547
+ // load failure surfaces directly — there is no second runtime to fall
548
+ // back to.
549
+ await this.dispatcher.load(plan);
550
+ this.startBackgroundManagement();
551
+ }
552
+
553
+ async generate(args: GenerateArgs): Promise<string> {
554
+ this.markActivity();
555
+ const streaming = this.voiceStreamingArgs(args);
556
+ const text = await this.dispatcher.generate(streaming.args);
557
+ await streaming.finish(text);
558
+ return text;
559
+ }
560
+
561
+ /**
562
+ * Vision describe via the running llama.cpp mtmd path. Requires the FFI
563
+ * backend with an mmproj-loaded bundle. The mmproj GGUF must have been
564
+ * declared by the active catalog tier and present on disk under the
565
+ * bundle root; if not, the active backend throws.
566
+ *
567
+ * No fallback: Florence-2 / Transformers.js was the previous fallback
568
+ * and has been removed (see VISION_MIGRATION.md).
569
+ */
570
+ async describeImage(args: {
571
+ bytes: Uint8Array;
572
+ mimeType?: string;
573
+ prompt?: string;
574
+ maxTokens?: number;
575
+ temperature?: number;
576
+ signal?: AbortSignal;
577
+ }): Promise<{
578
+ text: string;
579
+ projectorMs?: number;
580
+ decodeMs?: number;
581
+ }> {
582
+ this.markActivity();
583
+ // The dispatcher throws an actionable error if the active backend
584
+ // doesn't implement describeImage (e.g. an FFI backend without mmproj
585
+ // parity). No need for a pre-check.
586
+ return this.dispatcher.describeImage(args);
587
+ }
588
+
589
+ /** True when the active server can serve vision describe (mmproj loaded). */
590
+ canDescribeImages(): boolean {
591
+ if (this.activeBackendId() !== "llama-cpp") return false;
592
+ if (!this.dispatcher.hasLoadedModel()) return false;
593
+ return this.dispatcher.currentMmprojPath() !== null;
594
+ }
595
+
596
+ /**
597
+ * Diagnostic snapshot of an in-process JS session pool. Always null on the
598
+ * FFI runtime — its KV slots live in the native backend (C), not in a JS
599
+ * session pool. Retained so the API cache-stats panel keeps a stable shape.
600
+ */
601
+ describeSessionPool(): {
602
+ size: number;
603
+ maxSize: number;
604
+ keys: string[];
605
+ } | null {
606
+ return null;
607
+ }
608
+
609
+ /**
610
+ * Reserve a slot for a long-lived conversation. Subsequent
611
+ * `generateInConversation` calls reuse the same slot, so the prefix
612
+ * KV survives across turns regardless of hash collisions with other
613
+ * concurrent conversations.
614
+ *
615
+ * Idempotent for the same (conversationId, modelId): repeated open
616
+ * calls return the same handle. The runtime side should call this
617
+ * lazily on the first turn of a conversation and `closeConversation`
618
+ * when the chat session ends.
619
+ */
620
+ openConversation(args: {
621
+ conversationId: string;
622
+ modelId: string;
623
+ ttlMs?: number;
624
+ }): ConversationHandle {
625
+ const parallel = this.activeParallel();
626
+ const handle = conversationRegistry.open({
627
+ conversationId: args.conversationId,
628
+ modelId: args.modelId,
629
+ parallel,
630
+ ttlMs: args.ttlMs,
631
+ });
632
+ // Lazy-restore previously-persisted KV state for this conversation.
633
+ // Fire-and-forget — a missing or unreadable file just means the
634
+ // conversation cold-prefills on the next request, which is the
635
+ // pre-restore default. Only meaningful once the FFI backend is loaded.
636
+ if (this.activeBackendId() === "llama-cpp") {
637
+ void this.dispatcher
638
+ .restoreConversationKv(args.conversationId, handle.slotId)
639
+ .catch(() => {
640
+ // KV restore failures must never break the open call — the
641
+ // conversation just doesn't get its old prefix back.
642
+ });
643
+ }
644
+ return handle;
645
+ }
646
+
647
+ /**
648
+ * Run one generation pinned to a previously-opened conversation
649
+ * handle. Cache key, slot id, and (for optimized llama.cpp) kv-restore are
650
+ * all owned by the registry — callers don't need to thread them.
651
+ *
652
+ * Returns the Anthropic-shape `LocalUsageBlock` alongside the text so
653
+ * agentic callers can surface cache-hit telemetry without re-scraping
654
+ * `/metrics` themselves.
655
+ */
656
+ async generateInConversation(
657
+ handle: ConversationHandle,
658
+ args: Omit<GenerateArgs, "cacheKey">,
659
+ ): Promise<{ text: string; usage: LocalUsageBlock; slotId: number }> {
660
+ if (handle.closed) {
661
+ throw new Error(
662
+ `[local-inference] Conversation ${handle.conversationId} has been closed; reopen before generating`,
663
+ );
664
+ }
665
+ this.markActivity();
666
+ handle.lastUsedMs = Date.now();
667
+ const cacheKey = `conv:${handle.conversationId}`;
668
+ const streaming = this.voiceStreamingArgs(args);
669
+ if (this.activeBackendId() === "llama-cpp") {
670
+ const result: LocalGenerateWithUsageResult =
671
+ await this.dispatcher.generateWithUsage({
672
+ ...streaming.args,
673
+ cacheKey,
674
+ slotId: handle.slotId,
675
+ });
676
+ await streaming.finish(result.text);
677
+ return {
678
+ text: result.text,
679
+ usage: {
680
+ input_tokens: Number(result.usage?.prompt_tokens ?? 0),
681
+ output_tokens: Number(result.usage?.completion_tokens ?? 0),
682
+ cache_creation_input_tokens: 0,
683
+ cache_read_input_tokens: 0,
684
+ ...(result.mtpStats
685
+ ? {
686
+ mtp_drafted_tokens: result.mtpStats.drafted,
687
+ mtp_accepted_tokens: result.mtpStats.accepted,
688
+ mtp_acceptance_rate:
689
+ result.mtpStats.acceptanceRate ?? undefined,
690
+ }
691
+ : {}),
692
+ },
693
+ slotId: result.slotId ?? handle.slotId,
694
+ };
695
+ }
696
+ // No FFI backend loaded yet: forward via the dispatcher (which throws an
697
+ // actionable "no backend loaded" error) and synthesize a zero-counter
698
+ // usage block for the shape.
699
+ const text = await this.dispatcher.generate({
700
+ ...streaming.args,
701
+ cacheKey,
702
+ });
703
+ await streaming.finish(text);
704
+ return {
705
+ text,
706
+ usage: {
707
+ input_tokens: 0,
708
+ output_tokens: 0,
709
+ cache_creation_input_tokens: 0,
710
+ cache_read_input_tokens: 0,
711
+ },
712
+ slotId: handle.slotId,
713
+ };
714
+ }
715
+
716
+ /**
717
+ * KV-prefill a conversation's pinned slot with a known prompt prefix
718
+ * (system prompt + provider context + tool/action schema block + the
719
+ * assistant-turn start), before the real request lands. This is item I1 /
720
+ * C1 of the voice swarm — fire it the moment a message arrives / STT
721
+ * starts so the response-handler prompt is already in the slot's KV when
722
+ * the user's tokens are appended.
723
+ *
724
+ * `conversationOrId` may be a `ConversationHandle` (preferred — pins to
725
+ * the handle's slot) or a raw conversation id (a handle is opened on the
726
+ * fly so the slot derivation matches the real request). Idempotent /
727
+ * cheap to call repeatedly: `cache_prompt: true` reuses the prefix so a
728
+ * second call is a no-op forward pass. Only meaningful once the FFI
729
+ * backend is loaded — returns false otherwise. Returns true when a
730
+ * pre-warm request was issued.
731
+ */
732
+ async prewarmConversation(
733
+ conversationOrId: ConversationHandle | string,
734
+ promptPrefix: string,
735
+ opts: { modelId?: string } = {},
736
+ ): Promise<boolean> {
737
+ if (this.activeBackendId() !== "llama-cpp") return false;
738
+ this.markActivity();
739
+ let slotId: number;
740
+ let cacheKey: string;
741
+ if (typeof conversationOrId === "string") {
742
+ const modelId =
743
+ opts.modelId ?? this.currentModelPath() ?? "default-local-model";
744
+ const handle =
745
+ this.conversation(conversationOrId, modelId) ??
746
+ this.openConversation({ conversationId: conversationOrId, modelId });
747
+ slotId = handle.slotId;
748
+ cacheKey = `conv:${handle.conversationId}`;
749
+ } else {
750
+ if (conversationOrId.closed) return false;
751
+ slotId = conversationOrId.slotId;
752
+ cacheKey = `conv:${conversationOrId.conversationId}`;
753
+ }
754
+ return this.dispatcher.prewarmConversation(promptPrefix, {
755
+ slotId,
756
+ cacheKey,
757
+ });
758
+ }
759
+
760
+ /**
761
+ * Close + drop a conversation handle. Persists the final KV state to
762
+ * disk so a later open with the same id can lazy-restore. Idempotent;
763
+ * closing an unknown id is a no-op.
764
+ */
765
+ async closeConversation(handle: ConversationHandle): Promise<void> {
766
+ if (handle.closed) return;
767
+ if (this.activeBackendId() === "llama-cpp") {
768
+ // Snapshot KV before deregistering so the slot id is still valid.
769
+ await this.dispatcher
770
+ .persistConversationKv(handle.conversationId, handle.slotId)
771
+ .catch(() => {
772
+ // A failed save must not block close — the slot will fall back
773
+ // to the in-RAM-only path on next open.
774
+ });
775
+ }
776
+ conversationRegistry.close(handle.conversationId, handle.modelId);
777
+ }
778
+
779
+ /**
780
+ * Read-side accessor for the conversation registry. The runtime handler
781
+ * uses this to look up an existing handle before opening a new one,
782
+ * avoiding the need to thread a handle through every layer.
783
+ */
784
+ conversation(
785
+ conversationId: string,
786
+ modelId: string,
787
+ ): ConversationHandle | null {
788
+ return conversationRegistry.get(conversationId, modelId);
789
+ }
790
+
791
+ /**
792
+ * Largest concurrent open-conversation count seen this process lifetime.
793
+ * The auto-tune-parallel path consults this and warns when it exceeds
794
+ * the running server's slot count.
795
+ */
796
+ conversationHighWaterMark(): number {
797
+ return conversationRegistry.highWater();
798
+ }
799
+
800
+ /**
801
+ * Recommended `--parallel` value given the current conversation
802
+ * high-water mark plus a small headroom (max(2, 25%)), never below the
803
+ * running slot count. Delegates to `ConversationRegistry.recommendedParallel`
804
+ * so the math lives in one place. When this exceeds `parallelSlots()` the
805
+ * engine can grow the running server (`maybeAutoResizeParallel`).
806
+ */
807
+ recommendedParallel(): number {
808
+ return conversationRegistry.recommendedParallel(this.activeParallel());
809
+ }
810
+
811
+ /**
812
+ * Emit a one-line warning when the running `--parallel` slot count is
813
+ * below the recommended value (high-water mark + headroom). Returns true
814
+ * when a warning was emitted. No-op when the FFI backend isn't loaded.
815
+ * The actual resize is `maybeAutoResizeParallel()`
816
+ * — kept separate from this hot-path check so a `useModel` call never
817
+ * blocks on (or is interrupted by) a server restart; the auto-resize is
818
+ * opted into via `ELIZA_LOCAL_AUTO_RESIZE_PARALLEL=1`, in which case this
819
+ * also kicks one off fire-and-forget.
820
+ */
821
+ warnIfParallelTooLow(logger?: { warn: (msg: string) => void }): boolean {
822
+ if (this.activeBackendId() !== "llama-cpp") return false;
823
+ const actual = this.dispatcher.parallelSlots();
824
+ const recommended = conversationRegistry.recommendedParallel(actual);
825
+ if (recommended <= actual) return false;
826
+ const message = `[local-inference] Conversation high-water mark (${conversationRegistry.highWater()}) exceeds running --parallel ${actual}. Recommended: ${recommended}. Restart llama.cpp with ELIZA_LOCAL_PARALLEL=${recommended} or higher (or set ELIZA_LOCAL_AUTO_RESIZE_PARALLEL=1) to avoid slot thrashing.`;
827
+ if (logger?.warn) {
828
+ logger.warn(message);
829
+ } else {
830
+ console.warn(message);
831
+ }
832
+ if (process.env.ELIZA_LOCAL_AUTO_RESIZE_PARALLEL === "1") {
833
+ void this.maybeAutoResizeParallel().catch(() => {
834
+ // Best-effort; the warning above already told the operator what to do.
835
+ });
836
+ }
837
+ return true;
838
+ }
839
+
840
+ /**
841
+ * Start the voice-streaming pipeline against an already-activated
842
+ * Eliza-1 bundle. Per AGENTS.md §3, voice is mandatory for Eliza-1
843
+ * tiers — every required artifact (speaker preset, fused FFI when
844
+ * `useFfiBackend`, bundle root) is checked up front and missing
845
+ * pieces surface as `VoiceStartupError`. There is no silent fallback
846
+ * to text-only, no log-and-continue.
847
+ *
848
+ * Idempotent guard: starting twice without `stopVoice()` between
849
+ * surfaces a hard error so callers do not double-allocate the
850
+ * scheduler.
851
+ */
852
+ startVoice(opts: EngineVoiceBridgeOptions): EngineVoiceBridge {
853
+ if (this.voiceBridge) {
854
+ throw new VoiceStartupError(
855
+ "already-started",
856
+ "[voice] Voice session is already active. Call stopVoice() before starting a new one.",
857
+ );
858
+ }
859
+ // Pass the engine's shared-resource registry through so voice ref-counts
860
+ // against the same canonical resources as text and the `MemoryMonitor`
861
+ // sees voice's evictable roles too. The engine's registry is canonical —
862
+ // callers don't get to substitute their own.
863
+ this.voiceBridge = EngineVoiceBridge.start({
864
+ ...opts,
865
+ sharedResources: this.sharedResources,
866
+ });
867
+ return this.voiceBridge;
868
+ }
869
+
870
+ /**
871
+ * True when a voice session is currently active on the engine. Callers
872
+ * use this to decide whether to lazy-start one (e.g. the TTS model
873
+ * handler in `ensure-local-inference-handler.ts`, which auto-starts a
874
+ * Kokoro-only bridge on the first TEXT_TO_SPEECH invocation when the
875
+ * Kokoro artifacts are on disk and no Eliza-1 bundle has activated).
876
+ */
877
+ hasActiveVoiceBridge(): boolean {
878
+ return this.voiceBridge !== null;
879
+ }
880
+
881
+ /**
882
+ * Arm the voice lifecycle on the active bridge — lazily loads the TTS
883
+ * mmap region, optional ASR region when present, voice caches, and
884
+ * voice scheduler nodes via the shared resource registry. Throws
885
+ * `VoiceLifecycleError` if any
886
+ * required artifact is unavailable (RAM pressure, mmap fail, kernel
887
+ * missing) — see `voice/lifecycle.ts` for the structured codes.
888
+ *
889
+ * Required before sustained voice use; `startVoice()` only stands up
890
+ * the cold scheduler and bridge. Splitting setup from arming lets
891
+ * the engine keep the voice surface in voice-off (no heavy weights
892
+ * mapped) until the user actually toggles voice on.
893
+ */
894
+ async armVoice(): Promise<void> {
895
+ const bridge = this.voiceBridge;
896
+ if (!bridge) {
897
+ throw new VoiceStartupError(
898
+ "not-started",
899
+ "[voice] Cannot arm: no voice session active. Call startVoice() first.",
900
+ );
901
+ }
902
+ await bridge.arm();
903
+ }
904
+
905
+ /**
906
+ * Lazily start + arm voice for the active Eliza-1 bundle. Runtime model
907
+ * handlers use this when visible chat text needs local speech output; direct
908
+ * engine callers still use `startVoice()` / `armVoice()` explicitly when they
909
+ * need custom sinks or test backends.
910
+ */
911
+ async ensureActiveBundleVoiceReady(): Promise<EngineVoiceBridge> {
912
+ if (this.voiceReadyPromise) return this.voiceReadyPromise;
913
+ this.voiceReadyPromise = this.ensureActiveBundleVoiceReadyOnce();
914
+ try {
915
+ return await this.voiceReadyPromise;
916
+ } finally {
917
+ this.voiceReadyPromise = null;
918
+ }
919
+ }
920
+
921
+ private async ensureActiveBundleVoiceReadyOnce(): Promise<EngineVoiceBridge> {
922
+ let bridge = this.voiceBridge;
923
+ if (!bridge) {
924
+ // If no text model is loaded yet, try to load the assigned one so
925
+ // the Eliza-1 bundle activates before voice needs it. This covers
926
+ // the boot-time warmup race where TTS fires before any text request.
927
+ if (!this.activeEliza1Bundle && !this.dispatcher.hasLoadedModel()) {
928
+ try {
929
+ const assignments = await readEffectiveAssignments();
930
+ const textModelId = assignments.TEXT_LARGE ?? assignments.TEXT_SMALL;
931
+ if (textModelId) {
932
+ const installed = await listInstalledModels();
933
+ const target = installed.find((m) => m.id === textModelId);
934
+ if (target) {
935
+ logger.info(
936
+ `[voice] Pre-loading text model ${textModelId} to activate Eliza-1 bundle for voice`,
937
+ );
938
+ await this.load(target.path);
939
+ }
940
+ }
941
+ } catch (err) {
942
+ logger.warn(
943
+ `[voice] Failed to pre-load text model for bundle activation: ${
944
+ err instanceof Error ? err.message : String(err)
945
+ }`,
946
+ );
947
+ }
948
+ }
949
+ const bundle = this.activeEliza1Bundle;
950
+ if (bundle) {
951
+ const bundleKokoroRoot = path.join(bundle.root, "tts", "kokoro");
952
+ const kokoro =
953
+ resolveKokoroEngineConfig(bundleKokoroRoot) ??
954
+ resolveKokoroEngineConfig();
955
+ const mode = readVoiceBackendModeFromEnv();
956
+ const decision = selectVoiceBackend({
957
+ mode,
958
+ mobile: isMobilePlatform(),
959
+ kokoroAvailable: kokoro !== null,
960
+ omnivoiceAvailable: isOmniVoiceBundleAvailable(bundle.root),
961
+ tierVoiceBackends: bundle.voiceBackends,
962
+ });
963
+ console.info(
964
+ `[voice] Selected ${decision.backend} backend for ${bundle.tierId}: ${decision.reason}`,
965
+ );
966
+ if (decision.backend === "kokoro") {
967
+ if (!kokoro) {
968
+ throw new VoiceStartupError(
969
+ "missing-bundle-root",
970
+ "[voice] Kokoro was selected but its model artifacts are not staged under <stateDir>/local-inference/models/kokoro/.",
971
+ );
972
+ }
973
+ bridge = this.startVoice({
974
+ bundleRoot: "",
975
+ useFfiBackend: false,
976
+ kokoroOnly: kokoro,
977
+ });
978
+ } else {
979
+ const { ensureSamanthaPresetReady } = await import(
980
+ "./voice/samantha-preset-regenerator"
981
+ );
982
+ const outcome = await ensureSamanthaPresetReady(bundle.root);
983
+ if (outcome.kind === "regenerated") {
984
+ logger.info(
985
+ `[voice] regenerated Samantha preset on first boot: ${outcome.bytes} bytes (K=${outcome.K}, refT=${outcome.refT})`,
986
+ );
987
+ } else if (outcome.kind === "placeholder-no-regen") {
988
+ logger.warn(
989
+ `[voice] Samantha preset is the I-wave placeholder and on-the-fly regen is unavailable (reason=${outcome.reason}, detail=${outcome.detail}). Run packages/training/scripts/voice/samantha_lora/RUNBOOK.md or plugins/plugin-local-inference/scripts/regenerate-samantha-preset.mjs to produce a real preset.`,
990
+ );
991
+ if (
992
+ mode !== "omnivoice" &&
993
+ kokoro &&
994
+ bundle.voiceBackends?.includes("kokoro")
995
+ ) {
996
+ logger.warn(
997
+ `[voice] Falling back to bundled Kokoro voice ${kokoro.defaultVoiceId} from ${kokoro.layout.root} because OmniVoice has only the placeholder Samantha preset.`,
998
+ );
999
+ bridge = this.startVoice({
1000
+ bundleRoot: bundle.root,
1001
+ useFfiBackend: true,
1002
+ speakerPresetOverride: createKokoroSpeakerPreset(kokoro),
1003
+ ttsBackendOverride: createKokoroTtsBackend(kokoro, {
1004
+ bundleRoot: bundle.root,
1005
+ }),
1006
+ });
1007
+ } else if (mode !== "omnivoice") {
1008
+ throw new VoiceStartupError(
1009
+ "missing-speaker-preset",
1010
+ `[voice] OmniVoice selected for ${bundle.tierId}, but its Samantha preset is still the placeholder and no bundle-supported Kokoro fallback is staged. ${outcome.detail}`,
1011
+ );
1012
+ }
1013
+ }
1014
+ if (!bridge) {
1015
+ bridge = this.startVoice({
1016
+ bundleRoot: bundle.root,
1017
+ useFfiBackend: true,
1018
+ });
1019
+ }
1020
+ }
1021
+ } else {
1022
+ // No Eliza-1 bundle. Fall back to the Kokoro-only path when its
1023
+ // artifacts are staged. No silent degrade: when both are absent
1024
+ // the error names both staging options.
1025
+ const kokoro = resolveKokoroEngineConfig();
1026
+ if (!kokoro) {
1027
+ throw new VoiceStartupError(
1028
+ "missing-bundle-root",
1029
+ "[voice] Cannot start local voice: no active Eliza-1 bundle is loaded and no Kokoro artifacts are staged under <stateDir>/local-inference/models/kokoro/. Install an Eliza-1 bundle, or stage the Kokoro ONNX + at least one voice .bin to enable local TTS.",
1030
+ );
1031
+ }
1032
+ bridge = this.startVoice({
1033
+ bundleRoot: "",
1034
+ useFfiBackend: false,
1035
+ kokoroOnly: kokoro,
1036
+ });
1037
+ }
1038
+ }
1039
+ await bridge.arm();
1040
+ return bridge;
1041
+ }
1042
+
1043
+ /**
1044
+ * Assemble + run the full live voice loop on top of `startVoice()` /
1045
+ * `armVoice()`: mic → (`pipeMicToRingBuffer` + `VadDetector.pushFrame`)
1046
+ * per frame → `StreamingTranscriber.feed` (VAD-gated) → `VoiceTurnController`
1047
+ * (speculative-on-pause, abort-on-resume, finalize/promote, barge-in) →
1048
+ * `VoiceScheduler` → TTS → audio sink.
1049
+ *
1050
+ * Gated behind a complete real backend chain (AGENTS.md §3 — no silent
1051
+ * backend-mode "voice"):
1052
+ * - a `MicSource` (caller-supplied, or `DesktopMicSource` under Electrobun),
1053
+ * - a Silero v5 GGML VAD (caller-supplied detector, or `createSileroVadDetector()` — runs through libelizainference's native VAD ABI),
1054
+ * - a working ASR (the bridge's `createStreamingTranscriber` throws
1055
+ * `AsrUnavailableError` when the fused decoder is unavailable — the
1056
+ * fused build is the sole on-device ASR runtime),
1057
+ * - a real OmniVoice TTS backend on the bridge (the `StubOmniVoiceBackend`
1058
+ * is rejected — it emits zeros).
1059
+ * Any missing piece fails loudly with the specific component named.
1060
+ *
1061
+ * `prewarm` defaults to `this.prewarmConversation(roomId, "")` (best-effort
1062
+ * KV-prefill); a caller with the response-handler stable prefix (W6) should
1063
+ * pass its own. `generate` is required — it builds the message and runs the
1064
+ * runtime turn (streaming `replyText` into TTS via this engine's
1065
+ * `generate({ onTextChunk })`, which routes through the voice scheduler).
1066
+ */
1067
+ async startVoiceSession(opts: {
1068
+ roomId: string;
1069
+ /** Mic source. Defaults to a `DesktopMicSource` (Electrobun). */
1070
+ micSource?: import("./voice/types").MicSource;
1071
+ /** VAD detector. Defaults to `createSileroVadDetector()`. */
1072
+ vad?: import("./voice/vad").VadDetector;
1073
+ /** Run one turn: build the message + stream `replyText` into TTS. Required. */
1074
+ generate: (
1075
+ request: import("./voice/turn-controller").VoiceGenerateRequest,
1076
+ ) => Promise<import("./voice/turn-controller").VoiceTurnOutcome>;
1077
+ /**
1078
+ * Semantic turn detector layered with VAD/STT. Defaults to the local
1079
+ * LiveKit ONNX model when installed, otherwise the deterministic heuristic.
1080
+ * Pass `false` only for tests/manual troubleshooting.
1081
+ */
1082
+ turnDetector?: import("./voice/eot-classifier").EotClassifier | false;
1083
+ /** Optional local LiveKit turn-detector directory override. */
1084
+ turnDetectorModelDir?: string;
1085
+ /**
1086
+ * Use the already-loaded eliza-1 text model as the EOT classifier — see
1087
+ * `voice/eliza1-eot-scorer.ts`. When set, the runtime skips the
1088
+ * separate LiveKit/Turnsense ONNX and reads P(`<|im_end|>`) directly
1089
+ * off the live model.
1090
+ *
1091
+ * `"auto"` (default): use eliza-1 EOT when `ELIZA_VOICE_EOT_BACKEND=eliza-1`
1092
+ * or when no bundled LiveKit ONNX is resolvable; otherwise fall
1093
+ * through to the existing LiveKit path. `true` forces eliza-1 EOT
1094
+ * (throws if the active backend is not in-process). `false` forces
1095
+ * the historical LiveKit path.
1096
+ */
1097
+ useEliza1Eot?: boolean | "auto";
1098
+ /**
1099
+ * Optional path to a fine-tuned EOT LoRA adapter to layer on top of
1100
+ * the drafter at scoring time. The training recipe lives in
1101
+ * `packages/training/scripts/turn_detector/`.
1102
+ */
1103
+ eliza1EotLoraPath?: string;
1104
+ /** KV-prefill / response-handler-prefix prewarm. Defaults to `prewarmConversation`. */
1105
+ prewarm?: (roomId: string) => void | Promise<void>;
1106
+ speculatePauseMs?: number;
1107
+ events?: import("./voice/turn-controller").VoiceTurnControllerEvents;
1108
+ /**
1109
+ * Opt-in openWakeWord hotword gate (local mode only — the
1110
+ * local-inference engine never runs in cloud mode, and the connector
1111
+ * UI hides this surface there per AGENTS.md §5 hide-not-disable).
1112
+ * Disabled by default: voice mode works push-to-talk / VAD-gated
1113
+ * without it. When `enabled` and the bundle ships the openWakeWord
1114
+ * graphs, mic frames are also fanned into an `OpenWakeWordDetector`;
1115
+ * each fresh detection prewarms the conversation and calls `onWake`
1116
+ * (the same place a push-to-talk press would arm a listening window).
1117
+ * Silently inert when the bundle has no wake-word model.
1118
+ */
1119
+ wakeWord?: {
1120
+ enabled: boolean;
1121
+ /** Wake phrase head name (defaults to the bundle's `hey-eliza`). */
1122
+ head?: string;
1123
+ /** P(wake) firing threshold (openWakeWord default ~0.5). */
1124
+ threshold?: number;
1125
+ /** Called once per detected utterance (refractory-debounced). */
1126
+ onWake?: () => void;
1127
+ };
1128
+ /**
1129
+ * Runtime reference for cancellation coordination (W3-9 F1).
1130
+ *
1131
+ * @deprecated G5.d: pass `runtime` to `startVoice()` (the
1132
+ * `EngineVoiceBridgeOptions`) instead. The bridge is the canonical
1133
+ * owner of `VoiceCancellationCoordinator` + `OptimisticGenerationPolicy`,
1134
+ * and `startVoiceSession()` now delegates to the bridge's coordinator.
1135
+ * When this field is supplied here without a matching bridge-level
1136
+ * runtime, `startVoiceSession()` logs once and ignores it — the
1137
+ * canonical wiring lives on the bridge.
1138
+ */
1139
+ runtime?: CoordinatorRuntime;
1140
+ }): Promise<import("./voice/turn-controller").VoiceTurnController> {
1141
+ const bridge = this.requireVoiceBridge("start a voice session");
1142
+ if (bridge.lifecycle.current().kind !== "voice-on") {
1143
+ throw new VoiceStartupError(
1144
+ "not-started",
1145
+ "[voice] Cannot start a voice session: voice lifecycle is not armed. Call armVoice() first.",
1146
+ );
1147
+ }
1148
+ const backendId = (bridge.backend as { id?: string }).id;
1149
+ if (backendId === "stub") {
1150
+ throw new VoiceStartupError(
1151
+ "missing-fused-build",
1152
+ "[voice] Cannot start a live voice session on the StubOmniVoiceBackend (it emits silence). Start the bridge with useFfiBackend:true or a real backendOverride.",
1153
+ );
1154
+ }
1155
+
1156
+ const [
1157
+ { DesktopMicSource, pipeMicToRingBuffer },
1158
+ vadMod,
1159
+ { VoiceTurnController },
1160
+ { InMemoryAudioSink },
1161
+ eotMod,
1162
+ eotGgmlMod,
1163
+ ] = await Promise.all([
1164
+ import("./voice/mic-source"),
1165
+ import("./voice/vad"),
1166
+ import("./voice/turn-controller"),
1167
+ import("./voice/ring-buffer"),
1168
+ import("./voice/eot-classifier"),
1169
+ import("./voice/eot-classifier-ggml"),
1170
+ ]);
1171
+
1172
+ const micSource = opts.micSource ?? new DesktopMicSource();
1173
+ const vad =
1174
+ opts.vad ??
1175
+ (await vadMod.createSileroVadDetector({
1176
+ bundleRoot: bridge.bundlePath(),
1177
+ ffi: bridge.ffi,
1178
+ ctx: bridge.ffi
1179
+ ? () => {
1180
+ const ctx = bridge.ffiCtx;
1181
+ if (ctx === null) {
1182
+ throw new VoiceStartupError(
1183
+ "missing-ffi",
1184
+ "[voice] Cannot initialize native VAD: fused FFI context is not loaded.",
1185
+ );
1186
+ }
1187
+ return ctx;
1188
+ }
1189
+ : undefined,
1190
+ }));
1191
+
1192
+ // ASR — throws `AsrUnavailableError` when the fused decoder is
1193
+ // unavailable (the fused build is the sole on-device ASR runtime). Gated
1194
+ // on the VAD so silent frames aren't decoded.
1195
+ const transcriber = bridge.createStreamingTranscriber({ vad });
1196
+ // Voice Wave 2 (2026-05-14): tier-aware turn-detector revision selection.
1197
+ // `0_8b` / `2b` ship the ~66 MB EN-only SmolLM2-135M distill
1198
+ // (`v1.2.2-en`); `4b`+ ship the ~396 MB multilingual pruned
1199
+ // Qwen2.5-0.5B (`v0.4.1-intl`). The on-disk layout is per-tier so the
1200
+ // bundle dir already contains the matching ONNX — `revision` here is a
1201
+ // telemetry label (the upstream tag the bundle was staged from). When no
1202
+ // active bundle is resolvable we omit the hint and the resolver falls
1203
+ // back to the upstream-default filename order.
1204
+ const activeTier = this.activeEliza1Bundle?.tierId;
1205
+ const tierRevision = activeTier
1206
+ ? eotMod.turnDetectorRevisionForTier(activeTier)
1207
+ : undefined;
1208
+ const eliza1EotSelected = resolveEliza1EotSelection(
1209
+ opts.useEliza1Eot,
1210
+ opts.eliza1EotLoraPath,
1211
+ );
1212
+ const eliza1EotClassifier =
1213
+ eliza1EotSelected !== "off" && opts.turnDetector !== false
1214
+ ? this.tryBuildEliza1EotClassifier(
1215
+ eliza1EotSelected,
1216
+ opts.eliza1EotLoraPath,
1217
+ )
1218
+ : null;
1219
+ if (eliza1EotSelected === "force" && !eliza1EotClassifier) {
1220
+ throw new VoiceStartupError(
1221
+ "missing-turn-detector",
1222
+ "[voice] useEliza1Eot:true requested but the in-process Eliza-1 EOT scorer is unavailable on the FFI runtime — use the GGUF turn detector by setting useEliza1Eot:false.",
1223
+ );
1224
+ }
1225
+ // Fused end-of-turn scorer (ABI v11): the model-based turn detector now
1226
+ // runs in-process through libelizainference — a composite of the fused
1227
+ // semantic scorer (P(<|im_end|>) over the loaded text model) and the
1228
+ // heuristic syntactic co-signal. Built only when the loaded fused build
1229
+ // wires the v11 EOT symbol; null on a pre-v11 library, in which case the
1230
+ // resolver falls through to the heuristic-only classifier.
1231
+ const bridgeFfi = bridge.ffi;
1232
+ const fusedEot =
1233
+ opts.turnDetector === false || !bridgeFfi
1234
+ ? null
1235
+ : eotMod.tryBuildFusedEotClassifier({
1236
+ ffi: bridgeFfi,
1237
+ getContext: () => {
1238
+ const ctx = bridge.ffiCtx;
1239
+ if (ctx === null) {
1240
+ throw new VoiceStartupError(
1241
+ "missing-ffi",
1242
+ "[voice] Cannot initialize fused EOT scorer: FFI context is not loaded.",
1243
+ );
1244
+ }
1245
+ return ctx;
1246
+ },
1247
+ });
1248
+ // Resolver order: prefer the fused composite EOT (v11), then the legacy
1249
+ // in-process Eliza-1 scorer + GGUF turn detector (both null on the FFI
1250
+ // runtime — they needed node-llama controlledEvaluate), then the
1251
+ // heuristic. The ONNX path was removed.
1252
+ const ggmlTurnDetector =
1253
+ opts.turnDetector === false || fusedEot
1254
+ ? undefined
1255
+ : await eotGgmlMod
1256
+ .createBundledLiveKitGgmlTurnDetector({
1257
+ ...(opts.turnDetectorModelDir
1258
+ ? { modelDir: opts.turnDetectorModelDir }
1259
+ : {}),
1260
+ ...(tierRevision ? { revision: tierRevision } : {}),
1261
+ })
1262
+ .catch(() => null);
1263
+ const turnDetector =
1264
+ opts.turnDetector === false
1265
+ ? undefined
1266
+ : (opts.turnDetector ??
1267
+ fusedEot ??
1268
+ eliza1EotClassifier ??
1269
+ ggmlTurnDetector ??
1270
+ new eotMod.HeuristicEotClassifier());
1271
+ if (turnDetector) {
1272
+ try {
1273
+ // Warm one short pass while the session is arming, so the first
1274
+ // real user pause does not pay model-load latency.
1275
+ await turnDetector.score("yes");
1276
+ } catch (err) {
1277
+ throw new VoiceStartupError(
1278
+ "missing-turn-detector",
1279
+ `[voice] Cannot initialize semantic turn detector: ${err instanceof Error ? err.message : String(err)}`,
1280
+ );
1281
+ }
1282
+ }
1283
+
1284
+ // G5.d (Gauntlet cleanup): delegate to the bridge's canonical
1285
+ // VoiceCancellationCoordinator. The bridge is the single owner — it
1286
+ // constructs the coordinator + policy at `EngineVoiceBridge.start()`
1287
+ // when `runtime` is passed in `EngineVoiceBridgeOptions` (see
1288
+ // `engine-bridge.ts buildCancellationWiring`). Earlier C0-F wiring
1289
+ // built a separate coordinator here; that path is removed.
1290
+ //
1291
+ // Back-compat: when callers still pass `opts.runtime` to
1292
+ // `startVoiceSession()` but did not pass `runtime` to `startVoice()`,
1293
+ // the bridge has no coordinator. We log once and proceed — the
1294
+ // caller-supplied runtime is ignored because the bridge owns the
1295
+ // FFI context that the coordinator targets.
1296
+ if (opts.runtime && !bridge.cancellationCoordinatorOrNull()) {
1297
+ console.warn(
1298
+ "[voice] startVoiceSession({ runtime }) supplied but the bridge has no canonical cancellation coordinator — pass `runtime` to startVoice() instead. Ignoring the session-level runtime.",
1299
+ );
1300
+ }
1301
+
1302
+ const controller = new VoiceTurnController(
1303
+ {
1304
+ vad,
1305
+ transcriber,
1306
+ scheduler: bridge.scheduler,
1307
+ ...(turnDetector ? { turnDetector } : {}),
1308
+ prewarm:
1309
+ opts.prewarm ??
1310
+ ((roomId: string) => {
1311
+ void this.prewarmConversation(roomId, "");
1312
+ }),
1313
+ playFirstAudioFiller: () => this.playFirstAudioFiller(),
1314
+ generate: opts.generate,
1315
+ },
1316
+ {
1317
+ roomId: opts.roomId,
1318
+ ...(opts.speculatePauseMs !== undefined
1319
+ ? { speculatePauseMs: opts.speculatePauseMs }
1320
+ : {}),
1321
+ },
1322
+ opts.events ?? {},
1323
+ );
1324
+
1325
+ // Bind the bridge's BargeInController into the bridge's canonical
1326
+ // coordinator (G5.d). No-op when the bridge was constructed without a
1327
+ // runtime — returns a no-op unsubscribe so the teardown path stays
1328
+ // branchless.
1329
+ const unsubCoordinator = bridge.bindBargeInControllerForRoom(opts.roomId);
1330
+
1331
+ // Mic → ring buffer (the buffer the ASR / instrumentation can read from)
1332
+ // + per-frame fan-out to the VAD and the streaming transcriber.
1333
+ const { unsubscribe: stopMicRing } = pipeMicToRingBuffer(
1334
+ micSource,
1335
+ new InMemoryAudioSink(),
1336
+ );
1337
+ // Optional openWakeWord hotword gate (opt-in, local mode). Resolved
1338
+ // against the active bundle; absent graphs → silently no wake word.
1339
+ let wakeWord: import("./voice/wake-word").OpenWakeWordDetector | null =
1340
+ null;
1341
+ let feedWakeFrame: ((pcm: Float32Array) => void) | null = null;
1342
+ if (opts.wakeWord?.enabled) {
1343
+ const {
1344
+ isPlaceholderWakeWordHead,
1345
+ loadBundledWakeWordModel,
1346
+ OPENWAKEWORD_DEFAULT_HEAD,
1347
+ OpenWakeWordDetector,
1348
+ } = await import("./voice/wake-word");
1349
+ const headName = opts.wakeWord.head?.trim() || OPENWAKEWORD_DEFAULT_HEAD;
1350
+ if (isPlaceholderWakeWordHead(headName)) {
1351
+ console.warn(
1352
+ `[voice] wake word head '${headName}' is a PLACEHOLDER (the upstream openWakeWord "hey jarvis" head, renamed) — it fires on "hey jarvis", not the Eliza-1 wake phrase. Experimental, opt-in only; see packages/inference/reports/porting/2026-05-11/wakeword-head-plan.md.`,
1353
+ );
1354
+ }
1355
+ if (!bridge.ffi) {
1356
+ throw new VoiceStartupError(
1357
+ "missing-ffi",
1358
+ "[voice] Cannot initialize wake-word detector: fused libelizainference FFI is not loaded. Wake-word detection requires the native GGUF runtime (eliza_inference_wakeword_* symbols).",
1359
+ );
1360
+ }
1361
+ const ffiCtxResolver = () => {
1362
+ const ctx = bridge.ffiCtx;
1363
+ if (ctx === null) {
1364
+ throw new VoiceStartupError(
1365
+ "missing-ffi",
1366
+ "[voice] Cannot initialize wake-word detector: fused FFI context is not loaded.",
1367
+ );
1368
+ }
1369
+ return ctx;
1370
+ };
1371
+ const model = await loadBundledWakeWordModel({
1372
+ ffi: bridge.ffi,
1373
+ ctx: ffiCtxResolver,
1374
+ bundleRoot: bridge.bundlePath(),
1375
+ ...(opts.wakeWord.head ? { head: opts.wakeWord.head } : {}),
1376
+ });
1377
+ if (model) {
1378
+ const detector = new OpenWakeWordDetector({
1379
+ model,
1380
+ ...(opts.wakeWord.threshold !== undefined
1381
+ ? { config: { threshold: opts.wakeWord.threshold } }
1382
+ : {}),
1383
+ onWake: () => {
1384
+ void this.prewarmConversation(opts.roomId, "");
1385
+ opts.wakeWord?.onWake?.();
1386
+ },
1387
+ });
1388
+ wakeWord = detector;
1389
+ // The mic frame size need not match the openWakeWord frame size
1390
+ // (1280 samples = 80 ms @ 16 kHz); re-buffer into exact frames.
1391
+ const need = model.frameSamples;
1392
+ let acc = new Float32Array(0);
1393
+ feedWakeFrame = (pcm: Float32Array) => {
1394
+ const merged = new Float32Array(acc.length + pcm.length);
1395
+ merged.set(acc);
1396
+ merged.set(pcm, acc.length);
1397
+ let off = 0;
1398
+ while (merged.length - off >= need) {
1399
+ const slice = merged.slice(off, off + need);
1400
+ off += need;
1401
+ void detector.pushFrame(slice);
1402
+ }
1403
+ acc = merged.slice(off);
1404
+ };
1405
+ } else {
1406
+ console.info(
1407
+ "[voice] wake word requested but no openWakeWord model in this bundle — running VAD-gated only",
1408
+ );
1409
+ }
1410
+ }
1411
+
1412
+ const unsubFrame = micSource.onFrame((frame) => {
1413
+ // The VAD forward pass is serialized internally; fire-and-forget so a
1414
+ // slow frame doesn't backpressure the mic (the VAD records overruns).
1415
+ void vad.pushFrame(frame);
1416
+ transcriber.feed(frame);
1417
+ feedWakeFrame?.(frame.pcm);
1418
+ });
1419
+
1420
+ controller.start();
1421
+ await micSource.start();
1422
+
1423
+ // Single teardown knob: stopping the controller stops the mic chain too.
1424
+ const origStop = controller.stop.bind(controller);
1425
+ controller.stop = () => {
1426
+ origStop();
1427
+ unsubFrame();
1428
+ stopMicRing();
1429
+ void micSource.stop();
1430
+ transcriber.dispose();
1431
+ wakeWord?.reset();
1432
+ // G5.d: tear down only the per-room barge-in binding. The bridge
1433
+ // owns the coordinator lifecycle and disposes it in
1434
+ // `EngineVoiceBridge.dispose()` — we must not dispose it here or
1435
+ // we would cancel armed tokens for other concurrent rooms.
1436
+ unsubCoordinator();
1437
+ };
1438
+ return controller;
1439
+ }
1440
+
1441
+ /**
1442
+ * Disarm the voice lifecycle — drains the ring buffer, settles the
1443
+ * scheduler, and drops TTS/ASR weights from RAM via `evictPages()`
1444
+ * (madvise / VirtualUnlock equivalent — see voice/engine-bridge.ts).
1445
+ * No-op when not armed.
1446
+ */
1447
+ async disarmVoice(): Promise<void> {
1448
+ const bridge = this.voiceBridge;
1449
+ if (!bridge) return;
1450
+ await bridge.disarm();
1451
+ }
1452
+
1453
+ /**
1454
+ * Tear down the active voice bridge. Idempotent; calling when no
1455
+ * voice session is active is a no-op. Disarms the lifecycle first
1456
+ * (drops voice weights via `evictPages`), then settles any in-flight
1457
+ * TTS so audio committed to the ring buffer surfaces to the sink
1458
+ * before the bridge is dropped.
1459
+ */
1460
+ async stopVoice(): Promise<void> {
1461
+ const bridge = this.voiceBridge;
1462
+ if (!bridge) return;
1463
+ try {
1464
+ await bridge.disarm();
1465
+ await bridge.settle();
1466
+ } finally {
1467
+ bridge.dispose();
1468
+ if (this.voiceBridge === bridge) this.voiceBridge = null;
1469
+ }
1470
+ }
1471
+
1472
+ async synthesizeSpeech(
1473
+ text: string,
1474
+ signal?: AbortSignal,
1475
+ ): Promise<Uint8Array> {
1476
+ this.markActivity();
1477
+ const bridge = this.requireVoiceBridge("synthesize speech");
1478
+ if ((bridge.backend as { id?: string }).id === "stub") {
1479
+ throw new VoiceStartupError(
1480
+ "missing-fused-build",
1481
+ "[voice] Cannot synthesize speech with StubOmniVoiceBackend (it emits silence). Start voice with useFfiBackend:true or inject a real backend.",
1482
+ );
1483
+ }
1484
+ return bridge.synthesizeTextToWav(text, signal);
1485
+ }
1486
+
1487
+ async prewarmVoicePhrases(
1488
+ texts: ReadonlyArray<string>,
1489
+ opts: { concurrency?: number } = {},
1490
+ ): Promise<{ warmed: number; cached: number }> {
1491
+ return this.requireVoiceBridge("prewarm voice phrases").prewarmPhrases(
1492
+ texts,
1493
+ opts,
1494
+ );
1495
+ }
1496
+
1497
+ /**
1498
+ * Idle-time auto-prewarm: synthesize the canonical common-phrase seed so
1499
+ * the phrase cache is warm before the next turn. No-op unless a real TTS
1500
+ * backend is present and voice is armed. Callers (the voice bridge /
1501
+ * connector) invoke this when the loop is idle.
1502
+ */
1503
+ async prewarmIdleVoicePhrases(
1504
+ opts: { concurrency?: number } = {},
1505
+ ): Promise<{ warmed: number; cached: number }> {
1506
+ return this.requireVoiceBridge(
1507
+ "prewarm idle voice phrases",
1508
+ ).prewarmIdlePhrases(opts);
1509
+ }
1510
+
1511
+ /**
1512
+ * Play the first-audio filler (a short cached acknowledgement) — the seam
1513
+ * W9's turn controller calls the instant VAD fires `speech-start` to mask
1514
+ * first-token latency. Returns the played filler text, or `null` if none
1515
+ * was played. No-op without a real TTS backend / armed voice.
1516
+ */
1517
+ playFirstAudioFiller(): string | null {
1518
+ return this.requireVoiceBridge(
1519
+ "play first-audio filler",
1520
+ ).playFirstAudioFiller();
1521
+ }
1522
+
1523
+ async transcribePcm(
1524
+ args: TranscriptionAudio,
1525
+ signal?: AbortSignal,
1526
+ ): Promise<string> {
1527
+ this.markActivity();
1528
+ if (signal?.aborted) {
1529
+ throw signal.reason instanceof Error
1530
+ ? signal.reason
1531
+ : new DOMException("Aborted", "AbortError");
1532
+ }
1533
+ const transcript = await this.requireVoiceBridge(
1534
+ "transcribe audio",
1535
+ ).transcribePcm(args, signal);
1536
+ if (signal?.aborted) {
1537
+ throw signal.reason instanceof Error
1538
+ ? signal.reason
1539
+ : new DOMException("Aborted", "AbortError");
1540
+ }
1541
+ return transcript;
1542
+ }
1543
+
1544
+ /**
1545
+ * Run one fused mic→speech voice turn through the overlapped
1546
+ * `VoicePipeline`: ASR → {MTP drafts ∥ target verifies} → phrase
1547
+ * chunker → OmniVoice → PCM ring buffer, with rollback-on-reject and
1548
+ * barge-in cancel. Requires `startVoice()` + `armVoice()` first.
1549
+ *
1550
+ * `opts.textRunner` lets a host that runs its own text engine in-process
1551
+ * (the iOS/Android FFI path or the desktop FFI runtime) supply its own
1552
+ * {@link MtpTextRunner}. When omitted, the active local dispatcher is
1553
+ * used.
1554
+ *
1555
+ * Resolves with the turn's exit reason (`done` / `token-cap` /
1556
+ * `cancelled`). A missing ASR region in voice mode surfaces as a
1557
+ * `VoiceStartupError` — no silent cloud fallback (AGENTS.md §3).
1558
+ */
1559
+ async runVoiceTurn(
1560
+ audio: TranscriptionAudio,
1561
+ opts: {
1562
+ maxDraftTokens?: number;
1563
+ maxGeneratedTokens?: number;
1564
+ events?: VoicePipelineEvents;
1565
+ /**
1566
+ * In-process text runner for the mobile FFI path. Must implement the
1567
+ * same `MtpTextRunner` contract (`hasDrafter()` +
1568
+ * `generateWithVerifierEvents()`); the AOSP/Capacitor bridge wraps
1569
+ * its libllama-context-backed speculative loop in one.
1570
+ */
1571
+ textRunner?: MtpTextRunner;
1572
+ } = {},
1573
+ ): Promise<"done" | "token-cap" | "cancelled"> {
1574
+ this.markActivity();
1575
+ const bridge = this.requireVoiceBridge("run a voice turn");
1576
+ return bridge.runVoiceTurn(
1577
+ audio,
1578
+ opts.textRunner ?? mtpTextRunner(this.dispatcher),
1579
+ {
1580
+ maxDraftTokens: opts.maxDraftTokens ?? DEFAULT_VOICE_MAX_DRAFT_TOKENS,
1581
+ maxGeneratedTokens: opts.maxGeneratedTokens,
1582
+ },
1583
+ opts.events,
1584
+ );
1585
+ }
1586
+
1587
+ /**
1588
+ * Active voice bridge, or null when voice mode is not running.
1589
+ * Callers (router, UI, agent runtime) read this to decide whether to
1590
+ * forward verifier events. Voice is mandatory for Eliza-1 tiers but
1591
+ * the bridge is still created lazily — `startVoice()` MUST be called
1592
+ * before `voice()` returns non-null.
1593
+ */
1594
+ voice(): EngineVoiceBridge | null {
1595
+ return this.voiceBridge;
1596
+ }
1597
+
1598
+ private requireVoiceBridge(action: string): EngineVoiceBridge {
1599
+ const bridge = this.voiceBridge;
1600
+ if (!bridge) {
1601
+ throw new VoiceStartupError(
1602
+ "not-started",
1603
+ `[voice] Cannot ${action}: no voice session active. Call startVoice() and armVoice() first.`,
1604
+ );
1605
+ }
1606
+ return bridge;
1607
+ }
1608
+
1609
+ private voiceStreamingArgs<T extends Omit<GenerateArgs, "cacheKey">>(
1610
+ args: T,
1611
+ ): {
1612
+ args: T;
1613
+ finish: (finalText: string) => Promise<void>;
1614
+ } {
1615
+ const bridge = this.voiceBridge;
1616
+ const voiceOn = bridge?.lifecycle.current().kind === "voice-on";
1617
+ const structuredVoiceFields =
1618
+ args.streamStructured === true
1619
+ ? resolveVoiceSkeletonStreamFields(args.responseSkeleton)
1620
+ : [];
1621
+ const hasShouldRespondGate =
1622
+ args.streamStructured === true &&
1623
+ skeletonHasFreeStringKey(args.responseSkeleton, "shouldRespond");
1624
+ const extractorStreamFields =
1625
+ hasShouldRespondGate && !structuredVoiceFields.includes("shouldRespond")
1626
+ ? ["shouldRespond", ...structuredVoiceFields]
1627
+ : structuredVoiceFields;
1628
+ const userVisibleVoice =
1629
+ args.voiceOutput === "user-visible" ||
1630
+ (args.voiceOutput === undefined &&
1631
+ (typeof args.onTextChunk === "function" ||
1632
+ structuredVoiceFields.length > 0));
1633
+ if (!voiceOn || !bridge || !userVisibleVoice) {
1634
+ return {
1635
+ args,
1636
+ finish: async () => {},
1637
+ };
1638
+ }
1639
+
1640
+ // Barge-in → LLM/drafter abort. A `hard-stop` from the scheduler's
1641
+ // barge-in controller (ASR-confirmed words, or `triggerBargeIn()`)
1642
+ // aborts this controller; we hand its signal to `dispatcher.generate`
1643
+ // so generation stops at the next kernel boundary — not just TTS
1644
+ // (AGENTS.md §4 / brief item 2). Composed with the caller's signal so
1645
+ // an external cancel still works.
1646
+ const bargeAbort = new AbortController();
1647
+ const detachBarge = bridge.scheduler.bargeIn.onSignal((signal) => {
1648
+ if (signal.type === "hard-stop" && !bargeAbort.signal.aborted) {
1649
+ bargeAbort.abort();
1650
+ }
1651
+ });
1652
+ const callerSignal = args.signal;
1653
+ if (callerSignal) {
1654
+ if (callerSignal.aborted) bargeAbort.abort();
1655
+ else
1656
+ callerSignal.addEventListener(
1657
+ "abort",
1658
+ () => {
1659
+ if (!bargeAbort.signal.aborted) bargeAbort.abort();
1660
+ },
1661
+ { once: true },
1662
+ );
1663
+ }
1664
+
1665
+ let nextIndex = 0;
1666
+ let streamedAny = false;
1667
+ let verifierHandled = false;
1668
+ const callerOnTextChunk = args.onTextChunk;
1669
+ const callerOnVerifierEvent = args.onVerifierEvent;
1670
+ let structuredVoicePush = Promise.resolve();
1671
+ let shouldRespondText = "";
1672
+ let shouldRespondAllowsVoice: boolean | null = hasShouldRespondGate
1673
+ ? null
1674
+ : true;
1675
+ const pendingStructuredReplyChunks: string[] = [];
1676
+ const pushStructuredVoiceChunk = (chunk: string) => {
1677
+ streamedAny = true;
1678
+ const token: TextToken = { index: nextIndex++, text: chunk };
1679
+ structuredVoicePush = structuredVoicePush.then(() =>
1680
+ bridge.pushAcceptedToken(token),
1681
+ );
1682
+ };
1683
+ const structuredVoiceExtractor =
1684
+ structuredVoiceFields.length > 0 && args.responseSkeleton
1685
+ ? new ResponseSkeletonStreamExtractor({
1686
+ skeleton: args.responseSkeleton,
1687
+ streamFields: extractorStreamFields,
1688
+ abortSignal: bargeAbort.signal,
1689
+ onChunk: (chunk: string, field?: string) => {
1690
+ if (chunk.length === 0) return;
1691
+ if (field === "shouldRespond") {
1692
+ shouldRespondText += chunk;
1693
+ const normalized = shouldRespondText
1694
+ .trim()
1695
+ .toUpperCase()
1696
+ .replace(/^[^A-Z]+/, "");
1697
+ if (
1698
+ normalized.startsWith("IG") ||
1699
+ normalized.startsWith("ST")
1700
+ ) {
1701
+ shouldRespondAllowsVoice = false;
1702
+ pendingStructuredReplyChunks.length = 0;
1703
+ } else if (normalized.startsWith("RE")) {
1704
+ shouldRespondAllowsVoice = true;
1705
+ for (const pending of pendingStructuredReplyChunks.splice(
1706
+ 0,
1707
+ )) {
1708
+ pushStructuredVoiceChunk(pending);
1709
+ }
1710
+ }
1711
+ return;
1712
+ }
1713
+ if (hasShouldRespondGate) {
1714
+ if (shouldRespondAllowsVoice === false) return;
1715
+ if (shouldRespondAllowsVoice !== true) {
1716
+ pendingStructuredReplyChunks.push(chunk);
1717
+ return;
1718
+ }
1719
+ }
1720
+ pushStructuredVoiceChunk(chunk);
1721
+ },
1722
+ })
1723
+ : null;
1724
+ const wrapped = {
1725
+ ...args,
1726
+ signal: bargeAbort.signal,
1727
+ onVerifierEvent: async (event: VerifierStreamEvent) => {
1728
+ if (structuredVoiceExtractor) {
1729
+ await callerOnVerifierEvent?.(event);
1730
+ return;
1731
+ }
1732
+ verifierHandled = true;
1733
+ if (event.kind === "accept" && event.tokens.length > 0) {
1734
+ streamedAny = true;
1735
+ const last = event.tokens[event.tokens.length - 1];
1736
+ nextIndex = Math.max(nextIndex, last.index + 1);
1737
+ }
1738
+ await this.pushVerifierEvent(event);
1739
+ await callerOnVerifierEvent?.(event);
1740
+ },
1741
+ onTextChunk: async (chunk: string) => {
1742
+ if (structuredVoiceExtractor) {
1743
+ structuredVoiceExtractor.push(chunk);
1744
+ await callerOnTextChunk?.(chunk);
1745
+ return;
1746
+ }
1747
+ if (chunk.length > 0 && !verifierHandled) {
1748
+ streamedAny = true;
1749
+ const token: TextToken = { index: nextIndex++, text: chunk };
1750
+ await bridge.pushAcceptedToken(token);
1751
+ }
1752
+ await callerOnTextChunk?.(chunk);
1753
+ },
1754
+ } as T;
1755
+
1756
+ return {
1757
+ args: wrapped,
1758
+ finish: async (finalText: string) => {
1759
+ try {
1760
+ if (structuredVoiceExtractor) {
1761
+ if (!streamedAny && finalText.length > 0) {
1762
+ structuredVoiceExtractor.push(finalText);
1763
+ }
1764
+ structuredVoiceExtractor.flush();
1765
+ await structuredVoicePush;
1766
+ }
1767
+ if (
1768
+ !structuredVoiceExtractor &&
1769
+ !streamedAny &&
1770
+ finalText.length > 0 &&
1771
+ !bargeAbort.signal.aborted
1772
+ ) {
1773
+ await bridge.pushAcceptedToken({
1774
+ index: nextIndex++,
1775
+ text: finalText,
1776
+ });
1777
+ }
1778
+ await bridge.settle();
1779
+ } finally {
1780
+ detachBarge();
1781
+ }
1782
+ },
1783
+ };
1784
+ }
1785
+
1786
+ /**
1787
+ * Forward a verifier-stream event into the voice scheduler. Accepted tokens flow into the
1788
+ * phrase chunker; rejected ranges trigger the rollback queue. No-op
1789
+ * when voice is not active so callers can fan out events
1790
+ * unconditionally.
1791
+ *
1792
+ * When MTP produces an accepted text token, the phrase chunker MUST hand
1793
+ * the chunk to TTS within the same scheduler tick.
1794
+ */
1795
+ async pushVerifierEvent(event: VerifierStreamEvent): Promise<void> {
1796
+ const bridge = this.voiceBridge;
1797
+ if (!bridge) return;
1798
+ if (event.kind === "accept") {
1799
+ const now = Date.now();
1800
+ for (const tok of event.tokens) {
1801
+ await bridge.pushAcceptedToken(tok, now);
1802
+ }
1803
+ return;
1804
+ }
1805
+ if (event.tokens.length === 0) return;
1806
+ const range: RejectedTokenRange = {
1807
+ fromIndex: event.tokens[0].index,
1808
+ toIndex: event.tokens[event.tokens.length - 1].index,
1809
+ };
1810
+ await bridge.pushRejectedRange(range);
1811
+ }
1812
+
1813
+ /**
1814
+ * Mic VAD → barge-in. Per AGENTS.md §4, the PCM ring buffer MUST
1815
+ * drain immediately and any in-flight TTS forward pass MUST be
1816
+ * cancelled at the next kernel boundary. The scheduler enforces both
1817
+ * — this is a thin pass-through.
1818
+ */
1819
+ triggerBargeIn(): void {
1820
+ this.voiceBridge?.triggerBargeIn();
1821
+ }
1822
+
1823
+ /**
1824
+ * Test surface: fan an accepted-token list into the bridge in one
1825
+ * call. Production callers should prefer `pushVerifierEvent` so the
1826
+ * accept/reject discriminator stays explicit; this exists so the
1827
+ * voice integration test can drive the scheduler without
1828
+ * reconstructing `VerifierStreamEvent` boilerplate.
1829
+ */
1830
+ async pushAcceptedTokens(tokens: ReadonlyArray<TextToken>): Promise<void> {
1831
+ await this.pushVerifierEvent({ kind: "accept", tokens: [...tokens] });
1832
+ }
1833
+
1834
+ /**
1835
+ * Active llama.cpp parallel slot count from the running FFI backend, or
1836
+ * the configured default pool size when no model is loaded yet.
1837
+ */
1838
+ private activeParallel(): number {
1839
+ if (this.activeBackendId() === "llama-cpp") {
1840
+ return this.dispatcher.parallelSlots();
1841
+ }
1842
+ return resolveDefaultPoolSize(process.env.ELIZA_LOCAL_SESSION_POOL_SIZE);
1843
+ }
1844
+
1845
+ /**
1846
+ * The in-process `Eliza1EotClassifier` required a node-bound `LlamaModel`
1847
+ * forward pass, which the FFI runtime does not expose. Always null now —
1848
+ * callers fall through to the GGUF (FFI) turn-detector and then the
1849
+ * heuristic chain.
1850
+ */
1851
+ private tryBuildEliza1EotClassifier(
1852
+ _mode: "prefer" | "force",
1853
+ _loraPath: string | undefined,
1854
+ ): import("./voice/eot-classifier").Eliza1EotClassifier | null {
1855
+ return null;
1856
+ }
1857
+ }
1858
+
1859
+ /**
1860
+ * Resolve which EOT classifier to build for a voice session. Precedence:
1861
+ * 1. Explicit `opts.useEliza1Eot` (`true` → `"force"`; `false` → `"off"`;
1862
+ * `"auto"` or unset → step 2).
1863
+ * 2. `ELIZA_VOICE_EOT_BACKEND` env var (`eliza-1` → `"force"`, anything
1864
+ * else like `livekit`/`turnsense`/`heuristic` → `"off"`; unset →
1865
+ * step 3).
1866
+ * 3. Default `"prefer"` — we try eliza-1 first when available and fall
1867
+ * back to LiveKit/Heuristic when the in-process backend is unavailable.
1868
+ *
1869
+ * Returns:
1870
+ * - `"force"` — must build; throw if preconditions fail.
1871
+ * - `"prefer"` — try; on null, fall through to the LiveKit chain.
1872
+ * - `"off"` — skip eliza-1 entirely.
1873
+ */
1874
+ function resolveEliza1EotSelection(
1875
+ optsValue: boolean | "auto" | undefined,
1876
+ _loraPath: string | undefined,
1877
+ ): "force" | "prefer" | "off" {
1878
+ if (optsValue === true) return "force";
1879
+ if (optsValue === false) return "off";
1880
+ const envValue = process.env.ELIZA_VOICE_EOT_BACKEND?.trim().toLowerCase();
1881
+ if (envValue === "eliza-1" || envValue === "eliza1") return "force";
1882
+ if (
1883
+ envValue === "livekit" ||
1884
+ envValue === "turnsense" ||
1885
+ envValue === "heuristic"
1886
+ )
1887
+ return "off";
1888
+ return "prefer";
1889
+ }
1890
+
1891
+ export const localInferenceEngine = new LocalInferenceEngine();