@clockgrove/assetgrove-search 0.0.0-stage → 0.3.2

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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/embedder.d.ts +20 -0
  4. package/dist/embedder.js +21 -0
  5. package/dist/errors.d.ts +12 -0
  6. package/dist/errors.js +12 -0
  7. package/dist/extension.d.ts +38 -0
  8. package/dist/extension.js +589 -0
  9. package/dist/find.d.ts +115 -0
  10. package/dist/find.js +203 -0
  11. package/dist/flatten.d.ts +15 -0
  12. package/dist/flatten.js +19 -0
  13. package/dist/index.d.ts +19 -0
  14. package/dist/index.js +18 -0
  15. package/dist/indexer.d.ts +48 -0
  16. package/dist/indexer.js +187 -0
  17. package/dist/lance-store.d.ts +98 -0
  18. package/dist/lance-store.js +456 -0
  19. package/dist/library.d.ts +63 -0
  20. package/dist/library.js +32 -0
  21. package/dist/lock.d.ts +11 -0
  22. package/dist/lock.js +176 -0
  23. package/dist/memory-store.d.ts +26 -0
  24. package/dist/memory-store.js +111 -0
  25. package/dist/model-manifest.d.ts +20 -0
  26. package/dist/model-manifest.js +14 -0
  27. package/dist/model-manifest.json +38 -0
  28. package/dist/outliers.d.ts +14 -0
  29. package/dist/outliers.js +41 -0
  30. package/dist/platform.d.ts +4 -0
  31. package/dist/platform.js +6 -0
  32. package/dist/route-embedder.d.ts +20 -0
  33. package/dist/route-embedder.js +47 -0
  34. package/dist/scripted.d.ts +15 -0
  35. package/dist/scripted.js +35 -0
  36. package/dist/setup.d.ts +26 -0
  37. package/dist/setup.js +60 -0
  38. package/dist/siglip2.d.ts +6 -0
  39. package/dist/siglip2.js +84 -0
  40. package/dist/store.d.ts +129 -0
  41. package/dist/store.js +2 -0
  42. package/dist/tokens.d.ts +6 -0
  43. package/dist/tokens.js +22 -0
  44. package/dist/where.d.ts +20 -0
  45. package/dist/where.js +164 -0
  46. package/package.json +55 -3
  47. package/skills/assetgrove-search/SKILL.md +41 -0
  48. package/skills/assetgrove-search/references/commands.md +65 -0
package/dist/lock.js ADDED
@@ -0,0 +1,176 @@
1
+ import { mkdir, open, readFile, stat, unlink } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { setTimeout as sleep } from "node:timers/promises";
4
+ import { SearchError } from "./errors.js";
5
+ const STALE_EMPTY_MS = 10_000;
6
+ function lockPath(storeDir) {
7
+ return join(storeDir, "write.lock");
8
+ }
9
+ export class WriteLock {
10
+ path;
11
+ constructor(path) {
12
+ this.path = path;
13
+ }
14
+ async release() {
15
+ try {
16
+ const text = await retryBusy(() => readFile(this.path, "utf8"));
17
+ if (Number.parseInt(text.trim(), 10) !== process.pid)
18
+ return;
19
+ await retryBusy(() => unlink(this.path));
20
+ }
21
+ catch (e) {
22
+ if (e.code !== "ENOENT")
23
+ throw e;
24
+ }
25
+ }
26
+ }
27
+ /**
28
+ * On Windows a file that another handle is creating, reading or deleting refuses an open or an
29
+ * unlink with one of these codes for a few milliseconds. They are contention, not a permission
30
+ * problem, so the operation is tried again.
31
+ */
32
+ function busy(e) {
33
+ const code = e.code;
34
+ return (process.platform === "win32" && (code === "EPERM" || code === "EBUSY" || code === "EACCES"));
35
+ }
36
+ async function retryBusy(operation) {
37
+ for (let attempt = 1;; attempt++) {
38
+ try {
39
+ return await operation();
40
+ }
41
+ catch (e) {
42
+ if (!busy(e) || attempt >= 10)
43
+ throw e;
44
+ await sleep(5 * attempt);
45
+ }
46
+ }
47
+ }
48
+ function alive(pid) {
49
+ try {
50
+ process.kill(pid, 0);
51
+ return true;
52
+ }
53
+ catch (e) {
54
+ return e.code !== "ESRCH";
55
+ }
56
+ }
57
+ /** The lock's state and the exact text it was judged on. */
58
+ async function heldState(path) {
59
+ let text;
60
+ try {
61
+ text = await retryBusy(() => readFile(path, "utf8"));
62
+ }
63
+ catch (e) {
64
+ if (e.code === "ENOENT")
65
+ return { state: "free" };
66
+ // Still busy after the retries: another process is working on the lock, so it counts as held.
67
+ if (busy(e))
68
+ return { state: "held" };
69
+ throw e;
70
+ }
71
+ const pid = Number.parseInt(text.trim(), 10);
72
+ if (!Number.isInteger(pid) || pid <= 0) {
73
+ try {
74
+ const { mtimeMs } = await stat(path);
75
+ return { state: Date.now() - mtimeMs > STALE_EMPTY_MS ? "stale" : "held", text };
76
+ }
77
+ catch {
78
+ return { state: "free" };
79
+ }
80
+ }
81
+ if (pid === process.pid)
82
+ return { state: "held", text };
83
+ return { state: alive(pid) ? "held" : "stale", text };
84
+ }
85
+ /**
86
+ * Removes a stale lock so that only one process can: the remover first takes
87
+ * `write.lock.takeover` by exclusive create, then re-reads the lock and removes it only while it
88
+ * still holds the same dead text. A second process that judged the same lock stale finds either
89
+ * the guard held or, once it is free, the winner's live lock, and removes nothing. A guard left
90
+ * by a process that died inside this window (milliseconds) is cleared after STALE_EMPTY_MS.
91
+ */
92
+ async function removeStale(path, staleText) {
93
+ const guard = `${path}.takeover`;
94
+ let handle;
95
+ try {
96
+ handle = await open(guard, "wx");
97
+ }
98
+ catch (e) {
99
+ if (busy(e))
100
+ return;
101
+ if (e.code !== "EEXIST")
102
+ throw e;
103
+ try {
104
+ const { mtimeMs } = await stat(guard);
105
+ if (Date.now() - mtimeMs > STALE_EMPTY_MS)
106
+ await unlink(guard);
107
+ }
108
+ catch (err) {
109
+ if (err.code !== "ENOENT")
110
+ throw err;
111
+ }
112
+ return;
113
+ }
114
+ try {
115
+ await handle.writeFile(`${process.pid}\n`);
116
+ await handle.close();
117
+ handle = undefined;
118
+ const now = await heldState(path);
119
+ if (now.state === "stale" && now.text === staleText) {
120
+ try {
121
+ await retryBusy(() => unlink(path));
122
+ }
123
+ catch (e) {
124
+ if (e.code !== "ENOENT" && !busy(e))
125
+ throw e;
126
+ }
127
+ }
128
+ }
129
+ finally {
130
+ await handle?.close();
131
+ await unlink(guard).catch(() => undefined);
132
+ }
133
+ }
134
+ export async function tryAcquireWriteLock(storeDir) {
135
+ await mkdir(storeDir, { recursive: true });
136
+ const path = lockPath(storeDir);
137
+ for (let attempt = 0; attempt < 2; attempt++) {
138
+ try {
139
+ const handle = await retryBusy(() => open(path, "wx"));
140
+ try {
141
+ await handle.writeFile(`${process.pid}\n`);
142
+ }
143
+ finally {
144
+ await handle.close();
145
+ }
146
+ return new WriteLock(path);
147
+ }
148
+ catch (e) {
149
+ if (e.code !== "EEXIST" && !busy(e))
150
+ throw e;
151
+ }
152
+ const { state, text } = await heldState(path);
153
+ if (state === "held")
154
+ return undefined;
155
+ if (state === "stale")
156
+ await removeStale(path, text);
157
+ }
158
+ return undefined;
159
+ }
160
+ export async function acquireWriteLock(storeDir, opts = {}) {
161
+ const timeoutMs = opts.timeoutMs ?? 60_000;
162
+ const pollMs = opts.pollMs ?? 50;
163
+ const deadline = Date.now() + timeoutMs;
164
+ for (;;) {
165
+ const lock = await tryAcquireWriteLock(storeDir);
166
+ if (lock)
167
+ return lock;
168
+ if (Date.now() >= deadline) {
169
+ throw new SearchError("store_locked", `Another process holds the search store write lock at ${lockPath(storeDir)}.`, { details: { path: lockPath(storeDir), timeoutMs } });
170
+ }
171
+ await sleep(pollMs);
172
+ }
173
+ }
174
+ export async function lockHeldByOther(storeDir) {
175
+ return (await heldState(lockPath(storeDir))).state === "held";
176
+ }
@@ -0,0 +1,26 @@
1
+ import type { BuiltFrom, CachedVector, EmbedderRecord, Hit, Row, SourceRow, Store, StoreQuery } from "./store.ts";
2
+ /** An exact in-memory store: flat cosine search, term-count full text. For tests and tiny libraries. */
3
+ export declare class MemoryStore implements Store {
4
+ private rows;
5
+ private built;
6
+ private sourceRows;
7
+ private vectors;
8
+ private record;
9
+ embedder(): Promise<EmbedderRecord | undefined>;
10
+ recordEmbedder(record: EmbedderRecord): Promise<void>;
11
+ upsert(rows: Row[]): Promise<void>;
12
+ remove(keys: string[]): Promise<void>;
13
+ removePaths(tree: string, paths: string[]): Promise<void>;
14
+ query(q: StoreQuery): Promise<Hit[]>;
15
+ recordBuiltFrom(tree: string, built: BuiltFrom): Promise<void>;
16
+ builtFrom(tree: string): Promise<BuiltFrom | undefined>;
17
+ sources(tree: string): Promise<SourceRow[]>;
18
+ putSources(rows: SourceRow[]): Promise<void>;
19
+ removeSources(tree: string, paths: string[]): Promise<void>;
20
+ cachedVectors(embedder: string, keys: {
21
+ sha256: string;
22
+ view: string;
23
+ }[]): Promise<CachedVector[]>;
24
+ cacheVectors(embedder: string, vectors: CachedVector[]): Promise<void>;
25
+ optimize(): Promise<void>;
26
+ }
@@ -0,0 +1,111 @@
1
+ import { cosine } from "./embedder.js";
2
+ import { NUMERIC_FILTER_FIELDS } from "./where.js";
3
+ function matches(row, t) {
4
+ if (t.op === "has")
5
+ return (row.tags ?? []).includes(String(t.value));
6
+ const v = row[t.field];
7
+ if (t.op === "in")
8
+ return v !== undefined && t.value.includes(v);
9
+ if (NUMERIC_FILTER_FIELDS.some((n) => n === t.field) && v === undefined)
10
+ return false;
11
+ switch (t.op) {
12
+ case "=":
13
+ return v === t.value;
14
+ case "!=":
15
+ return v !== t.value;
16
+ case "<":
17
+ return v !== undefined && v < t.value;
18
+ case "<=":
19
+ return v !== undefined && v <= t.value;
20
+ case ">=":
21
+ return v !== undefined && v >= t.value;
22
+ case ">":
23
+ return v !== undefined && v > t.value;
24
+ }
25
+ }
26
+ const words = (s) => s.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
27
+ /** An exact in-memory store: flat cosine search, term-count full text. For tests and tiny libraries. */
28
+ export class MemoryStore {
29
+ rows = new Map();
30
+ built = new Map();
31
+ sourceRows = new Map();
32
+ vectors = new Map();
33
+ record;
34
+ async embedder() {
35
+ return this.record && { ...this.record };
36
+ }
37
+ async recordEmbedder(record) {
38
+ this.record = { ...record };
39
+ }
40
+ async upsert(rows) {
41
+ for (const r of rows)
42
+ this.rows.set(r.key, structuredClone(r));
43
+ }
44
+ async remove(keys) {
45
+ for (const k of keys)
46
+ this.rows.delete(k);
47
+ }
48
+ async removePaths(tree, paths) {
49
+ const gone = new Set(paths);
50
+ for (const [k, r] of this.rows)
51
+ if (r.tree === tree && gone.has(r.path))
52
+ this.rows.delete(k);
53
+ }
54
+ async query(q) {
55
+ const rows = [...this.rows.values()]
56
+ .filter((r) => (q.filter ?? []).every((t) => matches(r, t)))
57
+ .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
58
+ let hits;
59
+ if (q.vector) {
60
+ const { column, value } = q.vector;
61
+ hits = rows.flatMap((row) => {
62
+ const v = row[column];
63
+ return v ? [{ row, score: cosine(v, value) }] : [];
64
+ });
65
+ }
66
+ else if (q.text !== undefined) {
67
+ const terms = words(q.text);
68
+ hits = rows
69
+ .map((row) => {
70
+ const have = words(row.text ?? "");
71
+ return { row, score: terms.filter((t) => have.includes(t)).length / (terms.length || 1) };
72
+ })
73
+ .filter((h) => h.score > 0);
74
+ }
75
+ else {
76
+ hits = rows.map((row) => ({ row, score: 0 }));
77
+ }
78
+ // Array.prototype.sort is stable, so ties keep key order.
79
+ if (q.vector || q.text !== undefined)
80
+ hits.sort((a, b) => b.score - a.score);
81
+ return hits.slice(0, q.limit);
82
+ }
83
+ async recordBuiltFrom(tree, built) {
84
+ this.built.set(tree, built);
85
+ }
86
+ async builtFrom(tree) {
87
+ return this.built.get(tree);
88
+ }
89
+ async sources(tree) {
90
+ return [...this.sourceRows.values()].filter((s) => s.tree === tree).map((s) => ({ ...s }));
91
+ }
92
+ async putSources(rows) {
93
+ for (const r of rows)
94
+ this.sourceRows.set(`${r.tree}\0${r.path}`, { ...r });
95
+ }
96
+ async removeSources(tree, paths) {
97
+ for (const p of paths)
98
+ this.sourceRows.delete(`${tree}\0${p}`);
99
+ }
100
+ async cachedVectors(embedder, keys) {
101
+ return keys.flatMap(({ sha256, view }) => {
102
+ const vec = this.vectors.get(`${embedder}\0${sha256}\0${view}`);
103
+ return vec ? [{ sha256, view, vec }] : [];
104
+ });
105
+ }
106
+ async cacheVectors(embedder, vectors) {
107
+ for (const v of vectors)
108
+ this.vectors.set(`${embedder}\0${v.sha256}\0${v.view}`, v.vec);
109
+ }
110
+ async optimize() { }
111
+ }
@@ -0,0 +1,20 @@
1
+ export interface ModelFile {
2
+ path: string;
3
+ /** Lower-case hex sha256; pinned. */
4
+ sha256: string;
5
+ }
6
+ export interface ModelManifest {
7
+ id: string;
8
+ repo: string;
9
+ /** The Hugging Face commit the weights are pinned to; empty while not pinned. */
10
+ revision: string;
11
+ dimension: number;
12
+ primaryBase: string;
13
+ mirrorBase: string;
14
+ files: ModelFile[];
15
+ }
16
+ export declare const MODEL_MANIFEST: ModelManifest;
17
+ export declare function isPinned(m: ModelManifest): boolean;
18
+ /** Where a file lives on the Hugging Face host and on the mirror (a release's flat assets). */
19
+ export declare function primaryUrl(m: ModelManifest, base: string, file: ModelFile): string;
20
+ export declare function mirrorUrl(base: string, file: ModelFile): string;
@@ -0,0 +1,14 @@
1
+ import manifestJson from "./model-manifest.json" with { type: "json" };
2
+ export const MODEL_MANIFEST = manifestJson;
3
+ export function isPinned(m) {
4
+ return (/^[0-9a-f]{40}$/.test(m.revision) &&
5
+ m.files.length > 0 &&
6
+ m.files.every((f) => /^[0-9a-f]{64}$/.test(f.sha256)));
7
+ }
8
+ /** Where a file lives on the Hugging Face host and on the mirror (a release's flat assets). */
9
+ export function primaryUrl(m, base, file) {
10
+ return `${base}/${m.repo}/resolve/${m.revision}/${file.path}`;
11
+ }
12
+ export function mirrorUrl(base, file) {
13
+ return `${base}/${file.path.replaceAll("/", "__")}`;
14
+ }
@@ -0,0 +1,38 @@
1
+ {
2
+ "id": "siglip2-base",
3
+ "repo": "onnx-community/siglip2-base-patch16-224-ONNX",
4
+ "revision": "ba1f3b0843f24bc5417d38e19c37b287d719b2f4",
5
+ "dimension": 768,
6
+ "primaryBase": "https://huggingface.co",
7
+ "mirrorBase": "https://github.com/clockgrove/assetgrove/releases/download/search-models-siglip2-base",
8
+ "files": [
9
+ {
10
+ "path": "config.json",
11
+ "sha256": "e43a9f7692d3819886a82cb2097048258d444f123c67d37ec825f9345b019cf2"
12
+ },
13
+ {
14
+ "path": "preprocessor_config.json",
15
+ "sha256": "9b36b57ebaf20f09bf4c22100ccc21877ea6bfe5aead0c00c59f8af8ccefacfc"
16
+ },
17
+ {
18
+ "path": "special_tokens_map.json",
19
+ "sha256": "baec30ea10906f16adb8c18af7a34023002c1746542612b8b41c9f09e1351351"
20
+ },
21
+ {
22
+ "path": "tokenizer.json",
23
+ "sha256": "cb9140fae3ac5122c972d37adf83e1248471a38147ad76f8215c8872c6fd8322"
24
+ },
25
+ {
26
+ "path": "tokenizer_config.json",
27
+ "sha256": "7c3a247599e741bceba1a3fe0285aea88d1044dc1fad2caa1e48cdd9fd25f630"
28
+ },
29
+ {
30
+ "path": "onnx/vision_model.onnx",
31
+ "sha256": "c0573e3f4140c3a7c4e9cc5912bd6b26a033b46a6a8e8af26cbea262b163bcad"
32
+ },
33
+ {
34
+ "path": "onnx/text_model_int8.onnx",
35
+ "sha256": "3a0603d3a00c05a80a6ded4743c16aaac7b1e62cdcc7e362e7ce418659b96400"
36
+ }
37
+ ]
38
+ }
@@ -0,0 +1,14 @@
1
+ export interface Member {
2
+ address: string;
3
+ vector: Float32Array;
4
+ }
5
+ export interface RankedMember {
6
+ address: string;
7
+ /** Mean cosine distance to every other member of the set. */
8
+ distance: number;
9
+ }
10
+ /**
11
+ * Every member's mean distance to the rest of the set, most distant first (ties by address), with
12
+ * no cut. A set under three members has no spread and ranks nothing.
13
+ */
14
+ export declare function findOutliers(members: readonly Member[]): RankedMember[];
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Set outliers (design section 7.5, #366): every member of a set gets its mean cosine distance to
3
+ * every other member, and the whole set comes back ranked most distant first, uncut. The distance
4
+ * is a free ranking, never a verdict: it tracks subject and pose as much as style, so core asks a
5
+ * decision call which of the most distant members are drawn in a different style. Free.
6
+ */
7
+ /** A set smaller than this has no spread to rank. */
8
+ const MIN_MEMBERS = 3;
9
+ /** Cosine distance of two vectors, normalised here so a store's scaling never matters. */
10
+ function distance(a, b) {
11
+ let dot = 0;
12
+ let na = 0;
13
+ let nb = 0;
14
+ for (let i = 0; i < a.length; i++) {
15
+ const x = a[i];
16
+ const y = b[i];
17
+ dot += x * y;
18
+ na += x * x;
19
+ nb += y * y;
20
+ }
21
+ const denom = Math.sqrt(na) * Math.sqrt(nb);
22
+ return denom === 0 ? 1 : Math.max(0, 1 - dot / denom);
23
+ }
24
+ /**
25
+ * Every member's mean distance to the rest of the set, most distant first (ties by address), with
26
+ * no cut. A set under three members has no spread and ranks nothing.
27
+ */
28
+ export function findOutliers(members) {
29
+ if (members.length < MIN_MEMBERS)
30
+ return [];
31
+ const sums = members.map(() => 0);
32
+ for (let i = 0; i < members.length; i++)
33
+ for (let j = i + 1; j < members.length; j++) {
34
+ const d = distance(members[i].vector, members[j].vector);
35
+ sums[i] = sums[i] + d;
36
+ sums[j] = sums[j] + d;
37
+ }
38
+ return members
39
+ .map((m, i) => ({ address: m.address, distance: sums[i] / (members.length - 1) }))
40
+ .sort((a, b) => b.distance - a.distance || (a.address < b.address ? -1 : 1));
41
+ }
@@ -0,0 +1,4 @@
1
+ export declare function assertSupportedPlatform(p?: {
2
+ platform: string;
3
+ arch: string;
4
+ }): void;
@@ -0,0 +1,6 @@
1
+ import { SearchError } from "./errors.js";
2
+ export function assertSupportedPlatform(p = { platform: process.platform, arch: process.arch }) {
3
+ if (p.platform === "darwin" && p.arch === "x64") {
4
+ throw new SearchError("extension_unavailable", "Search is unavailable on Intel Macs: neither LanceDB (since 0.23) nor onnxruntime-node builds for darwin-x64.", { details: { reason: "platform", platform: p.platform, arch: p.arch } });
5
+ }
6
+ }
@@ -0,0 +1,20 @@
1
+ import { type Embedder } from "./embedder.ts";
2
+ import type { SearchRouteEmbedder } from "@clockgrove/assetgrove/extension";
3
+ /**
4
+ * Embeds through the provider route core resolved. Built per call: the port differs between a
5
+ * paid run, which carries `embed`, and a read, which does not.
6
+ */
7
+ export declare class RouteEmbedder implements Embedder {
8
+ readonly id = "route";
9
+ /** Every call is a provider call that costs money. */
10
+ readonly paid = true;
11
+ readonly revision: string;
12
+ readonly route: string;
13
+ readonly model: string;
14
+ readonly dimension: number;
15
+ private readonly port;
16
+ constructor(port: SearchRouteEmbedder);
17
+ private embedEach;
18
+ embedImages(images: Uint8Array[]): Promise<Float32Array[]>;
19
+ embedTexts(texts: string[]): Promise<Float32Array[]>;
20
+ }
@@ -0,0 +1,47 @@
1
+ import { normalize } from "./embedder.js";
2
+ import { SearchError } from "./errors.js";
3
+ /**
4
+ * Embeds through the provider route core resolved. Built per call: the port differs between a
5
+ * paid run, which carries `embed`, and a read, which does not.
6
+ */
7
+ export class RouteEmbedder {
8
+ id = "route";
9
+ /** Every call is a provider call that costs money. */
10
+ paid = true;
11
+ revision;
12
+ route;
13
+ model;
14
+ dimension;
15
+ port;
16
+ constructor(port) {
17
+ this.port = port;
18
+ this.route = port.route;
19
+ this.model = port.model;
20
+ // The route is part of the revision, so the vector cache and the table names keep one
21
+ // provider's vectors apart from another's for the same model name.
22
+ this.revision = `${port.route}/${port.model}`;
23
+ this.dimension = port.dimension;
24
+ }
25
+ async embedEach(inputs) {
26
+ if (inputs.length > 0 && !this.port.embed) {
27
+ throw new SearchError("invalid_input", "This needs the hosted embedder, which embeds only in a paid request that was confirmed first.", {
28
+ hint: "Use the find tool (assetgrove find) with words, or search index; both ask before they spend.",
29
+ });
30
+ }
31
+ const out = [];
32
+ for (const input of inputs) {
33
+ const vec = await this.port.embed(input);
34
+ if (vec.length !== this.dimension) {
35
+ throw new SearchError("invalid_input", `The ${this.route} route returned a vector of ${vec.length} numbers; the embedder expects ${this.dimension}.`, { details: { route: this.route, model: this.model, got: vec.length } });
36
+ }
37
+ out.push(normalize(Float32Array.from(vec)));
38
+ }
39
+ return out;
40
+ }
41
+ embedImages(images) {
42
+ return this.embedEach(images.map((image) => ({ image })));
43
+ }
44
+ embedTexts(texts) {
45
+ return this.embedEach(texts.map((text) => ({ text })));
46
+ }
47
+ }
@@ -0,0 +1,15 @@
1
+ import { type Embedder } from "./embedder.ts";
2
+ /**
3
+ * A deterministic embedder for offline tests. Text becomes a bag of hashed words, so texts that
4
+ * share words are close. An image is embedded through its caption: the UTF-8 text of its bytes
5
+ * (tests pass the caption as the "image"), so an image and a text can be made to match.
6
+ */
7
+ export declare class ScriptedEmbedder implements Embedder {
8
+ readonly id = "scripted";
9
+ readonly revision = "1";
10
+ readonly dimension: number;
11
+ constructor(dimension?: number);
12
+ private embedText;
13
+ embedTexts(texts: string[]): Promise<Float32Array[]>;
14
+ embedImages(images: Uint8Array[]): Promise<Float32Array[]>;
15
+ }
@@ -0,0 +1,35 @@
1
+ import { createHash } from "node:crypto";
2
+ import { normalize } from "./embedder.js";
3
+ function hashedVector(seed, dimension, weight, into) {
4
+ const h = createHash("sha256").update(seed).digest();
5
+ const i = h.readUInt32BE(0) % dimension;
6
+ const j = h.readUInt32BE(4) % dimension;
7
+ into[i] = into[i] + weight;
8
+ into[j] = into[j] - weight / 2;
9
+ }
10
+ /**
11
+ * A deterministic embedder for offline tests. Text becomes a bag of hashed words, so texts that
12
+ * share words are close. An image is embedded through its caption: the UTF-8 text of its bytes
13
+ * (tests pass the caption as the "image"), so an image and a text can be made to match.
14
+ */
15
+ export class ScriptedEmbedder {
16
+ id = "scripted";
17
+ revision = "1";
18
+ dimension;
19
+ constructor(dimension = 768) {
20
+ this.dimension = dimension;
21
+ }
22
+ embedText(text) {
23
+ const v = new Float32Array(this.dimension);
24
+ for (const w of text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []) {
25
+ hashedVector(w, this.dimension, 1, v);
26
+ }
27
+ return normalize(v);
28
+ }
29
+ async embedTexts(texts) {
30
+ return texts.map((t) => this.embedText(t));
31
+ }
32
+ async embedImages(images) {
33
+ return images.map((b) => this.embedText(Buffer.from(b).toString("utf8")));
34
+ }
35
+ }
@@ -0,0 +1,26 @@
1
+ import type { SetupContext } from "@clockgrove/assetgrove/extension";
2
+ import { type ModelManifest } from "./model-manifest.ts";
3
+ export interface SetupOptions {
4
+ /** `<stateDir>/models`. */
5
+ modelsDir: string;
6
+ /** Tests point these at loopback servers; the defaults are the manifest's fixed hosts. */
7
+ manifest?: ModelManifest;
8
+ onProgress?: (message: string) => void;
9
+ /**
10
+ * Core's pinned download (`SetupContext.download`, `pinnedDownload`): the only way the package
11
+ * fetches a file. It hashes the bytes before the file is used, deletes it on a mismatch and fails.
12
+ */
13
+ download: SetupContext["download"];
14
+ }
15
+ export declare function modelFolder(modelsDir: string, manifest?: ModelManifest): string;
16
+ /** True when every manifest file is present with its pinned hash. */
17
+ export declare function modelIsInstalled(modelsDir: string, manifest?: ModelManifest): Promise<boolean>;
18
+ /**
19
+ * Every model file in `<modelsDir>/<id>`, each missing one fetched through core's pinned download
20
+ * (`options.download`), pinned to the manifest's revision and sha256: the Hugging Face host first,
21
+ * then the fixed mirror.
22
+ */
23
+ export declare function setupModel(options: SetupOptions): Promise<{
24
+ dir: string;
25
+ }>;
26
+ export declare function exists(path: string): Promise<boolean>;
package/dist/setup.js ADDED
@@ -0,0 +1,60 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFile, stat } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { SearchError } from "./errors.js";
5
+ import { MODEL_MANIFEST, isPinned, mirrorUrl, primaryUrl, } from "./model-manifest.js";
6
+ export function modelFolder(modelsDir, manifest = MODEL_MANIFEST) {
7
+ return join(modelsDir, manifest.id);
8
+ }
9
+ async function sha256File(path) {
10
+ try {
11
+ return createHash("sha256")
12
+ .update(await readFile(path))
13
+ .digest("hex");
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ /** True when every manifest file is present with its pinned hash. */
20
+ export async function modelIsInstalled(modelsDir, manifest = MODEL_MANIFEST) {
21
+ const dir = modelFolder(modelsDir, manifest);
22
+ for (const f of manifest.files) {
23
+ if ((await sha256File(join(dir, f.path))) !== f.sha256)
24
+ return false;
25
+ }
26
+ return true;
27
+ }
28
+ /**
29
+ * Every model file in `<modelsDir>/<id>`, each missing one fetched through core's pinned download
30
+ * (`options.download`), pinned to the manifest's revision and sha256: the Hugging Face host first,
31
+ * then the fixed mirror.
32
+ */
33
+ export async function setupModel(options) {
34
+ const manifest = options.manifest ?? MODEL_MANIFEST;
35
+ const say = options.onProgress ?? (() => { });
36
+ if (!isPinned(manifest)) {
37
+ throw new SearchError("model_unpinned", "The model manifest has no pinned commit or sha256 values; refusing to download unverified weights.", {
38
+ hint: "Run `pnpm pin-model` in packages/assetgrove-search where Hugging Face is reachable.",
39
+ });
40
+ }
41
+ const final = modelFolder(options.modelsDir, manifest);
42
+ for (const file of manifest.files) {
43
+ if ((await sha256File(join(final, file.path))) === file.sha256)
44
+ continue;
45
+ say(file.path);
46
+ await options.download({
47
+ urls: [
48
+ primaryUrl(manifest, manifest.primaryBase, file),
49
+ mirrorUrl(manifest.mirrorBase, file),
50
+ ],
51
+ version: manifest.revision,
52
+ sha256: file.sha256,
53
+ path: `${manifest.id}/${file.path}`,
54
+ });
55
+ }
56
+ return { dir: final };
57
+ }
58
+ export async function exists(path) {
59
+ return stat(path).then(() => true, () => false);
60
+ }
@@ -0,0 +1,6 @@
1
+ import type { Embedder } from "./embedder.ts";
2
+ import { type ModelManifest } from "./model-manifest.ts";
3
+ /** Throws a structured error naming `extensions setup search` when any model file is missing. No network call. */
4
+ export declare function assertModelFiles(modelsDir: string, manifest?: ModelManifest): Promise<string>;
5
+ /** SigLIP2 base patch16-224: image part fp32, text part int8, remote models off. */
6
+ export declare function loadSiglip2(modelsDir: string, manifest?: ModelManifest): Promise<Embedder>;