@qvac/sdk 0.10.2 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (326) hide show
  1. package/NOTICE +1455 -29
  2. package/README.md +2 -0
  3. package/dist/client/api/cancel.d.ts +24 -32
  4. package/dist/client/api/cancel.js +58 -31
  5. package/dist/client/api/classify.d.ts +23 -0
  6. package/dist/client/api/classify.js +43 -0
  7. package/dist/client/api/client-request-id.d.ts +17 -0
  8. package/dist/client/api/client-request-id.js +27 -0
  9. package/dist/client/api/completion-stream.d.ts +1 -1
  10. package/dist/client/api/completion-stream.js +34 -3
  11. package/dist/client/api/diffusion.d.ts +46 -0
  12. package/dist/client/api/diffusion.js +50 -1
  13. package/dist/client/api/download-asset.d.ts +12 -2
  14. package/dist/client/api/download-asset.js +21 -3
  15. package/dist/client/api/embed.d.ts +8 -4
  16. package/dist/client/api/embed.js +14 -1
  17. package/dist/client/api/get-model-info.d.ts +1 -1
  18. package/dist/client/api/index.d.ts +5 -0
  19. package/dist/client/api/index.js +5 -0
  20. package/dist/client/api/load-model.d.ts +12 -4
  21. package/dist/client/api/load-model.js +49 -2
  22. package/dist/client/api/rag.d.ts +9 -3
  23. package/dist/client/api/rag.js +23 -3
  24. package/dist/client/api/transcribe.d.ts +23 -8
  25. package/dist/client/api/transcribe.js +69 -4
  26. package/dist/client/api/unload-model.d.ts +5 -2
  27. package/dist/client/api/unload-model.js +9 -4
  28. package/dist/client/api/upscale.d.ts +45 -0
  29. package/dist/client/api/upscale.js +99 -0
  30. package/dist/client/api/video.d.ts +64 -0
  31. package/dist/client/api/video.js +147 -0
  32. package/dist/client/api/vla-helpers.d.ts +45 -0
  33. package/dist/client/api/vla-helpers.js +130 -0
  34. package/dist/client/api/vla.d.ts +65 -0
  35. package/dist/client/api/vla.js +109 -0
  36. package/dist/client/config-loader/resolve-config.node.d.ts +16 -0
  37. package/dist/client/config-loader/resolve-config.node.js +77 -23
  38. package/dist/client/plugins-factory.d.ts +8 -0
  39. package/dist/client/plugins-factory.js +10 -0
  40. package/dist/client/rpc/bare-client.js +62 -66
  41. package/dist/client/rpc/ensure-worker-ready.d.ts +9 -0
  42. package/dist/client/rpc/ensure-worker-ready.js +17 -0
  43. package/dist/client/rpc/expo-rpc-client.js +2 -1
  44. package/dist/client/rpc/node-rpc-client.js +22 -8
  45. package/dist/client/rpc/rpc-client.d.ts +2 -2
  46. package/dist/client/rpc/rpc-client.js +10 -4
  47. package/dist/client/rpc/rpc-error.d.ts +9 -0
  48. package/dist/client/rpc/rpc-error.js +105 -0
  49. package/dist/commands/bundle/bare-pack.d.ts +13 -0
  50. package/dist/commands/bundle/bare-pack.js +54 -0
  51. package/dist/commands/bundle/constants.d.ts +7 -0
  52. package/dist/commands/bundle/constants.js +23 -0
  53. package/dist/commands/bundle/entry-gen.d.ts +2 -0
  54. package/dist/commands/bundle/entry-gen.js +48 -0
  55. package/dist/commands/bundle/index.d.ts +20 -0
  56. package/dist/commands/bundle/index.js +141 -0
  57. package/dist/commands/bundle/manifest.d.ts +21 -0
  58. package/dist/commands/bundle/manifest.js +193 -0
  59. package/dist/commands/bundle/plugins.d.ts +9 -0
  60. package/dist/commands/bundle/plugins.js +51 -0
  61. package/dist/commands/index.d.ts +5 -0
  62. package/dist/commands/index.js +2 -0
  63. package/dist/commands/verify/abi.d.ts +52 -0
  64. package/dist/commands/verify/abi.js +125 -0
  65. package/dist/commands/verify/addon-source.d.ts +43 -0
  66. package/dist/commands/verify/addon-source.js +75 -0
  67. package/dist/commands/verify/bundle-source.d.ts +12 -0
  68. package/dist/commands/verify/bundle-source.js +53 -0
  69. package/dist/commands/verify/index.d.ts +59 -0
  70. package/dist/commands/verify/index.js +371 -0
  71. package/dist/commands/verify/node-modules-source.d.ts +11 -0
  72. package/dist/commands/verify/node-modules-source.js +76 -0
  73. package/dist/commands/verify/prebuilds.d.ts +15 -0
  74. package/dist/commands/verify/prebuilds.js +39 -0
  75. package/dist/examples/cancel-by-request-id.d.ts +38 -0
  76. package/dist/examples/cancel-by-request-id.js +103 -0
  77. package/dist/examples/classification/classify-image.d.ts +2 -0
  78. package/dist/examples/classification/classify-image.js +23 -0
  79. package/dist/examples/diffusion-esrgan-upscale.d.ts +2 -0
  80. package/dist/examples/diffusion-esrgan-upscale.js +78 -0
  81. package/dist/examples/diffusion-txt2vid.d.ts +2 -0
  82. package/dist/examples/diffusion-txt2vid.js +81 -0
  83. package/dist/examples/download-with-cancel.js +10 -10
  84. package/dist/examples/embed-multi-gpu.d.ts +2 -0
  85. package/dist/examples/embed-multi-gpu.js +46 -0
  86. package/dist/examples/llamacpp-multi-gpu.d.ts +2 -0
  87. package/dist/examples/llamacpp-multi-gpu.js +57 -0
  88. package/dist/examples/plugins.js +3 -7
  89. package/dist/examples/rag/rag-hyperdb/cancellation.js +20 -17
  90. package/dist/examples/tools/llamacpp-tools-gemma4.d.ts +2 -0
  91. package/dist/examples/tools/llamacpp-tools-gemma4.js +73 -0
  92. package/dist/examples/tools/llamacpp-tools-qwen35.d.ts +2 -0
  93. package/dist/examples/tools/llamacpp-tools-qwen35.js +69 -0
  94. package/dist/examples/transcription/parakeet-ctc-filesystem.js +18 -12
  95. package/dist/examples/transcription/parakeet-microphone-record.js +7 -12
  96. package/dist/examples/transcription/parakeet-microphone-stream.d.ts +2 -0
  97. package/dist/examples/transcription/parakeet-microphone-stream.js +79 -0
  98. package/dist/examples/transcription/parakeet-sortformer-streaming.d.ts +2 -0
  99. package/dist/examples/transcription/parakeet-sortformer-streaming.js +121 -0
  100. package/dist/examples/transcription/parakeet-sortformer.js +58 -55
  101. package/dist/examples/transcription/parakeet-tdt-filesystem.js +18 -15
  102. package/dist/examples/transcription/whispercpp-microphone-conversation.d.ts +2 -0
  103. package/dist/examples/transcription/whispercpp-microphone-conversation.js +107 -0
  104. package/dist/examples/tts/chatterbox.js +7 -16
  105. package/dist/examples/tts/llm-to-tts-streaming.js +3 -10
  106. package/dist/examples/tts/supertonic-multilingual.js +4 -12
  107. package/dist/examples/tts/supertonic.js +5 -12
  108. package/dist/examples/vla-smolvla.d.ts +2 -0
  109. package/dist/examples/vla-smolvla.js +75 -0
  110. package/dist/examples/voice-assistant/voice-assistant.js +3 -10
  111. package/dist/expo/plugins/find-in-ancestor-node-modules.d.ts +14 -0
  112. package/dist/expo/plugins/find-in-ancestor-node-modules.js +24 -0
  113. package/dist/expo/plugins/get-project-root.d.ts +22 -0
  114. package/dist/expo/plugins/get-project-root.js +23 -0
  115. package/dist/expo/plugins/index.d.ts +4 -0
  116. package/dist/expo/plugins/index.js +4 -0
  117. package/dist/expo/plugins/resolve-sdk-package-dir.d.ts +9 -2
  118. package/dist/expo/plugins/resolve-sdk-package-dir.js +38 -11
  119. package/dist/expo/plugins/withDeviceInfo.js +2 -1
  120. package/dist/expo/plugins/withMobileBundle.d.ts +5 -4
  121. package/dist/expo/plugins/withMobileBundle.js +42 -58
  122. package/dist/index.d.ts +6 -2
  123. package/dist/index.js +23 -2
  124. package/dist/models/registry/models.d.ts +3725 -514
  125. package/dist/models/registry/models.js +7269 -3910
  126. package/dist/models/update-models/naming.js +22 -8
  127. package/dist/pear/pre.d.ts +3 -0
  128. package/dist/pear/pre.js +9 -2
  129. package/dist/schemas/cancel.d.ts +172 -28
  130. package/dist/schemas/cancel.js +120 -19
  131. package/dist/schemas/classification.d.ts +53 -0
  132. package/dist/schemas/classification.js +33 -0
  133. package/dist/schemas/common.d.ts +860 -1379
  134. package/dist/schemas/common.js +8 -1
  135. package/dist/schemas/completion-event.d.ts +17 -0
  136. package/dist/schemas/completion-event.js +12 -1
  137. package/dist/schemas/completion-stream.d.ts +16 -1
  138. package/dist/schemas/completion-stream.js +25 -7
  139. package/dist/schemas/download-asset.d.ts +25 -9
  140. package/dist/schemas/download-asset.js +17 -6
  141. package/dist/schemas/embed.d.ts +1 -0
  142. package/dist/schemas/embed.js +5 -0
  143. package/dist/schemas/engine-addon-map.d.ts +3 -0
  144. package/dist/schemas/engine-addon-map.js +18 -5
  145. package/dist/schemas/error.d.ts +31 -0
  146. package/dist/schemas/error.js +29 -1
  147. package/dist/schemas/finetune.d.ts +2 -0
  148. package/dist/schemas/finetune.js +5 -0
  149. package/dist/schemas/get-model-info.d.ts +10 -6
  150. package/dist/schemas/get-model-info.js +2 -0
  151. package/dist/schemas/index.d.ts +3 -0
  152. package/dist/schemas/index.js +3 -0
  153. package/dist/schemas/llamacpp-config.d.ts +64 -8
  154. package/dist/schemas/llamacpp-config.js +12 -0
  155. package/dist/schemas/load-model.d.ts +4644 -8605
  156. package/dist/schemas/load-model.js +90 -7
  157. package/dist/schemas/model-src-utils.d.ts +34 -14
  158. package/dist/schemas/model-types.d.ts +54 -14
  159. package/dist/schemas/model-types.js +28 -5
  160. package/dist/schemas/ocr.d.ts +8 -3
  161. package/dist/schemas/plugin.d.ts +60 -6
  162. package/dist/schemas/plugin.js +31 -5
  163. package/dist/schemas/rag.d.ts +9 -0
  164. package/dist/schemas/rag.js +17 -9
  165. package/dist/schemas/registry.d.ts +74 -30
  166. package/dist/schemas/registry.js +5 -0
  167. package/dist/schemas/reload-config.d.ts +34 -14
  168. package/dist/schemas/sdcpp-config.d.ts +445 -16
  169. package/dist/schemas/sdcpp-config.js +387 -26
  170. package/dist/schemas/sdk-config.d.ts +2431 -2723
  171. package/dist/schemas/sdk-config.js +16 -1
  172. package/dist/schemas/sdk-errors-client.d.ts +6 -0
  173. package/dist/schemas/sdk-errors-client.js +31 -1
  174. package/dist/schemas/sdk-errors-server.d.ts +8 -1
  175. package/dist/schemas/sdk-errors-server.js +45 -5
  176. package/dist/schemas/text-to-speech.d.ts +81 -698
  177. package/dist/schemas/text-to-speech.js +46 -19
  178. package/dist/schemas/transcription-config.d.ts +40 -229
  179. package/dist/schemas/transcription-config.js +76 -15
  180. package/dist/schemas/transcription.d.ts +108 -2
  181. package/dist/schemas/transcription.js +81 -0
  182. package/dist/schemas/translate.d.ts +2 -0
  183. package/dist/schemas/translate.js +13 -2
  184. package/dist/schemas/translation-config.d.ts +90 -40
  185. package/dist/schemas/unload-model.d.ts +2 -1
  186. package/dist/schemas/unload-model.js +4 -1
  187. package/dist/schemas/vla.d.ts +87 -0
  188. package/dist/schemas/vla.js +108 -0
  189. package/dist/scripts/run-unit-tests.js +22 -3
  190. package/dist/server/bare/ops/cancel.d.ts +27 -1
  191. package/dist/server/bare/ops/cancel.js +36 -10
  192. package/dist/server/bare/ops/embed.d.ts +3 -3
  193. package/dist/server/bare/ops/embed.js +144 -28
  194. package/dist/server/bare/ops/kv-cache-utils.d.ts +0 -7
  195. package/dist/server/bare/ops/kv-cache-utils.js +8 -47
  196. package/dist/server/bare/ops/transcribe.d.ts +11 -5
  197. package/dist/server/bare/ops/transcribe.js +230 -50
  198. package/dist/server/bare/ops/translate.d.ts +1 -1
  199. package/dist/server/bare/ops/translate.js +197 -88
  200. package/dist/server/bare/plugins/ggml-classification/ops/classify.d.ts +6 -0
  201. package/dist/server/bare/plugins/ggml-classification/ops/classify.js +30 -0
  202. package/dist/server/bare/plugins/ggml-classification/plugin.d.ts +32 -0
  203. package/dist/server/bare/plugins/ggml-classification/plugin.js +55 -0
  204. package/dist/server/bare/plugins/ggml-vla/ops/vla-hparams.d.ts +3 -0
  205. package/dist/server/bare/plugins/ggml-vla/ops/vla-hparams.js +12 -0
  206. package/dist/server/bare/plugins/ggml-vla/ops/vla-run.d.ts +3 -0
  207. package/dist/server/bare/plugins/ggml-vla/ops/vla-run.js +75 -0
  208. package/dist/server/bare/plugins/ggml-vla/plugin.d.ts +54 -0
  209. package/dist/server/bare/plugins/ggml-vla/plugin.js +57 -0
  210. package/dist/server/bare/plugins/index.d.ts +3 -1
  211. package/dist/server/bare/plugins/index.js +3 -1
  212. package/dist/server/bare/plugins/llamacpp-completion/ops/completion-stream.d.ts +12 -3
  213. package/dist/server/bare/plugins/llamacpp-completion/ops/completion-stream.js +173 -172
  214. package/dist/server/bare/plugins/llamacpp-completion/ops/context-overflow.d.ts +29 -0
  215. package/dist/server/bare/plugins/llamacpp-completion/ops/context-overflow.js +65 -0
  216. package/dist/server/bare/plugins/llamacpp-completion/ops/finetune.js +125 -21
  217. package/dist/server/bare/plugins/llamacpp-completion/ops/kv-cache-session.d.ts +154 -0
  218. package/dist/server/bare/plugins/llamacpp-completion/ops/kv-cache-session.js +448 -0
  219. package/dist/server/bare/plugins/llamacpp-completion/ops/kv-cache-state.d.ts +21 -73
  220. package/dist/server/bare/plugins/llamacpp-completion/ops/kv-cache-state.js +18 -101
  221. package/dist/server/bare/plugins/llamacpp-completion/plugin.d.ts +36 -3
  222. package/dist/server/bare/plugins/llamacpp-completion/plugin.js +183 -85
  223. package/dist/server/bare/plugins/llamacpp-completion/transform.d.ts +10 -0
  224. package/dist/server/bare/plugins/llamacpp-completion/transform.js +34 -0
  225. package/dist/server/bare/plugins/llamacpp-embedding/plugin.d.ts +7 -0
  226. package/dist/server/bare/plugins/llamacpp-embedding/plugin.js +10 -1
  227. package/dist/server/bare/plugins/nmtcpp-translation/plugin.d.ts +42 -15
  228. package/dist/server/bare/plugins/nmtcpp-translation/plugin.js +5 -1
  229. package/dist/server/bare/plugins/onnx-ocr/plugin.d.ts +8 -3
  230. package/dist/server/bare/plugins/onnx-ocr/plugin.js +3 -0
  231. package/dist/server/bare/plugins/parakeet-transcription/plugin.d.ts +73 -244
  232. package/dist/server/bare/plugins/parakeet-transcription/plugin.js +68 -96
  233. package/dist/server/bare/plugins/sdcpp-generation/ops/diffusion.js +8 -0
  234. package/dist/server/bare/plugins/sdcpp-generation/ops/upscale.d.ts +3 -0
  235. package/dist/server/bare/plugins/sdcpp-generation/ops/upscale.js +40 -0
  236. package/dist/server/bare/plugins/sdcpp-generation/ops/video.d.ts +3 -0
  237. package/dist/server/bare/plugins/sdcpp-generation/ops/video.js +199 -0
  238. package/dist/server/bare/plugins/sdcpp-generation/plugin.d.ts +288 -15
  239. package/dist/server/bare/plugins/sdcpp-generation/plugin.js +150 -7
  240. package/dist/server/bare/plugins/{onnx-tts → tts-ggml}/ops/text-to-speech-stream.js +2 -15
  241. package/dist/server/bare/plugins/{onnx-tts → tts-ggml}/ops/text-to-speech.js +2 -1
  242. package/dist/server/bare/plugins/tts-ggml/plugin.d.ts +75 -0
  243. package/dist/server/bare/plugins/tts-ggml/plugin.js +189 -0
  244. package/dist/server/bare/plugins/whispercpp-transcription/plugin.d.ts +47 -3
  245. package/dist/server/bare/plugins/whispercpp-transcription/plugin.js +61 -14
  246. package/dist/server/bare/rag-hyperdb/index.d.ts +1 -1
  247. package/dist/server/bare/rag-hyperdb/index.js +1 -1
  248. package/dist/server/bare/rag-hyperdb/rag-operation-manager.d.ts +26 -4
  249. package/dist/server/bare/rag-hyperdb/rag-operation-manager.js +65 -28
  250. package/dist/server/bare/registry/model-config-utils.js +7 -0
  251. package/dist/server/bare/runtime/disposable-scope.d.ts +36 -0
  252. package/dist/server/bare/runtime/disposable-scope.js +69 -0
  253. package/dist/server/bare/runtime/index.d.ts +8 -0
  254. package/dist/server/bare/runtime/index.js +3 -0
  255. package/dist/server/bare/runtime/request-context.d.ts +49 -0
  256. package/dist/server/bare/runtime/request-context.js +1 -0
  257. package/dist/server/bare/runtime/request-id.d.ts +12 -0
  258. package/dist/server/bare/runtime/request-id.js +14 -0
  259. package/dist/server/bare/runtime/request-registry-singleton.d.ts +4 -0
  260. package/dist/server/bare/runtime/request-registry-singleton.js +27 -0
  261. package/dist/server/bare/runtime/request-registry.d.ts +136 -0
  262. package/dist/server/bare/runtime/request-registry.js +297 -0
  263. package/dist/server/bare/runtime/with-request-context.d.ts +22 -0
  264. package/dist/server/bare/runtime/with-request-context.js +53 -0
  265. package/dist/server/bare/runtime-lifecycle.js +9 -9
  266. package/dist/server/bare/types/addon-responses.d.ts +12 -1
  267. package/dist/server/env.js +4 -1
  268. package/dist/server/plugins/index.d.ts +1 -1
  269. package/dist/server/plugins/index.js +1 -1
  270. package/dist/server/plugins/registry.d.ts +1 -0
  271. package/dist/server/plugins/registry.js +5 -0
  272. package/dist/server/rpc/handler-registry.js +30 -7
  273. package/dist/server/rpc/handler-selection.d.ts +9 -0
  274. package/dist/server/rpc/handler-selection.js +14 -0
  275. package/dist/server/rpc/handler-utils.js +5 -13
  276. package/dist/server/rpc/handlers/cancel-delegated.js +28 -31
  277. package/dist/server/rpc/handlers/cancelHandler.d.ts +30 -1
  278. package/dist/server/rpc/handlers/cancelHandler.js +54 -22
  279. package/dist/server/rpc/handlers/classify.d.ts +3 -0
  280. package/dist/server/rpc/handlers/classify.js +4 -0
  281. package/dist/server/rpc/handlers/delete-cache.d.ts +9 -0
  282. package/dist/server/rpc/handlers/delete-cache.js +13 -15
  283. package/dist/server/rpc/handlers/download-asset.js +133 -40
  284. package/dist/server/rpc/handlers/index.d.ts +4 -0
  285. package/dist/server/rpc/handlers/index.js +4 -0
  286. package/dist/server/rpc/handlers/load-model/download-manager.d.ts +60 -2
  287. package/dist/server/rpc/handlers/load-model/download-manager.js +141 -8
  288. package/dist/server/rpc/handlers/load-model/handler.js +216 -98
  289. package/dist/server/rpc/handlers/load-model/http.js +3 -3
  290. package/dist/server/rpc/handlers/load-model/hyperdrive.js +1 -1
  291. package/dist/server/rpc/handlers/load-model/registry.js +1 -1
  292. package/dist/server/rpc/handlers/load-model/resolve-session.d.ts +20 -1
  293. package/dist/server/rpc/handlers/load-model/resolve-session.js +6 -5
  294. package/dist/server/rpc/handlers/load-model/resolve.d.ts +3 -2
  295. package/dist/server/rpc/handlers/load-model/resolve.js +18 -6
  296. package/dist/server/rpc/handlers/load-model/types.d.ts +24 -0
  297. package/dist/server/rpc/handlers/rag.js +133 -15
  298. package/dist/server/rpc/handlers/upscale-stream.d.ts +3 -0
  299. package/dist/server/rpc/handlers/upscale-stream.js +4 -0
  300. package/dist/server/rpc/handlers/video-stream.d.ts +3 -0
  301. package/dist/server/rpc/handlers/video-stream.js +4 -0
  302. package/dist/server/rpc/profiling/operation-metrics.js +23 -0
  303. package/dist/server/utils/completion-normalizer.js +8 -0
  304. package/dist/server/utils/config-transform.js +1 -1
  305. package/dist/server/utils/tools/dialect.js +4 -0
  306. package/dist/server/utils/tools/parser.js +16 -1
  307. package/dist/server/utils/tools/parsers/gemma4native.d.ts +4 -0
  308. package/dist/server/utils/tools/parsers/gemma4native.js +60 -0
  309. package/dist/server/utils/tools/parsers/qwen35.d.ts +4 -0
  310. package/dist/server/utils/tools/parsers/qwen35.js +120 -0
  311. package/dist/server/worker.js +14 -11
  312. package/dist/utils/aggregate-events.d.ts +9 -0
  313. package/dist/utils/aggregate-events.js +18 -3
  314. package/dist/utils/decorate-promise.d.ts +34 -0
  315. package/dist/utils/decorate-promise.js +35 -0
  316. package/dist/utils/errors-client.d.ts +18 -0
  317. package/dist/utils/errors-client.js +31 -0
  318. package/dist/utils/errors-server.d.ts +115 -2
  319. package/dist/utils/errors-server.js +148 -3
  320. package/package.json +68 -77
  321. package/dist/server/bare/plugins/onnx-tts/plugin.d.ts +0 -490
  322. package/dist/server/bare/plugins/onnx-tts/plugin.js +0 -266
  323. package/dist/server/bare/plugins/onnx-tts/wav-helper.d.ts +0 -14
  324. package/dist/server/bare/plugins/onnx-tts/wav-helper.js +0 -107
  325. /package/dist/server/bare/plugins/{onnx-tts → tts-ggml}/ops/text-to-speech-stream.d.ts +0 -0
  326. /package/dist/server/bare/plugins/{onnx-tts → tts-ggml}/ops/text-to-speech.d.ts +0 -0
@@ -1,114 +1,31 @@
1
1
  /**
2
- * Pure state + decision helpers for kv-cache bookkeeping used by
3
- * `completion-stream.ts`.
2
+ * Pure decision helper for kv-cache history slicing used by
3
+ * `completion-stream.ts` (via the slice computed from
4
+ * `TurnHandle.savedCount`).
4
5
  *
5
6
  * This module intentionally has **no** `bare-*` imports so it can be
6
- * exercised directly from unit tests running under `bun` without pulling
7
- * in the Bare runtime (which is not available in that environment).
8
- * The file-system-dependent pieces (e.g. `recordCacheSaveCount`) live in
9
- * `completion-stream.ts` and consume the state exported here.
10
- */
11
- /**
12
- * Number of chat messages the kv-cache file on disk is known to cover, keyed
13
- * by cache path. Written after a successful completion records a save, read
14
- * by `prepareMessagesForCache` to slice the history on the next turn so a
15
- * consumer can stage multiple messages between completions (e.g. an
16
- * `[assistant, user]` recovery sequence) without resending the whole history.
17
- *
18
- * INVARIANT: an entry is only present if the corresponding kv-cache file is
19
- * considered trustworthy. On any turn where the SDK cannot prove the saved
20
- * count reflects the on-disk state (cancellation mid-decode, zero-token
21
- * reply, cache file missing after a save attempt), the entry MUST be
22
- * deleted; a stale entry causes the next turn to slice its history down to
23
- * an empty payload and the model returns zero tokens.
24
- *
25
- * Mode notes:
26
- * - Static-mode turns are the only readers of this map. `clearStaleCount`
27
- * in `decideCachedHistorySlice` exists so a stale-but-non-zero entry
28
- * can be detected and dropped on the next read.
29
- * - Dynamic-mode turns do NOT consume this map — the addon trims tools
30
- * and the chain output from the kv-cache after each round, so the
31
- * SDK falls back to role-based dispatch in `prepareMessagesForCache`.
32
- * Writes still happen on dynamic-mode turns, but the recorded count
33
- * reflects the messages the SDK shipped, not the (possibly trimmed)
34
- * on-disk cache shape. The map is internally consistent within a
35
- * single mode; a `kvCache` key should not be reused across modes.
36
- */
37
- export const cachedMessageCounts = new Map();
38
- /**
39
- * Monotonic counter of cancel requests per model. `completion()` snapshots
40
- * the value before running the model and compares afterward to decide
41
- * whether the turn was cancelled mid-decode. A counter (not a boolean) is
42
- * used deliberately: a cancel that lands near a turn boundary cannot bleed
43
- * into the next turn because we always compare snapshots, not values.
44
- */
45
- const modelCancelCounters = new Map();
46
- /**
47
- * Clear bookkeeping entries. With no argument, clears the whole map. With a
48
- * `prefix`, removes any entry whose path is equal to it OR sits beneath it
49
- * as a directory (i.e. `key.startsWith(prefix + sep)`).
7
+ * exercised directly from unit tests running under `bun` without
8
+ * pulling in the Bare runtime (which is not available in that
9
+ * environment).
50
10
  *
51
- * Runtime callers MUST pass the platform path separator (e.g. `path.sep`
52
- * from `bare-path`) so directory-prefix matches are correct on every
53
- * target. The "/" default exists only for unit tests under `bun`, where
54
- * cache paths are POSIX-shaped and importing `bare-path` would pull in
55
- * the Bare runtime. The exported wrapper in `completion-stream.ts`
56
- * injects the real separator for in-process use.
11
+ * Cancel detection flows through the per-request `AbortSignal` from
12
+ * `RequestRegistry`; the `cachedMessageCounts` map lives in
13
+ * `kv-cache-session.ts`, which owns all three KV-cache bookkeeping
14
+ * layers (saved counts, init flags, on-disk files). Only the pure
15
+ * slice-decision helper remains here.
57
16
  */
58
- export function clearCachedMessageCounts(prefix, sep = "/") {
59
- if (!prefix) {
60
- cachedMessageCounts.clear();
61
- return;
62
- }
63
- for (const key of cachedMessageCounts.keys()) {
64
- if (key === prefix) {
65
- cachedMessageCounts.delete(key);
66
- continue;
67
- }
68
- if (!key.startsWith(prefix + sep))
69
- continue;
70
- cachedMessageCounts.delete(key);
71
- }
72
- }
73
- /**
74
- * Called from `server/bare/ops/cancel.ts` right before `addon.cancel()` so
75
- * that the in-flight `completion()` for this model can detect that its
76
- * current turn is being cancelled and skip poisoning `cachedMessageCounts`
77
- * with a `history.length + 1` entry that does not correspond to a real
78
- * assistant reply.
79
- */
80
- export function noteCancelRequested(modelId) {
81
- modelCancelCounters.set(modelId, (modelCancelCounters.get(modelId) ?? 0) + 1);
82
- }
83
- export function snapshotCancelCount(modelId) {
84
- return modelCancelCounters.get(modelId) ?? 0;
85
- }
86
- /** Test-only. */
87
- export function _resetCancelCountersForTest() {
88
- modelCancelCounters.clear();
89
- }
90
- /**
91
- * A completion's `savedCount` should only be recorded when the turn ran to
92
- * completion AND produced at least one token. Any other outcome —
93
- * cancelled mid-decode, legitimate zero-token reply, or an early EOS — must
94
- * clear the entry instead, because there is no guarantee that the kv-cache
95
- * file on disk matches the `history.length + 1` boundary the SDK would
96
- * otherwise record.
97
- */
98
- export function shouldRecordSavedCount(wasCancelled, producedTokens) {
99
- return !wasCancelled && producedTokens;
100
- }
101
17
  /**
102
18
  * Pure slice decision for `prepareMessagesForCache`.
103
19
  *
104
20
  * Mirrors the shape of the logic in `completion-stream.ts` but without
105
- * calling `transformMessages` (which depends on `bare-fs` for attachment
106
- * probing). Kept here so the decision can be unit-tested in isolation.
21
+ * calling `transformMessages` (which depends on `bare-fs` for
22
+ * attachment probing). Kept here so the decision can be unit-tested in
23
+ * isolation.
107
24
  *
108
- * The key regression guard: when a non-zero `savedCount` would slice the
109
- * history down to an empty array, it is treated as stale — the caller
110
- * falls back to sending the system-stripped full history rather than
111
- * handing the model an empty payload.
25
+ * The key regression guard: when a non-zero `savedCount` would slice
26
+ * the history down to an empty array, it is treated as stale — the
27
+ * caller falls back to sending the system-stripped full history rather
28
+ * than handing the model an empty payload.
112
29
  */
113
30
  export function decideCachedHistorySlice(savedCount, cacheExists, history) {
114
31
  if (!cacheExists || history.length === 0) {
@@ -28,7 +28,18 @@ export declare const llmPlugin: {
28
28
  }>>;
29
29
  "cache-type-k": import("zod").ZodOptional<import("zod").ZodString>;
30
30
  "cache-type-v": import("zod").ZodOptional<import("zod").ZodString>;
31
+ "main-gpu": import("zod").ZodOptional<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodEnum<{
32
+ integrated: "integrated";
33
+ dedicated: "dedicated";
34
+ }>]>>;
35
+ "split-mode": import("zod").ZodOptional<import("zod").ZodEnum<{
36
+ none: "none";
37
+ layer: "layer";
38
+ row: "row";
39
+ }>>;
40
+ "tensor-split": import("zod").ZodOptional<import("zod").ZodString>;
31
41
  openclCacheDir: import("zod").ZodOptional<import("zod").ZodString>;
42
+ reasoning_budget: import("zod").ZodOptional<import("zod").ZodUnion<readonly [import("zod").ZodLiteral<-1>, import("zod").ZodLiteral<0>]>>;
32
43
  projectionModelSrc: import("zod").ZodOptional<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodObject<{
33
44
  src: import("zod").ZodString;
34
45
  name: import("zod").ZodOptional<import("zod").ZodString>;
@@ -42,21 +53,26 @@ export declare const llmPlugin: {
42
53
  sha256Checksum: import("zod").ZodOptional<import("zod").ZodString>;
43
54
  addon: import("zod").ZodOptional<import("zod").ZodUnion<readonly [import("zod").ZodEnum<{
44
55
  embeddings: "embeddings";
56
+ diffusion: "diffusion";
57
+ tts: "tts";
58
+ ocr: "ocr";
59
+ vla: "vla";
45
60
  "llamacpp-completion": "llamacpp-completion";
46
61
  "whispercpp-transcription": "whispercpp-transcription";
47
62
  "llamacpp-embedding": "llamacpp-embedding";
48
63
  "nmtcpp-translation": "nmtcpp-translation";
49
64
  "onnx-tts": "onnx-tts";
65
+ "tts-ggml": "tts-ggml";
50
66
  "parakeet-transcription": "parakeet-transcription";
51
67
  "onnx-ocr": "onnx-ocr";
52
68
  "sdcpp-generation": "sdcpp-generation";
69
+ "ggml-vla": "ggml-vla";
70
+ "ggml-classification": "ggml-classification";
53
71
  llm: "llm";
54
72
  whisper: "whisper";
55
73
  nmt: "nmt";
56
74
  parakeet: "parakeet";
57
- tts: "tts";
58
- ocr: "ocr";
59
- diffusion: "diffusion";
75
+ classification: "classification";
60
76
  }>, import("zod").ZodLiteral<"vad">]>>;
61
77
  }, import("zod/v4/core").$strip>]>>;
62
78
  }, import("zod/v4/core").$strip>;
@@ -83,7 +99,11 @@ export declare const llmPlugin: {
83
99
  toolsMode?: "static" | "dynamic" | undefined;
84
100
  "cache-type-k"?: string | undefined;
85
101
  "cache-type-v"?: string | undefined;
102
+ "main-gpu"?: number | "integrated" | "dedicated" | undefined;
103
+ "split-mode"?: "none" | "layer" | "row" | undefined;
104
+ "tensor-split"?: string | undefined;
86
105
  openclCacheDir?: string | undefined;
106
+ reasoning_budget?: 0 | -1 | undefined;
87
107
  };
88
108
  artifacts?: never;
89
109
  } | {
@@ -109,7 +129,11 @@ export declare const llmPlugin: {
109
129
  toolsMode?: "static" | "dynamic" | undefined;
110
130
  "cache-type-k"?: string | undefined;
111
131
  "cache-type-v"?: string | undefined;
132
+ "main-gpu"?: number | "integrated" | "dedicated" | undefined;
133
+ "split-mode"?: "none" | "layer" | "row" | undefined;
134
+ "tensor-split"?: string | undefined;
112
135
  openclCacheDir?: string | undefined;
136
+ reasoning_budget?: 0 | -1 | undefined;
113
137
  };
114
138
  artifacts: {
115
139
  projectionModelPath: string;
@@ -158,6 +182,7 @@ export declare const llmPlugin: {
158
182
  frequency_penalty: import("zod").ZodOptional<import("zod").ZodNumber>;
159
183
  presence_penalty: import("zod").ZodOptional<import("zod").ZodNumber>;
160
184
  repeat_penalty: import("zod").ZodOptional<import("zod").ZodNumber>;
185
+ reasoning_budget: import("zod").ZodOptional<import("zod").ZodUnion<readonly [import("zod").ZodLiteral<-1>, import("zod").ZodLiteral<0>]>>;
161
186
  }, import("zod/v4/core").$strict>>;
162
187
  captureThinking: import("zod").ZodOptional<import("zod").ZodBoolean>;
163
188
  emitRawDeltas: import("zod").ZodOptional<import("zod").ZodBoolean>;
@@ -166,6 +191,8 @@ export declare const llmPlugin: {
166
191
  pythonic: "pythonic";
167
192
  json: "json";
168
193
  harmony: "harmony";
194
+ qwen35: "qwen35";
195
+ gemma4: "gemma4";
169
196
  }>>;
170
197
  responseFormat: import("zod").ZodOptional<import("zod").ZodDiscriminatedUnion<[import("zod").ZodObject<{
171
198
  type: import("zod").ZodLiteral<"text">;
@@ -180,6 +207,7 @@ export declare const llmPlugin: {
180
207
  strict: import("zod").ZodOptional<import("zod").ZodBoolean>;
181
208
  }, import("zod/v4/core").$strict>;
182
209
  }, import("zod/v4/core").$strict>], "type">>;
210
+ requestId: import("zod").ZodOptional<import("zod").ZodString>;
183
211
  type: import("zod").ZodLiteral<"completionStream">;
184
212
  }, import("zod/v4/core").$strip>, import("zod").ZodObject<{
185
213
  type: import("zod").ZodLiteral<"completionStream">;
@@ -224,6 +252,7 @@ export declare const llmPlugin: {
224
252
  timeToFirstToken: import("zod").ZodOptional<import("zod").ZodNumber>;
225
253
  tokensPerSecond: import("zod").ZodOptional<import("zod").ZodNumber>;
226
254
  cacheTokens: import("zod").ZodOptional<import("zod").ZodNumber>;
255
+ promptTokens: import("zod").ZodOptional<import("zod").ZodNumber>;
227
256
  generatedTokens: import("zod").ZodOptional<import("zod").ZodNumber>;
228
257
  backendDevice: import("zod").ZodOptional<import("zod").ZodEnum<{
229
258
  cpu: "cpu";
@@ -244,6 +273,7 @@ export declare const llmPlugin: {
244
273
  type: import("zod").ZodLiteral<"completionDone">;
245
274
  seq: import("zod").ZodNumber;
246
275
  stopReason: import("zod").ZodOptional<import("zod").ZodEnum<{
276
+ cancelled: "cancelled";
247
277
  eos: "eos";
248
278
  length: "length";
249
279
  stopSequence: "stopSequence";
@@ -315,6 +345,7 @@ export declare const llmPlugin: {
315
345
  resume: "resume";
316
346
  }>>;
317
347
  withProgress: import("zod").ZodOptional<import("zod").ZodBoolean>;
348
+ requestId: import("zod").ZodOptional<import("zod").ZodString>;
318
349
  }, import("zod/v4/core").$strict>, import("zod").ZodObject<{
319
350
  modelId: import("zod").ZodString;
320
351
  options: import("zod").ZodObject<{
@@ -412,6 +443,7 @@ export declare const llmPlugin: {
412
443
  nmt: "nmt";
413
444
  }>;
414
445
  type: import("zod").ZodLiteral<"translate">;
446
+ requestId: import("zod").ZodOptional<import("zod").ZodString>;
415
447
  }, import("zod/v4/core").$strip>, import("zod").ZodObject<{
416
448
  modelId: import("zod").ZodString;
417
449
  text: import("zod").ZodString;
@@ -424,6 +456,7 @@ export declare const llmPlugin: {
424
456
  to: import("zod").ZodString;
425
457
  context: import("zod").ZodOptional<import("zod").ZodString>;
426
458
  type: import("zod").ZodLiteral<"translate">;
459
+ requestId: import("zod").ZodOptional<import("zod").ZodString>;
427
460
  }, import("zod/v4/core").$strip>]>, import("zod").ZodObject<{
428
461
  type: import("zod").ZodLiteral<"translate">;
429
462
  token: import("zod").ZodString;
@@ -1,41 +1,73 @@
1
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
2
+ if (value !== null && value !== void 0) {
3
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
+ var dispose, inner;
5
+ if (async) {
6
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
+ dispose = value[Symbol.asyncDispose];
8
+ }
9
+ if (dispose === void 0) {
10
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
+ dispose = value[Symbol.dispose];
12
+ if (async) inner = dispose;
13
+ }
14
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
16
+ env.stack.push({ value: value, dispose: dispose, async: async });
17
+ }
18
+ else if (async) {
19
+ env.stack.push({ async: true });
20
+ }
21
+ return value;
22
+ };
23
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
24
+ return function (env) {
25
+ function fail(e) {
26
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
27
+ env.hasError = true;
28
+ }
29
+ var r, s = 0;
30
+ function next() {
31
+ while (r = env.stack.pop()) {
32
+ try {
33
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
34
+ if (r.dispose) {
35
+ var result = r.dispose.call(r.value);
36
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
37
+ }
38
+ else s |= 1;
39
+ }
40
+ catch (e) {
41
+ fail(e);
42
+ }
43
+ }
44
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
45
+ if (env.hasError) throw env.error;
46
+ }
47
+ return next();
48
+ };
49
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
50
+ var e = new Error(message);
51
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
+ });
1
53
  import LlmLlamacpp from "@qvac/llm-llamacpp";
2
54
  import llmAddonLogging from "@qvac/llm-llamacpp/addonLogging.js";
3
- import { definePlugin, defineHandler, finetuneRequestSchema, completionStreamRequestSchema, completionStreamResponseSchema, finetuneResponseSchema, translateRequestSchema, translateResponseSchema, ModelType, llmConfigBaseSchema, ADDON_LLM, TOOLS_MODE, } from "../../../../schemas/index.js";
55
+ import { definePlugin, defineHandler, finetuneRequestSchema, completionStreamRequestSchema, completionStreamResponseSchema, finetuneResponseSchema, translateRequestSchema, translateResponseSchema, ModelType, llmConfigBaseSchema, ADDON_LLM, } from "../../../../schemas/index.js";
4
56
  import { createStreamLogger, registerAddonLogger } from "../../../../logging/index.js";
5
57
  import { expandGGUFIntoShards } from "../../../utils/index.js";
6
58
  import { completion } from "./ops/completion-stream.js";
7
59
  import { finetune } from "./ops/finetune.js";
8
60
  import { translate } from "../../ops/translate.js";
61
+ import { transformLlmConfig } from "./transform.js";
9
62
  import { attachModelExecutionMs } from "../../../../profiling/model-execution.js";
10
63
  import { getModelConfig } from "../../registry/model-registry.js";
11
64
  import { createCompletionNormalizer } from "../../../utils/completion-normalizer.js";
12
65
  import { detectToolDialect } from "../../../utils/tool-integration.js";
13
- function transformLlmConfig(llmConfig) {
14
- const transformed = JSON.parse(JSON.stringify(llmConfig, (key, v) => key === "modelType"
15
- ? undefined
16
- : key === "stop_sequences"
17
- ? Array.isArray(v)
18
- ? v.join(", ")
19
- : v
20
- : typeof v === "number" || typeof v === "boolean"
21
- ? String(v)
22
- : v).replace(/"([a-z][A-Za-z]*)":/g, (_, key) => `"${key.replace(/[A-Z]/g, (l) => `_${l.toLowerCase()}`)}":`));
23
- if ("stop_sequences" in transformed) {
24
- transformed["reverse_prompt"] = transformed["stop_sequences"];
25
- delete transformed["stop_sequences"];
26
- }
27
- if ("opencl_cache_dir" in transformed) {
28
- transformed["openclCacheDir"] = transformed["opencl_cache_dir"];
29
- delete transformed["opencl_cache_dir"];
30
- }
31
- if ("tools_mode" in transformed) {
32
- if (transformed["tools_mode"] === TOOLS_MODE.dynamic) {
33
- transformed["tools_compact"] = "true";
34
- }
35
- delete transformed["tools_mode"];
36
- }
37
- return transformed;
38
- }
66
+ import { getRequestRegistry, withRequestContext, } from "../../runtime/index.js";
67
+ import { generateServerRequestId } from "../../runtime/request-id.js";
68
+ import { getServerLogger } from "../../../../logging/index.js";
69
+ import { ContextOverflowError } from "../../../../utils/errors-server.js";
70
+ import { isAddonContextOverflowError, parseContextOverflowMessage, } from "./ops/context-overflow.js";
39
71
  function createLlmModel(modelId, modelPath, llmConfig, projectionModelPath) {
40
72
  const logger = createStreamLogger(modelId, ModelType.llamacppCompletion);
41
73
  registerAddonLogger(modelId, ModelType.llamacppCompletion, logger);
@@ -78,71 +110,119 @@ export const llmPlugin = definePlugin({
78
110
  requestSchema: completionStreamRequestSchema,
79
111
  responseSchema: completionStreamResponseSchema,
80
112
  streaming: true,
113
+ cancel: { scope: "model", hard: true },
81
114
  handler: async function* (request) {
82
- const filteredHistory = request.history.map(({ role, content, attachments }) => ({
83
- role,
84
- content,
85
- attachments: attachments ?? [],
86
- }));
87
- const modelCfg = getModelConfig(request.modelId);
88
- const toolsActive = (request.tools?.length ?? 0) > 0 &&
89
- modelCfg.tools === true;
90
- const capabilities = {
91
- toolCalling: toolsActive ? "textParse" : "none",
92
- thinkingFraming: request.captureThinking ? "thinkTags" : "none",
93
- };
94
- // Dialect runs regardless of tool availability — thinking/content
95
- // stripping is needed even on plain completions.
96
- const dialect = request.toolDialect ?? detectToolDialect(request.modelId);
97
- const normalizer = createCompletionNormalizer({
98
- capabilities,
99
- tools: request.tools ?? [],
100
- captureThinking: request.captureThinking ?? false,
101
- emitRawDeltas: request.emitRawDeltas ?? false,
102
- toolDialect: dialect,
103
- });
104
- const stream = completion({
105
- history: filteredHistory,
106
- modelId: request.modelId,
107
- kvCache: request.kvCache,
108
- ...(toolsActive && request.tools && { tools: request.tools }),
109
- ...(request.generationParams && { generationParams: request.generationParams }),
110
- ...(toolsActive && { toolDialect: dialect }),
111
- ...(request.responseFormat && { responseFormat: request.responseFormat }),
112
- });
115
+ const env_1 = { stack: [], error: void 0, hasError: false };
113
116
  try {
114
- const batchedEvents = [];
115
- let result = await stream.next();
116
- while (!result.done) {
117
- const events = normalizer.push(result.value.token);
118
- if (request.stream) {
119
- yield {
120
- type: "completionStream",
121
- events,
122
- };
117
+ const filteredHistory = request.history.map(({ role, content, attachments }) => ({
118
+ role,
119
+ content,
120
+ attachments: attachments ?? [],
121
+ }));
122
+ const modelCfg = getModelConfig(request.modelId);
123
+ const toolsActive = (request.tools?.length ?? 0) > 0 &&
124
+ modelCfg.tools === true;
125
+ const capabilities = {
126
+ toolCalling: toolsActive ? "textParse" : "none",
127
+ thinkingFraming: request.captureThinking ? "thinkTags" : "none",
128
+ };
129
+ // Dialect runs regardless of tool availability — thinking/content
130
+ // stripping is needed even on plain completions.
131
+ const dialect = request.toolDialect ?? detectToolDialect(request.modelId);
132
+ const normalizer = createCompletionNormalizer({
133
+ capabilities,
134
+ tools: request.tools ?? [],
135
+ captureThinking: request.captureThinking ?? false,
136
+ emitRawDeltas: request.emitRawDeltas ?? false,
137
+ toolDialect: dialect,
138
+ });
139
+ // Open a request-scoped lifecycle. The registry is the single
140
+ // source of truth for "is this turn cancelled?" — we plumb the
141
+ // signal into `completion()` and expose `requestId` so the
142
+ // client can target this run with `cancel({ requestId })`.
143
+ // Falls back to a server-generated id if the client (e.g. an
144
+ // older release) didn't send one.
145
+ const ctx = __addDisposableResource(env_1, getRequestRegistry().begin({
146
+ requestId: request.requestId ?? generateServerRequestId(),
147
+ kind: "completion",
148
+ modelId: request.modelId,
149
+ }), true);
150
+ const requestLogger = withRequestContext(getServerLogger(), ctx);
151
+ const stream = completion({
152
+ history: filteredHistory,
153
+ modelId: request.modelId,
154
+ kvCache: request.kvCache,
155
+ ...(toolsActive && request.tools && { tools: request.tools }),
156
+ ...(request.generationParams && { generationParams: request.generationParams }),
157
+ ...(toolsActive && { toolDialect: dialect }),
158
+ ...(request.responseFormat && { responseFormat: request.responseFormat }),
159
+ }, { signal: ctx.signal, scope: ctx.scope, logger: requestLogger });
160
+ try {
161
+ const batchedEvents = [];
162
+ let result = await stream.next();
163
+ while (!result.done) {
164
+ const events = normalizer.push(result.value.token);
165
+ if (request.stream) {
166
+ yield {
167
+ type: "completionStream",
168
+ events,
169
+ };
170
+ }
171
+ else {
172
+ batchedEvents.push(...events);
173
+ }
174
+ result = await stream.next();
123
175
  }
124
- else {
125
- batchedEvents.push(...events);
176
+ const { modelExecutionMs, stats, toolCalls } = result.value;
177
+ // `stopReason: "cancelled"` rides the success-done path: the
178
+ // events stream ends normally, the cancellation is observable
179
+ // via the last event's `stopReason`, and the client-side
180
+ // `CompletionRun` aggregates (`final` / `text` / `toolCalls` /
181
+ // `stats`) reject with `InferenceCancelledError` carrying the
182
+ // partial state.
183
+ const cancelled = ctx.signal.aborted;
184
+ const terminalEvents = normalizer.finish({
185
+ ...(stats && { stats }),
186
+ ...(toolCalls.length > 0 && { toolCalls }),
187
+ ...(cancelled && { stopReason: "cancelled" }),
188
+ });
189
+ if (!request.stream) {
190
+ batchedEvents.push(...terminalEvents);
126
191
  }
127
- result = await stream.next();
192
+ const finalEvents = request.stream ? terminalEvents : batchedEvents;
193
+ yield attachModelExecutionMs({
194
+ type: "completionStream",
195
+ done: true,
196
+ events: finalEvents,
197
+ }, modelExecutionMs);
128
198
  }
129
- const { modelExecutionMs, stats, toolCalls } = result.value;
130
- const terminalEvents = normalizer.finish({
131
- ...(stats && { stats }),
132
- ...(toolCalls.length > 0 && { toolCalls }),
133
- });
134
- if (!request.stream) {
135
- batchedEvents.push(...terminalEvents);
199
+ catch (err) {
200
+ // The llama.cpp addon emits a structured `ContextOverflow` status
201
+ // (LlmErrors.hpp::ContextOverflow = 14) when the prompt exceeds
202
+ // the model's `ctx_size`. Bare's `js_throw_error(env, code, msg)`
203
+ // surfaces it as a JS Error with `.code = "[ <addonId> :: ContextOverflow ]"`
204
+ // and `.message` carrying the C++-formatted detail. Rethrow as
205
+ // a typed `ContextOverflowError` so consumers can switch on the
206
+ // class (and `err.code === SDK_SERVER_ERROR_CODES.CONTEXT_OVERFLOW`)
207
+ // instead of substring-matching on the raw addon message.
208
+ if (isAddonContextOverflowError(err)) {
209
+ const { promptTokens, ctxSize } = parseContextOverflowMessage(err instanceof Error ? err.message : "");
210
+ throw new ContextOverflowError(promptTokens, ctxSize, request.modelId, err);
211
+ }
212
+ throw err;
136
213
  }
137
- const finalEvents = request.stream ? terminalEvents : batchedEvents;
138
- yield attachModelExecutionMs({
139
- type: "completionStream",
140
- done: true,
141
- events: finalEvents,
142
- }, modelExecutionMs);
214
+ finally {
215
+ await stream.return?.(undefined);
216
+ }
217
+ }
218
+ catch (e_1) {
219
+ env_1.error = e_1;
220
+ env_1.hasError = true;
143
221
  }
144
222
  finally {
145
- await stream.return?.(undefined);
223
+ const result_1 = __disposeResources(env_1);
224
+ if (result_1)
225
+ await result_1;
146
226
  }
147
227
  },
148
228
  }),
@@ -150,6 +230,14 @@ export const llmPlugin = definePlugin({
150
230
  requestSchema: finetuneRequestSchema,
151
231
  responseSchema: finetuneResponseSchema,
152
232
  streaming: false,
233
+ // Reality matches addon: llama.cpp exposes `model.cancel()` for
234
+ // the running finetune job, so we flip from `scope: "none"` to
235
+ // `{ scope: "model", hard: true }`. The `startFinetune` op
236
+ // forwards the registry's abort signal to that call; the broad
237
+ // `cancel({ modelId, kind: "finetune" })` and legacy
238
+ // `cancelFinetune(modelId)` paths both flow through the
239
+ // registry.
240
+ cancel: { scope: "model", hard: true },
153
241
  handler: function (request) {
154
242
  return finetune(request);
155
243
  },
@@ -158,8 +246,9 @@ export const llmPlugin = definePlugin({
158
246
  requestSchema: translateRequestSchema,
159
247
  responseSchema: translateResponseSchema,
160
248
  streaming: true,
249
+ cancel: { scope: "model", hard: true },
161
250
  handler: async function* (request) {
162
- const stream = translate(request);
251
+ const stream = translate(request, request.requestId);
163
252
  try {
164
253
  let result = await stream.next();
165
254
  while (!result.done) {
@@ -177,6 +266,15 @@ export const llmPlugin = definePlugin({
177
266
  ...(stats && { stats }),
178
267
  }, modelExecutionMs);
179
268
  }
269
+ catch (err) {
270
+ // Same addon, same overflow path as `completionStream`. Wrap so
271
+ // translate consumers can `instanceof ContextOverflowError` too.
272
+ if (isAddonContextOverflowError(err)) {
273
+ const { promptTokens, ctxSize } = parseContextOverflowMessage(err instanceof Error ? err.message : "");
274
+ throw new ContextOverflowError(promptTokens, ctxSize, request.modelId, err);
275
+ }
276
+ throw err;
277
+ }
180
278
  finally {
181
279
  await stream.return?.(undefined);
182
280
  }
@@ -0,0 +1,10 @@
1
+ import { type LlmConfig } from "../../../../schemas/index";
2
+ /**
3
+ * Converts an LlmConfig into the flat string-keyed map the C++ addon expects.
4
+ *
5
+ * JS-only fields excluded from the output (must NOT be forwarded to the addon):
6
+ * - modelType (schema discriminant, meaningless at C++ level)
7
+ * - system_prompt (JS-side history seeding only; C++ removed --system-prompt in 8189)
8
+ */
9
+ export declare function transformLlmConfig(llmConfig: LlmConfig): Record<string, string>;
10
+ //# sourceMappingURL=transform.d.ts.map
@@ -0,0 +1,34 @@
1
+ import { TOOLS_MODE } from "../../../../schemas/index.js";
2
+ /**
3
+ * Converts an LlmConfig into the flat string-keyed map the C++ addon expects.
4
+ *
5
+ * JS-only fields excluded from the output (must NOT be forwarded to the addon):
6
+ * - modelType (schema discriminant, meaningless at C++ level)
7
+ * - system_prompt (JS-side history seeding only; C++ removed --system-prompt in 8189)
8
+ */
9
+ export function transformLlmConfig(llmConfig) {
10
+ const transformed = JSON.parse(JSON.stringify(llmConfig, (key, v) => key === "modelType" || key === "system_prompt"
11
+ ? undefined
12
+ : key === "stop_sequences"
13
+ ? Array.isArray(v)
14
+ ? v.join(", ")
15
+ : v
16
+ : typeof v === "number" || typeof v === "boolean"
17
+ ? String(v)
18
+ : v).replace(/"([a-z][A-Za-z]*)":/g, (_, key) => `"${key.replace(/[A-Z]/g, (l) => `_${l.toLowerCase()}`)}":`));
19
+ if ("stop_sequences" in transformed) {
20
+ transformed["reverse_prompt"] = transformed["stop_sequences"];
21
+ delete transformed["stop_sequences"];
22
+ }
23
+ if ("opencl_cache_dir" in transformed) {
24
+ transformed["openclCacheDir"] = transformed["opencl_cache_dir"];
25
+ delete transformed["opencl_cache_dir"];
26
+ }
27
+ if ("tools_mode" in transformed) {
28
+ if (transformed["tools_mode"] === TOOLS_MODE.dynamic) {
29
+ transformed["tools_compact"] = "true";
30
+ }
31
+ delete transformed["tools_mode"];
32
+ }
33
+ return transformed;
34
+ }