@qvac/sdk 0.22.0 → 0.24.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 (284) hide show
  1. package/NOTICE +194 -97
  2. package/README.md +29 -470
  3. package/dist/examples/asr/parakeet-sortformer.js +24 -14
  4. package/dist/examples/asr/parakeet-transcribepsy-filesystem.d.ts +2 -0
  5. package/dist/examples/asr/parakeet-transcribepsy-filesystem.js +105 -0
  6. package/dist/examples/asr/parakeet-unified-coreml.js +14 -9
  7. package/dist/examples/asr/whispercpp-prompt.js +9 -5
  8. package/dist/examples/assess-model-fit.d.ts +7 -9
  9. package/dist/examples/assess-model-fit.js +22 -43
  10. package/dist/examples/calc-tokens.d.ts +2 -0
  11. package/dist/examples/calc-tokens.js +21 -0
  12. package/dist/examples/classification/classify-image.js +11 -5
  13. package/dist/examples/completion-stop-reason.d.ts +3 -3
  14. package/dist/examples/completion-stop-reason.js +4 -4
  15. package/dist/examples/diffusion-flux3-klein.d.ts +2 -0
  16. package/dist/examples/diffusion-flux3-klein.js +102 -0
  17. package/dist/examples/diffusion-img2vid-ltx.js +7 -14
  18. package/dist/examples/diffusion-moss-image.d.ts +2 -0
  19. package/dist/examples/diffusion-moss-image.js +126 -0
  20. package/dist/examples/diffusion-qwen-image-21.d.ts +2 -0
  21. package/dist/examples/diffusion-qwen-image-21.js +115 -0
  22. package/dist/examples/diffusion-txt2vid-ltx.js +7 -14
  23. package/dist/examples/embed-multimodal.d.ts +2 -0
  24. package/dist/examples/embed-multimodal.js +80 -0
  25. package/dist/examples/embed-p2p.js +2 -2
  26. package/dist/examples/finetune/llamacpp-finetune.js +9 -4
  27. package/dist/examples/image/megaloc.d.ts +2 -0
  28. package/dist/examples/image/megaloc.js +37 -0
  29. package/dist/examples/llamacpp-multimodal.js +21 -1
  30. package/dist/examples/mcp-websearch.js +1 -1
  31. package/dist/examples/plugins.js +1 -1
  32. package/dist/examples/rag/rag-hyperdb/pipeline.js +2 -2
  33. package/dist/examples/rag/rag-turbovec.js +2 -2
  34. package/dist/examples/rerank.d.ts +2 -0
  35. package/dist/examples/rerank.js +33 -0
  36. package/dist/examples/sessions.d.ts +17 -0
  37. package/dist/examples/sessions.js +63 -0
  38. package/dist/examples/tools/llamacpp-deferred-tools.js +12 -8
  39. package/dist/examples/tools/llamacpp-tools-auto-dialect.js +4 -3
  40. package/dist/examples/tools/llamacpp-tools-gemma4.js +3 -3
  41. package/dist/examples/tools/llamacpp-tools-qwen35.js +4 -3
  42. package/dist/scripts/check-resource-collectors-packaging.js +7 -6
  43. package/dist/scripts/contract/build-contract.d.ts +2 -1
  44. package/dist/scripts/contract/build-contract.js +13 -1
  45. package/dist/scripts/contract/constants-registry.d.ts +19 -0
  46. package/dist/scripts/contract/constants-registry.js +9 -2
  47. package/dist/scripts/contract/method-shapes.d.ts +5 -0
  48. package/dist/scripts/contract/method-shapes.js +5 -0
  49. package/dist/scripts/enforce-inference-versions.d.ts +1 -1
  50. package/dist/scripts/enforce-inference-versions.js +28 -18
  51. package/dist/scripts/generate-bare-kit-runtimes.js +101 -69
  52. package/dist/src/client/api/assess-model-fit.d.ts +17 -17
  53. package/dist/src/client/api/assess-model-fit.js +19 -32
  54. package/dist/src/client/api/audio-edit.d.ts +5 -3
  55. package/dist/src/client/api/audio-edit.js +7 -5
  56. package/dist/src/client/api/audio-gen-result.js +136 -47
  57. package/dist/src/client/api/audio-gen.d.ts +40 -3
  58. package/dist/src/client/api/audio-gen.js +42 -5
  59. package/dist/src/client/api/audio-understand.d.ts +2 -2
  60. package/dist/src/client/api/audio-understand.js +4 -4
  61. package/dist/src/client/api/batch-completion.js +4 -3
  62. package/dist/src/client/api/bci-transcribe.js +3 -3
  63. package/dist/src/client/api/calc-tokens.d.ts +33 -0
  64. package/dist/src/client/api/calc-tokens.js +44 -0
  65. package/dist/src/client/api/cancel.d.ts +2 -2
  66. package/dist/src/client/api/cancel.js +3 -3
  67. package/dist/src/client/api/classify.d.ts +12 -5
  68. package/dist/src/client/api/classify.js +18 -6
  69. package/dist/src/client/api/client-request-id.d.ts +0 -15
  70. package/dist/src/client/api/client-request-id.js +15 -12
  71. package/dist/src/client/api/completion-stream.d.ts +9 -1
  72. package/dist/src/client/api/completion-stream.js +14 -3
  73. package/dist/src/client/api/decide.d.ts +1 -1
  74. package/dist/src/client/api/decide.js +3 -3
  75. package/dist/src/client/api/delete-cache.d.ts +9 -2
  76. package/dist/src/client/api/delete-cache.js +14 -4
  77. package/dist/src/client/api/diffusion.d.ts +38 -5
  78. package/dist/src/client/api/diffusion.js +42 -7
  79. package/dist/src/client/api/download-asset.js +3 -3
  80. package/dist/src/client/api/embed.d.ts +82 -29
  81. package/dist/src/client/api/embed.js +66 -21
  82. package/dist/src/client/api/finetune.js +3 -3
  83. package/dist/src/client/api/get-loaded-model-info.js +1 -1
  84. package/dist/src/client/api/get-model-info.d.ts +2 -2
  85. package/dist/src/client/api/get-model-info.js +3 -3
  86. package/dist/src/client/api/get-system-resources.d.ts +2 -2
  87. package/dist/src/client/api/get-system-resources.js +3 -3
  88. package/dist/src/client/api/heartbeat.d.ts +3 -2
  89. package/dist/src/client/api/heartbeat.js +4 -3
  90. package/dist/src/client/api/index.d.ts +8 -6
  91. package/dist/src/client/api/index.js +6 -4
  92. package/dist/src/client/api/invoke-plugin.d.ts +8 -2
  93. package/dist/src/client/api/invoke-plugin.js +18 -3
  94. package/dist/src/client/api/load-model.js +9 -6
  95. package/dist/src/client/api/logging-stream.d.ts +11 -2
  96. package/dist/src/client/api/logging-stream.js +12 -3
  97. package/dist/src/client/api/ocr.d.ts +5 -3
  98. package/dist/src/client/api/ocr.js +45 -22
  99. package/dist/src/client/api/rag.d.ts +1 -1
  100. package/dist/src/client/api/rag.js +3 -3
  101. package/dist/src/client/api/registry.d.ts +19 -8
  102. package/dist/src/client/api/registry.js +43 -17
  103. package/dist/src/client/api/rerank.d.ts +22 -0
  104. package/dist/src/client/api/rerank.js +39 -0
  105. package/dist/src/client/api/resume.d.ts +2 -1
  106. package/dist/src/client/api/resume.js +3 -3
  107. package/dist/src/client/api/rpc-server.d.ts +4 -4
  108. package/dist/src/client/api/rpc-server.js +12 -12
  109. package/dist/src/client/api/state.d.ts +2 -2
  110. package/dist/src/client/api/state.js +3 -3
  111. package/dist/src/client/api/subscribe-logs.d.ts +2 -2
  112. package/dist/src/client/api/subscribe-logs.js +4 -3
  113. package/dist/src/client/api/suspend.d.ts +4 -2
  114. package/dist/src/client/api/suspend.js +5 -4
  115. package/dist/src/client/api/text-to-speech.d.ts +14 -5
  116. package/dist/src/client/api/text-to-speech.js +86 -32
  117. package/dist/src/client/api/transcribe.d.ts +7 -3
  118. package/dist/src/client/api/transcribe.js +9 -3
  119. package/dist/src/client/api/translate.js +2 -2
  120. package/dist/src/client/api/unload-model.d.ts +19 -7
  121. package/dist/src/client/api/unload-model.js +31 -13
  122. package/dist/src/client/api/upscale.d.ts +6 -3
  123. package/dist/src/client/api/upscale.js +10 -5
  124. package/dist/src/client/api/vector-index.d.ts +51 -17
  125. package/dist/src/client/api/vector-index.js +101 -49
  126. package/dist/src/client/api/video-request.d.ts +5 -5
  127. package/dist/src/client/api/video.d.ts +3 -2
  128. package/dist/src/client/api/video.js +6 -5
  129. package/dist/src/client/api/vla.d.ts +9 -5
  130. package/dist/src/client/api/vla.js +17 -8
  131. package/dist/src/client/api/world-result.js +2 -2
  132. package/dist/src/client/api/world.d.ts +6 -6
  133. package/dist/src/client/api/world.js +6 -6
  134. package/dist/src/client/init-hooks.d.ts +6 -4
  135. package/dist/src/client/init-hooks.js +12 -15
  136. package/dist/src/client/logging-stream-registry.d.ts +6 -3
  137. package/dist/src/client/logging-stream-registry.js +36 -14
  138. package/dist/src/client/plugins-factory.d.ts +1 -1
  139. package/dist/src/client/plugins-factory.js +1 -1
  140. package/dist/src/client/rpc/bundle-stamp.d.ts +29 -0
  141. package/dist/src/client/rpc/bundle-stamp.js +75 -0
  142. package/dist/src/client/rpc/expo-home-dir.d.ts +2 -0
  143. package/dist/src/client/rpc/expo-home-dir.js +4 -0
  144. package/dist/src/client/rpc/expo-rpc-client.js +192 -138
  145. package/dist/src/client/rpc/node-rpc-client.js +324 -426
  146. package/dist/src/client/rpc/pear-runtime.d.ts +12 -0
  147. package/dist/src/client/rpc/pear-runtime.js +12 -0
  148. package/dist/src/client/rpc/rpc-client.d.ts +6 -4
  149. package/dist/src/client/rpc/rpc-client.js +168 -31
  150. package/dist/src/client/rpc/rpc-error.js +24 -2
  151. package/dist/src/client/rpc/unbundled-harness.d.ts +16 -0
  152. package/dist/src/client/rpc/unbundled-harness.js +27 -0
  153. package/dist/src/client/rpc/worker-failure.d.ts +27 -0
  154. package/dist/src/client/rpc/worker-failure.js +61 -0
  155. package/dist/src/client/session-registry.d.ts +75 -0
  156. package/dist/src/client/session-registry.js +149 -0
  157. package/dist/src/client/session.d.ts +125 -0
  158. package/dist/src/client/session.js +148 -0
  159. package/dist/src/commands/bundle/addons.d.ts +14 -0
  160. package/dist/src/commands/bundle/addons.js +65 -0
  161. package/dist/src/commands/bundle/constants.js +2 -0
  162. package/dist/src/commands/bundle/entry-gen.d.ts +1 -5
  163. package/dist/src/commands/bundle/entry-gen.js +18 -51
  164. package/dist/src/commands/bundle/index.d.ts +60 -14
  165. package/dist/src/commands/bundle/index.js +350 -126
  166. package/dist/src/commands/bundle/link.d.ts +58 -0
  167. package/dist/src/commands/bundle/link.js +135 -0
  168. package/dist/src/commands/bundle/node-support.d.ts +13 -0
  169. package/dist/src/commands/bundle/node-support.js +23 -0
  170. package/dist/src/commands/bundle/plugins.js +1 -1
  171. package/dist/src/commands/bundle/read-bundle.d.ts +9 -0
  172. package/dist/src/commands/bundle/read-bundle.js +27 -0
  173. package/dist/src/commands/bundle/resolve-sdk-import.d.ts +6 -0
  174. package/dist/src/commands/bundle/resolve-sdk-import.js +24 -28
  175. package/dist/src/commands/bundle/scratch.d.ts +35 -0
  176. package/dist/src/commands/bundle/scratch.js +178 -0
  177. package/dist/src/commands/bundle/targets.d.ts +14 -0
  178. package/dist/src/commands/bundle/targets.js +37 -0
  179. package/dist/src/commands/host-prebuilds/index.d.ts +8 -7
  180. package/dist/src/commands/host-prebuilds/index.js +13 -11
  181. package/dist/src/commands/index.d.ts +13 -12
  182. package/dist/src/commands/index.js +7 -7
  183. package/dist/src/commands/verify/abi.d.ts +21 -15
  184. package/dist/src/commands/verify/abi.js +12 -80
  185. package/dist/src/commands/verify/bare-kit-runtime.d.ts +20 -22
  186. package/dist/src/commands/verify/bare-kit-runtime.js +102 -150
  187. package/dist/src/commands/verify/bare-kit-runtimes.d.ts +10 -9
  188. package/dist/src/commands/verify/bare-kit-runtimes.js +21 -21
  189. package/dist/src/commands/verify/bundle-source.d.ts +1 -1
  190. package/dist/src/commands/verify/bundle-source.js +27 -23
  191. package/dist/src/commands/verify/engines-advice.d.ts +6 -12
  192. package/dist/src/commands/verify/engines-advice.js +9 -56
  193. package/dist/src/commands/verify/index.d.ts +34 -33
  194. package/dist/src/commands/verify/index.js +96 -204
  195. package/dist/src/commands/verify/node-modules-source.d.ts +1 -1
  196. package/dist/src/commands/verify/node-modules-source.js +1 -1
  197. package/dist/src/commands/verify/prebuilds.d.ts +4 -6
  198. package/dist/src/commands/verify/prebuilds.js +3 -4
  199. package/dist/src/commands/verify/resource-collectors.d.ts +0 -6
  200. package/dist/src/commands/verify/resource-collectors.js +3 -52
  201. package/dist/src/commands/verify/sidecar-runtime.d.ts +6 -0
  202. package/dist/src/commands/verify/sidecar-runtime.js +51 -0
  203. package/dist/src/expo/plugins/get-project-root.d.ts +1 -1
  204. package/dist/src/expo/plugins/withAndroidArchitecture.d.ts +1 -1
  205. package/dist/src/expo/plugins/withAndroidNdkVersion.d.ts +1 -1
  206. package/dist/src/expo/plugins/withAndroidNdkVersion.js +16 -10
  207. package/dist/src/expo/plugins/withBareKit.d.ts +59 -0
  208. package/dist/src/expo/plugins/withBareKit.js +204 -0
  209. package/dist/src/expo/plugins/withDeviceInfo.d.ts +1 -1
  210. package/dist/src/expo/plugins/withDeviceInfo.js +19 -5
  211. package/dist/src/expo/plugins/withMobileBundle.d.ts +5 -12
  212. package/dist/src/expo/plugins/withMobileBundle.js +38 -59
  213. package/dist/src/expo/plugins/withOpenCL.d.ts +1 -1
  214. package/dist/src/expo/plugins/withQvacSDK.d.ts +2 -1
  215. package/dist/src/expo/plugins/withQvacSDK.js +3 -0
  216. package/dist/src/index.d.ts +6 -5
  217. package/dist/src/index.js +10 -14
  218. package/dist/src/logging/addon.d.ts +1 -1
  219. package/dist/src/logging/base-logger.js +1 -1
  220. package/dist/src/logging/utils.js +11 -3
  221. package/dist/src/plugin-ids.d.ts +3 -1
  222. package/dist/src/plugin-ids.js +4 -0
  223. package/dist/src/schemas/public.d.ts +1 -1
  224. package/dist/src/schemas/public.js +1 -1
  225. package/dist/src/schemas/sdk-errors-client.d.ts +5 -6
  226. package/dist/src/schemas/sdk-errors-client.js +30 -36
  227. package/dist/src/schemas/sdk-errors-server.d.ts +12 -1
  228. package/dist/src/schemas/sdk-errors-server.js +65 -2
  229. package/dist/src/server/rpc/rpc-utils.d.ts +26 -0
  230. package/dist/src/server/rpc/rpc-utils.js +41 -0
  231. package/dist/src/utils/aggregate-events.d.ts +1 -1
  232. package/dist/src/utils/aggregate-events.js +2 -2
  233. package/dist/src/utils/errors-client.d.ts +37 -29
  234. package/dist/src/utils/errors-client.js +50 -41
  235. package/dist/src/utils/errors-server.d.ts +65 -1
  236. package/dist/src/utils/errors-server.js +122 -1
  237. package/dist/src/utils/mcp-adapter.d.ts +1 -1
  238. package/dist/src/utils/mcp-adapter.js +1 -1
  239. package/dist/src/utils/tool-helpers.js +1 -1
  240. package/dist/src/utils/withTimeout.js +34 -17
  241. package/dist/src/worker/handle-request.js +26 -21
  242. package/dist/src/worker/handler-utils.d.ts +2 -6
  243. package/dist/src/worker/handler-utils.js +2 -20
  244. package/dist/src/worker/index.d.ts +2 -4
  245. package/dist/src/worker/index.js +24 -34
  246. package/dist/src/worker/plugins/ggml-image-embedding.d.ts +2 -0
  247. package/dist/src/worker/plugins/ggml-image-embedding.js +1 -0
  248. package/dist/src/worker/plugins/llamacpp-rerank.d.ts +2 -0
  249. package/dist/src/worker/plugins/llamacpp-rerank.js +1 -0
  250. package/dist/src/worker/shim.d.ts +4 -0
  251. package/dist/src/worker/shim.js +7 -0
  252. package/dist/src/worker/start.d.ts +9 -0
  253. package/dist/src/worker/start.js +16 -0
  254. package/dist/src/worker/unbundled-shim.d.ts +2 -0
  255. package/dist/src/worker/unbundled-shim.js +4 -0
  256. package/docs/system-resources-support-matrix.md +27 -19
  257. package/package.json +91 -74
  258. package/src/electron-forge/index.cjs +65 -91
  259. package/dist/examples/model-fit-ui/server.d.ts +0 -24
  260. package/dist/examples/model-fit-ui/server.js +0 -221
  261. package/dist/src/client/rpc/ensure-worker-ready.d.ts +0 -9
  262. package/dist/src/client/rpc/ensure-worker-ready.js +0 -17
  263. package/dist/src/client/rpc/init-timeout.d.ts +0 -26
  264. package/dist/src/client/rpc/init-timeout.js +0 -25
  265. package/dist/src/client/rpc/worker-startup-error.d.ts +0 -12
  266. package/dist/src/client/rpc/worker-startup-error.js +0 -13
  267. package/dist/src/commands/bundle/bare-pack.d.ts +0 -21
  268. package/dist/src/commands/bundle/bare-pack.js +0 -77
  269. package/dist/src/commands/bundle/manifest.d.ts +0 -25
  270. package/dist/src/commands/bundle/manifest.js +0 -192
  271. package/dist/src/expo/plugins/link-addons.d.ts +0 -18
  272. package/dist/src/expo/plugins/link-addons.js +0 -65
  273. package/dist/src/pear/pre.d.ts +0 -21
  274. package/dist/src/pear/pre.js +0 -448
  275. package/dist/src/server/env.d.ts +0 -22
  276. package/dist/src/server/env.js +0 -59
  277. package/dist/src/server/utils/qvac-paths.d.ts +0 -2
  278. package/dist/src/server/utils/qvac-paths.js +0 -5
  279. package/dist/src/server/utils/worker-lock.d.ts +0 -3
  280. package/dist/src/server/utils/worker-lock.js +0 -67
  281. package/dist/src/worker/create-server.d.ts +0 -8
  282. package/dist/src/worker/create-server.js +0 -51
  283. package/dist/src/worker/lifecycle.d.ts +0 -23
  284. package/dist/src/worker/lifecycle.js +0 -149
@@ -1,448 +0,0 @@
1
- /**
2
- * QVAC Pear Pre-Hook
3
- *
4
- * Invoked by Pear before `pear run` or `pear stage` to:
5
- * 1. Generate `qvac/worker.pear.entry.mjs` with selected plugins
6
- * 2. Persist `pear.stage.entrypoints` to package.json for routing
7
- *
8
- * Note: `qvac verify bundle` is not wired here yet — run it manually
9
- * (locally and/or in CI) before `pear stage` / `pear run`.
10
- *
11
- * @example package.json configuration
12
- * ```json
13
- * {
14
- * "pear": {
15
- * "pre": ["@qvac/sdk/pear-pre"]
16
- * }
17
- * }
18
- * ```
19
- */
20
- import * as cenc from 'compact-encoding';
21
- import pearPipe from 'pear-pipe';
22
- import fs from 'bare-fs';
23
- import path from 'bare-path';
24
- const CONFIG_CANDIDATES = [
25
- 'qvac.config.json',
26
- 'qvac.config.js',
27
- 'qvac.config.mjs',
28
- 'qvac.config.ts'
29
- ];
30
- const BUILTIN_PLUGINS = [
31
- '@qvac/sdk/llamacpp-completion/plugin',
32
- '@qvac/sdk/llamacpp-embedding/plugin',
33
- '@qvac/sdk/llamacpp-decision/plugin',
34
- '@qvac/sdk/whispercpp-transcription/plugin',
35
- '@qvac/sdk/bci-whispercpp-transcription/plugin',
36
- '@qvac/sdk/nmtcpp-translation/plugin',
37
- '@qvac/sdk/tts-ggml/plugin',
38
- '@qvac/sdk/ggml-ocr/plugin',
39
- '@qvac/sdk/sdcpp-generation/plugin',
40
- '@qvac/sdk/audiogen-ggml/plugin',
41
- '@qvac/sdk/ggml-vla/plugin',
42
- '@qvac/sdk/ggml-classification/plugin'
43
- ];
44
- const BUILTIN_PLUGIN_EXPORTS = {
45
- 'llamacpp-completion': 'llmPlugin',
46
- 'llamacpp-embedding': 'embeddingsPlugin',
47
- 'llamacpp-decision': 'decisionPlugin',
48
- 'whispercpp-transcription': 'whisperPlugin',
49
- 'bci-whispercpp-transcription': 'bciPlugin',
50
- 'nmtcpp-translation': 'nmtPlugin',
51
- 'tts-ggml': 'ttsPlugin',
52
- 'ggml-ocr': 'ocrPlugin',
53
- 'sdcpp-generation': 'diffusionPlugin',
54
- 'audiogen-ggml': 'audioGenPlugin',
55
- 'ggml-vla': 'vlaPlugin',
56
- 'ggml-classification': 'classificationPlugin'
57
- };
58
- const SDK_NAME = '@qvac/sdk';
59
- const DEFAULT_PEAR_WORKER = 'worker.js';
60
- const PEAR_WORKER_ENTRY_PATH = 'qvac/worker.pear.entry.mjs';
61
- const LOG_PREFIX = '[qvac/pear-pre]';
62
- /** Normalize path to Pear config format (POSIX-style, leading slash) */
63
- function toPearConfigPath(pathFromAppRoot) {
64
- let p = String(pathFromAppRoot).replaceAll('\\', '/');
65
- if (p.startsWith('./'))
66
- p = p.slice(2);
67
- if (!p.startsWith('/'))
68
- p = `/${p}`;
69
- return p.replaceAll('/./', '/').replace(/\/{2,}/g, '/');
70
- }
71
- function toPosixPath(p) {
72
- return String(p).replaceAll('\\', '/');
73
- }
74
- function pathToFileUrl(absPath) {
75
- let p = toPosixPath(absPath);
76
- // Windows drive letter paths need a leading slash in file:// URLs.
77
- if (/^[A-Za-z]:\//.test(p))
78
- p = `/${p}`;
79
- if (!p.startsWith('/'))
80
- p = `/${p}`;
81
- const segments = p.split('/');
82
- const encoded = segments
83
- .map((seg, idx) => {
84
- if (idx === 0)
85
- return '';
86
- // Preserve "C:" drive segment in Windows file URLs (file:///C:/...)
87
- if (idx === 1 && /^[A-Za-z]:$/.test(seg))
88
- return seg;
89
- return encodeURIComponent(seg);
90
- })
91
- .join('/');
92
- return `file://${encoded}`;
93
- }
94
- function detectJsonIndent(raw) {
95
- const match = raw.match(/\n([ \t]+)"/);
96
- if (match?.[1])
97
- return match[1];
98
- return 2;
99
- }
100
- function detectJsonNewline(raw) {
101
- return raw.includes('\r\n') ? '\r\n' : '\n';
102
- }
103
- function ensureObjectProp(obj, prop) {
104
- const existing = obj[prop];
105
- if (existing === undefined) {
106
- const created = {};
107
- obj[prop] = created;
108
- return created;
109
- }
110
- if (typeof existing === 'object' && existing && !Array.isArray(existing)) {
111
- return existing;
112
- }
113
- throw new Error(`package.json "${prop}" must be an object`);
114
- }
115
- function normalizeStringArray(value) {
116
- if (value === undefined || value === null)
117
- return [];
118
- if (typeof value === 'string')
119
- return value.length ? [value] : [];
120
- if (Array.isArray(value))
121
- return uniqStrings(value);
122
- throw new Error('Expected an array of strings');
123
- }
124
- function atomicWriteFileSync(targetPath, content) {
125
- const tmpPath = `${targetPath}.qvac-pre.tmp`;
126
- fs.writeFileSync(tmpPath, content, 'utf8');
127
- fs.renameSync(tmpPath, targetPath);
128
- }
129
- function normalizePearWorkerPath(value) {
130
- if (typeof value !== 'string')
131
- return DEFAULT_PEAR_WORKER;
132
- let p = value.trim();
133
- if (!p)
134
- return DEFAULT_PEAR_WORKER;
135
- p = toPosixPath(p);
136
- if (/^[A-Za-z]:\//.test(p)) {
137
- throw new Error(`"pearWorker" must be a path inside the app root (got absolute path: ${JSON.stringify(value)})`);
138
- }
139
- if (p.startsWith('./'))
140
- p = p.slice(2);
141
- while (p.startsWith('/'))
142
- p = p.slice(1);
143
- if (!p)
144
- return DEFAULT_PEAR_WORKER;
145
- if (p === '.' || p === '..' || p.startsWith('../') || p.includes('/../')) {
146
- throw new Error(`"pearWorker" must be a path inside the app root (got: ${JSON.stringify(value)})`);
147
- }
148
- return p;
149
- }
150
- /**
151
- * Converts an absolute path to a relative ESM import specifier, using POSIX separators.
152
- */
153
- function toRelativeImportSpecifier(fromDir, targetPath) {
154
- let rel = path.relative(fromDir, targetPath);
155
- rel = toPosixPath(rel);
156
- if (!rel.startsWith('.'))
157
- rel = `./${rel}`;
158
- return rel;
159
- }
160
- /** Extract unique strings from an array, preserving order */
161
- function uniqStrings(values) {
162
- if (!Array.isArray(values))
163
- return [];
164
- const out = [];
165
- const seen = new Set();
166
- for (const v of values) {
167
- if (typeof v === 'string' && !seen.has(v)) {
168
- seen.add(v);
169
- out.push(v);
170
- }
171
- }
172
- return out;
173
- }
174
- /** Ensure array contains required values, returning new array and change flag */
175
- function ensureArrayIncludes(existing, required) {
176
- const next = [...existing];
177
- const set = new Set(existing);
178
- let changed = false;
179
- for (const v of required) {
180
- if (!set.has(v)) {
181
- set.add(v);
182
- next.push(v);
183
- changed = true;
184
- }
185
- }
186
- return { next, changed };
187
- }
188
- /**
189
- * Persist pear.stage.entrypoints to package.json.
190
- *
191
- * Required because workers are spawned with --no-pre, bypassing dynamic config.
192
- * pear-state merges stage.entrypoints into unrouted automatically.
193
- */
194
- function persistStageEntrypointsToPackageJson(appRoot, requiredEntrypoints) {
195
- const packageJsonPath = path.join(appRoot, 'package.json');
196
- if (!fs.existsSync(packageJsonPath)) {
197
- throw new Error(`package.json not found at ${packageJsonPath}`);
198
- }
199
- const raw = fs.readFileSync(packageJsonPath, 'utf8');
200
- const newline = detectJsonNewline(raw);
201
- const indent = detectJsonIndent(raw);
202
- const hasFinalNewline = raw.endsWith('\n') || raw.endsWith('\r\n');
203
- let pkg;
204
- try {
205
- pkg = JSON.parse(raw);
206
- }
207
- catch (err) {
208
- throw new Error(`Failed to parse ${packageJsonPath}: ${String(err)}`);
209
- }
210
- const pear = ensureObjectProp(pkg, 'pear');
211
- const stage = ensureObjectProp(pear, 'stage');
212
- const existing = normalizeStringArray(stage['entrypoints']);
213
- const required = uniqStrings(requiredEntrypoints);
214
- const { next, changed } = ensureArrayIncludes(existing, required);
215
- if (!changed)
216
- return;
217
- stage['entrypoints'] = next;
218
- let nextRaw = JSON.stringify(pkg, null, indent);
219
- if (newline === '\r\n')
220
- nextRaw = nextRaw.replaceAll('\n', '\r\n');
221
- if (hasFinalNewline)
222
- nextRaw += newline;
223
- atomicWriteFileSync(packageJsonPath, nextRaw);
224
- }
225
- /** Extract app root directory from Pear's applink */
226
- function getAppRoot() {
227
- const applink = Pear.config?.applink;
228
- if (typeof applink !== 'string' || applink.length === 0) {
229
- throw new Error('Pear.config.applink is not available');
230
- }
231
- // Pear provides a file:// URL to the application root.
232
- let pathname;
233
- let url;
234
- try {
235
- url = new URL(applink);
236
- }
237
- catch {
238
- // Some environments may provide a plain filesystem path instead of a URL.
239
- return path.normalize(applink);
240
- }
241
- if (url.protocol !== 'file:') {
242
- throw new Error(`Expected Pear.config.applink to be a file:// URL (got: ${applink})`);
243
- }
244
- pathname = url.pathname;
245
- try {
246
- pathname = decodeURIComponent(pathname);
247
- }
248
- catch {
249
- // If decoding fails, keep the raw pathname.
250
- }
251
- // Handle Windows paths (e.g., /C:/path)
252
- if (pathname[0] === '/' && pathname[2] === ':') {
253
- pathname = pathname.slice(1);
254
- }
255
- return path.normalize(pathname);
256
- }
257
- /** Find the first existing qvac config file */
258
- function findConfigFile(appRoot) {
259
- for (const candidate of CONFIG_CANDIDATES) {
260
- const configPath = path.join(appRoot, candidate);
261
- if (fs.existsSync(configPath)) {
262
- return configPath;
263
- }
264
- }
265
- return null;
266
- }
267
- /** Load and parse a qvac config file */
268
- async function loadConfig(configPath) {
269
- const ext = path.extname(configPath).toLowerCase();
270
- if (ext === '.json') {
271
- const content = fs.readFileSync(configPath, 'utf8');
272
- try {
273
- return JSON.parse(content);
274
- }
275
- catch (err) {
276
- throw new Error(`Failed to parse ${configPath}: ${String(err)}`);
277
- }
278
- }
279
- if (ext === '.js' || ext === '.mjs') {
280
- const module = (await import(pathToFileUrl(configPath)));
281
- return module.default ?? module;
282
- }
283
- if (ext === '.ts') {
284
- throw new Error('TypeScript config not supported in Pear pre-hook. Use qvac.config.json or qvac.config.mjs.');
285
- }
286
- throw new Error(`Unsupported config format: ${ext}. Use .json, .js, or .mjs`);
287
- }
288
- /** Discover and load qvac config, returning null if not found */
289
- async function discoverConfig(appRoot) {
290
- const configPath = findConfigFile(appRoot);
291
- if (!configPath) {
292
- return { config: null, configFile: null };
293
- }
294
- const config = await loadConfig(configPath);
295
- return { config, configFile: path.basename(configPath) };
296
- }
297
- /** Resolve plugin set from config or default to all built-in plugins */
298
- function resolvePlugins(config) {
299
- const fromConfig = uniqStrings(config?.plugins);
300
- if (fromConfig.length)
301
- return fromConfig;
302
- return [...BUILTIN_PLUGINS];
303
- }
304
- /** Parse SDK builtin plugin specifier to extract export info */
305
- function parseBuiltinSpecifier(specifier) {
306
- const prefix = `${SDK_NAME}/`;
307
- const pluginSuffix = '/plugin';
308
- if (specifier.startsWith(prefix) && specifier.endsWith(pluginSuffix)) {
309
- const middle = specifier.slice(prefix.length, -pluginSuffix.length);
310
- const exportName = BUILTIN_PLUGIN_EXPORTS[middle];
311
- if (!middle.includes('/') && exportName) {
312
- return { suffix: middle, exportName };
313
- }
314
- }
315
- return null;
316
- }
317
- /** Generate the Pear worker entry file content */
318
- function generatePearWorkerEntry(plugins, appWorkerPath) {
319
- const imports = [];
320
- const registrations = [];
321
- let varIndex = 0;
322
- for (const specifier of plugins) {
323
- const builtin = parseBuiltinSpecifier(specifier);
324
- if (builtin) {
325
- imports.push(`import { ${builtin.exportName} } from "${SDK_NAME}/${builtin.suffix}/plugin";`);
326
- registrations.push(`registerPlugin(${builtin.exportName});`);
327
- }
328
- else {
329
- const varName = `customPlugin${varIndex++}`;
330
- imports.push(`import ${varName} from "${specifier}";`);
331
- registrations.push(`registerPlugin(${varName});`);
332
- }
333
- }
334
- const pluginsList = plugins.map((p) => `* - ${p}`).join('\n');
335
- return `/**
336
- * QVAC Pear Worker Entry (auto-generated)
337
- * Plugins: ${plugins.length}
338
- *
339
- ${pluginsList}
340
- */
341
-
342
- import { registerPlugin } from "@qvac/inference/plugins";
343
-
344
- ${imports.join('\n')}
345
-
346
- ${registrations.join('\n')}
347
-
348
- await import(${JSON.stringify(appWorkerPath)});
349
- `;
350
- }
351
- /** Write worker entry file if content changed (idempotent) */
352
- function writeWorkerEntryIfChanged(appRoot, content) {
353
- const outputDir = path.join(appRoot, 'qvac');
354
- const entryPath = path.join(appRoot, PEAR_WORKER_ENTRY_PATH);
355
- if (fs.existsSync(entryPath)) {
356
- try {
357
- if (fs.readFileSync(entryPath, 'utf8') === content) {
358
- return false;
359
- }
360
- }
361
- catch {
362
- // Will rewrite on error
363
- }
364
- }
365
- if (!fs.existsSync(outputDir)) {
366
- fs.mkdirSync(outputDir, { recursive: true });
367
- }
368
- atomicWriteFileSync(entryPath, content);
369
- return true;
370
- }
371
- /** Main configuration handler */
372
- async function configure(options) {
373
- const appRoot = getAppRoot();
374
- const { config: qvacConfig } = await discoverConfig(appRoot);
375
- const plugins = resolvePlugins(qvacConfig);
376
- const pearWorker = normalizePearWorkerPath(qvacConfig?.pearWorker);
377
- // Validate worker file exists
378
- const workerAbs = path.join(appRoot, pearWorker);
379
- if (!fs.existsSync(workerAbs)) {
380
- const hint = qvacConfig?.pearWorker
381
- ? `"${String(qvacConfig.pearWorker)}" (resolved to ${workerAbs})`
382
- : `"${DEFAULT_PEAR_WORKER}". Set "pearWorker" in qvac.config.json to specify your worker path.`;
383
- throw new Error(`Worker file not found: ${hint}`);
384
- }
385
- // Generate worker entry with relative import path from qvac/ directory
386
- const outputDir = path.join(appRoot, 'qvac');
387
- const appWorkerImport = toRelativeImportSpecifier(outputDir, workerAbs);
388
- const workerEntryContent = generatePearWorkerEntry(plugins, appWorkerImport);
389
- writeWorkerEntryIfChanged(appRoot, workerEntryContent);
390
- // Persist entrypoint to package.json for worker routing
391
- const workerEntryPath = toPearConfigPath(PEAR_WORKER_ENTRY_PATH);
392
- persistStageEntrypointsToPackageJson(appRoot, [workerEntryPath]);
393
- return options;
394
- }
395
- // IPC Protocol
396
- const pipe = pearPipe();
397
- if (!pipe) {
398
- console.error(`${LOG_PREFIX} No IPC pipe available`);
399
- process.exit(1);
400
- }
401
- pipe.autoexit = true;
402
- let exitCode = 0;
403
- pipe.on('end', () => {
404
- try {
405
- Pear.pipe.end();
406
- }
407
- finally {
408
- if (exitCode !== 0)
409
- process.exit(exitCode);
410
- }
411
- });
412
- pipe.once('error', (err) => {
413
- exitCode = exitCode || 1;
414
- console.error(LOG_PREFIX, err);
415
- });
416
- pipe.once('data', (data) => {
417
- void (async () => {
418
- let options = null;
419
- try {
420
- options = cenc.decode(cenc.any, data);
421
- }
422
- catch (err) {
423
- exitCode = 1;
424
- console.error(LOG_PREFIX, err);
425
- try {
426
- pipe.end(cenc.encode(cenc.any, { tag: 'configure', data: {} }));
427
- }
428
- catch {
429
- pipe.destroy(err);
430
- }
431
- return;
432
- }
433
- try {
434
- const config = await configure(options);
435
- pipe.end(cenc.encode(cenc.any, { tag: 'configure', data: config }));
436
- }
437
- catch (err) {
438
- exitCode = 1;
439
- console.error(LOG_PREFIX, err);
440
- try {
441
- pipe.end(cenc.encode(cenc.any, { tag: 'configure', data: options }));
442
- }
443
- catch {
444
- pipe.destroy(err);
445
- }
446
- }
447
- })();
448
- });
@@ -1,22 +0,0 @@
1
- /**
2
- * Initialize the worker environment. Call once at worker startup.
3
- * Returns whether RPC config was parsed from arguments.
4
- */
5
- export declare function initEnv(): {
6
- hasRPCConfig: boolean;
7
- };
8
- /**
9
- * Get the worker environment. Must call initEnv() first.
10
- */
11
- export declare function getEnv(): {
12
- HOME_DIR: string;
13
- QVAC_IPC_SOCKET_PATH?: string | undefined;
14
- };
15
- /**
16
- * Get the validated env config. Must call initEnv() first.
17
- */
18
- export declare function getValidatedEnv(): {
19
- HOME_DIR: string;
20
- QVAC_IPC_SOCKET_PATH?: string | undefined;
21
- };
22
- //# sourceMappingURL=env.d.ts.map
@@ -1,59 +0,0 @@
1
- import env from 'bare-env';
2
- import { isBareKit } from 'which-runtime';
3
- import { z } from 'zod';
4
- const envSchema = z.object({
5
- QVAC_IPC_SOCKET_PATH: z.string().optional(),
6
- HOME_DIR: z.string()
7
- });
8
- let validatedEnv = null;
9
- /**
10
- * Initialize the worker environment. Call once at worker startup.
11
- * Returns whether RPC config was parsed from arguments.
12
- */
13
- export function initEnv() {
14
- const defaultHomeDir =
15
- // Snap's HOME can be revision-scoped; SNAP_USER_COMMON is stable.
16
- env['SNAP_USER_COMMON'] ?? env['HOME'] ?? env['USERPROFILE'] ?? '/tmp';
17
- let envConfig = {
18
- HOME_DIR: defaultHomeDir
19
- };
20
- let hasRPCConfig = false;
21
- if (isBareKit && Bare.argv[0]) {
22
- envConfig['HOME_DIR'] = Bare.argv[0];
23
- }
24
- // Try to parse any argument as JSON config (fail gracefully)
25
- if (Bare.argv[2]) {
26
- try {
27
- const rpcArgs = JSON.parse(Bare.argv[2]);
28
- envConfig = { ...envConfig, ...rpcArgs };
29
- hasRPCConfig = true;
30
- }
31
- catch {
32
- // Not JSON or invalid - use defaults (direct mode)
33
- }
34
- }
35
- validatedEnv = envSchema.parse(envConfig);
36
- return { hasRPCConfig };
37
- }
38
- /**
39
- * Get the worker environment. Must call initEnv() first.
40
- */
41
- export function getEnv() {
42
- if (!validatedEnv) {
43
- // Fallback initialization for cases where initEnv wasn't called
44
- initEnv();
45
- }
46
- return {
47
- ...env,
48
- ...validatedEnv
49
- };
50
- }
51
- /**
52
- * Get the validated env config. Must call initEnv() first.
53
- */
54
- export function getValidatedEnv() {
55
- if (!validatedEnv) {
56
- initEnv();
57
- }
58
- return validatedEnv;
59
- }
@@ -1,2 +0,0 @@
1
- export declare function getQvacPath(...subPaths: string[]): string;
2
- //# sourceMappingURL=qvac-paths.d.ts.map
@@ -1,5 +0,0 @@
1
- import path from 'bare-path';
2
- import { getEnv } from '../env.js';
3
- export function getQvacPath(...subPaths) {
4
- return path.join(getEnv().HOME_DIR, '.qvac', ...subPaths);
5
- }
@@ -1,3 +0,0 @@
1
- export declare function acquireWorkerLock(): void;
2
- export declare function releaseWorkerLock(): void;
3
- //# sourceMappingURL=worker-lock.d.ts.map
@@ -1,67 +0,0 @@
1
- import fs from 'bare-fs';
2
- import path from 'bare-path';
3
- import os from 'bare-os';
4
- import { getServerLogger } from '../../logging/index.js';
5
- import { getQvacPath } from './qvac-paths.js';
6
- const logger = getServerLogger();
7
- const LOCK_FILENAME = '.worker.lock';
8
- function getLockFilePath() {
9
- return getQvacPath(LOCK_FILENAME);
10
- }
11
- function isProcessAlive(pid) {
12
- try {
13
- os.kill(pid, 0);
14
- return true;
15
- }
16
- catch {
17
- return false;
18
- }
19
- }
20
- function readLockFile(lockPath) {
21
- try {
22
- if (!fs.existsSync(lockPath))
23
- return null;
24
- const raw = fs.readFileSync(lockPath, 'utf-8');
25
- return JSON.parse(raw);
26
- }
27
- catch {
28
- return null;
29
- }
30
- }
31
- export function acquireWorkerLock() {
32
- const lockPath = getLockFilePath();
33
- const existing = readLockFile(lockPath);
34
- if (existing) {
35
- if (isProcessAlive(existing.pid)) {
36
- logger.warn(`Another worker (PID ${existing.pid}) is still running — lock file exists at ${lockPath}`);
37
- }
38
- else {
39
- logger.warn(`Stale lock file detected (PID ${existing.pid} is dead, started ${existing.startedAt}). Removing.`);
40
- }
41
- }
42
- const content = {
43
- pid: os.pid(),
44
- startedAt: new Date().toISOString()
45
- };
46
- try {
47
- fs.mkdirSync(path.dirname(lockPath), { recursive: true });
48
- fs.writeFileSync(lockPath, JSON.stringify(content));
49
- logger.debug(`Worker lock acquired (PID ${os.pid()})`);
50
- }
51
- catch (error) {
52
- logger.error('Failed to write worker lock file:', error instanceof Error ? error.message : String(error));
53
- }
54
- }
55
- export function releaseWorkerLock() {
56
- const lockPath = getLockFilePath();
57
- try {
58
- const existing = readLockFile(lockPath);
59
- if (existing && existing.pid === os.pid()) {
60
- fs.unlinkSync(lockPath);
61
- logger.debug('Worker lock released');
62
- }
63
- }
64
- catch {
65
- // Best-effort — may already be gone
66
- }
67
- }
@@ -1,8 +0,0 @@
1
- import RPC from 'bare-rpc';
2
- export declare function createBareKitRPCServer(): RPC;
3
- export interface IPCClientOptions {
4
- onDisconnect?: () => void;
5
- authToken?: string | undefined;
6
- }
7
- export declare function createIPCClient(socketPath: string, options?: IPCClientOptions): RPC;
8
- //# sourceMappingURL=create-server.d.ts.map
@@ -1,51 +0,0 @@
1
- import RPC from 'bare-rpc';
2
- import { connect } from 'bare-net';
3
- import { handleRequest } from './handle-request.js';
4
- import { getServerLogger } from '../logging/index.js';
5
- const logger = getServerLogger();
6
- export function createBareKitRPCServer() {
7
- const { IPC } = globalThis.BareKit;
8
- return new RPC(IPC, handleRequest);
9
- }
10
- /**
11
- * Dial the client's IPC endpoint. Two encodings cross the handshake:
12
- *
13
- * - `tcp://host:port` — a loopback TCP endpoint. Used by clients whose
14
- * runtime has no portable server for filesystem sockets, notably the
15
- * Python `asyncio` transport (`start_unix_server` is Unix-only, and
16
- * asyncio has no cross-platform named-pipe server). One code path on
17
- * every OS, so Windows dials the same way Linux/macOS do.
18
- * - anything else — a filesystem path: a Unix domain socket, or a
19
- * `\\.\pipe\...` named pipe on Windows, as the Node client (`node:net`)
20
- * creates.
21
- */
22
- function connectToEndpoint(endpoint) {
23
- if (endpoint.startsWith('tcp://')) {
24
- const hostPort = endpoint.slice('tcp://'.length);
25
- const sep = hostPort.lastIndexOf(':');
26
- const host = hostPort.slice(0, sep);
27
- const port = Number(hostPort.slice(sep + 1));
28
- return connect(port, host);
29
- }
30
- return connect(endpoint);
31
- }
32
- export function createIPCClient(socketPath, options) {
33
- logger.info(`Connecting to IPC socket at ${socketPath}`);
34
- const socket = connectToEndpoint(socketPath);
35
- socket.on('connect', () => {
36
- logger.info('Connected to IPC server');
37
- });
38
- socket.on('error', (err) => {
39
- logger.error('IPC client connection error:', err);
40
- });
41
- socket.on('close', () => {
42
- logger.warn('IPC socket closed — parent process likely terminated');
43
- options?.onDisconnect?.();
44
- });
45
- // Pipe and Unix-socket clients have no reader for this line, so a token
46
- // inherited from the parent's environment must not reach them.
47
- if (options?.authToken && socketPath.startsWith('tcp://')) {
48
- socket.write(options.authToken + '\n');
49
- }
50
- return new RPC(socket, handleRequest);
51
- }