@qvac/sdk 0.23.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 (239) hide show
  1. package/NOTICE +115 -58
  2. package/README.md +10 -13
  3. package/dist/examples/asr/parakeet-sortformer.js +24 -14
  4. package/dist/examples/asr/parakeet-transcribepsy-filesystem.js +40 -11
  5. package/dist/examples/asr/parakeet-unified-coreml.js +14 -9
  6. package/dist/examples/asr/whispercpp-prompt.js +9 -5
  7. package/dist/examples/assess-model-fit.d.ts +7 -9
  8. package/dist/examples/assess-model-fit.js +22 -43
  9. package/dist/examples/calc-tokens.d.ts +2 -0
  10. package/dist/examples/calc-tokens.js +21 -0
  11. package/dist/examples/classification/classify-image.js +11 -5
  12. package/dist/examples/completion-stop-reason.d.ts +3 -3
  13. package/dist/examples/completion-stop-reason.js +4 -4
  14. package/dist/examples/diffusion-flux3-klein.d.ts +2 -0
  15. package/dist/examples/diffusion-flux3-klein.js +102 -0
  16. package/dist/examples/diffusion-moss-image.d.ts +2 -0
  17. package/dist/examples/diffusion-moss-image.js +126 -0
  18. package/dist/examples/diffusion-qwen-image-21.js +15 -4
  19. package/dist/examples/embed-multimodal.d.ts +2 -0
  20. package/dist/examples/embed-multimodal.js +80 -0
  21. package/dist/examples/embed-p2p.js +2 -2
  22. package/dist/examples/image/megaloc.d.ts +2 -0
  23. package/dist/examples/image/megaloc.js +37 -0
  24. package/dist/examples/llamacpp-multimodal.js +18 -0
  25. package/dist/examples/rag/rag-hyperdb/pipeline.js +2 -2
  26. package/dist/examples/rag/rag-turbovec.js +2 -2
  27. package/dist/examples/sessions.d.ts +17 -0
  28. package/dist/examples/sessions.js +63 -0
  29. package/dist/examples/tools/llamacpp-deferred-tools.js +8 -4
  30. package/dist/scripts/check-resource-collectors-packaging.js +7 -6
  31. package/dist/scripts/contract/build-contract.d.ts +2 -1
  32. package/dist/scripts/contract/build-contract.js +13 -1
  33. package/dist/scripts/contract/constants-registry.d.ts +17 -0
  34. package/dist/scripts/contract/constants-registry.js +8 -2
  35. package/dist/scripts/contract/method-shapes.d.ts +4 -0
  36. package/dist/scripts/contract/method-shapes.js +4 -0
  37. package/dist/scripts/enforce-inference-versions.d.ts +1 -1
  38. package/dist/scripts/enforce-inference-versions.js +28 -18
  39. package/dist/scripts/generate-bare-kit-runtimes.js +101 -69
  40. package/dist/src/client/api/assess-model-fit.d.ts +17 -17
  41. package/dist/src/client/api/assess-model-fit.js +18 -31
  42. package/dist/src/client/api/audio-edit.d.ts +5 -3
  43. package/dist/src/client/api/audio-edit.js +5 -3
  44. package/dist/src/client/api/audio-gen-result.js +134 -45
  45. package/dist/src/client/api/audio-gen.d.ts +40 -3
  46. package/dist/src/client/api/audio-gen.js +40 -3
  47. package/dist/src/client/api/audio-understand.d.ts +2 -2
  48. package/dist/src/client/api/audio-understand.js +2 -2
  49. package/dist/src/client/api/batch-completion.js +2 -1
  50. package/dist/src/client/api/calc-tokens.d.ts +33 -0
  51. package/dist/src/client/api/calc-tokens.js +44 -0
  52. package/dist/src/client/api/cancel.d.ts +2 -2
  53. package/dist/src/client/api/cancel.js +2 -2
  54. package/dist/src/client/api/classify.d.ts +12 -5
  55. package/dist/src/client/api/classify.js +17 -5
  56. package/dist/src/client/api/client-request-id.d.ts +0 -15
  57. package/dist/src/client/api/client-request-id.js +15 -12
  58. package/dist/src/client/api/completion-stream.d.ts +8 -1
  59. package/dist/src/client/api/completion-stream.js +10 -1
  60. package/dist/src/client/api/delete-cache.d.ts +9 -2
  61. package/dist/src/client/api/delete-cache.js +13 -3
  62. package/dist/src/client/api/diffusion.d.ts +20 -4
  63. package/dist/src/client/api/diffusion.js +23 -5
  64. package/dist/src/client/api/embed.d.ts +82 -29
  65. package/dist/src/client/api/embed.js +64 -19
  66. package/dist/src/client/api/get-model-info.d.ts +2 -2
  67. package/dist/src/client/api/get-model-info.js +2 -2
  68. package/dist/src/client/api/get-system-resources.d.ts +2 -2
  69. package/dist/src/client/api/get-system-resources.js +2 -2
  70. package/dist/src/client/api/heartbeat.d.ts +3 -2
  71. package/dist/src/client/api/heartbeat.js +3 -2
  72. package/dist/src/client/api/index.d.ts +4 -3
  73. package/dist/src/client/api/index.js +2 -1
  74. package/dist/src/client/api/invoke-plugin.d.ts +8 -2
  75. package/dist/src/client/api/invoke-plugin.js +17 -2
  76. package/dist/src/client/api/load-model.js +5 -2
  77. package/dist/src/client/api/ocr.d.ts +5 -3
  78. package/dist/src/client/api/ocr.js +44 -21
  79. package/dist/src/client/api/rag.d.ts +1 -1
  80. package/dist/src/client/api/rag.js +1 -1
  81. package/dist/src/client/api/registry.d.ts +17 -7
  82. package/dist/src/client/api/registry.js +37 -12
  83. package/dist/src/client/api/resume.d.ts +2 -1
  84. package/dist/src/client/api/resume.js +2 -2
  85. package/dist/src/client/api/rpc-server.d.ts +4 -4
  86. package/dist/src/client/api/rpc-server.js +10 -10
  87. package/dist/src/client/api/state.d.ts +2 -2
  88. package/dist/src/client/api/state.js +2 -2
  89. package/dist/src/client/api/subscribe-logs.d.ts +2 -2
  90. package/dist/src/client/api/subscribe-logs.js +2 -2
  91. package/dist/src/client/api/suspend.d.ts +4 -2
  92. package/dist/src/client/api/suspend.js +4 -3
  93. package/dist/src/client/api/text-to-speech.d.ts +14 -5
  94. package/dist/src/client/api/text-to-speech.js +83 -29
  95. package/dist/src/client/api/transcribe.d.ts +6 -2
  96. package/dist/src/client/api/transcribe.js +7 -1
  97. package/dist/src/client/api/unload-model.d.ts +19 -7
  98. package/dist/src/client/api/unload-model.js +29 -11
  99. package/dist/src/client/api/upscale.d.ts +6 -3
  100. package/dist/src/client/api/upscale.js +9 -4
  101. package/dist/src/client/api/vector-index.d.ts +50 -16
  102. package/dist/src/client/api/vector-index.js +100 -48
  103. package/dist/src/client/api/video-request.d.ts +5 -5
  104. package/dist/src/client/api/video.d.ts +3 -2
  105. package/dist/src/client/api/video.js +3 -2
  106. package/dist/src/client/api/vla.d.ts +9 -5
  107. package/dist/src/client/api/vla.js +17 -8
  108. package/dist/src/client/api/world.d.ts +5 -5
  109. package/dist/src/client/api/world.js +4 -4
  110. package/dist/src/client/init-hooks.d.ts +6 -4
  111. package/dist/src/client/init-hooks.js +12 -15
  112. package/dist/src/client/logging-stream-registry.d.ts +6 -3
  113. package/dist/src/client/logging-stream-registry.js +31 -12
  114. package/dist/src/client/rpc/bundle-stamp.d.ts +29 -0
  115. package/dist/src/client/rpc/bundle-stamp.js +75 -0
  116. package/dist/src/client/rpc/expo-home-dir.d.ts +2 -0
  117. package/dist/src/client/rpc/expo-home-dir.js +4 -0
  118. package/dist/src/client/rpc/expo-rpc-client.js +189 -135
  119. package/dist/src/client/rpc/node-rpc-client.js +322 -413
  120. package/dist/src/client/rpc/pear-runtime.d.ts +12 -0
  121. package/dist/src/client/rpc/pear-runtime.js +12 -0
  122. package/dist/src/client/rpc/rpc-client.d.ts +5 -4
  123. package/dist/src/client/rpc/rpc-client.js +126 -23
  124. package/dist/src/client/rpc/rpc-error.js +21 -2
  125. package/dist/src/client/rpc/unbundled-harness.d.ts +16 -0
  126. package/dist/src/client/rpc/unbundled-harness.js +27 -0
  127. package/dist/src/client/rpc/worker-failure.d.ts +27 -0
  128. package/dist/src/client/rpc/worker-failure.js +61 -0
  129. package/dist/src/client/session-registry.d.ts +75 -0
  130. package/dist/src/client/session-registry.js +149 -0
  131. package/dist/src/client/session.d.ts +125 -0
  132. package/dist/src/client/session.js +148 -0
  133. package/dist/src/commands/bundle/addons.d.ts +14 -0
  134. package/dist/src/commands/bundle/addons.js +65 -0
  135. package/dist/src/commands/bundle/constants.js +1 -0
  136. package/dist/src/commands/bundle/entry-gen.d.ts +1 -5
  137. package/dist/src/commands/bundle/entry-gen.js +17 -50
  138. package/dist/src/commands/bundle/index.d.ts +59 -13
  139. package/dist/src/commands/bundle/index.js +345 -121
  140. package/dist/src/commands/bundle/link.d.ts +58 -0
  141. package/dist/src/commands/bundle/link.js +135 -0
  142. package/dist/src/commands/bundle/node-support.d.ts +13 -0
  143. package/dist/src/commands/bundle/node-support.js +23 -0
  144. package/dist/src/commands/bundle/read-bundle.d.ts +9 -0
  145. package/dist/src/commands/bundle/read-bundle.js +27 -0
  146. package/dist/src/commands/bundle/resolve-sdk-import.d.ts +6 -0
  147. package/dist/src/commands/bundle/resolve-sdk-import.js +24 -28
  148. package/dist/src/commands/bundle/scratch.d.ts +35 -0
  149. package/dist/src/commands/bundle/scratch.js +178 -0
  150. package/dist/src/commands/bundle/targets.d.ts +14 -0
  151. package/dist/src/commands/bundle/targets.js +37 -0
  152. package/dist/src/commands/host-prebuilds/index.d.ts +5 -4
  153. package/dist/src/commands/host-prebuilds/index.js +9 -7
  154. package/dist/src/commands/index.d.ts +4 -3
  155. package/dist/src/commands/verify/abi.d.ts +20 -14
  156. package/dist/src/commands/verify/abi.js +11 -79
  157. package/dist/src/commands/verify/bare-kit-runtime.d.ts +20 -22
  158. package/dist/src/commands/verify/bare-kit-runtime.js +102 -150
  159. package/dist/src/commands/verify/bare-kit-runtimes.d.ts +10 -9
  160. package/dist/src/commands/verify/bare-kit-runtimes.js +21 -21
  161. package/dist/src/commands/verify/bundle-source.js +25 -21
  162. package/dist/src/commands/verify/engines-advice.d.ts +2 -8
  163. package/dist/src/commands/verify/engines-advice.js +7 -54
  164. package/dist/src/commands/verify/index.d.ts +30 -29
  165. package/dist/src/commands/verify/index.js +92 -200
  166. package/dist/src/commands/verify/prebuilds.d.ts +3 -5
  167. package/dist/src/commands/verify/prebuilds.js +1 -2
  168. package/dist/src/commands/verify/resource-collectors.d.ts +0 -6
  169. package/dist/src/commands/verify/resource-collectors.js +1 -50
  170. package/dist/src/commands/verify/sidecar-runtime.d.ts +6 -0
  171. package/dist/src/commands/verify/sidecar-runtime.js +51 -0
  172. package/dist/src/expo/plugins/withBareKit.d.ts +59 -0
  173. package/dist/src/expo/plugins/withBareKit.js +204 -0
  174. package/dist/src/expo/plugins/withMobileBundle.d.ts +4 -11
  175. package/dist/src/expo/plugins/withMobileBundle.js +36 -57
  176. package/dist/src/expo/plugins/withQvacSDK.d.ts +1 -0
  177. package/dist/src/expo/plugins/withQvacSDK.js +3 -0
  178. package/dist/src/index.d.ts +6 -5
  179. package/dist/src/index.js +10 -14
  180. package/dist/src/logging/utils.js +10 -2
  181. package/dist/src/plugin-ids.d.ts +2 -1
  182. package/dist/src/plugin-ids.js +2 -0
  183. package/dist/src/schemas/public.d.ts +1 -1
  184. package/dist/src/schemas/public.js +1 -1
  185. package/dist/src/schemas/sdk-errors-client.d.ts +5 -6
  186. package/dist/src/schemas/sdk-errors-client.js +30 -36
  187. package/dist/src/schemas/sdk-errors-server.d.ts +11 -1
  188. package/dist/src/schemas/sdk-errors-server.js +60 -2
  189. package/dist/src/server/rpc/rpc-utils.d.ts +25 -4
  190. package/dist/src/server/rpc/rpc-utils.js +39 -5
  191. package/dist/src/utils/errors-client.d.ts +37 -29
  192. package/dist/src/utils/errors-client.js +50 -41
  193. package/dist/src/utils/errors-server.d.ts +59 -1
  194. package/dist/src/utils/errors-server.js +110 -1
  195. package/dist/src/utils/withTimeout.js +34 -17
  196. package/dist/src/worker/handle-request.js +25 -22
  197. package/dist/src/worker/handler-utils.d.ts +2 -6
  198. package/dist/src/worker/handler-utils.js +2 -20
  199. package/dist/src/worker/index.d.ts +2 -4
  200. package/dist/src/worker/index.js +23 -35
  201. package/dist/src/worker/plugins/ggml-image-embedding.d.ts +2 -0
  202. package/dist/src/worker/plugins/ggml-image-embedding.js +1 -0
  203. package/dist/src/worker/shim.d.ts +4 -0
  204. package/dist/src/worker/shim.js +7 -0
  205. package/dist/src/worker/start.d.ts +9 -0
  206. package/dist/src/worker/start.js +16 -0
  207. package/dist/src/worker/unbundled-shim.d.ts +2 -0
  208. package/dist/src/worker/unbundled-shim.js +4 -0
  209. package/docs/system-resources-support-matrix.md +27 -19
  210. package/package.json +62 -51
  211. package/src/electron-forge/index.cjs +65 -91
  212. package/dist/examples/model-fit-ui/server.d.ts +0 -24
  213. package/dist/examples/model-fit-ui/server.js +0 -221
  214. package/dist/src/client/rpc/ensure-worker-ready.d.ts +0 -9
  215. package/dist/src/client/rpc/ensure-worker-ready.js +0 -17
  216. package/dist/src/client/rpc/init-timeout.d.ts +0 -26
  217. package/dist/src/client/rpc/init-timeout.js +0 -25
  218. package/dist/src/client/rpc/ipc-socket-path.d.ts +0 -11
  219. package/dist/src/client/rpc/ipc-socket-path.js +0 -30
  220. package/dist/src/client/rpc/worker-startup-error.d.ts +0 -12
  221. package/dist/src/client/rpc/worker-startup-error.js +0 -13
  222. package/dist/src/commands/bundle/bare-pack.d.ts +0 -21
  223. package/dist/src/commands/bundle/bare-pack.js +0 -77
  224. package/dist/src/commands/bundle/manifest.d.ts +0 -25
  225. package/dist/src/commands/bundle/manifest.js +0 -192
  226. package/dist/src/expo/plugins/link-addons.d.ts +0 -18
  227. package/dist/src/expo/plugins/link-addons.js +0 -65
  228. package/dist/src/pear/pre.d.ts +0 -21
  229. package/dist/src/pear/pre.js +0 -450
  230. package/dist/src/server/env.d.ts +0 -22
  231. package/dist/src/server/env.js +0 -59
  232. package/dist/src/server/utils/qvac-paths.d.ts +0 -2
  233. package/dist/src/server/utils/qvac-paths.js +0 -5
  234. package/dist/src/server/utils/worker-lock.d.ts +0 -3
  235. package/dist/src/server/utils/worker-lock.js +0 -67
  236. package/dist/src/worker/create-server.d.ts +0 -8
  237. package/dist/src/worker/create-server.js +0 -51
  238. package/dist/src/worker/lifecycle.d.ts +0 -23
  239. package/dist/src/worker/lifecycle.js +0 -149
@@ -1,435 +1,369 @@
1
1
  import RPC from 'bare-rpc';
2
- import spawn, {} from 'bare-runtime/spawn';
3
2
  import fs from 'node:fs';
4
- import { createServer } from 'node:net';
5
3
  import os from 'node:os';
6
4
  import path from 'node:path';
7
- import { fileURLToPath } from 'node:url';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
8
6
  import { initializeConfig } from '../../client/init-hooks.js';
9
7
  import { resolveConfig } from '../../client/config-loader/resolve-config.node.js';
10
- import { getClientLogger, getLogger, SDK_SERVER_NAMESPACE } from '../../logging/index.js';
11
- import { BareRuntimeBinaryNotFoundError, RPCInitTimeoutError, WorkerCrashedError, WorkerShutdownError } from '../../utils/errors-client.js';
12
- import { createRPCInitTimeoutCause } from './worker-startup-error.js';
13
- import { createIPCSocketPath, removeIPCSocketPath } from './ipc-socket-path.js';
14
- import { RPC_INIT_TIMEOUT_ENV_VAR, resolveRPCInitTimeoutMs } from './init-timeout.js';
15
- const WORKER_STDERR_TAIL_CHARS = 16_384;
8
+ import { findInAncestorNodeModules } from '../../expo/plugins/find-in-ancestor-node-modules.js';
9
+ import { getClientLogger } from '../../logging/index.js';
10
+ import { WorkerCrashedError, WorkerFileNotFoundError, WorkerShutdownError, WorkerStartupError } from '../../utils/errors-client.js';
11
+ import { bundledSdkMismatch, bundledTarget, installedSdkVersion } from './bundle-stamp.js';
12
+ import { getPearRuntime } from './pear-runtime.js';
13
+ import { start as startUnbundled } from './unbundled-harness.js';
14
+ import { DEFAULT_WORKER_START_TIMEOUT_MS, rejectOnAbort, startDeadline, stderrTail, WORKER_SHUTDOWN_GRACE_MS, workerCrashed, workerStartupFailed } from './worker-failure.js';
16
15
  const logger = getClientLogger();
17
- // Addons route real logs through their JS callback; anything written straight to the
18
- // worker's stderr is treated as debug.
19
- const workerLogger = getLogger(SDK_SERVER_NAMESPACE, { enableConsole: false });
16
+ const STOWED_HARNESS = 'index.js';
17
+ const STOWED_BUNDLE = 'index.bundle';
20
18
  let rpcInstance = null;
21
19
  let rpcPromise = null;
22
- let bareWorkerProc = null;
23
- let ipcServer = null;
24
- let currentSocketPath = null;
20
+ let worker = null;
25
21
  let closePromise = null;
26
- // Aborted when the worker dies (crash) or close() runs (planned). Used
27
- // to unblock in-flight `req.reply()` callers โ€” bare-rpc's `_onerror`
28
- // does not iterate `_outgoingRequests`, so without this signal they
29
- // would hang on the dead socket.
22
+ // Bumped by close(); a start that finishes under an older generation stops its
23
+ // own worker, so a caller waiting on that start never receives a closed client.
24
+ let generation = 0;
25
+ // Aborted when the worker dies (crash) or close() runs (planned).
30
26
  let workerLifeController = null;
31
- /**
32
- * Find project root by looking for package.json (sync version)
33
- * Safe to call at module load time
34
- */
27
+ // Set while a worker is launching and not yet ready; close() aborts it.
28
+ let launchController = null;
29
+ const workerErrors = new WeakMap();
35
30
  function findProjectRootSync() {
36
31
  let dir = process.cwd();
37
32
  const root = path.parse(dir).root;
38
33
  while (dir !== root) {
39
- if (fs.existsSync(path.join(dir, 'package.json'))) {
34
+ if (fs.existsSync(path.join(dir, 'package.json')))
40
35
  return dir;
41
- }
42
36
  dir = path.dirname(dir);
43
37
  }
44
38
  return undefined;
45
39
  }
46
- function getResourcesPathSync() {
47
- const { resourcesPath } = process;
48
- return typeof resourcesPath === 'string' ? resourcesPath : undefined;
49
- }
50
- function resolvePackagedWorkerPath() {
51
- const resourcesPath = getResourcesPathSync();
52
- if (!resourcesPath)
40
+ /**
41
+ * The harness in `dir` when it holds a bundle for `target`. A bundle for
42
+ * another target is skipped with a warning; one that does not record its
43
+ * target is used.
44
+ */
45
+ function stowedHarness(dir, target) {
46
+ const harness = path.join(dir, STOWED_HARNESS);
47
+ if (!fs.existsSync(harness) || !fs.existsSync(path.join(dir, STOWED_BUNDLE)))
48
+ return undefined;
49
+ const bundledFor = bundledTarget(dir);
50
+ if (bundledFor !== undefined && bundledFor !== target) {
51
+ logger.warn(`โš ๏ธ The worker in ${dir} was bundled for ${bundledFor}; this app runs ${target}. ` +
52
+ `Run \`qvac bundle sdk --target ${target}\` to use a bundled worker.`);
53
53
  return undefined;
54
- const candidates = [
55
- path.join(resourcesPath, 'app.asar.unpacked', 'qvac', 'worker.entry.mjs'),
56
- path.join(resourcesPath, 'app', 'qvac', 'worker.entry.mjs'),
57
- path.join(resourcesPath, 'qvac', 'worker.entry.mjs')
58
- ];
59
- for (const candidate of candidates) {
60
- if (fs.existsSync(candidate))
61
- return candidate;
62
54
  }
63
- return undefined;
55
+ const installed = installedSdkVersion();
56
+ const mismatch = installed === undefined ? null : bundledSdkMismatch(dir, installed);
57
+ if (mismatch)
58
+ logger.warn(`โš ๏ธ ${mismatch}`);
59
+ return harness;
60
+ }
61
+ function packagedWorkerDirs() {
62
+ const { resourcesPath } = process;
63
+ if (typeof resourcesPath !== 'string')
64
+ return [];
65
+ return [
66
+ path.join(resourcesPath, 'app.asar.unpacked', 'qvac', 'worker'),
67
+ path.join(resourcesPath, 'app', 'qvac', 'worker'),
68
+ path.join(resourcesPath, 'qvac', 'worker')
69
+ ];
64
70
  }
65
71
  /**
66
- * Resolve the SDK's default worker entry via bundler-visible asset references.
67
- *
68
- * The worker is transpiled with its `@/` aliases resolved into
69
- * `dist/src/worker/index.js`; Bare cannot run the `@/`-laden source. This file
70
- * compiles to `dist/src/client/rpc/node-rpc-client.js`, so the built worker sits
71
- * at `../../worker/index.js` for both the dev and packaged layouts.
72
- *
73
- * `path.resolve(__dirname, ...)` is invisible to static analysis, so packaged
74
- * consumers ship without the worker. We use `import.meta.asset(<literal>)` on
75
- * Bare (detected by bare-module-lexer) and fall back to
76
- * `new URL(<literal>, import.meta.url)` elsewhere. The spec must be a string
77
- * literal at the call site.
72
+ * An asset reference keeps the file visible to bundlers of the host app:
73
+ * `import.meta.asset(<literal>)` on Bare, `new URL(<literal>, import.meta.url)`
74
+ * elsewhere. This module compiles to `dist/src/client/rpc/`.
78
75
  */
79
- function getDefaultWorkerPath() {
80
- const hasAsset = typeof import.meta.asset === 'function';
81
- const workerUrl = hasAsset
82
- ? new URL(import.meta.asset('../../worker/index.js'))
83
- : new URL('../../worker/index.js', import.meta.url);
84
- return fileURLToPath(workerUrl);
76
+ function sdkWorkerEntry() {
77
+ const asset = import.meta.asset;
78
+ return fileURLToPath(asset ? asset('../../worker/index.js') : new URL('../../worker/index.js', import.meta.url));
79
+ }
80
+ /** An entry that imports `worker-lifecycle` was generated by an older `@qvac/sdk`, which this one cannot run. */
81
+ function assertCurrentEntry(entry) {
82
+ if (!fs.readFileSync(entry, 'utf8').includes('/worker-lifecycle'))
83
+ return entry;
84
+ throw new WorkerStartupError(`${entry} was generated by an older @qvac/sdk. Run \`qvac bundle sdk\` again.`, { exitCode: null, exitSignal: null, timedOut: false });
85
85
  }
86
86
  /**
87
- * Resolve worker path with priority:
88
- * 1. QVAC_WORKER_PATH environment variable
89
- * 2. Packaged Electron app worker entry
90
- * 3. qvac/worker.entry.mjs in project root (generated by npx qvac bundle sdk)
91
- * 4. Default SDK worker
87
+ * With a Pear runtime registered, the `pear-runtime` bundle from
88
+ * QVAC_WORKER_PATH, the packaged app, or `qvac/worker/` in the project root.
92
89
  */
93
- function resolveWorkerPath() {
94
- const envWorkerPath = process.env['QVAC_WORKER_PATH'];
95
- if (envWorkerPath) {
96
- const normalized = path.resolve(envWorkerPath);
97
- if (fs.existsSync(normalized)) {
98
- logger.info(`๐Ÿ”ง Using worker entry from QVAC_WORKER_PATH: ${normalized}`);
99
- return normalized;
90
+ function resolvePearWorkerSource(pear) {
91
+ const envPath = process.env['QVAC_WORKER_PATH'];
92
+ const projectRoot = findProjectRootSync();
93
+ const projectWorkerDir = path.join(projectRoot ?? process.cwd(), 'qvac', 'worker');
94
+ if (envPath && fs.existsSync(envPath) && fs.statSync(envPath).isFile()) {
95
+ logger.warn(`โš ๏ธ QVAC_WORKER_PATH is a file, but a Pear app runs a bundled worker folder. Ignoring ${envPath}.`);
96
+ }
97
+ const dirs = [
98
+ ...(envPath ? [path.resolve(envPath)] : []),
99
+ ...packagedWorkerDirs(),
100
+ projectWorkerDir
101
+ ];
102
+ for (const dir of dirs) {
103
+ const harness = stowedHarness(dir, 'pear-runtime');
104
+ if (harness) {
105
+ logger.info(`๐Ÿ”ง Using Pear worker: ${harness}`);
106
+ return { harness, pear };
100
107
  }
101
- logger.warn(`โš ๏ธ QVAC_WORKER_PATH was set but file was not found: ${normalized}. Falling back.`);
102
108
  }
103
- // Prefer packaged worker entry when running as a packaged Electron app.
104
- // This avoids accidental coupling to the project's cwd, and ensures the
105
- // bare worker reads JS modules from the filesystem (not app.asar).
106
- const packagedWorker = resolvePackagedWorkerPath();
107
- if (packagedWorker) {
108
- logger.info(`๐Ÿ”ง Using packaged worker entry: ${packagedWorker}`);
109
- return packagedWorker;
109
+ throw new WorkerFileNotFoundError(path.join(projectWorkerDir, STOWED_HARNESS));
110
+ }
111
+ /**
112
+ * The worker to start, in order:
113
+ * 1. QVAC_WORKER_PATH: a bundled worker folder, or a worker entry file
114
+ * 2. The packaged Electron app's bundled worker
115
+ * 3. `qvac/worker/` in the project root, written by `bundleSdk`
116
+ * 4. `qvac/worker.entry.mjs` in the project root, run unbundled
117
+ * 5. The SDK's default worker, run unbundled
118
+ */
119
+ function resolveWorkerSource() {
120
+ const pear = getPearRuntime();
121
+ if (pear)
122
+ return resolvePearWorkerSource(pear);
123
+ const envPath = process.env['QVAC_WORKER_PATH'];
124
+ if (envPath) {
125
+ const resolved = path.resolve(envPath);
126
+ const harness = stowedHarness(resolved, 'bare-sidecar');
127
+ if (harness) {
128
+ logger.info(`๐Ÿ”ง Using bundled worker from QVAC_WORKER_PATH: ${resolved}`);
129
+ return { harness };
130
+ }
131
+ if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) {
132
+ logger.info(`๐Ÿ”ง Using worker entry from QVAC_WORKER_PATH: ${resolved}`);
133
+ return { entry: assertCurrentEntry(resolved) };
134
+ }
135
+ logger.warn(`โš ๏ธ QVAC_WORKER_PATH was set but no worker was found at ${resolved}. Falling back.`);
136
+ }
137
+ for (const dir of packagedWorkerDirs()) {
138
+ const harness = stowedHarness(dir, 'bare-sidecar');
139
+ if (harness) {
140
+ logger.info(`๐Ÿ”ง Using packaged worker: ${harness}`);
141
+ return { harness };
142
+ }
110
143
  }
111
- // Check for custom worker entry at project root
112
- // Note: We use worker.entry.mjs (unbundled ESM) for desktop because bare can
113
- // load ES modules directly. The packed bundle is for mobile only.
114
144
  const projectRoot = findProjectRootSync();
115
145
  if (projectRoot) {
116
- const customEntry = path.join(projectRoot, 'qvac', 'worker.entry.mjs');
117
- if (fs.existsSync(customEntry)) {
118
- logger.info(`๐Ÿ”ง Using custom worker entry: ${customEntry}`);
119
- return customEntry;
146
+ const harness = stowedHarness(path.join(projectRoot, 'qvac', 'worker'), 'bare-sidecar');
147
+ if (harness) {
148
+ logger.info(`๐Ÿ”ง Using bundled worker: ${harness}`);
149
+ return { harness };
150
+ }
151
+ const entry = path.join(projectRoot, 'qvac', 'worker.entry.mjs');
152
+ if (fs.existsSync(entry)) {
153
+ logger.info(`๐Ÿ”ง Using worker entry: ${entry}`);
154
+ return { entry: assertCurrentEntry(entry) };
120
155
  }
121
156
  }
122
- // Fallback to default SDK worker
123
- const defaultPath = getDefaultWorkerPath();
124
- logger.debug(`๐Ÿ”ง Using default SDK worker: ${defaultPath}`);
125
- return defaultPath;
157
+ const entry = sdkWorkerEntry();
158
+ logger.debug(`๐Ÿ”ง Using default SDK worker: ${entry}`);
159
+ return { entry };
126
160
  }
127
- const WORKER_PATH = resolveWorkerPath();
128
- function bestEffortRemoveSocket(socketPath) {
129
- if (!socketPath)
130
- return;
161
+ async function importHarness(file) {
162
+ const loaded = (await import(pathToFileURL(file).href));
163
+ return typeof loaded.start === 'function' ? loaded : loaded.default;
164
+ }
165
+ /**
166
+ * The config file, read before the worker starts because it sets the startup
167
+ * timeout. A config that fails to load is reported by `initializeConfig`,
168
+ * which reads it again.
169
+ */
170
+ async function readConfigBeforeStart() {
131
171
  try {
132
- removeIPCSocketPath(socketPath);
172
+ return { config: await resolveConfig() };
133
173
  }
134
174
  catch (error) {
135
- logger.debug('Failed to remove IPC socket path', { socketPath, error });
175
+ logger.debug('Reading the config for the worker startup timeout failed; using the default', {
176
+ error
177
+ });
178
+ return null;
136
179
  }
137
180
  }
138
- function appendWorkerStderrTail(current, chunk) {
139
- const next = current + chunk;
140
- if (next.length <= WORKER_STDERR_TAIL_CHARS)
141
- return next;
142
- return next.slice(next.length - WORKER_STDERR_TAIL_CHARS);
181
+ /**
182
+ * Spawns the bare-sidecar bundle next to `harnessFile` with stderr piped, and
183
+ * hands the process to the harness's `connect`. Without the bare-sidecar the
184
+ * harness imports, the harness starts it with stderr inherited.
185
+ */
186
+ async function startBundled(harnessFile, harness, options, onStderr, onSpawn) {
187
+ const sidecarDir = findInAncestorNodeModules(path.dirname(harnessFile), 'bare-sidecar');
188
+ if (sidecarDir === null || harness.connect === undefined)
189
+ return harness.start(options);
190
+ const { default: Sidecar } = (await import(pathToFileURL(path.join(sidecarDir, 'index.js')).href));
191
+ const bundle = path.join(path.dirname(harnessFile), STOWED_BUNDLE);
192
+ const sidecar = new Sidecar(bundle, { stdio: ['inherit', 'inherit', 'pipe'] });
193
+ sidecar.stderr?.on('data', onStderr);
194
+ onSpawn(sidecar);
195
+ return harness.connect(sidecar, options);
143
196
  }
144
- function resetModuleState() {
145
- rpcInstance = null;
146
- rpcPromise = null;
147
- bareWorkerProc = null;
148
- ipcServer = null;
149
- currentSocketPath = null;
150
- workerLifeController = null;
197
+ /** `pear` with each process it runs passed to `onSpawn`. */
198
+ function pearReporting(pear, onSpawn) {
199
+ return {
200
+ run(...args) {
201
+ const child = pear.run(...args);
202
+ onSpawn(child);
203
+ return child;
204
+ }
205
+ };
151
206
  }
152
- function snapshotAndResetState() {
153
- const workerToClose = bareWorkerProc;
154
- const serverToClose = ipcServer;
155
- const socketPathToClose = currentSocketPath;
156
- resetModuleState();
157
- return { workerToClose, serverToClose, socketPathToClose };
207
+ /** Kills each spawned worker process once `signal` aborts. */
208
+ function killOnAbort(signal) {
209
+ return (child) => {
210
+ const kill = () => child.kill('SIGKILL');
211
+ if (signal.aborted)
212
+ kill();
213
+ else
214
+ signal.addEventListener('abort', kill, { once: true });
215
+ };
158
216
  }
159
- // Shared cleanup for every init reject path: reset module state, stop the
160
- // worker + IPC server, and remove the socket so a failed start never leaks
161
- // resources. Mirrors closeSyncForExit without the planned-shutdown abort.
162
- function teardownFailedInit() {
163
- const { workerToClose, serverToClose, socketPathToClose } = snapshotAndResetState();
164
- if (workerToClose) {
165
- try {
166
- workerToClose.kill('SIGTERM');
167
- }
168
- catch (error) {
169
- logger.debug('Failed to kill bare worker after init failure', { error });
170
- }
217
+ async function launchWorker(source, timeout, onStderr, onSpawn) {
218
+ const options = { timeout, grace: WORKER_SHUTDOWN_GRACE_MS };
219
+ if ('entry' in source) {
220
+ return (await startUnbundled(source.entry, { ...options, onStderr, onSpawn })).ipc;
171
221
  }
172
- if (serverToClose) {
173
- try {
174
- serverToClose.close();
175
- }
176
- catch (error) {
177
- logger.debug('Failed to close IPC server after init failure', { error });
178
- }
222
+ const harness = await importHarness(source.harness);
223
+ if ('pear' in source) {
224
+ return (await harness.start(pearReporting(source.pear, onSpawn), options)).ipc;
179
225
  }
180
- bestEffortRemoveSocket(socketPathToClose);
181
- }
182
- export function getWorkerLifeSignal() {
183
- return workerLifeController?.signal ?? null;
226
+ return (await startBundled(source.harness, harness, options, onStderr, onSpawn)).ipc;
184
227
  }
185
- // Called by the RPC layer when it detects the channel closed out from under
186
- // an in-flight call (bare-rpc's own teardown beat the child `'exit'` event
187
- // we normally rely on). Tears down immediately rather than waiting on that
188
- // slower signal, so the next call respawns instead of reusing the dead
189
- // connection. A no-op if the life signal already aborted โ€” e.g. the real
190
- // exit handler got there first, or a concurrent caller already tore down.
191
- export function notifyChannelClosed() {
192
- const controller = workerLifeController;
193
- if (!controller || controller.signal.aborted)
194
- return;
195
- const { workerToClose, serverToClose, socketPathToClose } = snapshotAndResetState();
196
- if (workerToClose) {
197
- try {
198
- workerToClose.kill('SIGTERM');
199
- }
200
- catch (error) {
201
- logger.debug('Failed to kill bare worker after channel close', { error });
202
- }
228
+ /** Starts the worker; aborting `signal` before it is ready kills the worker process. */
229
+ async function startWorker(source, timeout, signal) {
230
+ const stderr = stderrTail((text) => logger.debug(`[worker] ${text}`));
231
+ let ipc;
232
+ try {
233
+ ipc = await launchWorker(source, timeout, stderr.write, killOnAbort(signal));
203
234
  }
204
- if (serverToClose) {
205
- try {
206
- serverToClose.close();
207
- }
208
- catch (error) {
209
- logger.debug('Failed to close IPC server after channel close', { error });
210
- }
235
+ catch (error) {
236
+ throw workerStartupFailed(error, stderr.read());
211
237
  }
212
- bestEffortRemoveSocket(socketPathToClose);
213
- controller.abort(new WorkerCrashedError(null, null));
238
+ ipc.on('error', (error) => workerErrors.set(ipc, error));
239
+ return ipc;
214
240
  }
215
- function getWorkerStderr(proc) {
216
- return proc.stderr ?? null;
241
+ function watchWorker(ipc, controller) {
242
+ let exitCode;
243
+ ipc.on('exit', (code) => {
244
+ exitCode = code;
245
+ });
246
+ ipc.on('close', () => {
247
+ if (controller.signal.aborted)
248
+ return;
249
+ logger.info(`๐Ÿชฆ Bare worker ${exitCode === undefined ? 'closed' : 'exited'} unexpectedly`);
250
+ if (workerLifeController === controller)
251
+ resetModuleState();
252
+ controller.abort(workerCrashed(workerErrors.get(ipc) ?? { exitCode }));
253
+ });
217
254
  }
218
- // `bare-runtime` resolves its platform binary with
219
- // `require('bare-runtime-<platform>-<arch>')` and throws a terse
220
- // `No binaries found for target '<platform>-<arch>'` whenever that package โ€”
221
- // or one of its nested deps โ€” is absent. Under pnpm that happens even on a
222
- // supported platform, so surface an actionable error instead of the raw throw.
223
- function mapBareSpawnError(error) {
224
- const message = error instanceof Error ? error.message : String(error);
225
- if (/No binar(?:y|ies) found for target/i.test(message)) {
226
- return new BareRuntimeBinaryNotFoundError(process.platform, process.arch, error);
227
- }
228
- return error instanceof Error ? error : new Error(message);
255
+ /** Stops `ipc` in the background; a start that follows waits for it. */
256
+ function stopInBackground(ipc) {
257
+ const stopping = ipc
258
+ .terminate()
259
+ .then(() => { }, () => { })
260
+ .finally(() => {
261
+ if (closePromise === stopping)
262
+ closePromise = null;
263
+ });
264
+ closePromise = stopping;
229
265
  }
230
- // `spawn` carries this listener's own captured resources. Module-level
231
- // state may belong to a newer ensureRPC() by the time we fire.
232
- function handlePostHandshakeExit(code, exitSignal, spawn) {
233
- if (spawn.controller.signal.aborted) {
234
- // close() already handled teardown.
235
- logger.debug(`Bare worker exited after planned shutdown (code=${code}, signal=${exitSignal})`);
236
- return;
237
- }
238
- logger.info(`๐Ÿชฆ Bare worker exited post-handshake (code=${code}, signal=${exitSignal})`);
239
- // Only clear module state if we're still the active spawn.
240
- if (workerLifeController === spawn.controller) {
241
- resetModuleState();
242
- }
243
- try {
244
- spawn.server.close();
245
- }
246
- catch (err) {
247
- logger.debug('Failed to close IPC server after worker crash', { err });
248
- }
249
- spawn.controller.abort(new WorkerCrashedError(code, exitSignal));
250
- bestEffortRemoveSocket(spawn.socketPath);
266
+ function resetModuleState() {
267
+ rpcInstance = null;
268
+ rpcPromise = null;
269
+ worker = null;
270
+ workerLifeController = null;
251
271
  }
252
- function closeSyncForExit() {
253
- // Abort before kill so the exit handler sees planned intent.
254
- workerLifeController?.abort(new WorkerShutdownError());
255
- const { workerToClose, serverToClose, socketPathToClose } = snapshotAndResetState();
256
- if (workerToClose) {
272
+ async function ensureRPC() {
273
+ if (rpcInstance)
274
+ return rpcInstance;
275
+ if (rpcPromise)
276
+ return rpcPromise;
277
+ if (closePromise) {
278
+ await closePromise;
279
+ return ensureRPC();
280
+ }
281
+ const startGeneration = generation;
282
+ const attempt = (async () => {
283
+ const preloaded = await readConfigBeforeStart();
284
+ if (startGeneration !== generation)
285
+ throw new WorkerShutdownError();
286
+ const timeout = preloaded?.config?.rpcInitTimeoutMs ?? DEFAULT_WORKER_START_TIMEOUT_MS;
287
+ const launchedAt = Date.now();
288
+ const launch = new AbortController();
289
+ launchController = launch;
290
+ let started;
257
291
  try {
258
- workerToClose.kill('SIGTERM');
292
+ started = await startWorker(resolveWorkerSource(), timeout, launch.signal);
259
293
  }
260
294
  catch (error) {
261
- logger.debug('Failed to kill bare worker during process exit', { error });
295
+ if (startGeneration !== generation)
296
+ throw new WorkerShutdownError(error);
297
+ throw error;
262
298
  }
263
- }
264
- if (serverToClose) {
299
+ finally {
300
+ if (launchController === launch)
301
+ launchController = null;
302
+ }
303
+ if (startGeneration !== generation) {
304
+ await started.terminate();
305
+ throw new WorkerShutdownError();
306
+ }
307
+ const controller = new AbortController();
308
+ worker = started;
309
+ workerLifeController = controller;
310
+ watchWorker(started, controller);
311
+ const rpc = new RPC(started, () => { });
312
+ const runtimeContext = {
313
+ runtime: 'node',
314
+ platform: process.platform
315
+ };
316
+ // Snap's HOME can be revision-scoped; SNAP_USER_COMMON is stable.
317
+ const homeDir = process.env['SNAP_USER_COMMON'] ?? os.homedir();
318
+ const deadline = startDeadline(timeout - (Date.now() - launchedAt));
265
319
  try {
266
- serverToClose.close();
320
+ await Promise.race([
321
+ initializeConfig(rpc, preloaded ? async () => preloaded.config : resolveConfig, runtimeContext, homeDir),
322
+ rejectOnAbort(controller.signal),
323
+ deadline.expired
324
+ ]);
267
325
  }
268
- catch (error) {
269
- logger.debug('Failed to close IPC server during process exit', { error });
326
+ finally {
327
+ deadline.clear();
270
328
  }
271
- }
272
- bestEffortRemoveSocket(socketPathToClose);
273
- }
274
- /** Distinguishes "config file failed to load" from "no config file present". */
275
- const CONFIG_UNRESOLVED = Symbol('config-unresolved');
276
- /**
277
- * The handshake timeout has to be known before the worker is spawned, but the
278
- * config file is normally read after it (init-hooks). Read it early and hand
279
- * the same object to init-hooks so the file is not parsed twice.
280
- *
281
- * A config that fails to load is swallowed here. init-hooks re-runs the
282
- * resolver post-handshake, so the config error surfaces there rather than as a
283
- * spawn failure.
284
- */
285
- async function preresolveConfig() {
329
+ if (startGeneration !== generation)
330
+ throw new WorkerShutdownError();
331
+ if (controller.signal.aborted)
332
+ throw controller.signal.reason;
333
+ rpcInstance = rpc;
334
+ return rpc;
335
+ })();
336
+ rpcPromise = attempt;
286
337
  try {
287
- return await resolveConfig();
338
+ return await attempt;
288
339
  }
289
340
  catch (error) {
290
- logger.debug('Config preload for the RPC init timeout failed; using the default', { error });
291
- return CONFIG_UNRESOLVED;
341
+ if (startGeneration === generation) {
342
+ const failed = worker;
343
+ const failedController = workerLifeController;
344
+ resetModuleState();
345
+ failedController?.abort(error);
346
+ if (failed)
347
+ stopInBackground(failed);
348
+ }
349
+ throw error;
292
350
  }
293
351
  }
294
- async function ensureRPC() {
295
- if (rpcInstance)
296
- return rpcInstance;
297
- if (rpcPromise)
298
- return rpcPromise;
299
- if (closePromise) {
300
- await closePromise;
301
- }
302
- const preresolved = await preresolveConfig();
303
- const initTimeoutMs = resolveRPCInitTimeoutMs({
304
- envValue: process.env[RPC_INIT_TIMEOUT_ENV_VAR],
305
- configValue: preresolved === CONFIG_UNRESOLVED ? undefined : (preresolved?.rpcInitTimeoutMs ?? undefined),
306
- onInvalidEnvValue: (value) => logger.warn(`Ignoring invalid ${RPC_INIT_TIMEOUT_ENV_VAR}=${value}; expected a positive integer of milliseconds`)
307
- });
308
- const socketPath = createIPCSocketPath();
309
- currentSocketPath = socketPath;
310
- // Allocated here so the init race and exit handler share one controller.
311
- const spawnController = new AbortController();
312
- workerLifeController = spawnController;
313
- rpcPromise = new Promise((resolve, reject) => {
314
- let settled = false;
315
- let workerStderrTail = '';
316
- let workerExitBeforeHandshake = null;
317
- const timer = setTimeout(() => {
318
- if (settled)
319
- return;
320
- settled = true;
321
- const cause = createRPCInitTimeoutCause(workerStderrTail, workerExitBeforeHandshake);
322
- teardownFailedInit();
323
- reject(new RPCInitTimeoutError(initTimeoutMs, cause));
324
- }, initTimeoutMs);
325
- ipcServer = createServer((socket) => {
326
- if (settled)
327
- return;
328
- settled = true;
329
- clearTimeout(timer);
330
- rpcInstance = new RPC(socket, () => { });
331
- resolve(rpcInstance);
332
- });
333
- ipcServer.on('error', (error) => {
334
- if (settled)
335
- return;
336
- settled = true;
337
- clearTimeout(timer);
338
- teardownFailedInit();
339
- reject(error);
340
- });
341
- ipcServer.listen(socketPath, () => {
342
- const spawnResources = {
343
- controller: spawnController,
344
- server: ipcServer,
345
- socketPath
346
- };
347
- try {
348
- bareWorkerProc = spawn('bare', {
349
- args: [
350
- WORKER_PATH,
351
- JSON.stringify({
352
- QVAC_IPC_SOCKET_PATH: socketPath,
353
- // Snap's HOME can be revision-scoped; SNAP_USER_COMMON is stable.
354
- HOME_DIR: process.env['SNAP_USER_COMMON']
355
- ? String(process.env['SNAP_USER_COMMON'])
356
- : os.homedir()
357
- })
358
- ],
359
- platform: process.platform,
360
- arch: process.arch,
361
- stdio: ['inherit', 'inherit', 'pipe']
362
- });
363
- }
364
- catch (error) {
365
- // `spawn` resolves the bare binary synchronously and can throw before
366
- // the worker exists, so there is no process to emit "exit". Without
367
- // this, the throw escapes the `listen` callback as an uncaught
368
- // exception and crashes the host process.
369
- if (settled)
370
- return;
371
- settled = true;
372
- clearTimeout(timer);
373
- teardownFailedInit();
374
- reject(mapBareSpawnError(error));
375
- return;
376
- }
377
- if (bareWorkerProc) {
378
- getWorkerStderr(bareWorkerProc)?.on('data', (chunk) => {
379
- const text = chunk.toString();
380
- workerStderrTail = appendWorkerStderrTail(workerStderrTail, text);
381
- for (const line of text.split('\n')) {
382
- if (line.trim())
383
- workerLogger.debug(line);
384
- }
385
- });
386
- bareWorkerProc.on('exit', (code, exitSignal) => {
387
- if (settled) {
388
- handlePostHandshakeExit(code, exitSignal, spawnResources);
389
- return;
390
- }
391
- // Keep waiting for "close" so piped stderr can drain, but retain the
392
- // exit status in case a slow stream (for example, a core dump) lets
393
- // the initialization timer win that race.
394
- workerExitBeforeHandshake = { code, signal: exitSignal };
395
- });
396
- bareWorkerProc.on('close', (...args) => {
397
- if (settled)
398
- return;
399
- const code = typeof args[0] === 'number' ? args[0] : null;
400
- const exitSignal = typeof args[1] === 'string' ? args[1] : null;
401
- // Worker died before handshake. Use close, not exit, so piped
402
- // stderr has drained before we build the error cause.
403
- settled = true;
404
- clearTimeout(timer);
405
- teardownFailedInit();
406
- reject(new RPCInitTimeoutError(initTimeoutMs, createRPCInitTimeoutCause(workerStderrTail, { code, signal: exitSignal })));
407
- });
408
- }
409
- });
410
- });
411
- const rpc = await rpcPromise;
412
- const runtimeContext = {
413
- runtime: 'node',
414
- platform: process.platform
415
- };
416
- // init-hooks calls bare-rpc directly, bypassing rpc-client's race.
417
- const resolveConfigForInit = preresolved === CONFIG_UNRESOLVED ? resolveConfig : async () => preresolved;
418
- await Promise.race([
419
- initializeConfig(rpc, resolveConfigForInit, runtimeContext),
420
- rejectOnAbort(spawnController.signal)
421
- ]);
422
- return rpc;
352
+ export function getWorkerLifeSignal() {
353
+ return workerLifeController?.signal ?? null;
423
354
  }
424
- function rejectOnAbort(signal) {
425
- return new Promise((_, reject) => {
426
- const fail = () => reject(signal.reason instanceof Error ? signal.reason : new WorkerCrashedError(null, null));
427
- if (signal.aborted) {
428
- fail();
429
- return;
430
- }
431
- signal.addEventListener('abort', fail, { once: true });
432
- });
355
+ // Called by the RPC layer when it sees the channel close under an in-flight
356
+ // call before the worker's `close` event arrives. Tears down now, so the next
357
+ // call starts a new worker. A no-op once the life signal has aborted.
358
+ export function notifyChannelClosed() {
359
+ const controller = workerLifeController;
360
+ if (!controller || controller.signal.aborted)
361
+ return;
362
+ const closed = worker;
363
+ resetModuleState();
364
+ controller.abort(workerCrashed(closed ? workerErrors.get(closed) : undefined));
365
+ if (closed)
366
+ stopInBackground(closed);
433
367
  }
434
368
  export async function getRPC() {
435
369
  return ensureRPC();
@@ -439,24 +373,21 @@ export async function createDuplexSession(payload, commandId) {
439
373
  const req = rpc.request(commandId);
440
374
  const requestStream = req.createRequestStream();
441
375
  const responseStream = req.createResponseStream({ encoding: 'utf-8' });
376
+ // bare-rpc cancels the request when the response stream closes first, which
377
+ // destroys this stream with CANCELLED. Consumers read errors from the
378
+ // response stream, so pass the error there instead of throwing it uncaught.
379
+ requestStream.on('error', (error) => responseStream.destroy(error));
442
380
  requestStream.write(payload, 'utf-8');
443
381
  // Destroy on worker death so consumers' for-await throws instead of hangs.
444
382
  const lifeSignal = workerLifeController?.signal;
445
383
  if (lifeSignal && !lifeSignal.aborted) {
446
384
  const onAbort = () => {
447
385
  const err = lifeSignal.reason instanceof Error ? lifeSignal.reason : new WorkerCrashedError(null, null);
448
- try {
449
- ;
450
- requestStream.destroy?.(err);
451
- }
452
- catch { }
453
- try {
454
- ;
455
- responseStream.destroy?.(err);
456
- }
457
- catch { }
386
+ requestStream.destroy(err);
387
+ responseStream.destroy(err);
458
388
  };
459
389
  lifeSignal.addEventListener('abort', onAbort, { once: true });
390
+ responseStream.once('close', () => lifeSignal.removeEventListener('abort', onAbort));
460
391
  }
461
392
  return { requestStream, responseStream };
462
393
  }
@@ -465,36 +396,23 @@ export async function close() {
465
396
  await closePromise;
466
397
  return;
467
398
  }
468
- if (!rpcInstance && !rpcPromise && !bareWorkerProc && !ipcServer)
469
- return;
470
- logger.info('๐Ÿงน Closing RPC client');
471
- // Abort before kill: exit handler sees planned intent; any in-flight
472
- // caller (contract violators) rejects with WorkerShutdownError.
473
- workerLifeController?.abort(new WorkerShutdownError());
474
- const { workerToClose, serverToClose, socketPathToClose } = snapshotAndResetState();
399
+ generation++;
475
400
  closePromise = (async () => {
476
- if (workerToClose) {
477
- logger.info('๐Ÿป๐Ÿ”ซ Killing bare worker process');
478
- try {
479
- workerToClose.kill('SIGTERM');
480
- }
481
- catch (error) {
482
- logger.debug('Failed to kill bare worker process', { error });
483
- }
484
- }
485
- if (serverToClose) {
486
- logger.info('๐Ÿ”Œ Closing IPC server');
487
- await new Promise((resolve) => {
488
- try {
489
- serverToClose.close(() => resolve());
490
- }
491
- catch (error) {
492
- logger.debug('Failed to close IPC server', { error });
493
- resolve();
494
- }
495
- });
401
+ const closing = worker;
402
+ if (!closing) {
403
+ const pending = rpcPromise;
404
+ rpcPromise = null;
405
+ launchController?.abort();
406
+ launchController = null;
407
+ await pending?.catch(() => { });
408
+ return;
496
409
  }
497
- bestEffortRemoveSocket(socketPathToClose);
410
+ logger.info('๐Ÿงน Closing RPC client');
411
+ // Abort before terminating: the close handler sees planned intent, and any
412
+ // in-flight caller rejects with WorkerShutdownError.
413
+ workerLifeController?.abort(new WorkerShutdownError());
414
+ resetModuleState();
415
+ await closing.terminate();
498
416
  })();
499
417
  try {
500
418
  await closePromise;
@@ -503,12 +421,3 @@ export async function close() {
503
421
  closePromise = null;
504
422
  }
505
423
  }
506
- function handleTerminationSignal(signal) {
507
- logger.info(`Received ${signal}, closing RPC resources...`);
508
- closeSyncForExit();
509
- process.kill(process.pid, signal);
510
- }
511
- process.once('SIGINT', () => handleTerminationSignal('SIGINT'));
512
- process.once('SIGTERM', () => handleTerminationSignal('SIGTERM'));
513
- process.once('SIGHUP', () => handleTerminationSignal('SIGHUP'));
514
- process.once('exit', closeSyncForExit);