@jayyuen66/dsh-zvec-grep 0.1.0

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/host.js ADDED
@@ -0,0 +1,2457 @@
1
+ // GENERATED by build-host.mjs — edit host.ts / lib/*.ts, then run `node build-host.mjs`.
2
+ import Schema from "@deepseek-ai/schemastery";
3
+ import { existsSync } from "node:fs";
4
+ import { randomUUID } from "node:crypto";
5
+ import { guardBody, queryParam, sendJson } from "@jayyuen66/dsh-plugin-shared/lib/http";
6
+ import { guardTrust } from "@jayyuen66/dsh-plugin-shared/lib/trust";
7
+ import { isRecord } from "@jayyuen66/dsh-plugin-shared/lib/record";
8
+ import { errorText } from "@jayyuen66/dsh-plugin-shared/lib/errors";
9
+ import { LOCALE_SETTINGS_NAMESPACE, messagesFor, resolveLocalePreference } from "@jayyuen66/dsh-plugin-shared/lib/locale";
10
+ import { truncateEnd, truncateStart } from "@jayyuen66/dsh-plugin-shared/lib/text";
11
+ import { jobOutcomeOf } from "@jayyuen66/dsh-plugin-shared/lib/job-outcome";
12
+ //#region lib/embedding-catalog.ts
13
+ /** 默认模型:本地最强(1024 维 / 8192 上下文 / 中英通用),约 640MB 一次性下载。 */
14
+ const DEFAULT_EMBEDDING = "local/qwen3-embedding-0.6b";
15
+ /**
16
+ * transformers.js 后端的 id。清单里 384/768 维的那批纯 JS ONNX 小模型都挂这一档,
17
+ * 故取值归一处;带 `LocalEmbeddingBackend` 标注,枚举成员改名时这里当场编译红,
18
+ * 而不是静默产出一个不在联合里的字符串。
19
+ */
20
+ const TRANSFORMERS_JS_BACKEND = "transformers-js";
21
+ /**
22
+ * 本地候选清单,按后端分三档(体积/语言口径,实测 zg v0.2.1):
23
+ * - llama-cpp:qwen3-embedding-0.6b 约 640MB(本包默认)、
24
+ * embeddinggemma-300m 约 300MB(英文)——两档都要原生件,Metal 加速由 zg 侧 device=auto 试;
25
+ * - model2vec:potion-code-16m-v2 约 32MB(代码专用、最轻最快)、potion-multilingual-128m
26
+ * (多语言轻量)、potion-retrieval-32m(通用检索)——纯 JS worker,零原生依赖;
27
+ * - transformers-js:其余 ONNX 小模型,384 维那批是英文/多语言轻量档,768 维那批里
28
+ * jina 面向代码、gte/nomic 面向 8192 长文。
29
+ */
30
+ const LOCAL_EMBEDDINGS = [
31
+ {
32
+ reference: "local/qwen3-embedding-0.6b",
33
+ backend: "llama-cpp",
34
+ dimension: 1024
35
+ },
36
+ {
37
+ reference: "local/embeddinggemma-300m",
38
+ backend: "llama-cpp",
39
+ dimension: 768
40
+ },
41
+ {
42
+ reference: "local/potion-code-16m-v2",
43
+ backend: "model2vec",
44
+ dimension: 256
45
+ },
46
+ {
47
+ reference: "local/potion-multilingual-128m",
48
+ backend: "model2vec",
49
+ dimension: 256
50
+ },
51
+ {
52
+ reference: "local/potion-retrieval-32m",
53
+ backend: "model2vec",
54
+ dimension: 512
55
+ },
56
+ {
57
+ reference: "local/bge-small-en-v1.5",
58
+ backend: TRANSFORMERS_JS_BACKEND,
59
+ dimension: 384
60
+ },
61
+ {
62
+ reference: "local/all-minilm-l6-v2",
63
+ backend: TRANSFORMERS_JS_BACKEND,
64
+ dimension: 384
65
+ },
66
+ {
67
+ reference: "local/multilingual-e5-small",
68
+ backend: TRANSFORMERS_JS_BACKEND,
69
+ dimension: 384
70
+ },
71
+ {
72
+ reference: "local/jina-embeddings-v2-base-code",
73
+ backend: TRANSFORMERS_JS_BACKEND,
74
+ dimension: 768
75
+ },
76
+ {
77
+ reference: "local/gte-modernbert-base",
78
+ backend: TRANSFORMERS_JS_BACKEND,
79
+ dimension: 768
80
+ },
81
+ {
82
+ reference: "local/nomic-embed-text-v1.5",
83
+ backend: TRANSFORMERS_JS_BACKEND,
84
+ dimension: 768
85
+ }
86
+ ];
87
+ function isLocalEmbedding(reference) {
88
+ return LOCAL_EMBEDDINGS.some((entry) => entry.reference === reference);
89
+ }
90
+ //#endregion
91
+ //#region lib/messages.ts
92
+ const MESSAGES = {
93
+ zh: {
94
+ 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 重新检索。",
95
+ indexToolDescription: "为工作区 root 创建/增量更新/重建/删除持久检索索引(建后 zg_search 才可用)。仅在用户明确要求建/重建/删索引时调用,且 confirm 必须为 true;绝不静默建索引。root 默认取当前会话工作区,也可显式指定其它绝对路径(需用户确认过的目标)。embedding 默认用设置里的 defaultEmbedding,也可显式指定;切换 embedding 需 rebuild=true 才重新生效。删除传 drop=true。",
96
+ statusToolDescription: "查询工作区 root 的索引状态(是否已建、文件数、freshness、活动任务)。用于索引缺失/失败/取消后的诊断或显式进度监控;普通搜索前不要调用。",
97
+ rootSearchDescription: "工作区绝对路径(可选:缺省=当前会话工作区;跨会话检索其它 root 时显式指定)",
98
+ rootIndexDescription: "工作区绝对路径(可选:缺省=当前会话工作区;跨会话操作其它 root 时显式指定)",
99
+ rootStatusDescription: "工作区绝对路径(可选:缺省=当前会话工作区)",
100
+ queryDescription: "单个混合查询(语义+词法)",
101
+ queriesDescription: "多个混合查询组",
102
+ ftsDescription: "词法查询组(如标识符、报错串)",
103
+ vectorDescription: "纯语义查询组",
104
+ fuseDescription: "融合所有组为单一排名",
105
+ limitDescription: "每组最大条数 1-50,默认 10",
106
+ globsDescription: "路径 glob(如 src/**)",
107
+ globsIndexDescription: "路径 glob",
108
+ insensitiveGlobsDescription: "大小写不敏感 glob",
109
+ fileTypesDescription: "文件类型(如 ts、py)",
110
+ fileTypesIndexDescription: "文件类型",
111
+ excludedFileTypesDescription: "排除的文件类型",
112
+ symbolTypesDescription: "符号类型过滤",
113
+ preferSymbolDescription: "优先精确符号",
114
+ modifiedAfterDescription: "只搜该时间后修改的文件",
115
+ modifiedBeforeDescription: "只搜该时间前修改的文件",
116
+ deviceDescription: "auto/cpu/metal/vulkan/cuda;默认 auto(Metal 加速,失败自动回退 CPU)",
117
+ confirmDescription: "用户已明确要求本次建/重建/删索引,必须为 true",
118
+ embeddingDescription: "本地 embedding 模型引用(默认取设置 defaultEmbedding)",
119
+ rebuildDescription: "重建已有索引(切换 embedding 时必须为 true)",
120
+ dropDescription: "删除索引(与其它索引选项互斥)",
121
+ ignoreFilesDescription: "额外的 ignore 文件路径(如 .gitignore 之外的排除清单),透传 zg --ignore-file",
122
+ excludeSecretsDescription: "是否默认排除私钥/密钥库格式(*.pem/*.key/*.p12/*.pfx/*.keystore/id_rsa*),默认 true;仅在明确需要索引此类文件时置 false",
123
+ hiddenDescription: "包含隐藏文件(默认不含,隐藏密钥文件因此已被排除)",
124
+ noIgnoreDescription: "不读 ignore 文件",
125
+ maxDepthDescription: "最大目录深度",
126
+ maxFileSizeBytesDescription: "单文件大小上限(字节)",
127
+ followDescription: "跟随符号链接",
128
+ embeddingConcurrencyDescription: "embedding 并发数",
129
+ routingText: [
130
+ "# zvec-grep(zg)工作区检索规则",
131
+ "",
132
+ "本环境的工作区检索路由:",
133
+ "- 工作区已建 zg 索引(存在 .zvec-grep/ 目录)时:所有检索必须先调用 zg_search(语义/混合,命中更全更准);grep/rg 只作为 zg_search 之后的精确字面/正则补充。每次成功的 zg_search 解锁少量 grep/rg 配额(次数/时效见设置),配额用尽或过期后门禁会再次拦截,此时应换一个更准确的 query/fts 重新 zg_search。门禁同时覆盖 bash 里的 grep/rg 命令与原生 grep 工具。",
134
+ "- 无索引工作区:精确查找(单个定义、字面量、文件名、配置键、报错信息、正则、穷举列表)→ 用原生 grep / glob / read。",
135
+ "- 语义/关系/跨文件/多跳证据(架构、调用链、依赖、生命周期、数据流或控制流、设计意图、对比、跨文件综合)→ 必须先调用 zg_search。",
136
+ "- zg_status 只用于索引缺失/失败/取消后的诊断或显式进度监控;普通搜索前不要调用。",
137
+ "",
138
+ "zg 规则:",
139
+ "1. 有索引的工作区先用 zg_search 定向发现,不要先做宽泛的文件枚举或直接 grep。",
140
+ "2. zg_search 结果已含有界源片段,视为已读证据;仅当所需细节在片段外时才用 read 打开对应文件/行段。",
141
+ "3. 证据足够即停止搜索,不为重复确认而重复相似查询或扩大排查。",
142
+ "4. zg_index 仅在用户明确要求建/重建/删索引时调用,且 confirm 必须为 true;绝不静默建索引。",
143
+ "5. 新建索引用用户选定的 embedding,未选定时不得臆测;切换 embedding 需 rebuild 才生效。",
144
+ "6. zg_* 的 root 可省略:缺省为当前会话工作区(绝对路径);显式传入时必须是 daemon 可见的绝对路径。"
145
+ ].join("\n"),
146
+ argsMustBeObject: "zg {name}: 参数必须是一个 JSON 对象(收到 {received})",
147
+ missingRequiredArgs: "zg {name}: 缺少必填参数 {fields}(缺失即拒绝,不产生副作用)",
148
+ sandboxFacts: "(沙箱 mode={mode}{enforcement})",
149
+ sandboxEnforcement: "、enforcement={value}",
150
+ runnerFailed: "zg 未执行:沙箱 runner 启动失败{facts}。请检查沙箱后端配置(这与 zg 是否安装无关)。",
151
+ sandboxDenied: "沙箱策略拒绝了一次文件操作{facts}",
152
+ detailMiddle: "{head} …[中间省略]… {tail}",
153
+ timeoutFailure: "zg 执行超时:检索默认带 --refresh wait(同步刷新既有索引),大型工作区可能耗时过长。请用 globs / fileTypes 缩小范围后重试,或先用手写 grep/glob。",
154
+ abortedFailure: "zg 执行被中止",
155
+ deniedFailure: "zg 执行失败(exit={exit}):{denied}——本次检索目标不在该会话可读写范围内,请换工作区或让用户批准更宽的文件策略。{detail}",
156
+ notInstalledFailure: "zg 未安装或不在 PATH:请先 `npm install -g @zvec/zvec-grep`。{detail}",
157
+ genericFailure: "zg 执行失败(exit={exit}){detail}",
158
+ detailPrefix: " 详情:{detail}",
159
+ detailColon: ":{detail}",
160
+ outputTruncated: "[zvec-grep] 注意:输出超过 {maxBytes} 字节上限,已截断,仅保留尾部{spill}。如需完整结果请缩小检索范围(更精确的 query / 更小的 limit / 更窄的 root)。",
161
+ spillNote: "(完整输出已落盘:{path})",
162
+ sandboxWarning: "[zvec-grep] 警告:{denied}——下面的结果可能缺少被拒读写的文件,别把它当成全工作区的完整检索结论。",
163
+ stderrNote: "[zvec-grep] zg stderr(可能含降级提示,如退化为纯词法检索 / 跳过 --refresh):{marked}{tail}",
164
+ hitSummary: "[zvec-grep] 命中摘要:{groups} 个查询组,共 {hits} 条命中;请求 --limit {limit}{capped}{truncated}",
165
+ hitCapped: "(已达单组上限,可能还有未显示的命中)",
166
+ hitTruncated: ";输出已截尾,计数只含保留部分",
167
+ rootMissing: "root 目录不存在(zg 需要真实存在的工作区路径):{root}",
168
+ jobOutputTruncated: "\n[zvec-grep] 输出过长,已截断,只保留尾部",
169
+ jobOutputLost: "\n[zvec-grep] 注意:执行器缓冲区溢出,zg 输出有**丢失**(下方不是完整日志);完整过程请看 zg 自身日志或缩小重建范围。",
170
+ rebuildRunnerFailed: "\n[zvec-grep] 重建失败:沙箱 runner 启动失败{facts}(zg 未被执行)。",
171
+ rebuildDenied: "\n[zvec-grep] 重建过程中{denied},索引可能不完整——请检查该会话的文件策略(read-only 下 zg 无法写 .zvec-grep/)。",
172
+ rebuildTimeout: "\n[zvec-grep] 重建超时(超过 {minutes} 分钟)已被强制终止",
173
+ jobReasonTimeout: "重建超过 {minutes} 分钟,由 zvec-grep 回收",
174
+ jobReasonUnload: "zvec-grep 插件卸载",
175
+ endpointRootInvalid: "root 无效:{reason}",
176
+ endpointRootUntracked: "root 不在本 daemon 观测到的工作区白名单内:{root}(可从卡片候选里选)",
177
+ endpointRootGone: "root 目录已不存在:{root}",
178
+ endpointStartFailed: "启动重建失败:{reason}",
179
+ endpointJobsUnavailable: "后台重建不可用:宿主未提供 ctx.jobs(@deepseek-ai/dsh-jobs-local 未装载),本插件不再自带任务注册表",
180
+ endpointRegistryReplaced: "后台作业服务已被替换(新注册表重新从同一个 id 开始签发作业),本次重建已放弃并终止:请重载 zvec-grep 插件后再发起,否则旧面板会跟着另一棵树的作业走",
181
+ endpointJobsAtCapacity: "后台作业已满(宿主上限 {limit} 条,进行中与正在收尾的都计数),本次重建未启动:请先在模型侧用 job_kill 收掉不再需要的作业,再重新发起重建",
182
+ unknownJobId: "unknown jobId(这条重建记录已移出历史窗口:本插件只保留最近 {maxJobs} 条已结束的重建,超限时最老的已结束记录先被移除;进行中的重建不会被顶掉,但并发满员时新的启动请求会被直接拒绝。请重新发起重建)",
183
+ jobOutputView: "\n[zvec-grep](仅显示尾部 {shown} 字符,共 {total} 字符)",
184
+ textTooLong: "{name} 超过 {maxChars} 字符上限(实际 {actual})",
185
+ mustBeString: "{name} 必须是字符串(收到 {received})",
186
+ noNulBytes: "{name} 不能包含 NUL 字节",
187
+ mustBeBoolean: "{name} 必须是布尔值(收到 {received})",
188
+ rootEscapesFs: "root 含越界的 .. 段:{path}",
189
+ rootMustBeString: "root 必须是字符串(收到 {received})",
190
+ rootRequired: "root 必填,且为工作区绝对路径",
191
+ rootMustBeAbsolute: "root 必须是绝对路径(以 / 开头):{path}",
192
+ rootIsFsRoot: "root 不能是文件系统根目录 /",
193
+ rootRequiredWithFallback: "root 必填,且为工作区绝对路径(可省略:缺省为当前会话工作区)",
194
+ mustBeStringArray: "{name} 必须是字符串数组",
195
+ tooManyItems: "{name} 最多 {maxItems} 项(实际 {actual})",
196
+ nonStringItem: "{name} 含非字符串项({received})",
197
+ commandTooLong: "zg 命令总长 {length} 超过 {maxChars} 字符上限,请缩小检索范围",
198
+ tooManyQueryRoutes: "检索路由合计 {count} 组,超过 {max} 组上限",
199
+ searchNeedsQuery: "zg_search 需要 query/queries/fts/vector 至少其一",
200
+ intWithReceived: "{name} 必须是 >= {min} 的整数(收到 {received})",
201
+ intRequired: "{name} 必须是 >= {min} 的整数",
202
+ guardRootRejected: "{name} 的 root 不被接受:{reason}",
203
+ guardIndexConfirmRequired: "zg_index 会创建/重建/删除持久索引,必须由用户明确要求且 confirm 为 true 才能调用",
204
+ guardAbsoluteRootRequired: "{name} 需要绝对 root 路径(可省略:缺省为当前会话工作区)",
205
+ gateNeverSearched: "尚未执行过 zg_search",
206
+ gateQuotaExhausted: "grep/rg 配额已用尽",
207
+ gateUnlockExpired: "上一次 zg_search 的解锁已过期",
208
+ gateReason: "[zvec-grep] 工作区检索门禁({state}):当前工作区已建 zg 索引({indexRoot}/{indexDir}),直接 grep/rg 字面检索经常漏检。请先调用 zg_search(语义/混合检索,覆盖面与相关性更好;把当前检索目标作为 query/fts),每次成功的 zg_search 解锁 {budget} 次 grep/rg({windowMin} 分钟内有效),用于精确字面/正则补充。"
209
+ },
210
+ en: {
211
+ 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.",
213
+ 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: "Absolute workspace path (optional: default = current session workspace; name it explicitly when searching another root)",
215
+ rootIndexDescription: "Absolute workspace path (optional: default = current session workspace; name it explicitly when operating on another root)",
216
+ rootStatusDescription: "Absolute workspace path (optional: default = current session workspace)",
217
+ queryDescription: "Single hybrid query (semantic + lexical)",
218
+ queriesDescription: "Multiple hybrid query groups",
219
+ ftsDescription: "Lexical query groups (identifiers, error strings)",
220
+ vectorDescription: "Purely semantic query groups",
221
+ fuseDescription: "Fuse all groups into a single ranking",
222
+ limitDescription: "Max hits per group, 1-50, default 10",
223
+ globsDescription: "Path globs (e.g. src/**)",
224
+ globsIndexDescription: "Path globs",
225
+ insensitiveGlobsDescription: "Case-insensitive globs",
226
+ fileTypesDescription: "File types (e.g. ts, py)",
227
+ fileTypesIndexDescription: "File types",
228
+ excludedFileTypesDescription: "File types to exclude",
229
+ symbolTypesDescription: "Symbol kind filter",
230
+ preferSymbolDescription: "Prefer exact symbol matches",
231
+ modifiedAfterDescription: "Only search files modified after this time",
232
+ modifiedBeforeDescription: "Only search files modified before this time",
233
+ deviceDescription: "auto/cpu/metal/vulkan/cuda; default auto (Metal acceleration, falls back to CPU on failure)",
234
+ confirmDescription: "The user explicitly asked for this index build/rebuild/drop; must be true",
235
+ embeddingDescription: "Local embedding model reference (defaults to defaultEmbedding setting)",
236
+ rebuildDescription: "Rebuild the existing index (must be true when switching embedding)",
237
+ dropDescription: "Delete the index (mutually exclusive with the other index options)",
238
+ ignoreFilesDescription: "Extra ignore-file paths (exclusion lists beyond .gitignore), passed through as zg --ignore-file",
239
+ excludeSecretsDescription: "Whether to exclude private-key/keystore formats by default (*.pem/*.key/*.p12/*.pfx/*.keystore/id_rsa*), default true; set false only when such files genuinely must be indexed",
240
+ hiddenDescription: "Include hidden files (excluded by default, which also drops hidden key files)",
241
+ noIgnoreDescription: "Do not read ignore files",
242
+ maxDepthDescription: "Maximum directory depth",
243
+ maxFileSizeBytesDescription: "Per-file size limit (bytes)",
244
+ followDescription: "Follow symbolic links",
245
+ embeddingConcurrencyDescription: "Embedding concurrency",
246
+ routingText: [
247
+ "# zvec-grep (zg) workspace search rules",
248
+ "",
249
+ "Search routing for this environment:",
250
+ "- 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) → use the native grep / glob / read.",
252
+ "- 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
+ "- zg_status is only for diagnosing a missing/failed/cancelled index or explicit progress watching; do not call it before a normal search.",
254
+ "",
255
+ "zg rules:",
256
+ "1. In an indexed workspace start with zg_search to aim the discovery; do not enumerate files broadly or grep first.",
257
+ "2. zg_search results already carry bounded source snippets — treat them as read evidence; only use read when the detail you need lies outside the snippet.",
258
+ "3. Stop searching once the evidence is sufficient; do not repeat similar queries or widen the hunt just to re-confirm.",
259
+ "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
+ "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); when passed explicitly it must be an absolute path the daemon can see."
262
+ ].join("\n"),
263
+ argsMustBeObject: "zg {name}: arguments must be a JSON object (received {received})",
264
+ missingRequiredArgs: "zg {name}: missing required arguments {fields} (refused outright, no side effects)",
265
+ sandboxFacts: " (sandbox mode={mode}{enforcement})",
266
+ sandboxEnforcement: ", enforcement={value}",
267
+ runnerFailed: "zg never ran: the sandbox runner failed to start{facts}. Check the sandbox backend configuration (this is unrelated to whether zg is installed).",
268
+ sandboxDenied: "the sandbox policy denied a file operation{facts}",
269
+ detailMiddle: "{head} …[middle omitted]… {tail}",
270
+ 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
+ abortedFailure: "zg execution was aborted",
272
+ 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
+ notInstalledFailure: "zg is not installed or not on PATH: run `npm install -g @zvec/zvec-grep` first. {detail}",
274
+ genericFailure: "zg failed (exit={exit}){detail}",
275
+ detailPrefix: " details: {detail}",
276
+ detailColon: ": {detail}",
277
+ outputTruncated: "[zvec-grep] note: output exceeded the {maxBytes} byte limit and was truncated, only the tail is kept{spill}. Narrow the search for full results (sharper query / smaller limit / narrower root).",
278
+ spillNote: " (full output spilled to {path})",
279
+ 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
+ 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), {hits} hit(s) total; requested --limit {limit}{capped}{truncated}",
282
+ hitCapped: " (per-group cap reached; more hits may exist)",
283
+ hitTruncated: "; output truncated, the count covers only the kept part",
284
+ rootMissing: "root directory does not exist (zg needs a real workspace path): {root}",
285
+ jobOutputTruncated: "\n[zvec-grep] output too long, truncated — only the tail is kept",
286
+ jobOutputLost: "\n[zvec-grep] note: the executor's buffer overflowed, so zg output **lost** bytes (below is not the full log); read zg's own log or narrow the rebuild.",
287
+ rebuildRunnerFailed: "\n[zvec-grep] rebuild failed: the sandbox runner did not start{facts} (zg was never executed).",
288
+ rebuildDenied: "\n[zvec-grep] during the rebuild {denied} — the index may be incomplete; check this session's file policy (read-only cannot write .zvec-grep/).",
289
+ rebuildTimeout: "\n[zvec-grep] rebuild killed after exceeding {minutes} minutes",
290
+ jobReasonTimeout: "rebuild reclaimed by zvec-grep after {minutes} minutes",
291
+ jobReasonUnload: "zvec-grep plugin unloaded",
292
+ endpointRootInvalid: "invalid root: {reason}",
293
+ endpointRootUntracked: "root is not in the workspace whitelist this daemon observed: {root} (pick one of the card's candidates)",
294
+ endpointRootGone: "root directory no longer exists: {root}",
295
+ endpointStartFailed: "failed to start the rebuild: {reason}",
296
+ endpointJobsUnavailable: "background rebuild unavailable: the host provides no ctx.jobs (dsh-jobs-local is not loaded); this plugin no longer ships its own job registry",
297
+ endpointRegistryReplaced: "the background job service was replaced (a fresh registry restarts id numbering), so this rebuild was abandoned and its process terminated: reload the zvec-grep plugin before retrying, otherwise a stale panel would follow a different workspace's job",
298
+ endpointJobsAtCapacity: "background jobs are at the host's limit ({limit} slots; running and stopping both count), so this rebuild never started: stop what you no longer need with job_kill, then start the rebuild again",
299
+ unknownJobId: "unknown jobId (this rebuild record left the history window: the plugin keeps the most recent {maxJobs} finished rebuilds and drops the oldest settled one first; running rebuilds are never displaced, but a start request is refused outright once the concurrent limit is reached. Start the rebuild again)",
300
+ jobOutputView: "\n[zvec-grep] (showing only the last {shown} of {total} characters)",
301
+ textTooLong: "{name} exceeds the {maxChars} character limit (actual {actual})",
302
+ mustBeString: "{name} must be a string (received {received})",
303
+ noNulBytes: "{name} must not contain NUL bytes",
304
+ mustBeBoolean: "{name} must be a boolean (received {received})",
305
+ rootEscapesFs: "root contains a .. segment that escapes the filesystem root: {path}",
306
+ rootMustBeString: "root must be a string (received {received})",
307
+ rootRequired: "root is required and must be an absolute workspace path",
308
+ rootMustBeAbsolute: "root must be an absolute path (starting with /): {path}",
309
+ rootIsFsRoot: "root must not be the filesystem root /",
310
+ rootRequiredWithFallback: "root is required and must be an absolute workspace path (it may be omitted: defaults to the current session workspace)",
311
+ mustBeStringArray: "{name} must be an array of strings",
312
+ tooManyItems: "{name} allows at most {maxItems} items (actual {actual})",
313
+ nonStringItem: "{name} contains a non-string item ({received})",
314
+ commandTooLong: "the zg command is {length} characters, over the {maxChars} character limit — narrow the search",
315
+ tooManyQueryRoutes: "{count} query routes in total, over the limit of {max}",
316
+ searchNeedsQuery: "zg_search needs at least one of query/queries/fts/vector",
317
+ intWithReceived: "{name} must be an integer >= {min} (received {received})",
318
+ intRequired: "{name} must be an integer >= {min}",
319
+ guardRootRejected: "the root given to {name} is not accepted: {reason}",
320
+ guardIndexConfirmRequired: "zg_index creates/rebuilds/deletes a persistent index and requires an explicit user request with confirm true",
321
+ guardAbsoluteRootRequired: "{name} needs an absolute root path (it may be omitted: defaults to the current session workspace)",
322
+ gateNeverSearched: "no zg_search has run yet",
323
+ gateQuotaExhausted: "the grep/rg quota is spent",
324
+ gateUnlockExpired: "the unlock from the last zg_search has expired",
325
+ gateReason: "[zvec-grep] workspace search gate ({state}): this workspace already has a zg index ({indexRoot}/{indexDir}), and plain grep/rg frequently misses things. Call zg_search first (semantic/hybrid, better coverage and relevance; pass the current target as query/fts). Each successful zg_search unlocks {budget} grep/rg calls valid for {windowMin} minutes, to be used for exact literal/regex follow-up."
326
+ }
327
+ };
328
+ /**
329
+ * `{name}` 占位符插值(与官方 locale 的 Translate 参数语义同源)。
330
+ *
331
+ * host 侧没有官方 translator,字典里的模板要自己填;缺键(占位符没给值)一律替成
332
+ * 空串——文案是给人看的,不该因为一个占位符打断工具调用。
333
+ * @param template - 字典里的模板。
334
+ * @param params - 占位符名 → 值(null 照实渲染成 "null",与旧模板字符串一致)。
335
+ * @returns 填好的文本。
336
+ */
337
+ function fill(template, params) {
338
+ return template.replaceAll(/\{(?<key>\w+)\}/gu, (_all, key) => {
339
+ const value = params[key];
340
+ return value === void 0 ? "" : String(value);
341
+ });
342
+ }
343
+ //#endregion
344
+ //#region lib/argv-guard.ts
345
+ const MAX_COMMAND_BYTES = 64e3;
346
+ /** 单条 query 文本上限(再长属误用:zg 的语义检索按句切分)。 */
347
+ const MAX_QUERY_CHARS = 8e3;
348
+ /** 过滤类数组(globs/types/…)单项条数上限。只在本模块作 `stringList` 的缺省档,不外露。 */
349
+ const MAX_FILTER_ITEMS = 64;
350
+ /** 过滤类数组单项长度上限(glob 不该长成文章)。 */
351
+ const MAX_FILTER_CHARS = 1e3;
352
+ /** POSIX sh 单引号转义:' → '\''。把任意字符串安全放进单引号内,防注入。 */
353
+ function shq(value) {
354
+ return `'${value.replaceAll("'", String.raw`'\''`)}'`;
355
+ }
356
+ /** 长度上界校验(超限即抛,避免整条命令撑爆 argv)。 */
357
+ function assertTextLen(value, name, messages, maxChars) {
358
+ if (value.length > maxChars) throw new TypeError(fill(messages.textTooLong, {
359
+ name,
360
+ maxChars,
361
+ actual: value.length
362
+ }));
363
+ return value;
364
+ }
365
+ /**
366
+ * 可选文本取值:未给 → 空串;非字符串 → 报错(绝不静默降级成默认值);
367
+ * 去首尾空白并校验 NUL 与长度。
368
+ */
369
+ function optionalText(value, name, messages, maxChars) {
370
+ if (value === void 0 || value === null) return "";
371
+ if (typeof value !== "string") throw new TypeError(fill(messages.mustBeString, {
372
+ name,
373
+ received: typeof value
374
+ }));
375
+ if (value.includes("\0")) throw new Error(fill(messages.noNulBytes, { name }));
376
+ return assertTextLen(value.trim(), name, messages, maxChars);
377
+ }
378
+ /**
379
+ * 字符串数组规范化:非数组报错;**非字符串项报错**(旧实现静默丢弃,模型写
380
+ * `globs:["src/**", 5]` 时用户以为 5 那条过滤生效了);含 NUL 报错;超条数/
381
+ * 超长度报错;trim 后空串丢弃。
382
+ */
383
+ function stringList(value, name, messages, maxItems = MAX_FILTER_ITEMS, maxChars = MAX_FILTER_CHARS) {
384
+ if (value === void 0 || value === null) return [];
385
+ if (!Array.isArray(value)) throw new TypeError(fill(messages.mustBeStringArray, { name }));
386
+ if (value.length > maxItems) throw new TypeError(fill(messages.tooManyItems, {
387
+ name,
388
+ maxItems,
389
+ actual: value.length
390
+ }));
391
+ const out = [];
392
+ for (const item of value) {
393
+ if (typeof item !== "string") throw new TypeError(fill(messages.nonStringItem, {
394
+ name,
395
+ received: typeof item
396
+ }));
397
+ if (item.includes("\0")) throw new Error(fill(messages.noNulBytes, { name }));
398
+ const trimmed = assertTextLen(item.trim(), name, messages, maxChars);
399
+ if (trimmed.length > 0) out.push(trimmed);
400
+ }
401
+ return out;
402
+ }
403
+ /**
404
+ * 默认密钥排除:只收无歧义的私钥/密钥库格式(实测这类文件常既不在
405
+ * .gitignore、也不以 `.` 开头,会躲过 zg 默认规则被索引,把私钥带进向量库并
406
+ * 可能回显到模型上下文)。刻意不含 `*secret*` / `*credential*` 这类宽泛词
407
+ * 模式——它们会误伤正常源码与文档,造成"为什么搜不到"的隐性困惑。
408
+ * 项目特定策略请走 ignoreFiles(--ignore-file)或 globs。excludeSecrets=false 可关。
409
+ */
410
+ const SECRET_EXCLUDE_GLOBS = [
411
+ "!*.pem",
412
+ "!*.key",
413
+ "!*.p12",
414
+ "!*.pfx",
415
+ "!*.keystore",
416
+ "!id_rsa*",
417
+ "!id_ed25519*"
418
+ ];
419
+ //#endregion
420
+ //#region lib/cli.ts
421
+ const LIMIT_MIN = 1;
422
+ const LIMIT_MAX = 50;
423
+ /**
424
+ * 归一化 zg 的设备参数:显式传入用显式值,否则默认 auto(让 llama.cpp 自探测
425
+ * Metal GPU,失败自动回退 CPU)。auto/cpu/metal/vulkan/cuda 之外的非法值由
426
+ * zg 端 parseDevice 拒绝;这里只负责类型、是否带 --device、如何转义。
427
+ */
428
+ function deviceFlag(value, messages) {
429
+ const raw = optionalText(value, "device", messages, MAX_FILTER_CHARS);
430
+ return `--device ${shq(raw.length > 0 ? raw : "auto")}`;
431
+ }
432
+ /** 布尔旗标严格取值:缺省回 fallback,非布尔即报错(`1`/`"true"` 不算真)。 */
433
+ function boolOf(value, name, messages, fallback = false) {
434
+ if (value === void 0 || value === null) return fallback;
435
+ if (typeof value !== "boolean") throw new TypeError(fill(messages.mustBeBoolean, {
436
+ name,
437
+ received: typeof value
438
+ }));
439
+ return value;
440
+ }
441
+ /**
442
+ * 词典化归一绝对路径(不触盘):折叠空段与 `.`、解析 `..`。
443
+ * `..` 越过文件系统根(如 `/../../etc`)即抛错——归一后落回 `/etc` 看似合法,
444
+ * 实为借相对段逃逸调用方意图中的目录,绝不放行。
445
+ */
446
+ function normalizeAbsolutePath(path, messages) {
447
+ const parts = [];
448
+ for (const seg of path.split("/")) if (seg === "..") {
449
+ if (parts.length === 0) throw new Error(fill(messages.rootEscapesFs, { path }));
450
+ parts.pop();
451
+ } else if (seg !== "" && seg !== ".") parts.push(seg);
452
+ return `/${parts.join("/")}`;
453
+ }
454
+ /** 绝对路径校验(macOS/Linux):非空、以 / 开头、无 NUL、词典归一后仍在根内。 */
455
+ function assertAbsoluteRoot(root, messages) {
456
+ if (typeof root !== "string") throw new TypeError(fill(messages.rootMustBeString, { received: root === null ? "null" : typeof root }));
457
+ if (root.trim().length === 0) throw new Error(messages.rootRequired);
458
+ const trimmed = root.trim();
459
+ if (trimmed.includes("\0")) throw new Error(fill(messages.noNulBytes, { name: "root" }));
460
+ if (!trimmed.startsWith("/")) throw new Error(fill(messages.rootMustBeAbsolute, { path: trimmed }));
461
+ const normalized = normalizeAbsolutePath(trimmed, messages);
462
+ if (normalized === "/") throw new Error(messages.rootIsFsRoot);
463
+ return normalized;
464
+ }
465
+ /**
466
+ * root 解析:显式绝对路径优先;缺失/空串回退到 fallback(当前会话工作区,
467
+ * 调用方从 exec.agent.session.header.cwd 取——官方 dsh-tool-fs-search 同模式)。
468
+ * ROC 原则:fallback 也走 assertAbsoluteRoot 校验,绝不无条件接受。
469
+ */
470
+ function resolveRoot(value, fallback, messages) {
471
+ if (typeof value === "string" && value.trim().length > 0) return assertAbsoluteRoot(value.trim(), messages);
472
+ if (typeof fallback === "string" && fallback.trim().length > 0) return assertAbsoluteRoot(fallback.trim(), messages);
473
+ throw new Error(messages.rootRequiredWithFallback);
474
+ }
475
+ /** limit 钳制:非整数回默认,越界钳到 [LIMIT_MIN, LIMIT_MAX]。 */
476
+ function clampLimit(value, fallback = 10) {
477
+ if (value === void 0 || value === null) return fallback;
478
+ const num = typeof value === "number" ? value : Number(value);
479
+ if (!Number.isSafeInteger(num)) return fallback;
480
+ return Math.min(LIMIT_MAX, Math.max(LIMIT_MIN, num));
481
+ }
482
+ /** 检索类数组(queries/fts/vector)取值:条数与单条长度都放宽到 query 档。 */
483
+ function queryList(value, name, messages) {
484
+ return stringList(value, name, messages, 32, MAX_QUERY_CHARS);
485
+ }
486
+ /** 整条命令的规模闸门:超 MAX_COMMAND_BYTES 即拒(防 E2BIG 与无界内存)。 */
487
+ function assembled(parts, workdir, messages) {
488
+ const command = parts.join(" ");
489
+ const { length } = command;
490
+ if (length > 64e3) throw new Error(fill(messages.commandTooLong, {
491
+ length,
492
+ maxChars: MAX_COMMAND_BYTES
493
+ }));
494
+ return {
495
+ command,
496
+ workdir
497
+ };
498
+ }
499
+ /**
500
+ * 追加 query 路由主体参数(single/单查询 + 混合 lists),返回路由命中数
501
+ * 与 dashGuard(query 以 '-' 开头需在命令末尾 `-- <query>` 分隔)供调用方使用。
502
+ */
503
+ function pushQueryArgs(parts, args, messages) {
504
+ let routeCount = 0;
505
+ const single = optionalText(args.query, "query", messages, MAX_QUERY_CHARS);
506
+ const dashGuard = single.length > 0 && single.startsWith("-");
507
+ if (single.length > 0) {
508
+ if (!dashGuard) parts.push(shq(single));
509
+ routeCount += 1;
510
+ }
511
+ for (const query of queryList(args.queries, "queries", messages)) {
512
+ parts.push("--hybrid", shq(query));
513
+ routeCount += 1;
514
+ }
515
+ for (const query of queryList(args.fts, "fts", messages)) {
516
+ parts.push("--fts", shq(query));
517
+ routeCount += 1;
518
+ }
519
+ for (const query of queryList(args.vector, "vector", messages)) {
520
+ parts.push("--vector", shq(query));
521
+ routeCount += 1;
522
+ }
523
+ if (routeCount > 32) throw new Error(fill(messages.tooManyQueryRoutes, {
524
+ count: routeCount,
525
+ max: 32
526
+ }));
527
+ return {
528
+ routeCount,
529
+ dashGuard
530
+ };
531
+ }
532
+ /** 追加检索过滤 globs(glob/iglob/type/type-not/symbol-type)。 */
533
+ function pushSearchGlobs(parts, args, messages) {
534
+ for (const glob of stringList(args.globs, "globs", messages)) parts.push("--glob", shq(glob));
535
+ for (const glob of stringList(args.insensitiveGlobs, "insensitiveGlobs", messages)) parts.push("--iglob", shq(glob));
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));
539
+ }
540
+ /** 取单条 query 的原文(与 pushQueryArgs 同一取值器,保证 dashGuard 两侧一致)。 */
541
+ function singleText(args, messages) {
542
+ return optionalText(args.query, "query", messages, MAX_QUERY_CHARS);
543
+ }
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);
550
+ const parts = ["zg", "query"];
551
+ const { routeCount, dashGuard } = pushQueryArgs(parts, args, messages);
552
+ if (routeCount === 0) throw new Error(messages.searchNeedsQuery);
553
+ if (boolOf(args.fuse, "fuse", messages)) parts.push("--fuse");
554
+ parts.push("--limit", String(clampLimit(args.limit)), "--preview", "short", "--refresh", "wait");
555
+ pushSearchGlobs(parts, args, messages);
556
+ if (boolOf(args.preferSymbol, "preferSymbol", messages)) parts.push("--prefer-symbol");
557
+ const after = optionalText(args.modifiedAfter, "modifiedAfter", messages, MAX_FILTER_CHARS);
558
+ if (after.length > 0) parts.push("--modified-after", shq(after));
559
+ const before = optionalText(args.modifiedBefore, "modifiedBefore", messages, MAX_FILTER_CHARS);
560
+ if (before.length > 0) parts.push("--modified-before", shq(before));
561
+ parts.push(deviceFlag(args.device, messages), "--mode", "direct");
562
+ if (dashGuard) parts.push("--", shq(singleText(args, messages)));
563
+ return assembled(parts, root, messages);
564
+ }
565
+ /** 非负/正整数字符串化;非数值类型或非整数报错(`true` 不算 1)。 */
566
+ function intFlag(value, name, messages, min) {
567
+ if (typeof value !== "number" && typeof value !== "string") throw new TypeError(fill(messages.intWithReceived, {
568
+ name,
569
+ min,
570
+ received: typeof value
571
+ }));
572
+ const num = typeof value === "number" ? value : Number(value);
573
+ if (!Number.isSafeInteger(num) || num < min) throw new Error(fill(messages.intRequired, {
574
+ name,
575
+ min
576
+ }));
577
+ return String(num);
578
+ }
579
+ /**
580
+ * 一次性读完全部布尔旗标:drop=true 的分支不拼 embedding/过滤段,若就地取值,
581
+ * `{drop:true, hidden:"true"}` 里的非法类型会被静默忽略。先取值再分支,任何
582
+ * 非法布尔都在命令构造前报错。
583
+ */
584
+ function readIndexFlags(args, messages) {
585
+ return {
586
+ rebuild: boolOf(args.rebuild, "rebuild", messages),
587
+ hidden: boolOf(args.hidden, "hidden", messages),
588
+ noIgnore: boolOf(args.noIgnore, "noIgnore", messages),
589
+ follow: boolOf(args.follow, "follow", messages),
590
+ excludeSecrets: boolOf(args.excludeSecrets, "excludeSecrets", messages, true)
591
+ };
592
+ }
593
+ /** 追加索引布尔旗标(rebuild 在 globs 前)。 */
594
+ function pushIndexBoolFlags(parts, flags) {
595
+ if (flags.rebuild) parts.push("--rebuild");
596
+ }
597
+ /**
598
+ * 追加索引过滤 globs 与密钥排除(内部顺序固定:globs → iglob → type →
599
+ * type-not → 密钥排除 → ignore-file)。
600
+ * 密钥排除:默认开,可 excludeSecrets=false 关;纯 `!` 取反已实测可独立工作。
601
+ */
602
+ function pushIndexGlobs(parts, args, flags, messages) {
603
+ for (const glob of stringList(args.globs, "globs", messages)) parts.push("--glob", shq(glob));
604
+ for (const glob of stringList(args.insensitiveGlobs, "insensitiveGlobs", messages)) parts.push("--iglob", shq(glob));
605
+ for (const typeName of stringList(args.fileTypes, "fileTypes", messages)) parts.push("--type", shq(typeName));
606
+ for (const typeName of stringList(args.excludedFileTypes, "excludedFileTypes", messages)) parts.push("--type-not", shq(typeName));
607
+ if (flags.excludeSecrets) for (const glob of SECRET_EXCLUDE_GLOBS) parts.push("--glob", shq(glob));
608
+ for (const filePath of stringList(args.ignoreFiles, "ignoreFiles", messages)) parts.push("--ignore-file", shq(filePath));
609
+ }
610
+ /** 追加索引数值旗标(内部顺序固定:maxDepth → maxFileSizeBytes)。 */
611
+ function pushIndexIntFlags(parts, args, messages) {
612
+ if (args.maxDepth !== void 0 && args.maxDepth !== null) parts.push("--max-depth", intFlag(args.maxDepth, "maxDepth", messages, 0));
613
+ if (args.maxFileSizeBytes !== void 0 && args.maxFileSizeBytes !== null) parts.push("--max-filesize", intFlag(args.maxFileSizeBytes, "maxFileSizeBytes", messages, 0));
614
+ }
615
+ /** 追加索引布尔旗标(hidden/no-ignore 紧随过滤 globs)。 */
616
+ function pushIndexHideFlags(parts, flags) {
617
+ if (flags.hidden) parts.push("--hidden");
618
+ if (flags.noIgnore) parts.push("--no-ignore");
619
+ }
620
+ /** 追加索引布尔旗标(follow 位于 max-filesize 之后)。 */
621
+ function pushIndexFollowFlag(parts, flags) {
622
+ if (flags.follow) parts.push("--follow");
623
+ }
624
+ /** 追加索引数值旗标(embedding-concurrency 位于 follow 之后)。 */
625
+ function pushIndexConcurrencyFlag(parts, args, messages) {
626
+ if (args.embeddingConcurrency !== void 0 && args.embeddingConcurrency !== null) parts.push("--embedding-concurrency", intFlag(args.embeddingConcurrency, "embeddingConcurrency", messages, 1));
627
+ }
628
+ /**
629
+ * 构造 zg index 命令。root 是位置参数(转义)。
630
+ * - drop=true:`zg index <root> --drop --yes --mode direct`(非交互 shell 必须 --yes)。
631
+ * - 否则:`zg index <root> --embedding <m> [--rebuild] ... --mode direct`。
632
+ * embedding 缺省时由调用方传入 defaultEmbedding(设置里的默认值)。
633
+ * 旗标顺序与 filter globs 交错固定(rebuild → globs → hidden → no-ignore →
634
+ * max-depth → max-filesize → follow → embedding-concurrency),不得重排(测试锁死)。
635
+ */
636
+ function buildIndexCommand(args, defaultEmbedding, messages) {
637
+ const root = assertAbsoluteRoot(args.root, messages);
638
+ const parts = [
639
+ "zg",
640
+ "index",
641
+ shq(root)
642
+ ];
643
+ const flags = readIndexFlags(args, messages);
644
+ if (boolOf(args.drop, "drop", messages)) {
645
+ parts.push("--drop", "--yes", "--mode", "direct");
646
+ return assembled(parts, root, messages);
647
+ }
648
+ const given = optionalText(args.embedding, "embedding", messages, MAX_FILTER_CHARS);
649
+ const embedding = given.length > 0 ? given : defaultEmbedding;
650
+ parts.push("--embedding", shq(embedding));
651
+ pushIndexBoolFlags(parts, flags);
652
+ pushIndexGlobs(parts, args, flags, messages);
653
+ pushIndexHideFlags(parts, flags);
654
+ pushIndexIntFlags(parts, args, messages);
655
+ pushIndexFollowFlag(parts, flags);
656
+ pushIndexConcurrencyFlag(parts, args, messages);
657
+ parts.push(deviceFlag(args.device, messages), "--mode", "direct");
658
+ return assembled(parts, root, messages);
659
+ }
660
+ /** 构造 zg status 命令(root 位置参数)。 */
661
+ function buildStatusCommand(args, messages) {
662
+ const root = assertAbsoluteRoot(args.root, messages);
663
+ return assembled([
664
+ "zg",
665
+ "status",
666
+ shq(root),
667
+ "--mode",
668
+ "direct"
669
+ ], root, messages);
670
+ }
671
+ //#endregion
672
+ //#region lib/search-predicates.ts
673
+ const GREP_COMMAND_NAMES = /* @__PURE__ */ new Set([
674
+ "grep",
675
+ "egrep",
676
+ "fgrep",
677
+ "rg"
678
+ ]);
679
+ /** 含这些旗标的命令会立即打印并退出(--help/--version/-V),不产生检索。 */
680
+ const PROBE_FLAGS = /* @__PURE__ */ new Set([
681
+ "--help",
682
+ "--version",
683
+ "-V"
684
+ ]);
685
+ /**
686
+ * 包装/前缀命令:其首个实参本身就是「被执行的命令」,同样算命令位
687
+ * (`git grep`、`… | xargs grep TODO`、`env rg foo` 都是真检索)。
688
+ */
689
+ const SEARCH_PREFIX_WORDS = /* @__PURE__ */ new Set([
690
+ "git",
691
+ "xargs",
692
+ "env",
693
+ "nohup",
694
+ "sudo",
695
+ "time",
696
+ "timeout",
697
+ "nice",
698
+ "parallel"
699
+ ]);
700
+ /** 结束一个 token、但**不**开启新命令位的字符(空白、右括号、重定向)。 */
701
+ const TOKEN_BREAK_CHARS = /* @__PURE__ */ new Set([
702
+ " ",
703
+ " ",
704
+ "\v",
705
+ "\f",
706
+ ")",
707
+ "<",
708
+ ">"
709
+ ]);
710
+ /** 结束一个 token 并让紧随其后的 token 处于命令位(控制符 / 换行 / 反引号 / 组)。 */
711
+ const COMMAND_BREAK_CHARS = /* @__PURE__ */ new Set([
712
+ "|",
713
+ ";",
714
+ "&",
715
+ "(",
716
+ "\n",
717
+ "\r",
718
+ "`",
719
+ "{",
720
+ "}"
721
+ ]);
722
+ /** 引号字符:词首开引号、词尾闭引号都只有这两个,用集合而不是逐字符比较。 */
723
+ const QUOTE_CHARS = /* @__PURE__ */ new Set(["'", "\""]);
724
+ /**
725
+ * 当前引号状态下,这个字符是否只是要写进 buffer 的字面量(既不结束引号、也不参与分隔)。
726
+ * 单引号内一切皆字面量,只有同种引号本身能收束;双引号还认 `\` 转义,故反斜杠也出列。
727
+ */
728
+ function isQuotedLiteral(char, quote) {
729
+ return quote === "'" && char !== "'" || quote === "\"" && char !== "\"" && char !== "\\";
730
+ }
731
+ /**
732
+ * 注释段读完后的续读下标:停在行尾换行**之前**(循环末尾还有一次 +1),换行才能照常
733
+ * 充当命令分隔符——否则会连 `\n` 一起跳过,`# x\ngrep foo` 里的真检索就被漏掉。
734
+ * 串内已无换行 = 注释一直到串尾。
735
+ */
736
+ function indexAfterComment(command, from) {
737
+ const nextLine = command.indexOf("\n", from);
738
+ return nextLine === -1 ? command.length : nextLine - 1;
739
+ }
740
+ /**
741
+ * 手写 shell 切词(只为「找出命令位上的命令名」服务,不做完整求值):
742
+ * - 单/双引号与反斜杠转义**内部**的字符不参与分隔 → `echo "grep x"`、
743
+ * `printf 'grep'`、`git commit -m "use rg"` 里的字面量不再被当成命令
744
+ * (旧实现把引号当分隔符,故这三种全被判为检索 → 过度拦截);
745
+ * - 引号外、词首的 `#` 起为注释,整段跳到行尾;
746
+ * - 控制符(`|` `;` `&` `(` 换行 反引号 `{` `}`)之后的 token 记为命令位。
747
+ * 双引号内保留字面内容(含空格),故 `"/usr/bin/rg foo"` 是一个非命令位 token。
748
+ */
749
+ function tokenizeShell(command) {
750
+ const tokens = [];
751
+ const state = {
752
+ buffer: "",
753
+ atCommand: true,
754
+ quote: ""
755
+ };
756
+ const flush = () => {
757
+ if (state.buffer.length > 0) {
758
+ tokens.push({
759
+ text: state.buffer,
760
+ atCommand: state.atCommand
761
+ });
762
+ state.buffer = "";
763
+ state.atCommand = false;
764
+ }
765
+ };
766
+ let index = 0;
767
+ let escaped = false;
768
+ while (index < command.length) {
769
+ const char = command.slice(index, index + 1);
770
+ if (escaped) {
771
+ state.buffer += char;
772
+ escaped = false;
773
+ } else if (isQuotedLiteral(char, state.quote)) state.buffer += char;
774
+ else if (state.quote === "" && char === "#" && state.buffer.length === 0) index = indexAfterComment(command, index);
775
+ else if (char === "\\") escaped = true;
776
+ else if (QUOTE_CHARS.has(char)) state.quote = state.quote === char ? "" : char;
777
+ else if (COMMAND_BREAK_CHARS.has(char)) {
778
+ flush();
779
+ state.atCommand = true;
780
+ } else if (TOKEN_BREAK_CHARS.has(char)) flush();
781
+ else state.buffer += char;
782
+ index += 1;
783
+ }
784
+ flush();
785
+ return tokens;
786
+ }
787
+ /** token 的命令名(basename,小写);`-*` 选项一律不算命令名(返回空串)。 */
788
+ function baseName(text) {
789
+ if (text.startsWith("-")) return "";
790
+ return text.slice(text.lastIndexOf("/") + 1).toLowerCase();
791
+ }
792
+ /**
793
+ * 挑出处在「被执行位置」的 token:串首 / 控制符之后 / 包装命令(git、xargs、
794
+ * env…)之后的第一个实参。
795
+ */
796
+ function commandPositionTokens(tokens) {
797
+ const out = [];
798
+ let afterPrefix = false;
799
+ for (const token of tokens) {
800
+ const isCommand = token.atCommand || afterPrefix;
801
+ if (isCommand) out.push(token);
802
+ afterPrefix = isCommand && SEARCH_PREFIX_WORDS.has(baseName(token.text));
803
+ }
804
+ return out;
805
+ }
806
+ /**
807
+ * 识别 bash/pwsh 命令串里的 grep/rg 检索调用:引号/注释感知切词后,只认
808
+ * **命令位**上的 token 名(basename)精确匹配 grep/egrep/fgrep/rg
809
+ * (大小写不敏感)。管道 `… | grep foo`、绝对路径 `/usr/bin/rg foo`、
810
+ * `git grep foo`、`find … | xargs grep TODO` 均算检索;`--grep=x` 选项、路径
811
+ * 片段(grepbar)、引号内字面量与注释里的 grep 都不算。
812
+ * 已知近似(均为漏拦方向,代价由 systemPrompt 路由文本兜底):
813
+ * - --help/--version/-V 豁免按整条命令判断(`rg a --version && grep b c`
814
+ * 复合命令会漏拦 grep);
815
+ * - shell 关键字(`for … ; do grep`、`if … ; then rg`)不是控制符,其后的
816
+ * grep 不在命令位;`VAR=1 grep x` 同理。
817
+ */
818
+ function isGrepRgCommand(command) {
819
+ const tokens = tokenizeShell(command);
820
+ if (tokens.some((token) => PROBE_FLAGS.has(token.text))) return false;
821
+ return commandPositionTokens(tokens).some((token) => GREP_COMMAND_NAMES.has(baseName(token.text)));
822
+ }
823
+ /** 去掉尾部斜杠的 root 归一化('/' 自身保持 '/')。 */
824
+ function normalizeRoot(path) {
825
+ const trimmed = path.replace(/\/+$/u, "");
826
+ return trimmed.length > 0 ? trimmed : "/";
827
+ }
828
+ /**
829
+ * 判断检索目标是否落在 root 之内(按路径段前缀,防 /fo 误吞 /foo)。
830
+ * target 缺省/空串 = 缺省搜整个工作区(原生 grep 工具语义)→ true;
831
+ * 相对路径按相对 root 解析(含 ../ 逃逸检测)。
832
+ * 与 cli 的 assertAbsoluteRoot 同一归一化函数,但语义相反一侧不能抛错:
833
+ * 归一化时 `..` 越出文件系统根,说明目标必然在 root 之外 → 直接 false
834
+ * (这里是「判范围」,不是「判合法性」)。messages 只为把归一化异常喂给
835
+ * normalizeAbsolutePath——那条文本在这里被丢弃,出界才是结论。
836
+ */
837
+ function pathInsideRoot(target, root, messages) {
838
+ if (target === void 0 || target.trim().length === 0) return true;
839
+ const base = normalizeRoot(root);
840
+ const targetText = target.trim();
841
+ const joined = targetText.startsWith("/") ? targetText : `${base}/${targetText}`;
842
+ let absolute;
843
+ try {
844
+ absolute = normalizeAbsolutePath(joined, messages);
845
+ } catch {
846
+ return false;
847
+ }
848
+ return absolute === base || absolute.startsWith(`${base}/`);
849
+ }
850
+ /**
851
+ * bash/pwsh 命令串中是否存在「索引根之外」的路径证据。
852
+ * 只认明确的路径形状:以 / 开头的绝对路径、含 / 的相对路径(含 ../ 逃逸)、
853
+ * 以及裸 `..`(父目录)。flag 选项(-*)与无路径形状的 token(模式词、文件名)
854
+ * 跳过。返回 true = 命令明确检索索引根之外的目标 → 门禁放行(与原生 grep 工具
855
+ * 的 pathInsideRoot 出界放行语义一致)。
856
+ * 切词同样引号/注释感知:注释里的路径不再是证据;引号内的整串是一个 token
857
+ * (`grep x "注释 里的 /tmp/p"` 仍按含 / 的 token 判外部目标,属已知近似——
858
+ * 方向是放行,宁可漏拦)。
859
+ * 已知近似:bash 自由文本无法可靠区分「模式」与「相对路径」token,故 `../` 形态
860
+ * 的模式词可能被误判为外部目标而放行(漏拦,安全方向);混合目标(如
861
+ * `rg foo /repo/src /tmp/x`)因存在外部绝对路径而整体放行。
862
+ */
863
+ function hasExternalTarget(root, command, messages) {
864
+ const base = normalizeRoot(root);
865
+ for (const token of tokenizeShell(command)) {
866
+ const { text } = token;
867
+ if (!text.startsWith("-") && (text.startsWith("/") || text.includes("/") || text === "..") && !pathInsideRoot(text, base, messages)) return true;
868
+ }
869
+ return false;
870
+ }
871
+ /** 解锁是否可用:存在、有余量、未过期。 */
872
+ function unlockActive(unlock, now) {
873
+ return unlock !== void 0 && unlock.grepsLeft > 0 && now < unlock.expiresAt;
874
+ }
875
+ //#endregion
876
+ //#region lib/routing.ts
877
+ /** 紧跟 TOOL_GREP(1500) 之后、TOOL_JOBS(1600) 之前。 */
878
+ const ROUTING_ORDER = 1550;
879
+ const ROUTING_NAME = "zvec-grep-routing";
880
+ /**
881
+ * `ZG_TOOLS` 的集合视图 + 窄化判据。
882
+ *
883
+ * 为什么要它:`zgGuard` 原本写的是 `(ZG_TOOLS as readonly string[]).includes(name)`,
884
+ * 判定通过后 `name` 仍是 `string` —— 于是下游 `name === "zg_index"` 这类比较与
885
+ * `ZG_TOOLS` 之间**没有任何编译期绑定**。工具改名或这里少打一个字符,比较就静默
886
+ * 永不相等,"zg_index 必须 confirm=true" 这道闸会无声失效(不报错、测试也照样绿)。
887
+ * 窄化成 `ZgToolName` 之后,取值集合只由 `ZG_TOOLS` 一处决定,写错名字当场编译不过。
888
+ *
889
+ * 判据本身不收 `as`:集合按 `string` 建,`has` 的入参就是 `string`,无需说服编译器。
890
+ */
891
+ const ZG_TOOL_NAMES = /* @__PURE__ */ new Set([
892
+ "zg_search",
893
+ "zg_index",
894
+ "zg_status"
895
+ ]);
896
+ /** 运行时判定 + 类型窄化:`name` 是否是本包注册的 zg_* 工具。 */
897
+ function isZgToolName(name) {
898
+ return typeof name === "string" && ZG_TOOL_NAMES.has(name);
899
+ }
900
+ /** 会话工作区(官方 Agent.session.header.cwd;值按 unknown 读,理由见 SessionFace)。 */
901
+ function sessionHeaderCwd$1(execution) {
902
+ const raw = execution.agent?.session?.header?.cwd;
903
+ return typeof raw === "string" && raw.length > 0 ? raw : void 0;
904
+ }
905
+ /**
906
+ * root 判据(与 execute 的 assertAbsoluteRoot 完全同源):合法返回 undefined;
907
+ * 非法时返回可直接给模型的原因。
908
+ */
909
+ function rootProblem(name, root, messages) {
910
+ let problem;
911
+ try {
912
+ assertAbsoluteRoot(root, messages);
913
+ } catch (error) {
914
+ problem = fill(messages.guardRootRejected, {
915
+ name,
916
+ reason: errorText(error)
917
+ });
918
+ }
919
+ return problem;
920
+ }
921
+ /** 单个 zg_* 调用的拒绝原因(confirm / root 两道,见 zgGuard 的注释)。 */
922
+ function zgToolProblem(name, args, execution, messages) {
923
+ const { root } = args;
924
+ let problem;
925
+ if (name === "zg_index" && args["confirm"] !== true) problem = messages.guardIndexConfirmRequired;
926
+ else if (root === void 0 || root === null || root === "") problem = sessionHeaderCwd$1(execution) === void 0 ? fill(messages.guardAbsoluteRootRequired, { name }) : void 0;
927
+ else problem = rootProblem(name, root, messages);
928
+ return problem;
929
+ }
930
+ /**
931
+ * 安全兜底 guard:只拦截 zg_* 工具,其它工具一律放行(返回 undefined)。
932
+ * - zg_index 无 confirm=true → 拒绝(防静默建/删索引)。
933
+ * - 所有 zg_* 无 root 且无会话工作区可回退 → 拒绝(快速失败,比 shell 报错更清晰)。
934
+ * - root 非法(相对路径 / NUL / 越界 `..` / 文件系统根)→ 拒绝,判据与 execute 同源。
935
+ * - root 缺失但 execution.agent 提供会话 cwd → 放行(execute 内 resolveRoot 兜底)。
936
+ * @param execution - tools.guard 收到的执行体。
937
+ * @param messages - 拒绝理由的文案表(宿主按语言注入)。
938
+ * @returns 拒绝理由;undefined = 放行。
939
+ */
940
+ function zgGuard(execution, messages) {
941
+ const { name } = execution;
942
+ const args = isRecord(execution.arguments) ? execution.arguments : {};
943
+ let reason;
944
+ if (isZgToolName(name)) reason = zgToolProblem(name, args, execution, messages);
945
+ return reason;
946
+ }
947
+ /** zg 索引库目录名(zg index 的落盘位置:<root>/.zvec-grep/)。 */
948
+ const INDEX_DIR_NAME = ".zvec-grep";
949
+ /**
950
+ * 从 startDir 向上找含 zg 索引库的最近祖先(含自身),返回该索引根。
951
+ * 会话工作区可能是索引根的子目录(如索引在仓库根、会话开在子包)——不向上走
952
+ * 会漏拦。probe 注入(宿主用 existsSync),本函数保持纯函数可单测。
953
+ */
954
+ function findIndexRoot(startDir, probe, maxDepth = 8) {
955
+ let dir = normalizeRoot(startDir);
956
+ let found;
957
+ for (let depth = 0; depth <= maxDepth; depth += 1) {
958
+ if (probe(dir)) {
959
+ found = dir;
960
+ break;
961
+ }
962
+ if (dir === "/") break;
963
+ const cut = dir.lastIndexOf("/");
964
+ dir = cut <= 0 ? "/" : dir.slice(0, cut);
965
+ }
966
+ return found;
967
+ }
968
+ /** 会话状态分片键:session.id(字符串/数字)→ 稳定键;无 id 归入共享桶。 */
969
+ function sessionKeyOf(execution) {
970
+ const id = execution?.agent?.session?.id;
971
+ if (typeof id === "string" && id.length > 0) return id;
972
+ if (typeof id === "number" && Number.isSafeInteger(id)) return String(id);
973
+ return "__anonymous__";
974
+ }
975
+ /**
976
+ * search-first 门禁(硬约束):拦截对象为
977
+ * - bash/pwsh:命令串里出现 grep/rg 检索调用(isGrepRgCommand),且目标未被
978
+ * hasExternalTarget 判定为索引根之外;
979
+ * - 原生 grep 工具:检索目标位于会话工作区内(path 出界不属工作区检索,放行)。
980
+ * 会话工作区(含祖先)存在 zg 索引且当前无可用解锁额度(从未 zg_search、配额
981
+ * 用尽或已过期)→ 拒绝并给出可行动出路。解锁额度按「会话 × 索引根」计,
982
+ * 每次成功的 zg_search 重置为 N 次、M 分钟有效——保证语义检索频率与 grep
983
+ * 用量成正比,而不是一次放行终身豁免。
984
+ * 已知近似:bash 自由文本无法可靠区分模式与相对路径 token,hasExternalTarget
985
+ * 只认明确的路径形状,`../` 形态的模式词可能被误判为外部目标而放行(漏拦,
986
+ * 安全方向);混合目标(如 `rg foo /repo/src /tmp/x`)整体放行。
987
+ */
988
+ /**
989
+ * 索引根已定后的门禁裁决:无索引根 / 检索索引根之外 / 有可扣额度 → 放行
990
+ * (undefined);否则返回拦截文案。放行会触发 consumeGrep 副作用。
991
+ */
992
+ function buildSearchFirstReason(cwd, command, deps, messages) {
993
+ const indexRoot = findIndexRoot(cwd, deps.indexProbe);
994
+ let reason;
995
+ if (indexRoot !== void 0 && (command === void 0 || !hasExternalTarget(indexRoot, command, messages))) {
996
+ const unlock = deps.lookupUnlock(indexRoot);
997
+ if (unlock !== void 0 && unlockActive(unlock, deps.now())) deps.consumeGrep(unlock);
998
+ else {
999
+ let state;
1000
+ if (unlock === void 0) state = messages.gateNeverSearched;
1001
+ else if (unlock.grepsLeft <= 0) state = messages.gateQuotaExhausted;
1002
+ else state = messages.gateUnlockExpired;
1003
+ reason = fill(messages.gateReason, {
1004
+ state,
1005
+ indexRoot,
1006
+ indexDir: INDEX_DIR_NAME,
1007
+ budget: deps.grepBudget,
1008
+ windowMin: deps.windowMin
1009
+ });
1010
+ }
1011
+ }
1012
+ return reason;
1013
+ }
1014
+ /**
1015
+ * shell 面(bash/pwsh)的一次检索裁决:命令串里真出现 grep/rg 才交给门禁,
1016
+ * 否则放行。`command` 非字符串(模型产出的是 unknown)按空串处理,与旧实现同形。
1017
+ */
1018
+ function shellSearchProblem(args, cwd, deps, messages) {
1019
+ const commandRaw = args["command"];
1020
+ const command = typeof commandRaw === "string" ? commandRaw : "";
1021
+ return isGrepRgCommand(command) ? buildSearchFirstReason(cwd, command, deps, messages) : void 0;
1022
+ }
1023
+ /**
1024
+ * 原生 grep 工具面的一次检索裁决:`path` 出界 = 不是本工作区的检索 → 放行
1025
+ * (与 pathInsideRoot 的「判范围不判合法性」同侧)。无 path 参数按搜整个工作区。
1026
+ */
1027
+ function nativeGrepProblem(args, cwd, deps, messages) {
1028
+ return pathInsideRoot(typeof args["path"] === "string" ? args["path"] : void 0, cwd, messages) ? buildSearchFirstReason(cwd, void 0, deps, messages) : void 0;
1029
+ }
1030
+ /**
1031
+ * search-first 门禁入口。
1032
+ * @param execution - tools.guard 收到的执行体。
1033
+ * @param deps - 判据依赖(索引探测/时钟/额度表,全部宿主注入)。
1034
+ * @param messages - 拦截文案的字典(宿主按语言取一份传进来)。
1035
+ * @returns 拦截理由;undefined = 放行。
1036
+ */
1037
+ function searchFirstGuard(execution, deps, messages) {
1038
+ const { name } = execution;
1039
+ const args = isRecord(execution.arguments) ? execution.arguments : {};
1040
+ const cwd = sessionHeaderCwd$1(execution);
1041
+ let reason;
1042
+ if (deps.enabled && cwd !== void 0) {
1043
+ if (name === "bash" || name === "pwsh") reason = shellSearchProblem(args, cwd, deps, messages);
1044
+ else if (name === "grep") reason = nativeGrepProblem(args, cwd, deps, messages);
1045
+ }
1046
+ return reason;
1047
+ }
1048
+ //#endregion
1049
+ //#region host.ts
1050
+ const SEARCH_TIMEOUT_MS = 3e5;
1051
+ const STATUS_TIMEOUT_MS = 6e4;
1052
+ const INDEX_TIMEOUT_MS = 6e5;
1053
+ const STDOUT_MAX_BYTES = 4e5;
1054
+ const REBUILD_PATH = "/_dsh/zvec-grep/rebuild";
1055
+ const REBUILD_STATUS_PATH = "/_dsh/zvec-grep/rebuild-status";
1056
+ /** 卡片取「可选工作区 + CSRF token」的引导端点(GET,只回本插件自己的数据)。 */
1057
+ const REBUILD_ROOTS_PATH = "/_dsh/zvec-grep/rebuild-roots";
1058
+ /** 动作端点的 CSRF 头名(值是每次 apply 重新生成的随机 token)。 */
1059
+ const REBUILD_CSRF_HEADER = "x-zvec-grep-csrf";
1060
+ /** rebuild 端点没有业务请求体,但必须把它读完(keep-alive 残留字节的协议正确性)。 */
1061
+ const REBUILD_BODY_MAX_BYTES = 4096;
1062
+ /** 工作区白名单容量:超过按插入序淘汰最早记录(常驻进程内存有界)。 */
1063
+ const MAX_LEDGER_ROOTS = 64;
1064
+ /** 成功执行里回显 stderr 的尾部长度(降级提示常就在这一行)。 */
1065
+ const STDERR_NOTE_CHARS = 400;
1066
+ /** 具名方法在位(typeof 函数)——只看 `typeof x === "object"` 会放过 null、
1067
+ * 也会放过「是个对象但没注册方法」的错注入。 */
1068
+ function hasMethod(value, name, keys) {
1069
+ const member = value[name];
1070
+ return isRecord(member) && keys.every((key) => typeof member[key] === "function");
1071
+ }
1072
+ /**
1073
+ * host 是否为本插件所需服务面:五个注入面都必须是**带相应方法的对象**,
1074
+ * 且 `get` 可调用。守卫失败即 apply 抛错(fail-fast),比运行到某次工具调用
1075
+ * 才 `undefined is not a function` 更早、更可诊断。
1076
+ *
1077
+ * settings 只探 `describe`:0.1.7 起那是本包唯一**直接调**的 settings 方法
1078
+ * (跨命名空间读 locale)。`configure` 经 `ctx.inject` 的子上下文才拿到,
1079
+ * `mutate` 本包 host 侧根本不用(写是卡片经 settingsScope 走 client 面)——
1080
+ * 探它们等于断言一条没有测试撑着的能力。
1081
+ */
1082
+ function isZvecGrepHost(value) {
1083
+ if (!isRecord(value)) return false;
1084
+ return hasMethod(value, "settings", ["describe"]) && hasMethod(value, "shell", ["resolve", "execute"]) && hasMethod(value, "tools", ["register", "guard"]) && hasMethod(value, "systemPrompt", ["section"]) && hasMethod(value, "timer", ["timeout"]) && typeof value["get"] === "function";
1085
+ }
1086
+ /** 当前会话工作区(root 缺省回退源);非字符串视为缺(读取面见 lib/routing.ts 的 SessionFace)。 */
1087
+ function sessionHeaderCwd(exec) {
1088
+ const raw = exec.agent?.session?.header?.cwd;
1089
+ return typeof raw === "string" && raw.length > 0 ? raw : void 0;
1090
+ }
1091
+ /**
1092
+ * JSON.stringify 在本包**拥有的声明**上把返回宽成 `string | undefined`:lib 的签名恒为
1093
+ * `string`,但 ECMA-262 规定入参是 undefined / 函数 / 符号时它返回 undefined(下面
1094
+ * textBlock 的用例就直喂 undefined)。宽化只能落在这里——调用点里 `JSON.stringify(...) ?? x`
1095
+ * 会被 TS 的收窄按声明面判成冗余守卫,而删掉那道具象兜底会把 `{ text: undefined }` 交给官方。
1096
+ */
1097
+ function stringifyJson(value) {
1098
+ return JSON.stringify(value, null, 2);
1099
+ }
1100
+ function textBlock(value) {
1101
+ const { text: textValue } = isRecord(value) ? value : {};
1102
+ if (typeof textValue === "string") return [{
1103
+ type: "text",
1104
+ text: textValue
1105
+ }];
1106
+ let text;
1107
+ try {
1108
+ text = stringifyJson(value) ?? String(value);
1109
+ } catch {
1110
+ try {
1111
+ text = String(value);
1112
+ } catch {
1113
+ text = "[unrenderable value]";
1114
+ }
1115
+ }
1116
+ return [{
1117
+ type: "text",
1118
+ text
1119
+ }];
1120
+ }
1121
+ const TEXT_OUTPUT_SCHEMA = {
1122
+ type: "object",
1123
+ additionalProperties: false,
1124
+ properties: { text: { type: "string" } }
1125
+ };
1126
+ /** 沙箱事实的公共后缀(把 mode/enforcement 一并交代清楚,避免只说「被拒」)。 */
1127
+ function sandboxFacts(info, messages) {
1128
+ const enforcement = info.enforcement === void 0 ? "" : fill(messages.sandboxEnforcement, { value: info.enforcement });
1129
+ return fill(messages.sandboxFacts, {
1130
+ mode: info.mode,
1131
+ enforcement
1132
+ });
1133
+ }
1134
+ /**
1135
+ * 沙箱侧的**硬**失败:命令根本没跑起来。
1136
+ * runnerFailed 与 exitCode 无关——runner 在命令执行前就挂了,exit 码是 runner 的,
1137
+ * 拿来判「zg 未安装」是把沙箱故障误报成用户缺二进制。
1138
+ */
1139
+ function sandboxFailure(result, messages) {
1140
+ const info = result.sandbox;
1141
+ if (info?.runnerFailed !== true) return null;
1142
+ return fill(messages.runnerFailed, { facts: sandboxFacts(info, messages) });
1143
+ }
1144
+ /** 沙箱策略拒绝的可读说明(拒绝 ≠ 崩溃:既用于失败消息,也用于成功但残缺的结果)。 */
1145
+ function deniedNote(info, messages) {
1146
+ return fill(messages.sandboxDenied, { facts: sandboxFacts(info, messages) });
1147
+ }
1148
+ /** 错误详情:首尾各留一段(zg/cargo 等错误的最终原因常在尾部)。
1149
+ * 两半各用一个函数,因为是两种缺陷:头切点会留下孤立**高**代理(`truncateEnd` 丢掉它),
1150
+ * 尾切点会留下孤立**低**代理(`truncateStart` 丢掉它);对调两个函数同样不留孤立代理,
1151
+ * 只是头尾内容掉头 ⇒ 测试里另有一组哨兵断言钉住归属。 */
1152
+ function failureDetail(result, messages) {
1153
+ const raw = result.stderr.text.length > 0 ? result.stderr.text : result.stdout.text;
1154
+ if (raw.length <= 800) return raw;
1155
+ const half = 400;
1156
+ return fill(messages.detailMiddle, {
1157
+ head: truncateEnd(raw, half),
1158
+ tail: truncateStart(raw, half)
1159
+ });
1160
+ }
1161
+ /** 有详情才带前缀拼接(不同句式各有前缀),空详情绝不留孤儿标点。 */
1162
+ function withDetail(detail, prefix) {
1163
+ return detail.length > 0 ? fill(prefix, { detail }) : "";
1164
+ }
1165
+ function shellFailure(result, messages) {
1166
+ const runnerFailure = sandboxFailure(result, messages);
1167
+ if (runnerFailure !== null) return runnerFailure;
1168
+ if (result.timedOut) return messages.timeoutFailure;
1169
+ if (result.aborted) return messages.abortedFailure;
1170
+ if (result.exitCode === 0) return null;
1171
+ const detail = failureDetail(result, messages);
1172
+ const { sandbox } = result;
1173
+ if (sandbox?.denied === true) return fill(messages.deniedFailure, {
1174
+ exit: result.exitCode,
1175
+ denied: deniedNote(sandbox, messages),
1176
+ detail: withDetail(detail, messages.detailPrefix)
1177
+ });
1178
+ if (result.exitCode === 127) return fill(messages.notInstalledFailure, { detail: withDetail(detail, messages.detailPrefix) });
1179
+ return fill(messages.genericFailure, {
1180
+ exit: result.exitCode,
1181
+ detail: withDetail(detail, messages.detailColon)
1182
+ });
1183
+ }
1184
+ /**
1185
+ * 成功(exit 0)执行的结果体检:把「其实不完整」的三类事实显式打标,避免模型
1186
+ * 把残缺输出当完整证据用。
1187
+ * 1. stdout 超上限被截尾(可能已落 spill);
1188
+ * 2. 沙箱在执行中拒绝过一次文件操作(zg 仍可 exit 0,但结果少了被拒的部分);
1189
+ * 3. **stderr 非空**:zg 的降级提示(例如 embedding 模型拉不到 → 退化为纯词法
1190
+ * 兜底、跳过 --refresh)只写在 stderr,旧实现整个丢掉 → 用户把「只有词法
1191
+ * 结果」的检索当语义检索的完整结果。这里回显尾部一段。
1192
+ */
1193
+ function successNotes(result, messages, stdoutMaxBytes) {
1194
+ const notes = [];
1195
+ if (result.stdout.truncated) {
1196
+ const spill = result.stdout.spillPath === void 0 ? "" : fill(messages.spillNote, { path: result.stdout.spillPath });
1197
+ notes.push(fill(messages.outputTruncated, {
1198
+ maxBytes: stdoutMaxBytes,
1199
+ spill
1200
+ }));
1201
+ }
1202
+ const { sandbox } = result;
1203
+ if (sandbox?.denied === true) notes.push(fill(messages.sandboxWarning, { denied: deniedNote(sandbox, messages) }));
1204
+ const { stderr } = result;
1205
+ if (stderr.text.length > 0) {
1206
+ const tail = truncateStart(stderr.text, STDERR_NOTE_CHARS);
1207
+ const truncatedMark = stderr.truncated ? "[…]" : "";
1208
+ notes.push(fill(messages.stderrNote, {
1209
+ marked: truncatedMark,
1210
+ tail
1211
+ }));
1212
+ }
1213
+ return notes;
1214
+ }
1215
+ /** 各环境读一个 HF 镜像/代理基地址的优先级:显式入参 > 设置。
1216
+ * `typeof` 判断是 host 侧兜底:值域正常时 schema 的 `.default()` 已保证是字符串,
1217
+ * 引用被交回 undefined(条目未投影/宿主退化)时宁可不带 env,也不发一个空 HF_ENDPOINT。 */
1218
+ function hfEndpointEnv(config) {
1219
+ const endpoint = config.hfEndpoint.get();
1220
+ let env;
1221
+ if (typeof endpoint === "string" && endpoint.trim().length > 0) env = { HF_ENDPOINT: endpoint.trim().replace(/\/+$/u, "") };
1222
+ return env;
1223
+ }
1224
+ /**
1225
+ * zg query 输出的命中摘要(官方检索惯例:总数/上限/截断事实显式化,模型不再把
1226
+ * 触顶/截尾的结果当完整证据用——tool-fs-search 的 grep 卡同样携带 truncated/total)。
1227
+ * zg 每个查询组打一行裸 `hits: <n>`(源码行都带行号前缀,不会撞同一形状);输出里
1228
+ * 一条计数行都没有(空结果/形状意外)时返回 null,不做摘要——不数就是不谎称。
1229
+ * 某组命中数 ≥ limit 视为触顶(zg 每组各取 top limit)。
1230
+ */
1231
+ /** zg 每个查询组的计数行前缀(实测输出形状:`hits: 3`,源码行都带行号前缀)。 */
1232
+ const HITS_LINE_PREFIX = "hits: ";
1233
+ function hitSummary(stdoutText, limit, truncated, messages) {
1234
+ const perGroup = stdoutText.split("\n").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
+ if (perGroup.length === 0) return null;
1236
+ const hits = perGroup.reduce((sum, count) => sum + count, 0);
1237
+ const capped = perGroup.some((count) => count >= limit);
1238
+ return fill(messages.hitSummary, {
1239
+ groups: perGroup.length,
1240
+ hits,
1241
+ limit,
1242
+ capped: capped ? messages.hitCapped : "",
1243
+ truncated: truncated ? messages.hitTruncated : ""
1244
+ });
1245
+ }
1246
+ async function runForeground(host, command, workdir, timeoutMs, opts) {
1247
+ const spec = host.shell.resolve({
1248
+ command,
1249
+ workdir,
1250
+ timeoutMs,
1251
+ stdoutMaxBytes: opts.stdoutMaxBytes,
1252
+ signal: opts.signal,
1253
+ ...opts.env ? { env: opts.env } : {}
1254
+ });
1255
+ const result = await (await host.shell.execute(spec)).result();
1256
+ const failure = shellFailure(result, opts.messages);
1257
+ if (failure !== null) throw new Error(failure);
1258
+ const notes = successNotes(result, opts.messages, opts.stdoutMaxBytes);
1259
+ const { text } = result.stdout;
1260
+ const summary = opts.summaryLimit === void 0 ? null : hitSummary(text, opts.summaryLimit, result.stdout.truncated, opts.messages);
1261
+ const extras = summary === null ? notes : [...notes, summary];
1262
+ return extras.length > 0 ? `${text}\n${extras.join("\n")}` : text;
1263
+ }
1264
+ /**
1265
+ * root 的存在性预检(item:不验存在)。zg 的 cwd 不存在时,spawn 直接以
1266
+ * ENOENT 失败——那与「bash 没装」「zg 没装」在同一句 stderr 里无法区分,
1267
+ * 模型据此给出的建议会把用户带偏。提前一次 existsSync 换明确归因。
1268
+ */
1269
+ function assertRootExists(root, messages) {
1270
+ if (!existsSync(root)) throw new Error(fill(messages.rootMissing, { root }));
1271
+ return root;
1272
+ }
1273
+ function readDefaultEmbedding(config) {
1274
+ const raw = config.defaultEmbedding.get();
1275
+ if (typeof raw === "string" && isLocalEmbedding(raw)) return raw;
1276
+ return DEFAULT_EMBEDDING;
1277
+ }
1278
+ /**
1279
+ * 默认每组结果数:值域 1-50 由 Config schema(隐式命名空间与行 config 共用)保证,
1280
+ * 这里只处理「字段缺省」。真正兜住越界的是 cli.clampLimit(命令构造边界)。
1281
+ */
1282
+ function readDefaultLimit(config) {
1283
+ return config.defaultLimit.get() ?? 10;
1284
+ }
1285
+ /** search-first 解锁配额:每次成功 zg_search 发放的 grep/rg 次数(值域 1-20 由 schema 保证)。 */
1286
+ function readGrepBudget(config) {
1287
+ return config.grepBudgetPerSearch.get() ?? 3;
1288
+ }
1289
+ /** search-first 解锁时效(分钟,值域 1-240 由 schema 保证)。 */
1290
+ function readUnlockWindowMin(config) {
1291
+ return config.unlockWindowMin.get() ?? 10;
1292
+ }
1293
+ /** search-first 门禁开关:**fail-closed**。schema 默认已是 true,引用仍交回 undefined
1294
+ * (条目没被投影 / 宿主退化)时按「门禁开着」处理——宁可多拦一次 grep,也不能把
1295
+ * 「读不到设置」静默当成「用户关了门禁」。 */
1296
+ function readEnforceSearchFirst(config) {
1297
+ return config.enforceSearchFirst.get() ?? true;
1298
+ }
1299
+ /** zg 索引库存在性探测(search-first 门禁与 zg_search 登记共用)。
1300
+ * 必须连 workspace manifest 一起看:`<dir>/.zvec-grep/` 这个名字被 zg 自己的**全局
1301
+ * home** 征用(`ZVEC_GREP_HOME ?? ~/.zvec-grep`,装的是 config.json / locks / models),
1302
+ * 只判目录存在的话,一个从没建过索引的工作区会因祖先目录撞名而被当成「已建索引」——
1303
+ * 门禁随即在没有任何索引可搜的情况下拦下 grep/rg,而 zg_search 也答不出任何东西。
1304
+ * manifest 是上游写索引时落的那一份(`writeWorkspaceManifest`),只有它在场,
1305
+ * 才说明这个工作区真的建过索引。 */
1306
+ function indexProbeOf(dir) {
1307
+ return existsSync(`${dir}/.zvec-grep`) && existsSync(`${dir}/.zvec-grep/manifest.json`);
1308
+ }
1309
+ /** 工具入参的 root:显式值 > 会话工作区,再过存在性预检(一处三工具共用)。 */
1310
+ function rootOf(args, exec, messages) {
1311
+ return assertRootExists(resolveRoot(args["root"], sessionHeaderCwd(exec), messages), messages);
1312
+ }
1313
+ function define(host, spec) {
1314
+ const { parameters } = spec;
1315
+ const required = Array.isArray(parameters["required"]) ? parameters["required"].filter((item) => typeof item === "string") : [];
1316
+ host.tools.register({
1317
+ name: spec.name,
1318
+ description: spec.description,
1319
+ parameters,
1320
+ output: {
1321
+ schema: TEXT_OUTPUT_SCHEMA,
1322
+ render: (_args, value) => textBlock(value)
1323
+ },
1324
+ execute: async (rawArgs, exec) => {
1325
+ const messages = spec.messages();
1326
+ if (!isRecord(rawArgs)) throw new Error(fill(messages.argsMustBeObject, {
1327
+ name: spec.name,
1328
+ received: rawArgs === null ? "null" : typeof rawArgs
1329
+ }));
1330
+ const missing = required.filter((fieldName) => rawArgs[fieldName] === void 0);
1331
+ if (missing.length > 0) throw new Error(fill(messages.missingRequiredArgs, {
1332
+ name: spec.name,
1333
+ fields: missing.join(", ")
1334
+ }));
1335
+ return await spec.run(rawArgs, exec, messages);
1336
+ }
1337
+ });
1338
+ }
1339
+ /** 隐式命名空间与 loader 行 config 共用同一 schema(单源,防漂移)。
1340
+ * 值名退避为 configSchema:避免与同名 interface Config 触发 no-redeclare;
1341
+ * 外部仍以 `Config` 名导入(export as),公开 API 不变。
1342
+ *
1343
+ * 0.1.7 迁移要点(两处都是静默失效,写错不报错):
1344
+ * - `.volatile()` 决定字段是否进设置表单。宿主 `describe()` 只投影 volatile 字段
1345
+ * (packages/settings/settings/src/schema.ts 的 volatileForm),全漏标则整条被跳过
1346
+ * (settings/src/index.ts:308-309)、写入抛 `has no volatile fields`(:386)。
1347
+ * - `settings.register(ns, schema, { base })` 的「底座」层已被宿主移除:内置默认逐字段
1348
+ * 落成下面的 `.default()`(原 BUILTIN_BASE 原样搬来,单一来源),cordis 装载期按同一
1349
+ * 份 schema 校验行 config 并填默认,再把 volatile 字段包成引用交给 apply。
1350
+ * 六个 volatile 字段全是本卡的可编辑项,一个都不该漏;四个非 volatile 部署值
1351
+ * (超时三项 + stdout 上限)只走行 config,标 volatile 反而会把它们变成设置卡项。 */
1352
+ const configSchema = Schema.object({
1353
+ defaultEmbedding: Schema.string().default(DEFAULT_EMBEDDING).volatile(),
1354
+ defaultLimit: Schema.natural().min(1).max(50).default(10).volatile(),
1355
+ hfEndpoint: Schema.string().default("https://modelscope.cn/models").volatile(),
1356
+ enforceSearchFirst: Schema.boolean().default(true).volatile(),
1357
+ grepBudgetPerSearch: Schema.natural().min(1).max(20).default(3).volatile(),
1358
+ unlockWindowMin: Schema.natural().min(1).max(240).default(10).volatile(),
1359
+ searchTimeoutMs: Schema.natural().min(1).default(SEARCH_TIMEOUT_MS),
1360
+ statusTimeoutMs: Schema.natural().min(1).default(STATUS_TIMEOUT_MS),
1361
+ indexTimeoutMs: Schema.natural().min(1).default(INDEX_TIMEOUT_MS),
1362
+ stdoutMaxBytes: Schema.natural().min(1).default(STDOUT_MAX_BYTES)
1363
+ });
1364
+ /** 官方注册表里本包作业的 kind;宿主据此发出的 id 形如 `zvec-grep-rebuild-N`。 */
1365
+ const REBUILD_JOB_KIND = "zvec-grep-rebuild";
1366
+ /**
1367
+ * 本 kind 在注册表里的**已落定**记录上限:每次 start 前先剪到 `MAX-1` 条,新那条落定后
1368
+ * 正好 `MAX` 条在册(文案与卡片 404 提示都按这个数说)。同时能跑几个不在这里——那是
1369
+ * 注册表的容量闸(实测未拥有桶 10,满员是**拒绝**新 start,不是淘汰旧的)。官方件**不会**
1370
+ * 自行回收落定记录("A settled record stays listed until its owner's disposal, service
1371
+ * disposal, or an explicit remove"),而注册表又随宿主活着、不随本插件卸载而死 ⇒ 这条
1372
+ * 裁剪是本包的责任。注意它只管历史窗口:**同时能跑几个**由注册表的容量说了算
1373
+ * (实测默认 10,且超限是**拒绝**,不是替我们杀在跑的任务)。
1374
+ */
1375
+ const REBUILD_HISTORY_MAX = 10;
1376
+ /** 卡片视图的尾部长度(打标文案在 lib/messages.ts,随语言走)。 */
1377
+ const JOB_OUT_VIEW_CHARS = 4e3;
1378
+ /**
1379
+ * 名册里那条 id 是不是**我们**的那条作业。
1380
+ *
1381
+ * 只比 id 不够:计数器是注册表的实例字段(实测两枚实例对同一 kind 都从 1 开始),换一枚
1382
+ * 实例就重名。出生时刻由官方签(`Date.now()`),跨实例撞上同一毫秒的机会与"用户在服务重载后
1383
+ * 一毫秒内又起一次重建"同阶,而那已经是另一次用户意图,卡片 404 重来即可。
1384
+ * @param state 这条记录的状态盒
1385
+ * @param view 名册里同 id 的那条投影
1386
+ * @returns 同一条作业
1387
+ */
1388
+ function sameJob(state, view, live) {
1389
+ return state.owner === live && state.bornAt === view.startedAt;
1390
+ }
1391
+ /** 终止重建进程:kill 异常忽略(进程可能已自然退出/已被回收)。 */
1392
+ function killProc(proc) {
1393
+ try {
1394
+ proc.kill();
1395
+ } catch {}
1396
+ }
1397
+ /**
1398
+ * 本包作业的输出面:官方 pull source,stdout/stderr 各一只游标,外加一层"读失败不许
1399
+ * 拖垮泵"的兜。选 pull 而不是生产者 push(`JobHandle.append`)是复核
1400
+ * 后按实测定下的:
1401
+ * - `proc.observed[*].readFrom` 是**非消费**的独立观察者面(installed dsh-shell
1402
+ * types.d.ts:199-203:"without stealing bytes from `readOutput`"),与本包前台用的
1403
+ * 消费式游标互不干扰——此前本仓写的"官方泵会与 readOutput 争同一份游标"是错的;
1404
+ * - 泵按注册表自己的节拍跑(实测默认 150ms,落定前再排最后一次)⇒ **卡片关着环也前进**,
1405
+ * 模型侧 job_output 随时看得见进度;push 形态把可见性绑在了轮询上。
1406
+ * @param proc 后台进程句柄
1407
+ * @param state 这条重建的状态盒(见 {@link RebuildState})
1408
+ * @returns 交给 JobSpec.output 的两条源
1409
+ */
1410
+ function rebuildSources(proc, state) {
1411
+ return ["stdout", "stderr"].map((channel) => {
1412
+ let failed = false;
1413
+ return {
1414
+ channel,
1415
+ read: (fromByte) => {
1416
+ if (failed) return {
1417
+ text: "",
1418
+ nextOffset: fromByte,
1419
+ lossy: true
1420
+ };
1421
+ try {
1422
+ const read = proc.observed[channel].readFrom(fromByte);
1423
+ if (read.lossy) state.lost = true;
1424
+ return read;
1425
+ } catch {
1426
+ state.lost = true;
1427
+ failed = true;
1428
+ return {
1429
+ text: "",
1430
+ nextOffset: fromByte,
1431
+ lossy: true
1432
+ };
1433
+ }
1434
+ }
1435
+ };
1436
+ });
1437
+ }
1438
+ /** 官方件对未知/已淘汰 id 抛错;本包的判据要的是"有没有",不是异常(无 ⇒ null)。 */
1439
+ function jobView(jobs, id) {
1440
+ try {
1441
+ return jobs.get(id);
1442
+ } catch {
1443
+ return null;
1444
+ }
1445
+ }
1446
+ /** 轮询端点的一次成对读数:状态投影 + 留存窗内容;注册表已无此 id ⇒ undefined。 */
1447
+ function readRebuildOutput(jobs, id) {
1448
+ try {
1449
+ return {
1450
+ view: jobs.get(id),
1451
+ retained: jobs.readAt(id, 0)
1452
+ };
1453
+ } catch {
1454
+ return null;
1455
+ }
1456
+ }
1457
+ /** 官方 JobStatus 里"仍在跑"的两枚:`stopping` 是取消已发出、进程还没收完。 */
1458
+ function isLiveStatus(status) {
1459
+ return status === "running" || status === "stopping";
1460
+ }
1461
+ /**
1462
+ * 历史窗口有界:按注册表的**可见集合**淘汰本 kind 最老的已落定记录。
1463
+ *
1464
+ * 剪到**只剩 `MAX-1` 条**才是对的:这一剪发生在 start 之前,紧接着就有一条新作业进来,
1465
+ * 它落定之后名册里正好是最近 `MAX` 条已落定记录 ⇒ 与卡片文案「只保留最近 10 条已结束的重建」
1466
+ * 同一口径。剪到 `MAX` 条会让册子在任何时刻都有 `MAX+1` 条已结束记录(实测 11 条),
1467
+ * 最初把这条判反了(只看剪完那一刻的 9 条),后来回退。
1468
+ * 在跑的一条不动——官方件对超额的答法是拒绝 start(实测),不是替我们杀任务,
1469
+ * 这里跟着杀等于把"用户的重建被静默终止"重新发明一遍。
1470
+ * 侧表里没有的 id(上一次 apply 卸载后残留的记录)同样要能清掉,所以遍历的是
1471
+ * `list()` 而不是 `records`。
1472
+ * @param jobs 官方注册表
1473
+ * @param records 本包侧表(被淘汰记录同步删掉)
1474
+ * @returns {void}
1475
+ */
1476
+ function pruneRebuildHistory(jobs, records) {
1477
+ const settled = jobs.list().filter((job) => job.kind === REBUILD_JOB_KIND).filter((job) => !isLiveStatus(job.status));
1478
+ for (const job of settled.slice(0, Math.max(settled.length - 9, 0))) {
1479
+ jobs.remove(job.id);
1480
+ records.delete(job.id);
1481
+ }
1482
+ }
1483
+ /**
1484
+ * 从官方容量闸的错误文本里取出上限(实测原文:`background job limit reached for this
1485
+ * owner (limit: 10)`)。认不出来 ⇒ undefined,调用方退回通用的启动失败文案。
1486
+ * 为什么单独认这一条:它是本包唯一会把宿主英文原话插进中文卡片的错误,又恰恰最该翻成
1487
+ * 人话的那一条——用户此时要做的是去 job_list 里收掉不需要的作业,而不是读一句英文。
1488
+ */
1489
+ function capacityLimitOf(error) {
1490
+ return /\(limit: (?<limit>\d+)\)/u.exec(errorText(error))?.groups?.["limit"];
1491
+ }
1492
+ /**
1493
+ * 「工作区重建」动作端点的四道前置校验:绝对路径 + 归一化、本 daemon 观测过的白名单、
1494
+ * 目录此刻仍存在。不过就把错误就地答完并返回 undefined(错误文本全走双语字典)。
1495
+ *
1496
+ * 这四道是**动作**端点的闸门:webServer 可被配成绑 0.0.0.0,没有白名单的话任何能连上
1497
+ * 服务面的一方都能拿任意绝对路径去 `zg index --rebuild`——读遍那棵树、写 `.zvec-grep/`,
1498
+ * 还可能把其中的非隐藏敏感文件灌进向量库并回显到上下文。
1499
+ * @param req 请求对象
1500
+ * @param res 响应对象(不过时由本函数就地应答)
1501
+ * @param ledger 观测到的工作区白名单
1502
+ * @param started 本次请求语言的文案表
1503
+ * @returns 归一化后可用的绝对路径;不合格时 null(那时本函数已经答过)
1504
+ */
1505
+ function acceptableRebuildRoot(req, res, ledger, started) {
1506
+ let root;
1507
+ try {
1508
+ root = assertAbsoluteRoot(queryParam(req, "root"), started);
1509
+ } catch (error) {
1510
+ sendJson(res, 400, {
1511
+ ok: false,
1512
+ error: fill(started.endpointRootInvalid, { reason: errorText(error) })
1513
+ });
1514
+ return null;
1515
+ }
1516
+ if (!ledger.has(root)) {
1517
+ sendJson(res, 403, {
1518
+ ok: false,
1519
+ error: fill(started.endpointRootUntracked, { root })
1520
+ });
1521
+ return null;
1522
+ }
1523
+ if (!existsSync(root)) {
1524
+ sendJson(res, 400, {
1525
+ ok: false,
1526
+ error: fill(started.endpointRootGone, { root })
1527
+ });
1528
+ return null;
1529
+ }
1530
+ return root;
1531
+ }
1532
+ /**
1533
+ * 这个 root 上有没有**仍在跑**的本包重建?有 ⇒ 返回那枚作业 id 让新面板跟随。
1534
+ *
1535
+ * 判据是三条一起:"侧表里有这条" + "名册里同 id 的那条确实是我们那条(比出生时刻)" +
1536
+ * "状态还在跑/正在收"。第二条不能省:jobs 被重载之后 id 会重名,只查侧表就把一张新面板
1537
+ * 领到别人的作业上。
1538
+ * 就地答完(200 + 复用旗标)并返回 true ⇒ 调用方直接 return;否则返回 false 继续起进程。
1539
+ * @param jobs 当前这枚注册表(缺席 ⇒ 无从判断)
1540
+ * @param records 本包侧表
1541
+ * @param res 响应对象
1542
+ * @param root 已归一化的工作区
1543
+ * @returns 是否已把这张面板领到在跑的那条上(领到了就地答完 200)
1544
+ */
1545
+ function followRunningRebuild(jobs, records, res, root) {
1546
+ const following = jobs === void 0 ? void 0 : [...records.values()].find((record) => {
1547
+ if (record.root !== root) return false;
1548
+ const view = jobView(jobs, record.id);
1549
+ return view !== null && sameJob(record.state, view, jobs) && isLiveStatus(view.status);
1550
+ });
1551
+ if (following === void 0) return false;
1552
+ sendJson(res, 200, {
1553
+ ok: true,
1554
+ jobId: following.id,
1555
+ reused: true
1556
+ });
1557
+ return true;
1558
+ }
1559
+ /**
1560
+ * 起一条重建失败时的收口:先杀掉那条已经起来的进程,再把原因翻成卡片文案。
1561
+ *
1562
+ * 官方件在 preflight(controller/容量/入参)拒掉作业时进程**已经**起来了(spawn 在注册之前)
1563
+ * ⇒ 不能留一条没登记、谁也停不掉的 zg。满员那一档单独翻文案:它是本包唯一会把宿主英文原话
1564
+ * 插进中文卡片的错误,又最该翻成人话(用户要做的是去 job_list 收作业,不是读一句英文)。
1565
+ * @param res 响应对象
1566
+ * @param error 官方件(或本包 starter)抛出的原因
1567
+ * @param proc 已经起来的 zg 进程
1568
+ * @param started 本次请求语言的文案表
1569
+ * @returns {void}
1570
+ */
1571
+ function replyStartupFailure(res, error, proc, started) {
1572
+ killProc(proc);
1573
+ const capacity = capacityLimitOf(error);
1574
+ sendJson(res, 500, {
1575
+ ok: false,
1576
+ error: capacity === void 0 ? fill(started.endpointStartFailed, { reason: errorText(error) }) : fill(started.endpointJobsAtCapacity, { limit: capacity })
1577
+ });
1578
+ }
1579
+ /**
1580
+ * 在 controller 闸门下起一条未拥有作业。
1581
+ *
1582
+ * 官方件在"没有 controller 服务这个 owner"时直接拒绝 `start`(实测台架第 1 条),而未拥有
1583
+ * 作业只被 global 层服务;web 面上宿主自己的 `tool-jobs` 被移进了各 preset realm
1584
+ * (packages/bundle/web-app/cordis.patch.yml 把 tool-jobs 在宿主平面 disabled),
1585
+ * 所以本包必须自带一枚从无作用域上下文 attach 的 controller。但**只在 start 这一瞬挂**:
1586
+ * 实测挂上即放行、摘掉即恢复拒绝、可反复,而 global 层的 controller 只被 `servesOwner`
1587
+ * 读(installed dsh-jobs-local 全文只有那一处消费),作业的后续(read/kill/落定)都不
1588
+ * 依赖它。留一枚常驻 token 等于在"宿主故意没装 job 工具"的组成里替全宿主开着那道闸门——
1589
+ * 官方契约写的是"生产者不能起一台 owner 收不掉、停不掉的作业",常驻就是把它反过来做。
1590
+ */
1591
+ function startUnderController(jobs, spec) {
1592
+ const detach = jobs.attachController("zvec-grep: rebuild");
1593
+ try {
1594
+ return jobs.start(spec);
1595
+ } finally {
1596
+ detach();
1597
+ }
1598
+ }
1599
+ /**
1600
+ * 后台进程的沙箱事实提示。runner 失败 / 策略拒绝都不许被显示成「完成」:
1601
+ * dsh-shell 只在有沙箱的执行器下填 proc.sandbox,读了它才能把「zg 自己失败」
1602
+ * 与「zg 根本没跑起来」分开。
1603
+ */
1604
+ function procSandboxNote(proc, messages) {
1605
+ const info = proc.sandbox;
1606
+ if (info === void 0) return null;
1607
+ if (info.runnerFailed === true) return fill(messages.rebuildRunnerFailed, { facts: sandboxFacts(info, messages) });
1608
+ if (info.denied) return fill(messages.rebuildDenied, { denied: deniedNote(info, messages) });
1609
+ return null;
1610
+ }
1611
+ /** 白名单键:归一化后的绝对路径;非法 root(相对/越界/NUL)归 undefined。 */
1612
+ function ledgerKey(root, messages) {
1613
+ let key;
1614
+ try {
1615
+ key = assertAbsoluteRoot(root, messages);
1616
+ } catch {
1617
+ key = void 0;
1618
+ }
1619
+ return key;
1620
+ }
1621
+ /**
1622
+ * Map 有界化:超过上限按插入序淘汰最老的若干键(常驻进程内存有界)。
1623
+ * 先写后剪:新键总在末尾,故被淘汰的一定是最早的,语义与「满了再腾位」一致。
1624
+ */
1625
+ function trimMapTo(map, max) {
1626
+ const overflow = map.size - max;
1627
+ if (overflow <= 0) return;
1628
+ for (const key of [...map.keys()].slice(0, overflow)) map.delete(key);
1629
+ }
1630
+ /** 探测缓存的 TTL(ms):负向条目(当时无索引)的陈旧上界,选型论证见下。 */
1631
+ const INDEX_PROBE_TTL_MS = 6e4;
1632
+ /** 探测缓存容量(条):guard 一次调用至多探 9 层祖先,32 条覆盖多工作区来回切换。 */
1633
+ const INDEX_PROBE_CACHE_MAX = 32;
1634
+ /**
1635
+ * zg 索引库存在性探测的**按目录缓存**(P2:guard 每次工具调用里 findIndexRoot 最多
1636
+ * 向上探 9 层 existsSync,同一工作区的连续调用命中的是同一串祖先目录;zg_search 的
1637
+ * 解锁路径也要再走一遍同样的上溯)。
1638
+ *
1639
+ * 失效策略选**进程内 TTL(60s)**而不是会话内不过期:正向条目(有索引)在「索引目录
1640
+ * 运行期不会消失」的假设下永不陈旧,TTL 对它只是内存有界的双保险;真正需要 TTL 的是
1641
+ * **负向**条目——zg_index 是运行期动作,新索引落地后若永不过期,门禁要到进程重启才
1642
+ * 看得见它。60s 的负向陈旧只是「索引出现前的既有行为」(grep 不被拦)的短暂延续,
1643
+ * 方向安全,且与「建索引后立刻去搜」的真实节奏相比可忽略。
1644
+ *
1645
+ * 缓存是**纯性能优化**:只替 existsSync 的答案,不改 findIndexRoot 的走法——root 不
1646
+ * 存在(probe 恒 false)、走满 maxDepth、上溯到 / 等失败路径在相同探测结果下与原实现
1647
+ * 逐分支一致。命中即触摸(delete+set 挪到队尾),配合 trimMapTo 的插入序淘汰 ⇒ LRU。
1648
+ *
1649
+ * @param probe 目录探测(生产注入 indexProbeOf;测试注入计数桩)
1650
+ * @param now 时钟注入(默认 Date.now;测试用它推进过 TTL)
1651
+ * @param ttlMs 条目存活时长(默认 {@link INDEX_PROBE_TTL_MS})
1652
+ * @param max 容量上限(默认 {@link INDEX_PROBE_CACHE_MAX})
1653
+ * @returns 与 probe 同签名的缓存化探测函数
1654
+ */
1655
+ function createIndexProbeCache(probe, now = Date.now, ttlMs = INDEX_PROBE_TTL_MS, max = 32) {
1656
+ const cache = /* @__PURE__ */ new Map();
1657
+ return (dir) => {
1658
+ const at = now();
1659
+ const hit = cache.get(dir);
1660
+ if (hit !== void 0 && at - hit.probedAt < ttlMs) {
1661
+ cache.delete(dir);
1662
+ cache.set(dir, hit);
1663
+ return hit.result;
1664
+ }
1665
+ const result = probe(dir);
1666
+ cache.delete(dir);
1667
+ cache.set(dir, {
1668
+ result,
1669
+ probedAt: at
1670
+ });
1671
+ trimMapTo(cache, max);
1672
+ return result;
1673
+ };
1674
+ }
1675
+ function createRootLedger(messages, max = MAX_LEDGER_ROOTS) {
1676
+ const seen = /* @__PURE__ */ new Map();
1677
+ return {
1678
+ add(root) {
1679
+ const key = ledgerKey(root, messages);
1680
+ if (key === void 0) return;
1681
+ seen.set(key, true);
1682
+ trimMapTo(seen, max);
1683
+ },
1684
+ has(root) {
1685
+ const key = ledgerKey(root, messages);
1686
+ return key !== void 0 && seen.has(key);
1687
+ },
1688
+ list() {
1689
+ return [...seen.keys()];
1690
+ }
1691
+ };
1692
+ }
1693
+ /** 引导端点:交回本次 apply 生成的 CSRF token 与白名单里观测到的工作区。 */
1694
+ function handleRebuildRoots(routes, req, res) {
1695
+ const { csrf, ledger, servingNonLoopback } = routes;
1696
+ if (!guardTrust(req, res, { servingNonLoopback })) return;
1697
+ if (req.method !== "GET" && req.method !== "HEAD") {
1698
+ res.setHeader("Allow", "GET");
1699
+ sendJson(res, 405, {
1700
+ ok: false,
1701
+ error: "GET only"
1702
+ });
1703
+ return;
1704
+ }
1705
+ sendJson(res, 200, {
1706
+ ok: true,
1707
+ csrf,
1708
+ roots: ledger.list()
1709
+ });
1710
+ }
1711
+ /**
1712
+ * 交给注册表的作业规格:输出源 + `run` 的两枚钩子(cancel / done)与那枚 kill 定时器。
1713
+ * 单独成一段是因为它只在 `start` 的那一拍被同步调用一次,与「登记进侧表」是两件事。
1714
+ * @param routes 本次注册的共享依赖(config 现读超时、host 挂 timer、jobsOf 现读注册表)
1715
+ * @param proc 已经起来的 zg 进程
1716
+ * @param state 这条重建的状态盒(与侧表记录共用)
1717
+ * @param command 实际执行的命令行(作业 label,模型在 job_list 里看见的那句)
1718
+ * @returns 官方 JobSpec:kind / label / output / run
1719
+ */
1720
+ function rebuildJobSpec(routes, proc, state, command) {
1721
+ const { config, host, jobsOf, messages } = routes;
1722
+ return {
1723
+ kind: REBUILD_JOB_KIND,
1724
+ label: command,
1725
+ output: rebuildSources(proc, state),
1726
+ run: (handle) => {
1727
+ const liveJob = () => {
1728
+ const live = jobsOf();
1729
+ if (live === void 0) return null;
1730
+ const view = jobView(live, handle.id);
1731
+ if (view === null || !sameJob(state, view, live)) return null;
1732
+ return {
1733
+ jobs: live,
1734
+ status: view.status
1735
+ };
1736
+ };
1737
+ const cancelKillTimer = host.timer.timeout(() => {
1738
+ if (proc.status !== "running") return;
1739
+ const live = liveJob();
1740
+ if (live !== null && live.status !== "running") return;
1741
+ const minutes = Math.round(config.indexTimeoutMs / 6e4);
1742
+ state.timeoutNote = fill(messages().rebuildTimeout, { minutes });
1743
+ if (live === null) {
1744
+ killProc(proc);
1745
+ return;
1746
+ }
1747
+ live.jobs.kill(handle.id, void 0, fill(messages().jobReasonTimeout, { minutes }));
1748
+ }, config.indexTimeoutMs);
1749
+ return {
1750
+ cancel: () => {
1751
+ killProc(proc);
1752
+ },
1753
+ done: (async () => {
1754
+ await proc.done;
1755
+ cancelKillTimer();
1756
+ return jobOutcomeOf(proc);
1757
+ })()
1758
+ };
1759
+ }
1760
+ };
1761
+ }
1762
+ /**
1763
+ * 起那条 `zg index --rebuild`:命令构造 + resolve + execute 三步。
1764
+ * 任一步抛错即就地 500 并交回 null(调用方直接 return,不再登记)。
1765
+ * @param routes 本次注册的共享依赖(现读 config / host)
1766
+ * @param res 响应对象(失败时由本函数就地应答)
1767
+ * @param root 已过四道前置校验的工作区
1768
+ * @param started 本次请求语言的文案表
1769
+ * @returns 起来的进程与它跑的命令;失败为 null
1770
+ */
1771
+ async function spawnRebuildProcess(routes, res, root, started) {
1772
+ const { config, host } = routes;
1773
+ const embedding = readDefaultEmbedding(config);
1774
+ let spawned;
1775
+ try {
1776
+ const built = buildIndexCommand({
1777
+ root,
1778
+ embedding,
1779
+ rebuild: true
1780
+ }, embedding, started);
1781
+ const env = hfEndpointEnv(config);
1782
+ const spec = host.shell.resolve({
1783
+ command: built.command,
1784
+ workdir: built.workdir,
1785
+ onExpiry: "none",
1786
+ stdoutMaxBytes: config.stdoutMaxBytes,
1787
+ ...env ? { env } : {}
1788
+ });
1789
+ spawned = {
1790
+ proc: await host.shell.execute(spec),
1791
+ command: built.command
1792
+ };
1793
+ } catch (error) {
1794
+ sendJson(res, 500, {
1795
+ ok: false,
1796
+ error: fill(started.endpointStartFailed, { reason: errorText(error) })
1797
+ });
1798
+ return null;
1799
+ }
1800
+ return spawned;
1801
+ }
1802
+ /**
1803
+ * 把起来的那条进程登记进官方注册表与本包侧表,交回宿主签发的 id。
1804
+ * 三种失败(注册表换人 / 同名不同命 / start 抛错)都已就地应答,交回 null。
1805
+ * @param routes 本次注册的共享依赖(jobsOf 现读、侧表引用)
1806
+ * @param res 响应对象(失败时由本函数就地应答)
1807
+ * @param root 已过前置校验的工作区(写进侧表供卡片回显)
1808
+ * @param started 本次请求语言的文案表
1809
+ * @param spawned spawnRebuildProcess 交回的进程与命令
1810
+ * @returns 宿主签发的 JobId;失败为 null
1811
+ */
1812
+ function attachRebuildJob(routes, res, root, started, spawned) {
1813
+ const { jobsOf, records } = routes;
1814
+ const { proc, command } = spawned;
1815
+ const starting = jobsOf();
1816
+ if (starting === void 0) {
1817
+ killProc(proc);
1818
+ sendJson(res, 503, {
1819
+ ok: false,
1820
+ error: started.endpointJobsUnavailable
1821
+ });
1822
+ return null;
1823
+ }
1824
+ pruneRebuildHistory(starting, records);
1825
+ const state = {
1826
+ bornAt: 0,
1827
+ owner: null,
1828
+ lost: false,
1829
+ timeoutNote: null
1830
+ };
1831
+ let jobId;
1832
+ try {
1833
+ jobId = startUnderController(starting, rebuildJobSpec(routes, proc, state, command));
1834
+ state.bornAt = starting.get(jobId).startedAt;
1835
+ state.owner = starting;
1836
+ const clashed = records.get(jobId);
1837
+ if (clashed !== void 0 && clashed.state.owner !== starting) {
1838
+ killProc(proc);
1839
+ sendJson(res, 503, {
1840
+ ok: false,
1841
+ error: started.endpointRegistryReplaced
1842
+ });
1843
+ return null;
1844
+ }
1845
+ records.set(jobId, {
1846
+ proc,
1847
+ root,
1848
+ id: jobId,
1849
+ state
1850
+ });
1851
+ } catch (error) {
1852
+ replyStartupFailure(res, error, proc, started);
1853
+ return null;
1854
+ }
1855
+ return jobId;
1856
+ }
1857
+ /** 启动端点:四道前置校验(同源 / CSRF / 白名单 / 目录存在)后复用或起一条重建。 */
1858
+ async function handleRebuildStart(routes, req, res) {
1859
+ const { csrf, jobsOf, ledger, messages, records, servingNonLoopback } = routes;
1860
+ if (!guardTrust(req, res, { servingNonLoopback })) return;
1861
+ if (req.method !== "POST") {
1862
+ res.setHeader("Allow", "POST");
1863
+ sendJson(res, 405, {
1864
+ ok: false,
1865
+ error: "POST only"
1866
+ });
1867
+ return;
1868
+ }
1869
+ if (await guardBody(req, res, {
1870
+ maxBytes: REBUILD_BODY_MAX_BYTES,
1871
+ csrf: {
1872
+ token: csrf,
1873
+ headerName: REBUILD_CSRF_HEADER
1874
+ }
1875
+ }) === null) return;
1876
+ const started = messages();
1877
+ const root = acceptableRebuildRoot(req, res, ledger, started);
1878
+ if (root === null) return;
1879
+ if (followRunningRebuild(jobsOf(), records, res, root)) return;
1880
+ if (jobsOf() === void 0) {
1881
+ sendJson(res, 503, {
1882
+ ok: false,
1883
+ error: started.endpointJobsUnavailable
1884
+ });
1885
+ return;
1886
+ }
1887
+ const spawned = await spawnRebuildProcess(routes, res, root, started);
1888
+ if (spawned === null) return;
1889
+ const jobId = attachRebuildJob(routes, res, root, started, spawned);
1890
+ if (jobId === null) return;
1891
+ sendJson(res, 200, {
1892
+ ok: true,
1893
+ jobId
1894
+ });
1895
+ }
1896
+ /** 轮询端点:官方状态投影 + 退出码/沙箱事实 + 打标后的输出尾窗(卡片每 2s 敲一次)。 */
1897
+ function handleRebuildStatus(routes, req, res) {
1898
+ const { jobsOf, messages, records, servingNonLoopback } = routes;
1899
+ if (!guardTrust(req, res, { servingNonLoopback })) return;
1900
+ const jobId = queryParam(req, "jobId");
1901
+ const record = jobId === null || jobId === "" ? void 0 : records.get(jobId);
1902
+ if (record === void 0) {
1903
+ sendJson(res, 404, {
1904
+ ok: false,
1905
+ error: fill(messages().unknownJobId, { maxJobs: REBUILD_HISTORY_MAX })
1906
+ });
1907
+ return;
1908
+ }
1909
+ const marks = messages();
1910
+ const jobs = jobsOf();
1911
+ if (jobs === void 0) {
1912
+ sendJson(res, 503, {
1913
+ ok: false,
1914
+ error: marks.endpointJobsUnavailable
1915
+ });
1916
+ return;
1917
+ }
1918
+ const output = readRebuildOutput(jobs, record.id);
1919
+ if (output === null) {
1920
+ sendJson(res, 404, {
1921
+ ok: false,
1922
+ error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX })
1923
+ });
1924
+ return;
1925
+ }
1926
+ if (!sameJob(record.state, output.view, jobs)) {
1927
+ sendJson(res, 404, {
1928
+ ok: false,
1929
+ error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX })
1930
+ });
1931
+ return;
1932
+ }
1933
+ const { view, retained } = output;
1934
+ const text = retained.chunks.map((chunk) => chunk.text).join("");
1935
+ const shown = truncateStart(text, JOB_OUT_VIEW_CHARS);
1936
+ const viewMark = text.length > JOB_OUT_VIEW_CHARS ? fill(marks.jobOutputView, {
1937
+ shown: JOB_OUT_VIEW_CHARS,
1938
+ total: text.length
1939
+ }) : "";
1940
+ sendJson(res, 200, {
1941
+ ok: true,
1942
+ status: view.status,
1943
+ exitCode: record.proc.exitCode,
1944
+ root: record.root,
1945
+ ...record.proc.sandbox === void 0 ? {} : { sandbox: record.proc.sandbox },
1946
+ output: (view.output.earliest > 0 ? marks.jobOutputTruncated : "") + (record.state.lost ? marks.jobOutputLost : "") + (record.state.timeoutNote ?? "") + (procSandboxNote(record.proc, marks) ?? "") + viewMark + shown
1947
+ });
1948
+ }
1949
+ /**
1950
+ * 卸载效应的收口:三条路由已由调用方摘掉,这里把侧表里的进程与在册作业收干净。
1951
+ * @param routes 本次注册的共享依赖(jobsOf 现读、侧表引用、文案现取)
1952
+ * @returns {void}
1953
+ */
1954
+ function releaseRebuildRecords(routes) {
1955
+ const { jobsOf, messages, records } = routes;
1956
+ const unloadReason = messages().jobReasonUnload;
1957
+ const jobs = jobsOf();
1958
+ if (jobs === void 0) for (const record of records.values()) killProc(record.proc);
1959
+ else for (const record of records.values()) {
1960
+ const view = jobView(jobs, record.id);
1961
+ if (view === null || !sameJob(record.state, view, jobs)) killProc(record.proc);
1962
+ else if (isLiveStatus(view.status)) jobs.kill(record.id, void 0, unloadReason);
1963
+ else jobs.remove(record.id);
1964
+ }
1965
+ records.clear();
1966
+ }
1967
+ /** 设置卡片的「工作区重建」端点组(引导 / 启动 / 轮询)。按语义拆离 apply 主体。 */
1968
+ function registerRebuildEndpoints(deps) {
1969
+ const { ctx, host, config, csrf, ledger, messages } = deps;
1970
+ const webServer = host.get("webServer");
1971
+ if (!webServer) return;
1972
+ const servingNonLoopback = webServer.host === "0.0.0.0";
1973
+ const jobsOf = () => host.get("jobs");
1974
+ const routes = {
1975
+ host,
1976
+ config,
1977
+ csrf,
1978
+ ledger,
1979
+ messages,
1980
+ jobsOf,
1981
+ records: /* @__PURE__ */ new Map(),
1982
+ servingNonLoopback
1983
+ };
1984
+ const disposeRoots = webServer.register({
1985
+ kind: "exact",
1986
+ path: REBUILD_ROOTS_PATH,
1987
+ handler: (req, res) => {
1988
+ handleRebuildRoots(routes, req, res);
1989
+ }
1990
+ });
1991
+ const disposeRebuild = webServer.register({
1992
+ kind: "exact",
1993
+ path: REBUILD_PATH,
1994
+ handler: async (req, res) => {
1995
+ await handleRebuildStart(routes, req, res);
1996
+ }
1997
+ });
1998
+ const disposeStatus = webServer.register({
1999
+ kind: "exact",
2000
+ path: REBUILD_STATUS_PATH,
2001
+ handler: (req, res) => {
2002
+ handleRebuildStatus(routes, req, res);
2003
+ }
2004
+ });
2005
+ ctx.effect(() => () => {
2006
+ disposeRoots();
2007
+ disposeRebuild();
2008
+ disposeStatus();
2009
+ releaseRebuildRecords(routes);
2010
+ }, "zvec-grep: rebuild endpoints");
2011
+ }
2012
+ /**
2013
+ * 页面策略声明:本包自带设置卡片,别让宿主再生成一份自动表单页。
2014
+ *
2015
+ * 0.1.7 起命名空间是**隐式**的:宿主把本条目导出的 Config 里标了 `.volatile()` 的
2016
+ * 字段投影成设置表单,ns = profile 条目 id(`zvec-grep`,见 cordis.patch.yml)。
2017
+ * 插件侧不再注册、也不再交 base(内置默认已落成 schema 的 `.default()`,cordis 装载期
2018
+ * 按它校验行 config 后把引用交进 apply 的 config 参数),只剩这一条页面策略声明。
2019
+ * owner 必须显式传本插件 fiber(缺省是 settings 服务自己的 fiber),且经 child.effect
2020
+ * 挂载以便随注入子上下文回收——宿主 dsh-client-locale 同款写法。
2021
+ * @param host 已通过服务面守卫的宿主上下文
2022
+ * @returns {void}
2023
+ */
2024
+ function configureSettingsPage(host) {
2025
+ host.inject(["settings"], (child) => {
2026
+ child.effect(() => child.settings.configure({ auto: false }, host.fiber));
2027
+ });
2028
+ }
2029
+ /**
2030
+ * 文案语言随官方 locale 偏好走的读取器:用户在「设置 → 常规」里改语言后,下一次工具回显、
2031
+ * guard 拒绝与端点应答就是新文案(不重启、不加本包自己的 locale 设置项)。
2032
+ * 跨命名空间读在 0.1.7 只有 describe() 一条路:挑出 ns === 'locale' 那条的 value
2033
+ * (未装 client-locale / 该条目未被投影 → undefined → 中文默认)。
2034
+ * @param host 已通过服务面守卫的宿主上下文
2035
+ * @returns 每次现取一份文案的 thunk
2036
+ */
2037
+ function createLocaleMessages(host) {
2038
+ return () => messagesFor(MESSAGES, resolveLocalePreference(host.settings.describe().find((row) => row.ns === LOCALE_SETTINGS_NAMESPACE)?.value));
2039
+ }
2040
+ /** 观测到的工作区:既给重建端点当白名单,也让卡片能列出可重建的 root。 */
2041
+ function trackObservedRoot(ledger, exec) {
2042
+ const cwd = sessionHeaderCwd(exec);
2043
+ if (cwd !== void 0) ledger.add(cwd);
2044
+ }
2045
+ /** 会话分片的条数上限:常驻进程只增不减会随会话数无界增长,超上限按插入序淘汰最早的分片。 */
2046
+ const MAX_UNLOCK_SESSIONS = 256;
2047
+ /**
2048
+ * search-first 门禁解锁表:会话 → (归一化索引根 → 解锁额度)。
2049
+ * 每次成功 zg_search 发放 grepBudgetPerSearch 次配额、unlockWindowMin 分钟有效;
2050
+ * 配额用尽/过期后 grep/rg 再被拦,促使模型换更准的 query 重新语义检索。
2051
+ * 配额与时效都在发放/校验时**现读** config(行 config 改了立即跟着走)。
2052
+ * @param config apply 收到的那份 volatile 引用配置
2053
+ * @returns 会话解锁表(随 apply 闭包里的 Map 一起生死)
2054
+ */
2055
+ function createUnlockLedger(config) {
2056
+ const unlocksBySession = /* @__PURE__ */ new Map();
2057
+ return {
2058
+ grant(key, indexRoot) {
2059
+ let byRoot = unlocksBySession.get(key);
2060
+ if (byRoot === void 0) {
2061
+ byRoot = /* @__PURE__ */ new Map();
2062
+ unlocksBySession.set(key, byRoot);
2063
+ trimMapTo(unlocksBySession, MAX_UNLOCK_SESSIONS);
2064
+ }
2065
+ byRoot.set(normalizeRoot(indexRoot), {
2066
+ grepsLeft: readGrepBudget(config),
2067
+ expiresAt: Date.now() + readUnlockWindowMin(config) * 6e4
2068
+ });
2069
+ },
2070
+ lookup(sessionKey, indexRoot) {
2071
+ return unlocksBySession.get(sessionKey)?.get(normalizeRoot(indexRoot));
2072
+ },
2073
+ consume(unlock) {
2074
+ unlock.grepsLeft -= 1;
2075
+ }
2076
+ };
2077
+ }
2078
+ /** zg_search 的参数面:逐字段描述都取注册期文案(与 parameters 同生死)。 */
2079
+ function searchToolParameters(registered) {
2080
+ return {
2081
+ type: "object",
2082
+ properties: {
2083
+ root: {
2084
+ type: "string",
2085
+ description: registered.rootSearchDescription
2086
+ },
2087
+ query: {
2088
+ type: "string",
2089
+ description: registered.queryDescription
2090
+ },
2091
+ queries: {
2092
+ type: "array",
2093
+ items: { type: "string" },
2094
+ description: registered.queriesDescription
2095
+ },
2096
+ fts: {
2097
+ type: "array",
2098
+ items: { type: "string" },
2099
+ description: registered.ftsDescription
2100
+ },
2101
+ vector: {
2102
+ type: "array",
2103
+ items: { type: "string" },
2104
+ description: registered.vectorDescription
2105
+ },
2106
+ fuse: {
2107
+ type: "boolean",
2108
+ description: registered.fuseDescription
2109
+ },
2110
+ limit: {
2111
+ type: "integer",
2112
+ description: registered.limitDescription
2113
+ },
2114
+ globs: {
2115
+ type: "array",
2116
+ items: { type: "string" },
2117
+ description: registered.globsDescription
2118
+ },
2119
+ insensitiveGlobs: {
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
+ },
2134
+ symbolTypes: {
2135
+ type: "array",
2136
+ items: { type: "string" },
2137
+ description: registered.symbolTypesDescription
2138
+ },
2139
+ preferSymbol: {
2140
+ type: "boolean",
2141
+ description: registered.preferSymbolDescription
2142
+ },
2143
+ modifiedAfter: {
2144
+ type: "string",
2145
+ description: registered.modifiedAfterDescription
2146
+ },
2147
+ modifiedBefore: {
2148
+ type: "string",
2149
+ description: registered.modifiedBeforeDescription
2150
+ },
2151
+ device: {
2152
+ type: "string",
2153
+ description: registered.deviceDescription
2154
+ }
2155
+ }
2156
+ };
2157
+ }
2158
+ /**
2159
+ * zg_search 的执行体:登记工作区 → 构造命令 → 前台执行 → 命中索引即给本会话发放该根的配额。
2160
+ * @param runtime apply 的运行时依赖(config 现读、解锁表与探测缓存共用)
2161
+ * @param args 官方 deep-frozen 后的工具入参
2162
+ * @param exec 执行面(signal / 会话工作区)
2163
+ * @param messages 本次 execute 现取的文案表
2164
+ * @returns 交给官方 output schema 的 `{ text }`
2165
+ */
2166
+ async function runSearchTool(runtime, args, exec, messages) {
2167
+ const { config, host, indexProbe, ledger, unlocks } = runtime;
2168
+ trackObservedRoot(ledger, exec);
2169
+ const resolvedRoot = rootOf(args, exec, messages);
2170
+ const searchArgs = {
2171
+ ...args,
2172
+ root: resolvedRoot,
2173
+ limit: args["limit"] ?? readDefaultLimit(config)
2174
+ };
2175
+ const { command, workdir } = buildSearchCommand(searchArgs, messages);
2176
+ const text = await runForeground(host, command, workdir, config.searchTimeoutMs, {
2177
+ signal: exec.signal,
2178
+ env: hfEndpointEnv(config),
2179
+ stdoutMaxBytes: config.stdoutMaxBytes,
2180
+ messages,
2181
+ summaryLimit: clampLimit(searchArgs.limit)
2182
+ });
2183
+ const indexRoot = findIndexRoot(resolvedRoot, indexProbe);
2184
+ if (indexRoot !== void 0) unlocks.grant(sessionKeyOf(exec), indexRoot);
2185
+ return { text };
2186
+ }
2187
+ /** 注册 zg_search:语义/混合检索。 */
2188
+ function registerSearchTool(runtime, registered) {
2189
+ define(runtime.host, {
2190
+ name: "zg_search",
2191
+ description: registered.searchToolDescription,
2192
+ messages: runtime.messages,
2193
+ parameters: searchToolParameters(registered),
2194
+ run: (args, exec, messages) => runSearchTool(runtime, args, exec, messages)
2195
+ });
2196
+ }
2197
+ /** zg_index 的参数面:`confirm` 必填(guard 兜底见 registerToolGuards)。 */
2198
+ function indexToolParameters(registered) {
2199
+ return {
2200
+ type: "object",
2201
+ properties: {
2202
+ root: {
2203
+ type: "string",
2204
+ description: registered.rootIndexDescription
2205
+ },
2206
+ confirm: {
2207
+ type: "boolean",
2208
+ description: registered.confirmDescription
2209
+ },
2210
+ embedding: {
2211
+ type: "string",
2212
+ description: registered.embeddingDescription
2213
+ },
2214
+ rebuild: {
2215
+ type: "boolean",
2216
+ description: registered.rebuildDescription
2217
+ },
2218
+ drop: {
2219
+ type: "boolean",
2220
+ description: registered.dropDescription
2221
+ },
2222
+ globs: {
2223
+ type: "array",
2224
+ items: { type: "string" },
2225
+ description: registered.globsIndexDescription
2226
+ },
2227
+ insensitiveGlobs: {
2228
+ type: "array",
2229
+ items: { type: "string" },
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
2246
+ },
2247
+ excludeSecrets: {
2248
+ type: "boolean",
2249
+ description: registered.excludeSecretsDescription
2250
+ },
2251
+ hidden: {
2252
+ type: "boolean",
2253
+ description: registered.hiddenDescription
2254
+ },
2255
+ noIgnore: {
2256
+ type: "boolean",
2257
+ description: registered.noIgnoreDescription
2258
+ },
2259
+ maxDepth: {
2260
+ type: "integer",
2261
+ description: registered.maxDepthDescription
2262
+ },
2263
+ maxFileSizeBytes: {
2264
+ type: "integer",
2265
+ description: registered.maxFileSizeBytesDescription
2266
+ },
2267
+ follow: {
2268
+ type: "boolean",
2269
+ description: registered.followDescription
2270
+ },
2271
+ embeddingConcurrency: {
2272
+ type: "integer",
2273
+ description: registered.embeddingConcurrencyDescription
2274
+ },
2275
+ device: {
2276
+ type: "string",
2277
+ description: registered.deviceDescription
2278
+ }
2279
+ },
2280
+ required: ["confirm"]
2281
+ };
2282
+ }
2283
+ /**
2284
+ * zg_index 的执行体:登记工作区 → 建/重建/删索引命令 → 前台执行(文本原样透传)。
2285
+ * @param runtime apply 的运行时依赖
2286
+ * @param args 官方 deep-frozen 后的工具入参
2287
+ * @param exec 执行面(signal / 会话工作区)
2288
+ * @param messages 本次 execute 现取的文案表
2289
+ * @returns 交给官方 output schema 的 `{ text }`
2290
+ */
2291
+ async function runIndexTool(runtime, args, exec, messages) {
2292
+ const { config, host, ledger } = runtime;
2293
+ trackObservedRoot(ledger, exec);
2294
+ const { command, workdir } = buildIndexCommand({
2295
+ ...args,
2296
+ root: rootOf(args, exec, messages)
2297
+ }, readDefaultEmbedding(config), messages);
2298
+ return { text: await runForeground(host, command, workdir, config.indexTimeoutMs, {
2299
+ signal: exec.signal,
2300
+ env: hfEndpointEnv(config),
2301
+ stdoutMaxBytes: config.stdoutMaxBytes,
2302
+ messages
2303
+ }) };
2304
+ }
2305
+ /** 注册 zg_index:建/重建/删索引。 */
2306
+ function registerIndexTool(runtime, registered) {
2307
+ define(runtime.host, {
2308
+ name: "zg_index",
2309
+ description: registered.indexToolDescription,
2310
+ messages: runtime.messages,
2311
+ parameters: indexToolParameters(registered),
2312
+ run: (args, exec, messages) => runIndexTool(runtime, args, exec, messages)
2313
+ });
2314
+ }
2315
+ /**
2316
+ * zg_status 的执行体:登记工作区 → `zg status` → 文本原样透传。
2317
+ * @param runtime apply 的运行时依赖
2318
+ * @param args 官方 deep-frozen 后的工具入参
2319
+ * @param exec 执行面(signal / 会话工作区)
2320
+ * @param messages 本次 execute 现取的文案表
2321
+ * @returns 交给官方 output schema 的 `{ text }`
2322
+ */
2323
+ async function runStatusTool(runtime, args, exec, messages) {
2324
+ const { config, host, ledger } = runtime;
2325
+ trackObservedRoot(ledger, exec);
2326
+ const { command, workdir } = buildStatusCommand({ root: rootOf(args, exec, messages) }, messages);
2327
+ return { text: await runForeground(host, command, workdir, config.statusTimeoutMs, {
2328
+ signal: exec.signal,
2329
+ env: hfEndpointEnv(config),
2330
+ stdoutMaxBytes: config.stdoutMaxBytes,
2331
+ messages
2332
+ }) };
2333
+ }
2334
+ /** 注册 zg_status:索引状态。 */
2335
+ function registerStatusTool(runtime, registered) {
2336
+ define(runtime.host, {
2337
+ name: "zg_status",
2338
+ description: registered.statusToolDescription,
2339
+ messages: runtime.messages,
2340
+ parameters: {
2341
+ type: "object",
2342
+ properties: { root: {
2343
+ type: "string",
2344
+ description: registered.rootStatusDescription
2345
+ } }
2346
+ },
2347
+ run: (args, exec, messages) => runStatusTool(runtime, args, exec, messages)
2348
+ });
2349
+ }
2350
+ /** 三位 zg_* 工具的注册入口:描述与参数面都取注册期文案,执行体共用同一份运行时依赖。 */
2351
+ function registerZvecTools(runtime, registered) {
2352
+ registerSearchTool(runtime, registered);
2353
+ registerIndexTool(runtime, registered);
2354
+ registerStatusTool(runtime, registered);
2355
+ }
2356
+ /** 硬规则段(systemPrompt):文本取注册期文案,随注册一次性交给宿主。 */
2357
+ function registerRoutingSection(host, registered) {
2358
+ host.systemPrompt.section({
2359
+ name: ROUTING_NAME,
2360
+ order: ROUTING_ORDER,
2361
+ text: registered.routingText
2362
+ });
2363
+ }
2364
+ /**
2365
+ * 安全兜底 guard(只拦 zg_*)+ search-first 门禁(拦 bash/pwsh 里的 grep/rg
2366
+ * 检索与原生 grep 工具)。前者拒绝安全风险,后者拒绝检索顺序违规:每次成功
2367
+ * zg_search 发放配额(次数/时效见设置),用尽/过期再拦。两谓词均纯函数,
2368
+ * 索引探测(缓存化,见 createIndexProbeCache)、时钟与会话解锁表由运行时依赖注入。
2369
+ * guard 是**每个**工具调用都会经过的观测点:顺手把该会话的工作区记进重建白名单
2370
+ * (agent.session.header.cwd 由 harness 写,模型改不了,故可作为可信来源)。
2371
+ * 这里不给 `execution` 标注类型:官方 ToolGuard 交出 `Readonly<ToolExecution>`,
2372
+ * 于是 name/arguments/signal/agent 的键名与值域都由宿主声明负责——两个谓词收到的
2373
+ * 是本包加宽后的读取投影(lib/routing.ts),加宽即容错,收窄校验留在谓词内部。
2374
+ * @param runtime apply 的运行时依赖
2375
+ * @returns {void}
2376
+ */
2377
+ function registerToolGuards(runtime) {
2378
+ const { config, host, indexProbe, ledger, messages: localeMessages, unlocks } = runtime;
2379
+ host.tools.guard((execution) => {
2380
+ trackObservedRoot(ledger, execution);
2381
+ const messages = localeMessages();
2382
+ const zg = zgGuard(execution, messages);
2383
+ if (zg !== void 0) return zg;
2384
+ return searchFirstGuard(execution, {
2385
+ enabled: readEnforceSearchFirst(config),
2386
+ indexProbe,
2387
+ now: () => Date.now(),
2388
+ grepBudget: readGrepBudget(config),
2389
+ windowMin: readUnlockWindowMin(config),
2390
+ lookupUnlock: (indexRoot) => unlocks.lookup(sessionKeyOf(execution), indexRoot),
2391
+ consumeGrep: (unlock) => {
2392
+ unlocks.consume(unlock);
2393
+ }
2394
+ }, messages);
2395
+ });
2396
+ }
2397
+ /**
2398
+ * 设置卡片的「工作区重建」端点组(引导 + 后台进程 + 轮询状态)。
2399
+ *
2400
+ * ⚠ 这三条路由的归属方必须对 webServer **建立依赖**,不能在 apply 里读一次就算完:
2401
+ * `ctx.get` 是无 inject 语义的存储读(官方 reflect.d.ts:10-14 明写 "or `undefined`
2402
+ * when not (yet) provided"),而真实宿主上 webServer 比本条目晚到位——隔离 DSH_HOME
2403
+ * 实测 apply 当场读到 undefined、+1.3s 才交得出实例。旧写法的结果是三条路由在任何
2404
+ * web profile 上都不注册,卡片的「工作区重建」永远 404。子 fiber 只在依赖到位时激活、
2405
+ * 依赖换实例时先卸后装(registry.d.ts:97),故效应挂在**子上下文**上即得「后到即注册、
2406
+ * 重启即重注册」。不写进插件级 inject:那会让没有 webServer 的宿主(TUI)连三个工具
2407
+ * 一并失活。
2408
+ * @param runtime apply 的运行时依赖(host / config / 白名单 / 文案读取器)
2409
+ * @param csrf 本次 apply 生成的 CSRF token
2410
+ * @returns {void}
2411
+ */
2412
+ function registerRebuildRoutes(runtime, csrf) {
2413
+ const { config, host, ledger, messages } = runtime;
2414
+ host.inject(["webServer"], (child) => {
2415
+ registerRebuildEndpoints({
2416
+ ctx: child,
2417
+ host,
2418
+ config,
2419
+ csrf,
2420
+ ledger,
2421
+ messages
2422
+ });
2423
+ });
2424
+ }
2425
+ function apply(ctx, config) {
2426
+ if (!isZvecGrepHost(ctx)) throw new Error("[zvec-grep] required services (settings/shell/tools/systemPrompt/timer/get) missing");
2427
+ const host = ctx;
2428
+ configureSettingsPage(host);
2429
+ const localeMessages = createLocaleMessages(host);
2430
+ const csrf = randomUUID();
2431
+ const runtime = {
2432
+ host,
2433
+ config,
2434
+ messages: localeMessages,
2435
+ ledger: createRootLedger(localeMessages()),
2436
+ unlocks: createUnlockLedger(config),
2437
+ indexProbe: createIndexProbeCache(indexProbeOf)
2438
+ };
2439
+ const registered = localeMessages();
2440
+ registerZvecTools(runtime, registered);
2441
+ registerRoutingSection(host, registered);
2442
+ registerToolGuards(runtime);
2443
+ registerRebuildRoutes(runtime, csrf);
2444
+ }
2445
+ var host_default = {
2446
+ inject: [
2447
+ "settings",
2448
+ "shell",
2449
+ "tools",
2450
+ "systemPrompt",
2451
+ "timer"
2452
+ ],
2453
+ Config: configSchema,
2454
+ apply
2455
+ };
2456
+ //#endregion
2457
+ export { configSchema as Config, INDEX_PROBE_CACHE_MAX, INDEX_PROBE_TTL_MS, createIndexProbeCache, host_default as default, hitSummary };