@jayyuen66/dsh-zvec-grep 0.1.4 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +26 -20
- package/README.zh-CN.md +28 -20
- package/client.js +184 -137
- package/host.js +1260 -1327
- package/package.json +48 -43
package/host.js
CHANGED
|
@@ -2,13 +2,11 @@
|
|
|
2
2
|
import Schema from "@deepseek-ai/schemastery";
|
|
3
3
|
import { accessSync, constants, existsSync, readFileSync, statSync } from "node:fs";
|
|
4
4
|
import { tmpdir } from "node:os";
|
|
5
|
-
import { randomUUID } from "node:crypto";
|
|
6
|
-
import { guardBody, queryParam, sendJson } from "@jayyuen66/dsh-plugin-shared/lib/http";
|
|
7
|
-
import { guardTrust, isNonLoopbackBindHost } from "@jayyuen66/dsh-plugin-shared/lib/trust";
|
|
8
5
|
import { isRecord } from "@jayyuen66/dsh-plugin-shared/lib/record";
|
|
9
6
|
import { errorText } from "@jayyuen66/dsh-plugin-shared/lib/errors";
|
|
10
7
|
import { LOCALE_SETTINGS_NAMESPACE, messagesFor, resolveLocalePreference } from "@jayyuen66/dsh-plugin-shared/lib/locale";
|
|
11
8
|
import { truncateEnd, truncateStart } from "@jayyuen66/dsh-plugin-shared/lib/text";
|
|
9
|
+
import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
|
|
12
10
|
import { jobOutcomeOf } from "@jayyuen66/dsh-plugin-shared/lib/job-outcome";
|
|
13
11
|
//#region lib/embedding-catalog.ts
|
|
14
12
|
/** 默认模型:本地最强(1024 维 / 8192 上下文 / 中英通用),约 640MB 一次性下载。 */
|
|
@@ -203,7 +201,6 @@ const MESSAGES = {
|
|
|
203
201
|
endpointRootGone: "root 目录已不存在:{root}",
|
|
204
202
|
endpointStartFailed: "启动重建失败:{reason}",
|
|
205
203
|
endpointJobsUnavailable: "后台重建不可用:宿主未提供 ctx.jobs(@deepseek-ai/dsh-jobs-local 未装载),本插件不再自带任务注册表",
|
|
206
|
-
endpointRegistryReplaced: "后台作业服务已被替换(新注册表重新从同一个 id 开始签发作业),本次重建已放弃并终止:请重载 zvec-grep 插件后再发起,否则旧面板会跟着另一棵树的作业走",
|
|
207
204
|
endpointJobsAtCapacity: "后台作业已满(宿主上限 {limit} 条,进行中与正在收尾的都计数),本次重建未启动:请先在模型侧用 job_kill 收掉不再需要的作业,再重新发起重建",
|
|
208
205
|
unknownJobId: "unknown jobId(这条重建记录已移出历史窗口:本插件只保留最近 {maxJobs} 条已结束的重建,超限时最老的已结束记录先被移除;进行中的重建不会被顶掉,但并发满员时新的启动请求会被直接拒绝。请重新发起重建)",
|
|
209
206
|
jobOutputView: "\n[zvec-grep](仅显示尾部 {shown} 字符,共 {total} 字符)",
|
|
@@ -225,6 +222,7 @@ const MESSAGES = {
|
|
|
225
222
|
rootMustBeAbsolute: "root 必须是绝对路径(以 / 开头):{path}",
|
|
226
223
|
rootIsFsRoot: "root 不能是文件系统根目录 /",
|
|
227
224
|
rootRequiredWithFallback: "root 必填,且为工作区绝对路径(可省略:缺省为当前会话工作区)",
|
|
225
|
+
limitInvalid: "limit 必须是非负整数(省略则用默认值)",
|
|
228
226
|
mustBeStringArray: "{name} 必须是字符串数组",
|
|
229
227
|
tooManyItems: "{name} 最多 {maxItems} 项(实际 {actual})",
|
|
230
228
|
nonStringItem: "{name} 含非字符串项({received})",
|
|
@@ -356,7 +354,6 @@ const MESSAGES = {
|
|
|
356
354
|
endpointRootGone: "root directory no longer exists: {root}",
|
|
357
355
|
endpointStartFailed: "failed to start the rebuild: {reason}",
|
|
358
356
|
endpointJobsUnavailable: "background rebuild unavailable: the host provides no ctx.jobs (dsh-jobs-local is not loaded); this plugin no longer ships its own job registry",
|
|
359
|
-
endpointRegistryReplaced: "the background job service was replaced (a fresh registry restarts id numbering), so this rebuild was abandoned and its process terminated: reload the zvec-grep plugin before retrying, otherwise a stale panel would follow a different workspace's job",
|
|
360
357
|
endpointJobsAtCapacity: "background jobs are at the host's limit ({limit} slots; running and stopping both count), so this rebuild never started: stop what you no longer need with job_kill, then start the rebuild again",
|
|
361
358
|
unknownJobId: "unknown jobId (this rebuild record left the history window: the plugin keeps the most recent {maxJobs} finished rebuilds and drops the oldest settled one first; running rebuilds are never displaced, but a start request is refused outright once the concurrent limit is reached. Start the rebuild again)",
|
|
362
359
|
jobOutputView: "\n[zvec-grep] (showing only the last {shown} of {total} characters)",
|
|
@@ -378,6 +375,7 @@ const MESSAGES = {
|
|
|
378
375
|
rootMustBeAbsolute: "root must be an absolute path (starting with /): {path}",
|
|
379
376
|
rootIsFsRoot: "root must not be the filesystem root /",
|
|
380
377
|
rootRequiredWithFallback: "root is required and must be an absolute workspace path (it may be omitted: defaults to the current session workspace)",
|
|
378
|
+
limitInvalid: "limit must be a non-negative integer (omit it to use the default)",
|
|
381
379
|
mustBeStringArray: "{name} must be an array of strings",
|
|
382
380
|
tooManyItems: "{name} allows at most {maxItems} items (actual {actual})",
|
|
383
381
|
nonStringItem: "{name} contains a non-string item ({received})",
|
|
@@ -682,11 +680,11 @@ function resolveRoot(value, fallback, messages) {
|
|
|
682
680
|
if (typeof fallback === "string" && fallback.trim().length > 0) return assertAbsoluteRoot(fallback.trim(), messages);
|
|
683
681
|
throw new Error(messages.rootRequiredWithFallback);
|
|
684
682
|
}
|
|
685
|
-
/** limit
|
|
686
|
-
function clampLimit(value, fallback = 10) {
|
|
683
|
+
/** limit 钳制:省略(undefined/null)回默认;给了但不是非负整数即抛;越界钳到 [LIMIT_MIN, LIMIT_MAX]。 */
|
|
684
|
+
function clampLimit(value, messages, fallback = 10) {
|
|
687
685
|
if (value === void 0 || value === null) return fallback;
|
|
688
686
|
const num = typeof value === "number" ? value : Number(value);
|
|
689
|
-
if (!Number.isSafeInteger(num))
|
|
687
|
+
if (!Number.isSafeInteger(num) || num < 0) throw new Error(messages.limitInvalid);
|
|
690
688
|
return Math.min(LIMIT_MAX, Math.max(LIMIT_MIN, num));
|
|
691
689
|
}
|
|
692
690
|
/** 检索类数组(queries/fts/vector)取值:条数与单条长度都放宽到 query 档。 */
|
|
@@ -773,7 +771,7 @@ function buildIndexedCommand(args, root, messages, mode, backgroundSupport) {
|
|
|
773
771
|
const refresh = refreshOf(args.refresh, messages);
|
|
774
772
|
if (refresh === "background" && backgroundSupport === "daemon-down") throw new Error(fill(messages.refreshBackgroundNeedsServer, { root }));
|
|
775
773
|
if (refresh === "background" && backgroundSupport === "mode-direct") throw new Error(fill(messages.refreshBackgroundPinnedDirect, { root }));
|
|
776
|
-
parts.push("--limit", String(clampLimit(args.limit)), "--preview", previewOf(args.preview, messages), "--refresh", refresh);
|
|
774
|
+
parts.push("--limit", String(clampLimit(args.limit, messages)), "--preview", previewOf(args.preview, messages), "--refresh", refresh);
|
|
777
775
|
pushSearchGlobs(parts, args, messages);
|
|
778
776
|
if (boolOf(args.preferSymbol, "preferSymbol", messages)) parts.push("--prefer-symbol");
|
|
779
777
|
if (boolOf(args.trace, "trace", messages)) parts.push("--trace");
|
|
@@ -818,7 +816,7 @@ function buildExhaustiveCommand(args, root, messages, mode) {
|
|
|
818
816
|
if (pattern.length === 0) throw new Error(messages.exhaustiveNeedsPattern);
|
|
819
817
|
if (pattern.startsWith("-")) parts.push("-e", shq(pattern));
|
|
820
818
|
else parts.push(shq(pattern));
|
|
821
|
-
parts.push("--limit", String(clampLimit(args.limit)));
|
|
819
|
+
parts.push("--limit", String(clampLimit(args.limit, messages)));
|
|
822
820
|
pushPathFilters(parts, args, messages);
|
|
823
821
|
pushTimeFilters(parts, args, messages);
|
|
824
822
|
parts.push(deviceFlag(args.device, messages), modeFlag(mode));
|
|
@@ -877,10 +875,12 @@ function pushIndexBoolFlags(parts, flags) {
|
|
|
877
875
|
* type-not → 密钥排除 → ignore-file)。
|
|
878
876
|
*
|
|
879
877
|
* 密钥排除走 --iglob 而非 --glob,两个原因都是实测得来的:
|
|
880
|
-
* -
|
|
881
|
-
*
|
|
878
|
+
* - 扩展名大小写:`.pem` / `.p12` / `.pfx` / `.keystore` 都**确实会被索引**(真 zg 0.2.2 实测:
|
|
879
|
+
* 一份只有 `secret.pem` / `secret.P12` / `a.ts` 的工作区,`zg index` 回执就是
|
|
880
|
+
* `3 scanned, 3 added`,随后 `zg query MARKERPEMLINE` 交回 `#1 matchedBy=fts+vector secret.pem:1-2`),
|
|
881
|
+
* 且都存在混合大小写变体(`secret.P12` / `secret.PfX` / `secret.KEYSTORE` 同样入索引)。
|
|
882
882
|
* --glob 的 `!*.p12` 匹配不到 `secret.P12`,--iglob 走大小写不敏感匹配才能全部排除。
|
|
883
|
-
*
|
|
883
|
+
* 判据钉在 test/e2e/zg-cli.test.ts 的「密钥排除真的在挡东西」那一组。
|
|
884
884
|
* - 规则次序:引擎把全部 --glob 规则排在全部 --iglob 规则之前有序求值。密钥规则若
|
|
885
885
|
* 用 --glob,用户一条宽泛的正向 --iglob(如 `**`)会在其后求值并把无扩展名的
|
|
886
886
|
* `id_rsa*` 救回索引(实测「被索引」);用 --iglob 且排在本函数最后(用户 iglob
|
|
@@ -1711,91 +1711,45 @@ function tooOldZgVersion(stdout) {
|
|
|
1711
1711
|
return parsed === void 0 || versionAtLeast(parsed, MINIMUM) ? void 0 : parsed;
|
|
1712
1712
|
}
|
|
1713
1713
|
//#endregion
|
|
1714
|
-
//#region
|
|
1715
|
-
const SEARCH_TIMEOUT_MS = 3e5;
|
|
1716
|
-
const STATUS_TIMEOUT_MS = 6e4;
|
|
1717
|
-
const INDEX_TIMEOUT_MS = 6e5;
|
|
1718
|
-
const STDOUT_MAX_BYTES = 4e5;
|
|
1719
|
-
/** 检索等待同根重建落定的上限(ms)。部署值:大型工作区的重建可能跑很久,
|
|
1720
|
-
* 但也不该让一次检索无限期挂着。 */
|
|
1721
|
-
const REBUILD_WAIT_MS = 12e4;
|
|
1722
|
-
const REBUILD_PATH = "/_dsh/zvec-grep/rebuild";
|
|
1723
|
-
const REBUILD_STATUS_PATH = "/_dsh/zvec-grep/rebuild-status";
|
|
1724
|
-
/** 卡片取「可选工作区 + CSRF token」的引导端点(GET,只回本插件自己的数据)。 */
|
|
1725
|
-
const REBUILD_ROOTS_PATH = "/_dsh/zvec-grep/rebuild-roots";
|
|
1726
|
-
/** 动作端点的 CSRF 头名(值是每次 apply 重新生成的随机 token)。 */
|
|
1727
|
-
const REBUILD_CSRF_HEADER = "x-zvec-grep-csrf";
|
|
1728
|
-
/** rebuild 端点没有业务请求体,但必须把它读完(keep-alive 残留字节的协议正确性)。 */
|
|
1729
|
-
const REBUILD_BODY_MAX_BYTES = 4096;
|
|
1730
|
-
/** 工作区白名单容量:超过按最近使用淘汰最冷的一条(常驻进程内存有界)。 */
|
|
1731
|
-
const MAX_LEDGER_ROOTS = 64;
|
|
1732
|
-
/**
|
|
1733
|
-
* 白名单条目的有效期:多久没被提到就当它不再活跃。一天足够覆盖「今天开过的会话」,
|
|
1734
|
-
* 又不会让一个月前随手开过的一个目录一直占着名额。
|
|
1735
|
-
*/
|
|
1736
|
-
const LEDGER_TTL_MS = 864e5;
|
|
1737
|
-
/** 成功执行里回显 stderr 的尾部长度(降级提示常就在这一行)。 */
|
|
1738
|
-
const STDERR_NOTE_CHARS = 400;
|
|
1739
|
-
/** 具名方法在位(typeof 函数)——只看 `typeof x === "object"` 会放过 null、
|
|
1740
|
-
* 也会放过「是个对象但没注册方法」的错注入。 */
|
|
1741
|
-
function hasMethod(value, name, keys) {
|
|
1742
|
-
const member = value[name];
|
|
1743
|
-
return isRecord(member) && keys.every((key) => typeof member[key] === "function");
|
|
1744
|
-
}
|
|
1714
|
+
//#region lib/index-preflight.ts
|
|
1745
1715
|
/**
|
|
1746
|
-
*
|
|
1747
|
-
* 且 `get` 可调用。守卫失败即 apply 抛错(fail-fast),比运行到某次工具调用
|
|
1748
|
-
* 才 `undefined is not a function` 更早、更可诊断。
|
|
1716
|
+
* `ignoreFiles` 的可用性预检:模型给的第 N 条忽略文件必须是**当前进程读得了的普通文件**。
|
|
1749
1717
|
*
|
|
1750
|
-
*
|
|
1751
|
-
*
|
|
1752
|
-
*
|
|
1753
|
-
*
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
*
|
|
1766
|
-
*
|
|
1767
|
-
* textBlock 的用例就直喂 undefined)。宽化只能落在这里——调用点里 `JSON.stringify(...) ?? x`
|
|
1768
|
-
* 会被 TS 的收窄按声明面判成冗余守卫,而删掉那道具象兜底会把 `{ text: undefined }` 交给官方。
|
|
1718
|
+
* 判据「读得了 + 是文件」合成**一次** try(accessSync 在前):`statSync().isFile()` 对 mode 000
|
|
1719
|
+
* 的文件照样返回 true(stat 只要父目录可搜索、不要文件本身可读),故先 `accessSync(R_OK)` 补上
|
|
1720
|
+
* "当前进程真能 open 来读"这半段——它与 zg 的读权限同 uid 同源(root 下两者都放行、非 root 下
|
|
1721
|
+
* 两者都拒);再用 `isFile()` 挡掉目录。**不拆成「不存在」与「读不了」两条独立分支**:可读性那
|
|
1722
|
+
* 一档在 windows(chmod 只翻只读位,属主仍读得了)与 root(绕过 DAC)下根本造不出来,拆成独立
|
|
1723
|
+
* 分支会让 CI 的 windows 那格在 100% 覆盖率门禁下无从而钉(本仓不用 coverage-ignore 逃生口)。
|
|
1724
|
+
* 合成一句「不是存在且可读的文件」文案,三种成因都准确覆盖,且 catch 由「不存在」这一档跨平台钉住。
|
|
1725
|
+
*
|
|
1726
|
+
* drop 那一臂整段跳过:`--drop` 的命令只有 `zg index <root> --drop --yes`,ignoreFiles 被
|
|
1727
|
+
* buildIndexCommand 静默丢掉、根本不进 zg(见 lib/cli.ts 的 drop 分支),预检它没有意义,还会
|
|
1728
|
+
* 拿"给一个真实存在的忽略文件"这句误导文案把一次合法的删索引拦下。判 drop 用与构造器**同一个**
|
|
1729
|
+
* `boolOf`,两处口径不会漂。
|
|
1730
|
+
* @param args 索引入参(`ignoreFiles` 单值或数组;`drop` 为真时整段跳过)
|
|
1731
|
+
* @param root 已归一的工作区根(相对路径按它解析)
|
|
1732
|
+
* @param messages 文案表
|
|
1733
|
+
* @returns {void}
|
|
1734
|
+
* @throws Error 指向第一个不可用的条目(不静默丢弃用户给的那一项)
|
|
1769
1735
|
*/
|
|
1770
|
-
function
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
if (typeof textValue === "string") return [{
|
|
1776
|
-
type: "text",
|
|
1777
|
-
text: textValue
|
|
1778
|
-
}];
|
|
1779
|
-
let text;
|
|
1780
|
-
try {
|
|
1781
|
-
text = stringifyJson(value) ?? String(value);
|
|
1782
|
-
} catch {
|
|
1736
|
+
function assertIgnoreFilesExist(args, root, messages) {
|
|
1737
|
+
if (boolOf(args.drop, "drop", messages)) return;
|
|
1738
|
+
for (const entry of singleOrList(args.ignoreFiles, "ignoreFiles", messages)) {
|
|
1739
|
+
const target = entry.startsWith("/") ? entry : `${root}/${entry}`;
|
|
1740
|
+
let usable = false;
|
|
1783
1741
|
try {
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1742
|
+
accessSync(target, constants.R_OK);
|
|
1743
|
+
usable = statSync(target).isFile();
|
|
1744
|
+
} catch {}
|
|
1745
|
+
if (!usable) throw new Error(fill(messages.ignoreFileMissing, {
|
|
1746
|
+
path: entry,
|
|
1747
|
+
root
|
|
1748
|
+
}));
|
|
1788
1749
|
}
|
|
1789
|
-
return [{
|
|
1790
|
-
type: "text",
|
|
1791
|
-
text
|
|
1792
|
-
}];
|
|
1793
1750
|
}
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
additionalProperties: false,
|
|
1797
|
-
properties: { text: { type: "string" } }
|
|
1798
|
-
};
|
|
1751
|
+
//#endregion
|
|
1752
|
+
//#region lib/sandbox-note.ts
|
|
1799
1753
|
/** 沙箱事实的公共后缀(把 mode/enforcement 一并交代清楚,避免只说「被拒」)。 */
|
|
1800
1754
|
function sandboxFacts(info, messages) {
|
|
1801
1755
|
const enforcement = info.enforcement === void 0 ? "" : fill(messages.sandboxEnforcement, { value: info.enforcement });
|
|
@@ -1804,130 +1758,28 @@ function sandboxFacts(info, messages) {
|
|
|
1804
1758
|
enforcement
|
|
1805
1759
|
});
|
|
1806
1760
|
}
|
|
1807
|
-
/**
|
|
1808
|
-
* 沙箱侧的**硬**失败:命令根本没跑起来。
|
|
1809
|
-
* runnerFailed 与 exitCode 无关——runner 在命令执行前就挂了,exit 码是 runner 的,
|
|
1810
|
-
* 拿来判「zg 未安装」是把沙箱故障误报成用户缺二进制。
|
|
1811
|
-
*/
|
|
1812
|
-
function sandboxFailure(result, messages) {
|
|
1813
|
-
const info = result.sandbox;
|
|
1814
|
-
if (info?.runnerFailed !== true) return null;
|
|
1815
|
-
return fill(messages.runnerFailed, { facts: sandboxFacts(info, messages) });
|
|
1816
|
-
}
|
|
1817
1761
|
/** 沙箱策略拒绝的可读说明(拒绝 ≠ 崩溃:既用于失败消息,也用于成功但残缺的结果)。 */
|
|
1818
1762
|
function deniedNote(info, messages) {
|
|
1819
1763
|
return fill(messages.sandboxDenied, { facts: sandboxFacts(info, messages) });
|
|
1820
1764
|
}
|
|
1821
|
-
/** 错误详情:首尾各留一段(zg/cargo 等错误的最终原因常在尾部)。
|
|
1822
|
-
* 两半各用一个函数,因为是两种缺陷:头切点会留下孤立**高**代理(`truncateEnd` 丢掉它),
|
|
1823
|
-
* 尾切点会留下孤立**低**代理(`truncateStart` 丢掉它);对调两个函数同样不留孤立代理,
|
|
1824
|
-
* 只是头尾内容掉头 ⇒ 测试里另有一组哨兵断言钉住归属。 */
|
|
1825
|
-
function failureDetail(result, messages) {
|
|
1826
|
-
const raw = result.stderr.text.length > 0 ? result.stderr.text : result.stdout.text;
|
|
1827
|
-
if (raw.length <= 800) return raw;
|
|
1828
|
-
const half = 400;
|
|
1829
|
-
return fill(messages.detailMiddle, {
|
|
1830
|
-
head: truncateEnd(raw, half),
|
|
1831
|
-
tail: truncateStart(raw, half)
|
|
1832
|
-
});
|
|
1833
|
-
}
|
|
1834
|
-
/** 有详情才带前缀拼接(不同句式各有前缀),空详情绝不留孤儿标点。 */
|
|
1835
|
-
function withDetail(detail, prefix) {
|
|
1836
|
-
return detail.length > 0 ? fill(prefix, { detail }) : "";
|
|
1837
|
-
}
|
|
1838
|
-
/**
|
|
1839
|
-
* zg 的结构化失败在 stderr 上以一行 `Code: <CODE>` 交出错误码(上游 `src/cli/errors.ts`),
|
|
1840
|
-
* 本包所有按码归因的判据都读那一行。**缺了这一行**就意味着这次失败没有可机读的码,而上游
|
|
1841
|
-
* 恰好有两类塌法会长这样:不带 `--debug` 时 `MODEL2VEC_DOWNLOAD_FAILED` 与
|
|
1842
|
-
* `INDEXING.FILES_FAILED` 被折成一句无码文案(首次下载 embedding 权重正落在这一档)。
|
|
1843
|
-
* 这里据此补一条可行动的出路,而不是让模型对着「exit=1 + 一句话」猜。
|
|
1844
|
-
*
|
|
1845
|
-
* 空 detail 不补:什么都没打出来时谈不上「上游把原因塌成了一句」,那条指引只会占住回显预算。
|
|
1846
|
-
* 已有 `Code:` 行时也不补:那时归因本就够了。
|
|
1847
|
-
*/
|
|
1848
|
-
const STRUCTURED_ERROR_CODE = /^\s*Code:/imu;
|
|
1849
|
-
function noCodeHint(detail, messages) {
|
|
1850
|
-
return detail.length === 0 || STRUCTURED_ERROR_CODE.test(detail) ? "" : `\n${messages.noErrorCodeHint}`;
|
|
1851
|
-
}
|
|
1852
|
-
function shellFailure(result, messages) {
|
|
1853
|
-
const runnerFailure = sandboxFailure(result, messages);
|
|
1854
|
-
if (runnerFailure !== null) return runnerFailure;
|
|
1855
|
-
if (result.timedOut) return messages.timeoutFailure;
|
|
1856
|
-
if (result.aborted) return messages.abortedFailure;
|
|
1857
|
-
if (result.exitCode === 0) return null;
|
|
1858
|
-
const detail = failureDetail(result, messages);
|
|
1859
|
-
const { sandbox } = result;
|
|
1860
|
-
if (sandbox?.denied === true) return fill(messages.deniedFailure, {
|
|
1861
|
-
exit: result.exitCode,
|
|
1862
|
-
denied: deniedNote(sandbox, messages),
|
|
1863
|
-
detail: withDetail(detail, messages.detailPrefix)
|
|
1864
|
-
});
|
|
1865
|
-
if (result.exitCode === 127) return fill(messages.notInstalledFailure, { detail: withDetail(detail, messages.detailPrefix) });
|
|
1866
|
-
return `${fill(messages.genericFailure, {
|
|
1867
|
-
exit: result.exitCode,
|
|
1868
|
-
detail: withDetail(detail, messages.detailColon)
|
|
1869
|
-
})}${noCodeHint(detail, messages)}`;
|
|
1870
|
-
}
|
|
1871
|
-
/**
|
|
1872
|
-
* 成功执行的 stderr 里哪些是「进度噪声」、哪些必须交回。
|
|
1873
|
-
*
|
|
1874
|
-
* zg 在**成功**时也往 stderr 写索引进度(非 TTY 下逐行落盘,实测原文:`Scanning files...` /
|
|
1875
|
-
* `Preparing local/potion-code-16m-v2` / `Indexing complete`)。这些行每次建索引都在,写进
|
|
1876
|
-
* 工具回执只是让模型对着同一堆噪声反复读;真正需要它看见的是另一类:降级提示、锁冲突、
|
|
1877
|
-
* 沙箱事实,以及任何本包**不认识**的新增告警。
|
|
1878
|
-
*
|
|
1879
|
-
* 所以判据是「只丢认得的进度行,其余全留」,而不是「只留认得的告警」——后者一旦 zg 出了
|
|
1880
|
-
* 新提示就会静默吞掉,那正是最不该发生的失败模式。
|
|
1881
|
-
*
|
|
1882
|
-
* 进度行词表逐条对着上游的进度格式化函数核过(含下载与就绪两档):
|
|
1883
|
-
* Scanning files… / Indexing files… / Indexing complete / Preparing <model> /
|
|
1884
|
-
* Downloading <model> · … / Model ready: <model>
|
|
1885
|
-
* 其中 `Indexing complete` 用**整行相等**匹配,不能用前缀——`Indexing completed with 3 failed
|
|
1886
|
-
* files`(部分文件失败的信号,必须留着)字面上就以它开头。
|
|
1887
|
-
*/
|
|
1888
|
-
const STDERR_PROGRESS_LINES = /* @__PURE__ */ new Set(["Scanning files...", "Indexing complete"]);
|
|
1889
|
-
/** 该行是否只是进度噪声。`warning` / `Error` / `zvec-grep` 一律不判为噪声。 */
|
|
1890
|
-
function isStderrProgressLine(line) {
|
|
1891
|
-
const trimmed = line.trim();
|
|
1892
|
-
if (STDERR_PROGRESS_LINES.has(trimmed)) return true;
|
|
1893
|
-
return trimmed.startsWith("Indexing files") || trimmed.startsWith("Preparing ") || trimmed.startsWith("Downloading ") || trimmed.startsWith("Model ready: ");
|
|
1894
|
-
}
|
|
1895
|
-
/** 剥掉进度行,留下真正要交回的 stderr(可能为空串)。 */
|
|
1896
|
-
function signalStderr(text) {
|
|
1897
|
-
return text.split("\n").filter((line) => line.trim().length > 0 && !isStderrProgressLine(line)).join("\n");
|
|
1898
|
-
}
|
|
1899
1765
|
/**
|
|
1900
|
-
*
|
|
1901
|
-
*
|
|
1902
|
-
*
|
|
1903
|
-
* 2. 沙箱在执行中拒绝过一次文件操作(zg 仍可 exit 0,但结果少了被拒的部分);
|
|
1904
|
-
* 3. **stderr 去噪之后仍非空**:zg 的降级提示(例如 embedding 模型拉不到 → 退化为
|
|
1905
|
-
* 纯词法兜底、跳过 --refresh)只写在 stderr,旧实现整个丢掉 → 用户把「只有词法
|
|
1906
|
-
* 结果」的检索当语义检索的完整结果。这里回显尾部一段。整段都是索引进度时一句都不加。
|
|
1766
|
+
* 后台进程的沙箱事实提示。runner 失败 / 策略拒绝都不许被显示成「完成」:
|
|
1767
|
+
* dsh-shell 只在有沙箱的执行器下填 proc.sandbox,读了它才能把「zg 自己失败」
|
|
1768
|
+
* 与「zg 根本没跑起来」分开。
|
|
1907
1769
|
*/
|
|
1908
|
-
function
|
|
1909
|
-
const
|
|
1910
|
-
if (
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
spill
|
|
1915
|
-
}));
|
|
1916
|
-
}
|
|
1917
|
-
const { sandbox } = result;
|
|
1918
|
-
if (sandbox?.denied === true) notes.push(fill(messages.sandboxWarning, { denied: deniedNote(sandbox, messages) }));
|
|
1919
|
-
const { stderr } = result;
|
|
1920
|
-
const signal = signalStderr(stderr.text);
|
|
1921
|
-
if (signal.length > 0) {
|
|
1922
|
-
const tail = truncateStart(signal, STDERR_NOTE_CHARS);
|
|
1923
|
-
const truncatedMark = stderr.truncated ? "[…]" : "";
|
|
1924
|
-
notes.push(fill(messages.stderrNote, {
|
|
1925
|
-
marked: truncatedMark,
|
|
1926
|
-
tail
|
|
1927
|
-
}));
|
|
1928
|
-
}
|
|
1929
|
-
return notes;
|
|
1770
|
+
function procSandboxNote(proc, messages) {
|
|
1771
|
+
const info = proc.sandbox;
|
|
1772
|
+
if (info === void 0) return null;
|
|
1773
|
+
if (info.runnerFailed === true) return fill(messages.rebuildRunnerFailed, { facts: sandboxFacts(info, messages) });
|
|
1774
|
+
if (info.denied) return fill(messages.rebuildDenied, { denied: deniedNote(info, messages) });
|
|
1775
|
+
return null;
|
|
1930
1776
|
}
|
|
1777
|
+
//#endregion
|
|
1778
|
+
//#region lib/rebuild-shape.ts
|
|
1779
|
+
/** 宿主服务键 = 客户端线上命名空间(两侧共用的唯一来源)。 */
|
|
1780
|
+
const REBUILD_REMOTE_NAMESPACE = "zvecGrepRebuild";
|
|
1781
|
+
//#endregion
|
|
1782
|
+
//#region lib/zg-config.ts
|
|
1931
1783
|
/** 各环境读一个 HF 镜像/代理基地址的优先级:显式入参 > 设置。
|
|
1932
1784
|
* `typeof` 判断是 host 侧兜底:值域正常时 schema 的 `.default()` 已保证是字符串,
|
|
1933
1785
|
* 引用被交回 undefined(条目未投影/宿主退化)时宁可不带 env,也不发一个空 HF_ENDPOINT。 */
|
|
@@ -1961,14 +1813,13 @@ function allowRemoteEmbedding(config) {
|
|
|
1961
1813
|
* **密钥只走环境变量,绝不进 argv**。两道原因,都是实测/读源码得来的:
|
|
1962
1814
|
* - 本包把整条命令当官方作业的 `JobSpec.label` 回显给卡片,argv 里的密钥会进界面、
|
|
1963
1815
|
* 进日志、进 `ps` 的进程列表;
|
|
1964
|
-
* - 上游自己就优先读环境变量(zvec-grep v0.2.2 `src/engine/config.ts
|
|
1965
|
-
* `nonEmptyEnvironmentValue(environment.ZVEC_GREP_ENDPOINT)
|
|
1966
|
-
* `environmentApiKey()` 依次试 `ZVEC_GREP_API_KEY` / `DASHSCOPE_API_KEY` / `QWEN_API_KEY`),
|
|
1816
|
+
* - 上游自己就优先读环境变量(zvec-grep v0.2.2 `src/engine/config.ts` 的
|
|
1817
|
+
* `nonEmptyEnvironmentValue(environment.ZVEC_GREP_ENDPOINT)` / `environmentApiKey()`),
|
|
1967
1818
|
* 走 env 既是它的正路,也省掉一条 argv 泄露面。
|
|
1968
1819
|
*
|
|
1969
1820
|
* **凭据为什么是「宿主进程里某个环境变量的名字」而不是值本身**:官方 subprocess 层会把
|
|
1970
1821
|
* 名字命中 `/KEY|PASSWORD|SECRET|TOKEN/i` 的变量从子进程环境里**剔掉**
|
|
1971
|
-
*
|
|
1822
|
+
* (packages/subprocess/subprocess/src/index.ts 的 `scrubbedParentEnv`),所以光靠在
|
|
1972
1823
|
* 宿主进程里 export 一个 `ZVEC_GREP_API_KEY` 是到不了 zg 的——必须由本插件显式转发。
|
|
1973
1824
|
* 于是配置里只记**名字**、值现读现转:密钥不必落进插件配置文件,也不进 argv、不进日志。
|
|
1974
1825
|
* 两项都只在 allowRemoteEmbedding 打开时才读:默认部署下这段代码根本不执行。
|
|
@@ -1984,1215 +1835,1320 @@ function zgEnv(config) {
|
|
|
1984
1835
|
}
|
|
1985
1836
|
return Object.keys(env).length > 0 ? env : void 0;
|
|
1986
1837
|
}
|
|
1987
|
-
|
|
1988
|
-
const
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
/** 门槛文案:回显实际版本与门槛值,并给出唯一的出路(升级 zvec-grep)。 */
|
|
1992
|
-
function tooOldZgError(actual, messages) {
|
|
1993
|
-
return new Error(fill(messages.zgVersionTooOld, {
|
|
1994
|
-
actual: formatZgVersion(actual),
|
|
1995
|
-
minimum: MINIMUM_ZG_VERSION
|
|
1996
|
-
}));
|
|
1838
|
+
function readDefaultEmbedding(config) {
|
|
1839
|
+
const raw = config.defaultEmbedding.get();
|
|
1840
|
+
if (typeof raw === "string" && isLocalEmbedding(raw)) return raw;
|
|
1841
|
+
return DEFAULT_EMBEDDING;
|
|
1997
1842
|
}
|
|
1998
1843
|
/**
|
|
1999
|
-
*
|
|
2000
|
-
*
|
|
2001
|
-
*
|
|
1844
|
+
* zg 传输模式:域内取值由 schema 保证,这里只处理「字段缺省」与宿主退化时交回的非域值。
|
|
1845
|
+
* 读一次即传给检索、索引、状态与后台重建四条命令路径——混用模式会在守护进程持有索引
|
|
1846
|
+
* 租约时让写侧直接失败,故四条路径必须同源。
|
|
2002
1847
|
*/
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
try {
|
|
2006
|
-
const env = zgEnv(config);
|
|
2007
|
-
const spec = host.shell.resolve({
|
|
2008
|
-
command: "zg --version",
|
|
2009
|
-
workdir: tmpdir(),
|
|
2010
|
-
timeoutMs: ZG_VERSION_PROBE_TIMEOUT_MS,
|
|
2011
|
-
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
2012
|
-
...env ? { env } : {}
|
|
2013
|
-
});
|
|
2014
|
-
const result = await (await host.shell.execute(spec)).result();
|
|
2015
|
-
stdout = result.exitCode === 0 ? result.stdout.text : void 0;
|
|
2016
|
-
} catch {
|
|
2017
|
-
stdout = void 0;
|
|
2018
|
-
}
|
|
2019
|
-
return stdout === void 0 ? void 0 : tooOldZgVersion(stdout);
|
|
1848
|
+
function readClientMode(config, messages) {
|
|
1849
|
+
return clientModeOf(config.clientMode, messages);
|
|
2020
1850
|
}
|
|
1851
|
+
//#endregion
|
|
1852
|
+
//#region lib/rebuild-remote.ts
|
|
1853
|
+
/** 本包作业的 kind(宿主据此发出的 id 形如 `zvec-grep-rebuild-<hex>`)。 */
|
|
1854
|
+
const REBUILD_JOB_KIND = "zvec-grep-rebuild";
|
|
2021
1855
|
/**
|
|
2022
|
-
*
|
|
2023
|
-
*
|
|
2024
|
-
*
|
|
2025
|
-
*
|
|
1856
|
+
* 本 kind 在注册表里的**已落定**记录上限:每次 start 前先剪到 `MAX-1` 条,新那条落定后
|
|
1857
|
+
* 正好 `MAX` 条在册(文案与卡片拒绝提示都按这个数说)。同时能跑几个不在这里——那是
|
|
1858
|
+
* 注册表的容量闸(实测未拥有桶 10,满员是**拒绝**新 start,不是淘汰旧的)。官方件**不会**
|
|
1859
|
+
* 自行回收落定记录("A settled record stays listed until its owner's disposal, service
|
|
1860
|
+
* disposal, or an explicit remove"),而注册表又随宿主活着、不随本插件卸载而死 ⇒ 这条
|
|
1861
|
+
* 裁剪是本包的责任。
|
|
2026
1862
|
*/
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
cachedAt = now;
|
|
2038
|
-
cachedTooOld = probe;
|
|
2039
|
-
if (probe !== void 0) throw tooOldZgError(probe, messages);
|
|
2040
|
-
} };
|
|
1863
|
+
const REBUILD_HISTORY_MAX = 10;
|
|
1864
|
+
/** 卡片视图的尾部长度(打标文案在 lib/messages.ts,随语言走)。 */
|
|
1865
|
+
const JOB_OUT_VIEW_CHARS = 4e3;
|
|
1866
|
+
/** 从名册投影推导身份证(官方 `JobView` 的三段稳定事实)。 */
|
|
1867
|
+
function identityOf(view) {
|
|
1868
|
+
return {
|
|
1869
|
+
kind: view.kind,
|
|
1870
|
+
label: view.label,
|
|
1871
|
+
startedAt: view.startedAt
|
|
1872
|
+
};
|
|
2041
1873
|
}
|
|
2042
|
-
/**
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
const SERVER_READY_PROBE_TIMEOUT_MS = 1e4;
|
|
2046
|
-
/** 就绪探测命令行:`--check-ready` 把「就绪与否」 expressed 成退出码。 */
|
|
2047
|
-
const SERVER_READY_COMMAND = "zg server status --check-ready";
|
|
2048
|
-
/** 探一次守护进程就绪态:退出码 0 = 就绪。任何异常与非零退出都算未就绪。 */
|
|
2049
|
-
async function probeServerReady(host, config) {
|
|
2050
|
-
try {
|
|
2051
|
-
const env = zgEnv(config);
|
|
2052
|
-
const spec = host.shell.resolve({
|
|
2053
|
-
command: SERVER_READY_COMMAND,
|
|
2054
|
-
workdir: tmpdir(),
|
|
2055
|
-
timeoutMs: SERVER_READY_PROBE_TIMEOUT_MS,
|
|
2056
|
-
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
2057
|
-
...env ? { env } : {}
|
|
2058
|
-
});
|
|
2059
|
-
return (await (await host.shell.execute(spec)).result()).exitCode === 0;
|
|
2060
|
-
} catch {
|
|
2061
|
-
return false;
|
|
2062
|
-
}
|
|
1874
|
+
/** 两段身份证是否同一回事(三段全同才算)。 */
|
|
1875
|
+
function sameIdentity(left, right) {
|
|
1876
|
+
return left.kind === right.kind && left.label === right.label && left.startedAt === right.startedAt;
|
|
2063
1877
|
}
|
|
2064
1878
|
/**
|
|
2065
|
-
*
|
|
1879
|
+
* 身份证尚未盖章时的占位出生时刻。
|
|
2066
1880
|
*
|
|
2067
|
-
*
|
|
2068
|
-
*
|
|
1881
|
+
* `startedAt` 由官方签发(`Date.now()`,永不为 0),而 kind/label 在 `start` 之前就已
|
|
1882
|
+
* 已知——那正是本包递给官方的那份规格。于是"start 的同步块里就跑到了 `run()`"那一档读取
|
|
1883
|
+
* 比对时必然落到"对不上":那一刻还没有可比的出生时刻,不该把同 id 的另一条作业当成自己的收走。
|
|
2069
1884
|
*/
|
|
2070
|
-
|
|
2071
|
-
let cachedAt = 0;
|
|
2072
|
-
let cachedReady = false;
|
|
2073
|
-
let probed = false;
|
|
2074
|
-
return { async ready() {
|
|
2075
|
-
const now = Date.now();
|
|
2076
|
-
if (probed && now - cachedAt < SERVER_READY_TTL_MS) return cachedReady;
|
|
2077
|
-
cachedReady = await probeServerReady(host, config);
|
|
2078
|
-
cachedAt = now;
|
|
2079
|
-
probed = true;
|
|
2080
|
-
return cachedReady;
|
|
2081
|
-
} };
|
|
2082
|
-
}
|
|
1885
|
+
const UNSIGNED_STARTED_AT = 0;
|
|
2083
1886
|
/**
|
|
2084
|
-
*
|
|
2085
|
-
* 会被多个查询组各命中一次(名次与 `matchedBy` 逐组变化,实测同一 `src/beta.ts:1-3`
|
|
2086
|
-
* 在 fts 组排第 4、在 vector 组排第 1),直接求和会把同一处位置重复计入。
|
|
2087
|
-
* - 分组计数合计:各组 `hits:` 之和,反映 zg 实际跑了多少路。
|
|
2088
|
-
* - 去重后不同位置:按 `相对路径:行号范围` 这一稳定身份键去重——名次、匹配来源、
|
|
2089
|
-
* 分数都逐组变化,不能入键——反映模型真正看到几处不同代码。
|
|
2090
|
-
* 身份键取条目头行里 `matchedBy=` 之后的**整段原样**文本,不去拆行号范围:路径本身
|
|
2091
|
-
* 可以含空格与冒号(实测 `deep/a/b/c d/we:ird file.ts:1-2`),任何拆解都会引入误判,
|
|
2092
|
-
* 而原样文本已经恰好就是「相对路径 + 行号范围」。一条位置都数不出时整段去重口径省略,
|
|
2093
|
-
* 不数就不谎称。
|
|
1887
|
+
* 名册里那条 id 是不是**我们**的那条作业。
|
|
2094
1888
|
*
|
|
2095
|
-
*
|
|
2096
|
-
*
|
|
1889
|
+
* 只比 id 不够:id 是从请求里读进来的,名册里同 id 的那条完全可能是另一条作业(另一棵树、
|
|
1890
|
+
* 另一条命令),旧卡片跟上去就是串台。三段身份都由官方签发。
|
|
2097
1891
|
*/
|
|
2098
|
-
|
|
2099
|
-
|
|
1892
|
+
function sameJob(state, view) {
|
|
1893
|
+
return sameIdentity(state.identity, identityOf(view));
|
|
1894
|
+
}
|
|
2100
1895
|
/**
|
|
2101
|
-
*
|
|
2102
|
-
*
|
|
2103
|
-
*
|
|
2104
|
-
*
|
|
2105
|
-
*
|
|
2106
|
-
*
|
|
2107
|
-
*
|
|
2108
|
-
*
|
|
2109
|
-
*
|
|
2110
|
-
*
|
|
2111
|
-
* - `[global_fill]` / `[group_coverage: x]`:排在名次与 `matchedBy=` 之间,漏了它整行
|
|
2112
|
-
* 就匹配不上,那条命中会被当成不存在。
|
|
2113
|
-
*
|
|
2114
|
-
* preview 的源码行都带 `<行号>\t` 前缀、markdown 标题行是 `heading:`、追踪行是 `trace:`,
|
|
2115
|
-
* 都撞不上这一形状。匹配来源逐组变化(fts / vector / fts+vector),故 `\S+` 只消费来源。
|
|
1896
|
+
* 本包作业的输出面:官方 pull source,stdout/stderr 各一只游标,外加一层"读失败不许
|
|
1897
|
+
* 拖垮泵"的兜。选 pull 而不是生产者 push(`JobHandle.append`)是复核后按实测定下的:
|
|
1898
|
+
* - `proc.observed[*].readFrom` 是**非消费**的独立观察者面(installed dsh-shell
|
|
1899
|
+
* types.d.ts:"without stealing bytes from `readOutput`"),与本包前台用的
|
|
1900
|
+
* 消费式游标互不干扰;
|
|
1901
|
+
* - 泵按注册表自己的节拍跑(实测默认 150ms,落定前再排最后一次)⇒ **卡片关着环也前进**,
|
|
1902
|
+
* 模型侧 job_output 随时看得见进度;push 形态把可见性绑在了轮询上。
|
|
1903
|
+
* @param proc 后台进程句柄
|
|
1904
|
+
* @param state 这条重建的状态盒(见 {@link RebuildState})
|
|
1905
|
+
* @returns 交给 JobSpec.output 的两条源
|
|
2116
1906
|
*/
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
1907
|
+
function rebuildSources(proc, state) {
|
|
1908
|
+
return ["stdout", "stderr"].map((channel) => {
|
|
1909
|
+
let failed = false;
|
|
1910
|
+
return {
|
|
1911
|
+
channel,
|
|
1912
|
+
read: (fromByte) => {
|
|
1913
|
+
if (failed) return {
|
|
1914
|
+
text: "",
|
|
1915
|
+
nextOffset: fromByte,
|
|
1916
|
+
lossy: true
|
|
1917
|
+
};
|
|
1918
|
+
try {
|
|
1919
|
+
const read = proc.observed[channel].readFrom(fromByte);
|
|
1920
|
+
if (read.lossy) state.lost = true;
|
|
1921
|
+
return read;
|
|
1922
|
+
} catch {
|
|
1923
|
+
state.lost = true;
|
|
1924
|
+
failed = true;
|
|
1925
|
+
return {
|
|
1926
|
+
text: "",
|
|
1927
|
+
nextOffset: fromByte,
|
|
1928
|
+
lossy: true
|
|
1929
|
+
};
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
};
|
|
2136
1933
|
});
|
|
2137
1934
|
}
|
|
2138
|
-
/**
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
var RebuildLockBusyError = class extends Error {
|
|
2145
|
-
constructor(message) {
|
|
2146
|
-
super(message);
|
|
2147
|
-
this.name = "RebuildLockBusyError";
|
|
1935
|
+
/** 官方件对未知/已淘汰 id 抛错;本包的判据要的是"有没有",不是异常(无 ⇒ null)。 */
|
|
1936
|
+
function jobView(jobs, id) {
|
|
1937
|
+
try {
|
|
1938
|
+
return jobs.get(id);
|
|
1939
|
+
} catch {
|
|
1940
|
+
return null;
|
|
2148
1941
|
}
|
|
2149
|
-
}
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
const result = await (await host.shell.execute(spec)).result();
|
|
2160
|
-
const failure = shellFailure(result, opts.messages);
|
|
2161
|
-
if (failure !== null) {
|
|
2162
|
-
const resolved = opts.resolveFailure?.(failure, result) ?? null;
|
|
2163
|
-
if (resolved !== null) return resolved;
|
|
2164
|
-
const concurrent = classifyConcurrentFailure(result.stderr.text);
|
|
2165
|
-
throw concurrent?.kind === "lock-busy" && concurrent.rebuild ? new RebuildLockBusyError(failure) : new Error(failure);
|
|
1942
|
+
}
|
|
1943
|
+
/** 一次成对读数:状态投影 + 留存窗内容;注册表已无此 id ⇒ null。 */
|
|
1944
|
+
function readRebuildOutput(jobs, id) {
|
|
1945
|
+
try {
|
|
1946
|
+
return {
|
|
1947
|
+
view: jobs.get(id),
|
|
1948
|
+
retained: jobs.readAt(id, 0)
|
|
1949
|
+
};
|
|
1950
|
+
} catch {
|
|
1951
|
+
return null;
|
|
2166
1952
|
}
|
|
2167
|
-
const notes = successNotes(result, opts.messages, opts.stdoutMaxBytes);
|
|
2168
|
-
const { text } = result.stdout;
|
|
2169
|
-
const summary = opts.summaryLimit === void 0 ? null : hitSummary(text, opts.summaryLimit, result.stdout.truncated, opts.messages);
|
|
2170
|
-
const extras = summary === null ? notes : [...notes, summary];
|
|
2171
|
-
return extras.length > 0 ? `${text}\n${extras.join("\n")}` : text;
|
|
2172
1953
|
}
|
|
2173
|
-
/**
|
|
2174
|
-
function
|
|
2175
|
-
return
|
|
1954
|
+
/** 官方 JobStatus 里"仍在跑"的两枚:`stopping` 是取消已发出、进程还没收完。 */
|
|
1955
|
+
function isLiveStatus(status) {
|
|
1956
|
+
return status === "running" || status === "stopping";
|
|
2176
1957
|
}
|
|
2177
|
-
/**
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
1958
|
+
/**
|
|
1959
|
+
* 收掉子进程,**忽略抛错**:进程可能已自然退出或已被系统回收,此时 kill 失败不是本包的失败。
|
|
1960
|
+
* 调用点都在清理臂(卸载、被拒、超时)上,那里没有可行动的下一步;把异常抛出去只会让清理链
|
|
1961
|
+
* 半途而废,留下更难的现场。
|
|
1962
|
+
*/
|
|
1963
|
+
function killProc(proc) {
|
|
1964
|
+
try {
|
|
1965
|
+
proc.kill();
|
|
1966
|
+
} catch {}
|
|
2183
1967
|
}
|
|
2184
1968
|
/**
|
|
2185
|
-
*
|
|
1969
|
+
* 历史窗口有界:按注册表的**可见集合**淘汰本 kind 最老的已落定记录。
|
|
2186
1970
|
*
|
|
2187
|
-
*
|
|
2188
|
-
*
|
|
2189
|
-
*
|
|
2190
|
-
*
|
|
1971
|
+
* 剪到**只剩 `MAX-1` 条**才是对的:这一剪发生在 start 之前,紧接着就有一条新作业进来,
|
|
1972
|
+
* 它落定之后名册里正好是最近 `MAX` 条已落定记录 ⇒ 与卡片文案「只保留最近 10 条已结束的重建」
|
|
1973
|
+
* 同一口径。判据的时点是**新作业落定之后**,不是剪完那一刻——只看后者会把这条判反。
|
|
1974
|
+
* 在跑的一条不动——官方件对超额的答法是拒绝 start(实测),不是替我们杀任务。
|
|
1975
|
+
* 侧表里没有的 id(上一次 apply 卸载后残留的记录)同样要能清掉,所以遍历的是
|
|
1976
|
+
* `list()` 而不是 `records`。
|
|
1977
|
+
* @param jobs 官方注册表
|
|
1978
|
+
* @param records 本包侧表(被淘汰记录同步删掉)
|
|
1979
|
+
* @returns {void}
|
|
2191
1980
|
*/
|
|
2192
|
-
|
|
2193
|
-
const
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
messages: opts.messages,
|
|
2198
|
-
summaryLimit: opts.summaryLimit,
|
|
2199
|
-
resolveFailure: opts.resolveFailure
|
|
2200
|
-
};
|
|
2201
|
-
const wait = opts.rebuildWait;
|
|
2202
|
-
if (wait === void 0) return runForegroundOnce(host, command, workdir, timeoutMs, base);
|
|
2203
|
-
try {
|
|
2204
|
-
return await runForegroundOnce(host, command, workdir, timeoutMs, base);
|
|
2205
|
-
} catch (error) {
|
|
2206
|
-
const entry = wait.rebuilds.covering(wait.root, opts.messages);
|
|
2207
|
-
if (!(error instanceof RebuildLockBusyError) || entry === void 0) throw error;
|
|
2208
|
-
const outcome = await wait.rebuilds.wait(wait.root, opts.messages, wait.maxWaitMs, opts.signal);
|
|
2209
|
-
if (outcome === "settled") return runForegroundOnce(host, command, workdir, timeoutMs, base);
|
|
2210
|
-
throw new Error(outcome === "aborted" ? messagesAbortedWaiting(entry.root, opts.messages) : messagesWaitExpired(entry.root, wait.maxWaitMs, opts.messages), { cause: error });
|
|
1981
|
+
function pruneRebuildHistory(jobs, records) {
|
|
1982
|
+
const settled = jobs.list().filter((job) => job.kind === REBUILD_JOB_KIND).filter((job) => !isLiveStatus(job.status));
|
|
1983
|
+
for (const job of settled.slice(0, Math.max(settled.length - 9, 0))) {
|
|
1984
|
+
jobs.remove(job.id);
|
|
1985
|
+
records.delete(job.id);
|
|
2211
1986
|
}
|
|
2212
1987
|
}
|
|
2213
1988
|
/**
|
|
2214
|
-
*
|
|
2215
|
-
*
|
|
2216
|
-
*
|
|
1989
|
+
* 从官方容量闸的错误文本里取出上限(实测原文:`background job limit reached for this
|
|
1990
|
+
* owner (limit: 10)`)。认不出来 ⇒ undefined,调用方退回通用的启动失败文案。
|
|
1991
|
+
* 为什么单独认这一条:它是本包唯一会把宿主英文原话插进中文卡片的错误,又恰恰最该翻成
|
|
1992
|
+
* 人话的那一条——用户此时要做的是去 job_list 里收掉不需要的作业,而不是读一句英文。
|
|
2217
1993
|
*/
|
|
2218
|
-
function
|
|
2219
|
-
|
|
2220
|
-
return root;
|
|
2221
|
-
}
|
|
2222
|
-
function readDefaultEmbedding(config) {
|
|
2223
|
-
const raw = config.defaultEmbedding.get();
|
|
2224
|
-
if (typeof raw === "string" && isLocalEmbedding(raw)) return raw;
|
|
2225
|
-
return DEFAULT_EMBEDDING;
|
|
1994
|
+
function capacityLimitOf(error) {
|
|
1995
|
+
return /\(limit: (?<limit>\d+)\)/u.exec(errorText(error))?.groups?.["limit"];
|
|
2226
1996
|
}
|
|
2227
1997
|
/**
|
|
2228
|
-
*
|
|
2229
|
-
*
|
|
1998
|
+
* 「工作区重建」的四道前置校验:绝对路径 + 归一化、本 daemon 观测过的白名单、
|
|
1999
|
+
* 目录此刻仍存在。不过就交回可直接显示的文案(错误文本全走双语字典)。
|
|
2000
|
+
*
|
|
2001
|
+
* 白名单是**动作**的闸门:没有它,任何拿得到这条读面的一方都能用任意绝对路径去
|
|
2002
|
+
* `zg index --rebuild`——读遍那棵树、写 `.zvec-grep/`,还可能把其中的非隐藏敏感文件
|
|
2003
|
+
* 灌进向量库并回显到上下文。
|
|
2004
|
+
* @param raw 请求里带来的 root(未经类型校验)
|
|
2005
|
+
* @param ledger 观测到的工作区白名单
|
|
2006
|
+
* @param started 本次请求语言的文案表
|
|
2007
|
+
* @returns 归一化后可用的绝对路径;不合格时 `{ error }`
|
|
2230
2008
|
*/
|
|
2231
|
-
function
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2009
|
+
function acceptableRoot(raw, ledger, started) {
|
|
2010
|
+
let root;
|
|
2011
|
+
try {
|
|
2012
|
+
root = assertAbsoluteRoot(raw, started);
|
|
2013
|
+
} catch (error) {
|
|
2014
|
+
return { error: {
|
|
2015
|
+
value: fill(started.endpointRootInvalid, { reason: errorText(error) }),
|
|
2016
|
+
status: 400
|
|
2017
|
+
} };
|
|
2018
|
+
}
|
|
2019
|
+
if (!ledger.has(root)) return { error: {
|
|
2020
|
+
value: fill(started.endpointRootUntracked, { root }),
|
|
2021
|
+
status: 403
|
|
2022
|
+
} };
|
|
2023
|
+
if (!existsSync(root)) return { error: {
|
|
2024
|
+
value: fill(started.endpointRootGone, { root }),
|
|
2025
|
+
status: 400
|
|
2026
|
+
} };
|
|
2027
|
+
return { root };
|
|
2237
2028
|
}
|
|
2238
2029
|
/**
|
|
2239
|
-
*
|
|
2240
|
-
*
|
|
2241
|
-
*
|
|
2030
|
+
* 这个 root 上有没有**仍在跑**的本包重建?有 ⇒ 返回那枚作业 id 让新面板跟随。
|
|
2031
|
+
*
|
|
2032
|
+
* 判据是三条一起:"侧表里有这条" + "名册里同 id 的那条确实是我们那条(比出生时刻)" +
|
|
2033
|
+
* "状态还在跑/正在收"。第二条不能省:jobs 被重载之后 id 会重名,只查侧表就把一张新面板
|
|
2034
|
+
* 领到别人的作业上。
|
|
2035
|
+
* @param jobs 调用方已确认在场的注册表(缺席那一支在重建方法更早答过)
|
|
2036
|
+
* @param records 本包侧表
|
|
2037
|
+
* @param root 已归一化的工作区
|
|
2038
|
+
* @returns 跟进的那枚作业 id;没有可跟的就是 undefined
|
|
2242
2039
|
*/
|
|
2243
|
-
function
|
|
2244
|
-
return
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
}
|
|
2250
|
-
/** search-first 门禁开关:**fail-closed**。schema 默认已是 true,引用仍交回 undefined
|
|
2251
|
-
* (条目没被投影 / 宿主退化)时按「门禁开着」处理——宁可多拦一次 grep,也不能把
|
|
2252
|
-
* 「读不到设置」静默当成「用户关了门禁」。 */
|
|
2253
|
-
function readEnforceSearchFirst(config) {
|
|
2254
|
-
return config.enforceSearchFirst.get() ?? true;
|
|
2255
|
-
}
|
|
2256
|
-
/** 归一路径的跨平台可比形式:剥掉 macOS 的 `/private` 解析前缀(`/tmp` ⇄ `/private/tmp`)。 */
|
|
2257
|
-
function comparablePath(root) {
|
|
2258
|
-
return root.startsWith("/private/") ? root.slice(8) : root;
|
|
2040
|
+
function followRunningRebuild(jobs, records, root) {
|
|
2041
|
+
return [...records.values()].find((record) => {
|
|
2042
|
+
if (record.root !== root) return false;
|
|
2043
|
+
const view = jobView(jobs, record.id);
|
|
2044
|
+
return view !== null && sameJob(record.state, view) && isLiveStatus(view.status);
|
|
2045
|
+
})?.id;
|
|
2259
2046
|
}
|
|
2260
|
-
/** 认的清单版本:与上游 `CURRENT_MANIFEST_VERSION` 同值([v0.2.2] src/engine/manifest.ts:8)。 */
|
|
2261
|
-
const SUPPORTED_MANIFEST_VERSION = 1;
|
|
2262
2047
|
/**
|
|
2263
|
-
*
|
|
2048
|
+
* 把「起一条 zg 失败」的原因翻成卡片文案。
|
|
2264
2049
|
*
|
|
2265
|
-
*
|
|
2266
|
-
*
|
|
2267
|
-
*
|
|
2268
|
-
* 在这个目录里检索会报「索引不可用」,而门禁却按「已建索引」拦着 grep/rg。
|
|
2269
|
-
* - 清单的版本不是当前认的那一版——上游读它会直接抛 MANIFEST.INVALID(要求
|
|
2270
|
-
* `manifestVersion` 严格等于 `CURRENT_MANIFEST_VERSION`),此时本目录**一次检索都做不了**,
|
|
2271
|
-
* 却会被「是个数字」这种宽松判据放进门禁。故这里同样取严格相等。
|
|
2050
|
+
* **本函数不杀进程**:杀由 `attachIndexWrite` 负责——它才是真正握着那条进程句柄、
|
|
2051
|
+
* 且知道作业有没有登记成功的地方(preflight 在 controller/容量/入参上拒掉作业时,spawn
|
|
2052
|
+
* 已经发生,不杀就会留下一条没登记、谁也停不掉的 zg)。这里只管文案。
|
|
2272
2053
|
*
|
|
2273
|
-
*
|
|
2274
|
-
*
|
|
2275
|
-
|
|
2054
|
+
* 满员那一档单独翻文案:它是本包唯一会把宿主英文原话插进卡片的错误,又最该翻成人话
|
|
2055
|
+
* (用户要做的是去 job_list 收作业,不是读一句英文)。
|
|
2056
|
+
*/
|
|
2057
|
+
function startupFailureText(error, started) {
|
|
2058
|
+
const capacity = capacityLimitOf(error);
|
|
2059
|
+
return capacity === void 0 ? fill(started.endpointStartFailed, { reason: errorText(error) }) : fill(started.endpointJobsAtCapacity, { limit: capacity });
|
|
2060
|
+
}
|
|
2061
|
+
/**
|
|
2062
|
+
* 在 controller 闸门下起一条未拥有作业。
|
|
2276
2063
|
*
|
|
2277
|
-
*
|
|
2278
|
-
* `
|
|
2279
|
-
*
|
|
2064
|
+
* 官方件在"没有 controller 服务这个 owner"时直接拒绝 `start`(实测),而未拥有
|
|
2065
|
+
* 作业只被 global 层服务;web 面上宿主自己的 `tool-jobs` 被移进了各 preset realm
|
|
2066
|
+
* (packages/bundle/web-app/cordis.patch.yml 把 tool-jobs 在宿主平面 disabled),
|
|
2067
|
+
* 所以本包必须自带一枚从无作用域上下文 attach 的 controller。但**只在 start 这一瞬挂**:
|
|
2068
|
+
* 实测挂上即放行、摘掉即恢复拒绝、可反复,而 global 层的 controller 只被 `servesOwner`
|
|
2069
|
+
* 读,作业的后续(read/kill/落定)都不依赖它。留一枚常驻 token 等于在"宿主故意没装 job
|
|
2070
|
+
* 工具"的组成里替全宿主开着那道闸门——官方契约写的是"生产者不能起一台 owner 收不掉、
|
|
2071
|
+
* 停不掉的作业",常驻就是把它反过来做。
|
|
2280
2072
|
*/
|
|
2281
|
-
function
|
|
2282
|
-
|
|
2073
|
+
function startUnderController(jobs, spec) {
|
|
2074
|
+
const detach = jobs.attachController("zvec-grep: rebuild");
|
|
2283
2075
|
try {
|
|
2284
|
-
|
|
2285
|
-
}
|
|
2286
|
-
|
|
2076
|
+
return jobs.start(spec);
|
|
2077
|
+
} finally {
|
|
2078
|
+
detach();
|
|
2287
2079
|
}
|
|
2288
|
-
if (!isRecord(parsed) || !("manifestVersion" in parsed) || parsed["manifestVersion"] !== SUPPORTED_MANIFEST_VERSION) return false;
|
|
2289
|
-
const { rootPaths } = parsed;
|
|
2290
|
-
if (!Array.isArray(rootPaths) || rootPaths.length === 0) return false;
|
|
2291
|
-
const target = comparablePath(normalizeRoot(dir));
|
|
2292
|
-
return rootPaths.some((entry) => isRecord(entry) && typeof entry["absolutePath"] === "string" && entry["absolutePath"].length > 0 && comparablePath(normalizeRoot(entry["absolutePath"])) === target);
|
|
2293
2080
|
}
|
|
2294
|
-
/**
|
|
2295
|
-
*
|
|
2296
|
-
*
|
|
2297
|
-
*
|
|
2298
|
-
*
|
|
2299
|
-
*
|
|
2300
|
-
*
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2081
|
+
/**
|
|
2082
|
+
* 交给注册表的作业规格:输出源 + `run` 的两枚钩子(cancel / done)与那枚 kill 定时器。
|
|
2083
|
+
* 单独成一段是因为它只在 `start` 的那一拍被同步调用一次,与「登记进侧表」是两件事。
|
|
2084
|
+
* @param routes 本次注册的共享依赖(config 现读超时、host 挂 timer、jobsOf 现读注册表)
|
|
2085
|
+
* @param proc 已经起来的 zg 进程
|
|
2086
|
+
* @param state 这条重建的状态盒(与侧表记录共用)
|
|
2087
|
+
* @param command 实际执行的命令行(作业 label,模型在 job_list 里看见的那句)
|
|
2088
|
+
* @returns 官方 JobSpec:kind / label / output / run
|
|
2089
|
+
*/
|
|
2090
|
+
function rebuildJobSpec(routes, proc, state, command, root) {
|
|
2091
|
+
const { config, host, jobsOf, messages } = routes;
|
|
2092
|
+
return {
|
|
2093
|
+
kind: REBUILD_JOB_KIND,
|
|
2094
|
+
label: command,
|
|
2095
|
+
output: rebuildSources(proc, state),
|
|
2096
|
+
run: (handle) => {
|
|
2097
|
+
const liveJob = () => {
|
|
2098
|
+
const live = jobsOf();
|
|
2099
|
+
if (live === void 0) return null;
|
|
2100
|
+
const view = jobView(live, handle.id);
|
|
2101
|
+
if (view === null || !sameJob(state, view)) return null;
|
|
2102
|
+
return {
|
|
2103
|
+
jobs: live,
|
|
2104
|
+
status: view.status
|
|
2105
|
+
};
|
|
2106
|
+
};
|
|
2107
|
+
const cancelKillTimer = host.timer.timeout(() => {
|
|
2108
|
+
if (proc.status !== "running") return;
|
|
2109
|
+
const live = liveJob();
|
|
2110
|
+
if (live !== null && live.status !== "running") return;
|
|
2111
|
+
const minutes = Math.round(config.indexTimeoutMs / 6e4);
|
|
2112
|
+
state.timeoutNote = fill(messages().rebuildTimeout, { minutes });
|
|
2113
|
+
if (live === null) {
|
|
2114
|
+
killProc(proc);
|
|
2115
|
+
return;
|
|
2116
|
+
}
|
|
2117
|
+
live.jobs.kill(handle.id, void 0, fill(messages().jobReasonTimeout, { minutes }));
|
|
2118
|
+
}, config.indexTimeoutMs);
|
|
2119
|
+
return {
|
|
2120
|
+
cancel: () => {
|
|
2121
|
+
killProc(proc);
|
|
2122
|
+
},
|
|
2123
|
+
done: (async () => {
|
|
2124
|
+
await proc.done;
|
|
2125
|
+
cancelKillTimer();
|
|
2126
|
+
try {
|
|
2127
|
+
return jobOutcomeOf(proc);
|
|
2128
|
+
} finally {
|
|
2129
|
+
routes.rebuilds.release(root);
|
|
2130
|
+
}
|
|
2131
|
+
})()
|
|
2132
|
+
};
|
|
2133
|
+
}
|
|
2134
|
+
};
|
|
2305
2135
|
}
|
|
2306
|
-
/**
|
|
2307
|
-
|
|
2308
|
-
|
|
2136
|
+
/**
|
|
2137
|
+
* 起一条 `zg index`:命令构造 + resolve + execute 三步。
|
|
2138
|
+
*
|
|
2139
|
+
* 远程重建与模型侧后台索引**共用**这一个函数(不是复制品),所以两条入口起的作业
|
|
2140
|
+
* 在名册、状态投影、轮询读面上完全同形。命令形态由 `indexArgs` 决定,故它也服务普通建索引。
|
|
2141
|
+
*
|
|
2142
|
+
* 版本门槛排在命令构造**之前**:确知装的是太老的 zg 时,在这一行就给出可照做的指引,
|
|
2143
|
+
* 而不是起一条命令形态对不上的 zg 再让人对着结果猜。注意这个顺序也保证了「门槛失败」
|
|
2144
|
+
* 发生在任何进程存在之前,调用方那条 `release` 出口足以收干净。
|
|
2145
|
+
*
|
|
2146
|
+
* 任一步抛错即就地翻成 `{ error, status }`;**本函数不释放占位**,那由调用方做(它才持有 root)。
|
|
2147
|
+
* @param routes 本次注册的共享依赖(现读 config / host / jobsOf)
|
|
2148
|
+
* @param started 本次请求语言的文案表
|
|
2149
|
+
* @param indexArgs 已归一 root 的索引入参
|
|
2150
|
+
* @param embedding 设置里的默认 embedding(`indexArgs.embedding` 为空时用它)
|
|
2151
|
+
* @returns 起来的进程与它跑的命令;失败为 `{ error, status }`
|
|
2152
|
+
*/
|
|
2153
|
+
async function spawnIndexWrite(routes, started, indexArgs, embedding) {
|
|
2154
|
+
const { config, host } = routes;
|
|
2155
|
+
let spawned;
|
|
2309
2156
|
try {
|
|
2310
|
-
|
|
2157
|
+
await routes.versionGate.ensure(started);
|
|
2158
|
+
assertIgnoreFilesExist(indexArgs, assertAbsoluteRoot(indexArgs.root, started), started);
|
|
2159
|
+
const built = buildIndexCommand(indexArgs, embedding, started, readClientMode(config, started), allowRemoteEmbedding(config));
|
|
2160
|
+
const env = zgEnv(config);
|
|
2161
|
+
const spec = host.shell.resolve({
|
|
2162
|
+
command: built.command,
|
|
2163
|
+
workdir: built.workdir,
|
|
2164
|
+
onExpiry: "none",
|
|
2165
|
+
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
2166
|
+
...env ? { env } : {}
|
|
2167
|
+
});
|
|
2168
|
+
spawned = {
|
|
2169
|
+
proc: await host.shell.execute(spec),
|
|
2170
|
+
command: built.command
|
|
2171
|
+
};
|
|
2311
2172
|
} catch (error) {
|
|
2312
2173
|
return {
|
|
2313
|
-
|
|
2314
|
-
|
|
2174
|
+
error: fill(started.endpointStartFailed, { reason: errorText(error) }),
|
|
2175
|
+
status: 500
|
|
2315
2176
|
};
|
|
2316
2177
|
}
|
|
2317
|
-
|
|
2318
|
-
allowed: true,
|
|
2319
|
-
root: resolved,
|
|
2320
|
-
question: void 0
|
|
2321
|
-
};
|
|
2322
|
-
if (cwd !== void 0 && pathsRelated(resolved, cwd, messages)) return {
|
|
2323
|
-
allowed: true,
|
|
2324
|
-
root: resolved,
|
|
2325
|
-
question: {
|
|
2326
|
-
root: resolved,
|
|
2327
|
-
cwd
|
|
2328
|
-
}
|
|
2329
|
-
};
|
|
2330
|
-
return {
|
|
2331
|
-
allowed: false,
|
|
2332
|
-
reason: fill(messages.rootNotAuthorized, {
|
|
2333
|
-
root: resolved,
|
|
2334
|
-
cwd: cwd ?? messages.rootNoSession
|
|
2335
|
-
})
|
|
2336
|
-
};
|
|
2337
|
-
}
|
|
2338
|
-
/** 工具入参的 root:过 root 判据,放行后登记进白名单(一处三工具共用)。 */
|
|
2339
|
-
function rootOf(args, exec, messages, ledger) {
|
|
2340
|
-
const decision = judgeRoot(args["root"], sessionHeaderCwd(exec), messages, ledger);
|
|
2341
|
-
if (!decision.allowed) throw new Error(decision.reason);
|
|
2342
|
-
ledger.add(decision.root);
|
|
2343
|
-
return decision.root;
|
|
2344
|
-
}
|
|
2345
|
-
function define(host, spec) {
|
|
2346
|
-
const { parameters } = spec;
|
|
2347
|
-
const required = Array.isArray(parameters["required"]) ? parameters["required"].filter((item) => typeof item === "string") : [];
|
|
2348
|
-
host.tools.register({
|
|
2349
|
-
name: spec.name,
|
|
2350
|
-
description: spec.description,
|
|
2351
|
-
parameters,
|
|
2352
|
-
output: {
|
|
2353
|
-
schema: TEXT_OUTPUT_SCHEMA,
|
|
2354
|
-
render: (_args, value) => textBlock(value)
|
|
2355
|
-
},
|
|
2356
|
-
execute: async (rawArgs, exec) => {
|
|
2357
|
-
const messages = spec.messages();
|
|
2358
|
-
if (!isRecord(rawArgs)) throw new Error(fill(messages.argsMustBeObject, {
|
|
2359
|
-
name: spec.name,
|
|
2360
|
-
received: rawArgs === null ? "null" : typeof rawArgs
|
|
2361
|
-
}));
|
|
2362
|
-
const missing = required.filter((fieldName) => rawArgs[fieldName] === void 0);
|
|
2363
|
-
if (missing.length > 0) throw new Error(fill(messages.missingRequiredArgs, {
|
|
2364
|
-
name: spec.name,
|
|
2365
|
-
fields: missing.join(", ")
|
|
2366
|
-
}));
|
|
2367
|
-
return await spec.run(rawArgs, exec, messages);
|
|
2368
|
-
}
|
|
2369
|
-
});
|
|
2370
|
-
}
|
|
2371
|
-
/** 隐式命名空间与 loader 行 config 共用同一 schema(单源,防漂移)。
|
|
2372
|
-
* 值名退避为 configSchema:避免与同名 interface Config 触发 no-redeclare;
|
|
2373
|
-
* 外部仍以 `Config` 名导入(export as),公开 API 不变。
|
|
2374
|
-
*
|
|
2375
|
-
* 0.1.7 迁移要点(两处都是静默失效,写错不报错):
|
|
2376
|
-
* - `.volatile()` 决定字段是否进设置表单。宿主 `describe()` 只投影 volatile 字段
|
|
2377
|
-
* (packages/settings/settings/src/schema.ts 的 volatileForm),全漏标则整条被跳过
|
|
2378
|
-
* (settings/src/index.ts 里 `volatileForm(schema)` 空判即 `return []` 的那一处)、写入抛
|
|
2379
|
-
* `has no volatile fields`(同文件的那句 throw)。
|
|
2380
|
-
* - `settings.register(ns, schema, { base })` 的「底座」层已被宿主移除:内置默认逐字段
|
|
2381
|
-
* 落成下面的 `.default()`(原 BUILTIN_BASE 原样搬来,单一来源),cordis 装载期按同一
|
|
2382
|
-
* 份 schema 校验行 config 并填默认,再把 volatile 字段包成引用交给 apply。
|
|
2383
|
-
* 六个 volatile 字段全是本卡的可编辑项,一个都不该漏;四个非 volatile 部署值
|
|
2384
|
-
* (超时三项 + stdout 上限)只走行 config,标 volatile 反而会把它们变成设置卡项。 */
|
|
2385
|
-
const configSchema = Schema.object({
|
|
2386
|
-
defaultEmbedding: Schema.string().default(DEFAULT_EMBEDDING).volatile(),
|
|
2387
|
-
defaultLimit: Schema.natural().min(1).max(50).default(10).volatile(),
|
|
2388
|
-
hfEndpoint: Schema.string().default("https://modelscope.cn/models").volatile(),
|
|
2389
|
-
enforceSearchFirst: Schema.boolean().default(true).volatile(),
|
|
2390
|
-
grepBudgetPerSearch: Schema.natural().min(1).max(20).default(3).volatile(),
|
|
2391
|
-
unlockWindowMin: Schema.natural().min(1).max(240).default(10).volatile(),
|
|
2392
|
-
searchTimeoutMs: Schema.natural().min(1).default(SEARCH_TIMEOUT_MS),
|
|
2393
|
-
statusTimeoutMs: Schema.natural().min(1).default(STATUS_TIMEOUT_MS),
|
|
2394
|
-
indexTimeoutMs: Schema.natural().min(1).default(INDEX_TIMEOUT_MS),
|
|
2395
|
-
stdoutMaxBytes: Schema.natural().min(1).default(STDOUT_MAX_BYTES),
|
|
2396
|
-
clientMode: Schema.union([
|
|
2397
|
-
"auto",
|
|
2398
|
-
"direct",
|
|
2399
|
-
"server"
|
|
2400
|
-
]).default(DEFAULT_CLIENT_MODE),
|
|
2401
|
-
rebuildWaitMs: Schema.natural().min(1).default(REBUILD_WAIT_MS),
|
|
2402
|
-
allowRemoteEmbedding: Schema.boolean().default(false),
|
|
2403
|
-
remoteEmbeddingEndpoint: Schema.string().default(""),
|
|
2404
|
-
remoteEmbeddingApiKeyFrom: Schema.string().default(""),
|
|
2405
|
-
requireApprovalForExplicitRoot: Schema.boolean().default(false)
|
|
2406
|
-
});
|
|
2407
|
-
/** 官方注册表里本包作业的 kind;宿主据此发出的 id 形如 `zvec-grep-rebuild-N`。 */
|
|
2408
|
-
const REBUILD_JOB_KIND = "zvec-grep-rebuild";
|
|
2409
|
-
/**
|
|
2410
|
-
* 本 kind 在注册表里的**已落定**记录上限:每次 start 前先剪到 `MAX-1` 条,新那条落定后
|
|
2411
|
-
* 正好 `MAX` 条在册(文案与卡片 404 提示都按这个数说)。同时能跑几个不在这里——那是
|
|
2412
|
-
* 注册表的容量闸(实测未拥有桶 10,满员是**拒绝**新 start,不是淘汰旧的)。官方件**不会**
|
|
2413
|
-
* 自行回收落定记录("A settled record stays listed until its owner's disposal, service
|
|
2414
|
-
* disposal, or an explicit remove"),而注册表又随宿主活着、不随本插件卸载而死 ⇒ 这条
|
|
2415
|
-
* 裁剪是本包的责任。注意它只管历史窗口:**同时能跑几个**由注册表的容量说了算
|
|
2416
|
-
* (实测默认 10,且超限是**拒绝**,不是替我们杀在跑的任务)。
|
|
2417
|
-
*/
|
|
2418
|
-
const REBUILD_HISTORY_MAX = 10;
|
|
2419
|
-
/** 卡片视图的尾部长度(打标文案在 lib/messages.ts,随语言走)。 */
|
|
2420
|
-
const JOB_OUT_VIEW_CHARS = 4e3;
|
|
2421
|
-
/** 从名册投影推导身份证(官方 `JobView` 的三段稳定事实)。 */
|
|
2422
|
-
function identityOf(view) {
|
|
2423
|
-
return {
|
|
2424
|
-
kind: view.kind,
|
|
2425
|
-
label: view.label,
|
|
2426
|
-
startedAt: view.startedAt
|
|
2427
|
-
};
|
|
2428
|
-
}
|
|
2429
|
-
/** 两段身份证是否同一回事(三段全同才算)。 */
|
|
2430
|
-
function sameIdentity(left, right) {
|
|
2431
|
-
return left.kind === right.kind && left.label === right.label && left.startedAt === right.startedAt;
|
|
2178
|
+
return spawned;
|
|
2432
2179
|
}
|
|
2433
2180
|
/**
|
|
2434
|
-
*
|
|
2435
|
-
*
|
|
2436
|
-
* `startedAt` 由官方签发(`Date.now()`,永不为 0),而 kind/label 在 `start` 之前就已
|
|
2437
|
-
* 已知——那正是本包递给官方的那份规格。于是"start 的同步块里就跑到了 `run()`"那一档读取
|
|
2438
|
-
* (官方 `start` 会同步跑第一拍)比对时必然落到"对不上":那一刻还没有可比的出生时刻,
|
|
2439
|
-
* 不该把同 id 的另一条作业当成自己的收走。
|
|
2440
|
-
*/
|
|
2441
|
-
const UNSIGNED_STARTED_AT = 0;
|
|
2442
|
-
/**
|
|
2443
|
-
* 名册里那条 id 是不是**我们**的那条作业。
|
|
2181
|
+
* 把起来的那条进程登记进官方注册表与本包侧表,交回宿主签发的 id。
|
|
2444
2182
|
*
|
|
2445
|
-
*
|
|
2446
|
-
*
|
|
2447
|
-
*
|
|
2448
|
-
* @param
|
|
2449
|
-
* @
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
}
|
|
2454
|
-
/** 终止重建进程:kill 异常忽略(进程可能已自然退出/已被回收)。 */
|
|
2455
|
-
function killProc(proc) {
|
|
2456
|
-
try {
|
|
2457
|
-
proc.kill();
|
|
2458
|
-
} catch {}
|
|
2459
|
-
}
|
|
2460
|
-
/**
|
|
2461
|
-
* 本包作业的输出面:官方 pull source,stdout/stderr 各一只游标,外加一层"读失败不许
|
|
2462
|
-
* 拖垮泵"的兜。选 pull 而不是生产者 push(`JobHandle.append`)是复核
|
|
2463
|
-
* 后按实测定下的:
|
|
2464
|
-
* - `proc.observed[*].readFrom` 是**非消费**的独立观察者面(installed dsh-shell
|
|
2465
|
-
* types.d.ts:"without stealing bytes from `readOutput`"),与本包前台用的
|
|
2466
|
-
* 消费式游标互不干扰——此前本仓写的"官方泵会与 readOutput 争同一份游标"是错的;
|
|
2467
|
-
* - 泵按注册表自己的节拍跑(实测默认 150ms,落定前再排最后一次)⇒ **卡片关着环也前进**,
|
|
2468
|
-
* 模型侧 job_output 随时看得见进度;push 形态把可见性绑在了轮询上。
|
|
2469
|
-
* @param proc 后台进程句柄
|
|
2470
|
-
* @param state 这条重建的状态盒(见 {@link RebuildState})
|
|
2471
|
-
* @returns 交给 JobSpec.output 的两条源
|
|
2183
|
+
* 三种失败(注册表换人 / 同名不同命 / start 抛错)都**先把那条进程杀掉**再交回错误:
|
|
2184
|
+
* 此刻作业没进名册,没人能通过 job 工具收它,不杀就是一条孤儿 zg 占着这棵树的写锁。
|
|
2185
|
+
* 同样地,本函数不释放占位——那件事由调用方做。
|
|
2186
|
+
* @param routes 本次注册的共享依赖(jobsOf 现读、侧表引用)
|
|
2187
|
+
* @param root 已过前置校验的工作区(写进侧表供卡片回显)
|
|
2188
|
+
* @param started 本次请求语言的文案表
|
|
2189
|
+
* @param spawned spawnIndexWrite 交回的进程与命令
|
|
2190
|
+
* @returns 宿主签发的 `{ jobId }`;失败为 `{ error, status }`
|
|
2472
2191
|
*/
|
|
2473
|
-
function
|
|
2474
|
-
|
|
2475
|
-
|
|
2192
|
+
function attachIndexWrite(routes, root, started, spawned) {
|
|
2193
|
+
const { jobsOf, records } = routes;
|
|
2194
|
+
const { proc, command } = spawned;
|
|
2195
|
+
const starting = jobsOf();
|
|
2196
|
+
if (starting === void 0) {
|
|
2197
|
+
killProc(proc);
|
|
2476
2198
|
return {
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
if (failed) return {
|
|
2480
|
-
text: "",
|
|
2481
|
-
nextOffset: fromByte,
|
|
2482
|
-
lossy: true
|
|
2483
|
-
};
|
|
2484
|
-
try {
|
|
2485
|
-
const read = proc.observed[channel].readFrom(fromByte);
|
|
2486
|
-
if (read.lossy) state.lost = true;
|
|
2487
|
-
return read;
|
|
2488
|
-
} catch {
|
|
2489
|
-
state.lost = true;
|
|
2490
|
-
failed = true;
|
|
2491
|
-
return {
|
|
2492
|
-
text: "",
|
|
2493
|
-
nextOffset: fromByte,
|
|
2494
|
-
lossy: true
|
|
2495
|
-
};
|
|
2496
|
-
}
|
|
2497
|
-
}
|
|
2199
|
+
error: started.endpointJobsUnavailable,
|
|
2200
|
+
status: 503
|
|
2498
2201
|
};
|
|
2499
|
-
});
|
|
2500
|
-
}
|
|
2501
|
-
/** 官方件对未知/已淘汰 id 抛错;本包的判据要的是"有没有",不是异常(无 ⇒ null)。 */
|
|
2502
|
-
function jobView(jobs, id) {
|
|
2503
|
-
try {
|
|
2504
|
-
return jobs.get(id);
|
|
2505
|
-
} catch {
|
|
2506
|
-
return null;
|
|
2507
2202
|
}
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2203
|
+
pruneRebuildHistory(starting, records);
|
|
2204
|
+
const state = {
|
|
2205
|
+
identity: {
|
|
2206
|
+
kind: REBUILD_JOB_KIND,
|
|
2207
|
+
label: command,
|
|
2208
|
+
startedAt: UNSIGNED_STARTED_AT
|
|
2209
|
+
},
|
|
2210
|
+
lost: false,
|
|
2211
|
+
timeoutNote: null
|
|
2212
|
+
};
|
|
2213
|
+
let jobId;
|
|
2511
2214
|
try {
|
|
2215
|
+
jobId = startUnderController(starting, rebuildJobSpec(routes, proc, state, command, root));
|
|
2216
|
+
state.identity = identityOf(starting.get(jobId));
|
|
2217
|
+
records.set(jobId, {
|
|
2218
|
+
proc,
|
|
2219
|
+
root,
|
|
2220
|
+
id: jobId,
|
|
2221
|
+
state
|
|
2222
|
+
});
|
|
2223
|
+
} catch (error) {
|
|
2224
|
+
killProc(proc);
|
|
2512
2225
|
return {
|
|
2513
|
-
|
|
2514
|
-
|
|
2226
|
+
error: startupFailureText(error, started),
|
|
2227
|
+
status: 500
|
|
2515
2228
|
};
|
|
2516
|
-
} catch {
|
|
2517
|
-
return null;
|
|
2518
2229
|
}
|
|
2519
|
-
}
|
|
2520
|
-
/** 官方 JobStatus 里"仍在跑"的两枚:`stopping` 是取消已发出、进程还没收完。 */
|
|
2521
|
-
function isLiveStatus(status) {
|
|
2522
|
-
return status === "running" || status === "stopping";
|
|
2230
|
+
return { jobId };
|
|
2523
2231
|
}
|
|
2524
2232
|
/**
|
|
2525
|
-
*
|
|
2526
|
-
*
|
|
2527
|
-
* 剪到**只剩 `MAX-1` 条**才是对的:这一剪发生在 start 之前,紧接着就有一条新作业进来,
|
|
2528
|
-
* 它落定之后名册里正好是最近 `MAX` 条已落定记录 ⇒ 与卡片文案「只保留最近 10 条已结束的重建」
|
|
2529
|
-
* 同一口径。剪到 `MAX` 条会让册子在任何时刻都有 `MAX+1` 条已结束记录(实测 11 条),
|
|
2530
|
-
* 最初把这条判反了(只看剪完那一刻的 9 条),后来回退。
|
|
2531
|
-
* 在跑的一条不动——官方件对超额的答法是拒绝 start(实测),不是替我们杀任务,
|
|
2532
|
-
* 这里跟着杀等于把"用户的重建被静默终止"重新发明一遍。
|
|
2533
|
-
* 侧表里没有的 id(上一次 apply 卸载后残留的记录)同样要能清掉,所以遍历的是
|
|
2534
|
-
* `list()` 而不是 `records`。
|
|
2535
|
-
* @param jobs 官方注册表
|
|
2536
|
-
* @param records 本包侧表(被淘汰记录同步删掉)
|
|
2233
|
+
* 卸载效应的收口:把侧表里的进程与在册作业收干净。
|
|
2234
|
+
* @param deps 本次注册的共享依赖(jobsOf 现读、侧表引用、文案现取)
|
|
2537
2235
|
* @returns {void}
|
|
2538
2236
|
*/
|
|
2539
|
-
function
|
|
2540
|
-
const
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2237
|
+
function releaseRebuildRecords(deps) {
|
|
2238
|
+
const { jobsOf, messages, records } = deps;
|
|
2239
|
+
const unloadReason = messages().jobReasonUnload;
|
|
2240
|
+
const jobs = jobsOf();
|
|
2241
|
+
if (jobs === void 0) for (const record of records.values()) killProc(record.proc);
|
|
2242
|
+
else for (const record of records.values()) {
|
|
2243
|
+
const view = jobView(jobs, record.id);
|
|
2244
|
+
if (view === null || !sameJob(record.state, view)) killProc(record.proc);
|
|
2245
|
+
else if (isLiveStatus(view.status)) jobs.kill(record.id, void 0, unloadReason);
|
|
2246
|
+
else jobs.remove(record.id);
|
|
2544
2247
|
}
|
|
2248
|
+
records.clear();
|
|
2545
2249
|
}
|
|
2546
2250
|
/**
|
|
2547
|
-
*
|
|
2548
|
-
* owner (limit: 10)`)。认不出来 ⇒ undefined,调用方退回通用的启动失败文案。
|
|
2549
|
-
* 为什么单独认这一条:它是本包唯一会把宿主英文原话插进中文卡片的错误,又恰恰最该翻成
|
|
2550
|
-
* 人话的那一条——用户此时要做的是去 job_list 里收掉不需要的作业,而不是读一句英文。
|
|
2551
|
-
*/
|
|
2552
|
-
function capacityLimitOf(error) {
|
|
2553
|
-
return /\(limit: (?<limit>\d+)\)/u.exec(errorText(error))?.groups?.["limit"];
|
|
2554
|
-
}
|
|
2555
|
-
/**
|
|
2556
|
-
* 「工作区重建」动作端点的四道前置校验:绝对路径 + 归一化、本 daemon 观测过的白名单、
|
|
2557
|
-
* 目录此刻仍存在。不过就把错误就地答完并返回 undefined(错误文本全走双语字典)。
|
|
2251
|
+
* 设置卡片「工作区重建」的读面(引导 / 启动 / 轮询三个方法)。
|
|
2558
2252
|
*
|
|
2559
|
-
*
|
|
2560
|
-
*
|
|
2561
|
-
*
|
|
2562
|
-
*
|
|
2563
|
-
*
|
|
2564
|
-
*
|
|
2565
|
-
*
|
|
2566
|
-
*
|
|
2253
|
+
* ⚠ 服务在**构造时**注册(cordis `Service` 的契约:`ctx.reflect.provide`,随所属 fiber
|
|
2254
|
+
* 卸载自动撤),所以调用方拿实例没有任何用处——装入口 `installRebuildRemote` 说明了这一点。
|
|
2255
|
+
*
|
|
2256
|
+
* ⚠ `jobsOf` 必须每次用时现读,不在闭包里钉住一枚实例。`ctx.get` 是无 inject 语义的存储
|
|
2257
|
+
* 读(官方 reflect.d.ts:"or `undefined` when not (yet) provided",实测读一次就只那一次)——
|
|
2258
|
+
* 在 apply 里读会把两种正常事件变成永久故障:服务比本插件晚到位 ⇒ 启动从此一直回答不可用
|
|
2259
|
+
* (还指着用户去装一个其实装好了的包);服务被重载 ⇒ 从此往一枚已销毁的实例里起作业。
|
|
2260
|
+
* 本包也不把 `jobs` 列进 `inject` 名单:那会让缺席的整条 client 入口都不激活,而缺席只该让
|
|
2261
|
+
* 「启动/轮询」这一档不可用。
|
|
2567
2262
|
*/
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
sendJson(res, 400, {
|
|
2574
|
-
ok: false,
|
|
2575
|
-
error: fill(started.endpointRootInvalid, { reason: errorText(error) })
|
|
2576
|
-
});
|
|
2577
|
-
return null;
|
|
2263
|
+
var ZvecRebuildService = class extends TypertRemoteService {
|
|
2264
|
+
deps;
|
|
2265
|
+
constructor(ctx, deps) {
|
|
2266
|
+
super(ctx, REBUILD_REMOTE_NAMESPACE);
|
|
2267
|
+
this.deps = deps;
|
|
2578
2268
|
}
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
2269
|
+
/** 引导读面:白名单里的工作区 + 守护进程就绪态(都是本插件自己的数据)。 */
|
|
2270
|
+
async roots() {
|
|
2271
|
+
const serverReady = await this.deps.serverGate.ready();
|
|
2272
|
+
return {
|
|
2273
|
+
roots: this.deps.ledger.list(),
|
|
2274
|
+
serverReady
|
|
2275
|
+
};
|
|
2585
2276
|
}
|
|
2586
|
-
|
|
2587
|
-
|
|
2277
|
+
/**
|
|
2278
|
+
* 起一条重建(或跟随同根已在跑的那条)。
|
|
2279
|
+
*
|
|
2280
|
+
* 占位是**互斥的唯一依据**,必须落在第一个 await 之前。先「查在不在跑」再占位,
|
|
2281
|
+
* 两次并发点击会同时通过那次查询、各自 spawn——两个进程在同一份索引上互相啃,
|
|
2282
|
+
* 后一条被 zg 的写锁直接顶掉并报成「启动失败」。改成「先占位、抢不到就跟随」,
|
|
2283
|
+
* 这条竞态就没有窗口了。
|
|
2284
|
+
*/
|
|
2285
|
+
async rebuild(request) {
|
|
2286
|
+
const started = this.deps.messages();
|
|
2287
|
+
const accepted = acceptableRoot(isRecord(request) ? request.root : void 0, this.deps.ledger, started);
|
|
2288
|
+
if ("error" in accepted) return {
|
|
2588
2289
|
ok: false,
|
|
2589
|
-
error:
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
const
|
|
2612
|
-
|
|
2613
|
-
|
|
2614
|
-
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2290
|
+
error: accepted.error.value,
|
|
2291
|
+
status: accepted.error.status
|
|
2292
|
+
};
|
|
2293
|
+
const { root } = accepted;
|
|
2294
|
+
const jobs = this.deps.jobsOf();
|
|
2295
|
+
if (jobs === void 0) return {
|
|
2296
|
+
ok: false,
|
|
2297
|
+
error: started.endpointJobsUnavailable,
|
|
2298
|
+
status: 503
|
|
2299
|
+
};
|
|
2300
|
+
if (this.deps.rebuilds.claim(root, "card") === null) {
|
|
2301
|
+
const following = followRunningRebuild(jobs, this.deps.records, root);
|
|
2302
|
+
return following === void 0 ? {
|
|
2303
|
+
ok: false,
|
|
2304
|
+
error: started.endpointRebuildInFlight,
|
|
2305
|
+
status: 409
|
|
2306
|
+
} : {
|
|
2307
|
+
ok: true,
|
|
2308
|
+
jobId: following,
|
|
2309
|
+
reused: true
|
|
2310
|
+
};
|
|
2311
|
+
}
|
|
2312
|
+
const embedding = readDefaultEmbedding(this.deps.config);
|
|
2313
|
+
const spawned = await spawnIndexWrite(this.deps, started, {
|
|
2314
|
+
root,
|
|
2315
|
+
embedding,
|
|
2316
|
+
rebuild: true
|
|
2317
|
+
}, embedding);
|
|
2318
|
+
if ("error" in spawned) {
|
|
2319
|
+
this.deps.rebuilds.release(root);
|
|
2320
|
+
return {
|
|
2321
|
+
ok: false,
|
|
2322
|
+
error: spawned.error,
|
|
2323
|
+
status: spawned.status
|
|
2324
|
+
};
|
|
2325
|
+
}
|
|
2326
|
+
const attached = attachIndexWrite(this.deps, root, started, spawned);
|
|
2327
|
+
if ("error" in attached) {
|
|
2328
|
+
this.deps.rebuilds.release(root);
|
|
2329
|
+
return {
|
|
2330
|
+
ok: false,
|
|
2331
|
+
error: attached.error,
|
|
2332
|
+
status: attached.status
|
|
2333
|
+
};
|
|
2334
|
+
}
|
|
2335
|
+
this.deps.rebuilds.attach(root, attached.jobId);
|
|
2336
|
+
return {
|
|
2337
|
+
ok: true,
|
|
2338
|
+
jobId: attached.jobId
|
|
2339
|
+
};
|
|
2340
|
+
}
|
|
2341
|
+
/**
|
|
2342
|
+
* 轮询读面:官方状态投影 + 退出码/沙箱事实 + 打标后的输出尾窗(卡片每 2s 敲一次)。
|
|
2343
|
+
*
|
|
2344
|
+
* 侧表就是这条投影的授权边界:官方 id 是可预测的 `<kind>-<hex>`(宿主 bash 工具的
|
|
2345
|
+
* `bash-1` 同样猜得到),而它不在本包表里 ⇒ 一律拒绝,绝不代读别人的作业。
|
|
2346
|
+
*/
|
|
2347
|
+
status(request) {
|
|
2348
|
+
const marks = this.deps.messages();
|
|
2349
|
+
const raw = isRecord(request) ? request.jobId : void 0;
|
|
2350
|
+
const record = typeof raw === "string" && raw.length > 0 ? this.deps.records.get(raw) : void 0;
|
|
2351
|
+
if (record === void 0) return {
|
|
2352
|
+
ok: false,
|
|
2353
|
+
error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX }),
|
|
2354
|
+
status: 404
|
|
2355
|
+
};
|
|
2356
|
+
const jobs = this.deps.jobsOf();
|
|
2357
|
+
if (jobs === void 0) return {
|
|
2358
|
+
ok: false,
|
|
2359
|
+
error: marks.endpointJobsUnavailable,
|
|
2360
|
+
status: 503
|
|
2361
|
+
};
|
|
2362
|
+
const output = readRebuildOutput(jobs, record.id);
|
|
2363
|
+
if (output === null) return {
|
|
2364
|
+
ok: false,
|
|
2365
|
+
error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX }),
|
|
2366
|
+
status: 404
|
|
2367
|
+
};
|
|
2368
|
+
if (!sameJob(record.state, output.view)) return {
|
|
2369
|
+
ok: false,
|
|
2370
|
+
error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX }),
|
|
2371
|
+
status: 404
|
|
2372
|
+
};
|
|
2373
|
+
const { view, retained } = output;
|
|
2374
|
+
const text = retained.chunks.map((chunk) => chunk.text).join("");
|
|
2375
|
+
const shown = truncateStart(text, JOB_OUT_VIEW_CHARS);
|
|
2376
|
+
const viewMark = text.length > JOB_OUT_VIEW_CHARS ? fill(marks.jobOutputView, {
|
|
2377
|
+
shown: JOB_OUT_VIEW_CHARS,
|
|
2378
|
+
total: text.length
|
|
2379
|
+
}) : "";
|
|
2380
|
+
return {
|
|
2381
|
+
ok: true,
|
|
2382
|
+
status: view.status,
|
|
2383
|
+
exitCode: record.proc.exitCode,
|
|
2384
|
+
root: record.root,
|
|
2385
|
+
...record.proc.sandbox === void 0 ? {} : { sandbox: record.proc.sandbox },
|
|
2386
|
+
output: (view.output.earliest > 0 ? marks.jobOutputTruncated : "") + (record.state.lost ? marks.jobOutputLost : "") + (record.state.timeoutNote ?? "") + (procSandboxNote(record.proc, marks) ?? "") + viewMark + shown
|
|
2387
|
+
};
|
|
2388
|
+
}
|
|
2389
|
+
};
|
|
2390
|
+
/**
|
|
2391
|
+
* 标准装饰器的**程序化调用**:`@Remote` 的全部作用就是往类原型写一枚描述符,而标准装饰器
|
|
2392
|
+
* 语法需要一条 tsc 降级管线(本仓的测试/构建解析器都不降级它)。这里直接按 TC39 的
|
|
2393
|
+
* `ClassMethodDecoratorContext` 形状调同一个 decorator 函数,把标记落到真正的原型上,
|
|
2394
|
+
* 于是源码里不再需要装饰器语法,构建与测试都不必再挂那枚预转换插件。
|
|
2395
|
+
*/
|
|
2396
|
+
function markRemote(prototype, methodName) {
|
|
2397
|
+
const context = {
|
|
2398
|
+
kind: "method",
|
|
2399
|
+
name: methodName,
|
|
2400
|
+
static: false,
|
|
2401
|
+
private: false,
|
|
2402
|
+
addInitializer: (initializer) => {
|
|
2403
|
+
Reflect.apply(initializer, Object.create(prototype), []);
|
|
2404
|
+
}
|
|
2405
|
+
};
|
|
2406
|
+
const decorate = Remote(methodName);
|
|
2407
|
+
Reflect.apply(decorate, void 0, [Reflect.get(prototype, methodName), context]);
|
|
2621
2408
|
}
|
|
2409
|
+
markRemote(ZvecRebuildService.prototype, "roots");
|
|
2410
|
+
markRemote(ZvecRebuildService.prototype, "rebuild");
|
|
2411
|
+
markRemote(ZvecRebuildService.prototype, "status");
|
|
2622
2412
|
/**
|
|
2623
|
-
* 把「起一条 zg 失败」的原因翻成卡片文案。
|
|
2624
2413
|
*
|
|
2625
|
-
*
|
|
2626
|
-
*
|
|
2627
|
-
*
|
|
2414
|
+
* 为什么是一枚函数而不是让调用方直接 `new`:这枚 `new` 的**全部意义在构造期的注册副作用**
|
|
2415
|
+
* 上——实例由 cordis 的 fiber 持有(`Service` 基类把 `reflect.provide` 的 disposer 挂给
|
|
2416
|
+
* fiber),调用方拿到它没有任何用处。卸载效应也在这里登记:侧表里的进程与在册作业必须
|
|
2417
|
+
* 随本插件一起收干净。
|
|
2628
2418
|
*
|
|
2629
|
-
*
|
|
2630
|
-
*
|
|
2631
|
-
* @param error 官方件(或本包 starter)抛出的原因
|
|
2632
|
-
* @param started 本次请求语言的文案表
|
|
2633
|
-
* @returns 可直接进响应体的错误文案
|
|
2419
|
+
* @param ctx - 宿主上下文
|
|
2420
|
+
* @param deps - 重建读面的全部依赖(见 ZvecRebuildDeps)
|
|
2634
2421
|
*/
|
|
2635
|
-
function
|
|
2636
|
-
|
|
2637
|
-
|
|
2422
|
+
function installRebuildRemote(ctx, deps) {
|
|
2423
|
+
if (!isRecord(ctx) || !isRecord(ctx.reflect) || typeof ctx.reflect.provide !== "function") return false;
|
|
2424
|
+
new ZvecRebuildService(ctx, deps);
|
|
2425
|
+
ctx.effect(() => () => {
|
|
2426
|
+
releaseRebuildRecords(deps);
|
|
2427
|
+
}, "zvec-grep: rebuild records");
|
|
2428
|
+
return true;
|
|
2429
|
+
}
|
|
2430
|
+
//#endregion
|
|
2431
|
+
//#region host.ts
|
|
2432
|
+
const SEARCH_TIMEOUT_MS = 3e5;
|
|
2433
|
+
const STATUS_TIMEOUT_MS = 6e4;
|
|
2434
|
+
const INDEX_TIMEOUT_MS = 6e5;
|
|
2435
|
+
const STDOUT_MAX_BYTES = 4e5;
|
|
2436
|
+
/** 检索等待同根重建落定的上限(ms)。部署值:大型工作区的重建可能跑很久,
|
|
2437
|
+
* 但也不该让一次检索无限期挂着。 */
|
|
2438
|
+
const REBUILD_WAIT_MS = 12e4;
|
|
2439
|
+
/** 工作区白名单容量:超过按最近使用淘汰最冷的一条(常驻进程内存有界)。 */
|
|
2440
|
+
const MAX_LEDGER_ROOTS = 64;
|
|
2441
|
+
/**
|
|
2442
|
+
* 白名单条目的有效期:多久没被提到就当它不再活跃。一天足够覆盖「今天开过的会话」,
|
|
2443
|
+
* 又不会让一个月前随手开过的一个目录一直占着名额。
|
|
2444
|
+
*/
|
|
2445
|
+
const LEDGER_TTL_MS = 864e5;
|
|
2446
|
+
/** 成功执行里回显 stderr 的尾部长度(降级提示常就在这一行)。 */
|
|
2447
|
+
const STDERR_NOTE_CHARS = 400;
|
|
2448
|
+
/** 具名方法在位(typeof 函数)——只看 `typeof x === "object"` 会放过 null、
|
|
2449
|
+
* 也会放过「是个对象但没注册方法」的错注入。 */
|
|
2450
|
+
function hasMethod(value, name, keys) {
|
|
2451
|
+
const member = value[name];
|
|
2452
|
+
return isRecord(member) && keys.every((key) => typeof member[key] === "function");
|
|
2638
2453
|
}
|
|
2639
2454
|
/**
|
|
2640
|
-
*
|
|
2455
|
+
* host 是否为本插件所需服务面:五个注入面都必须是**带相应方法的对象**,
|
|
2456
|
+
* 且 `get` 可调用。守卫失败即 apply 抛错(fail-fast),比运行到某次工具调用
|
|
2457
|
+
* 才 `undefined is not a function` 更早、更可诊断。
|
|
2641
2458
|
*
|
|
2642
|
-
*
|
|
2643
|
-
*
|
|
2644
|
-
*
|
|
2645
|
-
*
|
|
2646
|
-
* 实测挂上即放行、摘掉即恢复拒绝、可反复,而 global 层的 controller 只被 `servesOwner`
|
|
2647
|
-
* 读(installed dsh-jobs-local 全文只有那一处消费),作业的后续(read/kill/落定)都不
|
|
2648
|
-
* 依赖它。留一枚常驻 token 等于在"宿主故意没装 job 工具"的组成里替全宿主开着那道闸门——
|
|
2649
|
-
* 官方契约写的是"生产者不能起一台 owner 收不掉、停不掉的作业",常驻就是把它反过来做。
|
|
2459
|
+
* settings 只探 `describe`:0.1.7 起那是本包唯一**直接调**的 settings 方法
|
|
2460
|
+
* (跨命名空间读 locale)。`configure` 经 `ctx.inject` 的子上下文才拿到,
|
|
2461
|
+
* `mutate` 本包 host 侧根本不用(写是卡片经 settingsScope 走 client 面)——
|
|
2462
|
+
* 探它们等于断言一条没有测试撑着的能力。
|
|
2650
2463
|
*/
|
|
2651
|
-
function
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2464
|
+
function isZvecGrepHost(value) {
|
|
2465
|
+
if (!isRecord(value)) return false;
|
|
2466
|
+
return hasMethod(value, "settings", ["describe"]) && hasMethod(value, "shell", ["resolve", "execute"]) && hasMethod(value, "tools", ["register", "guard"]) && hasMethod(value, "systemPrompt", ["section"]) && hasMethod(value, "timer", ["timeout"]) && typeof value["get"] === "function";
|
|
2467
|
+
}
|
|
2468
|
+
/** 当前会话工作区(root 缺省回退源);非字符串视为缺(读取面见 lib/routing.ts 的 SessionFace)。 */
|
|
2469
|
+
function sessionHeaderCwd(exec) {
|
|
2470
|
+
const raw = exec.agent?.session?.header?.cwd;
|
|
2471
|
+
return typeof raw === "string" && raw.length > 0 ? raw : void 0;
|
|
2658
2472
|
}
|
|
2659
2473
|
/**
|
|
2660
|
-
*
|
|
2661
|
-
*
|
|
2662
|
-
*
|
|
2474
|
+
* JSON.stringify 在本包**拥有的声明**上把返回宽成 `string | undefined`:lib 的签名恒为
|
|
2475
|
+
* `string`,但 ECMA-262 规定入参是 undefined / 函数 / 符号时它返回 undefined(下面
|
|
2476
|
+
* textBlock 的用例就直喂 undefined)。宽化只能落在这里——调用点里 `JSON.stringify(...) ?? x`
|
|
2477
|
+
* 会被 TS 的收窄按声明面判成冗余守卫,而删掉那道具象兜底会把 `{ text: undefined }` 交给官方。
|
|
2663
2478
|
*/
|
|
2664
|
-
function
|
|
2665
|
-
|
|
2666
|
-
if (info === void 0) return null;
|
|
2667
|
-
if (info.runnerFailed === true) return fill(messages.rebuildRunnerFailed, { facts: sandboxFacts(info, messages) });
|
|
2668
|
-
if (info.denied) return fill(messages.rebuildDenied, { denied: deniedNote(info, messages) });
|
|
2669
|
-
return null;
|
|
2479
|
+
function stringifyJson(value) {
|
|
2480
|
+
return JSON.stringify(value, null, 2);
|
|
2670
2481
|
}
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2482
|
+
function textBlock(value) {
|
|
2483
|
+
const { text: textValue } = isRecord(value) ? value : {};
|
|
2484
|
+
if (typeof textValue === "string") return [{
|
|
2485
|
+
type: "text",
|
|
2486
|
+
text: textValue
|
|
2487
|
+
}];
|
|
2488
|
+
let text;
|
|
2674
2489
|
try {
|
|
2675
|
-
|
|
2490
|
+
text = stringifyJson(value) ?? String(value);
|
|
2676
2491
|
} catch {
|
|
2677
|
-
|
|
2492
|
+
try {
|
|
2493
|
+
text = String(value);
|
|
2494
|
+
} catch {
|
|
2495
|
+
text = "[unrenderable value]";
|
|
2496
|
+
}
|
|
2678
2497
|
}
|
|
2679
|
-
return
|
|
2498
|
+
return [{
|
|
2499
|
+
type: "text",
|
|
2500
|
+
text
|
|
2501
|
+
}];
|
|
2680
2502
|
}
|
|
2503
|
+
const TEXT_OUTPUT_SCHEMA = {
|
|
2504
|
+
type: "object",
|
|
2505
|
+
additionalProperties: false,
|
|
2506
|
+
properties: { text: { type: "string" } }
|
|
2507
|
+
};
|
|
2681
2508
|
/**
|
|
2682
|
-
*
|
|
2683
|
-
*
|
|
2684
|
-
*
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2509
|
+
* 沙箱侧的**硬**失败:命令根本没跑起来。
|
|
2510
|
+
* runnerFailed 与 exitCode 无关——runner 在命令执行前就挂了,exit 码是 runner 的,
|
|
2511
|
+
* 拿来判「zg 未安装」是把沙箱故障误报成用户缺二进制。
|
|
2512
|
+
*/
|
|
2513
|
+
function sandboxFailure(result, messages) {
|
|
2514
|
+
const info = result.sandbox;
|
|
2515
|
+
if (info?.runnerFailed !== true) return null;
|
|
2516
|
+
return fill(messages.runnerFailed, { facts: sandboxFacts(info, messages) });
|
|
2517
|
+
}
|
|
2518
|
+
/** 错误详情:首尾各留一段(zg/cargo 等错误的最终原因常在尾部)。
|
|
2519
|
+
* 两半各用一个函数,因为是两种缺陷:头切点会留下孤立**高**代理(`truncateEnd` 丢掉它),
|
|
2520
|
+
* 尾切点会留下孤立**低**代理(`truncateStart` 丢掉它);对调两个函数同样不留孤立代理,
|
|
2521
|
+
* 只是头尾内容掉头 ⇒ 测试里另有一组哨兵断言钉住归属。 */
|
|
2522
|
+
function failureDetail(result, messages) {
|
|
2523
|
+
const raw = result.stderr.text.length > 0 ? result.stderr.text : result.stdout.text;
|
|
2524
|
+
if (raw.length <= 800) return raw;
|
|
2525
|
+
const half = 400;
|
|
2526
|
+
return fill(messages.detailMiddle, {
|
|
2527
|
+
head: truncateEnd(raw, half),
|
|
2528
|
+
tail: truncateStart(raw, half)
|
|
2529
|
+
});
|
|
2530
|
+
}
|
|
2531
|
+
/** 有详情才带前缀拼接(不同句式各有前缀),空详情绝不留孤儿标点。 */
|
|
2532
|
+
function withDetail(detail, prefix) {
|
|
2533
|
+
return detail.length > 0 ? fill(prefix, { detail }) : "";
|
|
2534
|
+
}
|
|
2535
|
+
/**
|
|
2536
|
+
* zg 的结构化失败在 stderr 上以一行 `Code: <CODE>` 交出错误码(上游 `src/cli/errors.ts`),
|
|
2537
|
+
* 本包所有按码归因的判据都读那一行。**缺了这一行**就意味着这次失败没有可机读的码,而上游
|
|
2538
|
+
* 恰好有两类塌法会长这样:不带 `--debug` 时 `MODEL2VEC_DOWNLOAD_FAILED` 与
|
|
2539
|
+
* `INDEXING.FILES_FAILED` 被折成一句无码文案(首次下载 embedding 权重正落在这一档)。
|
|
2540
|
+
* 这里据此补一条可行动的出路,而不是让模型对着「exit=1 + 一句话」猜。
|
|
2692
2541
|
*
|
|
2693
|
-
*
|
|
2694
|
-
*
|
|
2695
|
-
* @param expiresAt 取某条目的过期时刻;无则视为永不过期
|
|
2696
|
-
* @param now 当前时刻(epoch ms)
|
|
2542
|
+
* 空 detail 不补:什么都没打出来时谈不上「上游把原因塌成了一句」,那条指引只会占住回显预算。
|
|
2543
|
+
* 已有 `Code:` 行时也不补:那时归因本就够了。
|
|
2697
2544
|
*/
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
if (expiry !== void 0 && expiry <= now) map.delete(key);
|
|
2702
|
-
}
|
|
2703
|
-
for (const key of map.keys()) {
|
|
2704
|
-
if (map.size <= max) break;
|
|
2705
|
-
map.delete(key);
|
|
2706
|
-
}
|
|
2545
|
+
const STRUCTURED_ERROR_CODE = /^\s*Code:/imu;
|
|
2546
|
+
function noCodeHint(detail, messages) {
|
|
2547
|
+
return detail.length === 0 || STRUCTURED_ERROR_CODE.test(detail) ? "" : `\n${messages.noErrorCodeHint}`;
|
|
2707
2548
|
}
|
|
2708
|
-
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2549
|
+
function shellFailure(result, messages) {
|
|
2550
|
+
const runnerFailure = sandboxFailure(result, messages);
|
|
2551
|
+
if (runnerFailure !== null) return runnerFailure;
|
|
2552
|
+
if (result.timedOut) return messages.timeoutFailure;
|
|
2553
|
+
if (result.aborted) return messages.abortedFailure;
|
|
2554
|
+
if (result.exitCode === 0) return null;
|
|
2555
|
+
const detail = failureDetail(result, messages);
|
|
2556
|
+
const { sandbox } = result;
|
|
2557
|
+
if (sandbox?.denied === true) return fill(messages.deniedFailure, {
|
|
2558
|
+
exit: result.exitCode,
|
|
2559
|
+
denied: deniedNote(sandbox, messages),
|
|
2560
|
+
detail: withDetail(detail, messages.detailPrefix)
|
|
2561
|
+
});
|
|
2562
|
+
if (result.exitCode === 127) return fill(messages.notInstalledFailure, { detail: withDetail(detail, messages.detailPrefix) });
|
|
2563
|
+
return `${fill(messages.genericFailure, {
|
|
2564
|
+
exit: result.exitCode,
|
|
2565
|
+
detail: withDetail(detail, messages.detailColon)
|
|
2566
|
+
})}${noCodeHint(detail, messages)}`;
|
|
2712
2567
|
}
|
|
2713
|
-
/** 探测缓存的 TTL(ms):负向条目(当时无索引)的陈旧上界,选型论证见下。 */
|
|
2714
|
-
const INDEX_PROBE_TTL_MS = 6e4;
|
|
2715
|
-
/** 探测缓存容量(条):guard 一次调用至多探 9 层祖先,32 条覆盖多工作区来回切换。 */
|
|
2716
|
-
const INDEX_PROBE_CACHE_MAX = 32;
|
|
2717
2568
|
/**
|
|
2718
|
-
*
|
|
2719
|
-
* 向上探 9 层 existsSync,同一工作区的连续调用命中的是同一串祖先目录;zg_search 的
|
|
2720
|
-
* 解锁路径也要再走一遍同样的上溯)。
|
|
2569
|
+
* 成功执行的 stderr 里哪些是「进度噪声」、哪些必须交回。
|
|
2721
2570
|
*
|
|
2722
|
-
*
|
|
2723
|
-
*
|
|
2724
|
-
*
|
|
2725
|
-
*
|
|
2726
|
-
* 方向安全,且与「建索引后立刻去搜」的真实节奏相比可忽略。
|
|
2571
|
+
* zg 在**成功**时也往 stderr 写索引进度(非 TTY 下逐行落盘,实测原文:`Scanning files...` /
|
|
2572
|
+
* `Preparing local/potion-code-16m-v2` / `Indexing complete`)。这些行每次建索引都在,写进
|
|
2573
|
+
* 工具回执只是让模型对着同一堆噪声反复读;真正需要它看见的是另一类:降级提示、锁冲突、
|
|
2574
|
+
* 沙箱事实,以及任何本包**不认识**的新增告警。
|
|
2727
2575
|
*
|
|
2728
|
-
*
|
|
2729
|
-
*
|
|
2730
|
-
* 逐分支一致。命中即触摸(delete+set 挪到队尾),配合 trimMapTo 的插入序淘汰 ⇒ LRU。
|
|
2576
|
+
* 所以判据是「只丢认得的进度行,其余全留」,而不是「只留认得的告警」——后者一旦 zg 出了
|
|
2577
|
+
* 新提示就会静默吞掉,那正是最不该发生的失败模式。
|
|
2731
2578
|
*
|
|
2732
|
-
*
|
|
2733
|
-
*
|
|
2734
|
-
*
|
|
2735
|
-
*
|
|
2736
|
-
*
|
|
2579
|
+
* 进度行词表逐条对着上游的进度格式化函数核过(含下载与就绪两档):
|
|
2580
|
+
* Scanning files… / Indexing files… / Indexing complete / Preparing <model> /
|
|
2581
|
+
* Downloading <model> · … / Model ready: <model>
|
|
2582
|
+
* 其中 `Indexing complete` 用**整行相等**匹配,不能用前缀——`Indexing completed with 3 failed
|
|
2583
|
+
* files`(部分文件失败的信号,必须留着)字面上就以它开头。
|
|
2737
2584
|
*/
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2585
|
+
const STDERR_PROGRESS_LINES = /* @__PURE__ */ new Set(["Scanning files...", "Indexing complete"]);
|
|
2586
|
+
/** 该行是否只是进度噪声。`warning` / `Error` / `zvec-grep` 一律不判为噪声。 */
|
|
2587
|
+
function isStderrProgressLine(line) {
|
|
2588
|
+
const trimmed = line.trim();
|
|
2589
|
+
if (STDERR_PROGRESS_LINES.has(trimmed)) return true;
|
|
2590
|
+
return trimmed.startsWith("Indexing files") || trimmed.startsWith("Preparing ") || trimmed.startsWith("Downloading ") || trimmed.startsWith("Model ready: ");
|
|
2591
|
+
}
|
|
2592
|
+
/** 剥掉进度行,留下真正要交回的 stderr(可能为空串)。 */
|
|
2593
|
+
function signalStderr(text) {
|
|
2594
|
+
return text.split("\n").filter((line) => line.trim().length > 0 && !isStderrProgressLine(line)).join("\n");
|
|
2595
|
+
}
|
|
2596
|
+
/**
|
|
2597
|
+
* 成功(exit 0)执行的结果体检:把「其实不完整」的三类事实显式打标,避免模型
|
|
2598
|
+
* 把残缺输出当完整证据用。
|
|
2599
|
+
* 1. stdout 超上限被截尾(可能已落 spill);
|
|
2600
|
+
* 2. 沙箱在执行中拒绝过一次文件操作(zg 仍可 exit 0,但结果少了被拒的部分);
|
|
2601
|
+
* 3. **stderr 去噪之后仍非空**:zg 的降级提示(例如 embedding 模型拉不到 → 退化为
|
|
2602
|
+
* 纯词法兜底、跳过 --refresh)只写在 stderr,旧实现整个丢掉 → 用户把「只有词法
|
|
2603
|
+
* 结果」的检索当语义检索的完整结果。这里回显尾部一段。整段都是索引进度时一句都不加。
|
|
2604
|
+
*/
|
|
2605
|
+
function successNotes(result, messages, stdoutMaxBytes) {
|
|
2606
|
+
const notes = [];
|
|
2607
|
+
if (result.stdout.truncated) {
|
|
2608
|
+
const spill = result.stdout.spillPath === void 0 ? "" : fill(messages.spillNote, { path: result.stdout.spillPath });
|
|
2609
|
+
notes.push(fill(messages.outputTruncated, {
|
|
2610
|
+
maxBytes: stdoutMaxBytes,
|
|
2611
|
+
spill
|
|
2612
|
+
}));
|
|
2613
|
+
}
|
|
2614
|
+
const { sandbox } = result;
|
|
2615
|
+
if (sandbox?.denied === true) notes.push(fill(messages.sandboxWarning, { denied: deniedNote(sandbox, messages) }));
|
|
2616
|
+
const { stderr } = result;
|
|
2617
|
+
const signal = signalStderr(stderr.text);
|
|
2618
|
+
if (signal.length > 0) {
|
|
2619
|
+
const tail = truncateStart(signal, STDERR_NOTE_CHARS);
|
|
2620
|
+
const truncatedMark = stderr.truncated ? "[…]" : "";
|
|
2621
|
+
notes.push(fill(messages.stderrNote, {
|
|
2622
|
+
marked: truncatedMark,
|
|
2623
|
+
tail
|
|
2624
|
+
}));
|
|
2625
|
+
}
|
|
2626
|
+
return notes;
|
|
2627
|
+
}
|
|
2628
|
+
/** 版本探测结果的缓存时长:够长到一次会话里基本只探一次,够短到用户中途升级 zg 也算数。 */
|
|
2629
|
+
const ZG_VERSION_TTL_MS = 6e5;
|
|
2630
|
+
/** 探测自身的超时:`zg --version` 是纯打印,给它检索超时是浪费,也让它卡住主流程。 */
|
|
2631
|
+
const ZG_VERSION_PROBE_TIMEOUT_MS = 1e4;
|
|
2632
|
+
/** 门槛文案:回显实际版本与门槛值,并给出唯一的出路(升级 zvec-grep)。 */
|
|
2633
|
+
function tooOldZgError(actual, messages) {
|
|
2634
|
+
return new Error(fill(messages.zgVersionTooOld, {
|
|
2635
|
+
actual: formatZgVersion(actual),
|
|
2636
|
+
minimum: MINIMUM_ZG_VERSION
|
|
2637
|
+
}));
|
|
2638
|
+
}
|
|
2639
|
+
/**
|
|
2640
|
+
* 跑一次 `zg --version`,只把 stdout 交回来(undefined = 探测不出来:非零退出、
|
|
2641
|
+
* 读不懂的形状,或 spawn/执行器层面的任何失败)。**失败绝不外抛**:这道门槛的职责
|
|
2642
|
+
* 只有一个——把「确知太老」拦下来,拿「没读懂」去拦用户是在制造新故障。
|
|
2643
|
+
*/
|
|
2644
|
+
async function probeZgVersion(host, config) {
|
|
2645
|
+
let stdout;
|
|
2646
|
+
try {
|
|
2647
|
+
const env = zgEnv(config);
|
|
2648
|
+
const spec = host.shell.resolve({
|
|
2649
|
+
command: "zg --version",
|
|
2650
|
+
workdir: tmpdir(),
|
|
2651
|
+
timeoutMs: ZG_VERSION_PROBE_TIMEOUT_MS,
|
|
2652
|
+
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
2653
|
+
...env ? { env } : {}
|
|
2752
2654
|
});
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
}
|
|
2655
|
+
const result = await (await host.shell.execute(spec)).result();
|
|
2656
|
+
stdout = result.exitCode === 0 ? result.stdout.text : void 0;
|
|
2657
|
+
} catch {
|
|
2658
|
+
stdout = void 0;
|
|
2659
|
+
}
|
|
2660
|
+
return stdout === void 0 ? void 0 : tooOldZgVersion(stdout);
|
|
2756
2661
|
}
|
|
2757
2662
|
/**
|
|
2758
|
-
*
|
|
2663
|
+
* 建这道门槛。缓存挂在闭包里(随 apply 生死),TTL 到期或探测失败后重探一次。
|
|
2759
2664
|
*
|
|
2760
|
-
*
|
|
2761
|
-
*
|
|
2762
|
-
* 有效期是固定的 `LEDGER_TTL_MS`(一天),与解锁时效那个部署值无关——后者只有 1–240 分钟
|
|
2763
|
-
* 的取值域,量级差两个数量级,拿来当「这棵树多久算还在用」会短到让跨天的会话反复重新登记。
|
|
2764
|
-
* 上界与有效期两道都留着:上界保证常驻内存有界,有效期保证冷键不长期占位。
|
|
2665
|
+
* workdir 取系统临时目录而不是会话 cwd:这是一次与工作区无关的纯打印探测,
|
|
2666
|
+
* 不该因为某个会话的工作区不存在而失败,也不该顺手触发 root 授权那一套。
|
|
2765
2667
|
*/
|
|
2766
|
-
function
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
},
|
|
2775
|
-
has(root) {
|
|
2776
|
-
const key = ledgerKey(root, messages);
|
|
2777
|
-
if (key === void 0) return false;
|
|
2778
|
-
const seenAt = seen.get(key);
|
|
2779
|
-
if (seenAt === void 0 || now() - seenAt >= ttlMs) return false;
|
|
2780
|
-
touch(seen, key, seenAt);
|
|
2781
|
-
return true;
|
|
2782
|
-
},
|
|
2783
|
-
list() {
|
|
2784
|
-
return [...seen.keys()];
|
|
2668
|
+
function createZgVersionGate(host, config) {
|
|
2669
|
+
let cachedAt = 0;
|
|
2670
|
+
let cachedTooOld;
|
|
2671
|
+
return { async ensure(messages) {
|
|
2672
|
+
const now = Date.now();
|
|
2673
|
+
if (now - cachedAt < ZG_VERSION_TTL_MS) {
|
|
2674
|
+
if (cachedTooOld !== void 0) throw tooOldZgError(cachedTooOld, messages);
|
|
2675
|
+
return;
|
|
2785
2676
|
}
|
|
2786
|
-
|
|
2677
|
+
const probe = await probeZgVersion(host, config);
|
|
2678
|
+
cachedAt = now;
|
|
2679
|
+
cachedTooOld = probe;
|
|
2680
|
+
if (probe !== void 0) throw tooOldZgError(probe, messages);
|
|
2681
|
+
} };
|
|
2787
2682
|
}
|
|
2788
|
-
/**
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
|
|
2796
|
-
|
|
2683
|
+
/** 就绪态缓存时长:daemon 可被随时 `zg server on/off` 起停,比版本探测勤得多。 */
|
|
2684
|
+
const SERVER_READY_TTL_MS = 6e4;
|
|
2685
|
+
/** 探测自身超时:`zg server status` 是纯读,不该借检索超时。 */
|
|
2686
|
+
const SERVER_READY_PROBE_TIMEOUT_MS = 1e4;
|
|
2687
|
+
/** 就绪探测命令行:`--check-ready` 把「就绪与否」 expressed 成退出码。 */
|
|
2688
|
+
const SERVER_READY_COMMAND = "zg server status --check-ready";
|
|
2689
|
+
/** 探一次守护进程就绪态:退出码 0 = 就绪。任何异常与非零退出都算未就绪。 */
|
|
2690
|
+
async function probeServerReady(host, config) {
|
|
2691
|
+
try {
|
|
2692
|
+
const env = zgEnv(config);
|
|
2693
|
+
const spec = host.shell.resolve({
|
|
2694
|
+
command: SERVER_READY_COMMAND,
|
|
2695
|
+
workdir: tmpdir(),
|
|
2696
|
+
timeoutMs: SERVER_READY_PROBE_TIMEOUT_MS,
|
|
2697
|
+
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
2698
|
+
...env ? { env } : {}
|
|
2797
2699
|
});
|
|
2798
|
-
return;
|
|
2700
|
+
return (await (await host.shell.execute(spec)).result()).exitCode === 0;
|
|
2701
|
+
} catch {
|
|
2702
|
+
return false;
|
|
2799
2703
|
}
|
|
2800
|
-
const serverReady = await serverGate.ready();
|
|
2801
|
-
sendJson(res, 200, {
|
|
2802
|
-
ok: true,
|
|
2803
|
-
csrf,
|
|
2804
|
-
roots: ledger.list(),
|
|
2805
|
-
serverReady
|
|
2806
|
-
});
|
|
2807
2704
|
}
|
|
2808
2705
|
/**
|
|
2809
|
-
*
|
|
2810
|
-
*
|
|
2811
|
-
*
|
|
2812
|
-
*
|
|
2813
|
-
* @param state 这条重建的状态盒(与侧表记录共用)
|
|
2814
|
-
* @param command 实际执行的命令行(作业 label,模型在 job_list 里看见的那句)
|
|
2815
|
-
* @returns 官方 JobSpec:kind / label / output / run
|
|
2706
|
+
* 建这道门槛。缓存挂闭包(随 apply 生死),TTL 到期后重探。
|
|
2707
|
+
*
|
|
2708
|
+
* **并发不合并**:两条检索同时撞上 TTL 边界会各探一次,多起一发纯读进程而已——
|
|
2709
|
+
* 换来的是没有「在途 Promise 该不该共享」这层状态可测(与版本门槛同一口径)。
|
|
2816
2710
|
*/
|
|
2817
|
-
function
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
return {
|
|
2830
|
-
jobs: live,
|
|
2831
|
-
status: view.status
|
|
2832
|
-
};
|
|
2833
|
-
};
|
|
2834
|
-
const cancelKillTimer = host.timer.timeout(() => {
|
|
2835
|
-
if (proc.status !== "running") return;
|
|
2836
|
-
const live = liveJob();
|
|
2837
|
-
if (live !== null && live.status !== "running") return;
|
|
2838
|
-
const minutes = Math.round(config.indexTimeoutMs / 6e4);
|
|
2839
|
-
state.timeoutNote = fill(messages().rebuildTimeout, { minutes });
|
|
2840
|
-
if (live === null) {
|
|
2841
|
-
killProc(proc);
|
|
2842
|
-
return;
|
|
2843
|
-
}
|
|
2844
|
-
live.jobs.kill(handle.id, void 0, fill(messages().jobReasonTimeout, { minutes }));
|
|
2845
|
-
}, config.indexTimeoutMs);
|
|
2846
|
-
return {
|
|
2847
|
-
cancel: () => {
|
|
2848
|
-
killProc(proc);
|
|
2849
|
-
},
|
|
2850
|
-
done: (async () => {
|
|
2851
|
-
await proc.done;
|
|
2852
|
-
cancelKillTimer();
|
|
2853
|
-
try {
|
|
2854
|
-
return jobOutcomeOf(proc);
|
|
2855
|
-
} finally {
|
|
2856
|
-
routes.rebuilds.release(root);
|
|
2857
|
-
}
|
|
2858
|
-
})()
|
|
2859
|
-
};
|
|
2860
|
-
}
|
|
2861
|
-
};
|
|
2711
|
+
function createZgServerGate(host, config) {
|
|
2712
|
+
let cachedAt = 0;
|
|
2713
|
+
let cachedReady = false;
|
|
2714
|
+
let probed = false;
|
|
2715
|
+
return { async ready() {
|
|
2716
|
+
const now = Date.now();
|
|
2717
|
+
if (probed && now - cachedAt < SERVER_READY_TTL_MS) return cachedReady;
|
|
2718
|
+
cachedReady = await probeServerReady(host, config);
|
|
2719
|
+
cachedAt = now;
|
|
2720
|
+
probed = true;
|
|
2721
|
+
return cachedReady;
|
|
2722
|
+
} };
|
|
2862
2723
|
}
|
|
2863
2724
|
/**
|
|
2864
|
-
*
|
|
2865
|
-
*
|
|
2866
|
-
*
|
|
2867
|
-
*
|
|
2868
|
-
*
|
|
2869
|
-
*
|
|
2870
|
-
*
|
|
2871
|
-
*
|
|
2725
|
+
* zg query 输出的命中摘要。口径分两栏,因为**分组计数之和不是命中总数**:同一处代码
|
|
2726
|
+
* 会被多个查询组各命中一次(名次与 `matchedBy` 逐组变化,实测同一 `src/beta.ts:1-3`
|
|
2727
|
+
* 在 fts 组排第 4、在 vector 组排第 1),直接求和会把同一处位置重复计入。
|
|
2728
|
+
* - 分组计数合计:各组 `hits:` 之和,反映 zg 实际跑了多少路。
|
|
2729
|
+
* - 去重后不同位置:按 `相对路径:行号范围` 这一稳定身份键去重——名次、匹配来源、
|
|
2730
|
+
* 分数都逐组变化,不能入键——反映模型真正看到几处不同代码。
|
|
2731
|
+
* 身份键取条目头行里 `matchedBy=` 之后的**整段原样**文本,不去拆行号范围:路径本身
|
|
2732
|
+
* 可以含空格与冒号(实测 `deep/a/b/c d/we:ird file.ts:1-2`),任何拆解都会引入误判,
|
|
2733
|
+
* 而原样文本已经恰好就是「相对路径 + 行号范围」。一条位置都数不出时整段去重口径省略,
|
|
2734
|
+
* 不数就不谎称。
|
|
2872
2735
|
*
|
|
2873
|
-
*
|
|
2874
|
-
*
|
|
2875
|
-
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
*
|
|
2736
|
+
* zg 的输出**不提供**任何截断信号,故命中数正好等于 --limit 只能作为观察陈述,不能
|
|
2737
|
+
* 断言发生了截断(`hitCapped` 因此不含断言措辞)。
|
|
2738
|
+
*/
|
|
2739
|
+
/** zg 每个查询组的计数行前缀(实测输出形状:`hits: 3`,源码行都带行号前缀)。 */
|
|
2740
|
+
const HITS_LINE_PREFIX = "hits: ";
|
|
2741
|
+
/**
|
|
2742
|
+
* zg 命中条目头行的形状:`#<名次> [选择理由] matchedBy=<来源> [score=<分>] <相对路径>:<行号范围>`。
|
|
2743
|
+
* 捕获组即身份键。
|
|
2880
2744
|
*
|
|
2881
|
-
*
|
|
2882
|
-
*
|
|
2883
|
-
*
|
|
2884
|
-
*
|
|
2885
|
-
*
|
|
2886
|
-
*
|
|
2887
|
-
*
|
|
2888
|
-
*
|
|
2889
|
-
*
|
|
2745
|
+
* 两段可选装饰都不能进键,各有实测依据(`--trace` 开启时出现,见 formatScore 与
|
|
2746
|
+
* agentRankedItemHeader):
|
|
2747
|
+
* - `score=`:**同一处位置在两个组里分值可以不同**(实测 `src/beta.ts:1-2` 在 fts 组
|
|
2748
|
+
* 是 0.0164、在 vector 组是 0.0161)。带分值入键等于让每次命中都成"新位置",去重
|
|
2749
|
+
* 直接失效、位置数虚高一倍。分值形态是 `Number.isInteger ? String : toFixed(4)`,
|
|
2750
|
+
* 故整数与四位小数都要收;只认纯数字,路径若真以 `score=1.txt` 开头则不会被误剥
|
|
2751
|
+
* (`score=1` 后面跟的是 `.` 不是空白,整段不匹配)。
|
|
2752
|
+
* - `[global_fill]` / `[group_coverage: x]`:排在名次与 `matchedBy=` 之间,漏了它整行
|
|
2753
|
+
* 就匹配不上,那条命中会被当成不存在。
|
|
2754
|
+
*
|
|
2755
|
+
* preview 的源码行都带 `<行号>\t` 前缀、markdown 标题行是 `heading:`、追踪行是 `trace:`,
|
|
2756
|
+
* 都撞不上这一形状。匹配来源逐组变化(fts / vector / fts+vector),故 `\S+` 只消费来源。
|
|
2890
2757
|
*/
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
2898
|
-
|
|
2899
|
-
|
|
2900
|
-
|
|
2901
|
-
|
|
2902
|
-
|
|
2903
|
-
|
|
2758
|
+
const HIT_LINE_PREFIX = /^#\d+(?:\s+\[[^\]]*\])?\s+matchedBy=\S+\s+(?:score=-?\d+(?:\.\d+)?\s+)?(?<location>\S.*)$/u;
|
|
2759
|
+
function hitSummary(stdoutText, limit, truncated, messages) {
|
|
2760
|
+
const lines = stdoutText.split("\n");
|
|
2761
|
+
const perGroup = lines.filter((line) => line.startsWith(HITS_LINE_PREFIX)).map((line) => line.slice(6)).filter((digits) => /^\d+$/u.test(digits)).map((digits) => Math.trunc(Number(digits)));
|
|
2762
|
+
if (perGroup.length === 0) return null;
|
|
2763
|
+
const locations = /* @__PURE__ */ new Set();
|
|
2764
|
+
for (const line of lines) {
|
|
2765
|
+
const location = HIT_LINE_PREFIX.exec(line)?.groups?.["location"];
|
|
2766
|
+
if (location !== void 0) locations.add(location);
|
|
2767
|
+
}
|
|
2768
|
+
const grouped = perGroup.reduce((sum, count) => sum + count, 0);
|
|
2769
|
+
const capped = perGroup.some((count) => count >= limit);
|
|
2770
|
+
return fill(messages.hitSummary, {
|
|
2771
|
+
groups: perGroup.length,
|
|
2772
|
+
grouped,
|
|
2773
|
+
dedup: locations.size === 0 ? "" : fill(messages.hitDedup, { unique: locations.size }),
|
|
2774
|
+
limit,
|
|
2775
|
+
capped: capped ? messages.hitCapped : "",
|
|
2776
|
+
truncated: truncated ? messages.hitTruncated : ""
|
|
2777
|
+
});
|
|
2778
|
+
}
|
|
2779
|
+
/**
|
|
2780
|
+
* 被「本插件正在重建」挡住的失败:文案照常是人话,但额外带上结构化结论,
|
|
2781
|
+
* 让检索路径能判断「等它落定后重试一次」而不是无脑失败。
|
|
2782
|
+
* 只有占锁方自报重建才带这个类型——把「别的进程占锁」也当成可等的重建,
|
|
2783
|
+
* 会在一把永远不会由本插件放开的锁上无界挂起。
|
|
2784
|
+
*/
|
|
2785
|
+
var RebuildLockBusyError = class extends Error {
|
|
2786
|
+
constructor(message) {
|
|
2787
|
+
super(message);
|
|
2788
|
+
this.name = "RebuildLockBusyError";
|
|
2789
|
+
}
|
|
2790
|
+
};
|
|
2791
|
+
async function runForegroundOnce(host, command, workdir, timeoutMs, opts) {
|
|
2792
|
+
const spec = host.shell.resolve({
|
|
2793
|
+
command,
|
|
2794
|
+
workdir,
|
|
2795
|
+
timeoutMs,
|
|
2796
|
+
stdoutMaxBytes: opts.stdoutMaxBytes,
|
|
2797
|
+
signal: opts.signal,
|
|
2798
|
+
...opts.env ? { env: opts.env } : {}
|
|
2799
|
+
});
|
|
2800
|
+
const result = await (await host.shell.execute(spec)).result();
|
|
2801
|
+
const failure = shellFailure(result, opts.messages);
|
|
2802
|
+
if (failure !== null) {
|
|
2803
|
+
const resolved = opts.resolveFailure?.(failure, result) ?? null;
|
|
2804
|
+
if (resolved !== null) return resolved;
|
|
2805
|
+
const concurrent = classifyConcurrentFailure(result.stderr.text);
|
|
2806
|
+
throw concurrent?.kind === "lock-busy" && concurrent.rebuild ? new RebuildLockBusyError(failure) : new Error(failure);
|
|
2807
|
+
}
|
|
2808
|
+
const notes = successNotes(result, opts.messages, opts.stdoutMaxBytes);
|
|
2809
|
+
const { text } = result.stdout;
|
|
2810
|
+
const summary = opts.summaryLimit === void 0 ? null : hitSummary(text, opts.summaryLimit, result.stdout.truncated, opts.messages);
|
|
2811
|
+
const extras = summary === null ? notes : [...notes, summary];
|
|
2812
|
+
return extras.length > 0 ? `${text}\n${extras.join("\n")}` : text;
|
|
2813
|
+
}
|
|
2814
|
+
/** 等待期间被取消时的出路(与 zg 自身被中止区分开:这里等的是重建,不是命令)。 */
|
|
2815
|
+
function messagesAbortedWaiting(root, messages) {
|
|
2816
|
+
return fill(messages.rebuildWaitAborted, { root });
|
|
2817
|
+
}
|
|
2818
|
+
/** 等待重建落定超时:给出可行动出路,并说明不会因此发放 grep/rg 配额。 */
|
|
2819
|
+
function messagesWaitExpired(root, maxWaitMs, messages) {
|
|
2820
|
+
return fill(messages.rebuildWaitTimeout, {
|
|
2821
|
+
root,
|
|
2822
|
+
seconds: Math.round(maxWaitMs / 1e3)
|
|
2823
|
+
});
|
|
2824
|
+
}
|
|
2825
|
+
/**
|
|
2826
|
+
* 前台执行 + **一次**重建等待重试。
|
|
2827
|
+
*
|
|
2828
|
+
* 重建持有该根的写锁时,检索会立刻以「索引不可用」失败(zg 的锁是纯 fail-fast,不等)。
|
|
2829
|
+
* 直接把失败回给模型,等于在重建窗口内把该根的检索通道整个关掉——而门禁又要求先成功
|
|
2830
|
+
* 检索才放行 grep/rg,于是模型连退路都没有。这里改为:确认占锁方确实是本插件的重建,
|
|
2831
|
+
* 就等它落定后重跑一次;只等一次,不做轮询式长等,避免把一次检索拖成分钟级。
|
|
2832
|
+
*/
|
|
2833
|
+
async function runForeground(host, command, workdir, timeoutMs, opts) {
|
|
2834
|
+
const base = {
|
|
2835
|
+
signal: opts.signal,
|
|
2836
|
+
env: opts.env,
|
|
2837
|
+
stdoutMaxBytes: opts.stdoutMaxBytes,
|
|
2838
|
+
messages: opts.messages,
|
|
2839
|
+
summaryLimit: opts.summaryLimit,
|
|
2840
|
+
resolveFailure: opts.resolveFailure
|
|
2841
|
+
};
|
|
2842
|
+
const wait = opts.rebuildWait;
|
|
2843
|
+
if (wait === void 0) return runForegroundOnce(host, command, workdir, timeoutMs, base);
|
|
2844
|
+
try {
|
|
2845
|
+
return await runForegroundOnce(host, command, workdir, timeoutMs, base);
|
|
2846
|
+
} catch (error) {
|
|
2847
|
+
const entry = wait.rebuilds.covering(wait.root, opts.messages);
|
|
2848
|
+
if (!(error instanceof RebuildLockBusyError) || entry === void 0) throw error;
|
|
2849
|
+
const outcome = await wait.rebuilds.wait(wait.root, opts.messages, wait.maxWaitMs, opts.signal);
|
|
2850
|
+
if (outcome === "settled") return runForegroundOnce(host, command, workdir, timeoutMs, base);
|
|
2851
|
+
throw new Error(outcome === "aborted" ? messagesAbortedWaiting(entry.root, opts.messages) : messagesWaitExpired(entry.root, wait.maxWaitMs, opts.messages), { cause: error });
|
|
2852
|
+
}
|
|
2853
|
+
}
|
|
2854
|
+
/**
|
|
2855
|
+
* root 的存在性预检(item:不验存在)。zg 的 cwd 不存在时,spawn 直接以
|
|
2856
|
+
* ENOENT 失败——那与「bash 没装」「zg 没装」在同一句 stderr 里无法区分,
|
|
2857
|
+
* 模型据此给出的建议会把用户带偏。提前一次 existsSync 换明确归因。
|
|
2858
|
+
*/
|
|
2859
|
+
function assertRootExists(root, messages) {
|
|
2860
|
+
if (!existsSync(root)) throw new Error(fill(messages.rootMissing, { root }));
|
|
2861
|
+
return root;
|
|
2862
|
+
}
|
|
2863
|
+
/**
|
|
2864
|
+
* 默认每组结果数:值域 1-50 由 Config schema(隐式命名空间与行 config 共用)保证,
|
|
2865
|
+
* 这里只处理「字段缺省」。真正兜住越界的是 cli.clampLimit(命令构造边界)。
|
|
2866
|
+
*/
|
|
2867
|
+
function readDefaultLimit(config) {
|
|
2868
|
+
return config.defaultLimit.get() ?? 10;
|
|
2869
|
+
}
|
|
2870
|
+
/** search-first 解锁配额:每次成功 zg_search 发放的 grep/rg 次数(值域 1-20 由 schema 保证)。 */
|
|
2871
|
+
function readGrepBudget(config) {
|
|
2872
|
+
return config.grepBudgetPerSearch.get() ?? 3;
|
|
2873
|
+
}
|
|
2874
|
+
/** search-first 解锁时效(分钟,值域 1-240 由 schema 保证)。 */
|
|
2875
|
+
function readUnlockWindowMin(config) {
|
|
2876
|
+
return config.unlockWindowMin.get() ?? 10;
|
|
2877
|
+
}
|
|
2878
|
+
/** search-first 门禁开关:**fail-closed**。schema 默认已是 true,引用仍交回 undefined
|
|
2879
|
+
* (条目没被投影 / 宿主退化)时按「门禁开着」处理——宁可多拦一次 grep,也不能把
|
|
2880
|
+
* 「读不到设置」静默当成「用户关了门禁」。 */
|
|
2881
|
+
function readEnforceSearchFirst(config) {
|
|
2882
|
+
return config.enforceSearchFirst.get() ?? true;
|
|
2883
|
+
}
|
|
2884
|
+
/** 归一路径的跨平台可比形式:剥掉 macOS 的 `/private` 解析前缀(`/tmp` ⇄ `/private/tmp`)。 */
|
|
2885
|
+
function comparablePath(root) {
|
|
2886
|
+
return root.startsWith("/private/") ? root.slice(8) : root;
|
|
2887
|
+
}
|
|
2888
|
+
/** 认的清单版本:与上游 v0.2.2 的 `export const CURRENT_MANIFEST_VERSION = 1` 同值。 */
|
|
2889
|
+
const SUPPORTED_MANIFEST_VERSION = 1;
|
|
2890
|
+
/**
|
|
2891
|
+
* 索引清单是否**真的**覆盖这个工作区。
|
|
2892
|
+
*
|
|
2893
|
+
* 只判「文件在不在」是不够的,两种实况都会把它判成有索引而实际检索必然失败:
|
|
2894
|
+
* - 文件在,但内容不是一份清单(半截写入、被别的东西占了同名文件)——解析失败即不算。
|
|
2895
|
+
* - 清单在,但索引的根路径不覆盖这个目录(例如指向另一个盘符/被改写过的路径)——此时
|
|
2896
|
+
* 在这个目录里检索会报「索引不可用」,而门禁却按「已建索引」拦着 grep/rg。
|
|
2897
|
+
* - 清单的版本不是当前认的那一版——上游读它会直接抛 MANIFEST.INVALID(要求
|
|
2898
|
+
* `manifestVersion` 严格等于 `CURRENT_MANIFEST_VERSION`),此时本目录**一次检索都做不了**,
|
|
2899
|
+
* 却会被「是个数字」这种宽松判据放进门禁。故这里同样取严格相等。
|
|
2900
|
+
*
|
|
2901
|
+
* 认的结构只有真正用到的两处(实测上游的 workspace manifest 形状):
|
|
2902
|
+
* `manifestVersion` 严格等于 1,`rootPaths` 是非空数组且每项带一个非空 `absolutePath`。
|
|
2903
|
+
* 刻意不校验 embedding / policy 等字段——那些变了索引照样能用,判成「无索引」反而是错的。
|
|
2904
|
+
*
|
|
2905
|
+
* 覆盖判据是「归一后相等」。实测 macOS 上清单里写的是**未解析**路径(`/tmp/x`)而
|
|
2906
|
+
* `path` 字段才是解析过的(`/private/tmp/x`),会话 cwd 通常也是未解析那一支;但调用方
|
|
2907
|
+
* 完全可能交来解析过的形式,故两边都再剥一次 `/private` 前缀再比。
|
|
2908
|
+
*/
|
|
2909
|
+
function manifestCoversRoot(manifestPath, dir) {
|
|
2910
|
+
let parsed;
|
|
2911
|
+
try {
|
|
2912
|
+
parsed = JSON.parse(readFileSync(manifestPath, "utf8"));
|
|
2913
|
+
} catch {
|
|
2914
|
+
return false;
|
|
2915
|
+
}
|
|
2916
|
+
if (!isRecord(parsed) || !("manifestVersion" in parsed) || parsed["manifestVersion"] !== SUPPORTED_MANIFEST_VERSION) return false;
|
|
2917
|
+
const { rootPaths } = parsed;
|
|
2918
|
+
if (!Array.isArray(rootPaths) || rootPaths.length === 0) return false;
|
|
2919
|
+
const target = comparablePath(normalizeRoot(dir));
|
|
2920
|
+
return rootPaths.some((entry) => isRecord(entry) && typeof entry["absolutePath"] === "string" && entry["absolutePath"].length > 0 && comparablePath(normalizeRoot(entry["absolutePath"])) === target);
|
|
2921
|
+
}
|
|
2922
|
+
/** zg 索引库存在性探测(search-first 门禁与 zg_search 登记共用)。
|
|
2923
|
+
* 必须连 workspace manifest 一起看:`<dir>/.zvec-grep/` 这个名字被 zg 自己的**全局
|
|
2924
|
+
* home** 征用(`ZVEC_GREP_HOME ?? ~/.zvec-grep`,装的是 config.json / locks / models),
|
|
2925
|
+
* 只判目录存在的话,一个从没建过索引的工作区会因祖先目录撞名而被当成「已建索引」——
|
|
2926
|
+
* 门禁随即在没有任何索引可搜的情况下拦下 grep/rg,而 zg_search 也答不出任何东西。
|
|
2927
|
+
* manifest 是上游写索引时落的那一份(`writeWorkspaceManifest`),只有它在场,
|
|
2928
|
+
* 才说明这个工作区真的建过索引。 */
|
|
2929
|
+
function indexProbeOf(dir) {
|
|
2930
|
+
const base = `${dir}/${INDEX_DIR_NAME}`;
|
|
2931
|
+
if (!existsSync(base) || !existsSync(`${base}/manifest.json`)) return false;
|
|
2932
|
+
return manifestCoversRoot(`${base}/${WORKSPACE_MANIFEST_FILE}`, dir);
|
|
2933
|
+
}
|
|
2934
|
+
/** root 判据的单一来源:显式值 > 会话工作区 → 存在性 → 授权(已观测 / 同一棵树)。 */
|
|
2935
|
+
function judgeRoot(rawRoot, cwd, messages, ledger) {
|
|
2936
|
+
let resolved;
|
|
2937
|
+
try {
|
|
2938
|
+
resolved = assertRootExists(resolveRoot(rawRoot, cwd, messages), messages);
|
|
2939
|
+
} catch (error) {
|
|
2940
|
+
return {
|
|
2941
|
+
allowed: false,
|
|
2942
|
+
reason: errorText(error)
|
|
2943
|
+
};
|
|
2944
|
+
}
|
|
2945
|
+
if (cwd !== void 0 && normalizeRoot(resolved) === normalizeRoot(cwd) || ledger.has(resolved)) return {
|
|
2946
|
+
allowed: true,
|
|
2947
|
+
root: resolved,
|
|
2948
|
+
question: void 0
|
|
2949
|
+
};
|
|
2950
|
+
if (cwd !== void 0 && pathsRelated(resolved, cwd, messages)) return {
|
|
2951
|
+
allowed: true,
|
|
2952
|
+
root: resolved,
|
|
2953
|
+
question: {
|
|
2954
|
+
root: resolved,
|
|
2955
|
+
cwd
|
|
2956
|
+
}
|
|
2957
|
+
};
|
|
2958
|
+
return {
|
|
2959
|
+
allowed: false,
|
|
2960
|
+
reason: fill(messages.rootNotAuthorized, {
|
|
2961
|
+
root: resolved,
|
|
2962
|
+
cwd: cwd ?? messages.rootNoSession
|
|
2963
|
+
})
|
|
2964
|
+
};
|
|
2965
|
+
}
|
|
2966
|
+
/** 工具入参的 root:过 root 判据,放行后登记进白名单(一处三工具共用)。 */
|
|
2967
|
+
function rootOf(args, exec, messages, ledger) {
|
|
2968
|
+
const decision = judgeRoot(args["root"], sessionHeaderCwd(exec), messages, ledger);
|
|
2969
|
+
if (!decision.allowed) throw new Error(decision.reason);
|
|
2970
|
+
ledger.add(decision.root);
|
|
2971
|
+
return decision.root;
|
|
2972
|
+
}
|
|
2973
|
+
function define(host, spec) {
|
|
2974
|
+
const { parameters } = spec;
|
|
2975
|
+
const required = Array.isArray(parameters["required"]) ? parameters["required"].filter((item) => typeof item === "string") : [];
|
|
2976
|
+
host.tools.register({
|
|
2977
|
+
name: spec.name,
|
|
2978
|
+
description: spec.description,
|
|
2979
|
+
parameters,
|
|
2980
|
+
output: {
|
|
2981
|
+
schema: TEXT_OUTPUT_SCHEMA,
|
|
2982
|
+
render: (_args, value) => textBlock(value)
|
|
2983
|
+
},
|
|
2984
|
+
execute: async (rawArgs, exec) => {
|
|
2985
|
+
const messages = spec.messages();
|
|
2986
|
+
if (!isRecord(rawArgs)) throw new Error(fill(messages.argsMustBeObject, {
|
|
2987
|
+
name: spec.name,
|
|
2988
|
+
received: rawArgs === null ? "null" : typeof rawArgs
|
|
2989
|
+
}));
|
|
2990
|
+
const missing = required.filter((fieldName) => rawArgs[fieldName] === void 0);
|
|
2991
|
+
if (missing.length > 0) throw new Error(fill(messages.missingRequiredArgs, {
|
|
2992
|
+
name: spec.name,
|
|
2993
|
+
fields: missing.join(", ")
|
|
2994
|
+
}));
|
|
2995
|
+
return await spec.run(rawArgs, exec, messages);
|
|
2996
|
+
}
|
|
2997
|
+
});
|
|
2998
|
+
}
|
|
2999
|
+
/** 隐式命名空间与 loader 行 config 共用同一 schema(单源,防漂移)。
|
|
3000
|
+
* 值名退避为 configSchema:避免与同名 interface Config 触发 no-redeclare;
|
|
3001
|
+
* 外部仍以 `Config` 名导入(export as),公开 API 不变。
|
|
3002
|
+
*
|
|
3003
|
+
* 0.1.7 迁移要点(两处都是静默失效,写错不报错):
|
|
3004
|
+
* - `.volatile()` 决定字段是否进设置表单。宿主 `describe()` 只投影 volatile 字段
|
|
3005
|
+
* (packages/settings/settings/src/schema.ts 的 volatileForm),全漏标则整条被跳过
|
|
3006
|
+
* (settings/src/index.ts 里 `volatileForm(schema)` 空判即 `return []` 的那一处)、写入抛
|
|
3007
|
+
* `has no volatile fields`(同文件的那句 throw)。
|
|
3008
|
+
* - `settings.register(ns, schema, { base })` 的「底座」层已被宿主移除:内置默认逐字段
|
|
3009
|
+
* 落成下面的 `.default()`(原 BUILTIN_BASE 原样搬来,单一来源),cordis 装载期按同一
|
|
3010
|
+
* 份 schema 校验行 config 并填默认,再把 volatile 字段包成引用交给 apply。
|
|
3011
|
+
* 六个 volatile 字段全是本卡的可编辑项,一个都不该漏;四个非 volatile 部署值
|
|
3012
|
+
* (超时三项 + stdout 上限)只走行 config,标 volatile 反而会把它们变成设置卡项。 */
|
|
3013
|
+
const configSchema = Schema.object({
|
|
3014
|
+
defaultEmbedding: Schema.string().default(DEFAULT_EMBEDDING).volatile(),
|
|
3015
|
+
defaultLimit: Schema.natural().min(1).max(50).default(10).volatile(),
|
|
3016
|
+
hfEndpoint: Schema.string().default("https://modelscope.cn/models").volatile(),
|
|
3017
|
+
enforceSearchFirst: Schema.boolean().default(true).volatile(),
|
|
3018
|
+
grepBudgetPerSearch: Schema.natural().min(1).max(20).default(3).volatile(),
|
|
3019
|
+
unlockWindowMin: Schema.natural().min(1).max(240).default(10).volatile(),
|
|
3020
|
+
searchTimeoutMs: Schema.natural().min(1).default(SEARCH_TIMEOUT_MS),
|
|
3021
|
+
statusTimeoutMs: Schema.natural().min(1).default(STATUS_TIMEOUT_MS),
|
|
3022
|
+
indexTimeoutMs: Schema.natural().min(1).default(INDEX_TIMEOUT_MS),
|
|
3023
|
+
stdoutMaxBytes: Schema.natural().min(1).default(STDOUT_MAX_BYTES),
|
|
3024
|
+
clientMode: Schema.union([
|
|
3025
|
+
"auto",
|
|
3026
|
+
"direct",
|
|
3027
|
+
"server"
|
|
3028
|
+
]).default(DEFAULT_CLIENT_MODE),
|
|
3029
|
+
rebuildWaitMs: Schema.natural().min(1).default(REBUILD_WAIT_MS),
|
|
3030
|
+
allowRemoteEmbedding: Schema.boolean().default(false),
|
|
3031
|
+
remoteEmbeddingEndpoint: Schema.string().default(""),
|
|
3032
|
+
remoteEmbeddingApiKeyFrom: Schema.string().default(""),
|
|
3033
|
+
requireApprovalForExplicitRoot: Schema.boolean().default(false)
|
|
3034
|
+
});
|
|
3035
|
+
/** 白名单键:归一化后的绝对路径;非法 root(相对/越界/NUL)归 undefined。 */
|
|
3036
|
+
function ledgerKey(root, messages) {
|
|
3037
|
+
let key;
|
|
3038
|
+
try {
|
|
3039
|
+
key = assertAbsoluteRoot(root, messages);
|
|
3040
|
+
} catch {
|
|
3041
|
+
key = void 0;
|
|
2904
3042
|
}
|
|
3043
|
+
return key;
|
|
2905
3044
|
}
|
|
2906
3045
|
/**
|
|
2907
|
-
*
|
|
3046
|
+
* 淘汰一张常驻表:先按**有效期**丢过期项,再按**最近使用**丢最老项到不超过上限。
|
|
2908
3047
|
*
|
|
2909
|
-
*
|
|
2910
|
-
*
|
|
3048
|
+
* 为什么不是纯插入序(原 `trimMapTo`):`Map` 的插入序在 `delete` 后重排,故「插入序淘汰」
|
|
3049
|
+
* 实际是「最早插入且此后没被重新插入的先走」——一张每轮都被 `set` 命中的表(解锁额度就是,
|
|
3050
|
+
* 每次成功检索都重置同一批键)永远淘汰不掉真正冷掉的项,而一条很久没被碰过的键会一直占位。
|
|
3051
|
+
* 改成:命中即触摸(`delete` + `set` 把键挪到队尾),淘汰从队首取。这样「最久没用过」
|
|
3052
|
+
* 才有确定含义。
|
|
2911
3053
|
*
|
|
2912
|
-
*
|
|
2913
|
-
*
|
|
2914
|
-
* 发生在任何进程存在之前,调用方那条 `release` 出口足以收干净。
|
|
3054
|
+
* 有效期同样必要:一个只在半小时前出现过一次的工作区,到明天早就不该还占着白名单名额。
|
|
3055
|
+
* 两者都保留,故上界(内存有界)与语义(冷掉的先走)同时成立。
|
|
2915
3056
|
*
|
|
2916
|
-
*
|
|
2917
|
-
*
|
|
2918
|
-
* @param
|
|
2919
|
-
* @param
|
|
2920
|
-
* @param indexArgs 已归一 root 的索引入参
|
|
2921
|
-
* @param embedding 设置里的默认 embedding(`indexArgs.embedding` 为空时用它)
|
|
2922
|
-
* @returns 起来的进程与它跑的命令;失败为 `{ error, status }`
|
|
3057
|
+
* @param map 目标表(就地改)
|
|
3058
|
+
* @param max 条数上限
|
|
3059
|
+
* @param expiresAt 取某条目的过期时刻;无则视为永不过期
|
|
3060
|
+
* @param now 当前时刻(epoch ms)
|
|
2923
3061
|
*/
|
|
2924
|
-
|
|
2925
|
-
const
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
await routes.versionGate.ensure(started);
|
|
2929
|
-
assertIgnoreFilesExist(indexArgs, assertAbsoluteRoot(indexArgs.root, started), started);
|
|
2930
|
-
const built = buildIndexCommand(indexArgs, embedding, started, readClientMode(config, started), allowRemoteEmbedding(config));
|
|
2931
|
-
const env = zgEnv(config);
|
|
2932
|
-
const spec = host.shell.resolve({
|
|
2933
|
-
command: built.command,
|
|
2934
|
-
workdir: built.workdir,
|
|
2935
|
-
onExpiry: "none",
|
|
2936
|
-
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
2937
|
-
...env ? { env } : {}
|
|
2938
|
-
});
|
|
2939
|
-
spawned = {
|
|
2940
|
-
proc: await host.shell.execute(spec),
|
|
2941
|
-
command: built.command
|
|
2942
|
-
};
|
|
2943
|
-
} catch (error) {
|
|
2944
|
-
return {
|
|
2945
|
-
error: fill(started.endpointStartFailed, { reason: errorText(error) }),
|
|
2946
|
-
status: 500
|
|
2947
|
-
};
|
|
3062
|
+
function evictAged(map, max, expiresAt, now) {
|
|
3063
|
+
for (const [key, value] of map) {
|
|
3064
|
+
const expiry = expiresAt(value);
|
|
3065
|
+
if (expiry !== void 0 && expiry <= now) map.delete(key);
|
|
2948
3066
|
}
|
|
2949
|
-
|
|
3067
|
+
for (const key of map.keys()) {
|
|
3068
|
+
if (map.size <= max) break;
|
|
3069
|
+
map.delete(key);
|
|
3070
|
+
}
|
|
3071
|
+
}
|
|
3072
|
+
/** 命中即触摸:把键挪到队尾,使「最近使用」在插入序上成立。 */
|
|
3073
|
+
function touch(map, key, value) {
|
|
3074
|
+
map.delete(key);
|
|
3075
|
+
map.set(key, value);
|
|
2950
3076
|
}
|
|
3077
|
+
/** 探测缓存的 TTL(ms):负向条目(当时无索引)的陈旧上界,选型论证见下。 */
|
|
3078
|
+
const INDEX_PROBE_TTL_MS = 6e4;
|
|
3079
|
+
/** 探测缓存容量(条):guard 一次调用至多探 9 层祖先,32 条覆盖多工作区来回切换。 */
|
|
3080
|
+
const INDEX_PROBE_CACHE_MAX = 32;
|
|
2951
3081
|
/**
|
|
2952
|
-
*
|
|
3082
|
+
* zg 索引库存在性探测的**按目录缓存**(P2:guard 每次工具调用里 findIndexRoot 最多
|
|
3083
|
+
* 向上探 9 层 existsSync,同一工作区的连续调用命中的是同一串祖先目录;zg_search 的
|
|
3084
|
+
* 解锁路径也要再走一遍同样的上溯)。
|
|
2953
3085
|
*
|
|
2954
|
-
*
|
|
2955
|
-
*
|
|
2956
|
-
*
|
|
2957
|
-
*
|
|
2958
|
-
*
|
|
2959
|
-
*
|
|
2960
|
-
*
|
|
2961
|
-
*
|
|
3086
|
+
* 失效策略选**进程内 TTL(60s)**而不是会话内不过期:正向条目(有索引)在「索引目录
|
|
3087
|
+
* 运行期不会消失」的假设下永不陈旧,TTL 对它只是内存有界的双保险;真正需要 TTL 的是
|
|
3088
|
+
* **负向**条目——zg_index 是运行期动作,新索引落地后若永不过期,门禁要到进程重启才
|
|
3089
|
+
* 看得见它。60s 的负向陈旧只是「索引出现前的既有行为」(grep 不被拦)的短暂延续,
|
|
3090
|
+
* 方向安全,且与「建索引后立刻去搜」的真实节奏相比可忽略。
|
|
3091
|
+
*
|
|
3092
|
+
* 缓存是**纯性能优化**:只替 existsSync 的答案,不改 findIndexRoot 的走法——root 不
|
|
3093
|
+
* 存在(probe 恒 false)、走满 maxDepth、上溯到 / 等失败路径在相同探测结果下与原实现
|
|
3094
|
+
* 逐分支一致。命中即触摸(delete+set 挪到队尾),配合 trimMapTo 的插入序淘汰 ⇒ LRU。
|
|
3095
|
+
*
|
|
3096
|
+
* @param probe 目录探测(生产注入 indexProbeOf;测试注入计数桩)
|
|
3097
|
+
* @param now 时钟注入(默认 Date.now;测试用它推进过 TTL)
|
|
3098
|
+
* @param ttlMs 条目存活时长(默认 {@link INDEX_PROBE_TTL_MS})
|
|
3099
|
+
* @param max 容量上限(默认 {@link INDEX_PROBE_CACHE_MAX})
|
|
3100
|
+
* @returns 与 probe 同签名的缓存化探测函数
|
|
2962
3101
|
*/
|
|
2963
|
-
function
|
|
2964
|
-
const
|
|
2965
|
-
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
|
|
2971
|
-
status: 503
|
|
2972
|
-
};
|
|
2973
|
-
}
|
|
2974
|
-
pruneRebuildHistory(starting, records);
|
|
2975
|
-
const state = {
|
|
2976
|
-
identity: {
|
|
2977
|
-
kind: REBUILD_JOB_KIND,
|
|
2978
|
-
label: command,
|
|
2979
|
-
startedAt: UNSIGNED_STARTED_AT
|
|
2980
|
-
},
|
|
2981
|
-
lost: false,
|
|
2982
|
-
timeoutNote: null
|
|
2983
|
-
};
|
|
2984
|
-
let jobId;
|
|
2985
|
-
try {
|
|
2986
|
-
jobId = startUnderController(starting, rebuildJobSpec(routes, proc, state, command, root));
|
|
2987
|
-
state.identity = identityOf(starting.get(jobId));
|
|
2988
|
-
const clashed = records.get(jobId);
|
|
2989
|
-
if (clashed !== void 0 && !sameIdentity(clashed.state.identity, state.identity)) {
|
|
2990
|
-
killProc(proc);
|
|
2991
|
-
return {
|
|
2992
|
-
error: started.endpointRegistryReplaced,
|
|
2993
|
-
status: 503
|
|
2994
|
-
};
|
|
2995
|
-
}
|
|
2996
|
-
records.set(jobId, {
|
|
2997
|
-
proc,
|
|
2998
|
-
root,
|
|
2999
|
-
id: jobId,
|
|
3000
|
-
state
|
|
3001
|
-
});
|
|
3002
|
-
} catch (error) {
|
|
3003
|
-
killProc(proc);
|
|
3004
|
-
return {
|
|
3005
|
-
error: startupFailureText(error, started),
|
|
3006
|
-
status: 500
|
|
3007
|
-
};
|
|
3008
|
-
}
|
|
3009
|
-
return { jobId };
|
|
3010
|
-
}
|
|
3011
|
-
/** 启动端点:四道前置校验(同源 / CSRF / 白名单 / 目录存在)后复用或起一条重建。 */
|
|
3012
|
-
async function handleRebuildStart(routes, req, res) {
|
|
3013
|
-
const { csrf, jobsOf, ledger, messages, records, servingNonLoopback } = routes;
|
|
3014
|
-
if (!guardTrust(req, res, { servingNonLoopback })) return;
|
|
3015
|
-
if (req.method !== "POST") {
|
|
3016
|
-
res.setHeader("Allow", "POST");
|
|
3017
|
-
sendJson(res, 405, {
|
|
3018
|
-
ok: false,
|
|
3019
|
-
error: "POST only"
|
|
3020
|
-
});
|
|
3021
|
-
return;
|
|
3022
|
-
}
|
|
3023
|
-
if (await guardBody(req, res, {
|
|
3024
|
-
maxBytes: REBUILD_BODY_MAX_BYTES,
|
|
3025
|
-
csrf: {
|
|
3026
|
-
token: csrf,
|
|
3027
|
-
headerName: REBUILD_CSRF_HEADER
|
|
3102
|
+
function createIndexProbeCache(probe, now = Date.now, ttlMs = INDEX_PROBE_TTL_MS, max = 32) {
|
|
3103
|
+
const cache = /* @__PURE__ */ new Map();
|
|
3104
|
+
return (dir) => {
|
|
3105
|
+
const at = now();
|
|
3106
|
+
const hit = cache.get(dir);
|
|
3107
|
+
if (hit !== void 0 && at - hit.probedAt < ttlMs) {
|
|
3108
|
+
touch(cache, dir, hit);
|
|
3109
|
+
return hit.result;
|
|
3028
3110
|
}
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
if (jobs === void 0) {
|
|
3035
|
-
sendJson(res, 503, {
|
|
3036
|
-
ok: false,
|
|
3037
|
-
error: started.endpointJobsUnavailable
|
|
3038
|
-
});
|
|
3039
|
-
return;
|
|
3040
|
-
}
|
|
3041
|
-
if (routes.rebuilds.claim(root, "card") === null) {
|
|
3042
|
-
if (!followRunningRebuild(jobs, records, res, root)) sendJson(res, 409, {
|
|
3043
|
-
ok: false,
|
|
3044
|
-
error: started.endpointRebuildInFlight
|
|
3045
|
-
});
|
|
3046
|
-
return;
|
|
3047
|
-
}
|
|
3048
|
-
const embedding = readDefaultEmbedding(routes.config);
|
|
3049
|
-
const spawned = await spawnIndexWrite(routes, started, {
|
|
3050
|
-
root,
|
|
3051
|
-
embedding,
|
|
3052
|
-
rebuild: true
|
|
3053
|
-
}, embedding);
|
|
3054
|
-
if ("error" in spawned) {
|
|
3055
|
-
routes.rebuilds.release(root);
|
|
3056
|
-
sendJson(res, spawned.status, {
|
|
3057
|
-
ok: false,
|
|
3058
|
-
error: spawned.error
|
|
3059
|
-
});
|
|
3060
|
-
return;
|
|
3061
|
-
}
|
|
3062
|
-
const attached = attachIndexWrite(routes, root, started, spawned);
|
|
3063
|
-
if ("error" in attached) {
|
|
3064
|
-
routes.rebuilds.release(root);
|
|
3065
|
-
sendJson(res, attached.status, {
|
|
3066
|
-
ok: false,
|
|
3067
|
-
error: attached.error
|
|
3068
|
-
});
|
|
3069
|
-
return;
|
|
3070
|
-
}
|
|
3071
|
-
routes.rebuilds.attach(root, attached.jobId);
|
|
3072
|
-
sendJson(res, 200, {
|
|
3073
|
-
ok: true,
|
|
3074
|
-
jobId: attached.jobId
|
|
3075
|
-
});
|
|
3076
|
-
}
|
|
3077
|
-
/** 轮询端点:官方状态投影 + 退出码/沙箱事实 + 打标后的输出尾窗(卡片每 2s 敲一次)。 */
|
|
3078
|
-
function handleRebuildStatus(routes, req, res) {
|
|
3079
|
-
const { jobsOf, messages, records, servingNonLoopback } = routes;
|
|
3080
|
-
if (!guardTrust(req, res, { servingNonLoopback })) return;
|
|
3081
|
-
const jobId = queryParam(req, "jobId");
|
|
3082
|
-
const record = jobId === null || jobId === "" ? void 0 : records.get(jobId);
|
|
3083
|
-
if (record === void 0) {
|
|
3084
|
-
sendJson(res, 404, {
|
|
3085
|
-
ok: false,
|
|
3086
|
-
error: fill(messages().unknownJobId, { maxJobs: REBUILD_HISTORY_MAX })
|
|
3087
|
-
});
|
|
3088
|
-
return;
|
|
3089
|
-
}
|
|
3090
|
-
const marks = messages();
|
|
3091
|
-
const jobs = jobsOf();
|
|
3092
|
-
if (jobs === void 0) {
|
|
3093
|
-
sendJson(res, 503, {
|
|
3094
|
-
ok: false,
|
|
3095
|
-
error: marks.endpointJobsUnavailable
|
|
3096
|
-
});
|
|
3097
|
-
return;
|
|
3098
|
-
}
|
|
3099
|
-
const output = readRebuildOutput(jobs, record.id);
|
|
3100
|
-
if (output === null) {
|
|
3101
|
-
sendJson(res, 404, {
|
|
3102
|
-
ok: false,
|
|
3103
|
-
error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX })
|
|
3104
|
-
});
|
|
3105
|
-
return;
|
|
3106
|
-
}
|
|
3107
|
-
if (!sameJob(record.state, output.view)) {
|
|
3108
|
-
sendJson(res, 404, {
|
|
3109
|
-
ok: false,
|
|
3110
|
-
error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX })
|
|
3111
|
+
const result = probe(dir);
|
|
3112
|
+
cache.delete(dir);
|
|
3113
|
+
cache.set(dir, {
|
|
3114
|
+
result,
|
|
3115
|
+
probedAt: at
|
|
3111
3116
|
});
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3115
|
-
const text = retained.chunks.map((chunk) => chunk.text).join("");
|
|
3116
|
-
const shown = truncateStart(text, JOB_OUT_VIEW_CHARS);
|
|
3117
|
-
const viewMark = text.length > JOB_OUT_VIEW_CHARS ? fill(marks.jobOutputView, {
|
|
3118
|
-
shown: JOB_OUT_VIEW_CHARS,
|
|
3119
|
-
total: text.length
|
|
3120
|
-
}) : "";
|
|
3121
|
-
sendJson(res, 200, {
|
|
3122
|
-
ok: true,
|
|
3123
|
-
status: view.status,
|
|
3124
|
-
exitCode: record.proc.exitCode,
|
|
3125
|
-
root: record.root,
|
|
3126
|
-
...record.proc.sandbox === void 0 ? {} : { sandbox: record.proc.sandbox },
|
|
3127
|
-
output: (view.output.earliest > 0 ? marks.jobOutputTruncated : "") + (record.state.lost ? marks.jobOutputLost : "") + (record.state.timeoutNote ?? "") + (procSandboxNote(record.proc, marks) ?? "") + viewMark + shown
|
|
3128
|
-
});
|
|
3117
|
+
evictAged(cache, max, (entry) => entry.probedAt + ttlMs, at);
|
|
3118
|
+
return result;
|
|
3119
|
+
};
|
|
3129
3120
|
}
|
|
3130
3121
|
/**
|
|
3131
|
-
*
|
|
3132
|
-
*
|
|
3133
|
-
*
|
|
3122
|
+
* 工作区白名单:只认本 daemon 真实观测过的会话工作区(重建与 root 授权共用)。
|
|
3123
|
+
*
|
|
3124
|
+
* 条目记的是**最后一次被提到**的时刻,不是第一次:白名单的用途是「这棵树刚被用过」,
|
|
3125
|
+
* 一直热着的键理应活得比冷键久。故 `has` 命中即触摸,淘汰先按有效期、再按最近使用。
|
|
3126
|
+
* 有效期是固定的 `LEDGER_TTL_MS`(一天),与解锁时效那个部署值无关——后者只有 1–240 分钟
|
|
3127
|
+
* 的取值域,量级差两个数量级,拿来当「这棵树多久算还在用」会短到让跨天的会话反复重新登记。
|
|
3128
|
+
* 上界与有效期两道都留着:上界保证常驻内存有界,有效期保证冷键不长期占位。
|
|
3134
3129
|
*/
|
|
3135
|
-
function
|
|
3136
|
-
const
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
3140
|
-
|
|
3141
|
-
|
|
3142
|
-
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
|
|
3147
|
-
|
|
3148
|
-
|
|
3149
|
-
|
|
3150
|
-
|
|
3151
|
-
|
|
3152
|
-
|
|
3153
|
-
|
|
3154
|
-
|
|
3155
|
-
const { records } = deps;
|
|
3156
|
-
const routes = {
|
|
3157
|
-
host,
|
|
3158
|
-
config,
|
|
3159
|
-
csrf,
|
|
3160
|
-
ledger,
|
|
3161
|
-
messages,
|
|
3162
|
-
jobsOf,
|
|
3163
|
-
records,
|
|
3164
|
-
rebuilds,
|
|
3165
|
-
versionGate,
|
|
3166
|
-
serverGate,
|
|
3167
|
-
servingNonLoopback
|
|
3168
|
-
};
|
|
3169
|
-
const disposeRoots = webServer.register({
|
|
3170
|
-
kind: "exact",
|
|
3171
|
-
path: REBUILD_ROOTS_PATH,
|
|
3172
|
-
handler: async (req, res) => {
|
|
3173
|
-
await handleRebuildRoots(routes, req, res);
|
|
3174
|
-
}
|
|
3175
|
-
});
|
|
3176
|
-
const disposeRebuild = webServer.register({
|
|
3177
|
-
kind: "exact",
|
|
3178
|
-
path: REBUILD_PATH,
|
|
3179
|
-
handler: async (req, res) => {
|
|
3180
|
-
await handleRebuildStart(routes, req, res);
|
|
3181
|
-
}
|
|
3182
|
-
});
|
|
3183
|
-
const disposeStatus = webServer.register({
|
|
3184
|
-
kind: "exact",
|
|
3185
|
-
path: REBUILD_STATUS_PATH,
|
|
3186
|
-
handler: (req, res) => {
|
|
3187
|
-
handleRebuildStatus(routes, req, res);
|
|
3130
|
+
function createRootLedger(messages, max = MAX_LEDGER_ROOTS, now = Date.now, ttlMs = LEDGER_TTL_MS) {
|
|
3131
|
+
const seen = /* @__PURE__ */ new Map();
|
|
3132
|
+
return {
|
|
3133
|
+
add(root) {
|
|
3134
|
+
const key = ledgerKey(root, messages);
|
|
3135
|
+
if (key === void 0) return;
|
|
3136
|
+
touch(seen, key, now());
|
|
3137
|
+
evictAged(seen, max, (seenAt) => seenAt + ttlMs, now());
|
|
3138
|
+
},
|
|
3139
|
+
has(root) {
|
|
3140
|
+
const key = ledgerKey(root, messages);
|
|
3141
|
+
if (key === void 0) return false;
|
|
3142
|
+
const seenAt = seen.get(key);
|
|
3143
|
+
if (seenAt === void 0 || now() - seenAt >= ttlMs) return false;
|
|
3144
|
+
touch(seen, key, seenAt);
|
|
3145
|
+
return true;
|
|
3146
|
+
},
|
|
3147
|
+
list() {
|
|
3148
|
+
const at = now();
|
|
3149
|
+
return [...seen].filter(([, seenAt]) => at - seenAt < ttlMs).map(([root]) => root);
|
|
3188
3150
|
}
|
|
3189
|
-
}
|
|
3190
|
-
ctx.effect(() => () => {
|
|
3191
|
-
disposeRoots();
|
|
3192
|
-
disposeRebuild();
|
|
3193
|
-
disposeStatus();
|
|
3194
|
-
releaseRebuildRecords(routes);
|
|
3195
|
-
}, "zvec-grep: rebuild endpoints");
|
|
3151
|
+
};
|
|
3196
3152
|
}
|
|
3197
3153
|
/**
|
|
3198
3154
|
* 页面策略声明:本包自带设置卡片,别让宿主再生成一份自动表单页。
|
|
@@ -3213,7 +3169,7 @@ function configureSettingsPage(host) {
|
|
|
3213
3169
|
}
|
|
3214
3170
|
/**
|
|
3215
3171
|
* 文案语言随官方 locale 偏好走的读取器:用户在「设置 → 常规」里改语言后,下一次工具回显、
|
|
3216
|
-
* guard
|
|
3172
|
+
* guard 拒绝与重建应答就是新文案(不重启、不加本包自己的 locale 设置项)。
|
|
3217
3173
|
* 跨命名空间读在 0.1.7 只有 describe() 一条路:挑出 ns === 'locale' 那条的 value
|
|
3218
3174
|
* (未装 client-locale / 该条目未被投影 → undefined → 中文默认)。
|
|
3219
3175
|
* @param host 已通过服务面守卫的宿主上下文
|
|
@@ -3222,7 +3178,7 @@ function configureSettingsPage(host) {
|
|
|
3222
3178
|
function createLocaleMessages(host) {
|
|
3223
3179
|
return () => messagesFor(MESSAGES, resolveLocalePreference(host.settings.describe().find((row) => row.ns === LOCALE_SETTINGS_NAMESPACE)?.value));
|
|
3224
3180
|
}
|
|
3225
|
-
/**
|
|
3181
|
+
/** 观测到的工作区:既给重建当白名单,也让卡片能列出可重建的 root。 */
|
|
3226
3182
|
function trackObservedRoot(ledger, exec) {
|
|
3227
3183
|
const cwd = sessionHeaderCwd(exec);
|
|
3228
3184
|
if (cwd !== void 0) ledger.add(cwd);
|
|
@@ -3413,7 +3369,7 @@ function pickExhaustive(value, hasIndex) {
|
|
|
3413
3369
|
*
|
|
3414
3370
|
* 没人要这一档时交回 `daemon-down`——构造器只在 `refresh` 真的是 background 时才读它,
|
|
3415
3371
|
* 于是「不为没人要的档位起一发探测」与「拿不到判据时保守拒绝」两头同时成立,不必再引入
|
|
3416
|
-
* 第三种「不适用」状态。探测结果与 zg_status
|
|
3372
|
+
* 第三种「不适用」状态。探测结果与 zg_status 的回显、设置卡的引导读面共用同一份 TTL 缓存。
|
|
3417
3373
|
*/
|
|
3418
3374
|
async function backgroundSupportFor(runtime, rawRefresh, mode, exhaustive) {
|
|
3419
3375
|
if (exhaustive || !requestsBackgroundRefresh(rawRefresh)) return "daemon-down";
|
|
@@ -3449,7 +3405,7 @@ async function runSearchTool(runtime, args, exec, messages) {
|
|
|
3449
3405
|
env: zgEnv(config),
|
|
3450
3406
|
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
3451
3407
|
messages,
|
|
3452
|
-
summaryLimit: clampLimit(searchArgs.limit),
|
|
3408
|
+
summaryLimit: clampLimit(searchArgs.limit, messages),
|
|
3453
3409
|
rebuildWait: {
|
|
3454
3410
|
root: resolvedRoot,
|
|
3455
3411
|
rebuilds: runtime.rebuilds,
|
|
@@ -3550,7 +3506,7 @@ function indexToolParameters(registered) {
|
|
|
3550
3506
|
* 为什么不要求模型自己去起作业:宿主作业工具在 web 平面已停用,模型侧那条路根本不可走;
|
|
3551
3507
|
* 插件自己复用与设置卡**完全相同**的 spawn/登记/占位三步(`spawnIndexWrite` 与
|
|
3552
3508
|
* `attachIndexWrite` 是同两个函数,不是复制品),所以两条入口起的作业在名册、状态投影、
|
|
3553
|
-
*
|
|
3509
|
+
* 轮询读面上完全同形——卡片能看见模型起的重建,反之亦然。
|
|
3554
3510
|
*
|
|
3555
3511
|
* 占位在 `runIndexTool` 里、且落在第一个 await 之前就抢好了;本函数只管把已占的位接上作业号。
|
|
3556
3512
|
* 三条失败出口(注册表缺席 / spawn 失败 / attach 失败)都**交还占位**再抛或答复。
|
|
@@ -3784,50 +3740,17 @@ function registerToolGuards(runtime) {
|
|
|
3784
3740
|
}, messages);
|
|
3785
3741
|
});
|
|
3786
3742
|
}
|
|
3787
|
-
/**
|
|
3788
|
-
* 设置卡片的「工作区重建」端点组(引导 + 后台进程 + 轮询状态)。
|
|
3789
|
-
*
|
|
3790
|
-
* ⚠ 这三条路由的归属方必须对 webServer **建立依赖**,不能在 apply 里读一次就算完:
|
|
3791
|
-
* `ctx.get` 是无 inject 语义的存储读(官方 reflect.d.ts 明写 "or `undefined`
|
|
3792
|
-
* when not (yet) provided"),而真实宿主上 webServer 比本条目晚到位——隔离 DSH_HOME
|
|
3793
|
-
* 实测 apply 当场读到 undefined、+1.3s 才交得出实例。旧写法的结果是三条路由在任何
|
|
3794
|
-
* web profile 上都不注册,卡片的「工作区重建」永远 404。子 fiber 只在依赖到位时激活、
|
|
3795
|
-
* 依赖换实例时先卸后装(registry.d.ts),故效应挂在**子上下文**上即得「后到即注册、
|
|
3796
|
-
* 重启即重注册」。不写进插件级 inject:那会让没有 webServer 的宿主(TUI)连三个工具
|
|
3797
|
-
* 一并失活。
|
|
3798
|
-
* @param runtime apply 的运行时依赖(host / config / 白名单 / 文案读取器)
|
|
3799
|
-
* @param csrf 本次 apply 生成的 CSRF token
|
|
3800
|
-
* @returns {void}
|
|
3801
|
-
*/
|
|
3802
|
-
function registerRebuildRoutes(runtime, csrf) {
|
|
3803
|
-
const { config, host, ledger, messages, rebuilds, versionGate, serverGate } = runtime;
|
|
3804
|
-
host.inject(["webServer"], (child) => {
|
|
3805
|
-
registerRebuildEndpoints({
|
|
3806
|
-
ctx: child,
|
|
3807
|
-
host,
|
|
3808
|
-
config,
|
|
3809
|
-
csrf,
|
|
3810
|
-
ledger,
|
|
3811
|
-
messages,
|
|
3812
|
-
rebuilds,
|
|
3813
|
-
jobsOf: runtime.jobsOf,
|
|
3814
|
-
records: runtime.records,
|
|
3815
|
-
versionGate,
|
|
3816
|
-
serverGate
|
|
3817
|
-
});
|
|
3818
|
-
});
|
|
3819
|
-
}
|
|
3820
3743
|
function apply(ctx, config) {
|
|
3821
3744
|
if (!isZvecGrepHost(ctx)) throw new Error("[zvec-grep] required services (settings/shell/tools/systemPrompt/timer/get) missing");
|
|
3822
3745
|
const host = ctx;
|
|
3823
3746
|
configureSettingsPage(host);
|
|
3824
3747
|
const localeMessages = createLocaleMessages(host);
|
|
3825
|
-
const
|
|
3748
|
+
const ledger = createRootLedger(localeMessages());
|
|
3826
3749
|
const runtime = {
|
|
3827
3750
|
host,
|
|
3828
3751
|
config,
|
|
3829
3752
|
messages: localeMessages,
|
|
3830
|
-
ledger
|
|
3753
|
+
ledger,
|
|
3831
3754
|
unlocks: createUnlockLedger(config),
|
|
3832
3755
|
indexProbe: createIndexProbeCache(indexProbeOf),
|
|
3833
3756
|
rebuilds: createRebuildRegistry(),
|
|
@@ -3846,7 +3769,17 @@ function apply(ctx, config) {
|
|
|
3846
3769
|
registerRoutingSection(host, registered);
|
|
3847
3770
|
registerToolGuards(runtime);
|
|
3848
3771
|
registerRootApproval(runtime);
|
|
3849
|
-
|
|
3772
|
+
installRebuildRemote(host, {
|
|
3773
|
+
host,
|
|
3774
|
+
config,
|
|
3775
|
+
messages: localeMessages,
|
|
3776
|
+
jobsOf: runtime.jobsOf,
|
|
3777
|
+
records: runtime.records,
|
|
3778
|
+
rebuilds: runtime.rebuilds,
|
|
3779
|
+
versionGate: runtime.versionGate,
|
|
3780
|
+
ledger,
|
|
3781
|
+
serverGate: runtime.serverGate
|
|
3782
|
+
});
|
|
3850
3783
|
}
|
|
3851
3784
|
var host_default = {
|
|
3852
3785
|
inject: [
|