@elizaos/plugin-local-inference 2.0.0-beta.1 → 2.0.3-beta.2

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