@jayyuen66/dsh-zvec-grep 0.1.22 → 0.1.24

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 CHANGED
@@ -2,6 +2,31 @@
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.24
6
+
7
+ shared moves to `^0.3.3` through the catalog (both READMEs and the notices follow); the dev-toolchain catalog and CI move to the current pins (oxfmt 0.81.0 / oxlint 1.96.0 / vite 8.4.1, pnpm 12.25.1).
8
+
9
+ ### Fixed
10
+
11
+ - **保存成功后清空越界集改为带守卫**:设置卡在写请求在途期间仍可编辑,`useInvalidFields().clear({ guard: invalidAtSubmit })` 按引用判「期间有没有人上报过」——有人报过就整次作废(集合与 `resetToken` 都不动),用户新敲的越界草稿与保存门禁一起保住;没人动过才照旧清空并把数字框重置回已提交值。`<button onClick={state.clear}>` 会传事件对象,所以参数是选项对象而非位置参数。
12
+
13
+ ### Tests
14
+
15
+ - `test/instance-lock.test.ts` 的单实例锁用例按 shared 0.3.3 的 `claimInstance` 契约拆成两条:`provide` 抛错但锁名随后读得到(被另一份抢走)→ 让路;`provide` 抛错且锁名读不到(fiber 已 dispose / 键非法)→ 原样上抛,异常实例保持同一性,不把整份插件安静关掉。
16
+ ## 0.1.23
17
+
18
+ ### Fixed
19
+
20
+ - **守护进程就绪探测改为 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` 诊断透传保持不变。
21
+
22
+ ### Added
23
+
24
+ - **会话沙箱策略的三条真实宿主集成用例**:官方 `SandboxPolicyService` 在场时 `zg --status` 请求带 `workspaceRoot = 会话 cwd`;服务缺席时不带字段且命令照常执行;`zg --server on` 拉起 daemon 时刻意不带会话策略(Landlock 进程不可逆,单例 daemon 不能被某个会话的边界圈住)。设置卡重建路径另补一条「不带策略」的负断言。`devDependencies` 增 `@deepseek-ai/dsh-sandbox-policy@0.2.3-alpha.3`(仅测试用)。
25
+
26
+ ### Changed
27
+
28
+ - **`shell-facts` 的索引检索判据从 `zg --rg` 改为 `zg --hybrid`**:`--rg` 是穷举/文件发现通道,不会出现在索引通道的检索里;旧写法在缺席分支永远 undefined、就绪分支从未跑到过,是潜伏的错判据。
29
+
5
30
  ## 0.1.22
6
31
 
7
32
  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
@@ -88,7 +88,7 @@ Remove with `dsh plugin --profile web remove @jayyuen66/dsh-zvec-grep`. The pack
88
88
 
89
89
  If your profile pins `@jayyuen66/dsh-plugin-shared` with a pnpm `overrides` entry, that pin must be at least the version this package declares. A lower pin installs a copy without the names imported at runtime, and the host reports `N entries did not activate` with `does not provide an export named ...` at boot - installs fine, never loads, invisible to per-repository CI.
90
90
 
91
- Bundle order decides it too: from alpha.3 on, when several bundles insert the same `dsh-plugin-shared` row, the first bundle in `dsh.profile.bundles` that declares the dependency decides which copy loads. Keep that copy at or above the version this package declares, and upgrade mixed old/new plugin sets together. From this release on, the client stylesheets (`meta.stylesheets`) and `ProgressBar` require shared `0.3.2` or later; the `^0.3.1` range only keeps older plugins compatible, so treat `0.3.2` as the effective floor for releases and single-repository CI.
91
+ Bundle order decides it too: from alpha.3 on, when several bundles insert the same `dsh-plugin-shared` row, the first bundle in `dsh.profile.bundles` that declares the dependency decides which copy loads. Keep that copy at or above the version this package declares, and upgrade mixed old/new plugin sets together. From this release on, the client stylesheets (`meta.stylesheets`), `ProgressBar` and the save-path `useInvalidFields.clear({ guard })` require shared `0.3.3` or later; the `^0.3.1` / `^0.3.2` ranges only keep older plugins compatible, so treat `0.3.3` as the effective floor for releases and single-repository CI.
92
92
 
93
93
  ## <img src="https://api.iconify.design/lucide/circle-check.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> Verify it is live
94
94
 
@@ -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 exit code of `zg --server status --check-ready` is cached for 60 s (a failed probe counts as "not ready", never an infrastructure error), 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`.
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
@@ -88,7 +88,7 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
88
88
 
89
89
  如果你的 profile 用 pnpm `overrides` 把 `@jayyuen66/dsh-plugin-shared` 钉在某个版本,那个值必须不低于本包声明的版本。钉得更低就会装到一份缺少运行期所导入名字的产物,宿主起来时报 `N entries did not activate` 加 `does not provide an export named ...`——包装得上、永远不加载,单仓 CI 看不见。
90
90
 
91
- bundle 顺序也会决定这件事:alpha.3 起,多个 bundle 插入同名 `dsh-plugin-shared` 行时,由 `dsh.profile.bundles` 里最靠前且声明该依赖的 bundle 决定加载哪份。请让最终拿到的那份不低于本包声明的版本;混装新旧插件时先统一升级。 本版起的客户端样式表(`meta.stylesheets`)与 `ProgressBar` 需要 shared `0.3.2` 或更晚;`^0.3.1` 的范围只为兼容旧插件,发布与单仓 CI 请以 `0.3.2` 作为实际下限。
91
+ bundle 顺序也会决定这件事:alpha.3 起,多个 bundle 插入同名 `dsh-plugin-shared` 行时,由 `dsh.profile.bundles` 里最靠前且声明该依赖的 bundle 决定加载哪份。请让最终拿到的那份不低于本包声明的版本;混装新旧插件时先统一升级。 本版起的客户端样式表(`meta.stylesheets`)、`ProgressBar` 与保存回路的 `useInvalidFields.clear({ guard })` 需要 shared `0.3.3` 或更晚;`^0.3.1` / `^0.3.2` 的范围只为兼容旧插件,发布与单仓 CI 请以 `0.3.3` 作为实际下限。
92
92
 
93
93
  ## <img src="https://api.iconify.design/lucide/circle-check.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> 确认它真的在工作
94
94
 
@@ -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 缓存 `zg --server status --check-ready` 的退出码(探测失败按未就绪统一处理,绝不外抛基础设施故障),据此统一处理 `refresh=background`,并在 `zg_status` 输出尾与卡片各回显一行。探测由 `roots()` 读取接口、`zg_status` 与 `backgroundSupportFor` 发出。
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/client.js CHANGED
@@ -5,7 +5,7 @@ window.__ModuleLoader__.load({
5
5
  'use strict';
6
6
  const module = { exports: {} };
7
7
  let exports = module.exports;
8
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("react"),t=require("zod"),n=require("@jayyuen66/dsh-plugin-shared/client");const r=`transformers-js`,i=Object.freeze([{reference:`local/qwen3-embedding-0.6b`,backend:`llama-cpp`,dimension:1024},{reference:`local/embeddinggemma-300m`,backend:`llama-cpp`,dimension:768},{reference:`local/potion-code-16m-v2`,backend:`model2vec`,dimension:256},{reference:`local/potion-multilingual-128m`,backend:`model2vec`,dimension:256},{reference:`local/potion-retrieval-32m`,backend:`model2vec`,dimension:512},{reference:`local/bge-small-en-v1.5`,backend:r,dimension:384},{reference:`local/all-minilm-l6-v2`,backend:r,dimension:384},{reference:`local/multilingual-e5-small`,backend:r,dimension:384},{reference:`local/jina-embeddings-v2-base-code`,backend:r,dimension:768},{reference:`local/gte-modernbert-base`,backend:r,dimension:768},{reference:`local/nomic-embed-text-v1.5`,backend:r,dimension:768}].map(e=>Object.freeze(e))),a=Object.freeze([{reference:`qwen/qwen3-vl-embedding`,dimension:2560},{reference:`qwen/qwen3.7-text-embedding`,dimension:1024},{reference:`qwen/text-embedding-v4`,dimension:1024}].map(e=>Object.freeze(e)));function o(e,t){return Object.hasOwn(e,t)}function s(e,t,n){return o(e,n)?e[n]:Object.hasOwn(t,n)?t[n]:void 0}function c(e,t){return typeof e==`number`&&Number.isFinite(e)?String(e):t}function l(e){let t;return e===!0?t=`daemonReadyNote`:e===!1&&(t=`daemonOfflineNote`),t}function u(e){return e?`ok`:`warn`}function d(e){let t={status:`loading`,writable:!1,value:{}},n=null,r=t;return{getSnapshot(){let t=e.getSnapshot();return t!==n&&(n=t,r={status:t.status,writable:t.writable,value:t.value??{}}),r},subscribe(t){return e.subscribe(t)}}}function f(e,t,n,r){let i=s(e,t,n);return i===void 0?o(e,n)?``:r:c(i,r)}const p=t.z.url({protocol:/^https?$/u});function m(e,t){if(Object.hasOwn(e,`hfEndpoint`)){let t=e.hfEndpoint;return typeof t==`string`?t:``}let n=t.hfEndpoint;return typeof n==`string`&&p.safeParse(n).success?n:``}function h(e,t){let n=s(e,t,`defaultEmbedding`),r=s(e,t,`enforceSearchFirst`),i=s(e,t,`transport`);return{embedding:typeof n==`string`&&n.length>0?n:`local/qwen3-embedding-0.6b`,limitDisplay:f(e,t,`defaultLimit`,`10`),hfEndpoint:m(e,t),enforceSearchFirst:r!==!1,grepBudget:f(e,t,`grepBudgetPerSearch`,`3`),unlockWindow:f(e,t,`unlockWindowMin`,`10`),transport:i===`cli`||i===`mcp`||i===`auto`?i:`auto`}}const g=t.z.int().min(1).max(50),_=t.z.int().min(1).max(20),v=t.z.int().min(1).max(240),y=[`running`,`stopping`,`completed`,`killed`,`failed`],b=t.z.object({status:t.z.preprocess(e=>typeof e==`string`&&y.some(t=>t===e)?e:void 0,t.z.enum(y).optional()),exitCode:t.z.preprocess(e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,t.z.number().optional()),output:t.z.preprocess(e=>typeof e==`string`?e:void 0,t.z.string().optional())});function x(e,t){let n=b.safeParse(e),{status:r,exitCode:i,output:a}=n.success?n.data:{},o=a??``;if(r===`running`||r===`stopping`)return{phase:`running`,output:o.length>0?o:t(`rebuildRunning`)};if(r===`completed`&&i===0)return{phase:`done`,output:o};let s;return s=r===`killed`?t(`rebuildKilled`):r===`failed`?t(`rebuildFailed`):typeof i==`number`&&Number.isFinite(i)?t(`rebuildExitCode`,{exitCode:i}):t(`rebuildExitUnknown`),{phase:`error`,output:o.length>0?`${s}\n${o}`:s}}const S=`zvecGrepRebuild`,C=`remote.${S}`,w=`@jayyuen66/dsh-zvec-grep`,T=t.z.object({root:t.z.string({error:`rebuild request requires a string root`}).trim().min(1,{error:`rebuild request requires a non-empty root`})},{error:`rebuild request requires a string root`}),E=t.z.object({jobId:t.z.string({error:`rebuild status request requires a string jobId`}).trim().min(1,{error:`rebuild status request requires a non-empty jobId`})},{error:`rebuild status request requires a string jobId`}),D=[{id:`${w}#${S}/roots`,service:S,namespace:S,method:`roots`,invocation:{kind:`direct`},parameters:[],result:{mode:`src-json`}},{id:`${w}#${S}/rebuild`,service:S,namespace:S,method:`rebuild`,invocation:{kind:`direct`},parameters:[{name:`request`,wire:`request`,source:`json`,codec:{mode:`strict`,typeSymbol:`${w}#rebuild-request`,create:()=>({parse(e){return(0,n.parseOrThrow)(T,e,t.z.prettifyError)}})}}],result:{mode:`src-json`}},{id:`${w}#${S}/status`,service:S,namespace:S,method:`status`,invocation:{kind:`direct`},parameters:[{name:`request`,wire:`request`,source:`json`,codec:{mode:`strict`,typeSymbol:`${w}#rebuild-status-request`,create:()=>({parse(e){return(0,n.parseOrThrow)(E,e,t.z.prettifyError)}})}}],result:{mode:`src-json`}}],O=e=>(0,n.isRecord)(e)&&typeof e.roots==`function`&&typeof e.rebuild==`function`&&typeof e.status==`function`;async function k(e){let t=await e;if(t.ok)return t.value;throw Error(`${t.error.code}: ${t.error.message}`)}function A(e,t){let r,i=async()=>{let i=(0,n.remoteMounterOf)(e,!0);if(i===void 0)throw Error(t.remoteMissing());try{r??=i.$mount({package:w,descriptors:D}),await r}catch(e){throw r=void 0,e}let a=e.get?.(C);if(!O(a))throw Error(t.namespaceMissing(C));return a};return{async roots(){return k((await i()).roots())},async rebuild(e){let t=await k((await i()).rebuild({root:e}));if(t.ok)return t;throw Error(t.error)},async status(e){let t=await k((await i()).status({jobId:e}));if(t.ok)return{...t};throw Error(t.error)}}}function ee(e,t){return typeof e.get==`function`?A(e,t):void 0}const j=`https://modelscope.cn/models`,M={zh:{statusReadOnly:`当前作用域只读`,statusClean:`无未保存的修改`,dirtyCount:`已修改 {count} 项`,save:`保存`,saving:`保存中…`,revert:`撤销`,saveFailed:`保存失败:{reason}`,invalidFields:`有字段超出范围,先修正或撤销后再保存。`,saveRejected:`保存被宿主拒绝(配置校验未通过或写入被跳过),修改未生效`,modelSection:`检索模型`,fieldCount:`{count} 字段`,indexSection:`网络与索引`,unitResults:`条`,unitTimes:`次`,unitMinutes:`分钟`,outOfRange:`超出允许范围,未保存`,embeddingLabel:`默认 embedding`,embeddingHint:`本地模型直接可选;远程 qwen 模型需在插件部署配置里打开 allowRemoteEmbedding(内容会送往外部端点,首次索引需 zg --auth grant 授权)。只影响「新建」索引;切换并保存后,已有索引需点下方「重建」重新 embedding`,transportLabel:`检索传输方式`,transportHint:`自动 = 守护进程在跑时检索走 MCP(常驻模型池、队列调度),否则走 CLI;仅 CLI = 永不碰守护进程;仅 MCP = 检索恒走守护进程,缺席时由插件自动拉起(会开 127.0.0.1:7999 回环端口;拉起失败会明确报错而不是回退 CLI)`,transportAuto:`自动(守护进程在跑走 MCP,否则 CLI)`,transportCli:`仅 CLI(每次 spawn zg 进程)`,transportMcp:`仅 MCP(走守护进程,缺席自动拉起)`,backendRemote:`qwen 远程(内容出本机,需部署开放并授权)`,limitLabel:`默认每组结果数`,limitInvalid:`请输入 {min}-{max} 的整数`,limitClamped:`已钳到 {min}-{max} 范围:{value}`,endpointLabel:`HuggingFace 镜像地址`,endpointHint:`留空走 huggingface.co;国内网络可填 ${j} 等兼容镜像(仅 llama-cpp 后端生效,如 qwen3)`,enforceLabel:`强制 search-first(先 zg_search 再 grep/rg)`,enforceHint:`开启后,已建索引工作区内的 grep/rg 受配额门禁约束:每次成功 zg_search 解锁下方次数的 grep/rg(时效见下),用尽或过期后再次拦截(提高检索覆盖与准确性)`,budgetLabel:`每次 zg_search 解锁的 grep/rg 次数`,budgetHint:`配额越小语义检索越频繁、准确性约束越强;清空恢复默认 {default}`,windowLabel:`解锁时效`,windowHint:`超过该时长未再次 zg_search,配额整体过期;清空恢复默认 {default}(单位:分钟)`,rebuildLabel:`工作区重建(切换 embedding 并保存后执行)`,rebuildInputPlaceholder:`/workspace 的绝对路径`,daemonReadyNote:`守护进程:就绪(zg --server 在跑)。`,daemonOfflineNote:"守护进程:未就绪。守护进程提供的索引增量刷新、refresh=background 与常驻模型池在缺席时都不可用;需要时在终端执行 `zg --server on`。",panelRoots:`索引根`,panelServer:`索引服务`,panelReady:`就绪`,panelNotReady:`未就绪`,rebuildHint:`以当前默认模型重建:{embedding};等价于 zg --index --rebuild。{roots}`,rootsNoteWith:`候选工作区来自本 daemon 已打开过的会话(服务端白名单)。`,rootsNoteEmpty:`尚无可选工作区:先在该工作区里开一个会话(任一次工具调用即登记)。`,rebuildButton:`重建索引(动作,点击即执行)`,rebuildRunning:`重建中…`,rebuildDone:`重建完成`,rebuildStatusTitle:`重建作业`,copy:`复制`,copied:`已复制`,rebuildStarting:`正在后台重建索引…(首次会下载 embedding 模型,可能较慢)`,rebuildKilled:`重建进程被终止`,rebuildFailed:`重建作业被宿主注册表判定失败(没拿到进程退出码)`,rebuildExitCode:`重建进程退出码 {exitCode}(zg 未安装/权限不足/沙箱拒绝都会走到这里)`,rebuildExitUnknown:`重建没有可判定的结果(应答的 status 无法识别,或缺少进程退出码)`,rebuildMissingJobId:`启动重建失败:应答缺 jobId`,rebuildRootNotAbsolute:`root 必须是绝对路径(以 / 开头)`,rebuildUnavailable:`宿主没有提供工作区重建读面(未装远程服务)`,rebuildRemoteMissing:`工作区重建读面不可用:宿主网关没有提供 remote 服务`,rebuildNamespaceMissing:`{serviceKey} 未提供:宿主网关没有挂上这枚命名空间`,modelOption:`{reference}({dimension}维)`,backendLlamaCpp:`llama-cpp(原生,需 node-llama-cpp)`,backendTransformersJs:`transformers-js(纯 JS ONNX)`,backendModel2Vec:`model2vec(纯 JS worker,最轻)`},en:{statusReadOnly:`This scope is read-only`,statusClean:`No unsaved changes`,dirtyCount:`{count} changed`,save:`Save`,saving:`Saving…`,revert:`Revert`,saveFailed:`save failed: {reason}`,invalidFields:`Some fields are out of range; fix them or revert before saving.`,saveRejected:`save rejected by host (validation failed or write skipped) — changes not applied`,modelSection:`Retrieval model`,fieldCount:`{count} fields`,indexSection:`Network and index`,unitResults:`hits`,unitTimes:`times`,unitMinutes:`minutes`,outOfRange:`Out of the allowed range — not saved`,embeddingLabel:`Default embedding`,embeddingHint:`Local models are always selectable; the remote qwen models additionally require allowRemoteEmbedding in the deployment config (content leaves the machine, and the first index build needs a zg --auth grant). Affects newly built indexes only; after switching and saving, press Rebuild below to re-embed existing indexes`,transportLabel:`Search transport`,transportHint:`auto = searches go through the daemon (MCP) when it is running, CLI otherwise; CLI-only = never touch the daemon; MCP-only = searches always go through the daemon, auto-starting it when absent (opens the 127.0.0.1:7999 loopback port; a failed start is reported explicitly, never silently downgraded to CLI)`,transportAuto:`auto (daemon → MCP, otherwise CLI)`,transportCli:`CLI only (spawn zg each call)`,transportMcp:`MCP only (via daemon, auto-started when absent)`,backendRemote:`qwen remote (content leaves the machine; needs the deployment switch + grant)`,limitLabel:`Default hits per group`,limitInvalid:`enter an integer between {min} and {max}`,limitClamped:`clamped into the {min}-{max} range: {value}`,endpointLabel:`HuggingFace mirror URL`,endpointHint:`Leave empty for huggingface.co; on networks that cannot reach HF, fill a compatible mirror such as ${j} (llama-cpp backends only, e.g. qwen3)`,enforceLabel:`Enforce search-first (zg_search before grep/rg)`,enforceHint:`When on, grep/rg inside indexed workspaces is quota-gated: each successful zg_search unlocks the number of grep/rg calls below (valid for the window below), and the gate blocks again once it is spent or expired (better coverage and relevance)`,budgetLabel:`grep/rg calls unlocked per zg_search`,budgetHint:`A smaller quota means more semantic searches and a stronger relevance constraint; clear to restore the default {default}`,windowLabel:`Unlock window`,windowHint:`Without another zg_search inside this window the whole quota expires; clear to restore the default {default} (minutes)`,rebuildLabel:`Workspace rebuild (run after switching embedding and saving)`,rebuildInputPlaceholder:`absolute path to a /workspace`,daemonReadyNote:`Daemon: ready (zg --server is running).`,daemonOfflineNote:"Daemon: not ready. What the daemon provides — incremental index refresh, refresh=background and the resident embedding model pool — is unavailable while it is absent; run `zg --server on` in a terminal when you want it.",rebuildHint:`Rebuild with the current default model: {embedding}; same as zg --index --rebuild. {roots}`,panelRoots:`Index roots`,panelServer:`Index server`,panelReady:`Ready`,panelNotReady:`Not ready`,rootsNoteWith:`Candidates come from sessions this daemon already opened (server-side whitelist).`,rootsNoteEmpty:`No workspace to pick yet: open a session in that workspace first (any tool call registers it).`,rebuildButton:`Rebuild index (action, runs on click)`,rebuildRunning:`rebuilding…`,rebuildDone:`rebuild finished`,rebuildStatusTitle:`rebuild job`,copy:`Copy`,copied:`Copied`,rebuildStarting:`Rebuilding in the background… (the first run downloads the embedding model and may be slow)`,rebuildKilled:`the rebuild process was terminated`,rebuildFailed:`the host job registry reported the rebuild as failed (no process exit code)`,rebuildExitCode:`the rebuild process exited with code {exitCode} (missing zg, insufficient permissions and sandbox denials all land here)`,rebuildExitUnknown:`the rebuild has no determinable outcome (the response status is unrecognized, or its exit code is missing)`,rebuildMissingJobId:`failed to start the rebuild: the response has no jobId`,rebuildRootNotAbsolute:`root must be an absolute path (starting with /)`,rebuildUnavailable:`the host does not expose the rebuild Remote API`,rebuildRemoteMissing:`the rebuild Remote API is unavailable: the host gateway provides no remote service`,rebuildNamespaceMissing:`{serviceKey} was not provided: the host gateway did not mount this namespace`,modelOption:`{reference} ({dimension} dims)`,backendLlamaCpp:`llama-cpp (native, requires node-llama-cpp)`,backendTransformersJs:`transformers-js (pure JS ONNX)`,backendModel2Vec:`model2vec (pure JS worker, lightest)`}},N=String.fromCodePoint(92),P=/^[A-Za-z]:[\\/]/u,F=`zvec-grep`,I=[`llama-cpp`,`transformers-js`,`model2vec`],L=`zgc-rebuild-root-options`,R={"llama-cpp":`backendLlamaCpp`,"transformers-js":`backendTransformersJs`,model2vec:`backendModel2Vec`};function z(e){return e.value}function B(e,t,n){return e(`modelOption`,{reference:t,dimension:n})}function V(e,t,n){return e(`rebuildHint`,{embedding:t,roots:e(n?`rootsNoteWith`:`rootsNoteEmpty`)})}function H(e){let t=[];for(let n of I)for(let r of i)r.backend===n&&t.push({value:r.reference,label:B(e,r.reference,r.dimension),group:e(R[n])});for(let n of a)t.push({value:n.reference,label:B(e,n.reference,n.dimension),group:e(`backendRemote`)});return t}const U=[{value:`auto`},{value:`cli`},{value:`mcp`}],W={auto:`transportAuto`,cli:`transportCli`,mcp:`transportMcp`};function G(e){return U.map(t=>({value:t.value,label:e(W[t.value])}))}function K(e,t){let n=t.safeParse(e===``?NaN:Number(e));return n.success?n.data:void 0}function q(t){let{editable:r,fields:i,setField:a,t:o}=t,s=(0,e.createElement)(n.SelectField,{label:o(`embeddingLabel`),...(0,n.splitHint)(o(`embeddingHint`)),field:`defaultEmbedding`,value:i.embedding,options:H(o),disabled:!r,onChange:e=>{a(`defaultEmbedding`,e)}}),c=(0,e.createElement)(n.NumberField,{label:o(`limitLabel`),hint:o(`limitInvalid`,{min:1,max:50}),field:`defaultLimit`,value:K(i.limitDisplay,g),...(0,n.numberBoundsOf)(g,{min:1,max:50}),step:1,unit:o(`unitResults`),invalidHint:o(`outOfRange`),disabled:!r,resetToken:t.resetToken,onInvalidChange:e=>{t.reportInvalid(`defaultLimit`,e)},onChange:e=>{a(`defaultLimit`,e)}});return(0,e.createElement)(n.Section,{title:o(`modelSection`),count:o(`fieldCount`,{count:`2`})},s,c)}function J(t){let{fields:r,rebuild:i,root:a,roots:o,setRoot:s,t:c}=t,l=o.map(t=>(0,e.createElement)(`option`,{key:t,value:t})),u=(0,e.createElement)(`datalist`,{id:L},...l),d=(0,e.createElement)(`input`,{className:`dsu-input dsu-grow`,value:a,list:L,placeholder:c(`rebuildInputPlaceholder`),onChange:e=>{s(e.target.value)}}),f=(0,e.createElement)(`button`,{type:`button`,className:`dsu-btn`,"data-field":`rebuild`,disabled:i.phase===`running`,onClick:t.onRebuild},i.phase===`running`?c(`rebuildRunning`):c(`rebuildButton`));return(0,e.createElement)(n.Field,{label:c(`rebuildLabel`),...(0,n.splitHint)(V(c,r.embedding,o.length>0)),wide:!0},u,(0,e.createElement)(`div`,{className:`dsu-inlineRow`},d,f))}function Y(t){let{t:r}=t,i=l(t.serverReady);return i===void 0?null:(0,e.createElement)(`div`,{className:`dsu-inlineRow`,"data-field":`daemon-status`},(0,e.createElement)(n.StatusDot,{tone:u(t.serverReady===!0)}),(0,e.createElement)(`p`,{className:`dsu-hint`},r(i)))}function X(t){let{rebuild:r,t:i}=t;if(r.phase===`idle`)return null;if(r.phase===`error`)return(0,e.createElement)(n.Callout,{tone:`err`},r.output);let a;a=r.output===``?r.phase===`done`?i(`rebuildDone`):``:r.output;let o=(0,e.createElement)(n.LogPanel,{label:i(`rebuildStatusTitle`),tone:r.phase===`done`?`ok`:`mute`,semanticLines:!0,copyText:a,copyLabel:i(`copy`),copiedLabel:i(`copied`)},a);return r.phase===`running`?(0,e.createElement)(`div`,null,o,(0,e.createElement)(n.ProgressBar,{label:i(`rebuildRunning`)})):o}function te(t){let{editable:r,fields:i,setField:a,t:o}=t,s=(0,e.createElement)(n.SelectField,{label:o(`transportLabel`),...(0,n.splitHint)(o(`transportHint`)),field:`transport`,value:i.transport,options:G(o),disabled:!r,onChange:e=>{a(`transport`,e)}}),c=(0,e.createElement)(n.TextField,{label:o(`endpointLabel`),...(0,n.splitHint)(o(`endpointHint`)),field:`hfEndpoint`,value:i.hfEndpoint,placeholder:j,monospace:!0,disabled:!r,onChange:e=>{a(`hfEndpoint`,e.trim()===``?void 0:e.trim())}}),l=(0,e.createElement)(n.ToggleField,{label:o(`enforceLabel`),...(0,n.splitHint)(o(`enforceHint`)),field:`enforceSearchFirst`,checked:i.enforceSearchFirst,disabled:!r,onChange:e=>{a(`enforceSearchFirst`,e)}}),u=(0,e.createElement)(n.NumberField,{label:o(`budgetLabel`),...(0,n.splitHint)(o(`budgetHint`,{default:3})),field:`grepBudgetPerSearch`,value:K(i.grepBudget,_),...(0,n.numberBoundsOf)(_,{min:1,max:20}),step:1,unit:o(`unitTimes`),invalidHint:o(`outOfRange`),disabled:!r,resetToken:t.resetToken,onInvalidChange:e=>{t.reportInvalid(`grepBudgetPerSearch`,e)},onChange:e=>{a(`grepBudgetPerSearch`,e)}}),d=(0,e.createElement)(n.NumberField,{label:o(`windowLabel`),...(0,n.splitHint)(o(`windowHint`,{default:10})),field:`unlockWindowMin`,value:K(i.unlockWindow,v),...(0,n.numberBoundsOf)(v,{min:1,max:240}),step:1,unit:o(`unitMinutes`),invalidHint:o(`outOfRange`),disabled:!r,resetToken:t.resetToken,onInvalidChange:e=>{t.reportInvalid(`unlockWindowMin`,e)},onChange:e=>{a(`unlockWindowMin`,e)}});return(0,e.createElement)(n.Section,{title:o(`indexSection`),count:o(`fieldCount`,{count:`5`})},s,c,l,(0,e.createElement)(n.FieldTwoCol,null,u,d),Y(t),J(t),X(t))}function ne(t){let{t:r}=t,i=(0,e.createElement)(n.SaveBar,{dirty:t.dirty,blocked:t.blocked,busy:t.busy,writable:t.writable,error:t.saveError??(t.blocked?r(`invalidFields`):null),saveLabel:r(`save`),savingLabel:r(`saving`),revertLabel:r(`revert`),dirtyLabel:r(`dirtyCount`,{count:t.dirtyCount}),cleanLabel:r(`statusClean`),readOnlyLabel:r(`statusReadOnly`),onSave:t.onSave,onDiscard:t.onDiscard});return(0,e.createElement)(n.CardForm,null,q(t),te(t),i)}function re(e,t,n,r){t===`defaultEmbedding`?e.push(r(`defaultEmbedding`,n)):t===`defaultLimit`?e.push(r(`defaultLimit`,n)):t===`hfEndpoint`?e.push(r(`hfEndpoint`,n)):t===`enforceSearchFirst`?e.push(r(`enforceSearchFirst`,n)):t===`grepBudgetPerSearch`?e.push(r(`grepBudgetPerSearch`,n)):t===`unlockWindowMin`?e.push(r(`unlockWindowMin`,n)):t===`transport`&&e.push(r(`transport`,n))}function Z(e,t){if(e===void 0)throw Error(t(`rebuildUnavailable`));return e}const Q={roots:[],serverReady:void 0};function ie(r,i){let[a,o]=(0,e.useState)(``),[s,c]=(0,e.useState)(Q),[l,u]=(0,e.useState)({phase:`idle`,output:``}),d=(0,e.useRef)(null),f=(0,e.useRef)(!1),p=(0,e.useRef)(null),m=(0,e.useRef)(!0),h=()=>m.current;function g(){p.current=null,d.current!==null&&(clearInterval(d.current),d.current=null)}(0,e.useEffect)(()=>(m.current=!0,()=>{m.current=!1,g()}),[]);let _=(0,e.useCallback)(async()=>{let e=await Z(i,r).roots(),t={roots:[...e.roots],serverReady:e.serverReady};return c(t),t},[i,r]);(0,e.useEffect)(()=>{(async()=>{try{await _()}catch{c(Q)}})()},[_]);async function v(e){if(!f.current&&h()&&p.current===e){f.current=!0;try{let t=await Z(i,r).status(e);if(!h()||p.current!==e)return;let n=x(t,r);n.phase!==`running`&&g(),u({phase:n.phase,output:n.output})}catch(t){if(!h()||p.current!==e)return;g(),u({phase:`error`,output:(0,n.errorText)(t)})}finally{f.current=!1}}}async function y(){let e=await Z(i,r).rebuild(a.trim()),n=t.z.object({jobId:t.z.string()}).safeParse(e);if(!n.success)throw TypeError(r(`rebuildMissingJobId`));let{jobId:o}=n.data;p.current=o,d.current=setInterval(()=>{v(o)},2e3)}async function b(){let e=a.trim();if(!(e.startsWith(`/`)||P.test(e)||e.startsWith(N+N)))u({phase:`error`,output:r(`rebuildRootNotAbsolute`)});else{g(),u({phase:`running`,output:r(`rebuildStarting`)});try{await y()}catch(e){g(),u({phase:`error`,output:(0,n.errorText)(e)})}}}return{root:a,roots:s.roots,serverReady:s.serverReady,state:l,setRoot:o,start:b}}function ae(t){let{t:r}=t,i=t.useCard(e=>e),{status:a,writable:o}=i,s=a===`ready`&&o,c=z(i),[l,u]=(0,e.useState)(!1),[d,f]=(0,e.useState)(null),p=ie(r,t.rebuildRemote),{touched:m,setTouched:g,setField:_,discard:v,invalid:y,dirtyKeys:b}=(0,n.useCardDraft)(c,{onDiscard:()=>{f(null)}}),x=h(m,c),{blocked:S,fields:C,resetToken:w,reportInvalid:T}=y,E=new Set([...b,...C]).size,D=E>0||S,O=async()=>{let e=(0,n.diffTouched)(m,c);if(e.length===0||S)return;u(!0),f(null);let i=[];for(let n of e){let e=m[n];e===void 0?i.push(t.unset(n)):re(i,n,e,t.set)}try{if((await Promise.all(i)).some(e=>!e)){u(!1),f(r(`saveRejected`));return}}catch(e){u(!1),f(r(`saveFailed`,{reason:(0,n.errorText)(e)}));return}let a=new Set(e),o=Object.fromEntries(Object.entries(m).filter(([e])=>!a.has(e)));u(!1),g(o),y.clear()};return ne({t:r,fields:x,writable:s,editable:s&&!l,roots:p.roots,serverReady:p.serverReady,root:p.root,rebuild:p.state,dirty:D,blocked:S,resetToken:w,reportInvalid:T,dirtyCount:E,busy:l,saveError:d,setField:_,setRoot:p.setRoot,onSave:()=>{O()},onDiscard:v,onRebuild:()=>{p.start()}})}const $=`conversation.session.panel.section`;function oe(t){let{t:r,reader:i}=t,[a,o]=(0,e.useState)(null);if((0,e.useEffect)(()=>{let e=!0;return(async()=>{if(i!==void 0)try{let t=await i.roots();e&&o(t)}catch{}})(),()=>{e=!1}},[i]),i===void 0||a===null)return null;let s=a.serverReady===!0;return(0,e.createElement)(n.KpiGrid,null,(0,e.createElement)(n.KpiTile,{label:r(`panelRoots`),value:a.roots.length,count:a.roots.length}),(0,e.createElement)(n.KpiTile,{label:r(`panelServer`),value:r(s?`panelReady`:`panelNotReady`)}))}const se=[`slots`,`configForms`,`locale`];exports.apply=function(e){let t=e.configForms.get(F),n=d(t);e.effect(()=>e.locale.register(F,M),`zvec-grep-card: locale dictionaries`);let r=e.locale.bind(F),i=ee(e,{remoteMissing:()=>r(`rebuildRemoteMissing`),namespaceMissing:e=>r(`rebuildNamespaceMissing`,{serviceKey:e})}),a=async(e,n)=>{try{return await t.set(e,n)}catch(t){throw console.error(`[zvec-grep] set ${e} failed:`,t),t}},o=async e=>{try{return await t.unset(e)}catch(t){throw console.error(`[zvec-grep] unset ${e} failed:`,t),t}};e.slots.inject($,()=>e.slots.register({name:$,id:`zvec-index`,order:130,label:()=>r(`indexSection`),inject:()=>({t:r,reader:i})},oe)),e.slots.inject(`plugins.bundle.config`,()=>e.slots.register({name:`plugins.bundle.config`,key:`@jayyuen66/dsh-zvec-grep`,inject:()=>({t:r,hooks:{card:n},set:a,unset:o,rebuildRemote:i})},ae))},exports.cardStore=d,exports.draftFields=h,exports.inject=se,exports.parseRebuildPoll=x;
8
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("react"),t=require("zod"),n=require("@jayyuen66/dsh-plugin-shared/client");const r=`transformers-js`,i=Object.freeze([{reference:`local/qwen3-embedding-0.6b`,backend:`llama-cpp`,dimension:1024},{reference:`local/embeddinggemma-300m`,backend:`llama-cpp`,dimension:768},{reference:`local/potion-code-16m-v2`,backend:`model2vec`,dimension:256},{reference:`local/potion-multilingual-128m`,backend:`model2vec`,dimension:256},{reference:`local/potion-retrieval-32m`,backend:`model2vec`,dimension:512},{reference:`local/bge-small-en-v1.5`,backend:r,dimension:384},{reference:`local/all-minilm-l6-v2`,backend:r,dimension:384},{reference:`local/multilingual-e5-small`,backend:r,dimension:384},{reference:`local/jina-embeddings-v2-base-code`,backend:r,dimension:768},{reference:`local/gte-modernbert-base`,backend:r,dimension:768},{reference:`local/nomic-embed-text-v1.5`,backend:r,dimension:768}].map(e=>Object.freeze(e))),a=Object.freeze([{reference:`qwen/qwen3-vl-embedding`,dimension:2560},{reference:`qwen/qwen3.7-text-embedding`,dimension:1024},{reference:`qwen/text-embedding-v4`,dimension:1024}].map(e=>Object.freeze(e)));function o(e,t){return Object.hasOwn(e,t)}function s(e,t,n){return o(e,n)?e[n]:Object.hasOwn(t,n)?t[n]:void 0}function c(e,t){return typeof e==`number`&&Number.isFinite(e)?String(e):t}function l(e){let t;return e===!0?t=`daemonReadyNote`:e===!1&&(t=`daemonOfflineNote`),t}function u(e){return e?`ok`:`warn`}function d(e){let t={status:`loading`,writable:!1,value:{}},n=null,r=t;return{getSnapshot(){let t=e.getSnapshot();return t!==n&&(n=t,r={status:t.status,writable:t.writable,value:t.value??{}}),r},subscribe(t){return e.subscribe(t)}}}function f(e,t,n,r){let i=s(e,t,n);return i===void 0?o(e,n)?``:r:c(i,r)}const p=t.z.url({protocol:/^https?$/u});function m(e,t){if(Object.hasOwn(e,`hfEndpoint`)){let t=e.hfEndpoint;return typeof t==`string`?t:``}let n=t.hfEndpoint;return typeof n==`string`&&p.safeParse(n).success?n:``}function h(e,t){let n=s(e,t,`defaultEmbedding`),r=s(e,t,`enforceSearchFirst`),i=s(e,t,`transport`);return{embedding:typeof n==`string`&&n.length>0?n:`local/qwen3-embedding-0.6b`,limitDisplay:f(e,t,`defaultLimit`,`10`),hfEndpoint:m(e,t),enforceSearchFirst:r!==!1,grepBudget:f(e,t,`grepBudgetPerSearch`,`3`),unlockWindow:f(e,t,`unlockWindowMin`,`10`),transport:i===`cli`||i===`mcp`||i===`auto`?i:`auto`}}const g=t.z.int().min(1).max(50),_=t.z.int().min(1).max(20),v=t.z.int().min(1).max(240),y=[`running`,`stopping`,`completed`,`killed`,`failed`],b=t.z.object({status:t.z.preprocess(e=>typeof e==`string`&&y.some(t=>t===e)?e:void 0,t.z.enum(y).optional()),exitCode:t.z.preprocess(e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,t.z.number().optional()),output:t.z.preprocess(e=>typeof e==`string`?e:void 0,t.z.string().optional())});function x(e,t){let n=b.safeParse(e),{status:r,exitCode:i,output:a}=n.success?n.data:{},o=a??``;if(r===`running`||r===`stopping`)return{phase:`running`,output:o.length>0?o:t(`rebuildRunning`)};if(r===`completed`&&i===0)return{phase:`done`,output:o};let s;return s=r===`killed`?t(`rebuildKilled`):r===`failed`?t(`rebuildFailed`):typeof i==`number`&&Number.isFinite(i)?t(`rebuildExitCode`,{exitCode:i}):t(`rebuildExitUnknown`),{phase:`error`,output:o.length>0?`${s}\n${o}`:s}}const S=`zvecGrepRebuild`,C=`remote.${S}`,w=`@jayyuen66/dsh-zvec-grep`,T=t.z.object({root:t.z.string({error:`rebuild request requires a string root`}).trim().min(1,{error:`rebuild request requires a non-empty root`})},{error:`rebuild request requires a string root`}),E=t.z.object({jobId:t.z.string({error:`rebuild status request requires a string jobId`}).trim().min(1,{error:`rebuild status request requires a non-empty jobId`})},{error:`rebuild status request requires a string jobId`}),D=[{id:`${w}#${S}/roots`,service:S,namespace:S,method:`roots`,invocation:{kind:`direct`},parameters:[],result:{mode:`src-json`}},{id:`${w}#${S}/rebuild`,service:S,namespace:S,method:`rebuild`,invocation:{kind:`direct`},parameters:[{name:`request`,wire:`request`,source:`json`,codec:{mode:`strict`,typeSymbol:`${w}#rebuild-request`,create:()=>({parse(e){return(0,n.parseOrThrow)(T,e,t.z.prettifyError)}})}}],result:{mode:`src-json`}},{id:`${w}#${S}/status`,service:S,namespace:S,method:`status`,invocation:{kind:`direct`},parameters:[{name:`request`,wire:`request`,source:`json`,codec:{mode:`strict`,typeSymbol:`${w}#rebuild-status-request`,create:()=>({parse(e){return(0,n.parseOrThrow)(E,e,t.z.prettifyError)}})}}],result:{mode:`src-json`}}],O=e=>(0,n.isRecord)(e)&&typeof e.roots==`function`&&typeof e.rebuild==`function`&&typeof e.status==`function`;async function k(e){let t=await e;if(t.ok)return t.value;throw Error(`${t.error.code}: ${t.error.message}`)}function A(e,t){let r,i=async()=>{let i=(0,n.remoteMounterOf)(e,!0);if(i===void 0)throw Error(t.remoteMissing());try{r??=i.$mount({package:w,descriptors:D}),await r}catch(e){throw r=void 0,e}let a=e.get?.(C);if(!O(a))throw Error(t.namespaceMissing(C));return a};return{async roots(){return k((await i()).roots())},async rebuild(e){let t=await k((await i()).rebuild({root:e}));if(t.ok)return t;throw Error(t.error)},async status(e){let t=await k((await i()).status({jobId:e}));if(t.ok)return{...t};throw Error(t.error)}}}function ee(e,t){return typeof e.get==`function`?A(e,t):void 0}const j=`https://modelscope.cn/models`,M={zh:{statusReadOnly:`当前作用域只读`,statusClean:`无未保存的修改`,dirtyCount:`已修改 {count} 项`,save:`保存`,saving:`保存中…`,revert:`撤销`,saveFailed:`保存失败:{reason}`,invalidFields:`有字段超出范围,先修正或撤销后再保存。`,saveRejected:`保存被宿主拒绝(配置校验未通过或写入被跳过),修改未生效`,modelSection:`检索模型`,fieldCount:`{count} 字段`,indexSection:`网络与索引`,unitResults:`条`,unitTimes:`次`,unitMinutes:`分钟`,outOfRange:`超出允许范围,未保存`,embeddingLabel:`默认 embedding`,embeddingHint:`本地模型直接可选;远程 qwen 模型需在插件部署配置里打开 allowRemoteEmbedding(内容会送往外部端点,首次索引需 zg --auth grant 授权)。只影响「新建」索引;切换并保存后,已有索引需点下方「重建」重新 embedding`,transportLabel:`检索传输方式`,transportHint:`自动 = 守护进程在跑时检索走 MCP(常驻模型池、队列调度),否则走 CLI;仅 CLI = 永不碰守护进程;仅 MCP = 检索恒走守护进程,缺席时由插件自动拉起(会开 127.0.0.1:7999 回环端口;拉起失败会明确报错而不是回退 CLI)`,transportAuto:`自动(守护进程在跑走 MCP,否则 CLI)`,transportCli:`仅 CLI(每次 spawn zg 进程)`,transportMcp:`仅 MCP(走守护进程,缺席自动拉起)`,backendRemote:`qwen 远程(内容出本机,需部署开放并授权)`,limitLabel:`默认每组结果数`,limitInvalid:`请输入 {min}-{max} 的整数`,limitClamped:`已钳到 {min}-{max} 范围:{value}`,endpointLabel:`HuggingFace 镜像地址`,endpointHint:`留空走 huggingface.co;国内网络可填 ${j} 等兼容镜像(仅 llama-cpp 后端生效,如 qwen3)`,enforceLabel:`强制 search-first(先 zg_search 再 grep/rg)`,enforceHint:`开启后,已建索引工作区内的 grep/rg 受配额门禁约束:每次成功 zg_search 解锁下方次数的 grep/rg(时效见下),用尽或过期后再次拦截(提高检索覆盖与准确性)`,budgetLabel:`每次 zg_search 解锁的 grep/rg 次数`,budgetHint:`配额越小语义检索越频繁、准确性约束越强;清空恢复默认 {default}`,windowLabel:`解锁时效`,windowHint:`超过该时长未再次 zg_search,配额整体过期;清空恢复默认 {default}(单位:分钟)`,rebuildLabel:`工作区重建(切换 embedding 并保存后执行)`,rebuildInputPlaceholder:`/workspace 的绝对路径`,daemonReadyNote:`守护进程:就绪(zg --server 在跑)。`,daemonOfflineNote:"守护进程:未就绪。守护进程提供的索引增量刷新、refresh=background 与常驻模型池在缺席时都不可用;需要时在终端执行 `zg --server on`。",panelRoots:`索引根`,panelServer:`索引服务`,panelReady:`就绪`,panelNotReady:`未就绪`,rebuildHint:`以当前默认模型重建:{embedding};等价于 zg --index --rebuild。{roots}`,rootsNoteWith:`候选工作区来自本 daemon 已打开过的会话(服务端白名单)。`,rootsNoteEmpty:`尚无可选工作区:先在该工作区里开一个会话(任一次工具调用即登记)。`,rebuildButton:`重建索引(动作,点击即执行)`,rebuildRunning:`重建中…`,rebuildDone:`重建完成`,rebuildStatusTitle:`重建作业`,copy:`复制`,copied:`已复制`,rebuildStarting:`正在后台重建索引…(首次会下载 embedding 模型,可能较慢)`,rebuildKilled:`重建进程被终止`,rebuildFailed:`重建作业被宿主注册表判定失败(没拿到进程退出码)`,rebuildExitCode:`重建进程退出码 {exitCode}(zg 未安装/权限不足/沙箱拒绝都会走到这里)`,rebuildExitUnknown:`重建没有可判定的结果(应答的 status 无法识别,或缺少进程退出码)`,rebuildMissingJobId:`启动重建失败:应答缺 jobId`,rebuildRootNotAbsolute:`root 必须是绝对路径(以 / 开头)`,rebuildUnavailable:`宿主没有提供工作区重建读面(未装远程服务)`,rebuildRemoteMissing:`工作区重建读面不可用:宿主网关没有提供 remote 服务`,rebuildNamespaceMissing:`{serviceKey} 未提供:宿主网关没有挂上这枚命名空间`,modelOption:`{reference}({dimension}维)`,backendLlamaCpp:`llama-cpp(原生,需 node-llama-cpp)`,backendTransformersJs:`transformers-js(纯 JS ONNX)`,backendModel2Vec:`model2vec(纯 JS worker,最轻)`},en:{statusReadOnly:`This scope is read-only`,statusClean:`No unsaved changes`,dirtyCount:`{count} changed`,save:`Save`,saving:`Saving…`,revert:`Revert`,saveFailed:`save failed: {reason}`,invalidFields:`Some fields are out of range; fix them or revert before saving.`,saveRejected:`save rejected by host (validation failed or write skipped) — changes not applied`,modelSection:`Retrieval model`,fieldCount:`{count} fields`,indexSection:`Network and index`,unitResults:`hits`,unitTimes:`times`,unitMinutes:`minutes`,outOfRange:`Out of the allowed range — not saved`,embeddingLabel:`Default embedding`,embeddingHint:`Local models are always selectable; the remote qwen models additionally require allowRemoteEmbedding in the deployment config (content leaves the machine, and the first index build needs a zg --auth grant). Affects newly built indexes only; after switching and saving, press Rebuild below to re-embed existing indexes`,transportLabel:`Search transport`,transportHint:`auto = searches go through the daemon (MCP) when it is running, CLI otherwise; CLI-only = never touch the daemon; MCP-only = searches always go through the daemon, auto-starting it when absent (opens the 127.0.0.1:7999 loopback port; a failed start is reported explicitly, never silently downgraded to CLI)`,transportAuto:`auto (daemon → MCP, otherwise CLI)`,transportCli:`CLI only (spawn zg each call)`,transportMcp:`MCP only (via daemon, auto-started when absent)`,backendRemote:`qwen remote (content leaves the machine; needs the deployment switch + grant)`,limitLabel:`Default hits per group`,limitInvalid:`enter an integer between {min} and {max}`,limitClamped:`clamped into the {min}-{max} range: {value}`,endpointLabel:`HuggingFace mirror URL`,endpointHint:`Leave empty for huggingface.co; on networks that cannot reach HF, fill a compatible mirror such as ${j} (llama-cpp backends only, e.g. qwen3)`,enforceLabel:`Enforce search-first (zg_search before grep/rg)`,enforceHint:`When on, grep/rg inside indexed workspaces is quota-gated: each successful zg_search unlocks the number of grep/rg calls below (valid for the window below), and the gate blocks again once it is spent or expired (better coverage and relevance)`,budgetLabel:`grep/rg calls unlocked per zg_search`,budgetHint:`A smaller quota means more semantic searches and a stronger relevance constraint; clear to restore the default {default}`,windowLabel:`Unlock window`,windowHint:`Without another zg_search inside this window the whole quota expires; clear to restore the default {default} (minutes)`,rebuildLabel:`Workspace rebuild (run after switching embedding and saving)`,rebuildInputPlaceholder:`absolute path to a /workspace`,daemonReadyNote:`Daemon: ready (zg --server is running).`,daemonOfflineNote:"Daemon: not ready. What the daemon provides — incremental index refresh, refresh=background and the resident embedding model pool — is unavailable while it is absent; run `zg --server on` in a terminal when you want it.",rebuildHint:`Rebuild with the current default model: {embedding}; same as zg --index --rebuild. {roots}`,panelRoots:`Index roots`,panelServer:`Index server`,panelReady:`Ready`,panelNotReady:`Not ready`,rootsNoteWith:`Candidates come from sessions this daemon already opened (server-side whitelist).`,rootsNoteEmpty:`No workspace to pick yet: open a session in that workspace first (any tool call registers it).`,rebuildButton:`Rebuild index (action, runs on click)`,rebuildRunning:`rebuilding…`,rebuildDone:`rebuild finished`,rebuildStatusTitle:`rebuild job`,copy:`Copy`,copied:`Copied`,rebuildStarting:`Rebuilding in the background… (the first run downloads the embedding model and may be slow)`,rebuildKilled:`the rebuild process was terminated`,rebuildFailed:`the host job registry reported the rebuild as failed (no process exit code)`,rebuildExitCode:`the rebuild process exited with code {exitCode} (missing zg, insufficient permissions and sandbox denials all land here)`,rebuildExitUnknown:`the rebuild has no determinable outcome (the response status is unrecognized, or its exit code is missing)`,rebuildMissingJobId:`failed to start the rebuild: the response has no jobId`,rebuildRootNotAbsolute:`root must be an absolute path (starting with /)`,rebuildUnavailable:`the host does not expose the rebuild Remote API`,rebuildRemoteMissing:`the rebuild Remote API is unavailable: the host gateway provides no remote service`,rebuildNamespaceMissing:`{serviceKey} was not provided: the host gateway did not mount this namespace`,modelOption:`{reference} ({dimension} dims)`,backendLlamaCpp:`llama-cpp (native, requires node-llama-cpp)`,backendTransformersJs:`transformers-js (pure JS ONNX)`,backendModel2Vec:`model2vec (pure JS worker, lightest)`}},N=String.fromCodePoint(92),P=/^[A-Za-z]:[\\/]/u,F=`zvec-grep`,I=[`llama-cpp`,`transformers-js`,`model2vec`],L=`zgc-rebuild-root-options`,R={"llama-cpp":`backendLlamaCpp`,"transformers-js":`backendTransformersJs`,model2vec:`backendModel2Vec`};function z(e){return e.value}function B(e,t,n){return e(`modelOption`,{reference:t,dimension:n})}function V(e,t,n){return e(`rebuildHint`,{embedding:t,roots:e(n?`rootsNoteWith`:`rootsNoteEmpty`)})}function H(e){let t=[];for(let n of I)for(let r of i)r.backend===n&&t.push({value:r.reference,label:B(e,r.reference,r.dimension),group:e(R[n])});for(let n of a)t.push({value:n.reference,label:B(e,n.reference,n.dimension),group:e(`backendRemote`)});return t}const U=[{value:`auto`},{value:`cli`},{value:`mcp`}],W={auto:`transportAuto`,cli:`transportCli`,mcp:`transportMcp`};function G(e){return U.map(t=>({value:t.value,label:e(W[t.value])}))}function K(e,t){let n=t.safeParse(e===``?NaN:Number(e));return n.success?n.data:void 0}function q(t){let{editable:r,fields:i,setField:a,t:o}=t,s=(0,e.createElement)(n.SelectField,{label:o(`embeddingLabel`),...(0,n.splitHint)(o(`embeddingHint`)),field:`defaultEmbedding`,value:i.embedding,options:H(o),disabled:!r,onChange:e=>{a(`defaultEmbedding`,e)}}),c=(0,e.createElement)(n.NumberField,{label:o(`limitLabel`),hint:o(`limitInvalid`,{min:1,max:50}),field:`defaultLimit`,value:K(i.limitDisplay,g),...(0,n.numberBoundsOf)(g,{min:1,max:50}),step:1,unit:o(`unitResults`),invalidHint:o(`outOfRange`),disabled:!r,resetToken:t.resetToken,onInvalidChange:e=>{t.reportInvalid(`defaultLimit`,e)},onChange:e=>{a(`defaultLimit`,e)}});return(0,e.createElement)(n.Section,{title:o(`modelSection`),count:o(`fieldCount`,{count:`2`})},s,c)}function J(t){let{fields:r,rebuild:i,root:a,roots:o,setRoot:s,t:c}=t,l=o.map(t=>(0,e.createElement)(`option`,{key:t,value:t})),u=(0,e.createElement)(`datalist`,{id:L},...l),d=(0,e.createElement)(`input`,{className:`dsu-input dsu-grow`,value:a,list:L,placeholder:c(`rebuildInputPlaceholder`),onChange:e=>{s(e.target.value)}}),f=(0,e.createElement)(`button`,{type:`button`,className:`dsu-btn`,"data-field":`rebuild`,disabled:i.phase===`running`,onClick:t.onRebuild},i.phase===`running`?c(`rebuildRunning`):c(`rebuildButton`));return(0,e.createElement)(n.Field,{label:c(`rebuildLabel`),...(0,n.splitHint)(V(c,r.embedding,o.length>0)),wide:!0},u,(0,e.createElement)(`div`,{className:`dsu-inlineRow`},d,f))}function Y(t){let{t:r}=t,i=l(t.serverReady);return i===void 0?null:(0,e.createElement)(`div`,{className:`dsu-inlineRow`,"data-field":`daemon-status`},(0,e.createElement)(n.StatusDot,{tone:u(t.serverReady===!0)}),(0,e.createElement)(`p`,{className:`dsu-hint`},r(i)))}function X(t){let{rebuild:r,t:i}=t;if(r.phase===`idle`)return null;if(r.phase===`error`)return(0,e.createElement)(n.Callout,{tone:`err`},r.output);let a;a=r.output===``?r.phase===`done`?i(`rebuildDone`):``:r.output;let o=(0,e.createElement)(n.LogPanel,{label:i(`rebuildStatusTitle`),tone:r.phase===`done`?`ok`:`mute`,semanticLines:!0,copyText:a,copyLabel:i(`copy`),copiedLabel:i(`copied`)},a);return r.phase===`running`?(0,e.createElement)(`div`,null,o,(0,e.createElement)(n.ProgressBar,{label:i(`rebuildRunning`)})):o}function te(t){let{editable:r,fields:i,setField:a,t:o}=t,s=(0,e.createElement)(n.SelectField,{label:o(`transportLabel`),...(0,n.splitHint)(o(`transportHint`)),field:`transport`,value:i.transport,options:G(o),disabled:!r,onChange:e=>{a(`transport`,e)}}),c=(0,e.createElement)(n.TextField,{label:o(`endpointLabel`),...(0,n.splitHint)(o(`endpointHint`)),field:`hfEndpoint`,value:i.hfEndpoint,placeholder:j,monospace:!0,disabled:!r,onChange:e=>{a(`hfEndpoint`,e.trim()===``?void 0:e.trim())}}),l=(0,e.createElement)(n.ToggleField,{label:o(`enforceLabel`),...(0,n.splitHint)(o(`enforceHint`)),field:`enforceSearchFirst`,checked:i.enforceSearchFirst,disabled:!r,onChange:e=>{a(`enforceSearchFirst`,e)}}),u=(0,e.createElement)(n.NumberField,{label:o(`budgetLabel`),...(0,n.splitHint)(o(`budgetHint`,{default:3})),field:`grepBudgetPerSearch`,value:K(i.grepBudget,_),...(0,n.numberBoundsOf)(_,{min:1,max:20}),step:1,unit:o(`unitTimes`),invalidHint:o(`outOfRange`),disabled:!r,resetToken:t.resetToken,onInvalidChange:e=>{t.reportInvalid(`grepBudgetPerSearch`,e)},onChange:e=>{a(`grepBudgetPerSearch`,e)}}),d=(0,e.createElement)(n.NumberField,{label:o(`windowLabel`),...(0,n.splitHint)(o(`windowHint`,{default:10})),field:`unlockWindowMin`,value:K(i.unlockWindow,v),...(0,n.numberBoundsOf)(v,{min:1,max:240}),step:1,unit:o(`unitMinutes`),invalidHint:o(`outOfRange`),disabled:!r,resetToken:t.resetToken,onInvalidChange:e=>{t.reportInvalid(`unlockWindowMin`,e)},onChange:e=>{a(`unlockWindowMin`,e)}});return(0,e.createElement)(n.Section,{title:o(`indexSection`),count:o(`fieldCount`,{count:`5`})},s,c,l,(0,e.createElement)(n.FieldTwoCol,null,u,d),Y(t),J(t),X(t))}function ne(t){let{t:r}=t,i=(0,e.createElement)(n.SaveBar,{dirty:t.dirty,blocked:t.blocked,busy:t.busy,writable:t.writable,error:t.saveError??(t.blocked?r(`invalidFields`):null),saveLabel:r(`save`),savingLabel:r(`saving`),revertLabel:r(`revert`),dirtyLabel:r(`dirtyCount`,{count:t.dirtyCount}),cleanLabel:r(`statusClean`),readOnlyLabel:r(`statusReadOnly`),onSave:t.onSave,onDiscard:t.onDiscard});return(0,e.createElement)(n.CardForm,null,q(t),te(t),i)}function re(e,t,n,r){t===`defaultEmbedding`?e.push(r(`defaultEmbedding`,n)):t===`defaultLimit`?e.push(r(`defaultLimit`,n)):t===`hfEndpoint`?e.push(r(`hfEndpoint`,n)):t===`enforceSearchFirst`?e.push(r(`enforceSearchFirst`,n)):t===`grepBudgetPerSearch`?e.push(r(`grepBudgetPerSearch`,n)):t===`unlockWindowMin`?e.push(r(`unlockWindowMin`,n)):t===`transport`&&e.push(r(`transport`,n))}function Z(e,t){if(e===void 0)throw Error(t(`rebuildUnavailable`));return e}const Q={roots:[],serverReady:void 0};function ie(r,i){let[a,o]=(0,e.useState)(``),[s,c]=(0,e.useState)(Q),[l,u]=(0,e.useState)({phase:`idle`,output:``}),d=(0,e.useRef)(null),f=(0,e.useRef)(!1),p=(0,e.useRef)(null),m=(0,e.useRef)(!0),h=()=>m.current;function g(){p.current=null,d.current!==null&&(clearInterval(d.current),d.current=null)}(0,e.useEffect)(()=>(m.current=!0,()=>{m.current=!1,g()}),[]);let _=(0,e.useCallback)(async()=>{let e=await Z(i,r).roots(),t={roots:[...e.roots],serverReady:e.serverReady};return c(t),t},[i,r]);(0,e.useEffect)(()=>{(async()=>{try{await _()}catch{c(Q)}})()},[_]);async function v(e){if(!f.current&&h()&&p.current===e){f.current=!0;try{let t=await Z(i,r).status(e);if(!h()||p.current!==e)return;let n=x(t,r);n.phase!==`running`&&g(),u({phase:n.phase,output:n.output})}catch(t){if(!h()||p.current!==e)return;g(),u({phase:`error`,output:(0,n.errorText)(t)})}finally{f.current=!1}}}async function y(){let e=await Z(i,r).rebuild(a.trim()),n=t.z.object({jobId:t.z.string()}).safeParse(e);if(!n.success)throw TypeError(r(`rebuildMissingJobId`));let{jobId:o}=n.data;p.current=o,d.current=setInterval(()=>{v(o)},2e3)}async function b(){let e=a.trim();if(!(e.startsWith(`/`)||P.test(e)||e.startsWith(N+N)))u({phase:`error`,output:r(`rebuildRootNotAbsolute`)});else{g(),u({phase:`running`,output:r(`rebuildStarting`)});try{await y()}catch(e){g(),u({phase:`error`,output:(0,n.errorText)(e)})}}}return{root:a,roots:s.roots,serverReady:s.serverReady,state:l,setRoot:o,start:b}}function ae(t){let{t:r}=t,i=t.useCard(e=>e),{status:a,writable:o}=i,s=a===`ready`&&o,c=z(i),[l,u]=(0,e.useState)(!1),[d,f]=(0,e.useState)(null),p=ie(r,t.rebuildRemote),{touched:m,setTouched:g,setField:_,discard:v,invalid:y,dirtyKeys:b}=(0,n.useCardDraft)(c,{onDiscard:()=>{f(null)}}),x=h(m,c),{blocked:S,fields:C,resetToken:w,reportInvalid:T}=y,E=new Set([...b,...C]).size,D=E>0||S,O=async()=>{let e=(0,n.diffTouched)(m,c);if(e.length===0||S)return;u(!0),f(null);let i=y.fields,a=[];for(let n of e){let e=m[n];e===void 0?a.push(t.unset(n)):re(a,n,e,t.set)}try{if((await Promise.all(a)).some(e=>!e)){u(!1),f(r(`saveRejected`));return}}catch(e){u(!1),f(r(`saveFailed`,{reason:(0,n.errorText)(e)}));return}let o=new Set(e),s=Object.fromEntries(Object.entries(m).filter(([e])=>!o.has(e)));u(!1),g(s),y.clear({guard:i})};return ne({t:r,fields:x,writable:s,editable:s&&!l,roots:p.roots,serverReady:p.serverReady,root:p.root,rebuild:p.state,dirty:D,blocked:S,resetToken:w,reportInvalid:T,dirtyCount:E,busy:l,saveError:d,setField:_,setRoot:p.setRoot,onSave:()=>{O()},onDiscard:v,onRebuild:()=>{p.start()}})}const $=`conversation.session.panel.section`;function oe(t){let{t:r,reader:i}=t,[a,o]=(0,e.useState)(null);if((0,e.useEffect)(()=>{let e=!0;return(async()=>{if(i!==void 0)try{let t=await i.roots();e&&o(t)}catch{}})(),()=>{e=!1}},[i]),i===void 0||a===null)return null;let s=a.serverReady===!0;return(0,e.createElement)(n.KpiGrid,null,(0,e.createElement)(n.KpiTile,{label:r(`panelRoots`),value:a.roots.length,count:a.roots.length}),(0,e.createElement)(n.KpiTile,{label:r(`panelServer`),value:r(s?`panelReady`:`panelNotReady`)}))}const se=[`slots`,`configForms`,`locale`];exports.apply=function(e){let t=e.configForms.get(F),n=d(t);e.effect(()=>e.locale.register(F,M),`zvec-grep-card: locale dictionaries`);let r=e.locale.bind(F),i=ee(e,{remoteMissing:()=>r(`rebuildRemoteMissing`),namespaceMissing:e=>r(`rebuildNamespaceMissing`,{serviceKey:e})}),a=async(e,n)=>{try{return await t.set(e,n)}catch(t){throw console.error(`[zvec-grep] set ${e} failed:`,t),t}},o=async e=>{try{return await t.unset(e)}catch(t){throw console.error(`[zvec-grep] unset ${e} failed:`,t),t}};e.slots.inject($,()=>e.slots.register({name:$,id:`zvec-index`,order:130,label:()=>r(`indexSection`),inject:()=>({t:r,reader:i})},oe)),e.slots.inject(`plugins.bundle.config`,()=>e.slots.register({name:`plugins.bundle.config`,key:`@jayyuen66/dsh-zvec-grep`,inject:()=>({t:r,hooks:{card:n},set:a,unset:o,rebuildRemote:i})},ae))},exports.cardStore=d,exports.draftFields=h,exports.inject=se,exports.parseRebuildPoll=x;
9
9
  return module.exports;
10
10
  },
11
11
  });
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`]),wt=/\.(?:exe|cmd|bat|com|ps1)$/iu,Tt=new Set([`git`,`xargs`,`env`,`nohup`,`sudo`,`time`,`timeout`,`nice`,`parallel`]),Et=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`])]]),Dt=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(`.`)),Ot=/^[A-Za-z_]\w*=/u,kt=/^\d+$/u,At=new Set([` `,` `,`\v`,`\f`]),jt=new Set([`|`,`;`,`&`,`
64
- `,`\r`,"`"]),Mt=new Set([`<`,`>`]),Nt=new Set([`(`,`)`,`{`,`}`]),Pt=new Set([`'`,`"`]);function Ft(e,t,n){return n===`win32`?t===`'`&&e!==`'`||t===`"`&&e!==`"`&&e!=="`":t===`'`&&e!==`'`||t===`"`&&e!==`"`&&e!==`\\`}function It(e,t){let n=e.indexOf(`
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=>Nn.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 Rn(e){let t=e.split(`
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 Kr(e,t){if(e.includes(`text/event-stream`))return Gr(t);try{return[JSON.parse(t)]}catch{return[]}}function qr(e,t){let n=e.find(e=>m(e)&&e.id===t);return m(n)?n:void 0}function Jr(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 q=class extends Error{constructor(e){super(e),this.name=`DaemonProtocolError`}};function Yr(e){let t=e.tokenOf();return t===void 0?{}:{Authorization:`Bearer ${t}`}}function Xr(e,t){let n={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,...Yr(e)};return t!==void 0&&(n[`mcp-session-id`]=t),n}function Zr(e){let t=Error(e);return t.name=`AbortError`,t}async function Qr(e,t,n,r,i){if(r?.aborted===!0)throw Zr(`The operation was aborted`);let a=n-Date.now();if(a<=0)throw Zr(`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:Xr(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:Kr(n.headers.get(`content-type`)??``,r)}}finally{clearTimeout(s),r?.removeEventListener(`abort`,c)}}async function $r(e,t,n,r){if(t.id!==void 0)return;let i=await Qr(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 Qr(e,{jsonrpc:`2.0`,method:`notifications/initialized`},n,r,t.id)}function ei(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 J(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 ti(e,t,n,r,i){await $r(e,t,i,n.signal);let{status:a,payloads:o}=await Qr(e,{jsonrpc:`2.0`,id:r,method:`tools/call`,params:{name:n.tool,arguments:n.args}},i,n.signal,t.id);if(Wr.has(a))throw Error(`daemon rejected the session (HTTP ${a})`);if(a!==200)throw new q(`tools/call failed with HTTP ${a}`);let s=qr(o,r);if(s===void 0)throw new q(`tools/call reply missing from response`);if(m(s.error))throw new q(JSON.stringify(s.error));let{result:c}=s;return{text:Jr(c),isError:m(c)&&c.isError===!0}}function ni(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=ei(t);try{let i=await ti(t,r,e,1,n);return J(t,r,!0),i}catch(i){if(m(i)&&i.name===`AbortError`)throw J(t,r,!1),i;if(i instanceof q)throw J(t,r,!0),i;J(t,r,!1);let a=ei(t);try{let r=await ti(t,a,e,3,n);return J(t,a,!0),r}catch(e){throw J(t,a,e instanceof q),e}}}}}const ri={short:`short`,full:`full`};function ii(e,t){let n=Me(e,t);return n===`none`||n===`short`?ri.short:ri.full}function ai(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),A(t.fuse,`fuse`,n)&&(e.fuse=!0)}function oi(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),A(t.preferSymbol,`preferSymbol`,n)&&(e.preferSymbol=!0),A(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 si(e,t){if(C(e.device,`device`,t,1024).length>0)throw Error(t.deviceUnsupportedOnDaemon);let n={root:e.root,limit:M(e.limit,t),preview:ii(e.preview,t)};ai(n,e,t);let r=Fe(e.refresh,t);return r===`wait`?n.freshness=`wait_for_fresh`:(n.freshness=`eventual`,n.autoUpdate=r===`background`),oi(n,e,t),n}const ci=864e5;function Y(e,t,n){let r=e[t];return m(r)&&n.every(e=>typeof r[e]==`function`)}function li(e){return m(e)?Y(e,`settings`,[`describe`])&&Y(e,`shell`,[`resolve`,`execute`])&&Y(e,`tools`,[`register`,`guard`])&&Y(e,`systemPrompt`,[`section`])&&Y(e,`timer`,[`timeout`])&&typeof e.get==`function`:!1}function ui(e){return JSON.stringify(e,null,2)}function di(e){let{text:t}=m(e)?e:{};if(typeof t==`string`)return[{type:`text`,text:t}];let n;try{n=ui(e)??String(e)}catch{try{n=String(e)}catch{n=`[unrenderable value]`}}return[{type:`text`,text:n}]}const fi={type:`object`,additionalProperties:!1,properties:{text:{type:`string`}}};function pi(e,t){let n=e.sandbox;return n?.runnerFailed===!0?$n(t.runnerFailed,n,t):null}function mi(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 hi(e,t){return e.length>0?b(t,{detail:e}):``}const gi=/^\s*error\[/imu;function _i(e,t){return e.length===0||gi.test(e)?``:`\n${t.noErrorCodeHint}`}function vi(e,t){let n=pi(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=mi(e,t),{sandbox:i}=e;return i?.denied===!0?b(t.deniedFailure,{exit:e.exitCode,denied:er(i,t),detail:hi(r,t.detailPrefix)}):e.exitCode===127?b(t.notInstalledFailure,{detail:hi(r,t.detailPrefix)}):`${b(t.genericFailure,{exit:e.exitCode,detail:hi(r,t.detailColon)})}${_i(r,t)}`}const yi=[`Preparing model:`,`Downloading model:`,`Model ready:`,`Scanning`,`Indexing:`,`Files processed:`,`Optimizing index`,`Saving index`,`Finishing index`];function bi(e){let t=e.trim();return yi.some(e=>t.startsWith(e))}function xi(e){return e.split(`
70
- `).filter(e=>e.trim().length>0&&!bi(e)).join(`
71
- `)}function Si(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:er(i,t)}));let{stderr:a}=e,o=xi(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 Ci(e,t){return new U(H.versionTooOld,b(t.zgVersionTooOld,{actual:Vn(e),minimum:Hn}))}async function wi(e,t,n){let r;try{let i=n(),a=W(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:qn(r)}function Ti(e,t,n){let r=0,i;return{async ensure(a){let o=Date.now();if(o-r<6e5){if(i!==void 0)throw Ci(i,a);return}let s=await wi(e,t,n);if(r=o,i=s,s!==void 0)throw Ci(s,a)}}}async function Ei(e,t,n){try{let r=n(),i=W(t,r===void 0?void 0:{ZVEC_GREP_SERVER_TOKEN:r}),a=e.shell.resolve({command:`zg --server status --check-ready`,workdir:c(),timeoutMs:1e4,stdoutMaxBytes:t.stdoutMaxBytes,...i?{env:i}:{}});return(await(await e.shell.execute(a)).result()).exitCode===0}catch{return!1}}function Di(e,t,n){let r=0,i=!1,a=!1;return{async ready(){let o=Date.now();return a&&o-r<6e4||(i=await Ei(e,t,n),r=o,a=!0),i},invalidate(){a=!1,i=!1}}}const Oi=15e3;function X(e,t){return t===void 0||t.length===0?e:e.replaceAll(t,`[token]`)}function ki(e){let t=new URL(e),n=t.protocol===`https:`?`443`:`80`;return`${t.hostname}:${t.port===``?n:t.port}`}function Ai(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=ki(i),a=t===`127.0.0.1:7999`?`zg --server on`:`zg --server on --listen ${t}`,o;try{let t=W(r,{ZVEC_GREP_SERVER_TOKEN:e}),i=n.shell.resolve({command:a,workdir:c(),timeoutMs:Oi,stdoutMaxBytes:r.stdoutMaxBytes,env:t}),s=await(await n.shell.execute(i)).result();s.exitCode!==0&&(o=X(s.stderr.text.trim().length>0?s.stderr.text.trim():`exit ${s.exitCode}`,e))}catch(t){o=X(g(t),e)}return o},m=async e=>{if(await u.ready()){if(o()===void 0){let e=await Rr(a);e!==void 0&&s(e)}return}let n=o();if(n===void 0){let{token:e,owned:r}=await Hr(a,t(24).toString(`hex`));n=e,f=r,s(n)}let r=await p(n),i=await Rr(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 U(H.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 ji(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:Oi,stdoutMaxBytes:n.stdoutMaxBytes,env:e});(await(await t.shell.execute(i)).result()).exitCode===0&&await Ur(r)}catch{}},`zvec-grep: daemon shutdown`)}const Mi=/^\s*#\d+\s+(?<rest>\S.*)$/u;function Ni(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 Pi(e){return e!==void 0&&e>=48&&e<=57}function Fi(e){let t=e.lastIndexOf(`score=`);if(t===-1)return e;let n=t+6;e[n]===`-`&&(n+=1);let r=n;for(;Pi(e.codePointAt(n));)n+=1;if(n===r)return e;if(e[n]===`.`){n+=1;let t=n;for(;Pi(e.codePointAt(n));)n+=1;if(n===t)return e}if(n!==e.length)return e;let i=t;for(;Ni(e.codePointAt(i-1));)--i;return i===t?e:e.slice(0,i)}function Ii(e,t,n,r){let i=new Set;for(let t of e.split(`
72
- `)){let e=Mi.exec(t)?.groups?.rest;e!==void 0&&i.add(Fi(e))}return i.size===0?null:b(r.hitSummary,{unique:i.size,limit:t,truncated:n?r.hitTruncated:``})}var Li=class extends U{constructor(e){super(H.rebuildLockBusy,e),this.name=`RebuildLockBusyError`}};function Ri(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 zi(e,t,n,r,i){let a=e.shell.resolve(jn({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=vi(o,i.messages),l=c===null?null:X(c,s);if(l!==null){let e=i.resolveFailure?.(l,o)??null;if(e!==null)return e;let t=zn(o.stderr.text);throw t?.kind===`lock-busy`&&t.rebuild?new Li(l):t?.kind===`lock-busy`?new U(H.lockBusy,`${b(i.messages.lockBusyOtherOperation,{op:t.ownerOperation??`unknown`})}\n${l}`):t?.kind===`permission-denied`?new U(H.permissionDenied,`${l}\n${i.messages.remoteAuthDenied}`):new U(H.commandFailed,l)}let u=Si(o,i.messages,i.stdoutMaxBytes).map(e=>X(e,s)),d=X(o.stdout.text,s);return Ri(d,u,i.summaryLimit===void 0?null:Ii(d,i.summaryLimit,o.stdout.truncated,i.messages),i.sandboxDegradeNote)}function Bi(e,t){return b(t.rebuildWaitAborted,{root:e})}function Vi(e,t,n){return b(n.rebuildWaitTimeout,{root:e,seconds:Math.round(t/1e3)})}async function Hi(e,t,n,r){try{return await r()}catch(i){let a=e.rebuilds.covering(e.root,t);if(!(i instanceof Li)||a===void 0)throw i;let o=await e.rebuilds.wait(e.root,t,e.maxWaitMs,n);if(o===`settled`)return r();throw new U(H.lockBusy,o===`aborted`?Bi(a.root,t):Vi(a.root,e.maxWaitMs,t),{cause:i})}}async function Ui(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?zi(e,t,n,r,a):Hi(o,i.messages,i.signal,()=>zi(e,t,n,r,a))}function Wi(e,t){if(!i(e))throw new U(H.rootRejected,b(t.rootMissing,{root:e}));return e}function Gi(e){return e.defaultLimit.get()??10}function Ki(e){return e.grepBudgetPerSearch.get()??3}function qi(e){return e.unlockWindowMin.get()??10}function Ji(e){return e.enforceSearchFirst.get()??!0}function Yi(e){let t=e;return e.startsWith(`\\\\?\\UNC\\`)?t=`\\\\${e.slice(8)}`:e.startsWith(`\\\\?\\`)&&(t=e.slice(4)),ht(t.replaceAll(`/`,`\\`)).toLowerCase()}function Z(e,t=process.platform){return t===`win32`?Yi(e):t===`darwin`&&e.startsWith(`/private/`)?e.slice(8):e}function Xi(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&&Z(R(s,n),process.platform)===Z(R(t,n),process.platform)}function Zi(e,t=`posix`){let n=l.join(e,dn),r=l.join(n,`manifest.json`);return!i(n)||!i(r)?!1:Xi(r,e,t)}function Qi(e,t,n,r,i){let a;try{a=Wi(Ve(e,t,n,i),n)}catch(e){return{allowed:!1,reason:g(e)}}return t!==void 0&&Z(R(a,i),process.platform)===Z(R(t,i),process.platform)||r.has(a)?{allowed:!0,root:a,question:void 0}:t!==void 0&&rn(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 $i(e,t,n,r,i){let a=Qi(e.root,B(t),n,r,i);if(!a.allowed)throw new U(H.rootRejected,a.reason);return r.add(a.root),a.root}function ea(e,t,n){return(t?e*2+n:e)+6e4}function ta(e,t){let{root:n}=e;return typeof n==`string`&&n.length>0?n:t}function na(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 ra(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:fi,render:(e,t)=>di(t)},execute:async(e,n)=>{let i=t.messages();if(!m(e))throw new U(H.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 U(H.badArguments,b(i.missingRequiredArgs,{name:t.name,fields:a.join(`, `)}));return await t.run(e,n,i)}})}const ia=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 aa(e,t,n){let r;try{r=j(e,t,n)}catch{r=void 0}return r===void 0||n!==`win32`?r:r.toLowerCase()}function oa(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 Q(e,t,n){e.delete(t),e.set(t,n)}const sa=6e4,ca=32;function la(e,t=Date.now,n=sa,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 Q(i,a,s),s.result;let c=e(a);return i.delete(a),i.set(a,{result:c,probedAt:o}),oa(i,r,e=>e.probedAt+n,o),c};return o.invalidate=a,o}function ua(e,t=64,n=Date.now,r=ci,i=`posix`){let a=new Map;return{add(o){let s=aa(o,e,i);s!==void 0&&(Q(a,s,{root:o,seenAt:n()}),oa(a,t,e=>e.seenAt+r,n()))},has(t){let o=aa(t,e,i);if(o===void 0)return!1;let s=a.get(o);return s===void 0||n()-s.seenAt>=r?!1:(Q(a,o,s),!0)},list(){let e=n();return[...a.values()].filter(t=>e-t.seenAt<r).map(e=>e.root)}}}function da(e){e.inject([`settings`],t=>{t.effect(()=>t.settings.configure({auto:!1},e.fiber))})}function fa(e){return()=>re(Ce,ie(e.settings.describe().find(e=>e.ns===ne)?.value))}function pa(e,t){let n=B(t);n!==void 0&&e.add(n)}function ma(){}function ha(e,t){return _n(t,e.sessionParent)}function ga(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(R(a,n),{grepsLeft:Ki(e),expiresAt:t()+qi(e)*6e4}),Q(r,i,o),oa(r,256,ma,t())},lookup(e,i){let a=r.get(e),o=a===void 0?void 0:a.get(R(i,n));return a!==void 0&&o!==void 0&&o.expiresAt>t()&&Q(r,e,a),o},consume(e){--e.grepsLeft}}}function $(e){return{oneOf:[{type:`string`},{type:`array`,items:{type:`string`}}],description:e}}function _a(e,t){return{type:`string`,enum:[...e],description:t}}function va(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:_a(Ae,e.previewDescription),refresh:_a(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 ya(e,t,n){return e?`files`:t===void 0?n?`indexed`:`exhaustive`:t?`exhaustive`:`indexed`}async function ba(e,t,n,r){return!r||!Ie(t)?`daemon-down`:n===`direct`?`mode-direct`:await e.serverGate.ready()?`available`:`daemon-down`}async function xa(e,t){let n=ur(e.config.transport.get());return n===`mcp`?(await e.daemon.ensure(t),`mcp`):n===`cli`?`cli`:await e.serverGate.ready()?`mcp`:`cli`}function Sa(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 Ca(e,t){let n=b(t.genericFailure,{exit:1,detail:hi(Sa(e,t),t.detailColon)}),r=zn(e);return r?.kind===`lock-busy`&&r.rebuild?new Li(n):r?.kind===`lock-busy`?new U(H.lockBusy,`${b(t.lockBusyOtherOperation,{op:r.ownerOperation??`unknown`})}\n${n}`):r?.kind===`permission-denied`?new U(H.permissionDenied,`${n}\n${t.remoteAuthDenied}`):new U(H.commandFailed,n)}function wa(e,t,n,r){if(!(m(e)&&e.name===`AbortError`)){let t=X(g(e),r);return new U(H.daemonUnavailable,b(n.mcpCallFailed,{detail:t}),{cause:e})}return new U(H.daemonUnavailable,t.signal.aborted?n.abortedFailure:n.timeoutFailure)}function Ta(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=Ii(a,n,i,r);return s!==null&&o.push(s),o.length>0?`${a}\n${o.join(`
74
- `)}`:a}async function Ea(e,t,n,r,i){let{config:a}=e,o=si(t,n),s=M(t.limit,n);return Hi(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 Pn(wa(t,r,n,e.daemon.tokenOf()).message,i)}if(i)throw Ca(X(t,e.daemon.tokenOf()),n);return Ta(t,a.stdoutMaxBytes,s,n)})}async function Da(e,t,n,r,i){if(await xa(e,n)!==`mcp`)return{text:void 0,fallbackNote:void 0};try{return{text:await Ea(e,t,n,r,i),fallbackNote:void 0}}catch(a){let o=ur(e.config.transport.get());if(a instanceof Pn&&!a.aborted&&o===`mcp`)return await e.daemon.ensure(n),{text:await Ea(e,t,n,r,i),fallbackNote:void 0};if(!(a instanceof Pn)||a.aborted||o!==`auto`)throw a;return{text:void 0,fallbackNote:b(n.daemonFallbackNote,{detail:a.message})}}}async function Oa(e,t,n,r){let{config:i,host:a,indexProbe:o,ledger:s,unlocks:c}=e;pa(s,n);let l=$i(t,n,r,s,e.platform),u=hn(l,o,void 0,e.platform),d=t.rg===void 0||t.rg===null?void 0:A(t.rg,`rg`,r),f=ya(A(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??Gi(i)}};await e.versionGate.ensure(r);let h;if(f===`indexed`){let t=await Da(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(ha(e,n),u),{text:t.text}}let g=G(i,r),{command:_,workdir:ee}=$e(m,r,g,f,await ba(e,t.refresh,g,f===`indexed`)),te=An(a,n),ne=await Ui(a,_,ee,i.searchTimeoutMs,{signal:n.signal,env:W(i,e.daemonEnv()),stdoutMaxBytes:i.stdoutMaxBytes,messages:r,sandboxPolicy:te.policy,sandboxDegradeNote:Mn(te,r),summaryLimit:M(m.limit,r),rebuildWait:{root:l,rebuilds:e.rebuilds,maxWaitMs:i.rebuildWaitMs}});u!==void 0&&f===`indexed`&&c.grant(ha(e,n),u);let re=[h,p].filter(e=>e!==void 0).join(`
75
- `);return{text:re.length===0?ne:`${re}\n${ne}`}}function ka(e,t){ra(e.host,{name:`zg_search`,description:t.searchToolDescription,messages:e.messages,parameters:va(t),concurrencySafe:!0,timeoutMs:ea(e.config.searchTimeoutMs,!0,e.config.rebuildWaitMs),presentCall:e=>({card:`generic`,title:na(e),kind:`search`}),run:(t,n,r)=>Oa(e,t,n,r)})}function Aa(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 ja(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 U(H.daemonUnavailable,r.messages.endpointJobsUnavailable);let o=cr(e.config),s=An(e.host,r.exec),c=await jr(a,r.messages,n,o,s.policy);if(`error`in c)throw e.rebuilds.release(t,i),new U(H.commandFailed,c.error);let l=Mr(a,t,r.messages,c,i);if(`error`in l)throw e.rebuilds.release(t,i),new U(H.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=Mn(s,r.messages);return{text:d===``?u:`${u}\n${d}`}}async function Ma(e,t,n,r){let{config:i,host:a,ledger:o,rebuilds:s}=e;pa(o,n);let c=$i(t,n,r,o,e.platform),l={...t,root:c,platform:e.platform},u=A(t.background,`background`,r),d=A(t.rebuild,`rebuild`,r)||u;A(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 ja(e,c,l,{exec:n,messages:r},t);f=t}try{Zn(l,c,r);let{command:t,workdir:o}=dt(l,cr(i),r,G(i,r),or(i)),s=An(a,n),u=await Ui(a,t,o,i.indexTimeoutMs,{signal:n.signal,env:W(i,e.daemonEnv()),stdoutMaxBytes:i.stdoutMaxBytes,messages:r,sandboxPolicy:s.policy,sandboxDegradeNote:Mn(s,r)});return e.indexProbe.invalidate(c),{text:u}}finally{f!==void 0&&s.release(c,f)}}function Na(e,t){ra(e.host,{name:`zg_index`,description:t.indexToolDescription,messages:e.messages,parameters:Aa(t),concurrencySafe:!1,timeoutMs:ea(e.config.indexTimeoutMs,!1,e.config.rebuildWaitMs),presentCall:e=>({card:`generic`,title:ta(e,`zg_index`),kind:`other`}),run:(t,n,r)=>Ma(e,t,n,r)})}async function Pa(e,t,n,r){let{config:i,host:a,ledger:o,rebuilds:s}=e;pa(o,n);let c=$i(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=A(t.checkReady,`checkReady`,r);await e.versionGate.ensure(r);let{command:d,workdir:f}=ft({root:c,checkReady:u,platform:e.platform},r,G(i,r)),p=An(a,n),m=await Ui(a,d,f,i.statusTimeoutMs,{signal:n.signal,env:W(i,e.daemonEnv()),stdoutMaxBytes:i.stdoutMaxBytes,messages:r,sandboxPolicy:p.policy,sandboxDegradeNote:Mn(p,r),rebuildWait:{root:c,rebuilds:s,maxWaitMs:i.rebuildWaitMs},...u?{resolveFailure:(e,t)=>{if(t.timedOut||t.aborted||t.sandbox?.denied===!0||zn(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=G(i,r),g=await e.serverGate.ready(),_=null;return h!==`direct`&&(_=g?r.serverReadyNote:r.serverUnavailableNote),_===null?{text:m}:{text:`${m}\n${_}`}}function Fa(e,t){ra(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:ea(e.config.statusTimeoutMs,!0,e.config.rebuildWaitMs),presentCall:e=>({card:`generic`,title:ta(e,`zg_status`),kind:`read`}),run:(t,n,r)=>Pa(e,t,n,r)})}function Ia(e,t){ka(e,t),Na(e,t),Fa(e,t)}function La(e,t){e.systemPrompt.section({name:`zvec-grep-routing`,order:1550,text:t.routingSummary}),Jn(e,t.routingText,t.skillDescription)}function Ra(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=Qi(i,B(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 za(e){let{config:t,host:n,ledger:r,messages:i}=e;n.on(`tools/pre-execute`,(n,a)=>{if(!t.requireApprovalForExplicitRoot||!on(n.name))return a();let o=Ra(n,r,i(),e.platform);return o===void 0?a():Promise.resolve(o)})}function Ba(e){let{config:t,host:n,indexProbe:r,ledger:i,messages:a,rebuilds:o,unlocks:s}=e;n.tools.guard(n=>{pa(i,n);let c=a(),l=un(n,c,e.platform);return l===void 0?wn(n,{enabled:Ji(t),platform:e.platform,indexProbe:r,now:()=>Date.now(),grepBudget:Ki(t),windowMin:qi(t),lookupUnlock:t=>s.lookup(ha(e,n),t),consumeGrep:e=>{s.consume(e)},rebuildBypass:e=>o.covering(e,c)!==void 0},c):l})}function Va(e,t){if(!li(e))throw Error(`[zvec-grep] required services (settings/shell/tools/systemPrompt/timer/get) missing`);let n=e,r=pt();if(!oe({get:n.get,reflect:n.reflect},`@jayyuen66/dsh-zvec-grep/instance`)){console.warn(`[zvec-grep] 检测到本插件已在同一作用域内装载:本次装配让路,工具与设置卡由在册的那一份提供。`);return}da(n);let i=fa(n),a=ua(i(),64,Date.now,ci,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=dr(t.daemonUrl,i()),u=Lr(),d=Ti(n,t,s),f=Di(n,t,s),p={host:n,platform:r,config:t,messages:i,ledger:a,unlocks:ga(t,Date.now,r),indexProbe:la(e=>Zi(e,r)),rebuilds:On({platform:r}),versionGate:d,serverGate:f,daemon:Ai({host:n,config:t,daemonUrl:l,tokenFile:u,tokenOf:s,setToken:e=>{o.token=e},markStarted:()=>{o.startedByUs=!0},serverGate:f}),daemonEnv:c,daemonClient:ni({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();Ia(p,m),La(n,m),Ba(p),za(p),ji({host:n,config:t,tokenFile:u,daemonEnv:c,startedByUs:()=>o.startedByUs}),Fr(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 Ha={inject:[`settings`,`shell`,`tools`,`systemPrompt`,`timer`],Config:ia,apply:Va};export{ia as Config,ca as INDEX_PROBE_CACHE_MAX,sa as INDEX_PROBE_TTL_MS,Z as comparablePath,la as createIndexProbeCache,ua as createRootLedger,ga as createUnlockLedger,Ha as default,Ii as hitSummary,X as redactToken,xi as signalStderr};
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.22",
3
+ "version": "0.1.24",
4
4
  "description": "dsh 工作区语义检索插件(zg):zg_search / zg_index / zg_status + 本地 embedding 设置卡片 + systemPrompt 路由规则 + guard 安全兜底。",
5
5
  "keywords": [
6
6
  "cordis",
@@ -51,7 +51,7 @@
51
51
  "registry": "https://registry.npmjs.org"
52
52
  },
53
53
  "dependencies": {
54
- "@jayyuen66/dsh-plugin-shared": "^0.3.2",
54
+ "@jayyuen66/dsh-plugin-shared": "^0.3.3",
55
55
  "zod": "4.6.7"
56
56
  },
57
57
  "devDependencies": {
@@ -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",
@@ -104,14 +105,14 @@
104
105
  "eslint-plugin-sonarjs": "4.2.3",
105
106
  "eslint-plugin-zod": "5.4.0",
106
107
  "fast-check": "4.11.0",
107
- "oxfmt": "0.80.0",
108
- "oxlint": "1.95.0",
108
+ "oxfmt": "0.81.0",
109
+ "oxlint": "1.96.0",
109
110
  "oxlint-tsgolint": "7.0.2009",
110
111
  "react": "19.3.1",
111
112
  "react-dom": "19.3.1",
112
113
  "rolldown": "1.3.4",
113
114
  "typescript": "7.0.2",
114
- "vite": "8.4.0",
115
+ "vite": "8.4.1",
115
116
  "vitest": "5.1.2"
116
117
  },
117
118
  "peerDependencies": {