@kolisachint/hoocode-agent 0.5.59 → 0.5.60
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/CHANGELOG.md +30 -0
- package/dist/core/embsearch/chunker.d.ts +17 -1
- package/dist/core/embsearch/chunker.d.ts.map +1 -1
- package/dist/core/embsearch/chunker.js +20 -6
- package/dist/core/embsearch/chunker.js.map +1 -1
- package/dist/core/embsearch/client.d.ts +9 -0
- package/dist/core/embsearch/client.d.ts.map +1 -1
- package/dist/core/embsearch/client.js +2 -0
- package/dist/core/embsearch/client.js.map +1 -1
- package/dist/core/embsearch/embsearch-service.d.ts +37 -0
- package/dist/core/embsearch/embsearch-service.d.ts.map +1 -1
- package/dist/core/embsearch/embsearch-service.js +86 -7
- package/dist/core/embsearch/embsearch-service.js.map +1 -1
- package/dist/core/search/eval-harness.d.ts +86 -5
- package/dist/core/search/eval-harness.d.ts.map +1 -1
- package/dist/core/search/eval-harness.js +143 -3
- package/dist/core/search/eval-harness.js.map +1 -1
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.5.60] - 2026-09-05
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- **A semantic index built by an older embedding model now rebuilds instead of
|
|
8
|
+
switching semantic search off for good.** The embsearch daemon refuses to open
|
|
9
|
+
a store whose recorded model disagrees with its own — rightly, since vectors
|
|
10
|
+
from two models are not comparable — but refusing was where it stopped: the
|
|
11
|
+
store stayed on disk, the daemon never came up, and the service parked itself
|
|
12
|
+
in `unavailable` with a rebuild one directory-removal away. The check meant to
|
|
13
|
+
catch this ran *after* the spawn and reset only the sidecar, never the store,
|
|
14
|
+
so on a model change it was unreachable anyway. Recovery now catches the
|
|
15
|
+
refusal and confirms, via embsearch's `store-info` — which reads a store's
|
|
16
|
+
manifest without loading a model, and so is the only thing that can still
|
|
17
|
+
identify a store nothing will open — that a readable store is what the daemon
|
|
18
|
+
choked on, then rebuilds. A store it cannot read is left alone and the original
|
|
19
|
+
error stands, because deleting an index is the wrong answer to an unknown
|
|
20
|
+
fault. This was about to bite: embsearch 0.3.2 changed its model id, and only
|
|
21
|
+
the fact that an already-installed binary is never upgraded in place kept
|
|
22
|
+
anyone from hitting it. `store-info` ships in **embsearch 0.3.3**; against an
|
|
23
|
+
older binary the probe simply fails and the previous behaviour stands, so no
|
|
24
|
+
version floor is needed and nothing regresses on an older daemon.
|
|
25
|
+
- **A chunker change no longer leaves dead text in the index.** Bumping
|
|
26
|
+
`CHUNKER_VERSION` resets the sidecar, and the sidecar is the only record of how
|
|
27
|
+
many chunks each file produced — so it reported zero for every file, and the
|
|
28
|
+
loop that drops superseded chunks counts down from that number. Any file that
|
|
29
|
+
re-chunked into fewer pieces left its tail vectors behind holding text that no
|
|
30
|
+
longer existed anywhere, retrievable forever. Upserts hid it: chunk counts
|
|
31
|
+
looked right, the sidecar looked right, only the search results were wrong.
|
|
32
|
+
|
|
3
33
|
## [0.5.59] - 2026-09-05
|
|
4
34
|
|
|
5
35
|
### Fixed
|
|
@@ -11,6 +11,17 @@
|
|
|
11
11
|
* sidecar triggers a clean rebuild of the store.
|
|
12
12
|
*/
|
|
13
13
|
export declare const CHUNKER_VERSION = 2;
|
|
14
|
+
/**
|
|
15
|
+
* Hard character cap per chunk.
|
|
16
|
+
*
|
|
17
|
+
* The "~256 tokens ≈ 1000 chars" this was set from does not hold for code:
|
|
18
|
+
* measured against the bundled tokenizer over this repo, 1000 chars is **313
|
|
19
|
+
* tokens** at the median, so MiniLM (256) truncates 85.8% of chunks and drops
|
|
20
|
+
* 20.3% of the corpus's tokens, while bge-small (512) drops 0.1%. Raising this
|
|
21
|
+
* is therefore not free in the way the old comment implied — it spends a
|
|
22
|
+
* budget that is already overdrawn on one model and nearly full on the other.
|
|
23
|
+
*/
|
|
24
|
+
export declare const CHUNK_MAX_CHARS = 1000;
|
|
14
25
|
export interface Chunk {
|
|
15
26
|
/** `relpath#index` — the id stored in the vector index. */
|
|
16
27
|
id: string;
|
|
@@ -24,6 +35,11 @@ export interface Chunk {
|
|
|
24
35
|
/**
|
|
25
36
|
* Split `content` into chunks. `relPath` becomes the id prefix. Returns an
|
|
26
37
|
* empty array for empty or binary-looking content.
|
|
38
|
+
*
|
|
39
|
+
* `maxChars` overrides {@link CHUNK_MAX_CHARS} for eval arms that sweep the
|
|
40
|
+
* window. Production never passes it; a caller that does is changing what the
|
|
41
|
+
* index contains and owes the store a distinct key, since nothing about a
|
|
42
|
+
* stored vector records the cap it was built under.
|
|
27
43
|
*/
|
|
28
|
-
export declare function chunkFile(relPath: string, content: string): Chunk[];
|
|
44
|
+
export declare function chunkFile(relPath: string, content: string, maxChars?: number): Chunk[];
|
|
29
45
|
//# sourceMappingURL=chunker.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chunker.d.ts","sourceRoot":"","sources":["../../../src/core/embsearch/chunker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,eAAO,MAAM,eAAe,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"chunker.d.ts","sourceRoot":"","sources":["../../../src/core/embsearch/chunker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,eAAO,MAAM,eAAe,IAAI,CAAC;AAgBjC;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe,OAAO,CAAC;AAEpC,MAAM,WAAW,KAAK;IACrB,6DAA2D;IAC3D,EAAE,EAAE,MAAM,CAAC;IACX,iCAAiC;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,oCAAoC;IACpC,SAAS,EAAE,MAAM,CAAC;IAClB,kCAAkC;IAClC,OAAO,EAAE,MAAM,CAAC;CAChB;AAQD;;;;;;;;GAQG;AACH,wBAAgB,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,GAAE,MAAwB,GAAG,KAAK,EAAE,CA8CvG","sourcesContent":["/**\n * File chunking for semantic indexing.\n *\n * Splits a file into overlapping line windows, each capped by characters so a\n * chunk stays within the embedding model's effective token window (MiniLM\n * truncates around 256 tokens ≈ 1000 chars). Chunk ids are `relpath#index`;\n * the id → line-range mapping is kept in the sidecar metadata (index-meta.ts)\n * so search hits can be rendered as `path:start-end`.\n *\n * Bump CHUNKER_VERSION when the strategy changes — a version mismatch in the\n * sidecar triggers a clean rebuild of the store.\n */\n\nexport const CHUNKER_VERSION = 2;\n\n/**\n * Target lines per chunk.\n *\n * Halving this (30 lines / 500 chars) was measured and rejected. The theory\n * was dilution — a four-line answer sharing one vector with five neighbouring\n * methods — but sharper chunks cost reach: Recall@50 fell 79% -> 69% on\n * `auto +rr` and the boundary class went from 2 of 4 findable to 0 of 4.\n * A fixed top-k over smaller chunks retrieves less *content*: 50 chunks at\n * ~460 chars sees half the corpus that 50 at ~930 does. Recall@1 ticked up\n * (53% -> 55%), which is the sharpening, and it did not pay for the loss.\n */\nconst CHUNK_LINES = 60;\n/** Overlapping lines between consecutive chunks, for context continuity. */\nconst CHUNK_OVERLAP_LINES = 10;\n/**\n * Hard character cap per chunk.\n *\n * The \"~256 tokens ≈ 1000 chars\" this was set from does not hold for code:\n * measured against the bundled tokenizer over this repo, 1000 chars is **313\n * tokens** at the median, so MiniLM (256) truncates 85.8% of chunks and drops\n * 20.3% of the corpus's tokens, while bge-small (512) drops 0.1%. Raising this\n * is therefore not free in the way the old comment implied — it spends a\n * budget that is already overdrawn on one model and nearly full on the other.\n */\nexport const CHUNK_MAX_CHARS = 1000;\n\nexport interface Chunk {\n\t/** `relpath#index` — the id stored in the vector index. */\n\tid: string;\n\t/** Text sent to the embedder. */\n\ttext: string;\n\t/** 1-based inclusive start line. */\n\tstartLine: number;\n\t/** 1-based inclusive end line. */\n\tendLine: number;\n}\n\n/** Heuristic binary sniff: NUL byte in the first 8KB. */\nfunction looksBinary(content: string): boolean {\n\tconst probe = content.slice(0, 8192);\n\treturn probe.includes(\"\\u0000\");\n}\n\n/**\n * Split `content` into chunks. `relPath` becomes the id prefix. Returns an\n * empty array for empty or binary-looking content.\n *\n * `maxChars` overrides {@link CHUNK_MAX_CHARS} for eval arms that sweep the\n * window. Production never passes it; a caller that does is changing what the\n * index contains and owes the store a distinct key, since nothing about a\n * stored vector records the cap it was built under.\n */\nexport function chunkFile(relPath: string, content: string, maxChars: number = CHUNK_MAX_CHARS): Chunk[] {\n\tif (!content.trim() || looksBinary(content)) return [];\n\tconst lines = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").split(\"\\n\");\n\tconst chunks: Chunk[] = [];\n\tlet start = 0; // 0-based\n\tlet index = 0;\n\n\twhile (start < lines.length) {\n\t\tlet end = start; // exclusive\n\t\tlet chars = 0;\n\t\twhile (end < lines.length && end - start < CHUNK_LINES) {\n\t\t\tconst lineLen = lines[end].length + 1;\n\t\t\tif (chars + lineLen > maxChars && end > start) break;\n\t\t\tchars += lineLen;\n\t\t\tend++;\n\t\t}\n\t\t// Trim whole blank lines off both ends, and narrow the recorded range to\n\t\t// match. Trimming the joined string instead left `startLine`/`endLine`\n\t\t// claiming lines whose text was never embedded — 31% of chunks in this\n\t\t// repo, up to 3 lines each. Those lines were unfindable by the vector\n\t\t// leg while still being handed to the context assembler as if they were\n\t\t// part of the chunk.\n\t\tlet from = start;\n\t\tlet to = end; // exclusive\n\t\twhile (from < to && lines[from].trim() === \"\") from++;\n\t\twhile (to > from && lines[to - 1].trim() === \"\") to--;\n\t\tlet text = lines.slice(from, to).join(\"\\n\").trim();\n\t\tif (text.length > maxChars) {\n\t\t\t// Oversized chunk (e.g. long minified line): keep the prefix. The\n\t\t\t// underlying model would truncate anyway, so this stays bounded.\n\t\t\ttext = text.slice(0, maxChars);\n\t\t}\n\t\tif (text) {\n\t\t\tchunks.push({\n\t\t\t\tid: `${relPath}#${index}`,\n\t\t\t\ttext,\n\t\t\t\tstartLine: from + 1,\n\t\t\t\tendLine: to,\n\t\t\t});\n\t\t\tindex++;\n\t\t}\n\t\tif (end >= lines.length) break;\n\t\t// Step forward with overlap, but always make progress.\n\t\tstart = Math.max(end - CHUNK_OVERLAP_LINES, start + 1);\n\t}\n\treturn chunks;\n}\n"]}
|
|
@@ -25,8 +25,17 @@ export const CHUNKER_VERSION = 2;
|
|
|
25
25
|
const CHUNK_LINES = 60;
|
|
26
26
|
/** Overlapping lines between consecutive chunks, for context continuity. */
|
|
27
27
|
const CHUNK_OVERLAP_LINES = 10;
|
|
28
|
-
/**
|
|
29
|
-
|
|
28
|
+
/**
|
|
29
|
+
* Hard character cap per chunk.
|
|
30
|
+
*
|
|
31
|
+
* The "~256 tokens ≈ 1000 chars" this was set from does not hold for code:
|
|
32
|
+
* measured against the bundled tokenizer over this repo, 1000 chars is **313
|
|
33
|
+
* tokens** at the median, so MiniLM (256) truncates 85.8% of chunks and drops
|
|
34
|
+
* 20.3% of the corpus's tokens, while bge-small (512) drops 0.1%. Raising this
|
|
35
|
+
* is therefore not free in the way the old comment implied — it spends a
|
|
36
|
+
* budget that is already overdrawn on one model and nearly full on the other.
|
|
37
|
+
*/
|
|
38
|
+
export const CHUNK_MAX_CHARS = 1000;
|
|
30
39
|
/** Heuristic binary sniff: NUL byte in the first 8KB. */
|
|
31
40
|
function looksBinary(content) {
|
|
32
41
|
const probe = content.slice(0, 8192);
|
|
@@ -35,8 +44,13 @@ function looksBinary(content) {
|
|
|
35
44
|
/**
|
|
36
45
|
* Split `content` into chunks. `relPath` becomes the id prefix. Returns an
|
|
37
46
|
* empty array for empty or binary-looking content.
|
|
47
|
+
*
|
|
48
|
+
* `maxChars` overrides {@link CHUNK_MAX_CHARS} for eval arms that sweep the
|
|
49
|
+
* window. Production never passes it; a caller that does is changing what the
|
|
50
|
+
* index contains and owes the store a distinct key, since nothing about a
|
|
51
|
+
* stored vector records the cap it was built under.
|
|
38
52
|
*/
|
|
39
|
-
export function chunkFile(relPath, content) {
|
|
53
|
+
export function chunkFile(relPath, content, maxChars = CHUNK_MAX_CHARS) {
|
|
40
54
|
if (!content.trim() || looksBinary(content))
|
|
41
55
|
return [];
|
|
42
56
|
const lines = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
|
|
@@ -48,7 +62,7 @@ export function chunkFile(relPath, content) {
|
|
|
48
62
|
let chars = 0;
|
|
49
63
|
while (end < lines.length && end - start < CHUNK_LINES) {
|
|
50
64
|
const lineLen = lines[end].length + 1;
|
|
51
|
-
if (chars + lineLen >
|
|
65
|
+
if (chars + lineLen > maxChars && end > start)
|
|
52
66
|
break;
|
|
53
67
|
chars += lineLen;
|
|
54
68
|
end++;
|
|
@@ -66,10 +80,10 @@ export function chunkFile(relPath, content) {
|
|
|
66
80
|
while (to > from && lines[to - 1].trim() === "")
|
|
67
81
|
to--;
|
|
68
82
|
let text = lines.slice(from, to).join("\n").trim();
|
|
69
|
-
if (text.length >
|
|
83
|
+
if (text.length > maxChars) {
|
|
70
84
|
// Oversized chunk (e.g. long minified line): keep the prefix. The
|
|
71
85
|
// underlying model would truncate anyway, so this stays bounded.
|
|
72
|
-
text = text.slice(0,
|
|
86
|
+
text = text.slice(0, maxChars);
|
|
73
87
|
}
|
|
74
88
|
if (text) {
|
|
75
89
|
chunks.push({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chunker.js","sourceRoot":"","sources":["../../../src/core/embsearch/chunker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,CAAC;AAEjC;;;;;;;;;;GAUG;AACH,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB,4EAA4E;AAC5E,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B
|
|
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vD,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,mBAAmB,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;IACxD,CAAC;IACD,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["/**\n * File chunking for semantic indexing.\n *\n * Splits a file into overlapping line windows, each capped by characters so a\n * chunk stays within the embedding model's effective token window (MiniLM\n * truncates around 256 tokens ≈ 1000 chars). Chunk ids are `relpath#index`;\n * the id → line-range mapping is kept in the sidecar metadata (index-meta.ts)\n * so search hits can be rendered as `path:start-end`.\n *\n * Bump CHUNKER_VERSION when the strategy changes — a version mismatch in the\n * sidecar triggers a clean rebuild of the store.\n */\n\nexport const CHUNKER_VERSION = 2;\n\n/**\n * Target lines per chunk.\n *\n * Halving this (30 lines / 500 chars) was measured and rejected. The theory\n * was dilution — a four-line answer sharing one vector with five neighbouring\n * methods — but sharper chunks cost reach: Recall@50 fell 79% -> 69% on\n * `auto +rr` and the boundary class went from 2 of 4 findable to 0 of 4.\n * A fixed top-k over smaller chunks retrieves less *content*: 50 chunks at\n * ~460 chars sees half the corpus that 50 at ~930 does. Recall@1 ticked up\n * (53% -> 55%), which is the sharpening, and it did not pay for the loss.\n */\nconst CHUNK_LINES = 60;\n/** Overlapping lines between consecutive chunks, for context continuity. */\nconst CHUNK_OVERLAP_LINES = 10;\n/**\n * Hard character cap per chunk.\n *\n * The \"~256 tokens ≈ 1000 chars\" this was set from does not hold for code:\n * measured against the bundled tokenizer over this repo, 1000 chars is **313\n * tokens** at the median, so MiniLM (256) truncates 85.8% of chunks and drops\n * 20.3% of the corpus's tokens, while bge-small (512) drops 0.1%. Raising this\n * is therefore not free in the way the old comment implied — it spends a\n * budget that is already overdrawn on one model and nearly full on the other.\n */\nexport const CHUNK_MAX_CHARS = 1000;\n\nexport interface Chunk {\n\t/** `relpath#index` — the id stored in the vector index. */\n\tid: string;\n\t/** Text sent to the embedder. */\n\ttext: string;\n\t/** 1-based inclusive start line. */\n\tstartLine: number;\n\t/** 1-based inclusive end line. */\n\tendLine: number;\n}\n\n/** Heuristic binary sniff: NUL byte in the first 8KB. */\nfunction looksBinary(content: string): boolean {\n\tconst probe = content.slice(0, 8192);\n\treturn probe.includes(\"\\u0000\");\n}\n\n/**\n * Split `content` into chunks. `relPath` becomes the id prefix. Returns an\n * empty array for empty or binary-looking content.\n *\n * `maxChars` overrides {@link CHUNK_MAX_CHARS} for eval arms that sweep the\n * window. Production never passes it; a caller that does is changing what the\n * index contains and owes the store a distinct key, since nothing about a\n * stored vector records the cap it was built under.\n */\nexport function chunkFile(relPath: string, content: string, maxChars: number = CHUNK_MAX_CHARS): Chunk[] {\n\tif (!content.trim() || looksBinary(content)) return [];\n\tconst lines = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").split(\"\\n\");\n\tconst chunks: Chunk[] = [];\n\tlet start = 0; // 0-based\n\tlet index = 0;\n\n\twhile (start < lines.length) {\n\t\tlet end = start; // exclusive\n\t\tlet chars = 0;\n\t\twhile (end < lines.length && end - start < CHUNK_LINES) {\n\t\t\tconst lineLen = lines[end].length + 1;\n\t\t\tif (chars + lineLen > maxChars && end > start) break;\n\t\t\tchars += lineLen;\n\t\t\tend++;\n\t\t}\n\t\t// Trim whole blank lines off both ends, and narrow the recorded range to\n\t\t// match. Trimming the joined string instead left `startLine`/`endLine`\n\t\t// claiming lines whose text was never embedded — 31% of chunks in this\n\t\t// repo, up to 3 lines each. Those lines were unfindable by the vector\n\t\t// leg while still being handed to the context assembler as if they were\n\t\t// part of the chunk.\n\t\tlet from = start;\n\t\tlet to = end; // exclusive\n\t\twhile (from < to && lines[from].trim() === \"\") from++;\n\t\twhile (to > from && lines[to - 1].trim() === \"\") to--;\n\t\tlet text = lines.slice(from, to).join(\"\\n\").trim();\n\t\tif (text.length > maxChars) {\n\t\t\t// Oversized chunk (e.g. long minified line): keep the prefix. The\n\t\t\t// underlying model would truncate anyway, so this stays bounded.\n\t\t\ttext = text.slice(0, maxChars);\n\t\t}\n\t\tif (text) {\n\t\t\tchunks.push({\n\t\t\t\tid: `${relPath}#${index}`,\n\t\t\t\ttext,\n\t\t\t\tstartLine: from + 1,\n\t\t\t\tendLine: to,\n\t\t\t});\n\t\t\tindex++;\n\t\t}\n\t\tif (end >= lines.length) break;\n\t\t// Step forward with overlap, but always make progress.\n\t\tstart = Math.max(end - CHUNK_OVERLAP_LINES, start + 1);\n\t}\n\treturn chunks;\n}\n"]}
|
|
@@ -57,6 +57,15 @@ export interface EmbSearchClientOptions {
|
|
|
57
57
|
binaryPath: string;
|
|
58
58
|
/** Store directory passed as `--path`. */
|
|
59
59
|
storePath: string;
|
|
60
|
+
/**
|
|
61
|
+
* Model directory passed as `--model` (onnx builds only): a dir holding
|
|
62
|
+
* `model.onnx`, `tokenizer.json` and `model.json`.
|
|
63
|
+
*
|
|
64
|
+
* Omitted, the daemon uses the model bundled into the binary. Set, the
|
|
65
|
+
* binary no longer determines which model produced a vector — which is why
|
|
66
|
+
* the eval harness records `info.model_id` rather than the binary version.
|
|
67
|
+
*/
|
|
68
|
+
modelDir?: string;
|
|
60
69
|
/** Metric for a freshly created store. Default: "cosine". */
|
|
61
70
|
metric?: "cosine" | "dot" | "euclidean";
|
|
62
71
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/core/embsearch/client.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,MAAM,WAAW,eAAe;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,mBAAmB;IACnC,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd;;;;;;OAMG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB;;;;;;;;OAQG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,oDAAoD;AACpD,MAAM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MAAM,GAAG,OAAO,CAAC,qBAAqB,EAAE,CAAC,CAG3G;IAED;;;;OAIG;IACG,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAGnF;IAED,qEAAqE;IAC/D,IAAI,IAAI,OAAO,CAAC,mBAAmB,CAAC,CASzC;IAED,yDAAyD;IACnD,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAGzC;IAED,uDAAuD;IACjD,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAE7B;IAED,gDAAgD;IAC1C,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAE1B;IAED,+DAA+D;IACzD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAI3B;CACD","sourcesContent":["/**\n * Client for the `embsearch` stdio daemon (vendored from\n * github.com/kolisachint/embeddingsearchtools ts/client.ts).\n *\n * Spawns `embsearch serve` once and talks newline-delimited JSON over its\n * stdin/stdout. The process stays alive so the model and index load a single\n * time; every query after startup is hot.\n */\n\nimport { type ChildProcessWithoutNullStreams, spawn } from \"child_process\";\n\nexport interface EmbSearchResult {\n\tid: string;\n\tscore: number;\n}\n\nexport interface EmbSearchDaemonInfo {\n\tmodelId: string;\n\tdim: number;\n\tcount: number;\n\t/**\n\t * Whether the open store carries a BM25 index alongside its vectors.\n\t *\n\t * Fixed when the store is created — passing `--hybrid` at a non-hybrid\n\t * store only warns — so this is the only reliable way to find out, and the\n\t * signal that an existing store has to be rebuilt rather than reused.\n\t */\n\thybrid?: boolean;\n\t/**\n\t * Whether this daemon can actually serve `rerank`, or `undefined` from a\n\t * daemon too old to say.\n\t *\n\t * Reported separately from the version because the two came apart:\n\t * released binaries carry the `rerank` op but no longer bundle the ~23 MB\n\t * cross-encoder weights, so a version check alone would advertise a\n\t * reranker that fails on first call.\n\t */\n\trerank?: boolean;\n}\n\n/** One candidate sent for cross-encoder scoring. */\nexport interface EmbSearchRerankPassage {\n\tid: string;\n\ttext: string;\n}\n\n/** A cross-encoder relevance logit. Higher is more relevant, but the scale is\n * unnormalized and comparable only within one call. */\nexport interface EmbSearchRerankResult {\n\tid: string;\n\tscore: number;\n}\n\nexport interface EmbSearchBulkResult {\n\tinserted: number;\n\tupdated: number;\n}\n\n/** Which daemon-side retriever answers a query (embsearch >= 0.2.0). */\nexport type DaemonRetriever = \"dense\" | \"lexical\" | \"hybrid\";\n\nexport interface EmbSearchClientOptions {\n\t/** Open/create the store with a BM25 lexical index alongside the vectors. */\n\thybrid?: boolean;\n\t/** Path to the `embsearch` binary. */\n\tbinaryPath: string;\n\t/** Store directory passed as `--path`. */\n\tstorePath: string;\n\t/** Metric for a freshly created store. Default: \"cosine\". */\n\tmetric?: \"cosine\" | \"dot\" | \"euclidean\";\n}\n\ninterface Pending {\n\tresolve: (value: EmbSearchRawResponse) => void;\n\treject: (err: Error) => void;\n}\n\ninterface EmbSearchRawResponse {\n\tok: boolean;\n\terror?: string;\n\tresults?: EmbSearchResult[];\n\tinserted?: boolean;\n\tremoved?: boolean;\n\tcount?: number;\n\tinserted_count?: number;\n\tupdated_count?: number;\n\tmodel_id?: string;\n\tdim?: number;\n\t/** Cross-encoder scores. Separate from `results` because the daemon's\n\t * logits are not comparable to retrieval scores. */\n\treranked?: EmbSearchRerankResult[];\n\t/** `info` only: whether the open store has a BM25 index. */\n\thybrid?: boolean;\n\t/** `info` only: whether `rerank` will work. Absent on daemons too old to\n\t * report it. */\n\trerank?: boolean;\n}\n\nexport class EmbSearchClient {\n\tprivate proc: ChildProcessWithoutNullStreams;\n\tprivate queue: Pending[] = [];\n\tprivate buffer = \"\";\n\tprivate closed = false;\n\tprivate readyPromise: Promise<void>;\n\n\tconstructor(opts: EmbSearchClientOptions) {\n\t\tconst args = [\"serve\", \"--path\", opts.storePath];\n\t\tif (opts.metric) args.push(\"--metric\", opts.metric);\n\t\t// Hybrid-ness is fixed when a store is created: passing --hybrid against\n\t\t// an existing non-hybrid store warns and is ignored daemon-side, so a\n\t\t// hybrid store needs its own directory.\n\t\tif (opts.hybrid) args.push(\"--hybrid\");\n\n\t\tthis.proc = spawn(opts.binaryPath, args, { stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n\n\t\tthis.proc.stdout.setEncoding(\"utf8\");\n\t\tthis.proc.stdout.on(\"data\", (chunk: string) => this.onStdout(chunk));\n\t\t// Swallow the informational stderr banner; errors surface via responses/exit.\n\t\tthis.proc.stderr.resume();\n\n\t\t// Readiness = the daemon answering a ping (probes the actual request loop).\n\t\tthis.readyPromise = this.send({ op: \"ping\" }).then(() => undefined);\n\t\t// Spawn failures reject the pending ping via the exit handler; mark the\n\t\t// promise handled so a failed spawn doesn't raise an unhandled rejection\n\t\t// before ready() is awaited.\n\t\tthis.readyPromise.catch(() => {});\n\n\t\tthis.proc.on(\"error\", (err) => {\n\t\t\tthis.closed = true;\n\t\t\tfor (const p of this.queue.splice(0)) p.reject(err);\n\t\t});\n\t\tthis.proc.on(\"exit\", (code) => {\n\t\t\tthis.closed = true;\n\t\t\tconst err = new Error(`embsearch daemon exited (code ${code})`);\n\t\t\tfor (const p of this.queue.splice(0)) p.reject(err);\n\t\t});\n\t}\n\n\t/** Resolves once the daemon has loaded the model + index. */\n\tready(): Promise<void> {\n\t\treturn this.readyPromise;\n\t}\n\n\tget isClosed(): boolean {\n\t\treturn this.closed;\n\t}\n\n\tprivate onStdout(chunk: string): void {\n\t\tthis.buffer += chunk;\n\t\t// Each response is one line; dispatch FIFO against the pending queue.\n\t\tfor (let nl = this.buffer.indexOf(\"\\n\"); nl !== -1; nl = this.buffer.indexOf(\"\\n\")) {\n\t\t\tconst line = this.buffer.slice(0, nl).trim();\n\t\t\tthis.buffer = this.buffer.slice(nl + 1);\n\t\t\tif (!line) continue;\n\t\t\tconst pending = this.queue.shift();\n\t\t\tif (!pending) continue;\n\t\t\tlet msg: EmbSearchRawResponse;\n\t\t\ttry {\n\t\t\t\tmsg = JSON.parse(line) as EmbSearchRawResponse;\n\t\t\t} catch {\n\t\t\t\tpending.reject(new Error(`bad response: ${line}`));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (msg.ok) pending.resolve(msg);\n\t\t\telse pending.reject(new Error(msg.error ?? \"unknown error\"));\n\t\t}\n\t}\n\n\tprivate send(req: Record<string, unknown>): Promise<EmbSearchRawResponse> {\n\t\tif (this.closed) return Promise.reject(new Error(\"embsearch client is closed\"));\n\t\treturn new Promise<EmbSearchRawResponse>((resolve, reject) => {\n\t\t\tthis.queue.push({ resolve, reject });\n\t\t\tthis.proc.stdin.write(`${JSON.stringify(req)}\\n`);\n\t\t});\n\t}\n\n\t/**\n\t * Search for the top-`k` matches for `text`.\n\t *\n\t * `retriever` selects which leg answers:\n\t * - `dense` (default) — vector search, the historical behaviour;\n\t * - `lexical` — BM25 only, raw scores, no embedding computed;\n\t * - `hybrid` — both, pre-fused by the daemon's own RRF constant.\n\t *\n\t * `lexical` and `hybrid` need a store created with `--hybrid`. Prefer\n\t * `lexical` over `hybrid` when fusing here: `hybrid` collapses both legs\n\t * into one RRF score, discarding the per-retriever ranks the trace records\n\t * and preventing n-way fusion with the grep leg.\n\t */\n\tasync query(text: string, k = 10, retriever: DaemonRetriever = \"dense\"): Promise<EmbSearchResult[]> {\n\t\tconst res = await this.send(\n\t\t\tretriever === \"dense\" ? { op: \"query\", text, k } : { op: \"query\", text, k, retriever },\n\t\t);\n\t\treturn res.results ?? [];\n\t}\n\n\t/**\n\t * Score `passages` against `query` with the daemon's cross-encoder and\n\t * return the best `k`, best first.\n\t *\n\t * Passages are sent inline rather than referenced by id: the caller has the\n\t * exact spans it intends to show the model, and a cross-encoder scores the\n\t * text it is given, so sending anything else would score the wrong thing.\n\t * Requires an onnx build with reranker weights (embsearch >= 0.3.0).\n\t */\n\tasync rerank(query: string, passages: EmbSearchRerankPassage[], k: number): Promise<EmbSearchRerankResult[]> {\n\t\tconst res = await this.send({ op: \"rerank\", query, passages, k });\n\t\treturn res.reranked ?? [];\n\t}\n\n\t/**\n\t * Batched insert-or-replace. One embedding inference for the whole batch —\n\t * the fast path for bulk indexing. Keep batches modest (e.g. 32–64) so a\n\t * concurrent query is not stuck behind a huge inference.\n\t */\n\tasync bulk(items: Array<{ id: string; text: string }>): Promise<EmbSearchBulkResult> {\n\t\tconst res = await this.send({ op: \"bulk\", items });\n\t\treturn { inserted: res.inserted_count ?? 0, updated: res.updated_count ?? 0 };\n\t}\n\n\t/** Model id, dimensionality, and live vector count of the daemon. */\n\tasync info(): Promise<EmbSearchDaemonInfo> {\n\t\tconst res = await this.send({ op: \"info\" });\n\t\treturn {\n\t\t\tmodelId: res.model_id ?? \"\",\n\t\t\tdim: res.dim ?? 0,\n\t\t\tcount: res.count ?? 0,\n\t\t\thybrid: res.hybrid,\n\t\t\trerank: res.rerank,\n\t\t};\n\t}\n\n\t/** Remove a record. Resolves to `true` if it existed. */\n\tasync remove(id: string): Promise<boolean> {\n\t\tconst res = await this.send({ op: \"remove\", id });\n\t\treturn res.removed === true;\n\t}\n\n\t/** Reclaim tombstoned rows left behind by `remove`. */\n\tasync compact(): Promise<void> {\n\t\tawait this.send({ op: \"compact\" });\n\t}\n\n\t/** Persist the index to the store directory. */\n\tasync save(): Promise<void> {\n\t\tawait this.send({ op: \"save\" });\n\t}\n\n\t/** Shut the daemon down, closing stdin so it exits cleanly. */\n\tasync close(): Promise<void> {\n\t\tif (this.closed) return;\n\t\tthis.proc.stdin.end();\n\t\tawait new Promise<void>((resolve) => this.proc.on(\"exit\", () => resolve()));\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/core/embsearch/client.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,MAAM,WAAW,eAAe;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,mBA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QAAQ;IAqBhB,OAAO,CAAC,IAAI;IAQZ;;;;;;;;;;;;OAYG;IACG,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,SAAK,EAAE,SAAS,GAAE,eAAyB,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC,CAKlG;IAED;;;;;;;;OAQG;IACG,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,sBAAsB,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,qBAAqB,EAAE,CAAC,CAG3G;IAED;;;;OAIG;IACG,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAGnF;IAED,qEAAqE;IAC/D,IAAI,IAAI,OAAO,CAAC,mBAAmB,CAAC,CASzC;IAED,yDAAyD;IACnD,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAGzC;IAED,uDAAuD;IACjD,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAE7B;IAED,gDAAgD;IAC1C,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAE1B;IAED,+DAA+D;IACzD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAI3B;CACD","sourcesContent":["/**\n * Client for the `embsearch` stdio daemon (vendored from\n * github.com/kolisachint/embeddingsearchtools ts/client.ts).\n *\n * Spawns `embsearch serve` once and talks newline-delimited JSON over its\n * stdin/stdout. The process stays alive so the model and index load a single\n * time; every query after startup is hot.\n */\n\nimport { type ChildProcessWithoutNullStreams, spawn } from \"child_process\";\n\nexport interface EmbSearchResult {\n\tid: string;\n\tscore: number;\n}\n\nexport interface EmbSearchDaemonInfo {\n\tmodelId: string;\n\tdim: number;\n\tcount: number;\n\t/**\n\t * Whether the open store carries a BM25 index alongside its vectors.\n\t *\n\t * Fixed when the store is created — passing `--hybrid` at a non-hybrid\n\t * store only warns — so this is the only reliable way to find out, and the\n\t * signal that an existing store has to be rebuilt rather than reused.\n\t */\n\thybrid?: boolean;\n\t/**\n\t * Whether this daemon can actually serve `rerank`, or `undefined` from a\n\t * daemon too old to say.\n\t *\n\t * Reported separately from the version because the two came apart:\n\t * released binaries carry the `rerank` op but no longer bundle the ~23 MB\n\t * cross-encoder weights, so a version check alone would advertise a\n\t * reranker that fails on first call.\n\t */\n\trerank?: boolean;\n}\n\n/** One candidate sent for cross-encoder scoring. */\nexport interface EmbSearchRerankPassage {\n\tid: string;\n\ttext: string;\n}\n\n/** A cross-encoder relevance logit. Higher is more relevant, but the scale is\n * unnormalized and comparable only within one call. */\nexport interface EmbSearchRerankResult {\n\tid: string;\n\tscore: number;\n}\n\nexport interface EmbSearchBulkResult {\n\tinserted: number;\n\tupdated: number;\n}\n\n/** Which daemon-side retriever answers a query (embsearch >= 0.2.0). */\nexport type DaemonRetriever = \"dense\" | \"lexical\" | \"hybrid\";\n\nexport interface EmbSearchClientOptions {\n\t/** Open/create the store with a BM25 lexical index alongside the vectors. */\n\thybrid?: boolean;\n\t/** Path to the `embsearch` binary. */\n\tbinaryPath: string;\n\t/** Store directory passed as `--path`. */\n\tstorePath: string;\n\t/**\n\t * Model directory passed as `--model` (onnx builds only): a dir holding\n\t * `model.onnx`, `tokenizer.json` and `model.json`.\n\t *\n\t * Omitted, the daemon uses the model bundled into the binary. Set, the\n\t * binary no longer determines which model produced a vector — which is why\n\t * the eval harness records `info.model_id` rather than the binary version.\n\t */\n\tmodelDir?: string;\n\t/** Metric for a freshly created store. Default: \"cosine\". */\n\tmetric?: \"cosine\" | \"dot\" | \"euclidean\";\n}\n\ninterface Pending {\n\tresolve: (value: EmbSearchRawResponse) => void;\n\treject: (err: Error) => void;\n}\n\ninterface EmbSearchRawResponse {\n\tok: boolean;\n\terror?: string;\n\tresults?: EmbSearchResult[];\n\tinserted?: boolean;\n\tremoved?: boolean;\n\tcount?: number;\n\tinserted_count?: number;\n\tupdated_count?: number;\n\tmodel_id?: string;\n\tdim?: number;\n\t/** Cross-encoder scores. Separate from `results` because the daemon's\n\t * logits are not comparable to retrieval scores. */\n\treranked?: EmbSearchRerankResult[];\n\t/** `info` only: whether the open store has a BM25 index. */\n\thybrid?: boolean;\n\t/** `info` only: whether `rerank` will work. Absent on daemons too old to\n\t * report it. */\n\trerank?: boolean;\n}\n\nexport class EmbSearchClient {\n\tprivate proc: ChildProcessWithoutNullStreams;\n\tprivate queue: Pending[] = [];\n\tprivate buffer = \"\";\n\tprivate closed = false;\n\tprivate readyPromise: Promise<void>;\n\n\tconstructor(opts: EmbSearchClientOptions) {\n\t\tconst args = [\"serve\", \"--path\", opts.storePath];\n\t\tif (opts.metric) args.push(\"--metric\", opts.metric);\n\t\tif (opts.modelDir) args.push(\"--model\", opts.modelDir);\n\t\t// Hybrid-ness is fixed when a store is created: passing --hybrid against\n\t\t// an existing non-hybrid store warns and is ignored daemon-side, so a\n\t\t// hybrid store needs its own directory.\n\t\tif (opts.hybrid) args.push(\"--hybrid\");\n\n\t\tthis.proc = spawn(opts.binaryPath, args, { stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n\n\t\tthis.proc.stdout.setEncoding(\"utf8\");\n\t\tthis.proc.stdout.on(\"data\", (chunk: string) => this.onStdout(chunk));\n\t\t// Swallow the informational stderr banner; errors surface via responses/exit.\n\t\tthis.proc.stderr.resume();\n\n\t\t// Readiness = the daemon answering a ping (probes the actual request loop).\n\t\tthis.readyPromise = this.send({ op: \"ping\" }).then(() => undefined);\n\t\t// Spawn failures reject the pending ping via the exit handler; mark the\n\t\t// promise handled so a failed spawn doesn't raise an unhandled rejection\n\t\t// before ready() is awaited.\n\t\tthis.readyPromise.catch(() => {});\n\n\t\tthis.proc.on(\"error\", (err) => {\n\t\t\tthis.closed = true;\n\t\t\tfor (const p of this.queue.splice(0)) p.reject(err);\n\t\t});\n\t\tthis.proc.on(\"exit\", (code) => {\n\t\t\tthis.closed = true;\n\t\t\tconst err = new Error(`embsearch daemon exited (code ${code})`);\n\t\t\tfor (const p of this.queue.splice(0)) p.reject(err);\n\t\t});\n\t}\n\n\t/** Resolves once the daemon has loaded the model + index. */\n\tready(): Promise<void> {\n\t\treturn this.readyPromise;\n\t}\n\n\tget isClosed(): boolean {\n\t\treturn this.closed;\n\t}\n\n\tprivate onStdout(chunk: string): void {\n\t\tthis.buffer += chunk;\n\t\t// Each response is one line; dispatch FIFO against the pending queue.\n\t\tfor (let nl = this.buffer.indexOf(\"\\n\"); nl !== -1; nl = this.buffer.indexOf(\"\\n\")) {\n\t\t\tconst line = this.buffer.slice(0, nl).trim();\n\t\t\tthis.buffer = this.buffer.slice(nl + 1);\n\t\t\tif (!line) continue;\n\t\t\tconst pending = this.queue.shift();\n\t\t\tif (!pending) continue;\n\t\t\tlet msg: EmbSearchRawResponse;\n\t\t\ttry {\n\t\t\t\tmsg = JSON.parse(line) as EmbSearchRawResponse;\n\t\t\t} catch {\n\t\t\t\tpending.reject(new Error(`bad response: ${line}`));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (msg.ok) pending.resolve(msg);\n\t\t\telse pending.reject(new Error(msg.error ?? \"unknown error\"));\n\t\t}\n\t}\n\n\tprivate send(req: Record<string, unknown>): Promise<EmbSearchRawResponse> {\n\t\tif (this.closed) return Promise.reject(new Error(\"embsearch client is closed\"));\n\t\treturn new Promise<EmbSearchRawResponse>((resolve, reject) => {\n\t\t\tthis.queue.push({ resolve, reject });\n\t\t\tthis.proc.stdin.write(`${JSON.stringify(req)}\\n`);\n\t\t});\n\t}\n\n\t/**\n\t * Search for the top-`k` matches for `text`.\n\t *\n\t * `retriever` selects which leg answers:\n\t * - `dense` (default) — vector search, the historical behaviour;\n\t * - `lexical` — BM25 only, raw scores, no embedding computed;\n\t * - `hybrid` — both, pre-fused by the daemon's own RRF constant.\n\t *\n\t * `lexical` and `hybrid` need a store created with `--hybrid`. Prefer\n\t * `lexical` over `hybrid` when fusing here: `hybrid` collapses both legs\n\t * into one RRF score, discarding the per-retriever ranks the trace records\n\t * and preventing n-way fusion with the grep leg.\n\t */\n\tasync query(text: string, k = 10, retriever: DaemonRetriever = \"dense\"): Promise<EmbSearchResult[]> {\n\t\tconst res = await this.send(\n\t\t\tretriever === \"dense\" ? { op: \"query\", text, k } : { op: \"query\", text, k, retriever },\n\t\t);\n\t\treturn res.results ?? [];\n\t}\n\n\t/**\n\t * Score `passages` against `query` with the daemon's cross-encoder and\n\t * return the best `k`, best first.\n\t *\n\t * Passages are sent inline rather than referenced by id: the caller has the\n\t * exact spans it intends to show the model, and a cross-encoder scores the\n\t * text it is given, so sending anything else would score the wrong thing.\n\t * Requires an onnx build with reranker weights (embsearch >= 0.3.0).\n\t */\n\tasync rerank(query: string, passages: EmbSearchRerankPassage[], k: number): Promise<EmbSearchRerankResult[]> {\n\t\tconst res = await this.send({ op: \"rerank\", query, passages, k });\n\t\treturn res.reranked ?? [];\n\t}\n\n\t/**\n\t * Batched insert-or-replace. One embedding inference for the whole batch —\n\t * the fast path for bulk indexing. Keep batches modest (e.g. 32–64) so a\n\t * concurrent query is not stuck behind a huge inference.\n\t */\n\tasync bulk(items: Array<{ id: string; text: string }>): Promise<EmbSearchBulkResult> {\n\t\tconst res = await this.send({ op: \"bulk\", items });\n\t\treturn { inserted: res.inserted_count ?? 0, updated: res.updated_count ?? 0 };\n\t}\n\n\t/** Model id, dimensionality, and live vector count of the daemon. */\n\tasync info(): Promise<EmbSearchDaemonInfo> {\n\t\tconst res = await this.send({ op: \"info\" });\n\t\treturn {\n\t\t\tmodelId: res.model_id ?? \"\",\n\t\t\tdim: res.dim ?? 0,\n\t\t\tcount: res.count ?? 0,\n\t\t\thybrid: res.hybrid,\n\t\t\trerank: res.rerank,\n\t\t};\n\t}\n\n\t/** Remove a record. Resolves to `true` if it existed. */\n\tasync remove(id: string): Promise<boolean> {\n\t\tconst res = await this.send({ op: \"remove\", id });\n\t\treturn res.removed === true;\n\t}\n\n\t/** Reclaim tombstoned rows left behind by `remove`. */\n\tasync compact(): Promise<void> {\n\t\tawait this.send({ op: \"compact\" });\n\t}\n\n\t/** Persist the index to the store directory. */\n\tasync save(): Promise<void> {\n\t\tawait this.send({ op: \"save\" });\n\t}\n\n\t/** Shut the daemon down, closing stdin so it exits cleanly. */\n\tasync close(): Promise<void> {\n\t\tif (this.closed) return;\n\t\tthis.proc.stdin.end();\n\t\tawait new Promise<void>((resolve) => this.proc.on(\"exit\", () => resolve()));\n\t}\n}\n"]}
|
|
@@ -17,6 +17,8 @@ export class EmbSearchClient {
|
|
|
17
17
|
const args = ["serve", "--path", opts.storePath];
|
|
18
18
|
if (opts.metric)
|
|
19
19
|
args.push("--metric", opts.metric);
|
|
20
|
+
if (opts.modelDir)
|
|
21
|
+
args.push("--model", opts.modelDir);
|
|
20
22
|
// Hybrid-ness is fixed when a store is created: passing --hybrid against
|
|
21
23
|
// an existing non-hybrid store warns and is ignored daemon-side, so a
|
|
22
24
|
// hybrid store needs its own directory.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/core/embsearch/client.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAuC,KAAK,EAAE,MAAM,eAAe,CAAC;AAyF3E,MAAM,OAAO,eAAe;IACnB,IAAI,CAAiC;IACrC,KAAK,GAAc,EAAE,CAAC;IACtB,MAAM,GAAG,EAAE,CAAC;IACZ,MAAM,GAAG,KAAK,CAAC;IACf,YAAY,CAAgB;IAEpC,YAAY,IAA4B,EAAE;QACzC,MAAM,IAAI,GAAG,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;QACjD,IAAI,IAAI,CAAC,MAAM;YAAE,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QACpD,yEAAyE;QACzE,sEAAsE;QACtE,wCAAwC;QACxC,IAAI,IAAI,CAAC,MAAM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AM,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;IAAA,CAChC;IAED,+DAA+D;IAC/D,KAAK,CAAC,KAAK,GAAkB;QAC5B,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO;QACxB,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC;QACtB,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;IAAA,CAC5E;CACD","sourcesContent":["/**\n * Client for the `embsearch` stdio daemon (vendored from\n * github.com/kolisachint/embeddingsearchtools ts/client.ts).\n *\n * Spawns `embsearch serve` once and talks newline-delimited JSON over its\n * stdin/stdout. The process stays alive so the model and index load a single\n * time; every query after startup is hot.\n */\n\nimport { type ChildProcessWithoutNullStreams, spawn } from \"child_process\";\n\nexport interface EmbSearchResult {\n\tid: string;\n\tscore: number;\n}\n\nexport interface EmbSearchDaemonInfo {\n\tmodelId: string;\n\tdim: number;\n\tcount: number;\n\t/**\n\t * Whether the open store carries a BM25 index alongside its vectors.\n\t *\n\t * Fixed when the store is created — passing `--hybrid` at a non-hybrid\n\t * store only warns — so this is the only reliable way to find out, and the\n\t * signal that an existing store has to be rebuilt rather than reused.\n\t */\n\thybrid?: boolean;\n\t/**\n\t * Whether this daemon can actually serve `rerank`, or `undefined` from a\n\t * daemon too old to say.\n\t *\n\t * Reported separately from the version because the two came apart:\n\t * released binaries carry the `rerank` op but no longer bundle the ~23 MB\n\t * cross-encoder weights, so a version check alone would advertise a\n\t * reranker that fails on first call.\n\t */\n\trerank?: boolean;\n}\n\n/** One candidate sent for cross-encoder scoring. */\nexport interface EmbSearchRerankPassage {\n\tid: string;\n\ttext: string;\n}\n\n/** A cross-encoder relevance logit. Higher is more relevant, but the scale is\n * unnormalized and comparable only within one call. */\nexport interface EmbSearchRerankResult {\n\tid: string;\n\tscore: number;\n}\n\nexport interface EmbSearchBulkResult {\n\tinserted: number;\n\tupdated: number;\n}\n\n/** Which daemon-side retriever answers a query (embsearch >= 0.2.0). */\nexport type DaemonRetriever = \"dense\" | \"lexical\" | \"hybrid\";\n\nexport interface EmbSearchClientOptions {\n\t/** Open/create the store with a BM25 lexical index alongside the vectors. */\n\thybrid?: boolean;\n\t/** Path to the `embsearch` binary. */\n\tbinaryPath: string;\n\t/** Store directory passed as `--path`. */\n\tstorePath: string;\n\t/** Metric for a freshly created store. Default: \"cosine\". */\n\tmetric?: \"cosine\" | \"dot\" | \"euclidean\";\n}\n\ninterface Pending {\n\tresolve: (value: EmbSearchRawResponse) => void;\n\treject: (err: Error) => void;\n}\n\ninterface EmbSearchRawResponse {\n\tok: boolean;\n\terror?: string;\n\tresults?: EmbSearchResult[];\n\tinserted?: boolean;\n\tremoved?: boolean;\n\tcount?: number;\n\tinserted_count?: number;\n\tupdated_count?: number;\n\tmodel_id?: string;\n\tdim?: number;\n\t/** Cross-encoder scores. Separate from `results` because the daemon's\n\t * logits are not comparable to retrieval scores. */\n\treranked?: EmbSearchRerankResult[];\n\t/** `info` only: whether the open store has a BM25 index. */\n\thybrid?: boolean;\n\t/** `info` only: whether `rerank` will work. Absent on daemons too old to\n\t * report it. */\n\trerank?: boolean;\n}\n\nexport class EmbSearchClient {\n\tprivate proc: ChildProcessWithoutNullStreams;\n\tprivate queue: Pending[] = [];\n\tprivate buffer = \"\";\n\tprivate closed = false;\n\tprivate readyPromise: Promise<void>;\n\n\tconstructor(opts: EmbSearchClientOptions) {\n\t\tconst args = [\"serve\", \"--path\", opts.storePath];\n\t\tif (opts.metric) args.push(\"--metric\", opts.metric);\n\t\t// Hybrid-ness is fixed when a store is created: passing --hybrid against\n\t\t// an existing non-hybrid store warns and is ignored daemon-side, so a\n\t\t// hybrid store needs its own directory.\n\t\tif (opts.hybrid) args.push(\"--hybrid\");\n\n\t\tthis.proc = spawn(opts.binaryPath, args, { stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n\n\t\tthis.proc.stdout.setEncoding(\"utf8\");\n\t\tthis.proc.stdout.on(\"data\", (chunk: string) => this.onStdout(chunk));\n\t\t// Swallow the informational stderr banner; errors surface via responses/exit.\n\t\tthis.proc.stderr.resume();\n\n\t\t// Readiness = the daemon answering a ping (probes the actual request loop).\n\t\tthis.readyPromise = this.send({ op: \"ping\" }).then(() => undefined);\n\t\t// Spawn failures reject the pending ping via the exit handler; mark the\n\t\t// promise handled so a failed spawn doesn't raise an unhandled rejection\n\t\t// before ready() is awaited.\n\t\tthis.readyPromise.catch(() => {});\n\n\t\tthis.proc.on(\"error\", (err) => {\n\t\t\tthis.closed = true;\n\t\t\tfor (const p of this.queue.splice(0)) p.reject(err);\n\t\t});\n\t\tthis.proc.on(\"exit\", (code) => {\n\t\t\tthis.closed = true;\n\t\t\tconst err = new Error(`embsearch daemon exited (code ${code})`);\n\t\t\tfor (const p of this.queue.splice(0)) p.reject(err);\n\t\t});\n\t}\n\n\t/** Resolves once the daemon has loaded the model + index. */\n\tready(): Promise<void> {\n\t\treturn this.readyPromise;\n\t}\n\n\tget isClosed(): boolean {\n\t\treturn this.closed;\n\t}\n\n\tprivate onStdout(chunk: string): void {\n\t\tthis.buffer += chunk;\n\t\t// Each response is one line; dispatch FIFO against the pending queue.\n\t\tfor (let nl = this.buffer.indexOf(\"\\n\"); nl !== -1; nl = this.buffer.indexOf(\"\\n\")) {\n\t\t\tconst line = this.buffer.slice(0, nl).trim();\n\t\t\tthis.buffer = this.buffer.slice(nl + 1);\n\t\t\tif (!line) continue;\n\t\t\tconst pending = this.queue.shift();\n\t\t\tif (!pending) continue;\n\t\t\tlet msg: EmbSearchRawResponse;\n\t\t\ttry {\n\t\t\t\tmsg = JSON.parse(line) as EmbSearchRawResponse;\n\t\t\t} catch {\n\t\t\t\tpending.reject(new Error(`bad response: ${line}`));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (msg.ok) pending.resolve(msg);\n\t\t\telse pending.reject(new Error(msg.error ?? \"unknown error\"));\n\t\t}\n\t}\n\n\tprivate send(req: Record<string, unknown>): Promise<EmbSearchRawResponse> {\n\t\tif (this.closed) return Promise.reject(new Error(\"embsearch client is closed\"));\n\t\treturn new Promise<EmbSearchRawResponse>((resolve, reject) => {\n\t\t\tthis.queue.push({ resolve, reject });\n\t\t\tthis.proc.stdin.write(`${JSON.stringify(req)}\\n`);\n\t\t});\n\t}\n\n\t/**\n\t * Search for the top-`k` matches for `text`.\n\t *\n\t * `retriever` selects which leg answers:\n\t * - `dense` (default) — vector search, the historical behaviour;\n\t * - `lexical` — BM25 only, raw scores, no embedding computed;\n\t * - `hybrid` — both, pre-fused by the daemon's own RRF constant.\n\t *\n\t * `lexical` and `hybrid` need a store created with `--hybrid`. Prefer\n\t * `lexical` over `hybrid` when fusing here: `hybrid` collapses both legs\n\t * into one RRF score, discarding the per-retriever ranks the trace records\n\t * and preventing n-way fusion with the grep leg.\n\t */\n\tasync query(text: string, k = 10, retriever: DaemonRetriever = \"dense\"): Promise<EmbSearchResult[]> {\n\t\tconst res = await this.send(\n\t\t\tretriever === \"dense\" ? { op: \"query\", text, k } : { op: \"query\", text, k, retriever },\n\t\t);\n\t\treturn res.results ?? [];\n\t}\n\n\t/**\n\t * Score `passages` against `query` with the daemon's cross-encoder and\n\t * return the best `k`, best first.\n\t *\n\t * Passages are sent inline rather than referenced by id: the caller has the\n\t * exact spans it intends to show the model, and a cross-encoder scores the\n\t * text it is given, so sending anything else would score the wrong thing.\n\t * Requires an onnx build with reranker weights (embsearch >= 0.3.0).\n\t */\n\tasync rerank(query: string, passages: EmbSearchRerankPassage[], k: number): Promise<EmbSearchRerankResult[]> {\n\t\tconst res = await this.send({ op: \"rerank\", query, passages, k });\n\t\treturn res.reranked ?? [];\n\t}\n\n\t/**\n\t * Batched insert-or-replace. One embedding inference for the whole batch —\n\t * the fast path for bulk indexing. Keep batches modest (e.g. 32–64) so a\n\t * concurrent query is not stuck behind a huge inference.\n\t */\n\tasync bulk(items: Array<{ id: string; text: string }>): Promise<EmbSearchBulkResult> {\n\t\tconst res = await this.send({ op: \"bulk\", items });\n\t\treturn { inserted: res.inserted_count ?? 0, updated: res.updated_count ?? 0 };\n\t}\n\n\t/** Model id, dimensionality, and live vector count of the daemon. */\n\tasync info(): Promise<EmbSearchDaemonInfo> {\n\t\tconst res = await this.send({ op: \"info\" });\n\t\treturn {\n\t\t\tmodelId: res.model_id ?? \"\",\n\t\t\tdim: res.dim ?? 0,\n\t\t\tcount: res.count ?? 0,\n\t\t\thybrid: res.hybrid,\n\t\t\trerank: res.rerank,\n\t\t};\n\t}\n\n\t/** Remove a record. Resolves to `true` if it existed. */\n\tasync remove(id: string): Promise<boolean> {\n\t\tconst res = await this.send({ op: \"remove\", id });\n\t\treturn res.removed === true;\n\t}\n\n\t/** Reclaim tombstoned rows left behind by `remove`. */\n\tasync compact(): Promise<void> {\n\t\tawait this.send({ op: \"compact\" });\n\t}\n\n\t/** Persist the index to the store directory. */\n\tasync save(): Promise<void> {\n\t\tawait this.send({ op: \"save\" });\n\t}\n\n\t/** Shut the daemon down, closing stdin so it exits cleanly. */\n\tasync close(): Promise<void> {\n\t\tif (this.closed) return;\n\t\tthis.proc.stdin.end();\n\t\tawait new Promise<void>((resolve) => this.proc.on(\"exit\", () => resolve()));\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/core/embsearch/client.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAuC,KAAK,EAAE,MAAM,eAAe,CAAC;AAkG3E,MAAM,OAAO,eAAe;IACnB,IAAI,CAAiC;IACrC,KAAK,GAAc,EAAE,CAAC;IACtB,MAAM,GAAG,EAAE,CAAC;IACZ,MAAM,GAAG,KAAK,CAAC;IACf,YAAY,CAAgB;IAEpC,YAAY,IAA4B,EAAE;QACzC,MAAM,IAAI,GAAG,CAAC,OAAO,EAAE,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AC,IAAI,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAAC;QAClD,OAAO,GAAG,CAAC,OAAO,KAAK,IAAI,CAAC;IAAA,CAC5B;IAED,uDAAuD;IACvD,KAAK,CAAC,OAAO,GAAkB;QAC9B,MAAM,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;IAAA,CACnC;IAED,gDAAgD;IAChD,KAAK,CAAC,IAAI,GAAkB;QAC3B,MAAM,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;IAAA,CAChC;IAED,+DAA+D;IAC/D,KAAK,CAAC,KAAK,GAAkB;QAC5B,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO;QACxB,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC;QACtB,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;IAAA,CAC5E;CACD","sourcesContent":["/**\n * Client for the `embsearch` stdio daemon (vendored from\n * github.com/kolisachint/embeddingsearchtools ts/client.ts).\n *\n * Spawns `embsearch serve` once and talks newline-delimited JSON over its\n * stdin/stdout. The process stays alive so the model and index load a single\n * time; every query after startup is hot.\n */\n\nimport { type ChildProcessWithoutNullStreams, spawn } from \"child_process\";\n\nexport interface EmbSearchResult {\n\tid: string;\n\tscore: number;\n}\n\nexport interface EmbSearchDaemonInfo {\n\tmodelId: string;\n\tdim: number;\n\tcount: number;\n\t/**\n\t * Whether the open store carries a BM25 index alongside its vectors.\n\t *\n\t * Fixed when the store is created — passing `--hybrid` at a non-hybrid\n\t * store only warns — so this is the only reliable way to find out, and the\n\t * signal that an existing store has to be rebuilt rather than reused.\n\t */\n\thybrid?: boolean;\n\t/**\n\t * Whether this daemon can actually serve `rerank`, or `undefined` from a\n\t * daemon too old to say.\n\t *\n\t * Reported separately from the version because the two came apart:\n\t * released binaries carry the `rerank` op but no longer bundle the ~23 MB\n\t * cross-encoder weights, so a version check alone would advertise a\n\t * reranker that fails on first call.\n\t */\n\trerank?: boolean;\n}\n\n/** One candidate sent for cross-encoder scoring. */\nexport interface EmbSearchRerankPassage {\n\tid: string;\n\ttext: string;\n}\n\n/** A cross-encoder relevance logit. Higher is more relevant, but the scale is\n * unnormalized and comparable only within one call. */\nexport interface EmbSearchRerankResult {\n\tid: string;\n\tscore: number;\n}\n\nexport interface EmbSearchBulkResult {\n\tinserted: number;\n\tupdated: number;\n}\n\n/** Which daemon-side retriever answers a query (embsearch >= 0.2.0). */\nexport type DaemonRetriever = \"dense\" | \"lexical\" | \"hybrid\";\n\nexport interface EmbSearchClientOptions {\n\t/** Open/create the store with a BM25 lexical index alongside the vectors. */\n\thybrid?: boolean;\n\t/** Path to the `embsearch` binary. */\n\tbinaryPath: string;\n\t/** Store directory passed as `--path`. */\n\tstorePath: string;\n\t/**\n\t * Model directory passed as `--model` (onnx builds only): a dir holding\n\t * `model.onnx`, `tokenizer.json` and `model.json`.\n\t *\n\t * Omitted, the daemon uses the model bundled into the binary. Set, the\n\t * binary no longer determines which model produced a vector — which is why\n\t * the eval harness records `info.model_id` rather than the binary version.\n\t */\n\tmodelDir?: string;\n\t/** Metric for a freshly created store. Default: \"cosine\". */\n\tmetric?: \"cosine\" | \"dot\" | \"euclidean\";\n}\n\ninterface Pending {\n\tresolve: (value: EmbSearchRawResponse) => void;\n\treject: (err: Error) => void;\n}\n\ninterface EmbSearchRawResponse {\n\tok: boolean;\n\terror?: string;\n\tresults?: EmbSearchResult[];\n\tinserted?: boolean;\n\tremoved?: boolean;\n\tcount?: number;\n\tinserted_count?: number;\n\tupdated_count?: number;\n\tmodel_id?: string;\n\tdim?: number;\n\t/** Cross-encoder scores. Separate from `results` because the daemon's\n\t * logits are not comparable to retrieval scores. */\n\treranked?: EmbSearchRerankResult[];\n\t/** `info` only: whether the open store has a BM25 index. */\n\thybrid?: boolean;\n\t/** `info` only: whether `rerank` will work. Absent on daemons too old to\n\t * report it. */\n\trerank?: boolean;\n}\n\nexport class EmbSearchClient {\n\tprivate proc: ChildProcessWithoutNullStreams;\n\tprivate queue: Pending[] = [];\n\tprivate buffer = \"\";\n\tprivate closed = false;\n\tprivate readyPromise: Promise<void>;\n\n\tconstructor(opts: EmbSearchClientOptions) {\n\t\tconst args = [\"serve\", \"--path\", opts.storePath];\n\t\tif (opts.metric) args.push(\"--metric\", opts.metric);\n\t\tif (opts.modelDir) args.push(\"--model\", opts.modelDir);\n\t\t// Hybrid-ness is fixed when a store is created: passing --hybrid against\n\t\t// an existing non-hybrid store warns and is ignored daemon-side, so a\n\t\t// hybrid store needs its own directory.\n\t\tif (opts.hybrid) args.push(\"--hybrid\");\n\n\t\tthis.proc = spawn(opts.binaryPath, args, { stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n\n\t\tthis.proc.stdout.setEncoding(\"utf8\");\n\t\tthis.proc.stdout.on(\"data\", (chunk: string) => this.onStdout(chunk));\n\t\t// Swallow the informational stderr banner; errors surface via responses/exit.\n\t\tthis.proc.stderr.resume();\n\n\t\t// Readiness = the daemon answering a ping (probes the actual request loop).\n\t\tthis.readyPromise = this.send({ op: \"ping\" }).then(() => undefined);\n\t\t// Spawn failures reject the pending ping via the exit handler; mark the\n\t\t// promise handled so a failed spawn doesn't raise an unhandled rejection\n\t\t// before ready() is awaited.\n\t\tthis.readyPromise.catch(() => {});\n\n\t\tthis.proc.on(\"error\", (err) => {\n\t\t\tthis.closed = true;\n\t\t\tfor (const p of this.queue.splice(0)) p.reject(err);\n\t\t});\n\t\tthis.proc.on(\"exit\", (code) => {\n\t\t\tthis.closed = true;\n\t\t\tconst err = new Error(`embsearch daemon exited (code ${code})`);\n\t\t\tfor (const p of this.queue.splice(0)) p.reject(err);\n\t\t});\n\t}\n\n\t/** Resolves once the daemon has loaded the model + index. */\n\tready(): Promise<void> {\n\t\treturn this.readyPromise;\n\t}\n\n\tget isClosed(): boolean {\n\t\treturn this.closed;\n\t}\n\n\tprivate onStdout(chunk: string): void {\n\t\tthis.buffer += chunk;\n\t\t// Each response is one line; dispatch FIFO against the pending queue.\n\t\tfor (let nl = this.buffer.indexOf(\"\\n\"); nl !== -1; nl = this.buffer.indexOf(\"\\n\")) {\n\t\t\tconst line = this.buffer.slice(0, nl).trim();\n\t\t\tthis.buffer = this.buffer.slice(nl + 1);\n\t\t\tif (!line) continue;\n\t\t\tconst pending = this.queue.shift();\n\t\t\tif (!pending) continue;\n\t\t\tlet msg: EmbSearchRawResponse;\n\t\t\ttry {\n\t\t\t\tmsg = JSON.parse(line) as EmbSearchRawResponse;\n\t\t\t} catch {\n\t\t\t\tpending.reject(new Error(`bad response: ${line}`));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (msg.ok) pending.resolve(msg);\n\t\t\telse pending.reject(new Error(msg.error ?? \"unknown error\"));\n\t\t}\n\t}\n\n\tprivate send(req: Record<string, unknown>): Promise<EmbSearchRawResponse> {\n\t\tif (this.closed) return Promise.reject(new Error(\"embsearch client is closed\"));\n\t\treturn new Promise<EmbSearchRawResponse>((resolve, reject) => {\n\t\t\tthis.queue.push({ resolve, reject });\n\t\t\tthis.proc.stdin.write(`${JSON.stringify(req)}\\n`);\n\t\t});\n\t}\n\n\t/**\n\t * Search for the top-`k` matches for `text`.\n\t *\n\t * `retriever` selects which leg answers:\n\t * - `dense` (default) — vector search, the historical behaviour;\n\t * - `lexical` — BM25 only, raw scores, no embedding computed;\n\t * - `hybrid` — both, pre-fused by the daemon's own RRF constant.\n\t *\n\t * `lexical` and `hybrid` need a store created with `--hybrid`. Prefer\n\t * `lexical` over `hybrid` when fusing here: `hybrid` collapses both legs\n\t * into one RRF score, discarding the per-retriever ranks the trace records\n\t * and preventing n-way fusion with the grep leg.\n\t */\n\tasync query(text: string, k = 10, retriever: DaemonRetriever = \"dense\"): Promise<EmbSearchResult[]> {\n\t\tconst res = await this.send(\n\t\t\tretriever === \"dense\" ? { op: \"query\", text, k } : { op: \"query\", text, k, retriever },\n\t\t);\n\t\treturn res.results ?? [];\n\t}\n\n\t/**\n\t * Score `passages` against `query` with the daemon's cross-encoder and\n\t * return the best `k`, best first.\n\t *\n\t * Passages are sent inline rather than referenced by id: the caller has the\n\t * exact spans it intends to show the model, and a cross-encoder scores the\n\t * text it is given, so sending anything else would score the wrong thing.\n\t * Requires an onnx build with reranker weights (embsearch >= 0.3.0).\n\t */\n\tasync rerank(query: string, passages: EmbSearchRerankPassage[], k: number): Promise<EmbSearchRerankResult[]> {\n\t\tconst res = await this.send({ op: \"rerank\", query, passages, k });\n\t\treturn res.reranked ?? [];\n\t}\n\n\t/**\n\t * Batched insert-or-replace. One embedding inference for the whole batch —\n\t * the fast path for bulk indexing. Keep batches modest (e.g. 32–64) so a\n\t * concurrent query is not stuck behind a huge inference.\n\t */\n\tasync bulk(items: Array<{ id: string; text: string }>): Promise<EmbSearchBulkResult> {\n\t\tconst res = await this.send({ op: \"bulk\", items });\n\t\treturn { inserted: res.inserted_count ?? 0, updated: res.updated_count ?? 0 };\n\t}\n\n\t/** Model id, dimensionality, and live vector count of the daemon. */\n\tasync info(): Promise<EmbSearchDaemonInfo> {\n\t\tconst res = await this.send({ op: \"info\" });\n\t\treturn {\n\t\t\tmodelId: res.model_id ?? \"\",\n\t\t\tdim: res.dim ?? 0,\n\t\t\tcount: res.count ?? 0,\n\t\t\thybrid: res.hybrid,\n\t\t\trerank: res.rerank,\n\t\t};\n\t}\n\n\t/** Remove a record. Resolves to `true` if it existed. */\n\tasync remove(id: string): Promise<boolean> {\n\t\tconst res = await this.send({ op: \"remove\", id });\n\t\treturn res.removed === true;\n\t}\n\n\t/** Reclaim tombstoned rows left behind by `remove`. */\n\tasync compact(): Promise<void> {\n\t\tawait this.send({ op: \"compact\" });\n\t}\n\n\t/** Persist the index to the store directory. */\n\tasync save(): Promise<void> {\n\t\tawait this.send({ op: \"save\" });\n\t}\n\n\t/** Shut the daemon down, closing stdin so it exits cleanly. */\n\tasync close(): Promise<void> {\n\t\tif (this.closed) return;\n\t\tthis.proc.stdin.end();\n\t\tawait new Promise<void>((resolve) => this.proc.on(\"exit\", () => resolve()));\n\t}\n}\n"]}
|
|
@@ -38,6 +38,25 @@ export interface EmbsearchServiceOptions {
|
|
|
38
38
|
cwd: string;
|
|
39
39
|
/** Explicit binary path (settings override). Default: "embsearch" from PATH. */
|
|
40
40
|
binaryPath?: string;
|
|
41
|
+
/**
|
|
42
|
+
* Model directory handed to the daemon as `--model`, overriding the model
|
|
43
|
+
* bundled in the binary.
|
|
44
|
+
*
|
|
45
|
+
* Only the eval harness sets this, to score two embedding models from one
|
|
46
|
+
* binary. Pair it with a distinct `storeDir`: vectors from different models
|
|
47
|
+
* are incompatible, and the daemon refuses to open a store built by another
|
|
48
|
+
* model rather than mixing them.
|
|
49
|
+
*/
|
|
50
|
+
modelDir?: string;
|
|
51
|
+
/**
|
|
52
|
+
* Override the chunker's character cap.
|
|
53
|
+
*
|
|
54
|
+
* Only the eval harness sets this, to sweep the chunk window. It changes
|
|
55
|
+
* what every vector in the store *is*, and nothing stored records it, so it
|
|
56
|
+
* must be paired with a distinct `storeDir` exactly as `modelDir` is —
|
|
57
|
+
* otherwise a run silently scores an index built at another cap.
|
|
58
|
+
*/
|
|
59
|
+
chunkMaxChars?: number;
|
|
41
60
|
/** Minimum indexable bytes before indexing kicks in. */
|
|
42
61
|
thresholdBytes: number;
|
|
43
62
|
/**
|
|
@@ -83,6 +102,13 @@ export declare class EmbsearchService {
|
|
|
83
102
|
constructor(options: EmbsearchServiceOptions);
|
|
84
103
|
getState(): EmbsearchState;
|
|
85
104
|
/** Semantic search is usable (index ready, or still building with partial data). */
|
|
105
|
+
/**
|
|
106
|
+
* Model id reported by the running daemon, once it is up.
|
|
107
|
+
*
|
|
108
|
+
* This — not the binary's version — identifies which model produced the
|
|
109
|
+
* vectors in the store, because `--model` decouples the two.
|
|
110
|
+
*/
|
|
111
|
+
modelId(): string | undefined;
|
|
86
112
|
isAvailable(): boolean;
|
|
87
113
|
private setState;
|
|
88
114
|
/**
|
|
@@ -122,6 +148,17 @@ export declare class EmbsearchService {
|
|
|
122
148
|
*/
|
|
123
149
|
rerank(query: string, passages: EmbSearchRerankPassage[], k: number): Promise<EmbSearchRerankResult[]>;
|
|
124
150
|
private probeBinaryVersion;
|
|
151
|
+
/**
|
|
152
|
+
* What the store on disk says about itself, read straight from its manifest.
|
|
153
|
+
*
|
|
154
|
+
* `store-info` exists precisely for the case where the daemon will not open
|
|
155
|
+
* the store: a `serve` pairs a store with an embedder and refuses the pair
|
|
156
|
+
* when their models disagree, so at that moment nothing else can tell us
|
|
157
|
+
* what built it. Returns undefined when there is no readable store — which
|
|
158
|
+
* includes a binary too old to have the subcommand, and so degrades to the
|
|
159
|
+
* previous behaviour rather than guessing.
|
|
160
|
+
*/
|
|
161
|
+
private probeStore;
|
|
125
162
|
private resolveBinary;
|
|
126
163
|
/**
|
|
127
164
|
* Scan, threshold-check, and (when needed) index in the background.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"embsearch-service.d.ts","sourceRoot":"","sources":["../../../src/core/embsearch/embsearch-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAOH,OAAO,EACN,KAAK,eAAe,EAGpB,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC1B,MAAM,aAAa,CAAC;AAuDrB,MAAM,MAAM,cAAc,GACvB;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GACjB;IAAE,KAAK,EAAE,SAAS,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACpC;IAAE,KAAK,EAAE,aAAa,CAAC;IAAC,aAAa,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,GAC1E;IAAE,KAAK,EAAE,UAAU,CAAC;IAAC,IAAI,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I,CAMrF;AAED,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS,CAE7E;AAED,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAE5D","sourcesContent":["/**\n * Orchestrates semantic indexing and search for a repository.\n *\n * Lifecycle (all behind --enable-semantic-index):\n * 1. `start()` — resolve the embsearch binary, scan the repo (ignore-aware),\n * apply the byte threshold. Under threshold → dormant. Over → spawn the\n * daemon, verify the backend is not the mock embedder, then index changed\n * files in the background in small batches, reporting progress.\n * 2. `search()` — top-k semantic query, mapping chunk ids back to\n * `path:start-end` via the sidecar metadata.\n * 3. `dispose()` — save + close the daemon.\n *\n * Every failure degrades to `unavailable` with a reason; nothing here ever\n * blocks session startup or affects grep/find.\n */\n\nimport { execFileSync } from \"child_process\";\nimport { readFileSync, rmSync } from \"fs\";\nimport { minimatch } from \"minimatch\";\nimport { ensureTool } from \"../../utils/tools-manager.js\";\nimport { chunkFile } from \"./chunker.js\";\nimport {\n\ttype DaemonRetriever,\n\tEmbSearchClient,\n\ttype EmbSearchDaemonInfo,\n\ttype EmbSearchRerankPassage,\n\ttype EmbSearchRerankResult,\n} from \"./client.js\";\nimport {\n\temptyIndexMeta,\n\ttype FileMeta,\n\tgetEmbsearchStoreDir,\n\tgetVectorStoreDir,\n\thashContent,\n\ttype IndexMeta,\n\tloadIndexMeta,\n\tsaveIndexMeta,\n} from \"./index-meta.js\";\nimport { type RepoScanFile, scanRepo } from \"./repo-scan.js\";\n\n/** Chunks per bulk request. Small enough that a concurrent query is never\n * stuck long behind one padded batch inference. */\nconst BULK_BATCH_SIZE = 48;\n/** Yield between batches so background indexing doesn't starve the session. */\nconst BATCH_YIELD_MS = 15;\n/** The Rust mock backend's model id — semantically meaningless, never index with it. */\nconst MOCK_MODEL_ID = \"mock-hash-v1\";\n/**\n * First embsearch release serving `retriever: \"lexical\"`.\n *\n * The guard matters because the daemon does not reject unknown request fields:\n * an older binary silently ignores `retriever` and answers with dense results.\n * Fusing that list a second time as a \"bm25\" leg would double-count it and\n * corrupt the ranking with no error anywhere — so refuse instead of degrading.\n */\nconst MIN_LEXICAL_RETRIEVER_VERSION = [0, 2, 0] as const;\n/**\n * First embsearch release serving the `rerank` op.\n *\n * Necessary but no longer sufficient. Releases from 0.3.1 carry the op without\n * the ~23 MB cross-encoder weights — they measured worse than the\n * deterministic reranker on five of six query classes, so they are no longer\n * bundled — and such a daemon answers `rerank` with an error. The version is\n * therefore only the floor for *asking*; `info.rerank` is the answer, and\n * {@link EmbsearchService.supportsCrossEncoder} needs both.\n */\nconst MIN_RERANK_VERSION = [0, 3, 0] as const;\n\n/** `embsearch 0.2.0` -> [0, 2, 0]; undefined when it cannot be parsed. */\nfunction parseBinaryVersion(output: string): number[] | undefined {\n\tconst match = output.match(/(\\d+)\\.(\\d+)\\.(\\d+)/);\n\treturn match ? [Number(match[1]), Number(match[2]), Number(match[3])] : undefined;\n}\n\nfunction atLeast(version: readonly number[], minimum: readonly number[]): boolean {\n\tfor (let i = 0; i < minimum.length; i++) {\n\t\tconst part = version[i] ?? 0;\n\t\tif (part !== minimum[i]) return part > minimum[i];\n\t}\n\treturn true;\n}\n\nexport type EmbsearchState =\n\t| { phase: \"idle\" }\n\t| { phase: \"skipped\"; reason: string }\n\t| { phase: \"downloading\"; receivedBytes: number; totalBytes: number | null }\n\t| { phase: \"indexing\"; done: number; total: number }\n\t| { phase: \"ready\"; chunkCount: number }\n\t| { phase: \"unavailable\"; reason: string };\n\nexport interface EmbsearchServiceOptions {\n\tcwd: string;\n\t/** Explicit binary path (settings override). Default: \"embsearch\" from PATH. */\n\tbinaryPath?: string;\n\t/** Minimum indexable bytes before indexing kicks in. */\n\tthresholdBytes: number;\n\t/**\n\t * Override the store location. Only the eval harness sets this, so a\n\t * second index (e.g. a BM25-hybrid store) can exist for the same repo\n\t * without colliding with the primary one.\n\t */\n\tstoreDir?: string;\n\t/**\n\t * Create the store with the daemon's BM25 lexical index.\n\t *\n\t * Defaults to whatever the daemon can serve. Fixed at store creation, so an\n\t * existing store that disagrees is rebuilt once; when overriding this to\n\t * hold two different stores for one repo, pair it with a distinct\n\t * `storeDir` so they do not fight over the same directory.\n\t */\n\thybridStore?: boolean;\n\t/** Progress callback for UI (footer / stderr lines). */\n\tonProgress?: (state: EmbsearchState) => void;\n}\n\nexport interface SemanticHit {\n\tpath: string;\n\tstartLine: number;\n\tendLine: number;\n\tscore: number;\n}\n\nexport interface SemanticChunkHit extends SemanticHit {\n\t/** Per-build chunk id (`relpath#index`) — the fusion identity for hybrid search. */\n\tid: string;\n}\n\nexport class EmbsearchService {\n\tprivate readonly options: EmbsearchServiceOptions;\n\tprivate client: EmbSearchClient | undefined;\n\tprivate meta: IndexMeta | undefined;\n\tprivate state: EmbsearchState = { phase: \"idle\" };\n\tprivate disposed = false;\n\t/** Whether the resolved binary serves `retriever: \"lexical\"`. */\n\tprivate lexicalRetriever = false;\n\t/** Whether the store actually opened carries a BM25 index. */\n\tprivate hybridStore = false;\n\t/** Whether the resolved binary serves the cross-encoder `rerank` op. */\n\tprivate crossEncoder = false;\n\n\tconstructor(options: EmbsearchServiceOptions) {\n\t\tthis.options = options;\n\t}\n\n\tgetState(): EmbsearchState {\n\t\treturn this.state;\n\t}\n\n\t/** Semantic search is usable (index ready, or still building with partial data). */\n\tisAvailable(): boolean {\n\t\treturn this.state.phase === \"ready\" || this.state.phase === \"indexing\";\n\t}\n\n\tprivate setState(state: EmbsearchState): void {\n\t\tthis.state = state;\n\t\tthis.options.onProgress?.(state);\n\t}\n\n\t/**\n\t * Whether a BM25-only query will work: the daemon has to understand the\n\t * `lexical` retriever *and* the open store has to carry a BM25 index.\n\t */\n\tsupportsLexicalRetriever(): boolean {\n\t\treturn this.lexicalRetriever && this.hybridStore;\n\t}\n\n\t/**\n\t * Repo files whose on-disk content the index does not have — unknown to it,\n\t * or changed since it last read them.\n\t *\n\t * This is the set BM25 is structurally blind to, and the only place the\n\t * grep leg still earns its keep once BM25 is available. An agent that edits\n\t * a file and immediately searches for what it wrote is asking about exactly\n\t * these files; the index cannot answer until the next pass.\n\t *\n\t * Compares mtime and size only, never hashing: the check runs per query, and\n\t * a false positive merely lets grep cover a file BM25 already covers, while\n\t * a false negative would lose the edit.\n\t *\n\t * Deliberately uncached. A cache here caches the *absence* of an edit, which\n\t * is the one thing this must never do — an agent writes a file and searches\n\t * for it in the same breath. A 1s TTL was tried and cost the live-edit set\n\t * 75% to 100% of its score depending on how the timing fell, which is worse\n\t * than wrong: it was non-deterministic. One scan is ~25ms over ~1k files and\n\t * happens once per search, against retrieval that already costs more.\n\t */\n\tstaleFiles(signal?: AbortSignal): string[] {\n\t\tif (!this.meta) return [];\n\t\tconst meta = this.meta;\n\t\tconst files: string[] = [];\n\t\ttry {\n\t\t\tfor (const file of scanRepo(this.options.cwd, signal).files) {\n\t\t\t\tconst known = meta.files[file.rel];\n\t\t\t\tif (!known || known.mtimeMs !== file.mtimeMs || known.size !== file.size) files.push(file.rel);\n\t\t\t}\n\t\t} catch {\n\t\t\t// A failed scan must not silently narrow the grep leg to nothing;\n\t\t\t// report no staleness and let the indexed legs answer.\n\t\t\treturn [];\n\t\t}\n\t\treturn files;\n\t}\n\n\t/** Whether the running daemon can score with a cross-encoder. */\n\tsupportsCrossEncoder(): boolean {\n\t\treturn this.crossEncoder;\n\t}\n\n\t/**\n\t * Cross-encoder rerank of caller-supplied passages.\n\t *\n\t * Unlike the retrievers this does not consult the index at all — it scores\n\t * exactly the text passed in, which is why the caller sends its expanded\n\t * windows rather than chunk ids.\n\t */\n\tasync rerank(query: string, passages: EmbSearchRerankPassage[], k: number): Promise<EmbSearchRerankResult[]> {\n\t\tif (!this.client || this.client.isClosed) {\n\t\t\tthrow new Error(\"semantic index is not available\");\n\t\t}\n\t\tif (!this.crossEncoder) {\n\t\t\tthrow new Error(\n\t\t\t\t`this embsearch daemon cannot rerank (needs >= ${MIN_RERANK_VERSION.join(\".\")} reporting ` +\n\t\t\t\t\t\"`rerank: true`); released binaries ship without cross-encoder weights — start the daemon \" +\n\t\t\t\t\t\"with --reranker-model <dir>\",\n\t\t\t);\n\t\t}\n\t\treturn await this.client.rerank(query, passages, k);\n\t}\n\n\tprivate probeBinaryVersion(binary: string): number[] | undefined {\n\t\ttry {\n\t\t\treturn parseBinaryVersion(execFileSync(binary, [\"--version\"], { encoding: \"utf-8\", timeout: 10_000 }));\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate async resolveBinary(): Promise<string | undefined> {\n\t\tif (this.options.binaryPath) {\n\t\t\treturn this.options.binaryPath;\n\t\t}\n\t\t// Surface the on-demand binary download through the same progress channel as\n\t\t// indexing, so the first-run fetch renders a progress bar instead of a stall.\n\t\t// A cached binary resolves without ever invoking this callback.\n\t\treturn await ensureTool(\"embsearch\", true, (receivedBytes, totalBytes) => {\n\t\t\tthis.setState({ phase: \"downloading\", receivedBytes, totalBytes });\n\t\t});\n\t}\n\n\t/**\n\t * Scan, threshold-check, and (when needed) index in the background.\n\t * Resolves when indexing completes or the feature settles dormant.\n\t */\n\tasync start(signal?: AbortSignal): Promise<void> {\n\t\ttry {\n\t\t\tawait this.run(signal);\n\t\t} catch (e) {\n\t\t\tconst reason = e instanceof Error ? e.message : String(e);\n\t\t\tthis.setState({ phase: \"unavailable\", reason });\n\t\t\tawait this.closeClient();\n\t\t}\n\t}\n\n\tprivate async run(signal?: AbortSignal): Promise<void> {\n\t\tconst binary = await this.resolveBinary();\n\t\tif (!binary) {\n\t\t\tthis.setState({\n\t\t\t\tphase: \"unavailable\",\n\t\t\t\treason: \"embsearch binary not found (PATH or embsearchBinaryPath setting)\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst scan = scanRepo(this.options.cwd, signal);\n\t\tif (scan.totalBytes < this.options.thresholdBytes) {\n\t\t\tthis.setState({\n\t\t\t\tphase: \"skipped\",\n\t\t\t\treason: `repo under threshold (${scan.totalBytes} < ${this.options.thresholdBytes} bytes)`,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst binaryVersion = this.probeBinaryVersion(binary);\n\t\tthis.lexicalRetriever = binaryVersion !== undefined && atLeast(binaryVersion, MIN_LEXICAL_RETRIEVER_VERSION);\n\t\t// Provisional: the version says the daemon understands `rerank`. Whether\n\t\t// it can serve one is answered by `info` below, once the client is up.\n\t\tthis.crossEncoder = binaryVersion !== undefined && atLeast(binaryVersion, MIN_RERANK_VERSION);\n\n\t\tconst storeDir = this.options.storeDir ?? getEmbsearchStoreDir(this.options.cwd);\n\t\t// A hybrid store carries a BM25 index next to its vectors, which is what\n\t\t// lets search use BM25 as its lexical leg instead of ripgrep. Callers may\n\t\t// force it either way; by default it follows what the daemon can serve.\n\t\tconst wantHybrid = this.options.hybridStore ?? this.lexicalRetriever;\n\n\t\tconst openClient = async (): Promise<EmbSearchDaemonInfo> => {\n\t\t\tthis.client = new EmbSearchClient({\n\t\t\t\tbinaryPath: binary,\n\t\t\t\tstorePath: getVectorStoreDir(storeDir),\n\t\t\t\thybrid: wantHybrid,\n\t\t\t});\n\t\t\tawait this.client.ready();\n\t\t\treturn await this.client.info();\n\t\t};\n\n\t\tlet info = await openClient();\n\n\t\t// Hybrid-ness is fixed when a store is created and `--hybrid` against an\n\t\t// existing plain store only warns, so an index built before this was the\n\t\t// default would silently stay dense-only and every BM25 query against it\n\t\t// would fail. Ask the store itself rather than trusting the sidecar, and\n\t\t// rebuild once when it disagrees. `info.hybrid` is undefined on daemons\n\t\t// too old to report it — those cannot serve BM25 anyway, so leave them be.\n\t\tif (wantHybrid && info.hybrid === false) {\n\t\t\tthis.setState({ phase: \"indexing\", done: 0, total: 0 });\n\t\t\tawait this.closeClient();\n\t\t\trmSync(storeDir, { recursive: true, force: true });\n\t\t\tinfo = await openClient();\n\t\t}\n\t\tthis.hybridStore = info.hybrid === true;\n\t\t// A daemon old enough to omit the field is left on the version verdict —\n\t\t// back then the weights were bundled, so version did imply capability.\n\t\tif (info.rerank === false) this.crossEncoder = false;\n\t\tif (info.modelId === MOCK_MODEL_ID) {\n\t\t\tthrow new Error(\"embsearch binary uses the mock embedder (not semantic); install an onnx build\");\n\t\t}\n\n\t\t// Missing/stale sidecar (format, chunker, or model changed) → clean rebuild.\n\t\tthis.meta = loadIndexMeta(storeDir, info.modelId) ?? emptyIndexMeta(this.options.cwd, info.modelId);\n\t\tthis.meta.lastUsedMs = Date.now();\n\n\t\tawait this.indexChangedFiles(scan.files, storeDir, signal);\n\t}\n\n\tprivate async indexChangedFiles(files: RepoScanFile[], storeDir: string, signal?: AbortSignal): Promise<void> {\n\t\tconst meta = this.meta!;\n\t\tconst client = this.client!;\n\n\t\t// Diff scan vs sidecar: cheap mtime+size check first, hash only on delta.\n\t\tconst toIndex: Array<{ file: RepoScanFile; content: string; hash: string }> = [];\n\t\tconst seen = new Set<string>();\n\t\tfor (const file of files) {\n\t\t\tseen.add(file.rel);\n\t\t\tconst known = meta.files[file.rel];\n\t\t\tif (known && known.mtimeMs === file.mtimeMs && known.size === file.size) continue;\n\t\t\tlet content: string;\n\t\t\ttry {\n\t\t\t\tcontent = readFileSync(file.abs, \"utf-8\");\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst hash = hashContent(content);\n\t\t\tif (known && known.hash === hash) {\n\t\t\t\t// Touched but unchanged — refresh stat info only.\n\t\t\t\tknown.mtimeMs = file.mtimeMs;\n\t\t\t\tknown.size = file.size;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttoIndex.push({ file, content, hash });\n\t\t}\n\t\tconst toRemove = Object.keys(meta.files).filter((rel) => !seen.has(rel));\n\n\t\tif (toIndex.length === 0 && toRemove.length === 0) {\n\t\t\tsaveIndexMeta(storeDir, meta);\n\t\t\tthis.setState({ phase: \"ready\", chunkCount: this.countChunks(meta) });\n\t\t\treturn;\n\t\t}\n\n\t\t// Chunk changed files; count total upserts for exact progress.\n\t\tconst work: Array<{ rel: string; fileMeta: FileMeta; chunks: Array<{ id: string; text: string }> }> = [];\n\t\tlet totalChunks = 0;\n\t\tfor (const { file, content, hash } of toIndex) {\n\t\t\tconst chunks = chunkFile(file.rel, content);\n\t\t\twork.push({\n\t\t\t\trel: file.rel,\n\t\t\t\tfileMeta: {\n\t\t\t\t\tmtimeMs: file.mtimeMs,\n\t\t\t\t\tsize: file.size,\n\t\t\t\t\thash,\n\t\t\t\t\tchunks: chunks.map((c) => [c.startLine, c.endLine]),\n\t\t\t\t},\n\t\t\t\tchunks: chunks.map((c) => ({ id: c.id, text: c.text })),\n\t\t\t});\n\t\t\ttotalChunks += chunks.length;\n\t\t}\n\n\t\tthis.setState({ phase: \"indexing\", done: 0, total: totalChunks });\n\n\t\t// Drop vectors of deleted files and superseded chunk tails.\n\t\tfor (const rel of toRemove) {\n\t\t\tfor (let i = 0; i < meta.files[rel].chunks.length; i++) await client.remove(`${rel}#${i}`);\n\t\t\tdelete meta.files[rel];\n\t\t}\n\n\t\tlet done = 0;\n\t\tfor (const item of work) {\n\t\t\tif (signal?.aborted || this.disposed) return;\n\t\t\tconst oldChunkCount = meta.files[item.rel]?.chunks.length ?? 0;\n\t\t\t// Remove old chunks beyond the new count (upsert covers the rest).\n\t\t\tfor (let i = item.chunks.length; i < oldChunkCount; i++) await client.remove(`${item.rel}#${i}`);\n\n\t\t\tfor (let offset = 0; offset < item.chunks.length; offset += BULK_BATCH_SIZE) {\n\t\t\t\tif (signal?.aborted || this.disposed) return;\n\t\t\t\tconst batch = item.chunks.slice(offset, offset + BULK_BATCH_SIZE);\n\t\t\t\tawait client.bulk(batch);\n\t\t\t\tdone += batch.length;\n\t\t\t\tthis.setState({ phase: \"indexing\", done, total: totalChunks });\n\t\t\t\t// Yield so queries and the event loop stay responsive.\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, BATCH_YIELD_MS));\n\t\t\t}\n\t\t\tmeta.files[item.rel] = item.fileMeta;\n\t\t}\n\n\t\tawait client.compact();\n\t\tawait client.save();\n\t\tsaveIndexMeta(storeDir, meta);\n\t\tthis.setState({ phase: \"ready\", chunkCount: this.countChunks(meta) });\n\t}\n\n\tprivate countChunks(meta: IndexMeta): number {\n\t\tlet n = 0;\n\t\tfor (const rel of Object.keys(meta.files)) n += meta.files[rel].chunks.length;\n\t\treturn n;\n\t}\n\n\t/** Top-`k` semantic hits as `path` + line range + score. */\n\tasync search(query: string, k = 10): Promise<SemanticHit[]> {\n\t\treturn await this.searchChunks(query, k);\n\t}\n\n\t/** Top-`k` semantic hits including their chunk ids, for rank fusion. */\n\tasync searchChunks(\n\t\tquery: string,\n\t\tk = 10,\n\t\tglob?: string,\n\t\tretriever: DaemonRetriever = \"dense\",\n\t): Promise<SemanticChunkHit[]> {\n\t\tif (!this.client || this.client.isClosed || !this.meta) {\n\t\t\tthrow new Error(\"semantic index is not available\");\n\t\t}\n\t\tif (retriever === \"lexical\" && !this.lexicalRetriever) {\n\t\t\tthrow new Error(\n\t\t\t\t`embsearch is too old for retriever \"lexical\" (needs >= ${MIN_LEXICAL_RETRIEVER_VERSION.join(\".\")}); ` +\n\t\t\t\t\t\"an older daemon ignores the field and answers with dense results\",\n\t\t\t);\n\t\t}\n\t\tconst results = await this.client.query(query, k, retriever);\n\t\tconst hits: SemanticChunkHit[] = [];\n\t\tconst matchGlob = (rel: string): boolean => {\n\t\t\tif (!glob) return true;\n\t\t\treturn minimatch(rel, glob, { dot: true, matchBase: !glob.includes(\"/\") });\n\t\t};\n\t\tfor (const result of results) {\n\t\t\tconst sep = result.id.lastIndexOf(\"#\");\n\t\t\tif (sep === -1) continue;\n\t\t\tconst rel = result.id.slice(0, sep);\n\t\t\tif (!matchGlob(rel)) continue;\n\t\t\tconst chunkIndex = Number.parseInt(result.id.slice(sep + 1), 10);\n\t\t\tconst range = this.meta.files[rel]?.chunks[chunkIndex];\n\t\t\tif (!range) continue;\n\t\t\thits.push({ id: result.id, path: rel, startLine: range[0], endLine: range[1], score: result.score });\n\t\t}\n\t\treturn hits;\n\t}\n\n\t/**\n\t * Resolve a repo-relative path + line to its enclosing indexed chunk, or\n\t * undefined when the file/line is not covered by the index. Chunks overlap\n\t * by a few lines; the first (lowest-index) containing chunk wins so the\n\t * mapping is deterministic.\n\t */\n\tfindEnclosingChunk(\n\t\trel: string,\n\t\tline: number,\n\t): { id: string; path: string; startLine: number; endLine: number } | undefined {\n\t\tconst file = this.meta?.files[rel];\n\t\tif (!file) return undefined;\n\t\tfor (let i = 0; i < file.chunks.length; i++) {\n\t\t\tconst [startLine, endLine] = file.chunks[i];\n\t\t\tif (line >= startLine && line <= endLine) {\n\t\t\t\treturn { id: `${rel}#${i}`, path: rel, startLine, endLine };\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate async closeClient(): Promise<void> {\n\t\tconst client = this.client;\n\t\tthis.client = undefined;\n\t\tif (client && !client.isClosed) {\n\t\t\ttry {\n\t\t\t\tawait client.close();\n\t\t\t} catch {\n\t\t\t\t// already dead\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Persist state and shut the daemon down. Safe to call twice. */\n\tasync dispose(): Promise<void> {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\t\tif (this.client && !this.client.isClosed) {\n\t\t\ttry {\n\t\t\t\tawait this.client.save();\n\t\t\t} catch {\n\t\t\t\t// daemon may have exited; nothing to save\n\t\t\t}\n\t\t}\n\t\tawait this.closeClient();\n\t}\n}\n\n// --- Per-cwd service registry ---\n//\n// The search tool is constructed by the generic tool factory table and\n// only receives `cwd`; the service is created later during session init (flag\n// gated). This registry connects the two without threading a service instance\n// through every layer between main.ts and the tool factories.\n\nconst services = new Map<string, EmbsearchService>();\n\nexport function registerEmbsearchService(cwd: string, service: EmbsearchService): void {\n\tconst old = services.get(cwd);\n\tif (old && old !== service) {\n\t\told.dispose().catch(() => {});\n\t}\n\tservices.set(cwd, service);\n}\n\nexport function getEmbsearchService(cwd: string): EmbsearchService | undefined {\n\treturn services.get(cwd);\n}\n\nexport function unregisterEmbsearchService(cwd: string): void {\n\tservices.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OAAO,CAAC,IAAI,CAAC,CAQ/C;YAEa,GAAG;YAiHH,iBAAiB;IAqF/B,OAAO,CAAC,WAAW;IAMnB,4DAA4D;IACtD,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC,SAAK,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAE1D;IAED,wEAAwE;IAClE,YAAY,CACjB,KAAK,EAAE,MAAM,EACb,CAAC,SAAK,EACN,IAAI,CAAC,EAAE,MAAM,EACb,SAAS,GAAE,eAAyB,GAClC,OAAO,CAAC,gBAAgB,EAAE,CAAC,CA2B7B;IAED;;;;;OAKG;IACH,kBAAkB,CACjB,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,GACV;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAU9E;YAEa,WAAW;IAYzB,kEAAkE;IAC5D,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAW7B;CACD;AAWD,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,GAAG,IAAI,CAMrF;AAED,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS,CAE7E;AAED,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAE5D","sourcesContent":["/**\n * Orchestrates semantic indexing and search for a repository.\n *\n * Lifecycle (all behind --enable-semantic-index):\n * 1. `start()` — resolve the embsearch binary, scan the repo (ignore-aware),\n * apply the byte threshold. Under threshold → dormant. Over → spawn the\n * daemon, verify the backend is not the mock embedder, then index changed\n * files in the background in small batches, reporting progress.\n * 2. `search()` — top-k semantic query, mapping chunk ids back to\n * `path:start-end` via the sidecar metadata.\n * 3. `dispose()` — save + close the daemon.\n *\n * Every failure degrades to `unavailable` with a reason; nothing here ever\n * blocks session startup or affects grep/find.\n */\n\nimport { execFileSync } from \"child_process\";\nimport { readFileSync, rmSync } from \"fs\";\nimport { minimatch } from \"minimatch\";\nimport { ensureTool } from \"../../utils/tools-manager.js\";\nimport { chunkFile } from \"./chunker.js\";\nimport {\n\ttype DaemonRetriever,\n\tEmbSearchClient,\n\ttype EmbSearchDaemonInfo,\n\ttype EmbSearchRerankPassage,\n\ttype EmbSearchRerankResult,\n} from \"./client.js\";\nimport {\n\temptyIndexMeta,\n\ttype FileMeta,\n\tgetEmbsearchStoreDir,\n\tgetVectorStoreDir,\n\thashContent,\n\ttype IndexMeta,\n\tloadIndexMeta,\n\tsaveIndexMeta,\n} from \"./index-meta.js\";\nimport { type RepoScanFile, scanRepo } from \"./repo-scan.js\";\n\n/** Chunks per bulk request. Small enough that a concurrent query is never\n * stuck long behind one padded batch inference. */\nconst BULK_BATCH_SIZE = 48;\n/** Yield between batches so background indexing doesn't starve the session. */\nconst BATCH_YIELD_MS = 15;\n/** The Rust mock backend's model id — semantically meaningless, never index with it. */\nconst MOCK_MODEL_ID = \"mock-hash-v1\";\n/**\n * First embsearch release serving `retriever: \"lexical\"`.\n *\n * The guard matters because the daemon does not reject unknown request fields:\n * an older binary silently ignores `retriever` and answers with dense results.\n * Fusing that list a second time as a \"bm25\" leg would double-count it and\n * corrupt the ranking with no error anywhere — so refuse instead of degrading.\n */\nconst MIN_LEXICAL_RETRIEVER_VERSION = [0, 2, 0] as const;\n/**\n * First embsearch release serving the `rerank` op.\n *\n * Necessary but no longer sufficient. Releases from 0.3.1 carry the op without\n * the ~23 MB cross-encoder weights — they measured worse than the\n * deterministic reranker on five of six query classes, so they are no longer\n * bundled — and such a daemon answers `rerank` with an error. The version is\n * therefore only the floor for *asking*; `info.rerank` is the answer, and\n * {@link EmbsearchService.supportsCrossEncoder} needs both.\n */\nconst MIN_RERANK_VERSION = [0, 3, 0] as const;\n\n/** `embsearch 0.2.0` -> [0, 2, 0]; undefined when it cannot be parsed. */\nfunction parseBinaryVersion(output: string): number[] | undefined {\n\tconst match = output.match(/(\\d+)\\.(\\d+)\\.(\\d+)/);\n\treturn match ? [Number(match[1]), Number(match[2]), Number(match[3])] : undefined;\n}\n\nfunction atLeast(version: readonly number[], minimum: readonly number[]): boolean {\n\tfor (let i = 0; i < minimum.length; i++) {\n\t\tconst part = version[i] ?? 0;\n\t\tif (part !== minimum[i]) return part > minimum[i];\n\t}\n\treturn true;\n}\n\nexport type EmbsearchState =\n\t| { phase: \"idle\" }\n\t| { phase: \"skipped\"; reason: string }\n\t| { phase: \"downloading\"; receivedBytes: number; totalBytes: number | null }\n\t| { phase: \"indexing\"; done: number; total: number }\n\t| { phase: \"ready\"; chunkCount: number }\n\t| { phase: \"unavailable\"; reason: string };\n\nexport interface EmbsearchServiceOptions {\n\tcwd: string;\n\t/** Explicit binary path (settings override). Default: \"embsearch\" from PATH. */\n\tbinaryPath?: string;\n\t/**\n\t * Model directory handed to the daemon as `--model`, overriding the model\n\t * bundled in the binary.\n\t *\n\t * Only the eval harness sets this, to score two embedding models from one\n\t * binary. Pair it with a distinct `storeDir`: vectors from different models\n\t * are incompatible, and the daemon refuses to open a store built by another\n\t * model rather than mixing them.\n\t */\n\tmodelDir?: string;\n\t/**\n\t * Override the chunker's character cap.\n\t *\n\t * Only the eval harness sets this, to sweep the chunk window. It changes\n\t * what every vector in the store *is*, and nothing stored records it, so it\n\t * must be paired with a distinct `storeDir` exactly as `modelDir` is —\n\t * otherwise a run silently scores an index built at another cap.\n\t */\n\tchunkMaxChars?: number;\n\t/** Minimum indexable bytes before indexing kicks in. */\n\tthresholdBytes: number;\n\t/**\n\t * Override the store location. Only the eval harness sets this, so a\n\t * second index (e.g. a BM25-hybrid store) can exist for the same repo\n\t * without colliding with the primary one.\n\t */\n\tstoreDir?: string;\n\t/**\n\t * Create the store with the daemon's BM25 lexical index.\n\t *\n\t * Defaults to whatever the daemon can serve. Fixed at store creation, so an\n\t * existing store that disagrees is rebuilt once; when overriding this to\n\t * hold two different stores for one repo, pair it with a distinct\n\t * `storeDir` so they do not fight over the same directory.\n\t */\n\thybridStore?: boolean;\n\t/** Progress callback for UI (footer / stderr lines). */\n\tonProgress?: (state: EmbsearchState) => void;\n}\n\nexport interface SemanticHit {\n\tpath: string;\n\tstartLine: number;\n\tendLine: number;\n\tscore: number;\n}\n\nexport interface SemanticChunkHit extends SemanticHit {\n\t/** Per-build chunk id (`relpath#index`) — the fusion identity for hybrid search. */\n\tid: string;\n}\n\nexport class EmbsearchService {\n\tprivate readonly options: EmbsearchServiceOptions;\n\tprivate client: EmbSearchClient | undefined;\n\tprivate meta: IndexMeta | undefined;\n\tprivate state: EmbsearchState = { phase: \"idle\" };\n\tprivate disposed = false;\n\t/** Whether the resolved binary serves `retriever: \"lexical\"`. */\n\tprivate lexicalRetriever = false;\n\t/** Whether the store actually opened carries a BM25 index. */\n\tprivate hybridStore = false;\n\t/** Whether the resolved binary serves the cross-encoder `rerank` op. */\n\tprivate crossEncoder = false;\n\n\tconstructor(options: EmbsearchServiceOptions) {\n\t\tthis.options = options;\n\t}\n\n\tgetState(): EmbsearchState {\n\t\treturn this.state;\n\t}\n\n\t/** Semantic search is usable (index ready, or still building with partial data). */\n\t/**\n\t * Model id reported by the running daemon, once it is up.\n\t *\n\t * This — not the binary's version — identifies which model produced the\n\t * vectors in the store, because `--model` decouples the two.\n\t */\n\tmodelId(): string | undefined {\n\t\treturn this.meta?.modelId;\n\t}\n\n\tisAvailable(): boolean {\n\t\treturn this.state.phase === \"ready\" || this.state.phase === \"indexing\";\n\t}\n\n\tprivate setState(state: EmbsearchState): void {\n\t\tthis.state = state;\n\t\tthis.options.onProgress?.(state);\n\t}\n\n\t/**\n\t * Whether a BM25-only query will work: the daemon has to understand the\n\t * `lexical` retriever *and* the open store has to carry a BM25 index.\n\t */\n\tsupportsLexicalRetriever(): boolean {\n\t\treturn this.lexicalRetriever && this.hybridStore;\n\t}\n\n\t/**\n\t * Repo files whose on-disk content the index does not have — unknown to it,\n\t * or changed since it last read them.\n\t *\n\t * This is the set BM25 is structurally blind to, and the only place the\n\t * grep leg still earns its keep once BM25 is available. An agent that edits\n\t * a file and immediately searches for what it wrote is asking about exactly\n\t * these files; the index cannot answer until the next pass.\n\t *\n\t * Compares mtime and size only, never hashing: the check runs per query, and\n\t * a false positive merely lets grep cover a file BM25 already covers, while\n\t * a false negative would lose the edit.\n\t *\n\t * Deliberately uncached. A cache here caches the *absence* of an edit, which\n\t * is the one thing this must never do — an agent writes a file and searches\n\t * for it in the same breath. A 1s TTL was tried and cost the live-edit set\n\t * 75% to 100% of its score depending on how the timing fell, which is worse\n\t * than wrong: it was non-deterministic. One scan is ~25ms over ~1k files and\n\t * happens once per search, against retrieval that already costs more.\n\t */\n\tstaleFiles(signal?: AbortSignal): string[] {\n\t\tif (!this.meta) return [];\n\t\tconst meta = this.meta;\n\t\tconst files: string[] = [];\n\t\ttry {\n\t\t\tfor (const file of scanRepo(this.options.cwd, signal).files) {\n\t\t\t\tconst known = meta.files[file.rel];\n\t\t\t\tif (!known || known.mtimeMs !== file.mtimeMs || known.size !== file.size) files.push(file.rel);\n\t\t\t}\n\t\t} catch {\n\t\t\t// A failed scan must not silently narrow the grep leg to nothing;\n\t\t\t// report no staleness and let the indexed legs answer.\n\t\t\treturn [];\n\t\t}\n\t\treturn files;\n\t}\n\n\t/** Whether the running daemon can score with a cross-encoder. */\n\tsupportsCrossEncoder(): boolean {\n\t\treturn this.crossEncoder;\n\t}\n\n\t/**\n\t * Cross-encoder rerank of caller-supplied passages.\n\t *\n\t * Unlike the retrievers this does not consult the index at all — it scores\n\t * exactly the text passed in, which is why the caller sends its expanded\n\t * windows rather than chunk ids.\n\t */\n\tasync rerank(query: string, passages: EmbSearchRerankPassage[], k: number): Promise<EmbSearchRerankResult[]> {\n\t\tif (!this.client || this.client.isClosed) {\n\t\t\tthrow new Error(\"semantic index is not available\");\n\t\t}\n\t\tif (!this.crossEncoder) {\n\t\t\tthrow new Error(\n\t\t\t\t`this embsearch daemon cannot rerank (needs >= ${MIN_RERANK_VERSION.join(\".\")} reporting ` +\n\t\t\t\t\t\"`rerank: true`); released binaries ship without cross-encoder weights — start the daemon \" +\n\t\t\t\t\t\"with --reranker-model <dir>\",\n\t\t\t);\n\t\t}\n\t\treturn await this.client.rerank(query, passages, k);\n\t}\n\n\tprivate probeBinaryVersion(binary: string): number[] | undefined {\n\t\ttry {\n\t\t\treturn parseBinaryVersion(execFileSync(binary, [\"--version\"], { encoding: \"utf-8\", timeout: 10_000 }));\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t/**\n\t * What the store on disk says about itself, read straight from its manifest.\n\t *\n\t * `store-info` exists precisely for the case where the daemon will not open\n\t * the store: a `serve` pairs a store with an embedder and refuses the pair\n\t * when their models disagree, so at that moment nothing else can tell us\n\t * what built it. Returns undefined when there is no readable store — which\n\t * includes a binary too old to have the subcommand, and so degrades to the\n\t * previous behaviour rather than guessing.\n\t */\n\tprivate probeStore(binary: string, storeDir: string): { modelId: string; live: number } | undefined {\n\t\ttry {\n\t\t\tconst out = execFileSync(binary, [\"store-info\", \"--path\", getVectorStoreDir(storeDir), \"--json\"], {\n\t\t\t\tencoding: \"utf-8\",\n\t\t\t\ttimeout: 10_000,\n\t\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t\t});\n\t\t\tconst parsed = JSON.parse(out) as { model_id?: string; live?: number };\n\t\t\tif (typeof parsed.model_id !== \"string\") return undefined;\n\t\t\treturn { modelId: parsed.model_id, live: parsed.live ?? 0 };\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate async resolveBinary(): Promise<string | undefined> {\n\t\tif (this.options.binaryPath) {\n\t\t\treturn this.options.binaryPath;\n\t\t}\n\t\t// Surface the on-demand binary download through the same progress channel as\n\t\t// indexing, so the first-run fetch renders a progress bar instead of a stall.\n\t\t// A cached binary resolves without ever invoking this callback.\n\t\treturn await ensureTool(\"embsearch\", true, (receivedBytes, totalBytes) => {\n\t\t\tthis.setState({ phase: \"downloading\", receivedBytes, totalBytes });\n\t\t});\n\t}\n\n\t/**\n\t * Scan, threshold-check, and (when needed) index in the background.\n\t * Resolves when indexing completes or the feature settles dormant.\n\t */\n\tasync start(signal?: AbortSignal): Promise<void> {\n\t\ttry {\n\t\t\tawait this.run(signal);\n\t\t} catch (e) {\n\t\t\tconst reason = e instanceof Error ? e.message : String(e);\n\t\t\tthis.setState({ phase: \"unavailable\", reason });\n\t\t\tawait this.closeClient();\n\t\t}\n\t}\n\n\tprivate async run(signal?: AbortSignal): Promise<void> {\n\t\tconst binary = await this.resolveBinary();\n\t\tif (!binary) {\n\t\t\tthis.setState({\n\t\t\t\tphase: \"unavailable\",\n\t\t\t\treason: \"embsearch binary not found (PATH or embsearchBinaryPath setting)\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst scan = scanRepo(this.options.cwd, signal);\n\t\tif (scan.totalBytes < this.options.thresholdBytes) {\n\t\t\tthis.setState({\n\t\t\t\tphase: \"skipped\",\n\t\t\t\treason: `repo under threshold (${scan.totalBytes} < ${this.options.thresholdBytes} bytes)`,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst binaryVersion = this.probeBinaryVersion(binary);\n\t\tthis.lexicalRetriever = binaryVersion !== undefined && atLeast(binaryVersion, MIN_LEXICAL_RETRIEVER_VERSION);\n\t\t// Provisional: the version says the daemon understands `rerank`. Whether\n\t\t// it can serve one is answered by `info` below, once the client is up.\n\t\tthis.crossEncoder = binaryVersion !== undefined && atLeast(binaryVersion, MIN_RERANK_VERSION);\n\n\t\tconst storeDir = this.options.storeDir ?? getEmbsearchStoreDir(this.options.cwd);\n\t\t// A hybrid store carries a BM25 index next to its vectors, which is what\n\t\t// lets search use BM25 as its lexical leg instead of ripgrep. Callers may\n\t\t// force it either way; by default it follows what the daemon can serve.\n\t\tconst wantHybrid = this.options.hybridStore ?? this.lexicalRetriever;\n\n\t\tconst openClient = async (): Promise<EmbSearchDaemonInfo> => {\n\t\t\tthis.client = new EmbSearchClient({\n\t\t\t\tbinaryPath: binary,\n\t\t\t\tstorePath: getVectorStoreDir(storeDir),\n\t\t\t\thybrid: wantHybrid,\n\t\t\t\tmodelDir: this.options.modelDir,\n\t\t\t});\n\t\t\tawait this.client.ready();\n\t\t\treturn await this.client.info();\n\t\t};\n\n\t\t/** Discard the store and start clean. The only recovery from a store the\n\t\t * current binary cannot use — and the only way to be rid of vectors that\n\t\t * outlived the metadata describing them. */\n\t\tconst rebuildFrom = async (why: string): Promise<EmbSearchDaemonInfo> => {\n\t\t\tconsole.error(`embsearch: rebuilding the index (${why})`);\n\t\t\tthis.setState({ phase: \"indexing\", done: 0, total: 0 });\n\t\t\tawait this.closeClient();\n\t\t\trmSync(storeDir, { recursive: true, force: true });\n\t\t\treturn await openClient();\n\t\t};\n\n\t\tlet info: EmbSearchDaemonInfo;\n\t\ttry {\n\t\t\tinfo = await openClient();\n\t\t} catch (err) {\n\t\t\t// The daemon refuses to open a store whose recorded model disagrees\n\t\t\t// with its own — correctly, since vectors from different models are\n\t\t\t// not comparable. But refusing is where it stopped: the store stayed\n\t\t\t// on disk, the daemon never came up, and this service went\n\t\t\t// permanently unavailable with a rebuild one directory-removal away.\n\t\t\t//\n\t\t\t// Only a store that is present and *readable* is treated this way. If\n\t\t\t// `store-info` cannot read it either, the problem is not a model\n\t\t\t// mismatch and destroying an index would be the wrong response, so\n\t\t\t// the original failure stands.\n\t\t\tconst store = this.probeStore(binary, storeDir);\n\t\t\tif (!store) throw err;\n\t\t\tinfo = await rebuildFrom(`built by model '${store.modelId}', which this binary cannot read`);\n\t\t}\n\n\t\t// Hybrid-ness is fixed when a store is created and `--hybrid` against an\n\t\t// existing plain store only warns, so an index built before this was the\n\t\t// default would silently stay dense-only and every BM25 query against it\n\t\t// would fail. Ask the store itself rather than trusting the sidecar, and\n\t\t// rebuild once when it disagrees. `info.hybrid` is undefined on daemons\n\t\t// too old to report it — those cannot serve BM25 anyway, so leave them be.\n\t\tif (wantHybrid && info.hybrid === false) {\n\t\t\tinfo = await rebuildFrom(\"the existing store carries no BM25 index\");\n\t\t}\n\t\tthis.hybridStore = info.hybrid === true;\n\t\t// A daemon old enough to omit the field is left on the version verdict —\n\t\t// back then the weights were bundled, so version did imply capability.\n\t\tif (info.rerank === false) this.crossEncoder = false;\n\t\tif (info.modelId === MOCK_MODEL_ID) {\n\t\t\tthrow new Error(\"embsearch binary uses the mock embedder (not semantic); install an onnx build\");\n\t\t}\n\n\t\t// Missing/stale sidecar (format, chunker, or model changed) → clean rebuild.\n\t\t//\n\t\t// Resetting the sidecar alone is not enough, and used to be all this did.\n\t\t// The sidecar is the only record of how many chunks each file produced,\n\t\t// so an empty one reports zero for every file — and `indexChangedFiles`\n\t\t// removes stale chunks by counting down from that number. Re-chunking a\n\t\t// file into *fewer* pieces then leaves its tail vectors (`path#N`,\n\t\t// `path#N+1`, …) in the store, holding text that no longer exists\n\t\t// anywhere, retrievable forever. Upserts hide it: chunk counts look\n\t\t// right, the sidecar looks right, and only search results are wrong.\n\t\t//\n\t\t// So when the sidecar cannot be trusted and the store is not already\n\t\t// empty, the store goes too.\n\t\tlet meta = loadIndexMeta(storeDir, info.modelId);\n\t\tif (!meta && info.count > 0) {\n\t\t\tinfo = await rebuildFrom(\"index metadata is missing or was written by a different chunker or model\");\n\t\t\tmeta = loadIndexMeta(storeDir, info.modelId);\n\t\t}\n\t\tthis.meta = meta ?? emptyIndexMeta(this.options.cwd, info.modelId);\n\t\tthis.meta.lastUsedMs = Date.now();\n\n\t\tawait this.indexChangedFiles(scan.files, storeDir, signal);\n\t}\n\n\tprivate async indexChangedFiles(files: RepoScanFile[], storeDir: string, signal?: AbortSignal): Promise<void> {\n\t\tconst meta = this.meta!;\n\t\tconst client = this.client!;\n\n\t\t// Diff scan vs sidecar: cheap mtime+size check first, hash only on delta.\n\t\tconst toIndex: Array<{ file: RepoScanFile; content: string; hash: string }> = [];\n\t\tconst seen = new Set<string>();\n\t\tfor (const file of files) {\n\t\t\tseen.add(file.rel);\n\t\t\tconst known = meta.files[file.rel];\n\t\t\tif (known && known.mtimeMs === file.mtimeMs && known.size === file.size) continue;\n\t\t\tlet content: string;\n\t\t\ttry {\n\t\t\t\tcontent = readFileSync(file.abs, \"utf-8\");\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst hash = hashContent(content);\n\t\t\tif (known && known.hash === hash) {\n\t\t\t\t// Touched but unchanged — refresh stat info only.\n\t\t\t\tknown.mtimeMs = file.mtimeMs;\n\t\t\t\tknown.size = file.size;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttoIndex.push({ file, content, hash });\n\t\t}\n\t\tconst toRemove = Object.keys(meta.files).filter((rel) => !seen.has(rel));\n\n\t\tif (toIndex.length === 0 && toRemove.length === 0) {\n\t\t\tsaveIndexMeta(storeDir, meta);\n\t\t\tthis.setState({ phase: \"ready\", chunkCount: this.countChunks(meta) });\n\t\t\treturn;\n\t\t}\n\n\t\t// Chunk changed files; count total upserts for exact progress.\n\t\tconst work: Array<{ rel: string; fileMeta: FileMeta; chunks: Array<{ id: string; text: string }> }> = [];\n\t\tlet totalChunks = 0;\n\t\tfor (const { file, content, hash } of toIndex) {\n\t\t\tconst chunks = chunkFile(file.rel, content, this.options.chunkMaxChars);\n\t\t\twork.push({\n\t\t\t\trel: file.rel,\n\t\t\t\tfileMeta: {\n\t\t\t\t\tmtimeMs: file.mtimeMs,\n\t\t\t\t\tsize: file.size,\n\t\t\t\t\thash,\n\t\t\t\t\tchunks: chunks.map((c) => [c.startLine, c.endLine]),\n\t\t\t\t},\n\t\t\t\tchunks: chunks.map((c) => ({ id: c.id, text: c.text })),\n\t\t\t});\n\t\t\ttotalChunks += chunks.length;\n\t\t}\n\n\t\tthis.setState({ phase: \"indexing\", done: 0, total: totalChunks });\n\n\t\t// Drop vectors of deleted files and superseded chunk tails.\n\t\tfor (const rel of toRemove) {\n\t\t\tfor (let i = 0; i < meta.files[rel].chunks.length; i++) await client.remove(`${rel}#${i}`);\n\t\t\tdelete meta.files[rel];\n\t\t}\n\n\t\tlet done = 0;\n\t\tfor (const item of work) {\n\t\t\tif (signal?.aborted || this.disposed) return;\n\t\t\tconst oldChunkCount = meta.files[item.rel]?.chunks.length ?? 0;\n\t\t\t// Remove old chunks beyond the new count (upsert covers the rest).\n\t\t\tfor (let i = item.chunks.length; i < oldChunkCount; i++) await client.remove(`${item.rel}#${i}`);\n\n\t\t\tfor (let offset = 0; offset < item.chunks.length; offset += BULK_BATCH_SIZE) {\n\t\t\t\tif (signal?.aborted || this.disposed) return;\n\t\t\t\tconst batch = item.chunks.slice(offset, offset + BULK_BATCH_SIZE);\n\t\t\t\tawait client.bulk(batch);\n\t\t\t\tdone += batch.length;\n\t\t\t\tthis.setState({ phase: \"indexing\", done, total: totalChunks });\n\t\t\t\t// Yield so queries and the event loop stay responsive.\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, BATCH_YIELD_MS));\n\t\t\t}\n\t\t\tmeta.files[item.rel] = item.fileMeta;\n\t\t}\n\n\t\tawait client.compact();\n\t\tawait client.save();\n\t\tsaveIndexMeta(storeDir, meta);\n\t\tthis.setState({ phase: \"ready\", chunkCount: this.countChunks(meta) });\n\t}\n\n\tprivate countChunks(meta: IndexMeta): number {\n\t\tlet n = 0;\n\t\tfor (const rel of Object.keys(meta.files)) n += meta.files[rel].chunks.length;\n\t\treturn n;\n\t}\n\n\t/** Top-`k` semantic hits as `path` + line range + score. */\n\tasync search(query: string, k = 10): Promise<SemanticHit[]> {\n\t\treturn await this.searchChunks(query, k);\n\t}\n\n\t/** Top-`k` semantic hits including their chunk ids, for rank fusion. */\n\tasync searchChunks(\n\t\tquery: string,\n\t\tk = 10,\n\t\tglob?: string,\n\t\tretriever: DaemonRetriever = \"dense\",\n\t): Promise<SemanticChunkHit[]> {\n\t\tif (!this.client || this.client.isClosed || !this.meta) {\n\t\t\tthrow new Error(\"semantic index is not available\");\n\t\t}\n\t\tif (retriever === \"lexical\" && !this.lexicalRetriever) {\n\t\t\tthrow new Error(\n\t\t\t\t`embsearch is too old for retriever \"lexical\" (needs >= ${MIN_LEXICAL_RETRIEVER_VERSION.join(\".\")}); ` +\n\t\t\t\t\t\"an older daemon ignores the field and answers with dense results\",\n\t\t\t);\n\t\t}\n\t\tconst results = await this.client.query(query, k, retriever);\n\t\tconst hits: SemanticChunkHit[] = [];\n\t\tconst matchGlob = (rel: string): boolean => {\n\t\t\tif (!glob) return true;\n\t\t\treturn minimatch(rel, glob, { dot: true, matchBase: !glob.includes(\"/\") });\n\t\t};\n\t\tfor (const result of results) {\n\t\t\tconst sep = result.id.lastIndexOf(\"#\");\n\t\t\tif (sep === -1) continue;\n\t\t\tconst rel = result.id.slice(0, sep);\n\t\t\tif (!matchGlob(rel)) continue;\n\t\t\tconst chunkIndex = Number.parseInt(result.id.slice(sep + 1), 10);\n\t\t\tconst range = this.meta.files[rel]?.chunks[chunkIndex];\n\t\t\tif (!range) continue;\n\t\t\thits.push({ id: result.id, path: rel, startLine: range[0], endLine: range[1], score: result.score });\n\t\t}\n\t\treturn hits;\n\t}\n\n\t/**\n\t * Resolve a repo-relative path + line to its enclosing indexed chunk, or\n\t * undefined when the file/line is not covered by the index. Chunks overlap\n\t * by a few lines; the first (lowest-index) containing chunk wins so the\n\t * mapping is deterministic.\n\t */\n\tfindEnclosingChunk(\n\t\trel: string,\n\t\tline: number,\n\t): { id: string; path: string; startLine: number; endLine: number } | undefined {\n\t\tconst file = this.meta?.files[rel];\n\t\tif (!file) return undefined;\n\t\tfor (let i = 0; i < file.chunks.length; i++) {\n\t\t\tconst [startLine, endLine] = file.chunks[i];\n\t\t\tif (line >= startLine && line <= endLine) {\n\t\t\t\treturn { id: `${rel}#${i}`, path: rel, startLine, endLine };\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate async closeClient(): Promise<void> {\n\t\tconst client = this.client;\n\t\tthis.client = undefined;\n\t\tif (client && !client.isClosed) {\n\t\t\ttry {\n\t\t\t\tawait client.close();\n\t\t\t} catch {\n\t\t\t\t// already dead\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Persist state and shut the daemon down. Safe to call twice. */\n\tasync dispose(): Promise<void> {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\t\tif (this.client && !this.client.isClosed) {\n\t\t\ttry {\n\t\t\t\tawait this.client.save();\n\t\t\t} catch {\n\t\t\t\t// daemon may have exited; nothing to save\n\t\t\t}\n\t\t}\n\t\tawait this.closeClient();\n\t}\n}\n\n// --- Per-cwd service registry ---\n//\n// The search tool is constructed by the generic tool factory table and\n// only receives `cwd`; the service is created later during session init (flag\n// gated). This registry connects the two without threading a service instance\n// through every layer between main.ts and the tool factories.\n\nconst services = new Map<string, EmbsearchService>();\n\nexport function registerEmbsearchService(cwd: string, service: EmbsearchService): void {\n\tconst old = services.get(cwd);\n\tif (old && old !== service) {\n\t\told.dispose().catch(() => {});\n\t}\n\tservices.set(cwd, service);\n}\n\nexport function getEmbsearchService(cwd: string): EmbsearchService | undefined {\n\treturn services.get(cwd);\n}\n\nexport function unregisterEmbsearchService(cwd: string): void {\n\tservices.delete(cwd);\n}\n"]}
|