github-router 0.3.328 → 0.3.330
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/dist/{attribution-settings-CF1ZV58z.js → attribution-settings-DepziZU8.js} +138 -93
- package/dist/attribution-settings-DepziZU8.js.map +1 -0
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{claude-BdJupNy4.js → claude-Dw4V8o8l.js} +14 -11
- package/dist/{claude-BdJupNy4.js.map → claude-Dw4V8o8l.js.map} +1 -1
- package/dist/{codex-DgEG2i_w.js → codex-CXOpv4WP.js} +5 -5
- package/dist/{codex-DgEG2i_w.js.map → codex-CXOpv4WP.js.map} +1 -1
- package/dist/engine-CYba_zi7.js +2 -0
- package/dist/{gate-discovery-ufkJQE8V.js → gate-discovery-BGqS7R2g.js} +2 -2
- package/dist/{gate-discovery-ufkJQE8V.js.map → gate-discovery-BGqS7R2g.js.map} +1 -1
- package/dist/{hook-mcp-client-DBvm9608.js → hook-mcp-client-DbFtxo6_.js} +6 -5
- package/dist/hook-mcp-client-DbFtxo6_.js.map +1 -0
- package/dist/hooks.mjs +46 -15
- package/dist/hooks.sha256 +1 -1
- package/dist/{index-cmd-mPy73hig.js → index-cmd-DUjQs9zw.js} +16 -6
- package/dist/index-cmd-DUjQs9zw.js.map +1 -0
- package/dist/{internal-plan-review-DM-Zycyn.js → internal-plan-review-O2dwnQv3.js} +3 -3
- package/dist/{internal-plan-review-DM-Zycyn.js.map → internal-plan-review-O2dwnQv3.js.map} +1 -1
- package/dist/{internal-prompt-submit-6AKy89nq.js → internal-prompt-submit-CD0UFkT-.js} +11 -8
- package/dist/internal-prompt-submit-CD0UFkT-.js.map +1 -0
- package/dist/{internal-stop-hook-CWwkeyf_.js → internal-stop-hook-CH9SKjZ9.js} +3 -3
- package/dist/{internal-stop-hook-CWwkeyf_.js.map → internal-stop-hook-CH9SKjZ9.js.map} +1 -1
- package/dist/{internal-stop-review-CPk66wwo.js → internal-stop-review-a3rpzzhd.js} +9 -9
- package/dist/internal-stop-review-a3rpzzhd.js.map +1 -0
- package/dist/main.js +9 -9
- package/dist/{peer-mcp-personas-Dg2LJ0GF.js → peer-mcp-personas-CnYMTizo.js} +148 -1021
- package/dist/peer-mcp-personas-CnYMTizo.js.map +1 -0
- package/dist/{plan-review-hook-ChuywYy_.js → plan-review-hook-CfZBvsHd.js} +2 -2
- package/dist/{plan-review-hook-ChuywYy_.js.map → plan-review-hook-CfZBvsHd.js.map} +1 -1
- package/dist/{prompt-submit-hook-C0ZospPT.js → prompt-submit-hook-CRH6m7Vz.js} +33 -12
- package/dist/prompt-submit-hook-CRH6m7Vz.js.map +1 -0
- package/dist/{provision-l0THw3kO.js → provision-D5KOOw6n.js} +3 -3
- package/dist/{provision-l0THw3kO.js.map → provision-D5KOOw6n.js.map} +1 -1
- package/dist/{serve-DZY93dBo.js → serve-fJWhiivo.js} +11 -9
- package/dist/serve-fJWhiivo.js.map +1 -0
- package/dist/{server-setup-Bv7TGDC7.js → server-setup-DHMPOXKT.js} +4 -4
- package/dist/{server-setup-Bv7TGDC7.js.map → server-setup-DHMPOXKT.js.map} +1 -1
- package/dist/{runner-BoJPRQsK.js → service-backend-DYEPoszR.js} +959 -47
- package/dist/service-backend-DYEPoszR.js.map +1 -0
- package/dist/{start-2SrUerLA.js → start-Gs4jAwUR.js} +4 -4
- package/dist/{start-2SrUerLA.js.map → start-Gs4jAwUR.js.map} +1 -1
- package/package.json +1 -1
- package/dist/attribution-settings-CF1ZV58z.js.map +0 -1
- package/dist/engine-C3SnOV1U.js +0 -2
- package/dist/hook-mcp-client-DBvm9608.js.map +0 -1
- package/dist/index-cmd-mPy73hig.js.map +0 -1
- package/dist/internal-prompt-submit-6AKy89nq.js.map +0 -1
- package/dist/internal-stop-review-CPk66wwo.js.map +0 -1
- package/dist/peer-mcp-personas-Dg2LJ0GF.js.map +0 -1
- package/dist/prompt-submit-hook-C0ZospPT.js.map +0 -1
- package/dist/runner-BoJPRQsK.js.map +0 -1
- package/dist/serve-DZY93dBo.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as PATHS } from "./paths-P5ajjpzU.js";
|
|
2
2
|
import { l as runManagedExeCapture, o as resolveExecutable, u as spawnTaskkillBestEffort } from "./exec-COUT4QsS.js";
|
|
3
|
-
import { n as isPidAlive, s as trackChild, t as getColbertInstanceUuid } from "./lifecycle-D8vQXfeC.js";
|
|
3
|
+
import { c as untrackChild, n as isPidAlive, s as trackChild, t as getColbertInstanceUuid } from "./lifecycle-D8vQXfeC.js";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import consola from "consola";
|
|
6
6
|
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
@@ -18,6 +18,7 @@ import { createInterface } from "node:readline";
|
|
|
18
18
|
import { Language, Parser } from "web-tree-sitter";
|
|
19
19
|
import { Worker } from "node:worker_threads";
|
|
20
20
|
import { gunzipSync, inflateRawSync } from "node:zlib";
|
|
21
|
+
import * as net from "node:net";
|
|
21
22
|
//#region \0rolldown/runtime.js
|
|
22
23
|
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
|
23
24
|
//#endregion
|
|
@@ -193,48 +194,6 @@ function stableTreeSitterAssetsComplete() {
|
|
|
193
194
|
}
|
|
194
195
|
});
|
|
195
196
|
}
|
|
196
|
-
//#endregion
|
|
197
|
-
//#region src/lib/tree-sitter-grammars.ts
|
|
198
|
-
/**
|
|
199
|
-
* Shared tree-sitter grammar layer.
|
|
200
|
-
*
|
|
201
|
-
* This module is the pure grammar-loading + constant-table layer
|
|
202
|
-
* extracted from `src/lib/code-search.ts`. It owns:
|
|
203
|
-
*
|
|
204
|
-
* - the extension → language and language → wasm-filename tables,
|
|
205
|
-
* - the per-language definition-node-type sets and the shared
|
|
206
|
-
* identifier-node-type set,
|
|
207
|
-
* - the lazy `web-tree-sitter` `Parser.init()` + grammar-load cache
|
|
208
|
-
* (`getGrammarBundle`), pre-warmed at module import time, and
|
|
209
|
-
* - `outlineFile`, a compact navigational outline of a single file.
|
|
210
|
-
*
|
|
211
|
-
* The BM25F scoring, the structural-confirmation pass, and the parsed-
|
|
212
|
-
* tree LRU stay in `code-search.ts` — they are tightly coupled to the
|
|
213
|
-
* ranking flow and would not survive a clean move. `code-search.ts`
|
|
214
|
-
* imports the symbols here and continues to call the same functions, so
|
|
215
|
-
* the extraction is behavior-preserving for the structural pass.
|
|
216
|
-
*
|
|
217
|
-
* There is exactly ONE `Parser.init()` and ONE grammar cache across the
|
|
218
|
-
* whole process: every caller (the structural pass, `outlineFile`)
|
|
219
|
-
* awaits the same `getGrammarBundle().ready` promise.
|
|
220
|
-
*
|
|
221
|
-
* Version pin note (evaluated 2026-09): web-tree-sitter stays at 0.25.10
|
|
222
|
-
* with tree-sitter-wasms 0.1.13 prebuilts. Upgrading the runtime to 0.27.0
|
|
223
|
-
* was spike-tested — all 9 prebuilt grammars fail to load (WASM
|
|
224
|
-
* dynamic-linking format mismatch). The migration path is web-tree-sitter
|
|
225
|
-
* 0.27.0 + tree-sitter-wasm 1.1.3 (verified: all 9 load + parse), but that
|
|
226
|
-
* swaps grammar builds too, so DEFINITION_NODE_TYPES needs node-type
|
|
227
|
-
* parity validation per language before it ships. Deferred until the
|
|
228
|
-
* semantic-service work lands; the cost of staying is only the
|
|
229
|
-
* check-between-files (not mid-parse) structural budget.
|
|
230
|
-
*/
|
|
231
|
-
/**
|
|
232
|
-
* Cap the per-file size we'll parse. 1MB of source covers all
|
|
233
|
-
* reasonable hand-written files; bigger files are almost always
|
|
234
|
-
* generated code or vendored bundles whose AST signal is worthless
|
|
235
|
-
* for ranking real definitions.
|
|
236
|
-
*/
|
|
237
|
-
const STRUCTURAL_MAX_FILE_BYTES = 1048576;
|
|
238
197
|
/**
|
|
239
198
|
* Extension → grammar key. Grammars not in this map skip structural
|
|
240
199
|
* parsing (the hit falls back to the regex SYMBOL_REGEX heuristic for
|
|
@@ -5496,13 +5455,13 @@ function parseAndTrim(stdout, workspace) {
|
|
|
5496
5455
|
...typeof unit.end_line === "number" ? { endLine: unit.end_line } : {},
|
|
5497
5456
|
...typeof unit.name === "string" ? { name: unit.name } : {},
|
|
5498
5457
|
score: typeof item.score === "number" ? round2(item.score) : 0,
|
|
5499
|
-
snippet: buildSnippet(unit)
|
|
5458
|
+
snippet: buildSnippet$1(unit)
|
|
5500
5459
|
});
|
|
5501
5460
|
}
|
|
5502
5461
|
return out;
|
|
5503
5462
|
}
|
|
5504
5463
|
/** snippet = signature + first few representative lines (NOT full code). */
|
|
5505
|
-
function buildSnippet(unit) {
|
|
5464
|
+
function buildSnippet$1(unit) {
|
|
5506
5465
|
const sig = typeof unit.signature === "string" ? unit.signature.trim() : "";
|
|
5507
5466
|
const code = typeof unit.code === "string" ? unit.code : "";
|
|
5508
5467
|
if (!code) return sig;
|
|
@@ -5757,6 +5716,959 @@ async function runInit(workspace) {
|
|
|
5757
5716
|
await writeColbertMeta(finalMeta).catch(() => {});
|
|
5758
5717
|
}
|
|
5759
5718
|
//#endregion
|
|
5760
|
-
|
|
5719
|
+
//#region src/lib/colbert/service.ts
|
|
5720
|
+
/**
|
|
5721
|
+
* next-plaid-api service client + managed lifecycle (Phase 2e).
|
|
5722
|
+
*
|
|
5723
|
+
* The semantic backend moves from colgrep CLI-per-invocation (every query
|
|
5724
|
+
* re-loads ORT + model + index) to a persistent `next-plaid-api` server
|
|
5725
|
+
* (model warm, PLAID mmap'd, lock-free reads, batched async writes).
|
|
5726
|
+
* This module owns the HTTP protocol and the child-process lifecycle;
|
|
5727
|
+
* the query-path switch (runner → service) lands separately once a
|
|
5728
|
+
* provisioned binary exists (see the CI build workflow).
|
|
5729
|
+
*
|
|
5730
|
+
* API surface (next-plaid-api v1.7.0, verified from upstream README):
|
|
5731
|
+
* GET /health → system + per-index summaries
|
|
5732
|
+
* POST /indices {name, config} → declare index (409 taken)
|
|
5733
|
+
* POST /indices/{name}/update_with_encoding → 202 (async batch)
|
|
5734
|
+
* DELETE /indices/{name}/documents {condition, parameters} → 202
|
|
5735
|
+
* POST /indices/{name}/search_with_encoding → ranked hits + metadata
|
|
5736
|
+
*
|
|
5737
|
+
* Conventions shared with the colbert sidecar: never log response bodies
|
|
5738
|
+
* (they embed source code), bound every request with a timeout, fail
|
|
5739
|
+
* closed (throw → caller falls back to lexical).
|
|
5740
|
+
*/
|
|
5741
|
+
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
5742
|
+
async function fetchJson(url, init, timeoutMs) {
|
|
5743
|
+
const ac = new AbortController();
|
|
5744
|
+
const timer = setTimeout(() => ac.abort(/* @__PURE__ */ new Error("service request timeout")), timeoutMs);
|
|
5745
|
+
timer.unref?.();
|
|
5746
|
+
try {
|
|
5747
|
+
const res = await fetch(url, {
|
|
5748
|
+
...init,
|
|
5749
|
+
signal: ac.signal
|
|
5750
|
+
});
|
|
5751
|
+
const text = await res.text();
|
|
5752
|
+
let body = null;
|
|
5753
|
+
try {
|
|
5754
|
+
body = text.length > 0 ? JSON.parse(text) : null;
|
|
5755
|
+
} catch {
|
|
5756
|
+
body = null;
|
|
5757
|
+
}
|
|
5758
|
+
return {
|
|
5759
|
+
status: res.status,
|
|
5760
|
+
body
|
|
5761
|
+
};
|
|
5762
|
+
} finally {
|
|
5763
|
+
clearTimeout(timer);
|
|
5764
|
+
}
|
|
5765
|
+
}
|
|
5766
|
+
/**
|
|
5767
|
+
* Thin HTTP client over a running next-plaid-api server. Construct with
|
|
5768
|
+
* the base URL (`http://127.0.0.1:PORT`); use `startManagedServer` below
|
|
5769
|
+
* for process lifecycle, or point at an externally managed server.
|
|
5770
|
+
*/
|
|
5771
|
+
var NextPlaidClient = class {
|
|
5772
|
+
baseUrl;
|
|
5773
|
+
timeoutMs;
|
|
5774
|
+
constructor(baseUrl, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
5775
|
+
this.baseUrl = baseUrl.replace(/\/+$/, "");
|
|
5776
|
+
this.timeoutMs = timeoutMs;
|
|
5777
|
+
}
|
|
5778
|
+
async health() {
|
|
5779
|
+
const { status, body } = await fetchJson(`${this.baseUrl}/health`, {}, this.timeoutMs);
|
|
5780
|
+
if (status !== 200 || typeof body !== "object" || body === null) return {
|
|
5781
|
+
ok: false,
|
|
5782
|
+
indices: []
|
|
5783
|
+
};
|
|
5784
|
+
const b = body;
|
|
5785
|
+
return {
|
|
5786
|
+
ok: b.status === "healthy",
|
|
5787
|
+
indices: (b.indices ?? []).map((i) => ({
|
|
5788
|
+
name: typeof i.name === "string" ? i.name : "",
|
|
5789
|
+
num_documents: typeof i.num_documents === "number" ? i.num_documents : 0,
|
|
5790
|
+
num_embeddings: typeof i.num_embeddings === "number" ? i.num_embeddings : 0,
|
|
5791
|
+
dimension: typeof i.dimension === "number" ? i.dimension : 0
|
|
5792
|
+
})),
|
|
5793
|
+
model: b.model?.name
|
|
5794
|
+
};
|
|
5795
|
+
}
|
|
5796
|
+
/** Declare an index (idempotent: 409 taken is success). */
|
|
5797
|
+
async ensureIndex(name, config = {}) {
|
|
5798
|
+
const { status, body } = await fetchJson(`${this.baseUrl}/indices`, {
|
|
5799
|
+
method: "POST",
|
|
5800
|
+
headers: { "content-type": "application/json" },
|
|
5801
|
+
body: JSON.stringify({
|
|
5802
|
+
name,
|
|
5803
|
+
config: {
|
|
5804
|
+
nbits: config.nbits ?? 4,
|
|
5805
|
+
...config.pool_factor !== void 0 ? { pool_factor: config.pool_factor } : {},
|
|
5806
|
+
...config.start_from_scratch !== void 0 ? { start_from_scratch: config.start_from_scratch } : {}
|
|
5807
|
+
}
|
|
5808
|
+
})
|
|
5809
|
+
}, this.timeoutMs);
|
|
5810
|
+
if (status === 200 || status === 201 || status === 409) return;
|
|
5811
|
+
throw new Error(`ensureIndex ${name} failed: HTTP ${status} (${describeError(body)})`);
|
|
5812
|
+
}
|
|
5813
|
+
/**
|
|
5814
|
+
* Add/update documents (server encodes text). 202 = accepted into the
|
|
5815
|
+
* async batch queue (NOT yet searchable — the server merges within
|
|
5816
|
+
* ~100ms/300 docs). Never throws for queue-full: maps 503 to a typed
|
|
5817
|
+
* error the caller retries after backoff.
|
|
5818
|
+
*/
|
|
5819
|
+
async updateDocuments(index, documents, metadata, poolFactor = 2) {
|
|
5820
|
+
const { status, body } = await fetchJson(`${this.baseUrl}/indices/${encodeURIComponent(index)}/update_with_encoding`, {
|
|
5821
|
+
method: "POST",
|
|
5822
|
+
headers: { "content-type": "application/json" },
|
|
5823
|
+
body: JSON.stringify({
|
|
5824
|
+
documents,
|
|
5825
|
+
metadata,
|
|
5826
|
+
pool_factor: poolFactor
|
|
5827
|
+
})
|
|
5828
|
+
}, this.timeoutMs);
|
|
5829
|
+
if (status === 202) return;
|
|
5830
|
+
if (status === 503) throw new ServiceBusyError(index);
|
|
5831
|
+
throw new Error(`update ${index} failed: HTTP ${status} (${describeError(body)})`);
|
|
5832
|
+
}
|
|
5833
|
+
/** Delete by SQL predicate (batched server-side, 202 accepted). */
|
|
5834
|
+
async deleteDocuments(index, condition, parameters = []) {
|
|
5835
|
+
const { status, body } = await fetchJson(`${this.baseUrl}/indices/${encodeURIComponent(index)}/documents`, {
|
|
5836
|
+
method: "DELETE",
|
|
5837
|
+
headers: { "content-type": "application/json" },
|
|
5838
|
+
body: JSON.stringify({
|
|
5839
|
+
condition,
|
|
5840
|
+
parameters
|
|
5841
|
+
})
|
|
5842
|
+
}, this.timeoutMs);
|
|
5843
|
+
if (status === 202) return;
|
|
5844
|
+
if (status === 404) return;
|
|
5845
|
+
if (status === 503) throw new ServiceBusyError(index);
|
|
5846
|
+
throw new Error(`delete ${index} failed: HTTP ${status} (${describeError(body)})`);
|
|
5847
|
+
}
|
|
5848
|
+
/**
|
|
5849
|
+
* Hybrid search (semantic + FTS5 keyword, server-side RRF fusion).
|
|
5850
|
+
* `fileGlob` scopes via metadata filter when provided (the indexer
|
|
5851
|
+
* stores `file` per doc). Returns hits in ranked order.
|
|
5852
|
+
*/
|
|
5853
|
+
async search(index, query, opts = {}) {
|
|
5854
|
+
const top_k = Math.max(1, Math.floor(opts.topK ?? 15));
|
|
5855
|
+
const body = {
|
|
5856
|
+
queries: [query],
|
|
5857
|
+
params: {
|
|
5858
|
+
top_k,
|
|
5859
|
+
...opts.nIvfProbe !== void 0 ? { n_ivf_probe: opts.nIvfProbe } : {}
|
|
5860
|
+
}
|
|
5861
|
+
};
|
|
5862
|
+
if (opts.textQuery) {
|
|
5863
|
+
body.text_query = [opts.textQuery];
|
|
5864
|
+
body.alpha = opts.alpha ?? .75;
|
|
5865
|
+
body.fusion = "relative_score";
|
|
5866
|
+
}
|
|
5867
|
+
if (opts.fileGlob) {
|
|
5868
|
+
body.filter_condition = "file GLOB ?";
|
|
5869
|
+
body.filter_parameters = [opts.fileGlob];
|
|
5870
|
+
}
|
|
5871
|
+
const { status, body: res } = await fetchJson(`${this.baseUrl}/indices/${encodeURIComponent(index)}/search_with_encoding`, {
|
|
5872
|
+
method: "POST",
|
|
5873
|
+
headers: { "content-type": "application/json" },
|
|
5874
|
+
body: JSON.stringify(body)
|
|
5875
|
+
}, this.timeoutMs);
|
|
5876
|
+
if (status === 404) return [];
|
|
5877
|
+
if (status === 503) throw new ServiceBusyError(index);
|
|
5878
|
+
if (status !== 200) throw new Error(`search ${index} failed: HTTP ${status} (${describeError(res)})`);
|
|
5879
|
+
return toHits(res);
|
|
5880
|
+
}
|
|
5881
|
+
};
|
|
5882
|
+
/** Queue-full signal: retry after backoff, never fatal. */
|
|
5883
|
+
var ServiceBusyError = class extends Error {
|
|
5884
|
+
index;
|
|
5885
|
+
constructor(index) {
|
|
5886
|
+
super(`next-plaid index ${index} busy (queue full); retry after backoff`);
|
|
5887
|
+
this.name = "ServiceBusyError";
|
|
5888
|
+
this.index = index;
|
|
5889
|
+
}
|
|
5890
|
+
};
|
|
5891
|
+
function describeError(body) {
|
|
5892
|
+
if (typeof body === "object" && body !== null) {
|
|
5893
|
+
const b = body;
|
|
5894
|
+
const code = typeof b.code === "string" ? b.code : "?";
|
|
5895
|
+
const message = typeof b.message === "string" ? b.message : "";
|
|
5896
|
+
return `${code}${message ? `: ${message.slice(0, 200)}` : ""}`;
|
|
5897
|
+
}
|
|
5898
|
+
return "unparseable response";
|
|
5899
|
+
}
|
|
5900
|
+
/**
|
|
5901
|
+
* Map the API search response to file-anchored hits. Metadata carries the
|
|
5902
|
+
* unit fields the indexer stored (file/line/end_line/name/signature);
|
|
5903
|
+
* rows missing a file are dropped (never surface an unanchored hit).
|
|
5904
|
+
*/
|
|
5905
|
+
function toHits(res) {
|
|
5906
|
+
const out = [];
|
|
5907
|
+
for (const r of res.results ?? []) {
|
|
5908
|
+
const ids = r.document_ids ?? [];
|
|
5909
|
+
const scores = r.scores ?? [];
|
|
5910
|
+
const metas = r.metadata ?? [];
|
|
5911
|
+
for (let i = 0; i < ids.length; i++) {
|
|
5912
|
+
const meta = metas[i] ?? {};
|
|
5913
|
+
const file = meta.file;
|
|
5914
|
+
if (typeof file !== "string" || file.length === 0) continue;
|
|
5915
|
+
const line = meta.line;
|
|
5916
|
+
out.push({
|
|
5917
|
+
file,
|
|
5918
|
+
line: typeof line === "number" ? line : 1,
|
|
5919
|
+
...typeof meta.end_line === "number" ? { end_line: meta.end_line } : {},
|
|
5920
|
+
...typeof meta.name === "string" ? { name: meta.name } : {},
|
|
5921
|
+
score: typeof scores[i] === "number" ? scores[i] : 0,
|
|
5922
|
+
metadata: meta
|
|
5923
|
+
});
|
|
5924
|
+
}
|
|
5925
|
+
}
|
|
5926
|
+
return out;
|
|
5927
|
+
}
|
|
5928
|
+
/** Find a free loopback port (TOCTOU-racy by nature; retry on collision). */
|
|
5929
|
+
async function freePort() {
|
|
5930
|
+
return new Promise((resolve, reject) => {
|
|
5931
|
+
const s = net.createServer();
|
|
5932
|
+
s.on("error", reject);
|
|
5933
|
+
s.listen(0, "127.0.0.1", () => {
|
|
5934
|
+
const addr = s.address();
|
|
5935
|
+
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
|
5936
|
+
s.close((err) => err ? reject(err) : resolve(port));
|
|
5937
|
+
});
|
|
5938
|
+
});
|
|
5939
|
+
}
|
|
5940
|
+
/**
|
|
5941
|
+
* Spawn the server, wait for `/health`, return a managed handle. Throws
|
|
5942
|
+
* when the binary is missing, the port never becomes healthy, or the
|
|
5943
|
+
* child exits early (stderr is captured, truncated, never logged raw —
|
|
5944
|
+
* it can embed paths, not source, but the discipline is cheap).
|
|
5945
|
+
*/
|
|
5946
|
+
/**
|
|
5947
|
+
* Build the next-plaid-api argv (exported for unit tests; production
|
|
5948
|
+
* goes through `startManagedServer`). `--int8`/`--cuda` both require
|
|
5949
|
+
* `--model` (upstream CLI contract) and are never passed alone.
|
|
5950
|
+
*/
|
|
5951
|
+
function serverArgv(opts, port) {
|
|
5952
|
+
return [
|
|
5953
|
+
"--host",
|
|
5954
|
+
"127.0.0.1",
|
|
5955
|
+
"--port",
|
|
5956
|
+
String(port),
|
|
5957
|
+
"--index-dir",
|
|
5958
|
+
opts.indexDir,
|
|
5959
|
+
...opts.modelDir ? ["--model", opts.modelDir] : [],
|
|
5960
|
+
...opts.modelDir && opts.int8 !== false ? ["--int8"] : [],
|
|
5961
|
+
...opts.modelDir && opts.cuda === true ? ["--cuda"] : [],
|
|
5962
|
+
"--parallel",
|
|
5963
|
+
String(Math.max(1, Math.floor(opts.parallel ?? 1)))
|
|
5964
|
+
];
|
|
5965
|
+
}
|
|
5966
|
+
async function startManagedServer(opts) {
|
|
5967
|
+
const port = opts.port ?? await freePort();
|
|
5968
|
+
const args = opts.argv ?? serverArgv(opts, port);
|
|
5969
|
+
let child;
|
|
5970
|
+
try {
|
|
5971
|
+
child = spawn(opts.binaryPath, args, {
|
|
5972
|
+
env: {
|
|
5973
|
+
...process$1.env,
|
|
5974
|
+
...opts.env
|
|
5975
|
+
},
|
|
5976
|
+
stdio: [
|
|
5977
|
+
"ignore",
|
|
5978
|
+
"pipe",
|
|
5979
|
+
"pipe"
|
|
5980
|
+
],
|
|
5981
|
+
windowsHide: true
|
|
5982
|
+
});
|
|
5983
|
+
} catch (err) {
|
|
5984
|
+
throw new Error(`next-plaid server failed to spawn: ${err.message}`, { cause: err });
|
|
5985
|
+
}
|
|
5986
|
+
trackChild(child);
|
|
5987
|
+
child.on("error", () => {
|
|
5988
|
+
untrackChild(child);
|
|
5989
|
+
});
|
|
5990
|
+
let stderrTail = "";
|
|
5991
|
+
child.stderr?.setEncoding("utf8");
|
|
5992
|
+
child.stderr?.on("data", (chunk) => {
|
|
5993
|
+
stderrTail = (stderrTail + chunk).slice(-4096);
|
|
5994
|
+
});
|
|
5995
|
+
const url = `http://127.0.0.1:${port}`;
|
|
5996
|
+
const client = new NextPlaidClient(url);
|
|
5997
|
+
const deadline = Date.now() + (opts.startupTimeoutMs ?? 6e4);
|
|
5998
|
+
let exited = null;
|
|
5999
|
+
let spawnFailed = false;
|
|
6000
|
+
child.on("exit", (code) => {
|
|
6001
|
+
exited = code;
|
|
6002
|
+
});
|
|
6003
|
+
child.on("error", () => {
|
|
6004
|
+
spawnFailed = true;
|
|
6005
|
+
});
|
|
6006
|
+
child.on("close", () => {
|
|
6007
|
+
if (exited === null) spawnFailed = true;
|
|
6008
|
+
});
|
|
6009
|
+
try {
|
|
6010
|
+
for (;;) {
|
|
6011
|
+
if (exited !== null || spawnFailed) throw new Error(`next-plaid server exited during startup${exited !== null ? ` (code ${exited})` : ""}: ${stderrTail.slice(-500)}`);
|
|
6012
|
+
try {
|
|
6013
|
+
if ((await client.health()).ok) return {
|
|
6014
|
+
url,
|
|
6015
|
+
client,
|
|
6016
|
+
stop: () => stopServer(child)
|
|
6017
|
+
};
|
|
6018
|
+
} catch {}
|
|
6019
|
+
if (Date.now() > deadline) throw new Error(`next-plaid server not healthy after startup budget: ${stderrTail.slice(-500)}`);
|
|
6020
|
+
await new Promise((r) => {
|
|
6021
|
+
setTimeout(() => r(), 250).unref?.();
|
|
6022
|
+
});
|
|
6023
|
+
}
|
|
6024
|
+
} catch (err) {
|
|
6025
|
+
await stopServer(child).catch(() => {});
|
|
6026
|
+
throw err;
|
|
6027
|
+
}
|
|
6028
|
+
}
|
|
6029
|
+
async function stopServer(child) {
|
|
6030
|
+
try {
|
|
6031
|
+
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
6032
|
+
if (child.pid === void 0) return;
|
|
6033
|
+
let finished = false;
|
|
6034
|
+
let doneResolve = () => {};
|
|
6035
|
+
const done = new Promise((resolve) => {
|
|
6036
|
+
doneResolve = resolve;
|
|
6037
|
+
});
|
|
6038
|
+
const finish = () => {
|
|
6039
|
+
if (finished) return;
|
|
6040
|
+
finished = true;
|
|
6041
|
+
clearTimeout(escalation);
|
|
6042
|
+
clearTimeout(backstop);
|
|
6043
|
+
doneResolve();
|
|
6044
|
+
};
|
|
6045
|
+
child.once("exit", finish);
|
|
6046
|
+
child.once("close", finish);
|
|
6047
|
+
const escalation = setTimeout(() => {
|
|
6048
|
+
try {
|
|
6049
|
+
child.kill("SIGKILL");
|
|
6050
|
+
} catch {}
|
|
6051
|
+
}, 5e3);
|
|
6052
|
+
escalation.unref?.();
|
|
6053
|
+
const backstop = setTimeout(finish, 15e3);
|
|
6054
|
+
backstop.unref?.();
|
|
6055
|
+
try {
|
|
6056
|
+
child.kill("SIGTERM");
|
|
6057
|
+
} catch {
|
|
6058
|
+
finish();
|
|
6059
|
+
return;
|
|
6060
|
+
}
|
|
6061
|
+
if (process$1.platform === "win32") try {
|
|
6062
|
+
const { spawnSync } = await import("node:child_process");
|
|
6063
|
+
if (child.pid) spawnSync("taskkill", [
|
|
6064
|
+
"/T",
|
|
6065
|
+
"/F",
|
|
6066
|
+
"/PID",
|
|
6067
|
+
String(child.pid)
|
|
6068
|
+
], {
|
|
6069
|
+
stdio: "ignore",
|
|
6070
|
+
windowsHide: true
|
|
6071
|
+
});
|
|
6072
|
+
} catch {}
|
|
6073
|
+
await done;
|
|
6074
|
+
} finally {
|
|
6075
|
+
untrackChild(child);
|
|
6076
|
+
}
|
|
6077
|
+
}
|
|
6078
|
+
/** CPU-aware default parallelism for the managed server. */
|
|
6079
|
+
function serverParallelSessions() {
|
|
6080
|
+
const raw = Number(process$1.env.GH_ROUTER_NP_PARALLEL);
|
|
6081
|
+
if (Number.isSafeInteger(raw) && raw > 0) return raw;
|
|
6082
|
+
let cpus = 4;
|
|
6083
|
+
try {
|
|
6084
|
+
cpus = os$1.cpus().length;
|
|
6085
|
+
} catch {}
|
|
6086
|
+
return Math.max(1, Math.floor(cpus * .25));
|
|
6087
|
+
}
|
|
6088
|
+
/** Per-workspace index name: stable hash of the canonical workspace path. */
|
|
6089
|
+
function indexNameForWorkspace(canonicalWorkspace) {
|
|
6090
|
+
let h = 2166136261;
|
|
6091
|
+
for (let i = 0; i < canonicalWorkspace.length; i++) {
|
|
6092
|
+
h ^= canonicalWorkspace.charCodeAt(i);
|
|
6093
|
+
h = Math.imul(h, 16777619);
|
|
6094
|
+
}
|
|
6095
|
+
return `ws-${(h >>> 0).toString(16).padStart(8, "0")}`;
|
|
6096
|
+
}
|
|
6097
|
+
//#endregion
|
|
6098
|
+
//#region src/lib/colbert/units.ts
|
|
6099
|
+
/**
|
|
6100
|
+
* Semantic code-unit extraction (Phase 2b).
|
|
6101
|
+
*
|
|
6102
|
+
* The next-plaid service is a generic multi-vector document store — unlike
|
|
6103
|
+
* colgrep it does NOT parse code. This module owns the code-aware half:
|
|
6104
|
+
* tree-sitter parsing (reusing the warm grammar bundle + definition tables
|
|
6105
|
+
* from `~/lib/tree-sitter-grammars`), unit scoping (top-level + class-like
|
|
6106
|
+
* members — the same navigable scope as outlines), and structured-text
|
|
6107
|
+
* construction for embedding.
|
|
6108
|
+
*
|
|
6109
|
+
* Unit text mirrors colgrep's high-signal layers with the cheap subset:
|
|
6110
|
+
* name, signature (first line), leading doc comment, normalized file path,
|
|
6111
|
+
* and capped body. Call-graph / data-flow layers are deliberately omitted
|
|
6112
|
+
* in v1 (that analysis is computed by colgrep but never returned in our
|
|
6113
|
+
* responses today — see the Phase 2 plan — so nothing observable is lost).
|
|
6114
|
+
*
|
|
6115
|
+
* Pure file-level functions (no index state here): the service owns
|
|
6116
|
+
* storage/incremental logic; the freshness sidecar owns per-file hashes.
|
|
6117
|
+
* `extractUnits` never throws — per-file failures surface as `notice`.
|
|
6118
|
+
*/
|
|
6119
|
+
/** Max unit body chars embedded (~500 tokens). Longer bodies truncate. */
|
|
6120
|
+
const UNIT_MAX_BODY_CHARS = 2e3;
|
|
6121
|
+
/** Max signature chars (first line(s) of the unit). */
|
|
6122
|
+
const UNIT_MAX_SIGNATURE_CHARS = 300;
|
|
6123
|
+
/**
|
|
6124
|
+
* Normalize a file path for embedding: separators → spaces, snake_case /
|
|
6125
|
+
* CamelCase split (mirrors colgrep's path normalization AND the BM25F
|
|
6126
|
+
* `file_path` field, so lexical and semantic agree on path tokens).
|
|
6127
|
+
* `src/utils/HttpClient.ts` → `src utils Http Client ts`.
|
|
6128
|
+
*/
|
|
6129
|
+
function normalizePathForEmbedding(relPath) {
|
|
6130
|
+
return relPath.replace(/[/\\]/g, " ").replace(/\.[A-Za-z0-9]+$/, " $&").split(/[^A-Za-z0-9]+/).filter(Boolean).flatMap((piece) => {
|
|
6131
|
+
return piece.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+[0-9]*|[A-Z]+[0-9]*|[0-9]+/g) ?? [piece];
|
|
6132
|
+
}).join(" ");
|
|
6133
|
+
}
|
|
6134
|
+
/**
|
|
6135
|
+
* Leading doc comment for the unit starting at 1-indexed `startLine`:
|
|
6136
|
+
* consecutive comment-ish lines directly above (//, #, *, <!--, """, ''',
|
|
6137
|
+
* ///), blank-line-terminated. Language-agnostic and AST-free — runs on
|
|
6138
|
+
* raw source lines so it needs no per-language comment grammar.
|
|
6139
|
+
*/
|
|
6140
|
+
function leadingDocComment(sourceLines, startLine1) {
|
|
6141
|
+
const out = [];
|
|
6142
|
+
for (let i = startLine1 - 2; i >= 0; i--) {
|
|
6143
|
+
const line = sourceLines[i].trim();
|
|
6144
|
+
if (line.length === 0) break;
|
|
6145
|
+
if (line.startsWith("//") || line.startsWith("#") || line.startsWith("*") || line.startsWith("<!--") || line.startsWith("\"\"\"") || line.startsWith("'''")) {
|
|
6146
|
+
out.unshift(sourceLines[i].trim());
|
|
6147
|
+
if (out.length >= 10) break;
|
|
6148
|
+
} else break;
|
|
6149
|
+
}
|
|
6150
|
+
return out.length > 0 ? out.join("\n") : void 0;
|
|
6151
|
+
}
|
|
6152
|
+
/**
|
|
6153
|
+
* Structured text for one unit — what gets embedded. Field order mirrors
|
|
6154
|
+
* colgrep's (name → signature → description → path → code) so ranking
|
|
6155
|
+
* behavior stays close to the ColBERT sidecar it replaces.
|
|
6156
|
+
*/
|
|
6157
|
+
function buildUnitText(unit, relPath) {
|
|
6158
|
+
const parts = [`${labelForKind(unit.kind)}: ${unit.name}`];
|
|
6159
|
+
if (unit.signature && unit.signature !== unit.name) parts.push(`Signature: ${unit.signature}`);
|
|
6160
|
+
if (unit.docstring) parts.push(`Description: ${unit.docstring}`);
|
|
6161
|
+
parts.push(`File: ${normalizePathForEmbedding(relPath)}`);
|
|
6162
|
+
parts.push(`Code:\n${unit.code}`);
|
|
6163
|
+
return parts.join("\n");
|
|
6164
|
+
}
|
|
6165
|
+
function labelForKind(kind) {
|
|
6166
|
+
if (kind.includes("class")) return "Class";
|
|
6167
|
+
if (kind.includes("interface")) return "Interface";
|
|
6168
|
+
if (kind.includes("struct")) return "Struct";
|
|
6169
|
+
if (kind.includes("enum")) return "Enum";
|
|
6170
|
+
if (kind.includes("namespace") || kind.includes("module")) return "Namespace";
|
|
6171
|
+
if (kind.includes("method") || kind.includes("function")) return "Function";
|
|
6172
|
+
if (kind.includes("property")) return "Property";
|
|
6173
|
+
if (kind.includes("field")) return "Field";
|
|
6174
|
+
return "Symbol";
|
|
6175
|
+
}
|
|
6176
|
+
/**
|
|
6177
|
+
* Extract indexable units from one file. Read + parse + walk; frees the
|
|
6178
|
+
* tree before returning (units carry plain strings, never live nodes).
|
|
6179
|
+
* Never throws — failures surface as `notice` with empty `units`.
|
|
6180
|
+
*/
|
|
6181
|
+
async function extractUnits(absPath, relPath, signal) {
|
|
6182
|
+
if (signal?.aborted) return {
|
|
6183
|
+
units: [],
|
|
6184
|
+
language: null
|
|
6185
|
+
};
|
|
6186
|
+
const language = getLanguageKeyForPath(absPath);
|
|
6187
|
+
if (!language) return {
|
|
6188
|
+
units: [],
|
|
6189
|
+
language: null,
|
|
6190
|
+
notice: "no grammar for this file type"
|
|
6191
|
+
};
|
|
6192
|
+
let size;
|
|
6193
|
+
try {
|
|
6194
|
+
size = statSync(absPath).size;
|
|
6195
|
+
} catch {
|
|
6196
|
+
return {
|
|
6197
|
+
units: [],
|
|
6198
|
+
language,
|
|
6199
|
+
notice: "unreadable file"
|
|
6200
|
+
};
|
|
6201
|
+
}
|
|
6202
|
+
if (size > 1048576) return {
|
|
6203
|
+
units: [],
|
|
6204
|
+
language,
|
|
6205
|
+
notice: "file too large"
|
|
6206
|
+
};
|
|
6207
|
+
const grammars = await getGrammarBundle().ready;
|
|
6208
|
+
if (signal?.aborted) return {
|
|
6209
|
+
units: [],
|
|
6210
|
+
language
|
|
6211
|
+
};
|
|
6212
|
+
const lang = grammars.get(language);
|
|
6213
|
+
const defTypes = DEFINITION_NODE_TYPES[language];
|
|
6214
|
+
if (!lang || !defTypes) return {
|
|
6215
|
+
units: [],
|
|
6216
|
+
language,
|
|
6217
|
+
notice: "grammar unavailable"
|
|
6218
|
+
};
|
|
6219
|
+
let source;
|
|
6220
|
+
try {
|
|
6221
|
+
source = await readFile(absPath, "utf8");
|
|
6222
|
+
} catch {
|
|
6223
|
+
return {
|
|
6224
|
+
units: [],
|
|
6225
|
+
language,
|
|
6226
|
+
notice: "unreadable file"
|
|
6227
|
+
};
|
|
6228
|
+
}
|
|
6229
|
+
if (signal?.aborted) return {
|
|
6230
|
+
units: [],
|
|
6231
|
+
language
|
|
6232
|
+
};
|
|
6233
|
+
let parser = null;
|
|
6234
|
+
let tree = null;
|
|
6235
|
+
try {
|
|
6236
|
+
parser = new Parser();
|
|
6237
|
+
parser.setLanguage(lang);
|
|
6238
|
+
tree = parser.parse(source);
|
|
6239
|
+
if (!tree) return {
|
|
6240
|
+
units: [],
|
|
6241
|
+
language,
|
|
6242
|
+
notice: "parse failed"
|
|
6243
|
+
};
|
|
6244
|
+
const sourceLines = source.split("\n");
|
|
6245
|
+
const slashRel = relPath.replace(/\\/g, "/");
|
|
6246
|
+
const units = [];
|
|
6247
|
+
for (const u of collectUnitNodes(tree.rootNode, defTypes, signal)) {
|
|
6248
|
+
if (signal?.aborted) break;
|
|
6249
|
+
const line = u.node.startPosition.row + 1;
|
|
6250
|
+
const endLine = u.node.endPosition.row + 1;
|
|
6251
|
+
const firstLine = (sourceLines[line - 1] ?? "").trim().slice(0, UNIT_MAX_SIGNATURE_CHARS);
|
|
6252
|
+
const body = u.node.text.length > 2e3 ? u.node.text.slice(0, UNIT_MAX_BODY_CHARS) + "\n…[truncated]" : u.node.text;
|
|
6253
|
+
units.push({
|
|
6254
|
+
unit_id: `${slashRel}:${line}:${u.name}`,
|
|
6255
|
+
file: slashRel,
|
|
6256
|
+
name: u.name,
|
|
6257
|
+
kind: u.kind,
|
|
6258
|
+
line,
|
|
6259
|
+
end_line: endLine,
|
|
6260
|
+
signature: firstLine,
|
|
6261
|
+
code: body,
|
|
6262
|
+
...leadingDocComment(sourceLines, line) !== void 0 ? { docstring: leadingDocComment(sourceLines, line) } : {}
|
|
6263
|
+
});
|
|
6264
|
+
}
|
|
6265
|
+
units.sort((a, b) => a.line - b.line);
|
|
6266
|
+
return {
|
|
6267
|
+
units,
|
|
6268
|
+
language
|
|
6269
|
+
};
|
|
6270
|
+
} catch {
|
|
6271
|
+
return {
|
|
6272
|
+
units: [],
|
|
6273
|
+
language,
|
|
6274
|
+
notice: "parse failed"
|
|
6275
|
+
};
|
|
6276
|
+
} finally {
|
|
6277
|
+
if (tree) try {
|
|
6278
|
+
tree.delete();
|
|
6279
|
+
} catch {}
|
|
6280
|
+
if (parser) try {
|
|
6281
|
+
parser.delete();
|
|
6282
|
+
} catch {}
|
|
6283
|
+
}
|
|
6284
|
+
}
|
|
6285
|
+
//#endregion
|
|
6286
|
+
//#region src/lib/colbert/service-backend.ts
|
|
6287
|
+
/**
|
|
6288
|
+
* Service-backed semantic search orchestration (Phase 2e query path).
|
|
6289
|
+
*
|
|
6290
|
+
* Selects between the legacy colgrep CLI backend and the persistent
|
|
6291
|
+
* next-plaid-api server via `GH_ROUTER_SEMANTIC_BACKEND` (`colgrep` default,
|
|
6292
|
+
* `service` opt-in). The service path owns its own per-workspace state
|
|
6293
|
+
* (`svc-<hash>.json` sidecars — never touches the colgrep sidecar, so
|
|
6294
|
+
* flipping the flag back and forth loses nothing) and degrades to the
|
|
6295
|
+
* colgrep path on ANY service failure (missing binary, unhealthy server,
|
|
6296
|
+
* unknown index, busy queue).
|
|
6297
|
+
*
|
|
6298
|
+
* Indexing model: on-demand background populate. First query for a
|
|
6299
|
+
* workspace kicks `populateWorkspace` (enumerate → extractUnits →
|
|
6300
|
+
* batched updateDocuments) and returns `unavailable` meanwhile — the same
|
|
6301
|
+
* transparent-fallback contract as the CLI backend. Watcher-driven
|
|
6302
|
+
* proactive refresh lands separately (Phase 2d wiring).
|
|
6303
|
+
*
|
|
6304
|
+
* Binary resolution (no provisioner yet — CI artifacts pending):
|
|
6305
|
+
* 1. `GH_ROUTER_NEXTPLAID_BIN` explicit path
|
|
6306
|
+
* 2. Router-owned `<APP_DIR>/colbert/bin/next-plaid-api[.exe]`
|
|
6307
|
+
* 3. `next-plaid-api` on PATH
|
|
6308
|
+
* Model + ORT reuse the colbert provision (LateOn-Code-edge INT8 dir);
|
|
6309
|
+
* absent model ⇒ backend unavailable ⇒ colgrep fallback.
|
|
6310
|
+
*/
|
|
6311
|
+
/** Backend selection. Default `colgrep`; opt in with `=service`. */
|
|
6312
|
+
function semanticBackend() {
|
|
6313
|
+
return process.env.GH_ROUTER_SEMANTIC_BACKEND === "service" ? "service" : "colgrep";
|
|
6314
|
+
}
|
|
6315
|
+
/** True when the service backend is selected AND actionable. */
|
|
6316
|
+
function serviceBackendEnabled() {
|
|
6317
|
+
if (semanticBackend() !== "service") return false;
|
|
6318
|
+
if (resolveServiceBinary() === null && !nextPlaidServerPromoted("cpu") && !nextPlaidServerPromoted("cuda")) return false;
|
|
6319
|
+
if (!existsSync(canonicalColbertModelDir())) return false;
|
|
6320
|
+
return true;
|
|
6321
|
+
}
|
|
6322
|
+
/** Locate the server binary (env → router-owned → PATH). */
|
|
6323
|
+
function resolveServiceBinary() {
|
|
6324
|
+
const explicit = process.env.GH_ROUTER_NEXTPLAID_BIN;
|
|
6325
|
+
if (explicit && explicit.length > 0 && existsSync(explicit)) return explicit;
|
|
6326
|
+
for (const variant of ["cpu", "cuda"]) {
|
|
6327
|
+
const owned = nextPlaidServerBinaryPath(variant);
|
|
6328
|
+
if (existsSync(owned)) return owned;
|
|
6329
|
+
}
|
|
6330
|
+
return resolveExecutable("next-plaid-api");
|
|
6331
|
+
}
|
|
6332
|
+
/**
|
|
6333
|
+
* True when an NVIDIA GPU is visible (`nvidia-smi -L` exits 0). Never
|
|
6334
|
+
* throws; absent tool/driver ⇒ false ⇒ cpu variant. Bounded (~8s) so a
|
|
6335
|
+
* wedged driver can't stall startup.
|
|
6336
|
+
*/
|
|
6337
|
+
async function hasCudaGpu() {
|
|
6338
|
+
try {
|
|
6339
|
+
const smi = resolveExecutable("nvidia-smi");
|
|
6340
|
+
if (!smi) return false;
|
|
6341
|
+
const res = await runManagedExeCapture(smi, ["-L"], {
|
|
6342
|
+
timeoutMs: 8e3,
|
|
6343
|
+
maxStdoutBytes: 65536
|
|
6344
|
+
});
|
|
6345
|
+
return res.code === 0 && !res.timedOut;
|
|
6346
|
+
} catch {
|
|
6347
|
+
return false;
|
|
6348
|
+
}
|
|
6349
|
+
}
|
|
6350
|
+
/**
|
|
6351
|
+
* Pick the server compute variant. Explicit `GH_ROUTER_NEXTPLAID_VARIANT`
|
|
6352
|
+
* (`cpu`|`cuda`) wins (operator/test seam); otherwise cuda iff a GPU is
|
|
6353
|
+
* visible. Callers still fall back across variants when the preferred
|
|
6354
|
+
* binary can't be provisioned — selection is a preference, not a gate.
|
|
6355
|
+
*/
|
|
6356
|
+
async function selectServerVariant() {
|
|
6357
|
+
const override = process.env.GH_ROUTER_NEXTPLAID_VARIANT;
|
|
6358
|
+
if (override === "cpu" || override === "cuda") return override;
|
|
6359
|
+
return await hasCudaGpu() ? "cuda" : "cpu";
|
|
6360
|
+
}
|
|
6361
|
+
/**
|
|
6362
|
+
* Resolve the server binary + flags, provisioning on demand. Order:
|
|
6363
|
+
* explicit env (as-is; `--cuda` only via GH_ROUTER_NEXTPLAID_CUDA=1) →
|
|
6364
|
+
* preferred variant (provision, else on-disk) → cpu fallback (provision,
|
|
6365
|
+
* else on-disk) → PATH (cpu only). Null when nothing is usable.
|
|
6366
|
+
*/
|
|
6367
|
+
async function resolveServerBinaryWithVariant(variant) {
|
|
6368
|
+
const explicit = process.env.GH_ROUTER_NEXTPLAID_BIN;
|
|
6369
|
+
if (explicit && explicit.length > 0 && existsSync(explicit)) return {
|
|
6370
|
+
binary: explicit,
|
|
6371
|
+
cuda: process.env.GH_ROUTER_NEXTPLAID_CUDA === "1"
|
|
6372
|
+
};
|
|
6373
|
+
const ordered = variant === "cuda" ? ["cuda", "cpu"] : ["cpu"];
|
|
6374
|
+
for (const v of ordered) {
|
|
6375
|
+
const provisioned = await provisionNextPlaidServer(v);
|
|
6376
|
+
if (provisioned.path) return {
|
|
6377
|
+
binary: provisioned.path,
|
|
6378
|
+
cuda: v === "cuda"
|
|
6379
|
+
};
|
|
6380
|
+
const owned = nextPlaidServerBinaryPath(v);
|
|
6381
|
+
if (existsSync(owned)) return {
|
|
6382
|
+
binary: owned,
|
|
6383
|
+
cuda: v === "cuda"
|
|
6384
|
+
};
|
|
6385
|
+
}
|
|
6386
|
+
const onPath = resolveExecutable("next-plaid-api");
|
|
6387
|
+
if (onPath) return {
|
|
6388
|
+
binary: onPath,
|
|
6389
|
+
cuda: false
|
|
6390
|
+
};
|
|
6391
|
+
return null;
|
|
6392
|
+
}
|
|
6393
|
+
let _server = null;
|
|
6394
|
+
let _starting = null;
|
|
6395
|
+
/** Start (once) and health-check the server; null when unavailable. */
|
|
6396
|
+
async function ensureServer() {
|
|
6397
|
+
if (_server) {
|
|
6398
|
+
try {
|
|
6399
|
+
if ((await _server.client.health()).ok) return _server;
|
|
6400
|
+
} catch {}
|
|
6401
|
+
try {
|
|
6402
|
+
await _server.stop();
|
|
6403
|
+
} catch {}
|
|
6404
|
+
_server = null;
|
|
6405
|
+
}
|
|
6406
|
+
if (_starting) return _starting.catch(() => null);
|
|
6407
|
+
const resolved = await resolveServerBinaryWithVariant(await selectServerVariant());
|
|
6408
|
+
if (!resolved) return null;
|
|
6409
|
+
_starting = (async () => {
|
|
6410
|
+
const ortDir = path.dirname(colbertOrtDylibPath());
|
|
6411
|
+
const svc = await startManagedServer({
|
|
6412
|
+
binaryPath: resolved.binary,
|
|
6413
|
+
modelDir: canonicalColbertModelDir(),
|
|
6414
|
+
indexDir: PATHS.COLBERT_INDICES_DIR,
|
|
6415
|
+
parallel: serverParallelSessions(),
|
|
6416
|
+
cuda: resolved.cuda,
|
|
6417
|
+
env: {
|
|
6418
|
+
ORT_DYLIB_PATH: colbertOrtDylibPath(),
|
|
6419
|
+
PATH: `${ortDir}${path.delimiter}${process.env.PATH ?? ""}`
|
|
6420
|
+
},
|
|
6421
|
+
startupTimeoutMs: 12e4
|
|
6422
|
+
});
|
|
6423
|
+
_server = svc;
|
|
6424
|
+
return svc;
|
|
6425
|
+
})();
|
|
6426
|
+
try {
|
|
6427
|
+
return await _starting;
|
|
6428
|
+
} catch (err) {
|
|
6429
|
+
consola.debug(`service-backend: server start failed: ${err.message}`);
|
|
6430
|
+
return null;
|
|
6431
|
+
} finally {
|
|
6432
|
+
_starting = null;
|
|
6433
|
+
}
|
|
6434
|
+
}
|
|
6435
|
+
function serviceMetaPath(workspace) {
|
|
6436
|
+
return path.join(PATHS.COLBERT_META_DIR, `svc-${metaHash(workspace)}.json`);
|
|
6437
|
+
}
|
|
6438
|
+
function metaHash(workspace) {
|
|
6439
|
+
const canonical = canonicalWorkspace(workspace);
|
|
6440
|
+
let h = 2166136261;
|
|
6441
|
+
for (let i = 0; i < canonical.length; i++) {
|
|
6442
|
+
h ^= canonical.charCodeAt(i);
|
|
6443
|
+
h = Math.imul(h, 16777619);
|
|
6444
|
+
}
|
|
6445
|
+
return (h >>> 0).toString(16).padStart(8, "0");
|
|
6446
|
+
}
|
|
6447
|
+
async function readServiceMeta(workspace) {
|
|
6448
|
+
try {
|
|
6449
|
+
const raw = await fs$1.readFile(serviceMetaPath(workspace), "utf8");
|
|
6450
|
+
const parsed = JSON.parse(raw);
|
|
6451
|
+
if (parsed && typeof parsed === "object") return parsed;
|
|
6452
|
+
return null;
|
|
6453
|
+
} catch {
|
|
6454
|
+
return null;
|
|
6455
|
+
}
|
|
6456
|
+
}
|
|
6457
|
+
async function writeServiceMeta(meta) {
|
|
6458
|
+
await fs$1.mkdir(PATHS.COLBERT_META_DIR, { recursive: true });
|
|
6459
|
+
const dest = serviceMetaPath(meta.workspace);
|
|
6460
|
+
const tmp = `${dest}.${process.pid}.tmp`;
|
|
6461
|
+
try {
|
|
6462
|
+
await fs$1.writeFile(tmp, JSON.stringify(meta, null, 2));
|
|
6463
|
+
await fs$1.rename(tmp, dest);
|
|
6464
|
+
} catch {
|
|
6465
|
+
await fs$1.rm(tmp, { force: true }).catch(() => {});
|
|
6466
|
+
}
|
|
6467
|
+
}
|
|
6468
|
+
const _populateInFlight = /* @__PURE__ */ new Set();
|
|
6469
|
+
/** Fire-and-forget per-workspace populate (single-flight). Never throws. */
|
|
6470
|
+
function kickServiceIndex(workspace) {
|
|
6471
|
+
const key = path.resolve(workspace);
|
|
6472
|
+
if (_populateInFlight.has(key)) return;
|
|
6473
|
+
_populateInFlight.add(key);
|
|
6474
|
+
populateWorkspace(workspace).catch((err) => {
|
|
6475
|
+
consola.debug(`service-backend: populate failed for ${workspace}: ${err.message}`);
|
|
6476
|
+
}).finally(() => {
|
|
6477
|
+
_populateInFlight.delete(key);
|
|
6478
|
+
});
|
|
6479
|
+
}
|
|
6480
|
+
/** Max files enumerated per populate (whole-repo cap for v1). */
|
|
6481
|
+
const POPULATE_MAX_FILES = 2e4;
|
|
6482
|
+
/** Units per updateDocuments batch (server batches internally too). */
|
|
6483
|
+
const POPULATE_BATCH_UNITS = 100;
|
|
6484
|
+
/** Max concurrent file parses. */
|
|
6485
|
+
const POPULATE_PARSE_CONCURRENCY = 4;
|
|
6486
|
+
async function enumerateSourceFiles(rgPath, workspace, signal) {
|
|
6487
|
+
return new Promise((resolve) => {
|
|
6488
|
+
let child;
|
|
6489
|
+
try {
|
|
6490
|
+
child = spawn(rgPath, [
|
|
6491
|
+
"--files",
|
|
6492
|
+
"--no-follow",
|
|
6493
|
+
"-0"
|
|
6494
|
+
], {
|
|
6495
|
+
cwd: workspace,
|
|
6496
|
+
shell: false,
|
|
6497
|
+
stdio: [
|
|
6498
|
+
"ignore",
|
|
6499
|
+
"pipe",
|
|
6500
|
+
"ignore"
|
|
6501
|
+
]
|
|
6502
|
+
});
|
|
6503
|
+
} catch {
|
|
6504
|
+
resolve([]);
|
|
6505
|
+
return;
|
|
6506
|
+
}
|
|
6507
|
+
let buf = Buffer.alloc(0);
|
|
6508
|
+
const files = [];
|
|
6509
|
+
let done = false;
|
|
6510
|
+
const finish = (out) => {
|
|
6511
|
+
if (done) return;
|
|
6512
|
+
done = true;
|
|
6513
|
+
try {
|
|
6514
|
+
child.kill("SIGKILL");
|
|
6515
|
+
} catch {}
|
|
6516
|
+
resolve(out);
|
|
6517
|
+
};
|
|
6518
|
+
signal.addEventListener("abort", () => finish(files), { once: true });
|
|
6519
|
+
child.on("error", () => finish(files));
|
|
6520
|
+
child.stdout?.on("data", (chunk) => {
|
|
6521
|
+
buf = Buffer.concat([buf, chunk]);
|
|
6522
|
+
let idx;
|
|
6523
|
+
while ((idx = buf.indexOf(0)) >= 0 && files.length < POPULATE_MAX_FILES) {
|
|
6524
|
+
const rel = buf.subarray(0, idx).toString("utf8");
|
|
6525
|
+
buf = buf.subarray(idx + 1);
|
|
6526
|
+
if (rel.length > 0 && !path.isAbsolute(rel)) files.push(rel.replace(/\\/g, "/"));
|
|
6527
|
+
}
|
|
6528
|
+
if (files.length >= POPULATE_MAX_FILES) finish(files);
|
|
6529
|
+
});
|
|
6530
|
+
child.on("close", () => finish(files));
|
|
6531
|
+
});
|
|
6532
|
+
}
|
|
6533
|
+
function resolveRipgrepBin() {
|
|
6534
|
+
try {
|
|
6535
|
+
return resolveRipgrep().rgPath;
|
|
6536
|
+
} catch {
|
|
6537
|
+
return "rg";
|
|
6538
|
+
}
|
|
6539
|
+
}
|
|
6540
|
+
async function populateWorkspace(workspace) {
|
|
6541
|
+
const svc = await ensureServer();
|
|
6542
|
+
if (!svc) return;
|
|
6543
|
+
const canonical = canonicalWorkspace(workspace);
|
|
6544
|
+
const index = indexNameForWorkspace(canonical);
|
|
6545
|
+
await svc.client.ensureIndex(index, { nbits: 4 });
|
|
6546
|
+
const rgPath = resolveRipgrepBin();
|
|
6547
|
+
const ac = new AbortController();
|
|
6548
|
+
const timeout = setTimeout(() => ac.abort(), 18e5);
|
|
6549
|
+
timeout.unref?.();
|
|
6550
|
+
try {
|
|
6551
|
+
const parseable = (await enumerateSourceFiles(rgPath, canonical, ac.signal)).filter((f) => getLanguageKeyForPath(f) !== null);
|
|
6552
|
+
let units = [];
|
|
6553
|
+
let unitTotal = 0;
|
|
6554
|
+
const flush = async () => {
|
|
6555
|
+
if (units.length === 0) return;
|
|
6556
|
+
const batch = units;
|
|
6557
|
+
units = [];
|
|
6558
|
+
await svc.client.updateDocuments(index, batch.map((u) => u.text), batch.map((u) => u.metadata));
|
|
6559
|
+
unitTotal += batch.length;
|
|
6560
|
+
};
|
|
6561
|
+
let next = 0;
|
|
6562
|
+
const workers = Array.from({ length: Math.min(POPULATE_PARSE_CONCURRENCY, parseable.length) }, async () => {
|
|
6563
|
+
while (!ac.signal.aborted) {
|
|
6564
|
+
const i = next;
|
|
6565
|
+
next += 1;
|
|
6566
|
+
if (i >= parseable.length) break;
|
|
6567
|
+
const rel = parseable[i];
|
|
6568
|
+
try {
|
|
6569
|
+
const r = await extractUnits(path.join(canonical, rel), rel, ac.signal);
|
|
6570
|
+
for (const u of r.units) {
|
|
6571
|
+
units.push({
|
|
6572
|
+
text: buildUnitText(u, rel),
|
|
6573
|
+
metadata: {
|
|
6574
|
+
file: u.file,
|
|
6575
|
+
line: u.line,
|
|
6576
|
+
end_line: u.end_line,
|
|
6577
|
+
name: u.name,
|
|
6578
|
+
signature: u.signature,
|
|
6579
|
+
kind: u.kind,
|
|
6580
|
+
unit_id: u.unit_id
|
|
6581
|
+
}
|
|
6582
|
+
});
|
|
6583
|
+
if (units.length >= POPULATE_BATCH_UNITS) await flush();
|
|
6584
|
+
}
|
|
6585
|
+
} catch {}
|
|
6586
|
+
}
|
|
6587
|
+
});
|
|
6588
|
+
await Promise.all(workers);
|
|
6589
|
+
await flush();
|
|
6590
|
+
const g = await gitState(canonical).catch(() => ({ isRepo: false }));
|
|
6591
|
+
await writeServiceMeta({
|
|
6592
|
+
workspace: canonical,
|
|
6593
|
+
index,
|
|
6594
|
+
...g.isRepo ? {
|
|
6595
|
+
head: g.head,
|
|
6596
|
+
dirty: g.dirty ?? false
|
|
6597
|
+
} : {},
|
|
6598
|
+
indexedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
6599
|
+
docCount: unitTotal
|
|
6600
|
+
});
|
|
6601
|
+
consola.debug(`service-backend: indexed ${unitTotal} units in ${canonical}`);
|
|
6602
|
+
} finally {
|
|
6603
|
+
clearTimeout(timeout);
|
|
6604
|
+
}
|
|
6605
|
+
}
|
|
6606
|
+
/**
|
|
6607
|
+
* Search via the service backend. Returns `unavailable` (caller falls back
|
|
6608
|
+
* to colgrep/lexical) when the server, model, or index isn't ready; `failed`
|
|
6609
|
+
* only on unexpected errors. Served rows carry freshness labels per the
|
|
6610
|
+
* serve-while-stale policy.
|
|
6611
|
+
*/
|
|
6612
|
+
async function runServiceSearch(opts) {
|
|
6613
|
+
const { query, workspace } = opts;
|
|
6614
|
+
const limit = Math.max(1, Math.min(100, Math.floor(opts.limit ?? 15)));
|
|
6615
|
+
const canonical = canonicalWorkspace(workspace);
|
|
6616
|
+
const meta = await readServiceMeta(canonical);
|
|
6617
|
+
if (!meta) {
|
|
6618
|
+
kickServiceIndex(canonical);
|
|
6619
|
+
return { status: "unavailable" };
|
|
6620
|
+
}
|
|
6621
|
+
const svc = await ensureServer();
|
|
6622
|
+
if (!svc) return { status: "unavailable" };
|
|
6623
|
+
const index = indexNameForWorkspace(canonical);
|
|
6624
|
+
const g = await gitState(canonical).catch(() => ({ isRepo: false }));
|
|
6625
|
+
let freshness = "fresh";
|
|
6626
|
+
let staleFiles = 0;
|
|
6627
|
+
if (g.isRepo) {
|
|
6628
|
+
const headMoved = meta.head !== void 0 && g.head !== meta.head;
|
|
6629
|
+
const newlyDirty = g.dirty === true && meta.dirty !== true;
|
|
6630
|
+
if (headMoved || newlyDirty) {
|
|
6631
|
+
freshness = "stale";
|
|
6632
|
+
kickServiceIndex(canonical);
|
|
6633
|
+
try {
|
|
6634
|
+
const delta = await gitDeltaFiles(canonical, headMoved ? meta.head : void 0, headMoved ? g.head : void 0);
|
|
6635
|
+
if (delta.truncated || delta.files.length > serveStaleMaxFiles()) return { status: "unavailable" };
|
|
6636
|
+
staleFiles = delta.files.length;
|
|
6637
|
+
} catch {
|
|
6638
|
+
return { status: "unavailable" };
|
|
6639
|
+
}
|
|
6640
|
+
}
|
|
6641
|
+
}
|
|
6642
|
+
try {
|
|
6643
|
+
return {
|
|
6644
|
+
status: "ready",
|
|
6645
|
+
results: (await svc.client.search(index, query, {
|
|
6646
|
+
topK: limit,
|
|
6647
|
+
textQuery: query,
|
|
6648
|
+
alpha: .75
|
|
6649
|
+
})).map((h) => ({
|
|
6650
|
+
file: h.file,
|
|
6651
|
+
line: h.line,
|
|
6652
|
+
snippet: buildSnippet(h),
|
|
6653
|
+
...h.end_line !== void 0 ? { endLine: h.end_line } : {},
|
|
6654
|
+
...h.name !== void 0 ? { name: h.name } : {},
|
|
6655
|
+
score: h.score
|
|
6656
|
+
})),
|
|
6657
|
+
freshness,
|
|
6658
|
+
...freshness === "stale" ? { stale_files: staleFiles } : {}
|
|
6659
|
+
};
|
|
6660
|
+
} catch (err) {
|
|
6661
|
+
if (err instanceof ServiceBusyError) return { status: "unavailable" };
|
|
6662
|
+
consola.debug(`service-backend: search failed: ${err.message}`);
|
|
6663
|
+
return { status: "failed" };
|
|
6664
|
+
}
|
|
6665
|
+
}
|
|
6666
|
+
function buildSnippet(h) {
|
|
6667
|
+
const meta = h.metadata ?? {};
|
|
6668
|
+
const sig = typeof meta.signature === "string" ? meta.signature : "";
|
|
6669
|
+
return sig.length > 0 ? `${sig}\n${h.file}:${h.line}` : `${h.file}:${h.line}`;
|
|
6670
|
+
}
|
|
6671
|
+
//#endregion
|
|
6672
|
+
export { provisionTreeSitterAssets as A, searchCode as C, recommendedRgThreads as D, isSensitivePath as E, warmTreeSitterPool as O, resolveRipgrep as S, confineToWorkspaceResult as T, colbertSmokeOk as _, kickBackgroundInit as a, extractTarGzMember as b, waitForInit as c, freshnessVerdict as d, gitState as f, colbertArtifactsPresent as g, validateIndexIntegrity as h, serviceBackendEnabled as i, withInstallLock as j, outlineFile as k, colbertProjectDir as l, readColbertMeta as m, selectServerVariant as n, runSemanticSearch as o, indexDirSignature as p, semanticBackend as r, startupKickAllowed as s, runServiceSearch as t, completedIndexOnDisk as u, provisionColbert as v, validateWorkspace as w, extractZipMember as x, provisionNextPlaidServer as y };
|
|
5761
6673
|
|
|
5762
|
-
//# sourceMappingURL=
|
|
6674
|
+
//# sourceMappingURL=service-backend-DYEPoszR.js.map
|