@jayyuen66/dsh-zvec-grep 0.1.22 → 0.1.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/host.js +14 -14
- package/package.json +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,20 @@
|
|
|
2
2
|
|
|
3
3
|
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). The deviations below are deliberate: version headings carry no release date (publish times are recorded by the registry — `npm view <package> time`), and a release may add sections beyond the standard six, such as `Not changed, deliberately` and `Earlier`.
|
|
4
4
|
|
|
5
|
+
## 0.1.23
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
|
|
9
|
+
- **守护进程就绪探测改为 HTTP initialize 握手**:对 `daemonUrl` POST 一次 MCP `initialize`,`200 + mcp-session-id` 才算就绪;401、非 200、网络错与 10s 超时一律未就绪。旧判据 `zg --server status --check-ready` 依赖宿主 PID 可见性,DSH 沙箱(bwrap `--unshare-pid`)里活着的 daemon 会被误判为未就绪,mcp 档反复拉起撞端口、auto 档被拖去 CLI 冷加载;HTTP 探测不经 shell,PID namespace 隔离下仍能探到宿主 daemon。`zg_status` 的 `--check-ready` 诊断透传保持不变。
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- **会话沙箱策略的三条真实宿主集成用例**:官方 `SandboxPolicyService` 在场时 `zg --status` 请求带 `workspaceRoot = 会话 cwd`;服务缺席时不带字段且命令照常执行;`zg --server on` 拉起 daemon 时刻意不带会话策略(Landlock 进程不可逆,单例 daemon 不能被某个会话的边界圈住)。设置卡重建路径另补一条「不带策略」的负断言。`devDependencies` 增 `@deepseek-ai/dsh-sandbox-policy@0.2.3-alpha.3`(仅测试用)。
|
|
14
|
+
|
|
15
|
+
### Changed
|
|
16
|
+
|
|
17
|
+
- **`shell-facts` 的索引检索判据从 `zg --rg` 改为 `zg --hybrid`**:`--rg` 是穷举/文件发现通道,不会出现在索引通道的检索里;旧写法在缺席分支永远 undefined、就绪分支从未跑到过,是潜伏的错判据。
|
|
18
|
+
|
|
5
19
|
## 0.1.22
|
|
6
20
|
|
|
7
21
|
Moved to the shared 0.3.1 runtime entry points (`./tool` / `./client`) and rebuilt the host through `toolImportTransform` (the client still externalises `/client`). Path validation/normalisation (`assertAbsoluteRoot`, `normalizeAbsolutePath`), `shq` and `versionAtLeast` now come from shared; `lib/cli.ts` keeps only the message-table adapters, and the win32 path regressions move to a dedicated test. Remote readers use shared `parseOrThrow` / `remoteMounterOf`; the settings card uses `useCardDraft`. `@deepseek-ai/dsh-fs-patch` and `@rolldown/plugin-transform-imports` were added to devDependencies (peer window kept in step). The root-session key now follows `parentSession` only when `origin` is `subagent`; side sessions and ordinary forks keep their own quota. The zg 0.3.x contract and the tool surface are unchanged.
|
package/README.md
CHANGED
|
@@ -207,7 +207,7 @@ Off by default: `allowRemoteEmbedding=false`, `remoteEmbeddingEndpoint=""`, `rem
|
|
|
207
207
|
- Direct and server are **two capability surfaces**, not a speed knob: direct cold-loads the embedding model on every query; watcher-driven incremental refresh, `refresh=background` and a resident model pool exist only in server mode. Upstream probes readiness for `auto` but never starts a daemon.
|
|
208
208
|
- Whether this package starts one follows `transport`: `auto` / `cli` never do; `mcp` starts a daemon with a random token (`zg --server on`, on `daemonUrl`'s host:port; default loopback 7999) and feeds that same token to every CLI child via env and to MCP calls as the Bearer. On unload it stops the daemon **it started** with that token. A user-started daemon (no token by default) is only probed for readiness, never stopped. The token is persisted at `<ZVEC_GREP_HOME or ~/.zvec-grep>/dsh-zvec-grep.token` (0600): a crash/restart or another host reads it back, and concurrent cold starts converge on one token through an O_EXCL claim instead of overwriting each other.
|
|
209
209
|
- **Several agents can search at the same time.** A host coalesces its own cold start into one `zg --server on`; multiple hosts sharing `ZVEC_GREP_HOME` share the singleton daemon (upstream `instance.lock`; a duplicate start exits 0 with the same PID). Each concurrent tool call uses its own MCP session - one zg session handles one `tools/call` at a time - and idle sessions are reused, so agents do not queue behind each other. Only an index rebuild holds the workspace write lock; searches wait for it up to `rebuildWaitMs` (that is the one bounded wait, not startup). Different `ZVEC_GREP_HOME` values mean different daemons, so give each one its own `daemonUrl` port.
|
|
210
|
-
- Readiness is **explicit**: the
|
|
210
|
+
- Readiness is **explicit**: the result of one MCP initialize handshake against `daemonUrl` (plain HTTP POST, Bearer when the in-memory token exists; HTTP 200 + `mcp-session-id` = ready) is cached for 60 s. A network error, timeout or non-200 (401 included - a token mismatch is not ready) counts as "not ready", never an infrastructure error; it gates `refresh=background`, and is echoed once in `zg_status` output and once on the card. The probe is issued by the `roots()` read, `zg_status`, and `backgroundSupportFor`, and never goes through the shell sandbox, so a host-side daemon stays visible even under PID-namespace isolation.
|
|
211
211
|
- The card's `serverReady` is `true` / `false` at the card layer — a failed or erroring probe counts as `false` ("probe failure means not ready"), so the readiness line always renders. `undefined` only survives inside the raw `roots()` payload of an older card snapshot; the live card folds it to `false`. To run a shared daemon manually, use `zg --server on` in a terminal.
|
|
212
212
|
|
|
213
213
|
## <img src="https://api.iconify.design/lucide/network.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> Public interface
|
package/README.zh-CN.md
CHANGED
|
@@ -207,7 +207,7 @@ bundle 顺序也会决定这件事:alpha.3 起,多个 bundle 插入同名 `d
|
|
|
207
207
|
- direct 与 server 是**两种能力**,不是快慢之分:direct 每次查询都冷加载 embedding 模型;增量刷新(watcher)、`refresh=background` 与常驻模型池只在 server 模式下存在。上游对 `auto` 只做就绪探测、不拉起 daemon。
|
|
208
208
|
- 本包的拉起策略跟 `transport` 走:`auto` / `cli` 不拉;`mcp` 档会自启一个带随机 token 的 daemon(`zg --server on`,监听 `daemonUrl` 的 host:port,默认回环 7999),同一枚 token 经 env 喂给所有 CLI 子进程、经 Bearer 喂给 MCP 调用;卸载时用同一枚 token 执行 `zg --server off` 停掉**自己拉起**的那一个。用户自启的 daemon(默认无鉴权)本包只读就绪态,不会停它。token 持久化在 `<ZVEC_GREP_HOME 或 ~/.zvec-grep>/dsh-zvec-grep.token`(0600):崩溃/重启或另一宿主能读回同一枚,并发冷启动经 O_EXCL 认领收敛到一枚,不会互相覆盖。
|
|
209
209
|
- **多个 agent 可以同时检索。** 同一宿主内的冷启动合并成一发 `zg --server on`;共用 `ZVEC_GREP_HOME` 的多个宿主共用同一个 daemon(上游 `instance.lock`,重复启动退 0 并回同一个 PID)。每个并发工具调用各用一条 MCP 会话——同一条 zg 会话一次只处理一个 `tools/call`——空闲会话复用,agent 之间不排队。只有索引重建会占工作区写锁;检索最多等它 `rebuildWaitMs`(这是唯一的有界等待,不是启动等待)。不同 `ZVEC_GREP_HOME` 是不同 daemon,需各自配 `daemonUrl` 端口。
|
|
210
|
-
- 就绪态按 60 秒 TTL
|
|
210
|
+
- 就绪态按 60 秒 TTL 缓存一次对 `daemonUrl` 的 MCP initialize 握手(裸 HTTP POST,内存里有 token 时带 Bearer;HTTP 200 + `mcp-session-id` = 就绪)的结果。网络错、超时或非 200(含 401——token 不匹配不算就绪)一律按未就绪统一处理,绝不外抛基础设施故障;据此统一处理 `refresh=background`,并在 `zg_status` 输出尾与卡片各回显一行。探测由 `roots()` 读取接口、`zg_status` 与 `backgroundSupportFor` 发出,且不经 shell 沙箱——PID-namespace 隔离下宿主 daemon 仍照常探到。
|
|
211
211
|
- 卡片的 `serverReady` 在卡片层只可能是 `true` / `false`——探测失败按未就绪统一处理,就绪行恒渲染。`undefined` 只会出现在旧快照的 `roots()` 原始载荷里(那一次探测压根没跑),实时卡片把它折成 `false`。想手动起一个共享 daemon 就在终端里跑 `zg --server on`。
|
|
212
212
|
|
|
213
213
|
## <img src="https://api.iconify.design/lucide/network.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> 对外接口
|
package/host.js
CHANGED
|
@@ -59,17 +59,17 @@ The full rules (quota arithmetic, rebuild flow, embedding choice, how to read re
|
|
|
59
59
|
[zvec-grep] rebuild failed: the sandbox runner did not start{facts} (zg was never executed).`,rebuildDenied:`
|
|
60
60
|
[zvec-grep] during the rebuild {denied} — the index may be incomplete; check this session's file policy (read-only cannot write .zvec-grep/).`,rebuildTimeout:`
|
|
61
61
|
[zvec-grep] rebuild killed after exceeding {minutes} minutes`,jobReasonTimeout:`rebuild reclaimed by zvec-grep after {minutes} minutes`,jobReasonUnload:`zvec-grep plugin unloaded`,endpointRootInvalid:`invalid root: {reason}`,endpointRootUntracked:`root is not in the workspace whitelist this daemon observed: {root} (pick one of the card's candidates)`,endpointRootGone:`root directory no longer exists: {root}`,endpointStartFailed:`failed to start the rebuild: {reason}`,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`,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`,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)`,jobOutputView:`
|
|
62
|
-
[zvec-grep] (showing only the last {shown} of {total} characters)`,textTooLong:`{name} exceeds the {maxChars} character limit (actual {actual})`,mustBeString:`{name} must be a string (received {received})`,noNulBytes:`{name} must not contain NUL bytes`,mustBeBoolean:`{name} must be a boolean (received {received})`,clientModeInvalid:`invalid zg client mode: {received} (allowed: {allowed})`,previewInvalid:`invalid preview mode: {received} (allowed: {allowed})`,refreshInvalid:`invalid refresh policy: {received} (allowed: {allowed})`,refreshBackgroundNeedsServer:'{root} has no available zvec-grep daemon, so `refresh=background` was refused — it only holds in server mode. Without a daemon the CLI prints one stderr warning and silently turns refreshing **off**, which this plugin will not report as "refreshing in the background". Either keep the default refresh=wait (synchronous refresh before the search, works in direct mode) or run `zg --server on` in a terminal first — the daemon also brings incremental indexing and a resident embedding model pool.',refreshBackgroundPinnedDirect:"{root}: `refresh=background` was refused because this daemon's transport mode is pinned to direct by the deployment (the row config's `clientMode: direct`), while background refreshing only exists in server mode. Starting a daemon would not help here — either set clientMode back to auto/server in the row config, or search with the default refresh=wait.",serverReadyNote:`[zvec-grep] daemon: ready (searches can use server mode: incremental index refresh, resident embedding model pool)`,serverUnavailableNote:"[zvec-grep] daemon: not ready. Searches therefore run in direct mode and cold-load the embedding model every call (slower on large workspaces, and refresh=background is unavailable); run `zg --server on` in a terminal for incremental indexing and a resident model pool",symbolTypeInvalid:`invalid symbol type: {received} (allowed: {allowed}; lowercase only)`,rootEscapesFs:`root contains a .. segment that escapes the filesystem root: {path}`,rootMustBeString:`root must be a string (received {received})`,rootRequired:`root is required and must be an absolute workspace path`,rootMustBeAbsolute:`root must be an absolute path (starting with /): {path}`,rootIsFsRoot:`root must not be the filesystem root /`,rootRequiredWithFallback:`root is required and must be an absolute workspace path (it may be omitted: defaults to the current session workspace)`,limitInvalid:`limit must be a non-negative integer (omit it to use the default)`,limitOutOfRange:`limit is out of the allowed range {min}–{max} (omit it to use the default)`,mustBeStringOrArray:`must be a string or an array of strings`,mustBeStringArray:`{name} must be an array of strings`,tooManyItems:`{name} allows at most {maxItems} items (actual {actual})`,nonStringItem:`{name} contains a non-string item ({received})`,commandTooLong:`the zg command is {length} bytes, over the {maxBytes} byte limit — narrow the search`,tooManyQueryRoutes:`{count} query routes in total, over the limit of {max}`,searchNeedsQuery:`zg_search needs at least one of query/queries/fts/vector`,exhaustiveNeedsPattern:`exhaustive search (rg=true) needs a query to use as the pattern`,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`,filesConflicts:`file discovery (files=true) conflicts with these parameters: {names}. It only lists files and never searches content — query would be read as a path, limit is meaningless (upstream refuses it outright), and device plays no part in file discovery; drop them and resend`,embeddingNotAllowed:`embedding reference {reference} is not in the catalog. Local choices: {choices}; the remote qwen models require allowRemoteEmbedding turned on in the deployment config (and a one-time user authorization, zg --auth grant <root> --capability embedding --scope workspace). References with unknown prefixes are refused under every switch — a remote endpoint sends workspace content off the machine, and that decision belongs to the user.`,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.`,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.`,ignoreFileMissing:`{path} is not an existing file the current process can read (missing, a directory, or present-but-unreadable all count). zg 0.3.0 silently tolerates an unreadable ignore file — indexing succeeds, but that exclusion rule quietly does nothing (you believe it is filtering files while nothing is excluded), so this plugin refuses the bad path before the command is built. Give a path that really exists and that the current user can read.`,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.`,rgDescription:`Exhaustive lexical search (zg --rg): needs no index, matches literal text line by line. Leave it unset to fall back to it automatically when the workspace has no index, and to use the index when one exists. An explicit false demands indexed search only (an error when there is no index). It does not support preview / refresh / fuse / symbolTypes / preferSymbol / fts / vector / queries / category, and it grants no grep/rg quota`,intWithReceived:`{name} must be an integer >= {min} (received {received})`,intRequired:`{name} must be an integer >= {min}`,guardRootRejected:`the root given to {name} is not accepted: {reason}`,guardIndexConfirmRequired:`zg_index creates/rebuilds/deletes a persistent index and requires an explicit user request with confirm true`,guardAbsoluteRootRequired:`{name} needs an absolute root path (it may be omitted: defaults to the current session workspace)`,gateNeverSearched:`no zg_search has run yet`,gateQuotaExhausted:`the grep/rg quota is spent`,gateUnlockExpired:`the unlock from the last zg_search has expired`,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.`}};function b(e,t){return f(e,t)}const x=4e3,S=1024;function we(e,t=`posix`){return p(e,t)}function Te(e,t,n,r){if(e.length>r)throw TypeError(b(n.textTooLong,{name:t,maxChars:r,actual:e.length}));return e}function C(e,t,n,r){if(e==null)return``;if(typeof e!=`string`)throw TypeError(b(n.mustBeString,{name:t,received:typeof e}));if(e.includes(`\0`))throw Error(b(n.noNulBytes,{name:t}));return Te(e.trim(),t,n,r)}function w(e,t,n,r=128,i=S){if(e==null)return[];if(!Array.isArray(e))throw TypeError(b(n.mustBeStringArray,{name:t}));let a=[];for(let r of e){if(typeof r!=`string`)throw TypeError(b(n.nonStringItem,{name:t,received:typeof r}));if(r.includes(`\0`))throw Error(b(n.noNulBytes,{name:t}));let e=Te(r.trim(),t,n,i);e.length>0&&a.push(e)}if(a.length>r)throw TypeError(b(n.tooManyItems,{name:t,maxItems:r,actual:a.length}));return a}function T(e,t,n,r=128,i=S){if(e!=null&&typeof e!=`string`&&!Array.isArray(e))throw TypeError(b(n.mustBeStringOrArray,{name:t}));return w(typeof e==`string`?[e]:e,t,n,r,i)}const Ee=[`!*.pem`,`!*.key`,`!*.p12`,`!*.pfx`,`!*.keystore`,`!*.jks`,`!*.ppk`,`!id_rsa*`,`!id_ed25519*`],De=Object.keys({auto:`auto`,direct:`direct`,server:`server`}),E=`auto`;function Oe(e){return De.includes(e)}function ke(e,t){if(e==null)return E;if(typeof e!=`string`||!Oe(e))throw TypeError(b(t.clientModeInvalid,{received:typeof e==`string`?e:typeof e,allowed:De.join(` | `)}));return e}function D(e){return`--mode ${e}`}const Ae=Object.keys({none:`none`,short:`short`,full:`full`,detail:`detail`});function je(e){return Ae.includes(e)}function Me(e,t){if(e==null)return`short`;if(typeof e!=`string`||!je(e))throw TypeError(b(t.previewInvalid,{received:typeof e==`string`?e:typeof e,allowed:Ae.join(` | `)}));return e}const Ne=Object.keys({background:`background`,wait:`wait`,off:`off`});function Pe(e){return Ne.includes(e)}function Fe(e,t){if(e==null)return`wait`;if(typeof e!=`string`||!Pe(e))throw TypeError(b(t.refreshInvalid,{received:typeof e==`string`?e:typeof e,allowed:Ne.join(` | `)}));return e}function Ie(e){return e===`background`}const O=Object.keys({alias:`alias`,class:`class`,enum:`enum`,function:`function`,interface:`interface`,module:`module`,value:`value`});function Le(e){return O.includes(e)}function Re(e,t){let n=[];for(let r of w(e,`symbolTypes`,t,O.length)){if(!Le(r))throw TypeError(b(t.symbolTypeInvalid,{received:r,allowed:O.join(` | `)}));n.push(r)}return n}function k(e){return t=>we(t,e)}function ze(e,t,n){let r=C(e,`device`,t,S);return`--device ${n(r.length>0?r:`auto`)}`}function A(e,t,n,r=!1){if(e==null)return r;if(typeof e!=`boolean`)throw TypeError(b(n.mustBeBoolean,{name:t,received:typeof e}));return e}function Be(e,t,n=`posix`){return d(e,n,{mustBeAbsolute:e=>b(t.rootMustBeAbsolute,{path:e}),escapesRoot:e=>b(t.rootEscapesFs,{path:e})})}function j(e,t,n=`posix`){return u(e,n,{mustBeAbsolute:e=>b(t.rootMustBeAbsolute,{path:e}),escapesRoot:e=>b(t.rootEscapesFs,{path:e}),typeError:e=>b(t.rootMustBeString,{received:e}),required:t.rootRequired,nul:b(t.noNulBytes,{name:`root`}),filesystemRoot:()=>t.rootIsFsRoot})}function Ve(e,t,n,r=`posix`){if(e!=null&&typeof e!=`string`)throw TypeError(b(n.rootMustBeString,{received:typeof e}));if(typeof e==`string`&&e.trim().length>0)return j(e.trim(),n,r);if(typeof t==`string`&&t.trim().length>0)return j(t.trim(),n,r);throw Error(n.rootRequiredWithFallback)}function M(e,t,n=10){if(e==null)return n;if(typeof e!=`number`)throw TypeError(t.limitInvalid);if(!Number.isSafeInteger(e)||e<0)throw Error(t.limitInvalid);if(e<1||e>50)throw Error(b(t.limitOutOfRange,{min:1,max:50}));return e}function N(e,t,n){return w(e,t,n,32,x)}function P(e,t,n,r=`posix`){let i=e.join(` `),a=Buffer.byteLength(i,`utf8`),o=r===`win32`?24e3:64e3;if(a>o)throw Error(b(n.commandTooLong,{length:a,maxBytes:o}));return{command:i,workdir:t}}function He(e,t,n,r){let i=0,a=C(t.query,`query`,n,x);a.length>0&&(e.push(`--hybrid=${r(a)}`),i+=1);for(let a of N(t.queries,`queries`,n))e.push(`--hybrid=${r(a)}`),i+=1;for(let a of N(t.fts,`fts`,n))e.push(`--fts=${r(a)}`),i+=1;for(let a of N(t.vector,`vector`,n))e.push(`--vector=${r(a)}`),i+=1;if(i>32)throw Error(b(n.tooManyQueryRoutes,{count:i,max:32}));return i}function Ue(e,t,n,r){for(let i of T(t.globs,`globs`,n))e.push(`--glob`,r(i));for(let i of T(t.insensitiveGlobs,`insensitiveGlobs`,n))e.push(`--iglob`,r(i));for(let i of T(t.fileTypes,`fileTypes`,n))e.push(`--type`,r(i));for(let i of T(t.excludedFileTypes,`excludedFileTypes`,n))e.push(`--type-not`,r(i))}function We(e,t,n,r){let i=C(t.modifiedAfter,`modifiedAfter`,n,128);i.length>0&&e.push(`--modified-after`,r(i));let a=C(t.modifiedBefore,`modifiedBefore`,n,128);a.length>0&&e.push(`--modified-before`,r(a))}function Ge(e,t,n,r){Ue(e,t,n,r);for(let i of Re(t.symbolTypes,n))e.push(`--symbol-type`,r(i))}function Ke(e,t){return C(e.query,`query`,t,x)}function qe(e,t,n,r){for(let i of T(t.category,`category`,n))e.push(`--category`,r(i));for(let i of T(t.categoryNot,`categoryNot`,n))e.push(`--category-not`,r(i))}function Je(e,t,n,r,i){let a=[`zg`],o=k(e.platform??`posix`);if(He(a,e,n,o)===0)throw Error(n.searchNeedsQuery);A(e.fuse,`fuse`,n)&&a.push(`--fuse`);let s=Fe(e.refresh,n);if(s===`background`&&r===`direct`)throw Error(b(n.refreshBackgroundPinnedDirect,{root:t}));if(s===`background`&&i===`daemon-down`)throw Error(b(n.refreshBackgroundNeedsServer,{root:t}));return a.push(`--limit`,String(M(e.limit,n)),`--preview`,Me(e.preview,n),`--refresh`,s),Ge(a,e,n,o),qe(a,e,n,o),A(e.preferSymbol,`preferSymbol`,n)&&a.push(`--prefer-symbol`),A(e.trace,`trace`,n)&&a.push(`--trace`),We(a,e,n,o),a.push(ze(e.device,n,o),D(r)),P(a,t,n,e.platform??`posix`)}function Ye(e,t){let n=[];if(A(e.fuse,`fuse`,t)&&n.push(`fuse`),N(e.queries,`queries`,t).length>0&&n.push(`queries`),N(e.fts,`fts`,t).length>0&&n.push(`fts`),N(e.vector,`vector`,t).length>0&&n.push(`vector`),T(e.category,`category`,t).length>0&&n.push(`category`),T(e.categoryNot,`categoryNot`,t).length>0&&n.push(`categoryNot`),C(e.preview,`preview`,t,1024).length>0&&n.push(`preview`),C(e.refresh,`refresh`,t,1024).length>0&&n.push(`refresh`),w(e.symbolTypes,`symbolTypes`,t).length>0&&n.push(`symbolTypes`),A(e.preferSymbol,`preferSymbol`,t)&&n.push(`preferSymbol`),A(e.trace,`trace`,t)&&n.push(`trace`),n.length>0)throw Error(b(t.exhaustiveConflicts,{names:n.join(` | `)}))}function Xe(e,t){Ye(e,t);let n=[];if(Ke(e,t).length>0&&n.push(`query`),e.limit!==void 0&&e.limit!==null&&n.push(`limit`),C(e.device,`device`,t,1024).length>0&&n.push(`device`),n.length>0)throw Error(b(t.filesConflicts,{names:n.join(` | `)}))}function Ze(e,t,n,r){Ye(e,n);let i=k(e.platform??`posix`),a=[`zg`,`--rg`],o=C(e.query,`query`,n,x);if(o.length===0)throw Error(n.exhaustiveNeedsPattern);return o.startsWith(`-`)?a.push(`-e`,i(o)):a.push(i(o)),a.push(`--limit`,String(M(e.limit,n))),Ue(a,e,n,i),We(a,e,n,i),a.push(ze(e.device,n,i),D(r)),P(a,t,n,e.platform??`posix`)}function Qe(e,t,n,r){Xe(e,n);let i=k(e.platform??`posix`),a=[`zg`,`--rg`,`--files`];return Ue(a,e,n,i),We(a,e,n,i),a.push(D(r)),P(a,t,n,e.platform??`posix`)}function $e(e,t,n=E,r=`indexed`,i=`daemon-down`){let a=e.platform??`posix`,o=j(e.root,t,a);return r===`files`?Qe(e,o,t,n):r===`exhaustive`?Ze(e,o,t,n):Je(e,o,t,n,i)}function et(e,t,n,r){if(typeof e!=`number`)throw TypeError(b(n.intWithReceived,{name:t,min:r,received:typeof e}));if(!Number.isSafeInteger(e)||e<r)throw Error(b(n.intRequired,{name:t,min:r}));return String(e)}function tt(e,t){return{rebuild:A(e.rebuild,`rebuild`,t),hidden:A(e.hidden,`hidden`,t),noIgnore:A(e.noIgnore,`noIgnore`,t),nestedGit:A(e.nestedGit,`nestedGit`,t),follow:A(e.follow,`follow`,t),excludeSecrets:A(e.excludeSecrets,`excludeSecrets`,t,!0)}}function nt(e,t){t.rebuild&&e.push(`--rebuild`)}function rt(e,t,n,r,i){for(let n of T(t.globs,`globs`,r))e.push(`--glob`,i(n));for(let n of T(t.insensitiveGlobs,`insensitiveGlobs`,r))e.push(`--iglob`,i(n));for(let n of T(t.fileTypes,`fileTypes`,r))e.push(`--type`,i(n));for(let n of T(t.excludedFileTypes,`excludedFileTypes`,r))e.push(`--type-not`,i(n));if(n.excludeSecrets)for(let t of Ee)e.push(`--iglob`,i(t));for(let n of T(t.ignoreFiles,`ignoreFiles`,r))e.push(`--ignore-file`,i(n))}function it(e,t,n){t.maxDepth!==void 0&&t.maxDepth!==null&&e.push(`--max-depth`,et(t.maxDepth,`maxDepth`,n,0)),t.maxFileSizeBytes!==void 0&&t.maxFileSizeBytes!==null&&e.push(`--max-filesize`,et(t.maxFileSizeBytes,`maxFileSizeBytes`,n,0))}function at(e,t){t.hidden&&e.push(`--hidden`),t.noIgnore&&e.push(`--no-ignore`),t.nestedGit&&e.push(`--nested-git`)}function ot(e,t){t.follow&&e.push(`--follow`)}function st(e,t,n){t.embeddingConcurrency!==void 0&&t.embeddingConcurrency!==null&&e.push(`--embedding-concurrency`,et(t.embeddingConcurrency,`embeddingConcurrency`,n,1))}function ct(e,t,n){A(t.resetPaths,`resetPaths`,n)&&e.push(`--reset-paths`)}function lt(e,t,n,r){let i=C(e.embedding,`embedding`,n,S),a=i.length>0?i:t;if(_e(a))return{reference:a,remote:!1};if(ye(a)){if(r)return{reference:a,remote:!0};throw Error(b(n.embeddingNotAllowed,{reference:a,choices:ge.map(e=>e.reference).join(` | `)}))}throw Error(b(n.embeddingNotAllowed,{reference:a,choices:[...ge,...ve].map(e=>e.reference).join(` | `)}))}const ut=[`rebuild`,`embedding`,`globs`,`insensitiveGlobs`,`fileTypes`,`excludedFileTypes`,`ignoreFiles`,`hidden`,`noIgnore`,`nestedGit`,`excludeSecrets`,`maxDepth`,`maxFileSizeBytes`,`follow`,`embeddingConcurrency`,`device`];function dt(e,t,n,r=E,i=!1){let a=e.platform??`posix`,o=j(e.root,n,a),s=k(a),c=[`zg`,`--index`,s(o)],l=tt(e,n);if(A(e.drop,`drop`,n)){if(A(e.resetPaths,`resetPaths`,n))throw Error(n.dropWithResetPaths);let t=ut.filter(t=>e[t]!==void 0&&e[t]!==null);if(t.length>0)throw Error(b(n.dropWithIndexArgs,{names:t.join(` | `)}));return c.push(`--drop`,D(r)),P(c,o,n,e.platform??`posix`)}let{reference:u,remote:d}=lt(e,t,n,i);return c.push(`--embedding`,s(u)),d&&c.push(`--allow-remote`),nt(c,l),rt(c,e,l,n,s),at(c,l),it(c,e,n),ot(c,l),st(c,e,n),ct(c,e,n),c.push(ze(e.device,n,s),D(r)),P(c,o,n,e.platform??`posix`)}function ft(e,t,n=E){let r=e.platform??`posix`,i=j(e.root,t,r),a=[`zg`,`--status`,we(i,r)];return A(e.checkReady,`checkReady`,t)&&a.push(`--check-ready`),a.push(D(n)),P(a,i,t,e.platform??`posix`)}function pt(e=process.platform){return e===`win32`?`win32`:`posix`}const F=String.fromCodePoint(92);function mt(e){let t=e.length;for(;t>0&&e.codePointAt(t-1)===47;)--t;return t===e.length?e:e.slice(0,t)}function ht(e){let t=e.length;for(;t>0;){let n=e.codePointAt(t-1);if(n!==47&&n!==92)break;--t}return t===e.length?e:e.slice(0,t)}const gt=new Set([`grep`,`egrep`,`fgrep`,`rg`]),_t=new Set([`--help`,`--version`,`-V`]),vt=new Set([`sh`,`bash`,`zsh`,`dash`,`ksh`,`csh`,`fish`,`pwsh`,`powershell`]),yt=/^-[^c]*c$/u,bt=new Set([`-c`,`-command`]),xt=/^[A-Za-z]:[\\/]/u,St=/^[\\/]+/u,Ct=new Set([`|`,`;`,`&`,`
|
|
63
|
-
`,`\r`]),
|
|
64
|
-
`,`\r`,"`"]),
|
|
65
|
-
`,t);return n===-1?e.length:n-1}function Lt(e,t,n,r){r.atCommand=!0;let i=e.slice(t+1,t+2)===`|`||e.slice(t-1,t)===`|`;r.pipedNext=n===`|`&&!i}function Rt(e,t){t.buffer.length>0?t.buffer+=e:(e===`(`||e===`{`)&&(t.atCommand=!0)}function zt(e,t){return e===`(`&&t.quote===``&&t.buffer===`$`}function Bt(e,t){return t.quote===``&&e===`#`&&t.buffer.length===0}function Vt(e,t){return t===e?``:e}function Ht(e,t){return e&&(t.startsWith(`-`)||kt.test(t)||Ot.test(t))}function Ut(e,t){return t===`win32`?xt.test(e)||e.startsWith(F+F)||e.startsWith(F)||e.startsWith(`/`)||e.includes(F)||e.includes(`/`)||e===`.`||e===`..`:e.startsWith(`/`)||e.includes(`/`)||e===`.`||e===`..`}function I(e,t){if(t===`win32`){let t=e.replaceAll(`\\`,`/`);return t.slice(t.lastIndexOf(`/`)+1).toLowerCase().replace(wt,``)}return e.slice(e.lastIndexOf(`/`)+1).toLowerCase()}function Wt(e,t,n){let{text:r}=e,i=t.pendingValue,a={...t,pendingValue:!1};i?a.afterPrefix=!0:e.atCommand&&(a.wrapper=``,a.afterPrefix=!1);let o=e.atCommand||a.afterPrefix||a.wrapper!==``,s=o&&Et.get(a.wrapper)?.has(r)===!0;return i&&!e.atCommand?{state:a,command:!1}:s?(a.pendingValue=!0,{state:a,command:!1}):Ht(o,r)?(a.afterPrefix=!0,{state:a,command:!1}):(o&&(a.wrapper=Tt.has(I(r,n))?I(r,n):``),a.afterPrefix=!1,{state:a,command:o})}function L(e,t){t.buffer.length!==0&&(e.push({text:t.buffer,atCommand:t.atCommand,piped:t.pipedNext,redirect:t.redirectNext}),t.buffer=``,t.atCommand=!1,t.pipedNext=!1,t.redirectNext=!1)}function Gt(e,t,n){let r=e.slice(t,t+1);return e.slice(t+1,t+2)===r?(n.buffer+=r,t+1):(n.quote=``,t)}function Kt(e,t,n,r,i){let a=e.slice(t,t+1),o=i===`win32`?Ct:jt;if(n.escaped)n.buffer+=a,n.escaped=!1;else if(Ft(a,n.quote,i))n.buffer+=a;else if(Bt(a,n))return It(e,t);else if(a===(i===`win32`?"`":`\\`))n.escaped=!0;else if(i===`win32`&&n.quote!==``&&a===n.quote)return Gt(e,t,n);else Pt.has(a)?n.quote=Vt(a,n.quote):o.has(a)?(L(r,n),Lt(e,t,a,n)):zt(a,n)?(n.buffer=``,L(r,n),Lt(e,t,a,n)):Nt.has(a)?Rt(a,n):Mt.has(a)?(L(r,n),n.redirectNext=!0):At.has(a)?L(r,n):n.buffer+=a;return t}function qt(e,t){let n=[],r={buffer:``,atCommand:!0,pipedNext:!1,redirectNext:!1,quote:``,escaped:!1},i=0;for(;i<e.length;)i=Kt(e,i,r,n,t)+1;return L(n,r),n}function Jt(e,t){let n=[],r={wrapper:``,pendingValue:!1,afterPrefix:!1};for(let[i,a]of e.entries()){let e=Wt(a,r,t);r=e.state,e.command&&n.push(i)}return n}function Yt(e,t){let n=[];for(let[r,i]of e.entries()){let a=e[r+1],o=e[r+2],s=t===`win32`?a!==void 0&&bt.has(a.text.toLowerCase()):a!==void 0&&yt.test(a.text);i.atCommand&&vt.has(I(i.text,t))&&a!==void 0&&o!==void 0&&s&&!o.atCommand&&n.push(o.text)}return n}function Xt(e,t,n){for(let r of e.slice(t+1)){if(r.atCommand)break;if(!r.redirect&&!r.text.startsWith(`-`)&&Ut(r.text,n))return!0}return!1}function Zt(e,t=0,n=`posix`){let r=qt(e,n);return r.some(e=>_t.has(e.text))?!1:Jt(r,n).some(e=>{let t=r[e];return t===void 0||!gt.has(I(t.text,n))?!1:!(t.piped&&!Xt(r,e,n))})?!0:t>=2?!1:Yt(r,n).some(e=>Zt(e,t+1,n))}function R(e,t=`posix`){if(t===`win32`){let t=e.replaceAll(`/`,`\\`),n=l.win32.parse(t).root;if(t===n)return n;let r=ht(t);return r.length>0?r:n}let n=mt(e);return n.length>0?n:`/`}function Qt(e){let t=e.replaceAll(`/`,`\\`);return xt.test(t)||t.startsWith(F+F)}const $t=/^\.\.(?:[\\/]|$)/u;function en(e,t){if(Qt(e))return e;if(e.startsWith(F)||e.startsWith(`/`)){let{root:n}=l.win32.parse(t);return`${n}${e.replace(St,``)}`}return`${t}\\${e}`}function z(e,t,n,r=`posix`){if(e===void 0||e.trim().length===0)return!0;let i=R(t,r),a=e.trim();if(r===`win32`){let e;try{e=Be(en(a,i),n,`win32`)}catch{return!1}let t=l.win32.relative(i,e);return t===``||!$t.test(t)&&!l.win32.isAbsolute(t)}let o=a.startsWith(`/`)?a:`${i}/${a}`,s;try{s=Be(o,n)}catch{return!1}let c=i.endsWith(`/`)?i:`${i}/`;return s===i||s.startsWith(c)}function tn(e,t,n,r=`posix`){let i=R(e,r),a=qt(t,r),o=new Set(Jt(a,r)),s=!1;for(let[e,t]of a.entries()){let{text:a}=t,c=s;if(s=!1,!(o.has(e)||c||t.redirect)){if(a.startsWith(`-`))s=Dt.has(a);else if(Ut(a,r)&&!z(a,i,n,r))return!0}}return!1}function nn(e,t){return e!==void 0&&e.grepsLeft>0&&t<e.expiresAt}function rn(e,t,n,r=`posix`){return z(e,t,n,r)||z(t,e,n,r)}const an=new Set([`zg_search`,`zg_index`,`zg_status`]);function on(e){return typeof e==`string`&&an.has(e)}function sn(e){let{toolStep:t}=e;return t===void 0||t.declarations.some(e=>e.name===`zg_search`)}function B(e){return h(e.agent)}function cn(e,t,n,r){let i;try{j(t,n,r)}catch(t){i=b(n.guardRootRejected,{name:e,reason:g(t)})}return i}function ln(e,t,n,r,i){let{root:a}=t,o;return o=e===`zg_index`&&t.confirm!==!0?r.guardIndexConfirmRequired:a==null||a===``?B(n)===void 0?b(r.guardAbsoluteRootRequired,{name:e}):void 0:cn(e,a,r,i),o}function un(e,t,n=`posix`){let{name:r}=e,i=m(e.arguments)?e.arguments:{},a;return on(r)&&(a=ln(r,i,e,t,n)),a}const dn=`.zvec-grep`,fn=/^[A-Za-z]:[\\/]/u;function pn(e,t){return t===`win32`?fn.test(e)||e.startsWith(F+F):e.startsWith(`/`)}function mn(e,t){if(t===`win32`)return l.win32.dirname(e);if(e===`/`)return`/`;let n=e.lastIndexOf(`/`);return n<=0?`/`:e.slice(0,n)}function hn(e,t,n=8,r=`posix`){let i;if(pn(e,r)){let a=R(e,r);for(let e=0;e<=n;e+=1){if(t(a)){i=a;break}let e=mn(a,r);if(e===a)break;a=e}}return i}function gn(e){let t=e?.agent?.session?.id;return typeof t==`string`&&t.length>0?t:typeof t==`number`&&Number.isSafeInteger(t)?String(t):`__anonymous__`}function _n(e,t){let n=gn(e);if(n===`__anonymous__`)return n;let r=e?.agent?.session?.header;if(r?.origin!==`subagent`)return n;let i=r.parentSession;if(typeof i!=`string`||i.length===0)return n;let a=new Set([n,i]),o=i;for(let e=0;e<32;e+=1){if(t===void 0)return o;let e;try{e=t(o)}catch{e=void 0}if(e===void 0||e.origin!==`subagent`)return o;let n=e.parentSession;if(typeof n!=`string`||n.length===0||a.has(n))return o;a.add(n),o=n}return o}function vn(e,t,n){let r=R(e,n);return n===`win32`?fn.test(t)||t.startsWith(F+F)?t:`${r}\\${t}`:t.startsWith(`/`)?t:`${r}/${t}`}function yn(e,t,n,r,i){if(n===void 0||n.trim().length===0)return!0;let a=n.trim(),o;try{o=Be(vn(e,a,i),r,i)}catch{return!1}return z(o,t,r,i)}function bn(e,t,n,r,i){let a=r.platform??`posix`,o=n.kind===`shell`?!tn(e,n.command,i,a):yn(t,e,n.target,i,a),s;if(o&&r.rebuildBypass?.(e)!==!0){let t=r.lookupUnlock(e);if(t!==void 0&&nn(t,r.now()))r.consumeGrep(t);else{let n;n=t===void 0?i.gateNeverSearched:t.grepsLeft<=0?i.gateQuotaExhausted:i.gateUnlockExpired,s=b(i.gateReason,{state:n,indexRoot:e,indexDir:dn,budget:r.grepBudget,windowMin:r.windowMin})}}return s}function xn(e,t,n,r){let i=hn(e,n.indexProbe,n.findIndexDepth,n.platform??`posix`);return i===void 0?void 0:bn(i,e,t,n,r)}function Sn(e,t,n,r){let i=e.command,a=typeof i==`string`?i:``;return Zt(a,0,n.platform??`posix`)?xn(t,{kind:`shell`,command:a},n,r):void 0}function Cn(e,t,n,r){return xn(t,{kind:`native`,target:typeof e.path==`string`?e.path:void 0},n,r)}function wn(e,t,n){let{name:r}=e,i=m(e.arguments)?e.arguments:{},a=B(e),o;return t.enabled&&a!==void 0&&sn(e)&&(r===`bash`||r===`pwsh`?o=Sn(i,a,t,n):r===`grep`&&(o=Cn(i,a,t,n))),o}async function Tn(e){return await e.settled,`settled`}function En(e,t,n){return e.size<=t?!1:(n||console.warn(`[zvec-grep] 活跃重建表有 ${String(e.size)} 条,超过阈值 ${String(t)}:这不是容量淘汰(淘汰会让正在跑的重建失去占位,同根就能起第二条 zg),而是有一次 claim 没配对 release —— 请把这段告警连同调用场景报给维护者。`),!0)}function Dn(e,t,n,r){let i;for(let a of e.values())z(t,a.root,n,r)&&(i===void 0||a.startedAt<i.startedAt)&&(i=a);return i}function On(e={}){let t=e.now??Date.now,n=e.maxTracked??32,r=e.platform??`posix`,i=new Map,a=e=>{let t=R(e,r);return r===`win32`?t.toLowerCase():t},o=!1;return{claim(e,s,c){let l=a(e);if(i.has(l))return null;let{promise:u,resolve:d}=Promise.withResolvers(),f={root:R(e,r),origin:s,startedAt:c??t(),phase:`starting`,jobId:void 0,settled:u,settle:()=>{d(void 0)}};return i.set(l,f),o=En(i,n,o),f},attach(e,t,n){let r=i.get(a(e));return r===void 0||n!==void 0&&n!==r?!1:(r.jobId=t,r.phase=`running`,!0)},release:(e,t)=>{let r=a(e),s=i.get(r);return s===void 0||t!==void 0&&t!==s?!1:(i.delete(r),s.settle(),i.size<=n&&(o=!1),!0)},active(e){return i.get(a(e))},covering(e,t){return Dn(i,R(e,r),t,r)},async wait(e,t,n,a){let o=Dn(i,R(e,r),t,r);if(o===void 0)return`settled`;if(a?.aborted===!0)return`aborted`;let{promise:s,resolve:c}=Promise.withResolvers(),l=setTimeout(()=>{c(`timeout`)},Math.max(0,n)),u=()=>{c(`aborted`)};a?.addEventListener(`abort`,u,{once:!0});let d=async n=>{let a=await Promise.race([Tn(n),s]);if(a!==`settled`)return a;let o=Dn(i,e,t,r);return o===void 0?`settled`:d(o)};try{return await d(o)}finally{clearTimeout(l),a?.removeEventListener(`abort`,u)}},keys(){return[...i.keys()]}}}function kn(e){return typeof e==`object`&&!!e&&typeof e.resolve==`function`}const V={noSession:`no-session`,serviceMissing:`service-missing`,resolveFailed:`resolve-failed`};function An(e,t){let n=t.agent?.session;if(n===void 0)return{degrade:V.noSession};let r=e.get(`sandboxPolicy`);if(!kn(r))return{degrade:V.serviceMissing};try{return{policy:r.resolve({session:n})}}catch{return{degrade:V.resolveFailed}}}function jn(e,t){return t===void 0?e:{...e,sandboxPolicy:t}}function Mn(e,t){let{degrade:n}=e;if(n===void 0)return``;let r={[V.noSession]:t.sandboxPolicyNoSession,[V.serviceMissing]:t.sandboxPolicyServiceMissing,[V.resolveFailed]:t.sandboxPolicyResolveFailed};return b(t.sandboxPolicyDegraded,{reason:r[n]})}const Nn=/^ *error\[[a-z][\w.]*\]:/iu;var Pn=class extends Error{aborted;constructor(e,t){super(e),this.name=`DaemonCallFailureError`,this.aborted=t}};const Fn=/\boperation=(?<op>\S+)/u,In=/\b(?:lock|storage_dir)=(?<lock>\S+)/u;function Ln(e){let t=e.split(`
|
|
66
|
-
`).find(e=>
|
|
67
|
-
`).find(e=>Nn.test(e))??``,n=t.indexOf(`]:`);return n===-1?``:t.slice(n+2).trim()}function zn(e){let t=Ln(e);if(t===`ZG.ENGINE.RESOURCE_BUSY`){let t=Rn(e),n=Fn.exec(t)?.groups?.op;return{kind:`lock-busy`,ownerOperation:n,lockPath:In.exec(t)?.groups?.lock,rebuild:n===`index.rebuild`}}return t===`ZG.ENGINE.PERMISSION_DENIED`?{kind:`permission-denied`}:null}const H={versionTooOld:`ZG_VERSION_TOO_OLD`,rebuildLockBusy:`ZG_REBUILD_LOCK_BUSY`,lockBusy:`ZG_LOCK_BUSY`,permissionDenied:`ZG_PERMISSION_DENIED`,daemonUnavailable:`ZG_DAEMON_UNAVAILABLE`,rootRejected:`ZG_ROOT_REJECTED`,badArguments:`ZG_BAD_ARGUMENTS`,commandFailed:`ZG_COMMAND_FAILED`};var U=class extends _{constructor(e,t,n){super(t,e,n),this.name=`ZgToolError`}};const Bn={major:0,minor:3,patch:0};function Vn(e){return`${e.major}.${e.minor}.${e.patch}`}const Hn=Vn(Bn),Un=/^\s*v?(?<major>\d{1,9})\.(?<minor>\d{1,9})\.(?<patch>\d{1,9})\s*$/u;function Wn(e,t){let n=e?.groups?.[t];return n===void 0?-1:Number(n)}function Gn(e){let t=Un.exec(e),n=Wn(t,`major`),r=Wn(t,`minor`),i=Wn(t,`patch`);return n<0||r<0||i<0?void 0:{major:n,minor:r,patch:i}}function Kn(e,t){return ee(e,t)}function qn(e){let t=Gn(e);return t===void 0||Kn(t,Bn)?void 0:t}function Jn(e,t,n){return te(e,{name:`zvec-grep`,description:n,content:t})}const Yn=new Set([`ENOENT`,`EACCES`,`EISDIR`,`ENOTDIR`,`ENAMETOOLONG`]);function Xn(e){if(typeof e!=`object`||!e||!(`code`in e))return!1;let t=e.code;return typeof t==`string`&&Yn.has(t)}function Zn(e,t,i){if(!A(e.drop,`drop`,i))for(let a of T(e.ignoreFiles,`ignoreFiles`,i)){let e=l.isAbsolute(a)?a:l.resolve(t,a),s=!1;try{n(e,r.R_OK),s=o(e).isFile()}catch(e){if(!Xn(e))throw e}if(!s)throw Error(b(i.ignoreFileMissing,{path:e}))}}function Qn(e,t){let n=e.enforcement===void 0||e.enforcement.trim().length===0?``:b(t.sandboxEnforcement,{value:e.enforcement}),r=typeof e.mode==`string`&&e.mode.trim().length>0?e.mode.trim():`unknown`;return b(t.sandboxFacts,{mode:r,enforcement:n})}function $n(e,t,n){return b(e,{facts:Qn(t,n)})}function er(e,t){return $n(t.sandboxDenied,e,t)}function tr(e,t){let n=e.sandbox;return n===void 0?null:n.runnerFailed===!0?$n(t.rebuildRunnerFailed,n,t):n.denied?b(t.rebuildDenied,{denied:er(n,t)}):null}function nr(e){try{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&t.hostname!==``}catch{return!1}}function rr(e){let t=typeof e==`string`?mt(e.trim()):``;return t.length>0&&nr(t)?t:void 0}function ir(e){let t=rr(e.hfEndpoint.get());return t===void 0?void 0:{HF_ENDPOINT:t}}function ar(e){let t=typeof e==`string`?e.trim():``;return t.length>0?t:void 0}function or(e){return e.allowRemoteEmbedding}const sr=/^[A-Za-z_]\w*$/u;function W(e,t){let n={...ir(e),...t};if(or(e)){let t=rr(e.remoteEmbeddingEndpoint);t!==void 0&&(n.ZVEC_GREP_ENDPOINT=t);let r=ar(e.remoteEmbeddingApiKeyFrom),i=r!==void 0&&sr.test(r)?process.env[r]:void 0,a=typeof i==`string`?i.trim():void 0;a!==void 0&&a.length>0&&(n.ZVEC_GREP_API_KEY=a)}return Object.keys(n).length>0?n:void 0}function cr(e){let t=e.defaultEmbedding.get();return typeof t==`string`&&be(t)?t.trim():he}function lr(e){return e===`auto`||e===`cli`||e===`mcp`}function ur(e){return typeof e==`string`&&lr(e)?e:`auto`}function dr(e,t){let n=e.trim(),r;try{r=new URL(n)}catch{r=void 0}if(r===void 0||r.protocol!==`http:`&&r.protocol!==`https:`||r.hostname.length===0||r.pathname!==`/mcp`)throw Error(b(t.daemonUrlInvalid,{received:e}));return n}function G(e,t){return ke(e.clientMode,t)}var fr=function(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0},pr=function(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else(d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0};const mr=`zvec-grep-rebuild`,hr=4e3;function gr(e){return{kind:e.kind,label:e.label,startedAt:e.startedAt}}function _r(e,t){return e.kind===t.kind&&e.label===t.label&&e.startedAt===t.startedAt}function vr(e,t){return _r(e.identity,gr(t))}function yr(e,t){return[`stdout`,`stderr`].map(n=>{let r=!1;return{channel:n,read:i=>{if(r)return{text:``,nextOffset:i,lossy:!0};try{let r=e.observed[n].readFrom(i);return r.lossy&&(t.lost=!0),r}catch{return t.lost=!0,r=!0,{text:``,nextOffset:i,lossy:!0}}}}})}function br(e,t){try{return e.get(t)}catch{return null}}function xr(e,t){try{return{view:e.get(t),retained:e.readAt(t,0)}}catch{return null}}function Sr(e){return e===`running`||e===`stopping`}function K(e){try{e.kill()}catch{}}function Cr(e,t){let n=e.list().filter(e=>e.kind===mr).filter(e=>!Sr(e.status)).toSorted((e,t)=>e.startedAt-t.startedAt);for(let r of n.slice(0,Math.max(n.length-9,0)))e.remove(r.id),t.delete(r.id)}const wr=/\(limit: (?<limit>\d+)\)/u;function Tr(e){return wr.exec(g(e))?.groups?.limit}function Er(e,t,n,r){let a;try{a=j(e,n,r)}catch(e){return{error:{value:b(n.endpointRootInvalid,{reason:g(e)}),status:400}}}return t.has(a)?i(a)?{root:a}:{error:{value:b(n.endpointRootGone,{root:a}),status:400}}:{error:{value:b(n.endpointRootUntracked,{root:a}),status:403}}}function Dr(e,t,n){return[...t.values()].find(t=>{if(t.root!==n)return!1;let r=br(e,t.id);return r!==null&&vr(t.state,r)&&Sr(r.status)})?.id}function Or(e,t){let n=Tr(e);return n===void 0?b(t.endpointStartFailed,{reason:g(e)}):b(t.endpointJobsAtCapacity,{limit:n})}function kr(e,t){let n=e.attachController(`zvec-grep: rebuild`);try{return e.start(t)}finally{n()}}function Ar(e){let{routes:t,proc:n,state:r,command:i,root:a,claimed:o}=e,{config:s,host:c,jobsOf:l,messages:u}=t;return{kind:mr,label:i,output:yr(n,r),run:e=>{let i=()=>{let t=l();if(t===void 0)return null;let n=br(t,e.id);return n===null||!vr(r,n)?null:{jobs:t,status:n.status}},d=c.timer.timeout(()=>{if(n.status!==`running`)return;let t=i();if(t!==null&&t.status!==`running`)return;let a=Math.max(1,Math.ceil(s.indexTimeoutMs/6e4));if(r.timeoutNote=b(u().rebuildTimeout,{minutes:a}),t===null)K(n);else try{t.jobs.kill(e.id,void 0,b(u().jobReasonTimeout,{minutes:a}))}catch{K(n)}},s.indexTimeoutMs);return{cancel:()=>{K(n)},done:(async()=>{try{return await n.done,le(n)}finally{d(),t.rebuilds.release(a,o)}})()}}}}async function jr(e,t,n,r,i){let{config:a,host:o}=e,s;try{await e.versionGate.ensure(t);let{platform:c}=e;Zn(n,j(n.root,t,c),t);let l=dt({...n,platform:c},r,t,G(a,t),or(a)),u=W(a,e.daemonEnv?.()),d=o.shell.resolve({command:l.command,workdir:l.workdir,onExpiry:`none`,stdoutMaxBytes:a.stdoutMaxBytes,...u?{env:u}:{},...i===void 0?{}:{sandboxPolicy:i}});s={proc:await o.shell.execute(d),command:l.command}}catch(e){return{error:b(t.endpointStartFailed,{reason:g(e)}),status:500}}return s}function Mr(e,t,n,r,i){let{jobsOf:a,records:o}=e,{proc:s,command:c}=r,l=a();if(l===void 0)return K(s),{error:n.endpointJobsUnavailable,status:503};try{Cr(l,o)}catch(e){return K(s),{error:Or(e,n),status:500}}let u={identity:{kind:mr,label:c,startedAt:0},lost:!1,timeoutNote:null},d;try{d=kr(l,Ar({routes:e,proc:s,state:u,command:c,root:t,claimed:i})),u.identity=gr(l.get(d)),o.set(d,{proc:s,root:t,id:d,state:u})}catch(e){return K(s),{error:Or(e,n),status:500}}return{jobId:d}}function Nr(e){let{jobsOf:t,messages:n,records:r}=e,i=n().jobReasonUnload,a=t();if(a===void 0)for(let e of r.values())K(e.proc);else for(let e of r.values())try{let t=br(a,e.id);t===null||!vr(e.state,t)?K(e.proc):Sr(t.status)?a.kill(e.id,void 0,i):a.remove(e.id)}catch{K(e.proc)}r.clear()}let Pr=(()=>{let e=ce,t=[],n,r,i;return class extends e{static{let a=typeof Symbol==`function`&&Symbol.metadata?Object.create(e[Symbol.metadata]??null):void 0;n=[se(`roots`)],r=[se(`rebuild`)],i=[se(`status`)],pr(this,null,n,{kind:`method`,name:`roots`,static:!1,private:!1,access:{has:e=>`roots`in e,get:e=>e.roots},metadata:a},null,t),pr(this,null,r,{kind:`method`,name:`rebuild`,static:!1,private:!1,access:{has:e=>`rebuild`in e,get:e=>e.rebuild},metadata:a},null,t),pr(this,null,i,{kind:`method`,name:`status`,static:!1,private:!1,access:{has:e=>`status`in e,get:e=>e.status},metadata:a},null,t),a&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})}constructor(e,n){super(e,`zvecGrepRebuild`),fr(this,t),this.deps=n}async roots(){let e=!1;try{e=await this.deps.serverGate.ready()}catch{}return{roots:this.deps.ledger.list(),serverReady:e}}async rebuild(request){let e=this.deps.messages(),t=Er(m(request)?request.root:void 0,this.deps.ledger,e,this.deps.platform);if(`error`in t)return{ok:!1,error:t.error.value,status:t.error.status};let{root:n}=t,r=this.deps.jobsOf();if(r===void 0)return{ok:!1,error:e.endpointJobsUnavailable,status:503};let i=this.deps.rebuilds.claim(n,`card`);if(i===null){let t=Dr(r,this.deps.records,n);return t===void 0?{ok:!1,error:e.endpointRebuildInFlight,status:409}:{ok:!0,jobId:t,reused:!0}}let a=cr(this.deps.config),o=await jr(this.deps,e,{root:n,embedding:a,rebuild:!0},a);if(`error`in o)return this.deps.rebuilds.release(n,i),{ok:!1,error:o.error,status:o.status};let s=Mr(this.deps,n,e,o,i);return`error`in s?(this.deps.rebuilds.release(n,i),{ok:!1,error:s.error,status:s.status}):(this.deps.rebuilds.attach(n,s.jobId,i),{ok:!0,jobId:s.jobId})}status(request){let e=this.deps.messages(),t=m(request)?request.jobId:void 0,n=typeof t==`string`&&t.length>0?this.deps.records.get(t):void 0;if(n===void 0)return{ok:!1,error:b(e.unknownJobId,{maxJobs:10}),status:404};let r=this.deps.jobsOf();if(r===void 0)return{ok:!1,error:e.endpointJobsUnavailable,status:503};let i=xr(r,n.id);if(i===null||!vr(n.state,i.view))return{ok:!1,error:b(e.unknownJobId,{maxJobs:10}),status:404};let{view:a,retained:o}=i,s=o.chunks.map(e=>e.text).join(``),c=v(s,hr),l=s.length>hr?b(e.jobOutputView,{shown:hr,total:s.length}):``;return{ok:!0,status:a.status,exitCode:n.proc.exitCode,root:n.root,...n.proc.sandbox===void 0?{}:{sandbox:n.proc.sandbox},output:(a.output.earliest>0?e.jobOutputTruncated:``)+(n.state.lost?e.jobOutputLost:``)+(n.state.timeoutNote??``)+(tr(n.proc,e)??``)+l+c}}}})();function Fr(e,t){return!m(e)||!m(e.reflect)||typeof e.reflect.provide!=`function`?!1:(new Pr(e,t),e.effect(()=>()=>{Nr(t)},`zvec-grep: rebuild records`),!0)}const Ir=/^[\u0021-\u007E]{32,}$/u;function Lr(e=process.env){let t=e.ZVEC_GREP_HOME??l.join(s(),`.zvec-grep`);return l.join(t,`dsh-zvec-grep.token`)}async function Rr(e){let t;try{let n=(await de(e,`utf8`)).trim();t=Ir.test(n)?n:void 0}catch{}return t}async function zr(e,t){try{return await me(e,t,{mode:384}),!0}catch{return!1}}function Br(e){return typeof e==`object`&&!!e&&e.code===`EEXIST`}async function Vr(e,t){let n=await Rr(e);if(n!==void 0||t<=1)return n;let{promise:r,resolve:i}=Promise.withResolvers();return setImmediate(()=>{i(void 0)}),await r,Vr(e,t-1)}async function Hr(e,t){try{await ue(l.dirname(e),{recursive:!0})}catch{return{token:t,owned:!1}}try{return await pe(e,t,{mode:384,flag:`wx`}),{token:t,owned:!0}}catch(e){if(!Br(e))return{token:t,owned:!1}}let n=await Vr(e,3);if(n!==void 0)return{token:n,owned:!1};try{await fe(e,{force:!0})}catch{return{token:t,owned:!1}}return{token:t,owned:await zr(e,t)}}async function Ur(e){try{await fe(e,{force:!0})}catch{}}const Wr=new Set([400,404,405]);function Gr(e){let t=[];for(let n of e.split(`
|
|
68
|
-
`)){let e=n.trim(),r=e.startsWith(`data:`)?e.slice(5).trim():``;if(r.length>0)try{t.push(JSON.parse(r))}catch{}}return t}function
|
|
69
|
-
`)}var
|
|
70
|
-
`).filter(e=>e.trim().length>0&&!
|
|
71
|
-
`)}function
|
|
72
|
-
`)){let e=
|
|
73
|
-
`)}`:e}async function
|
|
74
|
-
`)}`:a}async function
|
|
75
|
-
`);return{text:re.length===0?ne:`${re}\n${ne}`}}function
|
|
62
|
+
[zvec-grep] (showing only the last {shown} of {total} characters)`,textTooLong:`{name} exceeds the {maxChars} character limit (actual {actual})`,mustBeString:`{name} must be a string (received {received})`,noNulBytes:`{name} must not contain NUL bytes`,mustBeBoolean:`{name} must be a boolean (received {received})`,clientModeInvalid:`invalid zg client mode: {received} (allowed: {allowed})`,previewInvalid:`invalid preview mode: {received} (allowed: {allowed})`,refreshInvalid:`invalid refresh policy: {received} (allowed: {allowed})`,refreshBackgroundNeedsServer:'{root} has no available zvec-grep daemon, so `refresh=background` was refused — it only holds in server mode. Without a daemon the CLI prints one stderr warning and silently turns refreshing **off**, which this plugin will not report as "refreshing in the background". Either keep the default refresh=wait (synchronous refresh before the search, works in direct mode) or run `zg --server on` in a terminal first — the daemon also brings incremental indexing and a resident embedding model pool.',refreshBackgroundPinnedDirect:"{root}: `refresh=background` was refused because this daemon's transport mode is pinned to direct by the deployment (the row config's `clientMode: direct`), while background refreshing only exists in server mode. Starting a daemon would not help here — either set clientMode back to auto/server in the row config, or search with the default refresh=wait.",serverReadyNote:`[zvec-grep] daemon: ready (searches can use server mode: incremental index refresh, resident embedding model pool)`,serverUnavailableNote:"[zvec-grep] daemon: not ready. Searches therefore run in direct mode and cold-load the embedding model every call (slower on large workspaces, and refresh=background is unavailable); run `zg --server on` in a terminal for incremental indexing and a resident model pool",symbolTypeInvalid:`invalid symbol type: {received} (allowed: {allowed}; lowercase only)`,rootEscapesFs:`root contains a .. segment that escapes the filesystem root: {path}`,rootMustBeString:`root must be a string (received {received})`,rootRequired:`root is required and must be an absolute workspace path`,rootMustBeAbsolute:`root must be an absolute path (starting with /): {path}`,rootIsFsRoot:`root must not be the filesystem root /`,rootRequiredWithFallback:`root is required and must be an absolute workspace path (it may be omitted: defaults to the current session workspace)`,limitInvalid:`limit must be a non-negative integer (omit it to use the default)`,limitOutOfRange:`limit is out of the allowed range {min}–{max} (omit it to use the default)`,mustBeStringOrArray:`must be a string or an array of strings`,mustBeStringArray:`{name} must be an array of strings`,tooManyItems:`{name} allows at most {maxItems} items (actual {actual})`,nonStringItem:`{name} contains a non-string item ({received})`,commandTooLong:`the zg command is {length} bytes, over the {maxBytes} byte limit — narrow the search`,tooManyQueryRoutes:`{count} query routes in total, over the limit of {max}`,searchNeedsQuery:`zg_search needs at least one of query/queries/fts/vector`,exhaustiveNeedsPattern:`exhaustive search (rg=true) needs a query to use as the pattern`,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`,filesConflicts:`file discovery (files=true) conflicts with these parameters: {names}. It only lists files and never searches content — query would be read as a path, limit is meaningless (upstream refuses it outright), and device plays no part in file discovery; drop them and resend`,embeddingNotAllowed:`embedding reference {reference} is not in the catalog. Local choices: {choices}; the remote qwen models require allowRemoteEmbedding turned on in the deployment config (and a one-time user authorization, zg --auth grant <root> --capability embedding --scope workspace). References with unknown prefixes are refused under every switch — a remote endpoint sends workspace content off the machine, and that decision belongs to the user.`,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.`,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.`,ignoreFileMissing:`{path} is not an existing file the current process can read (missing, a directory, or present-but-unreadable all count). zg 0.3.0 silently tolerates an unreadable ignore file — indexing succeeds, but that exclusion rule quietly does nothing (you believe it is filtering files while nothing is excluded), so this plugin refuses the bad path before the command is built. Give a path that really exists and that the current user can read.`,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.`,rgDescription:`Exhaustive lexical search (zg --rg): needs no index, matches literal text line by line. Leave it unset to fall back to it automatically when the workspace has no index, and to use the index when one exists. An explicit false demands indexed search only (an error when there is no index). It does not support preview / refresh / fuse / symbolTypes / preferSymbol / fts / vector / queries / category, and it grants no grep/rg quota`,intWithReceived:`{name} must be an integer >= {min} (received {received})`,intRequired:`{name} must be an integer >= {min}`,guardRootRejected:`the root given to {name} is not accepted: {reason}`,guardIndexConfirmRequired:`zg_index creates/rebuilds/deletes a persistent index and requires an explicit user request with confirm true`,guardAbsoluteRootRequired:`{name} needs an absolute root path (it may be omitted: defaults to the current session workspace)`,gateNeverSearched:`no zg_search has run yet`,gateQuotaExhausted:`the grep/rg quota is spent`,gateUnlockExpired:`the unlock from the last zg_search has expired`,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.`}};function b(e,t){return f(e,t)}const x=4e3,S=1024;function we(e,t=`posix`){return p(e,t)}function Te(e,t,n,r){if(e.length>r)throw TypeError(b(n.textTooLong,{name:t,maxChars:r,actual:e.length}));return e}function C(e,t,n,r){if(e==null)return``;if(typeof e!=`string`)throw TypeError(b(n.mustBeString,{name:t,received:typeof e}));if(e.includes(`\0`))throw Error(b(n.noNulBytes,{name:t}));return Te(e.trim(),t,n,r)}function w(e,t,n,r=128,i=S){if(e==null)return[];if(!Array.isArray(e))throw TypeError(b(n.mustBeStringArray,{name:t}));let a=[];for(let r of e){if(typeof r!=`string`)throw TypeError(b(n.nonStringItem,{name:t,received:typeof r}));if(r.includes(`\0`))throw Error(b(n.noNulBytes,{name:t}));let e=Te(r.trim(),t,n,i);e.length>0&&a.push(e)}if(a.length>r)throw TypeError(b(n.tooManyItems,{name:t,maxItems:r,actual:a.length}));return a}function T(e,t,n,r=128,i=S){if(e!=null&&typeof e!=`string`&&!Array.isArray(e))throw TypeError(b(n.mustBeStringOrArray,{name:t}));return w(typeof e==`string`?[e]:e,t,n,r,i)}const Ee=[`!*.pem`,`!*.key`,`!*.p12`,`!*.pfx`,`!*.keystore`,`!*.jks`,`!*.ppk`,`!id_rsa*`,`!id_ed25519*`],De=Object.keys({auto:`auto`,direct:`direct`,server:`server`}),E=`auto`;function Oe(e){return De.includes(e)}function ke(e,t){if(e==null)return E;if(typeof e!=`string`||!Oe(e))throw TypeError(b(t.clientModeInvalid,{received:typeof e==`string`?e:typeof e,allowed:De.join(` | `)}));return e}function D(e){return`--mode ${e}`}const Ae=Object.keys({none:`none`,short:`short`,full:`full`,detail:`detail`});function je(e){return Ae.includes(e)}function Me(e,t){if(e==null)return`short`;if(typeof e!=`string`||!je(e))throw TypeError(b(t.previewInvalid,{received:typeof e==`string`?e:typeof e,allowed:Ae.join(` | `)}));return e}const Ne=Object.keys({background:`background`,wait:`wait`,off:`off`});function Pe(e){return Ne.includes(e)}function Fe(e,t){if(e==null)return`wait`;if(typeof e!=`string`||!Pe(e))throw TypeError(b(t.refreshInvalid,{received:typeof e==`string`?e:typeof e,allowed:Ne.join(` | `)}));return e}function Ie(e){return e===`background`}const O=Object.keys({alias:`alias`,class:`class`,enum:`enum`,function:`function`,interface:`interface`,module:`module`,value:`value`});function Le(e){return O.includes(e)}function Re(e,t){let n=[];for(let r of w(e,`symbolTypes`,t,O.length)){if(!Le(r))throw TypeError(b(t.symbolTypeInvalid,{received:r,allowed:O.join(` | `)}));n.push(r)}return n}function ze(e){return t=>we(t,e)}function Be(e,t,n){let r=C(e,`device`,t,S);return`--device ${n(r.length>0?r:`auto`)}`}function k(e,t,n,r=!1){if(e==null)return r;if(typeof e!=`boolean`)throw TypeError(b(n.mustBeBoolean,{name:t,received:typeof e}));return e}function Ve(e,t,n=`posix`){return d(e,n,{mustBeAbsolute:e=>b(t.rootMustBeAbsolute,{path:e}),escapesRoot:e=>b(t.rootEscapesFs,{path:e})})}function A(e,t,n=`posix`){return u(e,n,{mustBeAbsolute:e=>b(t.rootMustBeAbsolute,{path:e}),escapesRoot:e=>b(t.rootEscapesFs,{path:e}),typeError:e=>b(t.rootMustBeString,{received:e}),required:t.rootRequired,nul:b(t.noNulBytes,{name:`root`}),filesystemRoot:()=>t.rootIsFsRoot})}function He(e,t,n,r=`posix`){if(e!=null&&typeof e!=`string`)throw TypeError(b(n.rootMustBeString,{received:typeof e}));if(typeof e==`string`&&e.trim().length>0)return A(e.trim(),n,r);if(typeof t==`string`&&t.trim().length>0)return A(t.trim(),n,r);throw Error(n.rootRequiredWithFallback)}function j(e,t,n=10){if(e==null)return n;if(typeof e!=`number`)throw TypeError(t.limitInvalid);if(!Number.isSafeInteger(e)||e<0)throw Error(t.limitInvalid);if(e<1||e>50)throw Error(b(t.limitOutOfRange,{min:1,max:50}));return e}function M(e,t,n){return w(e,t,n,32,x)}function N(e,t,n,r=`posix`){let i=e.join(` `),a=Buffer.byteLength(i,`utf8`),o=r===`win32`?24e3:64e3;if(a>o)throw Error(b(n.commandTooLong,{length:a,maxBytes:o}));return{command:i,workdir:t}}function Ue(e,t,n,r){let i=0,a=C(t.query,`query`,n,x);a.length>0&&(e.push(`--hybrid=${r(a)}`),i+=1);for(let a of M(t.queries,`queries`,n))e.push(`--hybrid=${r(a)}`),i+=1;for(let a of M(t.fts,`fts`,n))e.push(`--fts=${r(a)}`),i+=1;for(let a of M(t.vector,`vector`,n))e.push(`--vector=${r(a)}`),i+=1;if(i>32)throw Error(b(n.tooManyQueryRoutes,{count:i,max:32}));return i}function We(e,t,n,r){for(let i of T(t.globs,`globs`,n))e.push(`--glob`,r(i));for(let i of T(t.insensitiveGlobs,`insensitiveGlobs`,n))e.push(`--iglob`,r(i));for(let i of T(t.fileTypes,`fileTypes`,n))e.push(`--type`,r(i));for(let i of T(t.excludedFileTypes,`excludedFileTypes`,n))e.push(`--type-not`,r(i))}function Ge(e,t,n,r){let i=C(t.modifiedAfter,`modifiedAfter`,n,128);i.length>0&&e.push(`--modified-after`,r(i));let a=C(t.modifiedBefore,`modifiedBefore`,n,128);a.length>0&&e.push(`--modified-before`,r(a))}function Ke(e,t,n,r){We(e,t,n,r);for(let i of Re(t.symbolTypes,n))e.push(`--symbol-type`,r(i))}function qe(e,t){return C(e.query,`query`,t,x)}function Je(e,t,n,r){for(let i of T(t.category,`category`,n))e.push(`--category`,r(i));for(let i of T(t.categoryNot,`categoryNot`,n))e.push(`--category-not`,r(i))}function Ye(e,t,n,r,i){let a=[`zg`],o=ze(e.platform??`posix`);if(Ue(a,e,n,o)===0)throw Error(n.searchNeedsQuery);k(e.fuse,`fuse`,n)&&a.push(`--fuse`);let s=Fe(e.refresh,n);if(s===`background`&&r===`direct`)throw Error(b(n.refreshBackgroundPinnedDirect,{root:t}));if(s===`background`&&i===`daemon-down`)throw Error(b(n.refreshBackgroundNeedsServer,{root:t}));return a.push(`--limit`,String(j(e.limit,n)),`--preview`,Me(e.preview,n),`--refresh`,s),Ke(a,e,n,o),Je(a,e,n,o),k(e.preferSymbol,`preferSymbol`,n)&&a.push(`--prefer-symbol`),k(e.trace,`trace`,n)&&a.push(`--trace`),Ge(a,e,n,o),a.push(Be(e.device,n,o),D(r)),N(a,t,n,e.platform??`posix`)}function Xe(e,t){let n=[];if(k(e.fuse,`fuse`,t)&&n.push(`fuse`),M(e.queries,`queries`,t).length>0&&n.push(`queries`),M(e.fts,`fts`,t).length>0&&n.push(`fts`),M(e.vector,`vector`,t).length>0&&n.push(`vector`),T(e.category,`category`,t).length>0&&n.push(`category`),T(e.categoryNot,`categoryNot`,t).length>0&&n.push(`categoryNot`),C(e.preview,`preview`,t,1024).length>0&&n.push(`preview`),C(e.refresh,`refresh`,t,1024).length>0&&n.push(`refresh`),w(e.symbolTypes,`symbolTypes`,t).length>0&&n.push(`symbolTypes`),k(e.preferSymbol,`preferSymbol`,t)&&n.push(`preferSymbol`),k(e.trace,`trace`,t)&&n.push(`trace`),n.length>0)throw Error(b(t.exhaustiveConflicts,{names:n.join(` | `)}))}function Ze(e,t){Xe(e,t);let n=[];if(qe(e,t).length>0&&n.push(`query`),e.limit!==void 0&&e.limit!==null&&n.push(`limit`),C(e.device,`device`,t,1024).length>0&&n.push(`device`),n.length>0)throw Error(b(t.filesConflicts,{names:n.join(` | `)}))}function Qe(e,t,n,r){Xe(e,n);let i=ze(e.platform??`posix`),a=[`zg`,`--rg`],o=C(e.query,`query`,n,x);if(o.length===0)throw Error(n.exhaustiveNeedsPattern);return o.startsWith(`-`)?a.push(`-e`,i(o)):a.push(i(o)),a.push(`--limit`,String(j(e.limit,n))),We(a,e,n,i),Ge(a,e,n,i),a.push(Be(e.device,n,i),D(r)),N(a,t,n,e.platform??`posix`)}function $e(e,t,n,r){Ze(e,n);let i=ze(e.platform??`posix`),a=[`zg`,`--rg`,`--files`];return We(a,e,n,i),Ge(a,e,n,i),a.push(D(r)),N(a,t,n,e.platform??`posix`)}function et(e,t,n=E,r=`indexed`,i=`daemon-down`){let a=e.platform??`posix`,o=A(e.root,t,a);return r===`files`?$e(e,o,t,n):r===`exhaustive`?Qe(e,o,t,n):Ye(e,o,t,n,i)}function tt(e,t,n,r){if(typeof e!=`number`)throw TypeError(b(n.intWithReceived,{name:t,min:r,received:typeof e}));if(!Number.isSafeInteger(e)||e<r)throw Error(b(n.intRequired,{name:t,min:r}));return String(e)}function nt(e,t){return{rebuild:k(e.rebuild,`rebuild`,t),hidden:k(e.hidden,`hidden`,t),noIgnore:k(e.noIgnore,`noIgnore`,t),nestedGit:k(e.nestedGit,`nestedGit`,t),follow:k(e.follow,`follow`,t),excludeSecrets:k(e.excludeSecrets,`excludeSecrets`,t,!0)}}function rt(e,t){t.rebuild&&e.push(`--rebuild`)}function it(e,t,n,r,i){for(let n of T(t.globs,`globs`,r))e.push(`--glob`,i(n));for(let n of T(t.insensitiveGlobs,`insensitiveGlobs`,r))e.push(`--iglob`,i(n));for(let n of T(t.fileTypes,`fileTypes`,r))e.push(`--type`,i(n));for(let n of T(t.excludedFileTypes,`excludedFileTypes`,r))e.push(`--type-not`,i(n));if(n.excludeSecrets)for(let t of Ee)e.push(`--iglob`,i(t));for(let n of T(t.ignoreFiles,`ignoreFiles`,r))e.push(`--ignore-file`,i(n))}function at(e,t,n){t.maxDepth!==void 0&&t.maxDepth!==null&&e.push(`--max-depth`,tt(t.maxDepth,`maxDepth`,n,0)),t.maxFileSizeBytes!==void 0&&t.maxFileSizeBytes!==null&&e.push(`--max-filesize`,tt(t.maxFileSizeBytes,`maxFileSizeBytes`,n,0))}function ot(e,t){t.hidden&&e.push(`--hidden`),t.noIgnore&&e.push(`--no-ignore`),t.nestedGit&&e.push(`--nested-git`)}function st(e,t){t.follow&&e.push(`--follow`)}function ct(e,t,n){t.embeddingConcurrency!==void 0&&t.embeddingConcurrency!==null&&e.push(`--embedding-concurrency`,tt(t.embeddingConcurrency,`embeddingConcurrency`,n,1))}function lt(e,t,n){k(t.resetPaths,`resetPaths`,n)&&e.push(`--reset-paths`)}function ut(e,t,n,r){let i=C(e.embedding,`embedding`,n,S),a=i.length>0?i:t;if(_e(a))return{reference:a,remote:!1};if(ye(a)){if(r)return{reference:a,remote:!0};throw Error(b(n.embeddingNotAllowed,{reference:a,choices:ge.map(e=>e.reference).join(` | `)}))}throw Error(b(n.embeddingNotAllowed,{reference:a,choices:[...ge,...ve].map(e=>e.reference).join(` | `)}))}const dt=[`rebuild`,`embedding`,`globs`,`insensitiveGlobs`,`fileTypes`,`excludedFileTypes`,`ignoreFiles`,`hidden`,`noIgnore`,`nestedGit`,`excludeSecrets`,`maxDepth`,`maxFileSizeBytes`,`follow`,`embeddingConcurrency`,`device`];function ft(e,t,n,r=E,i=!1){let a=e.platform??`posix`,o=A(e.root,n,a),s=ze(a),c=[`zg`,`--index`,s(o)],l=nt(e,n);if(k(e.drop,`drop`,n)){if(k(e.resetPaths,`resetPaths`,n))throw Error(n.dropWithResetPaths);let t=dt.filter(t=>e[t]!==void 0&&e[t]!==null);if(t.length>0)throw Error(b(n.dropWithIndexArgs,{names:t.join(` | `)}));return c.push(`--drop`,D(r)),N(c,o,n,e.platform??`posix`)}let{reference:u,remote:d}=ut(e,t,n,i);return c.push(`--embedding`,s(u)),d&&c.push(`--allow-remote`),rt(c,l),it(c,e,l,n,s),ot(c,l),at(c,e,n),st(c,l),ct(c,e,n),lt(c,e,n),c.push(Be(e.device,n,s),D(r)),N(c,o,n,e.platform??`posix`)}function pt(e,t,n=E){let r=e.platform??`posix`,i=A(e.root,t,r),a=[`zg`,`--status`,we(i,r)];return k(e.checkReady,`checkReady`,t)&&a.push(`--check-ready`),a.push(D(n)),N(a,i,t,e.platform??`posix`)}function mt(e=process.platform){return e===`win32`?`win32`:`posix`}const P=String.fromCodePoint(92);function ht(e){let t=e.length;for(;t>0&&e.codePointAt(t-1)===47;)--t;return t===e.length?e:e.slice(0,t)}function gt(e){let t=e.length;for(;t>0;){let n=e.codePointAt(t-1);if(n!==47&&n!==92)break;--t}return t===e.length?e:e.slice(0,t)}const _t=new Set([`grep`,`egrep`,`fgrep`,`rg`]),vt=new Set([`--help`,`--version`,`-V`]),yt=new Set([`sh`,`bash`,`zsh`,`dash`,`ksh`,`csh`,`fish`,`pwsh`,`powershell`]),bt=/^-[^c]*c$/u,xt=new Set([`-c`,`-command`]),St=/^[A-Za-z]:[\\/]/u,Ct=/^[\\/]+/u,wt=new Set([`|`,`;`,`&`,`
|
|
63
|
+
`,`\r`]),Tt=/\.(?:exe|cmd|bat|com|ps1)$/iu,Et=new Set([`git`,`xargs`,`env`,`nohup`,`sudo`,`time`,`timeout`,`nice`,`parallel`]),Dt=new Map([[`git`,new Set([`-c`,`-C`,`--git-dir`,`--work-tree`,`--namespace`,`--super-prefix`,`--config-env`])],[`xargs`,new Set([`-a`,`-d`,`-E`,`-I`,`-L`,`-n`,`-P`,`-s`,`--arg-file`,`--delimiter`,`--eof`,`--max-args`,`--max-chars`,`--max-lines`,`--max-procs`,`--process-slot-var`,`--replace`])],[`env`,new Set([`-u`,`-C`,`-S`,`--unset`,`--chdir`,`--split-string`])],[`sudo`,new Set([`-u`,`-g`,`-C`,`-D`,`-h`,`-p`,`-r`,`-t`,`-T`,`-U`,`-R`,`--user`,`--group`,`--close-from`,`--chdir`,`--host`,`--prompt`,`--role`,`--type`,`--command-timeout`,`--other-user`,`--chroot`])],[`time`,new Set([`-f`,`-o`,`--format`,`--output`])],[`timeout`,new Set([`-s`,`-k`,`--signal`,`--kill-after`])],[`nice`,new Set([`-n`,`--adjustment`])],[`parallel`,new Set([`-j`,`-S`,`-n`,`--jobs`,`--sshlogin`,`--sshloginfile`,`--joblog`,`--results`,`--tmpdir`,`--delay`,`--max-args`])]]),Ot=new Set(`-e.-f.-g.-m.-A.-B.-C.-d.-D.-E.-j.-M.-r.-t.-T.--regexp.--file.--glob.--iglob.--type.--type-not.--max-count.--after-context.--before-context.--context.--directories.--devices.--encoding.--threads.--max-columns.--max-depth.--max-filesize.--replace.--sort.--sortr.--include.--exclude.--exclude-from.--exclude-dir.--include-dir.--label.--pre.--pre-glob.--ignore-file`.split(`.`)),kt=/^[A-Za-z_]\w*=/u,At=/^\d+$/u,jt=new Set([` `,` `,`\v`,`\f`]),Mt=new Set([`|`,`;`,`&`,`
|
|
64
|
+
`,`\r`,"`"]),Nt=new Set([`<`,`>`]),Pt=new Set([`(`,`)`,`{`,`}`]),Ft=new Set([`'`,`"`]);function It(e,t,n){return n===`win32`?t===`'`&&e!==`'`||t===`"`&&e!==`"`&&e!=="`":t===`'`&&e!==`'`||t===`"`&&e!==`"`&&e!==`\\`}function Lt(e,t){let n=e.indexOf(`
|
|
65
|
+
`,t);return n===-1?e.length:n-1}function Rt(e,t,n,r){r.atCommand=!0;let i=e.slice(t+1,t+2)===`|`||e.slice(t-1,t)===`|`;r.pipedNext=n===`|`&&!i}function zt(e,t){t.buffer.length>0?t.buffer+=e:(e===`(`||e===`{`)&&(t.atCommand=!0)}function Bt(e,t){return e===`(`&&t.quote===``&&t.buffer===`$`}function Vt(e,t){return t.quote===``&&e===`#`&&t.buffer.length===0}function Ht(e,t){return t===e?``:e}function Ut(e,t){return e&&(t.startsWith(`-`)||At.test(t)||kt.test(t))}function Wt(e,t){return t===`win32`?St.test(e)||e.startsWith(P+P)||e.startsWith(P)||e.startsWith(`/`)||e.includes(P)||e.includes(`/`)||e===`.`||e===`..`:e.startsWith(`/`)||e.includes(`/`)||e===`.`||e===`..`}function F(e,t){if(t===`win32`){let t=e.replaceAll(`\\`,`/`);return t.slice(t.lastIndexOf(`/`)+1).toLowerCase().replace(Tt,``)}return e.slice(e.lastIndexOf(`/`)+1).toLowerCase()}function Gt(e,t,n){let{text:r}=e,i=t.pendingValue,a={...t,pendingValue:!1};i?a.afterPrefix=!0:e.atCommand&&(a.wrapper=``,a.afterPrefix=!1);let o=e.atCommand||a.afterPrefix||a.wrapper!==``,s=o&&Dt.get(a.wrapper)?.has(r)===!0;return i&&!e.atCommand?{state:a,command:!1}:s?(a.pendingValue=!0,{state:a,command:!1}):Ut(o,r)?(a.afterPrefix=!0,{state:a,command:!1}):(o&&(a.wrapper=Et.has(F(r,n))?F(r,n):``),a.afterPrefix=!1,{state:a,command:o})}function I(e,t){t.buffer.length!==0&&(e.push({text:t.buffer,atCommand:t.atCommand,piped:t.pipedNext,redirect:t.redirectNext}),t.buffer=``,t.atCommand=!1,t.pipedNext=!1,t.redirectNext=!1)}function Kt(e,t,n){let r=e.slice(t,t+1);return e.slice(t+1,t+2)===r?(n.buffer+=r,t+1):(n.quote=``,t)}function qt(e,t,n,r,i){let a=e.slice(t,t+1),o=i===`win32`?wt:Mt;if(n.escaped)n.buffer+=a,n.escaped=!1;else if(It(a,n.quote,i))n.buffer+=a;else if(Vt(a,n))return Lt(e,t);else if(a===(i===`win32`?"`":`\\`))n.escaped=!0;else if(i===`win32`&&n.quote!==``&&a===n.quote)return Kt(e,t,n);else Ft.has(a)?n.quote=Ht(a,n.quote):o.has(a)?(I(r,n),Rt(e,t,a,n)):Bt(a,n)?(n.buffer=``,I(r,n),Rt(e,t,a,n)):Pt.has(a)?zt(a,n):Nt.has(a)?(I(r,n),n.redirectNext=!0):jt.has(a)?I(r,n):n.buffer+=a;return t}function Jt(e,t){let n=[],r={buffer:``,atCommand:!0,pipedNext:!1,redirectNext:!1,quote:``,escaped:!1},i=0;for(;i<e.length;)i=qt(e,i,r,n,t)+1;return I(n,r),n}function Yt(e,t){let n=[],r={wrapper:``,pendingValue:!1,afterPrefix:!1};for(let[i,a]of e.entries()){let e=Gt(a,r,t);r=e.state,e.command&&n.push(i)}return n}function Xt(e,t){let n=[];for(let[r,i]of e.entries()){let a=e[r+1],o=e[r+2],s=t===`win32`?a!==void 0&&xt.has(a.text.toLowerCase()):a!==void 0&&bt.test(a.text);i.atCommand&&yt.has(F(i.text,t))&&a!==void 0&&o!==void 0&&s&&!o.atCommand&&n.push(o.text)}return n}function Zt(e,t,n){for(let r of e.slice(t+1)){if(r.atCommand)break;if(!r.redirect&&!r.text.startsWith(`-`)&&Wt(r.text,n))return!0}return!1}function Qt(e,t=0,n=`posix`){let r=Jt(e,n);return r.some(e=>vt.has(e.text))?!1:Yt(r,n).some(e=>{let t=r[e];return t===void 0||!_t.has(F(t.text,n))?!1:!(t.piped&&!Zt(r,e,n))})?!0:t>=2?!1:Xt(r,n).some(e=>Qt(e,t+1,n))}function L(e,t=`posix`){if(t===`win32`){let t=e.replaceAll(`/`,`\\`),n=l.win32.parse(t).root;if(t===n)return n;let r=gt(t);return r.length>0?r:n}let n=ht(e);return n.length>0?n:`/`}function $t(e){let t=e.replaceAll(`/`,`\\`);return St.test(t)||t.startsWith(P+P)}const en=/^\.\.(?:[\\/]|$)/u;function tn(e,t){if($t(e))return e;if(e.startsWith(P)||e.startsWith(`/`)){let{root:n}=l.win32.parse(t);return`${n}${e.replace(Ct,``)}`}return`${t}\\${e}`}function R(e,t,n,r=`posix`){if(e===void 0||e.trim().length===0)return!0;let i=L(t,r),a=e.trim();if(r===`win32`){let e;try{e=Ve(tn(a,i),n,`win32`)}catch{return!1}let t=l.win32.relative(i,e);return t===``||!en.test(t)&&!l.win32.isAbsolute(t)}let o=a.startsWith(`/`)?a:`${i}/${a}`,s;try{s=Ve(o,n)}catch{return!1}let c=i.endsWith(`/`)?i:`${i}/`;return s===i||s.startsWith(c)}function nn(e,t,n,r=`posix`){let i=L(e,r),a=Jt(t,r),o=new Set(Yt(a,r)),s=!1;for(let[e,t]of a.entries()){let{text:a}=t,c=s;if(s=!1,!(o.has(e)||c||t.redirect)){if(a.startsWith(`-`))s=Ot.has(a);else if(Wt(a,r)&&!R(a,i,n,r))return!0}}return!1}function rn(e,t){return e!==void 0&&e.grepsLeft>0&&t<e.expiresAt}function an(e,t,n,r=`posix`){return R(e,t,n,r)||R(t,e,n,r)}const on=new Set([`zg_search`,`zg_index`,`zg_status`]);function sn(e){return typeof e==`string`&&on.has(e)}function cn(e){let{toolStep:t}=e;return t===void 0||t.declarations.some(e=>e.name===`zg_search`)}function z(e){return h(e.agent)}function ln(e,t,n,r){let i;try{A(t,n,r)}catch(t){i=b(n.guardRootRejected,{name:e,reason:g(t)})}return i}function un(e,t,n,r,i){let{root:a}=t,o;return o=e===`zg_index`&&t.confirm!==!0?r.guardIndexConfirmRequired:a==null||a===``?z(n)===void 0?b(r.guardAbsoluteRootRequired,{name:e}):void 0:ln(e,a,r,i),o}function dn(e,t,n=`posix`){let{name:r}=e,i=m(e.arguments)?e.arguments:{},a;return sn(r)&&(a=un(r,i,e,t,n)),a}const fn=`.zvec-grep`,pn=/^[A-Za-z]:[\\/]/u;function mn(e,t){return t===`win32`?pn.test(e)||e.startsWith(P+P):e.startsWith(`/`)}function hn(e,t){if(t===`win32`)return l.win32.dirname(e);if(e===`/`)return`/`;let n=e.lastIndexOf(`/`);return n<=0?`/`:e.slice(0,n)}function gn(e,t,n=8,r=`posix`){let i;if(mn(e,r)){let a=L(e,r);for(let e=0;e<=n;e+=1){if(t(a)){i=a;break}let e=hn(a,r);if(e===a)break;a=e}}return i}function _n(e){let t=e?.agent?.session?.id;return typeof t==`string`&&t.length>0?t:typeof t==`number`&&Number.isSafeInteger(t)?String(t):`__anonymous__`}function vn(e,t){let n=_n(e);if(n===`__anonymous__`)return n;let r=e?.agent?.session?.header;if(r?.origin!==`subagent`)return n;let i=r.parentSession;if(typeof i!=`string`||i.length===0)return n;let a=new Set([n,i]),o=i;for(let e=0;e<32;e+=1){if(t===void 0)return o;let e;try{e=t(o)}catch{e=void 0}if(e===void 0||e.origin!==`subagent`)return o;let n=e.parentSession;if(typeof n!=`string`||n.length===0||a.has(n))return o;a.add(n),o=n}return o}function yn(e,t,n){let r=L(e,n);return n===`win32`?pn.test(t)||t.startsWith(P+P)?t:`${r}\\${t}`:t.startsWith(`/`)?t:`${r}/${t}`}function bn(e,t,n,r,i){if(n===void 0||n.trim().length===0)return!0;let a=n.trim(),o;try{o=Ve(yn(e,a,i),r,i)}catch{return!1}return R(o,t,r,i)}function xn(e,t,n,r,i){let a=r.platform??`posix`,o=n.kind===`shell`?!nn(e,n.command,i,a):bn(t,e,n.target,i,a),s;if(o&&r.rebuildBypass?.(e)!==!0){let t=r.lookupUnlock(e);if(t!==void 0&&rn(t,r.now()))r.consumeGrep(t);else{let n;n=t===void 0?i.gateNeverSearched:t.grepsLeft<=0?i.gateQuotaExhausted:i.gateUnlockExpired,s=b(i.gateReason,{state:n,indexRoot:e,indexDir:fn,budget:r.grepBudget,windowMin:r.windowMin})}}return s}function Sn(e,t,n,r){let i=gn(e,n.indexProbe,n.findIndexDepth,n.platform??`posix`);return i===void 0?void 0:xn(i,e,t,n,r)}function Cn(e,t,n,r){let i=e.command,a=typeof i==`string`?i:``;return Qt(a,0,n.platform??`posix`)?Sn(t,{kind:`shell`,command:a},n,r):void 0}function wn(e,t,n,r){return Sn(t,{kind:`native`,target:typeof e.path==`string`?e.path:void 0},n,r)}function Tn(e,t,n){let{name:r}=e,i=m(e.arguments)?e.arguments:{},a=z(e),o;return t.enabled&&a!==void 0&&cn(e)&&(r===`bash`||r===`pwsh`?o=Cn(i,a,t,n):r===`grep`&&(o=wn(i,a,t,n))),o}async function En(e){return await e.settled,`settled`}function Dn(e,t,n){return e.size<=t?!1:(n||console.warn(`[zvec-grep] 活跃重建表有 ${String(e.size)} 条,超过阈值 ${String(t)}:这不是容量淘汰(淘汰会让正在跑的重建失去占位,同根就能起第二条 zg),而是有一次 claim 没配对 release —— 请把这段告警连同调用场景报给维护者。`),!0)}function On(e,t,n,r){let i;for(let a of e.values())R(t,a.root,n,r)&&(i===void 0||a.startedAt<i.startedAt)&&(i=a);return i}function kn(e={}){let t=e.now??Date.now,n=e.maxTracked??32,r=e.platform??`posix`,i=new Map,a=e=>{let t=L(e,r);return r===`win32`?t.toLowerCase():t},o=!1;return{claim(e,s,c){let l=a(e);if(i.has(l))return null;let{promise:u,resolve:d}=Promise.withResolvers(),f={root:L(e,r),origin:s,startedAt:c??t(),phase:`starting`,jobId:void 0,settled:u,settle:()=>{d(void 0)}};return i.set(l,f),o=Dn(i,n,o),f},attach(e,t,n){let r=i.get(a(e));return r===void 0||n!==void 0&&n!==r?!1:(r.jobId=t,r.phase=`running`,!0)},release:(e,t)=>{let r=a(e),s=i.get(r);return s===void 0||t!==void 0&&t!==s?!1:(i.delete(r),s.settle(),i.size<=n&&(o=!1),!0)},active(e){return i.get(a(e))},covering(e,t){return On(i,L(e,r),t,r)},async wait(e,t,n,a){let o=On(i,L(e,r),t,r);if(o===void 0)return`settled`;if(a?.aborted===!0)return`aborted`;let{promise:s,resolve:c}=Promise.withResolvers(),l=setTimeout(()=>{c(`timeout`)},Math.max(0,n)),u=()=>{c(`aborted`)};a?.addEventListener(`abort`,u,{once:!0});let d=async n=>{let a=await Promise.race([En(n),s]);if(a!==`settled`)return a;let o=On(i,e,t,r);return o===void 0?`settled`:d(o)};try{return await d(o)}finally{clearTimeout(l),a?.removeEventListener(`abort`,u)}},keys(){return[...i.keys()]}}}async function An(e){try{await e.body?.cancel()}catch{}}async function jn(e,t){let n=AbortSignal.timeout(1e4);try{let r=t(),i={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,...r===void 0?{}:{Authorization:`Bearer ${r}`}},a=await(0,globalThis.fetch)(e,{method:`POST`,headers:i,body:JSON.stringify({jsonrpc:`2.0`,id:0,method:`initialize`,params:{protocolVersion:`2025-06-18`,capabilities:{},clientInfo:{name:`dsh-zvec-grep-readiness-probe`,version:`0.0.0`}}}),signal:n});if(await An(a),a.status!==200)return!1;let o=a.headers.get(`mcp-session-id`);if(o===null)return!1;try{await An(await(0,globalThis.fetch)(e,{method:`POST`,headers:{...i,"mcp-session-id":o},body:JSON.stringify({jsonrpc:`2.0`,method:`notifications/initialized`}),signal:n}))}catch{}return!0}catch{return!1}}function Mn(e,t){let n=0,r=!1,i=!1;return{async ready(){let a=Date.now();return i&&a-n<6e4||(r=await jn(e,t),n=a,i=!0),r},invalidate(){i=!1,r=!1}}}function Nn(e){return typeof e==`object`&&!!e&&typeof e.resolve==`function`}const B={noSession:`no-session`,serviceMissing:`service-missing`,resolveFailed:`resolve-failed`};function Pn(e,t){let n=t.agent?.session;if(n===void 0)return{degrade:B.noSession};let r=e.get(`sandboxPolicy`);if(!Nn(r))return{degrade:B.serviceMissing};try{return{policy:r.resolve({session:n})}}catch{return{degrade:B.resolveFailed}}}function Fn(e,t){return t===void 0?e:{...e,sandboxPolicy:t}}function In(e,t){let{degrade:n}=e;if(n===void 0)return``;let r={[B.noSession]:t.sandboxPolicyNoSession,[B.serviceMissing]:t.sandboxPolicyServiceMissing,[B.resolveFailed]:t.sandboxPolicyResolveFailed};return b(t.sandboxPolicyDegraded,{reason:r[n]})}const Ln=/^ *error\[[a-z][\w.]*\]:/iu;var Rn=class extends Error{aborted;constructor(e,t){super(e),this.name=`DaemonCallFailureError`,this.aborted=t}};const zn=/\boperation=(?<op>\S+)/u,Bn=/\b(?:lock|storage_dir)=(?<lock>\S+)/u;function Vn(e){let t=e.split(`
|
|
66
|
+
`).find(e=>Ln.test(e)),n=t===void 0?-1:t.indexOf(`[`)+1,r=t===void 0?-1:t.indexOf(`]:`,n);return t!==void 0&&n>0&&r>n?t.slice(n,r):void 0}function Hn(e){let t=e.split(`
|
|
67
|
+
`).find(e=>Ln.test(e))??``,n=t.indexOf(`]:`);return n===-1?``:t.slice(n+2).trim()}function Un(e){let t=Vn(e);if(t===`ZG.ENGINE.RESOURCE_BUSY`){let t=Hn(e),n=zn.exec(t)?.groups?.op;return{kind:`lock-busy`,ownerOperation:n,lockPath:Bn.exec(t)?.groups?.lock,rebuild:n===`index.rebuild`}}return t===`ZG.ENGINE.PERMISSION_DENIED`?{kind:`permission-denied`}:null}const V={versionTooOld:`ZG_VERSION_TOO_OLD`,rebuildLockBusy:`ZG_REBUILD_LOCK_BUSY`,lockBusy:`ZG_LOCK_BUSY`,permissionDenied:`ZG_PERMISSION_DENIED`,daemonUnavailable:`ZG_DAEMON_UNAVAILABLE`,rootRejected:`ZG_ROOT_REJECTED`,badArguments:`ZG_BAD_ARGUMENTS`,commandFailed:`ZG_COMMAND_FAILED`};var H=class extends _{constructor(e,t,n){super(t,e,n),this.name=`ZgToolError`}};const Wn={major:0,minor:3,patch:0};function Gn(e){return`${e.major}.${e.minor}.${e.patch}`}const Kn=Gn(Wn),qn=/^\s*v?(?<major>\d{1,9})\.(?<minor>\d{1,9})\.(?<patch>\d{1,9})\s*$/u;function Jn(e,t){let n=e?.groups?.[t];return n===void 0?-1:Number(n)}function Yn(e){let t=qn.exec(e),n=Jn(t,`major`),r=Jn(t,`minor`),i=Jn(t,`patch`);return n<0||r<0||i<0?void 0:{major:n,minor:r,patch:i}}function Xn(e,t){return ee(e,t)}function Zn(e){let t=Yn(e);return t===void 0||Xn(t,Wn)?void 0:t}function Qn(e,t,n){return te(e,{name:`zvec-grep`,description:n,content:t})}const $n=new Set([`ENOENT`,`EACCES`,`EISDIR`,`ENOTDIR`,`ENAMETOOLONG`]);function er(e){if(typeof e!=`object`||!e||!(`code`in e))return!1;let t=e.code;return typeof t==`string`&&$n.has(t)}function tr(e,t,i){if(!k(e.drop,`drop`,i))for(let a of T(e.ignoreFiles,`ignoreFiles`,i)){let e=l.isAbsolute(a)?a:l.resolve(t,a),s=!1;try{n(e,r.R_OK),s=o(e).isFile()}catch(e){if(!er(e))throw e}if(!s)throw Error(b(i.ignoreFileMissing,{path:e}))}}function nr(e,t){let n=e.enforcement===void 0||e.enforcement.trim().length===0?``:b(t.sandboxEnforcement,{value:e.enforcement}),r=typeof e.mode==`string`&&e.mode.trim().length>0?e.mode.trim():`unknown`;return b(t.sandboxFacts,{mode:r,enforcement:n})}function rr(e,t,n){return b(e,{facts:nr(t,n)})}function ir(e,t){return rr(t.sandboxDenied,e,t)}function ar(e,t){let n=e.sandbox;return n===void 0?null:n.runnerFailed===!0?rr(t.rebuildRunnerFailed,n,t):n.denied?b(t.rebuildDenied,{denied:ir(n,t)}):null}function or(e){try{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&t.hostname!==``}catch{return!1}}function sr(e){let t=typeof e==`string`?ht(e.trim()):``;return t.length>0&&or(t)?t:void 0}function cr(e){let t=sr(e.hfEndpoint.get());return t===void 0?void 0:{HF_ENDPOINT:t}}function lr(e){let t=typeof e==`string`?e.trim():``;return t.length>0?t:void 0}function ur(e){return e.allowRemoteEmbedding}const dr=/^[A-Za-z_]\w*$/u;function U(e,t){let n={...cr(e),...t};if(ur(e)){let t=sr(e.remoteEmbeddingEndpoint);t!==void 0&&(n.ZVEC_GREP_ENDPOINT=t);let r=lr(e.remoteEmbeddingApiKeyFrom),i=r!==void 0&&dr.test(r)?process.env[r]:void 0,a=typeof i==`string`?i.trim():void 0;a!==void 0&&a.length>0&&(n.ZVEC_GREP_API_KEY=a)}return Object.keys(n).length>0?n:void 0}function fr(e){let t=e.defaultEmbedding.get();return typeof t==`string`&&be(t)?t.trim():he}function pr(e){return e===`auto`||e===`cli`||e===`mcp`}function mr(e){return typeof e==`string`&&pr(e)?e:`auto`}function hr(e,t){let n=e.trim(),r;try{r=new URL(n)}catch{r=void 0}if(r===void 0||r.protocol!==`http:`&&r.protocol!==`https:`||r.hostname.length===0||r.pathname!==`/mcp`)throw Error(b(t.daemonUrlInvalid,{received:e}));return n}function W(e,t){return ke(e.clientMode,t)}var gr=function(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0},_r=function(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else(d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0};const vr=`zvec-grep-rebuild`,yr=4e3;function br(e){return{kind:e.kind,label:e.label,startedAt:e.startedAt}}function xr(e,t){return e.kind===t.kind&&e.label===t.label&&e.startedAt===t.startedAt}function Sr(e,t){return xr(e.identity,br(t))}function Cr(e,t){return[`stdout`,`stderr`].map(n=>{let r=!1;return{channel:n,read:i=>{if(r)return{text:``,nextOffset:i,lossy:!0};try{let r=e.observed[n].readFrom(i);return r.lossy&&(t.lost=!0),r}catch{return t.lost=!0,r=!0,{text:``,nextOffset:i,lossy:!0}}}}})}function wr(e,t){try{return e.get(t)}catch{return null}}function Tr(e,t){try{return{view:e.get(t),retained:e.readAt(t,0)}}catch{return null}}function Er(e){return e===`running`||e===`stopping`}function G(e){try{e.kill()}catch{}}function Dr(e,t){let n=e.list().filter(e=>e.kind===vr).filter(e=>!Er(e.status)).toSorted((e,t)=>e.startedAt-t.startedAt);for(let r of n.slice(0,Math.max(n.length-9,0)))e.remove(r.id),t.delete(r.id)}const Or=/\(limit: (?<limit>\d+)\)/u;function kr(e){return Or.exec(g(e))?.groups?.limit}function Ar(e,t,n,r){let a;try{a=A(e,n,r)}catch(e){return{error:{value:b(n.endpointRootInvalid,{reason:g(e)}),status:400}}}return t.has(a)?i(a)?{root:a}:{error:{value:b(n.endpointRootGone,{root:a}),status:400}}:{error:{value:b(n.endpointRootUntracked,{root:a}),status:403}}}function jr(e,t,n){return[...t.values()].find(t=>{if(t.root!==n)return!1;let r=wr(e,t.id);return r!==null&&Sr(t.state,r)&&Er(r.status)})?.id}function Mr(e,t){let n=kr(e);return n===void 0?b(t.endpointStartFailed,{reason:g(e)}):b(t.endpointJobsAtCapacity,{limit:n})}function Nr(e,t){let n=e.attachController(`zvec-grep: rebuild`);try{return e.start(t)}finally{n()}}function Pr(e){let{routes:t,proc:n,state:r,command:i,root:a,claimed:o}=e,{config:s,host:c,jobsOf:l,messages:u}=t;return{kind:vr,label:i,output:Cr(n,r),run:e=>{let i=()=>{let t=l();if(t===void 0)return null;let n=wr(t,e.id);return n===null||!Sr(r,n)?null:{jobs:t,status:n.status}},d=c.timer.timeout(()=>{if(n.status!==`running`)return;let t=i();if(t!==null&&t.status!==`running`)return;let a=Math.max(1,Math.ceil(s.indexTimeoutMs/6e4));if(r.timeoutNote=b(u().rebuildTimeout,{minutes:a}),t===null)G(n);else try{t.jobs.kill(e.id,void 0,b(u().jobReasonTimeout,{minutes:a}))}catch{G(n)}},s.indexTimeoutMs);return{cancel:()=>{G(n)},done:(async()=>{try{return await n.done,le(n)}finally{d(),t.rebuilds.release(a,o)}})()}}}}async function Fr(e,t,n,r,i){let{config:a,host:o}=e,s;try{await e.versionGate.ensure(t);let{platform:c}=e;tr(n,A(n.root,t,c),t);let l=ft({...n,platform:c},r,t,W(a,t),ur(a)),u=U(a,e.daemonEnv?.()),d=o.shell.resolve({command:l.command,workdir:l.workdir,onExpiry:`none`,stdoutMaxBytes:a.stdoutMaxBytes,...u?{env:u}:{},...i===void 0?{}:{sandboxPolicy:i}});s={proc:await o.shell.execute(d),command:l.command}}catch(e){return{error:b(t.endpointStartFailed,{reason:g(e)}),status:500}}return s}function Ir(e,t,n,r,i){let{jobsOf:a,records:o}=e,{proc:s,command:c}=r,l=a();if(l===void 0)return G(s),{error:n.endpointJobsUnavailable,status:503};try{Dr(l,o)}catch(e){return G(s),{error:Mr(e,n),status:500}}let u={identity:{kind:vr,label:c,startedAt:0},lost:!1,timeoutNote:null},d;try{d=Nr(l,Pr({routes:e,proc:s,state:u,command:c,root:t,claimed:i})),u.identity=br(l.get(d)),o.set(d,{proc:s,root:t,id:d,state:u})}catch(e){return G(s),{error:Mr(e,n),status:500}}return{jobId:d}}function Lr(e){let{jobsOf:t,messages:n,records:r}=e,i=n().jobReasonUnload,a=t();if(a===void 0)for(let e of r.values())G(e.proc);else for(let e of r.values())try{let t=wr(a,e.id);t===null||!Sr(e.state,t)?G(e.proc):Er(t.status)?a.kill(e.id,void 0,i):a.remove(e.id)}catch{G(e.proc)}r.clear()}let Rr=(()=>{let e=ce,t=[],n,r,i;return class extends e{static{let a=typeof Symbol==`function`&&Symbol.metadata?Object.create(e[Symbol.metadata]??null):void 0;n=[se(`roots`)],r=[se(`rebuild`)],i=[se(`status`)],_r(this,null,n,{kind:`method`,name:`roots`,static:!1,private:!1,access:{has:e=>`roots`in e,get:e=>e.roots},metadata:a},null,t),_r(this,null,r,{kind:`method`,name:`rebuild`,static:!1,private:!1,access:{has:e=>`rebuild`in e,get:e=>e.rebuild},metadata:a},null,t),_r(this,null,i,{kind:`method`,name:`status`,static:!1,private:!1,access:{has:e=>`status`in e,get:e=>e.status},metadata:a},null,t),a&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})}constructor(e,n){super(e,`zvecGrepRebuild`),gr(this,t),this.deps=n}async roots(){let e=!1;try{e=await this.deps.serverGate.ready()}catch{}return{roots:this.deps.ledger.list(),serverReady:e}}async rebuild(request){let e=this.deps.messages(),t=Ar(m(request)?request.root:void 0,this.deps.ledger,e,this.deps.platform);if(`error`in t)return{ok:!1,error:t.error.value,status:t.error.status};let{root:n}=t,r=this.deps.jobsOf();if(r===void 0)return{ok:!1,error:e.endpointJobsUnavailable,status:503};let i=this.deps.rebuilds.claim(n,`card`);if(i===null){let t=jr(r,this.deps.records,n);return t===void 0?{ok:!1,error:e.endpointRebuildInFlight,status:409}:{ok:!0,jobId:t,reused:!0}}let a=fr(this.deps.config),o=await Fr(this.deps,e,{root:n,embedding:a,rebuild:!0},a);if(`error`in o)return this.deps.rebuilds.release(n,i),{ok:!1,error:o.error,status:o.status};let s=Ir(this.deps,n,e,o,i);return`error`in s?(this.deps.rebuilds.release(n,i),{ok:!1,error:s.error,status:s.status}):(this.deps.rebuilds.attach(n,s.jobId,i),{ok:!0,jobId:s.jobId})}status(request){let e=this.deps.messages(),t=m(request)?request.jobId:void 0,n=typeof t==`string`&&t.length>0?this.deps.records.get(t):void 0;if(n===void 0)return{ok:!1,error:b(e.unknownJobId,{maxJobs:10}),status:404};let r=this.deps.jobsOf();if(r===void 0)return{ok:!1,error:e.endpointJobsUnavailable,status:503};let i=Tr(r,n.id);if(i===null||!Sr(n.state,i.view))return{ok:!1,error:b(e.unknownJobId,{maxJobs:10}),status:404};let{view:a,retained:o}=i,s=o.chunks.map(e=>e.text).join(``),c=v(s,yr),l=s.length>yr?b(e.jobOutputView,{shown:yr,total:s.length}):``;return{ok:!0,status:a.status,exitCode:n.proc.exitCode,root:n.root,...n.proc.sandbox===void 0?{}:{sandbox:n.proc.sandbox},output:(a.output.earliest>0?e.jobOutputTruncated:``)+(n.state.lost?e.jobOutputLost:``)+(n.state.timeoutNote??``)+(ar(n.proc,e)??``)+l+c}}}})();function zr(e,t){return!m(e)||!m(e.reflect)||typeof e.reflect.provide!=`function`?!1:(new Rr(e,t),e.effect(()=>()=>{Lr(t)},`zvec-grep: rebuild records`),!0)}const Br=/^[\u0021-\u007E]{32,}$/u;function Vr(e=process.env){let t=e.ZVEC_GREP_HOME??l.join(s(),`.zvec-grep`);return l.join(t,`dsh-zvec-grep.token`)}async function Hr(e){let t;try{let n=(await de(e,`utf8`)).trim();t=Br.test(n)?n:void 0}catch{}return t}async function Ur(e,t){try{return await me(e,t,{mode:384}),!0}catch{return!1}}function Wr(e){return typeof e==`object`&&!!e&&e.code===`EEXIST`}async function Gr(e,t){let n=await Hr(e);if(n!==void 0||t<=1)return n;let{promise:r,resolve:i}=Promise.withResolvers();return setImmediate(()=>{i(void 0)}),await r,Gr(e,t-1)}async function Kr(e,t){try{await ue(l.dirname(e),{recursive:!0})}catch{return{token:t,owned:!1}}try{return await pe(e,t,{mode:384,flag:`wx`}),{token:t,owned:!0}}catch(e){if(!Wr(e))return{token:t,owned:!1}}let n=await Gr(e,3);if(n!==void 0)return{token:n,owned:!1};try{await fe(e,{force:!0})}catch{return{token:t,owned:!1}}return{token:t,owned:await Ur(e,t)}}async function qr(e){try{await fe(e,{force:!0})}catch{}}const Jr=new Set([400,404,405]);function Yr(e){let t=[];for(let n of e.split(`
|
|
68
|
+
`)){let e=n.trim(),r=e.startsWith(`data:`)?e.slice(5).trim():``;if(r.length>0)try{t.push(JSON.parse(r))}catch{}}return t}function Xr(e,t){if(e.includes(`text/event-stream`))return Yr(t);try{return[JSON.parse(t)]}catch{return[]}}function Zr(e,t){let n=e.find(e=>m(e)&&e.id===t);return m(n)?n:void 0}function Qr(e){return(m(e)&&Array.isArray(e.content)?e.content:[]).map(e=>m(e)&&e.type===`text`?e.text:void 0).filter(e=>typeof e==`string`).join(`
|
|
69
|
+
`)}var K=class extends Error{constructor(e){super(e),this.name=`DaemonProtocolError`}};function $r(e){let t=e.tokenOf();return t===void 0?{}:{Authorization:`Bearer ${t}`}}function ei(e,t){let n={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,...$r(e)};return t!==void 0&&(n[`mcp-session-id`]=t),n}function ti(e){let t=Error(e);return t.name=`AbortError`,t}async function ni(e,t,n,r,i){if(r?.aborted===!0)throw ti(`The operation was aborted`);let a=n-Date.now();if(a<=0)throw ti(`daemon call budget exhausted`);let o=new AbortController,s=setTimeout(()=>{o.abort()},a),c=()=>{o.abort()};r?.addEventListener(`abort`,c);try{let n=await e.doFetch(e.url,{method:`POST`,headers:ei(e,i),body:JSON.stringify(t),signal:o.signal}),r=await n.text(),a=n.headers.get(`mcp-session-id`)??void 0;return{status:n.status,sessionId:a,payloads:Xr(n.headers.get(`content-type`)??``,r)}}finally{clearTimeout(s),r?.removeEventListener(`abort`,c)}}async function ri(e,t,n,r){if(t.id!==void 0)return;let i=await ni(e,{jsonrpc:`2.0`,id:0,method:`initialize`,params:{protocolVersion:`2025-06-18`,capabilities:{},clientInfo:{name:e.clientName,version:`0.0.0`}}},n,r,void 0);if(i.status!==200)throw Error(`initialize failed with HTTP ${i.status}`);if(t.id=i.sessionId,t.id===void 0)throw Error(`daemon did not issue an mcp-session-id`);await ni(e,{jsonrpc:`2.0`,method:`notifications/initialized`},n,r,t.id)}function ii(e){let t=e.sessions.find(e=>!e.busy);if(t!==void 0)return t.busy=!0,t;let n={id:void 0,busy:!0};return e.sessions.push(n),n}function q(e,t,n){if(!n){e.sessions=e.sessions.filter(e=>e!==t);return}t.busy=!1;let r=e.sessions.filter(e=>!e.busy);if(r.length>8){let t=new Set(r.slice(0,r.length-8));e.sessions=e.sessions.filter(e=>!t.has(e))}}async function ai(e,t,n,r,i){await ri(e,t,i,n.signal);let{status:a,payloads:o}=await ni(e,{jsonrpc:`2.0`,id:r,method:`tools/call`,params:{name:n.tool,arguments:n.args}},i,n.signal,t.id);if(Jr.has(a))throw Error(`daemon rejected the session (HTTP ${a})`);if(a!==200)throw new K(`tools/call failed with HTTP ${a}`);let s=Zr(o,r);if(s===void 0)throw new K(`tools/call reply missing from response`);if(m(s.error))throw new K(JSON.stringify(s.error));let{result:c}=s;return{text:Qr(c),isError:m(c)&&c.isError===!0}}function oi(e){let t={url:e.url,doFetch:e.fetchImpl??globalThis.fetch.bind(globalThis),clientName:e.clientName??`dsh-zvec-grep`,tokenOf:e.tokenOf,sessions:[]};return{call:async e=>{let n=Date.now()+e.timeoutMs,r=ii(t);try{let i=await ai(t,r,e,1,n);return q(t,r,!0),i}catch(i){if(m(i)&&i.name===`AbortError`)throw q(t,r,!1),i;if(i instanceof K)throw q(t,r,!0),i;q(t,r,!1);let a=ii(t);try{let r=await ai(t,a,e,3,n);return q(t,a,!0),r}catch(e){throw q(t,a,e instanceof K),e}}}}}const si={short:`short`,full:`full`};function ci(e,t){let n=Me(e,t);return n===`none`||n===`short`?si.short:si.full}function li(e,t,n){let r=C(t.query,`query`,n,x);r.length>0&&(e.query=r);let i=w(t.queries,`queries`,n,32,x);i.length>0&&(e.queries=i);let a=w(t.fts,`fts`,n,32,x);a.length>0&&(e.fts=a);let o=w(t.vector,`vector`,n,32,x);o.length>0&&(e.vector=o),k(t.fuse,`fuse`,n)&&(e.fuse=!0)}function ui(e,t,n){let r=T(t.globs,`globs`,n);r.length>0&&(e.globs=r);let i=T(t.insensitiveGlobs,`insensitiveGlobs`,n);i.length>0&&(e.insensitiveGlobs=i);let a=T(t.fileTypes,`fileTypes`,n);a.length>0&&(e.fileTypes=a);let o=T(t.excludedFileTypes,`excludedFileTypes`,n);o.length>0&&(e.excludedFileTypes=o);let s=T(t.category,`category`,n);s.length>0&&(e.categories=s);let c=T(t.categoryNot,`categoryNot`,n);c.length>0&&(e.excludedCategories=c);let l=Re(t.symbolTypes,n);l.length>0&&(e.symbolTypes=l),k(t.preferSymbol,`preferSymbol`,n)&&(e.preferSymbol=!0),k(t.trace,`trace`,n)&&(e.trace=!0);let u=C(t.modifiedAfter,`modifiedAfter`,n,128);u.length>0&&(e.modifiedAfter=u);let d=C(t.modifiedBefore,`modifiedBefore`,n,128);d.length>0&&(e.modifiedBefore=d)}function di(e,t){if(C(e.device,`device`,t,1024).length>0)throw Error(t.deviceUnsupportedOnDaemon);let n={root:e.root,limit:j(e.limit,t),preview:ci(e.preview,t)};li(n,e,t);let r=Fe(e.refresh,t);return r===`wait`?n.freshness=`wait_for_fresh`:(n.freshness=`eventual`,n.autoUpdate=r===`background`),ui(n,e,t),n}const fi=864e5;function J(e,t,n){let r=e[t];return m(r)&&n.every(e=>typeof r[e]==`function`)}function pi(e){return m(e)?J(e,`settings`,[`describe`])&&J(e,`shell`,[`resolve`,`execute`])&&J(e,`tools`,[`register`,`guard`])&&J(e,`systemPrompt`,[`section`])&&J(e,`timer`,[`timeout`])&&typeof e.get==`function`:!1}function mi(e){return JSON.stringify(e,null,2)}function hi(e){let{text:t}=m(e)?e:{};if(typeof t==`string`)return[{type:`text`,text:t}];let n;try{n=mi(e)??String(e)}catch{try{n=String(e)}catch{n=`[unrenderable value]`}}return[{type:`text`,text:n}]}const gi={type:`object`,additionalProperties:!1,properties:{text:{type:`string`}}};function _i(e,t){let n=e.sandbox;return n?.runnerFailed===!0?rr(t.runnerFailed,n,t):null}function vi(e,t){let n=e.stderr.text.length>0?e.stderr.text:e.stdout.text;return n.length<=800?n:b(t.detailMiddle,{head:ae(n,400),tail:v(n,400)})}function yi(e,t){return e.length>0?b(t,{detail:e}):``}const bi=/^\s*error\[/imu;function xi(e,t){return e.length===0||bi.test(e)?``:`\n${t.noErrorCodeHint}`}function Si(e,t){let n=_i(e,t);if(n!==null)return n;if(e.timedOut)return t.timeoutFailure;if(e.aborted)return t.abortedFailure;if(e.exitCode===0)return null;let r=vi(e,t),{sandbox:i}=e;return i?.denied===!0?b(t.deniedFailure,{exit:e.exitCode,denied:ir(i,t),detail:yi(r,t.detailPrefix)}):e.exitCode===127?b(t.notInstalledFailure,{detail:yi(r,t.detailPrefix)}):`${b(t.genericFailure,{exit:e.exitCode,detail:yi(r,t.detailColon)})}${xi(r,t)}`}const Ci=[`Preparing model:`,`Downloading model:`,`Model ready:`,`Scanning`,`Indexing:`,`Files processed:`,`Optimizing index`,`Saving index`,`Finishing index`];function wi(e){let t=e.trim();return Ci.some(e=>t.startsWith(e))}function Ti(e){return e.split(`
|
|
70
|
+
`).filter(e=>e.trim().length>0&&!wi(e)).join(`
|
|
71
|
+
`)}function Ei(e,t,n){let r=[];if(e.stdout.truncated){let i=e.stdout.spillPath===void 0?``:b(t.spillNote,{path:e.stdout.spillPath});r.push(b(t.outputTruncated,{maxBytes:n,spill:i}))}let{sandbox:i}=e;i?.denied===!0&&r.push(b(t.sandboxWarning,{denied:ir(i,t)}));let{stderr:a}=e,o=Ti(a.text);if(o.length>0){let e=v(o,400),n=a.truncated?`[…]`:``;r.push(b(t.stderrNote,{marked:n,tail:e}))}return r}function Di(e,t){return new H(V.versionTooOld,b(t.zgVersionTooOld,{actual:Gn(e),minimum:Kn}))}async function Oi(e,t,n){let r;try{let i=n(),a=U(t,i===void 0?void 0:{ZVEC_GREP_SERVER_TOKEN:i}),o=e.shell.resolve({command:`zg --version`,workdir:c(),timeoutMs:1e4,stdoutMaxBytes:t.stdoutMaxBytes,...a?{env:a}:{}}),s=await(await e.shell.execute(o)).result();r=s.exitCode===0?s.stdout.text:void 0}catch{r=void 0}return r===void 0?void 0:Zn(r)}function ki(e,t,n){let r=0,i;return{async ensure(a){let o=Date.now();if(o-r<6e5){if(i!==void 0)throw Di(i,a);return}let s=await Oi(e,t,n);if(r=o,i=s,s!==void 0)throw Di(s,a)}}}const Ai=15e3;function Y(e,t){return t===void 0||t.length===0?e:e.replaceAll(t,`[token]`)}function ji(e){let t=new URL(e),n=t.protocol===`https:`?`443`:`80`;return`${t.hostname}:${t.port===``?n:t.port}`}function Mi(e){let{host:n,config:r,daemonUrl:i,tokenFile:a,tokenOf:o,setToken:s,markStarted:l,serverGate:u}=e,d,f=!1,p=async e=>{let t=ji(i),a=t===`127.0.0.1:7999`?`zg --server on`:`zg --server on --listen ${t}`,o;try{let t=U(r,{ZVEC_GREP_SERVER_TOKEN:e}),i=n.shell.resolve({command:a,workdir:c(),timeoutMs:Ai,stdoutMaxBytes:r.stdoutMaxBytes,env:t}),s=await(await n.shell.execute(i)).result();s.exitCode!==0&&(o=Y(s.stderr.text.trim().length>0?s.stderr.text.trim():`exit ${s.exitCode}`,e))}catch(t){o=Y(g(t),e)}return o},m=async e=>{if(await u.ready()){if(o()===void 0){let e=await Hr(a);e!==void 0&&s(e)}return}let n=o();if(n===void 0){let{token:e,owned:r}=await Kr(a,t(24).toString(`hex`));n=e,f=r,s(n)}let r=await p(n),i=await Hr(a)??n;if(i!==n&&s(i),u.invalidate(),await u.ready())r===void 0&&f&&i===n&&l();else throw s(void 0),f=!1,new H(V.daemonUnavailable,b(e.daemonStartFailed,{detail:r??`zg --server on exited 0 but the readiness probe still fails (another daemon may be using a different token)`}))};return{tokenOf:o,async ensure(e){return d===void 0&&(d=(async()=>{try{await m(e)}finally{d=void 0}})()),d}}}function Ni(e){let{host:t,config:n,tokenFile:r,daemonEnv:i,startedByUs:a}=e;t.effect(()=>async()=>{if(!a())return;let e=i();if(e!==void 0)try{let i=t.shell.resolve({command:`zg --server off`,workdir:c(),timeoutMs:Ai,stdoutMaxBytes:n.stdoutMaxBytes,env:e});(await(await t.shell.execute(i)).result()).exitCode===0&&await qr(r)}catch{}},`zvec-grep: daemon shutdown`)}const Pi=/^\s*#\d+\s+(?<rest>\S.*)$/u;function Fi(e){return e!==void 0&&(e>=9&&e<=13||e===32||e===160||e===5760||e>=8192&&e<=8202||e===8232||e===8233||e===8239||e===8287||e===12288||e===65279)}function Ii(e){return e!==void 0&&e>=48&&e<=57}function Li(e){let t=e.lastIndexOf(`score=`);if(t===-1)return e;let n=t+6;e[n]===`-`&&(n+=1);let r=n;for(;Ii(e.codePointAt(n));)n+=1;if(n===r)return e;if(e[n]===`.`){n+=1;let t=n;for(;Ii(e.codePointAt(n));)n+=1;if(n===t)return e}if(n!==e.length)return e;let i=t;for(;Fi(e.codePointAt(i-1));)--i;return i===t?e:e.slice(0,i)}function Ri(e,t,n,r){let i=new Set;for(let t of e.split(`
|
|
72
|
+
`)){let e=Pi.exec(t)?.groups?.rest;e!==void 0&&i.add(Li(e))}return i.size===0?null:b(r.hitSummary,{unique:i.size,limit:t,truncated:n?r.hitTruncated:``})}var zi=class extends H{constructor(e){super(V.rebuildLockBusy,e),this.name=`RebuildLockBusyError`}};function Bi(e,t,n,r){let i=n===null?t:[...t,n],a=r===``?i:[...i,r];return a.length>0?`${e}\n${a.join(`
|
|
73
|
+
`)}`:e}async function Vi(e,t,n,r,i){let a=e.shell.resolve(Fn({command:t,workdir:n,timeoutMs:r,stdoutMaxBytes:i.stdoutMaxBytes,signal:i.signal,...i.env?{env:i.env}:{}},i.sandboxPolicy)),o=await(await e.shell.execute(a)).result(),s=i.env?.ZVEC_GREP_SERVER_TOKEN,c=Si(o,i.messages),l=c===null?null:Y(c,s);if(l!==null){let e=i.resolveFailure?.(l,o)??null;if(e!==null)return e;let t=Un(o.stderr.text);throw t?.kind===`lock-busy`&&t.rebuild?new zi(l):t?.kind===`lock-busy`?new H(V.lockBusy,`${b(i.messages.lockBusyOtherOperation,{op:t.ownerOperation??`unknown`})}\n${l}`):t?.kind===`permission-denied`?new H(V.permissionDenied,`${l}\n${i.messages.remoteAuthDenied}`):new H(V.commandFailed,l)}let u=Ei(o,i.messages,i.stdoutMaxBytes).map(e=>Y(e,s)),d=Y(o.stdout.text,s);return Bi(d,u,i.summaryLimit===void 0?null:Ri(d,i.summaryLimit,o.stdout.truncated,i.messages),i.sandboxDegradeNote)}function Hi(e,t){return b(t.rebuildWaitAborted,{root:e})}function Ui(e,t,n){return b(n.rebuildWaitTimeout,{root:e,seconds:Math.round(t/1e3)})}async function Wi(e,t,n,r){try{return await r()}catch(i){let a=e.rebuilds.covering(e.root,t);if(!(i instanceof zi)||a===void 0)throw i;let o=await e.rebuilds.wait(e.root,t,e.maxWaitMs,n);if(o===`settled`)return r();throw new H(V.lockBusy,o===`aborted`?Hi(a.root,t):Ui(a.root,e.maxWaitMs,t),{cause:i})}}async function Gi(e,t,n,r,i){let a={signal:i.signal,env:i.env,stdoutMaxBytes:i.stdoutMaxBytes,messages:i.messages,summaryLimit:i.summaryLimit,sandboxPolicy:i.sandboxPolicy,sandboxDegradeNote:i.sandboxDegradeNote,resolveFailure:i.resolveFailure},o=i.rebuildWait;return o===void 0?Vi(e,t,n,r,a):Wi(o,i.messages,i.signal,()=>Vi(e,t,n,r,a))}function Ki(e,t){if(!i(e))throw new H(V.rootRejected,b(t.rootMissing,{root:e}));return e}function qi(e){return e.defaultLimit.get()??10}function Ji(e){return e.grepBudgetPerSearch.get()??3}function Yi(e){return e.unlockWindowMin.get()??10}function Xi(e){return e.enforceSearchFirst.get()??!0}function Zi(e){let t=e;return e.startsWith(`\\\\?\\UNC\\`)?t=`\\\\${e.slice(8)}`:e.startsWith(`\\\\?\\`)&&(t=e.slice(4)),gt(t.replaceAll(`/`,`\\`)).toLowerCase()}function X(e,t=process.platform){return t===`win32`?Zi(e):t===`darwin`&&e.startsWith(`/private/`)?e.slice(8):e}function Qi(e,t,n){let r;try{r=JSON.parse(a(e,`utf8`))}catch{return!1}if(!m(r))return!1;let i=r.indexVersion;if(typeof i!=`number`||!Number.isSafeInteger(i)||i<2)return!1;let{sourceRoot:o}=r;if(!m(o))return!1;let s=o.recordedPath;return typeof s==`string`&&s.length>0&&X(L(s,n),process.platform)===X(L(t,n),process.platform)}function $i(e,t=`posix`){let n=l.join(e,fn),r=l.join(n,`manifest.json`);return!i(n)||!i(r)?!1:Qi(r,e,t)}function ea(e,t,n,r,i){let a;try{a=Ki(He(e,t,n,i),n)}catch(e){return{allowed:!1,reason:g(e)}}return t!==void 0&&X(L(a,i),process.platform)===X(L(t,i),process.platform)||r.has(a)?{allowed:!0,root:a,question:void 0}:t!==void 0&&an(a,t,n,i)?{allowed:!0,root:a,question:{root:a,cwd:t}}:{allowed:!1,reason:b(n.rootNotAuthorized,{root:a,cwd:t??n.rootNoSession})}}function ta(e,t,n,r,i){let a=ea(e.root,z(t),n,r,i);if(!a.allowed)throw new H(V.rootRejected,a.reason);return r.add(a.root),a.root}function na(e,t,n){return(t?e*2+n:e)+6e4}function ra(e,t){let{root:n}=e;return typeof n==`string`&&n.length>0?n:t}function ia(e){let{query:t,queries:n,fts:r,root:i}=e;return typeof t==`string`&&t.length>0?t:Array.isArray(n)&&typeof n[0]==`string`&&n[0].length>0?n[0]:Array.isArray(r)&&typeof r[0]==`string`&&r[0].length>0?r[0]:typeof i==`string`&&i.length>0?i:`zg_search`}function aa(e,t){let{parameters:n}=t,r=Array.isArray(n.required)?n.required.filter(e=>typeof e==`string`):[];e.tools.register({name:t.name,description:t.description,parameters:n,timeoutMs:t.timeoutMs,presentCall:e=>t.presentCall(m(e)?e:{}),isConcurrencySafe:()=>t.concurrencySafe,output:{schema:gi,render:(e,t)=>hi(t)},execute:async(e,n)=>{let i=t.messages();if(!m(e))throw new H(V.badArguments,b(i.argsMustBeObject,{name:t.name,received:e===null?`null`:typeof e}));let a=r.filter(t=>e[t]===void 0);if(a.length>0)throw new H(V.badArguments,b(i.missingRequiredArgs,{name:t.name,fields:a.join(`, `)}));return await t.run(e,n,i)}})}const oa=e.object({defaultEmbedding:e.string().default(he).volatile(),defaultLimit:e.natural().min(1).max(50).default(10).volatile(),hfEndpoint:e.string().default(`https://modelscope.cn/models`).volatile(),enforceSearchFirst:e.boolean().default(!0).volatile(),grepBudgetPerSearch:e.natural().min(1).max(20).default(3).volatile(),unlockWindowMin:e.natural().min(1).max(240).default(10).volatile(),searchTimeoutMs:e.natural().min(1).default(3e5),statusTimeoutMs:e.natural().min(1).default(6e4),indexTimeoutMs:e.natural().min(1).default(6e5),stdoutMaxBytes:e.natural().min(1).default(4e5),clientMode:e.union([`auto`,`direct`,`server`]).default(E),transport:e.union([`auto`,`cli`,`mcp`]).default(`auto`).volatile(),daemonUrl:e.string().default(`http://127.0.0.1:7999/mcp`),rebuildWaitMs:e.natural().min(1).default(12e4),allowRemoteEmbedding:e.boolean().default(!1),remoteEmbeddingEndpoint:e.string().default(``),remoteEmbeddingApiKeyFrom:e.string().default(``),requireApprovalForExplicitRoot:e.boolean().default(!1)});function sa(e,t,n){let r;try{r=A(e,t,n)}catch{r=void 0}return r===void 0||n!==`win32`?r:r.toLowerCase()}function ca(e,t,n,r){for(let[t,i]of e){let a=n(i);a!==void 0&&a<=r&&e.delete(t)}for(let n of e.keys()){if(e.size<=t)break;e.delete(n)}}function Z(e,t,n){e.delete(t),e.set(t,n)}const la=6e4,ua=32;function da(e,t=Date.now,n=la,r=32){let i=new Map,a=e=>{i.delete(e)},o=a=>{let o=t(),s=i.get(a);if(s!==void 0&&o-s.probedAt<n)return Z(i,a,s),s.result;let c=e(a);return i.delete(a),i.set(a,{result:c,probedAt:o}),ca(i,r,e=>e.probedAt+n,o),c};return o.invalidate=a,o}function fa(e,t=64,n=Date.now,r=fi,i=`posix`){let a=new Map;return{add(o){let s=sa(o,e,i);s!==void 0&&(Z(a,s,{root:o,seenAt:n()}),ca(a,t,e=>e.seenAt+r,n()))},has(t){let o=sa(t,e,i);if(o===void 0)return!1;let s=a.get(o);return s===void 0||n()-s.seenAt>=r?!1:(Z(a,o,s),!0)},list(){let e=n();return[...a.values()].filter(t=>e-t.seenAt<r).map(e=>e.root)}}}function pa(e){e.inject([`settings`],t=>{t.effect(()=>t.settings.configure({auto:!1},e.fiber))})}function ma(e){return()=>re(Ce,ie(e.settings.describe().find(e=>e.ns===ne)?.value))}function Q(e,t){let n=z(t);n!==void 0&&e.add(n)}function ha(){}function ga(e,t){return vn(t,e.sessionParent)}function _a(e,t=Date.now,n=`posix`){let r=new Map;return{grant(i,a){let o=r.get(i);o===void 0&&(o=new Map,r.set(i,o)),o.set(L(a,n),{grepsLeft:Ji(e),expiresAt:t()+Yi(e)*6e4}),Z(r,i,o),ca(r,256,ha,t())},lookup(e,i){let a=r.get(e),o=a===void 0?void 0:a.get(L(i,n));return a!==void 0&&o!==void 0&&o.expiresAt>t()&&Z(r,e,a),o},consume(e){--e.grepsLeft}}}function $(e){return{oneOf:[{type:`string`},{type:`array`,items:{type:`string`}}],description:e}}function va(e,t){return{type:`string`,enum:[...e],description:t}}function ya(e){return{type:`object`,properties:{root:{type:`string`,description:e.rootSearchDescription},query:{type:`string`,description:e.queryDescription},queries:{type:`array`,items:{type:`string`},description:e.queriesDescription},fts:{type:`array`,items:{type:`string`},description:e.ftsDescription},vector:{type:`array`,items:{type:`string`},description:e.vectorDescription},fuse:{type:`boolean`,description:e.fuseDescription},rg:{type:`boolean`,description:e.rgDescription},limit:{type:`integer`,description:e.limitDescription},preview:va(Ae,e.previewDescription),refresh:va(Ne,e.refreshDescription),globs:$(e.globsDescription),insensitiveGlobs:$(e.insensitiveGlobsDescription),fileTypes:$(e.fileTypesDescription),excludedFileTypes:$(e.excludedFileTypesDescription),symbolTypes:{type:`array`,items:{type:`string`,enum:[...O]},description:e.symbolTypesDescription},preferSymbol:{type:`boolean`,description:e.preferSymbolDescription},trace:{type:`boolean`,description:e.traceDescription},modifiedAfter:{type:`string`,description:e.modifiedAfterDescription},modifiedBefore:{type:`string`,description:e.modifiedBeforeDescription},device:{type:`string`,description:e.deviceDescription},files:{type:`boolean`,description:e.filesDescription},category:$(e.categoryDescription),categoryNot:$(e.categoryNotDescription)}}}function ba(e,t,n){return e?`files`:t===void 0?n?`indexed`:`exhaustive`:t?`exhaustive`:`indexed`}async function xa(e,t,n,r){return!r||!Ie(t)?`daemon-down`:n===`direct`?`mode-direct`:await e.serverGate.ready()?`available`:`daemon-down`}async function Sa(e,t){let n=mr(e.config.transport.get());return n===`mcp`?(await e.daemon.ensure(t),`mcp`):n===`cli`?`cli`:await e.serverGate.ready()?`mcp`:`cli`}function Ca(e,t){if(e.length<=800)return e;let n=ae(e,400),r=v(e,400);return b(t.detailMiddle,{head:n,tail:r})}function wa(e,t){let n=b(t.genericFailure,{exit:1,detail:yi(Ca(e,t),t.detailColon)}),r=Un(e);return r?.kind===`lock-busy`&&r.rebuild?new zi(n):r?.kind===`lock-busy`?new H(V.lockBusy,`${b(t.lockBusyOtherOperation,{op:r.ownerOperation??`unknown`})}\n${n}`):r?.kind===`permission-denied`?new H(V.permissionDenied,`${n}\n${t.remoteAuthDenied}`):new H(V.commandFailed,n)}function Ta(e,t,n,r){if(!(m(e)&&e.name===`AbortError`)){let t=Y(g(e),r);return new H(V.daemonUnavailable,b(n.mcpCallFailed,{detail:t}),{cause:e})}return new H(V.daemonUnavailable,t.signal.aborted?n.abortedFailure:n.timeoutFailure)}function Ea(e,t,n,r){let i=Buffer.byteLength(e,`utf8`)>t,a=i?v(e,t):e,o=[];i&&o.push(b(r.outputTruncated,{maxBytes:t,spill:``}));let s=Ri(a,n,i,r);return s!==null&&o.push(s),o.length>0?`${a}\n${o.join(`
|
|
74
|
+
`)}`:a}async function Da(e,t,n,r,i){let{config:a}=e,o=di(t,n),s=j(t.limit,n);return Wi(i,n,r.signal,async()=>{let t,i;try{({text:t,isError:i}=await e.daemonClient.call({tool:`zvec_grep_search`,args:o,timeoutMs:a.searchTimeoutMs,signal:r.signal}))}catch(t){let i=m(t)&&t.name===`AbortError`;throw i||e.serverGate.invalidate(),new Rn(Ta(t,r,n,e.daemon.tokenOf()).message,i)}if(i)throw wa(Y(t,e.daemon.tokenOf()),n);return Ea(t,a.stdoutMaxBytes,s,n)})}async function Oa(e,t,n,r,i){if(await Sa(e,n)!==`mcp`)return{text:void 0,fallbackNote:void 0};try{return{text:await Da(e,t,n,r,i),fallbackNote:void 0}}catch(a){let o=mr(e.config.transport.get());if(a instanceof Rn&&!a.aborted&&o===`mcp`)return await e.daemon.ensure(n),{text:await Da(e,t,n,r,i),fallbackNote:void 0};if(!(a instanceof Rn)||a.aborted||o!==`auto`)throw a;return{text:void 0,fallbackNote:b(n.daemonFallbackNote,{detail:a.message})}}}async function ka(e,t,n,r){let{config:i,host:a,indexProbe:o,ledger:s,unlocks:c}=e;Q(s,n);let l=ta(t,n,r,s,e.platform),u=gn(l,o,void 0,e.platform),d=t.rg===void 0||t.rg===null?void 0:k(t.rg,`rg`,r),f=ba(k(t.files,`files`,r),d,u!==void 0),p=f===`exhaustive`&&d===void 0&&u===void 0?r.exhaustiveFallbackNote:void 0,m={...t,root:l,platform:e.platform,...f===`files`?{}:{limit:t.limit??qi(i)}};await e.versionGate.ensure(r);let h;if(f===`indexed`){let t=await Oa(e,m,r,n,{root:l,rebuilds:e.rebuilds,maxWaitMs:i.rebuildWaitMs});if(h=t.fallbackNote,t.text!==void 0)return u!==void 0&&c.grant(ga(e,n),u),{text:t.text}}let g=W(i,r),{command:_,workdir:ee}=et(m,r,g,f,await xa(e,t.refresh,g,f===`indexed`)),te=Pn(a,n),ne=await Gi(a,_,ee,i.searchTimeoutMs,{signal:n.signal,env:U(i,e.daemonEnv()),stdoutMaxBytes:i.stdoutMaxBytes,messages:r,sandboxPolicy:te.policy,sandboxDegradeNote:In(te,r),summaryLimit:j(m.limit,r),rebuildWait:{root:l,rebuilds:e.rebuilds,maxWaitMs:i.rebuildWaitMs}});u!==void 0&&f===`indexed`&&c.grant(ga(e,n),u);let re=[h,p].filter(e=>e!==void 0).join(`
|
|
75
|
+
`);return{text:re.length===0?ne:`${re}\n${ne}`}}function Aa(e,t){aa(e.host,{name:`zg_search`,description:t.searchToolDescription,messages:e.messages,parameters:ya(t),concurrencySafe:!0,timeoutMs:na(e.config.searchTimeoutMs,!0,e.config.rebuildWaitMs),presentCall:e=>({card:`generic`,title:ia(e),kind:`search`}),run:(t,n,r)=>ka(e,t,n,r)})}function ja(e){return{type:`object`,properties:{root:{type:`string`,description:e.rootIndexDescription},confirm:{type:`boolean`,description:e.confirmDescription},embedding:{type:`string`,description:e.embeddingDescription},rebuild:{type:`boolean`,description:e.rebuildDescription},drop:{type:`boolean`,description:e.dropDescription},globs:$(e.globsIndexDescription),insensitiveGlobs:$(e.insensitiveGlobsDescription),fileTypes:$(e.fileTypesIndexDescription),excludedFileTypes:$(e.excludedFileTypesDescription),ignoreFiles:$(e.ignoreFilesDescription),background:{type:`boolean`,description:e.backgroundDescription},excludeSecrets:{type:`boolean`,description:e.excludeSecretsDescription},hidden:{type:`boolean`,description:e.hiddenDescription},noIgnore:{type:`boolean`,description:e.noIgnoreDescription},nestedGit:{type:`boolean`,description:e.nestedGitDescription},maxDepth:{type:`integer`,description:e.maxDepthDescription},maxFileSizeBytes:{type:`integer`,description:e.maxFileSizeBytesDescription},follow:{type:`boolean`,description:e.followDescription},embeddingConcurrency:{type:`integer`,description:e.embeddingConcurrencyDescription},device:{type:`string`,description:e.deviceDescription},resetPaths:{type:`boolean`,description:e.resetPathsDescription}},required:[`confirm`]}}async function Ma(e,t,n,r,i){let a={host:e.host,platform:e.platform,config:e.config,messages:e.messages,jobsOf:e.jobsOf,records:e.records,rebuilds:e.rebuilds,versionGate:e.versionGate,daemonEnv:()=>{let t=e.daemon.tokenOf();return t===void 0?void 0:{ZVEC_GREP_SERVER_TOKEN:t}}};if(e.jobsOf()===void 0)throw e.rebuilds.release(t,i),new H(V.daemonUnavailable,r.messages.endpointJobsUnavailable);let o=fr(e.config),s=Pn(e.host,r.exec),c=await Fr(a,r.messages,n,o,s.policy);if(`error`in c)throw e.rebuilds.release(t,i),new H(V.commandFailed,c.error);let l=Ir(a,t,r.messages,c,i);if(`error`in l)throw e.rebuilds.release(t,i),new H(V.commandFailed,l.error);e.rebuilds.attach(t,l.jobId,i);let u=b(r.messages.indexBackgroundStarted,{root:t,jobId:l.jobId,command:c.command}),d=In(s,r.messages);return{text:d===``?u:`${u}\n${d}`}}async function Na(e,t,n,r){let{config:i,host:a,ledger:o,rebuilds:s}=e;Q(o,n);let c=ta(t,n,r,o,e.platform),l={...t,root:c,platform:e.platform},u=k(t.background,`background`,r),d=k(t.rebuild,`rebuild`,r)||u;k(t.confirm,`confirm`,r),await e.versionGate.ensure(r);let f;if(d){let t=s.claim(c,`tool`);if(t===null)return{text:b(r.indexRebuildInFlight,{root:c})};if(u)return Ma(e,c,l,{exec:n,messages:r},t);f=t}try{tr(l,c,r);let{command:t,workdir:o}=ft(l,fr(i),r,W(i,r),ur(i)),s=Pn(a,n),u=await Gi(a,t,o,i.indexTimeoutMs,{signal:n.signal,env:U(i,e.daemonEnv()),stdoutMaxBytes:i.stdoutMaxBytes,messages:r,sandboxPolicy:s.policy,sandboxDegradeNote:In(s,r)});return e.indexProbe.invalidate(c),{text:u}}finally{f!==void 0&&s.release(c,f)}}function Pa(e,t){aa(e.host,{name:`zg_index`,description:t.indexToolDescription,messages:e.messages,parameters:ja(t),concurrencySafe:!1,timeoutMs:na(e.config.indexTimeoutMs,!1,e.config.rebuildWaitMs),presentCall:e=>({card:`generic`,title:ra(e,`zg_index`),kind:`other`}),run:(t,n,r)=>Na(e,t,n,r)})}async function Fa(e,t,n,r){let{config:i,host:a,ledger:o,rebuilds:s}=e;Q(o,n);let c=ta(t,n,r,o,e.platform),l=s.covering(c,r);if(l?.jobId!==void 0)return{text:b(r.statusRebuilding,{root:l.root,jobId:l.jobId})};let u=k(t.checkReady,`checkReady`,r);await e.versionGate.ensure(r);let{command:d,workdir:f}=pt({root:c,checkReady:u,platform:e.platform},r,W(i,r)),p=Pn(a,n),m=await Gi(a,d,f,i.statusTimeoutMs,{signal:n.signal,env:U(i,e.daemonEnv()),stdoutMaxBytes:i.stdoutMaxBytes,messages:r,sandboxPolicy:p.policy,sandboxDegradeNote:In(p,r),rebuildWait:{root:c,rebuilds:s,maxWaitMs:i.rebuildWaitMs},...u?{resolveFailure:(e,t)=>{if(t.timedOut||t.aborted||t.sandbox?.denied===!0||Un(t.stderr.text)!==null)return null;let n=t.stdout.text.trim();return n.length>0?`${n}\n${b(r.statusNotReady,{root:c,detail:e})}`:null}}:{}}),h=W(i,r),g=await e.serverGate.ready(),_=null;return h!==`direct`&&(_=g?r.serverReadyNote:r.serverUnavailableNote),_===null?{text:m}:{text:`${m}\n${_}`}}function Ia(e,t){aa(e.host,{name:`zg_status`,description:t.statusToolDescription,messages:e.messages,parameters:{type:`object`,properties:{root:{type:`string`,description:t.rootStatusDescription},checkReady:{type:`boolean`,description:t.checkReadyDescription}}},concurrencySafe:!0,timeoutMs:na(e.config.statusTimeoutMs,!0,e.config.rebuildWaitMs),presentCall:e=>({card:`generic`,title:ra(e,`zg_status`),kind:`read`}),run:(t,n,r)=>Fa(e,t,n,r)})}function La(e,t){Aa(e,t),Pa(e,t),Ia(e,t)}function Ra(e,t){e.systemPrompt.section({name:`zvec-grep-routing`,order:1550,text:t.routingSummary}),Qn(e,t.routingText,t.skillDescription)}function za(e,t,n,r){let i=(m(e.arguments)?e.arguments:void 0)?.root,a;if(typeof i==`string`&&i.trim().length>0){let o=ea(i,z(e),n,t,r);a=o.allowed?o.question:void 0}return a===void 0?void 0:{kind:`ask`,reason:b(n.rootApprovalReason,{root:a.root,cwd:a.cwd}),displayReason:{en:b(Ce.en.rootApprovalPrompt,{root:a.root}),zh:b(Ce.zh.rootApprovalPrompt,{root:a.root})}}}function Ba(e){let{config:t,host:n,ledger:r,messages:i}=e;n.on(`tools/pre-execute`,(n,a)=>{if(!t.requireApprovalForExplicitRoot||!sn(n.name))return a();let o=za(n,r,i(),e.platform);return o===void 0?a():Promise.resolve(o)})}function Va(e){let{config:t,host:n,indexProbe:r,ledger:i,messages:a,rebuilds:o,unlocks:s}=e;n.tools.guard(n=>{Q(i,n);let c=a(),l=dn(n,c,e.platform);return l===void 0?Tn(n,{enabled:Xi(t),platform:e.platform,indexProbe:r,now:()=>Date.now(),grepBudget:Ji(t),windowMin:Yi(t),lookupUnlock:t=>s.lookup(ga(e,n),t),consumeGrep:e=>{s.consume(e)},rebuildBypass:e=>o.covering(e,c)!==void 0},c):l})}function Ha(e,t){if(!pi(e))throw Error(`[zvec-grep] required services (settings/shell/tools/systemPrompt/timer/get) missing`);let n=e,r=mt();if(!oe({get:n.get,reflect:n.reflect},`@jayyuen66/dsh-zvec-grep/instance`)){console.warn(`[zvec-grep] 检测到本插件已在同一作用域内装载:本次装配让路,工具与设置卡由在册的那一份提供。`);return}pa(n);let i=ma(n),a=fa(i(),64,Date.now,fi,r),o={token:void 0,startedByUs:!1},s=()=>o.token,c=()=>{let e=s();return e===void 0?void 0:{ZVEC_GREP_SERVER_TOKEN:e}},l=hr(t.daemonUrl,i()),u=Vr(),d=ki(n,t,s),f=Mn(l,s),p={host:n,platform:r,config:t,messages:i,ledger:a,unlocks:_a(t,Date.now,r),indexProbe:da(e=>$i(e,r)),rebuilds:kn({platform:r}),versionGate:d,serverGate:f,daemon:Mi({host:n,config:t,daemonUrl:l,tokenFile:u,tokenOf:s,setToken:e=>{o.token=e},markStarted:()=>{o.startedByUs=!0},serverGate:f}),daemonEnv:c,daemonClient:oi({url:l,tokenOf:s}),jobsOf:()=>n.get(`jobs`),records:new Map,sessionParent:e=>{let t=n.get(`sessions`),r=t===void 0?void 0:t.list().find(t=>t.id===e);return r===void 0?void 0:{parentSession:r.header.parentSession,origin:r.header.origin}}},m=i();La(p,m),Ra(n,m),Va(p),Ba(p),Ni({host:n,config:t,tokenFile:u,daemonEnv:c,startedByUs:()=>o.startedByUs}),zr(n,{host:n,platform:r,config:t,messages:i,jobsOf:p.jobsOf,records:p.records,rebuilds:p.rebuilds,versionGate:p.versionGate,ledger:a,serverGate:p.serverGate,daemonEnv:()=>{let e=s();return e===void 0?void 0:{ZVEC_GREP_SERVER_TOKEN:e}}})}var Ua={inject:[`settings`,`shell`,`tools`,`systemPrompt`,`timer`],Config:oa,apply:Ha};export{oa as Config,ua as INDEX_PROBE_CACHE_MAX,la as INDEX_PROBE_TTL_MS,X as comparablePath,da as createIndexProbeCache,fa as createRootLedger,_a as createUnlockLedger,Ua as default,Ri as hitSummary,Y as redactToken,Ti as signalStderr};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jayyuen66/dsh-zvec-grep",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.23",
|
|
4
4
|
"description": "dsh 工作区语义检索插件(zg):zg_search / zg_index / zg_status + 本地 embedding 设置卡片 + systemPrompt 路由规则 + guard 安全兜底。",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cordis",
|
|
@@ -79,6 +79,7 @@
|
|
|
79
79
|
"@deepseek-ai/dsh-output-retention": "0.2.3-alpha.3",
|
|
80
80
|
"@deepseek-ai/dsh-package-manifest": "0.2.3-alpha.3",
|
|
81
81
|
"@deepseek-ai/dsh-sandbox": "0.2.3-alpha.3",
|
|
82
|
+
"@deepseek-ai/dsh-sandbox-policy": "0.2.3-alpha.3",
|
|
82
83
|
"@deepseek-ai/dsh-scope": "0.2.3-alpha.3",
|
|
83
84
|
"@deepseek-ai/dsh-session": "0.2.3-alpha.3",
|
|
84
85
|
"@deepseek-ai/dsh-session-projection": "0.2.3-alpha.3",
|