@jayyuen66/dsh-zvec-grep 0.1.0 → 0.1.2
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 +62 -0
- package/README.md +72 -128
- package/README.zh-CN.md +164 -0
- package/THIRD_PARTY_NOTICES.md +37 -0
- package/client.js +35 -14
- package/cordis.patch.yml +2 -2
- package/host.js +1467 -267
- package/package.json +60 -38
package/host.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
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 { existsSync } from "node:fs";
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
4
5
|
import { randomUUID } from "node:crypto";
|
|
5
6
|
import { guardBody, queryParam, sendJson } from "@jayyuen66/dsh-plugin-shared/lib/http";
|
|
6
|
-
import { guardTrust } from "@jayyuen66/dsh-plugin-shared/lib/trust";
|
|
7
|
+
import { guardTrust, isNonLoopbackBindHost } from "@jayyuen66/dsh-plugin-shared/lib/trust";
|
|
7
8
|
import { isRecord } from "@jayyuen66/dsh-plugin-shared/lib/record";
|
|
8
9
|
import { errorText } from "@jayyuen66/dsh-plugin-shared/lib/errors";
|
|
9
10
|
import { LOCALE_SETTINGS_NAMESPACE, messagesFor, resolveLocalePreference } from "@jayyuen66/dsh-plugin-shared/lib/locale";
|
|
@@ -89,21 +90,27 @@ function isLocalEmbedding(reference) {
|
|
|
89
90
|
}
|
|
90
91
|
//#endregion
|
|
91
92
|
//#region lib/messages.ts
|
|
93
|
+
/** 中文侧「绝对路径 + 可操作范围」那句共用文案(三个 root 参数同义、同一份判据)。 */
|
|
94
|
+
const ABSOLUTE_ROOT_HINT_ZH = "工作区绝对路径(可选:缺省=当前会话工作区;显式传入时须在本会话可操作范围内——会话工作区本身、其上级或下级、或本会话已登记过的工作区)";
|
|
95
|
+
/** 英文侧「绝对路径 + 可操作范围」那句共用文案(检索/索引两个 root 参数同义)。 */
|
|
96
|
+
const ABSOLUTE_ROOT_HINT = "Absolute workspace path (optional: default = current session workspace; when passed explicitly it must stay inside this session's operable scope — the workspace itself, its parents or children, or a workspace this session already registered)";
|
|
92
97
|
const MESSAGES = {
|
|
93
98
|
zh: {
|
|
94
|
-
searchToolDescription: "对已建索引的工作区做语义/混合检索(BM25+向量+RRF),用于精确查找无法回答的问题:架构、调用链、依赖、生命周期、数据流/控制流、设计意图、跨文件对比与综合。root
|
|
95
|
-
indexToolDescription: "为工作区 root 创建/增量更新/重建/删除持久检索索引(建后 zg_search 才可用)。仅在用户明确要求建/重建/删索引时调用,且 confirm 必须为 true;绝不静默建索引。root
|
|
99
|
+
searchToolDescription: "对已建索引的工作区做语义/混合检索(BM25+向量+RRF),用于精确查找无法回答的问题:架构、调用链、依赖、生命周期、数据流/控制流、设计意图、跨文件对比与综合。root 缺省为当前会话工作区;显式传入时必须落在本会话可操作范围内(会话工作区本身、它的上级或下级目录,或本会话已登记过的工作区)。检索会自动同步既有索引的新鲜度(--refresh wait),因此改完代码无需先手动 zg_index 也能搜到新内容;但从未建索引的 root 仍会明确报错,不会静默建索引。每个命中都带**有界源码片段**(--preview short:锚点行 + 少量上下文),足够时视为已读证据,需要更多上下文再 read。精确字面/正则/文件名/报错串查找请用原生 grep/glob。大型工作区请用 globs/fileTypes 缩小范围,否则可能超时。至少提供 query/queries/fts/vector 之一。已建索引的工作区 grep/rg 受 search-first 门禁约束:每次成功的 zg_search 会为当前会话解锁 grepBudgetPerSearch 次 grep/rg(unlockWindowMin 分钟内有效),配额用尽或过期后需换一个更准确的 query/fts 重新检索。",
|
|
100
|
+
indexToolDescription: "为工作区 root 创建/增量更新/重建/删除持久检索索引(建后 zg_search 才可用)。仅在用户明确要求建/重建/删索引时调用,且 confirm 必须为 true;绝不静默建索引。root 缺省为当前会话工作区;显式传入时必须落在本会话可操作范围内——会话工作区本身、它的上级或下级目录,或本会话已登记过的工作区;其余绝对路径一律拒绝(一个合法绝对路径不构成授权)。embedding 默认用设置里的 defaultEmbedding,也可显式指定,但**只接受本地候选清单内的模型**(远程 embedding 会把工作区内容送到外部端点,须由用户在部署配置里显式开放,模型侧无法开启);切换 embedding 需 rebuild=true 才重新生效。删除传 drop=true。要清掉这个根继承来的文件选择设置传 resetPaths=true。",
|
|
96
101
|
statusToolDescription: "查询工作区 root 的索引状态(是否已建、文件数、freshness、活动任务)。用于索引缺失/失败/取消后的诊断或显式进度监控;普通搜索前不要调用。",
|
|
97
|
-
rootSearchDescription:
|
|
98
|
-
rootIndexDescription:
|
|
99
|
-
rootStatusDescription:
|
|
102
|
+
rootSearchDescription: ABSOLUTE_ROOT_HINT_ZH,
|
|
103
|
+
rootIndexDescription: ABSOLUTE_ROOT_HINT_ZH,
|
|
104
|
+
rootStatusDescription: ABSOLUTE_ROOT_HINT_ZH,
|
|
100
105
|
queryDescription: "单个混合查询(语义+词法)",
|
|
101
106
|
queriesDescription: "多个混合查询组",
|
|
102
107
|
ftsDescription: "词法查询组(如标识符、报错串)",
|
|
103
108
|
vectorDescription: "纯语义查询组",
|
|
104
109
|
fuseDescription: "融合所有组为单一排名",
|
|
105
110
|
limitDescription: "每组最大条数 1-50,默认 10",
|
|
106
|
-
|
|
111
|
+
previewDescription: "每条命中带的源码片段大小:none 只给锚点行、short 给锚点加一段有界上下文、full 给整段源码。默认 short",
|
|
112
|
+
refreshDescription: "检索前如何刷新索引:wait 等刷新到最新(默认)、off 不刷新、background 交给守护进程后台刷新。注意 background 只在守护进程模式下成立,直连模式下 zg 会降级成 off 并在 stderr 提示",
|
|
113
|
+
globsDescription: "路径 glob(如 src/**),单个字符串或数组",
|
|
107
114
|
globsIndexDescription: "路径 glob",
|
|
108
115
|
insensitiveGlobsDescription: "大小写不敏感 glob",
|
|
109
116
|
fileTypesDescription: "文件类型(如 ts、py)",
|
|
@@ -114,8 +121,9 @@ const MESSAGES = {
|
|
|
114
121
|
modifiedAfterDescription: "只搜该时间后修改的文件",
|
|
115
122
|
modifiedBeforeDescription: "只搜该时间前修改的文件",
|
|
116
123
|
deviceDescription: "auto/cpu/metal/vulkan/cuda;默认 auto(Metal 加速,失败自动回退 CPU)",
|
|
124
|
+
resetPathsDescription: "清掉这个根继承来的文件选择设置(globs/fileTypes/hidden/… 全部回到未设置),只影响本次写入的索引配置;可与 globs/fileTypes 同传(先清干净再按这次的规则选),但与 drop 互斥",
|
|
117
125
|
confirmDescription: "用户已明确要求本次建/重建/删索引,必须为 true",
|
|
118
|
-
embeddingDescription: "本地 embedding 模型引用(默认取设置 defaultEmbedding
|
|
126
|
+
embeddingDescription: "本地 embedding 模型引用(默认取设置 defaultEmbedding)。只接受本地清单内的模型;远程 embedding 会把工作区内容送到外部端点,须由用户在部署配置里显式开放,本插件不接受模型侧开启",
|
|
119
127
|
rebuildDescription: "重建已有索引(切换 embedding 时必须为 true)",
|
|
120
128
|
dropDescription: "删除索引(与其它索引选项互斥)",
|
|
121
129
|
ignoreFilesDescription: "额外的 ignore 文件路径(如 .gitignore 之外的排除清单),透传 zg --ignore-file",
|
|
@@ -131,7 +139,8 @@ const MESSAGES = {
|
|
|
131
139
|
"",
|
|
132
140
|
"本环境的工作区检索路由:",
|
|
133
141
|
"- 工作区已建 zg 索引(存在 .zvec-grep/ 目录)时:所有检索必须先调用 zg_search(语义/混合,命中更全更准);grep/rg 只作为 zg_search 之后的精确字面/正则补充。每次成功的 zg_search 解锁少量 grep/rg 配额(次数/时效见设置),配额用尽或过期后门禁会再次拦截,此时应换一个更准确的 query/fts 重新 zg_search。门禁同时覆盖 bash 里的 grep/rg 命令与原生 grep 工具。",
|
|
134
|
-
"-
|
|
142
|
+
"- 无索引工作区:zg_search 会自动改走**穷举词法检索**(逐行字面匹配,结果里会有一条前置声明)。精确查找(单个定义、字面量、文件名、配置键、报错信息、正则、穷举列表)用 zg_search 就够,不必先 zg_index(那要先下载 embedding 权重)。也可显式 rg=true 强制它,或 rg=false 拒绝改道。穷举检索是纯字面匹配,回答不了「这个模块的职责是什么」这类语义问题——那类问题仍应先建索引。",
|
|
143
|
+
"- 穷举检索**不发放** grep/rg 配额:它不读索引,不构成「先用过语义检索」的证据。有索引的工作区想用 grep/rg,仍要先走一次索引检索。",
|
|
135
144
|
"- 语义/关系/跨文件/多跳证据(架构、调用链、依赖、生命周期、数据流或控制流、设计意图、对比、跨文件综合)→ 必须先调用 zg_search。",
|
|
136
145
|
"- zg_status 只用于索引缺失/失败/取消后的诊断或显式进度监控;普通搜索前不要调用。",
|
|
137
146
|
"",
|
|
@@ -141,7 +150,7 @@ const MESSAGES = {
|
|
|
141
150
|
"3. 证据足够即停止搜索,不为重复确认而重复相似查询或扩大排查。",
|
|
142
151
|
"4. zg_index 仅在用户明确要求建/重建/删索引时调用,且 confirm 必须为 true;绝不静默建索引。",
|
|
143
152
|
"5. 新建索引用用户选定的 embedding,未选定时不得臆测;切换 embedding 需 rebuild 才生效。",
|
|
144
|
-
"6. zg_* 的 root
|
|
153
|
+
"6. zg_* 的 root 可省略:缺省为当前会话工作区(绝对路径)。显式传入时必须落在本会话可操作范围内——会话工作区本身、它的上级或下级目录,或本会话已登记过的工作区;其余绝对路径会被拒绝。"
|
|
145
154
|
].join("\n"),
|
|
146
155
|
argsMustBeObject: "zg {name}: 参数必须是一个 JSON 对象(收到 {received})",
|
|
147
156
|
missingRequiredArgs: "zg {name}: 缺少必填参数 {fields}(缺失即拒绝,不产生副作用)",
|
|
@@ -152,8 +161,23 @@ const MESSAGES = {
|
|
|
152
161
|
detailMiddle: "{head} …[中间省略]… {tail}",
|
|
153
162
|
timeoutFailure: "zg 执行超时:检索默认带 --refresh wait(同步刷新既有索引),大型工作区可能耗时过长。请用 globs / fileTypes 缩小范围后重试,或先用手写 grep/glob。",
|
|
154
163
|
abortedFailure: "zg 执行被中止",
|
|
164
|
+
rebuildWaitTimeout: "等待 {root} 的重建完成超时(约 {seconds} 秒),重建可能仍在进行;请稍后重试。本次不会发放 grep/rg 配额——重建期间索引不可读,先等它结束。",
|
|
165
|
+
rebuildWaitAborted: "等待 {root} 的重建完成时被中止。",
|
|
166
|
+
statusRebuilding: "{root} 正在重建中(作业 {jobId})。重建期间索引不可读,检索会自动等待它完成后重试。如需查看实时输出,请在设置卡的工作区重建面板里观察。此刻即使问「索引是否就绪」也是否定的答案——重建落定后再问。",
|
|
167
|
+
statusNotReady: "[zvec-grep] {root} 的索引**未就绪**(上面是 zg 的完整就绪报告)。这不是执行失败,而是 checkReady=true 要的那个结论:{detail}",
|
|
168
|
+
checkReadyDescription: "就绪判定:就绪报告照常给出,另行判定索引是否 ready 并在结论里明说。未就绪不是执行失败,报告仍会返回",
|
|
169
|
+
traceDescription: "排障用:每条命中附一行检索轨迹,说明它被哪几路召回、在各组里名次如何,并给出分值。输出会明显变长;穷举检索(rg)模式不支持该参数",
|
|
170
|
+
indexBackgroundStarted: "已在后台为 {root} 启动索引(作业 {jobId}),命令:{command}。索引落定前该根的语义检索会等它完成再重试,grep/rg 在这段时间不受门禁限制。用 zg_status 查就绪与否;本次调用不发放 grep/rg 配额",
|
|
171
|
+
backgroundDescription: "后台执行:起一条 zg 进程并把可轮询的作业号交回,本次调用立即返回。建索引可能要下载 embedding 权重、等很久,后台执行免得工具调用一直挂着。落定前该根的语义检索会自动等它完成再重试",
|
|
172
|
+
endpointRebuildInFlight: "该工作区已有一条重建正在进行,请稍后再试。",
|
|
173
|
+
indexRebuildInFlight: "{root} 已有一条重建在进行中,本次未执行——并发重建会互相顶掉并双双失败。请等它结束后再试,或用 zg_status 查看那条重建的状态。",
|
|
174
|
+
rootNotAuthorized: "root 未获授权:{root} 不在本会话可操作范围内(当前会话工作区:{cwd})。只能检索/建索引本会话工作区本身、它的上级或下级目录,以及本会话已登记过的工作区。若确实需要另一个工作区,请让用户新开一个会话到那里。",
|
|
175
|
+
rootNoSession: "(无会话工作区)",
|
|
155
176
|
deniedFailure: "zg 执行失败(exit={exit}):{denied}——本次检索目标不在该会话可读写范围内,请换工作区或让用户批准更宽的文件策略。{detail}",
|
|
156
177
|
notInstalledFailure: "zg 未安装或不在 PATH:请先 `npm install -g @zvec/zvec-grep`。{detail}",
|
|
178
|
+
rootApprovalReason: "模型为 {root} 指定了一个既不是本会话工作区、也不是本会话登记过的工作区(当前会话工作区:{cwd})。该路径会把这个目录的内容读进上下文。",
|
|
179
|
+
rootApprovalPrompt: "允许这一次对 {root} 建立/读取 zg 索引吗?该目录的内容会进入本次会话上下文,且只对这一次调用生效。",
|
|
180
|
+
zgVersionTooOld: "zg 版本过低:当前 {actual},本插件要求 >= {minimum}。本插件下发的命令形态与旗标名按该版本书写,太老的 zg 可能把命令当成别的东西执行、给出看起来正常实则什么都没查的结果——所以在发命令前就停在这里。请先升级:`npm install -g @zvec/zvec-grep@latest`,然后重试。",
|
|
157
181
|
genericFailure: "zg 执行失败(exit={exit}){detail}",
|
|
158
182
|
detailPrefix: " 详情:{detail}",
|
|
159
183
|
detailColon: ":{detail}",
|
|
@@ -161,8 +185,9 @@ const MESSAGES = {
|
|
|
161
185
|
spillNote: "(完整输出已落盘:{path})",
|
|
162
186
|
sandboxWarning: "[zvec-grep] 警告:{denied}——下面的结果可能缺少被拒读写的文件,别把它当成全工作区的完整检索结论。",
|
|
163
187
|
stderrNote: "[zvec-grep] zg stderr(可能含降级提示,如退化为纯词法检索 / 跳过 --refresh):{marked}{tail}",
|
|
164
|
-
hitSummary: "[zvec-grep] 命中摘要:{groups}
|
|
165
|
-
|
|
188
|
+
hitSummary: "[zvec-grep] 命中摘要:{groups} 个查询组,分组计数合计 {grouped} 条{dedup};请求 --limit {limit}{capped}{truncated}",
|
|
189
|
+
hitDedup: ",去重后 {unique} 个不同位置",
|
|
190
|
+
hitCapped: "(有组的命中数正好等于 --limit;zg 不提供截断信号,此处只陈述计数,不推断是否还有更多)",
|
|
166
191
|
hitTruncated: ";输出已截尾,计数只含保留部分",
|
|
167
192
|
rootMissing: "root 目录不存在(zg 需要真实存在的工作区路径):{root}",
|
|
168
193
|
jobOutputTruncated: "\n[zvec-grep] 输出过长,已截断,只保留尾部",
|
|
@@ -185,6 +210,10 @@ const MESSAGES = {
|
|
|
185
210
|
mustBeString: "{name} 必须是字符串(收到 {received})",
|
|
186
211
|
noNulBytes: "{name} 不能包含 NUL 字节",
|
|
187
212
|
mustBeBoolean: "{name} 必须是布尔值(收到 {received})",
|
|
213
|
+
clientModeInvalid: "zg 传输模式非法:{received}(合法取值:{allowed})",
|
|
214
|
+
previewInvalid: "预览档位非法:{received}(合法取值:{allowed})",
|
|
215
|
+
refreshInvalid: "刷新策略非法:{received}(合法取值:{allowed})",
|
|
216
|
+
symbolTypeInvalid: "符号类型非法:{received}(合法取值:{allowed},只接受小写)",
|
|
188
217
|
rootEscapesFs: "root 含越界的 .. 段:{path}",
|
|
189
218
|
rootMustBeString: "root 必须是字符串(收到 {received})",
|
|
190
219
|
rootRequired: "root 必填,且为工作区绝对路径",
|
|
@@ -197,6 +226,12 @@ const MESSAGES = {
|
|
|
197
226
|
commandTooLong: "zg 命令总长 {length} 超过 {maxChars} 字符上限,请缩小检索范围",
|
|
198
227
|
tooManyQueryRoutes: "检索路由合计 {count} 组,超过 {max} 组上限",
|
|
199
228
|
searchNeedsQuery: "zg_search 需要 query/queries/fts/vector 至少其一",
|
|
229
|
+
exhaustiveNeedsPattern: "穷举检索(rg=true)需要一个 query 作为匹配模式",
|
|
230
|
+
exhaustiveConflicts: "穷举检索(rg=true)与下列索引侧参数互斥:{names}。穷举是纯词法匹配,不支持这些参数;把它们去掉,或先建索引(zg_index)再用索引检索",
|
|
231
|
+
embeddingNotAllowed: "embedding 引用 {reference} 不在本地候选清单内,而本部署未开放远程 embedding。远程 embedding 会把工作区内容送到外部端点,必须由用户在部署配置里显式开放(allowRemoteEmbedding),本插件不接受模型侧开启。可选本地模型:{choices}。若用户确已自行配好远程凭据(zg config provider set / zg auth grant <root> --capability embedding --scope workspace),请在插件部署配置里打开对应开关后重试。",
|
|
232
|
+
dropWithResetPaths: "drop 与 resetPaths 互斥:--drop 整条命令只有删除索引一件事,resetPaths 无处安放(上游 zg 也拒这一对)。要清继承的文件选择设置,请不要传 drop。",
|
|
233
|
+
exhaustiveFallbackNote: "[zvec-grep] 该工作区(含向上各级)尚无 zg 索引,已自动改用穷举词法检索(rg 模式)。结果是逐行字面匹配,不是语义相关度排序;需要语义检索请先 zg_index 建索引。",
|
|
234
|
+
rgDescription: "穷举词法检索(对应 zg query --rg):不需要索引,逐行字面匹配。留空则在工作区无索引时自动改用它、有索引时照常走索引检索。显式 false 可要求只用索引检索(无索引即报错)。它不支持 preview / refresh / fuse / symbolTypes / preferSymbol / fts / vector / queries,且不发放 grep/rg 配额",
|
|
200
235
|
intWithReceived: "{name} 必须是 >= {min} 的整数(收到 {received})",
|
|
201
236
|
intRequired: "{name} 必须是 >= {min} 的整数",
|
|
202
237
|
guardRootRejected: "{name} 的 root 不被接受:{reason}",
|
|
@@ -209,18 +244,20 @@ const MESSAGES = {
|
|
|
209
244
|
},
|
|
210
245
|
en: {
|
|
211
246
|
searchToolDescription: "Semantic/hybrid search (BM25 + vector + RRF) over an indexed workspace, for questions exact lookup cannot answer: architecture, call chains, dependencies, lifecycles, data/control flow, design intent, cross-file comparison and synthesis. root defaults to the current session workspace; you may also name another already-indexed absolute path. Search refreshes the existing index automatically (--refresh wait), so code edited moments ago is searchable without re-running zg_index; a root that was never indexed still fails loudly rather than silently building an index. Every hit carries a **bounded source snippet** (--preview short: anchor line plus a little context) — treat it as read evidence when enough, otherwise read for more context. Use the native grep/glob for exact literal/regex/filename/error-string lookups. Narrow large workspaces with globs/fileTypes or the search may time out. Provide at least one of query/queries/fts/vector. In indexed workspaces grep/rg is gated by search-first: each successful zg_search unlocks grepBudgetPerSearch grep/rg calls for the current session (valid for unlockWindowMin minutes); once the quota is spent or expired, re-search with a more precise query/fts.",
|
|
212
|
-
indexToolDescription: "Create / incrementally update / rebuild / delete the persistent search index for workspace root (zg_search only works after that). Call it only when the user explicitly asks to build/rebuild/drop the index, and confirm must be true; never index silently. root defaults to the current session workspace; another absolute path may be named explicitly (a target the user confirmed). embedding defaults to the configured defaultEmbedding and may be set explicitly; switching embedding only takes effect with rebuild=true. Pass drop=true to delete.",
|
|
247
|
+
indexToolDescription: "Create / incrementally update / rebuild / delete the persistent search index for workspace root (zg_search only works after that). Call it only when the user explicitly asks to build/rebuild/drop the index, and confirm must be true; never index silently. root defaults to the current session workspace; another absolute path may be named explicitly (a target the user confirmed). embedding defaults to the configured defaultEmbedding and may be set explicitly, but **only models in the local catalog are accepted** (remote embedding sends workspace content to an external endpoint and must be enabled explicitly by the user in the deployment config — the model side cannot turn it on); switching embedding only takes effect with rebuild=true. Pass drop=true to delete. Pass resetPaths=true to clear the file-selection settings this root inherited.",
|
|
213
248
|
statusToolDescription: "Query the index status of workspace root (indexed or not, file count, freshness, running jobs). Use it to diagnose a missing/failed/cancelled index or to watch progress explicitly; do not call it before a normal search.",
|
|
214
|
-
rootSearchDescription:
|
|
215
|
-
rootIndexDescription:
|
|
216
|
-
rootStatusDescription:
|
|
249
|
+
rootSearchDescription: ABSOLUTE_ROOT_HINT,
|
|
250
|
+
rootIndexDescription: ABSOLUTE_ROOT_HINT,
|
|
251
|
+
rootStatusDescription: ABSOLUTE_ROOT_HINT,
|
|
217
252
|
queryDescription: "Single hybrid query (semantic + lexical)",
|
|
218
253
|
queriesDescription: "Multiple hybrid query groups",
|
|
219
254
|
ftsDescription: "Lexical query groups (identifiers, error strings)",
|
|
220
255
|
vectorDescription: "Purely semantic query groups",
|
|
221
256
|
fuseDescription: "Fuse all groups into a single ranking",
|
|
222
257
|
limitDescription: "Max hits per group, 1-50, default 10",
|
|
223
|
-
|
|
258
|
+
previewDescription: "How much source each hit carries: none anchor line only, short anchor plus a bounded context window, full the whole chunk. Default short",
|
|
259
|
+
refreshDescription: "How the index is refreshed before searching: wait refresh to the latest (default), off does not refresh, background hands it to the daemon. Note that background only holds in daemon mode; in direct mode zg degrades it to off and says so on stderr",
|
|
260
|
+
globsDescription: "Path globs (e.g. src/**), a single string or an array",
|
|
224
261
|
globsIndexDescription: "Path globs",
|
|
225
262
|
insensitiveGlobsDescription: "Case-insensitive globs",
|
|
226
263
|
fileTypesDescription: "File types (e.g. ts, py)",
|
|
@@ -231,8 +268,9 @@ const MESSAGES = {
|
|
|
231
268
|
modifiedAfterDescription: "Only search files modified after this time",
|
|
232
269
|
modifiedBeforeDescription: "Only search files modified before this time",
|
|
233
270
|
deviceDescription: "auto/cpu/metal/vulkan/cuda; default auto (Metal acceleration, falls back to CPU on failure)",
|
|
271
|
+
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",
|
|
234
272
|
confirmDescription: "The user explicitly asked for this index build/rebuild/drop; must be true",
|
|
235
|
-
embeddingDescription: "Local embedding model reference (defaults to defaultEmbedding setting)",
|
|
273
|
+
embeddingDescription: "Local embedding model reference (defaults to defaultEmbedding setting). Only models in the local catalog are accepted; remote embedding sends workspace content to an external endpoint and must be enabled explicitly by the user in the deployment config — this plugin never lets the model side enable it",
|
|
236
274
|
rebuildDescription: "Rebuild the existing index (must be true when switching embedding)",
|
|
237
275
|
dropDescription: "Delete the index (mutually exclusive with the other index options)",
|
|
238
276
|
ignoreFilesDescription: "Extra ignore-file paths (exclusion lists beyond .gitignore), passed through as zg --ignore-file",
|
|
@@ -248,7 +286,8 @@ const MESSAGES = {
|
|
|
248
286
|
"",
|
|
249
287
|
"Search routing for this environment:",
|
|
250
288
|
"- When the workspace has a zg index (a .zvec-grep/ directory 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.",
|
|
251
|
-
"- Workspaces without an index: exact lookups (a single definition, literals, file names, config keys, error messages, regexes, exhaustive lists)
|
|
289
|
+
"- 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.",
|
|
290
|
+
"- 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.",
|
|
252
291
|
"- 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.",
|
|
253
292
|
"- zg_status is only for diagnosing a missing/failed/cancelled index or explicit progress watching; do not call it before a normal search.",
|
|
254
293
|
"",
|
|
@@ -258,7 +297,7 @@ const MESSAGES = {
|
|
|
258
297
|
"3. Stop searching once the evidence is sufficient; do not repeat similar queries or widen the hunt just to re-confirm.",
|
|
259
298
|
"4. Call zg_index only when the user explicitly asks to build/rebuild/drop the index, and confirm must be true; never index silently.",
|
|
260
299
|
"5. Use the embedding the user picked for a new index; never guess when none was chosen. Switching embedding requires rebuild to take effect.",
|
|
261
|
-
"6. root may be omitted for zg_* tools: it defaults to the current session workspace (absolute path)
|
|
300
|
+
"6. root may be omitted for zg_* tools: it defaults to the current session workspace (absolute path). When passed explicitly it must stay inside this session's operable scope — the workspace itself, its parents or children, or a workspace this session already registered; any other absolute path is rejected."
|
|
262
301
|
].join("\n"),
|
|
263
302
|
argsMustBeObject: "zg {name}: arguments must be a JSON object (received {received})",
|
|
264
303
|
missingRequiredArgs: "zg {name}: missing required arguments {fields} (refused outright, no side effects)",
|
|
@@ -269,8 +308,23 @@ const MESSAGES = {
|
|
|
269
308
|
detailMiddle: "{head} …[middle omitted]… {tail}",
|
|
270
309
|
timeoutFailure: "zg timed out: search defaults to --refresh wait (it refreshes the existing index synchronously), which can take long on large workspaces. Retry with a narrower globs / fileTypes range, or use hand-written grep/glob first.",
|
|
271
310
|
abortedFailure: "zg execution was aborted",
|
|
311
|
+
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.",
|
|
312
|
+
rebuildWaitAborted: "aborted while waiting for the rebuild of {root} to finish",
|
|
313
|
+
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.",
|
|
314
|
+
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}",
|
|
315
|
+
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",
|
|
316
|
+
traceDescription: "For troubleshooting: every hit carries a search trace saying which routes recalled it, its rank in each group, and its score. Output gets noticeably longer; exhaustive (rg) search does not support this parameter",
|
|
317
|
+
indexBackgroundStarted: "Indexing for {root} started in the background (job {jobId}), command: {command}. Until it settles, semantic search on that root waits for it and retries, and grep/rg are not subject to the gate during that window. Use zg_status to check readiness; this call grants no grep/rg quota",
|
|
318
|
+
backgroundDescription: "Run in the background: starts a zg process, hands back a pollable job id and returns immediately. Building an index may download embedding weights and take a long time, so background execution keeps the tool call from hanging. Semantic search on that root waits for it to settle and retries",
|
|
319
|
+
endpointRebuildInFlight: "a rebuild of this workspace is already running; retry shortly.",
|
|
320
|
+
indexRebuildInFlight: "a rebuild of {root} is already running, so this call was not executed — concurrent rebuilds cancel each other. Retry after it finishes, or check it with zg_status.",
|
|
321
|
+
rootNotAuthorized: "root is not authorized: {root} is outside this session's operable scope (session workspace: {cwd}). Only this session's workspace, its parents and children, and workspaces already registered by this session may be searched or indexed. To work on another workspace, ask the user to start a new session there.",
|
|
322
|
+
rootNoSession: "(no session workspace)",
|
|
272
323
|
deniedFailure: "zg failed (exit={exit}): {denied} — this search target is outside what the session may read and write; switch workspace or ask the user to approve a broader file policy. {detail}",
|
|
273
324
|
notInstalledFailure: "zg is not installed or not on PATH: run `npm install -g @zvec/zvec-grep` first. {detail}",
|
|
325
|
+
rootApprovalReason: "the model named {root} for this call, which is neither the current session workspace nor a workspace this session registered (current session workspace: {cwd}). That path reads that directory's content into the conversation context.",
|
|
326
|
+
rootApprovalPrompt: "Allow this one call to build/read the zg index for {root}? Its content enters this session's context, and the permission covers this single call only.",
|
|
327
|
+
zgVersionTooOld: "zg is too old: found {actual}, this plugin requires >= {minimum}. The command shape and flag names this plugin sends are written against that version, and an older zg may execute them as something else — returning results that look normal but searched nothing — so the call stops here before any command is sent. Upgrade with `npm install -g @zvec/zvec-grep@latest`, then retry.",
|
|
274
328
|
genericFailure: "zg failed (exit={exit}){detail}",
|
|
275
329
|
detailPrefix: " details: {detail}",
|
|
276
330
|
detailColon: ": {detail}",
|
|
@@ -278,8 +332,9 @@ const MESSAGES = {
|
|
|
278
332
|
spillNote: " (full output spilled to {path})",
|
|
279
333
|
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.",
|
|
280
334
|
stderrNote: "[zvec-grep] zg stderr (may contain degradation notes, e.g. falling back to pure lexical search / skipping --refresh): {marked}{tail}",
|
|
281
|
-
hitSummary: "[zvec-grep] hit summary: {groups} query group(s), {
|
|
282
|
-
|
|
335
|
+
hitSummary: "[zvec-grep] hit summary: {groups} query group(s), {grouped} hit(s) in grouped counts{dedup}; requested --limit {limit}{capped}{truncated}",
|
|
336
|
+
hitDedup: ", {unique} distinct location(s) after dedup",
|
|
337
|
+
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)",
|
|
283
338
|
hitTruncated: "; output truncated, the count covers only the kept part",
|
|
284
339
|
rootMissing: "root directory does not exist (zg needs a real workspace path): {root}",
|
|
285
340
|
jobOutputTruncated: "\n[zvec-grep] output too long, truncated — only the tail is kept",
|
|
@@ -302,6 +357,10 @@ const MESSAGES = {
|
|
|
302
357
|
mustBeString: "{name} must be a string (received {received})",
|
|
303
358
|
noNulBytes: "{name} must not contain NUL bytes",
|
|
304
359
|
mustBeBoolean: "{name} must be a boolean (received {received})",
|
|
360
|
+
clientModeInvalid: "invalid zg client mode: {received} (allowed: {allowed})",
|
|
361
|
+
previewInvalid: "invalid preview mode: {received} (allowed: {allowed})",
|
|
362
|
+
refreshInvalid: "invalid refresh policy: {received} (allowed: {allowed})",
|
|
363
|
+
symbolTypeInvalid: "invalid symbol type: {received} (allowed: {allowed}; lowercase only)",
|
|
305
364
|
rootEscapesFs: "root contains a .. segment that escapes the filesystem root: {path}",
|
|
306
365
|
rootMustBeString: "root must be a string (received {received})",
|
|
307
366
|
rootRequired: "root is required and must be an absolute workspace path",
|
|
@@ -314,6 +373,12 @@ const MESSAGES = {
|
|
|
314
373
|
commandTooLong: "the zg command is {length} characters, over the {maxChars} character limit — narrow the search",
|
|
315
374
|
tooManyQueryRoutes: "{count} query routes in total, over the limit of {max}",
|
|
316
375
|
searchNeedsQuery: "zg_search needs at least one of query/queries/fts/vector",
|
|
376
|
+
exhaustiveNeedsPattern: "exhaustive search (rg=true) needs a query to use as the pattern",
|
|
377
|
+
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",
|
|
378
|
+
embeddingNotAllowed: "embedding reference {reference} is not in the local catalog, and this deployment has not enabled remote embedding. Remote embedding sends workspace content to an external endpoint and must be turned on explicitly by the user in the deployment config (allowRemoteEmbedding); this plugin never lets the model side enable it. Local choices: {choices}. If the user has already set up remote credentials themselves (zg config provider set / zg auth grant <root> --capability embedding --scope workspace), enable the matching deployment setting and retry.",
|
|
379
|
+
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.",
|
|
380
|
+
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.",
|
|
381
|
+
rgDescription: "Exhaustive lexical search (zg query --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, and it grants no grep/rg quota",
|
|
317
382
|
intWithReceived: "{name} must be an integer >= {min} (received {received})",
|
|
318
383
|
intRequired: "{name} must be an integer >= {min}",
|
|
319
384
|
guardRootRejected: "the root given to {name} is not accepted: {reason}",
|
|
@@ -344,11 +409,11 @@ function fill(template, params) {
|
|
|
344
409
|
//#region lib/argv-guard.ts
|
|
345
410
|
const MAX_COMMAND_BYTES = 64e3;
|
|
346
411
|
/** 单条 query 文本上限(再长属误用:zg 的语义检索按句切分)。 */
|
|
347
|
-
const MAX_QUERY_CHARS =
|
|
412
|
+
const MAX_QUERY_CHARS = 4e3;
|
|
348
413
|
/** 过滤类数组(globs/types/…)单项条数上限。只在本模块作 `stringList` 的缺省档,不外露。 */
|
|
349
|
-
const MAX_FILTER_ITEMS =
|
|
414
|
+
const MAX_FILTER_ITEMS = 128;
|
|
350
415
|
/** 过滤类数组单项长度上限(glob 不该长成文章)。 */
|
|
351
|
-
const MAX_FILTER_CHARS =
|
|
416
|
+
const MAX_FILTER_CHARS = 1024;
|
|
352
417
|
/** POSIX sh 单引号转义:' → '\''。把任意字符串安全放进单引号内,防注入。 */
|
|
353
418
|
function shq(value) {
|
|
354
419
|
return `'${value.replaceAll("'", String.raw`'\''`)}'`;
|
|
@@ -401,11 +466,33 @@ function stringList(value, name, messages, maxItems = MAX_FILTER_ITEMS, maxChars
|
|
|
401
466
|
return out;
|
|
402
467
|
}
|
|
403
468
|
/**
|
|
469
|
+
* 路径过滤类参数的取值:单值与数组两种形态都收,规范化成数组后交给 `stringList` 走同
|
|
470
|
+
* 一套校验(trim / 去空串 / NUL / 条数 / 长度)。
|
|
471
|
+
*
|
|
472
|
+
* 兼容单值是因为上游就这么收:zg 自己的对外契约里 globs / insensitiveGlobs / fileTypes /
|
|
473
|
+
* excludedFileTypes / ignoreFiles 都是「一个字符串或一个字符串数组」的并集,只收数组
|
|
474
|
+
* 会让模型按上游习惯写单个 glob 时撞上「必须是字符串数组」——形状没错、形状太严。
|
|
475
|
+
* 其余类型错误(非字符串、非数组的其它值)仍然照旧报错,不做任何静默降级。
|
|
476
|
+
*/
|
|
477
|
+
function singleOrList(value, name, messages, maxItems = MAX_FILTER_ITEMS, maxChars = MAX_FILTER_CHARS) {
|
|
478
|
+
return stringList(typeof value === "string" ? [value] : value, name, messages, maxItems, maxChars);
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
404
481
|
* 默认密钥排除:只收无歧义的私钥/密钥库格式(实测这类文件常既不在
|
|
405
482
|
* .gitignore、也不以 `.` 开头,会躲过 zg 默认规则被索引,把私钥带进向量库并
|
|
406
483
|
* 可能回显到模型上下文)。刻意不含 `*secret*` / `*credential*` 这类宽泛词
|
|
407
484
|
* 模式——它们会误伤正常源码与文档,造成"为什么搜不到"的隐性困惑。
|
|
408
|
-
*
|
|
485
|
+
*
|
|
486
|
+
* 这里只给**模式**,用哪个旗标发出由调用方决定:调用方必须以大小写不敏感形式
|
|
487
|
+
* (--iglob)发出并排在用户规则之后。实测 `.p12` / `.pfx` / `.keystore` 都有混合
|
|
488
|
+
* 大小写变体(`secret.P12` / `secret.PfX` / `secret.KEYSTORE` 皆会入索引),
|
|
489
|
+
* 大小写敏感的 `--glob` 排除不掉;`id_rsa*` 这类无扩展名规则还额外依赖「排在
|
|
490
|
+
* 用户正向 --iglob 之后」才能不被覆盖。详见 lib/cli.ts 的 pushIndexGlobs。
|
|
491
|
+
*
|
|
492
|
+
* 残留缺口:扩展名规则覆盖不到无扩展名的密钥文件(如 `myprivatekey`、
|
|
493
|
+
* `rsa_private`),id_rsa* / id_ed25519* 只覆盖 OpenSSH 默认命名。这类文件需走
|
|
494
|
+
* ignoreFiles(--ignore-file),由使用者显式声明,不在此处用宽泛词模式兜底。
|
|
495
|
+
* excludeSecrets=false 可整体关闭。
|
|
409
496
|
*/
|
|
410
497
|
const SECRET_EXCLUDE_GLOBS = [
|
|
411
498
|
"!*.pem",
|
|
@@ -420,6 +507,99 @@ const SECRET_EXCLUDE_GLOBS = [
|
|
|
420
507
|
//#region lib/cli.ts
|
|
421
508
|
const LIMIT_MIN = 1;
|
|
422
509
|
const LIMIT_MAX = 50;
|
|
510
|
+
const CLIENT_MODE_NAMES = Object.keys({
|
|
511
|
+
auto: "auto",
|
|
512
|
+
direct: "direct",
|
|
513
|
+
server: "server"
|
|
514
|
+
});
|
|
515
|
+
/** 缺省传输模式:有守护进程就用守护进程,没有就直连。 */
|
|
516
|
+
const DEFAULT_CLIENT_MODE = "auto";
|
|
517
|
+
/** 类型谓词(不是类型断言):把 string 收窄到模式域,供取值器零断言收窄。 */
|
|
518
|
+
function isClientMode(value) {
|
|
519
|
+
return CLIENT_MODE_NAMES.includes(value);
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* 传输模式取值器:缺省回缺省域,其余非本域取值一律报错。
|
|
523
|
+
* 宿主侧配置已由 schema 校验过,这道取值器是命令行构造边界的最后一道闸,与同文件其余
|
|
524
|
+
* 取值器同一口径——绝不把一个守护进程并不认识的模式串静默拼进命令。
|
|
525
|
+
*/
|
|
526
|
+
function clientModeOf(value, messages) {
|
|
527
|
+
if (value === void 0 || value === null) return DEFAULT_CLIENT_MODE;
|
|
528
|
+
if (typeof value !== "string" || !isClientMode(value)) throw new TypeError(fill(messages.clientModeInvalid, {
|
|
529
|
+
received: typeof value === "string" ? value : typeof value,
|
|
530
|
+
allowed: CLIENT_MODE_NAMES.join(" | ")
|
|
531
|
+
}));
|
|
532
|
+
return value;
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* 传输模式旗标。取值来自闭集且已由取值器校验过,不含用户可控字符,故不加引号——与设备
|
|
536
|
+
* 旗标不同,那一枚的值由用户直接给出,必须转义。
|
|
537
|
+
*/
|
|
538
|
+
function modeFlag(mode) {
|
|
539
|
+
return `--mode ${mode}`;
|
|
540
|
+
}
|
|
541
|
+
/** 合法预览档位名单,外供工具参数面的 JSON Schema `enum`,与取值器同一份来源。 */
|
|
542
|
+
const PREVIEW_NAMES = Object.keys({
|
|
543
|
+
none: "none",
|
|
544
|
+
short: "short",
|
|
545
|
+
full: "full"
|
|
546
|
+
});
|
|
547
|
+
/** 缺省预览档位:有界源码窗口,既不空手而归也不撑爆上下文。 */
|
|
548
|
+
const DEFAULT_PREVIEW = "short";
|
|
549
|
+
function isPreviewMode(value) {
|
|
550
|
+
return PREVIEW_NAMES.includes(value);
|
|
551
|
+
}
|
|
552
|
+
function previewOf(value, messages) {
|
|
553
|
+
if (value === void 0 || value === null) return DEFAULT_PREVIEW;
|
|
554
|
+
if (typeof value !== "string" || !isPreviewMode(value)) throw new TypeError(fill(messages.previewInvalid, {
|
|
555
|
+
received: typeof value === "string" ? value : typeof value,
|
|
556
|
+
allowed: PREVIEW_NAMES.join(" | ")
|
|
557
|
+
}));
|
|
558
|
+
return value;
|
|
559
|
+
}
|
|
560
|
+
/** 合法刷新策略名单,外供工具参数面的 JSON Schema `enum`,与取值器同一份来源。 */
|
|
561
|
+
const REFRESH_NAMES = Object.keys({
|
|
562
|
+
background: "background",
|
|
563
|
+
wait: "wait",
|
|
564
|
+
off: "off"
|
|
565
|
+
});
|
|
566
|
+
/** 缺省刷新策略:等索引刷到最新再检索(索引刚被本插件重建过时,这一条尤其重要)。 */
|
|
567
|
+
const DEFAULT_REFRESH = "wait";
|
|
568
|
+
function isRefreshPolicy(value) {
|
|
569
|
+
return REFRESH_NAMES.includes(value);
|
|
570
|
+
}
|
|
571
|
+
function refreshOf(value, messages) {
|
|
572
|
+
if (value === void 0 || value === null) return DEFAULT_REFRESH;
|
|
573
|
+
if (typeof value !== "string" || !isRefreshPolicy(value)) throw new TypeError(fill(messages.refreshInvalid, {
|
|
574
|
+
received: typeof value === "string" ? value : typeof value,
|
|
575
|
+
allowed: REFRESH_NAMES.join(" | ")
|
|
576
|
+
}));
|
|
577
|
+
return value;
|
|
578
|
+
}
|
|
579
|
+
/** 合法符号类型名单,外供工具参数面的 JSON Schema `enum`,与取值器同一份来源。 */
|
|
580
|
+
const SYMBOL_TYPE_NAMES = Object.keys({
|
|
581
|
+
module: "module",
|
|
582
|
+
class: "class",
|
|
583
|
+
interface: "interface",
|
|
584
|
+
function: "function",
|
|
585
|
+
value: "value",
|
|
586
|
+
alias: "alias"
|
|
587
|
+
});
|
|
588
|
+
function isSymbolType(value) {
|
|
589
|
+
return SYMBOL_TYPE_NAMES.includes(value);
|
|
590
|
+
}
|
|
591
|
+
/** 符号类型取值器:空缺省空数组,逐项校闭集(不是逐项静默丢弃)。 */
|
|
592
|
+
function symbolTypesOf(value, messages) {
|
|
593
|
+
const out = [];
|
|
594
|
+
for (const item of stringList(value, "symbolTypes", messages)) {
|
|
595
|
+
if (!isSymbolType(item)) throw new TypeError(fill(messages.symbolTypeInvalid, {
|
|
596
|
+
received: item,
|
|
597
|
+
allowed: SYMBOL_TYPE_NAMES.join(" | ")
|
|
598
|
+
}));
|
|
599
|
+
out.push(item);
|
|
600
|
+
}
|
|
601
|
+
return out;
|
|
602
|
+
}
|
|
423
603
|
/**
|
|
424
604
|
* 归一化 zg 的设备参数:显式传入用显式值,否则默认 auto(让 llama.cpp 自探测
|
|
425
605
|
* Metal GPU,失败自动回退 CPU)。auto/cpu/metal/vulkan/cuda 之外的非法值由
|
|
@@ -429,7 +609,15 @@ function deviceFlag(value, messages) {
|
|
|
429
609
|
const raw = optionalText(value, "device", messages, MAX_FILTER_CHARS);
|
|
430
610
|
return `--device ${shq(raw.length > 0 ? raw : "auto")}`;
|
|
431
611
|
}
|
|
432
|
-
/**
|
|
612
|
+
/**
|
|
613
|
+
* 布尔旗标严格取值:缺省回 fallback,非布尔即报错(`1`/`"true"` 不算真)。
|
|
614
|
+
*
|
|
615
|
+
* 导出的原因:宿主侧有几处**要拿布尔值本身做分支决策**(这次调用是后台还是前台、
|
|
616
|
+
* 这次是重建还是增量、这次查询带不带就绪判定),那些地方若写 `args["x"] === true`,
|
|
617
|
+
* 一个 `1` 或 `"true"` 就会静默走成 false——而参数面下方恰好声明着 `type: "boolean"`。
|
|
618
|
+
* 框架**不会**替我们兜这一层:宿主对 `parameters` 只在注册时做「输出」schema 检查,
|
|
619
|
+
* 入参原样交给 execute(本文件 define 一处的注释与 lib/cli.ts 的头注释都记着这件事)。
|
|
620
|
+
*/
|
|
433
621
|
function boolOf(value, name, messages, fallback = false) {
|
|
434
622
|
if (value === void 0 || value === null) return fallback;
|
|
435
623
|
if (typeof value !== "boolean") throw new TypeError(fill(messages.mustBeBoolean, {
|
|
@@ -529,39 +717,100 @@ function pushQueryArgs(parts, args, messages) {
|
|
|
529
717
|
dashGuard
|
|
530
718
|
};
|
|
531
719
|
}
|
|
532
|
-
/**
|
|
720
|
+
/**
|
|
721
|
+
* 路径过滤(glob / iglob / type / type-not)。三条通道共用:实测索引检索、索引命令与
|
|
722
|
+
* 穷举检索(`--rg`)下这四类旗标都被 zg 接受,故只在这里发一次。
|
|
723
|
+
*/
|
|
724
|
+
function pushPathFilters(parts, args, messages) {
|
|
725
|
+
for (const glob of singleOrList(args.globs, "globs", messages)) parts.push("--glob", shq(glob));
|
|
726
|
+
for (const glob of singleOrList(args.insensitiveGlobs, "insensitiveGlobs", messages)) parts.push("--iglob", shq(glob));
|
|
727
|
+
for (const typeName of singleOrList(args.fileTypes, "fileTypes", messages)) parts.push("--type", shq(typeName));
|
|
728
|
+
for (const typeName of singleOrList(args.excludedFileTypes, "excludedFileTypes", messages)) parts.push("--type-not", shq(typeName));
|
|
729
|
+
}
|
|
730
|
+
/** 时间过滤:两条检索通道共用(实测 `--modified-after` 在 `--rg` 下被接受)。 */
|
|
731
|
+
function pushTimeFilters(parts, args, messages) {
|
|
732
|
+
const after = optionalText(args.modifiedAfter, "modifiedAfter", messages, MAX_FILTER_CHARS);
|
|
733
|
+
if (after.length > 0) parts.push("--modified-after", shq(after));
|
|
734
|
+
const before = optionalText(args.modifiedBefore, "modifiedBefore", messages, MAX_FILTER_CHARS);
|
|
735
|
+
if (before.length > 0) parts.push("--modified-before", shq(before));
|
|
736
|
+
}
|
|
737
|
+
/** 追加检索过滤 globs(路径过滤 + 仅索引通道支持的符号类型)。 */
|
|
533
738
|
function pushSearchGlobs(parts, args, messages) {
|
|
534
|
-
|
|
535
|
-
for (const
|
|
536
|
-
for (const typeName of stringList(args.fileTypes, "fileTypes", messages)) parts.push("--type", shq(typeName));
|
|
537
|
-
for (const typeName of stringList(args.excludedFileTypes, "excludedFileTypes", messages)) parts.push("--type-not", shq(typeName));
|
|
538
|
-
for (const symbolKind of stringList(args.symbolTypes, "symbolTypes", messages)) parts.push("--symbol-type", shq(symbolKind));
|
|
739
|
+
pushPathFilters(parts, args, messages);
|
|
740
|
+
for (const symbolKind of symbolTypesOf(args.symbolTypes, messages)) parts.push("--symbol-type", shq(symbolKind));
|
|
539
741
|
}
|
|
540
742
|
/** 取单条 query 的原文(与 pushQueryArgs 同一取值器,保证 dashGuard 两侧一致)。 */
|
|
541
743
|
function singleText(args, messages) {
|
|
542
744
|
return optionalText(args.query, "query", messages, MAX_QUERY_CHARS);
|
|
543
745
|
}
|
|
544
|
-
|
|
545
|
-
* 构造 zg query 命令。注意:zg query 没有 --root,root 来自进程 cwd,
|
|
546
|
-
* 所以 root 只作为 workdir 返回,绝不进入命令行。
|
|
547
|
-
*/
|
|
548
|
-
function buildSearchCommand(args, messages) {
|
|
549
|
-
const root = assertAbsoluteRoot(args.root, messages);
|
|
746
|
+
function buildIndexedCommand(args, root, messages, mode) {
|
|
550
747
|
const parts = ["zg", "query"];
|
|
551
748
|
const { routeCount, dashGuard } = pushQueryArgs(parts, args, messages);
|
|
552
749
|
if (routeCount === 0) throw new Error(messages.searchNeedsQuery);
|
|
553
750
|
if (boolOf(args.fuse, "fuse", messages)) parts.push("--fuse");
|
|
554
|
-
parts.push("--limit", String(clampLimit(args.limit)), "--preview",
|
|
751
|
+
parts.push("--limit", String(clampLimit(args.limit)), "--preview", previewOf(args.preview, messages), "--refresh", refreshOf(args.refresh, messages));
|
|
555
752
|
pushSearchGlobs(parts, args, messages);
|
|
556
753
|
if (boolOf(args.preferSymbol, "preferSymbol", messages)) parts.push("--prefer-symbol");
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
if (before.length > 0) parts.push("--modified-before", shq(before));
|
|
561
|
-
parts.push(deviceFlag(args.device, messages), "--mode", "direct");
|
|
754
|
+
if (boolOf(args.trace, "trace", messages)) parts.push("--trace");
|
|
755
|
+
pushTimeFilters(parts, args, messages);
|
|
756
|
+
parts.push(deviceFlag(args.device, messages), modeFlag(mode));
|
|
562
757
|
if (dashGuard) parts.push("--", shq(singleText(args, messages)));
|
|
563
758
|
return assembled(parts, root, messages);
|
|
564
759
|
}
|
|
760
|
+
/**
|
|
761
|
+
* 穷举模式下 zg 明确拒绝的索引侧旗标,逐个拦在构造阶段。实测报错原文:
|
|
762
|
+
* `--preview` → "--preview is not supported with --rg; use -A/-B/-C for rg context"
|
|
763
|
+
* `--refresh` → "--rg cannot be combined with indexed refresh options"
|
|
764
|
+
* `--symbol-type` / `--prefer-symbol` → "--rg cannot be combined with indexed symbol options"
|
|
765
|
+
* `--fuse` → "--rg cannot be combined with --fuse"
|
|
766
|
+
* `--trace` → "--rg cannot be combined with --trace"
|
|
767
|
+
* `--fts` / `--vector` → "--rg cannot be combined with --hybrid, --fts, or --vector"
|
|
768
|
+
* 与其把模型交给一次子进程失败再原样回显 zg 的英文报错,不如在构造阶段就用本包的
|
|
769
|
+
* 双语文案说清「这些是索引侧参数」——并且**不静默丢弃**用户给的那一项。
|
|
770
|
+
*/
|
|
771
|
+
function assertExhaustiveArgs(args, messages) {
|
|
772
|
+
const conflicts = [];
|
|
773
|
+
if (boolOf(args.fuse, "fuse", messages)) conflicts.push("fuse");
|
|
774
|
+
if (queryList(args.queries, "queries", messages).length > 0) conflicts.push("queries");
|
|
775
|
+
if (queryList(args.fts, "fts", messages).length > 0) conflicts.push("fts");
|
|
776
|
+
if (queryList(args.vector, "vector", messages).length > 0) conflicts.push("vector");
|
|
777
|
+
if (optionalText(args.preview, "preview", messages, 1024).length > 0) conflicts.push("preview");
|
|
778
|
+
if (optionalText(args.refresh, "refresh", messages, 1024).length > 0) conflicts.push("refresh");
|
|
779
|
+
if (stringList(args.symbolTypes, "symbolTypes", messages).length > 0) conflicts.push("symbolTypes");
|
|
780
|
+
if (boolOf(args.preferSymbol, "preferSymbol", messages)) conflicts.push("preferSymbol");
|
|
781
|
+
if (boolOf(args.trace, "trace", messages)) conflicts.push("trace");
|
|
782
|
+
if (conflicts.length > 0) throw new Error(fill(messages.exhaustiveConflicts, { names: conflicts.join(" | ") }));
|
|
783
|
+
}
|
|
784
|
+
/** 穷举词法通道(`zg query --rg`)。与索引通道的合法旗标集合不同,见 assertExhaustiveArgs。 */
|
|
785
|
+
function buildExhaustiveCommand(args, root, messages, mode) {
|
|
786
|
+
assertExhaustiveArgs(args, messages);
|
|
787
|
+
const parts = [
|
|
788
|
+
"zg",
|
|
789
|
+
"query",
|
|
790
|
+
"--rg"
|
|
791
|
+
];
|
|
792
|
+
const pattern = optionalText(args.query, "query", messages, MAX_QUERY_CHARS);
|
|
793
|
+
if (pattern.length === 0) throw new Error(messages.exhaustiveNeedsPattern);
|
|
794
|
+
if (pattern.startsWith("-")) parts.push("-e", shq(pattern));
|
|
795
|
+
else parts.push(shq(pattern));
|
|
796
|
+
parts.push("--limit", String(clampLimit(args.limit)));
|
|
797
|
+
pushPathFilters(parts, args, messages);
|
|
798
|
+
pushTimeFilters(parts, args, messages);
|
|
799
|
+
parts.push(deviceFlag(args.device, messages), modeFlag(mode));
|
|
800
|
+
return assembled(parts, root, messages);
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* 构造 zg query 命令。注意:zg query 没有 --root,root 来自进程 cwd,
|
|
804
|
+
* 所以 root 只作为 workdir 返回,绝不进入命令行。
|
|
805
|
+
*
|
|
806
|
+
* `exhaustive` 走 zg 的穷举词法通道(`--rg`):不需要索引,是「工作区尚无索引」时的
|
|
807
|
+
* 首选路径。选哪条路由由**宿主**判(它才有索引探测能力),本纯函数只按判据构造——
|
|
808
|
+
* 判据见 host.ts 的 pickExhaustive。
|
|
809
|
+
*/
|
|
810
|
+
function buildSearchCommand(args, messages, mode = DEFAULT_CLIENT_MODE, exhaustive = false) {
|
|
811
|
+
const root = assertAbsoluteRoot(args.root, messages);
|
|
812
|
+
return exhaustive ? buildExhaustiveCommand(args, root, messages, mode) : buildIndexedCommand(args, root, messages, mode);
|
|
813
|
+
}
|
|
565
814
|
/** 非负/正整数字符串化;非数值类型或非整数报错(`true` 不算 1)。 */
|
|
566
815
|
function intFlag(value, name, messages, min) {
|
|
567
816
|
if (typeof value !== "number" && typeof value !== "string") throw new TypeError(fill(messages.intWithReceived, {
|
|
@@ -597,15 +846,25 @@ function pushIndexBoolFlags(parts, flags) {
|
|
|
597
846
|
/**
|
|
598
847
|
* 追加索引过滤 globs 与密钥排除(内部顺序固定:globs → iglob → type →
|
|
599
848
|
* type-not → 密钥排除 → ignore-file)。
|
|
600
|
-
*
|
|
849
|
+
*
|
|
850
|
+
* 密钥排除走 --iglob 而非 --glob,两个原因都是实测得来的:
|
|
851
|
+
* - 扩展名大小写:真正会被索引的密钥库格式里,`.p12` / `.pfx` / `.keystore` 都存在
|
|
852
|
+
* 混合大小写变体(`secret.P12`、`secret.PfX`、`secret.KEYSTORE` 皆实测入索引)。
|
|
853
|
+
* --glob 的 `!*.p12` 匹配不到 `secret.P12`,--iglob 走大小写不敏感匹配才能全部排除。
|
|
854
|
+
* (`.pem` 不在此列:它本就不在 zg 的可索引类型里,不下发任何规则也不会进索引。)
|
|
855
|
+
* - 规则次序:引擎把全部 --glob 规则排在全部 --iglob 规则之前有序求值。密钥规则若
|
|
856
|
+
* 用 --glob,用户一条宽泛的正向 --iglob(如 `**`)会在其后求值并把无扩展名的
|
|
857
|
+
* `id_rsa*` 救回索引(实测「被索引」);用 --iglob 且排在本函数最后(用户 iglob
|
|
858
|
+
* 之后),任何用户正向规则都无法覆盖它。
|
|
859
|
+
* 纯 `!` 取反已实测可独立工作。excludeSecrets=false 可整体关闭。
|
|
601
860
|
*/
|
|
602
861
|
function pushIndexGlobs(parts, args, flags, messages) {
|
|
603
|
-
for (const glob of
|
|
604
|
-
for (const glob of
|
|
605
|
-
for (const typeName of
|
|
606
|
-
for (const typeName of
|
|
607
|
-
if (flags.excludeSecrets) for (const glob of SECRET_EXCLUDE_GLOBS) parts.push("--
|
|
608
|
-
for (const filePath of
|
|
862
|
+
for (const glob of singleOrList(args.globs, "globs", messages)) parts.push("--glob", shq(glob));
|
|
863
|
+
for (const glob of singleOrList(args.insensitiveGlobs, "insensitiveGlobs", messages)) parts.push("--iglob", shq(glob));
|
|
864
|
+
for (const typeName of singleOrList(args.fileTypes, "fileTypes", messages)) parts.push("--type", shq(typeName));
|
|
865
|
+
for (const typeName of singleOrList(args.excludedFileTypes, "excludedFileTypes", messages)) parts.push("--type-not", shq(typeName));
|
|
866
|
+
if (flags.excludeSecrets) for (const glob of SECRET_EXCLUDE_GLOBS) parts.push("--iglob", shq(glob));
|
|
867
|
+
for (const filePath of singleOrList(args.ignoreFiles, "ignoreFiles", messages)) parts.push("--ignore-file", shq(filePath));
|
|
609
868
|
}
|
|
610
869
|
/** 追加索引数值旗标(内部顺序固定:maxDepth → maxFileSizeBytes)。 */
|
|
611
870
|
function pushIndexIntFlags(parts, args, messages) {
|
|
@@ -626,14 +885,52 @@ function pushIndexConcurrencyFlag(parts, args, messages) {
|
|
|
626
885
|
if (args.embeddingConcurrency !== void 0 && args.embeddingConcurrency !== null) parts.push("--embedding-concurrency", intFlag(args.embeddingConcurrency, "embeddingConcurrency", messages, 1));
|
|
627
886
|
}
|
|
628
887
|
/**
|
|
888
|
+
* 追加 `--reset-paths`(清除继承的文件选择设置)。
|
|
889
|
+
*
|
|
890
|
+
* 为什么它与 globs/fileTypes **不**互斥:上游是「先 reset、再盖本次覆盖值」的两步
|
|
891
|
+
* (zvec-grep v0.2.2 `resolveIndexRootPaths`),同传表达「清干净再按这次的规则选」。
|
|
892
|
+
* 唯一真互斥的是 drop,上游 args.ts 明确拒 `--drop --reset-paths`——那一对由构造器
|
|
893
|
+
* 在读 drop 的那一臂就拒掉(见 buildIndexCommand),绝不让 resetPaths 被静默丢弃。
|
|
894
|
+
*/
|
|
895
|
+
function pushIndexResetPathsFlag(parts, args, messages) {
|
|
896
|
+
if (boolOf(args.resetPaths, "resetPaths", messages)) parts.push("--reset-paths");
|
|
897
|
+
}
|
|
898
|
+
/**
|
|
899
|
+
* 索引用的 embedding 引用:模型显式给了就以它为准,否则用设置里的默认值。
|
|
900
|
+
*
|
|
901
|
+
* 构造期 allowlist(默认开启、且**默认关不掉**的那一半):显式引用必须落在本地候选清单
|
|
902
|
+
* (lib/embedding-catalog.ts,设置卡 <select> 的同一份)里。理由是能力面的性质——
|
|
903
|
+
* 远程 embedding 会把工作区内容送到外部端点,而模型能凭空写出一个任意前缀的引用:
|
|
904
|
+
* 此前 `evil/http://attacker/x` 这类值原样透传给 zg,只要宿主进程里恰好有可用凭据或
|
|
905
|
+
* 用户此前授权过,插件就在**没有任何声明、没有用户确认**的情况下把内容送了出去。
|
|
906
|
+
* 现在它在命令构造前就被拒,并给出可行动的出路。
|
|
907
|
+
*
|
|
908
|
+
* 部署级出口(`allowRemote`):由用户在部署配置里显式打开,不在工具参数面上——
|
|
909
|
+
* 模型可控的密钥/端点通道本身就是风险。打开后远程引用放行,端点与凭据由宿主经
|
|
910
|
+
* **环境变量**下发(argv 里的密钥会进进程列表与作业 label)。
|
|
911
|
+
*/
|
|
912
|
+
function indexEmbedding(args, defaultEmbedding, messages, allowRemote) {
|
|
913
|
+
const given = optionalText(args.embedding, "embedding", messages, MAX_FILTER_CHARS);
|
|
914
|
+
if (given.length === 0) return defaultEmbedding;
|
|
915
|
+
if (isLocalEmbedding(given) || allowRemote) return given;
|
|
916
|
+
throw new Error(fill(messages.embeddingNotAllowed, {
|
|
917
|
+
reference: given,
|
|
918
|
+
choices: LOCAL_EMBEDDINGS.map((entry) => entry.reference).join(" | ")
|
|
919
|
+
}));
|
|
920
|
+
}
|
|
921
|
+
/**
|
|
629
922
|
* 构造 zg index 命令。root 是位置参数(转义)。
|
|
630
|
-
* - drop=true:`zg index <root> --drop --yes --mode
|
|
631
|
-
* - 否则:`zg index <root> --embedding <m> [--rebuild] ... --mode
|
|
632
|
-
* embedding 缺省时由调用方传入 defaultEmbedding
|
|
923
|
+
* - drop=true:`zg index <root> --drop --yes --mode <mode>`(非交互 shell 必须 --yes)。
|
|
924
|
+
* - 否则:`zg index <root> --embedding <m> [--rebuild] ... --mode <mode>`。
|
|
925
|
+
* embedding 缺省时由调用方传入 defaultEmbedding(设置里的默认值);显式值过构造期
|
|
926
|
+
* allowlist(见 indexEmbedding)。
|
|
927
|
+
* 传输模式与检索、状态共用同一个入参:三条命令混用模式会在守护进程持有索引租约时
|
|
928
|
+
* 让写侧直接失败,故一致性由构造器的必填入参强制。
|
|
633
929
|
* 旗标顺序与 filter globs 交错固定(rebuild → globs → hidden → no-ignore →
|
|
634
|
-
* max-depth → max-filesize → follow → embedding-concurrency
|
|
930
|
+
* max-depth → max-filesize → follow → embedding-concurrency → reset-paths),
|
|
931
|
+
* 不得重排(测试锁死)。
|
|
635
932
|
*/
|
|
636
|
-
function buildIndexCommand(args, defaultEmbedding, messages) {
|
|
933
|
+
function buildIndexCommand(args, defaultEmbedding, messages, mode = DEFAULT_CLIENT_MODE, allowRemote = false) {
|
|
637
934
|
const root = assertAbsoluteRoot(args.root, messages);
|
|
638
935
|
const parts = [
|
|
639
936
|
"zg",
|
|
@@ -642,31 +939,40 @@ function buildIndexCommand(args, defaultEmbedding, messages) {
|
|
|
642
939
|
];
|
|
643
940
|
const flags = readIndexFlags(args, messages);
|
|
644
941
|
if (boolOf(args.drop, "drop", messages)) {
|
|
645
|
-
|
|
942
|
+
if (boolOf(args.resetPaths, "resetPaths", messages)) throw new Error(messages.dropWithResetPaths);
|
|
943
|
+
parts.push("--drop", "--yes", modeFlag(mode));
|
|
646
944
|
return assembled(parts, root, messages);
|
|
647
945
|
}
|
|
648
|
-
|
|
649
|
-
const embedding = given.length > 0 ? given : defaultEmbedding;
|
|
650
|
-
parts.push("--embedding", shq(embedding));
|
|
946
|
+
parts.push("--embedding", shq(indexEmbedding(args, defaultEmbedding, messages, allowRemote)));
|
|
651
947
|
pushIndexBoolFlags(parts, flags);
|
|
652
948
|
pushIndexGlobs(parts, args, flags, messages);
|
|
653
949
|
pushIndexHideFlags(parts, flags);
|
|
654
950
|
pushIndexIntFlags(parts, args, messages);
|
|
655
951
|
pushIndexFollowFlag(parts, flags);
|
|
656
952
|
pushIndexConcurrencyFlag(parts, args, messages);
|
|
657
|
-
parts
|
|
953
|
+
pushIndexResetPathsFlag(parts, args, messages);
|
|
954
|
+
parts.push(deviceFlag(args.device, messages), modeFlag(mode));
|
|
658
955
|
return assembled(parts, root, messages);
|
|
659
956
|
}
|
|
660
|
-
/**
|
|
661
|
-
|
|
957
|
+
/**
|
|
958
|
+
* 构造 zg status 命令(root 位置参数;传输模式与另两条命令同源)。
|
|
959
|
+
*
|
|
960
|
+
* `checkReady` 透传 `--check-ready`:zg 的帮助原文是「preserves the normal output and
|
|
961
|
+
* exits non-zero unless the Workspace index is ready」——即**就绪报告照常打在 stdout,
|
|
962
|
+
* 只用退出码表达就绪与否**。所以宿主侧必须成对处理这两半:报告要交回,退出码要翻译成
|
|
963
|
+
* 结论,不能像普通失败那样只留 stderr 把 stdout 丢掉(实测未就绪时 stdout 正是那份
|
|
964
|
+
* 「? Workspace index is not configured … Next: zg index or zg query --rg」报告)。
|
|
965
|
+
*/
|
|
966
|
+
function buildStatusCommand(args, messages, mode = DEFAULT_CLIENT_MODE) {
|
|
662
967
|
const root = assertAbsoluteRoot(args.root, messages);
|
|
663
|
-
|
|
968
|
+
const parts = [
|
|
664
969
|
"zg",
|
|
665
970
|
"status",
|
|
666
|
-
shq(root)
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
971
|
+
shq(root)
|
|
972
|
+
];
|
|
973
|
+
if (boolOf(args.checkReady, "checkReady", messages)) parts.push("--check-ready");
|
|
974
|
+
parts.push(modeFlag(mode));
|
|
975
|
+
return assembled(parts, root, messages);
|
|
670
976
|
}
|
|
671
977
|
//#endregion
|
|
672
978
|
//#region lib/search-predicates.ts
|
|
@@ -872,6 +1178,23 @@ function hasExternalTarget(root, command, messages) {
|
|
|
872
1178
|
function unlockActive(unlock, now) {
|
|
873
1179
|
return unlock !== void 0 && unlock.grepsLeft > 0 && now < unlock.expiresAt;
|
|
874
1180
|
}
|
|
1181
|
+
/**
|
|
1182
|
+
* 两个路径是否落在**同一棵树**里(互为祖先/后代,按路径段比)。
|
|
1183
|
+
*
|
|
1184
|
+
* 授权判据用它:会话工作区是 `/repo/packages/app` 时,模型显式指定 `/repo` 或
|
|
1185
|
+
* `/repo/packages/app/src` 都属「这棵树之内」,不该被当成越界;而 `/etc`、用户家目录
|
|
1186
|
+
* 或另一棵仓都与它无祖先关系,据此拒掉。
|
|
1187
|
+
*
|
|
1188
|
+
* 与门禁那边的 `pathInsideRoot` 是反向的一问:那边判「目标是否在 root 之内」,
|
|
1189
|
+
* 这边判「两者是否相关」,任一方向成立即可。
|
|
1190
|
+
* @param left 第一个路径
|
|
1191
|
+
* @param right 第二个路径
|
|
1192
|
+
* @param messages 文案表(归一化异常时喂给它,异常文本在此被丢弃,出界才是结论)
|
|
1193
|
+
* @returns 是否互为祖先/后代
|
|
1194
|
+
*/
|
|
1195
|
+
function pathsRelated(left, right, messages) {
|
|
1196
|
+
return pathInsideRoot(left, right, messages) || pathInsideRoot(right, left, messages);
|
|
1197
|
+
}
|
|
875
1198
|
//#endregion
|
|
876
1199
|
//#region lib/routing.ts
|
|
877
1200
|
/** 紧跟 TOOL_GREP(1500) 之后、TOOL_JOBS(1600) 之前。 */
|
|
@@ -893,7 +1216,12 @@ const ZG_TOOL_NAMES = /* @__PURE__ */ new Set([
|
|
|
893
1216
|
"zg_index",
|
|
894
1217
|
"zg_status"
|
|
895
1218
|
]);
|
|
896
|
-
/**
|
|
1219
|
+
/**
|
|
1220
|
+
* 运行时判定 + 类型窄化:`name` 是否是本包注册的 zg_* 工具。
|
|
1221
|
+
*
|
|
1222
|
+
* 也被 host.ts 的 pre-execute 确认闸用(只对 zg_* 发问,别家的工具不该被本插件拦)。
|
|
1223
|
+
* 判据仍只有 ZG_TOOLS 一处来源,故那边不再抄一份工具名单。
|
|
1224
|
+
*/
|
|
897
1225
|
function isZgToolName(name) {
|
|
898
1226
|
return typeof name === "string" && ZG_TOOL_NAMES.has(name);
|
|
899
1227
|
}
|
|
@@ -947,6 +1275,14 @@ function zgGuard(execution, messages) {
|
|
|
947
1275
|
/** zg 索引库目录名(zg index 的落盘位置:<root>/.zvec-grep/)。 */
|
|
948
1276
|
const INDEX_DIR_NAME = ".zvec-grep";
|
|
949
1277
|
/**
|
|
1278
|
+
* 工作区索引的判别文件名(上游 `@zvec/zvec` 的 `WORKSPACE_MANIFEST_FILE`,同名同值):
|
|
1279
|
+
* 写在 `<root>/.zvec-grep/manifest.json`。**只判目录名不足以认出索引**——
|
|
1280
|
+
* `.zvec-grep` 这个名字同时被 zg 自己的全局 home 征用
|
|
1281
|
+
* (`ZVEC_GREP_HOME ?? ~/.zvec-grep`,装的是 config.json / locks / models),
|
|
1282
|
+
* 于是一个从没建过索引、只是祖先目录撞名的普通工作区也会被当成「已建索引」。
|
|
1283
|
+
*/
|
|
1284
|
+
const WORKSPACE_MANIFEST_FILE = "manifest.json";
|
|
1285
|
+
/**
|
|
950
1286
|
* 从 startDir 向上找含 zg 索引库的最近祖先(含自身),返回该索引根。
|
|
951
1287
|
* 会话工作区可能是索引根的子目录(如索引在仓库根、会话开在子包)——不向上走
|
|
952
1288
|
* 会漏拦。probe 注入(宿主用 existsSync),本函数保持纯函数可单测。
|
|
@@ -965,12 +1301,43 @@ function findIndexRoot(startDir, probe, maxDepth = 8) {
|
|
|
965
1301
|
}
|
|
966
1302
|
return found;
|
|
967
1303
|
}
|
|
1304
|
+
/** 无会话身份时的共享桶名(沿用旧常量,不另起一个同义值)。 */
|
|
1305
|
+
const SHARED_SESSION_KEY = "__anonymous__";
|
|
968
1306
|
/** 会话状态分片键:session.id(字符串/数字)→ 稳定键;无 id 归入共享桶。 */
|
|
969
1307
|
function sessionKeyOf(execution) {
|
|
970
1308
|
const id = execution?.agent?.session?.id;
|
|
971
1309
|
if (typeof id === "string" && id.length > 0) return id;
|
|
972
1310
|
if (typeof id === "number" && Number.isSafeInteger(id)) return String(id);
|
|
973
|
-
return
|
|
1311
|
+
return SHARED_SESSION_KEY;
|
|
1312
|
+
}
|
|
1313
|
+
/**
|
|
1314
|
+
* 会话的**根**标识:沿 `header.parentSession` 一路上溯到最顶层那一跳。
|
|
1315
|
+
*
|
|
1316
|
+
* 为什么不用自己的 id 分片:子代理各自持有独立会话,于是「主代理搜过 → 放行 3 次 grep/rg」
|
|
1317
|
+
* 变成「主代理那 3 次」,子代理一次都没有——门禁想建立的「语义检索优先」在多代理下直接失效。
|
|
1318
|
+
* 按根分片后,同一棵委派树共享同一份额度,语义检索的证据也随之共享。
|
|
1319
|
+
*
|
|
1320
|
+
* 降级是三级的,都不抛错:
|
|
1321
|
+
* - 自身即顶层(没有 parentSession)→ 用自己的 id。
|
|
1322
|
+
* - 上溯到某一跳时查不到它的父(会话已落定、或 `lookup` 根本不存在——宿主没装会话存储)
|
|
1323
|
+
* → 停在**已知的最后一跳**,不猜。
|
|
1324
|
+
* - 链上出现环 → 停在首次重复前的位置。
|
|
1325
|
+
*/
|
|
1326
|
+
function rootSessionKeyOf(execution, lookup) {
|
|
1327
|
+
const own = sessionKeyOf(execution);
|
|
1328
|
+
if (own === "__anonymous__") return own;
|
|
1329
|
+
const parent = execution?.agent?.session?.header?.parentSession;
|
|
1330
|
+
if (typeof parent !== "string" || parent.length === 0) return own;
|
|
1331
|
+
const seen = /* @__PURE__ */ new Set([own, parent]);
|
|
1332
|
+
let cursor = parent;
|
|
1333
|
+
for (let hop = 0; hop < 32; hop += 1) {
|
|
1334
|
+
if (lookup === void 0) return cursor;
|
|
1335
|
+
const next = lookup(cursor)?.parentSession;
|
|
1336
|
+
if (typeof next !== "string" || next.length === 0 || seen.has(next)) return cursor;
|
|
1337
|
+
seen.add(next);
|
|
1338
|
+
cursor = next;
|
|
1339
|
+
}
|
|
1340
|
+
return cursor;
|
|
974
1341
|
}
|
|
975
1342
|
/**
|
|
976
1343
|
* search-first 门禁(硬约束):拦截对象为
|
|
@@ -993,8 +1360,9 @@ function buildSearchFirstReason(cwd, command, deps, messages) {
|
|
|
993
1360
|
const indexRoot = findIndexRoot(cwd, deps.indexProbe);
|
|
994
1361
|
let reason;
|
|
995
1362
|
if (indexRoot !== void 0 && (command === void 0 || !hasExternalTarget(indexRoot, command, messages))) {
|
|
996
|
-
const
|
|
997
|
-
|
|
1363
|
+
const rebuilding = deps.rebuildBypass?.(indexRoot) === true;
|
|
1364
|
+
const unlock = rebuilding ? void 0 : deps.lookupUnlock(indexRoot);
|
|
1365
|
+
if (rebuilding) {} else if (unlock !== void 0 && unlockActive(unlock, deps.now())) deps.consumeGrep(unlock);
|
|
998
1366
|
else {
|
|
999
1367
|
let state;
|
|
1000
1368
|
if (unlock === void 0) state = messages.gateNeverSearched;
|
|
@@ -1045,12 +1413,255 @@ function searchFirstGuard(execution, deps, messages) {
|
|
|
1045
1413
|
}
|
|
1046
1414
|
return reason;
|
|
1047
1415
|
}
|
|
1416
|
+
/** 等到信号被取消为止。 */
|
|
1417
|
+
async function abortOf(signal) {
|
|
1418
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
1419
|
+
signal.addEventListener("abort", () => {
|
|
1420
|
+
resolve(void 0);
|
|
1421
|
+
}, { once: true });
|
|
1422
|
+
return promise;
|
|
1423
|
+
}
|
|
1424
|
+
/** 等到信号被取消为止,并归一成等待的一种结局。 */
|
|
1425
|
+
async function abortedOutcome(signal) {
|
|
1426
|
+
await abortOf(signal);
|
|
1427
|
+
return "aborted";
|
|
1428
|
+
}
|
|
1429
|
+
/** 延时;用不可撤销的定时器换来收尾路径里没有「撤销自己」那种分支。 */
|
|
1430
|
+
async function delay(ms) {
|
|
1431
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
1432
|
+
setTimeout(() => {
|
|
1433
|
+
resolve(void 0);
|
|
1434
|
+
}, ms);
|
|
1435
|
+
return promise;
|
|
1436
|
+
}
|
|
1437
|
+
/**
|
|
1438
|
+
* 容量上限:超过就淘汰若干条目,但**绝不淘汰已经交出作业号的那条**。
|
|
1439
|
+
*
|
|
1440
|
+
* 为什么:淘汰会把条目从表里删掉并兑现它的 `settled`——对一条真在跑的重建来说,那等于
|
|
1441
|
+
* 告诉所有等待者「结束了」,而它的 zg 其实还在写这棵树的索引。表一空,下一条 claim 就会
|
|
1442
|
+
* 成功,于是两条 `zg index` 同时啃一份索引,撞上 zg 的写锁直接失败——那正是这个注册表
|
|
1443
|
+
* 存在的理由。官方作业注册表本身就把同时在跑的作业数卡在一个很小的量级,所以「全部都是
|
|
1444
|
+
* running、淘汰不动」时表短暂超限是无害的,内存依然有界。
|
|
1445
|
+
*/
|
|
1446
|
+
function trimToMax(entries, max, keep) {
|
|
1447
|
+
for (const [root, entry] of entries) {
|
|
1448
|
+
if (entries.size <= max) return;
|
|
1449
|
+
if (entry !== keep && entry.jobId === void 0) {
|
|
1450
|
+
entries.delete(root);
|
|
1451
|
+
entry.settle();
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
/**
|
|
1456
|
+
* 覆盖给定 root 的那条活跃条目:重建根是 root 的祖先或同一处时命中,多条命中取
|
|
1457
|
+
* startedAt 最早的一条。抽成自由函数是为了让 `covering` 与 `wait` 共用同一段判据
|
|
1458
|
+
* ——两者一旦分叉,就会重演「门禁等得到、等待等不到」那个口径不一致的毛病。
|
|
1459
|
+
*/
|
|
1460
|
+
function coveringOf(entries, root, messages) {
|
|
1461
|
+
let best;
|
|
1462
|
+
for (const entry of entries.values()) if (pathInsideRoot(root, entry.root, messages) && (best === void 0 || entry.startedAt < best.startedAt)) best = entry;
|
|
1463
|
+
return best;
|
|
1464
|
+
}
|
|
1465
|
+
/**
|
|
1466
|
+
* 建一份注册表。时钟可注入(单测推进时间用),等待上限可注入(单测不必真等)。
|
|
1467
|
+
*/
|
|
1468
|
+
function createRebuildRegistry(options = {}) {
|
|
1469
|
+
const now = options.now ?? Date.now;
|
|
1470
|
+
const maxTracked = options.maxTracked ?? 32;
|
|
1471
|
+
const entries = /* @__PURE__ */ new Map();
|
|
1472
|
+
const release = (root) => {
|
|
1473
|
+
const entry = entries.get(root);
|
|
1474
|
+
if (entry === void 0) return false;
|
|
1475
|
+
entries.delete(root);
|
|
1476
|
+
entry.settle();
|
|
1477
|
+
return true;
|
|
1478
|
+
};
|
|
1479
|
+
return {
|
|
1480
|
+
claim(root, origin, startedAt) {
|
|
1481
|
+
if (entries.has(root)) return null;
|
|
1482
|
+
const { promise: settled, resolve } = Promise.withResolvers();
|
|
1483
|
+
const settle = () => {
|
|
1484
|
+
resolve(void 0);
|
|
1485
|
+
};
|
|
1486
|
+
const entry = {
|
|
1487
|
+
root,
|
|
1488
|
+
origin,
|
|
1489
|
+
startedAt: startedAt ?? now(),
|
|
1490
|
+
phase: "starting",
|
|
1491
|
+
jobId: void 0,
|
|
1492
|
+
settled,
|
|
1493
|
+
settle
|
|
1494
|
+
};
|
|
1495
|
+
entries.set(root, entry);
|
|
1496
|
+
trimToMax(entries, maxTracked, entry);
|
|
1497
|
+
return entry;
|
|
1498
|
+
},
|
|
1499
|
+
attach(root, jobId) {
|
|
1500
|
+
const entry = entries.get(root);
|
|
1501
|
+
if (entry === void 0) return;
|
|
1502
|
+
entry.jobId = jobId;
|
|
1503
|
+
entry.phase = "running";
|
|
1504
|
+
},
|
|
1505
|
+
release,
|
|
1506
|
+
active(root) {
|
|
1507
|
+
return entries.get(root);
|
|
1508
|
+
},
|
|
1509
|
+
covering(root, messages) {
|
|
1510
|
+
return coveringOf(entries, root, messages);
|
|
1511
|
+
},
|
|
1512
|
+
hasPollable(root) {
|
|
1513
|
+
return entries.get(root)?.jobId !== void 0;
|
|
1514
|
+
},
|
|
1515
|
+
async wait(root, messages, timeoutMs, signal) {
|
|
1516
|
+
const entry = coveringOf(entries, root, messages);
|
|
1517
|
+
if (entry === void 0) return "settled";
|
|
1518
|
+
if (signal?.aborted === true) return "aborted";
|
|
1519
|
+
const settleOutcome = async () => {
|
|
1520
|
+
await entry.settled;
|
|
1521
|
+
return "settled";
|
|
1522
|
+
};
|
|
1523
|
+
const expireOutcome = async () => {
|
|
1524
|
+
await delay(Math.max(0, timeoutMs));
|
|
1525
|
+
return "timeout";
|
|
1526
|
+
};
|
|
1527
|
+
const settled = settleOutcome();
|
|
1528
|
+
const expired = expireOutcome();
|
|
1529
|
+
const raced = signal === void 0 ? [settled, expired] : [
|
|
1530
|
+
settled,
|
|
1531
|
+
expired,
|
|
1532
|
+
abortedOutcome(signal)
|
|
1533
|
+
];
|
|
1534
|
+
return Promise.race(raced);
|
|
1535
|
+
},
|
|
1536
|
+
keys() {
|
|
1537
|
+
return [...entries.keys()];
|
|
1538
|
+
}
|
|
1539
|
+
};
|
|
1540
|
+
}
|
|
1541
|
+
/** 索引重建与其它占用者分开:等与不等是两回事。 */
|
|
1542
|
+
const REBUILD_OPERATION = "index.rebuild";
|
|
1543
|
+
/** zg 明细块的键值行。键与值都命名捕获,避免按下标取。 */
|
|
1544
|
+
const DETAIL_LINE = /^\s*(?<key>[A-Za-z][A-Za-z0-9]*):\s*(?<value>.+?)\s*$/u;
|
|
1545
|
+
/** 输出里的错误码行。 */
|
|
1546
|
+
const CODE_LINE = /^\s*Code:\s*(?<code>\S+)\s*$/mu;
|
|
1547
|
+
/**
|
|
1548
|
+
* 抽错误码。没有该行就不是 zg 的结构化失败(旁路返回 null,交给通用失败文案)。
|
|
1549
|
+
* 只取第一处:一次失败只应有一个码,取多个说明输出形状已变,宁可不判。
|
|
1550
|
+
*/
|
|
1551
|
+
function zgErrorCode(stderr) {
|
|
1552
|
+
return CODE_LINE.exec(stderr)?.groups?.["code"];
|
|
1553
|
+
}
|
|
1554
|
+
/**
|
|
1555
|
+
* 明细块的键值表。`Details:` 之后的缩进行才是明细,标题与错误码行不参与。
|
|
1556
|
+
* 重复键取首次出现(zg 不会重复输出同一个键,重复即形状异常,不覆盖)。
|
|
1557
|
+
* 明细块遇到非键值行即终止:其后多半是尾部截断的散文,继续收只会捡到假键值。
|
|
1558
|
+
*/
|
|
1559
|
+
function zgErrorDetails(stderr) {
|
|
1560
|
+
const details = /* @__PURE__ */ new Map();
|
|
1561
|
+
const lines = stderr.split("\n");
|
|
1562
|
+
const start = lines.findIndex((line) => /^\s*Details:\s*$/u.test(line));
|
|
1563
|
+
if (start === -1) return details;
|
|
1564
|
+
for (const line of lines.slice(start + 1)) {
|
|
1565
|
+
const matched = DETAIL_LINE.exec(line);
|
|
1566
|
+
const key = matched?.groups?.["key"];
|
|
1567
|
+
const value = matched?.groups?.["value"];
|
|
1568
|
+
if (key !== void 0 && value !== void 0) {
|
|
1569
|
+
if (!details.has(key)) details.set(key, value);
|
|
1570
|
+
} else if (line.trim().length > 0) break;
|
|
1571
|
+
}
|
|
1572
|
+
return details;
|
|
1573
|
+
}
|
|
1574
|
+
/**
|
|
1575
|
+
* 识别并发类失败;不是并发失败(或输出形状不认识)一律返回 null。
|
|
1576
|
+
*
|
|
1577
|
+
* `rebuild` 只在占锁方自报重建时为真:等待策略据此决定要不要排队。把「别人占锁」也
|
|
1578
|
+
* 当成重建去等,会在永远不会被本插件放开的锁上无界挂起。
|
|
1579
|
+
*/
|
|
1580
|
+
function classifyConcurrentFailure(stderr) {
|
|
1581
|
+
const code = zgErrorCode(stderr);
|
|
1582
|
+
if (code === void 0) return null;
|
|
1583
|
+
const details = zgErrorDetails(stderr);
|
|
1584
|
+
const ownerOperation = details.get("ownerOperation");
|
|
1585
|
+
if (code === "ZVEC_GREP.ENGINE.LOCK.BUSY") return {
|
|
1586
|
+
kind: "lock-busy",
|
|
1587
|
+
ownerOperation,
|
|
1588
|
+
ownerPid: details.get("ownerPid"),
|
|
1589
|
+
lockPath: details.get("lock"),
|
|
1590
|
+
rebuild: ownerOperation === REBUILD_OPERATION
|
|
1591
|
+
};
|
|
1592
|
+
if (code === "ZVEC_GREP.ENGINE.DAEMON_LEASE_ACTIVE") return {
|
|
1593
|
+
kind: "daemon-lease",
|
|
1594
|
+
pid: details.get("pid")
|
|
1595
|
+
};
|
|
1596
|
+
return null;
|
|
1597
|
+
}
|
|
1598
|
+
//#endregion
|
|
1599
|
+
//#region lib/zg-version.ts
|
|
1600
|
+
/** 本包按之书写的 zg 语义版本。低于它一律在命令构造前拒绝。 */
|
|
1601
|
+
const MINIMUM_ZG_VERSION = "0.2.2";
|
|
1602
|
+
/**
|
|
1603
|
+
* 形状:整串就是一个三段数字版本,可带前后的空白与换行。
|
|
1604
|
+
* 刻意不接受 `v0.2.2` / `0.2.2-rc.1` / `>=0.2.2` 这类——真出现了就说明输出形态变了,
|
|
1605
|
+
* 那属于「读不懂」,归到 undefined 由调用方按「探测不到」处理。
|
|
1606
|
+
*/
|
|
1607
|
+
const VERSION_SHAPE = /^\s*(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)\s*$/u;
|
|
1608
|
+
/** 门槛值本身就是常量,拿它自己当被测对象即可(写成字面量免去一次可失败的解析)。 */
|
|
1609
|
+
const MINIMUM = {
|
|
1610
|
+
major: 0,
|
|
1611
|
+
minor: 2,
|
|
1612
|
+
patch: 2
|
|
1613
|
+
};
|
|
1614
|
+
/**
|
|
1615
|
+
* 不是版本号时用的哨兵:版本分量恒非负,故负数只可能来自「没解析出来」。
|
|
1616
|
+
* 三个函数都收敛成**单一 return**(`return a` 与 `return undefined` 混排会被本仓的
|
|
1617
|
+
* consistent-return 判成两种返回形态),故用哨兵而不是提前 return。
|
|
1618
|
+
*/
|
|
1619
|
+
const UNPARSED = -1;
|
|
1620
|
+
/** 取一段具名捕获组;组不存在时给哨兵。 */
|
|
1621
|
+
function segment(found, name) {
|
|
1622
|
+
const raw = found?.groups?.[name];
|
|
1623
|
+
return raw === void 0 ? UNPARSED : Number(raw);
|
|
1624
|
+
}
|
|
1625
|
+
/** 解析 `zg --version` 的 stdout;形状不符即 undefined(**不猜**)。 */
|
|
1626
|
+
function parseZgVersion(stdout) {
|
|
1627
|
+
const found = VERSION_SHAPE.exec(stdout);
|
|
1628
|
+
const major = segment(found, "major");
|
|
1629
|
+
const minor = segment(found, "minor");
|
|
1630
|
+
const patch = segment(found, "patch");
|
|
1631
|
+
return major < 0 || minor < 0 || patch < 0 ? void 0 : {
|
|
1632
|
+
major,
|
|
1633
|
+
minor,
|
|
1634
|
+
patch
|
|
1635
|
+
};
|
|
1636
|
+
}
|
|
1637
|
+
/** 版本号的字面形态(回显用:门槛文案要让用户看得见自己装的是哪个版本)。 */
|
|
1638
|
+
function formatZgVersion(version) {
|
|
1639
|
+
return `${version.major}.${version.minor}.${version.patch}`;
|
|
1640
|
+
}
|
|
1641
|
+
/** actual 是否 >= minimum:逐段比数值(不是比字符串,否则 `0.10.0 < 0.9.0`)。 */
|
|
1642
|
+
function versionAtLeast(actual, minimum) {
|
|
1643
|
+
if (actual.major !== minimum.major) return actual.major > minimum.major;
|
|
1644
|
+
if (actual.minor !== minimum.minor) return actual.minor > minimum.minor;
|
|
1645
|
+
return actual.patch >= minimum.patch;
|
|
1646
|
+
}
|
|
1647
|
+
/**
|
|
1648
|
+
* 门槛判定:够新(或读不懂)返回 undefined;确知太老则交回实际版本,供文案回显。
|
|
1649
|
+
* 「读不懂」与「太老」必须分开:前者放行、后者拒绝,混在一起就成了用一个猜出来的
|
|
1650
|
+
* 版本去拦真实用户。
|
|
1651
|
+
*/
|
|
1652
|
+
function tooOldZgVersion(stdout) {
|
|
1653
|
+
const parsed = parseZgVersion(stdout);
|
|
1654
|
+
return parsed === void 0 || versionAtLeast(parsed, MINIMUM) ? void 0 : parsed;
|
|
1655
|
+
}
|
|
1048
1656
|
//#endregion
|
|
1049
1657
|
//#region host.ts
|
|
1050
1658
|
const SEARCH_TIMEOUT_MS = 3e5;
|
|
1051
1659
|
const STATUS_TIMEOUT_MS = 6e4;
|
|
1052
1660
|
const INDEX_TIMEOUT_MS = 6e5;
|
|
1053
1661
|
const STDOUT_MAX_BYTES = 4e5;
|
|
1662
|
+
/** 检索等待同根重建落定的上限(ms)。部署值:大型工作区的重建可能跑很久,
|
|
1663
|
+
* 但也不该让一次检索无限期挂着。 */
|
|
1664
|
+
const REBUILD_WAIT_MS = 12e4;
|
|
1054
1665
|
const REBUILD_PATH = "/_dsh/zvec-grep/rebuild";
|
|
1055
1666
|
const REBUILD_STATUS_PATH = "/_dsh/zvec-grep/rebuild-status";
|
|
1056
1667
|
/** 卡片取「可选工作区 + CSRF token」的引导端点(GET,只回本插件自己的数据)。 */
|
|
@@ -1059,8 +1670,13 @@ const REBUILD_ROOTS_PATH = "/_dsh/zvec-grep/rebuild-roots";
|
|
|
1059
1670
|
const REBUILD_CSRF_HEADER = "x-zvec-grep-csrf";
|
|
1060
1671
|
/** rebuild 端点没有业务请求体,但必须把它读完(keep-alive 残留字节的协议正确性)。 */
|
|
1061
1672
|
const REBUILD_BODY_MAX_BYTES = 4096;
|
|
1062
|
-
/**
|
|
1673
|
+
/** 工作区白名单容量:超过按最近使用淘汰最冷的一条(常驻进程内存有界)。 */
|
|
1063
1674
|
const MAX_LEDGER_ROOTS = 64;
|
|
1675
|
+
/**
|
|
1676
|
+
* 白名单条目的有效期:多久没被提到就当它不再活跃。一天足够覆盖「今天开过的会话」,
|
|
1677
|
+
* 又不会让一个月前随手开过的一个目录一直占着名额。
|
|
1678
|
+
*/
|
|
1679
|
+
const LEDGER_TTL_MS = 864e5;
|
|
1064
1680
|
/** 成功执行里回显 stderr 的尾部长度(降级提示常就在这一行)。 */
|
|
1065
1681
|
const STDERR_NOTE_CHARS = 400;
|
|
1066
1682
|
/** 具名方法在位(typeof 函数)——只看 `typeof x === "object"` 会放过 null、
|
|
@@ -1182,13 +1798,41 @@ function shellFailure(result, messages) {
|
|
|
1182
1798
|
});
|
|
1183
1799
|
}
|
|
1184
1800
|
/**
|
|
1801
|
+
* 成功执行的 stderr 里哪些是「进度噪声」、哪些必须交回。
|
|
1802
|
+
*
|
|
1803
|
+
* zg 在**成功**时也往 stderr 写索引进度(非 TTY 下逐行落盘,实测原文:`Scanning files...` /
|
|
1804
|
+
* `Preparing local/potion-code-16m-v2` / `Indexing complete`)。这些行每次建索引都在,写进
|
|
1805
|
+
* 工具回执只是让模型对着同一堆噪声反复读;真正需要它看见的是另一类:降级提示、锁冲突、
|
|
1806
|
+
* 沙箱事实,以及任何本包**不认识**的新增告警。
|
|
1807
|
+
*
|
|
1808
|
+
* 所以判据是「只丢认得的进度行,其余全留」,而不是「只留认得的告警」——后者一旦 zg 出了
|
|
1809
|
+
* 新提示就会静默吞掉,那正是最不该发生的失败模式。
|
|
1810
|
+
*
|
|
1811
|
+
* 进度行词表逐条对着上游的进度格式化函数核过(含下载与就绪两档):
|
|
1812
|
+
* Scanning files… / Indexing files… / Indexing complete / Preparing <model> /
|
|
1813
|
+
* Downloading <model> · … / Model ready: <model>
|
|
1814
|
+
* 其中 `Indexing complete` 用**整行相等**匹配,不能用前缀——`Indexing completed with 3 failed
|
|
1815
|
+
* files`(部分文件失败的信号,必须留着)字面上就以它开头。
|
|
1816
|
+
*/
|
|
1817
|
+
const STDERR_PROGRESS_LINES = /* @__PURE__ */ new Set(["Scanning files...", "Indexing complete"]);
|
|
1818
|
+
/** 该行是否只是进度噪声。`warning` / `Error` / `zvec-grep` 一律不判为噪声。 */
|
|
1819
|
+
function isStderrProgressLine(line) {
|
|
1820
|
+
const trimmed = line.trim();
|
|
1821
|
+
if (STDERR_PROGRESS_LINES.has(trimmed)) return true;
|
|
1822
|
+
return trimmed.startsWith("Indexing files") || trimmed.startsWith("Preparing ") || trimmed.startsWith("Downloading ") || trimmed.startsWith("Model ready: ");
|
|
1823
|
+
}
|
|
1824
|
+
/** 剥掉进度行,留下真正要交回的 stderr(可能为空串)。 */
|
|
1825
|
+
function signalStderr(text) {
|
|
1826
|
+
return text.split("\n").filter((line) => line.trim().length > 0 && !isStderrProgressLine(line)).join("\n");
|
|
1827
|
+
}
|
|
1828
|
+
/**
|
|
1185
1829
|
* 成功(exit 0)执行的结果体检:把「其实不完整」的三类事实显式打标,避免模型
|
|
1186
1830
|
* 把残缺输出当完整证据用。
|
|
1187
1831
|
* 1. stdout 超上限被截尾(可能已落 spill);
|
|
1188
1832
|
* 2. 沙箱在执行中拒绝过一次文件操作(zg 仍可 exit 0,但结果少了被拒的部分);
|
|
1189
|
-
* 3. **stderr
|
|
1190
|
-
*
|
|
1191
|
-
*
|
|
1833
|
+
* 3. **stderr 去噪之后仍非空**:zg 的降级提示(例如 embedding 模型拉不到 → 退化为
|
|
1834
|
+
* 纯词法兜底、跳过 --refresh)只写在 stderr,旧实现整个丢掉 → 用户把「只有词法
|
|
1835
|
+
* 结果」的检索当语义检索的完整结果。这里回显尾部一段。整段都是索引进度时一句都不加。
|
|
1192
1836
|
*/
|
|
1193
1837
|
function successNotes(result, messages, stdoutMaxBytes) {
|
|
1194
1838
|
const notes = [];
|
|
@@ -1202,8 +1846,9 @@ function successNotes(result, messages, stdoutMaxBytes) {
|
|
|
1202
1846
|
const { sandbox } = result;
|
|
1203
1847
|
if (sandbox?.denied === true) notes.push(fill(messages.sandboxWarning, { denied: deniedNote(sandbox, messages) }));
|
|
1204
1848
|
const { stderr } = result;
|
|
1205
|
-
|
|
1206
|
-
|
|
1849
|
+
const signal = signalStderr(stderr.text);
|
|
1850
|
+
if (signal.length > 0) {
|
|
1851
|
+
const tail = truncateStart(signal, STDERR_NOTE_CHARS);
|
|
1207
1852
|
const truncatedMark = stderr.truncated ? "[…]" : "";
|
|
1208
1853
|
notes.push(fill(messages.stderrNote, {
|
|
1209
1854
|
marked: truncatedMark,
|
|
@@ -1222,28 +1867,175 @@ function hfEndpointEnv(config) {
|
|
|
1222
1867
|
return env;
|
|
1223
1868
|
}
|
|
1224
1869
|
/**
|
|
1225
|
-
*
|
|
1226
|
-
*
|
|
1227
|
-
*
|
|
1228
|
-
*
|
|
1229
|
-
|
|
1870
|
+
* 部署值里的可选字符串:空串/空白/非字符串一律归一成 undefined(=「没配」)。
|
|
1871
|
+
* 收 `string | undefined` 而不是 `string`:这两个字段是**非 volatile** 部署值,正常装载
|
|
1872
|
+
* 下必有值(schema 的 `.default("")`),但行 config 若被绕过 schema 直接塞进来,
|
|
1873
|
+
* 这里仍要能判成「没配」而不是 `undefined.trim()` 抛在命令构造的中途。
|
|
1874
|
+
*/
|
|
1875
|
+
function trimmedConfigString(value) {
|
|
1876
|
+
const trimmed = typeof value === "string" ? value.trim() : "";
|
|
1877
|
+
return trimmed.length > 0 ? trimmed : void 0;
|
|
1878
|
+
}
|
|
1879
|
+
/**
|
|
1880
|
+
* 远程 embedding 是否被本部署显式开放。默认 false ⇒ 命令构造期就拒掉一切非本地引用。
|
|
1881
|
+
* 取值直接用字段本身:schema 声明的是 boolean,cordis 装载期已按它校验过行 config,
|
|
1882
|
+
* 再写一遍 `=== true` 只会多一条恒真判断(lint 会当场判它 unnecessary)。
|
|
1883
|
+
*/
|
|
1884
|
+
function allowRemoteEmbedding(config) {
|
|
1885
|
+
return config.allowRemoteEmbedding;
|
|
1886
|
+
}
|
|
1887
|
+
/**
|
|
1888
|
+
* zg 子进程的环境变量:HF 镜像 + (仅在部署开放远程 embedding 时的)远程端点与凭据。
|
|
1889
|
+
*
|
|
1890
|
+
* **密钥只走环境变量,绝不进 argv**。两道原因,都是实测/读源码得来的:
|
|
1891
|
+
* - 本包把整条命令当官方作业的 `JobSpec.label` 回显给卡片,argv 里的密钥会进界面、
|
|
1892
|
+
* 进日志、进 `ps` 的进程列表;
|
|
1893
|
+
* - 上游自己就优先读环境变量(zvec-grep v0.2.2 `src/engine/config.ts`:
|
|
1894
|
+
* `nonEmptyEnvironmentValue(environment.ZVEC_GREP_ENDPOINT)`、
|
|
1895
|
+
* `environmentApiKey()` 依次试 `ZVEC_GREP_API_KEY` / `DASHSCOPE_API_KEY` / `QWEN_API_KEY`),
|
|
1896
|
+
* 走 env 既是它的正路,也省掉一条 argv 泄露面。
|
|
1897
|
+
*
|
|
1898
|
+
* **凭据为什么是「宿主进程里某个环境变量的名字」而不是值本身**:官方 subprocess 层会把
|
|
1899
|
+
* 名字命中 `/KEY|PASSWORD|SECRET|TOKEN/i` 的变量从子进程环境里**剔掉**
|
|
1900
|
+
* (`packages/subprocess/subprocess/src/index.ts` 的 `scrubbedParentEnv`),所以光靠在
|
|
1901
|
+
* 宿主进程里 export 一个 `ZVEC_GREP_API_KEY` 是到不了 zg 的——必须由本插件显式转发。
|
|
1902
|
+
* 于是配置里只记**名字**、值现读现转:密钥不必落进插件配置文件,也不进 argv、不进日志。
|
|
1903
|
+
* 两项都只在 allowRemoteEmbedding 打开时才读:默认部署下这段代码根本不执行。
|
|
1904
|
+
*/
|
|
1905
|
+
function zgEnv(config) {
|
|
1906
|
+
const env = { ...hfEndpointEnv(config) };
|
|
1907
|
+
if (allowRemoteEmbedding(config)) {
|
|
1908
|
+
const endpoint = trimmedConfigString(config.remoteEmbeddingEndpoint);
|
|
1909
|
+
if (endpoint !== void 0) env["ZVEC_GREP_ENDPOINT"] = endpoint;
|
|
1910
|
+
const keyName = trimmedConfigString(config.remoteEmbeddingApiKeyFrom);
|
|
1911
|
+
const secret = (keyName === void 0 ? void 0 : process.env[keyName])?.trim();
|
|
1912
|
+
if (secret !== void 0 && secret.length > 0) env["ZVEC_GREP_API_KEY"] = secret;
|
|
1913
|
+
}
|
|
1914
|
+
return Object.keys(env).length > 0 ? env : void 0;
|
|
1915
|
+
}
|
|
1916
|
+
/** 版本探测结果的缓存时长:够长到一次会话里基本只探一次,够短到用户中途升级 zg 也算数。 */
|
|
1917
|
+
const ZG_VERSION_TTL_MS = 6e5;
|
|
1918
|
+
/** 探测自身的超时:`zg --version` 是纯打印,给它检索超时是浪费,也让它卡住主流程。 */
|
|
1919
|
+
const ZG_VERSION_PROBE_TIMEOUT_MS = 1e4;
|
|
1920
|
+
/** 门槛文案:回显实际版本与门槛值,并给出唯一的出路(升级 zvec-grep)。 */
|
|
1921
|
+
function tooOldZgError(actual, messages) {
|
|
1922
|
+
return new Error(fill(messages.zgVersionTooOld, {
|
|
1923
|
+
actual: formatZgVersion(actual),
|
|
1924
|
+
minimum: MINIMUM_ZG_VERSION
|
|
1925
|
+
}));
|
|
1926
|
+
}
|
|
1927
|
+
/**
|
|
1928
|
+
* 跑一次 `zg --version`,只把 stdout 交回来(undefined = 探测不出来:非零退出、
|
|
1929
|
+
* 读不懂的形状,或 spawn/执行器层面的任何失败)。**失败绝不外抛**:这道门槛的职责
|
|
1930
|
+
* 只有一个——把「确知太老」拦下来,拿「没读懂」去拦用户是在制造新故障。
|
|
1931
|
+
*/
|
|
1932
|
+
async function probeZgVersion(host, config) {
|
|
1933
|
+
let stdout;
|
|
1934
|
+
try {
|
|
1935
|
+
const env = zgEnv(config);
|
|
1936
|
+
const spec = host.shell.resolve({
|
|
1937
|
+
command: "zg --version",
|
|
1938
|
+
workdir: tmpdir(),
|
|
1939
|
+
timeoutMs: ZG_VERSION_PROBE_TIMEOUT_MS,
|
|
1940
|
+
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
1941
|
+
...env ? { env } : {}
|
|
1942
|
+
});
|
|
1943
|
+
const result = await (await host.shell.execute(spec)).result();
|
|
1944
|
+
stdout = result.exitCode === 0 ? result.stdout.text : void 0;
|
|
1945
|
+
} catch {
|
|
1946
|
+
stdout = void 0;
|
|
1947
|
+
}
|
|
1948
|
+
return stdout === void 0 ? void 0 : tooOldZgVersion(stdout);
|
|
1949
|
+
}
|
|
1950
|
+
/**
|
|
1951
|
+
* 建这道门槛。缓存挂在闭包里(随 apply 生死),TTL 到期或探测失败后重探一次。
|
|
1952
|
+
*
|
|
1953
|
+
* workdir 取系统临时目录而不是会话 cwd:这是一次与工作区无关的纯打印探测,
|
|
1954
|
+
* 不该因为某个会话的工作区不存在而失败,也不该顺手触发 root 授权那一套。
|
|
1955
|
+
*/
|
|
1956
|
+
function createZgVersionGate(host, config) {
|
|
1957
|
+
let cachedAt = 0;
|
|
1958
|
+
let cachedTooOld;
|
|
1959
|
+
return { async ensure(messages) {
|
|
1960
|
+
const now = Date.now();
|
|
1961
|
+
if (now - cachedAt < ZG_VERSION_TTL_MS) {
|
|
1962
|
+
if (cachedTooOld !== void 0) throw tooOldZgError(cachedTooOld, messages);
|
|
1963
|
+
return;
|
|
1964
|
+
}
|
|
1965
|
+
const probe = await probeZgVersion(host, config);
|
|
1966
|
+
cachedAt = now;
|
|
1967
|
+
cachedTooOld = probe;
|
|
1968
|
+
if (probe !== void 0) throw tooOldZgError(probe, messages);
|
|
1969
|
+
} };
|
|
1970
|
+
}
|
|
1971
|
+
/**
|
|
1972
|
+
* zg query 输出的命中摘要。口径分两栏,因为**分组计数之和不是命中总数**:同一处代码
|
|
1973
|
+
* 会被多个查询组各命中一次(名次与 `matchedBy` 逐组变化,实测同一 `src/beta.ts:1-3`
|
|
1974
|
+
* 在 fts 组排第 4、在 vector 组排第 1),直接求和会把同一处位置重复计入。
|
|
1975
|
+
* - 分组计数合计:各组 `hits:` 之和,反映 zg 实际跑了多少路。
|
|
1976
|
+
* - 去重后不同位置:按 `相对路径:行号范围` 这一稳定身份键去重——名次、匹配来源、
|
|
1977
|
+
* 分数都逐组变化,不能入键——反映模型真正看到几处不同代码。
|
|
1978
|
+
* 身份键取条目头行里 `matchedBy=` 之后的**整段原样**文本,不去拆行号范围:路径本身
|
|
1979
|
+
* 可以含空格与冒号(实测 `deep/a/b/c d/we:ird file.ts:1-2`),任何拆解都会引入误判,
|
|
1980
|
+
* 而原样文本已经恰好就是「相对路径 + 行号范围」。一条位置都数不出时整段去重口径省略,
|
|
1981
|
+
* 不数就不谎称。
|
|
1982
|
+
*
|
|
1983
|
+
* zg 的输出**不提供**任何截断信号,故命中数正好等于 --limit 只能作为观察陈述,不能
|
|
1984
|
+
* 断言发生了截断(`hitCapped` 因此不含断言措辞)。
|
|
1230
1985
|
*/
|
|
1231
1986
|
/** zg 每个查询组的计数行前缀(实测输出形状:`hits: 3`,源码行都带行号前缀)。 */
|
|
1232
1987
|
const HITS_LINE_PREFIX = "hits: ";
|
|
1988
|
+
/**
|
|
1989
|
+
* zg 命中条目头行的形状:`#<名次> [选择理由] matchedBy=<来源> [score=<分>] <相对路径>:<行号范围>`。
|
|
1990
|
+
* 捕获组即身份键。
|
|
1991
|
+
*
|
|
1992
|
+
* 两段可选装饰都不能进键,各有实测依据(`--trace` 开启时出现,见 formatScore 与
|
|
1993
|
+
* agentRankedItemHeader):
|
|
1994
|
+
* - `score=`:**同一处位置在两个组里分值可以不同**(实测 `src/beta.ts:1-2` 在 fts 组
|
|
1995
|
+
* 是 0.0164、在 vector 组是 0.0161)。带分值入键等于让每次命中都成"新位置",去重
|
|
1996
|
+
* 直接失效、位置数虚高一倍。分值形态是 `Number.isInteger ? String : toFixed(4)`,
|
|
1997
|
+
* 故整数与四位小数都要收;只认纯数字,路径若真以 `score=1.txt` 开头则不会被误剥
|
|
1998
|
+
* (`score=1` 后面跟的是 `.` 不是空白,整段不匹配)。
|
|
1999
|
+
* - `[global_fill]` / `[group_coverage: x]`:排在名次与 `matchedBy=` 之间,漏了它整行
|
|
2000
|
+
* 就匹配不上,那条命中会被当成不存在。
|
|
2001
|
+
*
|
|
2002
|
+
* preview 的源码行都带 `<行号>\t` 前缀、markdown 标题行是 `heading:`、追踪行是 `trace:`,
|
|
2003
|
+
* 都撞不上这一形状。匹配来源逐组变化(fts / vector / fts+vector),故 `\S+` 只消费来源。
|
|
2004
|
+
*/
|
|
2005
|
+
const HIT_LINE_PREFIX = /^#\d+(?:\s+\[[^\]]*\])?\s+matchedBy=\S+\s+(?:score=-?\d+(?:\.\d+)?\s+)?(?<location>\S.*)$/u;
|
|
1233
2006
|
function hitSummary(stdoutText, limit, truncated, messages) {
|
|
1234
|
-
const
|
|
2007
|
+
const lines = stdoutText.split("\n");
|
|
2008
|
+
const perGroup = lines.filter((line) => line.startsWith(HITS_LINE_PREFIX)).map((line) => line.slice(6)).filter((digits) => /^\d+$/u.test(digits)).map((digits) => Math.trunc(Number(digits)));
|
|
1235
2009
|
if (perGroup.length === 0) return null;
|
|
1236
|
-
const
|
|
2010
|
+
const locations = /* @__PURE__ */ new Set();
|
|
2011
|
+
for (const line of lines) {
|
|
2012
|
+
const location = HIT_LINE_PREFIX.exec(line)?.groups?.["location"];
|
|
2013
|
+
if (location !== void 0) locations.add(location);
|
|
2014
|
+
}
|
|
2015
|
+
const grouped = perGroup.reduce((sum, count) => sum + count, 0);
|
|
1237
2016
|
const capped = perGroup.some((count) => count >= limit);
|
|
1238
2017
|
return fill(messages.hitSummary, {
|
|
1239
2018
|
groups: perGroup.length,
|
|
1240
|
-
|
|
2019
|
+
grouped,
|
|
2020
|
+
dedup: locations.size === 0 ? "" : fill(messages.hitDedup, { unique: locations.size }),
|
|
1241
2021
|
limit,
|
|
1242
2022
|
capped: capped ? messages.hitCapped : "",
|
|
1243
2023
|
truncated: truncated ? messages.hitTruncated : ""
|
|
1244
2024
|
});
|
|
1245
2025
|
}
|
|
1246
|
-
|
|
2026
|
+
/**
|
|
2027
|
+
* 被「本插件正在重建」挡住的失败:文案照常是人话,但额外带上结构化结论,
|
|
2028
|
+
* 让检索路径能判断「等它落定后重试一次」而不是无脑失败。
|
|
2029
|
+
* 只有占锁方自报重建才带这个类型——把「别的进程占锁」也当成可等的重建,
|
|
2030
|
+
* 会在一把永远不会由本插件放开的锁上无界挂起。
|
|
2031
|
+
*/
|
|
2032
|
+
var RebuildLockBusyError = class extends Error {
|
|
2033
|
+
constructor(message) {
|
|
2034
|
+
super(message);
|
|
2035
|
+
this.name = "RebuildLockBusyError";
|
|
2036
|
+
}
|
|
2037
|
+
};
|
|
2038
|
+
async function runForegroundOnce(host, command, workdir, timeoutMs, opts) {
|
|
1247
2039
|
const spec = host.shell.resolve({
|
|
1248
2040
|
command,
|
|
1249
2041
|
workdir,
|
|
@@ -1254,13 +2046,58 @@ async function runForeground(host, command, workdir, timeoutMs, opts) {
|
|
|
1254
2046
|
});
|
|
1255
2047
|
const result = await (await host.shell.execute(spec)).result();
|
|
1256
2048
|
const failure = shellFailure(result, opts.messages);
|
|
1257
|
-
if (failure !== null)
|
|
2049
|
+
if (failure !== null) {
|
|
2050
|
+
const resolved = opts.resolveFailure?.(failure, result) ?? null;
|
|
2051
|
+
if (resolved !== null) return resolved;
|
|
2052
|
+
const concurrent = classifyConcurrentFailure(result.stderr.text);
|
|
2053
|
+
throw concurrent?.kind === "lock-busy" && concurrent.rebuild ? new RebuildLockBusyError(failure) : new Error(failure);
|
|
2054
|
+
}
|
|
1258
2055
|
const notes = successNotes(result, opts.messages, opts.stdoutMaxBytes);
|
|
1259
2056
|
const { text } = result.stdout;
|
|
1260
2057
|
const summary = opts.summaryLimit === void 0 ? null : hitSummary(text, opts.summaryLimit, result.stdout.truncated, opts.messages);
|
|
1261
2058
|
const extras = summary === null ? notes : [...notes, summary];
|
|
1262
2059
|
return extras.length > 0 ? `${text}\n${extras.join("\n")}` : text;
|
|
1263
2060
|
}
|
|
2061
|
+
/** 等待期间被取消时的出路(与 zg 自身被中止区分开:这里等的是重建,不是命令)。 */
|
|
2062
|
+
function messagesAbortedWaiting(root, messages) {
|
|
2063
|
+
return fill(messages.rebuildWaitAborted, { root });
|
|
2064
|
+
}
|
|
2065
|
+
/** 等待重建落定超时:给出可行动出路,并说明不会因此发放 grep/rg 配额。 */
|
|
2066
|
+
function messagesWaitExpired(root, maxWaitMs, messages) {
|
|
2067
|
+
return fill(messages.rebuildWaitTimeout, {
|
|
2068
|
+
root,
|
|
2069
|
+
seconds: Math.round(maxWaitMs / 1e3)
|
|
2070
|
+
});
|
|
2071
|
+
}
|
|
2072
|
+
/**
|
|
2073
|
+
* 前台执行 + **一次**重建等待重试。
|
|
2074
|
+
*
|
|
2075
|
+
* 重建持有该根的写锁时,检索会立刻以「索引不可用」失败(zg 的锁是纯 fail-fast,不等)。
|
|
2076
|
+
* 直接把失败回给模型,等于在重建窗口内把该根的检索通道整个关掉——而门禁又要求先成功
|
|
2077
|
+
* 检索才放行 grep/rg,于是模型连退路都没有。这里改为:确认占锁方确实是本插件的重建,
|
|
2078
|
+
* 就等它落定后重跑一次;只等一次,不做轮询式长等,避免把一次检索拖成分钟级。
|
|
2079
|
+
*/
|
|
2080
|
+
async function runForeground(host, command, workdir, timeoutMs, opts) {
|
|
2081
|
+
const base = {
|
|
2082
|
+
signal: opts.signal,
|
|
2083
|
+
env: opts.env,
|
|
2084
|
+
stdoutMaxBytes: opts.stdoutMaxBytes,
|
|
2085
|
+
messages: opts.messages,
|
|
2086
|
+
summaryLimit: opts.summaryLimit,
|
|
2087
|
+
resolveFailure: opts.resolveFailure
|
|
2088
|
+
};
|
|
2089
|
+
const wait = opts.rebuildWait;
|
|
2090
|
+
if (wait === void 0) return runForegroundOnce(host, command, workdir, timeoutMs, base);
|
|
2091
|
+
try {
|
|
2092
|
+
return await runForegroundOnce(host, command, workdir, timeoutMs, base);
|
|
2093
|
+
} catch (error) {
|
|
2094
|
+
const entry = wait.rebuilds.covering(wait.root, opts.messages);
|
|
2095
|
+
if (!(error instanceof RebuildLockBusyError) || entry === void 0) throw error;
|
|
2096
|
+
const outcome = await wait.rebuilds.wait(wait.root, opts.messages, wait.maxWaitMs, opts.signal);
|
|
2097
|
+
if (outcome === "settled") return runForegroundOnce(host, command, workdir, timeoutMs, base);
|
|
2098
|
+
throw new Error(outcome === "aborted" ? messagesAbortedWaiting(entry.root, opts.messages) : messagesWaitExpired(entry.root, wait.maxWaitMs, opts.messages), { cause: error });
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
1264
2101
|
/**
|
|
1265
2102
|
* root 的存在性预检(item:不验存在)。zg 的 cwd 不存在时,spawn 直接以
|
|
1266
2103
|
* ENOENT 失败——那与「bash 没装」「zg 没装」在同一句 stderr 里无法区分,
|
|
@@ -1286,6 +2123,14 @@ function readDefaultLimit(config) {
|
|
|
1286
2123
|
function readGrepBudget(config) {
|
|
1287
2124
|
return config.grepBudgetPerSearch.get() ?? 3;
|
|
1288
2125
|
}
|
|
2126
|
+
/**
|
|
2127
|
+
* zg 传输模式:域内取值由 schema 保证,这里只处理「字段缺省」与宿主退化时交回的非域值。
|
|
2128
|
+
* 读一次即传给检索、索引、状态与后台重建四条命令路径——混用模式会在守护进程持有索引
|
|
2129
|
+
* 租约时让写侧直接失败,故四条路径必须同源。
|
|
2130
|
+
*/
|
|
2131
|
+
function readClientMode(config, messages) {
|
|
2132
|
+
return clientModeOf(config.clientMode, messages);
|
|
2133
|
+
}
|
|
1289
2134
|
/** search-first 解锁时效(分钟,值域 1-240 由 schema 保证)。 */
|
|
1290
2135
|
function readUnlockWindowMin(config) {
|
|
1291
2136
|
return config.unlockWindowMin.get() ?? 10;
|
|
@@ -1296,6 +2141,44 @@ function readUnlockWindowMin(config) {
|
|
|
1296
2141
|
function readEnforceSearchFirst(config) {
|
|
1297
2142
|
return config.enforceSearchFirst.get() ?? true;
|
|
1298
2143
|
}
|
|
2144
|
+
/** 归一路径的跨平台可比形式:剥掉 macOS 的 `/private` 解析前缀(`/tmp` ⇄ `/private/tmp`)。 */
|
|
2145
|
+
function comparablePath(root) {
|
|
2146
|
+
return root.startsWith("/private/") ? root.slice(8) : root;
|
|
2147
|
+
}
|
|
2148
|
+
/** 认的清单版本:与上游 `CURRENT_MANIFEST_VERSION` 同值([v0.2.2] src/engine/manifest.ts:8)。 */
|
|
2149
|
+
const SUPPORTED_MANIFEST_VERSION = 1;
|
|
2150
|
+
/**
|
|
2151
|
+
* 索引清单是否**真的**覆盖这个工作区。
|
|
2152
|
+
*
|
|
2153
|
+
* 只判「文件在不在」是不够的,两种实况都会把它判成有索引而实际检索必然失败:
|
|
2154
|
+
* - 文件在,但内容不是一份清单(半截写入、被别的东西占了同名文件)——解析失败即不算。
|
|
2155
|
+
* - 清单在,但索引的根路径不覆盖这个目录(例如指向另一个盘符/被改写过的路径)——此时
|
|
2156
|
+
* 在这个目录里检索会报「索引不可用」,而门禁却按「已建索引」拦着 grep/rg。
|
|
2157
|
+
* - 清单的版本不是当前认的那一版——上游读它会直接抛 MANIFEST.INVALID(要求
|
|
2158
|
+
* `manifestVersion` 严格等于 `CURRENT_MANIFEST_VERSION`),此时本目录**一次检索都做不了**,
|
|
2159
|
+
* 却会被「是个数字」这种宽松判据放进门禁。故这里同样取严格相等。
|
|
2160
|
+
*
|
|
2161
|
+
* 认的结构只有真正用到的两处(实测上游的 workspace manifest 形状):
|
|
2162
|
+
* `manifestVersion` 严格等于 1,`rootPaths` 是非空数组且每项带一个非空 `absolutePath`。
|
|
2163
|
+
* 刻意不校验 embedding / policy 等字段——那些变了索引照样能用,判成「无索引」反而是错的。
|
|
2164
|
+
*
|
|
2165
|
+
* 覆盖判据是「归一后相等」。实测 macOS 上清单里写的是**未解析**路径(`/tmp/x`)而
|
|
2166
|
+
* `path` 字段才是解析过的(`/private/tmp/x`),会话 cwd 通常也是未解析那一支;但调用方
|
|
2167
|
+
* 完全可能交来解析过的形式,故两边都再剥一次 `/private` 前缀再比。
|
|
2168
|
+
*/
|
|
2169
|
+
function manifestCoversRoot(manifestPath, dir) {
|
|
2170
|
+
let parsed;
|
|
2171
|
+
try {
|
|
2172
|
+
parsed = JSON.parse(readFileSync(manifestPath, "utf8"));
|
|
2173
|
+
} catch {
|
|
2174
|
+
return false;
|
|
2175
|
+
}
|
|
2176
|
+
if (!isRecord(parsed) || !("manifestVersion" in parsed) || parsed["manifestVersion"] !== SUPPORTED_MANIFEST_VERSION) return false;
|
|
2177
|
+
const { rootPaths } = parsed;
|
|
2178
|
+
if (!Array.isArray(rootPaths) || rootPaths.length === 0) return false;
|
|
2179
|
+
const target = comparablePath(normalizeRoot(dir));
|
|
2180
|
+
return rootPaths.some((entry) => isRecord(entry) && typeof entry["absolutePath"] === "string" && entry["absolutePath"].length > 0 && comparablePath(normalizeRoot(entry["absolutePath"])) === target);
|
|
2181
|
+
}
|
|
1299
2182
|
/** zg 索引库存在性探测(search-first 门禁与 zg_search 登记共用)。
|
|
1300
2183
|
* 必须连 workspace manifest 一起看:`<dir>/.zvec-grep/` 这个名字被 zg 自己的**全局
|
|
1301
2184
|
* home** 征用(`ZVEC_GREP_HOME ?? ~/.zvec-grep`,装的是 config.json / locks / models),
|
|
@@ -1304,11 +2187,20 @@ function readEnforceSearchFirst(config) {
|
|
|
1304
2187
|
* manifest 是上游写索引时落的那一份(`writeWorkspaceManifest`),只有它在场,
|
|
1305
2188
|
* 才说明这个工作区真的建过索引。 */
|
|
1306
2189
|
function indexProbeOf(dir) {
|
|
1307
|
-
|
|
2190
|
+
const base = `${dir}/${INDEX_DIR_NAME}`;
|
|
2191
|
+
if (!existsSync(base) || !existsSync(`${base}/manifest.json`)) return false;
|
|
2192
|
+
return manifestCoversRoot(`${base}/${WORKSPACE_MANIFEST_FILE}`, dir);
|
|
1308
2193
|
}
|
|
1309
2194
|
/** 工具入参的 root:显式值 > 会话工作区,再过存在性预检(一处三工具共用)。 */
|
|
1310
|
-
function rootOf(args, exec, messages) {
|
|
1311
|
-
|
|
2195
|
+
function rootOf(args, exec, messages, ledger) {
|
|
2196
|
+
const cwd = sessionHeaderCwd(exec);
|
|
2197
|
+
const root = assertRootExists(resolveRoot(args["root"], cwd, messages), messages);
|
|
2198
|
+
if (!ledger.has(root) && (cwd === void 0 || !pathsRelated(root, cwd, messages))) throw new Error(fill(messages.rootNotAuthorized, {
|
|
2199
|
+
root,
|
|
2200
|
+
cwd: cwd ?? messages.rootNoSession
|
|
2201
|
+
}));
|
|
2202
|
+
ledger.add(root);
|
|
2203
|
+
return root;
|
|
1312
2204
|
}
|
|
1313
2205
|
function define(host, spec) {
|
|
1314
2206
|
const { parameters } = spec;
|
|
@@ -1343,7 +2235,8 @@ function define(host, spec) {
|
|
|
1343
2235
|
* 0.1.7 迁移要点(两处都是静默失效,写错不报错):
|
|
1344
2236
|
* - `.volatile()` 决定字段是否进设置表单。宿主 `describe()` 只投影 volatile 字段
|
|
1345
2237
|
* (packages/settings/settings/src/schema.ts 的 volatileForm),全漏标则整条被跳过
|
|
1346
|
-
* (settings/src/index.ts
|
|
2238
|
+
* (settings/src/index.ts 里 `volatileForm(schema)` 空判即 `return []` 的那一处)、写入抛
|
|
2239
|
+
* `has no volatile fields`(同文件的那句 throw)。
|
|
1347
2240
|
* - `settings.register(ns, schema, { base })` 的「底座」层已被宿主移除:内置默认逐字段
|
|
1348
2241
|
* 落成下面的 `.default()`(原 BUILTIN_BASE 原样搬来,单一来源),cordis 装载期按同一
|
|
1349
2242
|
* 份 schema 校验行 config 并填默认,再把 volatile 字段包成引用交给 apply。
|
|
@@ -1359,7 +2252,17 @@ const configSchema = Schema.object({
|
|
|
1359
2252
|
searchTimeoutMs: Schema.natural().min(1).default(SEARCH_TIMEOUT_MS),
|
|
1360
2253
|
statusTimeoutMs: Schema.natural().min(1).default(STATUS_TIMEOUT_MS),
|
|
1361
2254
|
indexTimeoutMs: Schema.natural().min(1).default(INDEX_TIMEOUT_MS),
|
|
1362
|
-
stdoutMaxBytes: Schema.natural().min(1).default(STDOUT_MAX_BYTES)
|
|
2255
|
+
stdoutMaxBytes: Schema.natural().min(1).default(STDOUT_MAX_BYTES),
|
|
2256
|
+
clientMode: Schema.union([
|
|
2257
|
+
"auto",
|
|
2258
|
+
"direct",
|
|
2259
|
+
"server"
|
|
2260
|
+
]).default(DEFAULT_CLIENT_MODE),
|
|
2261
|
+
rebuildWaitMs: Schema.natural().min(1).default(REBUILD_WAIT_MS),
|
|
2262
|
+
allowRemoteEmbedding: Schema.boolean().default(false),
|
|
2263
|
+
remoteEmbeddingEndpoint: Schema.string().default(""),
|
|
2264
|
+
remoteEmbeddingApiKeyFrom: Schema.string().default(""),
|
|
2265
|
+
requireApprovalForExplicitRoot: Schema.boolean().default(false)
|
|
1363
2266
|
});
|
|
1364
2267
|
/** 官方注册表里本包作业的 kind;宿主据此发出的 id 形如 `zvec-grep-rebuild-N`。 */
|
|
1365
2268
|
const REBUILD_JOB_KIND = "zvec-grep-rebuild";
|
|
@@ -1399,7 +2302,7 @@ function killProc(proc) {
|
|
|
1399
2302
|
* 拖垮泵"的兜。选 pull 而不是生产者 push(`JobHandle.append`)是复核
|
|
1400
2303
|
* 后按实测定下的:
|
|
1401
2304
|
* - `proc.observed[*].readFrom` 是**非消费**的独立观察者面(installed dsh-shell
|
|
1402
|
-
* types.d.ts
|
|
2305
|
+
* types.d.ts:"without stealing bytes from `readOutput`"),与本包前台用的
|
|
1403
2306
|
* 消费式游标互不干扰——此前本仓写的"官方泵会与 readOutput 争同一份游标"是错的;
|
|
1404
2307
|
* - 泵按注册表自己的节拍跑(实测默认 150ms,落定前再排最后一次)⇒ **卡片关着环也前进**,
|
|
1405
2308
|
* 模型侧 job_output 随时看得见进度;push 形态把可见性绑在了轮询上。
|
|
@@ -1493,7 +2396,7 @@ function capacityLimitOf(error) {
|
|
|
1493
2396
|
* 「工作区重建」动作端点的四道前置校验:绝对路径 + 归一化、本 daemon 观测过的白名单、
|
|
1494
2397
|
* 目录此刻仍存在。不过就把错误就地答完并返回 undefined(错误文本全走双语字典)。
|
|
1495
2398
|
*
|
|
1496
|
-
* 这四道是**动作**端点的闸门:webServer
|
|
2399
|
+
* 这四道是**动作**端点的闸门:webServer 可被绑到本机网卡的具体地址,没有白名单的话任何能连上
|
|
1497
2400
|
* 服务面的一方都能拿任意绝对路径去 `zg index --rebuild`——读遍那棵树、写 `.zvec-grep/`,
|
|
1498
2401
|
* 还可能把其中的非隐藏敏感文件灌进向量库并回显到上下文。
|
|
1499
2402
|
* @param req 请求对象
|
|
@@ -1536,14 +2439,14 @@ function acceptableRebuildRoot(req, res, ledger, started) {
|
|
|
1536
2439
|
* "状态还在跑/正在收"。第二条不能省:jobs 被重载之后 id 会重名,只查侧表就把一张新面板
|
|
1537
2440
|
* 领到别人的作业上。
|
|
1538
2441
|
* 就地答完(200 + 复用旗标)并返回 true ⇒ 调用方直接 return;否则返回 false 继续起进程。
|
|
1539
|
-
* @param jobs
|
|
2442
|
+
* @param jobs 调用方已确认在场的注册表(缺席那一支在启动端点更早就答过 503)
|
|
1540
2443
|
* @param records 本包侧表
|
|
1541
2444
|
* @param res 响应对象
|
|
1542
2445
|
* @param root 已归一化的工作区
|
|
1543
2446
|
* @returns 是否已把这张面板领到在跑的那条上(领到了就地答完 200)
|
|
1544
2447
|
*/
|
|
1545
2448
|
function followRunningRebuild(jobs, records, res, root) {
|
|
1546
|
-
const following =
|
|
2449
|
+
const following = [...records.values()].find((record) => {
|
|
1547
2450
|
if (record.root !== root) return false;
|
|
1548
2451
|
const view = jobView(jobs, record.id);
|
|
1549
2452
|
return view !== null && sameJob(record.state, view, jobs) && isLiveStatus(view.status);
|
|
@@ -1557,24 +2460,21 @@ function followRunningRebuild(jobs, records, res, root) {
|
|
|
1557
2460
|
return true;
|
|
1558
2461
|
}
|
|
1559
2462
|
/**
|
|
1560
|
-
*
|
|
2463
|
+
* 把「起一条 zg 失败」的原因翻成卡片文案。
|
|
1561
2464
|
*
|
|
1562
|
-
*
|
|
1563
|
-
*
|
|
1564
|
-
*
|
|
1565
|
-
*
|
|
2465
|
+
* **本函数不再杀进程**:杀现在由 `attachIndexWrite` 负责——它才是真正握着那条进程句柄、
|
|
2466
|
+
* 且知道作业有没有登记成功的地方(preflight 在 controller/容量/入参上拒掉作业时,spawn
|
|
2467
|
+
* 已经发生,不杀就会留下一条没登记、谁也停不掉的 zg)。这里只管文案。
|
|
2468
|
+
*
|
|
2469
|
+
* 满员那一档单独翻文案:它是本包唯一会把宿主英文原话插进卡片的错误,又最该翻成人话
|
|
2470
|
+
* (用户要做的是去 job_list 收作业,不是读一句英文)。
|
|
1566
2471
|
* @param error 官方件(或本包 starter)抛出的原因
|
|
1567
|
-
* @param proc 已经起来的 zg 进程
|
|
1568
2472
|
* @param started 本次请求语言的文案表
|
|
1569
|
-
* @returns
|
|
2473
|
+
* @returns 可直接进响应体的错误文案
|
|
1570
2474
|
*/
|
|
1571
|
-
function
|
|
1572
|
-
killProc(proc);
|
|
2475
|
+
function startupFailureText(error, started) {
|
|
1573
2476
|
const capacity = capacityLimitOf(error);
|
|
1574
|
-
|
|
1575
|
-
ok: false,
|
|
1576
|
-
error: capacity === void 0 ? fill(started.endpointStartFailed, { reason: errorText(error) }) : fill(started.endpointJobsAtCapacity, { limit: capacity })
|
|
1577
|
-
});
|
|
2477
|
+
return capacity === void 0 ? fill(started.endpointStartFailed, { reason: errorText(error) }) : fill(started.endpointJobsAtCapacity, { limit: capacity });
|
|
1578
2478
|
}
|
|
1579
2479
|
/**
|
|
1580
2480
|
* 在 controller 闸门下起一条未拥有作业。
|
|
@@ -1619,13 +2519,36 @@ function ledgerKey(root, messages) {
|
|
|
1619
2519
|
return key;
|
|
1620
2520
|
}
|
|
1621
2521
|
/**
|
|
1622
|
-
*
|
|
1623
|
-
*
|
|
2522
|
+
* 淘汰一张常驻表:先按**有效期**丢过期项,再按**最近使用**丢最老项到不超过上限。
|
|
2523
|
+
*
|
|
2524
|
+
* 为什么不是纯插入序(原 `trimMapTo`):`Map` 的插入序在 `delete` 后重排,故「插入序淘汰」
|
|
2525
|
+
* 实际是「最早插入且此后没被重新插入的先走」——一张每轮都被 `set` 命中的表(解锁额度就是,
|
|
2526
|
+
* 每次成功检索都重置同一批键)永远淘汰不掉真正冷掉的项,而一条很久没被碰过的键会一直占位。
|
|
2527
|
+
* 改成:命中即触摸(`delete` + `set` 把键挪到队尾),淘汰从队首取。这样「最久没用过」
|
|
2528
|
+
* 才有确定含义。
|
|
2529
|
+
*
|
|
2530
|
+
* 有效期同样必要:一个只在半小时前出现过一次的工作区,到明天早就不该还占着白名单名额。
|
|
2531
|
+
* 两者都保留,故上界(内存有界)与语义(冷掉的先走)同时成立。
|
|
2532
|
+
*
|
|
2533
|
+
* @param map 目标表(就地改)
|
|
2534
|
+
* @param max 条数上限
|
|
2535
|
+
* @param expiresAt 取某条目的过期时刻;无则视为永不过期
|
|
2536
|
+
* @param now 当前时刻(epoch ms)
|
|
1624
2537
|
*/
|
|
1625
|
-
function
|
|
1626
|
-
const
|
|
1627
|
-
|
|
1628
|
-
|
|
2538
|
+
function evictAged(map, max, expiresAt, now) {
|
|
2539
|
+
for (const [key, value] of map) {
|
|
2540
|
+
const expiry = expiresAt(value);
|
|
2541
|
+
if (expiry !== void 0 && expiry <= now) map.delete(key);
|
|
2542
|
+
}
|
|
2543
|
+
for (const key of map.keys()) {
|
|
2544
|
+
if (map.size <= max) break;
|
|
2545
|
+
map.delete(key);
|
|
2546
|
+
}
|
|
2547
|
+
}
|
|
2548
|
+
/** 命中即触摸:把键挪到队尾,使「最近使用」在插入序上成立。 */
|
|
2549
|
+
function touch(map, key, value) {
|
|
2550
|
+
map.delete(key);
|
|
2551
|
+
map.set(key, value);
|
|
1629
2552
|
}
|
|
1630
2553
|
/** 探测缓存的 TTL(ms):负向条目(当时无索引)的陈旧上界,选型论证见下。 */
|
|
1631
2554
|
const INDEX_PROBE_TTL_MS = 6e4;
|
|
@@ -1658,8 +2581,7 @@ function createIndexProbeCache(probe, now = Date.now, ttlMs = INDEX_PROBE_TTL_MS
|
|
|
1658
2581
|
const at = now();
|
|
1659
2582
|
const hit = cache.get(dir);
|
|
1660
2583
|
if (hit !== void 0 && at - hit.probedAt < ttlMs) {
|
|
1661
|
-
cache
|
|
1662
|
-
cache.set(dir, hit);
|
|
2584
|
+
touch(cache, dir, hit);
|
|
1663
2585
|
return hit.result;
|
|
1664
2586
|
}
|
|
1665
2587
|
const result = probe(dir);
|
|
@@ -1668,22 +2590,35 @@ function createIndexProbeCache(probe, now = Date.now, ttlMs = INDEX_PROBE_TTL_MS
|
|
|
1668
2590
|
result,
|
|
1669
2591
|
probedAt: at
|
|
1670
2592
|
});
|
|
1671
|
-
|
|
2593
|
+
evictAged(cache, max, (entry) => entry.probedAt + ttlMs, at);
|
|
1672
2594
|
return result;
|
|
1673
2595
|
};
|
|
1674
2596
|
}
|
|
1675
|
-
|
|
2597
|
+
/**
|
|
2598
|
+
* 工作区白名单:只认本 daemon 真实观测过的会话工作区(重建端点与 root 授权共用)。
|
|
2599
|
+
*
|
|
2600
|
+
* 条目记的是**最后一次被提到**的时刻,不是第一次:白名单的用途是「这棵树刚被用过」,
|
|
2601
|
+
* 一直热着的键理应活得比冷键久。故 `has` 命中即触摸,淘汰先按有效期、再按最近使用。
|
|
2602
|
+
* 有效期是固定的 `LEDGER_TTL_MS`(一天),与解锁时效那个部署值无关——后者只有 1–240 分钟
|
|
2603
|
+
* 的取值域,量级差两个数量级,拿来当「这棵树多久算还在用」会短到让跨天的会话反复重新登记。
|
|
2604
|
+
* 上界与有效期两道都留着:上界保证常驻内存有界,有效期保证冷键不长期占位。
|
|
2605
|
+
*/
|
|
2606
|
+
function createRootLedger(messages, max = MAX_LEDGER_ROOTS, now = Date.now, ttlMs = LEDGER_TTL_MS) {
|
|
1676
2607
|
const seen = /* @__PURE__ */ new Map();
|
|
1677
2608
|
return {
|
|
1678
2609
|
add(root) {
|
|
1679
2610
|
const key = ledgerKey(root, messages);
|
|
1680
2611
|
if (key === void 0) return;
|
|
1681
|
-
seen
|
|
1682
|
-
|
|
2612
|
+
touch(seen, key, now());
|
|
2613
|
+
evictAged(seen, max, (seenAt) => seenAt + ttlMs, now());
|
|
1683
2614
|
},
|
|
1684
2615
|
has(root) {
|
|
1685
2616
|
const key = ledgerKey(root, messages);
|
|
1686
|
-
|
|
2617
|
+
if (key === void 0) return false;
|
|
2618
|
+
const seenAt = seen.get(key);
|
|
2619
|
+
if (seenAt === void 0 || now() - seenAt >= ttlMs) return false;
|
|
2620
|
+
touch(seen, key, seenAt);
|
|
2621
|
+
return true;
|
|
1687
2622
|
},
|
|
1688
2623
|
list() {
|
|
1689
2624
|
return [...seen.keys()];
|
|
@@ -1717,7 +2652,7 @@ function handleRebuildRoots(routes, req, res) {
|
|
|
1717
2652
|
* @param command 实际执行的命令行(作业 label,模型在 job_list 里看见的那句)
|
|
1718
2653
|
* @returns 官方 JobSpec:kind / label / output / run
|
|
1719
2654
|
*/
|
|
1720
|
-
function rebuildJobSpec(routes, proc, state, command) {
|
|
2655
|
+
function rebuildJobSpec(routes, proc, state, command, root) {
|
|
1721
2656
|
const { config, host, jobsOf, messages } = routes;
|
|
1722
2657
|
return {
|
|
1723
2658
|
kind: REBUILD_JOB_KIND,
|
|
@@ -1753,32 +2688,41 @@ function rebuildJobSpec(routes, proc, state, command) {
|
|
|
1753
2688
|
done: (async () => {
|
|
1754
2689
|
await proc.done;
|
|
1755
2690
|
cancelKillTimer();
|
|
1756
|
-
|
|
2691
|
+
try {
|
|
2692
|
+
return jobOutcomeOf(proc);
|
|
2693
|
+
} finally {
|
|
2694
|
+
routes.rebuilds.release(root);
|
|
2695
|
+
}
|
|
1757
2696
|
})()
|
|
1758
2697
|
};
|
|
1759
2698
|
}
|
|
1760
2699
|
};
|
|
1761
2700
|
}
|
|
1762
2701
|
/**
|
|
1763
|
-
*
|
|
1764
|
-
*
|
|
1765
|
-
*
|
|
1766
|
-
*
|
|
1767
|
-
*
|
|
2702
|
+
* 起一条 `zg index`:命令构造 + resolve + execute 三步。
|
|
2703
|
+
*
|
|
2704
|
+
* 设置卡重建端点与模型侧后台索引**共用**这一个函数(不是复制品),所以两条入口起的作业
|
|
2705
|
+
* 在名册、状态投影、轮询端点上完全同形。命令形态由 `indexArgs` 决定,故它也服务普通建索引。
|
|
2706
|
+
*
|
|
2707
|
+
* 版本门槛排在命令构造**之前**:确知装的是太老的 zg 时,在这一行就给出可照做的指引,
|
|
2708
|
+
* 而不是起一条命令形态对不上的 zg 再让人对着结果猜。注意这个顺序也保证了「门槛失败」
|
|
2709
|
+
* 发生在任何进程存在之前,调用方那条 `release` 出口足以收干净。
|
|
2710
|
+
*
|
|
2711
|
+
* 任一步抛错即就地翻成 `{ error, status }`;**本函数不写响应、不释放占位**,两件事都由
|
|
2712
|
+
* 调用方做(它们才持有 root 与响应对象)。
|
|
2713
|
+
* @param routes 本次注册的共享依赖(现读 config / host / jobsOf)
|
|
1768
2714
|
* @param started 本次请求语言的文案表
|
|
1769
|
-
* @
|
|
2715
|
+
* @param indexArgs 已归一 root 的索引入参
|
|
2716
|
+
* @param embedding 设置里的默认 embedding(`indexArgs.embedding` 为空时用它)
|
|
2717
|
+
* @returns 起来的进程与它跑的命令;失败为 `{ error, status }`
|
|
1770
2718
|
*/
|
|
1771
|
-
async function
|
|
2719
|
+
async function spawnIndexWrite(routes, started, indexArgs, embedding) {
|
|
1772
2720
|
const { config, host } = routes;
|
|
1773
|
-
const embedding = readDefaultEmbedding(config);
|
|
1774
2721
|
let spawned;
|
|
1775
2722
|
try {
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
rebuild: true
|
|
1780
|
-
}, embedding, started);
|
|
1781
|
-
const env = hfEndpointEnv(config);
|
|
2723
|
+
await routes.versionGate.ensure(started);
|
|
2724
|
+
const built = buildIndexCommand(indexArgs, embedding, started, readClientMode(config, started), allowRemoteEmbedding(config));
|
|
2725
|
+
const env = zgEnv(config);
|
|
1782
2726
|
const spec = host.shell.resolve({
|
|
1783
2727
|
command: built.command,
|
|
1784
2728
|
workdir: built.workdir,
|
|
@@ -1791,35 +2735,35 @@ async function spawnRebuildProcess(routes, res, root, started) {
|
|
|
1791
2735
|
command: built.command
|
|
1792
2736
|
};
|
|
1793
2737
|
} catch (error) {
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
}
|
|
1798
|
-
return null;
|
|
2738
|
+
return {
|
|
2739
|
+
error: fill(started.endpointStartFailed, { reason: errorText(error) }),
|
|
2740
|
+
status: 500
|
|
2741
|
+
};
|
|
1799
2742
|
}
|
|
1800
2743
|
return spawned;
|
|
1801
2744
|
}
|
|
1802
2745
|
/**
|
|
1803
2746
|
* 把起来的那条进程登记进官方注册表与本包侧表,交回宿主签发的 id。
|
|
1804
|
-
*
|
|
2747
|
+
*
|
|
2748
|
+
* 三种失败(注册表换人 / 同名不同命 / start 抛错)都**先把那条进程杀掉**再交回错误:
|
|
2749
|
+
* 此刻作业没进名册,没人能通过 job 工具收它,不杀就是一条孤儿 zg 占着这棵树的写锁。
|
|
2750
|
+
* 同样地,本函数不写响应、不释放占位——那两件事由调用方做。
|
|
1805
2751
|
* @param routes 本次注册的共享依赖(jobsOf 现读、侧表引用)
|
|
1806
|
-
* @param res 响应对象(失败时由本函数就地应答)
|
|
1807
2752
|
* @param root 已过前置校验的工作区(写进侧表供卡片回显)
|
|
1808
2753
|
* @param started 本次请求语言的文案表
|
|
1809
|
-
* @param spawned
|
|
1810
|
-
* @returns 宿主签发的
|
|
2754
|
+
* @param spawned spawnIndexWrite 交回的进程与命令
|
|
2755
|
+
* @returns 宿主签发的 `{ jobId }`;失败为 `{ error, status }`
|
|
1811
2756
|
*/
|
|
1812
|
-
function
|
|
2757
|
+
function attachIndexWrite(routes, root, started, spawned) {
|
|
1813
2758
|
const { jobsOf, records } = routes;
|
|
1814
2759
|
const { proc, command } = spawned;
|
|
1815
2760
|
const starting = jobsOf();
|
|
1816
2761
|
if (starting === void 0) {
|
|
1817
2762
|
killProc(proc);
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
}
|
|
1822
|
-
return null;
|
|
2763
|
+
return {
|
|
2764
|
+
error: started.endpointJobsUnavailable,
|
|
2765
|
+
status: 503
|
|
2766
|
+
};
|
|
1823
2767
|
}
|
|
1824
2768
|
pruneRebuildHistory(starting, records);
|
|
1825
2769
|
const state = {
|
|
@@ -1830,17 +2774,16 @@ function attachRebuildJob(routes, res, root, started, spawned) {
|
|
|
1830
2774
|
};
|
|
1831
2775
|
let jobId;
|
|
1832
2776
|
try {
|
|
1833
|
-
jobId = startUnderController(starting, rebuildJobSpec(routes, proc, state, command));
|
|
2777
|
+
jobId = startUnderController(starting, rebuildJobSpec(routes, proc, state, command, root));
|
|
1834
2778
|
state.bornAt = starting.get(jobId).startedAt;
|
|
1835
2779
|
state.owner = starting;
|
|
1836
2780
|
const clashed = records.get(jobId);
|
|
1837
2781
|
if (clashed !== void 0 && clashed.state.owner !== starting) {
|
|
1838
2782
|
killProc(proc);
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
}
|
|
1843
|
-
return null;
|
|
2783
|
+
return {
|
|
2784
|
+
error: started.endpointRegistryReplaced,
|
|
2785
|
+
status: 503
|
|
2786
|
+
};
|
|
1844
2787
|
}
|
|
1845
2788
|
records.set(jobId, {
|
|
1846
2789
|
proc,
|
|
@@ -1849,10 +2792,13 @@ function attachRebuildJob(routes, res, root, started, spawned) {
|
|
|
1849
2792
|
state
|
|
1850
2793
|
});
|
|
1851
2794
|
} catch (error) {
|
|
1852
|
-
|
|
1853
|
-
return
|
|
2795
|
+
killProc(proc);
|
|
2796
|
+
return {
|
|
2797
|
+
error: startupFailureText(error, started),
|
|
2798
|
+
status: 500
|
|
2799
|
+
};
|
|
1854
2800
|
}
|
|
1855
|
-
return jobId;
|
|
2801
|
+
return { jobId };
|
|
1856
2802
|
}
|
|
1857
2803
|
/** 启动端点:四道前置校验(同源 / CSRF / 白名单 / 目录存在)后复用或起一条重建。 */
|
|
1858
2804
|
async function handleRebuildStart(routes, req, res) {
|
|
@@ -1876,21 +2822,48 @@ async function handleRebuildStart(routes, req, res) {
|
|
|
1876
2822
|
const started = messages();
|
|
1877
2823
|
const root = acceptableRebuildRoot(req, res, ledger, started);
|
|
1878
2824
|
if (root === null) return;
|
|
1879
|
-
|
|
1880
|
-
if (
|
|
2825
|
+
const jobs = jobsOf();
|
|
2826
|
+
if (jobs === void 0) {
|
|
1881
2827
|
sendJson(res, 503, {
|
|
1882
2828
|
ok: false,
|
|
1883
2829
|
error: started.endpointJobsUnavailable
|
|
1884
2830
|
});
|
|
1885
2831
|
return;
|
|
1886
2832
|
}
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
2833
|
+
if (routes.rebuilds.claim(root, "card") === null) {
|
|
2834
|
+
if (!followRunningRebuild(jobs, records, res, root)) sendJson(res, 409, {
|
|
2835
|
+
ok: false,
|
|
2836
|
+
error: started.endpointRebuildInFlight
|
|
2837
|
+
});
|
|
2838
|
+
return;
|
|
2839
|
+
}
|
|
2840
|
+
const embedding = readDefaultEmbedding(routes.config);
|
|
2841
|
+
const spawned = await spawnIndexWrite(routes, started, {
|
|
2842
|
+
root,
|
|
2843
|
+
embedding,
|
|
2844
|
+
rebuild: true
|
|
2845
|
+
}, embedding);
|
|
2846
|
+
if ("error" in spawned) {
|
|
2847
|
+
routes.rebuilds.release(root);
|
|
2848
|
+
sendJson(res, spawned.status, {
|
|
2849
|
+
ok: false,
|
|
2850
|
+
error: spawned.error
|
|
2851
|
+
});
|
|
2852
|
+
return;
|
|
2853
|
+
}
|
|
2854
|
+
const attached = attachIndexWrite(routes, root, started, spawned);
|
|
2855
|
+
if ("error" in attached) {
|
|
2856
|
+
routes.rebuilds.release(root);
|
|
2857
|
+
sendJson(res, attached.status, {
|
|
2858
|
+
ok: false,
|
|
2859
|
+
error: attached.error
|
|
2860
|
+
});
|
|
2861
|
+
return;
|
|
2862
|
+
}
|
|
2863
|
+
routes.rebuilds.attach(root, attached.jobId);
|
|
1891
2864
|
sendJson(res, 200, {
|
|
1892
2865
|
ok: true,
|
|
1893
|
-
jobId
|
|
2866
|
+
jobId: attached.jobId
|
|
1894
2867
|
});
|
|
1895
2868
|
}
|
|
1896
2869
|
/** 轮询端点:官方状态投影 + 退出码/沙箱事实 + 打标后的输出尾窗(卡片每 2s 敲一次)。 */
|
|
@@ -1966,11 +2939,12 @@ function releaseRebuildRecords(routes) {
|
|
|
1966
2939
|
}
|
|
1967
2940
|
/** 设置卡片的「工作区重建」端点组(引导 / 启动 / 轮询)。按语义拆离 apply 主体。 */
|
|
1968
2941
|
function registerRebuildEndpoints(deps) {
|
|
1969
|
-
const { ctx, host, config, csrf, ledger, messages } = deps;
|
|
2942
|
+
const { ctx, host, config, csrf, ledger, messages, rebuilds, versionGate } = deps;
|
|
1970
2943
|
const webServer = host.get("webServer");
|
|
1971
2944
|
if (!webServer) return;
|
|
1972
|
-
const servingNonLoopback = webServer.host
|
|
1973
|
-
const jobsOf =
|
|
2945
|
+
const servingNonLoopback = isNonLoopbackBindHost(webServer.host);
|
|
2946
|
+
const { jobsOf } = deps;
|
|
2947
|
+
const { records } = deps;
|
|
1974
2948
|
const routes = {
|
|
1975
2949
|
host,
|
|
1976
2950
|
config,
|
|
@@ -1978,7 +2952,9 @@ function registerRebuildEndpoints(deps) {
|
|
|
1978
2952
|
ledger,
|
|
1979
2953
|
messages,
|
|
1980
2954
|
jobsOf,
|
|
1981
|
-
records
|
|
2955
|
+
records,
|
|
2956
|
+
rebuilds,
|
|
2957
|
+
versionGate,
|
|
1982
2958
|
servingNonLoopback
|
|
1983
2959
|
};
|
|
1984
2960
|
const disposeRoots = webServer.register({
|
|
@@ -2042,8 +3018,21 @@ function trackObservedRoot(ledger, exec) {
|
|
|
2042
3018
|
const cwd = sessionHeaderCwd(exec);
|
|
2043
3019
|
if (cwd !== void 0) ledger.add(cwd);
|
|
2044
3020
|
}
|
|
2045
|
-
/**
|
|
3021
|
+
/** 会话分片的条数上限:常驻进程只增不减会随会话数无界增长,超上限按最近使用淘汰最冷的分片。 */
|
|
2046
3022
|
const MAX_UNLOCK_SESSIONS = 256;
|
|
3023
|
+
/** 分片表里的额度条目自带 expiresAt,分片层面没有有效期可言。 */
|
|
3024
|
+
function noExpiry() {}
|
|
3025
|
+
/**
|
|
3026
|
+
* 配额分片键 = 会话沿父链上溯到的**根**会话 id。
|
|
3027
|
+
*
|
|
3028
|
+
* 分片用根而不是自己,是为了让同一棵委派树共享一份额度:主代理搜过一次,子代理随即就能用
|
|
3029
|
+
* 那几次 grep/rg。否则「语义检索优先」在多代理下等于失效——每个子代理都得自己搜一次才解锁,
|
|
3030
|
+
* 而它们搜的往往是同一棵树。缺席会话查询面时 `sessionParent` 为 undefined,查找恒返回
|
|
3031
|
+
* undefined,上溯自然停在「有父用父、无父用自己」,不会阻断任何调用。
|
|
3032
|
+
*/
|
|
3033
|
+
function quotaKeyOf(runtime, execution) {
|
|
3034
|
+
return rootSessionKeyOf(execution, runtime.sessionParent);
|
|
3035
|
+
}
|
|
2047
3036
|
/**
|
|
2048
3037
|
* search-first 门禁解锁表:会话 → (归一化索引根 → 解锁额度)。
|
|
2049
3038
|
* 每次成功 zg_search 发放 grepBudgetPerSearch 次配额、unlockWindowMin 分钟有效;
|
|
@@ -2052,7 +3041,7 @@ const MAX_UNLOCK_SESSIONS = 256;
|
|
|
2052
3041
|
* @param config apply 收到的那份 volatile 引用配置
|
|
2053
3042
|
* @returns 会话解锁表(随 apply 闭包里的 Map 一起生死)
|
|
2054
3043
|
*/
|
|
2055
|
-
function createUnlockLedger(config) {
|
|
3044
|
+
function createUnlockLedger(config, now = Date.now) {
|
|
2056
3045
|
const unlocksBySession = /* @__PURE__ */ new Map();
|
|
2057
3046
|
return {
|
|
2058
3047
|
grant(key, indexRoot) {
|
|
@@ -2060,21 +3049,59 @@ function createUnlockLedger(config) {
|
|
|
2060
3049
|
if (byRoot === void 0) {
|
|
2061
3050
|
byRoot = /* @__PURE__ */ new Map();
|
|
2062
3051
|
unlocksBySession.set(key, byRoot);
|
|
2063
|
-
trimMapTo(unlocksBySession, MAX_UNLOCK_SESSIONS);
|
|
2064
3052
|
}
|
|
2065
3053
|
byRoot.set(normalizeRoot(indexRoot), {
|
|
2066
3054
|
grepsLeft: readGrepBudget(config),
|
|
2067
|
-
expiresAt:
|
|
3055
|
+
expiresAt: now() + readUnlockWindowMin(config) * 6e4
|
|
2068
3056
|
});
|
|
3057
|
+
touch(unlocksBySession, key, byRoot);
|
|
3058
|
+
evictAged(unlocksBySession, MAX_UNLOCK_SESSIONS, noExpiry, now());
|
|
2069
3059
|
},
|
|
3060
|
+
/**
|
|
3061
|
+
* 只查不判有效期:门禁要把「过期」与「从未检索过」分成两种拒绝理由,那份区分权在门禁
|
|
3062
|
+
* 手上。这里若把过期条目删掉再答 undefined,门禁就再也分不出这两者、只能一律说成
|
|
3063
|
+
* 「尚未执行过 zg_search」——把一句有用的提示降级成一句误导的提示。
|
|
3064
|
+
* 触碰(LRU)只对真正还在生效的额度做。
|
|
3065
|
+
*/
|
|
2070
3066
|
lookup(sessionKey, indexRoot) {
|
|
2071
|
-
|
|
3067
|
+
const byRoot = unlocksBySession.get(sessionKey);
|
|
3068
|
+
const unlock = byRoot === void 0 ? void 0 : byRoot.get(normalizeRoot(indexRoot));
|
|
3069
|
+
if (byRoot !== void 0 && unlock !== void 0 && unlock.expiresAt > now()) touch(unlocksBySession, sessionKey, byRoot);
|
|
3070
|
+
return unlock;
|
|
2072
3071
|
},
|
|
2073
3072
|
consume(unlock) {
|
|
2074
3073
|
unlock.grepsLeft -= 1;
|
|
2075
3074
|
}
|
|
2076
3075
|
};
|
|
2077
3076
|
}
|
|
3077
|
+
/**
|
|
3078
|
+
* 路径过滤类参数的 JSON Schema:单个字符串或字符串数组。
|
|
3079
|
+
*
|
|
3080
|
+
* 用 `oneOf` 而不是更常见的 `anyOf`:宿主对工具参数面执行的是一个**受限子集**,
|
|
3081
|
+
* `anyOf` 不在其中(实测 `assertSupportedJsonSchema` 报 `anyOf is not a supported
|
|
3082
|
+
* keyword`),`oneOf` 才被接受,且至少要两个分支。`description` 是标注、与 `oneOf` 并存
|
|
3083
|
+
* 不冲突(实测通过),所以描述不丢。
|
|
3084
|
+
*
|
|
3085
|
+
* 之所以要单值:上游 zg 对这几项的对外契约就是「字符串或字符串数组」的并集,模型照着
|
|
3086
|
+
* 那个习惯只给一个 glob 很正常;取值侧 lib/argv-guard.ts 的 singleOrList 两种都收。
|
|
3087
|
+
*/
|
|
3088
|
+
function pathFilterParameter(description) {
|
|
3089
|
+
return {
|
|
3090
|
+
oneOf: [{ type: "string" }, {
|
|
3091
|
+
type: "array",
|
|
3092
|
+
items: { type: "string" }
|
|
3093
|
+
}],
|
|
3094
|
+
description
|
|
3095
|
+
};
|
|
3096
|
+
}
|
|
3097
|
+
/** 闭集枚举参数的 JSON Schema:取值与取值器共用同一份名单,不两处硬编码。 */
|
|
3098
|
+
function enumParameter(values, description) {
|
|
3099
|
+
return {
|
|
3100
|
+
type: "string",
|
|
3101
|
+
enum: [...values],
|
|
3102
|
+
description
|
|
3103
|
+
};
|
|
3104
|
+
}
|
|
2078
3105
|
/** zg_search 的参数面:逐字段描述都取注册期文案(与 parameters 同生死)。 */
|
|
2079
3106
|
function searchToolParameters(registered) {
|
|
2080
3107
|
return {
|
|
@@ -2107,39 +3134,36 @@ function searchToolParameters(registered) {
|
|
|
2107
3134
|
type: "boolean",
|
|
2108
3135
|
description: registered.fuseDescription
|
|
2109
3136
|
},
|
|
3137
|
+
rg: {
|
|
3138
|
+
type: "boolean",
|
|
3139
|
+
description: registered.rgDescription
|
|
3140
|
+
},
|
|
2110
3141
|
limit: {
|
|
2111
3142
|
type: "integer",
|
|
2112
3143
|
description: registered.limitDescription
|
|
2113
3144
|
},
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
type: "array",
|
|
2121
|
-
items: { type: "string" },
|
|
2122
|
-
description: registered.insensitiveGlobsDescription
|
|
2123
|
-
},
|
|
2124
|
-
fileTypes: {
|
|
2125
|
-
type: "array",
|
|
2126
|
-
items: { type: "string" },
|
|
2127
|
-
description: registered.fileTypesDescription
|
|
2128
|
-
},
|
|
2129
|
-
excludedFileTypes: {
|
|
2130
|
-
type: "array",
|
|
2131
|
-
items: { type: "string" },
|
|
2132
|
-
description: registered.excludedFileTypesDescription
|
|
2133
|
-
},
|
|
3145
|
+
preview: enumParameter(PREVIEW_NAMES, registered.previewDescription),
|
|
3146
|
+
refresh: enumParameter(REFRESH_NAMES, registered.refreshDescription),
|
|
3147
|
+
globs: pathFilterParameter(registered.globsDescription),
|
|
3148
|
+
insensitiveGlobs: pathFilterParameter(registered.insensitiveGlobsDescription),
|
|
3149
|
+
fileTypes: pathFilterParameter(registered.fileTypesDescription),
|
|
3150
|
+
excludedFileTypes: pathFilterParameter(registered.excludedFileTypesDescription),
|
|
2134
3151
|
symbolTypes: {
|
|
2135
3152
|
type: "array",
|
|
2136
|
-
items: {
|
|
3153
|
+
items: {
|
|
3154
|
+
type: "string",
|
|
3155
|
+
enum: [...SYMBOL_TYPE_NAMES]
|
|
3156
|
+
},
|
|
2137
3157
|
description: registered.symbolTypesDescription
|
|
2138
3158
|
},
|
|
2139
3159
|
preferSymbol: {
|
|
2140
3160
|
type: "boolean",
|
|
2141
3161
|
description: registered.preferSymbolDescription
|
|
2142
3162
|
},
|
|
3163
|
+
trace: {
|
|
3164
|
+
type: "boolean",
|
|
3165
|
+
description: registered.traceDescription
|
|
3166
|
+
},
|
|
2143
3167
|
modifiedAfter: {
|
|
2144
3168
|
type: "string",
|
|
2145
3169
|
description: registered.modifiedAfterDescription
|
|
@@ -2156,7 +3180,23 @@ function searchToolParameters(registered) {
|
|
|
2156
3180
|
};
|
|
2157
3181
|
}
|
|
2158
3182
|
/**
|
|
2159
|
-
*
|
|
3183
|
+
* 检索通道判据:`rg` 显式给就照办,没给就看有没有索引。
|
|
3184
|
+
*
|
|
3185
|
+
* rg=true → 穷举词法(不需要索引)
|
|
3186
|
+
* rg=false → 只走索引检索(无索引时让 zg 报 WORKSPACE_INDEX_NOT_FOUND,附带建索引提示)
|
|
3187
|
+
* rg 未给 → 有索引走索引检索,没有索引改走穷举词法
|
|
3188
|
+
*
|
|
3189
|
+
* 缺省之所以自动兜底而不是直接报错:工作区没有索引是**常态**而非异常(新克隆的仓库就是),
|
|
3190
|
+
* 而报错会把模型推向 `zg_index`——那意味着先下载 embedding 权重。对「先看看这个仓库里
|
|
3191
|
+
* 有什么」这类问题,逐行字面匹配就是够的,兜底不是妥协。自动改道的代价由 runSearchTool
|
|
3192
|
+
* 里的前置声明来偿。
|
|
3193
|
+
*/
|
|
3194
|
+
function pickExhaustive(value, hasIndex) {
|
|
3195
|
+
if (typeof value === "boolean") return value;
|
|
3196
|
+
return !hasIndex;
|
|
3197
|
+
}
|
|
3198
|
+
/**
|
|
3199
|
+
* zg_search 的执行体:登记工作区 → 选通道 → 构造命令 → 前台执行 → 索引通道成功才发配额。
|
|
2160
3200
|
* @param runtime apply 的运行时依赖(config 现读、解锁表与探测缓存共用)
|
|
2161
3201
|
* @param args 官方 deep-frozen 后的工具入参
|
|
2162
3202
|
* @param exec 执行面(signal / 会话工作区)
|
|
@@ -2166,23 +3206,32 @@ function searchToolParameters(registered) {
|
|
|
2166
3206
|
async function runSearchTool(runtime, args, exec, messages) {
|
|
2167
3207
|
const { config, host, indexProbe, ledger, unlocks } = runtime;
|
|
2168
3208
|
trackObservedRoot(ledger, exec);
|
|
2169
|
-
const resolvedRoot = rootOf(args, exec, messages);
|
|
3209
|
+
const resolvedRoot = rootOf(args, exec, messages, ledger);
|
|
3210
|
+
const indexRoot = findIndexRoot(resolvedRoot, indexProbe);
|
|
3211
|
+
const explicit = args["rg"];
|
|
3212
|
+
const exhaustive = pickExhaustive(explicit, indexRoot !== void 0);
|
|
3213
|
+
const fallback = exhaustive && explicit === void 0 && indexRoot === void 0 ? messages.exhaustiveFallbackNote : void 0;
|
|
2170
3214
|
const searchArgs = {
|
|
2171
3215
|
...args,
|
|
2172
3216
|
root: resolvedRoot,
|
|
2173
3217
|
limit: args["limit"] ?? readDefaultLimit(config)
|
|
2174
3218
|
};
|
|
2175
|
-
|
|
2176
|
-
const
|
|
3219
|
+
await runtime.versionGate.ensure(messages);
|
|
3220
|
+
const { command, workdir } = buildSearchCommand(searchArgs, messages, readClientMode(config, messages), exhaustive);
|
|
3221
|
+
const raw = await runForeground(host, command, workdir, config.searchTimeoutMs, {
|
|
2177
3222
|
signal: exec.signal,
|
|
2178
|
-
env:
|
|
3223
|
+
env: zgEnv(config),
|
|
2179
3224
|
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
2180
3225
|
messages,
|
|
2181
|
-
summaryLimit: clampLimit(searchArgs.limit)
|
|
3226
|
+
summaryLimit: clampLimit(searchArgs.limit),
|
|
3227
|
+
rebuildWait: {
|
|
3228
|
+
root: resolvedRoot,
|
|
3229
|
+
rebuilds: runtime.rebuilds,
|
|
3230
|
+
maxWaitMs: config.rebuildWaitMs
|
|
3231
|
+
}
|
|
2182
3232
|
});
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
return { text };
|
|
3233
|
+
if (indexRoot !== void 0 && !exhaustive) unlocks.grant(quotaKeyOf(runtime, exec), indexRoot);
|
|
3234
|
+
return { text: fallback === void 0 ? raw : `${fallback}\n${raw}` };
|
|
2186
3235
|
}
|
|
2187
3236
|
/** 注册 zg_search:语义/混合检索。 */
|
|
2188
3237
|
function registerSearchTool(runtime, registered) {
|
|
@@ -2219,30 +3268,14 @@ function indexToolParameters(registered) {
|
|
|
2219
3268
|
type: "boolean",
|
|
2220
3269
|
description: registered.dropDescription
|
|
2221
3270
|
},
|
|
2222
|
-
globs:
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
type: "
|
|
2229
|
-
|
|
2230
|
-
description: registered.insensitiveGlobsDescription
|
|
2231
|
-
},
|
|
2232
|
-
fileTypes: {
|
|
2233
|
-
type: "array",
|
|
2234
|
-
items: { type: "string" },
|
|
2235
|
-
description: registered.fileTypesIndexDescription
|
|
2236
|
-
},
|
|
2237
|
-
excludedFileTypes: {
|
|
2238
|
-
type: "array",
|
|
2239
|
-
items: { type: "string" },
|
|
2240
|
-
description: registered.excludedFileTypesDescription
|
|
2241
|
-
},
|
|
2242
|
-
ignoreFiles: {
|
|
2243
|
-
type: "array",
|
|
2244
|
-
items: { type: "string" },
|
|
2245
|
-
description: registered.ignoreFilesDescription
|
|
3271
|
+
globs: pathFilterParameter(registered.globsIndexDescription),
|
|
3272
|
+
insensitiveGlobs: pathFilterParameter(registered.insensitiveGlobsDescription),
|
|
3273
|
+
fileTypes: pathFilterParameter(registered.fileTypesIndexDescription),
|
|
3274
|
+
excludedFileTypes: pathFilterParameter(registered.excludedFileTypesDescription),
|
|
3275
|
+
ignoreFiles: pathFilterParameter(registered.ignoreFilesDescription),
|
|
3276
|
+
background: {
|
|
3277
|
+
type: "boolean",
|
|
3278
|
+
description: registered.backgroundDescription
|
|
2246
3279
|
},
|
|
2247
3280
|
excludeSecrets: {
|
|
2248
3281
|
type: "boolean",
|
|
@@ -2275,33 +3308,108 @@ function indexToolParameters(registered) {
|
|
|
2275
3308
|
device: {
|
|
2276
3309
|
type: "string",
|
|
2277
3310
|
description: registered.deviceDescription
|
|
3311
|
+
},
|
|
3312
|
+
resetPaths: {
|
|
3313
|
+
type: "boolean",
|
|
3314
|
+
description: registered.resetPathsDescription
|
|
2278
3315
|
}
|
|
2279
3316
|
},
|
|
2280
3317
|
required: ["confirm"]
|
|
2281
3318
|
};
|
|
2282
3319
|
}
|
|
2283
3320
|
/**
|
|
2284
|
-
*
|
|
3321
|
+
* 模型侧的后台建/重建:一次调用把「起进程 + 登记作业 + 挂超时回收」全做完,把可轮询的
|
|
3322
|
+
* 作业号交回模型,然后立刻返回。
|
|
3323
|
+
*
|
|
3324
|
+
* 为什么不要求模型自己去起作业:宿主作业工具在 web 平面已停用,模型侧那条路根本不可走;
|
|
3325
|
+
* 插件自己复用与设置卡**完全相同**的 spawn/登记/占位三步(`spawnIndexWrite` 与
|
|
3326
|
+
* `attachIndexWrite` 是同两个函数,不是复制品),所以两条入口起的作业在名册、状态投影、
|
|
3327
|
+
* 轮询端点上完全同形——卡片能看见模型起的重建,反之亦然。
|
|
3328
|
+
*
|
|
3329
|
+
* 占位在 `runIndexTool` 里、且落在第一个 await 之前就抢好了;本函数只管把已占的位接上作业号。
|
|
3330
|
+
* 三条失败出口(注册表缺席 / spawn 失败 / attach 失败)都**交还占位**再抛或答复。
|
|
2285
3331
|
* @param runtime apply 的运行时依赖
|
|
2286
|
-
* @param
|
|
2287
|
-
* @param
|
|
3332
|
+
* @param root 已过授权与存在性预检的工作区
|
|
3333
|
+
* @param indexArgs 已归一 root 的索引入参
|
|
2288
3334
|
* @param messages 本次 execute 现取的文案表
|
|
2289
3335
|
* @returns 交给官方 output schema 的 `{ text }`
|
|
2290
3336
|
*/
|
|
3337
|
+
async function startBackgroundIndex(runtime, root, indexArgs, messages) {
|
|
3338
|
+
const routes = {
|
|
3339
|
+
host: runtime.host,
|
|
3340
|
+
config: runtime.config,
|
|
3341
|
+
csrf: "",
|
|
3342
|
+
ledger: runtime.ledger,
|
|
3343
|
+
messages: runtime.messages,
|
|
3344
|
+
jobsOf: runtime.jobsOf,
|
|
3345
|
+
records: runtime.records,
|
|
3346
|
+
rebuilds: runtime.rebuilds,
|
|
3347
|
+
versionGate: runtime.versionGate,
|
|
3348
|
+
servingNonLoopback: false
|
|
3349
|
+
};
|
|
3350
|
+
if (runtime.jobsOf() === void 0) {
|
|
3351
|
+
runtime.rebuilds.release(root);
|
|
3352
|
+
throw new Error(messages.endpointJobsUnavailable);
|
|
3353
|
+
}
|
|
3354
|
+
const spawned = await spawnIndexWrite(routes, messages, indexArgs, readDefaultEmbedding(runtime.config));
|
|
3355
|
+
if ("error" in spawned) {
|
|
3356
|
+
runtime.rebuilds.release(root);
|
|
3357
|
+
throw new Error(spawned.error);
|
|
3358
|
+
}
|
|
3359
|
+
const attached = attachIndexWrite(routes, root, messages, spawned);
|
|
3360
|
+
if ("error" in attached) {
|
|
3361
|
+
runtime.rebuilds.release(root);
|
|
3362
|
+
throw new Error(attached.error);
|
|
3363
|
+
}
|
|
3364
|
+
runtime.rebuilds.attach(root, attached.jobId);
|
|
3365
|
+
return { text: fill(messages.indexBackgroundStarted, {
|
|
3366
|
+
root,
|
|
3367
|
+
jobId: attached.jobId,
|
|
3368
|
+
command: spawned.command
|
|
3369
|
+
}) };
|
|
3370
|
+
}
|
|
2291
3371
|
async function runIndexTool(runtime, args, exec, messages) {
|
|
2292
|
-
const { config, host, ledger } = runtime;
|
|
3372
|
+
const { config, host, ledger, rebuilds } = runtime;
|
|
2293
3373
|
trackObservedRoot(ledger, exec);
|
|
2294
|
-
const
|
|
3374
|
+
const root = rootOf(args, exec, messages, ledger);
|
|
3375
|
+
const indexArgs = {
|
|
2295
3376
|
...args,
|
|
2296
|
-
root
|
|
2297
|
-
}
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
3377
|
+
root
|
|
3378
|
+
};
|
|
3379
|
+
const background = boolOf(args["background"], "background", messages);
|
|
3380
|
+
const rewriting = boolOf(args["rebuild"], "rebuild", messages) || background;
|
|
3381
|
+
await runtime.versionGate.ensure(messages);
|
|
3382
|
+
if (rewriting && rebuilds.claim(root, "tool") === null) return { text: fill(messages.indexRebuildInFlight, { root }) };
|
|
3383
|
+
if (background) return startBackgroundIndex(runtime, root, indexArgs, messages);
|
|
3384
|
+
try {
|
|
3385
|
+
const { command, workdir } = buildIndexCommand(indexArgs, readDefaultEmbedding(config), messages, readClientMode(config, messages), allowRemoteEmbedding(config));
|
|
3386
|
+
return { text: await runForeground(host, command, workdir, config.indexTimeoutMs, {
|
|
3387
|
+
signal: exec.signal,
|
|
3388
|
+
env: zgEnv(config),
|
|
3389
|
+
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
3390
|
+
messages
|
|
3391
|
+
}) };
|
|
3392
|
+
} finally {
|
|
3393
|
+
if (rewriting) rebuilds.release(root);
|
|
3394
|
+
}
|
|
2304
3395
|
}
|
|
3396
|
+
/**
|
|
3397
|
+
* 模型侧的后台建/重建:一次调用把「起进程 + 登记作业 + 挂超时回收」全做完,把可轮询的
|
|
3398
|
+
* 作业号交回模型,然后立刻返回。
|
|
3399
|
+
*
|
|
3400
|
+
* 为什么不要求模型自己去起作业:宿主作业工具在 web 平面已停用,模型侧那条路根本不可走;
|
|
3401
|
+
* 插件自己复用与设置卡**完全相同**的 spawn/登记/占位三步(`spawnIndexWrite` 与
|
|
3402
|
+
* `attachIndexWrite` 是同两个函数,不是复制品),所以两条入口起的作业在名册、状态投影、
|
|
3403
|
+
* 轮询端点上完全同形——卡片能看见模型起的重建,反之亦然。
|
|
3404
|
+
*
|
|
3405
|
+
* 占位在 `runIndexTool` 里、且落在第一个 await 之前就抢好了;本函数只管把已占的位接上作业号。
|
|
3406
|
+
* 三条失败出口(注册表缺席 / spawn 失败 / attach 失败)都**交还占位**再抛或答复。
|
|
3407
|
+
* @param runtime apply 的运行时依赖
|
|
3408
|
+
* @param root 已过授权与存在性预检的工作区
|
|
3409
|
+
* @param indexArgs 已归一 root 的索引入参
|
|
3410
|
+
* @param messages 本次 execute 现取的文案表
|
|
3411
|
+
* @returns 交给官方 output schema 的 `{ text }`
|
|
3412
|
+
*/
|
|
2305
3413
|
/** 注册 zg_index:建/重建/删索引。 */
|
|
2306
3414
|
function registerIndexTool(runtime, registered) {
|
|
2307
3415
|
define(runtime.host, {
|
|
@@ -2321,14 +3429,37 @@ function registerIndexTool(runtime, registered) {
|
|
|
2321
3429
|
* @returns 交给官方 output schema 的 `{ text }`
|
|
2322
3430
|
*/
|
|
2323
3431
|
async function runStatusTool(runtime, args, exec, messages) {
|
|
2324
|
-
const { config, host, ledger } = runtime;
|
|
3432
|
+
const { config, host, ledger, rebuilds } = runtime;
|
|
2325
3433
|
trackObservedRoot(ledger, exec);
|
|
2326
|
-
const
|
|
3434
|
+
const root = rootOf(args, exec, messages, ledger);
|
|
3435
|
+
const entry = rebuilds.covering(root, messages);
|
|
3436
|
+
if (entry?.jobId !== void 0) return { text: fill(messages.statusRebuilding, {
|
|
3437
|
+
root: entry.root,
|
|
3438
|
+
jobId: entry.jobId
|
|
3439
|
+
}) };
|
|
3440
|
+
const checkReady = boolOf(args["checkReady"], "checkReady", messages);
|
|
3441
|
+
await runtime.versionGate.ensure(messages);
|
|
3442
|
+
const { command, workdir } = buildStatusCommand({
|
|
3443
|
+
root,
|
|
3444
|
+
checkReady
|
|
3445
|
+
}, messages, readClientMode(config, messages));
|
|
2327
3446
|
return { text: await runForeground(host, command, workdir, config.statusTimeoutMs, {
|
|
2328
3447
|
signal: exec.signal,
|
|
2329
|
-
env:
|
|
3448
|
+
env: zgEnv(config),
|
|
2330
3449
|
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
2331
|
-
messages
|
|
3450
|
+
messages,
|
|
3451
|
+
rebuildWait: {
|
|
3452
|
+
root,
|
|
3453
|
+
rebuilds,
|
|
3454
|
+
maxWaitMs: config.rebuildWaitMs
|
|
3455
|
+
},
|
|
3456
|
+
...checkReady ? { resolveFailure: (failure, result) => {
|
|
3457
|
+
const report = result.stdout.text.trim();
|
|
3458
|
+
return report.length > 0 ? `${report}\n${fill(messages.statusNotReady, {
|
|
3459
|
+
root,
|
|
3460
|
+
detail: failure
|
|
3461
|
+
})}` : null;
|
|
3462
|
+
} } : {}
|
|
2332
3463
|
}) };
|
|
2333
3464
|
}
|
|
2334
3465
|
/** 注册 zg_status:索引状态。 */
|
|
@@ -2339,10 +3470,16 @@ function registerStatusTool(runtime, registered) {
|
|
|
2339
3470
|
messages: runtime.messages,
|
|
2340
3471
|
parameters: {
|
|
2341
3472
|
type: "object",
|
|
2342
|
-
properties: {
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
3473
|
+
properties: {
|
|
3474
|
+
root: {
|
|
3475
|
+
type: "string",
|
|
3476
|
+
description: registered.rootStatusDescription
|
|
3477
|
+
},
|
|
3478
|
+
checkReady: {
|
|
3479
|
+
type: "boolean",
|
|
3480
|
+
description: registered.checkReadyDescription
|
|
3481
|
+
}
|
|
3482
|
+
}
|
|
2346
3483
|
},
|
|
2347
3484
|
run: (args, exec, messages) => runStatusTool(runtime, args, exec, messages)
|
|
2348
3485
|
});
|
|
@@ -2371,11 +3508,59 @@ function registerRoutingSection(host, registered) {
|
|
|
2371
3508
|
* 这里不给 `execution` 标注类型:官方 ToolGuard 交出 `Readonly<ToolExecution>`,
|
|
2372
3509
|
* 于是 name/arguments/signal/agent 的键名与值域都由宿主声明负责——两个谓词收到的
|
|
2373
3510
|
* 是本包加宽后的读取投影(lib/routing.ts),加宽即容错,收窄校验留在谓词内部。
|
|
2374
|
-
* @param runtime apply 的运行时依赖
|
|
2375
|
-
* @returns {void}
|
|
2376
3511
|
*/
|
|
3512
|
+
/** 显式 root 归一后是否就是本会话工作区;解析不了(畸形参数)一律交回 false。 */
|
|
3513
|
+
function sameAsSessionRoot(raw, cwd, messages) {
|
|
3514
|
+
if (cwd === void 0) return false;
|
|
3515
|
+
try {
|
|
3516
|
+
return normalizeRoot(resolveRoot(raw, cwd, messages)) === normalizeRoot(cwd);
|
|
3517
|
+
} catch {
|
|
3518
|
+
return false;
|
|
3519
|
+
}
|
|
3520
|
+
}
|
|
3521
|
+
/** 该不该为这次调用问一句;不该问就交回 undefined(调用方转交 next())。 */
|
|
3522
|
+
function explicitRootAsk(execution, ledger, messages) {
|
|
3523
|
+
const raw = (isRecord(execution.arguments) ? execution.arguments : void 0)?.["root"];
|
|
3524
|
+
const cwd = sessionHeaderCwd(execution);
|
|
3525
|
+
return typeof raw !== "string" || raw.trim().length === 0 || sameAsSessionRoot(raw, cwd, messages) || cwd !== void 0 && ledger.has(raw) ? void 0 : {
|
|
3526
|
+
kind: "ask",
|
|
3527
|
+
reason: fill(messages.rootApprovalReason, {
|
|
3528
|
+
root: raw,
|
|
3529
|
+
cwd: cwd ?? messages.rootNoSession
|
|
3530
|
+
}),
|
|
3531
|
+
displayReason: {
|
|
3532
|
+
en: fill(MESSAGES.en.rootApprovalPrompt, { root: raw }),
|
|
3533
|
+
zh: fill(MESSAGES.zh.rootApprovalPrompt, { root: raw })
|
|
3534
|
+
}
|
|
3535
|
+
};
|
|
3536
|
+
}
|
|
3537
|
+
/**
|
|
3538
|
+
* 显式 root 的用户确认闸(官方一等的确认面,**默认关**)。
|
|
3539
|
+
*
|
|
3540
|
+
* 为什么必须是 `tools/pre-execute` 而不是 `tools.guard`:`ToolGuard` 的返回只有
|
|
3541
|
+
* `string | undefined`(一串拒绝理由),它能**拒**但不能**问**——没有「允许」这个结果。
|
|
3542
|
+
* 能问的只有 pre-execute 瀑布:返回 `{ kind: 'ask' }` 后由宿主路由到 `ctx.approval.request()`,
|
|
3543
|
+
* 用户点「允许一次」才放行;approval 服务缺席、或策略是 `never`(danger-full-access 预设 /
|
|
3544
|
+
* 委派子代理)时,宿主把 ask **确定性降级成拒绝**(core/tools 的 serviceAsk)。
|
|
3545
|
+
*
|
|
3546
|
+
* 问的是哪一类调用:三个 zg 工具里,**显式给了 root**、且那个 root 既不是本会话工作区、
|
|
3547
|
+
* 也不在本包已登记的根集合里。也就是 rootOf() 走「互为祖先/后代」那条放行路径时——
|
|
3548
|
+
* 会话开在 /repo/pkg 而模型要去检索 /repo,用户最该被问一句的就是这种。
|
|
3549
|
+
*
|
|
3550
|
+
* 这道闸**只加不减**:`rootOf` 的授权判据一字未改,root 不存在/越界照样被拒。
|
|
3551
|
+
* 用户批准只对本次调用生效,不会把那个 root 写进白名单(那是 rootOf 成功后的事)。
|
|
3552
|
+
*/
|
|
3553
|
+
function registerRootApproval(runtime) {
|
|
3554
|
+
const { config, host, ledger, messages: localeMessages } = runtime;
|
|
3555
|
+
host.on("tools/pre-execute", (execution, next) => {
|
|
3556
|
+
if (!config.requireApprovalForExplicitRoot) return next();
|
|
3557
|
+
if (!isZgToolName(execution.name)) return next();
|
|
3558
|
+
const ask = explicitRootAsk(execution, ledger, localeMessages());
|
|
3559
|
+
return ask === void 0 ? next() : Promise.resolve(ask);
|
|
3560
|
+
});
|
|
3561
|
+
}
|
|
2377
3562
|
function registerToolGuards(runtime) {
|
|
2378
|
-
const { config, host, indexProbe, ledger, messages: localeMessages, unlocks } = runtime;
|
|
3563
|
+
const { config, host, indexProbe, ledger, messages: localeMessages, rebuilds, unlocks } = runtime;
|
|
2379
3564
|
host.tools.guard((execution) => {
|
|
2380
3565
|
trackObservedRoot(ledger, execution);
|
|
2381
3566
|
const messages = localeMessages();
|
|
@@ -2387,10 +3572,11 @@ function registerToolGuards(runtime) {
|
|
|
2387
3572
|
now: () => Date.now(),
|
|
2388
3573
|
grepBudget: readGrepBudget(config),
|
|
2389
3574
|
windowMin: readUnlockWindowMin(config),
|
|
2390
|
-
lookupUnlock: (indexRoot) => unlocks.lookup(
|
|
3575
|
+
lookupUnlock: (indexRoot) => unlocks.lookup(quotaKeyOf(runtime, execution), indexRoot),
|
|
2391
3576
|
consumeGrep: (unlock) => {
|
|
2392
3577
|
unlocks.consume(unlock);
|
|
2393
|
-
}
|
|
3578
|
+
},
|
|
3579
|
+
rebuildBypass: (indexRoot) => rebuilds.covering(indexRoot, messages) !== void 0
|
|
2394
3580
|
}, messages);
|
|
2395
3581
|
});
|
|
2396
3582
|
}
|
|
@@ -2398,11 +3584,11 @@ function registerToolGuards(runtime) {
|
|
|
2398
3584
|
* 设置卡片的「工作区重建」端点组(引导 + 后台进程 + 轮询状态)。
|
|
2399
3585
|
*
|
|
2400
3586
|
* ⚠ 这三条路由的归属方必须对 webServer **建立依赖**,不能在 apply 里读一次就算完:
|
|
2401
|
-
* `ctx.get` 是无 inject 语义的存储读(官方 reflect.d.ts
|
|
3587
|
+
* `ctx.get` 是无 inject 语义的存储读(官方 reflect.d.ts 明写 "or `undefined`
|
|
2402
3588
|
* when not (yet) provided"),而真实宿主上 webServer 比本条目晚到位——隔离 DSH_HOME
|
|
2403
3589
|
* 实测 apply 当场读到 undefined、+1.3s 才交得出实例。旧写法的结果是三条路由在任何
|
|
2404
3590
|
* web profile 上都不注册,卡片的「工作区重建」永远 404。子 fiber 只在依赖到位时激活、
|
|
2405
|
-
* 依赖换实例时先卸后装(registry.d.ts
|
|
3591
|
+
* 依赖换实例时先卸后装(registry.d.ts),故效应挂在**子上下文**上即得「后到即注册、
|
|
2406
3592
|
* 重启即重注册」。不写进插件级 inject:那会让没有 webServer 的宿主(TUI)连三个工具
|
|
2407
3593
|
* 一并失活。
|
|
2408
3594
|
* @param runtime apply 的运行时依赖(host / config / 白名单 / 文案读取器)
|
|
@@ -2410,7 +3596,7 @@ function registerToolGuards(runtime) {
|
|
|
2410
3596
|
* @returns {void}
|
|
2411
3597
|
*/
|
|
2412
3598
|
function registerRebuildRoutes(runtime, csrf) {
|
|
2413
|
-
const { config, host, ledger, messages } = runtime;
|
|
3599
|
+
const { config, host, ledger, messages, rebuilds, versionGate } = runtime;
|
|
2414
3600
|
host.inject(["webServer"], (child) => {
|
|
2415
3601
|
registerRebuildEndpoints({
|
|
2416
3602
|
ctx: child,
|
|
@@ -2418,7 +3604,11 @@ function registerRebuildRoutes(runtime, csrf) {
|
|
|
2418
3604
|
config,
|
|
2419
3605
|
csrf,
|
|
2420
3606
|
ledger,
|
|
2421
|
-
messages
|
|
3607
|
+
messages,
|
|
3608
|
+
rebuilds,
|
|
3609
|
+
jobsOf: runtime.jobsOf,
|
|
3610
|
+
records: runtime.records,
|
|
3611
|
+
versionGate
|
|
2422
3612
|
});
|
|
2423
3613
|
});
|
|
2424
3614
|
}
|
|
@@ -2434,12 +3624,22 @@ function apply(ctx, config) {
|
|
|
2434
3624
|
messages: localeMessages,
|
|
2435
3625
|
ledger: createRootLedger(localeMessages()),
|
|
2436
3626
|
unlocks: createUnlockLedger(config),
|
|
2437
|
-
indexProbe: createIndexProbeCache(indexProbeOf)
|
|
3627
|
+
indexProbe: createIndexProbeCache(indexProbeOf),
|
|
3628
|
+
rebuilds: createRebuildRegistry(),
|
|
3629
|
+
versionGate: createZgVersionGate(host, config),
|
|
3630
|
+
jobsOf: () => host.get("jobs"),
|
|
3631
|
+
records: /* @__PURE__ */ new Map(),
|
|
3632
|
+
sessionParent: (id) => {
|
|
3633
|
+
const sessions = host.get("sessions");
|
|
3634
|
+
const found = sessions === void 0 ? void 0 : sessions.list().find((entry) => entry.id === id);
|
|
3635
|
+
return found === void 0 ? void 0 : { parentSession: found.header.parentSession };
|
|
3636
|
+
}
|
|
2438
3637
|
};
|
|
2439
3638
|
const registered = localeMessages();
|
|
2440
3639
|
registerZvecTools(runtime, registered);
|
|
2441
3640
|
registerRoutingSection(host, registered);
|
|
2442
3641
|
registerToolGuards(runtime);
|
|
3642
|
+
registerRootApproval(runtime);
|
|
2443
3643
|
registerRebuildRoutes(runtime, csrf);
|
|
2444
3644
|
}
|
|
2445
3645
|
var host_default = {
|
|
@@ -2454,4 +3654,4 @@ var host_default = {
|
|
|
2454
3654
|
apply
|
|
2455
3655
|
};
|
|
2456
3656
|
//#endregion
|
|
2457
|
-
export { configSchema as Config, INDEX_PROBE_CACHE_MAX, INDEX_PROBE_TTL_MS, createIndexProbeCache, host_default as default, hitSummary };
|
|
3657
|
+
export { configSchema as Config, INDEX_PROBE_CACHE_MAX, INDEX_PROBE_TTL_MS, createIndexProbeCache, createRootLedger, createUnlockLedger, host_default as default, hitSummary, signalStderr };
|