@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.
- package/LICENSE +21 -0
- package/README.md +12 -2
- package/dist/embedder.d.ts +20 -0
- package/dist/embedder.js +21 -0
- package/dist/errors.d.ts +12 -0
- package/dist/errors.js +12 -0
- package/dist/extension.d.ts +38 -0
- package/dist/extension.js +589 -0
- package/dist/find.d.ts +115 -0
- package/dist/find.js +203 -0
- package/dist/flatten.d.ts +15 -0
- package/dist/flatten.js +19 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +18 -0
- package/dist/indexer.d.ts +48 -0
- package/dist/indexer.js +187 -0
- package/dist/lance-store.d.ts +98 -0
- package/dist/lance-store.js +456 -0
- package/dist/library.d.ts +63 -0
- package/dist/library.js +32 -0
- package/dist/lock.d.ts +11 -0
- package/dist/lock.js +176 -0
- package/dist/memory-store.d.ts +26 -0
- package/dist/memory-store.js +111 -0
- package/dist/model-manifest.d.ts +20 -0
- package/dist/model-manifest.js +14 -0
- package/dist/model-manifest.json +38 -0
- package/dist/outliers.d.ts +14 -0
- package/dist/outliers.js +41 -0
- package/dist/platform.d.ts +4 -0
- package/dist/platform.js +6 -0
- package/dist/route-embedder.d.ts +20 -0
- package/dist/route-embedder.js +47 -0
- package/dist/scripted.d.ts +15 -0
- package/dist/scripted.js +35 -0
- package/dist/setup.d.ts +26 -0
- package/dist/setup.js +60 -0
- package/dist/siglip2.d.ts +6 -0
- package/dist/siglip2.js +84 -0
- package/dist/store.d.ts +129 -0
- package/dist/store.js +2 -0
- package/dist/tokens.d.ts +6 -0
- package/dist/tokens.js +22 -0
- package/dist/where.d.ts +20 -0
- package/dist/where.js +164 -0
- package/package.json +55 -3
- package/skills/assetgrove-search/SKILL.md +41 -0
- package/skills/assetgrove-search/references/commands.md +65 -0
|
@@ -0,0 +1,589 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The search package's entry for core's extension API (design sections 7.1, 7.2 and 7.8): fills
|
|
3
|
+
* the `search` slot over a local index at `<stateDir>/search` and, when settings name one, a
|
|
4
|
+
* shared remote store. LanceDB and Transformers.js load lazily, after the platform check.
|
|
5
|
+
*/
|
|
6
|
+
import { readdir, rm } from "node:fs/promises";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { SearchError } from "./errors.js";
|
|
10
|
+
import { bestViewPerAsset, mergeByScore, rankAcross, rrf, SearchIndex, } from "./find.js";
|
|
11
|
+
import { embedderKey, embedderRecord, pendingWork, refreshTree, } from "./indexer.js";
|
|
12
|
+
import { LanceStore } from "./lance-store.js";
|
|
13
|
+
import { sha256Hex } from "./library.js";
|
|
14
|
+
import { findOutliers } from "./outliers.js";
|
|
15
|
+
import { acquireWriteLock } from "./lock.js";
|
|
16
|
+
import { RouteEmbedder } from "./route-embedder.js";
|
|
17
|
+
import { MODEL_MANIFEST } from "./model-manifest.js";
|
|
18
|
+
import { assertSupportedPlatform } from "./platform.js";
|
|
19
|
+
import { ScriptedEmbedder } from "./scripted.js";
|
|
20
|
+
import { loadSiglip2 } from "./siglip2.js";
|
|
21
|
+
import { modelIsInstalled, setupModel } from "./setup.js";
|
|
22
|
+
import { parseWhere } from "./where.js";
|
|
23
|
+
const embedders = new Map();
|
|
24
|
+
const stores = new Map();
|
|
25
|
+
const modelsDir = (ctx) => join(ctx.stateDir, "models");
|
|
26
|
+
const localDir = (ctx) => join(ctx.stateDir, "search");
|
|
27
|
+
function embedderFor(ctx) {
|
|
28
|
+
if (ctx.settings.embedder === "route") {
|
|
29
|
+
if (!ctx.embedder) {
|
|
30
|
+
return Promise.reject(new SearchError("settings_invalid", 'search.embedder is "route" but no embeddings route resolved.', { hint: "Give the embeddings role a provider and model in the developer settings." }));
|
|
31
|
+
}
|
|
32
|
+
// Never cached: the port differs per call, a paid run's carrying `embed`.
|
|
33
|
+
return Promise.resolve(new RouteEmbedder(ctx.embedder));
|
|
34
|
+
}
|
|
35
|
+
const key = `${ctx.settings.embedder}\0${modelsDir(ctx)}`;
|
|
36
|
+
let p = embedders.get(key);
|
|
37
|
+
if (!p) {
|
|
38
|
+
p =
|
|
39
|
+
ctx.settings.embedder === "scripted"
|
|
40
|
+
? Promise.resolve(new ScriptedEmbedder())
|
|
41
|
+
: loadSiglip2(modelsDir(ctx));
|
|
42
|
+
embedders.set(key, p);
|
|
43
|
+
p.catch(() => embedders.delete(key));
|
|
44
|
+
}
|
|
45
|
+
return p;
|
|
46
|
+
}
|
|
47
|
+
function openCached(key, open) {
|
|
48
|
+
let p = stores.get(key);
|
|
49
|
+
if (!p) {
|
|
50
|
+
p = open();
|
|
51
|
+
stores.set(key, p);
|
|
52
|
+
p.catch(() => stores.delete(key));
|
|
53
|
+
}
|
|
54
|
+
return p;
|
|
55
|
+
}
|
|
56
|
+
async function closeCached(key) {
|
|
57
|
+
const p = stores.get(key);
|
|
58
|
+
stores.delete(key);
|
|
59
|
+
if (p)
|
|
60
|
+
(await p.catch(() => undefined))?.close();
|
|
61
|
+
}
|
|
62
|
+
const sameEmbedder = (a, b) => a.id === b.id && a.revision === b.revision && a.route === b.route && a.model === b.model;
|
|
63
|
+
const embedderLabel = (r) => r.route !== undefined ? `${r.id} ${r.route}/${r.model}` : `${r.id}@${r.revision}`;
|
|
64
|
+
/** One embedder per index: a store built by another embedder is rebuilt, never mixed. */
|
|
65
|
+
async function assertSameEmbedder(store, embedder, where) {
|
|
66
|
+
const built = await store.embedder();
|
|
67
|
+
const current = embedderRecord(embedder);
|
|
68
|
+
if (!built || sameEmbedder(built, current))
|
|
69
|
+
return;
|
|
70
|
+
throw new SearchError("embedder_changed", `The index at ${where} was built by ${embedderLabel(built)} and this request uses ${embedderLabel(current)}. Run \`assetgrove search index --rebuild\` to rebuild it under the new embedder.`, {
|
|
71
|
+
hint: "Run `assetgrove search index --rebuild` to rebuild it under the new embedder.",
|
|
72
|
+
details: { built, current },
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
const remoteWhere = (ctx) => ctx.settings.store.uri;
|
|
76
|
+
/** Per URI scheme, each credential field and the object-store key Lance is handed it under. */
|
|
77
|
+
const CREDENTIAL_KEYS = {
|
|
78
|
+
s3: [
|
|
79
|
+
{ field: "accessKeyId", key: "aws_access_key_id" },
|
|
80
|
+
{ field: "secretAccessKey", key: "aws_secret_access_key" },
|
|
81
|
+
{ field: "sessionToken", key: "aws_session_token", optional: true },
|
|
82
|
+
],
|
|
83
|
+
gs: [{ field: "serviceAccountKey", key: "google_service_account_key" }],
|
|
84
|
+
az: [
|
|
85
|
+
{ field: "accountName", key: "azure_storage_account_name" },
|
|
86
|
+
{ field: "accountKey", key: "azure_storage_account_key" },
|
|
87
|
+
],
|
|
88
|
+
};
|
|
89
|
+
const settingsError = (message, details) => new SearchError("settings_invalid", message, {
|
|
90
|
+
details,
|
|
91
|
+
hint: "Set the variables search.store.credentialsEnv names in the developer settings.",
|
|
92
|
+
});
|
|
93
|
+
/**
|
|
94
|
+
* The storage options Lance is given: the settings' endpoint and region, and the credentials the
|
|
95
|
+
* settings name, under the keys the URI's scheme reads. A remote store is never opened without
|
|
96
|
+
* them, so the object store never authenticates with credentials it finds on the machine.
|
|
97
|
+
*/
|
|
98
|
+
export function storageOptions(store, env) {
|
|
99
|
+
const out = {};
|
|
100
|
+
if (store.options.endpoint !== undefined)
|
|
101
|
+
out.endpoint = store.options.endpoint;
|
|
102
|
+
if (store.options.region !== undefined)
|
|
103
|
+
out.region = store.options.region;
|
|
104
|
+
const scheme = store.uri.slice(0, store.uri.indexOf(":"));
|
|
105
|
+
const keys = CREDENTIAL_KEYS[scheme];
|
|
106
|
+
const names = store.credentialsEnv ?? {};
|
|
107
|
+
if (keys === undefined) {
|
|
108
|
+
throw settingsError(`A ${scheme}:// store is not one search.store accepts.`, { scheme });
|
|
109
|
+
}
|
|
110
|
+
for (const { field, key, optional } of keys) {
|
|
111
|
+
const name = names[field];
|
|
112
|
+
if (name === undefined) {
|
|
113
|
+
if (optional)
|
|
114
|
+
continue;
|
|
115
|
+
throw settingsError(`search.store.credentialsEnv names no ${field} variable; a ${scheme}:// store is never opened without explicit credentials.`, { field });
|
|
116
|
+
}
|
|
117
|
+
const v = env[name];
|
|
118
|
+
if (v === undefined || v === "") {
|
|
119
|
+
throw settingsError(`The store credential variable ${name} is not set in the environment.`, {
|
|
120
|
+
variable: name,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
out[key] = v;
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
const remoteKey = (uri, embedder) => `remote\0${uri}\0${embedder.id}@${embedder.revision}`;
|
|
128
|
+
function openRemote(ctx, embedder) {
|
|
129
|
+
const store = ctx.settings.store;
|
|
130
|
+
const isFile = store.uri.startsWith("file://");
|
|
131
|
+
return openCached(remoteKey(store.uri, embedder), () => LanceStore.open(isFile ? fileURLToPath(store.uri) : store.uri, {
|
|
132
|
+
embedder,
|
|
133
|
+
...(!isFile && { storageOptions: storageOptions(store, ctx.env), remote: true }),
|
|
134
|
+
}));
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* A shared index's tree key: the game id and the repository's root commits, so clones of one
|
|
138
|
+
* repository share rows on every machine while two repositories with the same game id never do.
|
|
139
|
+
*/
|
|
140
|
+
async function sharedTree(ctx) {
|
|
141
|
+
const origin = await ctx.library.origin();
|
|
142
|
+
if (origin === "") {
|
|
143
|
+
throw new SearchError("invalid_input", "A shared index needs the repository's root commit, and this work tree has none (outside Git, before the first commit, or a shallow clone).", {
|
|
144
|
+
hint: "Use a full clone with at least one commit, or drop search.store from the settings.",
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
return sha256Hex(`game:${ctx.game}\0origin:${origin}`);
|
|
148
|
+
}
|
|
149
|
+
const remoteLockDir = (ctx, uri) => join(localDir(ctx), "remote", sha256Hex(uri));
|
|
150
|
+
function adapt(lib, sources, candidates = true) {
|
|
151
|
+
const adapted = {
|
|
152
|
+
async list() {
|
|
153
|
+
const items = await lib.list(sources);
|
|
154
|
+
return candidates ? items : items.filter((i) => i.source !== "candidate");
|
|
155
|
+
},
|
|
156
|
+
load: (item) => lib.load(item),
|
|
157
|
+
head: () => lib.head(),
|
|
158
|
+
};
|
|
159
|
+
return adapted;
|
|
160
|
+
}
|
|
161
|
+
const REMOTE_SOURCES = ["pick", "reference"];
|
|
162
|
+
const LOCAL_WITH_REMOTE = ["candidate", "folder"];
|
|
163
|
+
const localLibrary = (ctx) => adapt(ctx.library, ctx.settings.store ? LOCAL_WITH_REMOTE : undefined, ctx.settings.candidates);
|
|
164
|
+
async function localIndex(ctx, embedder) {
|
|
165
|
+
const dir = localDir(ctx);
|
|
166
|
+
const store = await openCached(`local\0${dir}\0${embedder.id}@${embedder.revision}`, () => LanceStore.open(dir, { embedder }));
|
|
167
|
+
return SearchIndex.open({
|
|
168
|
+
dir,
|
|
169
|
+
embedder,
|
|
170
|
+
store,
|
|
171
|
+
worktree: ctx.worktree,
|
|
172
|
+
library: localLibrary(ctx),
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Whether a shared store is fresh for this work tree: built at its HEAD, or at a commit since which
|
|
177
|
+
* nothing it covers (the library root, the bible and its references) changed. A library that
|
|
178
|
+
* cannot answer `changedSince` leaves it fresh only at its build commit.
|
|
179
|
+
*/
|
|
180
|
+
async function sharedFresh(built, head, changedSince) {
|
|
181
|
+
if (built === undefined)
|
|
182
|
+
return false;
|
|
183
|
+
if (head !== undefined && built.head === (await head()))
|
|
184
|
+
return true;
|
|
185
|
+
return changedSince !== undefined && !(await changedSince(built.head));
|
|
186
|
+
}
|
|
187
|
+
const changedSinceOf = (library) => library.changedSince && ((commit) => library.changedSince(commit));
|
|
188
|
+
const toHit = ({ row, score }, i) => {
|
|
189
|
+
const defined = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
190
|
+
return {
|
|
191
|
+
address: row.address,
|
|
192
|
+
rank: i + 1,
|
|
193
|
+
score,
|
|
194
|
+
source: row.source,
|
|
195
|
+
path: row.path,
|
|
196
|
+
view: row.view ?? "",
|
|
197
|
+
fields: defined({
|
|
198
|
+
game: row.game,
|
|
199
|
+
kind: row.kind,
|
|
200
|
+
subject: row.subject,
|
|
201
|
+
tags: row.tags,
|
|
202
|
+
state: row.state,
|
|
203
|
+
bible: row.bible,
|
|
204
|
+
license: row.license,
|
|
205
|
+
origin: row.origin,
|
|
206
|
+
declaredOrigin: row.declaredOrigin,
|
|
207
|
+
originEvidence: row.originEvidence,
|
|
208
|
+
originSource: row.originSource,
|
|
209
|
+
originLicense: row.originLicense,
|
|
210
|
+
digitalSourceType: row.digitalSourceType,
|
|
211
|
+
width: row.width,
|
|
212
|
+
height: row.height,
|
|
213
|
+
durationS: row.durationS,
|
|
214
|
+
form: row.form,
|
|
215
|
+
tempo: row.tempo,
|
|
216
|
+
mediaType: row.mediaType,
|
|
217
|
+
mediaSha256: row.mediaSha256,
|
|
218
|
+
mediaStatus: row.mediaStatus,
|
|
219
|
+
mediaReason: row.mediaReason,
|
|
220
|
+
}),
|
|
221
|
+
sharedText: defined({ title: row.title, description: row.description, text: row.text }),
|
|
222
|
+
};
|
|
223
|
+
};
|
|
224
|
+
async function likeVector(like, embedder, searched, storedOnly = false) {
|
|
225
|
+
if ("image" in like && storedOnly) {
|
|
226
|
+
// A hosted embedder without its paid-run port: only an image already indexed has a vector.
|
|
227
|
+
const sha256 = sha256Hex(like.image);
|
|
228
|
+
for (const store of searched) {
|
|
229
|
+
const [cached] = await store.cachedVectors(embedderKey(embedder), [{ sha256, view: "" }]);
|
|
230
|
+
if (cached)
|
|
231
|
+
return cached.vec;
|
|
232
|
+
}
|
|
233
|
+
throw new SearchError("invalid_input", "This image is not in the index, and the hosted embedder embeds only in a paid request.", {
|
|
234
|
+
details: { sha256, reason: "not_indexed" },
|
|
235
|
+
hint: "Use the find tool (assetgrove find --like <file>), which asks before it spends.",
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
if ("image" in like)
|
|
239
|
+
return (await embedder.embedImages([like.image]))[0];
|
|
240
|
+
for (const store of searched) {
|
|
241
|
+
const found = await store.query({
|
|
242
|
+
filter: [{ field: "address", op: "=", value: like.address }],
|
|
243
|
+
limit: 50,
|
|
244
|
+
});
|
|
245
|
+
const vec = found.find((h) => h.row.imageVec)?.row.imageVec;
|
|
246
|
+
if (vec)
|
|
247
|
+
return vec;
|
|
248
|
+
}
|
|
249
|
+
throw new SearchError("invalid_input", `No indexed image for ${like.address}.`, {
|
|
250
|
+
details: { address: like.address },
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
/** The shipped find over an open local index and, when shared, the remote store: what `searchSlot.find` runs once settings name the embedder and stores. */
|
|
254
|
+
export async function findWith(q, o) {
|
|
255
|
+
const { embedder, local, remote } = o;
|
|
256
|
+
const terms = parseWhere(q.where ?? []);
|
|
257
|
+
const sources = q.sources ?? [];
|
|
258
|
+
// The requested sources filter in the store, so every ranking's pool is drawn from them.
|
|
259
|
+
if (sources.length === 1) {
|
|
260
|
+
terms.push({ field: "source", op: "=", value: sources[0] });
|
|
261
|
+
}
|
|
262
|
+
else if (sources.length > 1) {
|
|
263
|
+
terms.push({ field: "source", op: "in", value: [...sources] });
|
|
264
|
+
}
|
|
265
|
+
const scopes = [{ store: local.store, tree: local.tree }];
|
|
266
|
+
if (remote)
|
|
267
|
+
scopes.push({ store: remote.store, tree: remote.tree });
|
|
268
|
+
const inScope = (f, tree) => q.allGames ? f : [...f, { field: "tree", op: "=", value: tree }];
|
|
269
|
+
const refreshed = o.spends ? false : (await local.refresh()).fresh;
|
|
270
|
+
const words = q.words?.trim() ?? "";
|
|
271
|
+
const vectors = {};
|
|
272
|
+
if (words !== "")
|
|
273
|
+
vectors.words = (await embedder.embedTexts([words]))[0];
|
|
274
|
+
if (q.like) {
|
|
275
|
+
vectors.like = await likeVector(q.like, embedder, remote ? [local.store, remote.store] : [local.store], o.spends);
|
|
276
|
+
}
|
|
277
|
+
const searched = scopes.map(({ store, tree }) => ({ store, filter: inScope(terms, tree) }));
|
|
278
|
+
const ranked = await rankAcross(searched, q, vectors);
|
|
279
|
+
const hits = bestViewPerAsset(ranked).slice(0, q.limit).map(toHit);
|
|
280
|
+
if (!remote) {
|
|
281
|
+
return { hits, fresh: refreshed, builtFrom: (await local.store.builtFrom(local.tree)) ?? null };
|
|
282
|
+
}
|
|
283
|
+
const built = await remote.store.builtFrom(remote.tree);
|
|
284
|
+
const fresh = refreshed && (await sharedFresh(built, o.head, o.changedSince));
|
|
285
|
+
return { hits, fresh, builtFrom: built ?? null };
|
|
286
|
+
}
|
|
287
|
+
async function find(q, ctx) {
|
|
288
|
+
const embedder = await embedderFor(ctx);
|
|
289
|
+
const local = await localIndex(ctx, embedder);
|
|
290
|
+
const remote = ctx.settings.store ? await openRemote(ctx, embedder) : undefined;
|
|
291
|
+
await assertSameEmbedder(local.store, embedder, localDir(ctx));
|
|
292
|
+
if (remote)
|
|
293
|
+
await assertSameEmbedder(remote, embedder, remoteWhere(ctx));
|
|
294
|
+
// A hosted embedder spends, so without its paid-run port a read answers from stored vectors.
|
|
295
|
+
const spends = ctx.settings.embedder === "route" && !ctx.embedder?.embed;
|
|
296
|
+
return findWith(q, {
|
|
297
|
+
embedder,
|
|
298
|
+
local,
|
|
299
|
+
remote: remote && { store: remote, tree: await sharedTree(ctx) },
|
|
300
|
+
spends,
|
|
301
|
+
head: () => ctx.library.head(),
|
|
302
|
+
changedSince: changedSinceOf(ctx.library),
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
/** Every member of a set of asset addresses ranked by its indexed image vector, uncut (design 7.5). */
|
|
306
|
+
async function outliers(addresses, ctx) {
|
|
307
|
+
const embedder = await embedderFor(ctx);
|
|
308
|
+
const local = await localIndex(ctx, embedder);
|
|
309
|
+
await assertSameEmbedder(local.store, embedder, localDir(ctx));
|
|
310
|
+
// Pick and reference rows live in the shared store when one is set (design 7.8): look in both,
|
|
311
|
+
// and refuse either when another embedder built it (design 7.7).
|
|
312
|
+
const stores = [{ store: local.store, tree: local.tree }];
|
|
313
|
+
if (ctx.settings.store) {
|
|
314
|
+
const remote = await openRemote(ctx, embedder);
|
|
315
|
+
await assertSameEmbedder(remote, embedder, remoteWhere(ctx));
|
|
316
|
+
stores.push({ store: remote, tree: await sharedTree(ctx) });
|
|
317
|
+
}
|
|
318
|
+
// The ranking is free and a read (design 7.5): it ranks the vectors already stored and refreshes
|
|
319
|
+
// nothing, under every embedder, so a plan step or `estimate` writes no index. A member not yet
|
|
320
|
+
// indexed is not ranked; `search index` brings the index up to date.
|
|
321
|
+
const members = [];
|
|
322
|
+
for (const address of new Set(addresses)) {
|
|
323
|
+
for (const { store, tree } of stores) {
|
|
324
|
+
const found = await store.query({
|
|
325
|
+
filter: [
|
|
326
|
+
{ field: "tree", op: "=", value: tree },
|
|
327
|
+
{ field: "address", op: "=", value: address },
|
|
328
|
+
],
|
|
329
|
+
limit: 50,
|
|
330
|
+
});
|
|
331
|
+
const vector = found.find((h) => h.row.imageVec)?.row.imageVec;
|
|
332
|
+
if (vector) {
|
|
333
|
+
members.push({ address, vector });
|
|
334
|
+
break;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return { members: members.length, ranking: findOutliers(members) };
|
|
339
|
+
}
|
|
340
|
+
async function index(options, ctx) {
|
|
341
|
+
const embedder = await embedderFor(ctx);
|
|
342
|
+
const remoteSettings = ctx.settings.store;
|
|
343
|
+
if (remoteSettings?.writer && !(await ctx.library.clean())) {
|
|
344
|
+
throw new SearchError("invalid_input", "The shared index is built from a clean HEAD, but there are uncommitted changes under the library root.", { hint: "Commit or stash the changes, then run `assetgrove search index` again." });
|
|
345
|
+
}
|
|
346
|
+
if (options.rebuild) {
|
|
347
|
+
await closeCached(`local\0${localDir(ctx)}\0${embedder.id}@${embedder.revision}`);
|
|
348
|
+
const dir = localDir(ctx);
|
|
349
|
+
const names = await readdir(dir).catch(() => []);
|
|
350
|
+
// With a hosted embedder, `vectors.lance` (the content cache, keyed by embedder) survives, so
|
|
351
|
+
// a rebuild pays nothing twice for content it holds. The local model's rebuild deletes every
|
|
352
|
+
// table and embeds afresh, as it always has.
|
|
353
|
+
const keep = ctx.settings.embedder === "route" ? "vectors.lance" : undefined;
|
|
354
|
+
for (const n of names.filter((n) => n.endsWith(".lance") && n !== keep)) {
|
|
355
|
+
await rm(join(dir, n), { recursive: true, force: true });
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
const local = await localIndex(ctx, embedder);
|
|
359
|
+
if (!options.rebuild)
|
|
360
|
+
await assertSameEmbedder(local.store, embedder, localDir(ctx));
|
|
361
|
+
// A rebuild records its embedder under the write lock, before its refresh (design 7.3).
|
|
362
|
+
const recordUnderLock = options.rebuild
|
|
363
|
+
? { before: (store) => store.recordEmbedder(embedderRecord(embedder)) }
|
|
364
|
+
: {};
|
|
365
|
+
const result = { local: await local.index(recordUnderLock) };
|
|
366
|
+
if (!remoteSettings)
|
|
367
|
+
return result;
|
|
368
|
+
if (!remoteSettings.writer) {
|
|
369
|
+
return { ...result, remote: { written: false, reason: "writer false" } };
|
|
370
|
+
}
|
|
371
|
+
const remote = await openRemote(ctx, embedder);
|
|
372
|
+
const tree = await sharedTree(ctx);
|
|
373
|
+
if (!options.rebuild)
|
|
374
|
+
await assertSameEmbedder(remote, embedder, remoteSettings.uri);
|
|
375
|
+
const lock = await acquireWriteLock(remoteLockDir(ctx, remoteSettings.uri));
|
|
376
|
+
try {
|
|
377
|
+
if (options.rebuild)
|
|
378
|
+
await remote.recordEmbedder(embedderRecord(embedder));
|
|
379
|
+
const stats = await refreshTree({
|
|
380
|
+
store: remote,
|
|
381
|
+
embedder,
|
|
382
|
+
library: adapt(ctx.library, REMOTE_SOURCES),
|
|
383
|
+
tree,
|
|
384
|
+
});
|
|
385
|
+
const built = { head: await ctx.library.head(), at: new Date().toISOString() };
|
|
386
|
+
await remote.recordBuiltFrom(tree, built);
|
|
387
|
+
await remote.optimize();
|
|
388
|
+
result.remote = { written: true, uri: remoteSettings.uri, stats, builtFrom: built };
|
|
389
|
+
}
|
|
390
|
+
finally {
|
|
391
|
+
await lock.release();
|
|
392
|
+
}
|
|
393
|
+
return result;
|
|
394
|
+
}
|
|
395
|
+
async function status(ctx) {
|
|
396
|
+
const embedder = await embedderStatus(ctx);
|
|
397
|
+
const out = {
|
|
398
|
+
store: localDir(ctx),
|
|
399
|
+
embedder,
|
|
400
|
+
model: {
|
|
401
|
+
installed: ctx.settings.embedder === "local" ? await modelIsInstalled(modelsDir(ctx)) : true,
|
|
402
|
+
},
|
|
403
|
+
};
|
|
404
|
+
if (ctx.settings.embedder === "local" && !out.model.installed) {
|
|
405
|
+
return out;
|
|
406
|
+
}
|
|
407
|
+
const real = await embedderFor(ctx);
|
|
408
|
+
const local = await localIndex(ctx, real);
|
|
409
|
+
out.recordedEmbedder = (await local.store.embedder()) ?? null;
|
|
410
|
+
out.files = (await local.store.sources(local.tree)).length;
|
|
411
|
+
out.builtFrom = (await local.store.builtFrom(local.tree)) ?? null;
|
|
412
|
+
const remoteSettings = ctx.settings.store;
|
|
413
|
+
if (remoteSettings) {
|
|
414
|
+
const remote = await openRemote(ctx, real);
|
|
415
|
+
const built = (await remote.builtFrom(await sharedTree(ctx))) ?? null;
|
|
416
|
+
out.remote = {
|
|
417
|
+
uri: remoteSettings.uri,
|
|
418
|
+
writer: remoteSettings.writer,
|
|
419
|
+
recordedEmbedder: (await remote.embedder()) ?? null,
|
|
420
|
+
builtFrom: built,
|
|
421
|
+
fresh: await sharedFresh(built ?? undefined, () => ctx.library.head(), changedSinceOf(ctx.library)),
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
return out;
|
|
425
|
+
}
|
|
426
|
+
/** The embedder's identity without loading a model. */
|
|
427
|
+
async function embedderStatus(ctx) {
|
|
428
|
+
if (ctx.settings.embedder === "scripted") {
|
|
429
|
+
const { id, revision } = new ScriptedEmbedder();
|
|
430
|
+
return { id, revision };
|
|
431
|
+
}
|
|
432
|
+
if (ctx.settings.embedder === "route") {
|
|
433
|
+
const { id, revision, route, model } = await embedderFor(ctx);
|
|
434
|
+
return { id, revision, route, model };
|
|
435
|
+
}
|
|
436
|
+
return { id: MODEL_MANIFEST.id, revision: MODEL_MANIFEST.revision };
|
|
437
|
+
}
|
|
438
|
+
async function setup(ctx) {
|
|
439
|
+
if (ctx.search.embedder === "scripted")
|
|
440
|
+
return { model: "scripted", installed: true };
|
|
441
|
+
if (ctx.search.embedder === "route")
|
|
442
|
+
return { model: "route", installed: true };
|
|
443
|
+
const { dir } = await setupModel({
|
|
444
|
+
modelsDir: ctx.dir,
|
|
445
|
+
download: ctx.download,
|
|
446
|
+
onProgress: ctx.log,
|
|
447
|
+
});
|
|
448
|
+
return { dir, model: MODEL_MANIFEST.id, installed: true };
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* The picked assets closest to the request, by rank: its kind, subject and brief as words, fused
|
|
452
|
+
* with image similarity to its references. Only the kind filters; no similarity cut applies. When
|
|
453
|
+
* the embedder is paid nothing is embedded, neither the request nor unindexed library files: the
|
|
454
|
+
* index is searched as it stands, by full text and stored vectors only, and reported not fresh.
|
|
455
|
+
*/
|
|
456
|
+
export async function nearMatchesWith(q, ctx, options) {
|
|
457
|
+
const embedder = await embedderFor(ctx);
|
|
458
|
+
const local = await localIndex(ctx, embedder);
|
|
459
|
+
const remote = ctx.settings.store ? await openRemote(ctx, embedder) : undefined;
|
|
460
|
+
// One embedder per index (design 7.7): an index another embedder built is refused, and the plan
|
|
461
|
+
// step records the refusal as its searchError (design 7.6).
|
|
462
|
+
await assertSameEmbedder(local.store, embedder, localDir(ctx));
|
|
463
|
+
if (remote)
|
|
464
|
+
await assertSameEmbedder(remote, embedder, remoteWhere(ctx));
|
|
465
|
+
// Refreshing embeds every library file not yet indexed: a paid call before the person confirms
|
|
466
|
+
// spend. Under a paid embedder the index is searched as it stands and reported as not fresh.
|
|
467
|
+
const refreshed = options.paid ? false : (await local.refresh()).fresh;
|
|
468
|
+
const filter = [
|
|
469
|
+
{ field: "source", op: "=", value: "pick" },
|
|
470
|
+
{ field: "kind", op: "=", value: q.kind },
|
|
471
|
+
];
|
|
472
|
+
const words = [q.kind, q.subject, q.brief]
|
|
473
|
+
.map((w) => w?.trim() ?? "")
|
|
474
|
+
.filter((w) => w !== "")
|
|
475
|
+
.join(" ");
|
|
476
|
+
const searched = [{ store: local.store, tree: local.tree }];
|
|
477
|
+
if (remote)
|
|
478
|
+
searched.push({ store: remote, tree: await sharedTree(ctx) });
|
|
479
|
+
const wordVec = !options.paid && words !== "" ? (await embedder.embedTexts([words]))[0] : undefined;
|
|
480
|
+
const refVecs = [];
|
|
481
|
+
if (!options.paid) {
|
|
482
|
+
if (q.references.length > 0)
|
|
483
|
+
refVecs.push(...(await embedder.embedImages(q.references)));
|
|
484
|
+
}
|
|
485
|
+
else {
|
|
486
|
+
for (const bytes of q.references) {
|
|
487
|
+
const sha256 = sha256Hex(bytes);
|
|
488
|
+
for (const { store, tree } of searched) {
|
|
489
|
+
const found = await store.query({
|
|
490
|
+
filter: [
|
|
491
|
+
{ field: "tree", op: "=", value: tree },
|
|
492
|
+
{ field: "sha256", op: "=", value: sha256 },
|
|
493
|
+
],
|
|
494
|
+
limit: 50,
|
|
495
|
+
});
|
|
496
|
+
const vec = found.find((h) => h.row.imageVec)?.row.imageVec;
|
|
497
|
+
if (vec) {
|
|
498
|
+
refVecs.push(vec);
|
|
499
|
+
break;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
const pool = Math.max(20 * q.limit, 100);
|
|
505
|
+
const within = (tree) => [
|
|
506
|
+
...filter,
|
|
507
|
+
{ field: "tree", op: "=", value: tree },
|
|
508
|
+
];
|
|
509
|
+
const across = async (query) => mergeByScore(await Promise.all(searched.map(({ store, tree }) => store.query({ ...query, filter: within(tree) }))));
|
|
510
|
+
// The words fuse as `find` fuses them into one ranking; each reference adds one image ranking.
|
|
511
|
+
const wordLists = [];
|
|
512
|
+
if (words !== "")
|
|
513
|
+
wordLists.push(across({ text: words, limit: pool }));
|
|
514
|
+
if (wordVec) {
|
|
515
|
+
wordLists.push(across({ vector: { column: "imageVec", value: wordVec }, limit: pool }), across({ vector: { column: "textVec", value: wordVec }, limit: pool }));
|
|
516
|
+
}
|
|
517
|
+
const lists = [rrf(await Promise.all(wordLists))];
|
|
518
|
+
for (const value of refVecs) {
|
|
519
|
+
lists.push(await across({ vector: { column: "imageVec", value }, limit: pool }));
|
|
520
|
+
}
|
|
521
|
+
const ranked = rrf(lists);
|
|
522
|
+
const hits = bestViewPerAsset(ranked).slice(0, q.limit).map(toHit);
|
|
523
|
+
if (!remote) {
|
|
524
|
+
return { hits, fresh: refreshed, builtFrom: (await local.store.builtFrom(local.tree)) ?? null };
|
|
525
|
+
}
|
|
526
|
+
const built = await remote.builtFrom(await sharedTree(ctx));
|
|
527
|
+
const fresh = refreshed && (await sharedFresh(built, () => ctx.library.head(), changedSinceOf(ctx.library)));
|
|
528
|
+
return { hits, fresh, builtFrom: built ?? null };
|
|
529
|
+
}
|
|
530
|
+
const nearMatch = async (q, ctx) => nearMatchesWith(q, ctx, { paid: (await embedderFor(ctx)).paid === true });
|
|
531
|
+
const sumPending = (a, b) => ({
|
|
532
|
+
images: a.images + b.images,
|
|
533
|
+
texts: a.texts + b.texts,
|
|
534
|
+
fingerprint: `${a.fingerprint}${b.fingerprint}`,
|
|
535
|
+
});
|
|
536
|
+
/** What a request would embed, counted without embedding, writing or calling the port. */
|
|
537
|
+
async function forecast(request, ctx) {
|
|
538
|
+
const embedder = await embedderFor(ctx);
|
|
539
|
+
const rebuild = "index" in request ? request.index.rebuild === true : false;
|
|
540
|
+
const local = await localIndex(ctx, embedder);
|
|
541
|
+
if (!rebuild)
|
|
542
|
+
await assertSameEmbedder(local.store, embedder, localDir(ctx));
|
|
543
|
+
let pending = await pendingWork({
|
|
544
|
+
store: local.store,
|
|
545
|
+
embedder,
|
|
546
|
+
library: localLibrary(ctx),
|
|
547
|
+
tree: local.tree,
|
|
548
|
+
rebuild,
|
|
549
|
+
});
|
|
550
|
+
let queries = 0;
|
|
551
|
+
let query = "";
|
|
552
|
+
if ("index" in request) {
|
|
553
|
+
const remoteSettings = ctx.settings.store;
|
|
554
|
+
if (remoteSettings?.writer) {
|
|
555
|
+
const remote = await openRemote(ctx, embedder);
|
|
556
|
+
if (!rebuild)
|
|
557
|
+
await assertSameEmbedder(remote, embedder, remoteSettings.uri);
|
|
558
|
+
pending = sumPending(pending, await pendingWork({
|
|
559
|
+
store: remote,
|
|
560
|
+
embedder,
|
|
561
|
+
library: adapt(ctx.library, REMOTE_SOURCES),
|
|
562
|
+
tree: await sharedTree(ctx),
|
|
563
|
+
}));
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
else {
|
|
567
|
+
const q = request.find;
|
|
568
|
+
if (ctx.settings.store) {
|
|
569
|
+
await assertSameEmbedder(await openRemote(ctx, embedder), embedder, remoteWhere(ctx));
|
|
570
|
+
}
|
|
571
|
+
const words = q.words?.trim() ?? "";
|
|
572
|
+
if (words !== "")
|
|
573
|
+
queries++;
|
|
574
|
+
if (q.like && "image" in q.like)
|
|
575
|
+
queries++;
|
|
576
|
+
query = JSON.stringify({
|
|
577
|
+
words,
|
|
578
|
+
like: q.like && ("image" in q.like ? sha256Hex(q.like.image) : q.like.address),
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
const state = sha256Hex(JSON.stringify({ pending: pending.fingerprint, query }));
|
|
582
|
+
return { images: pending.images, texts: pending.texts, queries, state };
|
|
583
|
+
}
|
|
584
|
+
export const searchSlot = { find, outliers, index, status, nearMatch, forecast };
|
|
585
|
+
/** Core's entry: refuses on darwin-x64 before LanceDB or Transformers.js is imported. */
|
|
586
|
+
export default function searchExtension(context) {
|
|
587
|
+
assertSupportedPlatform();
|
|
588
|
+
return { api: context.api, name: "search", search: searchSlot, setup };
|
|
589
|
+
}
|