@gmickel/gno 2.14.0 → 2.16.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 (205) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/cli-reference.md +4 -2
  3. package/assets/spa-production.json.gz +0 -0
  4. package/browser-extension/artifacts/{gno-browser-clipper-v2.14.0.zip → gno-browser-clipper-v2.16.0.zip} +0 -0
  5. package/browser-extension/artifacts/gno-browser-clipper-v2.16.0.zip.sha256 +1 -0
  6. package/browser-extension/dist/manifest.json +1 -1
  7. package/package.json +1 -1
  8. package/spec/cli.md +88 -45
  9. package/spec/db/schema.sql +45 -0
  10. package/spec/output-schemas/embed-receipt.schema.json +89 -0
  11. package/src/cli/commands/agents/commands.ts +1 -1
  12. package/src/cli/commands/ask.ts +1 -1
  13. package/src/cli/commands/context-build.ts +1 -1
  14. package/src/cli/commands/embed.ts +341 -20
  15. package/src/cli/commands/links.ts +1 -1
  16. package/src/cli/commands/mcp/install.ts +2 -2
  17. package/src/cli/commands/mcp/status.ts +1 -1
  18. package/src/cli/commands/mcp/uninstall.ts +1 -1
  19. package/src/cli/commands/query.ts +1 -1
  20. package/src/cli/commands/shared.ts +4 -4
  21. package/src/cli/commands/skill/install.ts +1 -1
  22. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  23. package/src/cli/commands/skill/uninstall.ts +1 -1
  24. package/src/cli/commands/status.ts +75 -58
  25. package/src/cli/config-cache.ts +86 -0
  26. package/src/cli/globals.ts +64 -0
  27. package/src/cli/options.ts +23 -0
  28. package/src/cli/program.ts +44 -37
  29. package/src/cli/run.ts +121 -67
  30. package/src/cli/runtime-health.ts +132 -122
  31. package/src/cli/session-binding.ts +11 -2
  32. package/src/config/saver.ts +8 -0
  33. package/src/converters/adapters/browser-export/formats.ts +25 -15
  34. package/src/converters/adapters/email/adapter.ts +37 -53
  35. package/src/converters/adapters/email/html.ts +37 -20
  36. package/src/converters/adapters/email/mime.ts +71 -39
  37. package/src/converters/adapters/ical/adapter.ts +20 -12
  38. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  39. package/src/converters/adapters/shared/html-text.ts +55 -37
  40. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  41. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  42. package/src/converters/adapters/transcript/adapter.ts +12 -7
  43. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  44. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  45. package/src/converters/canonicalize.ts +17 -3
  46. package/src/converters/native/markdown.ts +24 -17
  47. package/src/converters/native/plaintext.ts +5 -6
  48. package/src/converters/registry.ts +130 -8
  49. package/src/core/activation-status.ts +4 -8
  50. package/src/core/change-diff.ts +38 -11
  51. package/src/core/context-compiler.ts +17 -18
  52. package/src/core/context-evidence.ts +116 -25
  53. package/src/core/context-verifier.ts +70 -31
  54. package/src/core/file-lock.ts +10 -2
  55. package/src/core/graph-analysis.ts +3 -3
  56. package/src/core/link-inventory-markdown.ts +2 -2
  57. package/src/core/links.ts +20 -87
  58. package/src/core/memory-fence.ts +16 -9
  59. package/src/core/memory-recall.ts +168 -34
  60. package/src/core/path-rules.ts +143 -0
  61. package/src/core/section-parse.ts +16 -6
  62. package/src/core/typed-metadata.ts +68 -0
  63. package/src/core/wiki-link-syntax.ts +88 -0
  64. package/src/embed/backlog.ts +173 -60
  65. package/src/embed/batch.ts +83 -12
  66. package/src/embed/resume-cursor.ts +103 -0
  67. package/src/embed/retry.ts +41 -32
  68. package/src/embed/variant-backlog.ts +697 -63
  69. package/src/embed/variant-plan.ts +41 -45
  70. package/src/embed/variant-retry.ts +157 -44
  71. package/src/index.ts +3 -3
  72. package/src/ingestion/budget-error-codes.ts +13 -0
  73. package/src/ingestion/chunker.ts +60 -49
  74. package/src/ingestion/compiled-context.ts +4 -5
  75. package/src/ingestion/convert-file.ts +1 -1
  76. package/src/ingestion/document-metadata.ts +16 -9
  77. package/src/ingestion/excluded-ranges.ts +97 -0
  78. package/src/ingestion/file-processor.ts +122 -37
  79. package/src/ingestion/frontmatter.ts +35 -7
  80. package/src/ingestion/graph-reconciliation.ts +187 -51
  81. package/src/ingestion/language.ts +66 -61
  82. package/src/ingestion/position.ts +5 -5
  83. package/src/ingestion/prepare-file.ts +50 -29
  84. package/src/ingestion/record-adapter-canonical.ts +37 -26
  85. package/src/ingestion/record-adapter.ts +46 -26
  86. package/src/ingestion/record-container.ts +121 -53
  87. package/src/ingestion/record-path.ts +5 -2
  88. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  89. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  90. package/src/ingestion/source-availability/readers.ts +51 -0
  91. package/src/ingestion/strip.ts +39 -105
  92. package/src/ingestion/sync.ts +692 -386
  93. package/src/ingestion/typed-metadata.ts +10 -4
  94. package/src/ingestion/walker.ts +485 -158
  95. package/src/llm/cache.ts +128 -84
  96. package/src/llm/http-inference.ts +112 -35
  97. package/src/llm/http-policy.ts +101 -0
  98. package/src/llm/httpEmbedding.ts +8 -1
  99. package/src/llm/httpGeneration.ts +5 -1
  100. package/src/llm/httpRerank.ts +5 -1
  101. package/src/llm/inference-scope.ts +15 -2
  102. package/src/llm/lazy-ports.ts +33 -3
  103. package/src/llm/lockfile.ts +34 -7
  104. package/src/llm/model-cleanup.ts +24 -0
  105. package/src/llm/native-worker/client.ts +23 -12
  106. package/src/llm/native-worker/dispatcher.ts +19 -9
  107. package/src/llm/native-worker/embedding-identity.ts +42 -16
  108. package/src/llm/native-worker/entry.ts +2 -1
  109. package/src/llm/native-worker/owner.ts +1 -0
  110. package/src/llm/native-worker/ports.ts +86 -23
  111. package/src/llm/native-worker/protocol.ts +386 -55
  112. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  113. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  114. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  115. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  116. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  117. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  118. package/src/llm/types.ts +14 -0
  119. package/src/mcp/context.ts +342 -23
  120. package/src/mcp/http-transport.ts +21 -3
  121. package/src/mcp/tool-profile-types.ts +62 -0
  122. package/src/mcp/tool-profile.ts +32 -56
  123. package/src/mcp/tools/context.ts +5 -1
  124. package/src/mcp/tools/index.ts +269 -191
  125. package/src/mcp/tools/links.ts +7 -5
  126. package/src/mcp/tools/query.ts +60 -37
  127. package/src/mcp/tools/vsearch.ts +25 -14
  128. package/src/pipeline/answer.ts +133 -40
  129. package/src/pipeline/claim-verification.ts +293 -189
  130. package/src/pipeline/claim-verifier.ts +6 -7
  131. package/src/pipeline/egress-lineage.ts +37 -26
  132. package/src/pipeline/exclude.ts +34 -11
  133. package/src/pipeline/expansion.ts +233 -19
  134. package/src/pipeline/filters.ts +169 -33
  135. package/src/pipeline/graph-retrieval.ts +117 -61
  136. package/src/pipeline/hybrid.ts +598 -329
  137. package/src/pipeline/hydration.ts +86 -24
  138. package/src/pipeline/intent.ts +15 -7
  139. package/src/pipeline/owner-fusion.ts +61 -19
  140. package/src/pipeline/query-language.ts +15 -2
  141. package/src/pipeline/rerank.ts +15 -22
  142. package/src/pipeline/search.ts +193 -72
  143. package/src/pipeline/snippet.ts +15 -2
  144. package/src/pipeline/temporal.ts +51 -10
  145. package/src/pipeline/vsearch.ts +250 -152
  146. package/src/publish/attachment-raster.ts +2 -16
  147. package/src/publish/encrypted-export.ts +15 -5
  148. package/src/serve/browse-tree.ts +50 -42
  149. package/src/serve/connectors.ts +2 -1
  150. package/src/serve/context.ts +13 -4
  151. package/src/serve/doc-events.ts +3 -0
  152. package/src/serve/public/app.tsx +49 -21
  153. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  154. package/src/serve/public/components/CaptureModal.tsx +14 -10
  155. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  156. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  157. package/src/serve/public/globals.built.css +1 -1
  158. package/src/serve/public/globals.css +19 -0
  159. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  160. package/src/serve/public/lib/metadata-filter.ts +234 -9
  161. package/src/serve/public/pages/Browse.tsx +61 -27
  162. package/src/serve/public/pages/DocView.tsx +44 -25
  163. package/src/serve/public/pages/GraphView.tsx +8 -3
  164. package/src/serve/resident-runtime.ts +199 -48
  165. package/src/serve/routes/api.ts +98 -67
  166. package/src/serve/routes/links.ts +18 -4
  167. package/src/serve/server.ts +1370 -1180
  168. package/src/serve/spa-bundle-source.ts +52 -27
  169. package/src/serve/status.ts +101 -52
  170. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  171. package/src/serve/watch-reconciliation-shared.ts +42 -4
  172. package/src/serve/watch-reconciliation.ts +21 -8
  173. package/src/serve/watch-service-events.ts +7 -1
  174. package/src/serve/watch-service-hosts.ts +3 -1
  175. package/src/serve/watch-service.ts +46 -21
  176. package/src/serve/watch-snapshot-scan.ts +6 -15
  177. package/src/sessions/archive.ts +20 -8
  178. package/src/sessions/sanitize.ts +38 -18
  179. package/src/sessions/service.ts +180 -102
  180. package/src/store/migrations/036-vector-mirror-state.ts +83 -0
  181. package/src/store/migrations/037-performance-indexes.ts +56 -0
  182. package/src/store/migrations/index.ts +4 -0
  183. package/src/store/sqlite/adapter.ts +1217 -651
  184. package/src/store/sqlite/chunking-policy.ts +15 -1
  185. package/src/store/sqlite/eligibility.ts +110 -70
  186. package/src/store/sqlite/graph-neighbors.ts +71 -46
  187. package/src/store/sqlite/graph-reference-state.ts +27 -3
  188. package/src/store/sqlite/graph-similarity.ts +59 -12
  189. package/src/store/sqlite/metadata-predicate.ts +123 -28
  190. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  191. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  192. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  193. package/src/store/types.ts +32 -0
  194. package/src/store/vector/eligibility.ts +39 -0
  195. package/src/store/vector/lazy.ts +17 -0
  196. package/src/store/vector/partition-index.ts +49 -47
  197. package/src/store/vector/proof-cache.ts +103 -0
  198. package/src/store/vector/sqlite-vec.ts +230 -139
  199. package/src/store/vector/stats.ts +29 -73
  200. package/src/store/vector/status.ts +151 -52
  201. package/src/store/vector/stored-vectors.ts +131 -45
  202. package/src/store/vector/types.ts +10 -0
  203. package/src/store/vector/variant-search.ts +771 -109
  204. package/src/store/vector/variants.ts +785 -144
  205. package/browser-extension/artifacts/gno-browser-clipper-v2.14.0.zip.sha256 +0 -1
package/src/llm/cache.ts CHANGED
@@ -53,10 +53,11 @@ type ValidatedCachedPath =
53
53
  | { ok: false; kind: "missing" }
54
54
  | { ok: false; kind: "invalid"; error: LlmError };
55
55
 
56
+ const HASH_CHUNK_BYTES = 4 * 1024 * 1024;
57
+ const UTF8_LENIENT_DECODER = new TextDecoder("utf-8", { fatal: false });
58
+
56
59
  function looksLikeHtml(bytes: Uint8Array): boolean {
57
- const text = new TextDecoder("utf-8", { fatal: false })
58
- .decode(bytes)
59
- .toLowerCase();
60
+ const text = UTF8_LENIENT_DECODER.decode(bytes).toLowerCase();
60
61
  return (
61
62
  text.includes("<!doctype") ||
62
63
  text.includes("<html") ||
@@ -67,7 +68,10 @@ function looksLikeHtml(bytes: Uint8Array): boolean {
67
68
  }
68
69
 
69
70
  function hasGgufMagic(bytes: Uint8Array): boolean {
70
- return GGUF_MAGIC.every((value, index) => bytes[index] === value);
71
+ return (
72
+ bytes.length >= GGUF_MAGIC.length &&
73
+ GGUF_MAGIC.every((value, index) => bytes[index] === value)
74
+ );
71
75
  }
72
76
 
73
77
  export async function validateGgufFile(
@@ -75,16 +79,42 @@ export async function validateGgufFile(
75
79
  uri: string,
76
80
  owner: ModelFileOwner
77
81
  ): Promise<LlmResult<void>> {
78
- const file = Bun.file(path);
79
- const exists = await file.exists();
80
- if (!exists) {
81
- return {
82
- ok: false,
83
- error: modelNotFoundError(uri, `File not found: ${path}`),
84
- };
82
+ let bytes: Uint8Array;
83
+ try {
84
+ const fh = await open(path, "r");
85
+ try {
86
+ const buf = new Uint8Array(512);
87
+ const { bytesRead } = await fh.read(buf, 0, 512, 0);
88
+ bytes = bytesRead === 512 ? buf : buf.subarray(0, bytesRead);
89
+ } finally {
90
+ await fh.close();
91
+ }
92
+ } catch (error) {
93
+ const code =
94
+ error && typeof error === "object" && "code" in error
95
+ ? String(error.code)
96
+ : "";
97
+ if (code === "ENOENT" || code === "ENOTDIR") {
98
+ return {
99
+ ok: false,
100
+ error: modelNotFoundError(uri, `File not found: ${path}`),
101
+ };
102
+ }
103
+ if (code === "EISDIR") {
104
+ return {
105
+ ok: false,
106
+ error: invalidModelFileError(
107
+ uri,
108
+ path,
109
+ error instanceof Error ? error.message : String(error)
110
+ ),
111
+ };
112
+ }
113
+ // Propagate transient/permission I/O errors (EACCES, EMFILE, EBUSY, EIO)
114
+ // so callers never mistake a healthy cached model for a corrupt file.
115
+ throw error;
85
116
  }
86
117
 
87
- const bytes = new Uint8Array(await file.slice(0, 512).arrayBuffer());
88
118
  if (hasGgufMagic(bytes)) {
89
119
  return { ok: true, value: undefined };
90
120
  }
@@ -108,20 +138,25 @@ export async function validateGgufFile(
108
138
 
109
139
  async function computeSha256(path: string): Promise<string> {
110
140
  const hasher = new Bun.CryptoHasher("sha256");
111
- const reader = Bun.file(path).stream().getReader();
112
-
141
+ const buffer = new Uint8Array(HASH_CHUNK_BYTES);
142
+ const fh = await open(path, "r");
113
143
  try {
144
+ let position = 0;
114
145
  while (true) {
115
- const { done, value } = await reader.read();
116
- if (done) {
117
- break;
118
- }
119
- if (value) {
120
- hasher.update(value);
121
- }
146
+ const { bytesRead } = await fh.read(
147
+ buffer,
148
+ 0,
149
+ buffer.byteLength,
150
+ position
151
+ );
152
+ if (bytesRead === 0) break;
153
+ hasher.update(
154
+ bytesRead === buffer.byteLength ? buffer : buffer.subarray(0, bytesRead)
155
+ );
156
+ position += bytesRead;
122
157
  }
123
158
  } finally {
124
- reader.releaseLock();
159
+ await fh.close();
125
160
  }
126
161
 
127
162
  return hasher.digest("hex");
@@ -271,6 +306,11 @@ export class ModelCache {
271
306
  private readonly manifestPath: string;
272
307
  private readonly resolveModelFileFn?: ResolveModelFile;
273
308
  private manifest: Manifest | null = null;
309
+ private readOnlyManifestCache: {
310
+ mtimeMs: number;
311
+ size: number;
312
+ manifest: Manifest;
313
+ } | null = null;
274
314
 
275
315
  constructor(
276
316
  cacheDir?: string,
@@ -291,18 +331,8 @@ export class ModelCache {
291
331
  return { ok: false, error: invalidUriError(uri, parsed.error) };
292
332
  }
293
333
 
294
- // Local files: verify existence
334
+ // Local files: open and validate directly (no redundant stat)
295
335
  if (parsed.value.scheme === "file") {
296
- const exists = await this.fileExists(parsed.value.file);
297
- if (!exists) {
298
- return {
299
- ok: false,
300
- error: modelNotFoundError(
301
- uri,
302
- `File not found: ${parsed.value.file}`
303
- ),
304
- };
305
- }
306
336
  const validation = await validateGgufFile(parsed.value.file, uri, "user");
307
337
  if (!validation.ok) {
308
338
  return validation;
@@ -338,18 +368,8 @@ export class ModelCache {
338
368
  return { ok: false, error: invalidUriError(uri, parsed.error) };
339
369
  }
340
370
 
341
- // Local files: just verify
371
+ // Local files: open and validate directly (no redundant stat)
342
372
  if (parsed.value.scheme === "file") {
343
- const exists = await this.fileExists(parsed.value.file);
344
- if (!exists) {
345
- return {
346
- ok: false,
347
- error: modelNotFoundError(
348
- uri,
349
- `File not found: ${parsed.value.file}`
350
- ),
351
- };
352
- }
353
373
  const validation = await validateGgufFile(parsed.value.file, uri, "user");
354
374
  if (!validation.ok) {
355
375
  return validation;
@@ -443,33 +463,14 @@ export class ModelCache {
443
463
  policy: DownloadPolicy,
444
464
  onProgress?: ProgressCallback
445
465
  ): Promise<LlmResult<string>> {
446
- // Fast path: check if already cached
447
- const cached = await this.getValidatedCachedPath(uri);
448
- if (cached.ok) {
449
- return { ok: true, value: cached.path };
450
- }
451
- if (cached.kind === "invalid") {
452
- return { ok: false, error: cached.error };
453
- }
454
-
455
- // Parse and validate URI
466
+ // Parse URI first so file: URIs never touch manifest.json.
456
467
  const parsed = parseModelUri(uri);
457
468
  if (!parsed.ok) {
458
469
  return { ok: false, error: invalidUriError(uri, parsed.error) };
459
470
  }
460
471
 
461
- // Local files: just verify existence (no download needed)
472
+ // Local files: validate directly (no manifest read, no double stat)
462
473
  if (parsed.value.scheme === "file") {
463
- const exists = await this.fileExists(parsed.value.file);
464
- if (!exists) {
465
- return {
466
- ok: false,
467
- error: modelNotFoundError(
468
- uri,
469
- `File not found: ${parsed.value.file}`
470
- ),
471
- };
472
- }
473
474
  const validation = await validateGgufFile(parsed.value.file, uri, "user");
474
475
  if (!validation.ok) {
475
476
  return validation;
@@ -477,6 +478,15 @@ export class ModelCache {
477
478
  return { ok: true, value: parsed.value.file };
478
479
  }
479
480
 
481
+ // Fast path: check if HF model is already cached
482
+ const cached = await this.getValidatedCachedPath(uri);
483
+ if (cached.ok) {
484
+ return { ok: true, value: cached.path };
485
+ }
486
+ if (cached.kind === "invalid") {
487
+ return { ok: false, error: cached.error };
488
+ }
489
+
480
490
  // HF models: check policy
481
491
  if (policy.offline) {
482
492
  return { ok: false, error: modelNotCachedError(uri, type) };
@@ -541,9 +551,9 @@ export class ModelCache {
541
551
  return validation.ok;
542
552
  }
543
553
 
544
- const manifest = await this.readManifestFromDisk();
554
+ const manifest = await this.readManifestStatCached();
545
555
  const entry = manifest.models.find((model) => model.uri === uri);
546
- if (!entry || !(await this.fileExists(entry.path))) return false;
556
+ if (!entry) return false;
547
557
  const validation = await validateGgufFile(entry.path, uri, "cache");
548
558
  return validation.ok;
549
559
  }
@@ -615,15 +625,6 @@ export class ModelCache {
615
625
  // Private
616
626
  // ───────────────────────────────────────────────────────────────────────────
617
627
 
618
- private async fileExists(path: string): Promise<boolean> {
619
- try {
620
- await stat(path);
621
- return true;
622
- } catch {
623
- return false;
624
- }
625
- }
626
-
627
628
  private async getValidatedCachedPath(
628
629
  uri: string
629
630
  ): Promise<ValidatedCachedPath> {
@@ -633,17 +634,16 @@ export class ModelCache {
633
634
  return { ok: false, kind: "missing" };
634
635
  }
635
636
 
636
- const exists = await this.fileExists(entry.path);
637
- if (!exists) {
638
- await this.removeFromManifest(uri);
639
- return { ok: false, kind: "missing" };
640
- }
641
-
642
637
  const validation = await validateGgufFile(entry.path, uri, "cache");
643
638
  if (validation.ok) {
644
639
  return { ok: true, path: entry.path };
645
640
  }
646
641
 
642
+ if (validation.error.code === "MODEL_NOT_FOUND") {
643
+ await this.removeFromManifest(uri);
644
+ return { ok: false, kind: "missing" };
645
+ }
646
+
647
647
  await rm(entry.path, { force: true }).catch(() => {
648
648
  // Ignore deletion errors
649
649
  });
@@ -656,10 +656,44 @@ export class ModelCache {
656
656
  return this.manifest;
657
657
  }
658
658
 
659
- this.manifest = await this.readManifestFromDisk();
659
+ this.manifest = await this.readManifestStatCached();
660
660
  return this.manifest;
661
661
  }
662
662
 
663
+ /**
664
+ * Read manifest from disk via a single open file descriptor, reusing the
665
+ * parsed manifest when (mtimeMs, size) on that descriptor is unchanged.
666
+ */
667
+ private async readManifestStatCached(): Promise<Manifest> {
668
+ try {
669
+ const fh = await open(this.manifestPath, "r");
670
+ try {
671
+ const st = await fh.stat();
672
+ const cached = this.readOnlyManifestCache;
673
+ if (
674
+ cached &&
675
+ cached.mtimeMs === st.mtimeMs &&
676
+ cached.size === st.size
677
+ ) {
678
+ return cached.manifest;
679
+ }
680
+ const content = await fh.readFile("utf-8");
681
+ const manifest = JSON.parse(content) as Manifest;
682
+ this.readOnlyManifestCache = {
683
+ mtimeMs: st.mtimeMs,
684
+ size: st.size,
685
+ manifest,
686
+ };
687
+ return manifest;
688
+ } finally {
689
+ await fh.close();
690
+ }
691
+ } catch {
692
+ this.readOnlyManifestCache = null;
693
+ return { version: MANIFEST_VERSION, models: [] };
694
+ }
695
+ }
696
+
663
697
  /**
664
698
  * Read manifest from disk without cache (for use under lock).
665
699
  */
@@ -693,8 +727,18 @@ export class ModelCache {
693
727
  // Write atomically
694
728
  await this.writeManifestAtomically(manifest);
695
729
 
696
- // Update cache
730
+ // Update caches
697
731
  this.manifest = manifest;
732
+ try {
733
+ const st = await stat(this.manifestPath);
734
+ this.readOnlyManifestCache = {
735
+ mtimeMs: st.mtimeMs,
736
+ size: st.size,
737
+ manifest,
738
+ };
739
+ } catch {
740
+ this.readOnlyManifestCache = null;
741
+ }
698
742
  return true;
699
743
  });
700
744
 
@@ -4,6 +4,7 @@ import type { Collection } from "../config/types";
4
4
  import type { CollectionEgressState } from "../core/egress-policy";
5
5
  import type { EgressDestinationZone } from "../core/egress-policy";
6
6
  import type {
7
+ HttpDestinationMaximumZone,
7
8
  HttpDestinationPolicyOptions,
8
9
  HttpDestinationResolver,
9
10
  PinnedHttpFetch,
@@ -16,7 +17,7 @@ import {
16
17
  } from "../core/egress-enforcement";
17
18
  import { evaluateEgressPolicy } from "../core/egress-policy";
18
19
  import { EgressProvenanceError } from "../core/egress-provenance";
19
- import { classifyHttpDestination, prepareHttpDestination } from "./http-policy";
20
+ import { prepareClassifiedHttpDestination } from "./http-policy";
20
21
 
21
22
  const REDIRECT_STATUSES = new Set([301, 302, 307, 308]);
22
23
 
@@ -32,6 +33,55 @@ export interface HttpInferenceOptions {
32
33
  env?: HttpDestinationPolicyOptions["env"];
33
34
  }
34
35
 
36
+ export interface CachedHttpInferenceContext {
37
+ readonly rawUrl: string;
38
+ readonly parsedUrl: URL | null;
39
+ readonly policyKey: string;
40
+ readonly states: readonly CollectionEgressState[];
41
+ readonly maximumZone: HttpDestinationMaximumZone | null;
42
+ }
43
+
44
+ const CONTEXT_CACHE = new WeakMap<
45
+ HttpInferenceOptions,
46
+ CachedHttpInferenceContext
47
+ >();
48
+ const PARSED_URL_CACHE = new WeakMap<
49
+ HttpInferenceOptions,
50
+ { rawUrl: string; parsedUrl: URL | null }
51
+ >();
52
+
53
+ function computePolicyCacheKey(options: HttpInferenceOptions): string {
54
+ // Fast fingerprint of current collection scope + live egressPolicy values so
55
+ // any in-place policy mutation invalidates the cached states immediately.
56
+ const parts: string[] = [
57
+ String(options.collections.length),
58
+ options.collectionNames.join("\0"),
59
+ ];
60
+ for (let i = 0; i < options.collections.length; i += 1) {
61
+ const col = options.collections[i]!;
62
+ parts.push(`${col.name}:${col.egressPolicy ?? ""}`);
63
+ }
64
+ return parts.join("|");
65
+ }
66
+
67
+ function getCachedParsedUrl(
68
+ rawUrl: string,
69
+ options: HttpInferenceOptions
70
+ ): URL | null {
71
+ const existing = PARSED_URL_CACHE.get(options);
72
+ if (existing && existing.rawUrl === rawUrl) {
73
+ return existing.parsedUrl;
74
+ }
75
+ let parsedUrl: URL | null = null;
76
+ try {
77
+ parsedUrl = new URL(rawUrl);
78
+ } catch {
79
+ parsedUrl = null;
80
+ }
81
+ PARSED_URL_CACHE.set(options, { rawUrl, parsedUrl });
82
+ return parsedUrl;
83
+ }
84
+
35
85
  const scopedStates = (
36
86
  options: HttpInferenceOptions
37
87
  ): readonly CollectionEgressState[] => {
@@ -43,6 +93,35 @@ const scopedStates = (
43
93
  }
44
94
  };
45
95
 
96
+ function buildHttpInferenceContext(
97
+ rawUrl: string,
98
+ options: HttpInferenceOptions,
99
+ policyKey: string
100
+ ): CachedHttpInferenceContext {
101
+ const parsedUrl = getCachedParsedUrl(rawUrl, options);
102
+ const states = scopedStates(options);
103
+ const maximumZone =
104
+ states.length === 0
105
+ ? null
106
+ : maximumDestinationZoneForCollections(
107
+ options.collections,
108
+ options.collectionNames
109
+ );
110
+ return { rawUrl, parsedUrl, policyKey, states, maximumZone };
111
+ }
112
+
113
+ /** Pre-parse URL and egress policy once per HTTP inference port instance. */
114
+ export function primeHttpInferenceContext(
115
+ rawUrl: string,
116
+ options: HttpInferenceOptions
117
+ ): void {
118
+ const policyKey = computePolicyCacheKey(options);
119
+ CONTEXT_CACHE.set(
120
+ options,
121
+ buildHttpInferenceContext(rawUrl, options, policyKey)
122
+ );
123
+ }
124
+
46
125
  const enforce = (
47
126
  states: readonly CollectionEgressState[],
48
127
  zone: EgressDestinationZone,
@@ -67,43 +146,41 @@ export const requestHttpInference = async (
67
146
  options: HttpInferenceOptions
68
147
  ): Promise<Response> => {
69
148
  init.signal?.throwIfAborted();
70
- const states = scopedStates(options);
149
+ const policyKey = computePolicyCacheKey(options);
150
+ const cached = CONTEXT_CACHE.get(options);
151
+ let ctx: CachedHttpInferenceContext;
152
+ if (cached && cached.rawUrl === rawUrl && cached.policyKey === policyKey) {
153
+ ctx = cached;
154
+ } else {
155
+ ctx = buildHttpInferenceContext(rawUrl, options, policyKey);
156
+ CONTEXT_CACHE.set(options, ctx);
157
+ }
158
+ const { states } = ctx;
71
159
  if (states.length === 0) {
72
160
  enforce(states, "remote", options);
73
161
  }
74
- const maximumZone = maximumDestinationZoneForCollections(
75
- options.collections,
76
- options.collectionNames
77
- );
78
-
79
- // DNS-only classification carries no headers, body, credentials, or model
80
- // metadata. Policy evaluates the proven zone before transport preparation.
81
- const classification = await classifyHttpDestination(rawUrl, {
82
- resolver: options.resolver,
83
- });
84
- if (!classification.ok) {
85
- throw new EgressDeniedError(
86
- evaluateEgressPolicy({
87
- collections: states,
88
- action: "remote_inference",
89
- destination: { zone: classification.classification.zone },
90
- caller: {
91
- authenticated: options.authenticated ?? true,
92
- operationAuthorized: false,
93
- },
94
- contentClass: "source",
95
- })
162
+ const maximumZone =
163
+ ctx.maximumZone ??
164
+ maximumDestinationZoneForCollections(
165
+ options.collections,
166
+ options.collectionNames
96
167
  );
97
- }
98
- enforce(states, classification.classification.zone, options);
99
- const url = new URL(rawUrl);
100
-
101
- let prepared = await prepareHttpDestination(url.href, {
102
- maximumZone,
103
- resolver: options.resolver,
104
- remoteProvider: classification.classification.zone === "remote",
105
- env: options.env,
106
- });
168
+
169
+ // Merged classify + prepare performs 1 DNS lookup (evaluating collection
170
+ // policy on the proven zone before transport/proxy/HTTPS checks), followed
171
+ // by acquireConnection()'s independent pre-connect DNS rebinding check (2
172
+ // DNS lookups total).
173
+ let prepared = await prepareClassifiedHttpDestination(
174
+ ctx.parsedUrl ?? rawUrl,
175
+ {
176
+ maximumZone,
177
+ resolver: options.resolver,
178
+ env: options.env,
179
+ assertZoneAllowed: (classification) => {
180
+ enforce(states, classification.zone, options);
181
+ },
182
+ }
183
+ );
107
184
  if (!prepared.ok) {
108
185
  throw new EgressDeniedError(
109
186
  evaluateEgressPolicy({
@@ -119,7 +196,7 @@ export const requestHttpInference = async (
119
196
  );
120
197
  }
121
198
 
122
- let currentUrl = url;
199
+ let currentUrl = ctx.parsedUrl ?? new URL(rawUrl);
123
200
  for (;;) {
124
201
  init.signal?.throwIfAborted();
125
202
  enforce(states, prepared.value.classification.zone, options);
@@ -502,6 +502,107 @@ export async function prepareHttpDestination(
502
502
  };
503
503
  }
504
504
 
505
+ /**
506
+ * Resolve, classify, and prepare an HTTP destination in one DNS lookup phase
507
+ * (eliminating the duplicate lookup between classifyHttpDestination and
508
+ * prepareHttpDestination). The caller's `assertZoneAllowed` runs against the
509
+ * proven network zone before transport/proxy/HTTPS policy checks, and
510
+ * `HttpDestinationPin.acquireConnection()` still performs its independent
511
+ * pre-connect DNS rebinding check.
512
+ */
513
+ export async function prepareClassifiedHttpDestination(
514
+ rawUrl: string | URL,
515
+ options: Omit<HttpDestinationPolicyOptions, "remoteProvider"> & {
516
+ redirectCount?: number;
517
+ assertZoneAllowed?: (classification: DestinationClassification) => void;
518
+ }
519
+ ): Promise<HttpDestinationPolicyResult> {
520
+ const redirectCount =
521
+ options.redirectCount === undefined ? 0 : options.redirectCount;
522
+ if (!Number.isSafeInteger(redirectCount) || redirectCount < 0) {
523
+ return denial("INVALID_REDIRECT_COUNT", invalidClassification(), null, 0);
524
+ }
525
+ if (redirectCount > MAX_HTTP_DESTINATION_REDIRECTS) {
526
+ return denial(
527
+ "REDIRECT_LIMIT",
528
+ invalidClassification(),
529
+ null,
530
+ redirectCount
531
+ );
532
+ }
533
+ const url = typeof rawUrl === "string" ? parseHttpUrl(rawUrl) : rawUrl;
534
+ const invalid = invalidClassification();
535
+ if (!url) return denial("INVALID_DESTINATION", invalid, null, redirectCount);
536
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
537
+ return denial("UNSUPPORTED_PROTOCOL", invalid, url, redirectCount);
538
+ }
539
+ if (url.username || url.password) {
540
+ return denial("CREDENTIALS_IN_URL", invalid, url, redirectCount);
541
+ }
542
+
543
+ const resolver = options.resolver ?? defaultResolver;
544
+ const env = options.env ?? process.env;
545
+ const resolved = await resolveAddresses(url, resolver);
546
+ if (!resolved.ok) {
547
+ return denial(resolved.reason, invalid, url, redirectCount);
548
+ }
549
+
550
+ const initialClassification = classifyDestination({
551
+ kind: "network",
552
+ hostname: resolved.hostname,
553
+ addresses: resolved.addresses,
554
+ });
555
+ options.assertZoneAllowed?.(initialClassification);
556
+
557
+ const remoteProvider = initialClassification.zone === "remote";
558
+ if (remoteProvider && url.protocol !== "https:") {
559
+ return denial("PROVIDER_HTTPS_REQUIRED", invalid, url, redirectCount);
560
+ }
561
+ if (options.maximumZone !== "remote" && hasActiveProxy(env)) {
562
+ return denial("PROXY_ENVIRONMENT_ACTIVE", invalid, url, redirectCount);
563
+ }
564
+
565
+ const classification = remoteProvider
566
+ ? classifyDestination({
567
+ kind: "network",
568
+ hostname: resolved.hostname,
569
+ addresses: resolved.addresses,
570
+ remoteProvider: true,
571
+ })
572
+ : initialClassification;
573
+ if (remoteProvider && !providerAddressesArePublic(classification)) {
574
+ return denial(
575
+ "PROVIDER_ADDRESS_NOT_PUBLIC",
576
+ classification,
577
+ url,
578
+ redirectCount
579
+ );
580
+ }
581
+ if (!zoneAllowed(classification.zone, options.maximumZone)) {
582
+ return denial("ZONE_NOT_ALLOWED", classification, url, redirectCount);
583
+ }
584
+
585
+ return {
586
+ ok: true,
587
+ reason: "DESTINATION_ALLOWED",
588
+ value: new HttpDestinationPin(
589
+ {
590
+ url,
591
+ hostname: resolved.hostname,
592
+ addresses: resolved.addresses,
593
+ classification,
594
+ },
595
+ {
596
+ maximumZone: options.maximumZone,
597
+ resolver,
598
+ remoteProvider,
599
+ env,
600
+ },
601
+ redirectCount
602
+ ),
603
+ };
604
+ }
605
+
505
606
  /**
506
607
  * Resolve and classify an HTTP destination without opening a socket or
507
608
  * transferring request headers/body. This bounded DNS-only phase lets the
@@ -10,7 +10,10 @@ import type { EmbeddingPort, LlmResult } from "./types";
10
10
 
11
11
  import { EgressDeniedError } from "../core/egress-enforcement";
12
12
  import { egressDeniedInferenceError, inferenceFailedError } from "./errors";
13
- import { requestHttpInference } from "./http-inference";
13
+ import {
14
+ primeHttpInferenceContext,
15
+ requestHttpInference,
16
+ } from "./http-inference";
14
17
  import { runHttpInference } from "./inference-scope";
15
18
 
16
19
  // ─────────────────────────────────────────────────────────────────────────────
@@ -57,9 +60,13 @@ export class HttpEmbedding implements EmbeddingPort {
57
60
  const pathParts = url.pathname.split("/");
58
61
  this.modelName = pathParts[pathParts.length - 1] || "embedding-model";
59
62
  }
63
+ primeHttpInferenceContext(this.apiUrl, this.requestOptions);
60
64
  }
61
65
 
62
66
  async init(options?: InferenceOptions): Promise<LlmResult<void>> {
67
+ if (this.dims !== null) {
68
+ return { ok: true, value: undefined };
69
+ }
63
70
  // Test connection with a simple embedding
64
71
  const result = await this.embed("test", options);
65
72
  if (!result.ok) {
@@ -14,7 +14,10 @@ import {
14
14
  inferenceFailedError,
15
15
  structuredOutputUnavailableError,
16
16
  } from "./errors";
17
- import { requestHttpInference } from "./http-inference";
17
+ import {
18
+ primeHttpInferenceContext,
19
+ requestHttpInference,
20
+ } from "./http-inference";
18
21
  import { runHttpInference } from "./inference-scope";
19
22
 
20
23
  // ─────────────────────────────────────────────────────────────────────────────
@@ -68,6 +71,7 @@ export class HttpGeneration implements GenerationPort {
68
71
  const pathParts = url.pathname.split("/");
69
72
  this.modelName = pathParts[pathParts.length - 1] || "llama";
70
73
  }
74
+ primeHttpInferenceContext(this.apiUrl, this.requestOptions);
71
75
  }
72
76
 
73
77
  async generate(
@@ -10,7 +10,10 @@ import type { LlmResult, RerankPort, RerankScore } from "./types";
10
10
 
11
11
  import { EgressDeniedError } from "../core/egress-enforcement";
12
12
  import { egressDeniedInferenceError, inferenceFailedError } from "./errors";
13
- import { requestHttpInference } from "./http-inference";
13
+ import {
14
+ primeHttpInferenceContext,
15
+ requestHttpInference,
16
+ } from "./http-inference";
14
17
  import { runHttpInference } from "./inference-scope";
15
18
 
16
19
  // ─────────────────────────────────────────────────────────────────────────────
@@ -57,6 +60,7 @@ export class HttpRerank implements RerankPort {
57
60
  const pathParts = url.pathname.split("/");
58
61
  this.modelName = pathParts[pathParts.length - 1] || "reranker-model";
59
62
  }
63
+ primeHttpInferenceContext(this.apiUrl, this.requestOptions);
60
64
  // Default instruction for retrieval tasks
61
65
  this.instruction =
62
66
  "Given a web search query, retrieve relevant passages that answer the query";