@jayyuen66/dsh-zvec-grep 0.1.6 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/LICENSE +1 -1
- package/README.md +272 -182
- package/README.zh-CN.md +272 -180
- package/client.js +162 -122
- package/cordis.patch.yml +3 -2
- package/host.js +335 -141
- package/package.json +41 -41
package/host.js
CHANGED
|
@@ -8,7 +8,8 @@ import { LOCALE_SETTINGS_NAMESPACE, messagesFor, resolveLocalePreference } from
|
|
|
8
8
|
import { truncateEnd, truncateStart } from "@jayyuen66/dsh-plugin-shared/lib/text";
|
|
9
9
|
import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
|
|
10
10
|
import { jobOutcomeOf } from "@jayyuen66/dsh-plugin-shared/lib/job-outcome";
|
|
11
|
-
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
// lib/embedding-catalog.ts
|
|
12
13
|
/** 默认模型:本地最强(1024 维 / 8192 上下文 / 中英通用),约 640MB 一次性下载。 */
|
|
13
14
|
const DEFAULT_EMBEDDING = "local/qwen3-embedding-0.6b";
|
|
14
15
|
/**
|
|
@@ -86,15 +87,14 @@ const LOCAL_EMBEDDINGS = [
|
|
|
86
87
|
function isLocalEmbedding(reference) {
|
|
87
88
|
return LOCAL_EMBEDDINGS.some((entry) => entry.reference === reference);
|
|
88
89
|
}
|
|
89
|
-
|
|
90
|
-
//#region lib/messages.ts
|
|
90
|
+
// lib/messages.ts
|
|
91
91
|
/** 中文侧「绝对路径 + 可操作范围」那句共用文案(三个 root 参数同义、同一份判据)。 */
|
|
92
92
|
const ABSOLUTE_ROOT_HINT_ZH = "工作区绝对路径(可选:缺省=当前会话工作区;显式传入时须在本会话可操作范围内——会话工作区本身、其上级或下级、或本会话已登记过的工作区)";
|
|
93
93
|
/** 英文侧「绝对路径 + 可操作范围」那句共用文案(检索/索引两个 root 参数同义)。 */
|
|
94
94
|
const ABSOLUTE_ROOT_HINT = "Absolute workspace path (optional: default = current session workspace; when passed explicitly it must stay inside this session's operable scope — the workspace itself, its parents or children, or a workspace this session already registered)";
|
|
95
95
|
const MESSAGES = {
|
|
96
96
|
zh: {
|
|
97
|
-
searchToolDescription: "对已建索引的工作区做语义/混合检索(BM25+向量+RRF),用于精确查找无法回答的问题:架构、调用链、依赖、生命周期、数据流/控制流、设计意图、跨文件对比与综合。root 缺省为当前会话工作区;显式传入时必须落在本会话可操作范围内(会话工作区本身、它的上级或下级目录,或本会话已登记过的工作区)。检索会自动同步既有索引的新鲜度(--refresh wait),因此改完代码无需先手动 zg_index
|
|
97
|
+
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 重新检索。",
|
|
98
98
|
indexToolDescription: "为工作区 root 创建/增量更新/重建/删除持久检索索引(建后 zg_search 才可用)。仅在用户明确要求建/重建/删索引时调用,且 confirm 必须为 true;绝不静默建索引。root 缺省为当前会话工作区;显式传入时必须落在本会话可操作范围内——会话工作区本身、它的上级或下级目录,或本会话已登记过的工作区;其余绝对路径一律拒绝(一个合法绝对路径不构成授权)。embedding 默认用设置里的 defaultEmbedding,也可显式指定,但**只接受本地候选清单内的模型**(远程 embedding 会把工作区内容送到外部端点,须由用户在部署配置里显式开放,模型侧无法开启);切换 embedding 需 rebuild=true 才重新生效。删除传 drop=true。要清掉这个根继承来的文件选择设置传 resetPaths=true。",
|
|
99
99
|
statusToolDescription: "查询工作区 root 的索引状态(是否已建、文件数、freshness、活动任务)。用于索引缺失/失败/取消后的诊断或显式进度监控;普通搜索前不要调用。",
|
|
100
100
|
rootSearchDescription: ABSOLUTE_ROOT_HINT_ZH,
|
|
@@ -105,7 +105,7 @@ const MESSAGES = {
|
|
|
105
105
|
ftsDescription: "词法查询组(如标识符、报错串)",
|
|
106
106
|
vectorDescription: "纯语义查询组",
|
|
107
107
|
fuseDescription: "融合所有组为单一排名",
|
|
108
|
-
limitDescription: "每组最大条数 1-50,默认 10",
|
|
108
|
+
limitDescription: "每组最大条数 1-50,默认 10;越出区间直接报错",
|
|
109
109
|
previewDescription: "每条命中带的源码片段大小:none 只给锚点行、short 给锚点加一段有界上下文、full 给整段源码。默认 short",
|
|
110
110
|
refreshDescription: "检索前如何刷新索引:wait 等刷新到最新(默认)、off 不刷新、background 交给守护进程后台刷新。background 只在守护进程就绪时可用:没有守护进程时这一档在命令构造前就被拒绝(直连模式下 zg 只会静默关掉刷新并留一行 stderr warning,那等于把「没刷新」说成「后台在刷」),要它请先在终端执行 `zg server on`",
|
|
111
111
|
globsDescription: "路径 glob(如 src/**),单个字符串或数组",
|
|
@@ -125,7 +125,7 @@ const MESSAGES = {
|
|
|
125
125
|
rebuildDescription: "重建已有索引(切换 embedding 时必须为 true)",
|
|
126
126
|
dropDescription: "删除索引(与其它索引选项互斥)",
|
|
127
127
|
ignoreFilesDescription: "额外的 ignore 文件路径(如 .gitignore 之外的排除清单),透传 zg --ignore-file",
|
|
128
|
-
excludeSecretsDescription: "是否排除私钥/密钥库格式(*.pem/*.key/*.p12/*.pfx/*.keystore/id_rsa*),默认 true。本插件的排除规则排在用户正向 glob 之后,用户规则覆盖不掉它——所以这一位是「要不要索引私钥」的唯一开关:置 false 会把这批文件灌进向量库,此后检索可以把它们回显到上下文。只有用户明确要求索引密钥夹具时才给 false",
|
|
128
|
+
excludeSecretsDescription: "是否排除私钥/密钥库格式(*.pem/*.key/*.p12/*.pfx/*.keystore/*.jks/*.ppk/id_rsa*),默认 true。本插件的排除规则排在用户正向 glob 之后,用户规则覆盖不掉它——所以这一位是「要不要索引私钥」的唯一开关:置 false 会把这批文件灌进向量库,此后检索可以把它们回显到上下文。只有用户明确要求索引密钥夹具时才给 false",
|
|
129
129
|
hiddenDescription: "包含隐藏文件(默认不含,隐藏密钥文件因此已被排除)",
|
|
130
130
|
noIgnoreDescription: "不读 ignore 文件",
|
|
131
131
|
maxDepthDescription: "最大目录深度",
|
|
@@ -161,6 +161,7 @@ const MESSAGES = {
|
|
|
161
161
|
abortedFailure: "zg 执行被中止",
|
|
162
162
|
rebuildWaitTimeout: "等待 {root} 的重建完成超时(约 {seconds} 秒),重建可能仍在进行;请稍后重试。本次不会发放 grep/rg 配额——重建期间索引不可读,先等它结束。",
|
|
163
163
|
rebuildWaitAborted: "等待 {root} 的重建完成时被中止。",
|
|
164
|
+
lockBusyOtherOperation: "zg 索引锁正被其他操作占用(ownerOperation: {op}),本命令没有等待它结束:这类操作(如索引刷新)可能耗时很久,稍后重试或等它落定后再查",
|
|
164
165
|
statusRebuilding: "{root} 正在重建中(作业 {jobId})。重建期间索引不可读,检索会自动等待它完成后重试。如需查看实时输出,请在设置卡的工作区重建面板里观察。此刻即使问「索引是否就绪」也是否定的答案——重建落定后再问。",
|
|
165
166
|
statusNotReady: "[zvec-grep] {root} 的索引**未就绪**(上面是 zg 的完整就绪报告)。这不是执行失败,而是 checkReady=true 要的那个结论:{detail} 若刷新反复失败(报告里出现 `read only mode` 一类写入被拒的措辞),那是该索引自身的状态问题,重建即可恢复:zg_index(root=\"…\", confirm=true, rebuild=true)。",
|
|
166
167
|
checkReadyDescription: "就绪判定:就绪报告照常给出,另行判定索引是否 ready 并在结论里明说。未就绪不是执行失败,报告仍会返回",
|
|
@@ -223,17 +224,19 @@ const MESSAGES = {
|
|
|
223
224
|
rootIsFsRoot: "root 不能是文件系统根目录 /",
|
|
224
225
|
rootRequiredWithFallback: "root 必填,且为工作区绝对路径(可省略:缺省为当前会话工作区)",
|
|
225
226
|
limitInvalid: "limit 必须是非负整数(省略则用默认值)",
|
|
227
|
+
limitOutOfRange: "limit 超出允许范围 {min}–{max}(省略则用默认值)",
|
|
226
228
|
mustBeStringArray: "{name} 必须是字符串数组",
|
|
227
229
|
tooManyItems: "{name} 最多 {maxItems} 项(实际 {actual})",
|
|
228
230
|
nonStringItem: "{name} 含非字符串项({received})",
|
|
229
|
-
commandTooLong: "zg 命令总长 {length}
|
|
231
|
+
commandTooLong: "zg 命令总长 {length} 字节,超过 {maxBytes} 字节上限,请缩小检索范围",
|
|
230
232
|
tooManyQueryRoutes: "检索路由合计 {count} 组,超过 {max} 组上限",
|
|
231
233
|
searchNeedsQuery: "zg_search 需要 query/queries/fts/vector 至少其一",
|
|
232
234
|
exhaustiveNeedsPattern: "穷举检索(rg=true)需要一个 query 作为匹配模式",
|
|
233
235
|
exhaustiveConflicts: "穷举检索(rg=true)与下列索引侧参数互斥:{names}。穷举是纯词法匹配,不支持这些参数;把它们去掉,或先建索引(zg_index)再用索引检索",
|
|
234
236
|
embeddingNotAllowed: "embedding 引用 {reference} 不在本地候选清单内,而本部署未开放远程 embedding。远程 embedding 会把工作区内容送到外部端点,必须由用户在部署配置里显式开放(allowRemoteEmbedding),本插件不接受模型侧开启。可选本地模型:{choices}。若用户确已自行配好远程凭据(zg config provider set / zg auth grant <root> --capability embedding --scope workspace),请在插件部署配置里打开对应开关后重试。",
|
|
235
237
|
dropWithResetPaths: "drop 与 resetPaths 互斥:--drop 整条命令只有删除索引一件事,resetPaths 无处安放(上游 zg 也拒这一对)。要清继承的文件选择设置,请不要传 drop。",
|
|
236
|
-
|
|
238
|
+
dropWithIndexArgs: "drop 与这些索引侧参数互斥:{names}。--drop 整条命令只有删除索引一件事,它们不会被使用(静默收下只会让人以为过滤/重建生效了);请去掉这些参数后重发删除。",
|
|
239
|
+
ignoreFileMissing: "ignoreFiles 里的 {path} 不是一份「存在且当前进程可读的文件」(不存在、是目录、或有文件但读不了都算)。上游 zg 遇到读不成的忽略文件不会按「没有这条规则」继续,而是整次索引失败(ENOENT / EISDIR / EACCES),并把这条坏路径写进工作区索引状态——此后这条树上的 zg index / zg status 都会报同一个错,--reset-paths 也清不掉,只有 zg_index drop 能救。请给一个真实存在、当前用户可读的忽略文件路径。",
|
|
237
240
|
exhaustiveFallbackNote: "[zvec-grep] 该工作区(含向上各级)尚无 zg 索引,已自动改用穷举词法检索(rg 模式)。结果是逐行字面匹配,不是语义相关度排序;需要语义检索请先 zg_index 建索引。",
|
|
238
241
|
rgDescription: "穷举词法检索(对应 zg query --rg):不需要索引,逐行字面匹配。留空则在工作区无索引时自动改用它、有索引时照常走索引检索。显式 false 可要求只用索引检索(无索引即报错)。它不支持 preview / refresh / fuse / symbolTypes / preferSymbol / fts / vector / queries,且不发放 grep/rg 配额",
|
|
239
242
|
intWithReceived: "{name} 必须是 >= {min} 的整数(收到 {received})",
|
|
@@ -247,8 +250,8 @@ const MESSAGES = {
|
|
|
247
250
|
gateReason: "[zvec-grep] 工作区检索门禁({state}):当前工作区已建 zg 索引({indexRoot}/{indexDir}),直接 grep/rg 字面检索经常漏检。请先调用 zg_search(语义/混合检索,覆盖面与相关性更好;把当前检索目标作为 query/fts),每次成功的 zg_search 解锁 {budget} 次 grep/rg({windowMin} 分钟内有效),用于精确字面/正则补充。"
|
|
248
251
|
},
|
|
249
252
|
en: {
|
|
250
|
-
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
|
|
251
|
-
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
|
|
253
|
+
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 is not indexed silently either: the call switches to exhaustive literal search and says so in the result. 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.",
|
|
254
|
+
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 is allowed only when this session can already reach it — a workspace or a parent/child of one this session has opened, or one this session already registered — and anything else is refused (a path merely existing is not an authorization). embedding defaults to the configured defaultEmbedding and may be set explicitly, but **only models in the local catalog are accepted** (remote embedding sends workspace content to an external endpoint and must be enabled explicitly by the user in the deployment config — the model side cannot turn it on); switching embedding only takes effect with rebuild=true. Pass drop=true to delete. Pass resetPaths=true to clear the file-selection settings this root inherited.",
|
|
252
255
|
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.",
|
|
253
256
|
rootSearchDescription: ABSOLUTE_ROOT_HINT,
|
|
254
257
|
rootIndexDescription: ABSOLUTE_ROOT_HINT,
|
|
@@ -258,7 +261,7 @@ const MESSAGES = {
|
|
|
258
261
|
ftsDescription: "Lexical query groups (identifiers, error strings)",
|
|
259
262
|
vectorDescription: "Purely semantic query groups",
|
|
260
263
|
fuseDescription: "Fuse all groups into a single ranking",
|
|
261
|
-
limitDescription: "Max hits per group, 1-50, default 10",
|
|
264
|
+
limitDescription: "Max hits per group, 1-50, default 10; a value outside that range is refused",
|
|
262
265
|
previewDescription: "How much source each hit carries: none anchor line only, short anchor plus a bounded context window, full the whole chunk. Default short",
|
|
263
266
|
refreshDescription: "How the index is refreshed before searching: wait refreshes to the latest (default), off does not refresh, background hands it to the daemon. background needs a ready daemon: without one it is refused before the command is built (in direct mode zg silently turns refreshing off and leaves one stderr warning, which would report \"refreshing in the background\" when nothing refreshes) — run `zg server on` in a terminal to get it",
|
|
264
267
|
globsDescription: "Path globs (e.g. src/**), a single string or an array",
|
|
@@ -278,7 +281,7 @@ const MESSAGES = {
|
|
|
278
281
|
rebuildDescription: "Rebuild the existing index (must be true when switching embedding)",
|
|
279
282
|
dropDescription: "Delete the index (mutually exclusive with the other index options)",
|
|
280
283
|
ignoreFilesDescription: "Extra ignore-file paths (exclusion lists beyond .gitignore), passed through as zg --ignore-file",
|
|
281
|
-
excludeSecretsDescription: "Whether to exclude private-key/keystore formats (*.pem/*.key/*.p12/*.pfx/*.keystore/id_rsa*), default true. These exclusion rules are evaluated after user include globs, so no user glob can bring the files back: this flag is the only switch for indexing private keys, and false feeds them into the vector store, from where search can echo them back into context. Set false only when the user explicitly asks to index key fixtures",
|
|
284
|
+
excludeSecretsDescription: "Whether to exclude private-key/keystore formats (*.pem/*.key/*.p12/*.pfx/*.keystore/*.jks/*.ppk/id_rsa*), default true. These exclusion rules are evaluated after user include globs, so no user glob can bring the files back: this flag is the only switch for indexing private keys, and false feeds them into the vector store, from where search can echo them back into context. Set false only when the user explicitly asks to index key fixtures",
|
|
282
285
|
hiddenDescription: "Include hidden files (excluded by default, which also drops hidden key files)",
|
|
283
286
|
noIgnoreDescription: "Do not read ignore files",
|
|
284
287
|
maxDepthDescription: "Maximum directory depth",
|
|
@@ -314,6 +317,7 @@ const MESSAGES = {
|
|
|
314
317
|
abortedFailure: "zg execution was aborted",
|
|
315
318
|
rebuildWaitTimeout: "timed out after about {seconds}s waiting for the rebuild of {root}; it may still be running. Retry later. No grep/rg quota is granted: the index is unreadable while the rebuild runs.",
|
|
316
319
|
rebuildWaitAborted: "aborted while waiting for the rebuild of {root} to finish",
|
|
320
|
+
lockBusyOtherOperation: "the zg index lock is held by another operation (ownerOperation: {op}); this command did not wait for it: such operations (e.g. an index refresh) can run very long — retry later, or query again once it settles",
|
|
317
321
|
statusRebuilding: "{root} is being rebuilt (job {jobId}). The index is unreadable while the rebuild runs; searches wait for it to finish and retry. Watch live output in the settings card rebuild panel. Asking whether the index is ready right now would get a negative answer anyway — ask again once the rebuild settles.",
|
|
318
322
|
statusNotReady: "[zvec-grep] the index for {root} is **not ready** (the full zg readiness report is above). This is not an execution failure, it is the conclusion checkReady=true asked for: {detail} If refreshes keep failing (wording like `read only mode` means writes are refused), that is the index's own state — rebuild it to recover: zg_index(root=\"…\", confirm=true, rebuild=true).",
|
|
319
323
|
checkReadyDescription: "Readiness verdict: the readiness report is still returned, and the tool additionally states whether the index is ready. Not-ready is not an execution failure — the report still comes back",
|
|
@@ -376,17 +380,19 @@ const MESSAGES = {
|
|
|
376
380
|
rootIsFsRoot: "root must not be the filesystem root /",
|
|
377
381
|
rootRequiredWithFallback: "root is required and must be an absolute workspace path (it may be omitted: defaults to the current session workspace)",
|
|
378
382
|
limitInvalid: "limit must be a non-negative integer (omit it to use the default)",
|
|
383
|
+
limitOutOfRange: "limit is out of the allowed range {min}–{max} (omit it to use the default)",
|
|
379
384
|
mustBeStringArray: "{name} must be an array of strings",
|
|
380
385
|
tooManyItems: "{name} allows at most {maxItems} items (actual {actual})",
|
|
381
386
|
nonStringItem: "{name} contains a non-string item ({received})",
|
|
382
|
-
commandTooLong: "the zg command is {length}
|
|
387
|
+
commandTooLong: "the zg command is {length} bytes, over the {maxBytes} byte limit — narrow the search",
|
|
383
388
|
tooManyQueryRoutes: "{count} query routes in total, over the limit of {max}",
|
|
384
389
|
searchNeedsQuery: "zg_search needs at least one of query/queries/fts/vector",
|
|
385
390
|
exhaustiveNeedsPattern: "exhaustive search (rg=true) needs a query to use as the pattern",
|
|
386
391
|
exhaustiveConflicts: "exhaustive search (rg=true) conflicts with these indexed-search parameters: {names}. Exhaustive search is pure lexical matching and does not support them; drop them, or build an index first (zg_index) and search the index",
|
|
387
392
|
embeddingNotAllowed: "embedding reference {reference} is not in the local catalog, and this deployment has not enabled remote embedding. Remote embedding sends workspace content to an external endpoint and must be turned on explicitly by the user in the deployment config (allowRemoteEmbedding); this plugin never lets the model side enable it. Local choices: {choices}. If the user has already set up remote credentials themselves (zg config provider set / zg auth grant <root> --capability embedding --scope workspace), enable the matching deployment setting and retry.",
|
|
388
393
|
dropWithResetPaths: "drop conflicts with resetPaths: --drop does nothing but delete the index, so resetPaths has nowhere to go (upstream zg rejects the pair too). To clear inherited file-selection settings, do not pass drop.",
|
|
389
|
-
|
|
394
|
+
dropWithIndexArgs: "drop conflicts with these index-side parameters: {names}. --drop does nothing but delete the index, so they would never be used (accepting them silently only suggests the filters/rebuild took effect); remove them and resend the drop.",
|
|
395
|
+
ignoreFileMissing: "{path} is not an existing file the current process can read (missing, a directory, or present-but-unreadable all count). Upstream zg does not treat a failed ignore-file read as \"no such rule\": the whole indexing run fails (ENOENT / EISDIR / EACCES) and the bad path is written into the workspace index state, after which every zg index / zg status on that tree reports the same error — even --reset-paths cannot clear it, only zg_index drop can. Give a path that really exists and that the current user can read.",
|
|
390
396
|
exhaustiveFallbackNote: "[zvec-grep] This workspace (and every directory above it) has no zg index, so the search fell back to exhaustive lexical matching (rg mode). Results are literal line matches, not ranked by semantic relevance; run zg_index first if you need semantic search.",
|
|
391
397
|
rgDescription: "Exhaustive lexical search (zg query --rg): needs no index, matches literal text line by line. Leave it unset to fall back to it automatically when the workspace has no index, and to use the index when one exists. An explicit false demands indexed search only (an error when there is no index). It does not support preview / refresh / fuse / symbolTypes / preferSymbol / fts / vector / queries, and it grants no grep/rg quota",
|
|
392
398
|
intWithReceived: "{name} must be an integer >= {min} (received {received})",
|
|
@@ -415,8 +421,7 @@ function fill(template, params) {
|
|
|
415
421
|
return value === void 0 ? "" : String(value);
|
|
416
422
|
});
|
|
417
423
|
}
|
|
418
|
-
|
|
419
|
-
//#region lib/argv-guard.ts
|
|
424
|
+
// lib/argv-guard.ts
|
|
420
425
|
const MAX_COMMAND_BYTES = 64e3;
|
|
421
426
|
/** 单条 query 文本上限(再长属误用:zg 的语义检索按句切分)。 */
|
|
422
427
|
const MAX_QUERY_CHARS = 4e3;
|
|
@@ -458,11 +463,6 @@ function optionalText(value, name, messages, maxChars) {
|
|
|
458
463
|
function stringList(value, name, messages, maxItems = MAX_FILTER_ITEMS, maxChars = MAX_FILTER_CHARS) {
|
|
459
464
|
if (value === void 0 || value === null) return [];
|
|
460
465
|
if (!Array.isArray(value)) throw new TypeError(fill(messages.mustBeStringArray, { name }));
|
|
461
|
-
if (value.length > maxItems) throw new TypeError(fill(messages.tooManyItems, {
|
|
462
|
-
name,
|
|
463
|
-
maxItems,
|
|
464
|
-
actual: value.length
|
|
465
|
-
}));
|
|
466
466
|
const out = [];
|
|
467
467
|
for (const item of value) {
|
|
468
468
|
if (typeof item !== "string") throw new TypeError(fill(messages.nonStringItem, {
|
|
@@ -473,6 +473,11 @@ function stringList(value, name, messages, maxItems = MAX_FILTER_ITEMS, maxChars
|
|
|
473
473
|
const trimmed = assertTextLen(item.trim(), name, messages, maxChars);
|
|
474
474
|
if (trimmed.length > 0) out.push(trimmed);
|
|
475
475
|
}
|
|
476
|
+
if (value.length > maxItems) throw new TypeError(fill(messages.tooManyItems, {
|
|
477
|
+
name,
|
|
478
|
+
maxItems,
|
|
479
|
+
actual: value.length
|
|
480
|
+
}));
|
|
476
481
|
return out;
|
|
477
482
|
}
|
|
478
483
|
/**
|
|
@@ -510,13 +515,12 @@ const SECRET_EXCLUDE_GLOBS = [
|
|
|
510
515
|
"!*.p12",
|
|
511
516
|
"!*.pfx",
|
|
512
517
|
"!*.keystore",
|
|
518
|
+
"!*.jks",
|
|
519
|
+
"!*.ppk",
|
|
513
520
|
"!id_rsa*",
|
|
514
521
|
"!id_ed25519*"
|
|
515
522
|
];
|
|
516
|
-
|
|
517
|
-
//#region lib/cli.ts
|
|
518
|
-
const LIMIT_MIN = 1;
|
|
519
|
-
const LIMIT_MAX = 50;
|
|
523
|
+
// lib/cli.ts
|
|
520
524
|
const CLIENT_MODE_NAMES = Object.keys({
|
|
521
525
|
auto: "auto",
|
|
522
526
|
direct: "direct",
|
|
@@ -674,35 +678,46 @@ function assertAbsoluteRoot(root, messages) {
|
|
|
674
678
|
* root 解析:显式绝对路径优先;缺失/空串回退到 fallback(当前会话工作区,
|
|
675
679
|
* 调用方从 exec.agent.session.header.cwd 取——官方 dsh-tool-fs-search 同模式)。
|
|
676
680
|
* ROC 原则:fallback 也走 assertAbsoluteRoot 校验,绝不无条件接受。
|
|
681
|
+
* 显式的**非字符串**值不进 fallback 分支:模型写 `{root: 123}` 时若静默滑到会话工作区,
|
|
682
|
+
* 搜索就在模型没指定的目录上执行并交回一份「合法」结果——类型错必须当场报。
|
|
677
683
|
*/
|
|
678
684
|
function resolveRoot(value, fallback, messages) {
|
|
685
|
+
if (value !== void 0 && value !== null && typeof value !== "string") throw new TypeError(fill(messages.rootMustBeString, { received: typeof value }));
|
|
679
686
|
if (typeof value === "string" && value.trim().length > 0) return assertAbsoluteRoot(value.trim(), messages);
|
|
680
687
|
if (typeof fallback === "string" && fallback.trim().length > 0) return assertAbsoluteRoot(fallback.trim(), messages);
|
|
681
688
|
throw new Error(messages.rootRequiredWithFallback);
|
|
682
689
|
}
|
|
683
690
|
/**
|
|
684
|
-
* limit
|
|
691
|
+
* limit 取值:省略(undefined/null)回默认;不是非负整数即抛;越界拒绝并点名区间。
|
|
685
692
|
*
|
|
686
693
|
* 类型只认 number:`Number()` 会把 `true` 折成 1、把 `[]` 折成 0——模型给一个类型错的 limit
|
|
687
|
-
*
|
|
694
|
+
* 就会静默只回一条结果,而它会把「只有一处命中」当成这次检索的事实。越界同样拒绝而不是
|
|
695
|
+
* 钳制:静默钳过的 limit 让模型以为要回了 999 条、实际只看到 50 条,还把「少」当成了事实;
|
|
696
|
+
* 拒绝并报区间,下一轮它自己改对。
|
|
688
697
|
*/
|
|
689
|
-
function
|
|
698
|
+
function resolveLimit(value, messages, fallback = 10) {
|
|
690
699
|
if (value === void 0 || value === null) return fallback;
|
|
691
700
|
if (typeof value !== "number") throw new TypeError(messages.limitInvalid);
|
|
692
701
|
if (!Number.isSafeInteger(value) || value < 0) throw new Error(messages.limitInvalid);
|
|
693
|
-
|
|
702
|
+
if (value < 1 || value > 50) throw new Error(fill(messages.limitOutOfRange, {
|
|
703
|
+
min: 1,
|
|
704
|
+
max: 50
|
|
705
|
+
}));
|
|
706
|
+
return value;
|
|
694
707
|
}
|
|
695
708
|
/** 检索类数组(queries/fts/vector)取值:条数与单条长度都放宽到 query 档。 */
|
|
696
709
|
function queryList(value, name, messages) {
|
|
697
710
|
return stringList(value, name, messages, 32, MAX_QUERY_CHARS);
|
|
698
711
|
}
|
|
699
|
-
/**
|
|
712
|
+
/** 整条命令的规模闸门:按 UTF-8 字节比 MAX_COMMAND_BYTES(防 E2BIG 与无界内存)。
|
|
713
|
+
* 多字节内容一个码元可占 3~4 字节,按 `String.length`(码元数)比会在中文/emoji 面上
|
|
714
|
+
* 放过 Linux MAX_ARG_STRLEN 的单参数上限——判据必须落在内核真正收到的字节数上。 */
|
|
700
715
|
function assembled(parts, workdir, messages) {
|
|
701
716
|
const command = parts.join(" ");
|
|
702
|
-
const
|
|
717
|
+
const length = Buffer.byteLength(command, "utf8");
|
|
703
718
|
if (length > 64e3) throw new Error(fill(messages.commandTooLong, {
|
|
704
719
|
length,
|
|
705
|
-
|
|
720
|
+
maxBytes: MAX_COMMAND_BYTES
|
|
706
721
|
}));
|
|
707
722
|
return {
|
|
708
723
|
command,
|
|
@@ -776,7 +791,7 @@ function buildIndexedCommand(args, root, messages, mode, backgroundSupport) {
|
|
|
776
791
|
const refresh = refreshOf(args.refresh, messages);
|
|
777
792
|
if (refresh === "background" && backgroundSupport === "daemon-down") throw new Error(fill(messages.refreshBackgroundNeedsServer, { root }));
|
|
778
793
|
if (refresh === "background" && backgroundSupport === "mode-direct") throw new Error(fill(messages.refreshBackgroundPinnedDirect, { root }));
|
|
779
|
-
parts.push("--limit", String(
|
|
794
|
+
parts.push("--limit", String(resolveLimit(args.limit, messages)), "--preview", previewOf(args.preview, messages), "--refresh", refresh);
|
|
780
795
|
pushSearchGlobs(parts, args, messages);
|
|
781
796
|
if (boolOf(args.preferSymbol, "preferSymbol", messages)) parts.push("--prefer-symbol");
|
|
782
797
|
if (boolOf(args.trace, "trace", messages)) parts.push("--trace");
|
|
@@ -821,7 +836,7 @@ function buildExhaustiveCommand(args, root, messages, mode) {
|
|
|
821
836
|
if (pattern.length === 0) throw new Error(messages.exhaustiveNeedsPattern);
|
|
822
837
|
if (pattern.startsWith("-")) parts.push("-e", shq(pattern));
|
|
823
838
|
else parts.push(shq(pattern));
|
|
824
|
-
parts.push("--limit", String(
|
|
839
|
+
parts.push("--limit", String(resolveLimit(args.limit, messages)));
|
|
825
840
|
pushPathFilters(parts, args, messages);
|
|
826
841
|
pushTimeFilters(parts, args, messages);
|
|
827
842
|
parts.push(deviceFlag(args.device, messages), modeFlag(mode));
|
|
@@ -952,8 +967,32 @@ function indexEmbedding(args, defaultEmbedding, messages, allowRemote) {
|
|
|
952
967
|
}));
|
|
953
968
|
}
|
|
954
969
|
/**
|
|
970
|
+
* drop 那一臂用不上的索引侧参数(--drop 的命令只有 `index <root> --drop --yes`)。
|
|
971
|
+
* 只在这里点名:出现任何一个,drop 臂整体拒绝而不是静默丢弃——布尔旗标在那之前已按
|
|
972
|
+
* 类型校验过、丢弃无声,其余参数连类型都没校验,两种待遇并存会让
|
|
973
|
+
* `{drop:true, hidden:"yes"}` 报错而 `{drop:true, maxDepth:"3"}` 静默通过。
|
|
974
|
+
*/
|
|
975
|
+
const INDEX_ONLY_PARAMS = [
|
|
976
|
+
"rebuild",
|
|
977
|
+
"embedding",
|
|
978
|
+
"globs",
|
|
979
|
+
"insensitiveGlobs",
|
|
980
|
+
"fileTypes",
|
|
981
|
+
"excludedFileTypes",
|
|
982
|
+
"ignoreFiles",
|
|
983
|
+
"hidden",
|
|
984
|
+
"noIgnore",
|
|
985
|
+
"excludeSecrets",
|
|
986
|
+
"maxDepth",
|
|
987
|
+
"maxFileSizeBytes",
|
|
988
|
+
"follow",
|
|
989
|
+
"embeddingConcurrency",
|
|
990
|
+
"device"
|
|
991
|
+
];
|
|
992
|
+
/**
|
|
955
993
|
* 构造 zg index 命令。root 是位置参数(转义)。
|
|
956
|
-
* - drop=true:`zg index <root> --drop --yes --mode <mode>`(非交互 shell 必须 --yes
|
|
994
|
+
* - drop=true:`zg index <root> --drop --yes --mode <mode>`(非交互 shell 必须 --yes);
|
|
995
|
+
* 索引侧参数与 drop 互斥(resetPaths 另有单独互斥文案),出现即点名拒绝。
|
|
957
996
|
* - 否则:`zg index <root> --embedding <m> [--rebuild] ... --mode <mode>`。
|
|
958
997
|
* embedding 缺省时由调用方传入 defaultEmbedding(设置里的默认值);显式值过构造期
|
|
959
998
|
* allowlist(见 indexEmbedding)。
|
|
@@ -973,6 +1012,8 @@ function buildIndexCommand(args, defaultEmbedding, messages, mode = DEFAULT_CLIE
|
|
|
973
1012
|
const flags = readIndexFlags(args, messages);
|
|
974
1013
|
if (boolOf(args.drop, "drop", messages)) {
|
|
975
1014
|
if (boolOf(args.resetPaths, "resetPaths", messages)) throw new Error(messages.dropWithResetPaths);
|
|
1015
|
+
const ignored = INDEX_ONLY_PARAMS.filter((name) => args[name] !== void 0 && args[name] !== null);
|
|
1016
|
+
if (ignored.length > 0) throw new Error(fill(messages.dropWithIndexArgs, { names: ignored.join(" | ") }));
|
|
976
1017
|
parts.push("--drop", "--yes", modeFlag(mode));
|
|
977
1018
|
return assembled(parts, root, messages);
|
|
978
1019
|
}
|
|
@@ -1007,8 +1048,7 @@ function buildStatusCommand(args, messages, mode = DEFAULT_CLIENT_MODE) {
|
|
|
1007
1048
|
parts.push(modeFlag(mode));
|
|
1008
1049
|
return assembled(parts, root, messages);
|
|
1009
1050
|
}
|
|
1010
|
-
|
|
1011
|
-
//#region lib/search-predicates.ts
|
|
1051
|
+
// lib/search-predicates.ts
|
|
1012
1052
|
const GREP_COMMAND_NAMES = /* @__PURE__ */ new Set([
|
|
1013
1053
|
"grep",
|
|
1014
1054
|
"egrep",
|
|
@@ -1036,6 +1076,44 @@ const SEARCH_PREFIX_WORDS = /* @__PURE__ */ new Set([
|
|
|
1036
1076
|
"nice",
|
|
1037
1077
|
"parallel"
|
|
1038
1078
|
]);
|
|
1079
|
+
/**
|
|
1080
|
+
* 包装命令里「带一个取值」的选项:其后那一个 token 是它的值,不是被执行的命令
|
|
1081
|
+
* (`sudo -u root grep`、`nice -n 10 rg`、`timeout -s 9 5 rg`)。
|
|
1082
|
+
*
|
|
1083
|
+
* 跨包装命令共用一张表:这些短选项在 git/xargs/env/sudo/time/nice/timeout 里
|
|
1084
|
+
* 语义一致,逐个包装登记一份只会让「加了新包装却忘了登记」多一处可能。
|
|
1085
|
+
*/
|
|
1086
|
+
const VALUE_TAKING_FLAGS = /* @__PURE__ */ new Set([
|
|
1087
|
+
"-a",
|
|
1088
|
+
"-c",
|
|
1089
|
+
"-C",
|
|
1090
|
+
"-d",
|
|
1091
|
+
"-E",
|
|
1092
|
+
"-f",
|
|
1093
|
+
"-g",
|
|
1094
|
+
"-I",
|
|
1095
|
+
"-k",
|
|
1096
|
+
"-L",
|
|
1097
|
+
"-n",
|
|
1098
|
+
"-o",
|
|
1099
|
+
"-p",
|
|
1100
|
+
"-P",
|
|
1101
|
+
"-r",
|
|
1102
|
+
"-s",
|
|
1103
|
+
"-t",
|
|
1104
|
+
"-T",
|
|
1105
|
+
"-u",
|
|
1106
|
+
"-U",
|
|
1107
|
+
"--adjustment",
|
|
1108
|
+
"--group",
|
|
1109
|
+
"--kill-after",
|
|
1110
|
+
"--signal",
|
|
1111
|
+
"--user"
|
|
1112
|
+
]);
|
|
1113
|
+
/** 命令前的壳层赋值(`VAR=1 grep x` 里的 `VAR=1`):它自己不是命令,其后仍是命令位。 */
|
|
1114
|
+
const SHELL_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/u;
|
|
1115
|
+
/** 包装命令的裸数值参数(`timeout 5 rg` 的 `5`):也不是被执行的命令。 */
|
|
1116
|
+
const BARE_NUMBER = /^\d+$/u;
|
|
1039
1117
|
/** 结束一个 token、但**不**开启新命令位的字符(空白、右括号、重定向)。 */
|
|
1040
1118
|
const TOKEN_BREAK_CHARS = /* @__PURE__ */ new Set([
|
|
1041
1119
|
" ",
|
|
@@ -1119,7 +1197,8 @@ function tokenizeShell(command) {
|
|
|
1119
1197
|
else if (COMMAND_BREAK_CHARS.has(char)) {
|
|
1120
1198
|
flush();
|
|
1121
1199
|
state.atCommand = true;
|
|
1122
|
-
|
|
1200
|
+
const neighbourIsPipe = command.slice(index + 1, index + 2) === "|" || command.slice(index - 1, index) === "|";
|
|
1201
|
+
state.pipedNext = char === "|" && !neighbourIsPipe;
|
|
1123
1202
|
} else if (TOKEN_BREAK_CHARS.has(char)) flush();
|
|
1124
1203
|
else state.buffer += char;
|
|
1125
1204
|
index += 1;
|
|
@@ -1127,22 +1206,40 @@ function tokenizeShell(command) {
|
|
|
1127
1206
|
flush();
|
|
1128
1207
|
return tokens;
|
|
1129
1208
|
}
|
|
1130
|
-
/**
|
|
1209
|
+
/**
|
|
1210
|
+
* token 的命令名(basename,小写)。
|
|
1211
|
+
* 两个调用点都只喂命令位 token,而命令位判据已经把 `-` 开头的选项排除了
|
|
1212
|
+
* (见 `commandPositionIndexes`),所以这里不再重复判一次前缀:那会是一条
|
|
1213
|
+
* 永远走不到的分支。
|
|
1214
|
+
*/
|
|
1131
1215
|
function baseName(text) {
|
|
1132
|
-
if (text.startsWith("-")) return "";
|
|
1133
1216
|
return text.slice(text.lastIndexOf("/") + 1).toLowerCase();
|
|
1134
1217
|
}
|
|
1135
1218
|
/**
|
|
1136
1219
|
* 挑出处在「被执行位置」的 token:串首 / 控制符之后 / 包装命令(git、xargs、
|
|
1137
|
-
* env
|
|
1220
|
+
* env…)之后那个真正的实参。
|
|
1221
|
+
*
|
|
1222
|
+
* 「包装命令之后」不是「紧邻的下一个 token」:包装命令自己的选项(`git --no-pager`、
|
|
1223
|
+
* `xargs -0`)、选项取值(`sudo -u root`)、裸数值(`timeout 5`)、壳层赋值(`VAR=1`)
|
|
1224
|
+
* 都还站在命令位之前。只认「紧邻下一个」时命令位链在这些形态上直接断掉,检索调用
|
|
1225
|
+
* 漏判 —— 而漏判的方向是门禁放行。这几类一律「跳过但不断链」。
|
|
1138
1226
|
*/
|
|
1139
1227
|
function commandPositionIndexes(tokens) {
|
|
1140
1228
|
const out = [];
|
|
1141
1229
|
let afterPrefix = false;
|
|
1230
|
+
let pendingValue = false;
|
|
1142
1231
|
for (const [index, token] of tokens.entries()) {
|
|
1232
|
+
const { text } = token;
|
|
1143
1233
|
const isCommand = token.atCommand || afterPrefix;
|
|
1144
|
-
if (
|
|
1145
|
-
|
|
1234
|
+
if (pendingValue) {
|
|
1235
|
+
pendingValue = false;
|
|
1236
|
+
afterPrefix = true;
|
|
1237
|
+
} else if (isCommand && VALUE_TAKING_FLAGS.has(text)) pendingValue = true;
|
|
1238
|
+
else if (isCommand && (text.startsWith("-") || BARE_NUMBER.test(text) || SHELL_ASSIGNMENT.test(text))) afterPrefix = true;
|
|
1239
|
+
else {
|
|
1240
|
+
if (isCommand) out.push(index);
|
|
1241
|
+
afterPrefix = isCommand && SEARCH_PREFIX_WORDS.has(baseName(text));
|
|
1242
|
+
}
|
|
1146
1243
|
}
|
|
1147
1244
|
return out;
|
|
1148
1245
|
}
|
|
@@ -1187,9 +1284,16 @@ function isGrepRgCommand(command) {
|
|
|
1187
1284
|
return !(token.piped && !hasPathOperand(tokens, index));
|
|
1188
1285
|
});
|
|
1189
1286
|
}
|
|
1190
|
-
/**
|
|
1191
|
-
|
|
1192
|
-
|
|
1287
|
+
/**
|
|
1288
|
+
* 去掉尾部斜杠的 root 归一化('/' 自身保持 '/')。
|
|
1289
|
+
*
|
|
1290
|
+
* 只认 `/`:本包的根判据(`assertAbsoluteRoot` 只收 `/` 开头的串)、命令 tokenizer 与
|
|
1291
|
+
* `rootPaths` 覆盖判据都按 POSIX 形切分,root 归一化再多认一种分隔符只会让上游认得出、
|
|
1292
|
+
* 下游判不回——README 的 Support surface 一节写明 Windows 主机不在支持面内,
|
|
1293
|
+
* 失败形态是 fail-fast 而不是静默漂移。要真正支持 Windows,得连上面那三处判据一起改。
|
|
1294
|
+
*/
|
|
1295
|
+
function normalizeRoot(root) {
|
|
1296
|
+
const trimmed = root.replace(/\/+$/u, "");
|
|
1193
1297
|
return trimmed.length > 0 ? trimmed : "/";
|
|
1194
1298
|
}
|
|
1195
1299
|
/**
|
|
@@ -1212,7 +1316,8 @@ function pathInsideRoot(target, root, messages) {
|
|
|
1212
1316
|
} catch {
|
|
1213
1317
|
return false;
|
|
1214
1318
|
}
|
|
1215
|
-
|
|
1319
|
+
const prefix = base.endsWith("/") ? base : `${base}/`;
|
|
1320
|
+
return absolute === base || absolute.startsWith(prefix);
|
|
1216
1321
|
}
|
|
1217
1322
|
/**
|
|
1218
1323
|
* bash/pwsh 命令串中是否存在「索引根之外」的路径证据。
|
|
@@ -1256,8 +1361,7 @@ function unlockActive(unlock, now) {
|
|
|
1256
1361
|
function pathsRelated(left, right, messages) {
|
|
1257
1362
|
return pathInsideRoot(left, right, messages) || pathInsideRoot(right, left, messages);
|
|
1258
1363
|
}
|
|
1259
|
-
|
|
1260
|
-
//#region lib/routing.ts
|
|
1364
|
+
// lib/routing.ts
|
|
1261
1365
|
/** 紧跟 TOOL_GREP(1500) 之后、TOOL_JOBS(1600) 之前。 */
|
|
1262
1366
|
const ROUTING_ORDER = 1550;
|
|
1263
1367
|
const ROUTING_NAME = "zvec-grep-routing";
|
|
@@ -1347,11 +1451,13 @@ const WORKSPACE_MANIFEST_FILE = "manifest.json";
|
|
|
1347
1451
|
* 从 startDir 向上找含 zg 索引库的最近祖先(含自身),返回该索引根。
|
|
1348
1452
|
* 会话工作区可能是索引根的子目录(如索引在仓库根、会话开在子包)——不向上走
|
|
1349
1453
|
* 会漏拦。probe 注入(宿主用 existsSync),本函数保持纯函数可单测。
|
|
1454
|
+
* 相对路径无从向上判(祖先链不是文件系统事实),按「探测不到」处理:返回 undefined,
|
|
1455
|
+
* 与「上一层没有索引」同形,门禁按无索引放行。
|
|
1350
1456
|
*/
|
|
1351
1457
|
function findIndexRoot(startDir, probe, maxDepth = 8) {
|
|
1352
1458
|
let dir = normalizeRoot(startDir);
|
|
1353
1459
|
let found;
|
|
1354
|
-
for (let depth = 0; depth <= maxDepth; depth += 1) {
|
|
1460
|
+
if (startDir.startsWith("/")) for (let depth = 0; depth <= maxDepth; depth += 1) {
|
|
1355
1461
|
if (probe(dir)) {
|
|
1356
1462
|
found = dir;
|
|
1357
1463
|
break;
|
|
@@ -1393,7 +1499,13 @@ function rootSessionKeyOf(execution, lookup) {
|
|
|
1393
1499
|
let cursor = parent;
|
|
1394
1500
|
for (let hop = 0; hop < 32; hop += 1) {
|
|
1395
1501
|
if (lookup === void 0) return cursor;
|
|
1396
|
-
|
|
1502
|
+
let parentView;
|
|
1503
|
+
try {
|
|
1504
|
+
parentView = lookup(cursor);
|
|
1505
|
+
} catch {
|
|
1506
|
+
parentView = void 0;
|
|
1507
|
+
}
|
|
1508
|
+
const next = parentView?.parentSession;
|
|
1397
1509
|
if (typeof next !== "string" || next.length === 0 || seen.has(next)) return cursor;
|
|
1398
1510
|
seen.add(next);
|
|
1399
1511
|
cursor = next;
|
|
@@ -1401,26 +1513,26 @@ function rootSessionKeyOf(execution, lookup) {
|
|
|
1401
1513
|
return cursor;
|
|
1402
1514
|
}
|
|
1403
1515
|
/**
|
|
1404
|
-
*
|
|
1405
|
-
*
|
|
1406
|
-
*
|
|
1407
|
-
* - 原生 grep 工具:检索目标位于会话工作区内(path 出界不属工作区检索,放行)。
|
|
1408
|
-
* 会话工作区(含祖先)存在 zg 索引且当前无可用解锁额度(从未 zg_search、配额
|
|
1409
|
-
* 用尽或已过期)→ 拒绝并给出可行动出路。解锁额度按「会话 × 索引根」计,
|
|
1410
|
-
* 每次成功的 zg_search 重置为 N 次、M 分钟有效——保证语义检索频率与 grep
|
|
1411
|
-
* 用量成正比,而不是一次放行终身豁免。
|
|
1412
|
-
* 已知近似:bash 自由文本无法可靠区分模式与相对路径 token,hasExternalTarget
|
|
1413
|
-
* 只认明确的路径形状,`../` 形态的模式词可能被误判为外部目标而放行(漏拦,
|
|
1414
|
-
* 安全方向);混合目标(如 `rg foo /repo/src /tmp/x`)整体放行。
|
|
1516
|
+
* 原生 grep 面的目标是否落在索引根之内。相对路径先按**会话工作区**解析成绝对路径,
|
|
1517
|
+
* 再按索引根判内外——按索引根直接拼相对段会把 `../other` 拼进索引根内部,方向判反。
|
|
1518
|
+
* `..` 越出文件系统根:目标必然不在索引根之内(判范围不判合法性,同 pathInsideRoot)。
|
|
1415
1519
|
*/
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1520
|
+
function nativeTargetInsideRoot(cwd, indexRoot, target, messages) {
|
|
1521
|
+
if (target === void 0 || target.trim().length === 0) return true;
|
|
1522
|
+
const text = target.trim();
|
|
1523
|
+
const joined = text.startsWith("/") ? text : `${normalizeRoot(cwd)}/${text}`;
|
|
1524
|
+
let absolute;
|
|
1525
|
+
try {
|
|
1526
|
+
absolute = normalizeAbsolutePath(joined, messages);
|
|
1527
|
+
} catch {
|
|
1528
|
+
return false;
|
|
1529
|
+
}
|
|
1530
|
+
return pathInsideRoot(absolute, indexRoot, messages);
|
|
1531
|
+
}
|
|
1532
|
+
function buildSearchFirstReason(cwd, scope, deps, messages) {
|
|
1533
|
+
const indexRoot = findIndexRoot(cwd, deps.indexProbe, deps.findIndexDepth);
|
|
1422
1534
|
let reason;
|
|
1423
|
-
if (indexRoot !== void 0 && (
|
|
1535
|
+
if (indexRoot !== void 0 && (scope.kind === "shell" ? !hasExternalTarget(indexRoot, scope.command, messages) : nativeTargetInsideRoot(cwd, indexRoot, scope.target, messages))) {
|
|
1424
1536
|
const rebuilding = deps.rebuildBypass?.(indexRoot) === true;
|
|
1425
1537
|
const unlock = rebuilding ? void 0 : deps.lookupUnlock(indexRoot);
|
|
1426
1538
|
if (rebuilding) {} else if (unlock !== void 0 && unlockActive(unlock, deps.now())) deps.consumeGrep(unlock);
|
|
@@ -1447,14 +1559,20 @@ function buildSearchFirstReason(cwd, command, deps, messages) {
|
|
|
1447
1559
|
function shellSearchProblem(args, cwd, deps, messages) {
|
|
1448
1560
|
const commandRaw = args["command"];
|
|
1449
1561
|
const command = typeof commandRaw === "string" ? commandRaw : "";
|
|
1450
|
-
return isGrepRgCommand(command) ? buildSearchFirstReason(cwd,
|
|
1562
|
+
return isGrepRgCommand(command) ? buildSearchFirstReason(cwd, {
|
|
1563
|
+
kind: "shell",
|
|
1564
|
+
command
|
|
1565
|
+
}, deps, messages) : void 0;
|
|
1451
1566
|
}
|
|
1452
1567
|
/**
|
|
1453
|
-
* 原生 grep
|
|
1568
|
+
* 原生 grep 工具面的一次检索裁决:目标在索引根之外 = 不是本工作区的检索 → 放行
|
|
1454
1569
|
* (与 pathInsideRoot 的「判范围不判合法性」同侧)。无 path 参数按搜整个工作区。
|
|
1455
1570
|
*/
|
|
1456
1571
|
function nativeGrepProblem(args, cwd, deps, messages) {
|
|
1457
|
-
return
|
|
1572
|
+
return buildSearchFirstReason(cwd, {
|
|
1573
|
+
kind: "native",
|
|
1574
|
+
target: typeof args["path"] === "string" ? args["path"] : void 0
|
|
1575
|
+
}, deps, messages);
|
|
1458
1576
|
}
|
|
1459
1577
|
/**
|
|
1460
1578
|
* search-first 门禁入口。
|
|
@@ -1475,22 +1593,20 @@ function searchFirstGuard(execution, deps, messages) {
|
|
|
1475
1593
|
return reason;
|
|
1476
1594
|
}
|
|
1477
1595
|
/**
|
|
1478
|
-
*
|
|
1596
|
+
* 表超过阈值就报警一次(不删任何条目)。
|
|
1479
1597
|
*
|
|
1480
|
-
*
|
|
1481
|
-
*
|
|
1482
|
-
*
|
|
1483
|
-
*
|
|
1484
|
-
*
|
|
1598
|
+
* 为什么只报不删:见 MAX_TRACKED_REBUILDS 的注释——两个阶段都可能有真在跑的 zg,
|
|
1599
|
+
* 淘汰就是造孤儿。真正该做的是让「有一次 claim 没配对 release」这件事被人看见。
|
|
1600
|
+
* 只在刚越过阈值那一刻报一次(回落之后才重新武装),否则每次 claim 都刷一行。
|
|
1601
|
+
* @param entries 活跃表
|
|
1602
|
+
* @param max 阈值
|
|
1603
|
+
* @param alreadyCrowded 上一次判定为「已越阈值」
|
|
1604
|
+
* @returns 本次是否越阈值(供调用方回写状态)
|
|
1485
1605
|
*/
|
|
1486
|
-
function
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
entries.delete(root);
|
|
1491
|
-
entry.settle();
|
|
1492
|
-
}
|
|
1493
|
-
}
|
|
1606
|
+
function warnIfCrowded(entries, max, alreadyCrowded) {
|
|
1607
|
+
if (entries.size <= max) return false;
|
|
1608
|
+
if (!alreadyCrowded) console.warn(`[zvec-grep] 活跃重建表有 ${String(entries.size)} 条,超过阈值 ${String(max)}:这不是容量淘汰(淘汰会让正在跑的重建失去占位,同根就能起第二条 zg),而是有一次 claim 没配对 release —— 请把这段告警连同调用场景报给维护者。`);
|
|
1609
|
+
return true;
|
|
1494
1610
|
}
|
|
1495
1611
|
/**
|
|
1496
1612
|
* 覆盖给定 root 的那条活跃条目:重建根是 root 的祖先或同一处时命中,多条命中取
|
|
@@ -1509,11 +1625,13 @@ function createRebuildRegistry(options = {}) {
|
|
|
1509
1625
|
const now = options.now ?? Date.now;
|
|
1510
1626
|
const maxTracked = options.maxTracked ?? 32;
|
|
1511
1627
|
const entries = /* @__PURE__ */ new Map();
|
|
1628
|
+
let crowded = false;
|
|
1512
1629
|
const release = (root) => {
|
|
1513
1630
|
const entry = entries.get(root);
|
|
1514
1631
|
if (entry === void 0) return false;
|
|
1515
1632
|
entries.delete(root);
|
|
1516
1633
|
entry.settle();
|
|
1634
|
+
if (entries.size <= maxTracked) crowded = false;
|
|
1517
1635
|
return true;
|
|
1518
1636
|
};
|
|
1519
1637
|
return {
|
|
@@ -1533,7 +1651,7 @@ function createRebuildRegistry(options = {}) {
|
|
|
1533
1651
|
settle
|
|
1534
1652
|
};
|
|
1535
1653
|
entries.set(root, entry);
|
|
1536
|
-
|
|
1654
|
+
crowded = warnIfCrowded(entries, maxTracked, crowded);
|
|
1537
1655
|
return entry;
|
|
1538
1656
|
},
|
|
1539
1657
|
attach(root, jobId) {
|
|
@@ -1582,16 +1700,28 @@ function createRebuildRegistry(options = {}) {
|
|
|
1582
1700
|
}
|
|
1583
1701
|
/** 索引重建与其它占用者分开:等与不等是两回事。 */
|
|
1584
1702
|
const REBUILD_OPERATION = "index.rebuild";
|
|
1585
|
-
/**
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1703
|
+
/**
|
|
1704
|
+
* zg 明细块的键值行。三个细节都来自「明细行是缩进的」这一实测形状:
|
|
1705
|
+
* - 缩进**必填**(`\s+`):明细块之后任何含冒号的非空行(第二个错误块的 `Error:` /
|
|
1706
|
+
* `Code:`、尾注 `Hint:`)都不该被当成明细键收进表,与已知键同名时会污染判断;
|
|
1707
|
+
* - 键字符集放宽到字母开头 + `[\w-]`:上游若改用 `owner_operation` 这类拼写,行至少
|
|
1708
|
+
* 还能被认出来(值是否被消费由查表侧决定),不至于整块收集在此中断;
|
|
1709
|
+
* - 值必须以非空白开头:把只含空白的行当成有效值没有意义。
|
|
1710
|
+
*/
|
|
1711
|
+
const DETAIL_LINE = /^(?:\s+)(?<key>[A-Za-z][\w-]*):\s*(?<value>\S.*?)\s*$/u;
|
|
1712
|
+
/** 错误码行的**定位**形状(只认行首,不核内容)。 */
|
|
1713
|
+
const CODE_LINE_PREFIX = /^\s*Code:/u;
|
|
1714
|
+
/** 错误码行的**取值**形状:`Code:` 之后是单一 token。 */
|
|
1715
|
+
const CODE_LINE = /^\s*Code:\s*(?<code>\S+)\s*$/u;
|
|
1589
1716
|
/**
|
|
1590
1717
|
* 抽错误码。没有该行就不是 zg 的结构化失败(旁路返回 null,交给通用失败文案)。
|
|
1591
|
-
*
|
|
1718
|
+
* 先定位第一条 `Code:` 行、再核它的内容是否为单一 token:一次失败只应有一个码,
|
|
1719
|
+
* 首处写成 `Code: XXX (detail)` 说明输出形状已变——宁可不判,也不许顺延到后文
|
|
1720
|
+
* 捞一个可能属于别的错误块的码回来。
|
|
1592
1721
|
*/
|
|
1593
1722
|
function zgErrorCode(stderr) {
|
|
1594
|
-
|
|
1723
|
+
const firstCodeLine = stderr.split("\n").find((line) => CODE_LINE_PREFIX.test(line));
|
|
1724
|
+
return firstCodeLine === void 0 ? void 0 : CODE_LINE.exec(firstCodeLine)?.groups?.["code"];
|
|
1595
1725
|
}
|
|
1596
1726
|
/**
|
|
1597
1727
|
* 明细块的键值表。`Details:` 之后的缩进行才是明细,标题与错误码行不参与。
|
|
@@ -1637,22 +1767,26 @@ function classifyConcurrentFailure(stderr) {
|
|
|
1637
1767
|
};
|
|
1638
1768
|
return null;
|
|
1639
1769
|
}
|
|
1640
|
-
|
|
1641
|
-
//#region lib/zg-version.ts
|
|
1642
|
-
/** 本包按之书写的 zg 语义版本。低于它一律在命令构造前拒绝。 */
|
|
1643
|
-
const MINIMUM_ZG_VERSION = "0.2.2";
|
|
1770
|
+
// lib/zg-version.ts
|
|
1644
1771
|
/**
|
|
1645
|
-
*
|
|
1646
|
-
*
|
|
1647
|
-
* 那属于「读不懂」,归到 undefined 由调用方按「探测不到」处理。
|
|
1772
|
+
* 门槛本体:比较用的对象是唯一事实来源,回显用的字符串由它派生——两处在编译期
|
|
1773
|
+
* 就不可能漂移,改门槛只改这一个字面量。
|
|
1648
1774
|
*/
|
|
1649
|
-
const VERSION_SHAPE = /^\s*(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)\s*$/u;
|
|
1650
|
-
/** 门槛值本身就是常量,拿它自己当被测对象即可(写成字面量免去一次可失败的解析)。 */
|
|
1651
1775
|
const MINIMUM = {
|
|
1652
1776
|
major: 0,
|
|
1653
1777
|
minor: 2,
|
|
1654
1778
|
patch: 2
|
|
1655
1779
|
};
|
|
1780
|
+
/** 本包按之书写的 zg 语义版本(字面形态,给文案回显)。低于它一律在命令构造前拒绝。 */
|
|
1781
|
+
const MINIMUM_ZG_VERSION = `${MINIMUM.major}.${MINIMUM.minor}.${MINIMUM.patch}`;
|
|
1782
|
+
/**
|
|
1783
|
+
* 形状:整串就是一个三段数字版本,`v` 前缀可有可无,可带前后的空白与换行。
|
|
1784
|
+
* 分量至多 9 位数字:`Number()` 对超长数字串会丢精度乃至得到 Infinity,畸形输入
|
|
1785
|
+
* 会被当成「版本极大」而放行——把「读不懂」当成「够新」是 fail-open。仍不接受
|
|
1786
|
+
* `0.2.2-rc.1` / `>=0.2.2` / 带标题前缀这类——真出现了就说明输出形态变了,那属于
|
|
1787
|
+
* 「读不懂」,归到 undefined 由调用方按「探测不到」处理。
|
|
1788
|
+
*/
|
|
1789
|
+
const VERSION_SHAPE = /^\s*v?(?<major>\d{1,9})\.(?<minor>\d{1,9})\.(?<patch>\d{1,9})\s*$/u;
|
|
1656
1790
|
/**
|
|
1657
1791
|
* 不是版本号时用的哨兵:版本分量恒非负,故负数只可能来自「没解析出来」。
|
|
1658
1792
|
* 三个函数都收敛成**单一 return**(`return a` 与 `return undefined` 混排会被本仓的
|
|
@@ -1695,8 +1829,25 @@ function tooOldZgVersion(stdout) {
|
|
|
1695
1829
|
const parsed = parseZgVersion(stdout);
|
|
1696
1830
|
return parsed === void 0 || versionAtLeast(parsed, MINIMUM) ? void 0 : parsed;
|
|
1697
1831
|
}
|
|
1698
|
-
|
|
1699
|
-
|
|
1832
|
+
// lib/index-preflight.ts
|
|
1833
|
+
/**
|
|
1834
|
+
* 预检判「文件不合适」时接受的家庭错误码:其余(fd 耗尽、链接环、IO 错误等环境故障)
|
|
1835
|
+
* 与用户给的路径无关,原样上抛——把 EMFILE 说成「请给一个真实存在的文件」会把排查
|
|
1836
|
+
* 引向错误的方向。
|
|
1837
|
+
*/
|
|
1838
|
+
const UNUSABLE_FILE_CODES = /* @__PURE__ */ new Set([
|
|
1839
|
+
"ENOENT",
|
|
1840
|
+
"EACCES",
|
|
1841
|
+
"EISDIR",
|
|
1842
|
+
"ENOTDIR"
|
|
1843
|
+
]);
|
|
1844
|
+
/** node:fs 的失败一律是带 string code 的 Error 实例;形状不合(非对象、无 code、码非串)
|
|
1845
|
+
* 一律按环境故障处理。导出只为把非 Error 形状的判别面钉进单测(真 fs 抛不出这些)。 */
|
|
1846
|
+
function isUnusableFileCode(error) {
|
|
1847
|
+
if (typeof error !== "object" || error === null || !("code" in error)) return false;
|
|
1848
|
+
const code = error.code;
|
|
1849
|
+
return typeof code === "string" && UNUSABLE_FILE_CODES.has(code);
|
|
1850
|
+
}
|
|
1700
1851
|
/**
|
|
1701
1852
|
* `ignoreFiles` 的可用性预检:模型给的第 N 条忽略文件必须是**当前进程读得了的普通文件**。
|
|
1702
1853
|
*
|
|
@@ -1708,70 +1859,97 @@ function tooOldZgVersion(stdout) {
|
|
|
1708
1859
|
* 分支会让 CI 的 windows 那格在 100% 覆盖率门禁下无从而钉(本仓不用 coverage-ignore 逃生口)。
|
|
1709
1860
|
* 合成一句「不是存在且可读的文件」文案,三种成因都准确覆盖,且 catch 由「不存在」这一档跨平台钉住。
|
|
1710
1861
|
*
|
|
1711
|
-
* drop
|
|
1712
|
-
*
|
|
1713
|
-
*
|
|
1714
|
-
* `boolOf`,两处口径不会漂。
|
|
1862
|
+
* drop 那一臂整段跳过:drop 的命令不含 ignoreFiles,且构造器对「drop 携带索引侧参数」会
|
|
1863
|
+
* 点名拒绝(见 lib/cli.ts 的 buildIndexCommand)——预检既没有可查的对象,也没有机会跑到;
|
|
1864
|
+
* 若照跑,反而会拿"给一个真实存在的忽略文件"这句误导文案把一次合法的删索引拦下。
|
|
1865
|
+
* 判 drop 用与构造器**同一个** `boolOf`,两处口径不会漂。
|
|
1715
1866
|
* @param args 索引入参(`ignoreFiles` 单值或数组;`drop` 为真时整段跳过)
|
|
1716
1867
|
* @param root 已归一的工作区根(相对路径按它解析)
|
|
1717
1868
|
* @param messages 文案表
|
|
1718
1869
|
* @returns {void}
|
|
1719
|
-
* @throws Error
|
|
1870
|
+
* @throws Error 指向第一个不可用的条目(不静默丢弃用户给的那一项);node:fs 的环境类
|
|
1871
|
+
* 故障(非文件形状问题)原样上抛
|
|
1720
1872
|
*/
|
|
1721
1873
|
function assertIgnoreFilesExist(args, root, messages) {
|
|
1722
1874
|
if (boolOf(args.drop, "drop", messages)) return;
|
|
1723
1875
|
for (const entry of singleOrList(args.ignoreFiles, "ignoreFiles", messages)) {
|
|
1724
|
-
const target =
|
|
1876
|
+
const target = path.isAbsolute(entry) ? entry : path.resolve(root, entry);
|
|
1725
1877
|
let usable = false;
|
|
1726
1878
|
try {
|
|
1727
1879
|
accessSync(target, constants.R_OK);
|
|
1728
1880
|
usable = statSync(target).isFile();
|
|
1729
|
-
} catch {
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
}));
|
|
1881
|
+
} catch (error) {
|
|
1882
|
+
if (!isUnusableFileCode(error)) throw error;
|
|
1883
|
+
}
|
|
1884
|
+
if (!usable) throw new Error(fill(messages.ignoreFileMissing, { path: target }));
|
|
1734
1885
|
}
|
|
1735
1886
|
}
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1887
|
+
// lib/sandbox-note.ts
|
|
1888
|
+
/**
|
|
1889
|
+
* 沙箱事实的公共后缀(把 mode/enforcement 一并交代清楚,避免只说「被拒」)。
|
|
1890
|
+
* enforcement 只认非空串:经序列化/反序列化的运行态数据可能交回空串,拼进模板
|
|
1891
|
+
* 会产出「enforcement=」这类残缺后缀——缺席与空白同归「不交代」。
|
|
1892
|
+
*/
|
|
1739
1893
|
function sandboxFacts(info, messages) {
|
|
1740
|
-
const enforcement = info.enforcement === void 0 ? "" : fill(messages.sandboxEnforcement, { value: info.enforcement });
|
|
1894
|
+
const enforcement = info.enforcement === void 0 || info.enforcement.length === 0 ? "" : fill(messages.sandboxEnforcement, { value: info.enforcement });
|
|
1741
1895
|
return fill(messages.sandboxFacts, {
|
|
1742
1896
|
mode: info.mode,
|
|
1743
1897
|
enforcement
|
|
1744
1898
|
});
|
|
1745
1899
|
}
|
|
1900
|
+
/**
|
|
1901
|
+
* 把「事实后缀」填进一条模板的统一入口:本文件与 host.ts 的 runnerFailed 共用,
|
|
1902
|
+
* 新增失败类别时漏掉 `sandboxFacts` 包裹或参数名写错都会在编译期红。
|
|
1903
|
+
*/
|
|
1904
|
+
function noteWithFacts(template, info, messages) {
|
|
1905
|
+
return fill(template, { facts: sandboxFacts(info, messages) });
|
|
1906
|
+
}
|
|
1746
1907
|
/** 沙箱策略拒绝的可读说明(拒绝 ≠ 崩溃:既用于失败消息,也用于成功但残缺的结果)。 */
|
|
1747
1908
|
function deniedNote(info, messages) {
|
|
1748
|
-
return
|
|
1909
|
+
return noteWithFacts(messages.sandboxDenied, info, messages);
|
|
1749
1910
|
}
|
|
1750
1911
|
/**
|
|
1751
1912
|
* 后台进程的沙箱事实提示。runner 失败 / 策略拒绝都不许被显示成「完成」:
|
|
1752
1913
|
* dsh-shell 只在有沙箱的执行器下填 proc.sandbox,读了它才能把「zg 自己失败」
|
|
1753
1914
|
* 与「zg 根本没跑起来」分开。
|
|
1915
|
+
*
|
|
1916
|
+
* 分支次序是刻意的:runnerFailed 优先于 denied——runner 都没起来时 zg 未被执行,
|
|
1917
|
+
* 策略根本没有可拒绝的动作,denied 那一位在那一档不成立;调整次序会无声改变
|
|
1918
|
+
* 同时携带两位时的归因。
|
|
1754
1919
|
*/
|
|
1755
1920
|
function procSandboxNote(proc, messages) {
|
|
1756
1921
|
const info = proc.sandbox;
|
|
1757
1922
|
if (info === void 0) return null;
|
|
1758
|
-
if (info.runnerFailed === true) return
|
|
1923
|
+
if (info.runnerFailed === true) return noteWithFacts(messages.rebuildRunnerFailed, info, messages);
|
|
1759
1924
|
if (info.denied) return fill(messages.rebuildDenied, { denied: deniedNote(info, messages) });
|
|
1760
1925
|
return null;
|
|
1761
1926
|
}
|
|
1762
|
-
|
|
1763
|
-
//#region lib/rebuild-shape.ts
|
|
1927
|
+
// lib/rebuild-shape.ts
|
|
1764
1928
|
/** 宿主服务键 = 客户端线上命名空间(两侧共用的唯一来源)。 */
|
|
1765
1929
|
const REBUILD_REMOTE_NAMESPACE = "zvecGrepRebuild";
|
|
1766
|
-
|
|
1767
|
-
|
|
1930
|
+
// lib/zg-config.ts
|
|
1931
|
+
/** http(s) 且带 host 的基地址才算端点:`http://`、`/` 这类值不是可用的镜像基地址。 */
|
|
1932
|
+
function isUsableBaseUrl(value) {
|
|
1933
|
+
try {
|
|
1934
|
+
const parsed = new URL(value);
|
|
1935
|
+
return (parsed.protocol === "http:" || parsed.protocol === "https:") && parsed.hostname !== "";
|
|
1936
|
+
} catch {
|
|
1937
|
+
return false;
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1768
1940
|
/** 各环境读一个 HF 镜像/代理基地址的优先级:显式入参 > 设置。
|
|
1769
1941
|
* `typeof` 判断是 host 侧兜底:值域正常时 schema 的 `.default()` 已保证是字符串,
|
|
1770
|
-
* 引用被交回 undefined(条目未投影/宿主退化)时宁可不带 env,也不发一个空 HF_ENDPOINT。
|
|
1942
|
+
* 引用被交回 undefined(条目未投影/宿主退化)时宁可不带 env,也不发一个空 HF_ENDPOINT。
|
|
1943
|
+
* 规范化(剥尾斜杠)之后还要再验一次:`/`、`///` 会被剥成空串,`http://` 这类没有
|
|
1944
|
+
* host 的值也不是基地址——发一个空的或畸形的 HF_ENDPOINT 只会把失败推迟到
|
|
1945
|
+
* node-llama-cpp 的下载期,定位成本远高于这里的一次静默省略。 */
|
|
1771
1946
|
function hfEndpointEnv(config) {
|
|
1772
1947
|
const endpoint = config.hfEndpoint.get();
|
|
1773
1948
|
let env;
|
|
1774
|
-
if (typeof endpoint === "string"
|
|
1949
|
+
if (typeof endpoint === "string") {
|
|
1950
|
+
const normalized = endpoint.trim().replace(/\/+$/u, "");
|
|
1951
|
+
if (normalized.length > 0 && isUsableBaseUrl(normalized)) env = { HF_ENDPOINT: normalized };
|
|
1952
|
+
}
|
|
1775
1953
|
return env;
|
|
1776
1954
|
}
|
|
1777
1955
|
/**
|
|
@@ -1793,6 +1971,12 @@ function allowRemoteEmbedding(config) {
|
|
|
1793
1971
|
return config.allowRemoteEmbedding;
|
|
1794
1972
|
}
|
|
1795
1973
|
/**
|
|
1974
|
+
* 远程凭据走的环境变量名形状:常规标识符。名字不受约束等于允许行 config 把宿主进程里
|
|
1975
|
+
* 任意变量(含与 zg 无关的敏感值)转发给子进程;`__proto__` / `constructor` 这类键还会
|
|
1976
|
+
* 让 `process.env[name]` 读到对象而不是字符串。不匹配的名字按「没配」处理。
|
|
1977
|
+
*/
|
|
1978
|
+
const ENV_NAME_SHAPE = /^[A-Za-z_][A-Za-z0-9_]*$/u;
|
|
1979
|
+
/**
|
|
1796
1980
|
* zg 子进程的环境变量:HF 镜像 + (仅在部署开放远程 embedding 时的)远程端点与凭据。
|
|
1797
1981
|
*
|
|
1798
1982
|
* **密钥只走环境变量,绝不进 argv**。两道原因,都是实测/读源码得来的:
|
|
@@ -1815,7 +1999,8 @@ function zgEnv(config) {
|
|
|
1815
1999
|
const endpoint = trimmedConfigString(config.remoteEmbeddingEndpoint);
|
|
1816
2000
|
if (endpoint !== void 0) env["ZVEC_GREP_ENDPOINT"] = endpoint;
|
|
1817
2001
|
const keyName = trimmedConfigString(config.remoteEmbeddingApiKeyFrom);
|
|
1818
|
-
const
|
|
2002
|
+
const key = keyName !== void 0 && ENV_NAME_SHAPE.test(keyName) ? process.env[keyName] : void 0;
|
|
2003
|
+
const secret = typeof key === "string" ? key.trim() : void 0;
|
|
1819
2004
|
if (secret !== void 0 && secret.length > 0) env["ZVEC_GREP_API_KEY"] = secret;
|
|
1820
2005
|
}
|
|
1821
2006
|
return Object.keys(env).length > 0 ? env : void 0;
|
|
@@ -1833,8 +2018,7 @@ function readDefaultEmbedding(config) {
|
|
|
1833
2018
|
function readClientMode(config, messages) {
|
|
1834
2019
|
return clientModeOf(config.clientMode, messages);
|
|
1835
2020
|
}
|
|
1836
|
-
|
|
1837
|
-
//#region lib/rebuild-remote.ts
|
|
2021
|
+
// lib/rebuild-remote.ts
|
|
1838
2022
|
/** 本包作业的 kind(宿主据此发出的 id 形如 `zvec-grep-rebuild-<hex>`)。 */
|
|
1839
2023
|
const REBUILD_JOB_KIND = "zvec-grep-rebuild";
|
|
1840
2024
|
/**
|
|
@@ -2106,11 +2290,11 @@ function rebuildJobSpec(routes, proc, state, command, root) {
|
|
|
2106
2290
|
killProc(proc);
|
|
2107
2291
|
},
|
|
2108
2292
|
done: (async () => {
|
|
2109
|
-
await proc.done;
|
|
2110
|
-
cancelKillTimer();
|
|
2111
2293
|
try {
|
|
2294
|
+
await proc.done;
|
|
2112
2295
|
return jobOutcomeOf(proc);
|
|
2113
2296
|
} finally {
|
|
2297
|
+
cancelKillTimer();
|
|
2114
2298
|
routes.rebuilds.release(root);
|
|
2115
2299
|
}
|
|
2116
2300
|
})()
|
|
@@ -2185,7 +2369,15 @@ function attachIndexWrite(routes, root, started, spawned) {
|
|
|
2185
2369
|
status: 503
|
|
2186
2370
|
};
|
|
2187
2371
|
}
|
|
2188
|
-
|
|
2372
|
+
try {
|
|
2373
|
+
pruneRebuildHistory(starting, records);
|
|
2374
|
+
} catch (error) {
|
|
2375
|
+
killProc(proc);
|
|
2376
|
+
return {
|
|
2377
|
+
error: startupFailureText(error, started),
|
|
2378
|
+
status: 500
|
|
2379
|
+
};
|
|
2380
|
+
}
|
|
2189
2381
|
const state = {
|
|
2190
2382
|
identity: {
|
|
2191
2383
|
kind: REBUILD_JOB_KIND,
|
|
@@ -2224,11 +2416,13 @@ function releaseRebuildRecords(deps) {
|
|
|
2224
2416
|
const unloadReason = messages().jobReasonUnload;
|
|
2225
2417
|
const jobs = jobsOf();
|
|
2226
2418
|
if (jobs === void 0) for (const record of records.values()) killProc(record.proc);
|
|
2227
|
-
else for (const record of records.values()) {
|
|
2419
|
+
else for (const record of records.values()) try {
|
|
2228
2420
|
const view = jobView(jobs, record.id);
|
|
2229
2421
|
if (view === null || !sameJob(record.state, view)) killProc(record.proc);
|
|
2230
2422
|
else if (isLiveStatus(view.status)) jobs.kill(record.id, void 0, unloadReason);
|
|
2231
2423
|
else jobs.remove(record.id);
|
|
2424
|
+
} catch {
|
|
2425
|
+
killProc(record.proc);
|
|
2232
2426
|
}
|
|
2233
2427
|
records.clear();
|
|
2234
2428
|
}
|
|
@@ -2412,8 +2606,7 @@ function installRebuildRemote(ctx, deps) {
|
|
|
2412
2606
|
}, "zvec-grep: rebuild records");
|
|
2413
2607
|
return true;
|
|
2414
2608
|
}
|
|
2415
|
-
|
|
2416
|
-
//#region host.ts
|
|
2609
|
+
// host.ts
|
|
2417
2610
|
const SEARCH_TIMEOUT_MS = 3e5;
|
|
2418
2611
|
const STATUS_TIMEOUT_MS = 6e4;
|
|
2419
2612
|
const INDEX_TIMEOUT_MS = 6e5;
|
|
@@ -2498,7 +2691,7 @@ const TEXT_OUTPUT_SCHEMA = {
|
|
|
2498
2691
|
function sandboxFailure(result, messages) {
|
|
2499
2692
|
const info = result.sandbox;
|
|
2500
2693
|
if (info?.runnerFailed !== true) return null;
|
|
2501
|
-
return
|
|
2694
|
+
return noteWithFacts(messages.runnerFailed, info, messages);
|
|
2502
2695
|
}
|
|
2503
2696
|
/** 错误详情:首尾各留一段(zg/cargo 等错误的最终原因常在尾部)。
|
|
2504
2697
|
* 两半各用一个函数,因为是两种缺陷:头切点会留下孤立**高**代理(`truncateEnd` 丢掉它),
|
|
@@ -2788,7 +2981,9 @@ async function runForegroundOnce(host, command, workdir, timeoutMs, opts) {
|
|
|
2788
2981
|
const resolved = opts.resolveFailure?.(failure, result) ?? null;
|
|
2789
2982
|
if (resolved !== null) return resolved;
|
|
2790
2983
|
const concurrent = classifyConcurrentFailure(result.stderr.text);
|
|
2791
|
-
|
|
2984
|
+
if (concurrent?.kind === "lock-busy" && concurrent.rebuild) throw new RebuildLockBusyError(failure);
|
|
2985
|
+
if (concurrent?.kind === "lock-busy") throw new Error(`${fill(opts.messages.lockBusyOtherOperation, { op: concurrent.ownerOperation ?? "unknown" })}\n${failure}`);
|
|
2986
|
+
throw new Error(failure);
|
|
2792
2987
|
}
|
|
2793
2988
|
const notes = successNotes(result, opts.messages, opts.stdoutMaxBytes);
|
|
2794
2989
|
const { text } = result.stdout;
|
|
@@ -2847,7 +3042,7 @@ function assertRootExists(root, messages) {
|
|
|
2847
3042
|
}
|
|
2848
3043
|
/**
|
|
2849
3044
|
* 默认每组结果数:值域 1-50 由 Config schema(隐式命名空间与行 config 共用)保证,
|
|
2850
|
-
*
|
|
3045
|
+
* 这里只处理「字段缺省」。越界的拒绝在 cli.resolveLimit(命令构造边界),不在此重复。
|
|
2851
3046
|
*/
|
|
2852
3047
|
function readDefaultLimit(config) {
|
|
2853
3048
|
return config.defaultLimit.get() ?? 10;
|
|
@@ -3393,7 +3588,7 @@ async function runSearchTool(runtime, args, exec, messages) {
|
|
|
3393
3588
|
env: zgEnv(config),
|
|
3394
3589
|
stdoutMaxBytes: config.stdoutMaxBytes,
|
|
3395
3590
|
messages,
|
|
3396
|
-
summaryLimit:
|
|
3591
|
+
summaryLimit: resolveLimit(searchArgs.limit, messages),
|
|
3397
3592
|
rebuildWait: {
|
|
3398
3593
|
root: resolvedRoot,
|
|
3399
3594
|
rebuilds: runtime.rebuilds,
|
|
@@ -3782,5 +3977,4 @@ var host_default = {
|
|
|
3782
3977
|
Config: configSchema,
|
|
3783
3978
|
apply
|
|
3784
3979
|
};
|
|
3785
|
-
//#endregion
|
|
3786
3980
|
export { configSchema as Config, INDEX_PROBE_CACHE_MAX, INDEX_PROBE_TTL_MS, createIndexProbeCache, createRootLedger, createUnlockLedger, host_default as default, hitSummary, signalStderr };
|