tr-plugin-embeddings 0.1.0 → 0.2.5
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/DESIGN.md +110 -0
- package/README.md +20 -2
- package/cli.mjs +403 -173
- package/package.json +14 -5
- package/plugin.json +51 -10
- package/skills/embeddings/SKILL.md +25 -0
- package/ui/chunks/benchmark.md +49 -0
- package/ui/chunks/coverage.md +53 -0
- package/ui/chunks/models.md +43 -0
- package/ui/chunks/pull.md +41 -0
- package/ui/chunks/status.md +59 -0
- package/ui/home.js +353 -0
- package/ui/card.js +0 -414
package/cli.mjs
CHANGED
|
@@ -4,20 +4,37 @@
|
|
|
4
4
|
* Executed via: npx total-recall embeddings <subcommand>
|
|
5
5
|
*
|
|
6
6
|
* Owns local embedding provider discovery and index coverage for a brain:
|
|
7
|
-
* which provider/model actually serves vectors, whether that
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
7
|
+
* which provider/model actually serves vectors, whether that endpoint is on
|
|
8
|
+
* this host, and how much of the vault has a vector core can still use.
|
|
9
|
+
* Building the index itself stays with `total-recall compile`, which owns the
|
|
10
|
+
* embeddings.db lifecycle; this plugin only ever opens it read-only.
|
|
11
|
+
*
|
|
12
|
+
* The selection and coverage rules mirror total-recall-brain core
|
|
13
|
+
* (src/core/ollama-embeddings.mjs, vault.mjs, embeddings.mjs). Core is not
|
|
14
|
+
* imported: its logger loads config.mjs, which loads the auth owner, and a
|
|
15
|
+
* read-only status must not unlock credentials. See the EMBEDDINGS_CARD
|
|
16
|
+
* architecture decision of 2026-11-05.
|
|
11
17
|
*/
|
|
12
18
|
import fs from 'node:fs';
|
|
13
19
|
import path from 'node:path';
|
|
14
|
-
import
|
|
20
|
+
import crypto from 'node:crypto';
|
|
15
21
|
|
|
16
22
|
const PLUGIN_ID = 'embeddings';
|
|
17
23
|
const PLUGIN_DIR = path.dirname(new URL(import.meta.url).pathname);
|
|
18
24
|
const PLUGIN_VERSION = JSON.parse(fs.readFileSync(path.join(PLUGIN_DIR, 'plugin.json'), 'utf8')).version;
|
|
19
|
-
const
|
|
20
|
-
|
|
25
|
+
const LOOPBACK_URL = 'http://127.0.0.1:11434';
|
|
26
|
+
// The vault index width (core embeddings.mjs EMBEDDING_DIMS). It is a storage
|
|
27
|
+
// constraint of the vss0 table, so a model of any other width is unusable.
|
|
28
|
+
const VAULT_DIMS = 768;
|
|
29
|
+
const PROBE_TIMEOUT_MS = 2500;
|
|
30
|
+
const SHOW_TIMEOUT_MS = 5000;
|
|
31
|
+
const EMBED_TIMEOUT_MS = 30000;
|
|
32
|
+
// The host runner kills a child at the manifest's timeout_ms; stay under it.
|
|
33
|
+
const PULL_DEADLINE_MS = 590000;
|
|
34
|
+
const BENCHMARK_DEADLINE_MS = 280000;
|
|
35
|
+
const BENCHMARK_MAX_SAMPLES = 20;
|
|
36
|
+
// Neutral benchmark input: never vault text, never a real contact.
|
|
37
|
+
const BENCHMARK_TEXT = 'The quick brown fox jumps over the lazy dog while the kettle boils.';
|
|
21
38
|
|
|
22
39
|
/** The brain this invocation targets: project brain when present, else global. */
|
|
23
40
|
function resolveVault() {
|
|
@@ -31,227 +48,437 @@ function resolveVault() {
|
|
|
31
48
|
return null;
|
|
32
49
|
}
|
|
33
50
|
|
|
34
|
-
|
|
35
|
-
|
|
51
|
+
// ─── Provider: the same endpoint and model core would use ────────────────────
|
|
52
|
+
|
|
53
|
+
/** Accepts `host`, `host:port`, or a full URL, as core's normalizeBaseUrl does. */
|
|
54
|
+
export function normalizeBaseUrl(value) {
|
|
55
|
+
const raw = String(value || '').trim();
|
|
56
|
+
if (!raw) return null;
|
|
36
57
|
const withScheme = /^https?:\/\//i.test(raw) ? raw : `http://${raw}`;
|
|
37
58
|
try {
|
|
38
59
|
const u = new URL(withScheme);
|
|
39
|
-
if (
|
|
60
|
+
if (u.username || u.password || u.search || u.hash || u.pathname !== '/') return null;
|
|
61
|
+
const authority = withScheme.match(/^https?:\/\/([^/]+)/i)?.[1];
|
|
62
|
+
if (!u.port && u.protocol === 'http:' && !/:\d+$/.test(authority)) u.port = '11434';
|
|
40
63
|
return u.origin;
|
|
41
|
-
} catch { return
|
|
64
|
+
} catch { return null; }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Configured endpoints first, then loopback: core's candidate order. */
|
|
68
|
+
function candidateUrls() {
|
|
69
|
+
const configured = [process.env.TR_OLLAMA_URL, process.env.OLLAMA_HOST].map(normalizeBaseUrl).filter(Boolean);
|
|
70
|
+
return [...new Set([...configured, LOOPBACK_URL])];
|
|
42
71
|
}
|
|
43
72
|
|
|
44
|
-
|
|
73
|
+
/** Whether text sent to this endpoint stays on this machine. */
|
|
74
|
+
export function endpointLocality(url) {
|
|
45
75
|
try {
|
|
46
|
-
const
|
|
47
|
-
if (
|
|
76
|
+
const host = new URL(url).hostname.replace(/^\[|\]$/g, '');
|
|
77
|
+
if (host === 'localhost' || host === '::1' || /^127\./.test(host)) return 'local';
|
|
78
|
+
return 'remote';
|
|
79
|
+
} catch { return 'unknown'; }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function fetchWithDeadline(url, options, timeoutMs) {
|
|
83
|
+
return fetch(url, { ...options, redirect: 'error', signal: AbortSignal.timeout(timeoutMs) });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function listModels(url) {
|
|
87
|
+
try {
|
|
88
|
+
const res = await fetchWithDeadline(`${url}/api/tags`, {}, PROBE_TIMEOUT_MS);
|
|
89
|
+
if (!res.ok) return { ok: false, reason: `HTTP ${res.status}` };
|
|
48
90
|
const data = await res.json();
|
|
49
|
-
return {
|
|
91
|
+
if (!Array.isArray(data?.models)) return { ok: false, reason: 'not an Ollama endpoint (no models array)' };
|
|
92
|
+
return { ok: true, models: data.models };
|
|
50
93
|
} catch (err) {
|
|
51
|
-
return {
|
|
94
|
+
return { ok: false, reason: err.message };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** First candidate that answers like Ollama, with every attempt recorded. */
|
|
99
|
+
async function resolveEndpoint() {
|
|
100
|
+
const attempts = [];
|
|
101
|
+
for (const url of candidateUrls()) {
|
|
102
|
+
const listed = await listModels(url);
|
|
103
|
+
attempts.push({ url, reachable: listed.ok, reason: listed.ok ? null : listed.reason });
|
|
104
|
+
if (listed.ok) return { url, models: listed.models, attempts };
|
|
52
105
|
}
|
|
106
|
+
return { url: null, models: [], attempts };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function describeModel(url, name) {
|
|
110
|
+
try {
|
|
111
|
+
const res = await fetchWithDeadline(`${url}/api/show`, {
|
|
112
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
113
|
+
body: JSON.stringify({ model: name }),
|
|
114
|
+
}, SHOW_TIMEOUT_MS);
|
|
115
|
+
if (!res.ok) return null;
|
|
116
|
+
return await res.json();
|
|
117
|
+
} catch { return null; }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Family-scoped width only: generative models publish other towers' widths too. */
|
|
121
|
+
export function embeddingWidth(info) {
|
|
122
|
+
const family = info?.details?.family;
|
|
123
|
+
const width = family ? info?.model_info?.[`${family}.embedding_length`] : undefined;
|
|
124
|
+
return Number.isFinite(width) ? width : null;
|
|
53
125
|
}
|
|
54
126
|
|
|
55
|
-
/**
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
127
|
+
/** The declared capability, never a name heuristic. */
|
|
128
|
+
export function canEmbed(info) {
|
|
129
|
+
return Array.isArray(info?.capabilities) && info.capabilities.includes('embedding');
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Every model annotated, plus the one core would select. */
|
|
133
|
+
async function inspectModels(url, models) {
|
|
134
|
+
const preferred = process.env.TR_OLLAMA_EMBED_MODEL || null;
|
|
135
|
+
const rows = [];
|
|
136
|
+
for (const m of models) {
|
|
137
|
+
const name = m.name || m.model;
|
|
138
|
+
if (!name) continue;
|
|
139
|
+
const info = await describeModel(url, name);
|
|
140
|
+
const embeds = info ? canEmbed(info) : false;
|
|
141
|
+
const dims = info ? embeddingWidth(info) : null;
|
|
142
|
+
const upstream = Boolean(m.remote_host || m.remote_model || info?.remote_host || info?.remote_model);
|
|
143
|
+
rows.push({
|
|
144
|
+
name, size: m.size ?? null, described: Boolean(info),
|
|
145
|
+
embedding_capable: embeds, dims, compatible: embeds && dims === VAULT_DIMS, upstream,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
return { rows, selected: chooseModel(rows, preferred), preferred };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** A viable pin wins; otherwise the smallest viable model, as core selects. */
|
|
152
|
+
export function chooseModel(rows, preferred = null) {
|
|
153
|
+
const viable = rows.filter(r => r.compatible);
|
|
154
|
+
const pinned = preferred && viable.find(r => r.name === preferred || r.name.split(':')[0] === preferred);
|
|
155
|
+
if (pinned) return pinned.name;
|
|
156
|
+
viable.sort((a, b) => (a.size ?? Number.MAX_SAFE_INTEGER) - (b.size ?? Number.MAX_SAFE_INTEGER));
|
|
157
|
+
return viable[0]?.name ?? null;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Which provider core would use and whether the text leaves this host.
|
|
162
|
+
* Hosted fallback keys are resolved by the auth owner, so their availability
|
|
163
|
+
* is reported as unknown rather than guessed from environment variable names.
|
|
164
|
+
*/
|
|
165
|
+
async function providerReport() {
|
|
166
|
+
const endpoint = await resolveEndpoint();
|
|
167
|
+
if (!endpoint.url) {
|
|
168
|
+
return { provider: 'hosted-fallback', locality: 'unknown', endpoint: null, selected_model: null, dims: null,
|
|
169
|
+
attempts: endpoint.attempts, models: [], hosted_fallback: 'unknown',
|
|
170
|
+
reason: 'No Ollama endpoint answered; core would try hosted providers whose keys the auth owner resolves.' };
|
|
171
|
+
}
|
|
172
|
+
const inspected = await inspectModels(endpoint.url, endpoint.models);
|
|
173
|
+
if (!inspected.selected) {
|
|
174
|
+
return { provider: 'hosted-fallback', locality: 'unknown', endpoint: endpoint.url, selected_model: null, dims: null,
|
|
175
|
+
attempts: endpoint.attempts, models: inspected.rows, hosted_fallback: 'unknown',
|
|
176
|
+
reason: `No model on ${endpoint.url} declares embedding at ${VAULT_DIMS} dims; core would try hosted providers.` };
|
|
177
|
+
}
|
|
178
|
+
const selected = inspected.rows.find(row => row.name === inspected.selected);
|
|
179
|
+
return { provider: 'ollama', locality: selected.upstream ? 'remote' : endpointLocality(endpoint.url), endpoint: endpoint.url,
|
|
180
|
+
selected_model: inspected.selected, dims: VAULT_DIMS, preferred: inspected.preferred,
|
|
181
|
+
attempts: endpoint.attempts, models: inspected.rows, hosted_fallback: 'not-used',
|
|
182
|
+
reason: selected.upstream ? 'The Ollama service reports an upstream model.' : null };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// ─── Coverage: rows core can still use for this vault ────────────────────────
|
|
186
|
+
|
|
187
|
+
const YAML_TAG = /(?:^|[:,\[{-])[ \t]*!!\S/m;
|
|
188
|
+
|
|
189
|
+
/** Core frontmatter.mjs matter(), on the same SSSS parser. Throws on what core refuses. */
|
|
190
|
+
function parseMarkdown(raw, fm) {
|
|
191
|
+
const text = fm.repairEscapedNewlines(raw.replace(/^/, ''));
|
|
192
|
+
const opening = /^---([^\r\n]*)\r?\n/.exec(text);
|
|
193
|
+
if (!opening || opening[1].startsWith('-')) return { data: {}, content: text };
|
|
194
|
+
const language = opening[1].trim().toLowerCase() || 'yaml';
|
|
195
|
+
if (!['yaml', 'yml', 'json'].includes(language)) throw new Error(`Unsupported frontmatter language: ${language}`);
|
|
196
|
+
const remainder = text.slice(opening[0].length);
|
|
197
|
+
const closing = /^---(?:\r?\n|$)/m.exec(remainder);
|
|
198
|
+
const metadata = closing ? remainder.slice(0, closing.index) : remainder;
|
|
199
|
+
if (language !== 'json' && YAML_TAG.test(metadata)) throw new Error('YAML tags are not allowed in frontmatter');
|
|
200
|
+
const data = (language === 'json' ? JSON.parse(metadata || '{}') : fm.parseFrontmatter(metadata.replace(/\r\n/g, '\n'), { strict: true })) || {};
|
|
201
|
+
return { data, content: closing ? remainder.slice(closing.index + closing[0].length) : '' };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Core vault.mjs walkMd: dot directories and proposals/ are not vault nodes. */
|
|
205
|
+
function walkMd(dir) {
|
|
206
|
+
const out = [];
|
|
207
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
208
|
+
const full = path.join(dir, entry.name);
|
|
209
|
+
if (entry.isDirectory()) {
|
|
210
|
+
if (!entry.name.startsWith('.') && entry.name !== 'proposals') out.push(...walkMd(full));
|
|
211
|
+
} else if (entry.isFile() && entry.name.endsWith('.md')) out.push(full);
|
|
212
|
+
}
|
|
213
|
+
return out;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Core vault.mjs loadNodes, returning parse failures instead of logging them. */
|
|
217
|
+
export async function loadVaultNodes(vaultDir) {
|
|
218
|
+
const fm = await import('@gregiteen/ssss-cli/frontmatter');
|
|
219
|
+
const nodes = [];
|
|
220
|
+
let parseErrors = 0;
|
|
221
|
+
for (const file of walkMd(vaultDir)) {
|
|
60
222
|
try {
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
|
|
223
|
+
const { data, content } = parseMarkdown(fs.readFileSync(file, 'utf8'), fm);
|
|
224
|
+
if (data.type !== 'memory' && data.type !== 'plugin_record') continue;
|
|
225
|
+
nodes.push({
|
|
226
|
+
...data,
|
|
227
|
+
slug: data.slug || (data.plugin_id ? `plugin-${data.plugin_id}` : path.basename(file, '.md')),
|
|
228
|
+
category: data.category || (data.type === 'plugin_record' ? 'plugins' : undefined),
|
|
229
|
+
tags: Array.isArray(data.tags) ? data.tags : (data.use_cases || []),
|
|
230
|
+
body: content.trim(),
|
|
64
231
|
});
|
|
65
|
-
|
|
66
|
-
const info = await res.json();
|
|
67
|
-
const caps = info.capabilities || [];
|
|
68
|
-
// Older servers do not report capabilities; fall back to a name hint.
|
|
69
|
-
const capable = caps.includes('embedding') || /embed/i.test(name);
|
|
70
|
-
if (!capable) continue;
|
|
71
|
-
const width = Object.entries(info.model_info || {})
|
|
72
|
-
.filter(([k]) => k.endsWith('.embedding_length')).map(([, v]) => v)[0];
|
|
73
|
-
if (width && width !== dims) continue;
|
|
74
|
-
return { name, width: width || null };
|
|
75
|
-
} catch { /* try the next model */ }
|
|
232
|
+
} catch { parseErrors++; }
|
|
76
233
|
}
|
|
77
|
-
return
|
|
234
|
+
return { nodes, parseErrors };
|
|
78
235
|
}
|
|
79
236
|
|
|
80
|
-
/**
|
|
81
|
-
function
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
if (
|
|
87
|
-
if (
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
n = c.execute('select count(*) from vault_embeddings').fetchone()[0]
|
|
93
|
-
models = [r[0] for r in c.execute('select model, count(*) from vault_embeddings group by model order by count(*) desc')]
|
|
94
|
-
print(json.dumps({'embedded': n, 'models': models}))
|
|
95
|
-
except Exception as e:
|
|
96
|
-
print(json.dumps({'error': str(e)}))
|
|
97
|
-
`], { encoding: 'utf8', timeout: 20000 });
|
|
237
|
+
/** Core embeddings.mjs nodeToEmbedText: the text whose hash marks a row current. */
|
|
238
|
+
export function nodeToEmbedText(node) {
|
|
239
|
+
const parts = [`Title: ${node.title || node.slug}`];
|
|
240
|
+
if (node.category) parts.push(`Category: ${node.category}`);
|
|
241
|
+
if (node.tags?.length) parts.push(`Tags: ${node.tags.join(', ')}`);
|
|
242
|
+
if (node.description) parts.push(`Description: ${node.description}`);
|
|
243
|
+
if (node.commands?.length) parts.push(`Commands: ${node.commands.join(', ')}`);
|
|
244
|
+
if (node.body) parts.push(`Body: ${node.body.slice(0, 2000)}`);
|
|
245
|
+
return parts.join('\n\n');
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function validVector(json) {
|
|
98
249
|
try {
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
} catch {
|
|
103
|
-
return result;
|
|
250
|
+
const v = JSON.parse(json);
|
|
251
|
+
if (!Array.isArray(v) || !v.every(Number.isFinite)) return { ok: false, width: null };
|
|
252
|
+
return { ok: v.length === VAULT_DIMS, width: v.length };
|
|
253
|
+
} catch { return { ok: false, width: null }; }
|
|
104
254
|
}
|
|
105
255
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
}
|
|
256
|
+
/**
|
|
257
|
+
* Classify every index row against the active vault. Only `compatible` rows
|
|
258
|
+
* are vectors core search can use for current content; the rest are named.
|
|
259
|
+
*/
|
|
260
|
+
export async function coverage(brainDir) {
|
|
261
|
+
const report = {
|
|
262
|
+
state: 'unknown', reason: null, vault_nodes: null, parse_errors: 0,
|
|
263
|
+
rows: null, embedded: null, stale: null, mismatched: null, orphaned: null, missing: null,
|
|
264
|
+
percent: null, model: null, models: [], db_bytes: null,
|
|
116
265
|
};
|
|
117
|
-
|
|
118
|
-
|
|
266
|
+
let nodes;
|
|
267
|
+
try {
|
|
268
|
+
const loaded = await loadVaultNodes(path.join(brainDir, 'memory-vault'));
|
|
269
|
+
nodes = loaded.nodes;
|
|
270
|
+
report.vault_nodes = nodes.length;
|
|
271
|
+
report.parse_errors = loaded.parseErrors;
|
|
272
|
+
} catch (err) {
|
|
273
|
+
report.state = 'unreadable';
|
|
274
|
+
report.reason = `vault could not be read: ${err.message}`;
|
|
275
|
+
return report;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const dbPath = path.join(brainDir, 'memory-derived', 'embeddings.db');
|
|
279
|
+
if (!fs.existsSync(dbPath)) {
|
|
280
|
+
report.state = 'no-index';
|
|
281
|
+
report.reason = 'no embeddings.db; run: total-recall compile';
|
|
282
|
+
report.missing = nodes.length;
|
|
283
|
+
return report;
|
|
284
|
+
}
|
|
285
|
+
let rows;
|
|
286
|
+
try {
|
|
287
|
+
report.db_bytes = fs.statSync(dbPath).size;
|
|
288
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
289
|
+
const db = new DatabaseSync(dbPath, { readOnly: true });
|
|
290
|
+
try {
|
|
291
|
+
rows = db.prepare('SELECT slug, model, content_sha256, embedding_json FROM vault_embeddings').all();
|
|
292
|
+
} finally { db.close(); }
|
|
293
|
+
} catch (err) {
|
|
294
|
+
report.state = 'unreadable';
|
|
295
|
+
report.reason = `embeddings.db could not be read: ${err.message}`;
|
|
296
|
+
return report;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const hashes = new Map(nodes.map(n => [n.slug, crypto.createHash('sha256').update(nodeToEmbedText(n)).digest('hex')]));
|
|
300
|
+
const counts = { embedded: 0, stale: 0, mismatched: 0, orphaned: 0 };
|
|
301
|
+
const models = new Map();
|
|
302
|
+
const indexed = new Set();
|
|
303
|
+
for (const row of rows) {
|
|
304
|
+
if (!hashes.has(row.slug)) { counts.orphaned++; continue; }
|
|
305
|
+
indexed.add(row.slug);
|
|
306
|
+
if (!validVector(row.embedding_json).ok) { counts.mismatched++; continue; }
|
|
307
|
+
if (!row.content_sha256 || row.content_sha256 !== hashes.get(row.slug)) { counts.stale++; continue; }
|
|
308
|
+
counts.embedded++;
|
|
309
|
+
models.set(row.model, (models.get(row.model) || 0) + 1);
|
|
310
|
+
}
|
|
311
|
+
Object.assign(report, counts, {
|
|
312
|
+
state: 'ok',
|
|
313
|
+
rows: rows.length,
|
|
314
|
+
missing: nodes.length - indexed.size,
|
|
315
|
+
models: [...models.entries()].sort((a, b) => b[1] - a[1]).map(([model, count]) => ({ model, count })),
|
|
316
|
+
});
|
|
317
|
+
report.model = report.models[0]?.model ?? null;
|
|
318
|
+
report.percent = nodes.length ? Math.round((counts.embedded / nodes.length) * 100) : null;
|
|
319
|
+
return report;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// ─── Subcommands ─────────────────────────────────────────────────────────────
|
|
323
|
+
|
|
324
|
+
function flagValue(args, name) {
|
|
325
|
+
const i = args.indexOf(name);
|
|
326
|
+
return i > -1 ? args[i + 1] : undefined;
|
|
119
327
|
}
|
|
120
328
|
|
|
121
329
|
const IMPLEMENTED = {};
|
|
122
330
|
|
|
123
331
|
IMPLEMENTED.status = async (args) => {
|
|
124
332
|
const json = args.includes('--json');
|
|
125
|
-
const
|
|
126
|
-
const probed = await probe(url);
|
|
127
|
-
const model = probed.reachable ? await selectModel(url) : null;
|
|
333
|
+
const provider = await providerReport();
|
|
128
334
|
const brain = resolveVault();
|
|
129
335
|
const report = {
|
|
130
336
|
plugin: PLUGIN_ID,
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
local
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
vault_nodes: vaultNodeCount(brain),
|
|
144
|
-
} : null,
|
|
337
|
+
configured_urls: candidateUrls(),
|
|
338
|
+
provider: provider.provider,
|
|
339
|
+
endpoint: provider.endpoint,
|
|
340
|
+
locality: provider.locality,
|
|
341
|
+
// `local` is true only when the serving endpoint is on this host.
|
|
342
|
+
local: provider.locality === 'local',
|
|
343
|
+
selected_model: provider.selected_model,
|
|
344
|
+
embedding_dims: provider.dims,
|
|
345
|
+
hosted_fallback: provider.hosted_fallback,
|
|
346
|
+
reason: provider.reason,
|
|
347
|
+
attempts: provider.attempts,
|
|
348
|
+
brain: brain ? { dir: brain, ...(await coverage(brain)) } : null,
|
|
145
349
|
};
|
|
146
|
-
if (report.brain && report.brain.vault_nodes && report.brain.embedded != null) {
|
|
147
|
-
report.brain.percent = Math.round((report.brain.embedded / report.brain.vault_nodes) * 100);
|
|
148
|
-
}
|
|
149
350
|
if (json) { console.log(JSON.stringify(report, null, 1)); return; }
|
|
351
|
+
const where = { local: 'yes — on this machine', remote: 'NO — the endpoint or selected model uses another machine', unknown: 'unknown — hosted fallback resolved by the auth owner' };
|
|
150
352
|
console.log(`Embeddings v${PLUGIN_VERSION}`);
|
|
151
|
-
console.log(` endpoint: ${url} ${
|
|
152
|
-
console.log(` model: ${
|
|
153
|
-
console.log(` local: ${
|
|
154
|
-
if (
|
|
155
|
-
if (report.brain) {
|
|
156
|
-
const b = report.brain;
|
|
157
|
-
console.log(` brain: ${b.dir}`);
|
|
158
|
-
console.log(` vault: ${b.vault_nodes} nodes`);
|
|
159
|
-
console.log(` embedded: ${b.embedded ?? 'no index'}${b.model ? ` (model: ${b.model})` : ''}${b.percent != null ? ` — ${b.percent}%` : ''}`);
|
|
160
|
-
}
|
|
353
|
+
for (const a of provider.attempts) console.log(` endpoint: ${a.url} ${a.reachable ? '(reachable)' : `(unreachable: ${a.reason})`}`);
|
|
354
|
+
console.log(` model: ${provider.selected_model ? `${provider.selected_model} (${provider.dims} dims)` : `none${provider.reason ? ` — ${provider.reason}` : ''}`}`);
|
|
355
|
+
console.log(` local: ${where[provider.locality]}`);
|
|
356
|
+
if (report.brain) printCoverage(report.brain);
|
|
161
357
|
};
|
|
162
358
|
|
|
359
|
+
function printCoverage(b) {
|
|
360
|
+
console.log(` brain: ${b.dir}`);
|
|
361
|
+
if (b.state !== 'ok') { console.log(` coverage: ${b.state} — ${b.reason}`); return; }
|
|
362
|
+
console.log(` vault: ${b.vault_nodes} nodes${b.parse_errors ? ` (${b.parse_errors} unparseable files)` : ''}`);
|
|
363
|
+
console.log(` usable: ${b.embedded}${b.model ? ` (model: ${b.model})` : ''}${b.percent != null ? ` — ${b.percent}%` : ''}`);
|
|
364
|
+
console.log(` not usable: ${b.stale} stale, ${b.mismatched} wrong width, ${b.missing} missing, ${b.orphaned} orphaned rows`);
|
|
365
|
+
}
|
|
366
|
+
|
|
163
367
|
IMPLEMENTED.models = async (args) => {
|
|
164
368
|
const json = args.includes('--json');
|
|
165
|
-
const
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
else console.error(`Embeddings: ${url} is unreachable (${probed.reason}).`);
|
|
369
|
+
const endpoint = await resolveEndpoint();
|
|
370
|
+
if (!endpoint.url) {
|
|
371
|
+
if (json) console.log(JSON.stringify({ url: null, reachable: false, attempts: endpoint.attempts, models: [] }));
|
|
372
|
+
else for (const a of endpoint.attempts) console.error(`Embeddings: ${a.url} is unreachable (${a.reason}).`);
|
|
170
373
|
process.exitCode = 1;
|
|
171
374
|
return;
|
|
172
375
|
}
|
|
173
|
-
const rows =
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
179
|
-
body: JSON.stringify({ model: name }), signal: AbortSignal.timeout(5000),
|
|
180
|
-
});
|
|
181
|
-
if (res.ok) {
|
|
182
|
-
const info = await res.json();
|
|
183
|
-
capable = (info.capabilities || []).includes('embedding') || /embed/i.test(name);
|
|
184
|
-
width = Object.entries(info.model_info || {}).filter(([k]) => k.endsWith('.embedding_length')).map(([, v]) => v)[0] ?? null;
|
|
185
|
-
}
|
|
186
|
-
} catch { /* report what is known */ }
|
|
187
|
-
rows.push({ name, embedding_capable: capable, dims: width });
|
|
376
|
+
const { rows, selected } = await inspectModels(endpoint.url, endpoint.models);
|
|
377
|
+
if (json) {
|
|
378
|
+
const locality = rows.find(row => row.name === selected)?.upstream ? 'remote' : endpointLocality(endpoint.url);
|
|
379
|
+
console.log(JSON.stringify({ url: endpoint.url, reachable: true, locality, vault_dims: VAULT_DIMS, selected, models: rows }, null, 1));
|
|
380
|
+
return;
|
|
188
381
|
}
|
|
189
|
-
|
|
190
|
-
console.log(`
|
|
191
|
-
|
|
192
|
-
if (!rows.some(r => r.embedding_capable)) console.log(' no embedding-capable model — run: embeddings pull');
|
|
382
|
+
console.log(`Embeddings v${PLUGIN_VERSION} — ${endpoint.url}`);
|
|
383
|
+
for (const r of rows) console.log(` ${r.compatible ? '●' : '○'} ${r.name}${r.dims ? ` (${r.dims} dims)` : ''}${r.name === selected ? ' ← selected' : ''}`);
|
|
384
|
+
if (!selected) console.log(` no model embeds at ${VAULT_DIMS} dims — run: embeddings pull <model>`);
|
|
193
385
|
};
|
|
194
386
|
|
|
195
387
|
IMPLEMENTED.pull = async (args) => {
|
|
196
|
-
const model = args.find(a => !a.startsWith('-')) || 'nomic-embed-text';
|
|
197
388
|
const json = args.includes('--json');
|
|
198
|
-
const
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
389
|
+
const model = args.find(a => !a.startsWith('-'));
|
|
390
|
+
const fail = (code, body, text) => {
|
|
391
|
+
if (json) console.log(JSON.stringify({ ok: false, ...body }));
|
|
392
|
+
else console.error(`Embeddings: ${text}`);
|
|
393
|
+
process.exitCode = code;
|
|
394
|
+
};
|
|
395
|
+
if (!model) return fail(2, { reason: 'model required' }, 'pull needs an explicit model: embeddings pull <model>');
|
|
396
|
+
const configured = process.env.TR_OLLAMA_URL || process.env.OLLAMA_HOST || LOOPBACK_URL;
|
|
397
|
+
const url = normalizeBaseUrl(configured);
|
|
398
|
+
if (!url || endpointLocality(url) !== 'local') {
|
|
399
|
+
return fail(2, { reason: 'pull requires a configured loopback Ollama origin' }, 'pull requires a configured loopback Ollama origin.');
|
|
400
|
+
}
|
|
401
|
+
const listed = await listModels(url);
|
|
402
|
+
if (!listed.ok) return fail(1, { model, url, reason: listed.reason }, 'the selected Ollama endpoint is unavailable.');
|
|
403
|
+
const existing = listed.models.find(entry => entry.name === model || entry.model === model || entry.name === `${model}:latest`);
|
|
404
|
+
if (existing?.remote_model || existing?.remote_host || /(?:[:-])cloud$/i.test(model)) {
|
|
405
|
+
return fail(2, { reason: 'pull requires a local model' }, 'pull requires a local model.');
|
|
406
|
+
}
|
|
407
|
+
if (!json) console.log(`Embeddings: pulling ${model} on ${url} ...`);
|
|
408
|
+
try {
|
|
409
|
+
const res = await fetchWithDeadline(`${url}/api/pull`, {
|
|
410
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
411
|
+
body: JSON.stringify({ model, stream: false }),
|
|
412
|
+
}, PULL_DEADLINE_MS);
|
|
413
|
+
const body = await res.json().catch(() => ({}));
|
|
414
|
+
if (!res.ok || body.error || body.status !== 'success') {
|
|
415
|
+
return fail(1, { model, url, status: res.status, reason: body.error || body.status || `HTTP ${res.status}` },
|
|
416
|
+
`pull failed: ${body.error || body.status || `HTTP ${res.status}`}`);
|
|
417
|
+
}
|
|
418
|
+
} catch (err) {
|
|
419
|
+
return fail(1, { model, url, reason: err.message }, `pull failed: ${err.message}`);
|
|
420
|
+
}
|
|
421
|
+
if (json) { console.log(JSON.stringify({ ok: true, model, url, locality: 'local' })); return; }
|
|
422
|
+
console.log(` ✅ ${model} ready on ${url}`);
|
|
208
423
|
};
|
|
209
424
|
|
|
210
425
|
IMPLEMENTED.benchmark = async (args) => {
|
|
211
426
|
const json = args.includes('--json');
|
|
212
|
-
const
|
|
213
|
-
const
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
if (!model) {
|
|
217
|
-
if (json) console.log(JSON.stringify({ ok: false, reason: 'no embedding-capable model available', url }));
|
|
218
|
-
else console.error(`Embeddings: no embedding-capable model at ${url}. Run: embeddings pull`);
|
|
427
|
+
const requested = Number(flagValue(args, '--count') ?? 10);
|
|
428
|
+
const fail = (body, text) => {
|
|
429
|
+
if (json) console.log(JSON.stringify({ ok: false, ...body }));
|
|
430
|
+
else console.error(`Embeddings: ${text}`);
|
|
219
431
|
process.exitCode = 1;
|
|
432
|
+
};
|
|
433
|
+
if (!Number.isInteger(requested) || requested < 1 || requested > BENCHMARK_MAX_SAMPLES) {
|
|
434
|
+
fail({ reason: `--count must be an integer from 1 to ${BENCHMARK_MAX_SAMPLES}` }, `--count must be an integer from 1 to ${BENCHMARK_MAX_SAMPLES}.`);
|
|
435
|
+
process.exitCode = 2;
|
|
220
436
|
return;
|
|
221
437
|
}
|
|
222
|
-
const
|
|
438
|
+
const provider = await providerReport();
|
|
439
|
+
if (provider.provider !== 'ollama') {
|
|
440
|
+
return fail({ reason: `no embedding-capable model at ${VAULT_DIMS} dims`, url: provider.endpoint, attempts: provider.attempts },
|
|
441
|
+
`no model embeds at ${VAULT_DIMS} dims. ${provider.reason || ''}`.trim());
|
|
442
|
+
}
|
|
443
|
+
if (provider.locality !== 'local') {
|
|
444
|
+
return fail({ reason: 'benchmark requires a local model on a loopback endpoint', locality: provider.locality },
|
|
445
|
+
'benchmark requires a local model on a loopback endpoint.');
|
|
446
|
+
}
|
|
447
|
+
const started = Date.now();
|
|
223
448
|
const timings = [];
|
|
224
|
-
for (let i = 0; i <
|
|
449
|
+
for (let i = 0; i < requested; i++) {
|
|
450
|
+
const left = BENCHMARK_DEADLINE_MS - (Date.now() - started);
|
|
451
|
+
if (left <= 0) return fail({ reason: 'benchmark deadline exceeded', completed: timings.length, url: provider.endpoint, model: provider.selected_model }, 'benchmark deadline exceeded.');
|
|
225
452
|
const t0 = Date.now();
|
|
226
453
|
try {
|
|
227
|
-
const res = await
|
|
454
|
+
const res = await fetchWithDeadline(`${provider.endpoint}/api/embed`, {
|
|
228
455
|
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
229
|
-
body: JSON.stringify({ model:
|
|
230
|
-
});
|
|
456
|
+
body: JSON.stringify({ model: provider.selected_model, input: BENCHMARK_TEXT }),
|
|
457
|
+
}, Math.min(EMBED_TIMEOUT_MS, left));
|
|
231
458
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
232
|
-
await res.json();
|
|
459
|
+
const vector = (await res.json())?.embeddings?.[0];
|
|
460
|
+
if (!Array.isArray(vector) || !vector.every(Number.isFinite)) throw new Error('response carried no numeric vector');
|
|
461
|
+
if (vector.length !== VAULT_DIMS) throw new Error(`vector has ${vector.length} dims, vault requires ${VAULT_DIMS}`);
|
|
233
462
|
timings.push(Date.now() - t0);
|
|
234
463
|
} catch (err) {
|
|
235
|
-
|
|
236
|
-
else console.error(`Embeddings: benchmark failed: ${err.message}`);
|
|
237
|
-
process.exitCode = 1;
|
|
238
|
-
return;
|
|
464
|
+
return fail({ reason: err.message, url: provider.endpoint, model: provider.selected_model, completed: timings.length }, `benchmark failed: ${err.message}`);
|
|
239
465
|
}
|
|
240
466
|
}
|
|
241
|
-
const
|
|
242
|
-
const avg = total / timings.length;
|
|
467
|
+
const avg = timings.reduce((a, b) => a + b, 0) / timings.length;
|
|
243
468
|
const brain = resolveVault();
|
|
244
|
-
|
|
469
|
+
let nodes = null;
|
|
470
|
+
if (brain) { try { nodes = (await loadVaultNodes(path.join(brain, 'memory-vault'))).nodes.length; } catch { nodes = null; } }
|
|
245
471
|
const report = {
|
|
246
|
-
ok: true, url,
|
|
472
|
+
ok: true, url: provider.endpoint, locality: provider.locality, model: provider.selected_model,
|
|
473
|
+
dims: VAULT_DIMS, samples: timings.length,
|
|
247
474
|
ms_per_embedding: Math.round(avg),
|
|
248
475
|
min_ms: Math.min(...timings), max_ms: Math.max(...timings),
|
|
249
476
|
vault_nodes: nodes,
|
|
250
477
|
projected_minutes: nodes ? Math.round((avg * nodes) / 60000) : null,
|
|
251
478
|
};
|
|
252
479
|
if (json) { console.log(JSON.stringify(report, null, 1)); return; }
|
|
253
|
-
console.log(`Embeddings v${PLUGIN_VERSION} — benchmark (${samples} samples, ${model.
|
|
254
|
-
console.log(` ${
|
|
480
|
+
console.log(`Embeddings v${PLUGIN_VERSION} — benchmark (${report.samples} samples, ${report.model} on ${report.url})`);
|
|
481
|
+
console.log(` ${report.ms_per_embedding} ms/embedding (min ${report.min_ms}, max ${report.max_ms}), ${VAULT_DIMS}-dim vectors verified`);
|
|
255
482
|
if (nodes) console.log(` ${nodes} vault nodes → about ${report.projected_minutes} minutes to embed fully`);
|
|
256
483
|
};
|
|
257
484
|
|
|
@@ -264,22 +491,19 @@ IMPLEMENTED.coverage = async (args) => {
|
|
|
264
491
|
process.exitCode = 1;
|
|
265
492
|
return;
|
|
266
493
|
}
|
|
267
|
-
const
|
|
268
|
-
const
|
|
269
|
-
const report = { ok
|
|
270
|
-
|
|
494
|
+
const cov = await coverage(brain);
|
|
495
|
+
const ok = cov.state === 'ok' || cov.state === 'no-index';
|
|
496
|
+
const report = { ok, brain, ...cov };
|
|
497
|
+
if (!ok) process.exitCode = 1;
|
|
271
498
|
if (json) { console.log(JSON.stringify(report, null, 1)); return; }
|
|
272
499
|
console.log(`Embeddings v${PLUGIN_VERSION} — coverage`);
|
|
273
|
-
|
|
274
|
-
console.log(
|
|
275
|
-
console.log(` embedded: ${cov.embedded ?? 'no index'}${cov.model ? ` (model: ${cov.model})` : ''}${report.percent != null ? ` — ${report.percent}%` : ''}`);
|
|
276
|
-
if (report.percent != null && report.percent < 100) console.log(' run: total-recall compile (builds the missing vectors)');
|
|
500
|
+
printCoverage({ dir: brain, ...cov });
|
|
501
|
+
if (cov.state === 'ok' && (cov.stale || cov.missing || cov.mismatched)) console.log(' run: total-recall compile (rebuilds the unusable vectors)');
|
|
277
502
|
};
|
|
278
503
|
|
|
279
504
|
export async function run(argv = []) {
|
|
280
505
|
const args = Array.isArray(argv) ? argv.slice(3) : [];
|
|
281
506
|
const sub = args[0] || 'status';
|
|
282
|
-
const json = args.includes('--json');
|
|
283
507
|
const wantsHelp = args.includes('--help') || args.includes('-h');
|
|
284
508
|
|
|
285
509
|
if (wantsHelp || sub === 'help') {
|
|
@@ -292,13 +516,19 @@ Subcommands:
|
|
|
292
516
|
${subs.map((s) => ` ${s}`).join('\n')}
|
|
293
517
|
|
|
294
518
|
Options:
|
|
295
|
-
--json
|
|
296
|
-
--
|
|
519
|
+
--json Machine-readable output
|
|
520
|
+
--count <n> benchmark samples, 1-${BENCHMARK_MAX_SAMPLES} (default 10)
|
|
521
|
+
pull <model> pull an explicitly named local model to the selected loopback endpoint
|
|
522
|
+
--help, -h Show this help
|
|
297
523
|
|
|
298
524
|
Environment:
|
|
299
|
-
TR_OLLAMA_URL / OLLAMA_HOST Ollama endpoint
|
|
300
|
-
|
|
301
|
-
|
|
525
|
+
TR_OLLAMA_URL / OLLAMA_HOST Ollama endpoint, tried before loopback
|
|
526
|
+
(http://127.0.0.1:11434). A non-loopback
|
|
527
|
+
endpoint receives vault text over the network.
|
|
528
|
+
TR_OLLAMA_EMBED_MODEL Preferred model, used when it embeds at ${VAULT_DIMS} dims
|
|
529
|
+
Benchmark runs only for a local model. A loopback Ollama server may
|
|
530
|
+
advertise a remote model. Core may try hosted providers if local
|
|
531
|
+
selection fails. When it does, vault text leaves the machine.`);
|
|
302
532
|
return;
|
|
303
533
|
}
|
|
304
534
|
|