@gmickel/gno 2.15.0 → 2.17.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 (218) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/SKILL.md +27 -0
  3. package/assets/skill/cli-reference.md +24 -15
  4. package/assets/spa-production.json.gz +0 -0
  5. package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.17.0.zip} +0 -0
  6. package/browser-extension/artifacts/gno-browser-clipper-v2.17.0.zip.sha256 +1 -0
  7. package/browser-extension/dist/manifest.json +1 -1
  8. package/package.json +1 -1
  9. package/spec/cli.md +43 -3
  10. package/spec/db/schema.sql +53 -1
  11. package/spec/mcp.md +9 -3
  12. package/spec/output-schemas/doctor.schema.json +27 -0
  13. package/spec/output-schemas/retrieval-trace-payloads.schema.json +14 -0
  14. package/spec/output-schemas/search-results.schema.json +14 -0
  15. package/spec/output-schemas/status.schema.json +22 -0
  16. package/src/cli/commands/agents/commands.ts +1 -1
  17. package/src/cli/commands/ask.ts +1 -1
  18. package/src/cli/commands/context-build.ts +1 -1
  19. package/src/cli/commands/doctor.ts +101 -29
  20. package/src/cli/commands/embed.ts +2 -2
  21. package/src/cli/commands/links.ts +30 -6
  22. package/src/cli/commands/mcp/install.ts +2 -2
  23. package/src/cli/commands/mcp/status.ts +1 -1
  24. package/src/cli/commands/mcp/uninstall.ts +1 -1
  25. package/src/cli/commands/query.ts +1 -1
  26. package/src/cli/commands/shared.ts +4 -4
  27. package/src/cli/commands/skill/install.ts +1 -1
  28. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  29. package/src/cli/commands/skill/uninstall.ts +1 -1
  30. package/src/cli/commands/status.ts +75 -58
  31. package/src/cli/commands/vec.ts +180 -8
  32. package/src/cli/config-cache.ts +86 -0
  33. package/src/cli/globals.ts +64 -0
  34. package/src/cli/program.ts +63 -36
  35. package/src/cli/run.ts +121 -67
  36. package/src/cli/runtime-health.ts +132 -122
  37. package/src/cli/session-binding.ts +11 -2
  38. package/src/config/saver.ts +8 -0
  39. package/src/config/types.ts +6 -0
  40. package/src/converters/adapters/browser-export/formats.ts +25 -15
  41. package/src/converters/adapters/email/adapter.ts +37 -53
  42. package/src/converters/adapters/email/html.ts +37 -20
  43. package/src/converters/adapters/email/mime.ts +71 -39
  44. package/src/converters/adapters/ical/adapter.ts +20 -12
  45. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  46. package/src/converters/adapters/shared/html-text.ts +55 -37
  47. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  48. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  49. package/src/converters/adapters/transcript/adapter.ts +12 -7
  50. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  51. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  52. package/src/converters/canonicalize.ts +17 -3
  53. package/src/converters/native/markdown.ts +24 -17
  54. package/src/converters/native/plaintext.ts +5 -6
  55. package/src/converters/registry.ts +130 -8
  56. package/src/core/activation-status.ts +4 -8
  57. package/src/core/change-diff.ts +38 -11
  58. package/src/core/context-compiler.ts +17 -18
  59. package/src/core/context-evidence.ts +116 -25
  60. package/src/core/context-verifier.ts +70 -31
  61. package/src/core/file-lock.ts +10 -2
  62. package/src/core/graph-analysis.ts +3 -3
  63. package/src/core/link-inventory-markdown.ts +2 -2
  64. package/src/core/links.ts +20 -87
  65. package/src/core/memory-fence.ts +16 -9
  66. package/src/core/memory-recall.ts +168 -34
  67. package/src/core/path-rules.ts +143 -0
  68. package/src/core/retrieval-trace-session.ts +3 -0
  69. package/src/core/retrieval-trace.ts +9 -0
  70. package/src/core/section-parse.ts +16 -6
  71. package/src/core/typed-metadata.ts +68 -0
  72. package/src/core/vector-partition-status.ts +13 -0
  73. package/src/core/wiki-link-syntax.ts +88 -0
  74. package/src/embed/backlog.ts +142 -60
  75. package/src/embed/retry.ts +39 -33
  76. package/src/embed/variant-backlog.ts +582 -116
  77. package/src/embed/variant-retry.ts +157 -48
  78. package/src/index.ts +3 -3
  79. package/src/ingestion/budget-error-codes.ts +13 -0
  80. package/src/ingestion/chunker.ts +60 -49
  81. package/src/ingestion/compiled-context.ts +4 -5
  82. package/src/ingestion/convert-file.ts +1 -1
  83. package/src/ingestion/document-metadata.ts +16 -9
  84. package/src/ingestion/excluded-ranges.ts +97 -0
  85. package/src/ingestion/file-processor.ts +122 -37
  86. package/src/ingestion/frontmatter.ts +35 -7
  87. package/src/ingestion/graph-reconciliation.ts +187 -51
  88. package/src/ingestion/language.ts +66 -61
  89. package/src/ingestion/position.ts +5 -5
  90. package/src/ingestion/prepare-file.ts +50 -29
  91. package/src/ingestion/record-adapter-canonical.ts +37 -26
  92. package/src/ingestion/record-adapter.ts +46 -26
  93. package/src/ingestion/record-container.ts +121 -53
  94. package/src/ingestion/record-path.ts +5 -2
  95. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  96. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  97. package/src/ingestion/source-availability/readers.ts +51 -0
  98. package/src/ingestion/strip.ts +39 -105
  99. package/src/ingestion/sync.ts +692 -386
  100. package/src/ingestion/typed-metadata.ts +10 -4
  101. package/src/ingestion/walker.ts +485 -158
  102. package/src/llm/cache.ts +128 -84
  103. package/src/llm/http-inference.ts +112 -35
  104. package/src/llm/http-policy.ts +101 -0
  105. package/src/llm/httpEmbedding.ts +8 -1
  106. package/src/llm/httpGeneration.ts +5 -1
  107. package/src/llm/httpRerank.ts +5 -1
  108. package/src/llm/inference-scope.ts +15 -2
  109. package/src/llm/lazy-ports.ts +33 -3
  110. package/src/llm/lockfile.ts +34 -7
  111. package/src/llm/model-cleanup.ts +24 -0
  112. package/src/llm/native-worker/client.ts +23 -12
  113. package/src/llm/native-worker/dispatcher.ts +19 -9
  114. package/src/llm/native-worker/embedding-identity.ts +42 -16
  115. package/src/llm/native-worker/entry.ts +2 -1
  116. package/src/llm/native-worker/owner.ts +1 -0
  117. package/src/llm/native-worker/ports.ts +86 -23
  118. package/src/llm/native-worker/protocol.ts +386 -55
  119. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  120. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  121. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  122. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  123. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  124. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  125. package/src/llm/types.ts +14 -0
  126. package/src/mcp/context.ts +342 -23
  127. package/src/mcp/http-transport.ts +21 -3
  128. package/src/mcp/tool-profile-types.ts +62 -0
  129. package/src/mcp/tool-profile.ts +32 -56
  130. package/src/mcp/tools/context.ts +5 -1
  131. package/src/mcp/tools/index.ts +269 -191
  132. package/src/mcp/tools/links.ts +14 -6
  133. package/src/mcp/tools/query.ts +60 -37
  134. package/src/mcp/tools/vsearch.ts +25 -14
  135. package/src/pipeline/answer.ts +133 -40
  136. package/src/pipeline/claim-verification.ts +293 -189
  137. package/src/pipeline/claim-verifier.ts +6 -7
  138. package/src/pipeline/egress-lineage.ts +37 -26
  139. package/src/pipeline/exclude.ts +34 -11
  140. package/src/pipeline/expansion.ts +233 -19
  141. package/src/pipeline/explain.ts +17 -2
  142. package/src/pipeline/filters.ts +169 -33
  143. package/src/pipeline/graph-retrieval.ts +117 -61
  144. package/src/pipeline/hybrid.ts +626 -330
  145. package/src/pipeline/hydration.ts +86 -24
  146. package/src/pipeline/intent.ts +15 -7
  147. package/src/pipeline/owner-fusion.ts +61 -19
  148. package/src/pipeline/query-language.ts +15 -2
  149. package/src/pipeline/rerank.ts +15 -22
  150. package/src/pipeline/search.ts +193 -72
  151. package/src/pipeline/snippet.ts +15 -2
  152. package/src/pipeline/temporal.ts +51 -10
  153. package/src/pipeline/types.ts +7 -0
  154. package/src/pipeline/vsearch.ts +269 -154
  155. package/src/publish/attachment-raster.ts +2 -16
  156. package/src/publish/encrypted-export.ts +15 -5
  157. package/src/serve/browse-tree.ts +50 -42
  158. package/src/serve/connectors.ts +2 -1
  159. package/src/serve/context.ts +13 -4
  160. package/src/serve/doc-events.ts +3 -0
  161. package/src/serve/public/app.tsx +49 -21
  162. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  163. package/src/serve/public/components/CaptureModal.tsx +14 -10
  164. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  165. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  166. package/src/serve/public/globals.built.css +1 -1
  167. package/src/serve/public/globals.css +19 -0
  168. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  169. package/src/serve/public/lib/metadata-filter.ts +234 -9
  170. package/src/serve/public/pages/Browse.tsx +61 -27
  171. package/src/serve/public/pages/DocView.tsx +44 -25
  172. package/src/serve/public/pages/GraphView.tsx +8 -3
  173. package/src/serve/resident-runtime.ts +199 -48
  174. package/src/serve/routes/api.ts +98 -67
  175. package/src/serve/routes/links.ts +25 -5
  176. package/src/serve/server.ts +1370 -1180
  177. package/src/serve/spa-bundle-source.ts +52 -27
  178. package/src/serve/status.ts +101 -52
  179. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  180. package/src/serve/watch-reconciliation-shared.ts +42 -4
  181. package/src/serve/watch-reconciliation.ts +21 -8
  182. package/src/serve/watch-service-events.ts +7 -1
  183. package/src/serve/watch-service-hosts.ts +3 -1
  184. package/src/serve/watch-service.ts +46 -21
  185. package/src/serve/watch-snapshot-scan.ts +6 -15
  186. package/src/sessions/archive.ts +20 -8
  187. package/src/sessions/sanitize.ts +38 -18
  188. package/src/sessions/service.ts +180 -102
  189. package/src/store/migrations/037-performance-indexes.ts +56 -0
  190. package/src/store/migrations/038-vector-mirror-null-cosine.ts +47 -0
  191. package/src/store/migrations/039-vector-mirror-v2.ts +94 -0
  192. package/src/store/migrations/index.ts +6 -0
  193. package/src/store/sqlite/adapter.ts +1260 -651
  194. package/src/store/sqlite/chunking-policy.ts +15 -1
  195. package/src/store/sqlite/eligibility.ts +110 -70
  196. package/src/store/sqlite/graph-neighbors.ts +71 -46
  197. package/src/store/sqlite/graph-reference-state.ts +27 -3
  198. package/src/store/sqlite/graph-similarity.ts +59 -12
  199. package/src/store/sqlite/metadata-predicate.ts +123 -28
  200. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  201. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  202. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  203. package/src/store/types.ts +32 -0
  204. package/src/store/vector/coarse-router.ts +312 -0
  205. package/src/store/vector/eligibility.ts +39 -0
  206. package/src/store/vector/lazy.ts +17 -0
  207. package/src/store/vector/partition-index.ts +333 -59
  208. package/src/store/vector/proof-cache.ts +209 -0
  209. package/src/store/vector/runtime-compat.ts +6 -0
  210. package/src/store/vector/sqlite-vec.ts +270 -162
  211. package/src/store/vector/stats.ts +37 -73
  212. package/src/store/vector/status.ts +169 -53
  213. package/src/store/vector/stored-vectors.ts +131 -45
  214. package/src/store/vector/types.ts +19 -0
  215. package/src/store/vector/v2-mirror.ts +669 -0
  216. package/src/store/vector/variant-search.ts +1187 -111
  217. package/src/store/vector/variants.ts +964 -160
  218. package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
@@ -59,8 +59,21 @@ export function inferenceOptions(
59
59
  };
60
60
  }
61
61
 
62
- export function assertInferenceActive(options: InferenceOptions = {}): void {
63
- if (scope.getStore()?.failure) throw scope.getStore()!.failure;
62
+ export function assertInferenceActive(options?: InferenceOptions): void {
63
+ const currentScope = scope.getStore();
64
+ if (options === undefined) {
65
+ if (currentScope === undefined) return;
66
+ if (currentScope.failure) throw currentScope.failure;
67
+ if (currentScope.signal?.aborted)
68
+ throw new DOMException("Inference cancelled", "AbortError");
69
+ if (
70
+ currentScope.deadlineAt !== undefined &&
71
+ Date.now() >= currentScope.deadlineAt
72
+ )
73
+ throw new DOMException("Inference deadline exceeded", "TimeoutError");
74
+ return;
75
+ }
76
+ if (currentScope?.failure) throw currentScope.failure;
64
77
  const current = inferenceOptions(options);
65
78
  if (current.signal?.aborted)
66
79
  throw new DOMException("Inference cancelled", "AbortError");
@@ -1,6 +1,7 @@
1
1
  /** Defer model resolution/download until an actual inference operation. */
2
2
  import type {
3
3
  EmbeddingPort,
4
+ GenerationModelIdentity,
4
5
  GenerationPort,
5
6
  LlmResult,
6
7
  RerankPort,
@@ -82,18 +83,47 @@ export function lazyEmbeddingPort(
82
83
  };
83
84
  }
84
85
 
86
+ export interface LazyGenerationPortOptions {
87
+ /** Read-only identity probe used before the underlying port is initialized. */
88
+ resolveModelIdentity?: () => Promise<GenerationModelIdentity | null>;
89
+ }
90
+
85
91
  export function lazyGenerationPort(
86
92
  modelUri: string,
87
- create: () => Promise<LlmResult<GenerationPort>>
93
+ create: () => Promise<LlmResult<GenerationPort>>,
94
+ options?: LazyGenerationPortOptions
88
95
  ): GenerationPort {
89
96
  const owner = lazyOwner(modelUri, create);
90
97
  return {
91
98
  modelUri,
99
+ get modelPath() {
100
+ return owner.peek()?.modelPath;
101
+ },
102
+ get modelFingerprint() {
103
+ return owner.peek()?.modelFingerprint;
104
+ },
105
+ async resolveModelIdentity() {
106
+ const existing = owner.peek();
107
+ if (existing) {
108
+ return existing.modelPath || existing.modelFingerprint
109
+ ? {
110
+ modelPath: existing.modelPath,
111
+ modelFingerprint: existing.modelFingerprint,
112
+ }
113
+ : null;
114
+ }
115
+ if (!options?.resolveModelIdentity) return null;
116
+ try {
117
+ return await options.resolveModelIdentity();
118
+ } catch {
119
+ return null;
120
+ }
121
+ },
92
122
  // These are the fixed native/HTTP adapter contracts; no probing required.
93
123
  structuredOutput: isHttpGenUri(modelUri) ? "none" : "json_schema",
94
- async generate(prompt, params) {
124
+ async generate(prompt, params, genOptions) {
95
125
  const port = await owner.get();
96
- return port.ok ? port.value.generate(prompt, params) : port;
126
+ return port.ok ? port.value.generate(prompt, params, genOptions) : port;
97
127
  },
98
128
  dispose: () => owner.dispose(),
99
129
  };
@@ -18,12 +18,32 @@ import { join } from "node:path";
18
18
  /** Default lock TTL in milliseconds (24 hours - long to avoid stealing during slow downloads) */
19
19
  const DEFAULT_LOCK_TTL_MS = 24 * 60 * 60 * 1000;
20
20
 
21
- /** Retry delay for lock acquisition (ms) */
21
+ /** Initial exponential backoff delay for lock acquisition (ms) */
22
+ const LOCK_INITIAL_RETRY_DELAY_MS = 15;
23
+
24
+ /** Max/capped retry delay for lock acquisition (ms) */
22
25
  const LOCK_RETRY_DELAY_MS = 500;
23
26
 
24
27
  /** Max retries before giving up (~10 minutes for multi-GB downloads) */
25
28
  const LOCK_MAX_RETRIES = 1200;
26
29
 
30
+ let cachedHostname: string | null = null;
31
+ let cachedUsername: string | null = null;
32
+
33
+ function getCachedHostname(): string {
34
+ if (cachedHostname === null) {
35
+ cachedHostname = hostname();
36
+ }
37
+ return cachedHostname;
38
+ }
39
+
40
+ function getCachedUsername(): string {
41
+ if (cachedUsername === null) {
42
+ cachedUsername = userInfo().username;
43
+ }
44
+ return cachedUsername;
45
+ }
46
+
27
47
  // ─────────────────────────────────────────────────────────────────────────────
28
48
  // Types
29
49
  // ─────────────────────────────────────────────────────────────────────────────
@@ -58,8 +78,8 @@ export interface LockOptions {
58
78
  function getLockMeta(): LockMeta {
59
79
  return {
60
80
  pid: process.pid,
61
- hostname: hostname(),
62
- user: userInfo().username,
81
+ hostname: getCachedHostname(),
82
+ user: getCachedUsername(),
63
83
  createdAt: new Date().toISOString(),
64
84
  };
65
85
  }
@@ -124,7 +144,7 @@ async function isLockStale(lockPath: string, ttlMs: number): Promise<boolean> {
124
144
  }
125
145
 
126
146
  const meta = await readLockMeta(lockPath);
127
- if (!meta || meta.hostname !== hostname()) {
147
+ if (!meta || meta.hostname !== getCachedHostname()) {
128
148
  return false;
129
149
  }
130
150
 
@@ -173,7 +193,7 @@ export async function acquireLock(
173
193
  ): Promise<LockHandle | null> {
174
194
  const ttlMs = options?.ttlMs ?? DEFAULT_LOCK_TTL_MS;
175
195
  const maxRetries = options?.maxRetries ?? LOCK_MAX_RETRIES;
176
- const retryDelayMs = options?.retryDelayMs ?? LOCK_RETRY_DELAY_MS;
196
+ const fixedRetryDelayMs = options?.retryDelayMs;
177
197
 
178
198
  let retries = 0;
179
199
 
@@ -210,9 +230,16 @@ export async function acquireLock(
210
230
  }
211
231
  }
212
232
 
213
- // Lock is held - wait and retry
233
+ // Lock is held - wait and retry with capped exponential backoff
234
+ // (15 ms -> 500 ms) unless caller specified an explicit fixed delay.
235
+ const delayMs =
236
+ fixedRetryDelayMs ??
237
+ Math.min(
238
+ LOCK_RETRY_DELAY_MS,
239
+ LOCK_INITIAL_RETRY_DELAY_MS * 2 ** Math.min(retries, 6)
240
+ );
214
241
  retries++;
215
- await sleep(retryDelayMs);
242
+ await sleep(delayMs);
216
243
  continue;
217
244
  }
218
245
 
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Zero-dependency shutdown hook for the lazy native ModelManager singleton.
3
+ * Allows CLI exit cleanup to avoid importing node-llama-cpp lifecycle code
4
+ * when no model manager was initialized during the command.
5
+ *
6
+ * @module src/llm/model-cleanup
7
+ */
8
+
9
+ type ModelManagerResetFn = () => Promise<void>;
10
+
11
+ let resetFn: ModelManagerResetFn | null = null;
12
+
13
+ /** Register the active ModelManager reset callback once a manager is created. */
14
+ export function registerModelManagerReset(fn: ModelManagerResetFn): void {
15
+ resetFn = fn;
16
+ }
17
+
18
+ /** Dispose any initialized ModelManager; no-op when models were never loaded. */
19
+ export async function resetLoadedModelManager(): Promise<void> {
20
+ if (!resetFn) {
21
+ return;
22
+ }
23
+ await resetFn();
24
+ }
@@ -22,7 +22,8 @@ import {
22
22
  recordCompletion,
23
23
  } from "./owner";
24
24
  import {
25
- frameNativeMessage,
25
+ encodeNativeMessage,
26
+ frameNativeBytes,
26
27
  NativeFrameDecoder,
27
28
  NativeRequestLedger,
28
29
  parseNativeRequest,
@@ -270,21 +271,25 @@ export class NativeWorkerClient {
270
271
  )
271
272
  throw new NativeWorkerError("stale_generation");
272
273
  const owner = this.owner ?? this.start();
274
+ const rawRequest = {
275
+ ...input,
276
+ deadlineAt: input.deadlineAt,
277
+ version: 1,
278
+ generation: owner.generation,
279
+ requestId: ++this.requestId,
280
+ };
281
+ const encodedBytes = encodeNativeMessage(rawRequest);
273
282
  const request = parseNativeRequest(
274
- {
275
- ...input,
276
- deadlineAt: input.deadlineAt,
277
- version: 1,
278
- generation: owner.generation,
279
- requestId: ++this.requestId,
280
- },
283
+ rawRequest,
281
284
  owner.generation,
282
- this.options.models
285
+ this.options.models,
286
+ encodedBytes.length
283
287
  );
284
- owner.ledger.admit(request);
288
+ owner.ledger.admit(request, encodedBytes.length);
285
289
  return new Promise((resolve) => {
286
290
  const pending: Pending = {
287
291
  request,
292
+ encodedBytes,
288
293
  resolve,
289
294
  settlement,
290
295
  background: isBackgroundInference(),
@@ -420,7 +425,10 @@ export class NativeWorkerClient {
420
425
  throw new NativeWorkerError("protocol");
421
426
  const decoded = owner.decoder.push(message);
422
427
  if (decoded === undefined) return;
423
- const response = owner.ledger.settle(decoded);
428
+ const response = owner.ledger.settle(
429
+ decoded,
430
+ owner.decoder.lastDecodedByteLength
431
+ );
424
432
  const pending = owner.pending[0];
425
433
  if (pending?.request.requestId !== response.requestId)
426
434
  throw new NativeWorkerError("protocol");
@@ -479,7 +487,10 @@ export class NativeWorkerClient {
479
487
  this.options.loadTimeout
480
488
  );
481
489
  try {
482
- for (const frame of frameNativeMessage(pending.request))
490
+ for (const frame of frameNativeBytes(
491
+ pending.request,
492
+ pending.encodedBytes
493
+ ))
483
494
  owner.child.send(frame);
484
495
  } catch {
485
496
  this.fail(owner, new NativeWorkerError("exited"));
@@ -48,24 +48,34 @@ export class NativeDispatcher {
48
48
  }
49
49
 
50
50
  private async port(model: ApprovedModel): Promise<Port> {
51
- if (
52
- (await realpath(model.path)) !== model.path ||
53
- !(await Bun.file(model.path).exists())
54
- ) {
51
+ let resolvedPath: string;
52
+ let identity: string;
53
+ try {
54
+ [resolvedPath, identity] = await Promise.all([
55
+ realpath(model.path),
56
+ fileIdentity(model.path),
57
+ ]);
58
+ } catch {
59
+ throw new NativeWorkerError("protocol");
60
+ }
61
+ if (resolvedPath !== model.path) {
55
62
  throw new NativeWorkerError("protocol");
56
63
  }
57
64
  const existing = this.ports.get(model.id);
58
65
  // ModelManager retains weights by URI after a port disposes its contexts.
59
66
  // Keep provenance at that same lifetime, not at the shorter port lifetime.
60
67
  const file = this.files.get(model.modelUri);
61
- const identity = await fileIdentity(model.path);
62
68
  if (file && (file.path !== model.path || file.identity !== identity))
63
69
  throw new NativeWorkerError("stale_generation");
64
70
  if (existing) return existing;
65
- const fingerprint =
66
- model.type === "embed"
67
- ? (file?.fingerprint ?? (await fingerprintModel(model.path)))
68
- : file?.fingerprint;
71
+ let fingerprint = file?.fingerprint;
72
+ if (model.type === "embed" && !fingerprint) {
73
+ // Overlap backend llama.cpp initialization with GGUF SHA-256 hashing;
74
+ // loadModel/port.init never starts until the post-hash identity check passes.
75
+ const llamaWarmup = this.manager.getLlama().catch(() => undefined);
76
+ fingerprint = await fingerprintModel(model.path);
77
+ await llamaWarmup;
78
+ }
69
79
  if (identity !== (await fileIdentity(model.path)))
70
80
  throw new NativeWorkerError("stale_generation");
71
81
  const Constructor =
@@ -1,31 +1,57 @@
1
- // Bun has no inode/ctime identity API. Check replacement during hashing/loading.
2
- import { stat } from "node:fs/promises";
1
+ // Bun has no sync readFileSync/fd-read or inode/ctime identity API.
2
+ import { readFileSync } from "node:fs";
3
+ import { open, stat } from "node:fs/promises";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const FINGERPRINT_BUFFER_BYTES = 4 * 1024 * 1024;
7
+ let cachedNativePackageVersion: string | null = null;
3
8
 
4
9
  /**
5
- * node-llama-cpp's version, part of the embedding runtime identity. A
6
- * standalone compiled executable ships no node-llama-cpp package (it cannot
7
- * run local inference), so the lookup must not stop it from loading.
10
+ * Lazily read node-llama-cpp's version from package.json on first use without
11
+ * top-level await or eager node-llama-cpp module evaluation. A standalone
12
+ * compiled executable ships no node-llama-cpp package, returning "unavailable".
8
13
  */
9
- const readNativePackage = async (): Promise<{ version: string }> => {
14
+ export function getNativePackageVersion(): string {
15
+ if (cachedNativePackageVersion !== null) {
16
+ return cachedNativePackageVersion;
17
+ }
10
18
  try {
11
- return (await Bun.file(
12
- new URL("../package.json", import.meta.resolve("node-llama-cpp"))
13
- ).json()) as { version: string };
19
+ const pkgUrl = new URL(
20
+ "../package.json",
21
+ import.meta.resolve("node-llama-cpp")
22
+ );
23
+ const parsed = JSON.parse(readFileSync(fileURLToPath(pkgUrl), "utf8")) as {
24
+ version?: unknown;
25
+ };
26
+ cachedNativePackageVersion =
27
+ typeof parsed.version === "string" && parsed.version.length > 0
28
+ ? parsed.version
29
+ : "unavailable";
14
30
  } catch {
15
- return { version: "unavailable" };
31
+ cachedNativePackageVersion = "unavailable";
16
32
  }
17
- };
18
- const nativePackage = await readNativePackage();
33
+ return cachedNativePackageVersion;
34
+ }
19
35
 
20
36
  export async function fileIdentity(path: string): Promise<string> {
21
37
  const info = await stat(path, { bigint: true });
22
38
  return [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(":");
23
39
  }
24
40
 
25
- /** Stream the actual child-approved artifact; never buffer a GGUF in parent RAM. */
41
+ /** Stream the actual child-approved artifact with a reusable 4 MB buffer; never buffer a GGUF in RAM. */
26
42
  export async function fingerprintModel(path: string): Promise<string> {
27
43
  const hash = new Bun.CryptoHasher("sha256");
28
- for await (const bytes of Bun.file(path).stream()) hash.update(bytes);
44
+ const fh = await open(path, "r");
45
+ const buf = new Uint8Array(FINGERPRINT_BUFFER_BYTES);
46
+ try {
47
+ for (;;) {
48
+ const { bytesRead } = await fh.read(buf, 0, buf.length, null);
49
+ if (bytesRead === 0) break;
50
+ hash.update(bytesRead === buf.length ? buf : buf.subarray(0, bytesRead));
51
+ }
52
+ } finally {
53
+ await fh.close();
54
+ }
29
55
  return hash.digest("hex");
30
56
  }
31
57
 
@@ -35,7 +61,7 @@ export function fingerprintRuntime(settings: Record<string, unknown>): string {
35
61
  JSON.stringify({
36
62
  policy: "native-embedding-v1",
37
63
  bun: Bun.version,
38
- nativeVersion: nativePackage.version,
64
+ nativeVersion: getNativePackageVersion(),
39
65
  platform: process.platform,
40
66
  arch: process.arch,
41
67
  ...settings,
@@ -66,7 +92,7 @@ export function runtimeCallerKey(
66
92
  JSON.stringify([
67
93
  model,
68
94
  Bun.version,
69
- nativePackage.version,
95
+ getNativePackageVersion(),
70
96
  process.platform,
71
97
  process.arch,
72
98
  RUNTIME_ENV.map((name) => env[name] ?? null),
@@ -133,7 +133,8 @@ process.on("message", (message: unknown) => {
133
133
  const request = parseNativeRequest(
134
134
  decoded,
135
135
  config.generation,
136
- config.models
136
+ config.models,
137
+ decoder.lastDecodedByteLength
137
138
  );
138
139
  const controller = new AbortController();
139
140
  activeRequest = { id: request.requestId, controller };
@@ -22,6 +22,7 @@ type Child = ReturnType<typeof Bun.spawn>;
22
22
  export interface Pending {
23
23
  background: boolean;
24
24
  request: NativeRequest;
25
+ encodedBytes: Uint8Array;
25
26
  settlement: InferenceSettlement<
26
27
  Extract<NativeResponse["result"], { ok: true }>["value"]
27
28
  >;
@@ -15,9 +15,13 @@ import type { NativeResponse } from "./protocol";
15
15
 
16
16
  import { inferenceOptions, finishInferenceCleanup } from "../inference-scope";
17
17
  import { NativeWorkerError } from "./errors";
18
- import { EmbeddingIdentitySchema } from "./protocol";
18
+ import {
19
+ EmbeddingIdentitySchema,
20
+ isPrevalidatedEmbedValue,
21
+ validateFiniteVector,
22
+ validateFiniteVectorBatch,
23
+ } from "./protocol";
19
24
 
20
- const vector = z.array(z.number().finite()).min(1);
21
25
  const scores = z.array(
22
26
  z.strictObject({
23
27
  index: z.number().int().nonnegative(),
@@ -41,11 +45,69 @@ function decode<T>(
41
45
  : { ok: false, error: new NativeWorkerError("protocol").detail };
42
46
  }
43
47
 
48
+ function decodeVector(
49
+ result: NativeResponse["result"],
50
+ expectedDims?: number
51
+ ): LlmResult<number[]> {
52
+ if (!result.ok) return result;
53
+ if (isPrevalidatedEmbedValue(result.value) && Array.isArray(result.value)) {
54
+ const vec = result.value as number[];
55
+ if (expectedDims !== undefined && vec.length !== expectedDims) {
56
+ return { ok: false, error: new NativeWorkerError("protocol").detail };
57
+ }
58
+ return { ok: true, value: vec };
59
+ }
60
+ try {
61
+ return {
62
+ ok: true,
63
+ value: validateFiniteVector(result.value, expectedDims),
64
+ };
65
+ } catch {
66
+ return { ok: false, error: new NativeWorkerError("protocol").detail };
67
+ }
68
+ }
69
+
70
+ function decodeVectorBatch(
71
+ result: NativeResponse["result"],
72
+ expectedCount: number,
73
+ expectedDims?: number
74
+ ): LlmResult<number[][]> {
75
+ if (!result.ok) return result;
76
+ if (isPrevalidatedEmbedValue(result.value) && Array.isArray(result.value)) {
77
+ const batch = result.value as number[][];
78
+ if (batch.length !== expectedCount) {
79
+ return { ok: false, error: new NativeWorkerError("protocol").detail };
80
+ }
81
+ if (
82
+ expectedDims !== undefined &&
83
+ batch.length > 0 &&
84
+ batch[0]!.length !== expectedDims
85
+ ) {
86
+ return { ok: false, error: new NativeWorkerError("protocol").detail };
87
+ }
88
+ return { ok: true, value: batch };
89
+ }
90
+ try {
91
+ return {
92
+ ok: true,
93
+ value: validateFiniteVectorBatch(
94
+ result.value,
95
+ expectedCount,
96
+ expectedDims
97
+ ),
98
+ };
99
+ } catch {
100
+ return { ok: false, error: new NativeWorkerError("protocol").detail };
101
+ }
102
+ }
103
+
44
104
  class NativePort {
45
105
  constructor(
46
106
  protected readonly client: NativeWorkerClient,
47
107
  protected readonly modelId: string,
48
- readonly modelUri: string
108
+ readonly modelUri: string,
109
+ readonly modelPath?: string,
110
+ readonly modelFingerprint?: string
49
111
  ) {}
50
112
 
51
113
  async dispose(): Promise<void> {
@@ -137,8 +199,13 @@ export class NativeEmbeddingPort extends NativePort implements EmbeddingPort {
137
199
  error: new NativeWorkerError("stale_generation").detail,
138
200
  };
139
201
  options = inferenceOptions(options);
140
- const initialized = await this.ensureIdentity(options);
141
- if (!initialized.ok) return initialized;
202
+ // Warm fast path: when identity is already valid for the current worker
203
+ // generation, avoid awaiting a microtask before dispatching operation()
204
+ // so IPC writes immediately before the caller runs overlapped SQLite work.
205
+ if (!this.getIdentity()) {
206
+ const initialized = await this.ensureIdentity(options);
207
+ if (!initialized.ok) return initialized;
208
+ }
142
209
  if (version !== this.version || this.disposing)
143
210
  return {
144
211
  ok: false,
@@ -189,14 +256,12 @@ export class NativeEmbeddingPort extends NativePort implements EmbeddingPort {
189
256
  options?: InferenceOptions
190
257
  ): Promise<LlmResult<number[]>> {
191
258
  return this.withIdentity(async (generation) => {
192
- const result = decode(
193
- await this.client.request(
194
- { op: "embed", modelId: this.modelId, text },
195
- generation,
196
- options
197
- ),
198
- vector
259
+ const raw = await this.client.request(
260
+ { op: "embed", modelId: this.modelId, text },
261
+ generation,
262
+ options
199
263
  );
264
+ const result = decodeVector(raw);
200
265
  if (result.ok && !this.acceptDimensions(result.value.length)) {
201
266
  await this.client.disposeModel(this.modelUri);
202
267
  return { ok: false, error: new NativeWorkerError("protocol").detail };
@@ -211,18 +276,16 @@ export class NativeEmbeddingPort extends NativePort implements EmbeddingPort {
211
276
  ): Promise<LlmResult<number[][]>> {
212
277
  if (!texts.length) return { ok: true, value: [] };
213
278
  return this.withIdentity(async (generation) => {
214
- const result = decode(
215
- await this.client.request(
216
- {
217
- op: "embedBatch",
218
- modelId: this.modelId,
219
- texts,
220
- },
221
- generation,
222
- options
223
- ),
224
- z.array(vector).length(texts.length)
279
+ const raw = await this.client.request(
280
+ {
281
+ op: "embedBatch",
282
+ modelId: this.modelId,
283
+ texts,
284
+ },
285
+ generation,
286
+ options
225
287
  );
288
+ const result = decodeVectorBatch(raw, texts.length);
226
289
  if (
227
290
  result.ok &&
228
291
  result.value.some((item) => !this.acceptDimensions(item.length))