@jayyuen66/dsh-zvec-grep 0.1.11 → 0.1.13
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 +88 -45
- package/README.md +21 -19
- package/README.zh-CN.md +46 -44
- package/THIRD_PARTY_NOTICES.md +4 -4
- package/client.js +128 -630
- package/cordis.patch.yml +4 -1
- package/docs/DETAIL.md +13 -6
- package/docs/DETAIL.zh.md +14 -7
- package/host.js +1739 -649
- package/package.json +50 -48
package/host.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
// GENERATED by build-host.mjs — edit host.ts / lib/*.ts, then run `node build-host.mjs`.
|
|
2
2
|
import Schema from "@deepseek-ai/schemastery";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
3
4
|
import { accessSync, constants, existsSync, readFileSync, statSync } from "node:fs";
|
|
4
|
-
import { tmpdir } from "node:os";
|
|
5
|
+
import { homedir, tmpdir } from "node:os";
|
|
6
|
+
import nodePath from "node:path";
|
|
5
7
|
import { scopeOf } from "@deepseek-ai/dsh-scope";
|
|
6
8
|
import { isRecord } from "@jayyuen66/dsh-plugin-shared/lib/record";
|
|
7
9
|
import { errorText } from "@jayyuen66/dsh-plugin-shared/lib/errors";
|
|
@@ -9,7 +11,7 @@ import { LOCALE_SETTINGS_NAMESPACE, messagesFor, resolveLocalePreference } from
|
|
|
9
11
|
import { truncateEnd, truncateStart } from "@jayyuen66/dsh-plugin-shared/lib/text";
|
|
10
12
|
import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
|
|
11
13
|
import { jobOutcomeOf } from "@jayyuen66/dsh-plugin-shared/lib/job-outcome";
|
|
12
|
-
import
|
|
14
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
13
15
|
// lib/embedding-catalog.ts
|
|
14
16
|
/** 默认模型:本地最强(1024 维 / 8192 上下文 / 中英通用),约 640MB 一次性下载。 */
|
|
15
17
|
const DEFAULT_EMBEDDING = "local/qwen3-embedding-0.6b";
|
|
@@ -80,6 +82,28 @@ function isLocalEmbedding(reference) {
|
|
|
80
82
|
const normalized = reference.trim();
|
|
81
83
|
return LOCAL_EMBEDDINGS.some((entry) => entry.reference === normalized);
|
|
82
84
|
}
|
|
85
|
+
const REMOTE_EMBEDDING_CATALOG = Object.freeze([
|
|
86
|
+
{
|
|
87
|
+
reference: "qwen/qwen3-vl-embedding",
|
|
88
|
+
dimension: 2560
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
reference: "qwen/qwen3.7-text-embedding",
|
|
92
|
+
dimension: 1024
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
reference: "qwen/text-embedding-v4",
|
|
96
|
+
dimension: 1024
|
|
97
|
+
}
|
|
98
|
+
].map((entry) => Object.freeze(entry)));
|
|
99
|
+
function isRemoteEmbedding(reference) {
|
|
100
|
+
const normalized = reference.trim();
|
|
101
|
+
return REMOTE_EMBEDDING_CATALOG.some((entry) => entry.reference === normalized);
|
|
102
|
+
}
|
|
103
|
+
/** 构造期 allowlist 的全集:本地 ∪ 远程。未知引用在任何部署开关下都不放行。 */
|
|
104
|
+
function isKnownEmbedding(reference) {
|
|
105
|
+
return isLocalEmbedding(reference) || isRemoteEmbedding(reference);
|
|
106
|
+
}
|
|
83
107
|
// lib/messages.ts
|
|
84
108
|
/** 中文侧「绝对路径 + 可操作范围」那句共用文案(三个 root 参数同义、同一份判据)。 */
|
|
85
109
|
const ABSOLUTE_ROOT_HINT_ZH = "工作区绝对路径(可选:缺省=当前会话工作区;显式传入时须在本会话可操作范围内——会话工作区本身、其上级或下级、或本会话已登记过的工作区)";
|
|
@@ -99,8 +123,8 @@ const MESSAGES = {
|
|
|
99
123
|
vectorDescription: "纯语义查询组",
|
|
100
124
|
fuseDescription: "融合所有组为单一排名",
|
|
101
125
|
limitDescription: "每组最大条数 1-50,默认 10;越出区间直接报错",
|
|
102
|
-
previewDescription: "每条命中带的源码片段大小:none 只给锚点行、short
|
|
103
|
-
refreshDescription: "检索前如何刷新索引:wait 等刷新到最新(默认)、off 不刷新、background 交给守护进程后台刷新。background 只在守护进程就绪时可用:没有守护进程时这一档在命令构造前就被拒绝(直连模式下 zg 只会静默关掉刷新并留一行 stderr warning,那等于把「没刷新」说成「后台在刷」),要它请先在终端执行 `zg server on`",
|
|
126
|
+
previewDescription: "每条命中带的源码片段大小:none 只给锚点行、short 给锚点加一段有界上下文(默认)、full 给整段源码、detail 另附符号/签名/Range 等结构化字段并按文件分组",
|
|
127
|
+
refreshDescription: "检索前如何刷新索引:wait 等刷新到最新(默认)、off 不刷新、background 交给守护进程后台刷新。background 只在守护进程就绪时可用:没有守护进程时这一档在命令构造前就被拒绝(直连模式下 zg 只会静默关掉刷新并留一行 stderr warning,那等于把「没刷新」说成「后台在刷」),要它请先在终端执行 `zg --server on`",
|
|
104
128
|
globsDescription: "路径 glob(如 src/**),单个字符串或数组",
|
|
105
129
|
globsIndexDescription: "路径 glob",
|
|
106
130
|
insensitiveGlobsDescription: "大小写不敏感 glob",
|
|
@@ -111,10 +135,14 @@ const MESSAGES = {
|
|
|
111
135
|
preferSymbolDescription: "优先精确符号",
|
|
112
136
|
modifiedAfterDescription: "只搜该时间后修改的文件",
|
|
113
137
|
modifiedBeforeDescription: "只搜该时间前修改的文件",
|
|
114
|
-
deviceDescription: "auto/cpu/metal/vulkan/cuda;默认 auto(Metal 加速,失败自动回退 CPU
|
|
138
|
+
deviceDescription: "auto/cpu/metal/vulkan/cuda;默认 auto(Metal 加速,失败自动回退 CPU)。仅 CLI 传输消费:MCP 传输(守护进程)的检索面没有这一位,显式传入会被拒绝",
|
|
139
|
+
filesDescription: "文件发现模式(对应 zg --rg --files):不搜索内容,按当前过滤规则(globs/fileTypes/modifiedAfter/…)列出文件清单——默认感知 .gitignore/.ignore/.rgignore,输出已排序且无条数上限(--limit 不适用)。与 query/queries/fts/vector/fuse/limit/preview/refresh 及全部索引侧参数互斥,也不发放 grep/rg 配额",
|
|
140
|
+
categoryDescription: "引擎分类过滤(如 code、document),单个字符串或数组",
|
|
141
|
+
categoryNotDescription: "排除的引擎分类,单个字符串或数组",
|
|
142
|
+
nestedGitDescription: "扫描嵌套 Git 仓库与子模块(默认不含)",
|
|
115
143
|
resetPathsDescription: "清掉这个根继承来的文件选择设置(globs/fileTypes/hidden/… 全部回到未设置),只影响本次写入的索引配置;可与 globs/fileTypes 同传(先清干净再按这次的规则选),但与 drop 互斥",
|
|
116
144
|
confirmDescription: "用户已明确要求本次建/重建/删索引,必须为 true",
|
|
117
|
-
embeddingDescription: "
|
|
145
|
+
embeddingDescription: "embedding 模型引用(默认取设置 defaultEmbedding)。本地清单内的模型直接可选;远程 qwen 模型须由用户在部署配置里打开 allowRemoteEmbedding 才可选(远程会把工作区内容送到外部端点,首次索引还要用户执行一次 zg --auth grant 授权),本插件不接受模型侧自行开启",
|
|
118
146
|
rebuildDescription: "重建已有索引(切换 embedding 时必须为 true)",
|
|
119
147
|
dropDescription: "删除索引(与其它索引选项互斥)",
|
|
120
148
|
ignoreFilesDescription: "额外的 ignore 文件路径(如 .gitignore 之外的排除清单),透传 zg --ignore-file",
|
|
@@ -129,7 +157,7 @@ const MESSAGES = {
|
|
|
129
157
|
"# zvec-grep(zg)工作区检索规则",
|
|
130
158
|
"",
|
|
131
159
|
"本环境的工作区检索路由:",
|
|
132
|
-
"- 工作区已建 zg 索引(存在 .zvec-grep/
|
|
160
|
+
"- 工作区已建 zg 索引(存在 .zvec-grep/manifest.json)时:所有检索必须先调用 zg_search(语义/混合,命中更全更准);grep/rg 只作为 zg_search 之后的精确字面/正则补充。每次成功的 zg_search 解锁少量 grep/rg 配额(次数/时效见设置),配额用尽或过期后门禁会再次拦截,此时应换一个更准确的 query/fts 重新 zg_search。门禁同时覆盖 bash 里的 grep/rg 命令与原生 grep 工具。",
|
|
133
161
|
"- 无索引工作区:zg_search 会自动改走**穷举词法检索**(逐行字面匹配,结果里会有一条前置声明)。精确查找(单个定义、字面量、文件名、配置键、报错信息、正则、穷举列表)用 zg_search 就够,不必先 zg_index(那要先下载 embedding 权重)。也可显式 rg=true 强制它,或 rg=false 拒绝改道。穷举检索是纯字面匹配,回答不了「这个模块的职责是什么」这类语义问题——那类问题仍应先建索引。",
|
|
134
162
|
"- 穷举检索**不发放** grep/rg 配额:它不读索引,不构成「先用过语义检索」的证据。有索引的工作区想用 grep/rg,仍要先走一次索引检索。",
|
|
135
163
|
"- 语义/关系/跨文件/多跳证据(架构、调用链、依赖、生命周期、数据流或控制流、设计意图、对比、跨文件综合)→ 必须先调用 zg_search。",
|
|
@@ -154,7 +182,13 @@ const MESSAGES = {
|
|
|
154
182
|
abortedFailure: "zg 执行被中止",
|
|
155
183
|
rebuildWaitTimeout: "等待 {root} 的重建完成超时(约 {seconds} 秒),重建可能仍在进行;请稍后重试。本次不会发放 grep/rg 配额——重建期间索引不可读,先等它结束。",
|
|
156
184
|
rebuildWaitAborted: "等待 {root} 的重建完成时被中止。",
|
|
157
|
-
lockBusyOtherOperation: "zg 索引锁正被其他操作占用(
|
|
185
|
+
lockBusyOtherOperation: "zg 索引锁正被其他操作占用(operation: {op}),本命令没有等待它结束:这类操作(如索引刷新)可能耗时很久,稍后重试或等它落定后再查",
|
|
186
|
+
remoteAuthDenied: "[zvec-grep] 这次索引被 zg 以远程授权拦下(上游报错原文里带有可照抄的 `zg --auth grant` 命令)。两条出路:让用户在持有终端时执行那条 grant(对工作区持久授权),或在插件部署配置里打开 allowRemoteEmbedding 并配好端点与凭据环境变量后重试——本插件不会替用户把工作区内容送出本机。",
|
|
187
|
+
daemonUrlInvalid: "daemonUrl 不是可用的 MCP 端点:{received}。需要 `http(s)://<host>[:<port>]/mcp`(默认 `http://127.0.0.1:7999/mcp`);transport=mcp 自启 daemon 时还会把它的 host:port 作为 `--listen`。改回合法端点或把 transport 换回「自动」/「仅 CLI」后重载插件。",
|
|
188
|
+
daemonStartFailed: "transport=mcp 需要守护进程,但自动拉起失败:{detail}。出路:在持有终端时手动执行 `zg --server on`(daemonUrl 不是默认端点时补 `--listen <host:port>`)后重试;或把设置卡的传输方式换回「自动」/「仅 CLI」。插件把自启 token 持久化在 `<ZVEC_GREP_HOME 或 ~/.zvec-grep>/dsh-zvec-grep.token`(0600),正常崩溃/重启会复用它;该文件丢失时才需要手工收尾:`zg --server status` 不需要令牌,可读到 PID,终止那个进程(POSIX `kill <pid>`;Windows `Stop-Process -Id <pid>`)后让本插件重新拉起;`zg --server off` 同样需要那枚已丢失的令牌。",
|
|
189
|
+
deviceUnsupportedOnDaemon: "device 参数仅 CLI 传输消费:守护进程(MCP 传输)的检索面没有这一位。去掉该参数重试,或改用「仅 CLI」传输档。",
|
|
190
|
+
mcpCallFailed: "zg 守护进程调用失败:{detail}",
|
|
191
|
+
daemonFallbackNote: "[zvec-grep] 守护进程调用失败,本次已回退到 CLI 通道(下次会重新探测守护进程):{detail}",
|
|
158
192
|
statusRebuilding: "{root} 正在重建中(作业 {jobId})。重建期间索引不可读,检索会自动等待它完成后重试。如需查看实时输出,请在设置卡的工作区重建面板里观察。此刻即使问「索引是否就绪」也是否定的答案——重建落定后再问。",
|
|
159
193
|
statusNotReady: "[zvec-grep] {root} 的索引**未就绪**(上面是 zg 的完整就绪报告)。这不是执行失败,而是 checkReady=true 要的那个结论:{detail} 若刷新反复失败(报告里出现 `read only mode` 一类写入被拒的措辞),那是该索引自身的状态问题,重建即可恢复:zg_index(root=\"…\", confirm=true, rebuild=true)。",
|
|
160
194
|
checkReadyDescription: "就绪判定:就绪报告照常给出,另行判定索引是否 ready 并在结论里明说。未就绪不是执行失败,报告仍会返回",
|
|
@@ -173,14 +207,12 @@ const MESSAGES = {
|
|
|
173
207
|
genericFailure: "zg 执行失败(exit={exit}){detail}",
|
|
174
208
|
detailPrefix: " 详情:{detail}",
|
|
175
209
|
detailColon: ":{detail}",
|
|
176
|
-
noErrorCodeHint: "(这条失败没有 zg 的结构化 `
|
|
210
|
+
noErrorCodeHint: "(这条失败没有 zg 的结构化 `Error[码]:` 行,本包无法按码归因。上游对部分失败会塌成一句无码文本;要拿到可归因的完整输出,请让持有终端的用户把同一条命令加上 `--debug` 复跑一次)",
|
|
177
211
|
outputTruncated: "[zvec-grep] 注意:输出超过 {maxBytes} 字节上限,已截断,仅保留尾部{spill}。如需完整结果请缩小检索范围(更精确的 query / 更小的 limit / 更窄的 root)。",
|
|
178
212
|
spillNote: "(完整输出已落盘:{path})",
|
|
179
213
|
sandboxWarning: "[zvec-grep] 警告:{denied}——下面的结果可能缺少被拒读写的文件,别把它当成全工作区的完整检索结论。",
|
|
180
214
|
stderrNote: "[zvec-grep] zg stderr(可能含降级提示,如退化为纯词法检索 / 跳过 --refresh):{marked}{tail}",
|
|
181
|
-
hitSummary: "[zvec-grep]
|
|
182
|
-
hitDedup: ",去重后 {unique} 个不同位置",
|
|
183
|
-
hitCapped: "(有组的命中数正好等于 --limit;zg 不提供截断信号,此处只陈述计数,不推断是否还有更多)",
|
|
215
|
+
hitSummary: "[zvec-grep] 命中摘要:去重后 {unique} 个不同位置(请求 --limit {limit}{truncated})",
|
|
184
216
|
hitTruncated: ";输出已截尾,计数只含保留部分",
|
|
185
217
|
rootMissing: "root 目录不存在(zg 需要真实存在的工作区路径):{root}",
|
|
186
218
|
jobOutputTruncated: "\n[zvec-grep] 输出过长,已截断,只保留尾部",
|
|
@@ -205,10 +237,10 @@ const MESSAGES = {
|
|
|
205
237
|
clientModeInvalid: "zg 传输模式非法:{received}(合法取值:{allowed})",
|
|
206
238
|
previewInvalid: "预览档位非法:{received}(合法取值:{allowed})",
|
|
207
239
|
refreshInvalid: "刷新策略非法:{received}(合法取值:{allowed})",
|
|
208
|
-
refreshBackgroundNeedsServer: "{root} 没有可用的 zg 守护进程,`refresh=background` 因此被拒绝——它只在守护进程模式下成立。缺了守护进程时这次调用要的是 background,而上游只会往 stderr 打一行 warning 就把**刷新整个关掉**,所以这里不再替它把「没刷新」说成「后台在刷」。两条出路:按默认 refresh=wait(检索前同步刷到最新,直连模式可用),或在持有终端时先执行 `zg server on` 再来要后台刷新——后者还会顺带带来索引增量刷新与常驻的模型池。",
|
|
240
|
+
refreshBackgroundNeedsServer: "{root} 没有可用的 zg 守护进程,`refresh=background` 因此被拒绝——它只在守护进程模式下成立。缺了守护进程时这次调用要的是 background,而上游只会往 stderr 打一行 warning 就把**刷新整个关掉**,所以这里不再替它把「没刷新」说成「后台在刷」。两条出路:按默认 refresh=wait(检索前同步刷到最新,直连模式可用),或在持有终端时先执行 `zg --server on` 再来要后台刷新——后者还会顺带带来索引增量刷新与常驻的模型池。",
|
|
209
241
|
refreshBackgroundPinnedDirect: "{root} 这次检索把 `refresh=background` 拒绝了:本 daemon 的传输模式被部署钉死在 direct(行 config 的 `clientMode: direct`),而后台刷新只在 server 模式下存在。这一档**不是**起一个守护进程能解决的——出路是把行 config 的 clientMode 改回 auto 或 server,或按缺省的 refresh=wait 检索。",
|
|
210
242
|
serverReadyNote: "[zvec-grep] 守护进程:就绪(检索可走 server 模式:索引增量刷新、embedding 模型池常驻)",
|
|
211
|
-
serverUnavailableNote: "[zvec-grep] 守护进程:未就绪。检索因此按直连模式逐次冷加载 embedding 模型(大工作区会更慢,且 refresh=background 不可用);需要增量索引与常驻模型池时,请在持有终端执行 `zg server on`",
|
|
243
|
+
serverUnavailableNote: "[zvec-grep] 守护进程:未就绪。检索因此按直连模式逐次冷加载 embedding 模型(大工作区会更慢,且 refresh=background 不可用);需要增量索引与常驻模型池时,请在持有终端执行 `zg --server on`",
|
|
212
244
|
symbolTypeInvalid: "符号类型非法:{received}(合法取值:{allowed},只接受小写)",
|
|
213
245
|
rootEscapesFs: "root 含越界的 .. 段:{path}",
|
|
214
246
|
rootMustBeString: "root 必须是字符串(收到 {received})",
|
|
@@ -227,12 +259,13 @@ const MESSAGES = {
|
|
|
227
259
|
searchNeedsQuery: "zg_search 需要 query/queries/fts/vector 至少其一",
|
|
228
260
|
exhaustiveNeedsPattern: "穷举检索(rg=true)需要一个 query 作为匹配模式",
|
|
229
261
|
exhaustiveConflicts: "穷举检索(rg=true)与下列索引侧参数互斥:{names}。穷举是纯词法匹配,不支持这些参数;把它们去掉,或先建索引(zg_index)再用索引检索",
|
|
230
|
-
|
|
262
|
+
filesConflicts: "文件发现模式(files=true)与这些参数互斥:{names}。它只列文件、不搜内容——query 会被当成路径、limit 没有意义(上游明拒)、device 不参与文件发现;请去掉这些参数后重发",
|
|
263
|
+
embeddingNotAllowed: "embedding 引用 {reference} 不在候选清单内。可选本地模型:{choices};远程模型(qwen/*)需在部署配置里打开 allowRemoteEmbedding 才可选,且首次索引要用户授权(zg --auth grant <root> --capability embedding --scope workspace)。未知前缀的引用在任何开关下都不放行——远程端点会把工作区内容送出本机,这个决定必须由用户显式做出。",
|
|
231
264
|
dropWithResetPaths: "drop 与 resetPaths 互斥:--drop 整条命令只有删除索引一件事,resetPaths 无处安放(上游 zg 也拒这一对)。要清继承的文件选择设置,请不要传 drop。",
|
|
232
265
|
dropWithIndexArgs: "drop 与这些索引侧参数互斥:{names}。--drop 整条命令只有删除索引一件事,它们不会被使用(静默收下只会让人以为过滤/重建生效了);请去掉这些参数后重发删除。",
|
|
233
|
-
ignoreFileMissing: "ignoreFiles 里的 {path}
|
|
266
|
+
ignoreFileMissing: "ignoreFiles 里的 {path} 不是一份「存在且当前进程可读的文件」(不存在、是目录、或有文件但读不了都算)。0.3.0 的 zg 对读不成的忽略文件会静默容忍——索引照常建立,但那条排除规则悄悄不生效(你以为它在挡文件,实际什么都没排除),本包因此在构造前就把坏路径拦下。请给一个真实存在、当前用户可读的忽略文件路径。",
|
|
234
267
|
exhaustiveFallbackNote: "[zvec-grep] 该工作区(含向上各级)尚无 zg 索引,已自动改用穷举词法检索(rg 模式)。结果是逐行字面匹配,不是语义相关度排序;需要语义检索请先 zg_index 建索引。",
|
|
235
|
-
rgDescription: "穷举词法检索(对应 zg
|
|
268
|
+
rgDescription: "穷举词法检索(对应 zg --rg):不需要索引,逐行字面匹配。留空则在工作区无索引时自动改用它、有索引时照常走索引检索。显式 false 可要求只用索引检索(无索引即报错)。它不支持 preview / refresh / fuse / symbolTypes / preferSymbol / fts / vector / queries / category,且不发放 grep/rg 配额",
|
|
236
269
|
intWithReceived: "{name} 必须是 >= {min} 的整数(收到 {received})",
|
|
237
270
|
intRequired: "{name} 必须是 >= {min} 的整数",
|
|
238
271
|
guardRootRejected: "{name} 的 root 不被接受:{reason}",
|
|
@@ -256,8 +289,8 @@ const MESSAGES = {
|
|
|
256
289
|
vectorDescription: "Purely semantic query groups",
|
|
257
290
|
fuseDescription: "Fuse all groups into a single ranking",
|
|
258
291
|
limitDescription: "Max hits per group, 1-50, default 10; a value outside that range is refused",
|
|
259
|
-
previewDescription: "How much source each hit carries: none anchor line only, short anchor plus a bounded context window, full the whole chunk
|
|
260
|
-
refreshDescription: "How the index is refreshed before searching: wait refreshes to the latest (default), off does not refresh, background hands it to the daemon. background needs a ready daemon: without one it is refused before the command is built (in direct mode zg silently turns refreshing off and leaves one stderr warning, which would report \"refreshing in the background\" when nothing refreshes) — run `zg server on` in a terminal to get it",
|
|
292
|
+
previewDescription: "How much source each hit carries: none anchor line only, short anchor plus a bounded context window (default), full the whole chunk, detail adds symbol/signature/Range metadata grouped per file",
|
|
293
|
+
refreshDescription: "How the index is refreshed before searching: wait refreshes to the latest (default), off does not refresh, background hands it to the daemon. background needs a ready daemon: without one it is refused before the command is built (in direct mode zg silently turns refreshing off and leaves one stderr warning, which would report \"refreshing in the background\" when nothing refreshes) — run `zg --server on` in a terminal to get it",
|
|
261
294
|
globsDescription: "Path globs (e.g. src/**), a single string or an array",
|
|
262
295
|
globsIndexDescription: "Path globs",
|
|
263
296
|
insensitiveGlobsDescription: "Case-insensitive globs",
|
|
@@ -268,10 +301,14 @@ const MESSAGES = {
|
|
|
268
301
|
preferSymbolDescription: "Prefer exact symbol matches",
|
|
269
302
|
modifiedAfterDescription: "Only search files modified after this time",
|
|
270
303
|
modifiedBeforeDescription: "Only search files modified before this time",
|
|
271
|
-
deviceDescription: "auto/cpu/metal/vulkan/cuda; default auto (Metal acceleration, falls back to CPU on failure)",
|
|
304
|
+
deviceDescription: "auto/cpu/metal/vulkan/cuda; default auto (Metal acceleration, falls back to CPU on failure). Consumed by the CLI transport only: the daemon (MCP transport) search surface has no such knob, and passing it is refused",
|
|
305
|
+
filesDescription: "File discovery mode (zg --rg --files): no content search — lists the files matching the current filters (globs/fileTypes/modifiedAfter/…). Respects .gitignore/.ignore/.rgignore by default; the list is sorted and uncapped (--limit does not apply). Conflicts with query/queries/fts/vector/fuse/limit/preview/refresh and every index-side parameter, and grants no grep/rg quota",
|
|
306
|
+
categoryDescription: "Engine category filter (e.g. code, document), a single string or an array",
|
|
307
|
+
categoryNotDescription: "Engine categories to exclude, a single string or an array",
|
|
308
|
+
nestedGitDescription: "Scan nested Git repositories and submodules (excluded by default)",
|
|
272
309
|
resetPathsDescription: "Clear the file-selection settings this root inherited (globs/fileTypes/hidden/… all go back to unset), affecting only the index config written this time. May be combined with globs/fileTypes (clear first, then apply this call's rules), but conflicts with drop",
|
|
273
310
|
confirmDescription: "The user explicitly asked for this index build/rebuild/drop; must be true",
|
|
274
|
-
embeddingDescription: "
|
|
311
|
+
embeddingDescription: "Embedding model reference (defaults to defaultEmbedding setting). Local catalog models are always selectable; the remote qwen models require allowRemoteEmbedding turned on in the deployment config (remote embedding sends workspace content to an external endpoint, and the first index build needs a one-time user authorization via zg --auth grant) — this plugin never lets the model side enable it",
|
|
275
312
|
rebuildDescription: "Rebuild the existing index (must be true when switching embedding)",
|
|
276
313
|
dropDescription: "Delete the index (mutually exclusive with the other index options)",
|
|
277
314
|
ignoreFilesDescription: "Extra ignore-file paths (exclusion lists beyond .gitignore), passed through as zg --ignore-file",
|
|
@@ -286,7 +323,7 @@ const MESSAGES = {
|
|
|
286
323
|
"# zvec-grep (zg) workspace search rules",
|
|
287
324
|
"",
|
|
288
325
|
"Search routing for this environment:",
|
|
289
|
-
"- When the workspace has a zg index (a .zvec-grep/
|
|
326
|
+
"- When the workspace has a zg index (a .zvec-grep/manifest.json exists): every search must call zg_search first (semantic/hybrid, broader and more precise hits); grep/rg only as the exact literal/regex follow-up after zg_search. Each successful zg_search unlocks a small grep/rg quota (count/window in the settings); once it is spent or expired the gate blocks again and you should re-run zg_search with a more precise query/fts. The gate covers both grep/rg commands inside bash and the native grep tool.",
|
|
290
327
|
"- Workspaces without an index: zg_search falls back to **exhaustive lexical search** (literal line-by-line matching, with a note saying so in front of the results). For exact lookups (a single definition, literals, file names, config keys, error messages, regexes, exhaustive lists) zg_search is enough — there is no need to zg_index first, which would mean downloading embedding weights. Pass rg=true to force it, or rg=false to refuse the fallback. Exhaustive search is purely literal and cannot answer questions like \"what is this module responsible for\" — for those, build an index first.",
|
|
291
328
|
"- Exhaustive search grants **no** grep/rg quota: it reads no index, so it is not evidence that semantic search has been used. In an indexed workspace, still run one indexed search before reaching for grep/rg.",
|
|
292
329
|
"- Semantic / relational / cross-file / multi-hop evidence (architecture, call chains, dependencies, lifecycles, data or control flow, design intent, comparisons, cross-file synthesis) → always call zg_search first.",
|
|
@@ -311,7 +348,13 @@ const MESSAGES = {
|
|
|
311
348
|
abortedFailure: "zg execution was aborted",
|
|
312
349
|
rebuildWaitTimeout: "timed out after about {seconds}s waiting for the rebuild of {root}; it may still be running. Retry later. No grep/rg quota is granted: the index is unreadable while the rebuild runs.",
|
|
313
350
|
rebuildWaitAborted: "aborted while waiting for the rebuild of {root} to finish",
|
|
314
|
-
lockBusyOtherOperation: "the zg index lock is held by another operation (
|
|
351
|
+
lockBusyOtherOperation: "the zg index lock is held by another operation (operation: {op}); this command did not wait for it: such operations (e.g. an index refresh) can run very long — retry later, or query again once it settles",
|
|
352
|
+
remoteAuthDenied: "[zvec-grep] zg refused this indexing on remote-authorization grounds (the upstream error text carries a ready-to-copy `zg --auth grant` command). Two ways out: have the user run that grant in a terminal (persistent per-workspace authorization), or turn on allowRemoteEmbedding in the plugin's deployment config with the endpoint and credential env configured, then retry — this plugin never sends workspace content off the machine on its own.",
|
|
353
|
+
daemonUrlInvalid: "daemonUrl is not a usable MCP endpoint: {received}. Expected `http(s)://<host>[:<port>]/mcp` (default `http://127.0.0.1:7999/mcp`); transport=mcp also passes its host:port as `--listen` when it starts the daemon. Fix the endpoint or switch transport back to auto/CLI, then reload the plugin.",
|
|
354
|
+
daemonStartFailed: "transport=mcp needs the daemon but auto-starting it failed: {detail}. Either run `zg --server on` in a terminal (add `--listen <host:port>` when daemonUrl is not the default endpoint) and retry, or switch the card's transport back to auto/CLI. The plugin persists its self-start token at `<ZVEC_GREP_HOME or ~/.zvec-grep>/dsh-zvec-grep.token` (0600) and reuses it after a crash/restart; only when that file is gone do you need to recover manually: `zg --server status` needs no token and prints the PID — terminate that process (POSIX `kill <pid>`; Windows `Stop-Process -Id <pid>`), then let the plugin start a new one; `zg --server off` also requires that lost token.",
|
|
355
|
+
deviceUnsupportedOnDaemon: "the device parameter is consumed by the CLI transport only: the daemon (MCP transport) search surface has no such knob. Drop the parameter and retry, or switch the transport to CLI-only.",
|
|
356
|
+
mcpCallFailed: "the zg daemon call failed: {detail}",
|
|
357
|
+
daemonFallbackNote: "[zvec-grep] the daemon call failed; this call fell back to the CLI transport (the next call probes the daemon again): {detail}",
|
|
315
358
|
statusRebuilding: "{root} is being rebuilt (job {jobId}). The index is unreadable while the rebuild runs; searches wait for it to finish and retry. Watch live output in the settings card rebuild panel. Asking whether the index is ready right now would get a negative answer anyway — ask again once the rebuild settles.",
|
|
316
359
|
statusNotReady: "[zvec-grep] the index for {root} is **not ready** (the full zg readiness report is above). This is not an execution failure, it is the conclusion checkReady=true asked for: {detail} If refreshes keep failing (wording like `read only mode` means writes are refused), that is the index's own state — rebuild it to recover: zg_index(root=\"…\", confirm=true, rebuild=true).",
|
|
317
360
|
checkReadyDescription: "Readiness verdict: the readiness report is still returned, and the tool additionally states whether the index is ready. Not-ready is not an execution failure — the report still comes back",
|
|
@@ -330,14 +373,12 @@ const MESSAGES = {
|
|
|
330
373
|
genericFailure: "zg failed (exit={exit}){detail}",
|
|
331
374
|
detailPrefix: " details: {detail}",
|
|
332
375
|
detailColon: ": {detail}",
|
|
333
|
-
noErrorCodeHint: "(this failure carries no structured `
|
|
376
|
+
noErrorCodeHint: "(this failure carries no structured `Error[<code>]:` line from zg, so it cannot be attributed by code. Upstream collapses some failures into a single uncode line — have a user with a terminal re-run the same command with `--debug` for attributable output)",
|
|
334
377
|
outputTruncated: "[zvec-grep] note: output exceeded the {maxBytes} byte limit and was truncated, only the tail is kept{spill}. Narrow the search for full results (sharper query / smaller limit / narrower root).",
|
|
335
378
|
spillNote: " (full output spilled to {path})",
|
|
336
379
|
sandboxWarning: "[zvec-grep] warning: {denied} — the result below may be missing files that were denied; do not treat it as a complete whole-workspace conclusion.",
|
|
337
380
|
stderrNote: "[zvec-grep] zg stderr (may contain degradation notes, e.g. falling back to pure lexical search / skipping --refresh): {marked}{tail}",
|
|
338
|
-
hitSummary: "[zvec-grep] hit summary: {
|
|
339
|
-
hitDedup: ", {unique} distinct location(s) after dedup",
|
|
340
|
-
hitCapped: " (some group's hit count equals --limit; zg gives no truncation signal, so this states the count only and infers nothing about further hits)",
|
|
381
|
+
hitSummary: "[zvec-grep] hit summary: {unique} distinct location(s) after dedup (requested --limit {limit}{truncated})",
|
|
341
382
|
hitTruncated: "; output truncated, the count covers only the kept part",
|
|
342
383
|
rootMissing: "root directory does not exist (zg needs a real workspace path): {root}",
|
|
343
384
|
jobOutputTruncated: "\n[zvec-grep] output too long, truncated — only the tail is kept",
|
|
@@ -362,10 +403,10 @@ const MESSAGES = {
|
|
|
362
403
|
clientModeInvalid: "invalid zg client mode: {received} (allowed: {allowed})",
|
|
363
404
|
previewInvalid: "invalid preview mode: {received} (allowed: {allowed})",
|
|
364
405
|
refreshInvalid: "invalid refresh policy: {received} (allowed: {allowed})",
|
|
365
|
-
refreshBackgroundNeedsServer: "{root} has no available zvec-grep daemon, so `refresh=background` was refused — it only holds in server mode. Without a daemon the CLI prints one stderr warning and silently turns refreshing **off**, which this plugin will not report as \"refreshing in the background\". Either keep the default refresh=wait (synchronous refresh before the search, works in direct mode) or run `zg server on` in a terminal first — the daemon also brings incremental indexing and a resident embedding model pool.",
|
|
406
|
+
refreshBackgroundNeedsServer: "{root} has no available zvec-grep daemon, so `refresh=background` was refused — it only holds in server mode. Without a daemon the CLI prints one stderr warning and silently turns refreshing **off**, which this plugin will not report as \"refreshing in the background\". Either keep the default refresh=wait (synchronous refresh before the search, works in direct mode) or run `zg --server on` in a terminal first — the daemon also brings incremental indexing and a resident embedding model pool.",
|
|
366
407
|
refreshBackgroundPinnedDirect: "{root}: `refresh=background` was refused because this daemon's transport mode is pinned to direct by the deployment (the row config's `clientMode: direct`), while background refreshing only exists in server mode. Starting a daemon would not help here — either set clientMode back to auto/server in the row config, or search with the default refresh=wait.",
|
|
367
408
|
serverReadyNote: "[zvec-grep] daemon: ready (searches can use server mode: incremental index refresh, resident embedding model pool)",
|
|
368
|
-
serverUnavailableNote: "[zvec-grep] daemon: not ready. Searches therefore run in direct mode and cold-load the embedding model every call (slower on large workspaces, and refresh=background is unavailable); run `zg server on` in a terminal for incremental indexing and a resident model pool",
|
|
409
|
+
serverUnavailableNote: "[zvec-grep] daemon: not ready. Searches therefore run in direct mode and cold-load the embedding model every call (slower on large workspaces, and refresh=background is unavailable); run `zg --server on` in a terminal for incremental indexing and a resident model pool",
|
|
369
410
|
symbolTypeInvalid: "invalid symbol type: {received} (allowed: {allowed}; lowercase only)",
|
|
370
411
|
rootEscapesFs: "root contains a .. segment that escapes the filesystem root: {path}",
|
|
371
412
|
rootMustBeString: "root must be a string (received {received})",
|
|
@@ -384,12 +425,13 @@ const MESSAGES = {
|
|
|
384
425
|
searchNeedsQuery: "zg_search needs at least one of query/queries/fts/vector",
|
|
385
426
|
exhaustiveNeedsPattern: "exhaustive search (rg=true) needs a query to use as the pattern",
|
|
386
427
|
exhaustiveConflicts: "exhaustive search (rg=true) conflicts with these indexed-search parameters: {names}. Exhaustive search is pure lexical matching and does not support them; drop them, or build an index first (zg_index) and search the index",
|
|
387
|
-
|
|
428
|
+
filesConflicts: "file discovery (files=true) conflicts with these parameters: {names}. It only lists files and never searches content — query would be read as a path, limit is meaningless (upstream refuses it outright), and device plays no part in file discovery; drop them and resend",
|
|
429
|
+
embeddingNotAllowed: "embedding reference {reference} is not in the catalog. Local choices: {choices}; the remote qwen models require allowRemoteEmbedding turned on in the deployment config (and a one-time user authorization, zg --auth grant <root> --capability embedding --scope workspace). References with unknown prefixes are refused under every switch — a remote endpoint sends workspace content off the machine, and that decision belongs to the user.",
|
|
388
430
|
dropWithResetPaths: "drop conflicts with resetPaths: --drop does nothing but delete the index, so resetPaths has nowhere to go (upstream zg rejects the pair too). To clear inherited file-selection settings, do not pass drop.",
|
|
389
431
|
dropWithIndexArgs: "drop conflicts with these index-side parameters: {names}. --drop does nothing but delete the index, so they would never be used (accepting them silently only suggests the filters/rebuild took effect); remove them and resend the drop.",
|
|
390
|
-
ignoreFileMissing: "{path} is not an existing file the current process can read (missing, a directory, or present-but-unreadable all count).
|
|
432
|
+
ignoreFileMissing: "{path} is not an existing file the current process can read (missing, a directory, or present-but-unreadable all count). zg 0.3.0 silently tolerates an unreadable ignore file — indexing succeeds, but that exclusion rule quietly does nothing (you believe it is filtering files while nothing is excluded), so this plugin refuses the bad path before the command is built. Give a path that really exists and that the current user can read.",
|
|
391
433
|
exhaustiveFallbackNote: "[zvec-grep] This workspace (and every directory above it) has no zg index, so the search fell back to exhaustive lexical matching (rg mode). Results are literal line matches, not ranked by semantic relevance; run zg_index first if you need semantic search.",
|
|
392
|
-
rgDescription: "Exhaustive lexical search (zg
|
|
434
|
+
rgDescription: "Exhaustive lexical search (zg --rg): needs no index, matches literal text line by line. Leave it unset to fall back to it automatically when the workspace has no index, and to use the index when one exists. An explicit false demands indexed search only (an error when there is no index). It does not support preview / refresh / fuse / symbolTypes / preferSymbol / fts / vector / queries / category, and it grants no grep/rg quota",
|
|
393
435
|
intWithReceived: "{name} must be an integer >= {min} (received {received})",
|
|
394
436
|
intRequired: "{name} must be an integer >= {min}",
|
|
395
437
|
guardRootRejected: "the root given to {name} is not accepted: {reason}",
|
|
@@ -416,6 +458,16 @@ function fill(template, params) {
|
|
|
416
458
|
return value === void 0 ? "" : String(value);
|
|
417
459
|
});
|
|
418
460
|
}
|
|
461
|
+
// lib/platform.ts
|
|
462
|
+
/** 把 Node 的 platform 收成两档:win32 单独一档,其余都按 POSIX。 */
|
|
463
|
+
function runtimePlatform(value = process.platform) {
|
|
464
|
+
return value === "win32" ? "win32" : "posix";
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* 一个反斜杠字符。写成 `String.fromCodePoint` 而不是 `"\\"`:后者会被
|
|
468
|
+
* prefer-string-raw 要求改成模板串,而模板串里单个反斜杠无法表达(会转义反引号)。
|
|
469
|
+
*/
|
|
470
|
+
const BACKSLASH = String.fromCodePoint(92);
|
|
419
471
|
// lib/argv-guard.ts
|
|
420
472
|
const MAX_COMMAND_BYTES = 64e3;
|
|
421
473
|
/** 单条 query 文本上限(再长属误用:zg 的语义检索按句切分)。 */
|
|
@@ -424,9 +476,18 @@ const MAX_QUERY_CHARS = 4e3;
|
|
|
424
476
|
const MAX_FILTER_ITEMS = 128;
|
|
425
477
|
/** 过滤类数组单项长度上限(glob 不该长成文章)。 */
|
|
426
478
|
const MAX_FILTER_CHARS = 1024;
|
|
427
|
-
/**
|
|
428
|
-
|
|
429
|
-
|
|
479
|
+
/**
|
|
480
|
+
* 单引号转义:POSIX sh 写成 `'…'`(内嵌 `'` → `'\''`),PowerShell 写成 `'…'`
|
|
481
|
+
* (内嵌 `'` → `''`)。两种壳的单引号内容都不做变量展开,故 `$`、反引号、反斜杠都按
|
|
482
|
+
* 字面量保留;差别只在内嵌单引号的写法。
|
|
483
|
+
*
|
|
484
|
+
* 缺省 "posix" 是给纯函数单测与 lib 内部调用的确定值;宿主按 `runtimePlatform()` 传入。
|
|
485
|
+
* @param value 待转义的原文
|
|
486
|
+
* @param platform 壳方言(win32 = pwsh)
|
|
487
|
+
* @returns 可直接拼进命令的单引号串
|
|
488
|
+
*/
|
|
489
|
+
function shq(value, platform = "posix") {
|
|
490
|
+
return platform === "win32" ? `'${value.replaceAll("'", "''")}'` : `'${value.replaceAll("'", String.raw`'\''`)}'`;
|
|
430
491
|
}
|
|
431
492
|
/** 长度上界校验(超限即抛,避免整条命令撑爆 argv)。 */
|
|
432
493
|
function assertTextLen(value, name, messages, maxChars) {
|
|
@@ -438,7 +499,7 @@ function assertTextLen(value, name, messages, maxChars) {
|
|
|
438
499
|
return value;
|
|
439
500
|
}
|
|
440
501
|
/**
|
|
441
|
-
* 可选文本取值:未给 → 空串;非字符串 →
|
|
502
|
+
* 可选文本取值:未给 → 空串;非字符串 → 报错(绝不会静默降级成默认值);
|
|
442
503
|
* 去首尾空白并校验 NUL 与长度。
|
|
443
504
|
*/
|
|
444
505
|
function optionalText(value, name, messages, maxChars) {
|
|
@@ -479,7 +540,7 @@ function stringList(value, name, messages, maxItems = MAX_FILTER_ITEMS, maxChars
|
|
|
479
540
|
* 路径过滤类参数的取值:单值与数组两种形态都收,规范化成数组后交给 `stringList` 走同
|
|
480
541
|
* 一套校验(trim / 去空串 / NUL / 条数 / 长度)。
|
|
481
542
|
*
|
|
482
|
-
* 兼容单值是因为上游就这么收:zg
|
|
543
|
+
* 兼容单值是因为上游就这么收:zg 自己的对外声明里 globs / insensitiveGlobs / fileTypes /
|
|
483
544
|
* excludedFileTypes / ignoreFiles 都是「一个字符串或一个字符串数组」的并集,只收数组
|
|
484
545
|
* 会让模型按上游习惯写单个 glob 时撞上「必须是字符串数组」——形状没错、形状太严。
|
|
485
546
|
* 其余类型错误(非字符串、非数组的其它值)仍然照旧报错,不做任何静默降级。
|
|
@@ -517,6 +578,8 @@ const SECRET_EXCLUDE_GLOBS = [
|
|
|
517
578
|
"!id_ed25519*"
|
|
518
579
|
];
|
|
519
580
|
// lib/cli.ts
|
|
581
|
+
/** 盘符根 `C:\`(path.win32.parse 的 root 形态;`C:` 是盘符相对,不算)。 */
|
|
582
|
+
const WIN32_DRIVE_ROOT = /^[A-Za-z]:\\$/u;
|
|
520
583
|
const CLIENT_MODE_NAMES = Object.keys({
|
|
521
584
|
auto: "auto",
|
|
522
585
|
direct: "direct",
|
|
@@ -531,7 +594,7 @@ function isClientMode(value) {
|
|
|
531
594
|
/**
|
|
532
595
|
* 传输模式取值器:缺省回缺省域,其余非本域取值一律报错。
|
|
533
596
|
* 宿主侧配置已由 schema 校验过,这道取值器是命令行构造边界的最后一道闸,与同文件其余
|
|
534
|
-
*
|
|
597
|
+
* 取值器同一种做法——绝不把一个守护进程并不认识的模式串静默拼进命令。
|
|
535
598
|
*/
|
|
536
599
|
function clientModeOf(value, messages) {
|
|
537
600
|
if (value === void 0 || value === null) return DEFAULT_CLIENT_MODE;
|
|
@@ -548,11 +611,12 @@ function clientModeOf(value, messages) {
|
|
|
548
611
|
function modeFlag(mode) {
|
|
549
612
|
return `--mode ${mode}`;
|
|
550
613
|
}
|
|
551
|
-
/**
|
|
614
|
+
/** 合法预览档位名单,外供工具参数的 JSON Schema `enum`,与取值器同一份来源。 */
|
|
552
615
|
const PREVIEW_NAMES = Object.keys({
|
|
553
616
|
none: "none",
|
|
554
617
|
short: "short",
|
|
555
|
-
full: "full"
|
|
618
|
+
full: "full",
|
|
619
|
+
detail: "detail"
|
|
556
620
|
});
|
|
557
621
|
/** 缺省预览档位:有界源码窗口,既不空手而归也不撑爆上下文。 */
|
|
558
622
|
const DEFAULT_PREVIEW = "short";
|
|
@@ -567,7 +631,7 @@ function previewOf(value, messages) {
|
|
|
567
631
|
}));
|
|
568
632
|
return value;
|
|
569
633
|
}
|
|
570
|
-
/**
|
|
634
|
+
/** 合法刷新策略名单,外供工具参数的 JSON Schema `enum`,与取值器同一份来源。 */
|
|
571
635
|
const REFRESH_NAMES = Object.keys({
|
|
572
636
|
background: "background",
|
|
573
637
|
wait: "wait",
|
|
@@ -596,14 +660,15 @@ function refreshOf(value, messages) {
|
|
|
596
660
|
function requestsBackgroundRefresh(value) {
|
|
597
661
|
return value === "background";
|
|
598
662
|
}
|
|
599
|
-
/**
|
|
663
|
+
/** 合法符号类型名单,外供工具参数的 JSON Schema `enum`,与取值器同一份来源。 */
|
|
600
664
|
const SYMBOL_TYPE_NAMES = Object.keys({
|
|
601
|
-
|
|
665
|
+
alias: "alias",
|
|
602
666
|
class: "class",
|
|
603
|
-
|
|
667
|
+
enum: "enum",
|
|
604
668
|
function: "function",
|
|
605
|
-
|
|
606
|
-
|
|
669
|
+
interface: "interface",
|
|
670
|
+
module: "module",
|
|
671
|
+
value: "value"
|
|
607
672
|
});
|
|
608
673
|
function isSymbolType(value) {
|
|
609
674
|
return SYMBOL_TYPE_NAMES.includes(value);
|
|
@@ -611,7 +676,7 @@ function isSymbolType(value) {
|
|
|
611
676
|
/** 符号类型取值器:空缺省空数组,逐项校闭集(不是逐项静默丢弃)。 */
|
|
612
677
|
function symbolTypesOf(value, messages) {
|
|
613
678
|
const out = [];
|
|
614
|
-
for (const item of stringList(value, "symbolTypes", messages)) {
|
|
679
|
+
for (const item of stringList(value, "symbolTypes", messages, SYMBOL_TYPE_NAMES.length)) {
|
|
615
680
|
if (!isSymbolType(item)) throw new TypeError(fill(messages.symbolTypeInvalid, {
|
|
616
681
|
received: item,
|
|
617
682
|
allowed: SYMBOL_TYPE_NAMES.join(" | ")
|
|
@@ -620,21 +685,20 @@ function symbolTypesOf(value, messages) {
|
|
|
620
685
|
}
|
|
621
686
|
return out;
|
|
622
687
|
}
|
|
623
|
-
/**
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
function deviceFlag(value, messages) {
|
|
688
|
+
/** 按平台绑定转义器:单测默认 POSIX;宿主按 runtimePlatform() 传入。 */
|
|
689
|
+
function quoteFor(platform) {
|
|
690
|
+
return (value) => shq(value, platform);
|
|
691
|
+
}
|
|
692
|
+
function deviceFlag(value, messages, quote) {
|
|
629
693
|
const raw = optionalText(value, "device", messages, MAX_FILTER_CHARS);
|
|
630
|
-
return `--device ${
|
|
694
|
+
return `--device ${quote(raw.length > 0 ? raw : "auto")}`;
|
|
631
695
|
}
|
|
632
696
|
/**
|
|
633
697
|
* 布尔旗标严格取值:缺省回 fallback,非布尔即报错(`1`/`"true"` 不算真)。
|
|
634
698
|
*
|
|
635
699
|
* 导出的原因:宿主侧有几处**要拿布尔值本身做分支决策**(这次调用是后台还是前台、
|
|
636
700
|
* 这次是重建还是增量、这次查询带不带就绪判定),那些地方若写 `args["x"] === true`,
|
|
637
|
-
* 一个 `1` 或 `"true"` 就会静默走成 false
|
|
701
|
+
* 一个 `1` 或 `"true"` 就会静默走成 false——而参数表下方恰好声明着 `type: "boolean"`。
|
|
638
702
|
* 框架**不会**替我们兜这一层:宿主对 `parameters` 只在注册时做「输出」schema 检查,
|
|
639
703
|
* 入参原样交给 execute(本文件 define 一处的注释与 lib/cli.ts 的头注释都记着这件事)。
|
|
640
704
|
*/
|
|
@@ -647,11 +711,48 @@ function boolOf(value, name, messages, fallback = false) {
|
|
|
647
711
|
return value;
|
|
648
712
|
}
|
|
649
713
|
/**
|
|
650
|
-
*
|
|
714
|
+
* 词典化归一绝对路径(不触盘):去掉空段与 `.`、解析 `..`。
|
|
651
715
|
* `..` 越过文件系统根(如 `/../../etc`)即抛错——归一后落回 `/etc` 看似合法,
|
|
652
716
|
* 实为借相对段逃逸调用方意图中的目录,绝不放行。
|
|
653
717
|
*/
|
|
654
|
-
|
|
718
|
+
/**
|
|
719
|
+
* 去掉 Windows 扩展长度/设备前缀:`\\?\C:\x` → `C:\x`、`\\?\UNC\srv\share\x` →
|
|
720
|
+
* `\\srv\share\x`。这些前缀只改变内核解释方式,不改变目标路径;保留它们会让同一目录
|
|
721
|
+
* 在清单覆盖与白名单里变成两个键。`\\.\` 设备前缀同理按普通盘符路径处理。
|
|
722
|
+
*/
|
|
723
|
+
function stripWin32Extended(input) {
|
|
724
|
+
if (input.startsWith("\\\\?\\UNC\\")) return `\\\\${input.slice(8)}`;
|
|
725
|
+
if (input.startsWith("\\\\?\\") || input.startsWith("\\\\.\\")) return input.slice(4);
|
|
726
|
+
return input;
|
|
727
|
+
}
|
|
728
|
+
/** 盘符绝对路径(`C:\` / `C:/`)或 UNC(`\\server\share`)的根前缀;不是完整限定路径时 undefined。 */
|
|
729
|
+
function win32RootOf(input) {
|
|
730
|
+
const separated = input.replaceAll("/", "\\");
|
|
731
|
+
const parsed = nodePath.win32.parse(separated).root;
|
|
732
|
+
return WIN32_DRIVE_ROOT.test(parsed) || parsed.startsWith(BACKSLASH + BACKSLASH) ? parsed : void 0;
|
|
733
|
+
}
|
|
734
|
+
/** win32 路径归一:统一 `\`、消 `.`/`..`、拒绝越出盘符/共享根;返回完整限定形式。 */
|
|
735
|
+
function normalizeWin32Absolute(input, messages) {
|
|
736
|
+
const canonical = stripWin32Extended(input).replaceAll("/", "\\");
|
|
737
|
+
const root = win32RootOf(canonical);
|
|
738
|
+
if (root === void 0) throw new Error(fill(messages.rootMustBeAbsolute, { path: input }));
|
|
739
|
+
const parts = [];
|
|
740
|
+
for (const segment of canonical.slice(root.length).split("\\")) if (segment === "..") {
|
|
741
|
+
if (parts.length === 0) throw new Error(fill(messages.rootEscapesFs, { path: input }));
|
|
742
|
+
parts.pop();
|
|
743
|
+
} else if (segment !== "" && segment !== ".") parts.push(segment);
|
|
744
|
+
return `${root}${parts.join("\\")}`;
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* 路径归一:POSIX 按 `/` 切段,win32 按 `\`(也接受 `/`)切段并保留盘符/UNC 根。
|
|
748
|
+
* 两种方言都拒绝 `..` 越出文件系统根(不是静默钳到根)。
|
|
749
|
+
* @param path 待归一的绝对路径
|
|
750
|
+
* @param messages 文案表
|
|
751
|
+
* @param platform 路径方言(缺省 posix,宿主按 runtimePlatform() 传入)
|
|
752
|
+
* @returns 归一后的绝对路径(无尾分隔符,根自身除外)
|
|
753
|
+
*/
|
|
754
|
+
function normalizeAbsolutePath(path, messages, platform = "posix") {
|
|
755
|
+
if (platform === "win32") return normalizeWin32Absolute(path, messages);
|
|
655
756
|
const parts = [];
|
|
656
757
|
for (const seg of path.split("/")) if (seg === "..") {
|
|
657
758
|
if (parts.length === 0) throw new Error(fill(messages.rootEscapesFs, { path }));
|
|
@@ -659,12 +760,21 @@ function normalizeAbsolutePath(path, messages) {
|
|
|
659
760
|
} else if (seg !== "" && seg !== ".") parts.push(seg);
|
|
660
761
|
return `/${parts.join("/")}`;
|
|
661
762
|
}
|
|
662
|
-
/**
|
|
663
|
-
|
|
763
|
+
/**
|
|
764
|
+
* 绝对路径校验。POSIX 只收 `/` 开头;win32 只收盘符绝对路径(`C:\…`)与 UNC
|
|
765
|
+
* (`\\server\share\…`)——`C:repo`(盘符相对)与 `\repo`(当前盘根相对)不是完整
|
|
766
|
+
* 限定路径,作为 workdir 会随进程当前盘漂移,故与相对路径同档拒绝。
|
|
767
|
+
*/
|
|
768
|
+
function assertAbsoluteRoot(root, messages, platform = "posix") {
|
|
664
769
|
if (typeof root !== "string") throw new TypeError(fill(messages.rootMustBeString, { received: root === null ? "null" : typeof root }));
|
|
665
770
|
if (root.trim().length === 0) throw new Error(messages.rootRequired);
|
|
666
771
|
const trimmed = root.trim();
|
|
667
772
|
if (trimmed.includes("\0")) throw new Error(fill(messages.noNulBytes, { name: "root" }));
|
|
773
|
+
if (platform === "win32") {
|
|
774
|
+
const normalized = normalizeAbsolutePath(trimmed, messages, "win32");
|
|
775
|
+
if (normalized === nodePath.win32.parse(normalized).root) throw new Error(messages.rootIsFsRoot);
|
|
776
|
+
return normalized;
|
|
777
|
+
}
|
|
668
778
|
if (!trimmed.startsWith("/")) throw new Error(fill(messages.rootMustBeAbsolute, { path: trimmed }));
|
|
669
779
|
const normalized = normalizeAbsolutePath(trimmed, messages);
|
|
670
780
|
if (normalized === "/") throw new Error(messages.rootIsFsRoot);
|
|
@@ -677,10 +787,10 @@ function assertAbsoluteRoot(root, messages) {
|
|
|
677
787
|
* 显式的**非字符串**值不进 fallback 分支:模型写 `{root: 123}` 时若静默滑到会话工作区,
|
|
678
788
|
* 搜索就在模型没指定的目录上执行并交回一份「合法」结果——类型错必须当场报。
|
|
679
789
|
*/
|
|
680
|
-
function resolveRoot(value, fallback, messages) {
|
|
790
|
+
function resolveRoot(value, fallback, messages, platform = "posix") {
|
|
681
791
|
if (value !== void 0 && value !== null && typeof value !== "string") throw new TypeError(fill(messages.rootMustBeString, { received: typeof value }));
|
|
682
|
-
if (typeof value === "string" && value.trim().length > 0) return assertAbsoluteRoot(value.trim(), messages);
|
|
683
|
-
if (typeof fallback === "string" && fallback.trim().length > 0) return assertAbsoluteRoot(fallback.trim(), messages);
|
|
792
|
+
if (typeof value === "string" && value.trim().length > 0) return assertAbsoluteRoot(value.trim(), messages, platform);
|
|
793
|
+
if (typeof fallback === "string" && fallback.trim().length > 0) return assertAbsoluteRoot(fallback.trim(), messages, platform);
|
|
684
794
|
throw new Error(messages.rootRequiredWithFallback);
|
|
685
795
|
}
|
|
686
796
|
/**
|
|
@@ -705,15 +815,20 @@ function resolveLimit(value, messages, fallback = 10) {
|
|
|
705
815
|
function queryList(value, name, messages) {
|
|
706
816
|
return stringList(value, name, messages, 32, MAX_QUERY_CHARS);
|
|
707
817
|
}
|
|
708
|
-
/**
|
|
818
|
+
/** Windows 的 CreateProcess 命令行上限约 32767 个 UTF-16 码元;留出 pwsh 前缀与编码
|
|
819
|
+
* 预置的余量后取 24000 字节。POSIX 仍用 MAX_COMMAND_BYTES(64K)。 */
|
|
820
|
+
const MAX_COMMAND_BYTES_WIN32 = 24e3;
|
|
821
|
+
/** 整条命令的规模上限:按 UTF-8 字节比平台上限(防 E2BIG 与无界内存)。
|
|
709
822
|
* 多字节内容一个码元可占 3~4 字节,按 `String.length`(码元数)比会在中文/emoji 面上
|
|
710
|
-
* 放过 Linux MAX_ARG_STRLEN 的单参数上限——判据必须落在内核真正收到的字节数上。
|
|
711
|
-
|
|
823
|
+
* 放过 Linux MAX_ARG_STRLEN 的单参数上限——判据必须落在内核真正收到的字节数上。
|
|
824
|
+
* win32 走 pwsh -Command,整条命令是一个 argv 项,受 CreateProcess 的 32767 码元限制。 */
|
|
825
|
+
function assembled(parts, workdir, messages, platform = "posix") {
|
|
712
826
|
const command = parts.join(" ");
|
|
713
827
|
const length = Buffer.byteLength(command, "utf8");
|
|
714
|
-
|
|
828
|
+
const maxBytes = platform === "win32" ? MAX_COMMAND_BYTES_WIN32 : MAX_COMMAND_BYTES;
|
|
829
|
+
if (length > maxBytes) throw new Error(fill(messages.commandTooLong, {
|
|
715
830
|
length,
|
|
716
|
-
maxBytes
|
|
831
|
+
maxBytes
|
|
717
832
|
}));
|
|
718
833
|
return {
|
|
719
834
|
command,
|
|
@@ -721,91 +836,100 @@ function assembled(parts, workdir, messages) {
|
|
|
721
836
|
};
|
|
722
837
|
}
|
|
723
838
|
/**
|
|
724
|
-
* 追加 query
|
|
725
|
-
*
|
|
726
|
-
|
|
727
|
-
|
|
839
|
+
* 追加 query 路由主体参数(全部走显式路由旗标),返回路由命中数。
|
|
840
|
+
*
|
|
841
|
+
* 0.3.0 起没有 `zg query` 子命令:裸词**就是**搜索文本(上游帮助原文 "Bare words such as
|
|
842
|
+
* query, index, and help are literal search text")。主查询仍走 `--hybrid=` 显式路由而不是
|
|
843
|
+
* 位置词,两个实测依据:路径形单词(`auth.ts`)作位置词会先被上游拿去匹配文件名并打
|
|
844
|
+
* stderr 警告(帮助原文 "A complete miss returns No matches."——一次看似成功实为空查),
|
|
845
|
+
* 而显式路由 bypass 这一行为;多个位置词含空格还有合并警告。`=` 连写(`--hybrid='…'`)
|
|
846
|
+
* 是防「以 `-` 开头的查询串作为独立词被 clap 当成另一个选项」,与 0.2.2 时代的
|
|
847
|
+
* `--hybrid=` 用法同一套转义纪律(shq 负责单引号)。
|
|
848
|
+
*/
|
|
849
|
+
function pushQueryArgs(parts, args, messages, quote) {
|
|
728
850
|
let routeCount = 0;
|
|
729
851
|
const single = optionalText(args.query, "query", messages, MAX_QUERY_CHARS);
|
|
730
|
-
const dashGuard = single.length > 0 && single.startsWith("-");
|
|
731
852
|
if (single.length > 0) {
|
|
732
|
-
|
|
853
|
+
parts.push(`--hybrid=${quote(single)}`);
|
|
733
854
|
routeCount += 1;
|
|
734
855
|
}
|
|
735
856
|
for (const query of queryList(args.queries, "queries", messages)) {
|
|
736
|
-
parts.push(`--hybrid=${
|
|
857
|
+
parts.push(`--hybrid=${quote(query)}`);
|
|
737
858
|
routeCount += 1;
|
|
738
859
|
}
|
|
739
860
|
for (const query of queryList(args.fts, "fts", messages)) {
|
|
740
|
-
parts.push(`--fts=${
|
|
861
|
+
parts.push(`--fts=${quote(query)}`);
|
|
741
862
|
routeCount += 1;
|
|
742
863
|
}
|
|
743
864
|
for (const query of queryList(args.vector, "vector", messages)) {
|
|
744
|
-
parts.push(`--vector=${
|
|
865
|
+
parts.push(`--vector=${quote(query)}`);
|
|
745
866
|
routeCount += 1;
|
|
746
867
|
}
|
|
747
868
|
if (routeCount > 32) throw new Error(fill(messages.tooManyQueryRoutes, {
|
|
748
869
|
count: routeCount,
|
|
749
870
|
max: 32
|
|
750
871
|
}));
|
|
751
|
-
return
|
|
752
|
-
routeCount,
|
|
753
|
-
dashGuard
|
|
754
|
-
};
|
|
872
|
+
return routeCount;
|
|
755
873
|
}
|
|
756
874
|
/**
|
|
757
875
|
* 路径过滤(glob / iglob / type / type-not)。三条通道共用:实测索引检索、索引命令与
|
|
758
876
|
* 穷举检索(`--rg`)下这四类旗标都被 zg 接受,故只在这里发一次。
|
|
759
877
|
*/
|
|
760
|
-
function pushPathFilters(parts, args, messages) {
|
|
761
|
-
for (const glob of singleOrList(args.globs, "globs", messages)) parts.push("--glob",
|
|
762
|
-
for (const glob of singleOrList(args.insensitiveGlobs, "insensitiveGlobs", messages)) parts.push("--iglob",
|
|
763
|
-
for (const typeName of singleOrList(args.fileTypes, "fileTypes", messages)) parts.push("--type",
|
|
764
|
-
for (const typeName of singleOrList(args.excludedFileTypes, "excludedFileTypes", messages)) parts.push("--type-not",
|
|
878
|
+
function pushPathFilters(parts, args, messages, quote) {
|
|
879
|
+
for (const glob of singleOrList(args.globs, "globs", messages)) parts.push("--glob", quote(glob));
|
|
880
|
+
for (const glob of singleOrList(args.insensitiveGlobs, "insensitiveGlobs", messages)) parts.push("--iglob", quote(glob));
|
|
881
|
+
for (const typeName of singleOrList(args.fileTypes, "fileTypes", messages)) parts.push("--type", quote(typeName));
|
|
882
|
+
for (const typeName of singleOrList(args.excludedFileTypes, "excludedFileTypes", messages)) parts.push("--type-not", quote(typeName));
|
|
765
883
|
}
|
|
766
884
|
/** 时间过滤:两条检索通道共用(实测 `--modified-after` 在 `--rg` 下被接受)。 */
|
|
767
|
-
function pushTimeFilters(parts, args, messages) {
|
|
768
|
-
const after = optionalText(args.modifiedAfter, "modifiedAfter", messages,
|
|
769
|
-
if (after.length > 0) parts.push("--modified-after",
|
|
770
|
-
const before = optionalText(args.modifiedBefore, "modifiedBefore", messages,
|
|
771
|
-
if (before.length > 0) parts.push("--modified-before",
|
|
885
|
+
function pushTimeFilters(parts, args, messages, quote) {
|
|
886
|
+
const after = optionalText(args.modifiedAfter, "modifiedAfter", messages, 128);
|
|
887
|
+
if (after.length > 0) parts.push("--modified-after", quote(after));
|
|
888
|
+
const before = optionalText(args.modifiedBefore, "modifiedBefore", messages, 128);
|
|
889
|
+
if (before.length > 0) parts.push("--modified-before", quote(before));
|
|
772
890
|
}
|
|
773
891
|
/** 追加检索过滤 globs(路径过滤 + 仅索引通道支持的符号类型)。 */
|
|
774
|
-
function pushSearchGlobs(parts, args, messages) {
|
|
775
|
-
pushPathFilters(parts, args, messages);
|
|
776
|
-
for (const symbolKind of symbolTypesOf(args.symbolTypes, messages)) parts.push("--symbol-type",
|
|
892
|
+
function pushSearchGlobs(parts, args, messages, quote) {
|
|
893
|
+
pushPathFilters(parts, args, messages, quote);
|
|
894
|
+
for (const symbolKind of symbolTypesOf(args.symbolTypes, messages)) parts.push("--symbol-type", quote(symbolKind));
|
|
777
895
|
}
|
|
778
|
-
/** 取单条 query 的原文(与 pushQueryArgs
|
|
896
|
+
/** 取单条 query 的原文(与 pushQueryArgs 同一取值器)。 */
|
|
779
897
|
function singleText(args, messages) {
|
|
780
898
|
return optionalText(args.query, "query", messages, MAX_QUERY_CHARS);
|
|
781
899
|
}
|
|
900
|
+
/** 分类过滤(0.3.0 新增 `--category` / `--category-not`,可重复;值域由上游校验)。 */
|
|
901
|
+
function pushCategoryFilters(parts, args, messages, quote) {
|
|
902
|
+
for (const name of singleOrList(args.category, "category", messages)) parts.push("--category", quote(name));
|
|
903
|
+
for (const name of singleOrList(args.categoryNot, "categoryNot", messages)) parts.push("--category-not", quote(name));
|
|
904
|
+
}
|
|
782
905
|
function buildIndexedCommand(args, root, messages, mode, backgroundSupport) {
|
|
783
|
-
const parts = ["zg"
|
|
784
|
-
const
|
|
785
|
-
if (
|
|
906
|
+
const parts = ["zg"];
|
|
907
|
+
const quote = quoteFor(args.platform ?? "posix");
|
|
908
|
+
if (pushQueryArgs(parts, args, messages, quote) === 0) throw new Error(messages.searchNeedsQuery);
|
|
786
909
|
if (boolOf(args.fuse, "fuse", messages)) parts.push("--fuse");
|
|
787
910
|
const refresh = refreshOf(args.refresh, messages);
|
|
788
911
|
if (refresh === "background" && mode === "direct") throw new Error(fill(messages.refreshBackgroundPinnedDirect, { root }));
|
|
789
912
|
if (refresh === "background" && backgroundSupport === "daemon-down") throw new Error(fill(messages.refreshBackgroundNeedsServer, { root }));
|
|
790
913
|
parts.push("--limit", String(resolveLimit(args.limit, messages)), "--preview", previewOf(args.preview, messages), "--refresh", refresh);
|
|
791
|
-
pushSearchGlobs(parts, args, messages);
|
|
914
|
+
pushSearchGlobs(parts, args, messages, quote);
|
|
915
|
+
pushCategoryFilters(parts, args, messages, quote);
|
|
792
916
|
if (boolOf(args.preferSymbol, "preferSymbol", messages)) parts.push("--prefer-symbol");
|
|
793
917
|
if (boolOf(args.trace, "trace", messages)) parts.push("--trace");
|
|
794
|
-
pushTimeFilters(parts, args, messages);
|
|
795
|
-
parts.push(deviceFlag(args.device, messages), modeFlag(mode));
|
|
796
|
-
|
|
797
|
-
return assembled(parts, root, messages);
|
|
918
|
+
pushTimeFilters(parts, args, messages, quote);
|
|
919
|
+
parts.push(deviceFlag(args.device, messages, quote), modeFlag(mode));
|
|
920
|
+
return assembled(parts, root, messages, args.platform ?? "posix");
|
|
798
921
|
}
|
|
799
922
|
/**
|
|
800
|
-
*
|
|
923
|
+
* 穷举/文件发现两通道下 zg 明确拒绝的索引侧旗标,逐个拦在构造阶段。实测报错原文:
|
|
801
924
|
* `--preview` → "--preview is not supported with --rg; use -A/-B/-C for rg context"
|
|
802
925
|
* `--refresh` → "--rg cannot be combined with indexed refresh options"
|
|
803
926
|
* `--symbol-type` / `--prefer-symbol` → "--rg cannot be combined with indexed symbol options"
|
|
804
927
|
* `--fuse` → "--rg cannot be combined with --fuse"
|
|
805
928
|
* `--trace` → "--rg cannot be combined with --trace"
|
|
806
929
|
* `--fts` / `--vector` → "--rg cannot be combined with --hybrid, --fts, or --vector"
|
|
930
|
+
* `--category` → 引擎分类是索引侧维度,内容检索与文件发现都不消费它
|
|
807
931
|
* 与其把模型交给一次子进程失败再原样回显 zg 的英文报错,不如在构造阶段就用本包的
|
|
808
|
-
*
|
|
932
|
+
* 双语文案说清「这些是索引侧参数」——并且**不会静默丢掉**用户给的那一项。
|
|
809
933
|
*/
|
|
810
934
|
function assertExhaustiveArgs(args, messages) {
|
|
811
935
|
const conflicts = [];
|
|
@@ -813,6 +937,8 @@ function assertExhaustiveArgs(args, messages) {
|
|
|
813
937
|
if (queryList(args.queries, "queries", messages).length > 0) conflicts.push("queries");
|
|
814
938
|
if (queryList(args.fts, "fts", messages).length > 0) conflicts.push("fts");
|
|
815
939
|
if (queryList(args.vector, "vector", messages).length > 0) conflicts.push("vector");
|
|
940
|
+
if (singleOrList(args.category, "category", messages).length > 0) conflicts.push("category");
|
|
941
|
+
if (singleOrList(args.categoryNot, "categoryNot", messages).length > 0) conflicts.push("categoryNot");
|
|
816
942
|
if (optionalText(args.preview, "preview", messages, 1024).length > 0) conflicts.push("preview");
|
|
817
943
|
if (optionalText(args.refresh, "refresh", messages, 1024).length > 0) conflicts.push("refresh");
|
|
818
944
|
if (stringList(args.symbolTypes, "symbolTypes", messages).length > 0) conflicts.push("symbolTypes");
|
|
@@ -820,39 +946,79 @@ function assertExhaustiveArgs(args, messages) {
|
|
|
820
946
|
if (boolOf(args.trace, "trace", messages)) conflicts.push("trace");
|
|
821
947
|
if (conflicts.length > 0) throw new Error(fill(messages.exhaustiveConflicts, { names: conflicts.join(" | ") }));
|
|
822
948
|
}
|
|
823
|
-
/**
|
|
949
|
+
/**
|
|
950
|
+
* 文件发现模式(`zg --rg --files`)在穷举内容检索的冲突集之外**再拒**的一批:
|
|
951
|
+
* - `--limit`:上游明拒,原文 "--limit cannot be combined with --rg --files; use glob or
|
|
952
|
+
* type filters to narrow the file list"(文件清单无上限是有意设计);
|
|
953
|
+
* - query/queries:`--files` 下全部 positional 参数都按**路径**读(上游帮助原文 "With
|
|
954
|
+
* --files, every positional argument is an input file or directory; no pattern is
|
|
955
|
+
* required"),query 传进来会被当成一个不存在的目录名——要么整树漏扫要么报错;
|
|
956
|
+
* - `--device`:文件发现不跑 embedding(上游 FilesOptions 没有这一位),传了只会被
|
|
957
|
+
* 静默忽略——本包不静默收下用不上的参数。
|
|
958
|
+
*/
|
|
959
|
+
function assertFilesArgs(args, messages) {
|
|
960
|
+
assertExhaustiveArgs(args, messages);
|
|
961
|
+
const conflicts = [];
|
|
962
|
+
if (singleText(args, messages).length > 0) conflicts.push("query");
|
|
963
|
+
if (args.limit !== void 0 && args.limit !== null) conflicts.push("limit");
|
|
964
|
+
if (optionalText(args.device, "device", messages, 1024).length > 0) conflicts.push("device");
|
|
965
|
+
if (conflicts.length > 0) throw new Error(fill(messages.filesConflicts, { names: conflicts.join(" | ") }));
|
|
966
|
+
}
|
|
967
|
+
/**
|
|
968
|
+
* 穷举词法通道(`zg --rg <pattern>`)。与索引通道的合法旗标集合不同,见 assertExhaustiveArgs。
|
|
969
|
+
* 0.3.0 起没有 `zg query` 子命令:`--rg` 直接挂在顶层 `zg` 之后,pattern 仍是第一个
|
|
970
|
+
* positional、其余 positional 全是路径(上游 managed_rg 的解析契约不变)。
|
|
971
|
+
*/
|
|
824
972
|
function buildExhaustiveCommand(args, root, messages, mode) {
|
|
825
973
|
assertExhaustiveArgs(args, messages);
|
|
826
|
-
const
|
|
827
|
-
|
|
828
|
-
"query",
|
|
829
|
-
"--rg"
|
|
830
|
-
];
|
|
974
|
+
const quote = quoteFor(args.platform ?? "posix");
|
|
975
|
+
const parts = ["zg", "--rg"];
|
|
831
976
|
const pattern = optionalText(args.query, "query", messages, MAX_QUERY_CHARS);
|
|
832
977
|
if (pattern.length === 0) throw new Error(messages.exhaustiveNeedsPattern);
|
|
833
|
-
if (pattern.startsWith("-")) parts.push("-e",
|
|
834
|
-
else parts.push(
|
|
978
|
+
if (pattern.startsWith("-")) parts.push("-e", quote(pattern));
|
|
979
|
+
else parts.push(quote(pattern));
|
|
835
980
|
parts.push("--limit", String(resolveLimit(args.limit, messages)));
|
|
836
|
-
pushPathFilters(parts, args, messages);
|
|
837
|
-
pushTimeFilters(parts, args, messages);
|
|
838
|
-
parts.push(deviceFlag(args.device, messages), modeFlag(mode));
|
|
839
|
-
return assembled(parts, root, messages);
|
|
981
|
+
pushPathFilters(parts, args, messages, quote);
|
|
982
|
+
pushTimeFilters(parts, args, messages, quote);
|
|
983
|
+
parts.push(deviceFlag(args.device, messages, quote), modeFlag(mode));
|
|
984
|
+
return assembled(parts, root, messages, args.platform ?? "posix");
|
|
840
985
|
}
|
|
841
986
|
/**
|
|
842
|
-
*
|
|
843
|
-
*
|
|
987
|
+
* 文件发现通道(0.3.0 的 `zg --rg --files`):不做内容搜索,按当前过滤规则列出文件清单。
|
|
988
|
+
* 上游 `file_selection/policy.rs` 实证三条价值:默认感知 .gitignore/.ignore/.rgignore 三件套、
|
|
989
|
+
* `paths.sort()` 排序、无结果上限(`--limit` 被上游明拒)。过滤面只收路径/时间两族
|
|
990
|
+
* (上游 files_options 的映射面:globs/iglob/type/type-not/modified-after/before),
|
|
991
|
+
* 其余参数由 assertFilesArgs 点名拒绝。
|
|
992
|
+
*/
|
|
993
|
+
function buildFilesCommand(args, root, messages, mode) {
|
|
994
|
+
assertFilesArgs(args, messages);
|
|
995
|
+
const quote = quoteFor(args.platform ?? "posix");
|
|
996
|
+
const parts = [
|
|
997
|
+
"zg",
|
|
998
|
+
"--rg",
|
|
999
|
+
"--files"
|
|
1000
|
+
];
|
|
1001
|
+
pushPathFilters(parts, args, messages, quote);
|
|
1002
|
+
pushTimeFilters(parts, args, messages, quote);
|
|
1003
|
+
parts.push(modeFlag(mode));
|
|
1004
|
+
return assembled(parts, root, messages, args.platform ?? "posix");
|
|
1005
|
+
}
|
|
1006
|
+
/**
|
|
1007
|
+
* 构造 zg 检索命令(索引通道 / `--rg` 穷举 / `--rg --files` 文件发现)。
|
|
1008
|
+
* 注意:zg 没有 --root,root 来自进程 cwd,所以 root 只作为 workdir 返回,绝不进入命令行。
|
|
844
1009
|
*
|
|
845
|
-
* `
|
|
846
|
-
*
|
|
847
|
-
* 判据见 host.ts 的 pickExhaustive。
|
|
1010
|
+
* 0.3.0 起没有 `zg query` 子命令(见 buildIndexedCommand 的注释);穷举与文件发现两通道
|
|
1011
|
+
* 走顶层 `zg --rg …`。
|
|
848
1012
|
*
|
|
849
|
-
* `backgroundSupport`
|
|
850
|
-
*
|
|
851
|
-
*
|
|
1013
|
+
* `backgroundSupport` 是宿主算得的「后台刷新能不能用」,只有索引通道用得上(穷举与文件
|
|
1014
|
+
* 发现通道本就不接受 refresh)。缺省按**不可用**处理:拿不到判据时把 background 拒掉是
|
|
1015
|
+
* 安全的一侧,而把「没算出来」当成「可用」放行等于把一句假话发给模型。
|
|
852
1016
|
*/
|
|
853
|
-
function buildSearchCommand(args, messages, mode = DEFAULT_CLIENT_MODE,
|
|
854
|
-
const
|
|
855
|
-
|
|
1017
|
+
function buildSearchCommand(args, messages, mode = DEFAULT_CLIENT_MODE, channel = "indexed", backgroundSupport = "daemon-down") {
|
|
1018
|
+
const platform = args.platform ?? "posix";
|
|
1019
|
+
const root = assertAbsoluteRoot(args.root, messages, platform);
|
|
1020
|
+
if (channel === "files") return buildFilesCommand(args, root, messages, mode);
|
|
1021
|
+
return channel === "exhaustive" ? buildExhaustiveCommand(args, root, messages, mode) : buildIndexedCommand(args, root, messages, mode, backgroundSupport);
|
|
856
1022
|
}
|
|
857
1023
|
/** 非负/正整数字符串化;非 number 或非整数报错(`true` 与数字字符串都不算数字)。 */
|
|
858
1024
|
function intFlag(value, name, messages, min) {
|
|
@@ -877,6 +1043,7 @@ function readIndexFlags(args, messages) {
|
|
|
877
1043
|
rebuild: boolOf(args.rebuild, "rebuild", messages),
|
|
878
1044
|
hidden: boolOf(args.hidden, "hidden", messages),
|
|
879
1045
|
noIgnore: boolOf(args.noIgnore, "noIgnore", messages),
|
|
1046
|
+
nestedGit: boolOf(args.nestedGit, "nestedGit", messages),
|
|
880
1047
|
follow: boolOf(args.follow, "follow", messages),
|
|
881
1048
|
excludeSecrets: boolOf(args.excludeSecrets, "excludeSecrets", messages, true)
|
|
882
1049
|
};
|
|
@@ -891,34 +1058,38 @@ function pushIndexBoolFlags(parts, flags) {
|
|
|
891
1058
|
*
|
|
892
1059
|
* 密钥排除走 --iglob 而非 --glob,两个原因都是实测得来的:
|
|
893
1060
|
* - 扩展名大小写:`.pem` / `.p12` / `.pfx` / `.keystore` 都**确实会被索引**(真 zg 0.2.2 实测:
|
|
894
|
-
* 一份只有 `secret.pem` / `secret.P12` / `a.ts`
|
|
895
|
-
* `3 scanned, 3 added
|
|
1061
|
+
* 一份只有 `secret.pem` / `secret.P12` / `a.ts` 的工作区,0.2.2 的 `zg index` 回执就是
|
|
1062
|
+
* `3 scanned, 3 added`,随后检索交回 `#1 matchedBy=fts+vector secret.pem:1-2`;0.3.0
|
|
1063
|
+
* 的扫描规则旗标(--glob/--iglob)与求值次序未变,这段实测记录仍适用于它的行为面),
|
|
896
1064
|
* 且都存在混合大小写变体(`secret.P12` / `secret.PfX` / `secret.KEYSTORE` 同样入索引)。
|
|
897
1065
|
* --glob 的 `!*.p12` 匹配不到 `secret.P12`,--iglob 走大小写不敏感匹配才能全部排除。
|
|
898
1066
|
* 判据钉在 test/e2e/zg-cli.test.ts 的「密钥排除真的在挡东西」那一组。
|
|
899
|
-
* -
|
|
900
|
-
*
|
|
1067
|
+
* - 规则次序:CLI 通道按命令行的**混排顺序**求值、后规则覆盖前规则(上游 zg-cli 的
|
|
1068
|
+
* ordered_glob_rules 保留 -g/--iglob 的出现次序,不是「全部 --glob 先于全部 --iglob」;
|
|
1069
|
+
* 只有 MCP 面才是 globs 之后追加 insensitiveGlobs)。密钥规则若用 --glob 且排在用户
|
|
1070
|
+
* 规则之前,用户一条宽泛的正向 --iglob(如 `**`)会在其后求值并把无扩展名的
|
|
901
1071
|
* `id_rsa*` 救回索引(实测「被索引」);用 --iglob 且排在本函数最后(用户 iglob
|
|
902
1072
|
* 之后),任何用户正向规则都无法覆盖它。
|
|
903
1073
|
* 纯 `!` 取反已实测可独立工作。excludeSecrets=false 可整体关闭。
|
|
904
1074
|
*/
|
|
905
|
-
function pushIndexGlobs(parts, args, flags, messages) {
|
|
906
|
-
for (const glob of singleOrList(args.globs, "globs", messages)) parts.push("--glob",
|
|
907
|
-
for (const glob of singleOrList(args.insensitiveGlobs, "insensitiveGlobs", messages)) parts.push("--iglob",
|
|
908
|
-
for (const typeName of singleOrList(args.fileTypes, "fileTypes", messages)) parts.push("--type",
|
|
909
|
-
for (const typeName of singleOrList(args.excludedFileTypes, "excludedFileTypes", messages)) parts.push("--type-not",
|
|
910
|
-
if (flags.excludeSecrets) for (const glob of SECRET_EXCLUDE_GLOBS) parts.push("--iglob",
|
|
911
|
-
for (const filePath of singleOrList(args.ignoreFiles, "ignoreFiles", messages)) parts.push("--ignore-file",
|
|
1075
|
+
function pushIndexGlobs(parts, args, flags, messages, quote) {
|
|
1076
|
+
for (const glob of singleOrList(args.globs, "globs", messages)) parts.push("--glob", quote(glob));
|
|
1077
|
+
for (const glob of singleOrList(args.insensitiveGlobs, "insensitiveGlobs", messages)) parts.push("--iglob", quote(glob));
|
|
1078
|
+
for (const typeName of singleOrList(args.fileTypes, "fileTypes", messages)) parts.push("--type", quote(typeName));
|
|
1079
|
+
for (const typeName of singleOrList(args.excludedFileTypes, "excludedFileTypes", messages)) parts.push("--type-not", quote(typeName));
|
|
1080
|
+
if (flags.excludeSecrets) for (const glob of SECRET_EXCLUDE_GLOBS) parts.push("--iglob", quote(glob));
|
|
1081
|
+
for (const filePath of singleOrList(args.ignoreFiles, "ignoreFiles", messages)) parts.push("--ignore-file", quote(filePath));
|
|
912
1082
|
}
|
|
913
1083
|
/** 追加索引数值旗标(内部顺序固定:maxDepth → maxFileSizeBytes)。 */
|
|
914
1084
|
function pushIndexIntFlags(parts, args, messages) {
|
|
915
1085
|
if (args.maxDepth !== void 0 && args.maxDepth !== null) parts.push("--max-depth", intFlag(args.maxDepth, "maxDepth", messages, 0));
|
|
916
1086
|
if (args.maxFileSizeBytes !== void 0 && args.maxFileSizeBytes !== null) parts.push("--max-filesize", intFlag(args.maxFileSizeBytes, "maxFileSizeBytes", messages, 0));
|
|
917
1087
|
}
|
|
918
|
-
/** 追加索引布尔旗标(hidden/no-ignore 紧随过滤 globs
|
|
1088
|
+
/** 追加索引布尔旗标(hidden/no-ignore/nested-git 紧随过滤 globs,与上游帮助的 Scan rules 次序一致)。 */
|
|
919
1089
|
function pushIndexHideFlags(parts, flags) {
|
|
920
1090
|
if (flags.hidden) parts.push("--hidden");
|
|
921
1091
|
if (flags.noIgnore) parts.push("--no-ignore");
|
|
1092
|
+
if (flags.nestedGit) parts.push("--nested-git");
|
|
922
1093
|
}
|
|
923
1094
|
/** 追加索引布尔旗标(follow 位于 max-filesize 之后)。 */
|
|
924
1095
|
function pushIndexFollowFlag(parts, flags) {
|
|
@@ -934,7 +1105,7 @@ function pushIndexConcurrencyFlag(parts, args, messages) {
|
|
|
934
1105
|
* 为什么它与 globs/fileTypes **不**互斥:上游是「先 reset、再盖本次覆盖值」的两步
|
|
935
1106
|
* (zvec-grep v0.2.2 `resolveIndexRootPaths`),同传表达「清干净再按这次的规则选」。
|
|
936
1107
|
* 唯一真互斥的是 drop,上游 args.ts 明确拒 `--drop --reset-paths`——那一对由构造器
|
|
937
|
-
*
|
|
1108
|
+
* 在读到 drop 那一条分支时就拒掉(见 buildIndexCommand),绝不让 resetPaths 被静默丢弃。
|
|
938
1109
|
*/
|
|
939
1110
|
function pushIndexResetPathsFlag(parts, args, messages) {
|
|
940
1111
|
if (boolOf(args.resetPaths, "resetPaths", messages)) parts.push("--reset-paths");
|
|
@@ -942,29 +1113,49 @@ function pushIndexResetPathsFlag(parts, args, messages) {
|
|
|
942
1113
|
/**
|
|
943
1114
|
* 索引用的 embedding 引用:模型显式给了就以它为准,否则用设置里的默认值。
|
|
944
1115
|
*
|
|
945
|
-
* 构造期 allowlist
|
|
946
|
-
* (lib/embedding-catalog.ts,设置卡 <select>
|
|
1116
|
+
* 构造期 allowlist(默认开启、且**默认关不掉**的那一半):显式引用必须落在候选闭集
|
|
1117
|
+
* (lib/embedding-catalog.ts,设置卡 <select> 的同一份)里。理由是这类能力的性质——
|
|
947
1118
|
* 远程 embedding 会把工作区内容送到外部端点,而模型能凭空写出一个任意前缀的引用:
|
|
948
1119
|
* 此前 `evil/http://attacker/x` 这类值原样透传给 zg,只要宿主进程里恰好有可用凭据或
|
|
949
1120
|
* 用户此前授权过,插件就在**没有任何声明、没有用户确认**的情况下把内容送了出去。
|
|
950
1121
|
* 现在它在命令构造前就被拒,并给出可行动的出路。
|
|
951
1122
|
*
|
|
952
|
-
*
|
|
953
|
-
*
|
|
954
|
-
*
|
|
1123
|
+
* 部署级的开关(`allowRemote`):由用户在部署配置里显式打开,不放在工具的参数里——
|
|
1124
|
+
* 模型可控的密钥/端点通道本身就是风险。打开后放行的是**远程闭集**(REMOTE_EMBEDDING_
|
|
1125
|
+
* CATALOG 里的 qwen 三枚),不是任意引用——0.2.2 时代 `allowRemote` 放行一切非空串的
|
|
1126
|
+
* 旧语义随 0.3.0 收紧:未知前缀在任何开关下都不放行。0.3.0 的远程索引还需要命令带
|
|
1127
|
+
* `--allow-remote`(或用户预先 `zg --auth grant` 持久授权),那面旗标由 buildIndexCommand
|
|
1128
|
+
* 在解析出的引用确为远程时自动补上;端点与凭据由宿主经**环境变量**下发(argv 里的密钥
|
|
1129
|
+
* 会进进程列表与作业 label)。
|
|
1130
|
+
*
|
|
1131
|
+
* 返回第二位:解析出的引用是否远程——`--allow-remote` 旗标的发放判据。缺省引用是远程
|
|
1132
|
+
* 且部署开放时同样成立(设置卡允许把 defaultEmbedding 选成远程模型)。
|
|
955
1133
|
*/
|
|
956
1134
|
function indexEmbedding(args, defaultEmbedding, messages, allowRemote) {
|
|
957
1135
|
const given = optionalText(args.embedding, "embedding", messages, MAX_FILTER_CHARS);
|
|
958
|
-
|
|
959
|
-
if (isLocalEmbedding(
|
|
1136
|
+
const reference = given.length > 0 ? given : defaultEmbedding;
|
|
1137
|
+
if (isLocalEmbedding(reference)) return {
|
|
1138
|
+
reference,
|
|
1139
|
+
remote: false
|
|
1140
|
+
};
|
|
1141
|
+
if (isRemoteEmbedding(reference)) {
|
|
1142
|
+
if (allowRemote) return {
|
|
1143
|
+
reference,
|
|
1144
|
+
remote: true
|
|
1145
|
+
};
|
|
1146
|
+
throw new Error(fill(messages.embeddingNotAllowed, {
|
|
1147
|
+
reference,
|
|
1148
|
+
choices: LOCAL_EMBEDDINGS.map((entry) => entry.reference).join(" | ")
|
|
1149
|
+
}));
|
|
1150
|
+
}
|
|
960
1151
|
throw new Error(fill(messages.embeddingNotAllowed, {
|
|
961
|
-
reference
|
|
962
|
-
choices: LOCAL_EMBEDDINGS.map((entry) => entry.reference).join(" | ")
|
|
1152
|
+
reference,
|
|
1153
|
+
choices: [...LOCAL_EMBEDDINGS, ...REMOTE_EMBEDDING_CATALOG].map((entry) => entry.reference).join(" | ")
|
|
963
1154
|
}));
|
|
964
1155
|
}
|
|
965
1156
|
/**
|
|
966
|
-
* drop
|
|
967
|
-
* 只在这里点名:出现任何一个,drop
|
|
1157
|
+
* drop 那一条分支用不上的索引侧参数(--drop 的命令只有 `--index <root> --drop`)。
|
|
1158
|
+
* 只在这里点名:出现任何一个,drop 那条分支整体拒绝,而不是静默丢掉——布尔旗标在那之前已按
|
|
968
1159
|
* 类型校验过、丢弃无声,其余参数连类型都没校验,两种待遇并存会让
|
|
969
1160
|
* `{drop:true, hidden:"yes"}` 报错而 `{drop:true, maxDepth:"3"}` 静默通过。
|
|
970
1161
|
*/
|
|
@@ -978,6 +1169,7 @@ const INDEX_ONLY_PARAMS = [
|
|
|
978
1169
|
"ignoreFiles",
|
|
979
1170
|
"hidden",
|
|
980
1171
|
"noIgnore",
|
|
1172
|
+
"nestedGit",
|
|
981
1173
|
"excludeSecrets",
|
|
982
1174
|
"maxDepth",
|
|
983
1175
|
"maxFileSizeBytes",
|
|
@@ -986,67 +1178,77 @@ const INDEX_ONLY_PARAMS = [
|
|
|
986
1178
|
"device"
|
|
987
1179
|
];
|
|
988
1180
|
/**
|
|
989
|
-
* 构造 zg index
|
|
990
|
-
* - drop=true:`zg index <root> --drop --
|
|
991
|
-
*
|
|
992
|
-
*
|
|
993
|
-
*
|
|
994
|
-
*
|
|
1181
|
+
* 构造 zg index 命令(0.3.0:`zg --index <root> …`,root 是位置参数(转义))。
|
|
1182
|
+
* - drop=true:`zg --index <root> --drop --mode <mode>`;0.3.0 起没有 `--yes`
|
|
1183
|
+
* (上游帮助原文 "Dropping an index runs immediately without a confirmation prompt.",
|
|
1184
|
+
* 实测 `--yes` 直接 exit 2),索引侧参数与 drop 互斥(resetPaths 另有单独互斥文案),
|
|
1185
|
+
* 出现即点名拒绝。
|
|
1186
|
+
* - 否则:`zg --index <root> --embedding <m> [--rebuild] ... --mode <mode>`。
|
|
1187
|
+
* embedding 缺省时由调用方传入 defaultEmbedding(设置里的默认值);解析出的引用过构造期
|
|
1188
|
+
* 闭集 allowlist(见 indexEmbedding),且引用为远程时自动补 `--allow-remote`
|
|
1189
|
+
* (0.3.0 的非交互远程索引没有它就被 PERMISSION_DENIED 拒,上游报错文案原文)。
|
|
995
1190
|
* 传输模式与检索、状态共用同一个入参:三条命令混用模式会在守护进程持有索引租约时
|
|
996
1191
|
* 让写侧直接失败,故一致性由构造器的必填入参强制。
|
|
997
|
-
* 旗标顺序与 filter globs 交错固定(rebuild → globs → hidden →
|
|
998
|
-
* max-depth → max-filesize → follow → embedding-concurrency →
|
|
999
|
-
*
|
|
1192
|
+
* 旗标顺序与 filter globs 交错固定(embedding → allow-remote → rebuild → globs → hidden →
|
|
1193
|
+
* no-ignore → nested-git → max-depth → max-filesize → follow → embedding-concurrency →
|
|
1194
|
+
* reset-paths),不得重排(测试锁死)。
|
|
1000
1195
|
*/
|
|
1001
1196
|
function buildIndexCommand(args, defaultEmbedding, messages, mode = DEFAULT_CLIENT_MODE, allowRemote = false) {
|
|
1002
|
-
const
|
|
1197
|
+
const platform = args.platform ?? "posix";
|
|
1198
|
+
const root = assertAbsoluteRoot(args.root, messages, platform);
|
|
1199
|
+
const quote = quoteFor(platform);
|
|
1003
1200
|
const parts = [
|
|
1004
1201
|
"zg",
|
|
1005
|
-
"index",
|
|
1006
|
-
|
|
1202
|
+
"--index",
|
|
1203
|
+
quote(root)
|
|
1007
1204
|
];
|
|
1008
1205
|
const flags = readIndexFlags(args, messages);
|
|
1009
1206
|
if (boolOf(args.drop, "drop", messages)) {
|
|
1010
1207
|
if (boolOf(args.resetPaths, "resetPaths", messages)) throw new Error(messages.dropWithResetPaths);
|
|
1011
1208
|
const ignored = INDEX_ONLY_PARAMS.filter((name) => args[name] !== void 0 && args[name] !== null);
|
|
1012
1209
|
if (ignored.length > 0) throw new Error(fill(messages.dropWithIndexArgs, { names: ignored.join(" | ") }));
|
|
1013
|
-
parts.push("--drop",
|
|
1014
|
-
return assembled(parts, root, messages);
|
|
1210
|
+
parts.push("--drop", modeFlag(mode));
|
|
1211
|
+
return assembled(parts, root, messages, args.platform ?? "posix");
|
|
1015
1212
|
}
|
|
1016
|
-
|
|
1213
|
+
const { reference, remote } = indexEmbedding(args, defaultEmbedding, messages, allowRemote);
|
|
1214
|
+
parts.push("--embedding", quote(reference));
|
|
1215
|
+
if (remote) parts.push("--allow-remote");
|
|
1017
1216
|
pushIndexBoolFlags(parts, flags);
|
|
1018
|
-
pushIndexGlobs(parts, args, flags, messages);
|
|
1217
|
+
pushIndexGlobs(parts, args, flags, messages, quote);
|
|
1019
1218
|
pushIndexHideFlags(parts, flags);
|
|
1020
1219
|
pushIndexIntFlags(parts, args, messages);
|
|
1021
1220
|
pushIndexFollowFlag(parts, flags);
|
|
1022
1221
|
pushIndexConcurrencyFlag(parts, args, messages);
|
|
1023
1222
|
pushIndexResetPathsFlag(parts, args, messages);
|
|
1024
|
-
parts.push(deviceFlag(args.device, messages), modeFlag(mode));
|
|
1025
|
-
return assembled(parts, root, messages);
|
|
1223
|
+
parts.push(deviceFlag(args.device, messages, quote), modeFlag(mode));
|
|
1224
|
+
return assembled(parts, root, messages, args.platform ?? "posix");
|
|
1026
1225
|
}
|
|
1027
1226
|
/**
|
|
1028
|
-
* 构造 zg status 命令(root
|
|
1227
|
+
* 构造 zg status 命令(0.3.0:`zg --status <root>`;传输模式与另两条命令同源)。
|
|
1029
1228
|
*
|
|
1030
1229
|
* `checkReady` 透传 `--check-ready`:zg 的帮助原文是「preserves the normal output and
|
|
1031
1230
|
* exits non-zero unless the Workspace index is ready」——即**就绪报告照常打在 stdout,
|
|
1032
1231
|
* 只用退出码表达就绪与否**。所以宿主侧必须成对处理这两半:报告要交回,退出码要翻译成
|
|
1033
1232
|
* 结论,不能像普通失败那样只留 stderr 把 stdout 丢掉(实测未就绪时 stdout 正是那份
|
|
1034
|
-
*
|
|
1233
|
+
* 「Coverage Unavailable (index not configured) …」四字段报告)。
|
|
1035
1234
|
*/
|
|
1036
1235
|
function buildStatusCommand(args, messages, mode = DEFAULT_CLIENT_MODE) {
|
|
1037
|
-
const
|
|
1236
|
+
const platform = args.platform ?? "posix";
|
|
1237
|
+
const root = assertAbsoluteRoot(args.root, messages, platform);
|
|
1038
1238
|
const parts = [
|
|
1039
1239
|
"zg",
|
|
1040
|
-
"status",
|
|
1041
|
-
shq(root)
|
|
1240
|
+
"--status",
|
|
1241
|
+
shq(root, platform)
|
|
1042
1242
|
];
|
|
1043
1243
|
if (boolOf(args.checkReady, "checkReady", messages)) parts.push("--check-ready");
|
|
1044
1244
|
parts.push(modeFlag(mode));
|
|
1045
|
-
return assembled(parts, root, messages);
|
|
1245
|
+
return assembled(parts, root, messages, args.platform ?? "posix");
|
|
1046
1246
|
}
|
|
1047
1247
|
// lib/search-predicates.ts
|
|
1048
|
-
/**
|
|
1248
|
+
/** 根目录末尾斜杠(POSIX)。 */
|
|
1049
1249
|
const TRAILING_SLASHES$1 = /\/+$/u;
|
|
1250
|
+
/** win32 根目录末尾分隔符(盘符根 `C:\` 与 UNC 根自身保留)。 */
|
|
1251
|
+
const WIN32_TRAILING_SEPARATORS$1 = /[\\/]+$/u;
|
|
1050
1252
|
const GREP_COMMAND_NAMES = /* @__PURE__ */ new Set([
|
|
1051
1253
|
"grep",
|
|
1052
1254
|
"egrep",
|
|
@@ -1077,10 +1279,30 @@ const SHELL_WRAPPER_NAMES = /* @__PURE__ */ new Set([
|
|
|
1077
1279
|
"dash",
|
|
1078
1280
|
"ksh",
|
|
1079
1281
|
"csh",
|
|
1080
|
-
"fish"
|
|
1282
|
+
"fish",
|
|
1283
|
+
"pwsh",
|
|
1284
|
+
"powershell"
|
|
1081
1285
|
]);
|
|
1082
1286
|
/** 壳层旗标里「其后一枚参数是脚本」的那些:`-c`、`-lc`、`-xc`(只认以 c 收尾的短旗标)。 */
|
|
1083
1287
|
const SHELL_SCRIPT_FLAG = /^-[^c]*c$/u;
|
|
1288
|
+
/** PowerShell 的脚本旗标(`-c` / `-Command`,大小写不敏感)。 */
|
|
1289
|
+
const PWSH_SCRIPT_FLAGS = /* @__PURE__ */ new Set(["-c", "-command"]);
|
|
1290
|
+
/** win32 的盘符绝对路径(`C:\` / `C:/`)。 */
|
|
1291
|
+
const WIN32_DRIVE_ABSOLUTE = /^[A-Za-z]:[\\/]/u;
|
|
1292
|
+
/** win32 根相对路径的前导分隔符(拼接用)。 */
|
|
1293
|
+
const WIN32_LEADING_SEPARATORS = /^[\\/]+/u;
|
|
1294
|
+
/** win32 的转义字符是反引号;反斜杠是路径分隔符,不能当转义符。 */
|
|
1295
|
+
const WIN32_ESCAPE = "`";
|
|
1296
|
+
/** win32 的命令分隔符:反引号在 pwsh 是转义,不是命令替换。 */
|
|
1297
|
+
const WIN32_COMMAND_BREAK_CHARS = /* @__PURE__ */ new Set([
|
|
1298
|
+
"|",
|
|
1299
|
+
";",
|
|
1300
|
+
"&",
|
|
1301
|
+
"\n",
|
|
1302
|
+
"\r"
|
|
1303
|
+
]);
|
|
1304
|
+
/** 命令名的可执行扩展:`rg.exe` / `grep.cmd` 与裸名同判。 */
|
|
1305
|
+
const WIN32_COMMAND_EXTENSIONS = /\.(?:exe|cmd|bat|com|ps1)$/iu;
|
|
1084
1306
|
/** 递归深度上限:一层脚本里的再一层脚本够了;更深的不判(也不该有)。 */
|
|
1085
1307
|
const MAX_SHELL_DEPTH = 2;
|
|
1086
1308
|
const SEARCH_PREFIX_WORDS = /* @__PURE__ */ new Set([
|
|
@@ -1250,7 +1472,7 @@ const SEARCH_VALUE_FLAGS = /* @__PURE__ */ new Set([
|
|
|
1250
1472
|
]);
|
|
1251
1473
|
/** 命令前的壳层赋值(`VAR=1 grep x` 里的 `VAR=1`):它自己不是命令,其后仍是命令位。 */
|
|
1252
1474
|
const SHELL_ASSIGNMENT = /^[A-Za-z_]\w*=/u;
|
|
1253
|
-
/**
|
|
1475
|
+
/** 包装命令的纯数字参数(`timeout 5 rg` 的 `5`):也不是被执行的命令。 */
|
|
1254
1476
|
const BARE_NUMBER = /^\d+$/u;
|
|
1255
1477
|
/** 结束一个 token、但**不**开启新命令位的字符(空白)。 */
|
|
1256
1478
|
const TOKEN_BREAK_CHARS = /* @__PURE__ */ new Set([
|
|
@@ -1291,7 +1513,13 @@ const QUOTE_CHARS = /* @__PURE__ */ new Set(["'", "\""]);
|
|
|
1291
1513
|
* 当前引号状态下,这个字符是否只是要写进 buffer 的字面量(既不结束引号、也不参与分隔)。
|
|
1292
1514
|
* 单引号内一切皆字面量,只有同种引号本身能收束;双引号还认 `\` 转义,故反斜杠也出列。
|
|
1293
1515
|
*/
|
|
1294
|
-
|
|
1516
|
+
/**
|
|
1517
|
+
* 当前引号状态下,这个字符是否只是要写进 buffer 的字面量(既不结束引号、也不参与分隔)。
|
|
1518
|
+
* POSIX:单引号内一切皆字面量;双引号还认 `\` 转义。
|
|
1519
|
+
* win32:单引号内一切皆字面量(反引号也 literal);双引号认 pwsh 的反引号转义。
|
|
1520
|
+
*/
|
|
1521
|
+
function isQuotedLiteral(char, quote, platform) {
|
|
1522
|
+
if (platform === "win32") return quote === "'" && char !== "'" || quote === "\"" && char !== "\"" && char !== WIN32_ESCAPE;
|
|
1295
1523
|
return quote === "'" && char !== "'" || quote === "\"" && char !== "\"" && char !== "\\";
|
|
1296
1524
|
}
|
|
1297
1525
|
/**
|
|
@@ -1345,24 +1573,27 @@ function isCommentStart(char, state) {
|
|
|
1345
1573
|
function toggleQuote(char, quote) {
|
|
1346
1574
|
return quote === char ? "" : char;
|
|
1347
1575
|
}
|
|
1348
|
-
/**
|
|
1576
|
+
/** 包装命令的旗标、纯数字参数、壳层赋值:都不是被执行的命令,也不结束命令位链。 */
|
|
1349
1577
|
function isWrapperNoiseText(isCommand, text) {
|
|
1350
1578
|
return isCommand && (text.startsWith("-") || BARE_NUMBER.test(text) || SHELL_ASSIGNMENT.test(text));
|
|
1351
1579
|
}
|
|
1352
1580
|
/**
|
|
1353
|
-
*
|
|
1354
|
-
*
|
|
1581
|
+
* 明确的路径形状:绝对路径、含分隔符的相对路径、裸 `.` 与 `..`(模式词与文件名不算)。
|
|
1582
|
+
* win32 额外认盘符绝对(`C:\` / `C:/`)、UNC(`\\server\share`)与任何含 `\` 的词。
|
|
1355
1583
|
*/
|
|
1356
|
-
function isPathShape(text) {
|
|
1584
|
+
function isPathShape(text, platform) {
|
|
1585
|
+
if (platform === "win32") return WIN32_DRIVE_ABSOLUTE.test(text) || text.startsWith(BACKSLASH + BACKSLASH) || text.startsWith(BACKSLASH) || text.startsWith("/") || text.includes(BACKSLASH) || text.includes("/") || text === "." || text === "..";
|
|
1357
1586
|
return text.startsWith("/") || text.includes("/") || text === "." || text === "..";
|
|
1358
1587
|
}
|
|
1359
1588
|
/**
|
|
1360
|
-
* token 的命令名(basename,小写)。
|
|
1361
|
-
*
|
|
1362
|
-
* (见 `commandPositionIndexes`),所以这里不再重复判一次前缀:那会是一条
|
|
1363
|
-
* 永远走不到的分支。
|
|
1589
|
+
* token 的命令名(basename,小写)。win32 按 `\` 与 `/` 都切,并剥掉 `.exe` / `.cmd`
|
|
1590
|
+
* 这类可执行扩展——`C:\tools\rg.exe` 与 `rg` 是同一个检索命令。
|
|
1364
1591
|
*/
|
|
1365
|
-
function baseName(text) {
|
|
1592
|
+
function baseName(text, platform) {
|
|
1593
|
+
if (platform === "win32") {
|
|
1594
|
+
const separated = text.replaceAll("\\", "/");
|
|
1595
|
+
return separated.slice(separated.lastIndexOf("/") + 1).toLowerCase().replace(WIN32_COMMAND_EXTENSIONS, "");
|
|
1596
|
+
}
|
|
1366
1597
|
return text.slice(text.lastIndexOf("/") + 1).toLowerCase();
|
|
1367
1598
|
}
|
|
1368
1599
|
/**
|
|
@@ -1371,7 +1602,7 @@ function baseName(text) {
|
|
|
1371
1602
|
* 单独成函数不为复用,只为把这条含 3 层嵌套的判定链从循环里挪出来——循环里只剩
|
|
1372
1603
|
* 「推进一步、命中就记下标」两件事。
|
|
1373
1604
|
*/
|
|
1374
|
-
function advanceCommandChain(token, state) {
|
|
1605
|
+
function advanceCommandChain(token, state, platform) {
|
|
1375
1606
|
const { text } = token;
|
|
1376
1607
|
const consumingValue = state.pendingValue;
|
|
1377
1608
|
const next = {
|
|
@@ -1403,74 +1634,77 @@ function advanceCommandChain(token, state) {
|
|
|
1403
1634
|
command: false
|
|
1404
1635
|
};
|
|
1405
1636
|
}
|
|
1406
|
-
if (isCommand) next.wrapper = SEARCH_PREFIX_WORDS.has(baseName(text)) ? baseName(text) : "";
|
|
1637
|
+
if (isCommand) next.wrapper = SEARCH_PREFIX_WORDS.has(baseName(text, platform)) ? baseName(text, platform) : "";
|
|
1407
1638
|
next.afterPrefix = false;
|
|
1408
1639
|
return {
|
|
1409
1640
|
state: next,
|
|
1410
1641
|
command: isCommand
|
|
1411
1642
|
};
|
|
1412
1643
|
}
|
|
1413
|
-
/**
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1644
|
+
/** 真吐出 token 才消费命令位:空 flush 若清位,控制符后的第一个词就丢了命令位。 */
|
|
1645
|
+
function flushToken(tokens, state) {
|
|
1646
|
+
if (state.buffer.length === 0) return;
|
|
1647
|
+
tokens.push({
|
|
1648
|
+
text: state.buffer,
|
|
1649
|
+
atCommand: state.atCommand,
|
|
1650
|
+
piped: state.pipedNext,
|
|
1651
|
+
redirect: state.redirectNext
|
|
1652
|
+
});
|
|
1653
|
+
state.buffer = "";
|
|
1654
|
+
state.atCommand = false;
|
|
1655
|
+
state.pipedNext = false;
|
|
1656
|
+
state.redirectNext = false;
|
|
1657
|
+
}
|
|
1658
|
+
/** pwsh 的引号内转义:`''` / `""` 是字面引号,不是闭合。返回续读下标。 */
|
|
1659
|
+
function consumeWin32Quote(command, index, state) {
|
|
1660
|
+
const char = command.slice(index, index + 1);
|
|
1661
|
+
if (command.slice(index + 1, index + 2) === char) {
|
|
1662
|
+
state.buffer += char;
|
|
1663
|
+
return index + 1;
|
|
1664
|
+
}
|
|
1665
|
+
state.quote = "";
|
|
1666
|
+
return index;
|
|
1667
|
+
}
|
|
1668
|
+
/** 推进一个字符,返回该字符处理后应继续读的下标(注释会一次跳多格)。 */
|
|
1669
|
+
function advanceTokenState(command, index, state, tokens, platform) {
|
|
1670
|
+
const char = command.slice(index, index + 1);
|
|
1671
|
+
const breakChars = platform === "win32" ? WIN32_COMMAND_BREAK_CHARS : COMMAND_BREAK_CHARS;
|
|
1672
|
+
if (state.escaped) {
|
|
1673
|
+
state.buffer += char;
|
|
1674
|
+
state.escaped = false;
|
|
1675
|
+
} else if (isQuotedLiteral(char, state.quote, platform)) state.buffer += char;
|
|
1676
|
+
else if (isCommentStart(char, state)) return indexAfterComment(command, index);
|
|
1677
|
+
else if (char === (platform === "win32" ? WIN32_ESCAPE : "\\")) state.escaped = true;
|
|
1678
|
+
else if (platform === "win32" && state.quote !== "" && char === state.quote) return consumeWin32Quote(command, index, state);
|
|
1679
|
+
else if (QUOTE_CHARS.has(char)) state.quote = toggleQuote(char, state.quote);
|
|
1680
|
+
else if (breakChars.has(char)) {
|
|
1681
|
+
flushToken(tokens, state);
|
|
1682
|
+
markCommandBreak(command, index, char, state);
|
|
1683
|
+
} else if (isCommandSubstitutionOpen(char, state)) {
|
|
1684
|
+
state.buffer = "";
|
|
1685
|
+
flushToken(tokens, state);
|
|
1686
|
+
markCommandBreak(command, index, char, state);
|
|
1687
|
+
} else if (GROUP_CHARS.has(char)) consumeGroupChar(char, state);
|
|
1688
|
+
else if (REDIRECT_CHARS.has(char)) {
|
|
1689
|
+
flushToken(tokens, state);
|
|
1690
|
+
state.redirectNext = true;
|
|
1691
|
+
} else if (TOKEN_BREAK_CHARS.has(char)) flushToken(tokens, state);
|
|
1692
|
+
else state.buffer += char;
|
|
1693
|
+
return index;
|
|
1694
|
+
}
|
|
1695
|
+
function tokenizeShell(command, platform) {
|
|
1425
1696
|
const tokens = [];
|
|
1426
1697
|
const state = {
|
|
1427
1698
|
buffer: "",
|
|
1428
1699
|
atCommand: true,
|
|
1429
1700
|
pipedNext: false,
|
|
1430
1701
|
redirectNext: false,
|
|
1431
|
-
quote: ""
|
|
1432
|
-
|
|
1433
|
-
const flush = () => {
|
|
1434
|
-
if (state.buffer.length > 0) {
|
|
1435
|
-
tokens.push({
|
|
1436
|
-
text: state.buffer,
|
|
1437
|
-
atCommand: state.atCommand,
|
|
1438
|
-
piped: state.pipedNext,
|
|
1439
|
-
redirect: state.redirectNext
|
|
1440
|
-
});
|
|
1441
|
-
state.buffer = "";
|
|
1442
|
-
state.atCommand = false;
|
|
1443
|
-
state.pipedNext = false;
|
|
1444
|
-
state.redirectNext = false;
|
|
1445
|
-
}
|
|
1702
|
+
quote: "",
|
|
1703
|
+
escaped: false
|
|
1446
1704
|
};
|
|
1447
1705
|
let index = 0;
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
const char = command.slice(index, index + 1);
|
|
1451
|
-
if (escaped) {
|
|
1452
|
-
state.buffer += char;
|
|
1453
|
-
escaped = false;
|
|
1454
|
-
} else if (isQuotedLiteral(char, state.quote)) state.buffer += char;
|
|
1455
|
-
else if (isCommentStart(char, state)) index = indexAfterComment(command, index);
|
|
1456
|
-
else if (char === "\\") escaped = true;
|
|
1457
|
-
else if (QUOTE_CHARS.has(char)) state.quote = toggleQuote(char, state.quote);
|
|
1458
|
-
else if (COMMAND_BREAK_CHARS.has(char)) {
|
|
1459
|
-
flush();
|
|
1460
|
-
markCommandBreak(command, index, char, state);
|
|
1461
|
-
} else if (isCommandSubstitutionOpen(char, state)) {
|
|
1462
|
-
state.buffer = "";
|
|
1463
|
-
flush();
|
|
1464
|
-
markCommandBreak(command, index, char, state);
|
|
1465
|
-
} else if (GROUP_CHARS.has(char)) consumeGroupChar(char, state);
|
|
1466
|
-
else if (REDIRECT_CHARS.has(char)) {
|
|
1467
|
-
flush();
|
|
1468
|
-
state.redirectNext = true;
|
|
1469
|
-
} else if (TOKEN_BREAK_CHARS.has(char)) flush();
|
|
1470
|
-
else state.buffer += char;
|
|
1471
|
-
index += 1;
|
|
1472
|
-
}
|
|
1473
|
-
flush();
|
|
1706
|
+
while (index < command.length) index = advanceTokenState(command, index, state, tokens, platform) + 1;
|
|
1707
|
+
flushToken(tokens, state);
|
|
1474
1708
|
return tokens;
|
|
1475
1709
|
}
|
|
1476
1710
|
/**
|
|
@@ -1478,11 +1712,11 @@ function tokenizeShell(command) {
|
|
|
1478
1712
|
* env…)之后那个真正的实参。
|
|
1479
1713
|
*
|
|
1480
1714
|
* 「包装命令之后」不是「紧邻的下一个 token」:包装命令自己的选项(`git --no-pager`、
|
|
1481
|
-
* `xargs -0`)、选项取值(`sudo -u root
|
|
1715
|
+
* `xargs -0`)、选项取值(`sudo -u root`)、纯数字参数(`timeout 5`)、壳层赋值(`VAR=1`)
|
|
1482
1716
|
* 都还站在命令位之前。只认「紧邻下一个」时命令位链在这些形态上直接断掉,检索调用
|
|
1483
1717
|
* 漏判 —— 而漏判的方向是门禁放行。这几类一律「跳过但不断链」。
|
|
1484
1718
|
*/
|
|
1485
|
-
function commandPositionIndexes(tokens) {
|
|
1719
|
+
function commandPositionIndexes(tokens, platform) {
|
|
1486
1720
|
const out = [];
|
|
1487
1721
|
let chain = {
|
|
1488
1722
|
wrapper: "",
|
|
@@ -1490,19 +1724,20 @@ function commandPositionIndexes(tokens) {
|
|
|
1490
1724
|
afterPrefix: false
|
|
1491
1725
|
};
|
|
1492
1726
|
for (const [index, token] of tokens.entries()) {
|
|
1493
|
-
const step = advanceCommandChain(token, chain);
|
|
1727
|
+
const step = advanceCommandChain(token, chain, platform);
|
|
1494
1728
|
chain = step.state;
|
|
1495
1729
|
if (step.command) out.push(index);
|
|
1496
1730
|
}
|
|
1497
1731
|
return out;
|
|
1498
1732
|
}
|
|
1499
1733
|
/** 取壳层包装那条 `-c` 脚本参数(`bash -c '…'` 里引号内那一整枚 token)。 */
|
|
1500
|
-
function shellScriptArguments(tokens) {
|
|
1734
|
+
function shellScriptArguments(tokens, platform) {
|
|
1501
1735
|
const scripts = [];
|
|
1502
1736
|
for (const [index, token] of tokens.entries()) {
|
|
1503
1737
|
const flag = tokens[index + 1];
|
|
1504
1738
|
const script = tokens[index + 2];
|
|
1505
|
-
|
|
1739
|
+
const scriptFlag = platform === "win32" ? flag !== void 0 && PWSH_SCRIPT_FLAGS.has(flag.text.toLowerCase()) : flag !== void 0 && SHELL_SCRIPT_FLAG.test(flag.text);
|
|
1740
|
+
if (token.atCommand && SHELL_WRAPPER_NAMES.has(baseName(token.text, platform)) && flag !== void 0 && script !== void 0 && scriptFlag && !script.atCommand) scripts.push(script.text);
|
|
1506
1741
|
}
|
|
1507
1742
|
return scripts;
|
|
1508
1743
|
}
|
|
@@ -1510,10 +1745,10 @@ function shellScriptArguments(tokens) {
|
|
|
1510
1745
|
* 该命令位 token 之后的实参里是否出现路径形状的操作数(旗标不算)。
|
|
1511
1746
|
* `.` 与 `..` 都算:`grep foo .` 检索的就是当前工作区。
|
|
1512
1747
|
*/
|
|
1513
|
-
function hasPathOperand(tokens, from) {
|
|
1748
|
+
function hasPathOperand(tokens, from, platform) {
|
|
1514
1749
|
for (const token of tokens.slice(from + 1)) {
|
|
1515
1750
|
if (token.atCommand) break;
|
|
1516
|
-
if (!token.redirect && !token.text.startsWith("-") && isPathShape(token.text)) return true;
|
|
1751
|
+
if (!token.redirect && !token.text.startsWith("-") && isPathShape(token.text, platform)) return true;
|
|
1517
1752
|
}
|
|
1518
1753
|
return false;
|
|
1519
1754
|
}
|
|
@@ -1541,28 +1776,53 @@ function hasPathOperand(tokens, from) {
|
|
|
1541
1776
|
* - 嵌套只认壳层包装名单里 `-c` 后面那一段,且最多看进去两层;名单外的前缀
|
|
1542
1777
|
* (`watch -n 5 grep`)与 `awk 'BEGIN{system("grep x y")}'` 一类不递归。
|
|
1543
1778
|
*/
|
|
1544
|
-
function isGrepRgCommand(command, depth = 0) {
|
|
1545
|
-
const tokens = tokenizeShell(command);
|
|
1779
|
+
function isGrepRgCommand(command, depth = 0, platform = "posix") {
|
|
1780
|
+
const tokens = tokenizeShell(command, platform);
|
|
1546
1781
|
if (tokens.some((token) => PROBE_FLAGS.has(token.text))) return false;
|
|
1547
|
-
if (commandPositionIndexes(tokens).some((index) => {
|
|
1782
|
+
if (commandPositionIndexes(tokens, platform).some((index) => {
|
|
1548
1783
|
const token = tokens[index];
|
|
1549
|
-
if (token === void 0 || !GREP_COMMAND_NAMES.has(baseName(token.text))) return false;
|
|
1550
|
-
return !(token.piped && !hasPathOperand(tokens, index));
|
|
1784
|
+
if (token === void 0 || !GREP_COMMAND_NAMES.has(baseName(token.text, platform))) return false;
|
|
1785
|
+
return !(token.piped && !hasPathOperand(tokens, index, platform));
|
|
1551
1786
|
})) return true;
|
|
1552
1787
|
if (depth >= MAX_SHELL_DEPTH) return false;
|
|
1553
|
-
return shellScriptArguments(tokens).some((script) => isGrepRgCommand(script, depth + 1));
|
|
1788
|
+
return shellScriptArguments(tokens, platform).some((script) => isGrepRgCommand(script, depth + 1, platform));
|
|
1789
|
+
}
|
|
1790
|
+
/**
|
|
1791
|
+
* 去掉尾部斜杠的 root 归一化。POSIX 只认 `/`;win32 认 `\` 与 `/`,盘符根 `C:\`
|
|
1792
|
+
* 与 UNC 共享根 `\\server\share\` 保留原形(它们本身就是根)。
|
|
1793
|
+
* @param root 待归一化的根
|
|
1794
|
+
* @param platform 路径方言(缺省 posix;宿主按 runtimePlatform() 传入)
|
|
1795
|
+
* @returns 归一后的根
|
|
1796
|
+
*/
|
|
1797
|
+
function normalizeRoot(root, platform = "posix") {
|
|
1798
|
+
if (platform === "win32") {
|
|
1799
|
+
const converted = root.replaceAll("/", "\\");
|
|
1800
|
+
const parsedRoot = nodePath.win32.parse(converted).root;
|
|
1801
|
+
if (converted === parsedRoot) return parsedRoot;
|
|
1802
|
+
const trimmed = converted.replace(WIN32_TRAILING_SEPARATORS$1, "");
|
|
1803
|
+
return trimmed.length > 0 ? trimmed : parsedRoot;
|
|
1804
|
+
}
|
|
1805
|
+
const trimmed = root.replace(TRAILING_SLASHES$1, "");
|
|
1806
|
+
return trimmed.length > 0 ? trimmed : "/";
|
|
1807
|
+
}
|
|
1808
|
+
/** win32 的完整限定路径(盘符绝对或 UNC);不是则 false。 */
|
|
1809
|
+
function isWin32Absolute(text) {
|
|
1810
|
+
const separated = text.replaceAll("/", "\\");
|
|
1811
|
+
return WIN32_DRIVE_ABSOLUTE.test(separated) || separated.startsWith(BACKSLASH + BACKSLASH);
|
|
1554
1812
|
}
|
|
1813
|
+
/** 相对路径离开根:`..`、`..\x`、`../x`(`..foo` 是正常子项,不算逃逸)。 */
|
|
1814
|
+
const ESCAPES_ROOT = /^\.\.(?:[\\/]|$)/u;
|
|
1555
1815
|
/**
|
|
1556
|
-
*
|
|
1557
|
-
*
|
|
1558
|
-
* 只认 `/`:本包的根判据(`assertAbsoluteRoot` 只收 `/` 开头的串)、命令 tokenizer 与
|
|
1559
|
-
* `rootPaths` 覆盖判据都按 POSIX 形切分,root 归一化再多认一种分隔符只会让上游认得出、
|
|
1560
|
-
* 下游判不回——README 的 Support surface 一节写明 Windows 主机不在支持面内,
|
|
1561
|
-
* 失败形态是 fail-fast 而不是静默漂移。要真正支持 Windows,得连上面那三处判据一起改。
|
|
1816
|
+
* win32 下的目标补全:完整限定路径原样用;`\foo` 或 `/foo` 按根的盘符/共享补全
|
|
1817
|
+
* (pwsh 的根相对路径语义);其余按相对 root 拼接。
|
|
1562
1818
|
*/
|
|
1563
|
-
function
|
|
1564
|
-
|
|
1565
|
-
|
|
1819
|
+
function qualifyWin32Target(target, base) {
|
|
1820
|
+
if (isWin32Absolute(target)) return target;
|
|
1821
|
+
if (target.startsWith(BACKSLASH) || target.startsWith("/")) {
|
|
1822
|
+
const { root } = nodePath.win32.parse(base);
|
|
1823
|
+
return `${root}${target.replace(WIN32_LEADING_SEPARATORS, "")}`;
|
|
1824
|
+
}
|
|
1825
|
+
return `${base}\\${target}`;
|
|
1566
1826
|
}
|
|
1567
1827
|
/**
|
|
1568
1828
|
* 判断检索目标是否落在 root 之内(按路径段前缀,防 /fo 误吞 /foo)。
|
|
@@ -1572,11 +1832,24 @@ function normalizeRoot(root) {
|
|
|
1572
1832
|
* 归一化时 `..` 越出文件系统根,说明目标必然在 root 之外 → 直接 false
|
|
1573
1833
|
* (这里是「判范围」,不是「判合法性」)。messages 只为把归一化异常喂给
|
|
1574
1834
|
* normalizeAbsolutePath——那条文本在这里被丢弃,出界才是结论。
|
|
1835
|
+
*
|
|
1836
|
+
* win32 的「之内」按 `path.win32.relative` 判:盘符大小写与分隔符差异都被归一,
|
|
1837
|
+
* 不同盘符/共享返回绝对路径 ⇒ 根外。
|
|
1575
1838
|
*/
|
|
1576
|
-
function pathInsideRoot(target, root, messages) {
|
|
1839
|
+
function pathInsideRoot(target, root, messages, platform = "posix") {
|
|
1577
1840
|
if (target === void 0 || target.trim().length === 0) return true;
|
|
1578
|
-
const base = normalizeRoot(root);
|
|
1841
|
+
const base = normalizeRoot(root, platform);
|
|
1579
1842
|
const targetText = target.trim();
|
|
1843
|
+
if (platform === "win32") {
|
|
1844
|
+
let absolute;
|
|
1845
|
+
try {
|
|
1846
|
+
absolute = normalizeAbsolutePath(qualifyWin32Target(targetText, base), messages, "win32");
|
|
1847
|
+
} catch {
|
|
1848
|
+
return false;
|
|
1849
|
+
}
|
|
1850
|
+
const relative = nodePath.win32.relative(base, absolute);
|
|
1851
|
+
return relative === "" || !ESCAPES_ROOT.test(relative) && !nodePath.win32.isAbsolute(relative);
|
|
1852
|
+
}
|
|
1580
1853
|
const joined = targetText.startsWith("/") ? targetText : `${base}/${targetText}`;
|
|
1581
1854
|
let absolute;
|
|
1582
1855
|
try {
|
|
@@ -1600,10 +1873,10 @@ function pathInsideRoot(target, root, messages) {
|
|
|
1600
1873
|
* 的模式词可能被误判为外部目标而放行(漏拦,安全方向);混合目标(如
|
|
1601
1874
|
* `rg foo /repo/src /tmp/x`)因存在外部绝对路径而整体放行。
|
|
1602
1875
|
*/
|
|
1603
|
-
function hasExternalTarget(root, command, messages) {
|
|
1604
|
-
const base = normalizeRoot(root);
|
|
1605
|
-
const tokens = tokenizeShell(command);
|
|
1606
|
-
const commandIndexes = new Set(commandPositionIndexes(tokens));
|
|
1876
|
+
function hasExternalTarget(root, command, messages, platform = "posix") {
|
|
1877
|
+
const base = normalizeRoot(root, platform);
|
|
1878
|
+
const tokens = tokenizeShell(command, platform);
|
|
1879
|
+
const commandIndexes = new Set(commandPositionIndexes(tokens, platform));
|
|
1607
1880
|
/** 上一枚是检索侧的取值旗标:这一枚是它的值(模式 / glob / 编码名…),不是目标。 */
|
|
1608
1881
|
let pendingValue = false;
|
|
1609
1882
|
for (const [index, token] of tokens.entries()) {
|
|
@@ -1612,7 +1885,7 @@ function hasExternalTarget(root, command, messages) {
|
|
|
1612
1885
|
pendingValue = false;
|
|
1613
1886
|
if (!(commandIndexes.has(index) || consumedValue || token.redirect)) {
|
|
1614
1887
|
if (text.startsWith("-")) pendingValue = SEARCH_VALUE_FLAGS.has(text);
|
|
1615
|
-
else if (isPathShape(text) && !pathInsideRoot(text, base, messages)) return true;
|
|
1888
|
+
else if (isPathShape(text, platform) && !pathInsideRoot(text, base, messages, platform)) return true;
|
|
1616
1889
|
}
|
|
1617
1890
|
}
|
|
1618
1891
|
return false;
|
|
@@ -1635,8 +1908,8 @@ function unlockActive(unlock, now) {
|
|
|
1635
1908
|
* @param messages 文案表(归一化异常时喂给它,异常文本在此被丢弃,出界才是结论)
|
|
1636
1909
|
* @returns 是否互为祖先/后代
|
|
1637
1910
|
*/
|
|
1638
|
-
function pathsRelated(left, right, messages) {
|
|
1639
|
-
return pathInsideRoot(left, right, messages) || pathInsideRoot(right, left, messages);
|
|
1911
|
+
function pathsRelated(left, right, messages, platform = "posix") {
|
|
1912
|
+
return pathInsideRoot(left, right, messages, platform) || pathInsideRoot(right, left, messages, platform);
|
|
1640
1913
|
}
|
|
1641
1914
|
// lib/routing.ts
|
|
1642
1915
|
/** 紧跟 TOOL_GREP(1500) 之后、TOOL_JOBS(1600) 之前。 */
|
|
@@ -1689,10 +1962,10 @@ function sessionHeaderCwd$1(execution) {
|
|
|
1689
1962
|
* root 判据(与 execute 的 assertAbsoluteRoot 完全同源):合法返回 undefined;
|
|
1690
1963
|
* 非法时返回可直接给模型的原因。
|
|
1691
1964
|
*/
|
|
1692
|
-
function rootProblem(name, root, messages) {
|
|
1965
|
+
function rootProblem(name, root, messages, platform) {
|
|
1693
1966
|
let problem;
|
|
1694
1967
|
try {
|
|
1695
|
-
assertAbsoluteRoot(root, messages);
|
|
1968
|
+
assertAbsoluteRoot(root, messages, platform);
|
|
1696
1969
|
} catch (error) {
|
|
1697
1970
|
problem = fill(messages.guardRootRejected, {
|
|
1698
1971
|
name,
|
|
@@ -1702,12 +1975,12 @@ function rootProblem(name, root, messages) {
|
|
|
1702
1975
|
return problem;
|
|
1703
1976
|
}
|
|
1704
1977
|
/** 单个 zg_* 调用的拒绝原因(confirm / root 两道,见 zgGuard 的注释)。 */
|
|
1705
|
-
function zgToolProblem(name, args, execution, messages) {
|
|
1978
|
+
function zgToolProblem(name, args, execution, messages, platform) {
|
|
1706
1979
|
const { root } = args;
|
|
1707
1980
|
let problem;
|
|
1708
1981
|
if (name === "zg_index" && args["confirm"] !== true) problem = messages.guardIndexConfirmRequired;
|
|
1709
1982
|
else if (root === void 0 || root === null || root === "") problem = sessionHeaderCwd$1(execution) === void 0 ? fill(messages.guardAbsoluteRootRequired, { name }) : void 0;
|
|
1710
|
-
else problem = rootProblem(name, root, messages);
|
|
1983
|
+
else problem = rootProblem(name, root, messages, platform);
|
|
1711
1984
|
return problem;
|
|
1712
1985
|
}
|
|
1713
1986
|
/**
|
|
@@ -1720,14 +1993,14 @@ function zgToolProblem(name, args, execution, messages) {
|
|
|
1720
1993
|
* @param messages - 拒绝理由的文案表(宿主按语言注入)。
|
|
1721
1994
|
* @returns 拒绝理由;undefined = 放行。
|
|
1722
1995
|
*/
|
|
1723
|
-
function zgGuard(execution, messages) {
|
|
1996
|
+
function zgGuard(execution, messages, platform = "posix") {
|
|
1724
1997
|
const { name } = execution;
|
|
1725
1998
|
const args = isRecord(execution.arguments) ? execution.arguments : {};
|
|
1726
1999
|
let reason;
|
|
1727
|
-
if (isZgToolName(name)) reason = zgToolProblem(name, args, execution, messages);
|
|
2000
|
+
if (isZgToolName(name)) reason = zgToolProblem(name, args, execution, messages, platform);
|
|
1728
2001
|
return reason;
|
|
1729
2002
|
}
|
|
1730
|
-
/** zg
|
|
2003
|
+
/** zg 索引库目录名(`zg --index` 的写到磁盘位置:<root>/.zvec-grep/)。 */
|
|
1731
2004
|
const INDEX_DIR_NAME = ".zvec-grep";
|
|
1732
2005
|
/**
|
|
1733
2006
|
* 工作区索引的判别文件名(上游 `@zvec/zvec` 的 `WORKSPACE_MANIFEST_FILE`,同名同值):
|
|
@@ -1737,6 +2010,20 @@ const INDEX_DIR_NAME = ".zvec-grep";
|
|
|
1737
2010
|
* 于是一个从没建过索引、只是祖先目录撞名的普通工作区也会被当成「已建索引」。
|
|
1738
2011
|
*/
|
|
1739
2012
|
const WORKSPACE_MANIFEST_FILE = "manifest.json";
|
|
2013
|
+
/** win32 的完整限定路径(盘符绝对或 UNC)。 */
|
|
2014
|
+
const WIN32_ABSOLUTE_PATH = /^[A-Za-z]:[\\/]/u;
|
|
2015
|
+
/** 起点是否是本平台的绝对路径(相对路径无从向上找索引根)。 */
|
|
2016
|
+
function isAbsoluteStart(dir, platform) {
|
|
2017
|
+
if (platform === "win32") return WIN32_ABSOLUTE_PATH.test(dir) || dir.startsWith(BACKSLASH + BACKSLASH);
|
|
2018
|
+
return dir.startsWith("/");
|
|
2019
|
+
}
|
|
2020
|
+
/** 上一级目录:POSIX 到 `/` 停,win32 交给 path.win32.dirname(盘符/UNC 根自返)。 */
|
|
2021
|
+
function parentDirectory(dir, platform) {
|
|
2022
|
+
if (platform === "win32") return nodePath.win32.dirname(dir);
|
|
2023
|
+
if (dir === "/") return "/";
|
|
2024
|
+
const cut = dir.lastIndexOf("/");
|
|
2025
|
+
return cut <= 0 ? "/" : dir.slice(0, cut);
|
|
2026
|
+
}
|
|
1740
2027
|
/**
|
|
1741
2028
|
* 从 startDir 向上找含 zg 索引库的最近祖先(含自身),返回该索引根。
|
|
1742
2029
|
* 会话工作区可能是索引根的子目录(如索引在仓库根、会话开在子包)——不向上走
|
|
@@ -1744,17 +2031,19 @@ const WORKSPACE_MANIFEST_FILE = "manifest.json";
|
|
|
1744
2031
|
* 相对路径无从向上判(祖先链不是文件系统事实),按「探测不到」处理:返回 undefined,
|
|
1745
2032
|
* 与「上一层没有索引」同形,门禁按无索引放行。
|
|
1746
2033
|
*/
|
|
1747
|
-
function findIndexRoot(startDir, probe, maxDepth = 8) {
|
|
1748
|
-
let dir = normalizeRoot(startDir);
|
|
2034
|
+
function findIndexRoot(startDir, probe, maxDepth = 8, platform = "posix") {
|
|
1749
2035
|
let found;
|
|
1750
|
-
if (startDir
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
2036
|
+
if (isAbsoluteStart(startDir, platform)) {
|
|
2037
|
+
let dir = normalizeRoot(startDir, platform);
|
|
2038
|
+
for (let depth = 0; depth <= maxDepth; depth += 1) {
|
|
2039
|
+
if (probe(dir)) {
|
|
2040
|
+
found = dir;
|
|
2041
|
+
break;
|
|
2042
|
+
}
|
|
2043
|
+
const parent = parentDirectory(dir, platform);
|
|
2044
|
+
if (parent === dir) break;
|
|
2045
|
+
dir = parent;
|
|
1754
2046
|
}
|
|
1755
|
-
if (dir === "/") break;
|
|
1756
|
-
const cut = dir.lastIndexOf("/");
|
|
1757
|
-
dir = cut <= 0 ? "/" : dir.slice(0, cut);
|
|
1758
2047
|
}
|
|
1759
2048
|
return found;
|
|
1760
2049
|
}
|
|
@@ -1803,25 +2092,31 @@ function rootSessionKeyOf(execution, lookup) {
|
|
|
1803
2092
|
return cursor;
|
|
1804
2093
|
}
|
|
1805
2094
|
/**
|
|
1806
|
-
* 原生 grep
|
|
2095
|
+
* 原生 grep 工具的目标是否落在索引根之内。相对路径先按**会话工作区**解析成绝对路径,
|
|
1807
2096
|
* 再按索引根判内外——按索引根直接拼相对段会把 `../other` 拼进索引根内部,方向判反。
|
|
1808
2097
|
* `..` 越出文件系统根:目标必然不在索引根之内(判范围不判合法性,同 pathInsideRoot)。
|
|
1809
2098
|
*/
|
|
1810
|
-
|
|
2099
|
+
/** 目标按 cwd 补成绝对路径:win32 的盘符/UNC 原样用,其余按 base 拼接。 */
|
|
2100
|
+
function absoluteTargetOf(cwd, target, platform) {
|
|
2101
|
+
const base = normalizeRoot(cwd, platform);
|
|
2102
|
+
if (platform === "win32") return WIN32_ABSOLUTE_PATH.test(target) || target.startsWith(BACKSLASH + BACKSLASH) ? target : `${base}\\${target}`;
|
|
2103
|
+
return target.startsWith("/") ? target : `${base}/${target}`;
|
|
2104
|
+
}
|
|
2105
|
+
function nativeTargetInsideRoot(cwd, indexRoot, target, messages, platform) {
|
|
1811
2106
|
if (target === void 0 || target.trim().length === 0) return true;
|
|
1812
2107
|
const text = target.trim();
|
|
1813
|
-
const joined = text.startsWith("/") ? text : `${normalizeRoot(cwd)}/${text}`;
|
|
1814
2108
|
let absolute;
|
|
1815
2109
|
try {
|
|
1816
|
-
absolute = normalizeAbsolutePath(
|
|
2110
|
+
absolute = normalizeAbsolutePath(absoluteTargetOf(cwd, text, platform), messages, platform);
|
|
1817
2111
|
} catch {
|
|
1818
2112
|
return false;
|
|
1819
2113
|
}
|
|
1820
|
-
return pathInsideRoot(absolute, indexRoot, messages);
|
|
2114
|
+
return pathInsideRoot(absolute, indexRoot, messages, platform);
|
|
1821
2115
|
}
|
|
1822
2116
|
/** 索引根已定且这棵树的范围判定要走门禁时的那句拒绝理由;交回 undefined 即放行。 */
|
|
1823
2117
|
function gateReasonAt(indexRoot, cwd, scope, deps, messages) {
|
|
1824
|
-
const
|
|
2118
|
+
const platform = deps.platform ?? "posix";
|
|
2119
|
+
const inScope = scope.kind === "shell" ? !hasExternalTarget(indexRoot, scope.command, messages, platform) : nativeTargetInsideRoot(cwd, indexRoot, scope.target, messages, platform);
|
|
1825
2120
|
let reason;
|
|
1826
2121
|
if (inScope) {
|
|
1827
2122
|
if (!(deps.rebuildBypass?.(indexRoot) === true)) {
|
|
@@ -1847,29 +2142,29 @@ function gateReasonAt(indexRoot, cwd, scope, deps, messages) {
|
|
|
1847
2142
|
/**
|
|
1848
2143
|
* 索引根已定后的门禁裁决:无索引根 / 检索索引根之外 / 有可扣额度 → 放行
|
|
1849
2144
|
* (undefined);否则返回拦截文案。放行会触发 consumeGrep 副作用。
|
|
1850
|
-
*
|
|
1851
|
-
* 子目录时,`../sibling` 或 `/repo/other` 相对 cwd 出界、相对索引根却在界内——shell
|
|
1852
|
-
* 的 hasExternalTarget 本来就按索引根判,原生 grep
|
|
1853
|
-
*
|
|
2145
|
+
* 两道拦截的「之内/之外」都以**索引根**为准(不是会话工作区):会话开在索引根的
|
|
2146
|
+
* 子目录时,`../sibling` 或 `/repo/other` 相对 cwd 出界、相对索引根却在界内——shell 工具
|
|
2147
|
+
* 的 hasExternalTarget 本来就按索引根判,原生 grep 工具若按 cwd 判,同样的目标会从
|
|
2148
|
+
* 工具这一层绕过门禁,两边各说各话。
|
|
1854
2149
|
*/
|
|
1855
2150
|
function buildSearchFirstReason(cwd, scope, deps, messages) {
|
|
1856
|
-
const indexRoot = findIndexRoot(cwd, deps.indexProbe, deps.findIndexDepth);
|
|
2151
|
+
const indexRoot = findIndexRoot(cwd, deps.indexProbe, deps.findIndexDepth, deps.platform ?? "posix");
|
|
1857
2152
|
return indexRoot === void 0 ? void 0 : gateReasonAt(indexRoot, cwd, scope, deps, messages);
|
|
1858
2153
|
}
|
|
1859
2154
|
/**
|
|
1860
|
-
* shell
|
|
2155
|
+
* shell 工具(bash/pwsh)的一次检索裁决:命令串里真出现 grep/rg 才交给门禁,
|
|
1861
2156
|
* 否则放行。`command` 非字符串(模型产出的是 unknown)按空串处理,与旧实现同形。
|
|
1862
2157
|
*/
|
|
1863
2158
|
function shellSearchProblem(args, cwd, deps, messages) {
|
|
1864
2159
|
const commandRaw = args["command"];
|
|
1865
2160
|
const command = typeof commandRaw === "string" ? commandRaw : "";
|
|
1866
|
-
return isGrepRgCommand(command) ? buildSearchFirstReason(cwd, {
|
|
2161
|
+
return isGrepRgCommand(command, 0, deps.platform ?? "posix") ? buildSearchFirstReason(cwd, {
|
|
1867
2162
|
kind: "shell",
|
|
1868
2163
|
command
|
|
1869
2164
|
}, deps, messages) : void 0;
|
|
1870
2165
|
}
|
|
1871
2166
|
/**
|
|
1872
|
-
* 原生 grep
|
|
2167
|
+
* 原生 grep 工具这一层的一次检索裁决:目标在索引根之外 = 不是本工作区的检索 → 放行
|
|
1873
2168
|
* (与 pathInsideRoot 的「判范围不判合法性」同侧)。无 path 参数按搜整个工作区。
|
|
1874
2169
|
*/
|
|
1875
2170
|
function nativeGrepProblem(args, cwd, deps, messages) {
|
|
@@ -1897,7 +2192,7 @@ function searchFirstGuard(execution, deps, messages) {
|
|
|
1897
2192
|
return reason;
|
|
1898
2193
|
}
|
|
1899
2194
|
// lib/rebuild-state.ts
|
|
1900
|
-
/**
|
|
2195
|
+
/** 「某条占位已落定」这条承诺的统一处理:只交回结论,把 promise 本身留在注册表内部。 */
|
|
1901
2196
|
async function settledOutcome(target) {
|
|
1902
2197
|
await target.settled;
|
|
1903
2198
|
return "settled";
|
|
@@ -1921,11 +2216,11 @@ function warnIfCrowded(entries, max, alreadyCrowded) {
|
|
|
1921
2216
|
/**
|
|
1922
2217
|
* 覆盖给定 root 的那条活跃条目:重建根是 root 的祖先或同一处时命中,多条命中取
|
|
1923
2218
|
* startedAt 最早的一条。抽成自由函数是为了让 `covering` 与 `wait` 共用同一段判据
|
|
1924
|
-
*
|
|
2219
|
+
* ——两者一旦分叉,就会重演「门禁等得到、等待等不到」那个规则不一致的毛病。
|
|
1925
2220
|
*/
|
|
1926
|
-
function coveringOf(entries, root, messages) {
|
|
2221
|
+
function coveringOf(entries, root, messages, platform) {
|
|
1927
2222
|
let best;
|
|
1928
|
-
for (const entry of entries.values()) if (pathInsideRoot(root, entry.root, messages) && (best === void 0 || entry.startedAt < best.startedAt)) best = entry;
|
|
2223
|
+
for (const entry of entries.values()) if (pathInsideRoot(root, entry.root, messages, platform) && (best === void 0 || entry.startedAt < best.startedAt)) best = entry;
|
|
1929
2224
|
return best;
|
|
1930
2225
|
}
|
|
1931
2226
|
/**
|
|
@@ -1934,10 +2229,16 @@ function coveringOf(entries, root, messages) {
|
|
|
1934
2229
|
function createRebuildRegistry(options = {}) {
|
|
1935
2230
|
const now = options.now ?? Date.now;
|
|
1936
2231
|
const maxTracked = options.maxTracked ?? 32;
|
|
2232
|
+
const platform = options.platform ?? "posix";
|
|
1937
2233
|
const entries = /* @__PURE__ */ new Map();
|
|
2234
|
+
/** 注册表键:win32 大小写不敏感(NTFS 默认),POSIX 保持原样。 */
|
|
2235
|
+
const keyOf = (root) => {
|
|
2236
|
+
const normalized = normalizeRoot(root, platform);
|
|
2237
|
+
return platform === "win32" ? normalized.toLowerCase() : normalized;
|
|
2238
|
+
};
|
|
1938
2239
|
let crowded = false;
|
|
1939
2240
|
const release = (root, claimed) => {
|
|
1940
|
-
const key =
|
|
2241
|
+
const key = keyOf(root);
|
|
1941
2242
|
const entry = entries.get(key);
|
|
1942
2243
|
if (entry === void 0 || claimed !== void 0 && claimed !== entry) return false;
|
|
1943
2244
|
entries.delete(key);
|
|
@@ -1947,14 +2248,14 @@ function createRebuildRegistry(options = {}) {
|
|
|
1947
2248
|
};
|
|
1948
2249
|
return {
|
|
1949
2250
|
claim(root, origin, startedAt) {
|
|
1950
|
-
const key =
|
|
2251
|
+
const key = keyOf(root);
|
|
1951
2252
|
if (entries.has(key)) return null;
|
|
1952
2253
|
const { promise: settled, resolve } = Promise.withResolvers();
|
|
1953
2254
|
const settle = () => {
|
|
1954
2255
|
resolve(void 0);
|
|
1955
2256
|
};
|
|
1956
2257
|
const entry = {
|
|
1957
|
-
root:
|
|
2258
|
+
root: normalizeRoot(root, platform),
|
|
1958
2259
|
origin,
|
|
1959
2260
|
startedAt: startedAt ?? now(),
|
|
1960
2261
|
phase: "starting",
|
|
@@ -1967,7 +2268,7 @@ function createRebuildRegistry(options = {}) {
|
|
|
1967
2268
|
return entry;
|
|
1968
2269
|
},
|
|
1969
2270
|
attach(root, jobId, claimed) {
|
|
1970
|
-
const entry = entries.get(
|
|
2271
|
+
const entry = entries.get(keyOf(root));
|
|
1971
2272
|
if (entry === void 0 || claimed !== void 0 && claimed !== entry) return false;
|
|
1972
2273
|
entry.jobId = jobId;
|
|
1973
2274
|
entry.phase = "running";
|
|
@@ -1975,13 +2276,13 @@ function createRebuildRegistry(options = {}) {
|
|
|
1975
2276
|
},
|
|
1976
2277
|
release,
|
|
1977
2278
|
active(root) {
|
|
1978
|
-
return entries.get(
|
|
2279
|
+
return entries.get(keyOf(root));
|
|
1979
2280
|
},
|
|
1980
2281
|
covering(root, messages) {
|
|
1981
|
-
return coveringOf(entries, normalizeRoot(root), messages);
|
|
2282
|
+
return coveringOf(entries, normalizeRoot(root, platform), messages, platform);
|
|
1982
2283
|
},
|
|
1983
2284
|
async wait(root, messages, timeoutMs, signal) {
|
|
1984
|
-
const entry = coveringOf(entries, normalizeRoot(root), messages);
|
|
2285
|
+
const entry = coveringOf(entries, normalizeRoot(root, platform), messages, platform);
|
|
1985
2286
|
if (entry === void 0) return "settled";
|
|
1986
2287
|
if (signal?.aborted === true) return "aborted";
|
|
1987
2288
|
const { promise, resolve } = Promise.withResolvers();
|
|
@@ -1995,7 +2296,7 @@ function createRebuildRegistry(options = {}) {
|
|
|
1995
2296
|
const waitCovering = async (target) => {
|
|
1996
2297
|
const outcome = await Promise.race([settledOutcome(target), promise]);
|
|
1997
2298
|
if (outcome !== "settled") return outcome;
|
|
1998
|
-
const next = coveringOf(entries, root, messages);
|
|
2299
|
+
const next = coveringOf(entries, root, messages, platform);
|
|
1999
2300
|
return next === void 0 ? "settled" : waitCovering(next);
|
|
2000
2301
|
};
|
|
2001
2302
|
try {
|
|
@@ -2010,114 +2311,87 @@ function createRebuildRegistry(options = {}) {
|
|
|
2010
2311
|
}
|
|
2011
2312
|
};
|
|
2012
2313
|
}
|
|
2013
|
-
/** 索引重建与其它占用者分开:等与不等是两回事。
|
|
2314
|
+
/** 索引重建与其它占用者分开:等与不等是两回事。0.3.0 的重建持锁方自报名仍为此串
|
|
2315
|
+
* (上游 indexing/service.rs:`options.rebuild ? "index.rebuild" : …`)。 */
|
|
2014
2316
|
const REBUILD_OPERATION = "index.rebuild";
|
|
2015
|
-
/**
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
/**
|
|
2020
|
-
* zg 明细块的键值行。三个细节都来自「明细行是缩进的」这一实测形状:
|
|
2021
|
-
* - 缩进**必填**(`\s+`):明细块之后任何含冒号的非空行(第二个错误块的 `Error:` /
|
|
2022
|
-
* `Code:`、尾注 `Hint:`)都不该被当成明细键收进表,与已知键同名时会污染判断;
|
|
2023
|
-
* - 键字符集放宽到字母开头 + `[\w-]`:上游若改用 `owner_operation` 这类拼写,行至少
|
|
2024
|
-
* 还能被认出来(值是否被消费由查表侧决定),不至于整块收集在此中断;
|
|
2025
|
-
* - 值必须以非空白开头:把只含空白的行当成有效值没有意义。
|
|
2026
|
-
*/
|
|
2027
|
-
const DETAIL_LINE = /^\s+(?<key>[A-Za-z][\w-]*):\s*(?<value>\S.*)$/u;
|
|
2028
|
-
/** 错误码行的**定位**形状(只认行首,不核内容)。 */
|
|
2029
|
-
const CODE_LINE_PREFIX = /^\s*Code:/u;
|
|
2030
|
-
/** 错误码行的**取值**形状:`Code:` 之后是单一 token。 */
|
|
2031
|
-
const CODE_LINE = /^\s*Code:\s*(?<code>\S+)\s*$/u;
|
|
2032
|
-
/**
|
|
2033
|
-
* 抽错误码。没有该行就不是 zg 的结构化失败(旁路返回 null,交给通用失败文案)。
|
|
2034
|
-
* 先定位第一条 `Code:` 行、再核它的内容是否为单一 token:一次失败只应有一个码,
|
|
2035
|
-
* 首处写成 `Code: XXX (detail)` 说明输出形状已变——宁可不判,也不许顺延到后文
|
|
2036
|
-
* 捞一个可能属于别的错误块的码回来。
|
|
2317
|
+
/**
|
|
2318
|
+
* 码行的**定位与取值**形状:`Error[<码>]:`(行首,MCP 文本为小写 `error[`)。
|
|
2319
|
+
* 码字符集取 `[A-Za-z0-9_.]`:0.3.0 的码形如 `ZG.ENGINE.RESOURCE_BUSY`;定位与取值
|
|
2320
|
+
* 同一条正则完成——0.3.0 没有独立的 `Code:` 行,码只在首行出现一次。
|
|
2037
2321
|
*/
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2322
|
+
/** 码行的定位形状(行首零个以上空格 + error[码]:;`\]` 之后的成因在代码里切片取)。 */
|
|
2323
|
+
const CODE_LINE_PREFIX = /^ *error\[[a-z][\w.]*\]:/iu;
|
|
2324
|
+
/** 成因串分隔符(码行里 `]:` 之后的部分;indexOf 定位,不与正则量词相邻)。 */
|
|
2325
|
+
const MESSAGE_DELIMITER = "]:";
|
|
2042
2326
|
/**
|
|
2043
|
-
*
|
|
2044
|
-
*
|
|
2045
|
-
* 块的键值。找不到返回 -1。
|
|
2327
|
+
* daemon 传输层失败(fetch 层):非工具错误、非协议拒绝。auto 档据此在同一次调用里
|
|
2328
|
+
* 回退 CLI;`aborted` 为真表示超时/取消,不回退(等待已经花掉了)。
|
|
2046
2329
|
*/
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2330
|
+
var DaemonCallFailureError = class extends Error {
|
|
2331
|
+
aborted;
|
|
2332
|
+
constructor(message, aborted) {
|
|
2333
|
+
super(message);
|
|
2334
|
+
this.name = "DaemonCallFailureError";
|
|
2335
|
+
this.aborted = aborted;
|
|
2052
2336
|
}
|
|
2053
|
-
|
|
2337
|
+
};
|
|
2338
|
+
/** 成因串里占锁方操作名的取值形状(`operation=<token>`)。 */
|
|
2339
|
+
const OPERATION_IN_MESSAGE = /\boperation=(?<op>\S+)/u;
|
|
2340
|
+
/** 成因串里锁路径的两种写法(立即失败 `lock=` / 等待超时 `storage_dir=`)。 */
|
|
2341
|
+
const LOCK_IN_MESSAGE = /\b(?:lock|storage_dir)=(?<lock>\S+)/u;
|
|
2342
|
+
/**
|
|
2343
|
+
* 抽错误码。没有该行就不是 zg 的结构化失败(旁路返回 undefined,交给通用失败文案)。
|
|
2344
|
+
* 只认第一条码行:一次失败只应有一个码,首处之后的行不属于这次判读。
|
|
2345
|
+
*/
|
|
2346
|
+
function zgErrorCode(stderr) {
|
|
2347
|
+
const line = stderr.split("\n").find((candidate) => CODE_LINE_PREFIX.test(candidate));
|
|
2348
|
+
const from = line === void 0 ? -1 : line.indexOf("[") + 1;
|
|
2349
|
+
const to = line === void 0 ? -1 : line.indexOf(MESSAGE_DELIMITER, from);
|
|
2350
|
+
return line !== void 0 && from > 0 && to > from ? line.slice(from, to) : void 0;
|
|
2054
2351
|
}
|
|
2055
2352
|
/**
|
|
2056
|
-
*
|
|
2057
|
-
*
|
|
2058
|
-
*
|
|
2059
|
-
* 导出只为把「没有 Code 行时不捡明细」这一支钉进单测;生产侧只经
|
|
2060
|
-
* `classifyConcurrentFailure` 调用(那里已先确认有码)。
|
|
2353
|
+
* 抽首条码行的成因串(`]:` 之后的文本)。0.3.0 没有独立明细块,占锁方信息全在这一段里。
|
|
2354
|
+
* 没有码行、或码行上没有分隔符时交回**空串**——调用方(classifyConcurrentFailure)只在
|
|
2355
|
+
* 码已命中的前提下读它,空串即「成因缺失」;要区分「没有码行」用 {@link zgErrorCode}。
|
|
2061
2356
|
*/
|
|
2062
|
-
|
|
2063
|
-
const
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
lock: "lock",
|
|
2067
|
-
pid: "pid"
|
|
2068
|
-
};
|
|
2069
|
-
function zgErrorDetails(stderr) {
|
|
2070
|
-
const details = /* @__PURE__ */ new Map();
|
|
2071
|
-
const lines = stderr.split("\n");
|
|
2072
|
-
const codeIndex = lines.findIndex((line) => CODE_LINE_PREFIX.test(line));
|
|
2073
|
-
if (codeIndex === -1) return details;
|
|
2074
|
-
const start = detailsStartAfter(lines, codeIndex);
|
|
2075
|
-
if (start === -1) return details;
|
|
2076
|
-
for (const line of lines.slice(start + 1)) {
|
|
2077
|
-
const matched = DETAIL_LINE.exec(line);
|
|
2078
|
-
const key = matched?.groups?.["key"];
|
|
2079
|
-
const value = matched?.groups?.["value"]?.trimEnd();
|
|
2080
|
-
if (key !== void 0 && value !== void 0) {
|
|
2081
|
-
if (!details.has(key)) details.set(key, value);
|
|
2082
|
-
} else if (line.trim().length > 0) break;
|
|
2083
|
-
}
|
|
2084
|
-
return details;
|
|
2357
|
+
function zgErrorMessage(stderr) {
|
|
2358
|
+
const line = stderr.split("\n").find((candidate) => CODE_LINE_PREFIX.test(candidate)) ?? "";
|
|
2359
|
+
const at = line.indexOf(MESSAGE_DELIMITER);
|
|
2360
|
+
return at === -1 ? "" : line.slice(at + 2).trim();
|
|
2085
2361
|
}
|
|
2086
2362
|
/**
|
|
2087
|
-
*
|
|
2363
|
+
* 识别本插件策略关心的失败;不关心的失败(或输出形状不认识)一律返回 null。
|
|
2088
2364
|
*
|
|
2089
2365
|
* `rebuild` 只在占锁方自报重建时为真:等待策略据此决定要不要排队。把「别人占锁」也
|
|
2090
|
-
* 当成重建去等,会在永远不会被本插件放开的锁上无界挂起。
|
|
2366
|
+
* 当成重建去等,会在永远不会被本插件放开的锁上无界挂起。0.3.0 的成因串里没有占锁方
|
|
2367
|
+
* 进程号(0.2.2 Details 块的 ownerPid),故该字段不再存在。
|
|
2091
2368
|
*/
|
|
2092
2369
|
function classifyConcurrentFailure(stderr) {
|
|
2093
2370
|
const code = zgErrorCode(stderr);
|
|
2094
|
-
if (code ===
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
}
|
|
2104
|
-
if (code === "
|
|
2105
|
-
kind: "daemon-lease",
|
|
2106
|
-
pid: details.get(DETAIL_KEY.pid)
|
|
2107
|
-
};
|
|
2371
|
+
if (code === "ZG.ENGINE.RESOURCE_BUSY") {
|
|
2372
|
+
const message = zgErrorMessage(stderr);
|
|
2373
|
+
const ownerOperation = OPERATION_IN_MESSAGE.exec(message)?.groups?.["op"];
|
|
2374
|
+
return {
|
|
2375
|
+
kind: "lock-busy",
|
|
2376
|
+
ownerOperation,
|
|
2377
|
+
lockPath: LOCK_IN_MESSAGE.exec(message)?.groups?.["lock"],
|
|
2378
|
+
rebuild: ownerOperation === REBUILD_OPERATION
|
|
2379
|
+
};
|
|
2380
|
+
}
|
|
2381
|
+
if (code === "ZG.ENGINE.PERMISSION_DENIED") return { kind: "permission-denied" };
|
|
2108
2382
|
return null;
|
|
2109
2383
|
}
|
|
2110
2384
|
// lib/zg-version.ts
|
|
2111
2385
|
/**
|
|
2112
|
-
*
|
|
2113
|
-
*
|
|
2386
|
+
* 版本下限本体:比较用的对象是唯一事实来源,回显用的字符串由它派生——两处在编译期
|
|
2387
|
+
* 就不可能漂移,改下限只改这一个字面量。
|
|
2114
2388
|
*/
|
|
2115
2389
|
const MINIMUM = {
|
|
2116
2390
|
major: 0,
|
|
2117
|
-
minor:
|
|
2118
|
-
patch:
|
|
2391
|
+
minor: 3,
|
|
2392
|
+
patch: 0
|
|
2119
2393
|
};
|
|
2120
|
-
/**
|
|
2394
|
+
/** 版本号的字面形态(回显用:版本过低的提示要让用户看得见自己装的是哪个版本)。 */
|
|
2121
2395
|
function formatZgVersion(version) {
|
|
2122
2396
|
return `${version.major}.${version.minor}.${version.patch}`;
|
|
2123
2397
|
}
|
|
@@ -2161,7 +2435,7 @@ function versionAtLeast(actual, minimum) {
|
|
|
2161
2435
|
return actual.patch >= minimum.patch;
|
|
2162
2436
|
}
|
|
2163
2437
|
/**
|
|
2164
|
-
*
|
|
2438
|
+
* 下限判定:够新(或读不懂)返回 undefined;确知太老则交回实际版本,供文案回显。
|
|
2165
2439
|
* 「读不懂」与「太老」必须分开:前者放行、后者拒绝,混在一起就成了用一个猜出来的
|
|
2166
2440
|
* 版本去拦真实用户。
|
|
2167
2441
|
*/
|
|
@@ -2171,7 +2445,7 @@ function tooOldZgVersion(stdout) {
|
|
|
2171
2445
|
}
|
|
2172
2446
|
// lib/index-preflight.ts
|
|
2173
2447
|
/**
|
|
2174
|
-
* 预检判「文件不合适」时接受的家庭错误码:其余(fd
|
|
2448
|
+
* 预检判「文件不合适」时接受的家庭错误码:其余(fd 耗尽、符号链接成环、IO 错误等环境故障)
|
|
2175
2449
|
* 与用户给的路径无关,原样上抛——把 EMFILE 说成「请给一个真实存在的文件」会把排查
|
|
2176
2450
|
* 引向错误的方向。
|
|
2177
2451
|
*/
|
|
@@ -2183,7 +2457,7 @@ const UNUSABLE_FILE_CODES = /* @__PURE__ */ new Set([
|
|
|
2183
2457
|
"ENAMETOOLONG"
|
|
2184
2458
|
]);
|
|
2185
2459
|
/** node:fs 的失败一律是带 string code 的 Error 实例;形状不合(非对象、无 code、码非串)
|
|
2186
|
-
* 一律按环境故障处理。导出只为把非 Error
|
|
2460
|
+
* 一律按环境故障处理。导出只为把非 Error 形状的判别规则固定进单测(真 fs 抛不出这些)。 */
|
|
2187
2461
|
function isUnusableFileCode(error) {
|
|
2188
2462
|
if (typeof error !== "object" || error === null || !("code" in error)) return false;
|
|
2189
2463
|
const code = error.code;
|
|
@@ -2200,21 +2474,21 @@ function isUnusableFileCode(error) {
|
|
|
2200
2474
|
* 分支会让 CI 的 windows 那格在 100% 覆盖率门禁下无从而钉(本仓不用 coverage-ignore 逃生口)。
|
|
2201
2475
|
* 合成一句「不是存在且可读的文件」文案,三种成因都准确覆盖,且 catch 由「不存在」这一档跨平台钉住。
|
|
2202
2476
|
*
|
|
2203
|
-
* drop
|
|
2477
|
+
* drop 那一条分支整段跳过:drop 的命令不含 ignoreFiles,且构造器对「drop 携带索引侧参数」会
|
|
2204
2478
|
* 点名拒绝(见 lib/cli.ts 的 buildIndexCommand)——预检既没有可查的对象,也没有机会跑到;
|
|
2205
2479
|
* 若照跑,反而会拿"给一个真实存在的忽略文件"这句误导文案把一次合法的删索引拦下。
|
|
2206
|
-
* 判 drop 用与构造器**同一个** `boolOf
|
|
2480
|
+
* 判 drop 用与构造器**同一个** `boolOf`,两处规则不会漂。
|
|
2207
2481
|
* @param args 索引入参(`ignoreFiles` 单值或数组;`drop` 为真时整段跳过)
|
|
2208
2482
|
* @param root 已归一的工作区根(相对路径按它解析)
|
|
2209
2483
|
* @param messages 文案表
|
|
2210
2484
|
* @returns {void}
|
|
2211
|
-
* @throws Error
|
|
2485
|
+
* @throws Error 指向第一个不可用的条目(不会静默丢掉用户给的那一项);node:fs 的环境类
|
|
2212
2486
|
* 故障(非文件形状问题)原样上抛
|
|
2213
2487
|
*/
|
|
2214
2488
|
function assertIgnoreFilesExist(args, root, messages) {
|
|
2215
2489
|
if (boolOf(args.drop, "drop", messages)) return;
|
|
2216
2490
|
for (const entry of singleOrList(args.ignoreFiles, "ignoreFiles", messages)) {
|
|
2217
|
-
const target =
|
|
2491
|
+
const target = nodePath.isAbsolute(entry) ? entry : nodePath.resolve(root, entry);
|
|
2218
2492
|
let usable = false;
|
|
2219
2493
|
try {
|
|
2220
2494
|
accessSync(target, constants.R_OK);
|
|
@@ -2308,7 +2582,7 @@ function trimmedConfigString(value) {
|
|
|
2308
2582
|
/**
|
|
2309
2583
|
* 远程 embedding 是否被本部署显式开放。默认 false ⇒ 命令构造期就拒掉一切非本地引用。
|
|
2310
2584
|
* 取值直接用字段本身:schema 声明的是 boolean,cordis 装载期已按它校验过行 config,
|
|
2311
|
-
* 再写一遍 `=== true`
|
|
2585
|
+
* 再写一遍 `=== true` 只会多一条永远成立判断(lint 会当场判它 unnecessary)。
|
|
2312
2586
|
*/
|
|
2313
2587
|
function allowRemoteEmbedding(config) {
|
|
2314
2588
|
return config.allowRemoteEmbedding;
|
|
@@ -2320,14 +2594,16 @@ function allowRemoteEmbedding(config) {
|
|
|
2320
2594
|
*/
|
|
2321
2595
|
const ENV_NAME_SHAPE = /^[A-Za-z_]\w*$/u;
|
|
2322
2596
|
/**
|
|
2323
|
-
* zg 子进程的环境变量:HF 镜像 + (仅在部署开放远程 embedding
|
|
2597
|
+
* zg 子进程的环境变量:HF 镜像 + (仅在部署开放远程 embedding 时的)远程端点与凭据,
|
|
2598
|
+
* 外加调用方要求追加的变量(transport=mcp 自启 daemon 时是 ZVEC_GREP_SERVER_TOKEN——
|
|
2599
|
+
* 该名含 TOKEN 会被官方 subprocess 层从继承环境剔掉,必须显式注入才到得了 zg 与它的
|
|
2600
|
+
* 子进程;同一名也作为 MCP 调用的 Bearer,见 host.ts 的 daemon 句柄)。
|
|
2324
2601
|
*
|
|
2325
2602
|
* **密钥只走环境变量,绝不进 argv**。两道原因,都是实测/读源码得来的:
|
|
2326
2603
|
* - 本包把整条命令当官方作业的 `JobSpec.label` 回显给卡片,argv 里的密钥会进界面、
|
|
2327
2604
|
* 进日志、进 `ps` 的进程列表;
|
|
2328
|
-
* - 上游自己就优先读环境变量(
|
|
2329
|
-
* `
|
|
2330
|
-
* 走 env 既是它的正路,也省掉一条 argv 泄露面。
|
|
2605
|
+
* - 上游自己就优先读环境变量(0.3.0 authorization.rs 的 remote_endpoint 读
|
|
2606
|
+
* `ZVEC_GREP_ENDPOINT`,凭据同理),走 env 既是它的正路,也省掉一处 argv 泄露。
|
|
2331
2607
|
*
|
|
2332
2608
|
* **凭据为什么是「宿主进程里某个环境变量的名字」而不是值本身**:官方 subprocess 层会把
|
|
2333
2609
|
* 名字命中 `/KEY|PASSWORD|SECRET|TOKEN/i` 的变量从子进程环境里**剔掉**
|
|
@@ -2336,8 +2612,11 @@ const ENV_NAME_SHAPE = /^[A-Za-z_]\w*$/u;
|
|
|
2336
2612
|
* 于是配置里只记**名字**、值现读现转:密钥不必落进插件配置文件,也不进 argv、不进日志。
|
|
2337
2613
|
* 两项都只在 allowRemoteEmbedding 打开时才读:默认部署下这段代码根本不执行。
|
|
2338
2614
|
*/
|
|
2339
|
-
function zgEnv(config) {
|
|
2340
|
-
const env = {
|
|
2615
|
+
function zgEnv(config, extra) {
|
|
2616
|
+
const env = {
|
|
2617
|
+
...hfEndpointEnv(config),
|
|
2618
|
+
...extra
|
|
2619
|
+
};
|
|
2341
2620
|
if (allowRemoteEmbedding(config)) {
|
|
2342
2621
|
const endpoint = normalizedEndpoint(config.remoteEmbeddingEndpoint);
|
|
2343
2622
|
if (endpoint !== void 0) env["ZVEC_GREP_ENDPOINT"] = endpoint;
|
|
@@ -2350,9 +2629,33 @@ function zgEnv(config) {
|
|
|
2350
2629
|
}
|
|
2351
2630
|
function readDefaultEmbedding(config) {
|
|
2352
2631
|
const raw = config.defaultEmbedding.get();
|
|
2353
|
-
if (typeof raw === "string" &&
|
|
2632
|
+
if (typeof raw === "string" && isKnownEmbedding(raw)) return raw.trim();
|
|
2354
2633
|
return DEFAULT_EMBEDDING;
|
|
2355
2634
|
}
|
|
2635
|
+
function isTransportMode(value) {
|
|
2636
|
+
return value === "auto" || value === "cli" || value === "mcp";
|
|
2637
|
+
}
|
|
2638
|
+
function readTransport(value) {
|
|
2639
|
+
return typeof value === "string" && isTransportMode(value) ? value : "auto";
|
|
2640
|
+
}
|
|
2641
|
+
/**
|
|
2642
|
+
* 校验部署里的 `daemonUrl`:MCP 传输只认 `http(s)://host[:port]/mcp`。畸形值若放到
|
|
2643
|
+
* 调用期才炸,表现是「每次检索都失败一次」,这里在装载期就点名配置项与允许形状。
|
|
2644
|
+
* @param value 行 config 里的 daemonUrl(schema 只保证是字符串)
|
|
2645
|
+
* @param messages 文案表
|
|
2646
|
+
* @returns 原值(已 trim)
|
|
2647
|
+
*/
|
|
2648
|
+
function readDaemonUrl(value, messages) {
|
|
2649
|
+
const trimmed = value.trim();
|
|
2650
|
+
let parsed;
|
|
2651
|
+
try {
|
|
2652
|
+
parsed = new URL(trimmed);
|
|
2653
|
+
} catch {
|
|
2654
|
+
parsed = void 0;
|
|
2655
|
+
}
|
|
2656
|
+
if (parsed === void 0 || parsed.protocol !== "http:" && parsed.protocol !== "https:" || parsed.hostname.length === 0 || parsed.pathname !== "/mcp") throw new Error(fill(messages.daemonUrlInvalid, { received: value }));
|
|
2657
|
+
return trimmed;
|
|
2658
|
+
}
|
|
2356
2659
|
/**
|
|
2357
2660
|
* zg 传输模式:域内取值由 schema 保证,这里只处理「字段缺省」与宿主退化时交回的非域值。
|
|
2358
2661
|
* 读一次即传给检索、索引、状态与后台重建四条命令路径——混用模式会在守护进程持有索引
|
|
@@ -2396,12 +2699,12 @@ function sameJob(state, view) {
|
|
|
2396
2699
|
return sameIdentity(state.identity, identityOf(view));
|
|
2397
2700
|
}
|
|
2398
2701
|
/**
|
|
2399
|
-
*
|
|
2702
|
+
* 本包作业输出的内容:官方 pull source,stdout/stderr 各一只游标,外加一层"读失败不许
|
|
2400
2703
|
* 拖垮泵"的兜。选 pull 而不是生产者 push(`JobHandle.append`)是复核后按实测定下的:
|
|
2401
|
-
* - `proc.observed[*].readFrom`
|
|
2704
|
+
* - `proc.observed[*].readFrom` 是**非消费**的独立观察者接口(installed dsh-shell
|
|
2402
2705
|
* types.d.ts:"without stealing bytes from `readOutput`"),与本包前台用的
|
|
2403
2706
|
* 消费式游标互不干扰;
|
|
2404
|
-
* - 泵按注册表自己的节拍跑(实测默认 150ms,落定前再排最后一次)⇒
|
|
2707
|
+
* - 泵按注册表自己的节拍跑(实测默认 150ms,落定前再排最后一次)⇒ **卡片关着、环形缓冲也照常前进**,
|
|
2405
2708
|
* 模型侧 job_output 随时看得见进度;push 形态把可见性绑在了轮询上。
|
|
2406
2709
|
* @param proc 后台进程句柄
|
|
2407
2710
|
* @param state 这条重建的状态盒(见 {@link RebuildState})
|
|
@@ -2460,7 +2763,7 @@ function isLiveStatus(status) {
|
|
|
2460
2763
|
}
|
|
2461
2764
|
/**
|
|
2462
2765
|
* 收掉子进程,**忽略抛错**:进程可能已自然退出或已被系统回收,此时 kill 失败不是本包的失败。
|
|
2463
|
-
*
|
|
2766
|
+
* 调用点都在清理那一条分支(卸载、被拒、超时)上,那里没有可行动的下一步;把异常抛出去只会让清理链
|
|
2464
2767
|
* 半途而废,留下更难的现场。
|
|
2465
2768
|
*/
|
|
2466
2769
|
function killProc(proc) {
|
|
@@ -2473,7 +2776,7 @@ function killProc(proc) {
|
|
|
2473
2776
|
*
|
|
2474
2777
|
* 剪到**只剩 `MAX-1` 条**才是对的:这一剪发生在 start 之前,紧接着就有一条新作业进来,
|
|
2475
2778
|
* 它落定之后名册里正好是最近 `MAX` 条已落定记录 ⇒ 与卡片文案「只保留最近 10 条已结束的重建」
|
|
2476
|
-
*
|
|
2779
|
+
* 同一种做法。判据的时点是**新作业落定之后**,不是剪完那一刻——只看后者会把这条判反。
|
|
2477
2780
|
* 在跑的一条不动——官方件对超额的答法是拒绝 start(实测),不是替我们杀任务。
|
|
2478
2781
|
* 侧表里没有的 id(上一次 apply 卸载后残留的记录)同样要能清掉,所以遍历的是
|
|
2479
2782
|
* `list()` 而不是 `records`。
|
|
@@ -2503,18 +2806,18 @@ function capacityLimitOf(error) {
|
|
|
2503
2806
|
* 「工作区重建」的四道前置校验:绝对路径 + 归一化、本 daemon 观测过的白名单、
|
|
2504
2807
|
* 目录此刻仍存在。不过就交回可直接显示的文案(错误文本全走双语字典)。
|
|
2505
2808
|
*
|
|
2506
|
-
*
|
|
2507
|
-
* `zg index --rebuild
|
|
2809
|
+
* 白名单管的是**动作**:没有它,任何拿得到这条读取接口的一方都能用任意绝对路径去
|
|
2810
|
+
* `zg --index --rebuild`——读遍该工作区的目录树、写 `.zvec-grep/`,还可能把其中的非隐藏敏感文件
|
|
2508
2811
|
* 灌进向量库并回显到上下文。
|
|
2509
2812
|
* @param raw 请求里带来的 root(未经类型校验)
|
|
2510
2813
|
* @param ledger 观测到的工作区白名单
|
|
2511
2814
|
* @param started 本次请求语言的文案表
|
|
2512
2815
|
* @returns 归一化后可用的绝对路径;不合格时 `{ error }`
|
|
2513
2816
|
*/
|
|
2514
|
-
function acceptableRoot(raw, ledger, started) {
|
|
2817
|
+
function acceptableRoot(raw, ledger, started, platform) {
|
|
2515
2818
|
let root;
|
|
2516
2819
|
try {
|
|
2517
|
-
root = assertAbsoluteRoot(raw, started);
|
|
2820
|
+
root = assertAbsoluteRoot(raw, started, platform);
|
|
2518
2821
|
} catch (error) {
|
|
2519
2822
|
return { error: {
|
|
2520
2823
|
value: fill(started.endpointRootInvalid, { reason: errorText(error) }),
|
|
@@ -2564,15 +2867,15 @@ function startupFailureText(error, started) {
|
|
|
2564
2867
|
return capacity === void 0 ? fill(started.endpointStartFailed, { reason: errorText(error) }) : fill(started.endpointJobsAtCapacity, { limit: capacity });
|
|
2565
2868
|
}
|
|
2566
2869
|
/**
|
|
2567
|
-
*
|
|
2870
|
+
* 起一条受 controller 记录的未拥有作业。
|
|
2568
2871
|
*
|
|
2569
2872
|
* 官方件在"没有 controller 服务这个 owner"时直接拒绝 `start`(实测),而未拥有
|
|
2570
2873
|
* 作业只被 global 层服务;web 面上宿主自己的 `tool-jobs` 被移进了各 preset realm
|
|
2571
|
-
* (packages/bundle/web-app/cordis.patch.yml 把 tool-jobs
|
|
2874
|
+
* (packages/bundle/web-app/cordis.patch.yml 把 tool-jobs 在宿主那一层 disabled),
|
|
2572
2875
|
* 所以本包必须自带一枚从无作用域上下文 attach 的 controller。但**只在 start 这一瞬挂**:
|
|
2573
2876
|
* 实测挂上即放行、摘掉即恢复拒绝、可反复,而 global 层的 controller 只被 `servesOwner`
|
|
2574
2877
|
* 读,作业的后续(read/kill/落定)都不依赖它。留一枚常驻 token 等于在"宿主故意没装 job
|
|
2575
|
-
* 工具"
|
|
2878
|
+
* 工具"的组成里替全宿主一直保持放行——官方契约写的是"生产者不能起一台 owner 收不掉、
|
|
2576
2879
|
* 停不掉的作业",常驻就是把它反过来做。
|
|
2577
2880
|
*/
|
|
2578
2881
|
function startUnderController(jobs, spec) {
|
|
@@ -2641,14 +2944,14 @@ function rebuildJobSpec(options) {
|
|
|
2641
2944
|
};
|
|
2642
2945
|
}
|
|
2643
2946
|
/**
|
|
2644
|
-
* 起一条 `zg index`:命令构造 + resolve + execute 三步。
|
|
2947
|
+
* 起一条 `zg --index`:命令构造 + resolve + execute 三步。
|
|
2645
2948
|
*
|
|
2646
2949
|
* 远程重建与模型侧后台索引**共用**这一个函数(不是复制品),所以两条入口起的作业
|
|
2647
2950
|
* 在名册、状态投影、轮询读面上完全同形。命令形态由 `indexArgs` 决定,故它也服务普通建索引。
|
|
2648
2951
|
*
|
|
2649
|
-
*
|
|
2650
|
-
* 而不是起一条命令形态对不上的 zg
|
|
2651
|
-
* 发生在任何进程存在之前,调用方那条 `release`
|
|
2952
|
+
* 版本下限排在命令构造**之前**:确知装的是太老的 zg 时,在这一行就给出可照做的指引,
|
|
2953
|
+
* 而不是起一条命令形态对不上的 zg 再让人对着结果猜。注意这个顺序也保证了「版本门槛没过」
|
|
2954
|
+
* 发生在任何进程存在之前,调用方那条 `release` 那条返回路径足以收干净。
|
|
2652
2955
|
*
|
|
2653
2956
|
* 任一步抛错即就地翻成 `{ error, status }`;**本函数不释放占位**,那由调用方做(它才持有 root)。
|
|
2654
2957
|
* @param routes 本次注册的共享依赖(现读 config / host / jobsOf)
|
|
@@ -2662,9 +2965,13 @@ async function spawnIndexWrite(routes, started, indexArgs, embedding) {
|
|
|
2662
2965
|
let spawned;
|
|
2663
2966
|
try {
|
|
2664
2967
|
await routes.versionGate.ensure(started);
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
const
|
|
2968
|
+
const { platform } = routes;
|
|
2969
|
+
assertIgnoreFilesExist(indexArgs, assertAbsoluteRoot(indexArgs.root, started, platform), started);
|
|
2970
|
+
const built = buildIndexCommand({
|
|
2971
|
+
...indexArgs,
|
|
2972
|
+
platform
|
|
2973
|
+
}, embedding, started, readClientMode(config, started), allowRemoteEmbedding(config));
|
|
2974
|
+
const env = zgEnv(config, routes.daemonEnv?.());
|
|
2668
2975
|
const spec = host.shell.resolve({
|
|
2669
2976
|
command: built.command,
|
|
2670
2977
|
workdir: built.workdir,
|
|
@@ -2689,7 +2996,7 @@ async function spawnIndexWrite(routes, started, indexArgs, embedding) {
|
|
|
2689
2996
|
*
|
|
2690
2997
|
* 两类失败(注册表缺席 / start 或登记抛错)都**先把那条进程杀掉**再交回错误:
|
|
2691
2998
|
* 此刻作业没进名册,没人能通过 job 工具收它,不杀就是一条孤儿 zg 占着这棵树的写锁。
|
|
2692
|
-
* (没有「同 id
|
|
2999
|
+
* (没有「同 id 撞车」那一条分支:jobId 由宿主签发,见 records.set 前的注释。)
|
|
2693
3000
|
* start 之后 get 抛错时同样先杀——但那条作业可能已登记进官方注册表,本包侧表
|
|
2694
3001
|
* 看不见它,要等注册表自身的 prune 兜底。
|
|
2695
3002
|
* 同样地,本函数不释放占位——那件事由调用方做。
|
|
@@ -2757,7 +3064,7 @@ function attachIndexWrite(routes, root, started, spawned, claimed) {
|
|
|
2757
3064
|
return { jobId };
|
|
2758
3065
|
}
|
|
2759
3066
|
/**
|
|
2760
|
-
*
|
|
3067
|
+
* 卸载效应的统一处理:把侧表里的进程与在册作业收干净。
|
|
2761
3068
|
* @param deps 本次注册的共享依赖(jobsOf 现读、侧表引用、文案现取)
|
|
2762
3069
|
* @returns {void}
|
|
2763
3070
|
*/
|
|
@@ -2777,7 +3084,7 @@ function releaseRebuildRecords(deps) {
|
|
|
2777
3084
|
records.clear();
|
|
2778
3085
|
}
|
|
2779
3086
|
/**
|
|
2780
|
-
*
|
|
3087
|
+
* 设置卡片「工作区重建」的读取接口(引导 / 启动 / 轮询三个方法)。
|
|
2781
3088
|
*
|
|
2782
3089
|
* ⚠ 服务在**构造时**注册(cordis `Service` 的契约:`ctx.reflect.provide`,随所属 fiber
|
|
2783
3090
|
* 卸载自动撤),所以调用方拿实例没有任何用处——装入口 `installRebuildRemote` 说明了这一点。
|
|
@@ -2795,7 +3102,7 @@ var ZvecRebuildService = class extends TypertRemoteService {
|
|
|
2795
3102
|
super(ctx, REBUILD_REMOTE_NAMESPACE);
|
|
2796
3103
|
this.deps = deps;
|
|
2797
3104
|
}
|
|
2798
|
-
/**
|
|
3105
|
+
/** 引导读取接口:白名单里的工作区 + 守护进程就绪态(都是本插件自己的数据)。 */
|
|
2799
3106
|
async roots() {
|
|
2800
3107
|
let serverReady = false;
|
|
2801
3108
|
try {
|
|
@@ -2816,7 +3123,7 @@ var ZvecRebuildService = class extends TypertRemoteService {
|
|
|
2816
3123
|
*/
|
|
2817
3124
|
async rebuild(request) {
|
|
2818
3125
|
const started = this.deps.messages();
|
|
2819
|
-
const accepted = acceptableRoot(isRecord(request) ? request.root : void 0, this.deps.ledger, started);
|
|
3126
|
+
const accepted = acceptableRoot(isRecord(request) ? request.root : void 0, this.deps.ledger, started, this.deps.platform);
|
|
2820
3127
|
if ("error" in accepted) return {
|
|
2821
3128
|
ok: false,
|
|
2822
3129
|
error: accepted.error.value,
|
|
@@ -2872,7 +3179,7 @@ var ZvecRebuildService = class extends TypertRemoteService {
|
|
|
2872
3179
|
};
|
|
2873
3180
|
}
|
|
2874
3181
|
/**
|
|
2875
|
-
*
|
|
3182
|
+
* 轮询读取接口:官方状态投影 + 退出码/沙箱事实 + 打标后的输出尾窗(卡片每 2s 敲一次)。
|
|
2876
3183
|
*
|
|
2877
3184
|
* 侧表就是这条投影的授权边界:官方 id 是可预测的 `<kind>-<hex>`(宿主 bash 工具的
|
|
2878
3185
|
* `bash-1` 同样猜得到),而它不在本包表里 ⇒ 一律拒绝,绝不代读别人的作业。
|
|
@@ -2922,7 +3229,7 @@ var ZvecRebuildService = class extends TypertRemoteService {
|
|
|
2922
3229
|
};
|
|
2923
3230
|
/**
|
|
2924
3231
|
* 标准装饰器的**程序化调用**:`@Remote` 的全部作用就是往类原型写一枚描述符,而标准装饰器
|
|
2925
|
-
*
|
|
3232
|
+
* 语法需要走一条 tsc 降级流水线(本仓的测试/构建解析器都不降级它)。这里直接按 TC39 的
|
|
2926
3233
|
* `ClassMethodDecoratorContext` 形状调同一个 decorator 函数,把标记落到真正的原型上,
|
|
2927
3234
|
* 于是源码里不再需要装饰器语法,构建与测试都不必再挂那枚预转换插件。
|
|
2928
3235
|
*/
|
|
@@ -2950,7 +3257,7 @@ markRemote(ZvecRebuildService.prototype, "status");
|
|
|
2950
3257
|
* 随本插件一起收干净。
|
|
2951
3258
|
*
|
|
2952
3259
|
* @param ctx - 宿主上下文
|
|
2953
|
-
* @param deps -
|
|
3260
|
+
* @param deps - 重建读取接口的全部依赖(见 ZvecRebuildDeps)
|
|
2954
3261
|
*/
|
|
2955
3262
|
function installRebuildRemote(ctx, deps) {
|
|
2956
3263
|
if (!isRecord(ctx) || !isRecord(ctx.reflect) || typeof ctx.reflect.provide !== "function") return false;
|
|
@@ -2960,9 +3267,423 @@ function installRebuildRemote(ctx, deps) {
|
|
|
2960
3267
|
}, "zvec-grep: rebuild records");
|
|
2961
3268
|
return true;
|
|
2962
3269
|
}
|
|
3270
|
+
// lib/daemon-token.ts
|
|
3271
|
+
/** 文件名(放在 zg home 下,与 daemon 的 instance.lock / logs 同级)。 */
|
|
3272
|
+
const TOKEN_FILE_NAME = "dsh-zvec-grep.token";
|
|
3273
|
+
/** 上游要求 token ≥32 字符且无控制字符;这里用更保守的可见 ASCII 子集。 */
|
|
3274
|
+
const TOKEN_SHAPE = /^[\u0021-\u007E]{32,}$/u;
|
|
3275
|
+
/**
|
|
3276
|
+
* token 文件的默认路径:`ZVEC_GREP_HOME` 优先于 `~/.zvec-grep`(与上游 daemon 的 home
|
|
3277
|
+
* 规则同源),文件名固定。
|
|
3278
|
+
* @param env 环境变量表(测试可注入)
|
|
3279
|
+
* @returns 绝对路径
|
|
3280
|
+
*/
|
|
3281
|
+
function tokenFilePath(env = process.env) {
|
|
3282
|
+
const home = env["ZVEC_GREP_HOME"] ?? nodePath.join(homedir(), ".zvec-grep");
|
|
3283
|
+
return nodePath.join(home, TOKEN_FILE_NAME);
|
|
3284
|
+
}
|
|
3285
|
+
/** 读持久化 token;文件缺失/不可读/形状不合一律 undefined(不猜、不半信)。 */
|
|
3286
|
+
async function readPersistedToken(file) {
|
|
3287
|
+
let token;
|
|
3288
|
+
try {
|
|
3289
|
+
const trimmed = (await readFile(file, "utf8")).trim();
|
|
3290
|
+
token = TOKEN_SHAPE.test(trimmed) ? trimmed : void 0;
|
|
3291
|
+
} catch {}
|
|
3292
|
+
return token;
|
|
3293
|
+
}
|
|
3294
|
+
/**
|
|
3295
|
+
* 原子写入 token(同目录临时文件 → rename),权限 0600。失败**不外抛**:持久化只是恢复
|
|
3296
|
+
* 路径的增强,写不进去时本次会话仍用内存 token,恢复退化为 daemonStartFailed 的指引。
|
|
3297
|
+
* @param file 目标路径
|
|
3298
|
+
* @param token 待写入的 token
|
|
3299
|
+
* @returns 是否写入成功(测试用;生产调用可忽略)
|
|
3300
|
+
*/
|
|
3301
|
+
async function persistToken(file, token) {
|
|
3302
|
+
try {
|
|
3303
|
+
await mkdir(nodePath.dirname(file), { recursive: true });
|
|
3304
|
+
const temporary = `${file}.${String(process.pid)}.tmp`;
|
|
3305
|
+
await writeFile(temporary, token, { mode: 384 });
|
|
3306
|
+
await rename(temporary, file);
|
|
3307
|
+
return true;
|
|
3308
|
+
} catch {
|
|
3309
|
+
return false;
|
|
3310
|
+
}
|
|
3311
|
+
}
|
|
3312
|
+
/** `wx` 撞上已有文件时 Node 交回的错误码;只认这一种,其余按「写不进去」处理。 */
|
|
3313
|
+
function isAlreadyExists(error) {
|
|
3314
|
+
return typeof error === "object" && error !== null && error.code === "EEXIST";
|
|
3315
|
+
}
|
|
3316
|
+
/**
|
|
3317
|
+
* 读 token 并允许极短的可见性重试:并发的 `wx` 失败方看到文件已存在时,成功方可能
|
|
3318
|
+
* 刚 open 完还没写完内容,此刻读会得到空串。让出事件循环再读,最多三次;仍读不出
|
|
3319
|
+
* 才按「坏文件」处理(那时才允许删除重建)。
|
|
3320
|
+
*/
|
|
3321
|
+
async function readTokenRetrying(file, attempts) {
|
|
3322
|
+
const token = await readPersistedToken(file);
|
|
3323
|
+
if (token !== void 0 || attempts <= 1) return token;
|
|
3324
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
3325
|
+
setImmediate(() => {
|
|
3326
|
+
resolve(void 0);
|
|
3327
|
+
});
|
|
3328
|
+
await promise;
|
|
3329
|
+
return readTokenRetrying(file, attempts - 1);
|
|
3330
|
+
}
|
|
3331
|
+
/**
|
|
3332
|
+
* 认领持久化 token:第一位写者原子创建文件,后来者读回同一枚。
|
|
3333
|
+
*
|
|
3334
|
+
* 为什么不能沿用「先读、没有就写」:多个 dsh 宿主进程同时冷启动时,两边都会读到
|
|
3335
|
+
* 「没有」,各自生成一枚再以 `zg --server on` 拉起同一个 daemon。上游对重复启动退 0
|
|
3336
|
+
* 并交回同一个 PID,并不校验调用方 env 里的 token;于是后写者的 token 覆盖文件、
|
|
3337
|
+
* 却认证不了先启动的 daemon——两边都只看到「拉起退 0 但探测 401」。把创建改成 O_EXCL
|
|
3338
|
+
* 后,所有进程拿到同一枚 token,重复启动退 0 后的探测也能通过。
|
|
3339
|
+
*
|
|
3340
|
+
* 文件存在但形状不合(半截写入、旧垃圾):删掉后重试一次,仍抢不到就按「这次写不进去」
|
|
3341
|
+
* 处理——调用方用内存 token 继续,恢复退化为下一次重试。
|
|
3342
|
+
*
|
|
3343
|
+
* @param file 目标路径
|
|
3344
|
+
* @param candidate 本进程生成的候选 token(仅在抢到创建权时落盘)
|
|
3345
|
+
* @returns 最终 token 与创建权
|
|
3346
|
+
*/
|
|
3347
|
+
async function claimPersistedToken(file, candidate) {
|
|
3348
|
+
try {
|
|
3349
|
+
await mkdir(nodePath.dirname(file), { recursive: true });
|
|
3350
|
+
} catch {
|
|
3351
|
+
return {
|
|
3352
|
+
token: candidate,
|
|
3353
|
+
owned: false
|
|
3354
|
+
};
|
|
3355
|
+
}
|
|
3356
|
+
try {
|
|
3357
|
+
await writeFile(file, candidate, {
|
|
3358
|
+
mode: 384,
|
|
3359
|
+
flag: "wx"
|
|
3360
|
+
});
|
|
3361
|
+
return {
|
|
3362
|
+
token: candidate,
|
|
3363
|
+
owned: true
|
|
3364
|
+
};
|
|
3365
|
+
} catch (error) {
|
|
3366
|
+
if (!isAlreadyExists(error)) return {
|
|
3367
|
+
token: candidate,
|
|
3368
|
+
owned: false
|
|
3369
|
+
};
|
|
3370
|
+
}
|
|
3371
|
+
const existing = await readTokenRetrying(file, 3);
|
|
3372
|
+
if (existing !== void 0) return {
|
|
3373
|
+
token: existing,
|
|
3374
|
+
owned: false
|
|
3375
|
+
};
|
|
3376
|
+
try {
|
|
3377
|
+
await rm(file, { force: true });
|
|
3378
|
+
} catch {
|
|
3379
|
+
return {
|
|
3380
|
+
token: candidate,
|
|
3381
|
+
owned: false
|
|
3382
|
+
};
|
|
3383
|
+
}
|
|
3384
|
+
return {
|
|
3385
|
+
token: candidate,
|
|
3386
|
+
owned: await persistToken(file, candidate)
|
|
3387
|
+
};
|
|
3388
|
+
}
|
|
3389
|
+
/** 成功后清理 token 文件(停 daemon 失败时保留,供下一次恢复)。 */
|
|
3390
|
+
async function clearPersistedToken(file) {
|
|
3391
|
+
try {
|
|
3392
|
+
await rm(file, { force: true });
|
|
3393
|
+
} catch {}
|
|
3394
|
+
}
|
|
3395
|
+
// lib/daemon-client.ts
|
|
3396
|
+
/** MCP 协议版本(对 0.3.0 daemon 实测接受的版本串)。 */
|
|
3397
|
+
const PROTOCOL_VERSION = "2025-06-18";
|
|
3398
|
+
/** 会话在哪些 HTTP 状态下视为失效:404(未知会话)、405/400(方法/请求形状被拒)。 */
|
|
3399
|
+
const SESSION_LOST_STATUS = /* @__PURE__ */ new Set([
|
|
3400
|
+
400,
|
|
3401
|
+
404,
|
|
3402
|
+
405
|
|
3403
|
+
]);
|
|
3404
|
+
/** 握手与工具调用的 JSON-RPC 常量。 */
|
|
3405
|
+
const JSONRPC = "2.0";
|
|
3406
|
+
function isRecord$1(value) {
|
|
3407
|
+
return typeof value === "object" && value !== null;
|
|
3408
|
+
}
|
|
3409
|
+
/** 从 SSE 正文收集全部 `data:` 行的 JSON 载荷;解析不了的行(心跳/注释)跳过。 */
|
|
3410
|
+
function ssePayloads(body) {
|
|
3411
|
+
const payloads = [];
|
|
3412
|
+
for (const line of body.split("\n")) {
|
|
3413
|
+
const trimmed = line.trim();
|
|
3414
|
+
const json = trimmed.startsWith("data:") ? trimmed.slice(5).trim() : "";
|
|
3415
|
+
if (json.length > 0) try {
|
|
3416
|
+
payloads.push(JSON.parse(json));
|
|
3417
|
+
} catch {}
|
|
3418
|
+
}
|
|
3419
|
+
return payloads;
|
|
3420
|
+
}
|
|
3421
|
+
/** 应答体的载荷收集:SSE 拆行,普通 JSON 整体一枚(解析失败按无载荷处理)。 */
|
|
3422
|
+
function responsePayloads(contentType, body) {
|
|
3423
|
+
if (contentType.includes("text/event-stream")) return ssePayloads(body);
|
|
3424
|
+
try {
|
|
3425
|
+
return [JSON.parse(body)];
|
|
3426
|
+
} catch {
|
|
3427
|
+
return [];
|
|
3428
|
+
}
|
|
3429
|
+
}
|
|
3430
|
+
/** tools/call 的 JSON-RPC 应答块:错误对象或结果对象二者之一。 */
|
|
3431
|
+
function replyOf(payloads, requestId) {
|
|
3432
|
+
const found = payloads.find((payload) => isRecord$1(payload) && payload["id"] === requestId);
|
|
3433
|
+
return isRecord$1(found) ? found : void 0;
|
|
3434
|
+
}
|
|
3435
|
+
/** 把 MCP result 的 content 拼成文本(只收 text 块)。 */
|
|
3436
|
+
function resultText(result) {
|
|
3437
|
+
return (isRecord$1(result) && Array.isArray(result["content"]) ? result["content"] : []).map((block) => isRecord$1(block) && block["type"] === "text" ? block["text"] : void 0).filter((piece) => typeof piece === "string").join("\n");
|
|
3438
|
+
}
|
|
3439
|
+
/**
|
|
3440
|
+
* 协议层失败:daemon **已经应答**(JSON-RPC error / 应答形状不符)。这类失败是确定性的,
|
|
3441
|
+
* 重握手再发一次只会得到同一个答案——call() 的「重握手重试一次」只针对传输/会话抖动。
|
|
3442
|
+
*/
|
|
3443
|
+
var DaemonProtocolError = class extends Error {
|
|
3444
|
+
constructor(message) {
|
|
3445
|
+
super(message);
|
|
3446
|
+
this.name = "DaemonProtocolError";
|
|
3447
|
+
}
|
|
3448
|
+
};
|
|
3449
|
+
/**
|
|
3450
|
+
* 空闲会话池上限:超出部分从池里移除(daemon 侧由自己的 30 分钟空闲回收兜底)。
|
|
3451
|
+
* 上限只约束**空闲**会话,不限制并发数——多个 agent 同时检索时各拿自己那条。
|
|
3452
|
+
*/
|
|
3453
|
+
const MAX_IDLE_SESSIONS = 8;
|
|
3454
|
+
function authHeaders(state) {
|
|
3455
|
+
const token = state.tokenOf();
|
|
3456
|
+
return token === void 0 ? {} : { Authorization: `Bearer ${token}` };
|
|
3457
|
+
}
|
|
3458
|
+
function buildHeaders(state, sessionId) {
|
|
3459
|
+
const headers = {
|
|
3460
|
+
"Content-Type": "application/json",
|
|
3461
|
+
Accept: "application/json, text/event-stream",
|
|
3462
|
+
...authHeaders(state)
|
|
3463
|
+
};
|
|
3464
|
+
if (sessionId !== void 0) headers["mcp-session-id"] = sessionId;
|
|
3465
|
+
return headers;
|
|
3466
|
+
}
|
|
3467
|
+
/**
|
|
3468
|
+
* 取消/预算耗尽的失败形状与真实 fetch 的取消一致:调用方(host.ts 的
|
|
3469
|
+
* daemonTransportFailure)按 AbortError 区分「超时/取消」与传输层错误。
|
|
3470
|
+
*/
|
|
3471
|
+
function abortedError(message) {
|
|
3472
|
+
const error = new Error(message);
|
|
3473
|
+
error.name = "AbortError";
|
|
3474
|
+
return error;
|
|
3475
|
+
}
|
|
3476
|
+
async function post(state, body, deadline, signal, sessionId) {
|
|
3477
|
+
if (signal?.aborted === true) throw abortedError("The operation was aborted");
|
|
3478
|
+
const remaining = deadline - Date.now();
|
|
3479
|
+
if (remaining <= 0) throw abortedError("daemon call budget exhausted");
|
|
3480
|
+
const controller = new AbortController();
|
|
3481
|
+
const timer = setTimeout(() => {
|
|
3482
|
+
controller.abort();
|
|
3483
|
+
}, remaining);
|
|
3484
|
+
const onExternalAbort = () => {
|
|
3485
|
+
controller.abort();
|
|
3486
|
+
};
|
|
3487
|
+
signal?.addEventListener("abort", onExternalAbort);
|
|
3488
|
+
try {
|
|
3489
|
+
const response = await state.doFetch(state.url, {
|
|
3490
|
+
method: "POST",
|
|
3491
|
+
headers: buildHeaders(state, sessionId),
|
|
3492
|
+
body: JSON.stringify(body),
|
|
3493
|
+
signal: controller.signal
|
|
3494
|
+
});
|
|
3495
|
+
const text = await response.text();
|
|
3496
|
+
const nextSession = response.headers.get("mcp-session-id") ?? void 0;
|
|
3497
|
+
return {
|
|
3498
|
+
status: response.status,
|
|
3499
|
+
sessionId: nextSession,
|
|
3500
|
+
payloads: responsePayloads(response.headers.get("content-type") ?? "", text)
|
|
3501
|
+
};
|
|
3502
|
+
} finally {
|
|
3503
|
+
clearTimeout(timer);
|
|
3504
|
+
signal?.removeEventListener("abort", onExternalAbort);
|
|
3505
|
+
}
|
|
3506
|
+
}
|
|
3507
|
+
/** initialize 握手:给这一条会话记下 id,再补 notifications/initialized。 */
|
|
3508
|
+
async function ensureSession(state, session, deadline, signal) {
|
|
3509
|
+
if (session.id !== void 0) return;
|
|
3510
|
+
const handshake = await post(state, {
|
|
3511
|
+
jsonrpc: JSONRPC,
|
|
3512
|
+
id: 0,
|
|
3513
|
+
method: "initialize",
|
|
3514
|
+
params: {
|
|
3515
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
3516
|
+
capabilities: {},
|
|
3517
|
+
clientInfo: {
|
|
3518
|
+
name: state.clientName,
|
|
3519
|
+
version: "0.0.0"
|
|
3520
|
+
}
|
|
3521
|
+
}
|
|
3522
|
+
}, deadline, signal, void 0);
|
|
3523
|
+
if (handshake.status !== 200) throw new Error(`initialize failed with HTTP ${handshake.status}`);
|
|
3524
|
+
session.id = handshake.sessionId;
|
|
3525
|
+
if (session.id === void 0) throw new Error("daemon did not issue an mcp-session-id");
|
|
3526
|
+
await post(state, {
|
|
3527
|
+
jsonrpc: JSONRPC,
|
|
3528
|
+
method: "notifications/initialized"
|
|
3529
|
+
}, deadline, signal, session.id);
|
|
3530
|
+
}
|
|
3531
|
+
/** 取一条空闲会话;都忙就新开一条。并发调用因此各用一条会话,互不排队。 */
|
|
3532
|
+
function acquireSession(state) {
|
|
3533
|
+
const idle = state.sessions.find((session) => !session.busy);
|
|
3534
|
+
if (idle !== void 0) {
|
|
3535
|
+
idle.busy = true;
|
|
3536
|
+
return idle;
|
|
3537
|
+
}
|
|
3538
|
+
const created = {
|
|
3539
|
+
id: void 0,
|
|
3540
|
+
busy: true
|
|
3541
|
+
};
|
|
3542
|
+
state.sessions.push(created);
|
|
3543
|
+
return created;
|
|
3544
|
+
}
|
|
3545
|
+
/**
|
|
3546
|
+
* 归还会话。`keep=false` 时从池里移除:会话被拒、请求被取消、或伺服方约定已乱,
|
|
3547
|
+
* 复用它只会把上一次的失败带进下一次调用。移除不发送 DELETE——daemon 自己的
|
|
3548
|
+
* 30 分钟空闲回收会关掉它;池只保留少量空闲会话,不长期占着。
|
|
3549
|
+
*/
|
|
3550
|
+
function releaseSession(state, session, keep) {
|
|
3551
|
+
if (!keep) {
|
|
3552
|
+
state.sessions = state.sessions.filter((entry) => entry !== session);
|
|
3553
|
+
return;
|
|
3554
|
+
}
|
|
3555
|
+
session.busy = false;
|
|
3556
|
+
const idle = state.sessions.filter((entry) => !entry.busy);
|
|
3557
|
+
if (idle.length > MAX_IDLE_SESSIONS) {
|
|
3558
|
+
const excess = new Set(idle.slice(0, idle.length - MAX_IDLE_SESSIONS));
|
|
3559
|
+
state.sessions = state.sessions.filter((entry) => !excess.has(entry));
|
|
3560
|
+
}
|
|
3561
|
+
}
|
|
3562
|
+
/** 工具调用的一次尝试(不含重试语义)。 */
|
|
3563
|
+
async function callOnce(state, session, callOptions, requestId, deadline) {
|
|
3564
|
+
await ensureSession(state, session, deadline, callOptions.signal);
|
|
3565
|
+
const { status, payloads } = await post(state, {
|
|
3566
|
+
jsonrpc: JSONRPC,
|
|
3567
|
+
id: requestId,
|
|
3568
|
+
method: "tools/call",
|
|
3569
|
+
params: {
|
|
3570
|
+
name: callOptions.tool,
|
|
3571
|
+
arguments: callOptions.args
|
|
3572
|
+
}
|
|
3573
|
+
}, deadline, callOptions.signal, session.id);
|
|
3574
|
+
if (SESSION_LOST_STATUS.has(status)) throw new Error(`daemon rejected the session (HTTP ${status})`);
|
|
3575
|
+
if (status !== 200) throw new DaemonProtocolError(`tools/call failed with HTTP ${status}`);
|
|
3576
|
+
const reply = replyOf(payloads, requestId);
|
|
3577
|
+
if (reply === void 0) throw new DaemonProtocolError("tools/call reply missing from response");
|
|
3578
|
+
if (isRecord$1(reply["error"])) throw new DaemonProtocolError(JSON.stringify(reply["error"]));
|
|
3579
|
+
const { result } = reply;
|
|
3580
|
+
return {
|
|
3581
|
+
text: resultText(result),
|
|
3582
|
+
isError: isRecord$1(result) && result["isError"] === true
|
|
3583
|
+
};
|
|
3584
|
+
}
|
|
3585
|
+
function createDaemonClient(options) {
|
|
3586
|
+
const state = {
|
|
3587
|
+
url: options.url,
|
|
3588
|
+
doFetch: options.fetchImpl ?? globalThis.fetch.bind(globalThis),
|
|
3589
|
+
clientName: options.clientName ?? "dsh-zvec-grep",
|
|
3590
|
+
tokenOf: options.tokenOf,
|
|
3591
|
+
sessions: []
|
|
3592
|
+
};
|
|
3593
|
+
return { call: async (callOptions) => {
|
|
3594
|
+
const deadline = Date.now() + callOptions.timeoutMs;
|
|
3595
|
+
const first = acquireSession(state);
|
|
3596
|
+
try {
|
|
3597
|
+
const result = await callOnce(state, first, callOptions, 1, deadline);
|
|
3598
|
+
releaseSession(state, first, true);
|
|
3599
|
+
return result;
|
|
3600
|
+
} catch (error) {
|
|
3601
|
+
if (isRecord$1(error) && error["name"] === "AbortError") {
|
|
3602
|
+
releaseSession(state, first, false);
|
|
3603
|
+
throw error;
|
|
3604
|
+
}
|
|
3605
|
+
if (error instanceof DaemonProtocolError) {
|
|
3606
|
+
releaseSession(state, first, true);
|
|
3607
|
+
throw error;
|
|
3608
|
+
}
|
|
3609
|
+
releaseSession(state, first, false);
|
|
3610
|
+
const retry = acquireSession(state);
|
|
3611
|
+
try {
|
|
3612
|
+
const result = await callOnce(state, retry, callOptions, 3, deadline);
|
|
3613
|
+
releaseSession(state, retry, true);
|
|
3614
|
+
return result;
|
|
3615
|
+
} catch (retryError) {
|
|
3616
|
+
releaseSession(state, retry, retryError instanceof DaemonProtocolError);
|
|
3617
|
+
throw retryError;
|
|
3618
|
+
}
|
|
3619
|
+
}
|
|
3620
|
+
} };
|
|
3621
|
+
}
|
|
3622
|
+
// lib/daemon-args.ts
|
|
3623
|
+
/** MCP 面接受的 preview 档位(0.3.0 inputSchema 枚举现量)。 */
|
|
3624
|
+
const DAEMON_PREVIEW = {
|
|
3625
|
+
short: "short",
|
|
3626
|
+
full: "full"
|
|
3627
|
+
};
|
|
3628
|
+
/** preview 就近降级:none 只留锚点 → short 最接近;detail 要结构化全文 → full 是上限档。 */
|
|
3629
|
+
function daemonPreviewOf(value, messages) {
|
|
3630
|
+
const preview = previewOf(value, messages);
|
|
3631
|
+
if (preview === "none" || preview === "short") return DAEMON_PREVIEW.short;
|
|
3632
|
+
return DAEMON_PREVIEW.full;
|
|
3633
|
+
}
|
|
3634
|
+
/** 查询路由主体(query/queries/fts/vector/fuse)。 */
|
|
3635
|
+
function pushQueryRoutes(mapped, args, messages) {
|
|
3636
|
+
const query = optionalText(args.query, "query", messages, MAX_QUERY_CHARS);
|
|
3637
|
+
if (query.length > 0) mapped["query"] = query;
|
|
3638
|
+
const queries = stringList(args.queries, "queries", messages, 32, MAX_QUERY_CHARS);
|
|
3639
|
+
if (queries.length > 0) mapped["queries"] = queries;
|
|
3640
|
+
const fts = stringList(args.fts, "fts", messages, 32, MAX_QUERY_CHARS);
|
|
3641
|
+
if (fts.length > 0) mapped["fts"] = fts;
|
|
3642
|
+
const vector = stringList(args.vector, "vector", messages, 32, MAX_QUERY_CHARS);
|
|
3643
|
+
if (vector.length > 0) mapped["vector"] = vector;
|
|
3644
|
+
if (boolOf(args.fuse, "fuse", messages)) mapped["fuse"] = true;
|
|
3645
|
+
}
|
|
3646
|
+
/** 路径/格式/分类/符号/时间过滤族的映射(与 CLI 通道同一批取值器)。 */
|
|
3647
|
+
function pushFilters(mapped, args, messages) {
|
|
3648
|
+
const globs = singleOrList(args.globs, "globs", messages);
|
|
3649
|
+
if (globs.length > 0) mapped["globs"] = globs;
|
|
3650
|
+
const insensitive = singleOrList(args.insensitiveGlobs, "insensitiveGlobs", messages);
|
|
3651
|
+
if (insensitive.length > 0) mapped["insensitiveGlobs"] = insensitive;
|
|
3652
|
+
const fileTypes = singleOrList(args.fileTypes, "fileTypes", messages);
|
|
3653
|
+
if (fileTypes.length > 0) mapped["fileTypes"] = fileTypes;
|
|
3654
|
+
const excludedFileTypes = singleOrList(args.excludedFileTypes, "excludedFileTypes", messages);
|
|
3655
|
+
if (excludedFileTypes.length > 0) mapped["excludedFileTypes"] = excludedFileTypes;
|
|
3656
|
+
const categories = singleOrList(args.category, "category", messages);
|
|
3657
|
+
if (categories.length > 0) mapped["categories"] = categories;
|
|
3658
|
+
const excludedCategories = singleOrList(args.categoryNot, "categoryNot", messages);
|
|
3659
|
+
if (excludedCategories.length > 0) mapped["excludedCategories"] = excludedCategories;
|
|
3660
|
+
const symbolTypes = symbolTypesOf(args.symbolTypes, messages);
|
|
3661
|
+
if (symbolTypes.length > 0) mapped["symbolTypes"] = symbolTypes;
|
|
3662
|
+
if (boolOf(args.preferSymbol, "preferSymbol", messages)) mapped["preferSymbol"] = true;
|
|
3663
|
+
if (boolOf(args.trace, "trace", messages)) mapped["trace"] = true;
|
|
3664
|
+
const modifiedAfter = optionalText(args.modifiedAfter, "modifiedAfter", messages, 128);
|
|
3665
|
+
if (modifiedAfter.length > 0) mapped["modifiedAfter"] = modifiedAfter;
|
|
3666
|
+
const modifiedBefore = optionalText(args.modifiedBefore, "modifiedBefore", messages, 128);
|
|
3667
|
+
if (modifiedBefore.length > 0) mapped["modifiedBefore"] = modifiedBefore;
|
|
3668
|
+
}
|
|
3669
|
+
function daemonSearchArgs(args, messages) {
|
|
3670
|
+
if (optionalText(args.device, "device", messages, 1024).length > 0) throw new Error(messages.deviceUnsupportedOnDaemon);
|
|
3671
|
+
const mapped = {
|
|
3672
|
+
root: args.root,
|
|
3673
|
+
limit: resolveLimit(args.limit, messages),
|
|
3674
|
+
preview: daemonPreviewOf(args.preview, messages)
|
|
3675
|
+
};
|
|
3676
|
+
pushQueryRoutes(mapped, args, messages);
|
|
3677
|
+
const refresh = refreshOf(args.refresh, messages);
|
|
3678
|
+
if (refresh === "wait") mapped["freshness"] = "wait_for_fresh";
|
|
3679
|
+
else {
|
|
3680
|
+
mapped["freshness"] = "eventual";
|
|
3681
|
+
mapped["autoUpdate"] = refresh === "background";
|
|
3682
|
+
}
|
|
3683
|
+
pushFilters(mapped, args, messages);
|
|
3684
|
+
return mapped;
|
|
3685
|
+
}
|
|
2963
3686
|
// host.ts
|
|
2964
|
-
/** 纯数字计数行。 */
|
|
2965
|
-
const DIGITS_ONLY = /^\d+$/u;
|
|
2966
3687
|
const SEARCH_TIMEOUT_MS = 3e5;
|
|
2967
3688
|
const STATUS_TIMEOUT_MS = 6e4;
|
|
2968
3689
|
const INDEX_TIMEOUT_MS = 6e5;
|
|
@@ -2986,7 +3707,7 @@ function hasMethod(value, name, keys) {
|
|
|
2986
3707
|
return isRecord(member) && keys.every((key) => typeof member[key] === "function");
|
|
2987
3708
|
}
|
|
2988
3709
|
/**
|
|
2989
|
-
* host
|
|
3710
|
+
* host 是否为本插件所需宿主服务:五个注入都必须是**带相应方法的对象**,
|
|
2990
3711
|
* 且 `get` 可调用。守卫失败即 apply 抛错(fail-fast),比运行到某次工具调用
|
|
2991
3712
|
* 才 `undefined is not a function` 更早、更可诊断。
|
|
2992
3713
|
*
|
|
@@ -2999,7 +3720,7 @@ function isZvecGrepHost(value) {
|
|
|
2999
3720
|
if (!isRecord(value)) return false;
|
|
3000
3721
|
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";
|
|
3001
3722
|
}
|
|
3002
|
-
/** 当前会话工作区(root
|
|
3723
|
+
/** 当前会话工作区(root 缺省回退源);非字符串视为缺(读取方式见 lib/routing.ts 的 SessionFace)。 */
|
|
3003
3724
|
function sessionHeaderCwd(exec) {
|
|
3004
3725
|
const raw = exec.agent?.session?.header?.cwd;
|
|
3005
3726
|
return typeof raw === "string" && raw.length > 0 ? raw : void 0;
|
|
@@ -3008,7 +3729,7 @@ function sessionHeaderCwd(exec) {
|
|
|
3008
3729
|
* JSON.stringify 在本包**拥有的声明**上把返回宽成 `string | undefined`:lib 的签名恒为
|
|
3009
3730
|
* `string`,但 ECMA-262 规定入参是 undefined / 函数 / 符号时它返回 undefined(下面
|
|
3010
3731
|
* textBlock 的用例就直喂 undefined)。宽化只能落在这里——调用点里 `JSON.stringify(...) ?? x`
|
|
3011
|
-
* 会被 TS
|
|
3732
|
+
* 会被 TS 的收窄按声明判成冗余守卫,而删掉那道具象兜底会把 `{ text: undefined }` 交给官方。
|
|
3012
3733
|
*/
|
|
3013
3734
|
function stringifyJson(value) {
|
|
3014
3735
|
return JSON.stringify(value, null, 2);
|
|
@@ -3067,16 +3788,16 @@ function withDetail(detail, prefix) {
|
|
|
3067
3788
|
return detail.length > 0 ? fill(prefix, { detail }) : "";
|
|
3068
3789
|
}
|
|
3069
3790
|
/**
|
|
3070
|
-
* zg 的结构化失败在 stderr 上以一行 `
|
|
3791
|
+
* zg 的结构化失败在 stderr 上以一行 `Error[<CODE>]: …` 交出错误码(0.3.0 上游
|
|
3792
|
+
* zg-cli/src/diagnostics.rs 的 format_error_report;MCP 传输的同一文本为小写 `error[`),
|
|
3071
3793
|
* 本包所有按码归因的判据都读那一行。**缺了这一行**就意味着这次失败没有可机读的码,而上游
|
|
3072
|
-
*
|
|
3073
|
-
*
|
|
3074
|
-
* 这里据此补一条可行动的出路,而不是让模型对着「exit=1 + 一句话」猜。
|
|
3794
|
+
* 恰好有两类塌法会长这样:普通非引擎错误(`Error: <message>` 单行,无码)与不带 `--debug`
|
|
3795
|
+
* 时被折叠的部分失败。这里据此补一条可行动的出路,而不是让模型对着「exit=1 + 一句话」猜。
|
|
3075
3796
|
*
|
|
3076
3797
|
* 空 detail 不补:什么都没打出来时谈不上「上游把原因塌成了一句」,那条指引只会占住回显预算。
|
|
3077
|
-
*
|
|
3798
|
+
* 已有码行时也不补:那时归因本就够了。
|
|
3078
3799
|
*/
|
|
3079
|
-
const STRUCTURED_ERROR_CODE = /^\s*
|
|
3800
|
+
const STRUCTURED_ERROR_CODE = /^\s*error\[/imu;
|
|
3080
3801
|
function noCodeHint(detail, messages) {
|
|
3081
3802
|
return detail.length === 0 || STRUCTURED_ERROR_CODE.test(detail) ? "" : `\n${messages.noErrorCodeHint}`;
|
|
3082
3803
|
}
|
|
@@ -3102,26 +3823,39 @@ function shellFailure(result, messages) {
|
|
|
3102
3823
|
/**
|
|
3103
3824
|
* 成功执行的 stderr 里哪些是「进度噪声」、哪些必须交回。
|
|
3104
3825
|
*
|
|
3105
|
-
* zg 在**成功**时也往 stderr 写索引进度(非 TTY
|
|
3106
|
-
* `
|
|
3107
|
-
*
|
|
3108
|
-
*
|
|
3826
|
+
* zg 在**成功**时也往 stderr 写索引进度(非 TTY 下逐行写到磁盘,0.3.0 实测原文:
|
|
3827
|
+
* `Scanning — scanning files` / `Indexing: 0/5 files` / `Preparing model: …`)。这些行每次
|
|
3828
|
+
* 建索引都在,写进工具回执只是让模型对着同一堆噪声反复读;真正需要它看见的是另一类:
|
|
3829
|
+
* 降级提示、锁冲突、沙箱事实,以及任何本包**不认识**的新增告警。
|
|
3109
3830
|
*
|
|
3110
3831
|
* 所以判据是「只丢认得的进度行,其余全留」,而不是「只留认得的告警」——后者一旦 zg 出了
|
|
3111
3832
|
* 新提示就会静默吞掉,那正是最不该发生的失败模式。
|
|
3112
3833
|
*
|
|
3113
|
-
*
|
|
3114
|
-
*
|
|
3115
|
-
*
|
|
3116
|
-
*
|
|
3117
|
-
* files
|
|
3118
|
-
|
|
3119
|
-
|
|
3834
|
+
* 0.3.0 的进度行尾部带变量(计数/文件名/模型名/进度),整行相等匹配不再成立,改用
|
|
3835
|
+
* **前缀**匹配。词表逐条对着上游 progress.rs 的 format_progress 核过(非 TTY 全部九种
|
|
3836
|
+
* stage):
|
|
3837
|
+
* Preparing model: … / Downloading model: … / Model ready: … / Scanning[ …] /
|
|
3838
|
+
* Indexing: N/M files[ …] / Files processed: N/M files / Optimizing index / Saving index /
|
|
3839
|
+
* Finishing index
|
|
3840
|
+
* 刻意**不收** `Model warning:`:它虽属进度阶段,但语义是告警(不受节流的那一档),
|
|
3841
|
+
* 交给下面的 stderr 注回显,把降级事实留给人看。`Indexing:` 带冒号、且 `Indexing completed`
|
|
3842
|
+
* 一类失败措辞不是这个前缀,两不相撞。
|
|
3843
|
+
*/
|
|
3844
|
+
const STDERR_PROGRESS_PREFIXES = [
|
|
3845
|
+
"Preparing model:",
|
|
3846
|
+
"Downloading model:",
|
|
3847
|
+
"Model ready:",
|
|
3848
|
+
"Scanning",
|
|
3849
|
+
"Indexing:",
|
|
3850
|
+
"Files processed:",
|
|
3851
|
+
"Optimizing index",
|
|
3852
|
+
"Saving index",
|
|
3853
|
+
"Finishing index"
|
|
3854
|
+
];
|
|
3120
3855
|
/** 该行是否只是进度噪声。`warning` / `Error` / `zvec-grep` 一律不判为噪声。 */
|
|
3121
3856
|
function isStderrProgressLine(line) {
|
|
3122
3857
|
const trimmed = line.trim();
|
|
3123
|
-
|
|
3124
|
-
return trimmed.startsWith("Indexing files") || trimmed.startsWith("Preparing ") || trimmed.startsWith("Downloading ") || trimmed.startsWith("Model ready: ");
|
|
3858
|
+
return STDERR_PROGRESS_PREFIXES.some((prefix) => trimmed.startsWith(prefix));
|
|
3125
3859
|
}
|
|
3126
3860
|
/** 剥掉进度行,留下真正要交回的 stderr(可能为空串)。 */
|
|
3127
3861
|
function signalStderr(text) {
|
|
@@ -3163,7 +3897,7 @@ function successNotes(result, messages, stdoutMaxBytes) {
|
|
|
3163
3897
|
const ZG_VERSION_TTL_MS = 6e5;
|
|
3164
3898
|
/** 探测自身的超时:`zg --version` 是纯打印,给它检索超时是浪费,也让它卡住主流程。 */
|
|
3165
3899
|
const ZG_VERSION_PROBE_TIMEOUT_MS = 1e4;
|
|
3166
|
-
/**
|
|
3900
|
+
/** 版本过低的文案:回显实际版本与下限值,并给出唯一的出路(升级 zvec-grep)。 */
|
|
3167
3901
|
function tooOldZgError(actual, messages) {
|
|
3168
3902
|
return new Error(fill(messages.zgVersionTooOld, {
|
|
3169
3903
|
actual: formatZgVersion(actual),
|
|
@@ -3175,10 +3909,11 @@ function tooOldZgError(actual, messages) {
|
|
|
3175
3909
|
* 读不懂的形状,或 spawn/执行器层面的任何失败)。**失败绝不外抛**:这道门槛的职责
|
|
3176
3910
|
* 只有一个——把「确知太老」拦下来,拿「没读懂」去拦用户是在制造新故障。
|
|
3177
3911
|
*/
|
|
3178
|
-
async function probeZgVersion(host, config) {
|
|
3912
|
+
async function probeZgVersion(host, config, tokenOf) {
|
|
3179
3913
|
let stdout;
|
|
3180
3914
|
try {
|
|
3181
|
-
const
|
|
3915
|
+
const token = tokenOf();
|
|
3916
|
+
const env = zgEnv(config, token === void 0 ? void 0 : { ZVEC_GREP_SERVER_TOKEN: token });
|
|
3182
3917
|
const spec = host.shell.resolve({
|
|
3183
3918
|
command: "zg --version",
|
|
3184
3919
|
workdir: tmpdir(),
|
|
@@ -3199,7 +3934,7 @@ async function probeZgVersion(host, config) {
|
|
|
3199
3934
|
* workdir 取系统临时目录而不是会话 cwd:这是一次与工作区无关的纯打印探测,
|
|
3200
3935
|
* 不该因为某个会话的工作区不存在而失败,也不该顺手触发 root 授权那一套。
|
|
3201
3936
|
*/
|
|
3202
|
-
function createZgVersionGate(host, config) {
|
|
3937
|
+
function createZgVersionGate(host, config, tokenOf) {
|
|
3203
3938
|
let cachedAt = 0;
|
|
3204
3939
|
let cachedTooOld;
|
|
3205
3940
|
return { async ensure(messages) {
|
|
@@ -3208,22 +3943,25 @@ function createZgVersionGate(host, config) {
|
|
|
3208
3943
|
if (cachedTooOld !== void 0) throw tooOldZgError(cachedTooOld, messages);
|
|
3209
3944
|
return;
|
|
3210
3945
|
}
|
|
3211
|
-
const probe = await probeZgVersion(host, config);
|
|
3946
|
+
const probe = await probeZgVersion(host, config, tokenOf);
|
|
3212
3947
|
cachedAt = now;
|
|
3213
3948
|
cachedTooOld = probe;
|
|
3214
3949
|
if (probe !== void 0) throw tooOldZgError(probe, messages);
|
|
3215
3950
|
} };
|
|
3216
3951
|
}
|
|
3217
|
-
/** 就绪态缓存时长:daemon 可被随时 `zg server on/off` 起停,比版本探测勤得多。 */
|
|
3952
|
+
/** 就绪态缓存时长:daemon 可被随时 `zg --server on/off` 起停,比版本探测勤得多。 */
|
|
3218
3953
|
const SERVER_READY_TTL_MS = 6e4;
|
|
3219
|
-
/** 探测自身超时:`zg server status` 是纯读,不该借检索超时。 */
|
|
3954
|
+
/** 探测自身超时:`zg --server status` 是纯读,不该借检索超时。 */
|
|
3220
3955
|
const SERVER_READY_PROBE_TIMEOUT_MS = 1e4;
|
|
3221
|
-
/**
|
|
3222
|
-
const SERVER_READY_COMMAND = "zg server status --check-ready";
|
|
3223
|
-
/** 探一次守护进程就绪态:退出码 0 = 就绪。任何异常与非零退出都算未就绪。
|
|
3224
|
-
|
|
3956
|
+
/** 就绪探测命令行(0.3.0 旗标形态):`--check-ready` 把「就绪与否」表达成退出码。 */
|
|
3957
|
+
const SERVER_READY_COMMAND = "zg --server status --check-ready";
|
|
3958
|
+
/** 探一次守护进程就绪态:退出码 0 = 就绪。任何异常与非零退出都算未就绪。
|
|
3959
|
+
* 注:插件自启的 daemon 带自生成 token,探测命令必须带上同一枚,否则 401 会被
|
|
3960
|
+
* 误读成「未就绪」并触发重复拉起。 */
|
|
3961
|
+
async function probeServerReady(host, config, tokenOf) {
|
|
3225
3962
|
try {
|
|
3226
|
-
const
|
|
3963
|
+
const token = tokenOf();
|
|
3964
|
+
const env = zgEnv(config, token === void 0 ? void 0 : { ZVEC_GREP_SERVER_TOKEN: token });
|
|
3227
3965
|
const spec = host.shell.resolve({
|
|
3228
3966
|
command: SERVER_READY_COMMAND,
|
|
3229
3967
|
workdir: tmpdir(),
|
|
@@ -3240,73 +3978,179 @@ async function probeServerReady(host, config) {
|
|
|
3240
3978
|
* 建这道门槛。缓存挂闭包(随 apply 生死),TTL 到期后重探。
|
|
3241
3979
|
*
|
|
3242
3980
|
* **并发不合并**:两条检索同时撞上 TTL 边界会各探一次,多起一发纯读进程而已——
|
|
3243
|
-
* 换来的是没有「在途 Promise
|
|
3981
|
+
* 换来的是没有「在途 Promise 该不该共享」这层状态可测(与版本下限同一种做法)。
|
|
3244
3982
|
*/
|
|
3245
|
-
function createZgServerGate(host, config) {
|
|
3983
|
+
function createZgServerGate(host, config, tokenOf) {
|
|
3246
3984
|
let cachedAt = 0;
|
|
3247
3985
|
let cachedReady = false;
|
|
3248
3986
|
let probed = false;
|
|
3249
|
-
return {
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
|
|
3253
|
-
|
|
3254
|
-
|
|
3255
|
-
|
|
3256
|
-
|
|
3987
|
+
return {
|
|
3988
|
+
async ready() {
|
|
3989
|
+
const now = Date.now();
|
|
3990
|
+
if (probed && now - cachedAt < SERVER_READY_TTL_MS) return cachedReady;
|
|
3991
|
+
cachedReady = await probeServerReady(host, config, tokenOf);
|
|
3992
|
+
cachedAt = now;
|
|
3993
|
+
probed = true;
|
|
3994
|
+
return cachedReady;
|
|
3995
|
+
},
|
|
3996
|
+
invalidate() {
|
|
3997
|
+
probed = false;
|
|
3998
|
+
cachedReady = false;
|
|
3999
|
+
}
|
|
4000
|
+
};
|
|
3257
4001
|
}
|
|
4002
|
+
const DAEMON_START_TIMEOUT_MS = 15e3;
|
|
3258
4003
|
/**
|
|
3259
|
-
*
|
|
3260
|
-
*
|
|
3261
|
-
*
|
|
3262
|
-
* - 分组计数合计:各组 `hits:` 之和,反映 zg 实际跑了多少路。
|
|
3263
|
-
* - 去重后不同位置:按 `相对路径:行号范围` 这一稳定身份键去重——名次、匹配来源、
|
|
3264
|
-
* 分数都逐组变化,不能入键——反映模型真正看到几处不同代码。
|
|
3265
|
-
* 身份键取条目头行里 `matchedBy=` 之后的**整段原样**文本,不去拆行号范围:路径本身
|
|
3266
|
-
* 可以含空格与冒号(实测 `deep/a/b/c d/we:ird file.ts:1-2`),任何拆解都会引入误判,
|
|
3267
|
-
* 而原样文本已经恰好就是「相对路径 + 行号范围」。一条位置都数不出时整段去重口径省略,
|
|
3268
|
-
* 不数就不谎称。
|
|
3269
|
-
*
|
|
3270
|
-
* zg 的输出**不提供**任何截断信号,故命中数正好等于 --limit 只能作为观察陈述,不能
|
|
3271
|
-
* 断言发生了截断(`hitCapped` 因此不含断言措辞)。
|
|
4004
|
+
* 本插件生成的 daemon token 只应出现在子进程 env 与 MCP 的 Bearer 头里。上游失败文本若把
|
|
4005
|
+
* 它回显出来(启动拒绝、错误回执等),会随工具回执进会话日志;任何要交给模型的失败详情
|
|
4006
|
+
* 都先过这一道。token 是 48 位 hex,字符串替换不会误伤普通文本。
|
|
3272
4007
|
*/
|
|
3273
|
-
|
|
3274
|
-
|
|
4008
|
+
function redactToken(text, token) {
|
|
4009
|
+
return token === void 0 || token.length === 0 ? text : text.replaceAll(token, "[token]");
|
|
4010
|
+
}
|
|
3275
4011
|
/**
|
|
3276
|
-
*
|
|
3277
|
-
*
|
|
4012
|
+
* 从 `daemonUrl` 取自启 daemon 的 `--listen` 值(host:port)。调用前 `readDaemonUrl`
|
|
4013
|
+
* 已在装载期校验过形状,这里只做提取,不再保留不可达的回退分支。
|
|
4014
|
+
*/
|
|
4015
|
+
function listenOf(daemonUrl) {
|
|
4016
|
+
const url = new URL(daemonUrl);
|
|
4017
|
+
const defaultPort = url.protocol === "https:" ? "443" : "80";
|
|
4018
|
+
return `${url.hostname}:${url.port === "" ? defaultPort : url.port}`;
|
|
4019
|
+
}
|
|
4020
|
+
function createDaemonHandle(options) {
|
|
4021
|
+
const { host, config, daemonUrl, tokenFile, tokenOf, setToken, markStarted, serverGate } = options;
|
|
4022
|
+
/**
|
|
4023
|
+
* 同一进程内的冷启动合并:多个 agent 同时发检索时只允许一发 `zg --server on`。
|
|
4024
|
+
* 合并的是**同一次 apply** 的生命周期;跨进程靠 `claimPersistedToken` 的 O_EXCL
|
|
4025
|
+
* 认领共享同一枚 token,上游对重复启动退 0,随后各进程的就绪探测都能过。
|
|
4026
|
+
*/
|
|
4027
|
+
let starting;
|
|
4028
|
+
/** 本进程是否以 O_EXCL 创建了 token 文件:只有创建者会在卸载时停自己拉起的 daemon。 */
|
|
4029
|
+
let ownsTokenFile = false;
|
|
4030
|
+
/** 跑一次 `zg --server on`;成功返回 undefined,失败返回已脱敏的详情。 */
|
|
4031
|
+
const runStartCommand = async (token) => {
|
|
4032
|
+
const listen = listenOf(daemonUrl);
|
|
4033
|
+
const startCommand = listen === "127.0.0.1:7999" ? "zg --server on" : `zg --server on --listen ${listen}`;
|
|
4034
|
+
let failure;
|
|
4035
|
+
try {
|
|
4036
|
+
const env = zgEnv(config, { ZVEC_GREP_SERVER_TOKEN: token });
|
|
4037
|
+
const spec = host.shell.resolve({
|
|
4038
|
+
command: startCommand,
|
|
4039
|
+
workdir: tmpdir(),
|
|
4040
|
+
timeoutMs: DAEMON_START_TIMEOUT_MS,
|
|
4041
|
+
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
4042
|
+
env
|
|
4043
|
+
});
|
|
4044
|
+
const result = await (await host.shell.execute(spec)).result();
|
|
4045
|
+
if (result.exitCode !== 0) failure = redactToken(result.stderr.text.trim().length > 0 ? result.stderr.text.trim() : `exit ${result.exitCode}`, token);
|
|
4046
|
+
} catch (error) {
|
|
4047
|
+
failure = redactToken(errorText(error), token);
|
|
4048
|
+
}
|
|
4049
|
+
return failure;
|
|
4050
|
+
};
|
|
4051
|
+
const ensureOnce = async (messages) => {
|
|
4052
|
+
if (await serverGate.ready()) {
|
|
4053
|
+
if (tokenOf() === void 0) {
|
|
4054
|
+
const persisted = await readPersistedToken(tokenFile);
|
|
4055
|
+
if (persisted !== void 0) setToken(persisted);
|
|
4056
|
+
}
|
|
4057
|
+
return;
|
|
4058
|
+
}
|
|
4059
|
+
let token = tokenOf();
|
|
4060
|
+
if (token === void 0) {
|
|
4061
|
+
const { token: claimedToken, owned } = await claimPersistedToken(tokenFile, randomBytes(24).toString("hex"));
|
|
4062
|
+
token = claimedToken;
|
|
4063
|
+
ownsTokenFile = owned;
|
|
4064
|
+
setToken(token);
|
|
4065
|
+
}
|
|
4066
|
+
const failure = await runStartCommand(token);
|
|
4067
|
+
const effective = await readPersistedToken(tokenFile) ?? token;
|
|
4068
|
+
if (effective !== token) setToken(effective);
|
|
4069
|
+
serverGate.invalidate();
|
|
4070
|
+
if (await serverGate.ready()) {
|
|
4071
|
+
if (failure === void 0 && ownsTokenFile && effective === token) markStarted();
|
|
4072
|
+
return;
|
|
4073
|
+
}
|
|
4074
|
+
setToken(void 0);
|
|
4075
|
+
ownsTokenFile = false;
|
|
4076
|
+
throw new Error(fill(messages.daemonStartFailed, { detail: failure ?? "zg --server on exited 0 but the readiness probe still fails (another daemon may be using a different token)" }));
|
|
4077
|
+
};
|
|
4078
|
+
return {
|
|
4079
|
+
tokenOf,
|
|
4080
|
+
async ensure(messages) {
|
|
4081
|
+
if (starting !== void 0) return starting;
|
|
4082
|
+
const run = async () => {
|
|
4083
|
+
try {
|
|
4084
|
+
await ensureOnce(messages);
|
|
4085
|
+
} finally {
|
|
4086
|
+
starting = void 0;
|
|
4087
|
+
}
|
|
4088
|
+
};
|
|
4089
|
+
starting = run();
|
|
4090
|
+
return starting;
|
|
4091
|
+
}
|
|
4092
|
+
};
|
|
4093
|
+
}
|
|
4094
|
+
/**
|
|
4095
|
+
* 卸载时的 daemon 收尾:**只有本插件自启的 daemon** 会被停掉。
|
|
4096
|
+
*
|
|
4097
|
+
* 判据就是 token 在不在:用户自己起的 daemon(默认无鉴权)没有 token,插件既没有权限、
|
|
4098
|
+
* 也不该替用户停它;自启失败时 token 已被收回,同样不发命令。token 持久化在 zg home 下的
|
|
4099
|
+
* 0600 文件里,因此崩溃/重启后的新实例仍能停掉旧 daemon;停成功后文件一并清理。
|
|
4100
|
+
* disposer 按 fiber 注册逆序执行(cordis 契约),本函数在 installRebuildRemote 之前注册 ⇒
|
|
4101
|
+
* 卸载时先由重建那一条回收作业,再停 daemon。失败只吞掉:清理路径不能因为一次失败
|
|
4102
|
+
* 阻断其余回收,残留 daemon 由 daemonStartFailed 的恢复指引(按 PID 终止)转交用户。
|
|
4103
|
+
*/
|
|
4104
|
+
function registerDaemonShutdown(options) {
|
|
4105
|
+
const { host, config, tokenFile, daemonEnv, startedByUs } = options;
|
|
4106
|
+
host.effect(() => async () => {
|
|
4107
|
+
if (!startedByUs()) return;
|
|
4108
|
+
const extra = daemonEnv();
|
|
4109
|
+
if (extra === void 0) return;
|
|
4110
|
+
try {
|
|
4111
|
+
const spec = host.shell.resolve({
|
|
4112
|
+
command: "zg --server off",
|
|
4113
|
+
workdir: tmpdir(),
|
|
4114
|
+
timeoutMs: DAEMON_START_TIMEOUT_MS,
|
|
4115
|
+
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
4116
|
+
env: extra
|
|
4117
|
+
});
|
|
4118
|
+
if ((await (await host.shell.execute(spec)).result()).exitCode === 0) await clearPersistedToken(tokenFile);
|
|
4119
|
+
} catch {}
|
|
4120
|
+
}, "zvec-grep: daemon shutdown");
|
|
4121
|
+
}
|
|
4122
|
+
/**
|
|
4123
|
+
* zg 检索输出的命中摘要。0.3.0 的输出不再有每组的 `hits: N` 计数行(0.2.2 的「分组计数」
|
|
4124
|
+
* 维度整个消失),多组结果只以 `-- query N/M: <文本> --` 分隔行衔接;但「同一处代码会被
|
|
4125
|
+
* 多个查询组各命中一次」的事实未变(实测多组不融合时 `a.ts:1-1` 在第 1、2 组各出现一次),
|
|
4126
|
+
* 去重计数因此仍是摘要唯一说得准的维度。
|
|
3278
4127
|
*
|
|
3279
|
-
*
|
|
3280
|
-
*
|
|
3281
|
-
*
|
|
3282
|
-
*
|
|
3283
|
-
*
|
|
3284
|
-
*
|
|
3285
|
-
* (`score=1` 后面跟的是 `.` 不是空白,整段不匹配)。
|
|
3286
|
-
* - `[global_fill]` / `[group_coverage: x]`:排在名次与 `matchedBy=` 之间,漏了它整行
|
|
3287
|
-
* 就匹配不上,那条命中会被当成不存在。
|
|
4128
|
+
* 身份键取条目头行 `#<名次>` 之后的整段原样文本,不去拆行号范围:路径本身可以含空格与
|
|
4129
|
+
* 冒号(0.2.2 实测 `deep/a/b/c d/we:ird file.ts:1-2`,0.3.0 未变),任何拆解都会引入误判。
|
|
4130
|
+
* 尾部可选的 ` score=<分>` 装饰**不进键**(分值逐组变化,实测同一处位置在两个组里分值
|
|
4131
|
+
* 不同;`--preview detail` 的头行是 `#<名次> <标题> score=<分>`,剥掉分值后身份退化为
|
|
4132
|
+
* 标题——比 short/full 的「路径:行号范围」弱,但仍是可用的去重键,且 detail 档的
|
|
4133
|
+
* `Range:` 行不带路径,没有更强的选择)。
|
|
3288
4134
|
*
|
|
3289
|
-
*
|
|
3290
|
-
*
|
|
3291
|
-
|
|
3292
|
-
|
|
4135
|
+
* 摘要只在数得出至少一个位置时出现:一条位置都数不出(穷举/文件发现的输出没有 `#N` 行、
|
|
4136
|
+
* 或输出形状变了)就整段省略,不数就不谎称。行首空白容忍(`--preview detail` 的头行带
|
|
4137
|
+
* 两格缩进,实测);`freshness:` 头行(MCP 传输)、组分隔行、`preview` 的源码行(都带
|
|
4138
|
+
* `<行号>\t` 前缀)、markdown 标题行(`#` 后无数字)与 `score:` / `trace:` 独立行都撞不上
|
|
4139
|
+
* 这一形状。
|
|
4140
|
+
*/
|
|
4141
|
+
const HIT_LINE_PREFIX = /^\s*#\d+\s+(?<rest>\S.*)$/u;
|
|
4142
|
+
/** rest 尾部的 `score=<分>` 装饰(--preview detail 的头行带它;整数与四位小数两种形态)。 */
|
|
4143
|
+
const TRAILING_SCORE = /\s+score=-?\d+(?:\.\d+)?$/u;
|
|
3293
4144
|
function hitSummary(stdoutText, limit, truncated, messages) {
|
|
3294
|
-
const lines = stdoutText.split("\n");
|
|
3295
|
-
const perGroup = lines.filter((line) => line.startsWith(HITS_LINE_PREFIX)).map((line) => line.slice(6)).filter((digits) => DIGITS_ONLY.test(digits)).map((digits) => Math.trunc(Number(digits)));
|
|
3296
|
-
if (perGroup.length === 0) return null;
|
|
3297
4145
|
const locations = /* @__PURE__ */ new Set();
|
|
3298
|
-
for (const line of
|
|
3299
|
-
const
|
|
3300
|
-
if (
|
|
4146
|
+
for (const line of stdoutText.split("\n")) {
|
|
4147
|
+
const rest = HIT_LINE_PREFIX.exec(line)?.groups?.["rest"];
|
|
4148
|
+
if (rest !== void 0) locations.add(rest.replace(TRAILING_SCORE, ""));
|
|
3301
4149
|
}
|
|
3302
|
-
|
|
3303
|
-
const capped = perGroup.some((count) => count >= limit);
|
|
4150
|
+
if (locations.size === 0) return null;
|
|
3304
4151
|
return fill(messages.hitSummary, {
|
|
3305
|
-
|
|
3306
|
-
grouped,
|
|
3307
|
-
dedup: locations.size === 0 ? "" : fill(messages.hitDedup, { unique: locations.size }),
|
|
4152
|
+
unique: locations.size,
|
|
3308
4153
|
limit,
|
|
3309
|
-
capped: capped ? messages.hitCapped : "",
|
|
3310
4154
|
truncated: truncated ? messages.hitTruncated : ""
|
|
3311
4155
|
});
|
|
3312
4156
|
}
|
|
@@ -3332,17 +4176,20 @@ async function runForegroundOnce(host, command, workdir, timeoutMs, opts) {
|
|
|
3332
4176
|
...opts.env ? { env: opts.env } : {}
|
|
3333
4177
|
});
|
|
3334
4178
|
const result = await (await host.shell.execute(spec)).result();
|
|
3335
|
-
const
|
|
4179
|
+
const secret = opts.env?.["ZVEC_GREP_SERVER_TOKEN"];
|
|
4180
|
+
const rawFailure = shellFailure(result, opts.messages);
|
|
4181
|
+
const failure = rawFailure === null ? null : redactToken(rawFailure, secret);
|
|
3336
4182
|
if (failure !== null) {
|
|
3337
4183
|
const resolved = opts.resolveFailure?.(failure, result) ?? null;
|
|
3338
4184
|
if (resolved !== null) return resolved;
|
|
3339
4185
|
const concurrent = classifyConcurrentFailure(result.stderr.text);
|
|
3340
4186
|
if (concurrent?.kind === "lock-busy" && concurrent.rebuild) throw new RebuildLockBusyError(failure);
|
|
3341
4187
|
if (concurrent?.kind === "lock-busy") throw new Error(`${fill(opts.messages.lockBusyOtherOperation, { op: concurrent.ownerOperation ?? "unknown" })}\n${failure}`);
|
|
4188
|
+
if (concurrent?.kind === "permission-denied") throw new Error(`${failure}\n${opts.messages.remoteAuthDenied}`);
|
|
3342
4189
|
throw new Error(failure);
|
|
3343
4190
|
}
|
|
3344
|
-
const notes = successNotes(result, opts.messages, opts.stdoutMaxBytes);
|
|
3345
|
-
const
|
|
4191
|
+
const notes = successNotes(result, opts.messages, opts.stdoutMaxBytes).map((note) => redactToken(note, secret));
|
|
4192
|
+
const text = redactToken(result.stdout.text, secret);
|
|
3346
4193
|
const summary = opts.summaryLimit === void 0 ? null : hitSummary(text, opts.summaryLimit, result.stdout.truncated, opts.messages);
|
|
3347
4194
|
const extras = summary === null ? notes : [...notes, summary];
|
|
3348
4195
|
return extras.length > 0 ? `${text}\n${extras.join("\n")}` : text;
|
|
@@ -3359,6 +4206,22 @@ function messagesWaitExpired(root, maxWaitMs, messages) {
|
|
|
3359
4206
|
});
|
|
3360
4207
|
}
|
|
3361
4208
|
/**
|
|
4209
|
+
* 重建等待的重试包装:attempt 抛 RebuildLockBusyError 且同根确有本插件的重建时,
|
|
4210
|
+
* 等它落定后再试**一次**。CLI lane(runForeground)与 MCP lane(runSearchViaDaemon)
|
|
4211
|
+
* 共用这一条包装——两条传输的锁语义相同,等待策略不该各写一遍。
|
|
4212
|
+
*/
|
|
4213
|
+
async function attemptWithRebuildWait(wait, messages, signal, attempt) {
|
|
4214
|
+
try {
|
|
4215
|
+
return await attempt();
|
|
4216
|
+
} catch (error) {
|
|
4217
|
+
const entry = wait.rebuilds.covering(wait.root, messages);
|
|
4218
|
+
if (!(error instanceof RebuildLockBusyError) || entry === void 0) throw error;
|
|
4219
|
+
const outcome = await wait.rebuilds.wait(wait.root, messages, wait.maxWaitMs, signal);
|
|
4220
|
+
if (outcome === "settled") return attempt();
|
|
4221
|
+
throw new Error(outcome === "aborted" ? messagesAbortedWaiting(entry.root, messages) : messagesWaitExpired(entry.root, wait.maxWaitMs, messages), { cause: error });
|
|
4222
|
+
}
|
|
4223
|
+
}
|
|
4224
|
+
/**
|
|
3362
4225
|
* 前台执行 + **一次**重建等待重试。
|
|
3363
4226
|
*
|
|
3364
4227
|
* 重建持有该根的写锁时,检索会立刻以「索引不可用」失败(zg 的锁是纯 fail-fast,不等)。
|
|
@@ -3377,15 +4240,7 @@ async function runForeground(host, command, workdir, timeoutMs, opts) {
|
|
|
3377
4240
|
};
|
|
3378
4241
|
const wait = opts.rebuildWait;
|
|
3379
4242
|
if (wait === void 0) return runForegroundOnce(host, command, workdir, timeoutMs, base);
|
|
3380
|
-
|
|
3381
|
-
return await runForegroundOnce(host, command, workdir, timeoutMs, base);
|
|
3382
|
-
} catch (error) {
|
|
3383
|
-
const entry = wait.rebuilds.covering(wait.root, opts.messages);
|
|
3384
|
-
if (!(error instanceof RebuildLockBusyError) || entry === void 0) throw error;
|
|
3385
|
-
const outcome = await wait.rebuilds.wait(wait.root, opts.messages, wait.maxWaitMs, opts.signal);
|
|
3386
|
-
if (outcome === "settled") return runForegroundOnce(host, command, workdir, timeoutMs, base);
|
|
3387
|
-
throw new Error(outcome === "aborted" ? messagesAbortedWaiting(entry.root, opts.messages) : messagesWaitExpired(entry.root, wait.maxWaitMs, opts.messages), { cause: error });
|
|
3388
|
-
}
|
|
4243
|
+
return attemptWithRebuildWait(wait, opts.messages, opts.signal, () => runForegroundOnce(host, command, workdir, timeoutMs, base));
|
|
3389
4244
|
}
|
|
3390
4245
|
/**
|
|
3391
4246
|
* root 的存在性预检(item:不验存在)。zg 的 cwd 不存在时,spawn 直接以
|
|
@@ -3417,20 +4272,41 @@ function readUnlockWindowMin(config) {
|
|
|
3417
4272
|
function readEnforceSearchFirst(config) {
|
|
3418
4273
|
return config.enforceSearchFirst.get() ?? true;
|
|
3419
4274
|
}
|
|
4275
|
+
/** win32 路径末尾分隔符(比较键去掉它;盘符根 `C:\` 会在折叠后成为 `c:`,两侧一致即可)。 */
|
|
4276
|
+
const WIN32_TRAILING_SEPARATORS = /\\+$/u;
|
|
3420
4277
|
/**
|
|
3421
|
-
*
|
|
4278
|
+
* 归一路径的跨平台可比形式:
|
|
4279
|
+
* - win32:统一 `\`、剥扩展长度前缀、去尾分隔符并转小写(NTFS 大小写不敏感);
|
|
4280
|
+
* - darwin:剥掉 `/private` 解析前缀(`/tmp` ⇄ `/private/tmp`);
|
|
4281
|
+
* - 其余原样。
|
|
3422
4282
|
*
|
|
3423
|
-
*
|
|
3424
|
-
*
|
|
3425
|
-
*
|
|
4283
|
+
* 剥 `/private` **只在 darwin 上成立**:darwin 的 `/private` 是 `/tmp` 等目录的 realpath
|
|
4284
|
+
* 前缀,两种拼写指同一目录;Linux 上 `/private/xxx` 是一个与 `/xxx` 无关的真实目录,
|
|
4285
|
+
* 无差别剥除会把两棵不同的树判成同一棵(manifest 覆盖判据随之错配)。win32 的
|
|
4286
|
+
* 大小写折叠同理必须门控在 win32 上:POSIX 文件名大小写敏感。
|
|
3426
4287
|
*
|
|
3427
4288
|
* `platform` 供测试注入:分支覆盖不依赖测试机自己的操作系统。导出只为可测。
|
|
3428
4289
|
*/
|
|
3429
4290
|
function comparablePath(root, platform = process.platform) {
|
|
4291
|
+
if (platform === "win32") {
|
|
4292
|
+
let extended = root;
|
|
4293
|
+
if (root.startsWith("\\\\?\\UNC\\")) extended = `\\\\${root.slice(8)}`;
|
|
4294
|
+
else if (root.startsWith("\\\\?\\")) extended = root.slice(4);
|
|
4295
|
+
return extended.replaceAll("/", "\\").replace(WIN32_TRAILING_SEPARATORS, "").toLowerCase();
|
|
4296
|
+
}
|
|
3430
4297
|
return platform === "darwin" && root.startsWith("/private/") ? root.slice(8) : root;
|
|
3431
4298
|
}
|
|
3432
|
-
/**
|
|
3433
|
-
|
|
4299
|
+
/** 认的索引版本:与上游 0.3.0 的 `indexVersion` 同值(实测 manifest 现量)。 */
|
|
4300
|
+
/**
|
|
4301
|
+
* 本包认得的最低索引版本(0.3.0 的 manifest 实测现量 2)。
|
|
4302
|
+
*
|
|
4303
|
+
* 判据是**下限**不是等号:插件不直接读索引,能不能读它由安装的那枚 zg 决定,而版本门
|
|
4304
|
+
* (lib/zg-version.ts)已保证 zg >= 0.3.0。上游未发布的 HEAD 已把
|
|
4305
|
+
* `CURRENT_INDEX_VERSION` 抬到 3——继续用等号会让新 zg 写出的索引被静默判成「无索引」,
|
|
4306
|
+
* 门禁随之关闭、检索静默改走穷举通道,没有任何报错。低于 2 的旧形状(含 0.2.x 的
|
|
4307
|
+
* `manifestVersion: 1`)仍判「无索引」。
|
|
4308
|
+
*/
|
|
4309
|
+
const MINIMUM_INDEX_VERSION = 2;
|
|
3434
4310
|
/**
|
|
3435
4311
|
* 索引清单是否**真的**覆盖这个工作区。
|
|
3436
4312
|
*
|
|
@@ -3438,30 +4314,31 @@ const SUPPORTED_MANIFEST_VERSION = 1;
|
|
|
3438
4314
|
* - 文件在,但内容不是一份清单(半截写入、被别的东西占了同名文件)——解析失败即不算。
|
|
3439
4315
|
* - 清单在,但索引的根路径不覆盖这个目录(例如指向另一个盘符/被改写过的路径)——此时
|
|
3440
4316
|
* 在这个目录里检索会报「索引不可用」,而门禁却按「已建索引」拦着 grep/rg。
|
|
3441
|
-
* -
|
|
3442
|
-
* `manifestVersion`
|
|
3443
|
-
* 却会被「是个数字」这种宽松判据放进门禁。故这里同样取严格相等。
|
|
4317
|
+
* - 清单的版本低于本包认的下限——0.3.0 的 manifest 用 `indexVersion`;0.2.x 的
|
|
4318
|
+
* `manifestVersion: 1` 旧形状判成「无索引」。
|
|
3444
4319
|
*
|
|
3445
|
-
*
|
|
3446
|
-
*
|
|
3447
|
-
*
|
|
4320
|
+
* 认的结构只有真正用到的两处:`indexVersion` 是不小于下限的整数(当前实测 2;更高版本
|
|
4321
|
+
* 由同一枚/更新的 zg 读写,插件不做上界断言),`sourceRoot.recordedPath` 非空。刻意不校验
|
|
4322
|
+
* scan/embedding 等字段——那些变了索引照样能用,判成「无索引」反而是错的。
|
|
3448
4323
|
*
|
|
3449
|
-
* 覆盖判据是「归一后相等」。实测 macOS
|
|
3450
|
-
*
|
|
3451
|
-
*
|
|
4324
|
+
* 覆盖判据是「归一后相等」。实测 macOS 上 0.3.0 的 `recordedPath` 写的是**解析过**的路径
|
|
4325
|
+
* (`/private/tmp/x`),会话 cwd 通常是未解析那一支;但调用方完全可能交来任一形式,
|
|
4326
|
+
* 故两边都再剥一次 `/private` 前缀再比。
|
|
3452
4327
|
*/
|
|
3453
|
-
function manifestCoversRoot(manifestPath, dir) {
|
|
4328
|
+
function manifestCoversRoot(manifestPath, dir, platform) {
|
|
3454
4329
|
let parsed;
|
|
3455
4330
|
try {
|
|
3456
4331
|
parsed = JSON.parse(readFileSync(manifestPath, "utf8"));
|
|
3457
4332
|
} catch {
|
|
3458
4333
|
return false;
|
|
3459
4334
|
}
|
|
3460
|
-
if (!isRecord(parsed)
|
|
3461
|
-
const
|
|
3462
|
-
if (!
|
|
3463
|
-
const
|
|
3464
|
-
|
|
4335
|
+
if (!isRecord(parsed)) return false;
|
|
4336
|
+
const version = parsed["indexVersion"];
|
|
4337
|
+
if (typeof version !== "number" || !Number.isSafeInteger(version) || version < MINIMUM_INDEX_VERSION) return false;
|
|
4338
|
+
const { sourceRoot } = parsed;
|
|
4339
|
+
if (!isRecord(sourceRoot)) return false;
|
|
4340
|
+
const recorded = sourceRoot["recordedPath"];
|
|
4341
|
+
return typeof recorded === "string" && recorded.length > 0 && comparablePath(normalizeRoot(recorded, platform), process.platform) === comparablePath(normalizeRoot(dir, platform), process.platform);
|
|
3465
4342
|
}
|
|
3466
4343
|
/** zg 索引库存在性探测(search-first 门禁与 zg_search 登记共用)。
|
|
3467
4344
|
* 必须连 workspace manifest 一起看:`<dir>/.zvec-grep/` 这个名字被 zg 自己的**全局
|
|
@@ -3470,28 +4347,29 @@ function manifestCoversRoot(manifestPath, dir) {
|
|
|
3470
4347
|
* 门禁随即在没有任何索引可搜的情况下拦下 grep/rg,而 zg_search 也答不出任何东西。
|
|
3471
4348
|
* manifest 是上游写索引时落的那一份(`writeWorkspaceManifest`),只有它在场,
|
|
3472
4349
|
* 才说明这个工作区真的建过索引。 */
|
|
3473
|
-
function indexProbeOf(dir) {
|
|
3474
|
-
const base =
|
|
3475
|
-
|
|
3476
|
-
|
|
4350
|
+
function indexProbeOf(dir, platform = "posix") {
|
|
4351
|
+
const base = nodePath.join(dir, INDEX_DIR_NAME);
|
|
4352
|
+
const manifestPath = nodePath.join(base, WORKSPACE_MANIFEST_FILE);
|
|
4353
|
+
if (!existsSync(base) || !existsSync(manifestPath)) return false;
|
|
4354
|
+
return manifestCoversRoot(manifestPath, dir, platform);
|
|
3477
4355
|
}
|
|
3478
4356
|
/** root 判据的单一来源:显式值 > 会话工作区 → 存在性 → 授权(已观测 / 同一棵树)。 */
|
|
3479
|
-
function judgeRoot(rawRoot, cwd, messages, ledger) {
|
|
4357
|
+
function judgeRoot(rawRoot, cwd, messages, ledger, platform) {
|
|
3480
4358
|
let resolved;
|
|
3481
4359
|
try {
|
|
3482
|
-
resolved = assertRootExists(resolveRoot(rawRoot, cwd, messages), messages);
|
|
4360
|
+
resolved = assertRootExists(resolveRoot(rawRoot, cwd, messages, platform), messages);
|
|
3483
4361
|
} catch (error) {
|
|
3484
4362
|
return {
|
|
3485
4363
|
allowed: false,
|
|
3486
4364
|
reason: errorText(error)
|
|
3487
4365
|
};
|
|
3488
4366
|
}
|
|
3489
|
-
if (cwd !== void 0 && normalizeRoot(resolved) === normalizeRoot(cwd) || ledger.has(resolved)) return {
|
|
4367
|
+
if (cwd !== void 0 && comparablePath(normalizeRoot(resolved, platform), process.platform) === comparablePath(normalizeRoot(cwd, platform), process.platform) || ledger.has(resolved)) return {
|
|
3490
4368
|
allowed: true,
|
|
3491
4369
|
root: resolved,
|
|
3492
4370
|
question: void 0
|
|
3493
4371
|
};
|
|
3494
|
-
if (cwd !== void 0 && pathsRelated(resolved, cwd, messages)) return {
|
|
4372
|
+
if (cwd !== void 0 && pathsRelated(resolved, cwd, messages, platform)) return {
|
|
3495
4373
|
allowed: true,
|
|
3496
4374
|
root: resolved,
|
|
3497
4375
|
question: {
|
|
@@ -3508,8 +4386,8 @@ function judgeRoot(rawRoot, cwd, messages, ledger) {
|
|
|
3508
4386
|
};
|
|
3509
4387
|
}
|
|
3510
4388
|
/** 工具入参的 root:过 root 判据,放行后登记进白名单(一处三工具共用)。 */
|
|
3511
|
-
function rootOf(args, exec, messages, ledger) {
|
|
3512
|
-
const decision = judgeRoot(args["root"], sessionHeaderCwd(exec), messages, ledger);
|
|
4389
|
+
function rootOf(args, exec, messages, ledger, platform) {
|
|
4390
|
+
const decision = judgeRoot(args["root"], sessionHeaderCwd(exec), messages, ledger, platform);
|
|
3513
4391
|
if (!decision.allowed) throw new Error(decision.reason);
|
|
3514
4392
|
ledger.add(decision.root);
|
|
3515
4393
|
return decision.root;
|
|
@@ -3540,7 +4418,7 @@ function define(host, spec) {
|
|
|
3540
4418
|
}
|
|
3541
4419
|
});
|
|
3542
4420
|
}
|
|
3543
|
-
/** 隐式命名空间与 loader 行 config 共用同一 schema
|
|
4421
|
+
/** 隐式命名空间与 loader 行 config 共用同一 schema(唯一来源,防漂移)。
|
|
3544
4422
|
* 值名退避为 configSchema:避免与同名 interface Config 触发 no-redeclare;
|
|
3545
4423
|
* 外部仍以 `Config` 名导入(export as),公开 API 不变。
|
|
3546
4424
|
*
|
|
@@ -3552,8 +4430,9 @@ function define(host, spec) {
|
|
|
3552
4430
|
* - `settings.register(ns, schema, { base })` 的「底座」层已被宿主移除:内置默认逐字段
|
|
3553
4431
|
* 落成下面的 `.default()`(原 BUILTIN_BASE 原样搬来,单一来源),cordis 装载期按同一
|
|
3554
4432
|
* 份 schema 校验行 config 并填默认,再把 volatile 字段包成引用交给 apply。
|
|
3555
|
-
*
|
|
3556
|
-
*
|
|
4433
|
+
* 七个 volatile 字段全是本卡的可编辑项,一个都不该漏;十一个非 volatile 部署值
|
|
4434
|
+
* (超时三项、stdout 上限、clientMode、daemonUrl、rebuildWaitMs、远程 embedding 三件套、
|
|
4435
|
+
* 显式 root 审批)只走行 config,标 volatile 反而会把它们变成设置卡项。 */
|
|
3557
4436
|
const configSchema = Schema.object({
|
|
3558
4437
|
defaultEmbedding: Schema.string().default(DEFAULT_EMBEDDING).volatile(),
|
|
3559
4438
|
defaultLimit: Schema.natural().min(1).max(50).default(10).volatile(),
|
|
@@ -3570,6 +4449,12 @@ const configSchema = Schema.object({
|
|
|
3570
4449
|
"direct",
|
|
3571
4450
|
"server"
|
|
3572
4451
|
]).default(DEFAULT_CLIENT_MODE),
|
|
4452
|
+
transport: Schema.union([
|
|
4453
|
+
"auto",
|
|
4454
|
+
"cli",
|
|
4455
|
+
"mcp"
|
|
4456
|
+
]).default("auto").volatile(),
|
|
4457
|
+
daemonUrl: Schema.string().default("http://127.0.0.1:7999/mcp"),
|
|
3573
4458
|
rebuildWaitMs: Schema.natural().min(1).default(REBUILD_WAIT_MS),
|
|
3574
4459
|
allowRemoteEmbedding: Schema.boolean().default(false),
|
|
3575
4460
|
remoteEmbeddingEndpoint: Schema.string().default(""),
|
|
@@ -3577,14 +4462,14 @@ const configSchema = Schema.object({
|
|
|
3577
4462
|
requireApprovalForExplicitRoot: Schema.boolean().default(false)
|
|
3578
4463
|
});
|
|
3579
4464
|
/** 白名单键:归一化后的绝对路径;非法 root(相对/越界/NUL)归 undefined。 */
|
|
3580
|
-
function ledgerKey(root, messages) {
|
|
4465
|
+
function ledgerKey(root, messages, platform) {
|
|
3581
4466
|
let key;
|
|
3582
4467
|
try {
|
|
3583
|
-
key = assertAbsoluteRoot(root, messages);
|
|
4468
|
+
key = assertAbsoluteRoot(root, messages, platform);
|
|
3584
4469
|
} catch {
|
|
3585
4470
|
key = void 0;
|
|
3586
4471
|
}
|
|
3587
|
-
return key;
|
|
4472
|
+
return key === void 0 || platform !== "win32" ? key : key.toLowerCase();
|
|
3588
4473
|
}
|
|
3589
4474
|
/**
|
|
3590
4475
|
* 淘汰一张常驻表:先按**有效期**丢过期项,再按**最近使用**丢最老项到不超过上限。
|
|
@@ -3680,26 +4565,29 @@ function createIndexProbeCache(probe, now = Date.now, ttlMs = INDEX_PROBE_TTL_MS
|
|
|
3680
4565
|
* 的取值域,量级差两个数量级,拿来当「这棵树多久算还在用」会短到让跨天的会话反复重新登记。
|
|
3681
4566
|
* 上界与有效期两道都留着:上界保证常驻内存有界,有效期保证冷键不长期占位。
|
|
3682
4567
|
*/
|
|
3683
|
-
function createRootLedger(messages, max = MAX_LEDGER_ROOTS, now = Date.now, ttlMs = LEDGER_TTL_MS) {
|
|
4568
|
+
function createRootLedger(messages, max = MAX_LEDGER_ROOTS, now = Date.now, ttlMs = LEDGER_TTL_MS, platform = "posix") {
|
|
3684
4569
|
const seen = /* @__PURE__ */ new Map();
|
|
3685
4570
|
return {
|
|
3686
4571
|
add(root) {
|
|
3687
|
-
const key = ledgerKey(root, messages);
|
|
4572
|
+
const key = ledgerKey(root, messages, platform);
|
|
3688
4573
|
if (key === void 0) return;
|
|
3689
|
-
touch(seen, key,
|
|
3690
|
-
|
|
4574
|
+
touch(seen, key, {
|
|
4575
|
+
root,
|
|
4576
|
+
seenAt: now()
|
|
4577
|
+
});
|
|
4578
|
+
evictAged(seen, max, (entry) => entry.seenAt + ttlMs, now());
|
|
3691
4579
|
},
|
|
3692
4580
|
has(root) {
|
|
3693
|
-
const key = ledgerKey(root, messages);
|
|
4581
|
+
const key = ledgerKey(root, messages, platform);
|
|
3694
4582
|
if (key === void 0) return false;
|
|
3695
|
-
const
|
|
3696
|
-
if (
|
|
3697
|
-
touch(seen, key,
|
|
4583
|
+
const entry = seen.get(key);
|
|
4584
|
+
if (entry === void 0 || now() - entry.seenAt >= ttlMs) return false;
|
|
4585
|
+
touch(seen, key, entry);
|
|
3698
4586
|
return true;
|
|
3699
4587
|
},
|
|
3700
4588
|
list() {
|
|
3701
4589
|
const at = now();
|
|
3702
|
-
return [...seen].filter((
|
|
4590
|
+
return [...seen.values()].filter((entry) => at - entry.seenAt < ttlMs).map((entry) => entry.root);
|
|
3703
4591
|
}
|
|
3704
4592
|
};
|
|
3705
4593
|
}
|
|
@@ -3712,7 +4600,7 @@ function createRootLedger(messages, max = MAX_LEDGER_ROOTS, now = Date.now, ttlM
|
|
|
3712
4600
|
* 按它校验行 config 后把引用交进 apply 的 config 参数),只剩这一条页面策略声明。
|
|
3713
4601
|
* owner 必须显式传本插件 fiber(缺省是 settings 服务自己的 fiber),且经 child.effect
|
|
3714
4602
|
* 挂载以便随注入子上下文回收——宿主 dsh-client-locale 同款写法。
|
|
3715
|
-
* @param host
|
|
4603
|
+
* @param host 已通过宿主服务守卫的宿主上下文
|
|
3716
4604
|
* @returns {void}
|
|
3717
4605
|
*/
|
|
3718
4606
|
function configureSettingsPage(host) {
|
|
@@ -3725,7 +4613,7 @@ function configureSettingsPage(host) {
|
|
|
3725
4613
|
* guard 拒绝与重建应答就是新文案(不重启、不加本包自己的 locale 设置项)。
|
|
3726
4614
|
* 跨命名空间读在 0.1.7 只有 describe() 一条路:挑出 ns === 'locale' 那条的 value
|
|
3727
4615
|
* (未装 client-locale / 该条目未被投影 → undefined → 中文默认)。
|
|
3728
|
-
* @param host
|
|
4616
|
+
* @param host 已通过宿主服务守卫的宿主上下文
|
|
3729
4617
|
* @returns 每次现取一份文案的 thunk
|
|
3730
4618
|
*/
|
|
3731
4619
|
function createLocaleMessages(host) {
|
|
@@ -3745,7 +4633,7 @@ function noExpiry() {}
|
|
|
3745
4633
|
*
|
|
3746
4634
|
* 分片用根而不是自己,是为了让同一棵委派树共享一份额度:主代理搜过一次,子代理随即就能用
|
|
3747
4635
|
* 那几次 grep/rg。否则「语义检索优先」在多代理下等于失效——每个子代理都得自己搜一次才解锁,
|
|
3748
|
-
*
|
|
4636
|
+
* 而它们搜的往往是同一棵树。宿主没给会话查询接口时 `sessionParent` 为 undefined,查找恒返回
|
|
3749
4637
|
* undefined,上溯自然停在「有父用父、无父用自己」,不会阻断任何调用。
|
|
3750
4638
|
*/
|
|
3751
4639
|
function quotaKeyOf(runtime, execution) {
|
|
@@ -3759,7 +4647,7 @@ function quotaKeyOf(runtime, execution) {
|
|
|
3759
4647
|
* @param config apply 收到的那份 volatile 引用配置
|
|
3760
4648
|
* @returns 会话解锁表(随 apply 闭包里的 Map 一起生死)
|
|
3761
4649
|
*/
|
|
3762
|
-
function createUnlockLedger(config, now = Date.now) {
|
|
4650
|
+
function createUnlockLedger(config, now = Date.now, platform = "posix") {
|
|
3763
4651
|
const unlocksBySession = /* @__PURE__ */ new Map();
|
|
3764
4652
|
return {
|
|
3765
4653
|
grant(key, indexRoot) {
|
|
@@ -3768,7 +4656,7 @@ function createUnlockLedger(config, now = Date.now) {
|
|
|
3768
4656
|
byRoot = /* @__PURE__ */ new Map();
|
|
3769
4657
|
unlocksBySession.set(key, byRoot);
|
|
3770
4658
|
}
|
|
3771
|
-
byRoot.set(normalizeRoot(indexRoot), {
|
|
4659
|
+
byRoot.set(normalizeRoot(indexRoot, platform), {
|
|
3772
4660
|
grepsLeft: readGrepBudget(config),
|
|
3773
4661
|
expiresAt: now() + readUnlockWindowMin(config) * 6e4
|
|
3774
4662
|
});
|
|
@@ -3783,7 +4671,7 @@ function createUnlockLedger(config, now = Date.now) {
|
|
|
3783
4671
|
*/
|
|
3784
4672
|
lookup(sessionKey, indexRoot) {
|
|
3785
4673
|
const byRoot = unlocksBySession.get(sessionKey);
|
|
3786
|
-
const unlock = byRoot === void 0 ? void 0 : byRoot.get(normalizeRoot(indexRoot));
|
|
4674
|
+
const unlock = byRoot === void 0 ? void 0 : byRoot.get(normalizeRoot(indexRoot, platform));
|
|
3787
4675
|
if (byRoot !== void 0 && unlock !== void 0 && unlock.expiresAt > now()) touch(unlocksBySession, sessionKey, byRoot);
|
|
3788
4676
|
return unlock;
|
|
3789
4677
|
},
|
|
@@ -3795,12 +4683,12 @@ function createUnlockLedger(config, now = Date.now) {
|
|
|
3795
4683
|
/**
|
|
3796
4684
|
* 路径过滤类参数的 JSON Schema:单个字符串或字符串数组。
|
|
3797
4685
|
*
|
|
3798
|
-
* 用 `oneOf` 而不是更常见的 `anyOf
|
|
4686
|
+
* 用 `oneOf` 而不是更常见的 `anyOf`:宿主对工具参数执行的是一个**受限子集**,
|
|
3799
4687
|
* `anyOf` 不在其中(实测 `assertSupportedJsonSchema` 报 `anyOf is not a supported
|
|
3800
4688
|
* keyword`),`oneOf` 才被接受,且至少要两个分支。`description` 是标注、与 `oneOf` 并存
|
|
3801
4689
|
* 不冲突(实测通过),所以描述不丢。
|
|
3802
4690
|
*
|
|
3803
|
-
* 之所以要单值:上游 zg
|
|
4691
|
+
* 之所以要单值:上游 zg 对这几项的对外声明就是「字符串或字符串数组」的并集,模型照着
|
|
3804
4692
|
* 那个习惯只给一个 glob 很正常;取值侧 lib/argv-guard.ts 的 singleOrList 两种都收。
|
|
3805
4693
|
*/
|
|
3806
4694
|
function pathFilterParameter(description) {
|
|
@@ -3820,7 +4708,7 @@ function enumParameter(values, description) {
|
|
|
3820
4708
|
description
|
|
3821
4709
|
};
|
|
3822
4710
|
}
|
|
3823
|
-
/** zg_search
|
|
4711
|
+
/** zg_search 的参数表:逐字段描述都取注册期文案(与 parameters 同生死)。 */
|
|
3824
4712
|
function searchToolParameters(registered) {
|
|
3825
4713
|
return {
|
|
3826
4714
|
type: "object",
|
|
@@ -3893,72 +4781,211 @@ function searchToolParameters(registered) {
|
|
|
3893
4781
|
device: {
|
|
3894
4782
|
type: "string",
|
|
3895
4783
|
description: registered.deviceDescription
|
|
3896
|
-
}
|
|
4784
|
+
},
|
|
4785
|
+
files: {
|
|
4786
|
+
type: "boolean",
|
|
4787
|
+
description: registered.filesDescription
|
|
4788
|
+
},
|
|
4789
|
+
category: pathFilterParameter(registered.categoryDescription),
|
|
4790
|
+
categoryNot: pathFilterParameter(registered.categoryNotDescription)
|
|
3897
4791
|
}
|
|
3898
4792
|
};
|
|
3899
4793
|
}
|
|
3900
4794
|
/**
|
|
3901
|
-
* 检索通道判据:`rg`
|
|
4795
|
+
* 检索通道判据:`files` 显式给就走文件发现;`rg` 显式给就照办;都没给则看有没有索引。
|
|
3902
4796
|
*
|
|
3903
|
-
*
|
|
3904
|
-
* rg=
|
|
3905
|
-
* rg
|
|
4797
|
+
* files=true → 文件发现(zg --rg --files,与 rg 互不相干)
|
|
4798
|
+
* rg=true → 穷举词法(不需要索引)
|
|
4799
|
+
* rg=false → 只走索引检索(无索引时让 zg 报 NOT_FOUND,附带建索引提示)
|
|
4800
|
+
* 都未给 → 有索引走索引检索,没有索引改走穷举词法
|
|
3906
4801
|
*
|
|
3907
4802
|
* 缺省之所以自动兜底而不是直接报错:工作区没有索引是**常态**而非异常(新克隆的仓库就是),
|
|
3908
4803
|
* 而报错会把模型推向 `zg_index`——那意味着先下载 embedding 权重。对「先看看这个仓库里
|
|
3909
4804
|
* 有什么」这类问题,逐行字面匹配就是够的,兜底不是妥协。自动改道的代价由 runSearchTool
|
|
3910
4805
|
* 里的前置声明来偿。
|
|
3911
4806
|
*
|
|
3912
|
-
* `
|
|
4807
|
+
* `rg` 只可能是「已过 `boolOf` 的布尔」或「没给」(undefined)——类型错的入参在到达
|
|
3913
4808
|
* 这里之前就已经报错,故这里不再有「非布尔也不缺省」这一档。
|
|
3914
4809
|
*/
|
|
3915
|
-
function
|
|
3916
|
-
if (
|
|
3917
|
-
return
|
|
4810
|
+
function pickChannel(files, rg, hasIndex) {
|
|
4811
|
+
if (files) return "files";
|
|
4812
|
+
if (rg !== void 0) return rg ? "exhaustive" : "indexed";
|
|
4813
|
+
return hasIndex ? "indexed" : "exhaustive";
|
|
3918
4814
|
}
|
|
3919
4815
|
/**
|
|
3920
4816
|
* 这次检索能不能用 `refresh=background`(取值语义见 lib/cli.ts 的 BackgroundSupport)。
|
|
3921
4817
|
*
|
|
3922
4818
|
* 要同时看两件事:**传输模式有没有被部署钉死在 direct**,以及**守护进程是否就绪**。
|
|
3923
|
-
* 钉死 direct 时后者根本无从生效,此时还叫用户去 `zg server on` 是指错方向;而守护进程
|
|
4819
|
+
* 钉死 direct 时后者根本无从生效,此时还叫用户去 `zg --server on` 是指错方向;而守护进程
|
|
3924
4820
|
* 缺席时叫他去起一个是有效的。两档各有各的文案,但判据只有这一处。
|
|
3925
4821
|
*
|
|
3926
4822
|
* 没人要这一档时交回 `daemon-down`——构造器只在 `refresh` 真的是 background 时才读它,
|
|
3927
4823
|
* 于是「不为没人要的档位起一发探测」与「拿不到判据时保守拒绝」两头同时成立,不必再引入
|
|
3928
|
-
* 第三种「不适用」状态。探测结果与 zg_status
|
|
4824
|
+
* 第三种「不适用」状态。探测结果与 zg_status 的回显、设置卡的引导读取接口共用同一份 TTL 缓存。
|
|
3929
4825
|
*/
|
|
3930
|
-
async function backgroundSupportFor(runtime, rawRefresh, mode,
|
|
3931
|
-
if (
|
|
4826
|
+
async function backgroundSupportFor(runtime, rawRefresh, mode, indexed) {
|
|
4827
|
+
if (!indexed || !requestsBackgroundRefresh(rawRefresh)) return "daemon-down";
|
|
3932
4828
|
if (mode === "direct") return "mode-direct";
|
|
3933
4829
|
return await runtime.serverGate.ready() ? "available" : "daemon-down";
|
|
3934
4830
|
}
|
|
3935
4831
|
/**
|
|
4832
|
+
* 这次(索引通道的)检索走哪条传输。mcp 档先经 daemon 句柄确保在场——用户显式选了
|
|
4833
|
+
* mcp,拉起 daemon 就是显式同意过的行为;起不来由句柄抛 daemonStartFailed,**不静默
|
|
4834
|
+
* 回退**。auto 档从不拉起:daemon 缺席就落回 CLI,与 `--mode auto` 的静默回落同一条哲学。
|
|
4835
|
+
* 穷举与文件发现通道不进 MCP(上游恒 direct 语义,MCP 面没有对应工具),由调用方分流。
|
|
4836
|
+
*/
|
|
4837
|
+
async function searchLaneOf(runtime, messages) {
|
|
4838
|
+
const transport = readTransport(runtime.config.transport.get());
|
|
4839
|
+
if (transport === "mcp") {
|
|
4840
|
+
await runtime.daemon.ensure(messages);
|
|
4841
|
+
return "mcp";
|
|
4842
|
+
}
|
|
4843
|
+
if (transport === "cli") return "cli";
|
|
4844
|
+
return await runtime.serverGate.ready() ? "mcp" : "cli";
|
|
4845
|
+
}
|
|
4846
|
+
/**
|
|
4847
|
+
* MCP lane 的索引检索:映射参数 → daemon tools/call → 与 CLI lane 同构的后处理
|
|
4848
|
+
* (锁忙识别、重建等待、命中摘要、截尾注)。成功回执与 CLI 的差异只有两件没有的事:
|
|
4849
|
+
* 沙箱事实(不经沙箱)与 spill(截尾就地保留尾部,不落盘)。
|
|
4850
|
+
*/
|
|
4851
|
+
/** MCP 错误文本的详情裁剪:首尾各留一段,与 failureDetail 同一纪律。 */
|
|
4852
|
+
function daemonFailureDetail(text, messages) {
|
|
4853
|
+
if (text.length <= 800) return text;
|
|
4854
|
+
const head = truncateEnd(text, 400);
|
|
4855
|
+
const tail = truncateStart(text, 400);
|
|
4856
|
+
return fill(messages.detailMiddle, {
|
|
4857
|
+
head,
|
|
4858
|
+
tail
|
|
4859
|
+
});
|
|
4860
|
+
}
|
|
4861
|
+
/** 把 daemon 的错误文本折成可抛的失败:锁忙/授权两类按结构化结论分派,其余通用。 */
|
|
4862
|
+
function daemonFailure(text, messages) {
|
|
4863
|
+
const failure = fill(messages.genericFailure, {
|
|
4864
|
+
exit: 1,
|
|
4865
|
+
detail: withDetail(daemonFailureDetail(text, messages), messages.detailColon)
|
|
4866
|
+
});
|
|
4867
|
+
const concurrent = classifyConcurrentFailure(text);
|
|
4868
|
+
if (concurrent?.kind === "lock-busy" && concurrent.rebuild) return new RebuildLockBusyError(failure);
|
|
4869
|
+
if (concurrent?.kind === "lock-busy") return /* @__PURE__ */ new Error(`${fill(messages.lockBusyOtherOperation, { op: concurrent.ownerOperation ?? "unknown" })}\n${failure}`);
|
|
4870
|
+
if (concurrent?.kind === "permission-denied") return /* @__PURE__ */ new Error(`${failure}\n${messages.remoteAuthDenied}`);
|
|
4871
|
+
return new Error(failure);
|
|
4872
|
+
}
|
|
4873
|
+
/** daemon 调用的传输层失败(fetch 层):取消/超时与 CLI lane 同一套归因。 */
|
|
4874
|
+
function daemonTransportFailure(error, exec, messages, token) {
|
|
4875
|
+
if (!(isRecord(error) && error["name"] === "AbortError")) {
|
|
4876
|
+
const detail = redactToken(errorText(error), token);
|
|
4877
|
+
return new Error(fill(messages.mcpCallFailed, { detail }), { cause: error });
|
|
4878
|
+
}
|
|
4879
|
+
return new Error(exec.signal.aborted ? messages.abortedFailure : messages.timeoutFailure);
|
|
4880
|
+
}
|
|
4881
|
+
/** daemon 成功应答的后处理:截尾(保尾部)与命中摘要,与 CLI lane 同一套路。 */
|
|
4882
|
+
function daemonSuccessText(text, stdoutMaxBytes, summaryLimit, messages) {
|
|
4883
|
+
const overLimit = Buffer.byteLength(text, "utf8") > stdoutMaxBytes;
|
|
4884
|
+
const clipped = overLimit ? truncateStart(text, stdoutMaxBytes) : text;
|
|
4885
|
+
const notes = [];
|
|
4886
|
+
if (overLimit) notes.push(fill(messages.outputTruncated, {
|
|
4887
|
+
maxBytes: stdoutMaxBytes,
|
|
4888
|
+
spill: ""
|
|
4889
|
+
}));
|
|
4890
|
+
const summary = hitSummary(clipped, summaryLimit, overLimit, messages);
|
|
4891
|
+
if (summary !== null) notes.push(summary);
|
|
4892
|
+
return notes.length > 0 ? `${clipped}\n${notes.join("\n")}` : clipped;
|
|
4893
|
+
}
|
|
4894
|
+
async function runSearchViaDaemon(runtime, searchArgs, messages, exec, wait) {
|
|
4895
|
+
const { config } = runtime;
|
|
4896
|
+
const args = daemonSearchArgs(searchArgs, messages);
|
|
4897
|
+
const summaryLimit = resolveLimit(searchArgs.limit, messages);
|
|
4898
|
+
const call = async () => {
|
|
4899
|
+
let text;
|
|
4900
|
+
let isError;
|
|
4901
|
+
try {
|
|
4902
|
+
({text, isError} = await runtime.daemonClient.call({
|
|
4903
|
+
tool: "zvec_grep_search",
|
|
4904
|
+
args,
|
|
4905
|
+
timeoutMs: config.searchTimeoutMs,
|
|
4906
|
+
signal: exec.signal
|
|
4907
|
+
}));
|
|
4908
|
+
} catch (error) {
|
|
4909
|
+
const aborted = isRecord(error) && error["name"] === "AbortError";
|
|
4910
|
+
if (!aborted) runtime.serverGate.invalidate();
|
|
4911
|
+
throw new DaemonCallFailureError(daemonTransportFailure(error, exec, messages, runtime.daemon.tokenOf()).message, aborted);
|
|
4912
|
+
}
|
|
4913
|
+
if (isError) throw daemonFailure(redactToken(text, runtime.daemon.tokenOf()), messages);
|
|
4914
|
+
return daemonSuccessText(text, config.stdoutMaxBytes, summaryLimit, messages);
|
|
4915
|
+
};
|
|
4916
|
+
return attemptWithRebuildWait(wait, messages, exec.signal, call);
|
|
4917
|
+
}
|
|
4918
|
+
/**
|
|
4919
|
+
* 索引通道的 daemon 尝试:选中 MCP 并成功时交回文本;auto 档传输失败时交回一句回退说明;
|
|
4920
|
+
* 其余(未选 MCP、显式 mcp 失败、取消/超时)交回空结果或原样上抛。
|
|
4921
|
+
*/
|
|
4922
|
+
async function tryDaemonLane(runtime, searchArgs, messages, exec, wait) {
|
|
4923
|
+
if (await searchLaneOf(runtime, messages) !== "mcp") return {
|
|
4924
|
+
text: void 0,
|
|
4925
|
+
fallbackNote: void 0
|
|
4926
|
+
};
|
|
4927
|
+
try {
|
|
4928
|
+
return {
|
|
4929
|
+
text: await runSearchViaDaemon(runtime, searchArgs, messages, exec, wait),
|
|
4930
|
+
fallbackNote: void 0
|
|
4931
|
+
};
|
|
4932
|
+
} catch (error) {
|
|
4933
|
+
const transport = readTransport(runtime.config.transport.get());
|
|
4934
|
+
if (error instanceof DaemonCallFailureError && !error.aborted && transport === "mcp") {
|
|
4935
|
+
await runtime.daemon.ensure(messages);
|
|
4936
|
+
return {
|
|
4937
|
+
text: await runSearchViaDaemon(runtime, searchArgs, messages, exec, wait),
|
|
4938
|
+
fallbackNote: void 0
|
|
4939
|
+
};
|
|
4940
|
+
}
|
|
4941
|
+
if (!(error instanceof DaemonCallFailureError) || error.aborted || transport !== "auto") throw error;
|
|
4942
|
+
return {
|
|
4943
|
+
text: void 0,
|
|
4944
|
+
fallbackNote: fill(messages.daemonFallbackNote, { detail: error.message })
|
|
4945
|
+
};
|
|
4946
|
+
}
|
|
4947
|
+
}
|
|
4948
|
+
/**
|
|
3936
4949
|
* zg_search 的执行体:登记工作区 → 选通道 → 构造命令 → 前台执行 → 索引通道成功才发配额。
|
|
3937
4950
|
* @param runtime apply 的运行时依赖(config 现读、解锁表与探测缓存共用)
|
|
3938
4951
|
* @param args 官方 deep-frozen 后的工具入参
|
|
3939
|
-
* @param exec
|
|
4952
|
+
* @param exec 执行上下文(signal 与会话工作区)
|
|
3940
4953
|
* @param messages 本次 execute 现取的文案表
|
|
3941
4954
|
* @returns 交给官方 output schema 的 `{ text }`
|
|
3942
4955
|
*/
|
|
3943
4956
|
async function runSearchTool(runtime, args, exec, messages) {
|
|
3944
4957
|
const { config, host, indexProbe, ledger, unlocks } = runtime;
|
|
3945
4958
|
trackObservedRoot(ledger, exec);
|
|
3946
|
-
const resolvedRoot = rootOf(args, exec, messages, ledger);
|
|
3947
|
-
const indexRoot = findIndexRoot(resolvedRoot, indexProbe);
|
|
4959
|
+
const resolvedRoot = rootOf(args, exec, messages, ledger, runtime.platform);
|
|
4960
|
+
const indexRoot = findIndexRoot(resolvedRoot, indexProbe, void 0, runtime.platform);
|
|
3948
4961
|
const explicit = args["rg"] === void 0 || args["rg"] === null ? void 0 : boolOf(args["rg"], "rg", messages);
|
|
3949
|
-
const
|
|
3950
|
-
const fallback = exhaustive && explicit === void 0 && indexRoot === void 0 ? messages.exhaustiveFallbackNote : void 0;
|
|
4962
|
+
const channel = pickChannel(boolOf(args["files"], "files", messages), explicit, indexRoot !== void 0);
|
|
4963
|
+
const fallback = channel === "exhaustive" && explicit === void 0 && indexRoot === void 0 ? messages.exhaustiveFallbackNote : void 0;
|
|
3951
4964
|
const searchArgs = {
|
|
3952
4965
|
...args,
|
|
3953
4966
|
root: resolvedRoot,
|
|
3954
|
-
|
|
4967
|
+
platform: runtime.platform,
|
|
4968
|
+
...channel === "files" ? {} : { limit: args["limit"] ?? readDefaultLimit(config) }
|
|
3955
4969
|
};
|
|
3956
4970
|
await runtime.versionGate.ensure(messages);
|
|
4971
|
+
let daemonFallbackNote;
|
|
4972
|
+
if (channel === "indexed") {
|
|
4973
|
+
const outcome = await tryDaemonLane(runtime, searchArgs, messages, exec, {
|
|
4974
|
+
root: resolvedRoot,
|
|
4975
|
+
rebuilds: runtime.rebuilds,
|
|
4976
|
+
maxWaitMs: config.rebuildWaitMs
|
|
4977
|
+
});
|
|
4978
|
+
daemonFallbackNote = outcome.fallbackNote;
|
|
4979
|
+
if (outcome.text !== void 0) {
|
|
4980
|
+
if (indexRoot !== void 0) unlocks.grant(quotaKeyOf(runtime, exec), indexRoot);
|
|
4981
|
+
return { text: outcome.text };
|
|
4982
|
+
}
|
|
4983
|
+
}
|
|
3957
4984
|
const mode = readClientMode(config, messages);
|
|
3958
|
-
const { command, workdir } = buildSearchCommand(searchArgs, messages, mode,
|
|
4985
|
+
const { command, workdir } = buildSearchCommand(searchArgs, messages, mode, channel, await backgroundSupportFor(runtime, args["refresh"], mode, channel === "indexed"));
|
|
3959
4986
|
const raw = await runForeground(host, command, workdir, config.searchTimeoutMs, {
|
|
3960
4987
|
signal: exec.signal,
|
|
3961
|
-
env: zgEnv(config),
|
|
4988
|
+
env: zgEnv(config, runtime.daemonEnv()),
|
|
3962
4989
|
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
3963
4990
|
messages,
|
|
3964
4991
|
summaryLimit: resolveLimit(searchArgs.limit, messages),
|
|
@@ -3968,8 +4995,9 @@ async function runSearchTool(runtime, args, exec, messages) {
|
|
|
3968
4995
|
maxWaitMs: config.rebuildWaitMs
|
|
3969
4996
|
}
|
|
3970
4997
|
});
|
|
3971
|
-
if (indexRoot !== void 0 &&
|
|
3972
|
-
|
|
4998
|
+
if (indexRoot !== void 0 && channel === "indexed") unlocks.grant(quotaKeyOf(runtime, exec), indexRoot);
|
|
4999
|
+
const prefix = [daemonFallbackNote, fallback].filter((note) => note !== void 0).join("\n");
|
|
5000
|
+
return { text: prefix.length === 0 ? raw : `${prefix}\n${raw}` };
|
|
3973
5001
|
}
|
|
3974
5002
|
/** 注册 zg_search:语义/混合检索。 */
|
|
3975
5003
|
function registerSearchTool(runtime, registered) {
|
|
@@ -3981,7 +5009,7 @@ function registerSearchTool(runtime, registered) {
|
|
|
3981
5009
|
run: (args, exec, messages) => runSearchTool(runtime, args, exec, messages)
|
|
3982
5010
|
});
|
|
3983
5011
|
}
|
|
3984
|
-
/** zg_index
|
|
5012
|
+
/** zg_index 的参数表:`confirm` 必填(guard 兜底见 registerToolGuards)。 */
|
|
3985
5013
|
function indexToolParameters(registered) {
|
|
3986
5014
|
return {
|
|
3987
5015
|
type: "object",
|
|
@@ -4027,6 +5055,10 @@ function indexToolParameters(registered) {
|
|
|
4027
5055
|
type: "boolean",
|
|
4028
5056
|
description: registered.noIgnoreDescription
|
|
4029
5057
|
},
|
|
5058
|
+
nestedGit: {
|
|
5059
|
+
type: "boolean",
|
|
5060
|
+
description: registered.nestedGitDescription
|
|
5061
|
+
},
|
|
4030
5062
|
maxDepth: {
|
|
4031
5063
|
type: "integer",
|
|
4032
5064
|
description: registered.maxDepthDescription
|
|
@@ -4059,13 +5091,13 @@ function indexToolParameters(registered) {
|
|
|
4059
5091
|
* 模型侧的后台建/重建:一次调用把「起进程 + 登记作业 + 挂超时回收」全做完,把可轮询的
|
|
4060
5092
|
* 作业号交回模型,然后立刻返回。
|
|
4061
5093
|
*
|
|
4062
|
-
* 为什么不要求模型自己去起作业:宿主作业工具在 web
|
|
5094
|
+
* 为什么不要求模型自己去起作业:宿主作业工具在 web 启动方式下已停用,模型侧那条路根本不可走;
|
|
4063
5095
|
* 插件自己复用与设置卡**完全相同**的 spawn/登记/占位三步(`spawnIndexWrite` 与
|
|
4064
5096
|
* `attachIndexWrite` 是同两个函数,不是复制品),所以两条入口起的作业在名册、状态投影、
|
|
4065
|
-
*
|
|
5097
|
+
* 轮询读取接口上完全同形——卡片能看见模型起的重建,反之亦然。
|
|
4066
5098
|
*
|
|
4067
5099
|
* 占位在 `runIndexTool` 里、且落在第一个 await 之前就抢好了;本函数只管把已占的位接上作业号。
|
|
4068
|
-
*
|
|
5100
|
+
* 三条失败的返回路径(注册表缺席、spawn 失败、attach 失败)都**先交还占位**再抛错或答复。
|
|
4069
5101
|
* @param runtime apply 的运行时依赖
|
|
4070
5102
|
* @param root 已过授权与存在性预检的工作区
|
|
4071
5103
|
* @param indexArgs 已归一 root 的索引入参
|
|
@@ -4075,12 +5107,17 @@ function indexToolParameters(registered) {
|
|
|
4075
5107
|
async function startBackgroundIndex(runtime, root, indexArgs, messages, claimed) {
|
|
4076
5108
|
const routes = {
|
|
4077
5109
|
host: runtime.host,
|
|
5110
|
+
platform: runtime.platform,
|
|
4078
5111
|
config: runtime.config,
|
|
4079
5112
|
messages: runtime.messages,
|
|
4080
5113
|
jobsOf: runtime.jobsOf,
|
|
4081
5114
|
records: runtime.records,
|
|
4082
5115
|
rebuilds: runtime.rebuilds,
|
|
4083
|
-
versionGate: runtime.versionGate
|
|
5116
|
+
versionGate: runtime.versionGate,
|
|
5117
|
+
daemonEnv: () => {
|
|
5118
|
+
const token = runtime.daemon.tokenOf();
|
|
5119
|
+
return token === void 0 ? void 0 : { ZVEC_GREP_SERVER_TOKEN: token };
|
|
5120
|
+
}
|
|
4084
5121
|
};
|
|
4085
5122
|
if (runtime.jobsOf() === void 0) {
|
|
4086
5123
|
runtime.rebuilds.release(root, claimed);
|
|
@@ -4106,10 +5143,11 @@ async function startBackgroundIndex(runtime, root, indexArgs, messages, claimed)
|
|
|
4106
5143
|
async function runIndexTool(runtime, args, exec, messages) {
|
|
4107
5144
|
const { config, host, ledger, rebuilds } = runtime;
|
|
4108
5145
|
trackObservedRoot(ledger, exec);
|
|
4109
|
-
const root = rootOf(args, exec, messages, ledger);
|
|
5146
|
+
const root = rootOf(args, exec, messages, ledger, runtime.platform);
|
|
4110
5147
|
const indexArgs = {
|
|
4111
5148
|
...args,
|
|
4112
|
-
root
|
|
5149
|
+
root,
|
|
5150
|
+
platform: runtime.platform
|
|
4113
5151
|
};
|
|
4114
5152
|
const background = boolOf(args["background"], "background", messages);
|
|
4115
5153
|
const rewriting = boolOf(args["rebuild"], "rebuild", messages) || background;
|
|
@@ -4127,7 +5165,7 @@ async function runIndexTool(runtime, args, exec, messages) {
|
|
|
4127
5165
|
const { command, workdir } = buildIndexCommand(indexArgs, readDefaultEmbedding(config), messages, readClientMode(config, messages), allowRemoteEmbedding(config));
|
|
4128
5166
|
const text = await runForeground(host, command, workdir, config.indexTimeoutMs, {
|
|
4129
5167
|
signal: exec.signal,
|
|
4130
|
-
env: zgEnv(config),
|
|
5168
|
+
env: zgEnv(config, runtime.daemonEnv()),
|
|
4131
5169
|
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
4132
5170
|
messages
|
|
4133
5171
|
});
|
|
@@ -4148,17 +5186,17 @@ function registerIndexTool(runtime, registered) {
|
|
|
4148
5186
|
});
|
|
4149
5187
|
}
|
|
4150
5188
|
/**
|
|
4151
|
-
* zg_status 的执行体:登记工作区 → `zg status` → 文本原样透传。
|
|
5189
|
+
* zg_status 的执行体:登记工作区 → `zg --status` → 文本原样透传。
|
|
4152
5190
|
* @param runtime apply 的运行时依赖
|
|
4153
5191
|
* @param args 官方 deep-frozen 后的工具入参
|
|
4154
|
-
* @param exec
|
|
5192
|
+
* @param exec 执行上下文(signal 与会话工作区)
|
|
4155
5193
|
* @param messages 本次 execute 现取的文案表
|
|
4156
5194
|
* @returns 交给官方 output schema 的 `{ text }`
|
|
4157
5195
|
*/
|
|
4158
5196
|
async function runStatusTool(runtime, args, exec, messages) {
|
|
4159
5197
|
const { config, host, ledger, rebuilds } = runtime;
|
|
4160
5198
|
trackObservedRoot(ledger, exec);
|
|
4161
|
-
const root = rootOf(args, exec, messages, ledger);
|
|
5199
|
+
const root = rootOf(args, exec, messages, ledger, runtime.platform);
|
|
4162
5200
|
const entry = rebuilds.covering(root, messages);
|
|
4163
5201
|
if (entry?.jobId !== void 0) return { text: fill(messages.statusRebuilding, {
|
|
4164
5202
|
root: entry.root,
|
|
@@ -4168,11 +5206,12 @@ async function runStatusTool(runtime, args, exec, messages) {
|
|
|
4168
5206
|
await runtime.versionGate.ensure(messages);
|
|
4169
5207
|
const { command, workdir } = buildStatusCommand({
|
|
4170
5208
|
root,
|
|
4171
|
-
checkReady
|
|
5209
|
+
checkReady,
|
|
5210
|
+
platform: runtime.platform
|
|
4172
5211
|
}, messages, readClientMode(config, messages));
|
|
4173
5212
|
const text = await runForeground(host, command, workdir, config.statusTimeoutMs, {
|
|
4174
5213
|
signal: exec.signal,
|
|
4175
|
-
env: zgEnv(config),
|
|
5214
|
+
env: zgEnv(config, runtime.daemonEnv()),
|
|
4176
5215
|
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
4177
5216
|
messages,
|
|
4178
5217
|
rebuildWait: {
|
|
@@ -4217,7 +5256,7 @@ function registerStatusTool(runtime, registered) {
|
|
|
4217
5256
|
run: (args, exec, messages) => runStatusTool(runtime, args, exec, messages)
|
|
4218
5257
|
});
|
|
4219
5258
|
}
|
|
4220
|
-
/** 三位 zg_*
|
|
5259
|
+
/** 三位 zg_* 工具的注册入口:描述与参数表都取注册期文案,执行体共用同一份运行时依赖。 */
|
|
4221
5260
|
function registerZvecTools(runtime, registered) {
|
|
4222
5261
|
registerSearchTool(runtime, registered);
|
|
4223
5262
|
registerIndexTool(runtime, registered);
|
|
@@ -4232,7 +5271,7 @@ function registerRoutingSection(host, registered) {
|
|
|
4232
5271
|
});
|
|
4233
5272
|
}
|
|
4234
5273
|
/**
|
|
4235
|
-
*
|
|
5274
|
+
* 安全后备 guard(只拦 zg_*)+ search-first 门禁(拦 bash/pwsh 里的 grep/rg
|
|
4236
5275
|
* 检索与原生 grep 工具)。前者拒绝安全风险,后者拒绝检索顺序违规:每次成功
|
|
4237
5276
|
* zg_search 发放配额(次数/时效见设置),用尽/过期再拦。两谓词均纯函数,
|
|
4238
5277
|
* 索引探测(缓存化,见 createIndexProbeCache)、时钟与会话解锁表由运行时依赖注入。
|
|
@@ -4243,11 +5282,11 @@ function registerRoutingSection(host, registered) {
|
|
|
4243
5282
|
* 是本包加宽后的读取投影(lib/routing.ts),加宽即容错,收窄校验留在谓词内部。
|
|
4244
5283
|
*/
|
|
4245
5284
|
/** 该不该为这次调用问一句;不该问就交回 undefined(调用方转交 next())。 */
|
|
4246
|
-
function explicitRootAsk(execution, ledger, messages) {
|
|
5285
|
+
function explicitRootAsk(execution, ledger, messages, platform) {
|
|
4247
5286
|
const raw = (isRecord(execution.arguments) ? execution.arguments : void 0)?.["root"];
|
|
4248
5287
|
let question;
|
|
4249
5288
|
if (typeof raw === "string" && raw.trim().length > 0) {
|
|
4250
|
-
const decision = judgeRoot(raw, sessionHeaderCwd(execution), messages, ledger);
|
|
5289
|
+
const decision = judgeRoot(raw, sessionHeaderCwd(execution), messages, ledger, platform);
|
|
4251
5290
|
question = decision.allowed ? decision.question : void 0;
|
|
4252
5291
|
}
|
|
4253
5292
|
return question === void 0 ? void 0 : {
|
|
@@ -4263,7 +5302,7 @@ function explicitRootAsk(execution, ledger, messages) {
|
|
|
4263
5302
|
};
|
|
4264
5303
|
}
|
|
4265
5304
|
/**
|
|
4266
|
-
* 显式 root
|
|
5305
|
+
* 显式 root 的用户确认闸(官方自带的确认接口,**默认关**)。
|
|
4267
5306
|
*
|
|
4268
5307
|
* 为什么必须是 `tools/pre-execute` 而不是 `tools.guard`:`ToolGuard` 的返回只有
|
|
4269
5308
|
* `string | undefined`(一串拒绝理由),它能**拒**但不能**问**——没有「允许」这个结果。
|
|
@@ -4286,7 +5325,7 @@ function registerRootApproval(runtime) {
|
|
|
4286
5325
|
host.on("tools/pre-execute", (execution, next) => {
|
|
4287
5326
|
if (!config.requireApprovalForExplicitRoot) return next();
|
|
4288
5327
|
if (!isZgToolName(execution.name)) return next();
|
|
4289
|
-
const ask = explicitRootAsk(execution, ledger, localeMessages());
|
|
5328
|
+
const ask = explicitRootAsk(execution, ledger, localeMessages(), runtime.platform);
|
|
4290
5329
|
return ask === void 0 ? next() : Promise.resolve(ask);
|
|
4291
5330
|
});
|
|
4292
5331
|
}
|
|
@@ -4295,10 +5334,11 @@ function registerToolGuards(runtime) {
|
|
|
4295
5334
|
host.tools.guard((execution) => {
|
|
4296
5335
|
trackObservedRoot(ledger, execution);
|
|
4297
5336
|
const messages = localeMessages();
|
|
4298
|
-
const zg = zgGuard(execution, messages);
|
|
5337
|
+
const zg = zgGuard(execution, messages, runtime.platform);
|
|
4299
5338
|
if (zg !== void 0) return zg;
|
|
4300
5339
|
return searchFirstGuard(execution, {
|
|
4301
5340
|
enabled: readEnforceSearchFirst(config),
|
|
5341
|
+
platform: runtime.platform,
|
|
4302
5342
|
indexProbe,
|
|
4303
5343
|
now: () => Date.now(),
|
|
4304
5344
|
grepBudget: readGrepBudget(config),
|
|
@@ -4314,19 +5354,57 @@ function registerToolGuards(runtime) {
|
|
|
4314
5354
|
function apply(ctx, config) {
|
|
4315
5355
|
if (!isZvecGrepHost(ctx)) throw new Error("[zvec-grep] required services (settings/shell/tools/systemPrompt/timer/get) missing");
|
|
4316
5356
|
const host = ctx;
|
|
5357
|
+
const platform = runtimePlatform();
|
|
4317
5358
|
configureSettingsPage(host);
|
|
4318
5359
|
const localeMessages = createLocaleMessages(host);
|
|
4319
|
-
const ledger = createRootLedger(localeMessages());
|
|
5360
|
+
const ledger = createRootLedger(localeMessages(), MAX_LEDGER_ROOTS, Date.now, LEDGER_TTL_MS, platform);
|
|
5361
|
+
const daemonState = {
|
|
5362
|
+
token: void 0,
|
|
5363
|
+
startedByUs: false
|
|
5364
|
+
};
|
|
5365
|
+
const tokenOf = () => daemonState.token;
|
|
5366
|
+
/**
|
|
5367
|
+
* 自启 daemon 的追加 env:**所有** CLI 子进程(检索 / 索引 / 状态 / 两道探测 / 后台写)
|
|
5368
|
+
* 与 MCP Bearer 都从这一处取值。token 可能在插件存活期间才生成(懒拉起那一拍),故每次现取。
|
|
5369
|
+
*/
|
|
5370
|
+
const daemonEnv = () => {
|
|
5371
|
+
const token = tokenOf();
|
|
5372
|
+
return token === void 0 ? void 0 : { ZVEC_GREP_SERVER_TOKEN: token };
|
|
5373
|
+
};
|
|
5374
|
+
const daemonUrl = readDaemonUrl(config.daemonUrl, localeMessages());
|
|
5375
|
+
const tokenFile = tokenFilePath();
|
|
5376
|
+
const versionGate = createZgVersionGate(host, config, tokenOf);
|
|
5377
|
+
const serverGate = createZgServerGate(host, config, tokenOf);
|
|
4320
5378
|
const runtime = {
|
|
4321
5379
|
host,
|
|
5380
|
+
platform,
|
|
4322
5381
|
config,
|
|
4323
5382
|
messages: localeMessages,
|
|
4324
5383
|
ledger,
|
|
4325
|
-
unlocks: createUnlockLedger(config),
|
|
4326
|
-
indexProbe: createIndexProbeCache(indexProbeOf),
|
|
4327
|
-
rebuilds: createRebuildRegistry(),
|
|
4328
|
-
versionGate
|
|
4329
|
-
serverGate
|
|
5384
|
+
unlocks: createUnlockLedger(config, Date.now, platform),
|
|
5385
|
+
indexProbe: createIndexProbeCache((dir) => indexProbeOf(dir, platform)),
|
|
5386
|
+
rebuilds: createRebuildRegistry({ platform }),
|
|
5387
|
+
versionGate,
|
|
5388
|
+
serverGate,
|
|
5389
|
+
daemon: createDaemonHandle({
|
|
5390
|
+
host,
|
|
5391
|
+
config,
|
|
5392
|
+
daemonUrl,
|
|
5393
|
+
tokenFile,
|
|
5394
|
+
tokenOf,
|
|
5395
|
+
setToken: (token) => {
|
|
5396
|
+
daemonState.token = token;
|
|
5397
|
+
},
|
|
5398
|
+
markStarted: () => {
|
|
5399
|
+
daemonState.startedByUs = true;
|
|
5400
|
+
},
|
|
5401
|
+
serverGate
|
|
5402
|
+
}),
|
|
5403
|
+
daemonEnv,
|
|
5404
|
+
daemonClient: createDaemonClient({
|
|
5405
|
+
url: daemonUrl,
|
|
5406
|
+
tokenOf
|
|
5407
|
+
}),
|
|
4330
5408
|
jobsOf: () => host.get("jobs"),
|
|
4331
5409
|
records: /* @__PURE__ */ new Map(),
|
|
4332
5410
|
sessionParent: (id) => {
|
|
@@ -4340,8 +5418,16 @@ function apply(ctx, config) {
|
|
|
4340
5418
|
registerRoutingSection(host, registered);
|
|
4341
5419
|
registerToolGuards(runtime);
|
|
4342
5420
|
registerRootApproval(runtime);
|
|
5421
|
+
registerDaemonShutdown({
|
|
5422
|
+
host,
|
|
5423
|
+
config,
|
|
5424
|
+
tokenFile,
|
|
5425
|
+
daemonEnv,
|
|
5426
|
+
startedByUs: () => daemonState.startedByUs
|
|
5427
|
+
});
|
|
4343
5428
|
installRebuildRemote(host, {
|
|
4344
5429
|
host,
|
|
5430
|
+
platform,
|
|
4345
5431
|
config,
|
|
4346
5432
|
messages: localeMessages,
|
|
4347
5433
|
jobsOf: runtime.jobsOf,
|
|
@@ -4349,7 +5435,11 @@ function apply(ctx, config) {
|
|
|
4349
5435
|
rebuilds: runtime.rebuilds,
|
|
4350
5436
|
versionGate: runtime.versionGate,
|
|
4351
5437
|
ledger,
|
|
4352
|
-
serverGate: runtime.serverGate
|
|
5438
|
+
serverGate: runtime.serverGate,
|
|
5439
|
+
daemonEnv: () => {
|
|
5440
|
+
const token = tokenOf();
|
|
5441
|
+
return token === void 0 ? void 0 : { ZVEC_GREP_SERVER_TOKEN: token };
|
|
5442
|
+
}
|
|
4353
5443
|
});
|
|
4354
5444
|
}
|
|
4355
5445
|
var host_default = {
|
|
@@ -4363,4 +5453,4 @@ var host_default = {
|
|
|
4363
5453
|
Config: configSchema,
|
|
4364
5454
|
apply
|
|
4365
5455
|
};
|
|
4366
|
-
export { configSchema as Config, INDEX_PROBE_CACHE_MAX, INDEX_PROBE_TTL_MS, comparablePath, createIndexProbeCache, createRootLedger, createUnlockLedger, host_default as default, hitSummary, signalStderr };
|
|
5456
|
+
export { configSchema as Config, INDEX_PROBE_CACHE_MAX, INDEX_PROBE_TTL_MS, comparablePath, createIndexProbeCache, createRootLedger, createUnlockLedger, host_default as default, hitSummary, redactToken, signalStderr };
|