@jayyuen66/dsh-zvec-grep 0.1.17 → 0.1.19

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/client.js CHANGED
@@ -5,1668 +5,9 @@ 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" });
9
- let react = require("react");
10
- let zod = require("zod");
11
- // lib/embedding-catalog.ts
12
- /** 默认模型:本地最强(1024 维 / 8192 上下文 / 中英通用),约 640MB 一次性下载。 */
13
- const DEFAULT_EMBEDDING = "local/qwen3-embedding-0.6b";
14
- /**
15
- * transformers.js 后端的 id。清单里 384/768 维的那批纯 JS ONNX 小模型都挂这一档,
16
- * 故取值归一处;带 `LocalEmbeddingBackend` 标注,枚举成员改名时这里当场编译红,
17
- * 而不是静默产出一个不在联合里的字符串。
18
- */
19
- const TRANSFORMERS_JS_BACKEND = "transformers-js";
20
- const LOCAL_EMBEDDINGS = Object.freeze([
21
- {
22
- reference: "local/qwen3-embedding-0.6b",
23
- backend: "llama-cpp",
24
- dimension: 1024
25
- },
26
- {
27
- reference: "local/embeddinggemma-300m",
28
- backend: "llama-cpp",
29
- dimension: 768
30
- },
31
- {
32
- reference: "local/potion-code-16m-v2",
33
- backend: "model2vec",
34
- dimension: 256
35
- },
36
- {
37
- reference: "local/potion-multilingual-128m",
38
- backend: "model2vec",
39
- dimension: 256
40
- },
41
- {
42
- reference: "local/potion-retrieval-32m",
43
- backend: "model2vec",
44
- dimension: 512
45
- },
46
- {
47
- reference: "local/bge-small-en-v1.5",
48
- backend: TRANSFORMERS_JS_BACKEND,
49
- dimension: 384
50
- },
51
- {
52
- reference: "local/all-minilm-l6-v2",
53
- backend: TRANSFORMERS_JS_BACKEND,
54
- dimension: 384
55
- },
56
- {
57
- reference: "local/multilingual-e5-small",
58
- backend: TRANSFORMERS_JS_BACKEND,
59
- dimension: 384
60
- },
61
- {
62
- reference: "local/jina-embeddings-v2-base-code",
63
- backend: TRANSFORMERS_JS_BACKEND,
64
- dimension: 768
65
- },
66
- {
67
- reference: "local/gte-modernbert-base",
68
- backend: TRANSFORMERS_JS_BACKEND,
69
- dimension: 768
70
- },
71
- {
72
- reference: "local/nomic-embed-text-v1.5",
73
- backend: TRANSFORMERS_JS_BACKEND,
74
- dimension: 768
75
- }
76
- ].map((entry) => Object.freeze(entry)));
77
- const REMOTE_EMBEDDING_CATALOG = Object.freeze([
78
- {
79
- reference: "qwen/qwen3-vl-embedding",
80
- dimension: 2560
81
- },
82
- {
83
- reference: "qwen/qwen3.7-text-embedding",
84
- dimension: 1024
85
- },
86
- {
87
- reference: "qwen/text-embedding-v4",
88
- dimension: 1024
89
- }
90
- ].map((entry) => Object.freeze(entry)));
91
- // node_modules/@jayyuen66/dsh-plugin-shared/dist/card-ui-yf56_khz.js
92
- const c = `
93
- .dsu-form{display:flex;flex-direction:column}
94
- .dsu-section{margin-top:24px;padding-top:24px;border-top:.5px solid var(--dsw-alias-border-l1)}
95
- .dsu-form>.dsu-section:first-child{margin-top:0;padding-top:0;border-top:0}
96
- .dsu-sectionTitle{margin:0;font-size:15px;font-weight:600;line-height:1.4;color:var(--dsw-alias-label-primary)}
97
- .dsu-sectionHint{margin:4px 0 0;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-tertiary)}
98
- .dsu-statusbar{display:flex;flex-wrap:wrap;gap:4px 8px;margin-top:8px;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-tertiary)}
99
- .dsu-field{display:grid;grid-template-columns:minmax(0,1fr) minmax(240px,360px);column-gap:32px;align-items:center;padding:12px 0;border-top:.5px solid var(--dsw-alias-border-l2)}
100
- .dsu-fieldMeta{display:flex;flex-direction:column;gap:4px;min-width:0}
101
- .dsu-labelRow{display:flex;align-items:center;gap:6px;min-width:0}
102
- .dsu-label{font-size:13px;font-weight:500;line-height:1.5;color:var(--dsw-alias-label-primary)}
103
- .dsu-labelMono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px}
104
- .dsu-hint{margin:0;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-tertiary)}
105
- .dsu-control{min-width:0;display:flex;align-items:center;gap:8px}
106
- .dsu-fieldWide{grid-template-columns:minmax(0,1fr);align-items:start}
107
- .dsu-fieldWide .dsu-control{width:100%;max-width:720px;margin-top:2px}
108
- .dsu-help{display:inline-flex;align-items:center;gap:6px;min-width:0}
109
- .dsu-helpBtn{appearance:none;border:0;background:transparent;padding:0;width:16px;height:16px;display:inline-flex;align-items:center;justify-content:center;color:var(--dsw-alias-label-tertiary);cursor:help;border-radius:50%;flex:none}
110
- .dsu-help:hover .dsu-helpBtn,.dsu-helpBtn:focus-visible{color:var(--dsw-alias-label-primary)}
111
- .dsu-helpBtn:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:1px}
112
- .dsu-tip{width:max-content;position:fixed;position-area:block-end span-inline-end;justify-self:start;margin-top:8px;z-index:60;box-sizing:border-box;max-width:min(340px,calc(100vw - 16px));max-height:calc(100vh - 16px);overflow:auto;overflow-wrap:anywhere;padding:10px 12px;border-radius:10px;background:var(--dsw-alias-bg-layer-2);border:.5px solid var(--dsw-alias-border-l3);box-shadow:0 12px 32px rgb(0 0 0 / 45%);font-size:12px;line-height:1.6;font-weight:400;color:var(--dsw-alias-label-secondary)}
113
- .dsu-input{width:100%;height:34px;padding:0 12px;border:.5px solid var(--dsw-alias-border-l4);border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-layer-3);color:var(--dsw-alias-label-primary);font:inherit;font-size:13px}
114
- .dsu-input:focus-visible{outline:none;border-color:var(--dsw-alias-state-business-primary)}
115
- .dsu-input[aria-invalid="true"]{border-color:var(--dsw-alias-state-error-primary)}
116
- .dsu-input:disabled{color:var(--dsw-alias-label-tertiary);cursor:not-allowed}
117
- .dsu-input::placeholder{color:var(--dsw-alias-label-tertiary)}
118
- .dsu-textarea{height:auto;min-height:96px;padding:8px 12px;line-height:1.6;resize:vertical}
119
- .dsu-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
120
- .dsu-numberWrap{display:flex;flex-direction:column;gap:4px;width:100%;min-width:0}
121
- .dsu-number{display:flex;align-items:center;gap:8px;min-width:0}
122
- .dsu-number .dsu-input{min-width:0}
123
- .dsu-unit{flex:none;font-size:12px;color:var(--dsw-alias-label-tertiary)}
124
- .dsu-error{margin:0;font-size:12px;line-height:1.5;color:var(--dsw-alias-state-error-primary)}
125
- .dsu-switch{appearance:none;width:36px;height:20px;border-radius:999px;border:0;padding:2px;background:var(--dsw-alias-border-l3);display:flex;align-items:center;cursor:pointer;flex:none;transition:background-color .16s}
126
- .dsu-knob{width:16px;height:16px;border-radius:50%;background:var(--dsw-alias-label-primary);transition:transform .16s,background-color .16s}
127
- .dsu-switch[aria-checked="true"]{background:var(--dsw-alias-label-primary)}
128
- .dsu-switch[aria-checked="true"] .dsu-knob{transform:translateX(16px);background:var(--dsw-alias-label-primary-foreground)}
129
- .dsu-switch:disabled{opacity:.4;cursor:not-allowed}
130
- .dsu-switch:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px}
131
- .dsu-selectWrap{position:relative;width:100%;min-width:0}
132
- .dsu-select{display:flex;align-items:center;justify-content:space-between;gap:8px;text-align:left;cursor:pointer}
133
- .dsu-select[aria-expanded="true"]{border-color:var(--dsw-alias-state-business-primary)}
134
- .dsu-selectValue{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
135
- .dsu-chevron{flex:none;color:var(--dsw-alias-label-tertiary);transition:transform .16s}
136
- .dsu-select[aria-expanded="true"] .dsu-chevron{transform:rotate(180deg)}
137
- .dsu-menu{position:fixed;position-area:block-end span-inline-end;justify-self:start;margin-top:6px;z-index:70;padding:4px;background:var(--dsw-alias-bg-layer-2);border:.5px solid var(--dsw-alias-border-l3);border-radius:12px;box-shadow:0 12px 32px rgb(0 0 0 / 50%);max-height:280px;overflow:auto}
138
- .dsu-option{appearance:none;border:0;background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;line-height:1.4;width:100%;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:8px 10px;border-radius:8px;cursor:pointer;text-align:left}
139
- .dsu-option:hover,.dsu-option[data-active="true"]{background:var(--dsw-alias-bg-layer-3)}
140
- .dsu-option:disabled{color:var(--dsw-alias-label-tertiary);cursor:not-allowed}
141
- .dsu-option:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:-2px}
142
- .dsu-optionGroup{padding:6px 10px 2px;font-size:11px;font-weight:600;color:var(--dsw-alias-label-tertiary)}
143
- .dsu-check{opacity:0;flex:none}
144
- .dsu-option[aria-selected="true"] .dsu-check{opacity:1}
145
- .dsu-savebar{display:flex;align-items:center;gap:8px;padding:12px 0;margin-top:24px;border-top:.5px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-base)}
146
- .dsu-savebar[data-dirty="true"]{position:sticky;bottom:0;z-index:2;box-shadow:0 -12px 24px rgb(0 0 0 / 35%)}
147
- .dsu-btn{appearance:none;border:.5px solid var(--dsw-alias-border-l2);background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;line-height:1.5;border-radius:var(--dsw-radius-md);padding:5px 14px;cursor:pointer;transition:background-color .12s,border-color .12s,color .12s,filter .12s}
148
- .dsu-btn:hover:not(:disabled){background:var(--dsw-alias-bg-layer-2);border-color:var(--dsw-alias-border-l3)}
149
- .dsu-btn:active:not(:disabled){background:var(--dsw-alias-bg-layer-1)}
150
- .dsu-btn:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:1px}
151
- .dsu-btn:disabled{opacity:.4;cursor:not-allowed}
152
- .dsu-btnPrimary{background:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-layer-3)}
153
- .dsu-btnPrimary:hover:not(:disabled){background:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-primary);filter:brightness(.9)}
154
- .dsu-btnPrimary:active:not(:disabled){background:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-primary);filter:brightness(.84)}
155
- .dsu-btnDanger{color:var(--dsw-alias-state-error-primary)}
156
- .dsu-btnDanger:hover:not(:disabled){color:var(--dsw-alias-state-error-primary);border-color:var(--dsw-alias-state-error-primary);background:var(--dsw-alias-bg-layer-2)}
157
- .dsu-status{margin-left:auto;font-size:12px;color:var(--dsw-alias-label-tertiary)}
158
- .dsu-statusError{color:var(--dsw-alias-state-error-primary)}
159
- .dsu-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(200px,100%),1fr));gap:0 24px}
160
- .dsu-grid>.dsu-field{display:flex;flex-direction:column;align-items:stretch;gap:6px;padding:10px 0;border-top:.5px solid var(--dsw-alias-border-l1)}
161
- .dsu-grid>.dsu-field .dsu-control{width:100%}
162
- @media (max-width:640px){
163
- .dsu-field{grid-template-columns:minmax(0,1fr);align-items:start}
164
- .dsu-control{width:100%;max-width:720px}
165
- .dsu-section{margin-top:20px;padding-top:20px}
166
- }
167
- @media (prefers-reduced-motion:reduce){
168
- .dsu-switch,.dsu-knob,.dsu-chevron,.dsu-btn{transition:none}
169
- }
170
- `;
171
- function l(e, t = 30) {
172
- return e.length <= t ? { hint: e } : { detail: e };
173
- }
174
- function u(t) {
175
- return (0, react.createElement)(`div`, { className: `dsu-form` }, t.children);
176
- }
177
- function d(t) {
178
- return (0, react.createElement)(`section`, { className: `dsu-section` }, (0, react.createElement)(`h2`, { className: `dsu-sectionTitle` }, t.title), t.hint === void 0 ? null : (0, react.createElement)(`p`, { className: `dsu-sectionHint` }, t.hint), t.children);
179
- }
180
- function m() {
181
- return `happyDOM` in globalThis ? !1 : typeof CSS < `u` && typeof CSS.supports == `function` && CSS.supports(`position-area: block-end`);
182
- }
183
- function h(e, t) {
184
- let n = Math.abs(t.left - e.left) <= 2, r = Math.abs(t.right - e.right) <= 2;
185
- if (!n && !r) return !0;
186
- let i = t.top >= e.bottom - 2, a = t.bottom <= e.top + 2;
187
- return !i && !a;
188
- }
189
- function g(a) {
190
- let c = (0, react.useId)(), l = `--dsu-tip-${c.replaceAll(/[^a-zA-Z0-9]/gu, ``)}`, [u, d] = (0, react.useState)(!1), f = (0, react.useRef)(!1), p = (0, react.useRef)(!1), g = (0, react.useRef)(!1), _ = (0, react.useRef)(null), v = (0, react.useRef)(null), y = (0, react.useRef)(null), b = (0, react.useRef)(null), x = (0, react.useCallback)(() => {
191
- b.current !== null && (clearTimeout(b.current), b.current = null);
192
- }, []), S = (0, react.useCallback)(() => {
193
- let e = v.current, t = y.current;
194
- /* v8 ignore next 3 -- place 只在 open 的 layout effect 与挂载期监听器里调用;refs 为空只可能是卸载竞态 */
195
- if (e === null || t === null) return;
196
- let n = m() && t.style.positionArea !== `none`, r = e.getBoundingClientRect();
197
- if (n && !h(r, t.getBoundingClientRect())) return;
198
- n && (t.style.positionArea = `none`), t.style.marginTop = `0px`;
199
- let i = t.offsetWidth, a = t.offsetHeight, { left: o } = r, s = r.bottom + 8;
200
- s + a > window.innerHeight - 8 && (s = r.top - a - 8), o + i > window.innerWidth - 8 && (o = window.innerWidth - i - 8);
201
- let c = Math.max(8, window.innerWidth - i - 8), l = Math.max(8, window.innerHeight - a - 8);
202
- t.style.left = `${Math.min(Math.max(8, o), c)}px`, t.style.top = `${Math.min(Math.max(8, s), l)}px`;
203
- }, []), C = (0, react.useCallback)(() => {
204
- x(), g.current = !1, d(!1);
205
- }, [x]), w = (0, react.useCallback)(() => {
206
- x(), d(!0);
207
- }, [x]), T = (0, react.useCallback)(() => {
208
- x(), f.current || p.current || g.current || (b.current = setTimeout(() => {
209
- /* v8 ignore next 3 -- 任何重新进入/钉住都会 cancelHide;这次复查只防未来的异步路径 */
210
- b.current = null, f.current || p.current || g.current || d(!1);
211
- }, 120));
212
- }, [x]), E = (0, react.useCallback)((e) => {
213
- g.current = e;
214
- }, []);
215
- (0, react.useLayoutEffect)(() => {
216
- if (!u) return () => {};
217
- S();
218
- let e = (e) => {
219
- let { target: t } = e;
220
- t instanceof Node && y.current?.contains(t) === !0 || (g.current ? S() : C());
221
- }, t = () => {
222
- S();
223
- }, n = (e) => {
224
- let t = e.target;
225
- _.current?.contains(t) !== !0 && C();
226
- };
227
- return document.addEventListener(`pointerdown`, n, !0), window.addEventListener(`scroll`, e, !0), window.addEventListener(`resize`, t), () => {
228
- document.removeEventListener(`pointerdown`, n, !0), window.removeEventListener(`scroll`, e, !0), window.removeEventListener(`resize`, t);
229
- };
230
- }, [
231
- u,
232
- a.detail,
233
- S,
234
- C
235
- ]), (0, react.useEffect)(() => {
236
- if (!u) return () => {};
237
- let e = (e) => {
238
- e.key === `Escape` && C();
239
- };
240
- return document.addEventListener(`keydown`, e), () => {
241
- document.removeEventListener(`keydown`, e);
242
- };
243
- }, [u, C]), (0, react.useEffect)(() => x, [x]);
244
- let D = (0, react.createElement)(`button`, {
245
- ref: v,
246
- type: `button`,
247
- className: `dsu-helpBtn`,
248
- style: { anchorName: l },
249
- "aria-label": `${a.label} 说明`,
250
- "aria-expanded": u,
251
- "aria-controls": c,
252
- onClick: () => {
253
- g.current ? C() : (E(!0), w());
254
- }
255
- }, (0, react.createElement)(`svg`, {
256
- width: 12,
257
- height: 12,
258
- viewBox: `0 0 14 14`,
259
- "aria-hidden": !0
260
- }, (0, react.createElement)(`circle`, {
261
- cx: 7,
262
- cy: 7,
263
- r: 6,
264
- fill: `none`,
265
- stroke: `currentColor`,
266
- strokeWidth: 1.2
267
- }), (0, react.createElement)(`path`, {
268
- d: `M7 6.2v4`,
269
- stroke: `currentColor`,
270
- strokeWidth: 1.3,
271
- strokeLinecap: `round`
272
- }), (0, react.createElement)(`circle`, {
273
- cx: 7,
274
- cy: 4.3,
275
- r: .8,
276
- fill: `currentColor`
277
- }))), O = (0, react.createElement)(`div`, {
278
- ref: y,
279
- id: c,
280
- role: `tooltip`,
281
- className: `dsu-tip`,
282
- style: {
283
- positionAnchor: l,
284
- positionTryFallbacks: `flip-block, flip-inline`
285
- },
286
- hidden: !u
287
- }, a.detail), k = a.showLabel === !1 ? null : (0, react.createElement)(`span`, { className: `dsu-label${a.compact === !0 ? ` dsu-labelMono` : ``}` }, a.label);
288
- return (0, react.createElement)(`span`, {
289
- ref: _,
290
- className: `dsu-help`,
291
- onMouseEnter: () => {
292
- f.current = !0, w();
293
- },
294
- onMouseLeave: () => {
295
- f.current = !1, T();
296
- },
297
- onFocus: () => {
298
- p.current = !0, w();
299
- },
300
- onBlur: (e) => {
301
- let t = e.relatedTarget;
302
- t instanceof Node && e.currentTarget.contains(t) || (p.current = !1, T());
303
- }
304
- }, k, D, O);
305
- }
306
- function _(t) {
307
- let n = `dsu-label${t.compact === !0 ? ` dsu-labelMono` : ``}`, r = t.controlId === void 0 ? (0, react.createElement)(`span`, { className: n }, t.label) : (0, react.createElement)(`label`, {
308
- className: n,
309
- htmlFor: t.controlId
310
- }, t.label);
311
- return (0, react.createElement)(`div`, { className: `dsu-labelRow` }, r, t.detail === void 0 ? null : (0, react.createElement)(g, {
312
- label: t.label,
313
- detail: t.detail,
314
- showLabel: !1
315
- }));
316
- }
317
- function v(t) {
318
- let n = t.controlId === void 0 ? void 0 : `${t.controlId}-hint`;
319
- return (0, react.createElement)(`div`, { className: `dsu-field${t.wide === !0 ? ` dsu-fieldWide` : ``}` }, (0, react.createElement)(`div`, { className: `dsu-fieldMeta` }, (0, react.createElement)(_, {
320
- label: t.label,
321
- detail: t.detail,
322
- compact: t.compact,
323
- controlId: t.controlId
324
- }), t.hint === void 0 ? null : (0, react.createElement)(`p`, {
325
- className: `dsu-hint`,
326
- id: n
327
- }, t.hint)), (0, react.createElement)(`div`, { className: `dsu-control` }, t.children));
328
- }
329
- function y(t) {
330
- let n = (0, react.useId)(), i = t.hint === void 0 ? void 0 : `${n}-hint`;
331
- return (0, react.createElement)(v, {
332
- ...t,
333
- controlId: n
334
- }, (0, react.createElement)(`button`, {
335
- type: `button`,
336
- role: `switch`,
337
- id: n,
338
- className: `dsu-switch`,
339
- "aria-checked": t.checked,
340
- "aria-describedby": i,
341
- "data-field": t.field,
342
- disabled: t.disabled === !0,
343
- onClick: () => {
344
- t.onChange(!t.checked);
345
- }
346
- }, (0, react.createElement)(`span`, { className: `dsu-knob` })));
347
- }
348
- function b(t) {
349
- let i = typeof t.value == `number` && Number.isFinite(t.value) ? String(t.value) : ``, [a, c] = (0, react.useState)(i), [l, u] = (0, react.useState)(!1), [d, f] = (0, react.useState)(!1), p = (0, react.useRef)(void 0), m = (0, react.useId)(), h = (0, react.useId)(), g = t.hint === void 0 ? void 0 : `${m}-hint`, _ = l && d, y = [g, _ ? h : void 0].filter((e) => e !== void 0), b = y.length === 0 ? void 0 : y.join(` `);
350
- (0, react.useEffect)(() => {
351
- t.value !== p.current && (p.current = t.value, c(i), u(!1), f(!1));
352
- }, [t.value, i]);
353
- let x = (e) => {
354
- let n = t.min ?? -1 / 0, r = t.max ?? 1 / 0;
355
- if (!Number.isFinite(e) || e < n || e > r) return !1;
356
- let { step: i } = t;
357
- if (i === void 0 || i <= 0) return !0;
358
- let a = (e - (t.min ?? 0)) / i;
359
- return Math.abs(a - Math.round(a)) < 1e-9;
360
- }, S = (e) => {
361
- if (f(!1), c(e), e === ``) {
362
- u(!1), p.current = void 0, t.onChange(void 0);
363
- return;
364
- }
365
- let n = Number(e);
366
- x(n) ? (u(!1), p.current = n, t.onChange(n)) : u(!0);
367
- }, C = () => {
368
- a === `` || l || c(String(Number(a)));
369
- }, w = () => {
370
- f(l), C();
371
- };
372
- return (0, react.createElement)(v, {
373
- ...t,
374
- controlId: m
375
- }, (0, react.createElement)(`div`, { className: `dsu-numberWrap` }, (0, react.createElement)(`div`, { className: `dsu-number` }, (0, react.createElement)(`input`, {
376
- className: `dsu-input`,
377
- type: `number`,
378
- inputMode: `numeric`,
379
- id: m,
380
- value: a,
381
- min: t.min,
382
- max: t.max,
383
- step: t.step,
384
- placeholder: t.placeholder,
385
- "aria-invalid": _ || void 0,
386
- "aria-describedby": b,
387
- "data-field": t.field,
388
- disabled: t.disabled === !0,
389
- onChange: (e) => {
390
- S(e.target.value);
391
- },
392
- onBlur: w
393
- }), t.unit === void 0 ? null : (0, react.createElement)(`span`, { className: `dsu-unit` }, t.unit)), _ ? (0, react.createElement)(`p`, {
394
- className: `dsu-error`,
395
- id: h
396
- }, t.invalidHint) : null));
397
- }
398
- function x(t) {
399
- let [i, a] = (0, react.useState)(t.value), [o, c] = (0, react.useState)(!1), l = (0, react.useId)(), u = t.hint === void 0 ? void 0 : `${l}-hint`;
400
- (0, react.useEffect)(() => {
401
- o || a(t.value);
402
- }, [t.value, o]);
403
- let d = {
404
- id: l,
405
- className: `dsu-input${t.multiline === !0 ? ` dsu-textarea` : ``}${t.monospace === !0 ? ` dsu-mono` : ``}`,
406
- value: i,
407
- placeholder: t.placeholder,
408
- "aria-describedby": u,
409
- "data-field": t.field,
410
- disabled: t.disabled === !0,
411
- onFocus: () => {
412
- c(!0);
413
- },
414
- onBlur: () => {
415
- c(!1);
416
- },
417
- onChange: (e) => {
418
- a(e.target.value), t.onChange(e.target.value);
419
- }
420
- };
421
- return (0, react.createElement)(v, {
422
- ...t,
423
- controlId: l
424
- }, t.multiline === !0 ? (0, react.createElement)(`textarea`, d) : (0, react.createElement)(`input`, d));
425
- }
426
- function C(c) {
427
- let [l, u] = (0, react.useState)(!1), [d, f] = (0, react.useState)(0), p = (0, react.useRef)(null), g = (0, react.useRef)(null), _ = (0, react.useId)(), y = (0, react.useId)(), b = `--dsu-${y.replaceAll(/[^a-zA-Z0-9]/gu, ``)}`, x = c.hint === void 0 ? void 0 : `${y}-hint`, { disabled: S, value: C, options: w, onChange: T } = c, E = (0, react.useMemo)(() => w.map((e, t) => ({
428
- option: e,
429
- index: t
430
- })).filter((e) => e.option.disabled !== !0), [w]), D = w.find((e) => e.value === C)?.label ?? C, O = w[d], k = O !== void 0 && O.disabled !== !0, A = (0, react.useCallback)(() => {
431
- let e = p.current, t = g.current;
432
- /* v8 ignore next 3 -- place 只在 open 的 layout effect 里调用;refs 为空只可能是卸载竞态 */
433
- if (e === null || t === null) return;
434
- let n = e.getBoundingClientRect(), r = Math.min(n.width, window.innerWidth - 16);
435
- t.style.width = `${r}px`;
436
- let i = m() && t.style.positionArea !== `none`;
437
- if (i && !h(n, t.getBoundingClientRect())) return;
438
- i && (t.style.positionArea = `none`), t.style.marginTop = `0px`;
439
- let { left: a } = n;
440
- a + r > window.innerWidth - 8 && (a = window.innerWidth - r - 8);
441
- let o = t.offsetHeight, s = n.bottom + 6;
442
- s + o > window.innerHeight - 8 && (s = n.top - o - 6);
443
- let c = Math.max(8, window.innerWidth - r - 8), l = Math.max(8, window.innerHeight - o - 8);
444
- t.style.left = `${Math.min(Math.max(8, a), c)}px`, t.style.top = `${Math.min(Math.max(8, s), l)}px`;
445
- }, []), j = (0, react.useCallback)(() => {
446
- u(!1);
447
- }, []), M = (0, react.useCallback)(() => {
448
- if (S === !0) return;
449
- let e = E.find((e) => e.option.value === C) ?? E.at(0);
450
- e !== void 0 && (f(e.index), u(!0));
451
- }, [
452
- S,
453
- C,
454
- E
455
- ]), N = (0, react.useCallback)((e) => {
456
- /* v8 ignore next 3 -- 浮层只能经由 openMenu 打开;组件禁用时打不开 */
457
- if (S === !0) return;
458
- let t = w[e];
459
- /* v8 ignore next 3 -- disabled 选项在浏览器里不派发 click;越界下标由调用方保证 */
460
- t !== void 0 && t.disabled !== !0 && (T(t.value), j(), p.current?.focus());
461
- }, [
462
- S,
463
- w,
464
- T,
465
- j
466
- ]), P = (0, react.useCallback)((e) => {
467
- let t = E.findIndex((e) => e.index === d);
468
- /* v8 ignore next 5 -- open 时归一 effect 已保证 enabled 非空且 active 落在可用项上 */
469
- if (t === -1 || E.length === 0) return;
470
- let n = (t + e + E.length) % E.length, r = E[n];
471
- /* v8 ignore next 3 -- next 由取模保证在界内 */
472
- r !== void 0 && f(r.index);
473
- }, [d, E]);
474
- (0, react.useLayoutEffect)(() => {
475
- if (!l) return () => {};
476
- A();
477
- let e = (e) => {
478
- let t = e.target;
479
- g.current?.contains(t) !== !0 && p.current?.contains(t) !== !0 && j();
480
- }, t = (e) => {
481
- let { target: t } = e;
482
- t instanceof Node && g.current?.contains(t) === !0 || j();
483
- }, n = () => {
484
- A();
485
- };
486
- return document.addEventListener(`pointerdown`, e, !0), window.addEventListener(`scroll`, t, !0), window.addEventListener(`resize`, n), () => {
487
- document.removeEventListener(`pointerdown`, e, !0), window.removeEventListener(`scroll`, t, !0), window.removeEventListener(`resize`, n);
488
- };
489
- }, [
490
- l,
491
- c.options,
492
- A,
493
- j
494
- ]), (0, react.useEffect)(() => {
495
- if (!l) return;
496
- if (S === !0 || E.length === 0) {
497
- j();
498
- return;
499
- }
500
- if (E.some((e) => e.index === d)) return;
501
- let e = E.find((e) => e.option.value === C) ?? E.at(0);
502
- /* v8 ignore next 3 -- enabled 非空在上一分支已保证 */
503
- e !== void 0 && f(e.index);
504
- }, [
505
- l,
506
- S,
507
- C,
508
- w,
509
- d,
510
- j,
511
- E
512
- ]), (0, react.useLayoutEffect)(() => {
513
- if (!l) return;
514
- let e = g.current;
515
- /* v8 ignore next 2 -- 同上,menu 在 open 的 commit 之后必然已挂上 */
516
- if (e === null) return;
517
- let t = e.querySelector(`[data-active="true"]`);
518
- /* v8 ignore next 2 -- active 已由归一 effect 保证落在可用项上 */
519
- t !== null && (t.offsetTop < e.scrollTop ? e.scrollTop = t.offsetTop : t.offsetTop + t.offsetHeight > e.scrollTop + e.clientHeight && (e.scrollTop = t.offsetTop + t.offsetHeight - e.clientHeight));
520
- }, [
521
- l,
522
- d,
523
- w
524
- ]);
525
- let F = (e) => {
526
- if (e.key === `ArrowDown` || e.key === `ArrowUp`) {
527
- if (e.preventDefault(), !l) {
528
- M();
529
- return;
530
- }
531
- P(e.key === `ArrowDown` ? 1 : -1);
532
- } else if (e.key === `Home` || e.key === `End`) {
533
- if (e.preventDefault(), l || M(), E.length === 0) return;
534
- let t = e.key === `Home` ? E.at(0) : E.at(-1);
535
- /* v8 ignore next 3 -- enabled 为空已在上一条返回 */
536
- if (t === void 0) return;
537
- f(t.index);
538
- } else if (e.key === `Enter` || e.key === ` `) {
539
- if (e.preventDefault(), !l) {
540
- M();
541
- return;
542
- }
543
- N(d);
544
- } else (e.key === `Tab` || e.key === `Escape`) && j();
545
- }, I = [], L;
546
- for (let [t, n] of w.entries()) n.group !== L && (n.group !== void 0 && I.push((0, react.createElement)(`div`, {
547
- key: `group-${t}-${n.group}`,
548
- className: `dsu-optionGroup`,
549
- role: `presentation`
550
- }, n.group)), L = n.group), I.push((0, react.createElement)(`button`, {
551
- key: `option-${n.value}`,
552
- type: `button`,
553
- role: `option`,
554
- id: `${_}-${t}`,
555
- className: `dsu-option`,
556
- tabIndex: -1,
557
- "aria-selected": n.value === c.value,
558
- "data-active": t === d,
559
- disabled: n.disabled === !0,
560
- onMouseDown: (e) => {
561
- e.preventDefault();
562
- },
563
- onClick: () => {
564
- N(t);
565
- },
566
- onMouseEnter: () => {
567
- /* v8 ignore next -- happy-dom 对 disabled 元素不派发 mouse 事件;浏览器实现各有差异,保留禁用检查 */
568
- n.disabled !== !0 && f(t);
569
- }
570
- }, (0, react.createElement)(`span`, null, n.label), (0, react.createElement)(`svg`, {
571
- className: `dsu-check`,
572
- width: 14,
573
- height: 14,
574
- viewBox: `0 0 14 14`,
575
- "aria-hidden": !0
576
- }, (0, react.createElement)(`path`, {
577
- d: `M2.5 7.5l3 3 6-7`,
578
- fill: `none`,
579
- stroke: `currentColor`,
580
- strokeWidth: 1.5,
581
- strokeLinecap: `round`,
582
- strokeLinejoin: `round`
583
- }))));
584
- return (0, react.createElement)(v, {
585
- ...c,
586
- controlId: y
587
- }, (0, react.createElement)(`div`, {
588
- className: `dsu-selectWrap`,
589
- onBlur: (e) => {
590
- let t = e.relatedTarget;
591
- t instanceof Node && e.currentTarget.contains(t) || j();
592
- }
593
- }, (0, react.createElement)(`button`, {
594
- ref: p,
595
- type: `button`,
596
- id: y,
597
- style: { anchorName: b },
598
- className: `dsu-select dsu-input`,
599
- role: `combobox`,
600
- "aria-haspopup": `listbox`,
601
- "aria-expanded": l,
602
- "aria-controls": `${_}-list`,
603
- "aria-activedescendant": l && k ? `${_}-${d}` : void 0,
604
- "aria-describedby": x,
605
- "data-field": c.field,
606
- disabled: S === !0 || w.length === 0,
607
- onClick: () => {
608
- l ? j() : M();
609
- },
610
- onKeyDown: F
611
- }, (0, react.createElement)(`span`, { className: `dsu-selectValue` }, D), (0, react.createElement)(`svg`, {
612
- className: `dsu-chevron`,
613
- width: 14,
614
- height: 14,
615
- viewBox: `0 0 14 14`,
616
- "aria-hidden": !0
617
- }, (0, react.createElement)(`path`, {
618
- d: `M3 5l4 4 4-4`,
619
- fill: `none`,
620
- stroke: `currentColor`,
621
- strokeWidth: 1.5,
622
- strokeLinecap: `round`,
623
- strokeLinejoin: `round`
624
- }))), (0, react.createElement)(`div`, {
625
- ref: g,
626
- id: `${_}-list`,
627
- role: `listbox`,
628
- className: `dsu-menu`,
629
- style: {
630
- positionAnchor: b,
631
- positionTryFallbacks: `flip-block, flip-inline`
632
- },
633
- "aria-label": c.label,
634
- hidden: !l
635
- }, ...I)));
636
- }
637
- function w(t) {
638
- let n = !t.writable || t.busy || !t.dirty, r;
639
- return r = t.error === null ? t.writable ? t.dirty ? t.dirtyLabel : t.cleanLabel : t.readOnlyLabel : t.error, (0, react.createElement)(`div`, {
640
- className: `dsu-savebar`,
641
- "data-dirty": t.dirty
642
- }, (0, react.createElement)(`button`, {
643
- type: `button`,
644
- className: `dsu-btn dsu-btnPrimary`,
645
- "data-field": `save`,
646
- disabled: n,
647
- onClick: t.onSave
648
- }, t.busy ? t.savingLabel : t.saveLabel), (0, react.createElement)(`button`, {
649
- type: `button`,
650
- className: `dsu-btn`,
651
- "data-field": `discard`,
652
- disabled: n,
653
- onClick: t.onDiscard
654
- }, t.revertLabel), (0, react.createElement)(`span`, {
655
- role: `status`,
656
- className: t.error === null ? `dsu-status` : `dsu-status dsu-statusError`
657
- }, r));
658
- }
659
- // node_modules/@jayyuen66/dsh-plugin-shared/dist/card-diff.js
660
- function e$1(t, n, r) {
661
- if (t == null || n == null) return (t ?? null) === (n ?? null);
662
- if (Object.is(t, n)) return !0;
663
- if (typeof t != `object` || typeof n != `object`) return !1;
664
- if (r.get(t) === n) return !0;
665
- if (r.set(t, n), Array.isArray(t) || Array.isArray(n)) return !Array.isArray(t) || !Array.isArray(n) || t.length !== n.length ? !1 : t.every((t, i) => e$1(t, n[i], r));
666
- let i = Object.keys(t), a = Object.keys(n);
667
- return i.length === a.length && i.every((i) => Object.hasOwn(n, i) && e$1(Reflect.get(t, i), Reflect.get(n, i), r));
668
- }
669
- function t$1(t, n) {
670
- let r = [];
671
- for (let i of Object.keys(t)) e$1(t[i], n[i], /* @__PURE__ */ new WeakMap()) || r.push(i);
672
- return r;
673
- }
674
- // node_modules/@jayyuen66/dsh-plugin-shared/dist/record.js
675
- function e(e) {
676
- return typeof e == `object` && !!e && !Array.isArray(e);
677
- }
678
- // node_modules/@jayyuen66/dsh-plugin-shared/dist/errors.js
679
- function t(e) {
680
- let t = Object.getOwnPropertyDescriptor(e, `message`);
681
- return t !== void 0 && `value` in t && typeof t.value == `string` ? t.value : void 0;
682
- }
683
- function n(e, r) {
684
- if (r.has(e)) return `<circular cause>`;
685
- r.add(e);
686
- try {
687
- if (!(e instanceof Error)) {
688
- if (typeof e == `object` && e) {
689
- let n = t(e);
690
- if (n !== void 0 && n !== ``) return n;
691
- }
692
- return String(e);
693
- }
694
- let i = e.message === `` ? e.name : e.message, a = typeof globalThis.AggregateError == `function` && e instanceof AggregateError && e.errors.length > 0 ? ` [${e.errors.map((e) => n(e, r)).join(`; `)}]` : ``, o = e.cause === void 0 || e.cause === null ? `` : n(e.cause, r);
695
- return `${i}${a}${o === `` || o === i ? `` : `: ${o}`}`;
696
- } catch {
697
- return `<unrenderable value>`;
698
- } finally {
699
- r.delete(e);
700
- }
701
- }
702
- function r(e) {
703
- return n(e, /* @__PURE__ */ new Set());
704
- }
705
- // lib/card-draft.ts
706
- /** 草稿优先取值:touched 有该键(哪怕值是 undefined=待清空)即用草稿。
707
- * 两层都只判**自有**属性:本函数收任意字段名,`in`/裸下标会沿原型链命中 `toString` /
708
- * `constructor` 这类继承键,把 Object.prototype 的成员当成已提交值交出去。 */
709
- function hasDraft(touched, field) {
710
- return Object.hasOwn(touched, field);
711
- }
712
- function draftOf(touched, value, field) {
713
- if (hasDraft(touched, field)) return touched[field];
714
- return Object.hasOwn(value, field) ? value[field] : void 0;
715
- }
716
- /** 数值型输入的显示文本:非有限数(含 undefined)回落到默认文案。 */
717
- function numberText(raw, fallback) {
718
- return typeof raw === "number" && Number.isFinite(raw) ? String(raw) : fallback;
719
- }
720
- // lib/card-logic.ts
721
- /**
722
- * 引导端点交回的守护进程就绪态该显示哪一行。
723
- *
724
- * `undefined` 是**必需**的一种取值,不是兜底默认:旧版 host 的应答里没有 `serverReady` 这个字段,
725
- * 而「应答里没写」与「写了未就绪」是两件事——把前者显示成后者,卡片就在用户眼前谎称了一次
726
- * 「没有守护进程」。判据收在可单测的这一层,client 只负责渲染它选出来的那一行。
727
- *
728
- * 入参写 `unknown` 而不是 `boolean | undefined`:应答里的这一位只有类型声明、没有运行时校验
729
- * (lib/rebuild-shape.ts),把形状收紧在声明上等于假定畸形值不会出现,而这里的严格判等正是
730
- * 为了不让 `null` / `"false"` / `0` 这类值被 falsy 判断误收成「未就绪」。调用方交来的仍是
731
- * `boolean | undefined`,收紧的一侧由它自己保证。
732
- */
733
- function daemonNoteKey(ready) {
734
- let key;
735
- if (ready === true) key = "daemonReadyNote";
736
- else if (ready === false) key = "daemonOfflineNote";
737
- return key;
738
- }
739
- /**
740
- * 把 settings scope 桥成 { getSnapshot, subscribe } store。
741
- * 缓存必须 per-scope(闭包内):模块全局会在多 scope 交错 getSnapshot 时互相
742
- * 冲 memo,导致 useSyncExternalStore 每次拿到新引用 → 无限重渲染。
743
- */
744
- function cardStore(scope) {
745
- const EMPTY_SNAPSHOT = {
746
- status: "loading",
747
- writable: false,
748
- value: {}
749
- };
750
- let cachedSnap = null;
751
- let cachedView = EMPTY_SNAPSHOT;
752
- return {
753
- getSnapshot() {
754
- const snap = scope.getSnapshot();
755
- if (snap !== cachedSnap) {
756
- cachedSnap = snap;
757
- cachedView = {
758
- status: snap.status,
759
- writable: snap.writable,
760
- value: snap.value ?? {}
761
- };
762
- }
763
- return cachedView;
764
- },
765
- subscribe(listener) {
766
- return scope.subscribe(listener);
767
- }
768
- };
769
- }
770
- /**
771
- * 三个数值字段的显示值都是「草稿优先 + 默认文案」,且共享同一条清空语义:
772
- * touched 里显式写了 undefined(用户清空输入)= 待 unset,显示空串;「从没动过、
773
- * 快照里也没有」不是清空,显示默认文案。判据统一收在这里,与卡片数值控件
774
- * (numberDisplay / NumberField)的「清空即回『未填』」对齐。
775
- */
776
- function numericFieldDisplay(touched, value, field, fallback) {
777
- const draft = draftOf(touched, value, field);
778
- if (draft === void 0) return hasDraft(touched, field) ? "" : fallback;
779
- return numberText(draft, fallback);
780
- }
781
- /** 已提交端点值只收 HTTP(S);坏文本显示成空(输入框里键入的草稿不走这条过滤)。 */
782
- const HTTP_URL_SCHEMA = zod.z.url({ protocol: /^https?$/u });
783
- /**
784
- * 端点字段的显示值:**草稿优先**,与三个数值字段同一条清空语义。
785
- *
786
- * 用户正在逐字键入时,草稿是「这一格此刻的文本」而不是待校验的值——半截 URL
787
- * 必须原样回显,否则输入第一个字符就被过滤成空串、删掉已提交 URL 的一个字符就整格清空。
788
- * 只有「这一格没动过、显示的是已提交快照」时才过 HTTP(S) 形态过滤:脏快照不该显示成
789
- * 一个看起来能保存的地址。
790
- */
791
- function endpointFieldDisplay(touched, value) {
792
- if (Object.hasOwn(touched, "hfEndpoint")) {
793
- const draft = touched["hfEndpoint"];
794
- return typeof draft === "string" ? draft : "";
795
- }
796
- const committed = value["hfEndpoint"];
797
- return typeof committed === "string" && HTTP_URL_SCHEMA.safeParse(committed).success ? committed : "";
798
- }
799
- /** 七个字段的草稿显示值(ZgCard 只渲染这里算出来的东西)。 */
800
- function draftFields(touched, value) {
801
- const embedding = draftOf(touched, value, "defaultEmbedding");
802
- const enforce = draftOf(touched, value, "enforceSearchFirst");
803
- const transport = draftOf(touched, value, "transport");
804
- return {
805
- embedding: typeof embedding === "string" && embedding.length > 0 ? embedding : DEFAULT_EMBEDDING,
806
- limitDisplay: numericFieldDisplay(touched, value, "defaultLimit", String(10)),
807
- hfEndpoint: endpointFieldDisplay(touched, value),
808
- enforceSearchFirst: enforce !== false,
809
- grepBudget: numericFieldDisplay(touched, value, "grepBudgetPerSearch", String(3)),
810
- unlockWindow: numericFieldDisplay(touched, value, "unlockWindowMin", String(10)),
811
- transport: transport === "cli" || transport === "mcp" || transport === "auto" ? transport : "auto"
812
- };
813
- }
814
- const LIMIT_SCHEMA = zod.z.int().min(1).max(50);
815
- const BUDGET_SCHEMA = zod.z.int().min(1).max(20);
816
- const WINDOW_SCHEMA = zod.z.int().min(1).max(240);
817
- /** 轮询应答的宽容形状:未知状态、非数字退出码、非字符串输出都折成缺位,
818
- * 下游文案只按“缺位”兜底,不把坏类型带到渲染期。 */
819
- const REBUILD_STATUSES = [
820
- "running",
821
- "stopping",
822
- "completed",
823
- "killed",
824
- "failed"
825
- ];
826
- const REBUILD_POLL_SCHEMA = zod.z.object({
827
- status: zod.z.preprocess((value) => typeof value === "string" && REBUILD_STATUSES.some((status) => status === value) ? value : void 0, zod.z.enum(REBUILD_STATUSES).optional()),
828
- exitCode: zod.z.preprocess((value) => typeof value === "number" && Number.isFinite(value) ? value : void 0, zod.z.number().optional()),
829
- output: zod.z.preprocess((value) => typeof value === "string" ? value : void 0, zod.z.string().optional())
830
- });
831
- /**
832
- * 轮询应答 → 卡片状态。
833
- * 关键:harness 的 bash-local 对**任何自然退出**都置 `status:'completed'`
834
- * (packages/shell/bash-local/src/index.ts 给 `proc.status` 的那一分支:只在信号终止/调用方 abort 时给
835
- * 'killed'),exit 127「zg 没装」也是 completed。只看 status 会把失败显示成
836
- * 「重建完成」,故成功判据 = completed 且 exit 0。
837
- * 状态词现取自官方作业注册表(ctx.jobs),比原先的进程态多两枚:
838
- * - `stopping`:取消已发出、进程还没收完 ⇒ 仍在跑,绝不能渲染成失败;
839
- * - `failed`:注册表侧判定失败(生产者的 done 被拒、或收尾抛错),此时没有退出码可读。
840
- */
841
- function parseRebuildPoll(body, t) {
842
- const parsed = REBUILD_POLL_SCHEMA.safeParse(body);
843
- const { status, exitCode, output } = parsed.success ? parsed.data : {};
844
- const outputText = output ?? "";
845
- if (status === "running" || status === "stopping") return {
846
- phase: "running",
847
- output: outputText.length > 0 ? outputText : t("rebuildRunning")
848
- };
849
- if (status === "completed" && exitCode === 0) return {
850
- phase: "done",
851
- output: outputText
852
- };
853
- let reason;
854
- if (status === "killed") reason = t("rebuildKilled");
855
- else if (status === "failed") reason = t("rebuildFailed");
856
- else if (typeof exitCode === "number" && Number.isFinite(exitCode)) reason = t("rebuildExitCode", { exitCode });
857
- else reason = t("rebuildExitUnknown");
858
- return {
859
- phase: "error",
860
- output: outputText.length > 0 ? `${reason}\n${outputText}` : reason
861
- };
862
- }
863
- // src/rebuild-reader.ts
864
- const REBUILD_NAMESPACE = "zvecGrepRebuild";
865
- /** 网关给命名空间注册的**服务键**:`remote.<namespace>`。它在 `$mount` 完成之后才存在,
866
- * 所以只能在挂载后按这个键去读,而不是提前 inject。 */
867
- const REBUILD_SERVICE_KEY = `remote.${REBUILD_NAMESPACE}`;
868
- /** 卡片所在 bundle 的包名(`$mount` 的 `package` 位与槽位键同源,见 client-entry.ts 的 BUNDLE_PKG)。 */
869
- const PACKAGE_NAME = "@jayyuen66/dsh-zvec-grep";
870
- /** strict codec 的统一的返回点:失败交给 zod 的 `prettifyError`,读到的是一份带字段路径的说明。 */
871
- function parseOrThrow(schema, value) {
872
- const parsed = schema.safeParse(value);
873
- if (!parsed.success) throw new TypeError(zod.z.prettifyError(parsed.error));
874
- return parsed.data;
875
- }
876
- const START_SCHEMA = zod.z.object({ root: zod.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" });
877
- const STATUS_SCHEMA = zod.z.object({ jobId: zod.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" });
878
- /** 把宿主那三个方法挂到客户端远程通道上的描述符(`id` 的形状照生成器:`<包>#<命名空间>/<方法>`)。
879
- * 导出它只为一件事:`test/rebuild-remote.test.ts` 拿它与宿主侧 `remoteMethods()` 的标记对质
880
- * —— 两侧分叉时卡片不会报错,只会"读不到",所以那条比较必须在门禁里。 */
881
- const REBUILD_DESCRIPTORS = [
882
- {
883
- id: `${PACKAGE_NAME}#${REBUILD_NAMESPACE}/roots`,
884
- service: REBUILD_NAMESPACE,
885
- namespace: REBUILD_NAMESPACE,
886
- method: "roots",
887
- invocation: { kind: "direct" },
888
- parameters: [],
889
- result: { mode: "src-json" }
890
- },
891
- {
892
- id: `${PACKAGE_NAME}#${REBUILD_NAMESPACE}/rebuild`,
893
- service: REBUILD_NAMESPACE,
894
- namespace: REBUILD_NAMESPACE,
895
- method: "rebuild",
896
- invocation: { kind: "direct" },
897
- parameters: [{
898
- name: "request",
899
- wire: "request",
900
- source: "json",
901
- codec: {
902
- mode: "strict",
903
- typeSymbol: `${PACKAGE_NAME}#rebuild-request`,
904
- create: () => ({ parse(value) {
905
- return parseOrThrow(START_SCHEMA, value);
906
- } })
907
- }
908
- }],
909
- result: { mode: "src-json" }
910
- },
911
- {
912
- id: `${PACKAGE_NAME}#${REBUILD_NAMESPACE}/status`,
913
- service: REBUILD_NAMESPACE,
914
- namespace: REBUILD_NAMESPACE,
915
- method: "status",
916
- invocation: { kind: "direct" },
917
- parameters: [{
918
- name: "request",
919
- wire: "request",
920
- source: "json",
921
- codec: {
922
- mode: "strict",
923
- typeSymbol: `${PACKAGE_NAME}#rebuild-status-request`,
924
- create: () => ({ parse(value) {
925
- return parseOrThrow(STATUS_SCHEMA, value);
926
- } })
927
- }
928
- }],
929
- result: { mode: "src-json" }
930
- }
931
- ];
932
- /** 这个值能当远程通道用吗(只核我们要调的那一位;服务来自别的实现或版本时保守当作没有)。 */
933
- const isRemoteMounter = (value) => e(value) && typeof value["$mount"] === "function";
934
- /** 同上:命名空间服务(挂载之后才有,缺它说明网关没认这枚贡献)。 */
935
- const isRebuildNamespace = (value) => e(value) && typeof value["roots"] === "function" && typeof value["rebuild"] === "function" && typeof value["status"] === "function";
936
- /**
937
- * 线上拒绝(result.ok=false)翻成异常:code 与 message 都来自网关的错误对象。
938
- * 三个方法同构,收成一个入口——同一份判据,不抄三份。
939
- */
940
- async function unwrapWire(call) {
941
- const result = await call;
942
- if (result.ok) return result.value;
943
- throw new Error(`${result.error.code}: ${result.error.message}`);
944
- }
945
- /**
946
- * 造出真正的读取器(remote 每次现读 + 挂载只在成功后缓存)。
947
- * @param ctx - 客户端上下文
948
- * @returns 读取器
949
- */
950
- function buildRebuildReader(ctx, messages) {
951
- let mounted;
952
- const namespaceOf = async () => {
953
- const mounter = ctx.get?.("remote");
954
- if (!isRemoteMounter(mounter)) throw new Error(messages.remoteMissing());
955
- try {
956
- mounted ??= mounter.$mount({
957
- package: PACKAGE_NAME,
958
- descriptors: REBUILD_DESCRIPTORS
959
- });
960
- await mounted;
961
- } catch (error) {
962
- mounted = void 0;
963
- throw error;
964
- }
965
- const namespace = ctx.get?.(REBUILD_SERVICE_KEY);
966
- if (!isRebuildNamespace(namespace)) throw new Error(messages.namespaceMissing(REBUILD_SERVICE_KEY));
967
- return namespace;
968
- };
969
- return {
970
- async roots() {
971
- return unwrapWire((await namespaceOf()).roots());
972
- },
973
- async rebuild(root) {
974
- const value = await unwrapWire((await namespaceOf()).rebuild({ root }));
975
- if (value.ok) return value;
976
- throw new Error(value.error);
977
- },
978
- async status(jobId) {
979
- const value = await unwrapWire((await namespaceOf()).status({ jobId }));
980
- if (value.ok) return { ...value };
981
- throw new Error(value.error);
982
- }
983
- };
984
- }
985
- /**
986
- * 造一个「读宿主侧工作区重建」的读取器;**连 ctx.get 面都不在时返回 `undefined`**
987
- * (卡片照常渲染,点重建时给出错误)。remote 服务是否在场**不在这一步判**:
988
- * 解析推迟到每次调用(见 buildRebuildReader),apply 期它可能还没注册。
989
- *
990
- * `$mount` 是**幂等**的(挂进本 fiber,随卡片卸载自动撤),成功后缓存那枚 promise:
991
- * 同一次会话里反复轮询只挂一次;失败则清缓存,下一次调用重新挂。
992
- *
993
- * @param ctx - 客户端上下文(只用 `get` 一位)
994
- * @returns 读取器;ctx 没有 get 面时 `undefined`
995
- */
996
- function createRebuildReader(ctx, messages) {
997
- return typeof ctx.get === "function" ? buildRebuildReader(ctx, messages) : void 0;
998
- }
999
- // src/ui-messages.ts
1000
- /** 推荐的 embedding 模型镜像(endpointHint 与 client-entry 的 placeholder 共用)。 */
1001
- const EMBEDDING_MIRROR_URL = "https://modelscope.cn/models";
1002
- const UI_MESSAGES = {
1003
- zh: {
1004
- statusReadOnly: "当前作用域只读",
1005
- statusClean: "无未保存的修改",
1006
- dirtyCount: "已修改 {count} 项",
1007
- save: "保存",
1008
- saving: "保存中…",
1009
- revert: "撤销",
1010
- saveFailed: "保存失败:{reason}",
1011
- saveRejected: "保存被宿主拒绝(配置校验未通过或写入被跳过),修改未生效",
1012
- modelSection: "检索模型",
1013
- indexSection: "网络与索引",
1014
- unitResults: "条",
1015
- unitTimes: "次",
1016
- unitMinutes: "分钟",
1017
- outOfRange: "超出允许范围,未保存",
1018
- embeddingLabel: "默认 embedding",
1019
- embeddingHint: "本地模型直接可选;远程 qwen 模型需在插件部署配置里打开 allowRemoteEmbedding(内容会送往外部端点,首次索引需 zg --auth grant 授权)。只影响「新建」索引;切换并保存后,已有索引需点下方「重建」重新 embedding",
1020
- transportLabel: "检索传输方式",
1021
- transportHint: "自动 = 守护进程在跑时检索走 MCP(常驻模型池、队列调度),否则走 CLI;仅 CLI = 永不碰守护进程;仅 MCP = 检索恒走守护进程,缺席时由插件自动拉起(会开 127.0.0.1:7999 回环端口;拉起失败会明确报错而不是回退 CLI)",
1022
- transportAuto: "自动(守护进程在跑走 MCP,否则 CLI)",
1023
- transportCli: "仅 CLI(每次 spawn zg 进程)",
1024
- transportMcp: "仅 MCP(走守护进程,缺席自动拉起)",
1025
- backendRemote: "qwen 远程(内容出本机,需部署开放并授权)",
1026
- limitLabel: "默认每组结果数",
1027
- limitInvalid: "请输入 {min}-{max} 的整数",
1028
- limitClamped: "已钳到 {min}-{max} 范围:{value}",
1029
- endpointLabel: "HuggingFace 镜像地址",
1030
- endpointHint: `留空走 huggingface.co;国内网络可填 ${EMBEDDING_MIRROR_URL} 等兼容镜像(仅 llama-cpp 后端生效,如 qwen3)`,
1031
- enforceLabel: "强制 search-first(先 zg_search 再 grep/rg)",
1032
- enforceHint: "开启后,已建索引工作区内的 grep/rg 受配额门禁约束:每次成功 zg_search 解锁下方次数的 grep/rg(时效见下),用尽或过期后再次拦截(提高检索覆盖与准确性)",
1033
- budgetLabel: "每次 zg_search 解锁的 grep/rg 次数",
1034
- budgetHint: "配额越小语义检索越频繁、准确性约束越强;清空恢复默认 {default}",
1035
- windowLabel: "解锁时效",
1036
- windowHint: "超过该时长未再次 zg_search,配额整体过期;清空恢复默认 {default}(单位:分钟)",
1037
- rebuildLabel: "工作区重建(切换 embedding 并保存后执行)",
1038
- rebuildInputPlaceholder: "/workspace 的绝对路径",
1039
- daemonReadyNote: "守护进程:就绪(zg --server 在跑)。",
1040
- daemonOfflineNote: "守护进程:未就绪。守护进程提供的索引增量刷新、refresh=background 与常驻模型池在缺席时都不可用;需要时在终端执行 `zg --server on`。",
1041
- rebuildHint: "以当前默认模型重建:{embedding};等价于 zg --index --rebuild。{roots}",
1042
- rootsNoteWith: "候选工作区来自本 daemon 已打开过的会话(服务端白名单)。",
1043
- rootsNoteEmpty: "尚无可选工作区:先在该工作区里开一个会话(任一次工具调用即登记)。",
1044
- rebuildButton: "重建索引(动作,点击即执行)",
1045
- rebuildRunning: "重建中…",
1046
- rebuildDone: "重建完成",
1047
- rebuildStarting: "正在后台重建索引…(首次会下载 embedding 模型,可能较慢)",
1048
- rebuildKilled: "重建进程被终止",
1049
- rebuildFailed: "重建作业被宿主注册表判定失败(没拿到进程退出码)",
1050
- rebuildExitCode: "重建进程退出码 {exitCode}(zg 未安装/权限不足/沙箱拒绝都会走到这里)",
1051
- rebuildExitUnknown: "重建没有可判定的结果(应答的 status 无法识别,或缺少进程退出码)",
1052
- rebuildMissingJobId: "启动重建失败:应答缺 jobId",
1053
- rebuildRootNotAbsolute: "root 必须是绝对路径(以 / 开头)",
1054
- rebuildUnavailable: "宿主没有提供工作区重建读面(未装远程服务)",
1055
- rebuildRemoteMissing: "工作区重建读面不可用:宿主网关没有提供 remote 服务",
1056
- rebuildNamespaceMissing: "{serviceKey} 未提供:宿主网关没有挂上这枚命名空间",
1057
- modelOption: "{reference}({dimension}维)",
1058
- backendLlamaCpp: "llama-cpp(原生,需 node-llama-cpp)",
1059
- backendTransformersJs: "transformers-js(纯 JS ONNX)",
1060
- backendModel2Vec: "model2vec(纯 JS worker,最轻)"
1061
- },
1062
- en: {
1063
- statusReadOnly: "This scope is read-only",
1064
- statusClean: "No unsaved changes",
1065
- dirtyCount: "{count} changed",
1066
- save: "Save",
1067
- saving: "Saving…",
1068
- revert: "Revert",
1069
- saveFailed: "save failed: {reason}",
1070
- saveRejected: "save rejected by host (validation failed or write skipped) — changes not applied",
1071
- modelSection: "Retrieval model",
1072
- indexSection: "Network and index",
1073
- unitResults: "hits",
1074
- unitTimes: "times",
1075
- unitMinutes: "minutes",
1076
- outOfRange: "Out of the allowed range — not saved",
1077
- embeddingLabel: "Default embedding",
1078
- 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",
1079
- transportLabel: "Search transport",
1080
- 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)",
1081
- transportAuto: "auto (daemon → MCP, otherwise CLI)",
1082
- transportCli: "CLI only (spawn zg each call)",
1083
- transportMcp: "MCP only (via daemon, auto-started when absent)",
1084
- backendRemote: "qwen remote (content leaves the machine; needs the deployment switch + grant)",
1085
- limitLabel: "Default hits per group",
1086
- limitInvalid: "enter an integer between {min} and {max}",
1087
- limitClamped: "clamped into the {min}-{max} range: {value}",
1088
- endpointLabel: "HuggingFace mirror URL",
1089
- endpointHint: `Leave empty for huggingface.co; on networks that cannot reach HF, fill a compatible mirror such as ${EMBEDDING_MIRROR_URL} (llama-cpp backends only, e.g. qwen3)`,
1090
- enforceLabel: "Enforce search-first (zg_search before grep/rg)",
1091
- 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)",
1092
- budgetLabel: "grep/rg calls unlocked per zg_search",
1093
- budgetHint: "A smaller quota means more semantic searches and a stronger relevance constraint; clear to restore the default {default}",
1094
- windowLabel: "Unlock window",
1095
- windowHint: "Without another zg_search inside this window the whole quota expires; clear to restore the default {default} (minutes)",
1096
- rebuildLabel: "Workspace rebuild (run after switching embedding and saving)",
1097
- rebuildInputPlaceholder: "absolute path to a /workspace",
1098
- daemonReadyNote: "Daemon: ready (zg --server is running).",
1099
- 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.",
1100
- rebuildHint: "Rebuild with the current default model: {embedding}; same as zg --index --rebuild. {roots}",
1101
- rootsNoteWith: "Candidates come from sessions this daemon already opened (server-side whitelist).",
1102
- rootsNoteEmpty: "No workspace to pick yet: open a session in that workspace first (any tool call registers it).",
1103
- rebuildButton: "Rebuild index (action, runs on click)",
1104
- rebuildRunning: "rebuilding…",
1105
- rebuildDone: "rebuild finished",
1106
- rebuildStarting: "Rebuilding in the background… (the first run downloads the embedding model and may be slow)",
1107
- rebuildKilled: "the rebuild process was terminated",
1108
- rebuildFailed: "the host job registry reported the rebuild as failed (no process exit code)",
1109
- rebuildExitCode: "the rebuild process exited with code {exitCode} (missing zg, insufficient permissions and sandbox denials all land here)",
1110
- rebuildExitUnknown: "the rebuild has no determinable outcome (the response status is unrecognized, or its exit code is missing)",
1111
- rebuildMissingJobId: "failed to start the rebuild: the response has no jobId",
1112
- rebuildRootNotAbsolute: "root must be an absolute path (starting with /)",
1113
- rebuildUnavailable: "the host does not expose the rebuild Remote API",
1114
- rebuildRemoteMissing: "the rebuild Remote API is unavailable: the host gateway provides no remote service",
1115
- rebuildNamespaceMissing: "{serviceKey} was not provided: the host gateway did not mount this namespace",
1116
- modelOption: "{reference} ({dimension} dims)",
1117
- backendLlamaCpp: "llama-cpp (native, requires node-llama-cpp)",
1118
- backendTransformersJs: "transformers-js (pure JS ONNX)",
1119
- backendModel2Vec: "model2vec (pure JS worker, lightest)"
1120
- }
1121
- };
1122
- // src/client-entry.ts
1123
- /** 一个反斜杠字符(客户端不引 lib/platform.ts:那份模块带 Node 的 process 类型)。 */
1124
- const BACKSLASH = String.fromCodePoint(92);
1125
- /** 卡片侧只做形状提示:win32 盘符绝对路径(`C:\…` / `C:/…`)。 */
1126
- const WIN32_ABSOLUTE_ROOT = /^[A-Za-z]:[\\/]/u;
1127
- const NS = "zvec-grep";
1128
- /**
1129
- * `plugins.bundle.config` 的 key = **bundle 的 npm 包名**(不是裸条目 id)。
1130
- * 派发证据(installed dsh 0.2.1-rc.2,按符号核对):
1131
- * · dsh-client-ui-plugin-manager 的 client.js 里 `renderSlot("plugins.bundle.config",
1132
- * { view: "page" }, { entryKey: pkg.name })`——pkg.name 是 bundle 包名;
1133
- * · 同文件里 `configured: ledger.bundles.has(openPkg.name)` 与 `packageView()` 的
1134
- * `name: bundle.name`(= bundle 包),所以没有第二条可匹配的 key;
1135
- * · 同包 lib/types/client/slot-contract.d.ts「A bundle's own configuration,
1136
- * **keyed by the bundle's package name**」,且 kind 为 `keyed` → `key` 必填;
1137
- * · dsh-client-ui-renderer 的 `entriesOfSlot(...).find((e) => e.options.key === opts?.entryKey)`
1138
- * 是逐字相等匹配,错一个字符就是「整张卡不渲染」(不是回落、不是报错)。
1139
- * 行槽(本包未用)则是 `<pkg>#<rowId>`(同包的 `rowConfigKey(bundle, rowId)`)。
1140
- * 值 = 本包 package.json 的 name,且必须出现在 profile 的 `dsh.profile.bundles` 里;
1141
- * test/build-client.test.ts 从 `~/.dsh/profiles/web/package.json` 解析校验,不在此处硬抄。
1142
- * 设置命名空间**不跟着改**:`ctx.configForms.get(entryId)` 仍吃裸条目 id(见 apply)。
1143
- */
1144
- const BUNDLE_PKG = "@jayyuen66/dsh-zvec-grep";
1145
- /** 重建轮询间隔(宿主后台进程,2s 足够跟上 zg 的进度输出)。 */
1146
- const REBUILD_POLL_MS = 2e3;
1147
- const CARD_CSS = [
1148
- ".zgc-rebuildInput{flex:1 1 240px;min-width:0}",
1149
- ".zgc-output{font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary,inherit);white-space:pre-wrap;word-break:break-all;max-height:180px;overflow:auto;background:var(--dsw-alias-fill-primary,transparent);border:1px solid var(--dsw-alias-border-l2);border-radius:6px;padding:8px;margin-top:8px}",
1150
- ".zgc-error{font-size:12px;color:var(--dsw-alias-text-danger,#d33);margin-top:8px}"
1151
- ].join("\n");
1152
- const BACKENDS = [
1153
- "llama-cpp",
1154
- "transformers-js",
1155
- "model2vec"
1156
- ];
1157
- /** 重建 root 输入框的候选列表 id(与 <datalist> 配对)。 */
1158
- const ROOT_OPTIONS_ID = "zgc-rebuild-root-options";
1159
- /** 候选按后端分组,供 <optgroup> 使用(文案取自 UI 字典,这里只留键)。 */
1160
- const BACKEND_LABEL_KEY = {
1161
- "llama-cpp": "backendLlamaCpp",
1162
- "transformers-js": "backendTransformersJs",
1163
- model2vec: "backendModel2Vec"
1164
- };
1165
- /** 取设置卡快照的配置值子对象(快照契约 {status, writable, value:{...}})。
1166
- * 独立函数保持字面量 `snap.value`(build-client.test 内容契约锁定该形态)。 */
1167
- function snapshotValue(snap) {
1168
- return snap.value;
1169
- }
1170
- /**
1171
- * embedding 候选项文本(官方 locale 的 {name} 插值)。提成模块级函数是为了不把
1172
- * t() 嵌进 createElement(unicorn/max-nested-calls 上限 3)。
1173
- */
1174
- function modelOptionText(t, reference, dimension) {
1175
- return t("modelOption", {
1176
- reference,
1177
- dimension
1178
- });
1179
- }
1180
- /** 重建行的整行提示(同上:把带插值的 t() 挪出 createElement)。 */
1181
- function rebuildHintText(t, embedding, hasRoots) {
1182
- return t("rebuildHint", {
1183
- embedding,
1184
- roots: t(hasRoots ? "rootsNoteWith" : "rootsNoteEmpty")
1185
- });
1186
- }
1187
- /** embedding 候选的显示文本与分组(供共享 SelectField 的 options):本地按后端三组 + 远程一组。 */
1188
- function embeddingOptions(t) {
1189
- const options = [];
1190
- for (const backend of BACKENDS) for (const entry of LOCAL_EMBEDDINGS) if (entry.backend === backend) options.push({
1191
- value: entry.reference,
1192
- label: modelOptionText(t, entry.reference, entry.dimension),
1193
- group: t(BACKEND_LABEL_KEY[backend])
1194
- });
1195
- for (const entry of REMOTE_EMBEDDING_CATALOG) options.push({
1196
- value: entry.reference,
1197
- label: modelOptionText(t, entry.reference, entry.dimension),
1198
- group: t("backendRemote")
1199
- });
1200
- return options;
1201
- }
1202
- /** 传输三档的闭集(与 host 侧 readTransport 同域;label 取 UI 字典)。 */
1203
- const TRANSPORT_OPTIONS = [
1204
- { value: "auto" },
1205
- { value: "cli" },
1206
- { value: "mcp" }
1207
- ];
1208
- const TRANSPORT_LABEL_KEY = {
1209
- auto: "transportAuto",
1210
- cli: "transportCli",
1211
- mcp: "transportMcp"
1212
- };
1213
- /** 传输三档的 SelectField 候选。 */
1214
- function transportOptions(t) {
1215
- return TRANSPORT_OPTIONS.map((entry) => ({
1216
- value: entry.value,
1217
- label: t(TRANSPORT_LABEL_KEY[entry.value])
1218
- }));
1219
- }
1220
- /** 数字草稿串 → 控件值:区间由 zod schema 判定;空串是「清空 = 恢复默认」,不是 0。 */
1221
- function numberDisplay(display, schema) {
1222
- const parsed = schema.safeParse(display === "" ? NaN : Number(display));
1223
- return parsed.success ? parsed.data : void 0;
1224
- }
1225
- /** 检索模型小节:embedding 下拉(按本地后端分组)+ 每组结果数。 */
1226
- function buildModelSection(deps) {
1227
- const { editable, fields, setField, t } = deps;
1228
- const embedding = (0, react.createElement)(C, {
1229
- label: t("embeddingLabel"),
1230
- ...l(t("embeddingHint")),
1231
- field: "defaultEmbedding",
1232
- value: fields.embedding,
1233
- options: embeddingOptions(t),
1234
- disabled: !editable,
1235
- onChange: (next) => {
1236
- setField("defaultEmbedding", next);
1237
- }
1238
- });
1239
- const limit = (0, react.createElement)(b, {
1240
- label: t("limitLabel"),
1241
- hint: t("limitInvalid", {
1242
- min: 1,
1243
- max: 50
1244
- }),
1245
- field: "defaultLimit",
1246
- value: numberDisplay(fields.limitDisplay, LIMIT_SCHEMA),
1247
- min: LIMIT_SCHEMA.minValue ?? 1,
1248
- max: LIMIT_SCHEMA.maxValue ?? 50,
1249
- step: 1,
1250
- unit: t("unitResults"),
1251
- invalidHint: t("outOfRange"),
1252
- disabled: !editable,
1253
- onChange: (next) => {
1254
- setField("defaultLimit", next);
1255
- }
1256
- });
1257
- return (0, react.createElement)(d, { title: t("modelSection") }, embedding, limit);
1258
- }
1259
- /** 重建行:root 输入(白名单候选进 <datalist>)+ 触发按钮(在跑时禁用)。 */
1260
- function buildRebuildField(deps) {
1261
- const { fields, rebuild, root, roots, setRoot, t } = deps;
1262
- const rootOptions = roots.map((entry) => (0, react.createElement)("option", {
1263
- key: entry,
1264
- value: entry
1265
- }));
1266
- const rootDatalist = (0, react.createElement)("datalist", { id: ROOT_OPTIONS_ID }, ...rootOptions);
1267
- const rebuildInput = (0, react.createElement)("input", {
1268
- className: "dsu-input zgc-rebuildInput",
1269
- value: root,
1270
- list: ROOT_OPTIONS_ID,
1271
- placeholder: t("rebuildInputPlaceholder"),
1272
- onChange: (ev) => {
1273
- setRoot(ev.target.value);
1274
- }
1275
- });
1276
- const rebuildButton = (0, react.createElement)("button", {
1277
- type: "button",
1278
- className: "dsu-btn",
1279
- "data-field": "rebuild",
1280
- disabled: rebuild.phase === "running",
1281
- onClick: deps.onRebuild
1282
- }, rebuild.phase === "running" ? t("rebuildRunning") : t("rebuildButton"));
1283
- return (0, react.createElement)(v, {
1284
- label: t("rebuildLabel"),
1285
- ...l(rebuildHintText(t, fields.embedding, roots.length > 0)),
1286
- wide: true
1287
- }, rootDatalist, rebuildInput, rebuildButton);
1288
- }
1289
- /**
1290
- * 守护进程(`zg --server`)就绪态一行,取自 rebuild-roots 引导端点。
1291
- *
1292
- * 为什么值得单独占一行:daemon 缺席时检索按直连模式逐次冷加载 embedding 模型,而
1293
- * `refresh=background`、索引增量刷新与常驻模型池都不存在——本包因此在命令构造期就拒
1294
- * background。把这一档摆在「工作区重建」旁边,用户才不至于从「检索怎么这么慢」倒推。
1295
- * `undefined` 那一档**不渲染**:旧版 host 的应答没有这个字段,说成「未就绪」是谎称。
1296
- */
1297
- function buildDaemonNote(deps) {
1298
- const { t } = deps;
1299
- const key = daemonNoteKey(deps.serverReady);
1300
- if (key === void 0) return null;
1301
- return (0, react.createElement)("p", { className: "dsu-hint" }, t(key));
1302
- }
1303
- /** 重建状态节点:phase 非 idle 才出现;done 且无输出时给一句「已完成」。 */
1304
- function buildRebuildStatusRow(deps) {
1305
- const { rebuild, t } = deps;
1306
- if (rebuild.phase === "idle") return null;
1307
- const displayClass = rebuild.phase === "error" ? "zgc-error" : "zgc-output";
1308
- let displayText;
1309
- if (rebuild.output === "") displayText = rebuild.phase === "done" ? t("rebuildDone") : "";
1310
- else displayText = rebuild.output;
1311
- return (0, react.createElement)("div", { className: displayClass }, displayText);
1312
- }
1313
- /** 网络与索引小节:传输三档、镜像地址、search-first 开关、配额与时效、工作区重建与守护进程状态。 */
1314
- function buildIndexSection(deps) {
1315
- const { editable, fields, setField, t } = deps;
1316
- const transport = (0, react.createElement)(C, {
1317
- label: t("transportLabel"),
1318
- ...l(t("transportHint")),
1319
- field: "transport",
1320
- value: fields.transport,
1321
- options: transportOptions(t),
1322
- disabled: !editable,
1323
- onChange: (next) => {
1324
- setField("transport", next);
1325
- }
1326
- });
1327
- const endpoint = (0, react.createElement)(x, {
1328
- label: t("endpointLabel"),
1329
- ...l(t("endpointHint")),
1330
- field: "hfEndpoint",
1331
- value: fields.hfEndpoint,
1332
- placeholder: EMBEDDING_MIRROR_URL,
1333
- monospace: true,
1334
- disabled: !editable,
1335
- onChange: (next) => {
1336
- setField("hfEndpoint", next.trim() === "" ? void 0 : next.trim());
1337
- }
1338
- });
1339
- const enforce = (0, react.createElement)(y, {
1340
- label: t("enforceLabel"),
1341
- ...l(t("enforceHint")),
1342
- field: "enforceSearchFirst",
1343
- checked: fields.enforceSearchFirst,
1344
- disabled: !editable,
1345
- onChange: (next) => {
1346
- setField("enforceSearchFirst", next);
1347
- }
1348
- });
1349
- const budget = (0, react.createElement)(b, {
1350
- label: t("budgetLabel"),
1351
- ...l(t("budgetHint", { default: 3 })),
1352
- field: "grepBudgetPerSearch",
1353
- value: numberDisplay(fields.grepBudget, BUDGET_SCHEMA),
1354
- min: BUDGET_SCHEMA.minValue ?? 1,
1355
- max: BUDGET_SCHEMA.maxValue ?? 20,
1356
- step: 1,
1357
- unit: t("unitTimes"),
1358
- invalidHint: t("outOfRange"),
1359
- disabled: !editable,
1360
- onChange: (next) => {
1361
- setField("grepBudgetPerSearch", next);
1362
- }
1363
- });
1364
- const window = (0, react.createElement)(b, {
1365
- label: t("windowLabel"),
1366
- ...l(t("windowHint", { default: 10 })),
1367
- field: "unlockWindowMin",
1368
- value: numberDisplay(fields.unlockWindow, WINDOW_SCHEMA),
1369
- min: WINDOW_SCHEMA.minValue ?? 1,
1370
- max: WINDOW_SCHEMA.maxValue ?? 240,
1371
- step: 1,
1372
- unit: t("unitMinutes"),
1373
- invalidHint: t("outOfRange"),
1374
- disabled: !editable,
1375
- onChange: (next) => {
1376
- setField("unlockWindowMin", next);
1377
- }
1378
- });
1379
- return (0, react.createElement)(d, { title: t("indexSection") }, transport, endpoint, enforce, budget, window, buildDaemonNote(deps), buildRebuildField(deps), buildRebuildStatusRow(deps));
1380
- }
1381
- /** 卡片主体:检索模型 / 网络与索引两节 + 保存条。 */
1382
- function buildCardBody(deps) {
1383
- const { t } = deps;
1384
- const saveBar = (0, react.createElement)(w, {
1385
- dirty: deps.dirty,
1386
- busy: deps.busy,
1387
- writable: deps.writable,
1388
- error: deps.saveError,
1389
- saveLabel: t("save"),
1390
- savingLabel: t("saving"),
1391
- revertLabel: t("revert"),
1392
- dirtyLabel: t("dirtyCount", { count: deps.dirtyCount }),
1393
- cleanLabel: t("statusClean"),
1394
- readOnlyLabel: t("statusReadOnly"),
1395
- onSave: deps.onSave,
1396
- onDiscard: deps.onDiscard
1397
- });
1398
- return (0, react.createElement)(u, null, buildModelSection(deps), buildIndexSection(deps), saveBar);
1399
- }
1400
- /** 显式字段写入(schema-coverage 门禁按 set('字段名') 字面量识别绑定)。 */
1401
- function pushFieldWrite(ops, key, draft, set) {
1402
- if (key === "defaultEmbedding") ops.push(set("defaultEmbedding", draft));
1403
- else if (key === "defaultLimit") ops.push(set("defaultLimit", draft));
1404
- else if (key === "hfEndpoint") ops.push(set("hfEndpoint", draft));
1405
- else if (key === "enforceSearchFirst") ops.push(set("enforceSearchFirst", draft));
1406
- else if (key === "grepBudgetPerSearch") ops.push(set("grepBudgetPerSearch", draft));
1407
- else if (key === "unlockWindowMin") ops.push(set("unlockWindowMin", draft));
1408
- else if (key === "transport") ops.push(set("transport", draft));
1409
- }
1410
- /** 读取器缺席时的可行动文案(只剩 ctx.get 缺席这一档;remote/命名空间的缺席由读取器现抛)。 */
1411
- function requireReader(reader, t) {
1412
- if (reader === void 0) throw new Error(t("rebuildUnavailable"));
1413
- return reader;
1414
- }
1415
- const NO_ACCESS = {
1416
- roots: [],
1417
- serverReady: void 0
1418
- };
1419
- /**
1420
- * 「工作区重建」状态机:取白名单 → 起一条重建 → 2s 轮询到终态。
1421
- * 从 ZgCard 拆出,保持组件体在一屏内可读。
1422
- * @param t - 取文案(官方 locale 的 translator,随卡片一起下发)。
1423
- * @param reader - 宿主重建读取接口;`undefined` = 当前部署没有远程通道(点重建时报错)。
1424
- */
1425
- function useRebuild(t, reader) {
1426
- const [root, setRoot] = (0, react.useState)("");
1427
- const [access, setAccess] = (0, react.useState)(NO_ACCESS);
1428
- const [rebuild, setRebuild] = (0, react.useState)({
1429
- phase: "idle",
1430
- output: ""
1431
- });
1432
- const pollRef = (0, react.useRef)(null);
1433
- const pollingRef = (0, react.useRef)(false);
1434
- const jobRef = (0, react.useRef)(null);
1435
- const mountedRef = (0, react.useRef)(true);
1436
- const isMounted = () => mountedRef.current;
1437
- function stopPolling() {
1438
- jobRef.current = null;
1439
- if (pollRef.current !== null) {
1440
- clearInterval(pollRef.current);
1441
- pollRef.current = null;
1442
- }
1443
- }
1444
- (0, react.useEffect)(() => {
1445
- mountedRef.current = true;
1446
- return () => {
1447
- mountedRef.current = false;
1448
- stopPolling();
1449
- };
1450
- }, []);
1451
- /** 拉白名单 + 就绪态。失败**不**改重建面板:面板 idle 时冒一个红字只是噪音,
1452
- * 用户真点「重建」时 start() 会把同一错误显示出来。 */
1453
- const refreshAccess = (0, react.useCallback)(async () => {
1454
- const next = await requireReader(reader, t).roots();
1455
- const view = {
1456
- roots: [...next.roots],
1457
- serverReady: next.serverReady
1458
- };
1459
- setAccess(view);
1460
- return view;
1461
- }, [reader, t]);
1462
- (0, react.useEffect)(() => {
1463
- (async () => {
1464
- try {
1465
- await refreshAccess();
1466
- } catch {
1467
- setAccess(NO_ACCESS);
1468
- }
1469
- })();
1470
- }, [refreshAccess]);
1471
- async function pollStatus(jobId) {
1472
- if (pollingRef.current || !isMounted() || jobRef.current !== jobId) return;
1473
- pollingRef.current = true;
1474
- try {
1475
- const body = await requireReader(reader, t).status(jobId);
1476
- if (!isMounted() || jobRef.current !== jobId) return;
1477
- const poll = parseRebuildPoll(body, t);
1478
- if (poll.phase !== "running") stopPolling();
1479
- setRebuild({
1480
- phase: poll.phase,
1481
- output: poll.output
1482
- });
1483
- } catch (error) {
1484
- if (!isMounted() || jobRef.current !== jobId) return;
1485
- stopPolling();
1486
- setRebuild({
1487
- phase: "error",
1488
- output: r(error)
1489
- });
1490
- } finally {
1491
- pollingRef.current = false;
1492
- }
1493
- }
1494
- /** 发起一次重建;成功后进入轮询。 */
1495
- async function startOnce() {
1496
- const started = await requireReader(reader, t).rebuild(root.trim());
1497
- const parsedStarted = zod.z.object({ jobId: zod.z.string() }).safeParse(started);
1498
- if (!parsedStarted.success) throw new TypeError(t("rebuildMissingJobId"));
1499
- const { jobId } = parsedStarted.data;
1500
- jobRef.current = jobId;
1501
- pollRef.current = setInterval(() => {
1502
- pollStatus(jobId);
1503
- }, REBUILD_POLL_MS);
1504
- }
1505
- async function start() {
1506
- const trimmedRoot = root.trim();
1507
- if (!(trimmedRoot.startsWith("/") || WIN32_ABSOLUTE_ROOT.test(trimmedRoot) || trimmedRoot.startsWith(BACKSLASH + BACKSLASH))) {
1508
- setRebuild({
1509
- phase: "error",
1510
- output: t("rebuildRootNotAbsolute")
1511
- });
1512
- return;
1513
- }
1514
- stopPolling();
1515
- setRebuild({
1516
- phase: "running",
1517
- output: t("rebuildStarting")
1518
- });
1519
- try {
1520
- await startOnce();
1521
- } catch (error) {
1522
- stopPolling();
1523
- setRebuild({
1524
- phase: "error",
1525
- output: r(error)
1526
- });
1527
- }
1528
- }
1529
- return {
1530
- root,
1531
- roots: access.roots,
1532
- serverReady: access.serverReady,
1533
- state: rebuild,
1534
- setRoot,
1535
- start
1536
- };
1537
- }
1538
- function ZgCard(props) {
1539
- const { t } = props;
1540
- const snap = props.useCard((state) => state);
1541
- const { status, writable: isSnapWritable } = snap;
1542
- const writable = status === "ready" && isSnapWritable;
1543
- const value = snapshotValue(snap);
1544
- const [touched, setTouched] = (0, react.useState)({});
1545
- const [busy, setBusy] = (0, react.useState)(false);
1546
- const [saveError, setSaveError] = (0, react.useState)(null);
1547
- const rebuildView = useRebuild(t, props.rebuildRemote);
1548
- const fields = draftFields(touched, value);
1549
- const dirtyCount = t$1(touched, value).length;
1550
- const dirty = dirtyCount > 0;
1551
- const setField = (field, draft) => {
1552
- setTouched((prev) => ({
1553
- ...prev,
1554
- [field]: draft
1555
- }));
1556
- };
1557
- const save = async () => {
1558
- const keys = t$1(touched, value);
1559
- if (keys.length === 0) return;
1560
- setBusy(true);
1561
- setSaveError(null);
1562
- const ops = [];
1563
- for (const key of keys) {
1564
- const draft = touched[key];
1565
- if (draft === void 0) ops.push(props.unset(key));
1566
- else pushFieldWrite(ops, key, draft, props.set);
1567
- }
1568
- try {
1569
- if ((await Promise.all(ops)).some((accepted) => !accepted)) {
1570
- setBusy(false);
1571
- setSaveError(t("saveRejected"));
1572
- return;
1573
- }
1574
- } catch (error) {
1575
- setBusy(false);
1576
- setSaveError(t("saveFailed", { reason: r(error) }));
1577
- return;
1578
- }
1579
- const savedKeys = new Set(keys);
1580
- const next = Object.fromEntries(Object.entries(touched).filter(([entryKey]) => !savedKeys.has(entryKey)));
1581
- setBusy(false);
1582
- setTouched(next);
1583
- };
1584
- const discard = () => {
1585
- setTouched({});
1586
- setSaveError(null);
1587
- };
1588
- return buildCardBody({
1589
- t,
1590
- fields,
1591
- writable,
1592
- editable: writable && !busy,
1593
- roots: rebuildView.roots,
1594
- serverReady: rebuildView.serverReady,
1595
- root: rebuildView.root,
1596
- rebuild: rebuildView.state,
1597
- dirty,
1598
- dirtyCount,
1599
- busy,
1600
- saveError,
1601
- setField,
1602
- setRoot: rebuildView.setRoot,
1603
- onSave: () => {
1604
- save();
1605
- },
1606
- onDiscard: discard,
1607
- onRebuild: () => {
1608
- rebuildView.start();
1609
- }
1610
- });
1611
- }
1612
- const inject = [
1613
- "slots",
1614
- "configForms",
1615
- "locale"
1616
- ];
1617
- function apply(ctx) {
1618
- ctx.effect(() => {
1619
- const tag = document.createElement("style");
1620
- tag.id = "zvec-grep-card-css";
1621
- tag.textContent = `${CARD_CSS}\n${c}`;
1622
- document.head.append(tag);
1623
- return () => {
1624
- tag.remove();
1625
- };
1626
- }, "zvec-grep-card: styles");
1627
- const scope = ctx.configForms.get(NS);
1628
- const store = cardStore(scope);
1629
- ctx.effect(() => ctx.locale.register(NS, UI_MESSAGES), "zvec-grep-card: locale dictionaries");
1630
- const t = ctx.locale.bind(NS);
1631
- const rebuildRemote = createRebuildReader(ctx, {
1632
- remoteMissing: () => t("rebuildRemoteMissing"),
1633
- namespaceMissing: (serviceKey) => t("rebuildNamespaceMissing", { serviceKey })
1634
- });
1635
- const writeField = async (field, valueDraft) => {
1636
- try {
1637
- return await scope.set(field, valueDraft);
1638
- } catch (error) {
1639
- console.error(`[zvec-grep] set ${field} failed:`, error);
1640
- throw error;
1641
- }
1642
- };
1643
- const unsetField = async (field) => {
1644
- try {
1645
- return await scope.unset(field);
1646
- } catch (error) {
1647
- console.error(`[zvec-grep] unset ${field} failed:`, error);
1648
- throw error;
1649
- }
1650
- };
1651
- ctx.slots.inject("plugins.bundle.config", () => {
1652
- return ctx.slots.register({
1653
- name: "plugins.bundle.config",
1654
- key: BUNDLE_PKG,
1655
- inject: () => ({
1656
- t,
1657
- hooks: { card: store },
1658
- set: writeField,
1659
- unset: unsetField,
1660
- rebuildRemote
1661
- })
1662
- }, ZgCard);
1663
- });
1664
- }
1665
- exports.apply = apply;
1666
- exports.cardStore = cardStore;
1667
- exports.draftFields = draftFields;
1668
- exports.inject = inject;
1669
- exports.parseRebuildPoll = parseRebuildPoll;
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){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 d(e,t,n,r){let i=s(e,t,n);return i===void 0?o(e,n)?``:r:c(i,r)}const f=t.z.url({protocol:/^https?$/u});function p(e,t){if(Object.hasOwn(e,`hfEndpoint`)){let t=e.hfEndpoint;return typeof t==`string`?t:``}let n=t.hfEndpoint;return typeof n==`string`&&f.safeParse(n).success?n:``}function m(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:d(e,t,`defaultLimit`,`10`),hfEndpoint:p(e,t),enforceSearchFirst:r!==!1,grepBudget:d(e,t,`grepBudgetPerSearch`,`3`),unlockWindow:d(e,t,`unlockWindowMin`,`10`),transport:i===`cli`||i===`mcp`||i===`auto`?i:`auto`}}const h=t.z.int().min(1).max(50),g=t.z.int().min(1).max(20),_=t.z.int().min(1).max(240),v=[`running`,`stopping`,`completed`,`killed`,`failed`],y=t.z.object({status:t.z.preprocess(e=>typeof e==`string`&&v.some(t=>t===e)?e:void 0,t.z.enum(v).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 b(e,t){let n=y.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 x=`zvecGrepRebuild`,S=`remote.${x}`,C=`@jayyuen66/dsh-zvec-grep`;function w(e,n){let r=e.safeParse(n);if(!r.success)throw TypeError(t.z.prettifyError(r.error));return r.data}const 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:`${C}#${x}/roots`,service:x,namespace:x,method:`roots`,invocation:{kind:`direct`},parameters:[],result:{mode:`src-json`}},{id:`${C}#${x}/rebuild`,service:x,namespace:x,method:`rebuild`,invocation:{kind:`direct`},parameters:[{name:`request`,wire:`request`,source:`json`,codec:{mode:`strict`,typeSymbol:`${C}#rebuild-request`,create:()=>({parse(e){return w(T,e)}})}}],result:{mode:`src-json`}},{id:`${C}#${x}/status`,service:x,namespace:x,method:`status`,invocation:{kind:`direct`},parameters:[{name:`request`,wire:`request`,source:`json`,codec:{mode:`strict`,typeSymbol:`${C}#rebuild-status-request`,create:()=>({parse(e){return w(E,e)}})}}],result:{mode:`src-json`}}],O=e=>(0,n.isRecord)(e)&&typeof e.$mount==`function`,ee=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 n,r=async()=>{let r=e.get?.(`remote`);if(!O(r))throw Error(t.remoteMissing());try{n??=r.$mount({package:C,descriptors:D}),await n}catch(e){throw n=void 0,e}let i=e.get?.(S);if(!ee(i))throw Error(t.namespaceMissing(S));return i};return{async roots(){return k((await r()).roots())},async rebuild(e){let t=await k((await r()).rebuild({root:e}));if(t.ok)return t;throw Error(t.error)},async status(e){let t=await k((await r()).status({jobId:e}));if(t.ok)return{...t};throw Error(t.error)}}}function j(e,t){return typeof e.get==`function`?A(e,t):void 0}const M=`https://modelscope.cn/models`,N={zh:{statusReadOnly:`当前作用域只读`,statusClean:`无未保存的修改`,dirtyCount:`已修改 {count} 项`,save:`保存`,saving:`保存中…`,revert:`撤销`,saveFailed:`保存失败:{reason}`,invalidFields:`有字段超出范围,先修正或撤销后再保存。`,saveRejected:`保存被宿主拒绝(配置校验未通过或写入被跳过),修改未生效`,modelSection:`检索模型`,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;国内网络可填 ${M} 等兼容镜像(仅 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`。",rebuildHint:`以当前默认模型重建:{embedding};等价于 zg --index --rebuild。{roots}`,rootsNoteWith:`候选工作区来自本 daemon 已打开过的会话(服务端白名单)。`,rootsNoteEmpty:`尚无可选工作区:先在该工作区里开一个会话(任一次工具调用即登记)。`,rebuildButton:`重建索引(动作,点击即执行)`,rebuildRunning:`重建中…`,rebuildDone:`重建完成`,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`,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 ${M} (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}`,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`,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)`}},P=String.fromCodePoint(92),te=/^[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,h),min:h.minValue??1,max:h.maxValue??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`)},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 zgc-rebuildInput`,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,d,f)}function Y(t){let{t:n}=t,r=l(t.serverReady);return r===void 0?null:(0,e.createElement)(`p`,{className:`dsu-hint`},n(r))}function X(t){let{rebuild:n,t:r}=t;if(n.phase===`idle`)return null;let i=n.phase===`error`?`zgc-error`:`zgc-output`,a;return a=n.output===``?n.phase===`done`?r(`rebuildDone`):``:n.output,(0,e.createElement)(`div`,{className:i},a)}function Z(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:M,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,g),min:g.minValue??1,max:g.maxValue??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,_),min:_.minValue??1,max:_.maxValue??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`)},s,c,l,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),Z(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 Q(e,t){if(e===void 0)throw Error(t(`rebuildUnavailable`));return e}const $={roots:[],serverReady:void 0};function ie(r,i){let[a,o]=(0,e.useState)(``),[s,c]=(0,e.useState)($),[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 Q(i,r).roots(),t={roots:[...e.roots],serverReady:e.serverReady};return c(t),t},[i,r]);(0,e.useEffect)(()=>{(async()=>{try{await _()}catch{c($)}})()},[_]);async function v(e){if(!f.current&&h()&&p.current===e){f.current=!0;try{let t=await Q(i,r).status(e);if(!h()||p.current!==e)return;let n=b(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 Q(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 x(){let e=a.trim();if(!(e.startsWith(`/`)||te.test(e)||e.startsWith(P+P)))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:x}}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)({}),[d,f]=(0,e.useState)(!1),[p,h]=(0,e.useState)(null),g=ie(r,t.rebuildRemote),_=m(l,c),v=(0,n.useInvalidFields)(),{blocked:y,fields:b,resetToken:x,reportInvalid:S}=v,C=new Set([...(0,n.diffTouched)(l,c),...b]).size,w=C>0||y,T=(e,t)=>{u(n=>({...n,[e]:t}))},E=async()=>{let e=(0,n.diffTouched)(l,c);if(e.length===0||y)return;f(!0),h(null);let i=[];for(let n of e){let e=l[n];e===void 0?i.push(t.unset(n)):re(i,n,e,t.set)}try{if((await Promise.all(i)).some(e=>!e)){f(!1),h(r(`saveRejected`));return}}catch(e){f(!1),h(r(`saveFailed`,{reason:(0,n.errorText)(e)}));return}let a=new Set(e),o=Object.fromEntries(Object.entries(l).filter(([e])=>!a.has(e)));f(!1),u(o),v.clear()};return ne({t:r,fields:_,writable:s,editable:s&&!d,roots:g.roots,serverReady:g.serverReady,root:g.root,rebuild:g.state,dirty:w,blocked:y,resetToken:x,reportInvalid:S,dirtyCount:C,busy:d,saveError:p,setField:T,setRoot:g.setRoot,onSave:()=>{E()},onDiscard:()=>{u({}),h(null),v.clear()},onRebuild:()=>{g.start()}})}const oe=[`slots`,`configForms`,`locale`];function se(e){e.effect(()=>{let e=(0,n.ensureCardUiCss)(),t=document.createElement(`style`);return t.id=`zvec-grep-card-css`,t.textContent=`.zgc-rebuildInput{flex:1 1 240px;min-width:0}
9
+ .zgc-output{font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary,inherit);white-space:pre-wrap;word-break:break-all;max-height:180px;overflow:auto;background:var(--dsw-alias-fill-primary,transparent);border:1px solid var(--dsw-alias-border-l2);border-radius:6px;padding:8px;margin-top:8px}
10
+ .zgc-error{font-size:12px;color:var(--dsw-alias-text-danger,#d33);margin-top:8px}`,document.head.append(t),()=>{t.remove(),e()}},`zvec-grep-card: styles`);let t=e.configForms.get(F),r=u(t);e.effect(()=>e.locale.register(F,N),`zvec-grep-card: locale dictionaries`);let i=e.locale.bind(F),a=j(e,{remoteMissing:()=>i(`rebuildRemoteMissing`),namespaceMissing:e=>i(`rebuildNamespaceMissing`,{serviceKey:e})}),o=async(e,n)=>{try{return await t.set(e,n)}catch(t){throw console.error(`[zvec-grep] set ${e} failed:`,t),t}},s=async e=>{try{return await t.unset(e)}catch(t){throw console.error(`[zvec-grep] unset ${e} failed:`,t),t}};e.slots.inject(`plugins.bundle.config`,()=>e.slots.register({name:`plugins.bundle.config`,key:`@jayyuen66/dsh-zvec-grep`,inject:()=>({t:i,hooks:{card:r},set:o,unset:s,rebuildRemote:a})},ae))}exports.apply=se,exports.cardStore=u,exports.draftFields=m,exports.inject=oe,exports.parseRebuildPoll=b;
1670
11
  return module.exports;
1671
12
  },
1672
13
  });