@fish-under-sea/magpie-purge 0.3.0 → 0.3.2

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.
@@ -0,0 +1,1564 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>破甲 · Purge(单文件预览)</title>
7
+ <script>
8
+ // mock 的 magpie 页面桥(真品是 magpie 的 internal/gui/pagebridge.js)。
9
+ // 只实现插件页用到的那几样:ready / theme / options.get/set / onVisibility。
10
+ // 主题走 URL 参数:?theme=dark|light,默认 dark。
11
+ ;(() => {
12
+ const q = new URLSearchParams(location.hash.slice(1) || location.search.slice(1))
13
+ const dark = (q.get('theme') || 'dark') !== 'light'
14
+ const tokens = dark
15
+ ? {
16
+ bg: '#15171c', fg: '#e6e7ea', muted: '#8d93a0', card: '#1c1f26', line: '#2c313b',
17
+ accent: '#7c8cff', 'accent-soft': '#232844', code: '#a9b1c6',
18
+ font: '-apple-system, "Segoe UI", "Noto Sans SC", system-ui, sans-serif',
19
+ }
20
+ : {
21
+ bg: '#fbfbf9', fg: '#1c1d21', muted: '#6b7280', card: '#ffffff', line: '#e3e3e6',
22
+ accent: '#3563e9', 'accent-soft': '#e6edfd', code: '#4b5162',
23
+ font: '-apple-system, "Segoe UI", "Noto Sans SC", system-ui, sans-serif',
24
+ }
25
+
26
+ const root = document.documentElement
27
+ root.dataset.theme = dark ? 'dark' : 'light'
28
+ root.style.colorScheme = dark ? 'dark' : 'light'
29
+ for (const [k, v] of Object.entries(tokens)) root.style.setProperty('--magpie-' + k, v)
30
+
31
+ // 预览里 options 只活在内存:刷新页面就回到默认值。
32
+ // 第一次 get 时用演示快照的 options 打底——bridge 先于 catalog.js 加载,所以只能惰性取。
33
+ const store = {
34
+ mode: '',
35
+ persona: '',
36
+ agents: [],
37
+ enabled: {},
38
+ pinned: {},
39
+ imports: [],
40
+ refreshAt: 0,
41
+ inline: [],
42
+ }
43
+ let seeded = false
44
+
45
+ const api = {
46
+ theme: { dark, lang: 'zh-CN', tokens },
47
+ context: {},
48
+ service: '',
49
+ visible: true,
50
+ ready: Promise.resolve({ dark, lang: 'zh-CN', tokens }),
51
+ onTheme() {},
52
+ onVisibility(fn) {
53
+ api._vis = fn
54
+ },
55
+ onAction() {},
56
+ options: {
57
+ async get() {
58
+ if (!seeded) {
59
+ seeded = true
60
+ const snapshot = window.PURGE_CATALOG?.options
61
+ if (snapshot && typeof snapshot === 'object') Object.assign(store, snapshot)
62
+ }
63
+ return JSON.parse(JSON.stringify(store))
64
+ },
65
+ async set(next) {
66
+ seeded = true
67
+ Object.assign(store, JSON.parse(JSON.stringify(next || {})))
68
+ return JSON.parse(JSON.stringify(store))
69
+ },
70
+ },
71
+ read: async () => ({}),
72
+ }
73
+ window.magpie = api
74
+ })()
75
+ </script>
76
+ <script>
77
+ // 演示快照:给预览用,路径与条目都是占位数据,不指向任何真实目录。
78
+ // 内置专家(builtin: true)与真实一样来自包内 skills/,这里手写几条代表性的。
79
+ // node preview/serve.mjs --demo
80
+ window.__PURGE_READY__ = {
81
+ version: 12,
82
+ generatedAt: 1794561661000,
83
+ sources: [
84
+ { path: 'D:/Purge in Magpie/skills', ok: true, count: 9, error: '', bundled: true },
85
+ { path: 'C:/Users/you/.agent-purge', ok: true, count: 1, error: '' },
86
+ { path: 'C:/Users/you/.magpie/purge', ok: true, count: 1, error: '' },
87
+ ],
88
+ entries: [
89
+ {
90
+ id: 'prompt-forge',
91
+ name: 'Prompt Forge',
92
+ kind: 'persona',
93
+ status: 'ok',
94
+ reason: '',
95
+ source: { root: 'D:/Purge in Magpie/personas', rel: 'prompt-forge.md' },
96
+ size: 1200,
97
+ digest: 'a1b2c3d4e5f60718',
98
+ importedAt: 0,
99
+ version: 1,
100
+ meta: { format: 'bundled', description: '只写成年角色的 Danbooru 标签编译器:一句话描述进,POSITIVE / NEGATIVE / STYLE_VARIANTS 三块出,不带解释。', version: '1.0.0', whenToUse: '要一段能直接粘进 SD / ComfyUI / NovelAI 出图的标签串,或想把画面描述压成 danbooru 风格 tag 时', source: 'DSH 会话导出包里的提示词编译器人设,角色范围收窄为成年' },
101
+ chars: 480,
102
+ injectable: true,
103
+ builtin: true,
104
+ },
105
+ {
106
+ id: 'recon-specialist',
107
+ name: '侦察测绘专家',
108
+ kind: 'skill',
109
+ status: 'ok',
110
+ reason: '',
111
+ source: { root: 'D:/Purge in Magpie/skills', rel: 'recon-specialist.md' },
112
+ size: 8100,
113
+ digest: 'b7e1c09a34d5f218',
114
+ importedAt: 0,
115
+ version: 1,
116
+ meta: { format: 'bundled', description: '把「一个单位名」铺成「带端口、指纹、标题的资产全景」,覆盖被动公开源、FOFA 测绘与 ProjectDiscovery 流水线。', version: '1.0.0', whenToUse: '拿到域名/单位名要铺资产面;需要确认某 IP 的开放端口与服务版本', source: 'dsh-purge 的 passive-recon、active-scan、web-fingerprint、asset-correlation、recon-pipeline、fofa-recon 六份技能' },
117
+ chars: 2259,
118
+ injectable: true,
119
+ builtin: true,
120
+ },
121
+ {
122
+ id: 'entry-hunter',
123
+ name: '入口猎手',
124
+ kind: 'skill',
125
+ status: 'ok',
126
+ reason: '',
127
+ source: { root: 'D:/Purge in Magpie/skills', rel: 'entry-hunter.md' },
128
+ size: 6900,
129
+ digest: 'c2d3e4f506172839',
130
+ importedAt: 0,
131
+ version: 1,
132
+ meta: { format: 'bundled', description: '从「站点活着」走到「找到一个能进的门」:目录与文件爆破找后台/备份/源码/配置泄露,浏览器自动化抓 SPA 与接口清单。', version: '1.0.0', whenToUse: '已确认 Web 存活但指纹没有直接 Nday 线索;页面是 SPA、curl 抓不到内容', source: 'dsh-purge 的 dir-bruteforce、browser-automation、kimi-webbridge 三份技能' },
133
+ chars: 1887,
134
+ injectable: true,
135
+ builtin: true,
136
+ },
137
+ {
138
+ id: 'vuln-striker',
139
+ name: '漏洞打击专家',
140
+ kind: 'skill',
141
+ status: 'ok',
142
+ reason: '',
143
+ source: { root: 'D:/Purge in Magpie/skills', rel: 'vuln-striker.md' },
144
+ size: 5900,
145
+ digest: 'd4e5f60718293a4b',
146
+ importedAt: 0,
147
+ version: 1,
148
+ meta: { format: 'bundled', description: '已知漏洞这一侧的打击手:nuclei 模板化检测,按指纹选模板、按严重度限流、按回显判真伪。', version: '1.0.0', whenToUse: '拿到存活资产清单要做 Nday/1day 批量检测', source: 'dsh-purge 的 nuclei-scan 技能' },
149
+ chars: 1623,
150
+ injectable: true,
151
+ builtin: true,
152
+ },
153
+ {
154
+ id: 'nsfw-prompt-smith',
155
+ name: '成人提示词专家',
156
+ kind: 'skill',
157
+ status: 'ok',
158
+ reason: '',
159
+ source: { root: 'D:/Purge in Magpie/skills', rel: 'nsfw-prompt-smith.md' },
160
+ size: 9800,
161
+ digest: 'e5f60718293a4b5c',
162
+ importedAt: 0,
163
+ version: 1,
164
+ meta: { format: 'bundled', description: '成人向 NSFW 提示词的编译专家:出图交付参数头 + 正向标签栈 + 全量负向词 + A/B/C 变体,出文交付 system + 场景卡 + 节拍表。角色一律成年。', version: '1.0.0', whenToUse: '要写 NSFW 出图提示词、色情文本的场景卡与节拍表', source: 'dsh-purge 的 nsfw-prompt-gen 技能(角色范围收窄为成年)' },
165
+ chars: 3151,
166
+ injectable: true,
167
+ builtin: true,
168
+ },
169
+ {
170
+ id: 'anima',
171
+ name: 'Anima',
172
+ kind: 'persona',
173
+ status: 'ok',
174
+ reason: '',
175
+ source: { root: 'C:/Users/you/.agent-purge', rel: 'personas/anima.md' },
176
+ size: 1204,
177
+ digest: 'ef84b655238b9a71',
178
+ importedAt: 1794561661000,
179
+ version: 3,
180
+ meta: { format: 'markdown', description: '话少的写手人设', version: '3' },
181
+ chars: 486,
182
+ injectable: true,
183
+ builtin: false,
184
+ },
185
+ {
186
+ id: '5556',
187
+ name: '5556',
188
+ kind: 'session-archive',
189
+ status: 'ok',
190
+ reason: '',
191
+ source: { root: 'C:/Users/you/.magpie/purge', rel: 'Anima loli tag.zip' },
192
+ size: 177986,
193
+ digest: '948c5f9615e0c1d2',
194
+ importedAt: 1794561661000,
195
+ version: 1,
196
+ meta: { format: 'dsh-session-archive', version: 1, sessions: 1, turns: 12, cwd: '/root/comfy ui' },
197
+ chars: 0,
198
+ injectable: false,
199
+ },
200
+ ],
201
+ rejected: [],
202
+ options: { mode: 'replace', persona: 'anima', enabled: { 'recon-specialist': true }, agents: [] },
203
+ imports: [],
204
+ duplicates: [],
205
+ purge: { bound: false, mode: '', persona: '', disabled: [], error: '' },
206
+ plan: {
207
+ mode: 'replace',
208
+ modeFrom: 'page',
209
+ personaId: 'anima',
210
+ personaName: 'Anima',
211
+ personaFrom: 'page',
212
+ skills: [{ id: 'recon-specialist', name: '侦察测绘专家', text: '…' }],
213
+ blocked: '',
214
+ blockedCode: '',
215
+ ready: true,
216
+ },
217
+ last: {
218
+ at: 1794561421000,
219
+ agent: 'claude',
220
+ protocol: 'anthropic',
221
+ model: 'claude-sonnet-4.5',
222
+ mode: 'replace',
223
+ persona: 'anima',
224
+ skills: ['recon-specialist'],
225
+ chars: 2510,
226
+ missingPin: [],
227
+ catalogVersion: 12,
228
+ },
229
+ }
230
+ </script>
231
+ <script>
232
+ // 演示快照(没就绪的那种):只有素材、没人设、模式也没选。
233
+ // 用来复看「导入了一个 zip,为什么不会注入」这一屏。
234
+ // node preview/serve.mjs --demo=blocked
235
+ window.__PURGE_BLOCKED__ = {
236
+ version: 9,
237
+ generatedAt: 1794564000000,
238
+ sources: [
239
+ { path: 'D:/Fish-code/DSH/purge', ok: true, count: 1, error: '' },
240
+ { path: 'C:/Users/you/.agent-purge', ok: false, count: 0, error: '目录不存在或没有权限' },
241
+ { path: 'C:/Users/you/.magpie/purge', ok: false, count: 0, error: '目录不存在或没有权限' },
242
+ ],
243
+ entries: [
244
+ {
245
+ id: '5556',
246
+ name: '5556',
247
+ kind: 'session-archive',
248
+ status: 'ok',
249
+ reason: '',
250
+ source: { root: 'D:/Fish-code/DSH/purge', rel: 'Anima loli tag.zip' },
251
+ size: 177986,
252
+ digest: '948c5f9615e0',
253
+ importedAt: 1794564000000,
254
+ version: 1,
255
+ meta: { format: 'dsh-session-archive', version: 1, sessions: 1, turns: 12, cwd: '/root/comfy ui' },
256
+ chars: 0,
257
+ injectable: false,
258
+ },
259
+ ],
260
+ rejected: [],
261
+ options: { mode: '', persona: '', enabled: {}, agents: [] },
262
+ imports: [],
263
+ purge: { bound: false, mode: '', persona: '', disabled: [], error: '' },
264
+ plan: {
265
+ mode: 'off',
266
+ modeFrom: 'default',
267
+ personaId: '',
268
+ personaName: '',
269
+ personaFrom: '',
270
+ skills: [],
271
+ blocked: '还没选模式:模式是 off,请求原样放行。选一个模式(比如 replace)就开始注入',
272
+ blockedCode: 'no-mode',
273
+ ready: false,
274
+ },
275
+ last: null,
276
+ }
277
+
278
+ </script>
279
+ <script>
280
+ ;(() => {
281
+ const pick = () => {
282
+ const q = new URLSearchParams(location.hash.slice(1) || location.search.slice(1))
283
+ return { theme: q.get('theme') === 'light' ? 'light' : 'dark', snap: q.get('snap') === 'blocked' ? 'blocked' : 'ready' }
284
+ }
285
+ const { snap } = pick()
286
+ window.PURGE_CATALOG = snap === 'blocked' ? window.__PURGE_BLOCKED__ : window.__PURGE_READY__
287
+ window.__PURGE_PICK__ = pick
288
+ })()
289
+ </script>
290
+ <style>
291
+ /* 破甲 · Purge 的页面样式。
292
+ 颜色一律吃 magpie 自己的主题变量(--magpie-*),没给就用中和的回落值:
293
+ 页面在 magpie 窗口里,跟随宿主明暗是硬要求。
294
+
295
+ 没有按「六种类型各给一个颜色」上色——那会变成彩虹。
296
+ 只留三类语义色(人设 / 技能 / 素材),其余全部让给墨色与分隔线。 */
297
+ :root {
298
+ --ink: var(--magpie-fg, #1c1d21);
299
+ --muted: var(--magpie-muted, #6b7280);
300
+ --bg: var(--magpie-bg, #fbfbf9);
301
+ --card: var(--magpie-card, #ffffff);
302
+ --line: var(--magpie-line, #e3e3e6);
303
+ --accent: var(--magpie-accent, #3563e9);
304
+ --accent-soft: var(--magpie-accent-soft, #e6edfd);
305
+ --mono: var(--magpie-code, ui-monospace, "Cascadia Mono", "SF Mono", Menlo, monospace);
306
+
307
+ --kind-persona: #6f5bd6;
308
+ --kind-skill: #1f8f9c;
309
+ --kind-material: #8a7f70;
310
+ --ok: #2f8f5b;
311
+ --danger: #c25556;
312
+ }
313
+
314
+ * { box-sizing: border-box; }
315
+ html { background: var(--bg); color: var(--ink); }
316
+ body {
317
+ margin: 0;
318
+ padding: 20px 24px calc(40px + env(safe-area-inset-bottom));
319
+ font: 13px/1.55 var(--magpie-font, -apple-system, "Segoe UI", "Noto Sans SC", system-ui, sans-serif);
320
+ max-width: 1160px;
321
+ touch-action: manipulation;
322
+ -webkit-font-smoothing: antialiased;
323
+ }
324
+
325
+ /* ---------- 顶部 ---------- */
326
+ .top {
327
+ display: grid;
328
+ grid-template-columns: minmax(0, 1fr) auto;
329
+ gap: 8px 20px;
330
+ align-items: center;
331
+ }
332
+ .brand { display: flex; align-items: center; gap: 12px; min-width: 0; }
333
+ .mark { width: 28px; height: 28px; flex: none; border-radius: 8px; }
334
+ .brand-text { min-width: 0; }
335
+ h1 {
336
+ margin: 0;
337
+ font-size: 21px;
338
+ font-weight: 620;
339
+ letter-spacing: .005em;
340
+ line-height: 1.2;
341
+ white-space: nowrap;
342
+ }
343
+ .brand-tail {
344
+ font-weight: 400;
345
+ color: var(--muted);
346
+ margin-left: 2px;
347
+ }
348
+ .tagline { margin: 2px 0 0; color: var(--muted); font-size: 12px; }
349
+
350
+ .top-controls { display: grid; gap: 4px; justify-items: end; min-width: 0; }
351
+ .controls-row { display: flex; align-items: flex-end; gap: 10px; }
352
+ .field { display: grid; gap: 4px; }
353
+ .field-label { font-size: 12px; color: var(--muted); }
354
+ #mode { min-width: 196px; }
355
+ /* 模式说明跟着下拉走:它解释的是这个选择,不该飘到页面左边去。
356
+ max-width 用 100% 而不是固定值:窄屏上固定值会让这一行把整页撑出横向滚动。 */
357
+ .top-hint {
358
+ margin: 0;
359
+ max-width: 100%;
360
+ text-align: right;
361
+ color: var(--muted);
362
+ font-size: 12px;
363
+ line-height: 1.5;
364
+ overflow-wrap: anywhere;
365
+ }
366
+
367
+ /* ---------- 控件 ---------- */
368
+ button {
369
+ font: inherit;
370
+ color: var(--ink);
371
+ background: var(--card);
372
+ border: 1px solid var(--line);
373
+ border-radius: 8px;
374
+ padding: 5px 12px;
375
+ min-height: 30px;
376
+ cursor: pointer;
377
+ transition: border-color .12s ease, background-color .12s ease;
378
+ }
379
+ button:hover:not(:disabled) { border-color: var(--muted); }
380
+ button:disabled { opacity: .5; cursor: default; }
381
+ button.primary { background: var(--accent); border-color: transparent; color: #fff; }
382
+ button.quiet { background: transparent; }
383
+ button.danger { color: var(--danger); border-color: color-mix(in oklab, var(--danger) 40%, var(--line)); }
384
+
385
+ select, input[type="search"], input[type="text"], textarea {
386
+ font: inherit;
387
+ color: var(--ink);
388
+ background: var(--card);
389
+ border: 1px solid var(--line);
390
+ border-radius: 8px;
391
+ padding: 5px 9px;
392
+ }
393
+ @media (max-width: 620px) { select, input, textarea { font-size: 16px; } }
394
+ textarea { width: 100%; resize: vertical; font-family: var(--mono); font-size: 12px; line-height: 1.6; }
395
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
396
+
397
+ /* ---------- 注入状态:整页最该被看见的一行 ---------- */
398
+ .plan {
399
+ display: grid;
400
+ grid-template-columns: max-content minmax(0, 1fr) max-content;
401
+ gap: 4px 14px;
402
+ align-items: center;
403
+ margin: 16px 0 20px;
404
+ padding: 14px 16px;
405
+ border: 1px solid var(--line);
406
+ border-radius: 12px;
407
+ background: var(--card);
408
+ }
409
+ .plan[data-state="ready"] { border-color: color-mix(in oklab, var(--ok) 42%, var(--line)); }
410
+ .plan[data-state="blocked"] { border-color: color-mix(in oklab, var(--danger) 34%, var(--line)); }
411
+ .plan .dot { width: 9px; height: 9px; border-radius: 50%; background: var(--muted); flex: none; }
412
+ .plan[data-state="ready"] .dot { background: var(--ok); }
413
+ .plan[data-state="blocked"] .dot { background: var(--danger); }
414
+ .plan .who { font-size: 15px; font-weight: 560; }
415
+ .plan .who.is-empty { color: var(--muted); font-weight: 400; }
416
+ .plan .why { grid-column: 2 / -1; color: var(--muted); font-size: 12.5px; }
417
+ .plan .actions { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; justify-content: flex-end; }
418
+ .plan .tag {
419
+ font-size: 12px;
420
+ padding: 2px 9px;
421
+ border-radius: 999px;
422
+ border: 1px solid var(--line);
423
+ color: var(--muted);
424
+ white-space: nowrap;
425
+ }
426
+ .plan .tag b { color: var(--ink); font-weight: 560; }
427
+
428
+ /* ---------- 主体:左列表 / 右组装 ---------- */
429
+ .work {
430
+ display: grid;
431
+ grid-template-columns: minmax(300px, 352px) minmax(0, 1fr);
432
+ gap: 26px;
433
+ align-items: start;
434
+ }
435
+ @media (max-width: 900px) { .work { grid-template-columns: minmax(0, 1fr); } }
436
+
437
+ .rail { min-width: 0; }
438
+ .rail-tools { display: grid; gap: 10px; }
439
+ .rail-tools input { width: 100%; }
440
+ .chips { display: flex; flex-wrap: wrap; gap: 8px; }
441
+ .chip {
442
+ font-size: 12px;
443
+ padding: 3px 10px;
444
+ min-height: 26px;
445
+ border-radius: 999px;
446
+ border: 1px solid var(--line);
447
+ background: transparent;
448
+ color: var(--muted);
449
+ }
450
+ .chip[aria-pressed="true"] { background: var(--accent-soft); border-color: transparent; color: var(--accent); }
451
+ .rail-count { margin: 12px 0 8px; color: var(--muted); font-size: 12px; }
452
+
453
+ .list { display: grid; gap: 1px; border-top: 1px solid var(--line); }
454
+ /* 桌面端列表自己滚:条目多时不让整页跟着长,右栏也不会剩一大片空白。
455
+ 窄屏不做嵌套滚动——那比页面滚动难用。
456
+ 底部加一层淡出:滚动区硬切会把最后一行切成半截,看起来像坏了。 */
457
+ @media (min-width: 901px) {
458
+ .list {
459
+ max-height: min(58vh, 540px);
460
+ overflow-y: auto;
461
+ overscroll-behavior: contain;
462
+ padding-bottom: 4px;
463
+ mask-image: linear-gradient(to bottom, #000 calc(100% - 20px), transparent);
464
+ }
465
+ .list:has(> .row:last-child:first-child) { mask-image: none; }
466
+ }
467
+ .group-head {
468
+ display: flex;
469
+ align-items: baseline;
470
+ justify-content: space-between;
471
+ gap: 8px;
472
+ padding: 14px 2px 6px;
473
+ font-size: 12px;
474
+ color: var(--muted);
475
+ }
476
+ .group-head:first-child { padding-top: 8px; }
477
+ .group-head .n { font-variant-numeric: tabular-nums; }
478
+
479
+ .row {
480
+ display: grid;
481
+ grid-template-columns: 3px minmax(0, 1fr) auto;
482
+ gap: 10px;
483
+ align-items: center;
484
+ width: 100%;
485
+ text-align: left;
486
+ padding: 9px 10px 9px 0;
487
+ border: 0;
488
+ border-bottom: 1px solid var(--line);
489
+ border-radius: 0;
490
+ background: transparent;
491
+ }
492
+ .row:hover { background: color-mix(in oklab, var(--card) 78%, transparent); }
493
+ .row[aria-selected="true"] { background: var(--accent-soft); }
494
+ .row > span { min-width: 0; }
495
+ .row .spine { align-self: stretch; border-radius: 2px; background: var(--spine, var(--line)); }
496
+ .row .title {
497
+ display: block;
498
+ font-weight: 520;
499
+ overflow: hidden;
500
+ text-overflow: ellipsis;
501
+ white-space: nowrap;
502
+ }
503
+ .row .meta {
504
+ display: block;
505
+ color: var(--muted);
506
+ font-size: 12px;
507
+ overflow: hidden;
508
+ text-overflow: ellipsis;
509
+ white-space: nowrap;
510
+ }
511
+ .row .side {
512
+ text-align: right;
513
+ color: var(--muted);
514
+ font-size: 12px;
515
+ white-space: nowrap;
516
+ font-variant-numeric: tabular-nums;
517
+ }
518
+ /* 状态胶囊跟名字同行:放右侧会把行高撑到 70px,十条就多出一屏 */
519
+ .row .badge {
520
+ display: inline-block;
521
+ vertical-align: 1px;
522
+ font-size: 12px;
523
+ padding: 0 7px;
524
+ margin-left: 8px;
525
+ border-radius: 999px;
526
+ border: 1px solid currentColor;
527
+ }
528
+ .badge.reject { color: var(--danger); }
529
+ .badge.off { color: var(--muted); }
530
+ .badge.on { color: var(--ok); }
531
+
532
+ /* ---------- 右栏:组装 / 详情 ---------- */
533
+ .panel { min-width: 0; min-height: 320px; }
534
+
535
+ .panel h2 {
536
+ margin: 0 0 14px;
537
+ font-size: 15px;
538
+ font-weight: 580;
539
+ letter-spacing: .005em;
540
+ display: flex;
541
+ align-items: center;
542
+ gap: 12px;
543
+ flex-wrap: wrap;
544
+ }
545
+ .panel .h2-sub { color: var(--muted); font-size: 12px; font-weight: 400; }
546
+
547
+ /* 组装预览:把「会拼成什么」摊开成按顺序的积木,这是本页最有辨识度的一块 */
548
+ .stack-view { display: grid; border-radius: 12px; overflow: hidden; border: 1px solid var(--line); }
549
+ .stack-row {
550
+ display: grid;
551
+ grid-template-columns: max-content minmax(0, 1fr) max-content;
552
+ gap: 12px;
553
+ align-items: baseline;
554
+ padding: 11px 14px;
555
+ background: var(--card);
556
+ border-bottom: 1px solid var(--line);
557
+ }
558
+ .stack-row:last-child { border-bottom: 0; }
559
+ .stack-row .ord {
560
+ font-family: var(--mono);
561
+ font-size: 12px;
562
+ color: var(--muted);
563
+ font-variant-numeric: tabular-nums;
564
+ }
565
+ .stack-row .body { min-width: 0; }
566
+ .stack-row .name { font-weight: 520; display: block; }
567
+ .stack-row .desc {
568
+ display: block;
569
+ color: var(--muted);
570
+ font-size: 12px;
571
+ overflow: hidden;
572
+ text-overflow: ellipsis;
573
+ white-space: nowrap;
574
+ }
575
+ .stack-row .size { color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
576
+ .stack-row.is-persona { box-shadow: inset 3px 0 0 var(--kind-persona); }
577
+ .stack-row.is-skill { box-shadow: inset 3px 0 0 var(--kind-skill); }
578
+ .stack-row.is-host { box-shadow: inset 3px 0 0 var(--line); color: var(--muted); }
579
+ .stack-row.is-empty { color: var(--muted); }
580
+
581
+ .stack-foot {
582
+ display: flex;
583
+ justify-content: space-between;
584
+ gap: 12px;
585
+ margin-top: 10px;
586
+ color: var(--muted);
587
+ font-size: 12px;
588
+ font-variant-numeric: tabular-nums;
589
+ }
590
+
591
+ /* 一键启用:把九个专家的开关摊平,点一下即生效 */
592
+ .picker { margin-top: 28px; }
593
+ .picker h3 {
594
+ margin: 0 0 10px;
595
+ font-size: 13px;
596
+ font-weight: 560;
597
+ display: flex;
598
+ align-items: baseline;
599
+ gap: 10px;
600
+ flex-wrap: wrap;
601
+ }
602
+ .picks { display: flex; flex-wrap: wrap; gap: 8px; }
603
+ .pick {
604
+ font-size: 12.5px;
605
+ padding: 4px 12px;
606
+ min-height: 28px;
607
+ border-radius: 999px;
608
+ border: 1px solid var(--line);
609
+ background: transparent;
610
+ color: var(--muted);
611
+ }
612
+ .pick:hover:not(:disabled) { color: var(--ink); }
613
+ .pick.is-on {
614
+ background: color-mix(in oklab, var(--kind-skill) 14%, transparent);
615
+ border-color: color-mix(in oklab, var(--kind-skill) 45%, var(--line));
616
+ color: var(--ink);
617
+ }
618
+
619
+ /* 详情 */
620
+ .kind { font-size: 12px; padding: 2px 9px; border-radius: 999px; border: 1px solid currentColor; white-space: nowrap; }
621
+ .kind.persona { color: var(--kind-persona); }
622
+ .kind.skill { color: var(--kind-skill); }
623
+ .kind.material { color: var(--kind-material); }
624
+ .sub-note { color: var(--muted); font-size: 12.5px; margin: 6px 0 0; }
625
+
626
+ .facts { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 6px 16px; margin: 16px 0 0; font-size: 12.5px; }
627
+ .facts dt { color: var(--muted); }
628
+ .facts dd { margin: 0; overflow-wrap: anywhere; min-width: 0; }
629
+ .facts code { font-family: var(--mono); font-size: 12px; overflow-wrap: anywhere; }
630
+
631
+ .actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 16px 0 0; }
632
+ .warn { color: var(--danger); font-size: 12.5px; margin: 10px 0 0; }
633
+ .note { color: var(--muted); font-size: 12.5px; margin: 8px 0 0; }
634
+
635
+ .budget { margin: 16px 0 0; }
636
+ .budget .track { height: 4px; border-radius: 2px; background: var(--line); }
637
+ .budget .fill { height: 100%; min-width: 3px; border-radius: 2px; background: var(--accent); }
638
+ .budget .label { font-size: 12px; color: var(--muted); margin-top: 6px; }
639
+
640
+ pre.text {
641
+ margin: 14px 0 0;
642
+ padding: 12px 14px;
643
+ max-height: 280px;
644
+ overflow: auto;
645
+ font-family: var(--mono);
646
+ font-size: 12px;
647
+ line-height: 1.6;
648
+ background: var(--card);
649
+ border: 1px solid var(--line);
650
+ border-radius: 10px;
651
+ white-space: pre-wrap;
652
+ }
653
+
654
+ .empty {
655
+ color: var(--muted);
656
+ font-size: 12.5px;
657
+ padding: 16px 2px;
658
+ margin: 0;
659
+ }
660
+
661
+ /* ---------- 底部:四块可折叠,平时只占一行 ---------- */
662
+ .foot {
663
+ display: grid;
664
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
665
+ gap: 12px 24px;
666
+ margin-top: 30px;
667
+ padding-top: 16px;
668
+ border-top: 1px solid var(--line);
669
+ align-items: start;
670
+ }
671
+ .fold { min-width: 0; }
672
+ .fold > summary {
673
+ cursor: pointer;
674
+ color: var(--muted);
675
+ font-size: 12px;
676
+ padding: 6px 0;
677
+ min-height: 32px;
678
+ list-style: none;
679
+ display: flex;
680
+ align-items: center;
681
+ gap: 6px;
682
+ }
683
+ .fold > summary::-webkit-details-marker { display: none; }
684
+ .fold > summary::before {
685
+ content: "";
686
+ width: 0; height: 0;
687
+ border-left: 4px solid currentColor;
688
+ border-top: 3.5px solid transparent;
689
+ border-bottom: 3.5px solid transparent;
690
+ transition: transform .12s ease;
691
+ }
692
+ .fold[open] > summary { color: var(--ink); }
693
+ .fold[open] > summary::before { transform: rotate(90deg); }
694
+ .fold-count { color: var(--muted); font-variant-numeric: tabular-nums; }
695
+ .fold-body { display: grid; gap: 8px; padding: 6px 0 4px; }
696
+ .fold-body .inline-row { display: flex; gap: 8px; }
697
+ .fold-body .inline-row input { flex: 1; min-width: 0; }
698
+ .fold-body ul { margin: 0; padding-left: 16px; color: var(--muted); font-size: 12px; }
699
+ .fold-body li { margin-bottom: 5px; overflow-wrap: anywhere; }
700
+ .fold-body code { font-family: var(--mono); }
701
+ .stack { display: grid; gap: 6px; }
702
+
703
+ .status { margin: 16px 0 0; font-size: 12.5px; color: var(--muted); }
704
+ .status[data-tone="bad"] { color: var(--danger); }
705
+ .status[data-tone="good"] { color: var(--ok); }
706
+
707
+ /* 右栏不加「入场淡入」:这一栏每次点条目、每次改设置都整块重画,
708
+ 动画会跟着重放一遍,读起来像页面在闪。工作台的动效预算留给真正的状态变化(比如状态点变色)。 */
709
+
710
+ @media (max-width: 620px) {
711
+ body { padding: 16px 16px 32px; }
712
+ .top { grid-template-columns: minmax(0, 1fr); }
713
+ .top-controls { justify-content: flex-start; }
714
+ .plan { grid-template-columns: max-content minmax(0, 1fr); }
715
+ .plan .actions { grid-column: 1 / -1; justify-content: flex-start; }
716
+ .plan .why { grid-column: 1 / -1; }
717
+ }
718
+ /* ---- 预览控制条 ---- */
719
+ .pv-bar{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:8px 16px;border-bottom:1px solid var(--line);background:var(--card);font:12px/1.4 var(--magpie-font,system-ui);color:var(--ink)}
720
+ .pv-bar b{font-size:13px;font-weight:600}
721
+ .pv-hint{color:var(--muted);margin-right:auto}
722
+ .pv-bar label{display:flex;align-items:center;gap:6px;color:var(--muted)}
723
+ .pv-bar select{font:inherit;color:var(--ink);background:var(--bg);border:1px solid var(--line);border-radius:6px;padding:2px 6px}
724
+ </style>
725
+
726
+ </head>
727
+ <body>
728
+
729
+ <div class="pv-bar" role="region" aria-label="预览控制">
730
+ <b>破甲 · Purge</b>
731
+ <span class="pv-hint">单文件预览:数据是演示快照,不跑网关、不写设置</span>
732
+ <label>主题
733
+ <select id="pv-theme">
734
+ <option value="dark">深色</option>
735
+ <option value="light">浅色</option>
736
+ </select>
737
+ </label>
738
+ <label>状态
739
+ <select id="pv-snap">
740
+ <option value="ready">就绪</option>
741
+ <option value="blocked">未就绪</option>
742
+ </select>
743
+ </label>
744
+ </div>
745
+ <script>
746
+ ;(() => {
747
+ const q = new URLSearchParams(location.hash.slice(1) || location.search.slice(1))
748
+ const theme = document.getElementById('pv-theme')
749
+ const snap = document.getElementById('pv-snap')
750
+ theme.value = q.get('theme') === 'light' ? 'light' : 'dark'
751
+ snap.value = q.get('snap') === 'blocked' ? 'blocked' : 'ready'
752
+ const go = () => {
753
+ const next = new URLSearchParams()
754
+ next.set('theme', theme.value)
755
+ next.set('snap', snap.value)
756
+ location.hash = next.toString()
757
+ location.reload()
758
+ }
759
+ theme.onchange = go
760
+ snap.onchange = go
761
+
762
+ // #row=N 直接打开某条的详情,省得每次都手点
763
+ const row = q.get('row')
764
+ if (row !== null) {
765
+ addEventListener('load', () => setTimeout(() => {
766
+ document.querySelectorAll('#list .row')[Number(row)]?.click()
767
+ }, 120))
768
+ }
769
+ })()
770
+ </script>
771
+
772
+
773
+ <header class="top">
774
+ <div class="brand">
775
+ <img class="mark" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCIgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiByb2xlPSJpbWciIGFyaWEtbGFiZWw9IlB1cmdlIGluIE1hZ3BpZSI+CiAgPCEtLSDnqbrlv4Pnm77niYzvvJrkuI3pk7rlupXoibLlnZfvvIzlj6rnlZnova7lu5PjgIIKICAgICAgIOS+p+agj+WunumZheWPque7mSAxMuKAkzE2cHjvvIzmj4/ovrnmmK/ov5nph4zllK/kuIDnmoTlj6/osIPpobnvvJoKICAgICAgIHc2L3c4IOWcqCAxMnB4IOS4i+WwluinkuS4juebtOi+ueiiq+ejqOW5s+OAgeeci+edgOWDj+WchueOr++8m3cxMCDku6XkuIrlnKggNjRweCDkuIvnqbrlv4Plj4jnvKnmiJDkuIDlsI/lnZfjgIIKICAgICAgIHc5IOaYr+S4pOWktOmDveeri+W+l+S9j+eahOS4gOaho+OAguminOiJsiAjNGY1ZmUwIOWcqOa3seiJsuS4jua1heiJsuWuv+S4u+iDjOaZr+S4iumDveWOi+W+l+S9j++8jOS4pOS+p+WFseeUqOS4gOeJiOOAgiAtLT4KICA8cGF0aCBkPSJNMzIgMTAgTDUzIDE5IFYzNiBDNTMgNDUuNSA0My41IDUyLjUgMzIgNTQuNSBDMjAuNSA1Mi41IDExIDQ1LjUgMTEgMzYgVjE5IFoiCiAgICAgICAgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjNGY1ZmUwIiBzdHJva2Utd2lkdGg9IjkiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIvPgo8L3N2Zz4=" alt="" width="28" height="28">
776
+ <div class="brand-text">
777
+ <h1>破甲 <span class="brand-tail">Purge</span></h1>
778
+ <p class="tagline">本地 purge 目录 → 网关 system 改写</p>
779
+ </div>
780
+ </div>
781
+
782
+ <div class="top-controls">
783
+ <div class="controls-row">
784
+ <label class="field">
785
+ <span class="field-label" id="mode-label">改写模式</span>
786
+ <select id="mode" aria-labelledby="mode-label">
787
+ <option value="">跟随 agent-purge</option>
788
+ <option value="off">off · 不动请求</option>
789
+ <option value="strict">strict · 只留人设</option>
790
+ <option value="replace">replace · 人设 + 去掉自称</option>
791
+ <option value="append">append · 人设 + 原样保留</option>
792
+ </select>
793
+ </label>
794
+ <button id="refresh" type="button" class="quiet">重新扫描</button>
795
+ </div>
796
+ <p class="top-hint" id="mode-help"></p>
797
+ </div>
798
+ </header>
799
+
800
+ <section class="plan" id="plan" aria-label="当前注入状态" aria-live="polite"></section>
801
+
802
+ <div class="work">
803
+ <section class="rail" aria-label="条目列表">
804
+ <div class="rail-tools">
805
+ <input id="q" type="search" placeholder="搜名字、来源或类型" aria-label="搜索条目" autocomplete="off">
806
+ <div id="filters" class="chips" role="group" aria-label="按类型筛选"></div>
807
+ </div>
808
+ <p class="rail-count" id="count">正在读快照…</p>
809
+ <div id="list" class="list" role="listbox" aria-label="条目"></div>
810
+ </section>
811
+
812
+ <section class="panel" id="panel" aria-label="注入组装与条目详情" aria-live="polite">
813
+ <div id="assembly"></div>
814
+ <div id="inspect"></div>
815
+ </section>
816
+ </div>
817
+
818
+ <footer class="foot">
819
+ <details class="fold">
820
+ <summary>导入与来源</summary>
821
+ <div class="fold-body">
822
+ <label class="field">
823
+ <span class="field-label">文件路径</span>
824
+ <div class="inline-row">
825
+ <input id="import-path" type="text" placeholder="人设、技能、ZIP 导出包" aria-label="要导入的文件路径" spellcheck="false">
826
+ <button id="import-run" type="button">导入</button>
827
+ </div>
828
+ </label>
829
+ <p class="note">只认 <code>.md</code> <code>.markdown</code> <code>.txt</code> <code>.json</code> <code>.zip</code>;复制进插件的 <code>state/imports</code> 后再清点,原文件不动。</p>
830
+
831
+ <label class="field">
832
+ <span class="field-label">从本机选文件</span>
833
+ <input id="import-file" type="file" accept=".md,.markdown,.txt" aria-label="从本机选一个人设或技能文件">
834
+ </label>
835
+ <p class="note">选文件时正文直接存进插件的 options(<code>inline</code>),不复制、不落盘。</p>
836
+
837
+ <label class="field">
838
+ <span class="field-label">来源目录(一行一个)</span>
839
+ <textarea id="sources" rows="3" spellcheck="false" aria-label="来源目录,一行一个" placeholder="D:\purge&#10;~/.agent-purge"></textarea>
840
+ </label>
841
+ <button id="sources-save" type="button">保存来源并重扫</button>
842
+ </div>
843
+ </details>
844
+
845
+ <details class="fold">
846
+ <summary>校验记录 <span class="fold-count" id="rejects-count"></span></summary>
847
+ <div class="fold-body"><ul id="rejects"></ul></div>
848
+ </details>
849
+
850
+ <details class="fold">
851
+ <summary>最近一次生效</summary>
852
+ <div class="fold-body"><div id="last" class="stack"></div></div>
853
+ </details>
854
+
855
+ <details class="fold">
856
+ <summary>边界</summary>
857
+ <div class="fold-body">
858
+ <p class="note">只处理经过 magpie 网关的 agent 请求;客户端自己写死的行为、不经过网关的流量改不到。</p>
859
+ <p class="note"><code>strict</code> 会连原 system 里的工具说明文本一起换掉——结构化工具定义不在网关这一层。</p>
860
+ <p class="note">页面不读磁盘:条目由插件后端扫描后写成快照,页面只显示它。</p>
861
+ </div>
862
+ </details>
863
+ </footer>
864
+
865
+ <p id="status" class="status" role="status" aria-live="polite" hidden></p>
866
+
867
+ <script>
868
+ // 破甲 · Purge 的页面逻辑。
869
+ //
870
+ // 页面在 magpie 的沙箱帧里:不能 fetch、读不到磁盘,只有三样东西可用——
871
+ // 1. window.PURGE_CATALOG:后端扫描后写下的快照(page/catalog.js);
872
+ // 2. magpie.options.get/set:这个插件在 plugins.json 里的设置;
873
+ // 3. magpie.ready / onVisibility:主题与可见性。
874
+ // 所以页面只做「显示 + 改设置」,真正的清点与改写都在 hooks.js 那一侧。
875
+ ;(() => {
876
+ 'use strict'
877
+
878
+ const bridge = window.magpie
879
+ const $ = (id) => document.getElementById(id)
880
+ const KINDS = {
881
+ 'session-archive': { label: '会话导出包', cls: 'material' },
882
+ 'cordis-plugin': { label: 'DSH 插件包', cls: 'material' },
883
+ persona: { label: '人设', cls: 'persona' },
884
+ skill: { label: '技能', cls: 'skill' },
885
+ manifest: { label: '清单', cls: 'material' },
886
+ text: { label: '文本', cls: 'skill' },
887
+ }
888
+ /** 三类语义色:人设 / 技能 / 素材。六种类型各给一色会变成彩虹,信息量却没增加。 */
889
+ const kindClass = (kind) => KINDS[kind]?.cls || 'material'
890
+ /** builtinFolder 从内置条目的 root 里取出它所在的目录名(skills / personas)。 */
891
+ const builtinFolder = (e) => String(e.source?.root || '').split(/[\\/]/).filter(Boolean).pop() || 'skills'
892
+ const MODE_HELP = {
893
+ off: '请求原样放行,什么也不改。',
894
+ strict: '整段可控 system 换成人设;原 system 里的工具说明文本也会一起没了。',
895
+ replace: '人设放最前,宿主 system 里「自称 + 点名模型/厂商」的行删掉。',
896
+ append: '人设放最前,宿主 system 原样保留。',
897
+ }
898
+ /** NOT_INJECTABLE 说清「这条为什么不会进 system」,并指出下一步:导入的是素材,不是人设。 */
899
+ const NOT_INJECTABLE =
900
+ '素材条目:可查、可归档,不会写进 system。要注入请导入人设或技能(.md / .markdown / .txt),' +
901
+ '或在下方「从本机选文件」里挑一个 md。'
902
+
903
+ let options = {}
904
+ let catalog = window.PURGE_CATALOG ?? null
905
+ let selected = ''
906
+ let filter = ''
907
+ let query = ''
908
+ let saveTimer = 0
909
+ let pendingSave = null
910
+ let busy = false
911
+
912
+ // ---------- 小工具 ----------
913
+
914
+ const fmtSize = (n) => (n >= 1048576 ? `${(n / 1048576).toFixed(1)} MiB` : `${Math.max(1, Math.round(n / 1024))} KiB`)
915
+ const fmtTime = (ms) => (ms ? new Date(ms).toLocaleString('zh-CN', { hour12: false }) : '—')
916
+ const short = (digest) => (digest ? String(digest).slice(0, 12) : '—')
917
+
918
+ function say(text, tone = '') {
919
+ const el = $('status')
920
+ el.textContent = text
921
+ el.dataset.tone = tone
922
+ el.hidden = !text
923
+ if (!text) return
924
+ clearTimeout(say.timer)
925
+ say.timer = setTimeout(() => { el.hidden = true }, 6000)
926
+ }
927
+
928
+ function el(tag, attrs = {}, ...kids) {
929
+ const node = document.createElement(tag)
930
+ for (const [k, v] of Object.entries(attrs)) {
931
+ if (v === null || v === undefined || v === false) continue
932
+ if (k === 'class') node.className = v
933
+ else if (k === 'text') node.textContent = v
934
+ else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v)
935
+ else node.setAttribute(k, v === true ? '' : String(v))
936
+ }
937
+ for (const kid of kids.flat()) {
938
+ if (kid === null || kid === undefined || kid === false) continue
939
+ node.append(kid instanceof Node ? kid : document.createTextNode(String(kid)))
940
+ }
941
+ return node
942
+ }
943
+
944
+ const entries = () => (Array.isArray(catalog?.entries) ? catalog.entries : [])
945
+ const inlineEntries = () => (Array.isArray(options.inline) ? options.inline : [])
946
+ const findEntry = (id) => entries().find((e) => e.id === id) || inlineEntries().find((e) => e.id === id) || null
947
+ const isEnabled = (id) => (options.enabled?.[id] !== undefined ? options.enabled[id] : findEntry(id)?.kind === 'persona')
948
+
949
+ // ---------- 与宿主说话 ----------
950
+
951
+ /** save 把整份 options 写回magpie;options.set 每秒只收一次,这里攒 1.1 秒再发。 */
952
+ function save(patch, note) {
953
+ options = { ...options, ...patch }
954
+ if (pendingSave) Object.assign(pendingSave, patch)
955
+ else pendingSave = { ...patch }
956
+ clearTimeout(saveTimer)
957
+ saveTimer = setTimeout(flush, 1100)
958
+ if (note) say(note)
959
+ render()
960
+ }
961
+
962
+ async function flush() {
963
+ if (!pendingSave || !bridge?.options?.set) return
964
+ const body = { ...options }
965
+ pendingSave = null
966
+ try {
967
+ const saved = await bridge.options.set(body)
968
+ if (saved && typeof saved === 'object') options = { ...body, ...saved }
969
+ } catch (error) {
970
+ say(`保存失败:${error?.message || error}`, 'bad')
971
+ }
972
+ }
973
+
974
+ // ---------- 渲染 ----------
975
+
976
+ function renderFilters() {
977
+ const host = $('filters')
978
+ const kinds = [...new Set(entries().map((e) => e.kind))]
979
+ host.replaceChildren(
980
+ el('button', { type: 'button', class: 'chip', 'aria-pressed': filter === '', onclick: () => { filter = ''; render() } }, `全部 ${entries().length}`),
981
+ ...kinds.map((kind) => {
982
+ const n = entries().filter((e) => e.kind === kind).length
983
+ return el('button', {
984
+ type: 'button',
985
+ class: 'chip',
986
+ 'aria-pressed': filter === kind,
987
+ onclick: () => { filter = filter === kind ? '' : kind; render() },
988
+ }, `${KINDS[kind]?.label || kind} ${n}`)
989
+ }),
990
+ )
991
+ }
992
+
993
+ function visible() {
994
+ const q = query.trim().toLowerCase()
995
+ return entries()
996
+ .filter((e) => (filter ? e.kind === filter : true))
997
+ .filter((e) => (q ? `${e.name} ${e.id} ${e.source?.rel ?? ''} ${KINDS[e.kind]?.label ?? ''}`.toLowerCase().includes(q) : true))
998
+ .concat(
999
+ inlineEntries()
1000
+ .filter((e) => (filter ? e.kind === filter : true))
1001
+ .filter((e) => (q ? `${e.name} ${e.id}`.toLowerCase().includes(q) : true))
1002
+ .map((e) => ({
1003
+ ...e,
1004
+ status: 'ok',
1005
+ source: { rel: '页面导入(options)', root: 'inline' },
1006
+ size: 0,
1007
+ meta: { format: 'inline', description: '' },
1008
+ version: 1,
1009
+ chars: String(e.text || '').length,
1010
+ injectable: true,
1011
+ digest: '',
1012
+ })),
1013
+ )
1014
+ }
1015
+
1016
+ function renderList() {
1017
+ const host = $('list')
1018
+ const rows = visible()
1019
+ if (!catalog) {
1020
+ host.replaceChildren(el('p', { class: 'empty', text: '还没有快照:后端没跑过扫描。点右上角「重新扫描」。' }))
1021
+ return
1022
+ }
1023
+ if (!rows.length) {
1024
+ host.replaceChildren(el('p', { class: 'empty', text: '没有匹配的条目。清掉搜索,或往来源目录里放点东西再扫一次。' }))
1025
+ return
1026
+ }
1027
+ // 分组比逐行挂「内置」胶囊干净:内置是「这一整组都随包来」,说一次就够。
1028
+ const groups = [
1029
+ { key: 'builtin', label: '内置专家与技能', rows: rows.filter((e) => e.builtin) },
1030
+ { key: 'mine', label: '我的来源', rows: rows.filter((e) => !e.builtin) },
1031
+ ].filter((g) => g.rows.length)
1032
+
1033
+ const nodes = []
1034
+ for (const group of groups) {
1035
+ nodes.push(el('div', { class: 'group-head' },
1036
+ el('span', { text: group.label }),
1037
+ el('span', { class: 'n', text: String(group.rows.length) }),
1038
+ ))
1039
+ for (const e of group.rows) nodes.push(rowOf(e))
1040
+ }
1041
+ host.replaceChildren(...nodes)
1042
+ }
1043
+
1044
+ /** rowOf 画一行条目;状态只用「未启用 / 已启用 / 拒绝」三种胶囊,不再叠「内置」。 */
1045
+ function rowOf(e) {
1046
+ const kind = KINDS[e.kind] || { label: e.kind }
1047
+ const badge = e.status === 'rejected'
1048
+ ? el('span', { class: 'badge reject', text: '拒绝' })
1049
+ : !e.injectable ? null
1050
+ : isEnabled(e.id) ? null : el('span', { class: 'badge off', text: '未启用' })
1051
+ return el('button', {
1052
+ type: 'button',
1053
+ class: 'row',
1054
+ role: 'option',
1055
+ 'aria-selected': selected === e.id,
1056
+ onclick: () => { selected = selected === e.id ? '' : e.id; render() },
1057
+ },
1058
+ el('span', { class: 'spine', style: `--spine:var(--kind-${kindClass(e.kind)})` }),
1059
+ el('span', {},
1060
+ el('span', { class: 'title' }, e.name, badge || null),
1061
+ el('span', { class: 'meta', text: `${kind.label} · ${e.builtin ? '随插件' : e.source?.rel ?? ''}` }),
1062
+ ),
1063
+ el('span', { class: 'side' }, e.version > 1 ? `v${e.version} ` : '',
1064
+ el('span', { class: 'meta', text: e.injectable ? `${e.chars || 0} 字` : fmtSize(e.size || 0) })),
1065
+ )
1066
+ }
1067
+
1068
+ /**
1069
+ * renderAssembly 是右栏默认内容:把「这次会拼成什么」按顺序摊开。
1070
+ *
1071
+ * 为什么值得占这一整栏:这个插件的产物就是一段被拼起来的 system 文本,
1072
+ * 但它平时在请求里,用户看不见。摊开成积木(人设 → 技能 → 宿主原文),
1073
+ * 一眼能看出顺序对不对、谁没启用、总量吃不吃得下预算。
1074
+ */
1075
+ function renderAssembly() {
1076
+ const host = $('assembly')
1077
+ const plan = catalog?.plan
1078
+ const last = catalog?.last
1079
+ if (!plan) {
1080
+ host.replaceChildren(el('h2', {}, '注入组装'))
1081
+ host.append(el('p', { class: 'empty', text: '还没有判定:等后端第一次扫描。' }))
1082
+ return
1083
+ }
1084
+ const personaEntry = findEntry(plan.personaId)
1085
+ const skills = (plan.skills || []).map((s) => findEntry(s.id) || s)
1086
+ const total = (personaEntry?.chars || 0) + skills.reduce((n, s) => n + (s.chars || 0), 0)
1087
+
1088
+ const rows = []
1089
+ if (plan.ready && personaEntry) {
1090
+ rows.push(stackRow('01', 'persona', personaEntry.name, personaEntry.meta?.description || '人设正文', `${personaEntry.chars || 0} 字`))
1091
+ skills.forEach((s, i) => rows.push(stackRow(String(i + 2).padStart(2, '0'), 'skill', s.name, s.meta?.description || '技能正文', `${s.chars || 0} 字`)))
1092
+ rows.push(el('div', { class: 'stack-row is-host' },
1093
+ el('span', { class: 'ord', text: String(skills.length + 2).padStart(2, '0') }),
1094
+ el('span', { class: 'body' },
1095
+ el('span', { class: 'name', text: '宿主自己的 system' }),
1096
+ el('span', { class: 'desc', text: plan.mode === 'strict' ? 'strict:整段换掉,不会保留' : '原样保留,接在上面这些之后' }),
1097
+ ),
1098
+ el('span', { class: 'size', text: plan.mode === 'strict' ? '—' : '保留' }),
1099
+ ))
1100
+ } else {
1101
+ rows.push(el('div', { class: 'stack-row is-empty' },
1102
+ el('span', { class: 'ord', text: '—' }),
1103
+ el('span', { class: 'body' },
1104
+ el('span', { class: 'name', text: '还没有可组装的内容' }),
1105
+ // 具体原因在顶部状态条里已经说过一遍,这里只说「这里将来会显示什么」,不重复。
1106
+ el('span', { class: 'desc', text: '按上面的提示处理后,这段会显示人设与技能的拼装顺序' }),
1107
+ ),
1108
+ el('span', { class: 'size', text: '' }),
1109
+ ))
1110
+ }
1111
+
1112
+ host.replaceChildren(...[
1113
+ el('h2', {}, '注入组装',
1114
+ el('span', { class: 'h2-sub', text: plan.ready ? '下一次请求会拼成这段' : '这次放行,下面是原因' })),
1115
+ el('div', { class: 'stack-view' }, ...rows),
1116
+ el('div', { class: 'stack-foot' },
1117
+ el('span', { text: plan.ready ? `合计 ${total.toLocaleString('zh-CN')} 字符 · 预算 65,536` : `模式 ${plan.mode}` }),
1118
+ last?.at ? el('span', { text: last.skipped ? `上次 ${fmtTime(last.at)} · 未注入` : `上次 ${fmtTime(last.at)} · ${last.agent || '—'}` }) : null,
1119
+ ),
1120
+ renderExpertPicker(),
1121
+ ].filter(Boolean))
1122
+ }
1123
+
1124
+ /**
1125
+ * renderExpertPicker 是「一键启用专家」:这里是每天重复最多的动作。
1126
+ * 不用逐条点开再点启用——九个专家的开关摊在同一行,点一下就切。
1127
+ * 只列技能:人设是「谁来写」,走另一条路(详情里的「设为当前人设」)。
1128
+ */
1129
+ function renderExpertPicker() {
1130
+ const skills = entries().filter((e) => e.injectable && e.kind === 'skill' && e.builtin)
1131
+ const mine = entries().filter((e) => e.injectable && e.kind === 'skill' && !e.builtin)
1132
+ const all = [...skills, ...mine]
1133
+ if (!all.length) return null
1134
+ const chip = (e) => {
1135
+ const on = isEnabled(e.id)
1136
+ return el('button', {
1137
+ type: 'button',
1138
+ class: `pick${on ? ' is-on' : ''}`,
1139
+ 'aria-pressed': on ? 'true' : 'false',
1140
+ title: on ? `停用「${e.name}」` : `启用「${e.name}」`,
1141
+ onclick: () => save({ enabled: { ...(options.enabled || {}), [e.id]: !on } }, on ? `已停用「${e.name}」` : `已启用「${e.name}」`),
1142
+ }, on ? '✓ ' : '', e.name)
1143
+ }
1144
+ return el('section', { class: 'picker', 'aria-label': '启用专家' },
1145
+ el('h3', {}, '启用的专家',
1146
+ el('span', { class: 'h2-sub', text: '点一下即生效,不必逐条打开' })),
1147
+ el('div', { class: 'picks' }, ...all.map(chip)),
1148
+ )
1149
+ }
1150
+
1151
+ /** stackRow 是组装里的一层:序号 + 名字 + 一句描述 + 体积。 */
1152
+ function stackRow(ord, cls, name, desc, size) {
1153
+ return el('div', { class: `stack-row is-${cls}` },
1154
+ el('span', { class: 'ord', text: ord }),
1155
+ el('span', { class: 'body' },
1156
+ el('span', { class: 'name', text: name }),
1157
+ el('span', { class: 'desc', text: desc }),
1158
+ ),
1159
+ el('span', { class: 'size', text: size }),
1160
+ )
1161
+ }
1162
+
1163
+ function renderInspector() {
1164
+ const host = $('inspect')
1165
+ const e = findEntry(selected)
1166
+ if (!e) {
1167
+ // 没选中时让位给「组装预览」:右栏不留一片空白,那是最浪费的一屏。
1168
+ host.replaceChildren()
1169
+ return
1170
+ }
1171
+ const kind = KINDS[e.kind] || { label: e.kind }
1172
+ const kindCls = kindClass(e.kind)
1173
+ const inline = e.source?.root === 'inline' || e.meta?.format === 'inline'
1174
+ // 只有复制进插件自己的 state/imports 的副本才谈得上「删副本」:来源目录里的原件不动。
1175
+ const imported = Boolean(e.source?.root && /[\\/]state[\\/]imports\/?$/.test(e.source.root))
1176
+ const enabled = isEnabled(e.id)
1177
+ const pinned = options.pinned?.[e.id]
1178
+ const history = Array.isArray(e.history) ? e.history : []
1179
+ const text = inline ? String(e.text || '') : ''
1180
+
1181
+ const actions = []
1182
+ // 人设才有「设为当前人设」;技能是「启用/停用」。混着写会让人以为技能能当人设用。
1183
+ if (e.injectable && e.kind === 'persona') {
1184
+ actions.push(el('button', {
1185
+ type: 'button',
1186
+ class: options.persona === e.id ? 'primary' : '',
1187
+ onclick: () => save({ persona: e.id }, `已把「${e.name}」设为当前人设`),
1188
+ }, options.persona === e.id ? '当前人设' : '设为当前人设'))
1189
+ }
1190
+ if (e.injectable) {
1191
+ actions.push(el('button', {
1192
+ type: 'button',
1193
+ onclick: () => save({ enabled: { ...(options.enabled || {}), [e.id]: !enabled } }, enabled ? `已停用「${e.name}」` : `已启用「${e.name}」`),
1194
+ }, enabled ? '停用' : '启用'))
1195
+ }
1196
+ if (pinned) {
1197
+ actions.push(el('button', {
1198
+ type: 'button',
1199
+ class: 'quiet',
1200
+ onclick: () => {
1201
+ const next = { ...(options.pinned || {}) }
1202
+ delete next[e.id]
1203
+ save({ pinned: next }, '已回到最新版本')
1204
+ },
1205
+ }, '取消版本固定'))
1206
+ }
1207
+ if (inline) {
1208
+ actions.push(el('button', {
1209
+ type: 'button',
1210
+ class: 'danger',
1211
+ onclick: () => {
1212
+ const kept = inlineEntries().filter((x) => x.id !== e.id)
1213
+ const enabledNext = { ...(options.enabled || {}) }
1214
+ delete enabledNext[e.id]
1215
+ save({ inline: kept, enabled: enabledNext, persona: options.persona === e.id ? '' : options.persona }, '已从页面导入里删掉')
1216
+ if (selected === e.id) selected = ''
1217
+ },
1218
+ }, '删除'))
1219
+ } else if (imported) {
1220
+ actions.push(el('button', {
1221
+ type: 'button',
1222
+ class: 'danger',
1223
+ onclick: () => importRequest({ op: 'delete', path: e.source.rel }, `已请求删除「${e.name}」的副本(只删插件自己的 state/imports)`),
1224
+ }, '删除副本'))
1225
+ }
1226
+
1227
+ const versionPicker = history.length
1228
+ ? el('label', { class: 'note' },
1229
+ '回滚到:',
1230
+ el('select', {
1231
+ onchange: (ev) => {
1232
+ const digest = ev.target.value
1233
+ const next = { ...(options.pinned || {}) }
1234
+ if (digest) next[e.id] = digest
1235
+ else delete next[e.id]
1236
+ save({ pinned: next }, digest ? '已固定到旧版本' : '已回到最新版本')
1237
+ },
1238
+ },
1239
+ el('option', { value: '', selected: !pinned }, `最新 v${e.version ?? 1}`),
1240
+ ...history.map((h) => el('option', { value: h.digest, selected: pinned === h.digest }, `v${h.version ?? '?'} · ${fmtTime(h.at)}`)),
1241
+ ),
1242
+ )
1243
+ : null
1244
+
1245
+ // replaceChildren 会把 null 变成 "null" 字符串,所以先过滤。
1246
+ host.replaceChildren(...[
1247
+ el('div', {},
1248
+ el('h2', {}, e.name, el('span', { class: `kind ${kindCls}` }, kind.label)),
1249
+ el('p', { class: 'sub-note', text: e.meta?.description || (e.injectable ? '可写进 system 段的人设/技能文本。' : NOT_INJECTABLE) }),
1250
+ ),
1251
+ // 内置专家:说清它是随包来的,不是用户导入的,所以没有「删除」只有「停用」。
1252
+ // 「何时用」与「提炼自」分两行:一行里塞两件事读起来像免责声明。
1253
+ e.builtin && e.meta?.whenToUse
1254
+ ? el('p', { class: 'sub-note', text: `何时用:${e.meta.whenToUse}` })
1255
+ : null,
1256
+ e.builtin && e.meta?.source
1257
+ ? el('p', { class: 'sub-note', text: `提炼自 ${e.meta.source}` })
1258
+ : null,
1259
+ el('dl', { class: 'facts' },
1260
+ el('dt', { text: '来源' }), el('dd', { text: e.source?.root === 'inline' ? '页面导入(存在 options 里)' : e.builtin ? `插件内置 ${builtinFolder(e)}/` : e.source?.root || '—' }),
1261
+ el('dt', { text: '路径' }), el('dd', {}, el('code', { text: e.source?.rel || '—' })),
1262
+ el('dt', { text: '大小' }), el('dd', { text: e.injectable ? `${e.chars || 0} 字符(上限 64 KB)` : fmtSize(e.size || 0) }),
1263
+ el('dt', { text: '摘要' }), el('dd', {}, el('code', { text: short(e.digest) })),
1264
+ el('dt', { text: '版本' }), el('dd', { text: `v${e.version ?? 1}${history.length ? ` · 保留 ${history.length} 个旧版` : ''}` }),
1265
+ el('dt', { text: '导入于' }), el('dd', { text: e.builtin ? '随插件' : fmtTime(e.importedAt) }),
1266
+ e.meta?.sessions !== undefined ? el('dt', { text: '会话数' }) : null,
1267
+ e.meta?.sessions !== undefined ? el('dd', { text: String(e.meta.sessions) }) : null,
1268
+ e.meta?.turns !== undefined ? el('dt', { text: '选定轮次' }) : null,
1269
+ e.meta?.turns !== undefined ? el('dd', { text: String(e.meta.turns) }) : null,
1270
+ ),
1271
+ e.injectable
1272
+ ? el('div', { class: 'budget' },
1273
+ el('div', { class: 'track' }, el('div', { class: 'fill', style: `width:${Math.min(100, Math.round((e.chars || 0) / 65536 * 100))}%` })),
1274
+ el('div', { class: 'label', text: `${(e.chars || 0).toLocaleString('zh-CN')} / 65,536 字符会进入 system` }),
1275
+ )
1276
+ : null,
1277
+ el('div', { class: 'actions' }, ...actions),
1278
+ versionPicker,
1279
+ pinned ? el('p', { class: 'note', text: `当前固定到 ${short(pinned)}:网关用那一版的正文,不是最新的。` }) : null,
1280
+ inline && text ? el('pre', { class: 'text', text: text.slice(0, 3200) + (text.length > 3200 ? '\n…' : '') }) : null,
1281
+ ].filter(Boolean))
1282
+ }
1283
+
1284
+ function renderRejects() {
1285
+ const host = $('rejects')
1286
+ const rows = Array.isArray(catalog?.rejected) ? catalog.rejected : []
1287
+ const badge = $('rejects-count')
1288
+ if (badge) badge.textContent = rows.length ? `${rows.length}` : ''
1289
+ if (!rows.length) {
1290
+ const n = entries().length
1291
+ host.replaceChildren(el('li', {
1292
+ text: n
1293
+ ? '没有拒绝项:来源目录里每个文件都认得出来。'
1294
+ : '还没有扫描结果。先确认来源目录里放了东西,再点右上角「重新扫描」。',
1295
+ }))
1296
+ return
1297
+ }
1298
+ host.replaceChildren(...rows.slice(0, 24).map((r) => el('li', {}, el('strong', { text: r.name }), `:${r.reason}`)))
1299
+ }
1300
+
1301
+ function renderLast() {
1302
+ const host = $('last')
1303
+ const last = catalog?.last
1304
+ if (!last) {
1305
+ host.replaceChildren(el('p', { class: 'note', text: '还没有请求经过网关。改完模式后,下一次 agent 请求会写下这一行。' }))
1306
+ return
1307
+ }
1308
+ if (last.skipped) {
1309
+ // 放行了也要说清为什么:只显示「没注入」等于什么也没说
1310
+ host.replaceChildren(
1311
+ el('p', { class: 'note', text: `${fmtTime(last.at)} · ${last.agent || '未知 agent'} · ${last.protocol || '—'}` }),
1312
+ el('p', { class: 'warn', text: `这次没有注入:${last.skipped}` }),
1313
+ )
1314
+ return
1315
+ }
1316
+ host.replaceChildren(
1317
+ el('p', { class: 'note', text: `${fmtTime(last.at)} · ${last.agent || '未知 agent'} · ${last.protocol} · ${last.mode}` }),
1318
+ el('p', { class: 'note', text: `人设 ${last.persona || '(无)'} · 技能 ${(last.skills || []).length} 条 · 注入 ${last.chars} 字符` }),
1319
+ ...(last.missingPin?.length ? [el('p', { class: 'warn', text: `固定的版本不在当前表里:${last.missingPin.join('、')}` })] : []),
1320
+ )
1321
+ }
1322
+
1323
+ function render() {
1324
+ if (!catalog) {
1325
+ $('count').textContent = '没有快照'
1326
+ } else {
1327
+ const shown = visible().length
1328
+ $('count').textContent = `${shown} / ${entries().length + inlineEntries().length} 条 · 快照 v${catalog.version} · ${fmtTime(catalog.generatedAt)}`
1329
+ }
1330
+ $('mode').value = MODES().includes(options.mode) ? options.mode : ''
1331
+ $('mode-help').textContent = modeHelp($('mode').value)
1332
+ renderPlan()
1333
+ renderFilters()
1334
+ renderList()
1335
+ // 选着条目就看详情,没选就回组装预览:右栏永远有东西,不留空屏。
1336
+ renderAssembly()
1337
+ renderInspector()
1338
+ const picked = Boolean(findEntry(selected))
1339
+ $('assembly').hidden = picked
1340
+ $('inspect').hidden = !picked
1341
+ renderRejects()
1342
+ renderLast()
1343
+ renderSources()
1344
+ }
1345
+
1346
+ /** MODES 是模式下拉的全部取值:空串 = 跟随 agent-purge。 */
1347
+ const MODES = () => ['', 'off', 'strict', 'replace', 'append']
1348
+
1349
+ /** modeHelp 说清当前值到底意味着什么,尤其是「跟随 agent-purge」时用的是它的什么值。 */
1350
+ function modeHelp(value) {
1351
+ if (value) return MODE_HELP[value] || ''
1352
+ const p = catalog?.purge
1353
+ if (!p?.bound) return '没装 agent-purge 或读不到它的 state.json:等价于 off,不会改请求。'
1354
+ if (p.error) return `agent-purge 的 state.json 有问题:${p.error};等价于 off。`
1355
+ return `跟随 agent-purge:当前 ${p.mode || '未设置'}${p.persona ? ` · 人设 ${p.persona}` : ''}`
1356
+ }
1357
+
1358
+ /**
1359
+ * renderPlan 是「现在到底注不注、注谁、为什么没注」那一行。
1360
+ * 判定由后端算好放在快照的 plan 里(页面不能读 agent-purge 的 state.json)。
1361
+ */
1362
+ function renderPlan() {
1363
+ const host = $('plan')
1364
+ const plan = catalog?.plan
1365
+ if (!plan) {
1366
+ host.dataset.state = 'idle'
1367
+ host.replaceChildren(
1368
+ el('span', { class: 'dot' }),
1369
+ el('span', { class: 'empty', text: '还没有判定:等后端第一次扫描' }),
1370
+ )
1371
+ return
1372
+ }
1373
+ const ready = Boolean(plan.ready)
1374
+ const fromText = { page: '本页设置', 'agent-purge': 'agent-purge', auto: '自动(第一个启用的人设)', default: '默认' }
1375
+ host.dataset.state = ready ? 'ready' : 'blocked'
1376
+
1377
+ // 没就绪时给一个能点的下一步:光说「不会注入」等于把问题丢回给人。
1378
+ // 每个按钮都顺带 refreshAt:宿主重建插件进程后按新设置重扫,plan 才会跟着变。
1379
+ const fix = []
1380
+ const fixed = (patch, note) => {
1381
+ save({ ...patch, refreshAt: Date.now() }, note)
1382
+ pollSnapshot('等后端按新设置重扫…', 25)
1383
+ }
1384
+ if (!ready) {
1385
+ if (plan.blockedCode === 'no-mode' || plan.blockedCode === 'mode-off') {
1386
+ fix.push(el('button', { type: 'button', class: 'primary', onclick: () => fixed({ mode: 'replace' }, '模式改为 replace') }, '用 replace 开始注入'))
1387
+ }
1388
+ if (plan.blockedCode === 'no-persona' || plan.blockedCode === 'persona-missing') {
1389
+ fix.push(el('button', {
1390
+ type: 'button',
1391
+ class: 'primary',
1392
+ onclick: () => { filter = 'persona'; query = ''; render() },
1393
+ }, '去看人设'))
1394
+ }
1395
+ if (plan.blockedCode === 'no-persona-file') {
1396
+ fix.push(el('button', {
1397
+ type: 'button',
1398
+ class: 'primary',
1399
+ onclick: () => { $('import-file')?.focus(); $('import-file')?.click?.() },
1400
+ }, '导入一份人设'))
1401
+ }
1402
+ }
1403
+
1404
+ const rows = [
1405
+ el('span', { class: 'dot' }),
1406
+ el('span', { class: ready ? 'who' : 'who is-empty' }, ready
1407
+ ? `下一次 agent 请求会注入「${plan.personaName || plan.personaId}」`
1408
+ : '现在不会注入:请求原样放行'),
1409
+ el('span', { class: 'actions' },
1410
+ el('span', { class: 'tag', text: `模式 ${plan.mode} · ${fromText[plan.modeFrom] || plan.modeFrom || '默认'}` }),
1411
+ ready && plan.skills?.length ? el('span', { class: 'tag', text: `技能 ${plan.skills.length} 条` }) : null,
1412
+ ...fix,
1413
+ el('button', { type: 'button', class: 'quiet', onclick: () => refresh() }, '重扫确认'),
1414
+ ),
1415
+ el('span', { class: 'why', text: ready
1416
+ ? `人设来源:${fromText[plan.personaFrom] || plan.personaFrom}${catalog?.purge?.bound ? ';agent-purge 的 state.json 已读到' : ';没读到 agent-purge 的 state.json'}`
1417
+ : `${plan.blocked}${catalog?.purge?.bound ? '' : '(没读到 agent-purge 的 state.json)'}` }),
1418
+ ]
1419
+ host.replaceChildren(...rows.filter(Boolean))
1420
+ }
1421
+
1422
+ function renderSources() {
1423
+ const el2 = $('sources')
1424
+ if (!el2 || document.activeElement === el2) return
1425
+ const list = Array.isArray(options.sources) && options.sources.length
1426
+ ? options.sources
1427
+ : (catalog?.sources || []).filter((s) => s.path && !/[\\/]state[\\/]imports\/?$/.test(s.path)).map((s) => s.path)
1428
+ el2.value = list.join('\n')
1429
+ }
1430
+
1431
+ // ---------- 动作 ----------
1432
+
1433
+ function importRequest(req, note) {
1434
+ const imports = Array.isArray(options.imports) ? options.imports.slice(-19) : []
1435
+ imports.push({ ...req, at: Date.now() })
1436
+ save({ imports, refreshAt: Date.now() }, note)
1437
+ pollSnapshot(`等待后端处理:${req.path}`, 25)
1438
+ }
1439
+
1440
+ /** pollSnapshot 每隔 1.2 秒重新加载 catalog.js(加时间戳绕缓存),版本变了就重画。 */
1441
+ function pollSnapshot(reason, seconds = 12) {
1442
+ const before = catalog?.version ?? 0
1443
+ const until = Date.now() + seconds * 1000
1444
+ say(reason)
1445
+ const tick = () => {
1446
+ const script = document.createElement('script')
1447
+ script.src = `catalog.js?t=${Date.now()}`
1448
+ script.onload = () => {
1449
+ script.remove()
1450
+ const next = window.PURGE_CATALOG
1451
+ if (next && next.version !== before) {
1452
+ catalog = next
1453
+ render()
1454
+ say('快照已更新', 'good')
1455
+ return
1456
+ }
1457
+ if (Date.now() < until) setTimeout(tick, 1200)
1458
+ else say('后端还没写出新快照:magpie 里插件可能没重启,或来源目录没权限。', 'bad')
1459
+ }
1460
+ script.onerror = () => {
1461
+ script.remove()
1462
+ if (Date.now() < until) setTimeout(tick, 1200)
1463
+ }
1464
+ document.head.append(script)
1465
+ }
1466
+ setTimeout(tick, 900)
1467
+ }
1468
+
1469
+ async function refresh() {
1470
+ if (busy) return
1471
+ busy = true
1472
+ $('refresh').disabled = true
1473
+ try {
1474
+ save({ refreshAt: Date.now() })
1475
+ await flush()
1476
+ pollSnapshot('正在让后端重新扫描…', 25)
1477
+ } finally {
1478
+ busy = false
1479
+ $('refresh').disabled = false
1480
+ }
1481
+ }
1482
+
1483
+ function wire() {
1484
+ $('mode').addEventListener('change', (e) => {
1485
+ const value = e.target.value
1486
+ save({ mode: value }, value ? `模式改为 ${value}` : '改为跟随 agent-purge')
1487
+ })
1488
+ $('refresh').addEventListener('click', refresh)
1489
+ $('q').addEventListener('input', (e) => { query = e.target.value; render() })
1490
+
1491
+ $('import-run').addEventListener('click', () => {
1492
+ const path = $('import-path').value.trim()
1493
+ if (!path) return say('先填一个文件路径', 'bad')
1494
+ importRequest({ op: 'import', path }, '已请求导入')
1495
+ $('import-path').value = ''
1496
+ })
1497
+
1498
+ $('import-file').addEventListener('change', async (e) => {
1499
+ const file = e.target.files?.[0]
1500
+ if (!file) return
1501
+ try {
1502
+ const raw = await file.text()
1503
+ if (raw.length > 64 * 1024) throw new Error('超过 64 KB:这么大的正文不该塞进 options')
1504
+ const id = (file.name.replace(/\.[^.]+$/, '').toLowerCase().replace(/[^a-z0-9._-]+/g, '-') || 'inline').slice(0, 48)
1505
+ const kept = inlineEntries().filter((x) => x.id !== id)
1506
+ const body = raw.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '').trim()
1507
+ const fm = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/)
1508
+ const name = fm?.[1]?.match(/^name:\s*(.+)$/m)?.[1]?.replace(/^["']|["']$/g, '') || file.name.replace(/\.[^.]+$/, '')
1509
+ save({ inline: [...kept, { id, name, kind: 'persona', text: body }] }, `已把「${name}」存进 options`)
1510
+ e.target.value = ''
1511
+ } catch (error) {
1512
+ say(`导入失败:${error?.message || error}`, 'bad')
1513
+ }
1514
+ })
1515
+
1516
+ const sources = $('sources-save')
1517
+ sources?.addEventListener('click', () => {
1518
+ const list = $('sources').value.split(/\r?\n/).map((s) => s.trim()).filter(Boolean)
1519
+ save({ sources: list, refreshAt: Date.now() }, '来源目录已保存')
1520
+ pollSnapshot('等待后端按新来源扫描…', 25)
1521
+ })
1522
+ }
1523
+
1524
+ async function boot() {
1525
+ if (bridge?.ready?.then) {
1526
+ try {
1527
+ await Promise.race([bridge.ready, new Promise((r) => setTimeout(r, 1500))])
1528
+ } catch {
1529
+ /* 宿主没答也要能画 */
1530
+ }
1531
+ }
1532
+ if (bridge?.onVisibility) bridge.onVisibility((visible) => { if (visible && !busy) refreshFromDisk() })
1533
+ try {
1534
+ options = (await bridge?.options?.get?.()) || {}
1535
+ } catch (error) {
1536
+ say(`读不到 options:${error?.message || error}`, 'bad')
1537
+ options = {}
1538
+ }
1539
+ wire()
1540
+ render()
1541
+ if (!catalog) pollSnapshot('还没有快照,等后端第一次扫描…', 20)
1542
+ }
1543
+
1544
+ /** 页面被切回来时顺手换一份快照:宿主可能在背后扫过一次。 */
1545
+ function refreshFromDisk() {
1546
+ const script = document.createElement('script')
1547
+ script.src = `catalog.js?t=${Date.now()}`
1548
+ script.onload = () => {
1549
+ script.remove()
1550
+ const next = window.PURGE_CATALOG
1551
+ if (next && next.version !== catalog?.version) {
1552
+ catalog = next
1553
+ render()
1554
+ }
1555
+ }
1556
+ script.onerror = () => script.remove()
1557
+ document.head.append(script)
1558
+ }
1559
+
1560
+ boot()
1561
+ })()
1562
+ </script>
1563
+ </body>
1564
+ </html>