github-router 0.3.327 → 0.3.328
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/{aic-ledger-DRU89gJg.js → aic-ledger-CsBx1crE.js} +2 -2
- package/dist/{aic-ledger-DRU89gJg.js.map → aic-ledger-CsBx1crE.js.map} +1 -1
- package/dist/{attribution-settings-FdE6tYAl.js → attribution-settings-CF1ZV58z.js} +10 -10
- package/dist/attribution-settings-CF1ZV58z.js.map +1 -0
- package/dist/{auth-DSLN1arH.js → auth-xgFZGZbf.js} +3 -3
- package/dist/{auth-DSLN1arH.js.map → auth-xgFZGZbf.js.map} +1 -1
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-B_12ALvf.js → check-usage-vUDk6oV7.js} +4 -4
- package/dist/{check-usage-B_12ALvf.js.map → check-usage-vUDk6oV7.js.map} +1 -1
- package/dist/{claude-C6Ddvt8L.js → claude-BdJupNy4.js} +21 -21
- package/dist/{claude-C6Ddvt8L.js.map → claude-BdJupNy4.js.map} +1 -1
- package/dist/{codex-DikHPpLj.js → codex-DgEG2i_w.js} +6 -6
- package/dist/{codex-DikHPpLj.js.map → codex-DgEG2i_w.js.map} +1 -1
- package/dist/{copilot-discount-D8t7Q3Tp.js → copilot-discount-0lG67i9O.js} +2 -2
- package/dist/{copilot-discount-D8t7Q3Tp.js.map → copilot-discount-0lG67i9O.js.map} +1 -1
- package/dist/{debug-D8iD6G4O.js → debug-a737qcCC.js} +2 -2
- package/dist/{debug-D8iD6G4O.js.map → debug-a737qcCC.js.map} +1 -1
- package/dist/engine-C3SnOV1U.js +2 -0
- package/dist/{gate-discovery-CBna9eP-.js → gate-discovery-ufkJQE8V.js} +5 -5
- package/dist/{gate-discovery-CBna9eP-.js.map → gate-discovery-ufkJQE8V.js.map} +1 -1
- package/dist/{get-copilot-usage-Bs-FEPMf.js → get-copilot-usage-VKU2IvuE.js} +2 -2
- package/dist/{get-copilot-usage-Bs-FEPMf.js.map → get-copilot-usage-VKU2IvuE.js.map} +1 -1
- package/dist/{index-cmd-BnIqDmBT.js → index-cmd-mPy73hig.js} +4 -4
- package/dist/{index-cmd-BnIqDmBT.js.map → index-cmd-mPy73hig.js.map} +1 -1
- package/dist/{internal-aic-status-BaUKlisM.js → internal-aic-status-Cfl5HiAN.js} +3 -3
- package/dist/{internal-aic-status-BaUKlisM.js.map → internal-aic-status-Cfl5HiAN.js.map} +1 -1
- package/dist/{internal-artifact-open-U-Ht7R-O.js → internal-artifact-open-CX2fRP_D.js} +2 -2
- package/dist/{internal-artifact-open-U-Ht7R-O.js.map → internal-artifact-open-CX2fRP_D.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-Dnjoj0pV.js → internal-fast-dispatch-guard-BoTxjO6b.js} +2 -2
- package/dist/{internal-fast-dispatch-guard-Dnjoj0pV.js.map → internal-fast-dispatch-guard-BoTxjO6b.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-uztSu0c8.js → internal-fast-dispatch-guard-Cxattkm4.js} +1 -1
- package/dist/{internal-first-mate-guard-ZqPHrYlh.js → internal-first-mate-guard-97qsseTP.js} +1 -1
- package/dist/{internal-first-mate-guard-Cj_g7RFr.js → internal-first-mate-guard-D_JFcrl_.js} +3 -3
- package/dist/{internal-first-mate-guard-Cj_g7RFr.js.map → internal-first-mate-guard-D_JFcrl_.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-Sp_rCYk_.js → internal-max-dispatch-guard-Cxe8h12x.js} +2 -2
- package/dist/{internal-max-dispatch-guard-Sp_rCYk_.js.map → internal-max-dispatch-guard-Cxe8h12x.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-CxG_c3cc.js → internal-max-dispatch-guard-DQMyOds8.js} +1 -1
- package/dist/{internal-plan-review-Co01iHOW.js → internal-plan-review-DM-Zycyn.js} +3 -3
- package/dist/{internal-plan-review-Co01iHOW.js.map → internal-plan-review-DM-Zycyn.js.map} +1 -1
- package/dist/{internal-prompt-submit-dflz0bqH.js → internal-prompt-submit-6AKy89nq.js} +4 -4
- package/dist/{internal-prompt-submit-dflz0bqH.js.map → internal-prompt-submit-6AKy89nq.js.map} +1 -1
- package/dist/{internal-session-bind-BVQy7Vd4.js → internal-session-bind-CHIOd5ys.js} +2 -2
- package/dist/{internal-session-bind-BVQy7Vd4.js.map → internal-session-bind-CHIOd5ys.js.map} +1 -1
- package/dist/{internal-stop-hook-DNfS5cxB.js → internal-stop-hook-CWwkeyf_.js} +5 -5
- package/dist/{internal-stop-hook-DNfS5cxB.js.map → internal-stop-hook-CWwkeyf_.js.map} +1 -1
- package/dist/{internal-stop-review-CrnG4IJo.js → internal-stop-review-CPk66wwo.js} +2 -2
- package/dist/{internal-stop-review-CrnG4IJo.js.map → internal-stop-review-CPk66wwo.js.map} +1 -1
- package/dist/{internal-worker-guard-Dd14aDXQ.js → internal-worker-guard-BY5seBqp.js} +2 -2
- package/dist/{internal-worker-guard-Dd14aDXQ.js.map → internal-worker-guard-BY5seBqp.js.map} +1 -1
- package/dist/{internal-workspace-header-booLOzwD.js → internal-workspace-header-CPZNphnk.js} +2 -2
- package/dist/{internal-workspace-header-booLOzwD.js.map → internal-workspace-header-CPZNphnk.js.map} +1 -1
- package/dist/lifecycle-B2eB8nRg.js +2 -0
- package/dist/{lifecycle-C1LDvDD6.js → lifecycle-D8vQXfeC.js} +7 -3
- package/dist/{lifecycle-C1LDvDD6.js.map → lifecycle-D8vQXfeC.js.map} +1 -1
- package/dist/lifecycle-Dz-Rq8pD.js +2 -0
- package/dist/{lifecycle-BYPEqFdV.js → lifecycle-MmpJWRcl.js} +2 -2
- package/dist/{lifecycle-BYPEqFdV.js.map → lifecycle-MmpJWRcl.js.map} +1 -1
- package/dist/main.js +21 -21
- package/dist/{mcp-workspace-header-BIW0SRgs.js → mcp-workspace-header-DX_mD0JT.js} +2 -2
- package/dist/{mcp-workspace-header-BIW0SRgs.js.map → mcp-workspace-header-DX_mD0JT.js.map} +1 -1
- package/dist/{models-B9tdaM6B.js → models-BjCRO0AC.js} +3 -3
- package/dist/{models-B9tdaM6B.js.map → models-BjCRO0AC.js.map} +1 -1
- package/dist/{orchestration-DvsdorFq.js → orchestration-Dn5v8c0a.js} +2 -2
- package/dist/{orchestration-DvsdorFq.js.map → orchestration-Dn5v8c0a.js.map} +1 -1
- package/dist/paths-DVXBtLyo.js +2 -0
- package/dist/{paths-BnZwolac.js → paths-P5ajjpzU.js} +3 -3
- package/dist/{paths-BnZwolac.js.map → paths-P5ajjpzU.js.map} +1 -1
- package/dist/{peer-mcp-personas-Cs7qXWA7.js → peer-mcp-personas-Dg2LJ0GF.js} +1005 -21
- package/dist/peer-mcp-personas-Dg2LJ0GF.js.map +1 -0
- package/dist/{plan-review-hook-BlsGnG02.js → plan-review-hook-ChuywYy_.js} +3 -3
- package/dist/{plan-review-hook-BlsGnG02.js.map → plan-review-hook-ChuywYy_.js.map} +1 -1
- package/dist/{prompt-submit-hook-BJFLzCaT.js → prompt-submit-hook-C0ZospPT.js} +3 -3
- package/dist/{prompt-submit-hook-BJFLzCaT.js.map → prompt-submit-hook-C0ZospPT.js.map} +1 -1
- package/dist/{provision-5FSlDXXk.js → provision-l0THw3kO.js} +5 -5
- package/dist/{provision-5FSlDXXk.js.map → provision-l0THw3kO.js.map} +1 -1
- package/dist/{runner-CFR2seH4.js → runner-BoJPRQsK.js} +154 -16
- package/dist/runner-BoJPRQsK.js.map +1 -0
- package/dist/{self-invocation-opSXHEs0.js → self-invocation-DBWyjvGm.js} +2 -2
- package/dist/{self-invocation-opSXHEs0.js.map → self-invocation-DBWyjvGm.js.map} +1 -1
- package/dist/{serve-DPeyTjn0.js → serve-DZY93dBo.js} +13 -13
- package/dist/{serve-DPeyTjn0.js.map → serve-DZY93dBo.js.map} +1 -1
- package/dist/{server-setup-Bymo8rfd.js → server-setup-Bv7TGDC7.js} +8 -8
- package/dist/{server-setup-Bymo8rfd.js.map → server-setup-Bv7TGDC7.js.map} +1 -1
- package/dist/{start-RwIzqSUq.js → start-2SrUerLA.js} +4 -4
- package/dist/{start-RwIzqSUq.js.map → start-2SrUerLA.js.map} +1 -1
- package/dist/{stop-gate-hook-DvNM8zFf.js → stop-gate-hook-BACb8dlj.js} +3 -3
- package/dist/{stop-gate-hook-DvNM8zFf.js.map → stop-gate-hook-BACb8dlj.js.map} +1 -1
- package/dist/{stop-gate-policy-C5pXbY59.js → stop-gate-policy-D6jIeOXB.js} +2 -2
- package/dist/{stop-gate-policy-C5pXbY59.js.map → stop-gate-policy-D6jIeOXB.js.map} +1 -1
- package/dist/{token-Css-ARGL.js → token-Dlb_84hW.js} +2 -2
- package/dist/{token-Css-ARGL.js.map → token-Dlb_84hW.js.map} +1 -1
- package/dist/{worker-dispatch-CcQygiAA.js → worker-dispatch-DtjQchvM.js} +2 -2
- package/dist/{worker-dispatch-CcQygiAA.js.map → worker-dispatch-DtjQchvM.js.map} +1 -1
- package/package.json +1 -1
- package/dist/attribution-settings-FdE6tYAl.js.map +0 -1
- package/dist/engine-CNDZ4OP_.js +0 -2
- package/dist/lifecycle-Cz99P30h.js +0 -2
- package/dist/lifecycle-DqTFEJpS.js +0 -2
- package/dist/paths-BzM6uxmd.js +0 -2
- package/dist/peer-mcp-personas-Cs7qXWA7.js.map +0 -1
- package/dist/runner-CFR2seH4.js.map +0 -1
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as recommendedRgThreads, E as searchCode, F as getGrammarBundle, I as getLanguageKeyForPath, L as outlineFile, M as DEFINITION_NODE_TYPES, O as confineToWorkspaceResult, P as collectUnitNodes, T as resolveRipgrep, _ as colbertOrtDylibPath, a as canonicalWorkspace, b as provisionColbert, f as readColbertMeta, g as colbertArtifactsPresent, h as canonicalColbertModelDir, k as isSensitivePath, l as gitDeltaFiles, n as runSemanticSearch, p as serveStaleMaxFiles, r as startupKickAllowed, t as kickBackgroundInit, u as gitState, v as colbertSmokeOk, w as nextPlaidServerPromoted, x as provisionNextPlaidServer, y as nextPlaidServerBinaryPath } from "./runner-BoJPRQsK.js";
|
|
2
2
|
import { n as explicitPackageRoot } from "./package-root-B-osctCk.js";
|
|
3
3
|
import { t as getPackageVersion } from "./version-C8x2hQrZ.js";
|
|
4
|
-
import { t as PATHS } from "./paths-
|
|
4
|
+
import { t as PATHS } from "./paths-P5ajjpzU.js";
|
|
5
5
|
import { t as state } from "./state-BlMpEFAt.js";
|
|
6
|
-
import { C as GITHUB_GRAPHQL_URL, D as githubAgentGraphQLHeaders, E as copilotVersion, O as githubAgentHeaders, S as GITHUB_API_BASE_URL, T as copilotHeaders, b as sanitizeTransportText, d as resolveModel, f as sleep$2, g as HTTPError, h as isAllowedCopilotHost, i as tryRefreshAndRetry, v as classifyTransportError, w as copilotBaseUrl, x as withTransientRetry, y as fetchWithTransientRetry } from "./token-
|
|
6
|
+
import { C as GITHUB_GRAPHQL_URL, D as githubAgentGraphQLHeaders, E as copilotVersion, O as githubAgentHeaders, S as GITHUB_API_BASE_URL, T as copilotHeaders, b as sanitizeTransportText, d as resolveModel, f as sleep$2, g as HTTPError, h as isAllowedCopilotHost, i as tryRefreshAndRetry, v as classifyTransportError, w as copilotBaseUrl, x as withTransientRetry, y as fetchWithTransientRetry } from "./token-Dlb_84hW.js";
|
|
7
7
|
import { a as parseIntEnv, i as parseBoolEnv, l as runManagedExeCapture, o as resolveExecutable } from "./exec-COUT4QsS.js";
|
|
8
8
|
import { a as FAST_PROFILE_ASTRA_MODEL, c as FAST_PROFILE_MODELS, d as FAST_PROFILE_NATIVE_MODELS, f as FAST_PROFILE_ORACLE_EFFORT, n as FAST_PROFILE_ADVISOR_EFFORT, p as FAST_PROFILE_ORACLE_MODEL, r as FAST_PROFILE_ADVISOR_MODEL, u as FAST_PROFILE_NATIVE_EFFORTS } from "./fast-profile-contract-DmsyQQrw.js";
|
|
9
9
|
import { A as normalizeTrailingOneMSuffix, D as maxPeerInstructions, E as maxPeerDescription, O as fastEndpointForCatalogId, b as MAX_ADVISOR_SYSTEM_PROMPT, f as maxCodexReviewerModel, g as maxProReplacementModel, h as maxOpusModel, i as MAX_PROFILE_MODELS, k as fastEndpointForModel, m as maxGrokModel, p as maxGeminiModel, r as MAX_PROFILE_LEAD_MODEL, v as maxSonnetModel } from "./max-profile-contract-Bl7I_EOC.js";
|
|
10
|
-
import { i as registerExitHandlers$1, n as getInstanceUuid, r as recordWorkerRepo, t as WorktreeRegistry } from "./lifecycle-
|
|
11
|
-
import { t as MCP_WORKSPACE_HEADER } from "./mcp-workspace-header-
|
|
10
|
+
import { i as registerExitHandlers$1, n as getInstanceUuid, r as recordWorkerRepo, t as WorktreeRegistry } from "./lifecycle-MmpJWRcl.js";
|
|
11
|
+
import { t as MCP_WORKSPACE_HEADER } from "./mcp-workspace-header-DX_mD0JT.js";
|
|
12
12
|
import { n as ArtifactError, r as applyInsecureTls, t as ArtifactClient } from "./client-CQMfroGV.js";
|
|
13
|
-
import { r as registerColbertExitHandlers } from "./lifecycle-
|
|
14
|
-
import { a as extractAndRecordPricedAic, i as extractAndRecordAic, l as recordAic, p as extractCopilotUsage } from "./aic-ledger-
|
|
15
|
-
import { h as runGateChecks, m as sealedGateIds, p as resolveSealedGate } from "./stop-gate-hook-
|
|
16
|
-
import { t as liveExec } from "./orchestration-
|
|
13
|
+
import { c as untrackChild, r as registerColbertExitHandlers, s as trackChild } from "./lifecycle-D8vQXfeC.js";
|
|
14
|
+
import { a as extractAndRecordPricedAic, i as extractAndRecordAic, l as recordAic, p as extractCopilotUsage } from "./aic-ledger-CsBx1crE.js";
|
|
15
|
+
import { h as runGateChecks, m as sealedGateIds, p as resolveSealedGate } from "./stop-gate-hook-BACb8dlj.js";
|
|
16
|
+
import { t as liveExec } from "./orchestration-Dn5v8c0a.js";
|
|
17
17
|
import { createRequire } from "node:module";
|
|
18
18
|
import consola from "consola";
|
|
19
19
|
import { chmodSync, closeSync, constants, cpSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
|
|
@@ -22,12 +22,15 @@ import path from "node:path";
|
|
|
22
22
|
import { fileURLToPath } from "node:url";
|
|
23
23
|
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
24
24
|
import fs$1, { open, readFile, stat } from "node:fs/promises";
|
|
25
|
+
import * as os$1 from "node:os";
|
|
25
26
|
import os, { homedir, platform } from "node:os";
|
|
26
27
|
import process$1 from "node:process";
|
|
27
28
|
import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
|
|
28
29
|
import { ProxyAgent } from "undici";
|
|
29
30
|
import { z } from "zod";
|
|
30
31
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
32
|
+
import { Parser } from "web-tree-sitter";
|
|
33
|
+
import * as net from "node:net";
|
|
31
34
|
import WebSocket from "ws";
|
|
32
35
|
import { events } from "fetch-event-stream";
|
|
33
36
|
import { Type, Type as Type$1 } from "typebox";
|
|
@@ -12416,6 +12419,959 @@ function anyProp(description) {
|
|
|
12416
12419
|
return { description };
|
|
12417
12420
|
}
|
|
12418
12421
|
//#endregion
|
|
12422
|
+
//#region src/lib/colbert/service.ts
|
|
12423
|
+
/**
|
|
12424
|
+
* next-plaid-api service client + managed lifecycle (Phase 2e).
|
|
12425
|
+
*
|
|
12426
|
+
* The semantic backend moves from colgrep CLI-per-invocation (every query
|
|
12427
|
+
* re-loads ORT + model + index) to a persistent `next-plaid-api` server
|
|
12428
|
+
* (model warm, PLAID mmap'd, lock-free reads, batched async writes).
|
|
12429
|
+
* This module owns the HTTP protocol and the child-process lifecycle;
|
|
12430
|
+
* the query-path switch (runner → service) lands separately once a
|
|
12431
|
+
* provisioned binary exists (see the CI build workflow).
|
|
12432
|
+
*
|
|
12433
|
+
* API surface (next-plaid-api v1.7.0, verified from upstream README):
|
|
12434
|
+
* GET /health → system + per-index summaries
|
|
12435
|
+
* POST /indices {name, config} → declare index (409 taken)
|
|
12436
|
+
* POST /indices/{name}/update_with_encoding → 202 (async batch)
|
|
12437
|
+
* DELETE /indices/{name}/documents {condition, parameters} → 202
|
|
12438
|
+
* POST /indices/{name}/search_with_encoding → ranked hits + metadata
|
|
12439
|
+
*
|
|
12440
|
+
* Conventions shared with the colbert sidecar: never log response bodies
|
|
12441
|
+
* (they embed source code), bound every request with a timeout, fail
|
|
12442
|
+
* closed (throw → caller falls back to lexical).
|
|
12443
|
+
*/
|
|
12444
|
+
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
12445
|
+
async function fetchJson(url, init, timeoutMs) {
|
|
12446
|
+
const ac = new AbortController();
|
|
12447
|
+
const timer = setTimeout(() => ac.abort(/* @__PURE__ */ new Error("service request timeout")), timeoutMs);
|
|
12448
|
+
timer.unref?.();
|
|
12449
|
+
try {
|
|
12450
|
+
const res = await fetch(url, {
|
|
12451
|
+
...init,
|
|
12452
|
+
signal: ac.signal
|
|
12453
|
+
});
|
|
12454
|
+
const text = await res.text();
|
|
12455
|
+
let body = null;
|
|
12456
|
+
try {
|
|
12457
|
+
body = text.length > 0 ? JSON.parse(text) : null;
|
|
12458
|
+
} catch {
|
|
12459
|
+
body = null;
|
|
12460
|
+
}
|
|
12461
|
+
return {
|
|
12462
|
+
status: res.status,
|
|
12463
|
+
body
|
|
12464
|
+
};
|
|
12465
|
+
} finally {
|
|
12466
|
+
clearTimeout(timer);
|
|
12467
|
+
}
|
|
12468
|
+
}
|
|
12469
|
+
/**
|
|
12470
|
+
* Thin HTTP client over a running next-plaid-api server. Construct with
|
|
12471
|
+
* the base URL (`http://127.0.0.1:PORT`); use `startManagedServer` below
|
|
12472
|
+
* for process lifecycle, or point at an externally managed server.
|
|
12473
|
+
*/
|
|
12474
|
+
var NextPlaidClient = class {
|
|
12475
|
+
baseUrl;
|
|
12476
|
+
timeoutMs;
|
|
12477
|
+
constructor(baseUrl, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
12478
|
+
this.baseUrl = baseUrl.replace(/\/+$/, "");
|
|
12479
|
+
this.timeoutMs = timeoutMs;
|
|
12480
|
+
}
|
|
12481
|
+
async health() {
|
|
12482
|
+
const { status, body } = await fetchJson(`${this.baseUrl}/health`, {}, this.timeoutMs);
|
|
12483
|
+
if (status !== 200 || typeof body !== "object" || body === null) return {
|
|
12484
|
+
ok: false,
|
|
12485
|
+
indices: []
|
|
12486
|
+
};
|
|
12487
|
+
const b = body;
|
|
12488
|
+
return {
|
|
12489
|
+
ok: b.status === "healthy",
|
|
12490
|
+
indices: (b.indices ?? []).map((i) => ({
|
|
12491
|
+
name: typeof i.name === "string" ? i.name : "",
|
|
12492
|
+
num_documents: typeof i.num_documents === "number" ? i.num_documents : 0,
|
|
12493
|
+
num_embeddings: typeof i.num_embeddings === "number" ? i.num_embeddings : 0,
|
|
12494
|
+
dimension: typeof i.dimension === "number" ? i.dimension : 0
|
|
12495
|
+
})),
|
|
12496
|
+
model: b.model?.name
|
|
12497
|
+
};
|
|
12498
|
+
}
|
|
12499
|
+
/** Declare an index (idempotent: 409 taken is success). */
|
|
12500
|
+
async ensureIndex(name, config = {}) {
|
|
12501
|
+
const { status, body } = await fetchJson(`${this.baseUrl}/indices`, {
|
|
12502
|
+
method: "POST",
|
|
12503
|
+
headers: { "content-type": "application/json" },
|
|
12504
|
+
body: JSON.stringify({
|
|
12505
|
+
name,
|
|
12506
|
+
config: {
|
|
12507
|
+
nbits: config.nbits ?? 4,
|
|
12508
|
+
...config.pool_factor !== void 0 ? { pool_factor: config.pool_factor } : {},
|
|
12509
|
+
...config.start_from_scratch !== void 0 ? { start_from_scratch: config.start_from_scratch } : {}
|
|
12510
|
+
}
|
|
12511
|
+
})
|
|
12512
|
+
}, this.timeoutMs);
|
|
12513
|
+
if (status === 200 || status === 201 || status === 409) return;
|
|
12514
|
+
throw new Error(`ensureIndex ${name} failed: HTTP ${status} (${describeError$1(body)})`);
|
|
12515
|
+
}
|
|
12516
|
+
/**
|
|
12517
|
+
* Add/update documents (server encodes text). 202 = accepted into the
|
|
12518
|
+
* async batch queue (NOT yet searchable — the server merges within
|
|
12519
|
+
* ~100ms/300 docs). Never throws for queue-full: maps 503 to a typed
|
|
12520
|
+
* error the caller retries after backoff.
|
|
12521
|
+
*/
|
|
12522
|
+
async updateDocuments(index, documents, metadata, poolFactor = 2) {
|
|
12523
|
+
const { status, body } = await fetchJson(`${this.baseUrl}/indices/${encodeURIComponent(index)}/update_with_encoding`, {
|
|
12524
|
+
method: "POST",
|
|
12525
|
+
headers: { "content-type": "application/json" },
|
|
12526
|
+
body: JSON.stringify({
|
|
12527
|
+
documents,
|
|
12528
|
+
metadata,
|
|
12529
|
+
pool_factor: poolFactor
|
|
12530
|
+
})
|
|
12531
|
+
}, this.timeoutMs);
|
|
12532
|
+
if (status === 202) return;
|
|
12533
|
+
if (status === 503) throw new ServiceBusyError(index);
|
|
12534
|
+
throw new Error(`update ${index} failed: HTTP ${status} (${describeError$1(body)})`);
|
|
12535
|
+
}
|
|
12536
|
+
/** Delete by SQL predicate (batched server-side, 202 accepted). */
|
|
12537
|
+
async deleteDocuments(index, condition, parameters = []) {
|
|
12538
|
+
const { status, body } = await fetchJson(`${this.baseUrl}/indices/${encodeURIComponent(index)}/documents`, {
|
|
12539
|
+
method: "DELETE",
|
|
12540
|
+
headers: { "content-type": "application/json" },
|
|
12541
|
+
body: JSON.stringify({
|
|
12542
|
+
condition,
|
|
12543
|
+
parameters
|
|
12544
|
+
})
|
|
12545
|
+
}, this.timeoutMs);
|
|
12546
|
+
if (status === 202) return;
|
|
12547
|
+
if (status === 404) return;
|
|
12548
|
+
if (status === 503) throw new ServiceBusyError(index);
|
|
12549
|
+
throw new Error(`delete ${index} failed: HTTP ${status} (${describeError$1(body)})`);
|
|
12550
|
+
}
|
|
12551
|
+
/**
|
|
12552
|
+
* Hybrid search (semantic + FTS5 keyword, server-side RRF fusion).
|
|
12553
|
+
* `fileGlob` scopes via metadata filter when provided (the indexer
|
|
12554
|
+
* stores `file` per doc). Returns hits in ranked order.
|
|
12555
|
+
*/
|
|
12556
|
+
async search(index, query, opts = {}) {
|
|
12557
|
+
const top_k = Math.max(1, Math.floor(opts.topK ?? 15));
|
|
12558
|
+
const body = {
|
|
12559
|
+
queries: [query],
|
|
12560
|
+
params: {
|
|
12561
|
+
top_k,
|
|
12562
|
+
...opts.nIvfProbe !== void 0 ? { n_ivf_probe: opts.nIvfProbe } : {}
|
|
12563
|
+
}
|
|
12564
|
+
};
|
|
12565
|
+
if (opts.textQuery) {
|
|
12566
|
+
body.text_query = [opts.textQuery];
|
|
12567
|
+
body.alpha = opts.alpha ?? .75;
|
|
12568
|
+
body.fusion = "relative_score";
|
|
12569
|
+
}
|
|
12570
|
+
if (opts.fileGlob) {
|
|
12571
|
+
body.filter_condition = "file GLOB ?";
|
|
12572
|
+
body.filter_parameters = [opts.fileGlob];
|
|
12573
|
+
}
|
|
12574
|
+
const { status, body: res } = await fetchJson(`${this.baseUrl}/indices/${encodeURIComponent(index)}/search_with_encoding`, {
|
|
12575
|
+
method: "POST",
|
|
12576
|
+
headers: { "content-type": "application/json" },
|
|
12577
|
+
body: JSON.stringify(body)
|
|
12578
|
+
}, this.timeoutMs);
|
|
12579
|
+
if (status === 404) return [];
|
|
12580
|
+
if (status === 503) throw new ServiceBusyError(index);
|
|
12581
|
+
if (status !== 200) throw new Error(`search ${index} failed: HTTP ${status} (${describeError$1(res)})`);
|
|
12582
|
+
return toHits(res);
|
|
12583
|
+
}
|
|
12584
|
+
};
|
|
12585
|
+
/** Queue-full signal: retry after backoff, never fatal. */
|
|
12586
|
+
var ServiceBusyError = class extends Error {
|
|
12587
|
+
index;
|
|
12588
|
+
constructor(index) {
|
|
12589
|
+
super(`next-plaid index ${index} busy (queue full); retry after backoff`);
|
|
12590
|
+
this.name = "ServiceBusyError";
|
|
12591
|
+
this.index = index;
|
|
12592
|
+
}
|
|
12593
|
+
};
|
|
12594
|
+
function describeError$1(body) {
|
|
12595
|
+
if (typeof body === "object" && body !== null) {
|
|
12596
|
+
const b = body;
|
|
12597
|
+
const code = typeof b.code === "string" ? b.code : "?";
|
|
12598
|
+
const message = typeof b.message === "string" ? b.message : "";
|
|
12599
|
+
return `${code}${message ? `: ${message.slice(0, 200)}` : ""}`;
|
|
12600
|
+
}
|
|
12601
|
+
return "unparseable response";
|
|
12602
|
+
}
|
|
12603
|
+
/**
|
|
12604
|
+
* Map the API search response to file-anchored hits. Metadata carries the
|
|
12605
|
+
* unit fields the indexer stored (file/line/end_line/name/signature);
|
|
12606
|
+
* rows missing a file are dropped (never surface an unanchored hit).
|
|
12607
|
+
*/
|
|
12608
|
+
function toHits(res) {
|
|
12609
|
+
const out = [];
|
|
12610
|
+
for (const r of res.results ?? []) {
|
|
12611
|
+
const ids = r.document_ids ?? [];
|
|
12612
|
+
const scores = r.scores ?? [];
|
|
12613
|
+
const metas = r.metadata ?? [];
|
|
12614
|
+
for (let i = 0; i < ids.length; i++) {
|
|
12615
|
+
const meta = metas[i] ?? {};
|
|
12616
|
+
const file = meta.file;
|
|
12617
|
+
if (typeof file !== "string" || file.length === 0) continue;
|
|
12618
|
+
const line = meta.line;
|
|
12619
|
+
out.push({
|
|
12620
|
+
file,
|
|
12621
|
+
line: typeof line === "number" ? line : 1,
|
|
12622
|
+
...typeof meta.end_line === "number" ? { end_line: meta.end_line } : {},
|
|
12623
|
+
...typeof meta.name === "string" ? { name: meta.name } : {},
|
|
12624
|
+
score: typeof scores[i] === "number" ? scores[i] : 0,
|
|
12625
|
+
metadata: meta
|
|
12626
|
+
});
|
|
12627
|
+
}
|
|
12628
|
+
}
|
|
12629
|
+
return out;
|
|
12630
|
+
}
|
|
12631
|
+
/** Find a free loopback port (TOCTOU-racy by nature; retry on collision). */
|
|
12632
|
+
async function freePort() {
|
|
12633
|
+
return new Promise((resolve, reject) => {
|
|
12634
|
+
const s = net.createServer();
|
|
12635
|
+
s.on("error", reject);
|
|
12636
|
+
s.listen(0, "127.0.0.1", () => {
|
|
12637
|
+
const addr = s.address();
|
|
12638
|
+
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
|
12639
|
+
s.close((err) => err ? reject(err) : resolve(port));
|
|
12640
|
+
});
|
|
12641
|
+
});
|
|
12642
|
+
}
|
|
12643
|
+
/**
|
|
12644
|
+
* Spawn the server, wait for `/health`, return a managed handle. Throws
|
|
12645
|
+
* when the binary is missing, the port never becomes healthy, or the
|
|
12646
|
+
* child exits early (stderr is captured, truncated, never logged raw —
|
|
12647
|
+
* it can embed paths, not source, but the discipline is cheap).
|
|
12648
|
+
*/
|
|
12649
|
+
/**
|
|
12650
|
+
* Build the next-plaid-api argv (exported for unit tests; production
|
|
12651
|
+
* goes through `startManagedServer`). `--int8`/`--cuda` both require
|
|
12652
|
+
* `--model` (upstream CLI contract) and are never passed alone.
|
|
12653
|
+
*/
|
|
12654
|
+
function serverArgv(opts, port) {
|
|
12655
|
+
return [
|
|
12656
|
+
"--host",
|
|
12657
|
+
"127.0.0.1",
|
|
12658
|
+
"--port",
|
|
12659
|
+
String(port),
|
|
12660
|
+
"--index-dir",
|
|
12661
|
+
opts.indexDir,
|
|
12662
|
+
...opts.modelDir ? ["--model", opts.modelDir] : [],
|
|
12663
|
+
...opts.modelDir && opts.int8 !== false ? ["--int8"] : [],
|
|
12664
|
+
...opts.modelDir && opts.cuda === true ? ["--cuda"] : [],
|
|
12665
|
+
"--parallel",
|
|
12666
|
+
String(Math.max(1, Math.floor(opts.parallel ?? 1)))
|
|
12667
|
+
];
|
|
12668
|
+
}
|
|
12669
|
+
async function startManagedServer(opts) {
|
|
12670
|
+
const port = opts.port ?? await freePort();
|
|
12671
|
+
const args = opts.argv ?? serverArgv(opts, port);
|
|
12672
|
+
let child;
|
|
12673
|
+
try {
|
|
12674
|
+
child = spawn(opts.binaryPath, args, {
|
|
12675
|
+
env: {
|
|
12676
|
+
...process$1.env,
|
|
12677
|
+
...opts.env
|
|
12678
|
+
},
|
|
12679
|
+
stdio: [
|
|
12680
|
+
"ignore",
|
|
12681
|
+
"pipe",
|
|
12682
|
+
"pipe"
|
|
12683
|
+
],
|
|
12684
|
+
windowsHide: true
|
|
12685
|
+
});
|
|
12686
|
+
} catch (err) {
|
|
12687
|
+
throw new Error(`next-plaid server failed to spawn: ${err.message}`, { cause: err });
|
|
12688
|
+
}
|
|
12689
|
+
trackChild(child);
|
|
12690
|
+
child.on("error", () => {
|
|
12691
|
+
untrackChild(child);
|
|
12692
|
+
});
|
|
12693
|
+
let stderrTail = "";
|
|
12694
|
+
child.stderr?.setEncoding("utf8");
|
|
12695
|
+
child.stderr?.on("data", (chunk) => {
|
|
12696
|
+
stderrTail = (stderrTail + chunk).slice(-4096);
|
|
12697
|
+
});
|
|
12698
|
+
const url = `http://127.0.0.1:${port}`;
|
|
12699
|
+
const client = new NextPlaidClient(url);
|
|
12700
|
+
const deadline = Date.now() + (opts.startupTimeoutMs ?? 6e4);
|
|
12701
|
+
let exited = null;
|
|
12702
|
+
let spawnFailed = false;
|
|
12703
|
+
child.on("exit", (code) => {
|
|
12704
|
+
exited = code;
|
|
12705
|
+
});
|
|
12706
|
+
child.on("error", () => {
|
|
12707
|
+
spawnFailed = true;
|
|
12708
|
+
});
|
|
12709
|
+
child.on("close", () => {
|
|
12710
|
+
if (exited === null) spawnFailed = true;
|
|
12711
|
+
});
|
|
12712
|
+
try {
|
|
12713
|
+
for (;;) {
|
|
12714
|
+
if (exited !== null || spawnFailed) throw new Error(`next-plaid server exited during startup${exited !== null ? ` (code ${exited})` : ""}: ${stderrTail.slice(-500)}`);
|
|
12715
|
+
try {
|
|
12716
|
+
if ((await client.health()).ok) return {
|
|
12717
|
+
url,
|
|
12718
|
+
client,
|
|
12719
|
+
stop: () => stopServer(child)
|
|
12720
|
+
};
|
|
12721
|
+
} catch {}
|
|
12722
|
+
if (Date.now() > deadline) throw new Error(`next-plaid server not healthy after startup budget: ${stderrTail.slice(-500)}`);
|
|
12723
|
+
await new Promise((r) => {
|
|
12724
|
+
setTimeout(() => r(), 250).unref?.();
|
|
12725
|
+
});
|
|
12726
|
+
}
|
|
12727
|
+
} catch (err) {
|
|
12728
|
+
await stopServer(child).catch(() => {});
|
|
12729
|
+
throw err;
|
|
12730
|
+
}
|
|
12731
|
+
}
|
|
12732
|
+
async function stopServer(child) {
|
|
12733
|
+
try {
|
|
12734
|
+
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
12735
|
+
if (child.pid === void 0) return;
|
|
12736
|
+
let finished = false;
|
|
12737
|
+
let doneResolve = () => {};
|
|
12738
|
+
const done = new Promise((resolve) => {
|
|
12739
|
+
doneResolve = resolve;
|
|
12740
|
+
});
|
|
12741
|
+
const finish = () => {
|
|
12742
|
+
if (finished) return;
|
|
12743
|
+
finished = true;
|
|
12744
|
+
clearTimeout(escalation);
|
|
12745
|
+
clearTimeout(backstop);
|
|
12746
|
+
doneResolve();
|
|
12747
|
+
};
|
|
12748
|
+
child.once("exit", finish);
|
|
12749
|
+
child.once("close", finish);
|
|
12750
|
+
const escalation = setTimeout(() => {
|
|
12751
|
+
try {
|
|
12752
|
+
child.kill("SIGKILL");
|
|
12753
|
+
} catch {}
|
|
12754
|
+
}, 5e3);
|
|
12755
|
+
escalation.unref?.();
|
|
12756
|
+
const backstop = setTimeout(finish, 15e3);
|
|
12757
|
+
backstop.unref?.();
|
|
12758
|
+
try {
|
|
12759
|
+
child.kill("SIGTERM");
|
|
12760
|
+
} catch {
|
|
12761
|
+
finish();
|
|
12762
|
+
return;
|
|
12763
|
+
}
|
|
12764
|
+
if (process$1.platform === "win32") try {
|
|
12765
|
+
const { spawnSync } = await import("node:child_process");
|
|
12766
|
+
if (child.pid) spawnSync("taskkill", [
|
|
12767
|
+
"/T",
|
|
12768
|
+
"/F",
|
|
12769
|
+
"/PID",
|
|
12770
|
+
String(child.pid)
|
|
12771
|
+
], {
|
|
12772
|
+
stdio: "ignore",
|
|
12773
|
+
windowsHide: true
|
|
12774
|
+
});
|
|
12775
|
+
} catch {}
|
|
12776
|
+
await done;
|
|
12777
|
+
} finally {
|
|
12778
|
+
untrackChild(child);
|
|
12779
|
+
}
|
|
12780
|
+
}
|
|
12781
|
+
/** CPU-aware default parallelism for the managed server. */
|
|
12782
|
+
function serverParallelSessions() {
|
|
12783
|
+
const raw = Number(process$1.env.GH_ROUTER_NP_PARALLEL);
|
|
12784
|
+
if (Number.isSafeInteger(raw) && raw > 0) return raw;
|
|
12785
|
+
let cpus = 4;
|
|
12786
|
+
try {
|
|
12787
|
+
cpus = os$1.cpus().length;
|
|
12788
|
+
} catch {}
|
|
12789
|
+
return Math.max(1, Math.floor(cpus * .25));
|
|
12790
|
+
}
|
|
12791
|
+
/** Per-workspace index name: stable hash of the canonical workspace path. */
|
|
12792
|
+
function indexNameForWorkspace(canonicalWorkspace) {
|
|
12793
|
+
let h = 2166136261;
|
|
12794
|
+
for (let i = 0; i < canonicalWorkspace.length; i++) {
|
|
12795
|
+
h ^= canonicalWorkspace.charCodeAt(i);
|
|
12796
|
+
h = Math.imul(h, 16777619);
|
|
12797
|
+
}
|
|
12798
|
+
return `ws-${(h >>> 0).toString(16).padStart(8, "0")}`;
|
|
12799
|
+
}
|
|
12800
|
+
//#endregion
|
|
12801
|
+
//#region src/lib/colbert/units.ts
|
|
12802
|
+
/**
|
|
12803
|
+
* Semantic code-unit extraction (Phase 2b).
|
|
12804
|
+
*
|
|
12805
|
+
* The next-plaid service is a generic multi-vector document store — unlike
|
|
12806
|
+
* colgrep it does NOT parse code. This module owns the code-aware half:
|
|
12807
|
+
* tree-sitter parsing (reusing the warm grammar bundle + definition tables
|
|
12808
|
+
* from `~/lib/tree-sitter-grammars`), unit scoping (top-level + class-like
|
|
12809
|
+
* members — the same navigable scope as outlines), and structured-text
|
|
12810
|
+
* construction for embedding.
|
|
12811
|
+
*
|
|
12812
|
+
* Unit text mirrors colgrep's high-signal layers with the cheap subset:
|
|
12813
|
+
* name, signature (first line), leading doc comment, normalized file path,
|
|
12814
|
+
* and capped body. Call-graph / data-flow layers are deliberately omitted
|
|
12815
|
+
* in v1 (that analysis is computed by colgrep but never returned in our
|
|
12816
|
+
* responses today — see the Phase 2 plan — so nothing observable is lost).
|
|
12817
|
+
*
|
|
12818
|
+
* Pure file-level functions (no index state here): the service owns
|
|
12819
|
+
* storage/incremental logic; the freshness sidecar owns per-file hashes.
|
|
12820
|
+
* `extractUnits` never throws — per-file failures surface as `notice`.
|
|
12821
|
+
*/
|
|
12822
|
+
/** Max unit body chars embedded (~500 tokens). Longer bodies truncate. */
|
|
12823
|
+
const UNIT_MAX_BODY_CHARS = 2e3;
|
|
12824
|
+
/** Max signature chars (first line(s) of the unit). */
|
|
12825
|
+
const UNIT_MAX_SIGNATURE_CHARS = 300;
|
|
12826
|
+
/**
|
|
12827
|
+
* Normalize a file path for embedding: separators → spaces, snake_case /
|
|
12828
|
+
* CamelCase split (mirrors colgrep's path normalization AND the BM25F
|
|
12829
|
+
* `file_path` field, so lexical and semantic agree on path tokens).
|
|
12830
|
+
* `src/utils/HttpClient.ts` → `src utils Http Client ts`.
|
|
12831
|
+
*/
|
|
12832
|
+
function normalizePathForEmbedding(relPath) {
|
|
12833
|
+
return relPath.replace(/[/\\]/g, " ").replace(/\.[A-Za-z0-9]+$/, " $&").split(/[^A-Za-z0-9]+/).filter(Boolean).flatMap((piece) => {
|
|
12834
|
+
return piece.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+[0-9]*|[A-Z]+[0-9]*|[0-9]+/g) ?? [piece];
|
|
12835
|
+
}).join(" ");
|
|
12836
|
+
}
|
|
12837
|
+
/**
|
|
12838
|
+
* Leading doc comment for the unit starting at 1-indexed `startLine`:
|
|
12839
|
+
* consecutive comment-ish lines directly above (//, #, *, <!--, """, ''',
|
|
12840
|
+
* ///), blank-line-terminated. Language-agnostic and AST-free — runs on
|
|
12841
|
+
* raw source lines so it needs no per-language comment grammar.
|
|
12842
|
+
*/
|
|
12843
|
+
function leadingDocComment(sourceLines, startLine1) {
|
|
12844
|
+
const out = [];
|
|
12845
|
+
for (let i = startLine1 - 2; i >= 0; i--) {
|
|
12846
|
+
const line = sourceLines[i].trim();
|
|
12847
|
+
if (line.length === 0) break;
|
|
12848
|
+
if (line.startsWith("//") || line.startsWith("#") || line.startsWith("*") || line.startsWith("<!--") || line.startsWith("\"\"\"") || line.startsWith("'''")) {
|
|
12849
|
+
out.unshift(sourceLines[i].trim());
|
|
12850
|
+
if (out.length >= 10) break;
|
|
12851
|
+
} else break;
|
|
12852
|
+
}
|
|
12853
|
+
return out.length > 0 ? out.join("\n") : void 0;
|
|
12854
|
+
}
|
|
12855
|
+
/**
|
|
12856
|
+
* Structured text for one unit — what gets embedded. Field order mirrors
|
|
12857
|
+
* colgrep's (name → signature → description → path → code) so ranking
|
|
12858
|
+
* behavior stays close to the ColBERT sidecar it replaces.
|
|
12859
|
+
*/
|
|
12860
|
+
function buildUnitText(unit, relPath) {
|
|
12861
|
+
const parts = [`${labelForKind(unit.kind)}: ${unit.name}`];
|
|
12862
|
+
if (unit.signature && unit.signature !== unit.name) parts.push(`Signature: ${unit.signature}`);
|
|
12863
|
+
if (unit.docstring) parts.push(`Description: ${unit.docstring}`);
|
|
12864
|
+
parts.push(`File: ${normalizePathForEmbedding(relPath)}`);
|
|
12865
|
+
parts.push(`Code:\n${unit.code}`);
|
|
12866
|
+
return parts.join("\n");
|
|
12867
|
+
}
|
|
12868
|
+
function labelForKind(kind) {
|
|
12869
|
+
if (kind.includes("class")) return "Class";
|
|
12870
|
+
if (kind.includes("interface")) return "Interface";
|
|
12871
|
+
if (kind.includes("struct")) return "Struct";
|
|
12872
|
+
if (kind.includes("enum")) return "Enum";
|
|
12873
|
+
if (kind.includes("namespace") || kind.includes("module")) return "Namespace";
|
|
12874
|
+
if (kind.includes("method") || kind.includes("function")) return "Function";
|
|
12875
|
+
if (kind.includes("property")) return "Property";
|
|
12876
|
+
if (kind.includes("field")) return "Field";
|
|
12877
|
+
return "Symbol";
|
|
12878
|
+
}
|
|
12879
|
+
/**
|
|
12880
|
+
* Extract indexable units from one file. Read + parse + walk; frees the
|
|
12881
|
+
* tree before returning (units carry plain strings, never live nodes).
|
|
12882
|
+
* Never throws — failures surface as `notice` with empty `units`.
|
|
12883
|
+
*/
|
|
12884
|
+
async function extractUnits(absPath, relPath, signal) {
|
|
12885
|
+
if (signal?.aborted) return {
|
|
12886
|
+
units: [],
|
|
12887
|
+
language: null
|
|
12888
|
+
};
|
|
12889
|
+
const language = getLanguageKeyForPath(absPath);
|
|
12890
|
+
if (!language) return {
|
|
12891
|
+
units: [],
|
|
12892
|
+
language: null,
|
|
12893
|
+
notice: "no grammar for this file type"
|
|
12894
|
+
};
|
|
12895
|
+
let size;
|
|
12896
|
+
try {
|
|
12897
|
+
size = statSync(absPath).size;
|
|
12898
|
+
} catch {
|
|
12899
|
+
return {
|
|
12900
|
+
units: [],
|
|
12901
|
+
language,
|
|
12902
|
+
notice: "unreadable file"
|
|
12903
|
+
};
|
|
12904
|
+
}
|
|
12905
|
+
if (size > 1048576) return {
|
|
12906
|
+
units: [],
|
|
12907
|
+
language,
|
|
12908
|
+
notice: "file too large"
|
|
12909
|
+
};
|
|
12910
|
+
const grammars = await getGrammarBundle().ready;
|
|
12911
|
+
if (signal?.aborted) return {
|
|
12912
|
+
units: [],
|
|
12913
|
+
language
|
|
12914
|
+
};
|
|
12915
|
+
const lang = grammars.get(language);
|
|
12916
|
+
const defTypes = DEFINITION_NODE_TYPES[language];
|
|
12917
|
+
if (!lang || !defTypes) return {
|
|
12918
|
+
units: [],
|
|
12919
|
+
language,
|
|
12920
|
+
notice: "grammar unavailable"
|
|
12921
|
+
};
|
|
12922
|
+
let source;
|
|
12923
|
+
try {
|
|
12924
|
+
source = await readFile(absPath, "utf8");
|
|
12925
|
+
} catch {
|
|
12926
|
+
return {
|
|
12927
|
+
units: [],
|
|
12928
|
+
language,
|
|
12929
|
+
notice: "unreadable file"
|
|
12930
|
+
};
|
|
12931
|
+
}
|
|
12932
|
+
if (signal?.aborted) return {
|
|
12933
|
+
units: [],
|
|
12934
|
+
language
|
|
12935
|
+
};
|
|
12936
|
+
let parser = null;
|
|
12937
|
+
let tree = null;
|
|
12938
|
+
try {
|
|
12939
|
+
parser = new Parser();
|
|
12940
|
+
parser.setLanguage(lang);
|
|
12941
|
+
tree = parser.parse(source);
|
|
12942
|
+
if (!tree) return {
|
|
12943
|
+
units: [],
|
|
12944
|
+
language,
|
|
12945
|
+
notice: "parse failed"
|
|
12946
|
+
};
|
|
12947
|
+
const sourceLines = source.split("\n");
|
|
12948
|
+
const slashRel = relPath.replace(/\\/g, "/");
|
|
12949
|
+
const units = [];
|
|
12950
|
+
for (const u of collectUnitNodes(tree.rootNode, defTypes, signal)) {
|
|
12951
|
+
if (signal?.aborted) break;
|
|
12952
|
+
const line = u.node.startPosition.row + 1;
|
|
12953
|
+
const endLine = u.node.endPosition.row + 1;
|
|
12954
|
+
const firstLine = (sourceLines[line - 1] ?? "").trim().slice(0, UNIT_MAX_SIGNATURE_CHARS);
|
|
12955
|
+
const body = u.node.text.length > 2e3 ? u.node.text.slice(0, UNIT_MAX_BODY_CHARS) + "\n…[truncated]" : u.node.text;
|
|
12956
|
+
units.push({
|
|
12957
|
+
unit_id: `${slashRel}:${line}:${u.name}`,
|
|
12958
|
+
file: slashRel,
|
|
12959
|
+
name: u.name,
|
|
12960
|
+
kind: u.kind,
|
|
12961
|
+
line,
|
|
12962
|
+
end_line: endLine,
|
|
12963
|
+
signature: firstLine,
|
|
12964
|
+
code: body,
|
|
12965
|
+
...leadingDocComment(sourceLines, line) !== void 0 ? { docstring: leadingDocComment(sourceLines, line) } : {}
|
|
12966
|
+
});
|
|
12967
|
+
}
|
|
12968
|
+
units.sort((a, b) => a.line - b.line);
|
|
12969
|
+
return {
|
|
12970
|
+
units,
|
|
12971
|
+
language
|
|
12972
|
+
};
|
|
12973
|
+
} catch {
|
|
12974
|
+
return {
|
|
12975
|
+
units: [],
|
|
12976
|
+
language,
|
|
12977
|
+
notice: "parse failed"
|
|
12978
|
+
};
|
|
12979
|
+
} finally {
|
|
12980
|
+
if (tree) try {
|
|
12981
|
+
tree.delete();
|
|
12982
|
+
} catch {}
|
|
12983
|
+
if (parser) try {
|
|
12984
|
+
parser.delete();
|
|
12985
|
+
} catch {}
|
|
12986
|
+
}
|
|
12987
|
+
}
|
|
12988
|
+
//#endregion
|
|
12989
|
+
//#region src/lib/colbert/service-backend.ts
|
|
12990
|
+
/**
|
|
12991
|
+
* Service-backed semantic search orchestration (Phase 2e query path).
|
|
12992
|
+
*
|
|
12993
|
+
* Selects between the legacy colgrep CLI backend and the persistent
|
|
12994
|
+
* next-plaid-api server via `GH_ROUTER_SEMANTIC_BACKEND` (`colgrep` default,
|
|
12995
|
+
* `service` opt-in). The service path owns its own per-workspace state
|
|
12996
|
+
* (`svc-<hash>.json` sidecars — never touches the colgrep sidecar, so
|
|
12997
|
+
* flipping the flag back and forth loses nothing) and degrades to the
|
|
12998
|
+
* colgrep path on ANY service failure (missing binary, unhealthy server,
|
|
12999
|
+
* unknown index, busy queue).
|
|
13000
|
+
*
|
|
13001
|
+
* Indexing model: on-demand background populate. First query for a
|
|
13002
|
+
* workspace kicks `populateWorkspace` (enumerate → extractUnits →
|
|
13003
|
+
* batched updateDocuments) and returns `unavailable` meanwhile — the same
|
|
13004
|
+
* transparent-fallback contract as the CLI backend. Watcher-driven
|
|
13005
|
+
* proactive refresh lands separately (Phase 2d wiring).
|
|
13006
|
+
*
|
|
13007
|
+
* Binary resolution (no provisioner yet — CI artifacts pending):
|
|
13008
|
+
* 1. `GH_ROUTER_NEXTPLAID_BIN` explicit path
|
|
13009
|
+
* 2. Router-owned `<APP_DIR>/colbert/bin/next-plaid-api[.exe]`
|
|
13010
|
+
* 3. `next-plaid-api` on PATH
|
|
13011
|
+
* Model + ORT reuse the colbert provision (LateOn-Code-edge INT8 dir);
|
|
13012
|
+
* absent model ⇒ backend unavailable ⇒ colgrep fallback.
|
|
13013
|
+
*/
|
|
13014
|
+
/** Backend selection. Default `colgrep`; opt in with `=service`. */
|
|
13015
|
+
function semanticBackend() {
|
|
13016
|
+
return process.env.GH_ROUTER_SEMANTIC_BACKEND === "service" ? "service" : "colgrep";
|
|
13017
|
+
}
|
|
13018
|
+
/** True when the service backend is selected AND actionable. */
|
|
13019
|
+
function serviceBackendEnabled() {
|
|
13020
|
+
if (semanticBackend() !== "service") return false;
|
|
13021
|
+
if (resolveServiceBinary() === null && !nextPlaidServerPromoted("cpu") && !nextPlaidServerPromoted("cuda")) return false;
|
|
13022
|
+
if (!existsSync(canonicalColbertModelDir())) return false;
|
|
13023
|
+
return true;
|
|
13024
|
+
}
|
|
13025
|
+
/** Locate the server binary (env → router-owned → PATH). */
|
|
13026
|
+
function resolveServiceBinary() {
|
|
13027
|
+
const explicit = process.env.GH_ROUTER_NEXTPLAID_BIN;
|
|
13028
|
+
if (explicit && explicit.length > 0 && existsSync(explicit)) return explicit;
|
|
13029
|
+
for (const variant of ["cpu", "cuda"]) {
|
|
13030
|
+
const owned = nextPlaidServerBinaryPath(variant);
|
|
13031
|
+
if (existsSync(owned)) return owned;
|
|
13032
|
+
}
|
|
13033
|
+
return resolveExecutable("next-plaid-api");
|
|
13034
|
+
}
|
|
13035
|
+
/**
|
|
13036
|
+
* True when an NVIDIA GPU is visible (`nvidia-smi -L` exits 0). Never
|
|
13037
|
+
* throws; absent tool/driver ⇒ false ⇒ cpu variant. Bounded (~8s) so a
|
|
13038
|
+
* wedged driver can't stall startup.
|
|
13039
|
+
*/
|
|
13040
|
+
async function hasCudaGpu() {
|
|
13041
|
+
try {
|
|
13042
|
+
const smi = resolveExecutable("nvidia-smi");
|
|
13043
|
+
if (!smi) return false;
|
|
13044
|
+
const res = await runManagedExeCapture(smi, ["-L"], {
|
|
13045
|
+
timeoutMs: 8e3,
|
|
13046
|
+
maxStdoutBytes: 65536
|
|
13047
|
+
});
|
|
13048
|
+
return res.code === 0 && !res.timedOut;
|
|
13049
|
+
} catch {
|
|
13050
|
+
return false;
|
|
13051
|
+
}
|
|
13052
|
+
}
|
|
13053
|
+
/**
|
|
13054
|
+
* Pick the server compute variant. Explicit `GH_ROUTER_NEXTPLAID_VARIANT`
|
|
13055
|
+
* (`cpu`|`cuda`) wins (operator/test seam); otherwise cuda iff a GPU is
|
|
13056
|
+
* visible. Callers still fall back across variants when the preferred
|
|
13057
|
+
* binary can't be provisioned — selection is a preference, not a gate.
|
|
13058
|
+
*/
|
|
13059
|
+
async function selectServerVariant() {
|
|
13060
|
+
const override = process.env.GH_ROUTER_NEXTPLAID_VARIANT;
|
|
13061
|
+
if (override === "cpu" || override === "cuda") return override;
|
|
13062
|
+
return await hasCudaGpu() ? "cuda" : "cpu";
|
|
13063
|
+
}
|
|
13064
|
+
/**
|
|
13065
|
+
* Resolve the server binary + flags, provisioning on demand. Order:
|
|
13066
|
+
* explicit env (as-is; `--cuda` only via GH_ROUTER_NEXTPLAID_CUDA=1) →
|
|
13067
|
+
* preferred variant (provision, else on-disk) → cpu fallback (provision,
|
|
13068
|
+
* else on-disk) → PATH (cpu only). Null when nothing is usable.
|
|
13069
|
+
*/
|
|
13070
|
+
async function resolveServerBinaryWithVariant(variant) {
|
|
13071
|
+
const explicit = process.env.GH_ROUTER_NEXTPLAID_BIN;
|
|
13072
|
+
if (explicit && explicit.length > 0 && existsSync(explicit)) return {
|
|
13073
|
+
binary: explicit,
|
|
13074
|
+
cuda: process.env.GH_ROUTER_NEXTPLAID_CUDA === "1"
|
|
13075
|
+
};
|
|
13076
|
+
const ordered = variant === "cuda" ? ["cuda", "cpu"] : ["cpu"];
|
|
13077
|
+
for (const v of ordered) {
|
|
13078
|
+
const provisioned = await provisionNextPlaidServer(v);
|
|
13079
|
+
if (provisioned.path) return {
|
|
13080
|
+
binary: provisioned.path,
|
|
13081
|
+
cuda: v === "cuda"
|
|
13082
|
+
};
|
|
13083
|
+
const owned = nextPlaidServerBinaryPath(v);
|
|
13084
|
+
if (existsSync(owned)) return {
|
|
13085
|
+
binary: owned,
|
|
13086
|
+
cuda: v === "cuda"
|
|
13087
|
+
};
|
|
13088
|
+
}
|
|
13089
|
+
const onPath = resolveExecutable("next-plaid-api");
|
|
13090
|
+
if (onPath) return {
|
|
13091
|
+
binary: onPath,
|
|
13092
|
+
cuda: false
|
|
13093
|
+
};
|
|
13094
|
+
return null;
|
|
13095
|
+
}
|
|
13096
|
+
let _server = null;
|
|
13097
|
+
let _starting = null;
|
|
13098
|
+
/** Start (once) and health-check the server; null when unavailable. */
|
|
13099
|
+
async function ensureServer() {
|
|
13100
|
+
if (_server) {
|
|
13101
|
+
try {
|
|
13102
|
+
if ((await _server.client.health()).ok) return _server;
|
|
13103
|
+
} catch {}
|
|
13104
|
+
try {
|
|
13105
|
+
await _server.stop();
|
|
13106
|
+
} catch {}
|
|
13107
|
+
_server = null;
|
|
13108
|
+
}
|
|
13109
|
+
if (_starting) return _starting.catch(() => null);
|
|
13110
|
+
const resolved = await resolveServerBinaryWithVariant(await selectServerVariant());
|
|
13111
|
+
if (!resolved) return null;
|
|
13112
|
+
_starting = (async () => {
|
|
13113
|
+
const ortDir = path.dirname(colbertOrtDylibPath());
|
|
13114
|
+
const svc = await startManagedServer({
|
|
13115
|
+
binaryPath: resolved.binary,
|
|
13116
|
+
modelDir: canonicalColbertModelDir(),
|
|
13117
|
+
indexDir: PATHS.COLBERT_INDICES_DIR,
|
|
13118
|
+
parallel: serverParallelSessions(),
|
|
13119
|
+
cuda: resolved.cuda,
|
|
13120
|
+
env: {
|
|
13121
|
+
ORT_DYLIB_PATH: colbertOrtDylibPath(),
|
|
13122
|
+
PATH: `${ortDir}${path.delimiter}${process.env.PATH ?? ""}`
|
|
13123
|
+
},
|
|
13124
|
+
startupTimeoutMs: 12e4
|
|
13125
|
+
});
|
|
13126
|
+
_server = svc;
|
|
13127
|
+
return svc;
|
|
13128
|
+
})();
|
|
13129
|
+
try {
|
|
13130
|
+
return await _starting;
|
|
13131
|
+
} catch (err) {
|
|
13132
|
+
consola.debug(`service-backend: server start failed: ${err.message}`);
|
|
13133
|
+
return null;
|
|
13134
|
+
} finally {
|
|
13135
|
+
_starting = null;
|
|
13136
|
+
}
|
|
13137
|
+
}
|
|
13138
|
+
function serviceMetaPath(workspace) {
|
|
13139
|
+
return path.join(PATHS.COLBERT_META_DIR, `svc-${metaHash(workspace)}.json`);
|
|
13140
|
+
}
|
|
13141
|
+
function metaHash(workspace) {
|
|
13142
|
+
const canonical = canonicalWorkspace(workspace);
|
|
13143
|
+
let h = 2166136261;
|
|
13144
|
+
for (let i = 0; i < canonical.length; i++) {
|
|
13145
|
+
h ^= canonical.charCodeAt(i);
|
|
13146
|
+
h = Math.imul(h, 16777619);
|
|
13147
|
+
}
|
|
13148
|
+
return (h >>> 0).toString(16).padStart(8, "0");
|
|
13149
|
+
}
|
|
13150
|
+
async function readServiceMeta(workspace) {
|
|
13151
|
+
try {
|
|
13152
|
+
const raw = await fs$1.readFile(serviceMetaPath(workspace), "utf8");
|
|
13153
|
+
const parsed = JSON.parse(raw);
|
|
13154
|
+
if (parsed && typeof parsed === "object") return parsed;
|
|
13155
|
+
return null;
|
|
13156
|
+
} catch {
|
|
13157
|
+
return null;
|
|
13158
|
+
}
|
|
13159
|
+
}
|
|
13160
|
+
async function writeServiceMeta(meta) {
|
|
13161
|
+
await fs$1.mkdir(PATHS.COLBERT_META_DIR, { recursive: true });
|
|
13162
|
+
const dest = serviceMetaPath(meta.workspace);
|
|
13163
|
+
const tmp = `${dest}.${process.pid}.tmp`;
|
|
13164
|
+
try {
|
|
13165
|
+
await fs$1.writeFile(tmp, JSON.stringify(meta, null, 2));
|
|
13166
|
+
await fs$1.rename(tmp, dest);
|
|
13167
|
+
} catch {
|
|
13168
|
+
await fs$1.rm(tmp, { force: true }).catch(() => {});
|
|
13169
|
+
}
|
|
13170
|
+
}
|
|
13171
|
+
const _populateInFlight = /* @__PURE__ */ new Set();
|
|
13172
|
+
/** Fire-and-forget per-workspace populate (single-flight). Never throws. */
|
|
13173
|
+
function kickServiceIndex(workspace) {
|
|
13174
|
+
const key = path.resolve(workspace);
|
|
13175
|
+
if (_populateInFlight.has(key)) return;
|
|
13176
|
+
_populateInFlight.add(key);
|
|
13177
|
+
populateWorkspace(workspace).catch((err) => {
|
|
13178
|
+
consola.debug(`service-backend: populate failed for ${workspace}: ${err.message}`);
|
|
13179
|
+
}).finally(() => {
|
|
13180
|
+
_populateInFlight.delete(key);
|
|
13181
|
+
});
|
|
13182
|
+
}
|
|
13183
|
+
/** Max files enumerated per populate (whole-repo cap for v1). */
|
|
13184
|
+
const POPULATE_MAX_FILES = 2e4;
|
|
13185
|
+
/** Units per updateDocuments batch (server batches internally too). */
|
|
13186
|
+
const POPULATE_BATCH_UNITS = 100;
|
|
13187
|
+
/** Max concurrent file parses. */
|
|
13188
|
+
const POPULATE_PARSE_CONCURRENCY = 4;
|
|
13189
|
+
async function enumerateSourceFiles(rgPath, workspace, signal) {
|
|
13190
|
+
return new Promise((resolve) => {
|
|
13191
|
+
let child;
|
|
13192
|
+
try {
|
|
13193
|
+
child = spawn(rgPath, [
|
|
13194
|
+
"--files",
|
|
13195
|
+
"--no-follow",
|
|
13196
|
+
"-0"
|
|
13197
|
+
], {
|
|
13198
|
+
cwd: workspace,
|
|
13199
|
+
shell: false,
|
|
13200
|
+
stdio: [
|
|
13201
|
+
"ignore",
|
|
13202
|
+
"pipe",
|
|
13203
|
+
"ignore"
|
|
13204
|
+
]
|
|
13205
|
+
});
|
|
13206
|
+
} catch {
|
|
13207
|
+
resolve([]);
|
|
13208
|
+
return;
|
|
13209
|
+
}
|
|
13210
|
+
let buf = Buffer.alloc(0);
|
|
13211
|
+
const files = [];
|
|
13212
|
+
let done = false;
|
|
13213
|
+
const finish = (out) => {
|
|
13214
|
+
if (done) return;
|
|
13215
|
+
done = true;
|
|
13216
|
+
try {
|
|
13217
|
+
child.kill("SIGKILL");
|
|
13218
|
+
} catch {}
|
|
13219
|
+
resolve(out);
|
|
13220
|
+
};
|
|
13221
|
+
signal.addEventListener("abort", () => finish(files), { once: true });
|
|
13222
|
+
child.on("error", () => finish(files));
|
|
13223
|
+
child.stdout?.on("data", (chunk) => {
|
|
13224
|
+
buf = Buffer.concat([buf, chunk]);
|
|
13225
|
+
let idx;
|
|
13226
|
+
while ((idx = buf.indexOf(0)) >= 0 && files.length < POPULATE_MAX_FILES) {
|
|
13227
|
+
const rel = buf.subarray(0, idx).toString("utf8");
|
|
13228
|
+
buf = buf.subarray(idx + 1);
|
|
13229
|
+
if (rel.length > 0 && !path.isAbsolute(rel)) files.push(rel.replace(/\\/g, "/"));
|
|
13230
|
+
}
|
|
13231
|
+
if (files.length >= POPULATE_MAX_FILES) finish(files);
|
|
13232
|
+
});
|
|
13233
|
+
child.on("close", () => finish(files));
|
|
13234
|
+
});
|
|
13235
|
+
}
|
|
13236
|
+
function resolveRipgrepBin() {
|
|
13237
|
+
try {
|
|
13238
|
+
return resolveRipgrep().rgPath;
|
|
13239
|
+
} catch {
|
|
13240
|
+
return "rg";
|
|
13241
|
+
}
|
|
13242
|
+
}
|
|
13243
|
+
async function populateWorkspace(workspace) {
|
|
13244
|
+
const svc = await ensureServer();
|
|
13245
|
+
if (!svc) return;
|
|
13246
|
+
const canonical = canonicalWorkspace(workspace);
|
|
13247
|
+
const index = indexNameForWorkspace(canonical);
|
|
13248
|
+
await svc.client.ensureIndex(index, { nbits: 4 });
|
|
13249
|
+
const rgPath = resolveRipgrepBin();
|
|
13250
|
+
const ac = new AbortController();
|
|
13251
|
+
const timeout = setTimeout(() => ac.abort(), 18e5);
|
|
13252
|
+
timeout.unref?.();
|
|
13253
|
+
try {
|
|
13254
|
+
const parseable = (await enumerateSourceFiles(rgPath, canonical, ac.signal)).filter((f) => getLanguageKeyForPath(f) !== null);
|
|
13255
|
+
let units = [];
|
|
13256
|
+
let unitTotal = 0;
|
|
13257
|
+
const flush = async () => {
|
|
13258
|
+
if (units.length === 0) return;
|
|
13259
|
+
const batch = units;
|
|
13260
|
+
units = [];
|
|
13261
|
+
await svc.client.updateDocuments(index, batch.map((u) => u.text), batch.map((u) => u.metadata));
|
|
13262
|
+
unitTotal += batch.length;
|
|
13263
|
+
};
|
|
13264
|
+
let next = 0;
|
|
13265
|
+
const workers = Array.from({ length: Math.min(POPULATE_PARSE_CONCURRENCY, parseable.length) }, async () => {
|
|
13266
|
+
while (!ac.signal.aborted) {
|
|
13267
|
+
const i = next;
|
|
13268
|
+
next += 1;
|
|
13269
|
+
if (i >= parseable.length) break;
|
|
13270
|
+
const rel = parseable[i];
|
|
13271
|
+
try {
|
|
13272
|
+
const r = await extractUnits(path.join(canonical, rel), rel, ac.signal);
|
|
13273
|
+
for (const u of r.units) {
|
|
13274
|
+
units.push({
|
|
13275
|
+
text: buildUnitText(u, rel),
|
|
13276
|
+
metadata: {
|
|
13277
|
+
file: u.file,
|
|
13278
|
+
line: u.line,
|
|
13279
|
+
end_line: u.end_line,
|
|
13280
|
+
name: u.name,
|
|
13281
|
+
signature: u.signature,
|
|
13282
|
+
kind: u.kind,
|
|
13283
|
+
unit_id: u.unit_id
|
|
13284
|
+
}
|
|
13285
|
+
});
|
|
13286
|
+
if (units.length >= POPULATE_BATCH_UNITS) await flush();
|
|
13287
|
+
}
|
|
13288
|
+
} catch {}
|
|
13289
|
+
}
|
|
13290
|
+
});
|
|
13291
|
+
await Promise.all(workers);
|
|
13292
|
+
await flush();
|
|
13293
|
+
const g = await gitState(canonical).catch(() => ({ isRepo: false }));
|
|
13294
|
+
await writeServiceMeta({
|
|
13295
|
+
workspace: canonical,
|
|
13296
|
+
index,
|
|
13297
|
+
...g.isRepo ? {
|
|
13298
|
+
head: g.head,
|
|
13299
|
+
dirty: g.dirty ?? false
|
|
13300
|
+
} : {},
|
|
13301
|
+
indexedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
13302
|
+
docCount: unitTotal
|
|
13303
|
+
});
|
|
13304
|
+
consola.debug(`service-backend: indexed ${unitTotal} units in ${canonical}`);
|
|
13305
|
+
} finally {
|
|
13306
|
+
clearTimeout(timeout);
|
|
13307
|
+
}
|
|
13308
|
+
}
|
|
13309
|
+
/**
|
|
13310
|
+
* Search via the service backend. Returns `unavailable` (caller falls back
|
|
13311
|
+
* to colgrep/lexical) when the server, model, or index isn't ready; `failed`
|
|
13312
|
+
* only on unexpected errors. Served rows carry freshness labels per the
|
|
13313
|
+
* serve-while-stale policy.
|
|
13314
|
+
*/
|
|
13315
|
+
async function runServiceSearch(opts) {
|
|
13316
|
+
const { query, workspace } = opts;
|
|
13317
|
+
const limit = Math.max(1, Math.min(100, Math.floor(opts.limit ?? 15)));
|
|
13318
|
+
const canonical = canonicalWorkspace(workspace);
|
|
13319
|
+
const meta = await readServiceMeta(canonical);
|
|
13320
|
+
if (!meta) {
|
|
13321
|
+
kickServiceIndex(canonical);
|
|
13322
|
+
return { status: "unavailable" };
|
|
13323
|
+
}
|
|
13324
|
+
const svc = await ensureServer();
|
|
13325
|
+
if (!svc) return { status: "unavailable" };
|
|
13326
|
+
const index = indexNameForWorkspace(canonical);
|
|
13327
|
+
const g = await gitState(canonical).catch(() => ({ isRepo: false }));
|
|
13328
|
+
let freshness = "fresh";
|
|
13329
|
+
let staleFiles = 0;
|
|
13330
|
+
if (g.isRepo) {
|
|
13331
|
+
const headMoved = meta.head !== void 0 && g.head !== meta.head;
|
|
13332
|
+
const newlyDirty = g.dirty === true && meta.dirty !== true;
|
|
13333
|
+
if (headMoved || newlyDirty) {
|
|
13334
|
+
freshness = "stale";
|
|
13335
|
+
kickServiceIndex(canonical);
|
|
13336
|
+
try {
|
|
13337
|
+
const delta = await gitDeltaFiles(canonical, headMoved ? meta.head : void 0, headMoved ? g.head : void 0);
|
|
13338
|
+
if (delta.truncated || delta.files.length > serveStaleMaxFiles()) return { status: "unavailable" };
|
|
13339
|
+
staleFiles = delta.files.length;
|
|
13340
|
+
} catch {
|
|
13341
|
+
return { status: "unavailable" };
|
|
13342
|
+
}
|
|
13343
|
+
}
|
|
13344
|
+
}
|
|
13345
|
+
try {
|
|
13346
|
+
return {
|
|
13347
|
+
status: "ready",
|
|
13348
|
+
results: (await svc.client.search(index, query, {
|
|
13349
|
+
topK: limit,
|
|
13350
|
+
textQuery: query,
|
|
13351
|
+
alpha: .75
|
|
13352
|
+
})).map((h) => ({
|
|
13353
|
+
file: h.file,
|
|
13354
|
+
line: h.line,
|
|
13355
|
+
snippet: buildSnippet(h),
|
|
13356
|
+
...h.end_line !== void 0 ? { endLine: h.end_line } : {},
|
|
13357
|
+
...h.name !== void 0 ? { name: h.name } : {},
|
|
13358
|
+
score: h.score
|
|
13359
|
+
})),
|
|
13360
|
+
freshness,
|
|
13361
|
+
...freshness === "stale" ? { stale_files: staleFiles } : {}
|
|
13362
|
+
};
|
|
13363
|
+
} catch (err) {
|
|
13364
|
+
if (err instanceof ServiceBusyError) return { status: "unavailable" };
|
|
13365
|
+
consola.debug(`service-backend: search failed: ${err.message}`);
|
|
13366
|
+
return { status: "failed" };
|
|
13367
|
+
}
|
|
13368
|
+
}
|
|
13369
|
+
function buildSnippet(h) {
|
|
13370
|
+
const meta = h.metadata ?? {};
|
|
13371
|
+
const sig = typeof meta.signature === "string" ? meta.signature : "";
|
|
13372
|
+
return sig.length > 0 ? `${sig}\n${h.file}:${h.line}` : `${h.file}:${h.line}`;
|
|
13373
|
+
}
|
|
13374
|
+
//#endregion
|
|
12419
13375
|
//#region src/lib/colbert/index.ts
|
|
12420
13376
|
/**
|
|
12421
13377
|
* ColBERT semantic-search sidecar — public entry points.
|
|
@@ -12587,14 +13543,14 @@ function lexicalSearchCodeMode(mode) {
|
|
|
12587
13543
|
* repository size, so a hard figure would be wrong for most callers.
|
|
12588
13544
|
*/
|
|
12589
13545
|
const FALLBACK_GUIDANCE_MARKER = "retry mode:\"semantic\"";
|
|
12590
|
-
const FALLBACK_GUIDANCE = `${FALLBACK_GUIDANCE_MARKER} in
|
|
13546
|
+
const FALLBACK_GUIDANCE = `${FALLBACK_GUIDANCE_MARKER} in minutes or use exact symbols`;
|
|
12591
13547
|
function fallbackNoticeFor(status) {
|
|
12592
13548
|
const tail = FALLBACK_GUIDANCE;
|
|
12593
13549
|
switch (status) {
|
|
12594
|
-
case "building": return `semantic index
|
|
12595
|
-
case "stale": return `semantic index
|
|
12596
|
-
case "unavailable": return `no semantic index
|
|
12597
|
-
case "failed": return `semantic index
|
|
13550
|
+
case "building": return `semantic index building — returned lexical matches; ${tail}`;
|
|
13551
|
+
case "stale": return `semantic index stale (HEAD moved) — re-index started, returned lexical matches; ${tail}`;
|
|
13552
|
+
case "unavailable": return `no semantic index yet — build started, returned lexical matches; ${tail}`;
|
|
13553
|
+
case "failed": return `semantic index failed — this query started a background rebuild, returned lexical matches; ${tail}`;
|
|
12598
13554
|
default: return "returned lexical results";
|
|
12599
13555
|
}
|
|
12600
13556
|
}
|
|
@@ -12615,7 +13571,7 @@ function semanticFallbackNotice(sem) {
|
|
|
12615
13571
|
return `${sem.notice} — ${FALLBACK_GUIDANCE}`;
|
|
12616
13572
|
}
|
|
12617
13573
|
async function outlinesForSemanticResults(input, results, signal) {
|
|
12618
|
-
if (input.summary
|
|
13574
|
+
if (input.summary !== true) return void 0;
|
|
12619
13575
|
const seen = /* @__PURE__ */ new Set();
|
|
12620
13576
|
const files = [];
|
|
12621
13577
|
for (const result of results) {
|
|
@@ -12716,6 +13672,31 @@ async function runUnifiedCodeSearch(input, signal) {
|
|
|
12716
13672
|
notice: joinNotice(r.notice, "semantic search is off (launch with --search to enable); returned lexical results")
|
|
12717
13673
|
};
|
|
12718
13674
|
}
|
|
13675
|
+
if (serviceBackendEnabled()) try {
|
|
13676
|
+
const svc = await runServiceSearch({
|
|
13677
|
+
query: input.query,
|
|
13678
|
+
workspace: input.workspace,
|
|
13679
|
+
limit: input.limit,
|
|
13680
|
+
signal
|
|
13681
|
+
});
|
|
13682
|
+
if (svc.status === "ready") {
|
|
13683
|
+
const results = (svc.results ?? []).map((r) => ({
|
|
13684
|
+
file: r.file,
|
|
13685
|
+
line: r.line,
|
|
13686
|
+
snippet: r.snippet,
|
|
13687
|
+
...r.endLine !== void 0 ? { endLine: r.endLine } : {},
|
|
13688
|
+
...r.name !== void 0 ? { name: r.name } : {},
|
|
13689
|
+
...r.score !== void 0 ? { score: r.score } : {}
|
|
13690
|
+
}));
|
|
13691
|
+
return {
|
|
13692
|
+
source: "semantic",
|
|
13693
|
+
results,
|
|
13694
|
+
outlines: await outlinesForSemanticResults(input, results, signal),
|
|
13695
|
+
...svc.freshness ? { freshness: svc.freshness } : {},
|
|
13696
|
+
...svc.stale_files !== void 0 ? { stale_files: svc.stale_files } : {}
|
|
13697
|
+
};
|
|
13698
|
+
}
|
|
13699
|
+
} catch {}
|
|
12719
13700
|
let sem;
|
|
12720
13701
|
try {
|
|
12721
13702
|
sem = await runSemanticSearch({
|
|
@@ -14214,7 +15195,7 @@ function logAudit$1(record) {
|
|
|
14214
15195
|
try {
|
|
14215
15196
|
const fs = await import("node:fs/promises");
|
|
14216
15197
|
const path = await import("node:path");
|
|
14217
|
-
const { PATHS } = await import("./paths-
|
|
15198
|
+
const { PATHS } = await import("./paths-DVXBtLyo.js");
|
|
14218
15199
|
const dir = path.join(PATHS.APP_DIR, "browser-mcp");
|
|
14219
15200
|
await fs.mkdir(dir, { recursive: true });
|
|
14220
15201
|
const line = JSON.stringify({
|
|
@@ -27850,7 +28831,7 @@ function codeSearchTool(workspace) {
|
|
|
27850
28831
|
return {
|
|
27851
28832
|
name: "code_search",
|
|
27852
28833
|
label: "Code search (semantic-first)",
|
|
27853
|
-
description: "Semantic-first code search over the worker's workspace. Default (`mode:\"semantic\"`) ranks by MEANING via ColBERT and transparently falls back to lexical BM25F when the index isn't ready (the response `source` is \"semantic\" | \"lexical\" | \"lexical-fallback\"). Force lexical with mode `lexical` (exact symbols) / `exact` / `regex` / `ast`. Prefer over `grep` for \"where is X / which files reference Y\" discovery. Returns `{source, results:[{file,line,snippet}], ...}` in JSON.",
|
|
28834
|
+
description: "Semantic-first code search over the worker's workspace. Default (`mode:\"semantic\"`) ranks by MEANING via ColBERT and transparently falls back to lexical BM25F when the index isn't ready (the response `source` is \"semantic\" | \"lexical\" | \"lexical-fallback\"). Semantic hits carry `score` (0-1 relevance), `endLine`, `name`; stale semantic carries `freshness:\"stale\"` + `stale_files:N`. Force lexical with mode `lexical` (exact symbols) / `exact` / `regex` / `ast`. Prefer over `grep` for \"where is X / which files reference Y\" discovery. Returns `{source, results:[{file,line,snippet,score?,endLine?,name?}], ...}` in JSON.",
|
|
27854
28835
|
parameters: CODE_SEARCH_PARAMS,
|
|
27855
28836
|
async execute(_toolCallId, params, signal) {
|
|
27856
28837
|
const r = await runUnifiedCodeSearch({
|
|
@@ -27872,7 +28853,10 @@ function codeSearchTool(workspace) {
|
|
|
27872
28853
|
results: r.results.map((h) => ({
|
|
27873
28854
|
file: h.file,
|
|
27874
28855
|
line: h.line,
|
|
27875
|
-
snippet: h.snippet
|
|
28856
|
+
snippet: h.snippet,
|
|
28857
|
+
...h.score !== void 0 ? { score: h.score } : {},
|
|
28858
|
+
...h.endLine !== void 0 ? { endLine: h.endLine } : {},
|
|
28859
|
+
...h.name !== void 0 ? { name: h.name } : {}
|
|
27876
28860
|
})),
|
|
27877
28861
|
truncated: r.truncated ?? false,
|
|
27878
28862
|
notice: r.notice ?? void 0,
|
|
@@ -31795,7 +32779,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
|
|
|
31795
32779
|
{
|
|
31796
32780
|
toolNameHttp: "code",
|
|
31797
32781
|
group: "search",
|
|
31798
|
-
description: "Fast structured code search over a local workspace. Default (`mode:\"semantic\"`, or omit `mode`) ranks by MEANING via ColBERT over a per-workspace index — best for intent/concept queries where the literal keywords may not appear (\"where do we rate-limit\", \"auth token refresh\"). When that index is building/stale/absent it TRANSPARENTLY returns lexical (BM25F) results and labels the response `source` (\"lexical-fallback\") so a degrade is never silent. On a `lexical-fallback` the `notice` says how to proceed: retry `mode:\"semantic\"` shortly (the index self-heals in the background) or re-query with specific symbols — the lexical engine matches keywords/symbols, not natural-language phrases. Other modes force the lexical engine: `lexical` (BM25F ranked, best for exact symbols), `exact` (fixed-string), `regex` (PCRE2), `ast` (ast-grep structural via `ast_pattern`+`ast_lang`). Lexical ranking refines a `symbol-context` field with tree-sitter AST analysis so definitions outrank incidental matches. Launch multiple code searches in parallel to triangulate — e.g. definition + callers + tests in one round-trip. Prefer this over Grep/Bash+grep for ranked discovery (\"where is X defined\", \"which files reference Y\", \"find code that does Z\"). Use Grep for exact-pattern enumeration when you need every hit unranked, and Glob for file-name patterns (no content match). `workspace` is any absolute path to a DIRECTORY the proxy process can read — typically the project root or a sub-tree you're working in. It must be a directory, not a file; to narrow to one file or a set of them, keep `workspace` at the root and pass `file_glob`. Each response also carries a tree-sitter structural outline of the matched files (`summary` on by default; set it false to omit).",
|
|
32782
|
+
description: "Fast structured code search over a local workspace. Default (`mode:\"semantic\"`, or omit `mode`) ranks by MEANING via ColBERT over a per-workspace index — best for intent/concept queries where the literal keywords may not appear (\"where do we rate-limit\", \"auth token refresh\"). When that index is building/stale/absent it TRANSPARENTLY returns lexical (BM25F) results and labels the response `source` (\"semantic\" | \"lexical\" | \"lexical-fallback\") so a degrade is never silent. Semantic hits carry `score` (0-1 relevance), `endLine`, `name`; stale semantic carries `freshness:\"stale\" + `stale_files:N` (results predate recent edits). On a `lexical-fallback` the `notice` says how to proceed: retry `mode:\"semantic\"` shortly (the index self-heals in the background) or re-query with specific symbols — the lexical engine matches keywords/symbols, not natural-language phrases. Other modes force the lexical engine: `lexical` (BM25F ranked, best for exact symbols), `exact` (fixed-string), `regex` (PCRE2), `ast` (ast-grep structural via `ast_pattern`+`ast_lang`). Lexical ranking refines a `symbol-context` field with tree-sitter AST analysis so definitions outrank incidental matches. Launch multiple code searches in parallel to triangulate — e.g. definition + callers + tests in one round-trip. Prefer this over Grep/Bash+grep for ranked discovery (\"where is X defined\", \"which files reference Y\", \"find code that does Z\"). Use Grep for exact-pattern enumeration when you need every hit unranked, and Glob for file-name patterns (no content match). `workspace` is any absolute path to a DIRECTORY the proxy process can read — typically the project root or a sub-tree you're working in. It must be a directory, not a file; to narrow to one file or a set of them, keep `workspace` at the root and pass `file_glob`. Each response also carries a tree-sitter structural outline of the matched files (`summary` on by default; set it false to omit).",
|
|
31799
32783
|
inputSchema: {
|
|
31800
32784
|
type: "object",
|
|
31801
32785
|
required: ["query", "workspace"],
|
|
@@ -31839,7 +32823,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
|
|
|
31839
32823
|
},
|
|
31840
32824
|
summary: {
|
|
31841
32825
|
type: "boolean",
|
|
31842
|
-
description: "Structural summary,
|
|
32826
|
+
description: "Structural summary, OPT-IN (default false): pass true and the response includes `outlines` — a tree-sitter outline (top-level symbols + line numbers) of the distinct files in the result set (first 10, in result order), a compact map of where the matches live that augments each hit's `snippet`. Omit it when you only need the matching lines."
|
|
31843
32827
|
},
|
|
31844
32828
|
complete: {
|
|
31845
32829
|
type: "boolean",
|
|
@@ -32921,4 +33905,4 @@ function enumerateInjectedMcpToolNames(groupKeys, opts = {}) {
|
|
|
32921
33905
|
//#endregion
|
|
32922
33906
|
export { EFFORT_ORDER as $, MAX_RESPONSE_BODY_BYTES as $t, TOOLBELT_TOOLS$1 as A, withOneMSuffix as An, implementerFastModel as At, resolveAdvisorEffort as B, CHEAPEST_PROFILE_NATIVE_EFFORTS as Bn, countTokens as Bt, runWorkerAgent as C, pickClaudeDefault as Cn, fastOracleModel as Ct, toolbeltEnabled as D, classifyMessagesRoute as Dn, fleetToolsEnabled as Dt, buildToolbeltAwareness as E, upstreamMaxConnections as En, fastScoutModel as Et, ADVISOR_TOOL_INSTRUCTIONS as F, BALANCED_PROFILE_NATIVE_MODELS as Fn, scoutModel as Ft, repairKnownThinkingHistory as G, CHEAP_PROFILE_NATIVE_AGENT_NAMES as Gn, findLaunchBySecret as Gt, resolveCheapestAdvisorModel as H, CHEAPEST_PROFILE_SUBAGENT_CONTEXT_TOKENS as Hn, getTextTokenCount as Ht, FAST_ADVISOR_TOOL_INSTRUCTIONS as I, BALANCED_PROFILE_SUBAGENT_CONTEXT_TOKENS as In, scribeModel as It, buildOpenAIErrorEvent as J, CHEAP_PROFILE_SUBAGENT_CONTEXT_TOKENS as Jn, assembleResponsesPayload as Jt, repairRejectedThinkingHistory as K, CHEAP_PROFILE_NATIVE_EFFORTS as Kn, registerLaunch as Kt, buildAdvisorStream as L, CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL as Ln, standInToolEnabled as Lt, satisfiesMinVersion as M, BALANCED_PROFILE_MODELS as Mn, resolveGeminiReviewModel as Mt, searchWeb as N, BALANCED_PROFILE_NATIVE_AGENT_NAMES as Nn, reviewerFastModel as Nt, toolbeltSkipSet as O, catalogAdvertises1M as On, geminiAvailable as Ot, ADVISOR_INTERNAL_TOOL_NAME as P, BALANCED_PROFILE_NATIVE_EFFORTS as Pn, reviewerModel as Pt, relayAnthropicStream as Q, createChatCompletions as Qt, injectAdvisorTool as R, CHEAPEST_PROFILE_MODELS as Rn, workerToolsEnabled as Rt, resolveWorkerRunOpts as S, isBudgetClaudeLead as Sn, fastGeneralPurposeModel as St, availableToolCommands as T, upstreamAllowH2 as Tn, fastReviewerModel as Tt, formatThinkingRepairDecline as U, CHEAP_PROFILE_ADVISOR_CLIENT_MODEL as Un, getTokenCount as Ut, resolveAdvisorModel as V, CHEAPEST_PROFILE_NATIVE_MODELS as Vn, createMessages as Vt, rememberThinkingHistoryRepair as W, CHEAP_PROFILE_MODELS as Wn, getTokenizerFromModel as Wt, logStreamError as X, resolveMcpToolTimeoutMs as Xt, isControllerClosedError as Y, warnOnTokenPriceDrift as Yt, readIteratorWithTimeout as Z, createResponses as Zt, REVIEW_DEFAULT_MODEL as _, DEFAULT_CODEX_MODEL_FALLBACKS as _n, cheapestAdvisorModel as _t, buildAgentPrompt as a, colbertDegradedWarning as an, agentToolsEnabled as at, resolveDefaultModel as b, UPSTREAM_INACTIVITY_TIMEOUT_MS as bn, fastAdvisorModel as bt, enumerateInjectedMcpToolNames as c, CONDENSED_OPERATING_SEQUENCE as cn, balancedOracleModel as ct, BROWSE_DEFAULT_MODEL as d, collapsePathKeys as dn, browseAgentEnabled as dt, readResponseBodyCapped as en, UNKNOWN_EFFORT_ANCHOR as et, DEFAULT_MODEL_CHAIN as f, toolbeltPathOverride as fn, browserCompoundToolsEnabled as ft, PLAN_DEFAULT_MODEL as g, DEFAULT_CODEX_MODEL as gn, cheapReviewerModel as gt, IMPLEMENT_DEFAULT_MODEL as h, DEFAULT_CLAUDE_MODEL_FALLBACKS as hn, cheapOracleModel as ht, assertMcpToolSurfaceConsistent as i, hasSupportedBrowserInstalled as in, handleMcpPost as it, assetFor as j, withOneMSuffixForLead as jn, nativeSubagentModel as jt, vscodeRipgrepPath as k, oneMContextDisabled as kn, generalPurposeFastModel as kt, maxPersonasFor as l, DEFINITION_OF_GREATNESS as ln, balancedReviewerModel as lt, EXPLORE_DEFAULT_THINKING as m, BUDGET_SMALL_FAST_SLUG as mn, cheapAdvisorModel as mt, MCP_GROUPS as n, normalizeOpenAIUsage as nn, clampEffort as nt, buildPeerAwarenessSnippet as o, provisionAndIndexColbert as on, artifactToolsEnabled as ot, EXPLORE_DEFAULT_MODEL as p, BUDGET_SMALL_FAST_CATALOG_ID as pn, browserToolsEnabled as pt, buildAnthropicErrorEvent as q, CHEAP_PROFILE_NATIVE_MODELS as qn, unregisterLaunch as qt, agentNamesForToolAllowlist as r, provisionBrowserAssets as rn, handleMcpDelete as rt, buildPeerAwarenessSummary as s, semanticSearchOptedIn as sn, balancedAdvisorModel as st, GROUP_META as t, parseJsonOrDiagnose as tn, bucketEffort as tt, personasFor as u, shouldUseInsecureTls as un, brainstormModel as ut, TEST_DEFAULT_MODEL as v, DEFAULT_PORT as vn, cheapestOracleModel as vt, buildEnv as w, resolveLeadSlugArg as wn, fastPlanModel as wt, resolveModeDefaults as x, generateRandomPort as xn, fastAstraModel as xt, appendPlanReminder as y, UPSTREAM_FETCH_TIMEOUT_MS as yn, cheapestReviewerModel as yt, isAdvisorRequested as z, CHEAPEST_PROFILE_NATIVE_AGENT_NAMES as zn, shimDefaultsToXhigh as zt };
|
|
32923
33907
|
|
|
32924
|
-
//# sourceMappingURL=peer-mcp-personas-
|
|
33908
|
+
//# sourceMappingURL=peer-mcp-personas-Dg2LJ0GF.js.map
|