@fish-under-sea/magpie-purge 0.4.0 → 0.4.1

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/README.md CHANGED
@@ -103,7 +103,8 @@
103
103
  `agent-purge` 的 magpie 插件只认 `~/.agent-purge/` 的人设,页面也不能读盘。
104
104
  本插件把这条链补成三件事:
105
105
 
106
- 1. **来源可以是任意目录**:默认 `~/.magpie/purge`(用 `PURGE_HOME` 可改),也能在页面里改成多个目录;
106
+ 1. **内容只从两条路来**:随包分发的 9 位专家 + 1 份底座人设,以及你自己**导入**的文件。
107
+ 不再去翻磁盘上的任意目录——「它会不会自己扫我的硬盘」不该是个悬念;
107
108
  2. **认得四种东西**:DSH 会话导出包(`dsh-session-archive`)、DSH cordis 插件包、
108
109
  人设 / 技能 markdown、裸文本与 JSON 清单——坏包给出具体拒绝原因,不半途落盘;
109
110
  3. **页面能调配**:条目列表、检查器(含查看原文)、模式、启用、版本回滚、校验记录、最近一次生效记录。
@@ -120,7 +121,7 @@ magpie plugin add "./magpie-purge"
120
121
  magpie plugin list
121
122
  ```
122
123
 
123
- 装好后 magpie 的侧栏会多出一页「破甲 · Purge」;插件页第一次打开时,后端会扫一遍来源目录,
124
+ 装好后 magpie 的侧栏会多出一页「破甲 · Purge」;插件页第一次打开时,后端会清点包内内容与已导入的文件,
124
125
  写出 `state/catalog.json` 与 `page/catalog.js` 两份快照,页面读的是后者。
125
126
 
126
127
  ## 配置
@@ -134,7 +135,6 @@ magpie plugin list
134
135
  | `agents` | 只对这些 magpie agent 生效,如 `["claude","codex"]`;空数组 = 全部 |
135
136
  | `enabled` | `{条目id: true/false}`:技能必须显式为 `true` 才注入;人设默认启用 |
136
137
  | `pinned` | `{条目id: 摘要}`:固定到某一版,网关用那一版的正文 |
137
- | `sources` | 来源目录列表;空数组用默认的 `~/.magpie/purge` |
138
138
  | `imports` | 页面写的导入请求(`{op, path, at}`),后端处理后复制进 `state/imports` |
139
139
  | `inline` | 页面里直接贴进来的人设/技能正文,不进磁盘 |
140
140
  | `gatewayTimeoutMs` | 钩子预算,默认 1500 ms(magpie 侧 100–10000) |
@@ -180,6 +180,17 @@ magpie plugin options magpie-purge '{"useAgentPurge":true}'
180
180
 
181
181
  导入的 `.zip` 是素材(会话导出包、DSH 插件包),**不会进 system**——检查器里会直说,别把素材当人设。
182
182
 
183
+ ### 导入分两步
184
+
185
+ 「导入」折叠区里:**先点「选择」挑文件**(路径会填进输入框,你能看见选中了什么),
186
+ **再点「导入」才真的写进去**。一步到底容易误触——浏览器选完就落盘,人还没确认类型。
187
+
188
+ - 框里直接粘**绝对路径**时走另一条路:后端把原件复制进 `state/imports`,原文件不动;
189
+ - 「这份文件是」三选一(自动判断 / 人设 / 技能):自动判断按 frontmatter 与正文结构猜,
190
+ 猜错就在检查器里点**「改判为技能 / 人设」**,不必删了重导;
191
+ - 删的时候用检查器里的**「删除导入」**(页面导入的)或**「删除副本」**(复制进 `state/imports` 的),
192
+ 指向它的 `persona` / `enabled` / `pinned` 引用会一起清掉——否则会卡在「指定的人设不在了」。
193
+
183
194
  选中任一条目,检查器里有**「查看原文」**:正文(去掉 frontmatter 之后真正会拼进 system 的那段)
184
195
  随快照一起下发,点开就能读,不用去磁盘翻文件。超过 8000 字符会截断并标出总长度;
185
196
  换条目自动收起,不会把上一条的正文带过来。
@@ -299,7 +310,7 @@ npm run preview:serve # → http://127.0.0.1:55172
299
310
  node --test --test-isolation=none "tests/*.test.mjs"
300
311
 
301
312
  # 离线清点,看看本机 purge 目录里都认得什么
302
- node tools/scan.mjs --sources "D:\purge" --sources "~/.magpie/purge"
313
+ node tools/scan.mjs --import "D:\purge\我的.md"
303
314
 
304
315
  # 只打条目表到 stdout(不写文件)
305
316
  node tools/scan.mjs --json
@@ -312,19 +323,20 @@ node tools/scan.mjs --json
312
323
 
313
324
  | 项 | agent-purge 的 `magpie-plugin/` | 本插件 |
314
325
  | --- | --- | --- |
315
- | 来源 | 只读 `~/.agent-purge/` | 可配多个目录 + `state/imports` + 内置专家包 |
326
+ | 来源 | 只读 `~/.agent-purge/` | 包内专家包 + `state/imports`(只认导入) |
316
327
  | 判型 | 只有人设 markdown | 导出包 / DSH 插件包 / 人设 / 技能 / 文本 / 清单 |
317
328
  | 注入 | 一个人设 | 人设 + 显式启用的技能(含 9 位内置专家) |
318
329
  | 页面 | 人设选择 + 导入 | 条目列表 + 检查器 + 模式 + 回滚 + 校验记录 |
319
330
  | 快照 | 生成脚本写 `personas.js` | 后端每次扫描写 `catalog.js`,页面不读盘 |
320
331
  | 版本 | 无 | 同 id 新摘要算新版本,留两版可回滚 |
321
- | 与 agent-purge 的关系 | 读 `state.json` 但页面改不了模式 | **认它的 state.json**(mode/persona/overrides/disabledHarnesses),同时页面设置优先,两边都能改 |
332
+ | 与 agent-purge 的关系 | 读 `state.json` 但页面改不了模式 | 默认不读;要读得显式设 `useAgentPurge: true` |
322
333
  | 状态可见性 | 无 | 顶部状态条直接回答「注不注、注谁、为什么没注」 |
323
334
 
324
335
  ## 版本
325
336
 
326
337
  | 版本 | 要点 |
327
338
  | --- | --- |
339
+ | `0.4.1` | 修「选完模式又被换回」「确认注入点了没用」;导入区改成「选择 → 再点导入」两步并可选人设/技能;去掉来源目录与自动扫描,只扫包内与 `state/imports` |
328
340
  | `0.4.0` | 底座人设 `大肥鱼` 取代 Prompt Forge:不绑定任务,0–9 位专家随意组合;默认不再读上游 `state.json`(要读设 `useAgentPurge:true`);默认来源只剩 `~/.magpie/purge`;模式下拉去掉「跟随上游」 |
329
341
  | `0.3.0` | 内置 9 位专家技能包(由本机 `dsh-purge` 的 23 份原子技能提炼);内置条目带「内置」标、可停用不可删 |
330
342
  | `0.2.0` | 认 agent-purge 的 `state.json`(原生语义);页面加「当前注入」状态条与可点的下一步;导入素材后不再一头雾水 |
package/hooks.js CHANGED
@@ -83,10 +83,14 @@ export function createHook(root = here, { deadlineMs = 400, rescanMs = 30_000, w
83
83
  const scans = new Map()
84
84
  let lastWrite = 0
85
85
 
86
- /** keyOf 是「这次配置要不要重扫」的粗指纹:来源目录 + 刷新戳。 */
86
+ /**
87
+ * keyOf 是「这次配置要不要重扫」的粗指纹:导入请求 + 刷新戳。
88
+ *
89
+ * 以前还带来源目录,现在不再扫用户磁盘目录,所以只剩这两样会真的改变条目表。
90
+ */
87
91
  const keyOf = (options = {}) => {
88
- const sources = Array.isArray(options.sources) ? options.sources.filter((s) => typeof s === 'string' && s.trim()) : []
89
- return [sources.join('|') || 'default', String(options.refreshAt ?? 0)].join('@')
92
+ const imports = Array.isArray(options.imports) ? options.imports.map((i) => `${i?.path}@${i?.at}`).join(',') : ''
93
+ return [imports, String(options.refreshAt ?? 0)].join('@')
90
94
  }
91
95
 
92
96
  /** scanOnce 按配置键去重:同一份配置同时只扫一次,不同配置并行。 */
package/lib/inventory.mjs CHANGED
@@ -45,21 +45,6 @@ export function expandHome(p, base = process.cwd()) {
45
45
  return isAbsolute(raw) ? normalize(raw) : resolve(base, raw)
46
46
  }
47
47
 
48
- /**
49
- * defaultSources 是没配 sources 时看的目录。
50
- *
51
- * 只认自己的:PURGE_HOME,加 magpie 配置下的 purge。不再默认指向 ~/.agent-purge——
52
- * 那是上游的家,装了这个插件的人未必装过它;默认去翻别人的目录,只会多出一串
53
- * 「目录不存在」的噪音。想用它的内容,把路径自己填进来就行。
54
- */
55
- export function defaultSources(env = process.env) {
56
- const out = []
57
- const fromEnv = String(env.PURGE_HOME || '').trim()
58
- if (fromEnv) out.push(fromEnv)
59
- out.push(join(homedir(), '.magpie', 'purge'))
60
- return out
61
- }
62
-
63
48
  export const digestOf = (bytes) => createHash('sha256').update(bytes).digest('hex')
64
49
 
65
50
  /** slug 让名字变成稳定的 id 片段:只留字母数字与 ._-,全非 ASCII 时退回摘要前缀。 */
package/lib/plan.mjs CHANGED
@@ -70,14 +70,20 @@ export function resolve({ options = {}, state = null, entries = [], agent = '' }
70
70
 
71
71
  if (!personaId) {
72
72
  if (missingPersona) {
73
+ // 指名要谁却找不到:不偷偷换人(那会变成「我选了 A,注入的却是 B」),
74
+ // 但要把「现在能挑谁」直接列出来——否则用户只看到一句「不在来源里」,无从下手。
75
+ const names = personas.slice(0, 4).map((e) => e.name || e.id).join('、')
73
76
  return {
74
77
  ...blank(modeFrom, mode, '', 'persona-missing'),
75
- blocked: `指定的「${missingPersona}」不在当前来源里:把它放进来源目录,或在这里挑一个`,
78
+ blocked: names
79
+ ? `指定的「${missingPersona}」已经不在了:现在可用的有 ${names}${personas.length > 4 ? ' 等' : ''}`
80
+ : `指定的「${missingPersona}」已经不在了,来源里也还没有其它人设`,
81
+ missingPersona,
76
82
  }
77
83
  }
78
84
  const why = personas.length
79
85
  ? '还没有选人设:左边挑一条「人设」点“设为当前人设”'
80
- : '来源里还没有人设(.md):导入一份,或在「导入与来源」里挑一个文件'
86
+ : '来源里还没有人设(.md):导入一份试试'
81
87
  return { ...blank(modeFrom, mode, '', personas.length ? 'no-persona' : 'no-persona-file'), blocked: why }
82
88
  }
83
89
 
@@ -100,5 +106,5 @@ export function resolve({ options = {}, state = null, entries = [], agent = '' }
100
106
  }
101
107
 
102
108
  function blank(modeFrom, mode, blocked, blockedCode = '') {
103
- return { mode: mode || 'off', modeFrom, personaId: '', personaName: '', personaFrom: '', skills: [], blocked, blockedCode, ready: false }
109
+ return { mode: mode || 'off', modeFrom, personaId: '', personaName: '', personaFrom: '', skills: [], blocked, blockedCode, ready: false, missingPersona: '' }
104
110
  }
package/lib/state.mjs CHANGED
@@ -12,7 +12,6 @@ import { homedir } from 'node:os'
12
12
  import { basename, extname, join, normalize } from 'node:path'
13
13
  import {
14
14
  LIMITS,
15
- defaultSources,
16
15
  expandHome,
17
16
  mergeEntries,
18
17
  scan,
@@ -46,18 +45,15 @@ const readJson = (file, fallback) => {
46
45
  const sha = (text) => createHash('sha256').update(String(text)).digest('hex').slice(0, 16)
47
46
 
48
47
  /** sourceSignature 是「这次要不要重扫」的判断依据:目录 mtime + 导入请求 + 强制刷新戳 + 包内专家。 */
49
- function sourceSignature(sources, imports = [], refreshAt = 0, bundledEntries = []) {
50
- const stamps = []
51
- for (const dir of sources) {
52
- try {
53
- const st = statSync(dir)
54
- stamps.push(`${dir}:${st.mtimeMs}`)
55
- } catch {
56
- stamps.push(`${dir}:missing`)
57
- }
58
- }
48
+ /**
49
+ * sourceSignature 决定「这次要不要重扫」。
50
+ *
51
+ * 现在只剩两处会变:导入请求(imports)与随包内容(bundledEntries)。
52
+ * 不再把磁盘目录的 mtime 算进来——那等于每次磁盘有动静就重扫一遍。
53
+ */
54
+ function sourceSignature(imports = [], refreshAt = 0, bundledEntries = []) {
59
55
  const own = bundledEntries.map((e) => `${e.id}:${e.digest}`).join(',')
60
- return sha([...stamps, imports.map((i) => `${i.path}@${i.at}`).join(','), refreshAt, own].join('|'))
56
+ return sha([imports.map((i) => `${i.path}@${i.at}`).join(','), refreshAt, own].join('|'))
61
57
  }
62
58
 
63
59
  /**
@@ -111,22 +107,22 @@ export function sync(here, options = {}, { force = false, limits = LIMITS, now =
111
107
  mkdirSync(p.stateDir, { recursive: true })
112
108
  mkdirSync(p.importsDir, { recursive: true })
113
109
 
114
- const configured = Array.isArray(options.sources) ? options.sources.filter((s) => typeof s === 'string' && s.trim()) : []
115
- const sources = configured.length ? configured : defaultSources()
110
+ // 只扫两处:包内随包内容(bundledRows)与 state/imports(用户导入的副本)。
111
+ // 不再扫用户配的任意目录——那是「它会自己去翻我的磁盘」的来源,默认关掉更符合预期。
116
112
  const imports = Array.isArray(options.imports) ? options.imports.filter((i) => i && typeof i.path === 'string') : []
117
113
  const previous = loadCatalog(p)
118
114
  // 包内专家技能先读出来:它们随包走,签名也要算进它们,
119
115
  // 否则插件更新后(新增/改写专家)会因为「来源没变」而一直用旧表。
120
116
  const bundledRows = bundledScan(here)
121
- const signature = sourceSignature(sources, imports, options.refreshAt ?? 0, bundledRows.entries)
117
+ const signature = sourceSignature(imports, options.refreshAt ?? 0, bundledRows.entries)
122
118
 
123
119
  if (!force && previous.signature === signature) {
124
120
  return { catalog: previous, changed: false, snapshot: snapshotFrom(p, previous, options, now) }
125
121
  }
126
122
 
127
123
  const importRows = applyImports(p, imports, previous, now)
128
- // 导入的副本本身就是一个来源目录:放在最前面,页面能看到「来源:导入」。
129
- const scanned = scan([p.importsDir, ...sources], { limits, now })
124
+ // 只有导入目录参与扫描;用户没导入就只剩包内那 9 位专家 + 1 份底座人设。
125
+ const scanned = scan([p.importsDir], { limits, now })
130
126
  const { entries: scannedEntries, duplicates } = mergeEntries(scanned.entries, previous.entries)
131
127
  // 包内专家技能永远在场:不参与「来源」的增删,也不吃版本号(它随包走,不是用户导入的)。
132
128
  const entries = [...bundledRows.entries, ...scannedEntries]
@@ -204,7 +200,7 @@ export function applyImports(p, imports, previous, now) {
204
200
  row.ok = removeImport(p, req.path)
205
201
  row.error = row.ok ? '' : '没有找到这条导入的副本'
206
202
  } else {
207
- row.file = importFile(p, req.path)
203
+ row.file = importFile(p, req.path, req.kind)
208
204
  row.ok = Boolean(row.file)
209
205
  row.error = row.ok ? '' : `只接受 ${[...IMPORT_EXT].join(' / ')} 文件`
210
206
  row.keep = row.ok
@@ -217,7 +213,14 @@ export function applyImports(p, imports, previous, now) {
217
213
  return rows
218
214
  }
219
215
 
220
- function importFile(p, rawPath) {
216
+ /**
217
+ * importFile 把原件复制进 state/imports。
218
+ *
219
+ * kind 是用户在导入时指定的类型(persona/skill):写进副本的 frontmatter。
220
+ * 这样类型跟着文件走,不依赖 options 里一份易失的映射;注入时 frontmatter 本来就会被剥掉,
221
+ * 不会混进 system。
222
+ */
223
+ function importFile(p, rawPath, kind) {
221
224
  const src = String(rawPath).trim()
222
225
  if (!src) throw new Error('空路径')
223
226
  const ext = extname(src).toLowerCase()
@@ -225,12 +228,32 @@ function importFile(p, rawPath) {
225
228
  const st = statSync(src)
226
229
  if (!st.isFile()) throw new Error('不是文件')
227
230
  if (st.size > LIMITS.fileBytes) throw new Error(`文件超过 ${LIMITS.fileBytes / 1024} KiB 上限`)
228
- const digest = sha(`${st.size}:${st.mtimeMs}:${src}`)
231
+ const digest = sha(`${st.size}:${st.mtimeMs}:${src}:${kind || ''}`)
229
232
  const target = join(p.importsDir, `${digest}${ext}`)
230
- if (!existsSync(target)) copyFileSync(src, target)
233
+ if (existsSync(target)) return target
234
+ // 只有 markdown / 文本类才谈得上 frontmatter;zip、json 原样复制。
235
+ const asText = ext === '.md' || ext === '.markdown' || ext === '.txt'
236
+ if (asText && (kind === 'persona' || kind === 'skill')) {
237
+ writeFileSync(target, withKind(readFileSync(src, 'utf8'), kind), 'utf8')
238
+ } else {
239
+ copyFileSync(src, target)
240
+ }
231
241
  return target
232
242
  }
233
243
 
244
+ /** withKind 把 kind 写进 frontmatter:已有就替换,没有就补一段。 */
245
+ function withKind(raw, kind) {
246
+ const text = String(raw ?? '')
247
+ const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/)
248
+ if (!m) return `---\nkind: ${kind}\n---\n${text}`
249
+ const head = m[1]
250
+ const body = text.slice(m[0].length)
251
+ const next = /^kind\s*:/m.test(head)
252
+ ? head.replace(/^kind\s*:.*$/m, `kind: ${kind}`)
253
+ : `${head}\nkind: ${kind}`
254
+ return `---\n${next}\n---\n${body}`
255
+ }
256
+
234
257
  function removeImport(p, rawPath) {
235
258
  const base = basename(String(rawPath).trim())
236
259
  const target = join(p.importsDir, base)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fish-under-sea/magpie-purge",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "magpie-purge: a magpie page plugin that treats a local purge folder as a free plugin/skill source, inspects and validates what is in it, and rewrites the gateway's system prompt by mode (off / strict / replace / append).",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/page/app.js CHANGED
@@ -48,6 +48,10 @@
48
48
  let busy = false
49
49
  /** showingText 是「查看原文」的展开态;换条目时要收回去,否则新条目一进来就是展开的。 */
50
50
  let showingText = false
51
+ /** pendingFile 是「点过选择、还没点导入」的那个文件;两步导入靠它接上。 */
52
+ let pendingFile = null
53
+ /** importKind 是导入时选的类型:auto 交给判定,persona/skill 覆盖它。 */
54
+ let importKind = 'auto'
51
55
  /** confirmedSig 记「用户按下确认时的那套配置」;配置一变就失效,退回「确认注入」。 */
52
56
  let confirmedSig = ''
53
57
  /** modeMenuOpen 是模式下拉面板是否展开;每次重画都要记住,否则点一下就收。 */
@@ -94,6 +98,12 @@
94
98
  const inlineEntries = () => (Array.isArray(options.inline) ? options.inline : [])
95
99
  const findEntry = (id) => entries().find((e) => e.id === id) || inlineEntries().find((e) => e.id === id) || null
96
100
  const isEnabled = (id) => (options.enabled?.[id] !== undefined ? options.enabled[id] : findEntry(id)?.kind === 'persona')
101
+ /** defaultPersona 是「现在最能顶上的人设」:内置底座优先,其次第一个可用的人设。 */
102
+ const defaultPersona = () =>
103
+ entries().find((e) => e.kind === 'persona' && e.default === true) ||
104
+ entries().find((e) => e.kind === 'persona') ||
105
+ inlineEntries().find((e) => e.kind !== 'skill') ||
106
+ null
97
107
 
98
108
  // ---------- 与宿主说话 ----------
99
109
 
@@ -110,11 +120,18 @@
110
120
 
111
121
  async function flush() {
112
122
  if (!pendingSave || !bridge?.options?.set) return
123
+ // 记住这一轮自己刚写下去的键:宿主回包只用来「补全它规范化的字段」,
124
+ // 不许它把我们刚设的值盖回去——否则「选了模式又被换回」会反复发生。
125
+ const sent = { ...(pendingSave || {}) }
113
126
  const body = { ...options }
114
127
  pendingSave = null
115
128
  try {
116
129
  const saved = await bridge.options.set(body)
117
- if (saved && typeof saved === 'object') options = { ...body, ...saved }
130
+ if (saved && typeof saved === 'object') {
131
+ const merged = { ...body, ...saved }
132
+ for (const key of Object.keys(sent)) merged[key] = body[key]
133
+ options = merged
134
+ }
118
135
  } catch (error) {
119
136
  say(`保存失败:${error?.message || error}`, 'bad')
120
137
  }
@@ -327,8 +344,9 @@
327
344
  const kind = KINDS[e.kind] || { label: e.kind }
328
345
  const kindCls = kindClass(e.kind)
329
346
  const inline = e.source?.root === 'inline' || e.meta?.format === 'inline'
330
- // 只有复制进插件自己的 state/imports 的副本才谈得上「删副本」:来源目录里的原件不动。
331
- const imported = Boolean(e.source?.root && /[\\/]state[\\/]imports\/?$/.test(e.source.root))
347
+ // 只有复制进插件自己的 state/imports 的副本才谈得上「删副本」:原件不动。
348
+ // root 可能是绝对路径(真机)也可能是相对路径(演示快照),所以不要求前导分隔符。
349
+ const imported = Boolean(e.source?.root && /(^|[\\/])state[\\/]imports\/?$/.test(e.source.root))
332
350
  const enabled = isEnabled(e.id)
333
351
  const pinned = options.pinned?.[e.id]
334
352
  const history = Array.isArray(e.history) ? e.history : []
@@ -377,18 +395,53 @@
377
395
  type: 'button',
378
396
  class: 'danger',
379
397
  onclick: () => {
398
+ // 删掉导入的条目时,指向它的引用也要一起清:否则 plan 会卡在 persona-missing,
399
+ // 用户还得再点一次「改用」才能恢复注入。
380
400
  const kept = inlineEntries().filter((x) => x.id !== e.id)
381
401
  const enabledNext = { ...(options.enabled || {}) }
382
402
  delete enabledNext[e.id]
383
- save({ inline: kept, enabled: enabledNext, persona: options.persona === e.id ? '' : options.persona }, '已从页面导入里删掉')
403
+ const pinnedNext = { ...(options.pinned || {}) }
404
+ delete pinnedNext[e.id]
405
+ const fallback = kept.find((x) => x.kind !== 'skill')
406
+ save({
407
+ inline: kept,
408
+ enabled: enabledNext,
409
+ pinned: pinnedNext,
410
+ persona: options.persona === e.id ? (fallback?.id || '') : options.persona,
411
+ }, `已删除「${e.name}」`)
384
412
  if (selected === e.id) selected = ''
413
+ render()
385
414
  },
386
- }, '删除'))
415
+ }, '删除导入'))
416
+ // 类型选错时能就地改:重扫猜出来的类型不一定对,硬编码成「人设」更糟。
417
+ actions.push(el('button', {
418
+ type: 'button',
419
+ class: 'quiet',
420
+ onclick: () => {
421
+ const nextKind = e.kind === 'skill' ? 'persona' : 'skill'
422
+ const next = inlineEntries().map((x) => (x.id === e.id ? { ...x, kind: nextKind } : x))
423
+ save({ inline: next }, `已改判为${nextKind === 'skill' ? '技能' : '人设'}`)
424
+ render()
425
+ },
426
+ }, e.kind === 'skill' ? '改判为人设' : '改判为技能'))
387
427
  } else if (imported) {
388
428
  actions.push(el('button', {
389
429
  type: 'button',
390
430
  class: 'danger',
391
- onclick: () => importRequest({ op: 'delete', path: e.source.rel }, `已请求删除「${e.name}」的副本(只删插件自己的 state/imports)`),
431
+ onclick: () => {
432
+ // 删副本同时把指向它的引用清掉:留着会让 plan 卡在 persona-missing。
433
+ const enabledNext = { ...(options.enabled || {}) }
434
+ delete enabledNext[e.id]
435
+ const pinnedNext = { ...(options.pinned || {}) }
436
+ delete pinnedNext[e.id]
437
+ save({
438
+ enabled: enabledNext,
439
+ pinned: pinnedNext,
440
+ persona: options.persona === e.id ? '' : options.persona,
441
+ })
442
+ importRequest({ op: 'delete', path: e.source.rel }, `已请求删除「${e.name}」的副本(只删插件自己的 state/imports)`)
443
+ if (selected === e.id) selected = ''
444
+ },
392
445
  }, '删除副本'))
393
446
  }
394
447
 
@@ -539,7 +592,6 @@
539
592
  $('inspect').hidden = !picked
540
593
  renderRejects()
541
594
  renderLast()
542
- renderSources()
543
595
  }
544
596
 
545
597
  /** MODES 是模式下拉的全部取值:没有「跟随上游」这一档,模式必须自己选。 */
@@ -583,10 +635,19 @@
583
635
  if (plan.blockedCode === 'no-mode' || plan.blockedCode === 'mode-off') {
584
636
  fix.push(el('button', { type: 'button', class: 'primary', onclick: () => fixed({ mode: 'replace' }, '模式改为 replace') }, '用 replace 开始注入'))
585
637
  }
586
- if (plan.blockedCode === 'no-persona' || plan.blockedCode === 'persona-missing') {
638
+ // 旧人设被删掉后 options.persona 会一直指着它,卡在 persona-missing:
639
+ // 这个问题点「去看人设」永远绕不出来,得给一个直接改掉它的动作。
640
+ if (plan.blockedCode === 'persona-missing' && defaultPersona()) {
641
+ const next = defaultPersona()
587
642
  fix.push(el('button', {
588
643
  type: 'button',
589
644
  class: 'primary',
645
+ onclick: () => fixed({ persona: next.id }, `人设改为「${next.name}」`),
646
+ }, `改用「${next.name}」`))
647
+ }
648
+ if (plan.blockedCode === 'no-persona' || plan.blockedCode === 'persona-missing') {
649
+ fix.push(el('button', {
650
+ type: 'button',
590
651
  onclick: () => { filter = 'persona'; query = ''; render() },
591
652
  }, '去看人设'))
592
653
  }
@@ -594,7 +655,7 @@
594
655
  fix.push(el('button', {
595
656
  type: 'button',
596
657
  class: 'primary',
597
- onclick: () => { $('import-file')?.focus(); $('import-file')?.click?.() },
658
+ onclick: () => { filter = 'persona'; query = ''; render() },
598
659
  }, '导入一份人设'))
599
660
  }
600
661
  }
@@ -738,15 +799,6 @@
738
799
  }, applied ? '已注入' : '确认注入')
739
800
  }
740
801
 
741
- function renderSources() {
742
- const el2 = $('sources')
743
- if (!el2 || document.activeElement === el2) return
744
- const list = Array.isArray(options.sources) && options.sources.length
745
- ? options.sources
746
- : (catalog?.sources || []).filter((s) => s.path && !/[\\/]state[\\/]imports\/?$/.test(s.path)).map((s) => s.path)
747
- el2.value = list.join('\n')
748
- }
749
-
750
802
  // ---------- 动作 ----------
751
803
 
752
804
  function importRequest(req, note) {
@@ -809,37 +861,84 @@
809
861
  renderPlan()
810
862
  })
811
863
 
812
- $('import-run').addEventListener('click', () => {
813
- const path = $('import-path').value.trim()
814
- if (!path) return say('先填一个文件路径', 'bad')
815
- importRequest({ op: 'import', path }, '已请求导入')
816
- $('import-path').value = ''
864
+ // 导入分两步:先选文件(把路径填进输入框),再点「导入」才真的导入。
865
+ // 一步到底容易误触:浏览器选完就导入,用户还没确认类型就落盘了。
866
+ $('import-pick').addEventListener('click', () => {
867
+ const input = document.createElement('input')
868
+ input.type = 'file'
869
+ input.accept = '.md,.markdown,.txt,.json,.zip'
870
+ input.addEventListener('change', () => {
871
+ const file = input.files?.[0]
872
+ if (!file) return
873
+ // 浏览器出于安全不暴露真实路径,只能拿到文件名。
874
+ // 这一步先把名字填进去,让人看见选中了什么;真正导入走下面那条 inline 通道。
875
+ $('import-path').value = file.name
876
+ pendingFile = file
877
+ say(`已选中「${file.name}」,再点一次「导入」就写入`, 'good')
878
+ })
879
+ input.click()
817
880
  })
818
881
 
819
- $('import-file').addEventListener('change', async (e) => {
820
- const file = e.target.files?.[0]
821
- if (!file) return
882
+ $('import-run').addEventListener('click', async () => {
883
+ const typed = $('import-path').value.trim()
884
+ // 手填的是绝对路径:交给后端复制(原文件不动,副本进 state/imports)。
885
+ if (typed && !pendingFile) {
886
+ importRequest({ op: 'import', path: typed, kind: importKind }, '已请求导入')
887
+ $('import-path').value = ''
888
+ return
889
+ }
890
+ const file = pendingFile
891
+ if (!file) return say('先点「选择」挑一个文件,或在框里填绝对路径', 'bad')
822
892
  try {
823
893
  const raw = await file.text()
824
894
  if (raw.length > 64 * 1024) throw new Error('超过 64 KB:这么大的正文不该塞进 options')
825
895
  const id = (file.name.replace(/\.[^.]+$/, '').toLowerCase().replace(/[^a-z0-9._-]+/g, '-') || 'inline').slice(0, 48)
826
896
  const kept = inlineEntries().filter((x) => x.id !== id)
827
- const body = raw.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '').trim()
828
897
  const fm = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/)
898
+ const declared = fm?.[1]?.match(/^kind:\s*(persona|skill)\s*$/m)?.[1]
829
899
  const name = fm?.[1]?.match(/^name:\s*(.+)$/m)?.[1]?.replace(/^["']|["']$/g, '') || file.name.replace(/\.[^.]+$/, '')
830
- save({ inline: [...kept, { id, name, kind: 'persona', text: body }] }, `已把「${name}」存进 options`)
831
- e.target.value = ''
900
+ const body = raw.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '').trim()
901
+ // 类型的优先级:用户明确选的 > 文件自己写的 > 猜。
902
+ const kind = importKind !== 'auto' ? importKind : declared || guessKind(body)
903
+ save({ inline: [...kept, { id, name, kind, text: body }] }, `已导入「${name}」(${kind === 'skill' ? '技能' : '人设'})`)
904
+ pendingFile = null
905
+ $('import-path').value = ''
906
+ refreshAfterImport()
832
907
  } catch (error) {
833
908
  say(`导入失败:${error?.message || error}`, 'bad')
834
909
  }
835
910
  })
836
911
 
837
- const sources = $('sources-save')
838
- sources?.addEventListener('click', () => {
839
- const list = $('sources').value.split(/\r?\n/).map((s) => s.trim()).filter(Boolean)
840
- save({ sources: list, refreshAt: Date.now() }, '来源目录已保存')
841
- pollSnapshot('等待后端按新来源扫描…', 25)
842
- })
912
+ // 导入类型:三选一,选中项自己管自己的 aria-pressed。
913
+ for (const chip of document.querySelectorAll('#import-kind .chip')) {
914
+ chip.addEventListener('click', () => {
915
+ importKind = chip.dataset.kind || 'auto'
916
+ for (const other of document.querySelectorAll('#import-kind .chip')) {
917
+ other.setAttribute('aria-pressed', other === chip ? 'true' : 'false')
918
+ }
919
+ })
920
+ }
921
+ }
922
+
923
+ /**
924
+ * guessKind 猜一份 .md 是人设还是技能。
925
+ *
926
+ * 判据来自本插件自己的两种文件长相:人设是完整第二人称,通常带 `## 你是什么`/`你是谁`;
927
+ * 技能是「某个领域的专家」,标题一般是 `# X专家`,正文多含命令与表格。
928
+ */
929
+ function guessKind(body) {
930
+ const text = String(body || '')
931
+ if (/^##\s*(你是什么|你是谁|你是谁?)/m.test(text)) return 'persona'
932
+ if (/^(你是|你现在是)/m.test(text) && !/^#\s/m.test(text)) return 'persona'
933
+ if (/^#\s/m.test(text) && /(\||命令|工具|参数)/.test(text)) return 'skill'
934
+ return 'persona'
935
+ }
936
+
937
+ /** refreshAfterImport 让新导入的条目立刻出现在列表里,并让后端按新 options 重扫。 */
938
+ function refreshAfterImport() {
939
+ save({ refreshAt: Date.now() })
940
+ render()
941
+ pollSnapshot('等后端按新导入重扫…', 20)
843
942
  }
844
943
 
845
944
  async function boot() {
package/page/index.html CHANGED
@@ -40,28 +40,27 @@
40
40
 
41
41
  <footer class="foot">
42
42
  <details class="fold">
43
- <summary>导入与来源</summary>
43
+ <summary>导入</summary>
44
44
  <div class="fold-body">
45
45
  <label class="field">
46
46
  <span class="field-label">文件路径</span>
47
47
  <div class="inline-row">
48
- <input id="import-path" type="text" placeholder="人设、技能、ZIP 导出包" aria-label="要导入的文件路径" spellcheck="false">
48
+ <input id="import-path" type="text" placeholder="留空点「选择」挑文件,或直接粘一个绝对路径" aria-label="要导入的文件路径" spellcheck="false">
49
+ <button id="import-pick" type="button">选择</button>
49
50
  <button id="import-run" type="button">导入</button>
50
51
  </div>
51
52
  </label>
52
- <p class="note">只认 <code>.md</code> <code>.markdown</code> <code>.txt</code> <code>.json</code> <code>.zip</code>;复制进插件的 <code>state/imports</code> 后再清点,原文件不动。</p>
53
+ <p class="note" id="import-hint">只认 <code>.md</code> <code>.markdown</code> <code>.txt</code> <code>.json</code> <code>.zip</code>。选文件后路径会填进来,再点一次「导入」才真的导入。</p>
53
54
 
54
55
  <label class="field">
55
- <span class="field-label">从本机选文件</span>
56
- <input id="import-file" type="file" accept=".md,.markdown,.txt" aria-label="从本机选一个人设或技能文件">
57
- </label>
58
- <p class="note">选文件时正文直接存进插件的 options(<code>inline</code>),不复制、不落盘。</p>
59
-
60
- <label class="field">
61
- <span class="field-label">来源目录(一行一个)</span>
62
- <textarea id="sources" rows="3" spellcheck="false" aria-label="来源目录,一行一个" placeholder="D:\purge&#10;~/.magpie/purge"></textarea>
56
+ <span class="field-label">这份文件是</span>
57
+ <div class="chips" id="import-kind" role="group" aria-label="导入类型">
58
+ <button type="button" class="chip" data-kind="auto" aria-pressed="true">自动判断</button>
59
+ <button type="button" class="chip" data-kind="persona" aria-pressed="false">人设</button>
60
+ <button type="button" class="chip" data-kind="skill" aria-pressed="false">技能</button>
61
+ </div>
63
62
  </label>
64
- <button id="sources-save" type="button">保存来源并重扫</button>
63
+ <p class="note">「自动判断」按 frontmatter 与正文结构猜;猜错就在这里指定,它会覆盖判定结果。</p>
65
64
  </div>
66
65
  </details>
67
66
 
package/page/style.css CHANGED
@@ -555,6 +555,9 @@ pre.text {
555
555
  align-items: start;
556
556
  }
557
557
  .fold { min-width: 0; }
558
+ /* 展开的那块占满整行:折叠态是一排等宽标题,展开后是表单,
559
+ 挤在 220px 一列里连路径都填不下。 */
560
+ .fold[open] { grid-column: 1 / -1; }
558
561
  .fold > summary {
559
562
  cursor: pointer;
560
563
  color: var(--muted);
@@ -6,7 +6,6 @@ window.PURGE_CATALOG = {
6
6
  generatedAt: 1794561661000,
7
7
  sources: [
8
8
  { path: '(包内)skills + personas', ok: true, count: 10, error: '', bundled: true },
9
- { path: 'C:/Users/you/.magpie/purge', ok: true, count: 1, error: '' },
10
9
  ],
11
10
  entries: [
12
11
  {
@@ -101,7 +100,7 @@ window.PURGE_CATALOG = {
101
100
  kind: 'persona',
102
101
  status: 'ok',
103
102
  reason: '',
104
- source: { root: 'C:/Users/you/.magpie/purge', rel: 'personas/anima.md' },
103
+ source: { root: 'state/imports', rel: 'anima.md' },
105
104
  size: 1204,
106
105
  digest: 'ef84b655238b9a71',
107
106
  importedAt: 1794561661000,
@@ -118,7 +117,7 @@ window.PURGE_CATALOG = {
118
117
  kind: 'session-archive',
119
118
  status: 'ok',
120
119
  reason: '',
121
- source: { root: 'C:/Users/you/.magpie/purge', rel: 'Anima loli tag.zip' },
120
+ source: { root: 'state/imports', rel: '5556.zip' },
122
121
  size: 177986,
123
122
  digest: '948c5f9615e0c1d2',
124
123
  importedAt: 1794561661000,
@@ -82,7 +82,6 @@ window.__PURGE_READY__ = {
82
82
  generatedAt: 1794561661000,
83
83
  sources: [
84
84
  { path: '(包内)skills + personas', ok: true, count: 10, error: '', bundled: true },
85
- { path: 'C:/Users/you/.magpie/purge', ok: true, count: 1, error: '' },
86
85
  ],
87
86
  entries: [
88
87
  {
@@ -177,7 +176,7 @@ window.__PURGE_READY__ = {
177
176
  kind: 'persona',
178
177
  status: 'ok',
179
178
  reason: '',
180
- source: { root: 'C:/Users/you/.magpie/purge', rel: 'personas/anima.md' },
179
+ source: { root: 'state/imports', rel: 'anima.md' },
181
180
  size: 1204,
182
181
  digest: 'ef84b655238b9a71',
183
182
  importedAt: 1794561661000,
@@ -194,7 +193,7 @@ window.__PURGE_READY__ = {
194
193
  kind: 'session-archive',
195
194
  status: 'ok',
196
195
  reason: '',
197
- source: { root: 'C:/Users/you/.magpie/purge', rel: 'Anima loli tag.zip' },
196
+ source: { root: 'state/imports', rel: '5556.zip' },
198
197
  size: 177986,
199
198
  digest: '948c5f9615e0c1d2',
200
199
  importedAt: 1794561661000,
@@ -857,6 +856,9 @@ pre.text {
857
856
  align-items: start;
858
857
  }
859
858
  .fold { min-width: 0; }
859
+ /* 展开的那块占满整行:折叠态是一排等宽标题,展开后是表单,
860
+ 挤在 220px 一列里连路径都填不下。 */
861
+ .fold[open] { grid-column: 1 / -1; }
860
862
  .fold > summary {
861
863
  cursor: pointer;
862
864
  color: var(--muted);
@@ -997,28 +999,27 @@ pre.text {
997
999
 
998
1000
  <footer class="foot">
999
1001
  <details class="fold">
1000
- <summary>导入与来源</summary>
1002
+ <summary>导入</summary>
1001
1003
  <div class="fold-body">
1002
1004
  <label class="field">
1003
1005
  <span class="field-label">文件路径</span>
1004
1006
  <div class="inline-row">
1005
- <input id="import-path" type="text" placeholder="人设、技能、ZIP 导出包" aria-label="要导入的文件路径" spellcheck="false">
1007
+ <input id="import-path" type="text" placeholder="留空点「选择」挑文件,或直接粘一个绝对路径" aria-label="要导入的文件路径" spellcheck="false">
1008
+ <button id="import-pick" type="button">选择</button>
1006
1009
  <button id="import-run" type="button">导入</button>
1007
1010
  </div>
1008
1011
  </label>
1009
- <p class="note">只认 <code>.md</code> <code>.markdown</code> <code>.txt</code> <code>.json</code> <code>.zip</code>;复制进插件的 <code>state/imports</code> 后再清点,原文件不动。</p>
1012
+ <p class="note" id="import-hint">只认 <code>.md</code> <code>.markdown</code> <code>.txt</code> <code>.json</code> <code>.zip</code>。选文件后路径会填进来,再点一次「导入」才真的导入。</p>
1010
1013
 
1011
1014
  <label class="field">
1012
- <span class="field-label">从本机选文件</span>
1013
- <input id="import-file" type="file" accept=".md,.markdown,.txt" aria-label="从本机选一个人设或技能文件">
1014
- </label>
1015
- <p class="note">选文件时正文直接存进插件的 options(<code>inline</code>),不复制、不落盘。</p>
1016
-
1017
- <label class="field">
1018
- <span class="field-label">来源目录(一行一个)</span>
1019
- <textarea id="sources" rows="3" spellcheck="false" aria-label="来源目录,一行一个" placeholder="D:\purge&#10;~/.magpie/purge"></textarea>
1015
+ <span class="field-label">这份文件是</span>
1016
+ <div class="chips" id="import-kind" role="group" aria-label="导入类型">
1017
+ <button type="button" class="chip" data-kind="auto" aria-pressed="true">自动判断</button>
1018
+ <button type="button" class="chip" data-kind="persona" aria-pressed="false">人设</button>
1019
+ <button type="button" class="chip" data-kind="skill" aria-pressed="false">技能</button>
1020
+ </div>
1020
1021
  </label>
1021
- <button id="sources-save" type="button">保存来源并重扫</button>
1022
+ <p class="note">「自动判断」按 frontmatter 与正文结构猜;猜错就在这里指定,它会覆盖判定结果。</p>
1022
1023
  </div>
1023
1024
  </details>
1024
1025
 
@@ -1095,6 +1096,10 @@ pre.text {
1095
1096
  let busy = false
1096
1097
  /** showingText 是「查看原文」的展开态;换条目时要收回去,否则新条目一进来就是展开的。 */
1097
1098
  let showingText = false
1099
+ /** pendingFile 是「点过选择、还没点导入」的那个文件;两步导入靠它接上。 */
1100
+ let pendingFile = null
1101
+ /** importKind 是导入时选的类型:auto 交给判定,persona/skill 覆盖它。 */
1102
+ let importKind = 'auto'
1098
1103
  /** confirmedSig 记「用户按下确认时的那套配置」;配置一变就失效,退回「确认注入」。 */
1099
1104
  let confirmedSig = ''
1100
1105
  /** modeMenuOpen 是模式下拉面板是否展开;每次重画都要记住,否则点一下就收。 */
@@ -1141,6 +1146,12 @@ pre.text {
1141
1146
  const inlineEntries = () => (Array.isArray(options.inline) ? options.inline : [])
1142
1147
  const findEntry = (id) => entries().find((e) => e.id === id) || inlineEntries().find((e) => e.id === id) || null
1143
1148
  const isEnabled = (id) => (options.enabled?.[id] !== undefined ? options.enabled[id] : findEntry(id)?.kind === 'persona')
1149
+ /** defaultPersona 是「现在最能顶上的人设」:内置底座优先,其次第一个可用的人设。 */
1150
+ const defaultPersona = () =>
1151
+ entries().find((e) => e.kind === 'persona' && e.default === true) ||
1152
+ entries().find((e) => e.kind === 'persona') ||
1153
+ inlineEntries().find((e) => e.kind !== 'skill') ||
1154
+ null
1144
1155
 
1145
1156
  // ---------- 与宿主说话 ----------
1146
1157
 
@@ -1157,11 +1168,18 @@ pre.text {
1157
1168
 
1158
1169
  async function flush() {
1159
1170
  if (!pendingSave || !bridge?.options?.set) return
1171
+ // 记住这一轮自己刚写下去的键:宿主回包只用来「补全它规范化的字段」,
1172
+ // 不许它把我们刚设的值盖回去——否则「选了模式又被换回」会反复发生。
1173
+ const sent = { ...(pendingSave || {}) }
1160
1174
  const body = { ...options }
1161
1175
  pendingSave = null
1162
1176
  try {
1163
1177
  const saved = await bridge.options.set(body)
1164
- if (saved && typeof saved === 'object') options = { ...body, ...saved }
1178
+ if (saved && typeof saved === 'object') {
1179
+ const merged = { ...body, ...saved }
1180
+ for (const key of Object.keys(sent)) merged[key] = body[key]
1181
+ options = merged
1182
+ }
1165
1183
  } catch (error) {
1166
1184
  say(`保存失败:${error?.message || error}`, 'bad')
1167
1185
  }
@@ -1374,8 +1392,9 @@ pre.text {
1374
1392
  const kind = KINDS[e.kind] || { label: e.kind }
1375
1393
  const kindCls = kindClass(e.kind)
1376
1394
  const inline = e.source?.root === 'inline' || e.meta?.format === 'inline'
1377
- // 只有复制进插件自己的 state/imports 的副本才谈得上「删副本」:来源目录里的原件不动。
1378
- const imported = Boolean(e.source?.root && /[\\/]state[\\/]imports\/?$/.test(e.source.root))
1395
+ // 只有复制进插件自己的 state/imports 的副本才谈得上「删副本」:原件不动。
1396
+ // root 可能是绝对路径(真机)也可能是相对路径(演示快照),所以不要求前导分隔符。
1397
+ const imported = Boolean(e.source?.root && /(^|[\\/])state[\\/]imports\/?$/.test(e.source.root))
1379
1398
  const enabled = isEnabled(e.id)
1380
1399
  const pinned = options.pinned?.[e.id]
1381
1400
  const history = Array.isArray(e.history) ? e.history : []
@@ -1424,18 +1443,53 @@ pre.text {
1424
1443
  type: 'button',
1425
1444
  class: 'danger',
1426
1445
  onclick: () => {
1446
+ // 删掉导入的条目时,指向它的引用也要一起清:否则 plan 会卡在 persona-missing,
1447
+ // 用户还得再点一次「改用」才能恢复注入。
1427
1448
  const kept = inlineEntries().filter((x) => x.id !== e.id)
1428
1449
  const enabledNext = { ...(options.enabled || {}) }
1429
1450
  delete enabledNext[e.id]
1430
- save({ inline: kept, enabled: enabledNext, persona: options.persona === e.id ? '' : options.persona }, '已从页面导入里删掉')
1451
+ const pinnedNext = { ...(options.pinned || {}) }
1452
+ delete pinnedNext[e.id]
1453
+ const fallback = kept.find((x) => x.kind !== 'skill')
1454
+ save({
1455
+ inline: kept,
1456
+ enabled: enabledNext,
1457
+ pinned: pinnedNext,
1458
+ persona: options.persona === e.id ? (fallback?.id || '') : options.persona,
1459
+ }, `已删除「${e.name}」`)
1431
1460
  if (selected === e.id) selected = ''
1461
+ render()
1462
+ },
1463
+ }, '删除导入'))
1464
+ // 类型选错时能就地改:重扫猜出来的类型不一定对,硬编码成「人设」更糟。
1465
+ actions.push(el('button', {
1466
+ type: 'button',
1467
+ class: 'quiet',
1468
+ onclick: () => {
1469
+ const nextKind = e.kind === 'skill' ? 'persona' : 'skill'
1470
+ const next = inlineEntries().map((x) => (x.id === e.id ? { ...x, kind: nextKind } : x))
1471
+ save({ inline: next }, `已改判为${nextKind === 'skill' ? '技能' : '人设'}`)
1472
+ render()
1432
1473
  },
1433
- }, '删除'))
1474
+ }, e.kind === 'skill' ? '改判为人设' : '改判为技能'))
1434
1475
  } else if (imported) {
1435
1476
  actions.push(el('button', {
1436
1477
  type: 'button',
1437
1478
  class: 'danger',
1438
- onclick: () => importRequest({ op: 'delete', path: e.source.rel }, `已请求删除「${e.name}」的副本(只删插件自己的 state/imports)`),
1479
+ onclick: () => {
1480
+ // 删副本同时把指向它的引用清掉:留着会让 plan 卡在 persona-missing。
1481
+ const enabledNext = { ...(options.enabled || {}) }
1482
+ delete enabledNext[e.id]
1483
+ const pinnedNext = { ...(options.pinned || {}) }
1484
+ delete pinnedNext[e.id]
1485
+ save({
1486
+ enabled: enabledNext,
1487
+ pinned: pinnedNext,
1488
+ persona: options.persona === e.id ? '' : options.persona,
1489
+ })
1490
+ importRequest({ op: 'delete', path: e.source.rel }, `已请求删除「${e.name}」的副本(只删插件自己的 state/imports)`)
1491
+ if (selected === e.id) selected = ''
1492
+ },
1439
1493
  }, '删除副本'))
1440
1494
  }
1441
1495
 
@@ -1586,7 +1640,6 @@ pre.text {
1586
1640
  $('inspect').hidden = !picked
1587
1641
  renderRejects()
1588
1642
  renderLast()
1589
- renderSources()
1590
1643
  }
1591
1644
 
1592
1645
  /** MODES 是模式下拉的全部取值:没有「跟随上游」这一档,模式必须自己选。 */
@@ -1630,10 +1683,19 @@ pre.text {
1630
1683
  if (plan.blockedCode === 'no-mode' || plan.blockedCode === 'mode-off') {
1631
1684
  fix.push(el('button', { type: 'button', class: 'primary', onclick: () => fixed({ mode: 'replace' }, '模式改为 replace') }, '用 replace 开始注入'))
1632
1685
  }
1633
- if (plan.blockedCode === 'no-persona' || plan.blockedCode === 'persona-missing') {
1686
+ // 旧人设被删掉后 options.persona 会一直指着它,卡在 persona-missing:
1687
+ // 这个问题点「去看人设」永远绕不出来,得给一个直接改掉它的动作。
1688
+ if (plan.blockedCode === 'persona-missing' && defaultPersona()) {
1689
+ const next = defaultPersona()
1634
1690
  fix.push(el('button', {
1635
1691
  type: 'button',
1636
1692
  class: 'primary',
1693
+ onclick: () => fixed({ persona: next.id }, `人设改为「${next.name}」`),
1694
+ }, `改用「${next.name}」`))
1695
+ }
1696
+ if (plan.blockedCode === 'no-persona' || plan.blockedCode === 'persona-missing') {
1697
+ fix.push(el('button', {
1698
+ type: 'button',
1637
1699
  onclick: () => { filter = 'persona'; query = ''; render() },
1638
1700
  }, '去看人设'))
1639
1701
  }
@@ -1641,7 +1703,7 @@ pre.text {
1641
1703
  fix.push(el('button', {
1642
1704
  type: 'button',
1643
1705
  class: 'primary',
1644
- onclick: () => { $('import-file')?.focus(); $('import-file')?.click?.() },
1706
+ onclick: () => { filter = 'persona'; query = ''; render() },
1645
1707
  }, '导入一份人设'))
1646
1708
  }
1647
1709
  }
@@ -1785,15 +1847,6 @@ pre.text {
1785
1847
  }, applied ? '已注入' : '确认注入')
1786
1848
  }
1787
1849
 
1788
- function renderSources() {
1789
- const el2 = $('sources')
1790
- if (!el2 || document.activeElement === el2) return
1791
- const list = Array.isArray(options.sources) && options.sources.length
1792
- ? options.sources
1793
- : (catalog?.sources || []).filter((s) => s.path && !/[\\/]state[\\/]imports\/?$/.test(s.path)).map((s) => s.path)
1794
- el2.value = list.join('\n')
1795
- }
1796
-
1797
1850
  // ---------- 动作 ----------
1798
1851
 
1799
1852
  function importRequest(req, note) {
@@ -1856,37 +1909,84 @@ pre.text {
1856
1909
  renderPlan()
1857
1910
  })
1858
1911
 
1859
- $('import-run').addEventListener('click', () => {
1860
- const path = $('import-path').value.trim()
1861
- if (!path) return say('先填一个文件路径', 'bad')
1862
- importRequest({ op: 'import', path }, '已请求导入')
1863
- $('import-path').value = ''
1912
+ // 导入分两步:先选文件(把路径填进输入框),再点「导入」才真的导入。
1913
+ // 一步到底容易误触:浏览器选完就导入,用户还没确认类型就落盘了。
1914
+ $('import-pick').addEventListener('click', () => {
1915
+ const input = document.createElement('input')
1916
+ input.type = 'file'
1917
+ input.accept = '.md,.markdown,.txt,.json,.zip'
1918
+ input.addEventListener('change', () => {
1919
+ const file = input.files?.[0]
1920
+ if (!file) return
1921
+ // 浏览器出于安全不暴露真实路径,只能拿到文件名。
1922
+ // 这一步先把名字填进去,让人看见选中了什么;真正导入走下面那条 inline 通道。
1923
+ $('import-path').value = file.name
1924
+ pendingFile = file
1925
+ say(`已选中「${file.name}」,再点一次「导入」就写入`, 'good')
1926
+ })
1927
+ input.click()
1864
1928
  })
1865
1929
 
1866
- $('import-file').addEventListener('change', async (e) => {
1867
- const file = e.target.files?.[0]
1868
- if (!file) return
1930
+ $('import-run').addEventListener('click', async () => {
1931
+ const typed = $('import-path').value.trim()
1932
+ // 手填的是绝对路径:交给后端复制(原文件不动,副本进 state/imports)。
1933
+ if (typed && !pendingFile) {
1934
+ importRequest({ op: 'import', path: typed, kind: importKind }, '已请求导入')
1935
+ $('import-path').value = ''
1936
+ return
1937
+ }
1938
+ const file = pendingFile
1939
+ if (!file) return say('先点「选择」挑一个文件,或在框里填绝对路径', 'bad')
1869
1940
  try {
1870
1941
  const raw = await file.text()
1871
1942
  if (raw.length > 64 * 1024) throw new Error('超过 64 KB:这么大的正文不该塞进 options')
1872
1943
  const id = (file.name.replace(/\.[^.]+$/, '').toLowerCase().replace(/[^a-z0-9._-]+/g, '-') || 'inline').slice(0, 48)
1873
1944
  const kept = inlineEntries().filter((x) => x.id !== id)
1874
- const body = raw.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '').trim()
1875
1945
  const fm = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/)
1946
+ const declared = fm?.[1]?.match(/^kind:\s*(persona|skill)\s*$/m)?.[1]
1876
1947
  const name = fm?.[1]?.match(/^name:\s*(.+)$/m)?.[1]?.replace(/^["']|["']$/g, '') || file.name.replace(/\.[^.]+$/, '')
1877
- save({ inline: [...kept, { id, name, kind: 'persona', text: body }] }, `已把「${name}」存进 options`)
1878
- e.target.value = ''
1948
+ const body = raw.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '').trim()
1949
+ // 类型的优先级:用户明确选的 > 文件自己写的 > 猜。
1950
+ const kind = importKind !== 'auto' ? importKind : declared || guessKind(body)
1951
+ save({ inline: [...kept, { id, name, kind, text: body }] }, `已导入「${name}」(${kind === 'skill' ? '技能' : '人设'})`)
1952
+ pendingFile = null
1953
+ $('import-path').value = ''
1954
+ refreshAfterImport()
1879
1955
  } catch (error) {
1880
1956
  say(`导入失败:${error?.message || error}`, 'bad')
1881
1957
  }
1882
1958
  })
1883
1959
 
1884
- const sources = $('sources-save')
1885
- sources?.addEventListener('click', () => {
1886
- const list = $('sources').value.split(/\r?\n/).map((s) => s.trim()).filter(Boolean)
1887
- save({ sources: list, refreshAt: Date.now() }, '来源目录已保存')
1888
- pollSnapshot('等待后端按新来源扫描…', 25)
1889
- })
1960
+ // 导入类型:三选一,选中项自己管自己的 aria-pressed。
1961
+ for (const chip of document.querySelectorAll('#import-kind .chip')) {
1962
+ chip.addEventListener('click', () => {
1963
+ importKind = chip.dataset.kind || 'auto'
1964
+ for (const other of document.querySelectorAll('#import-kind .chip')) {
1965
+ other.setAttribute('aria-pressed', other === chip ? 'true' : 'false')
1966
+ }
1967
+ })
1968
+ }
1969
+ }
1970
+
1971
+ /**
1972
+ * guessKind 猜一份 .md 是人设还是技能。
1973
+ *
1974
+ * 判据来自本插件自己的两种文件长相:人设是完整第二人称,通常带 `## 你是什么`/`你是谁`;
1975
+ * 技能是「某个领域的专家」,标题一般是 `# X专家`,正文多含命令与表格。
1976
+ */
1977
+ function guessKind(body) {
1978
+ const text = String(body || '')
1979
+ if (/^##\s*(你是什么|你是谁|你是谁?)/m.test(text)) return 'persona'
1980
+ if (/^(你是|你现在是)/m.test(text) && !/^#\s/m.test(text)) return 'persona'
1981
+ if (/^#\s/m.test(text) && /(\||命令|工具|参数)/.test(text)) return 'skill'
1982
+ return 'persona'
1983
+ }
1984
+
1985
+ /** refreshAfterImport 让新导入的条目立刻出现在列表里,并让后端按新 options 重扫。 */
1986
+ function refreshAfterImport() {
1987
+ save({ refreshAt: Date.now() })
1988
+ render()
1989
+ pollSnapshot('等后端按新导入重扫…', 20)
1890
1990
  }
1891
1991
 
1892
1992
  async function boot() {
package/tools/scan.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- // 离线清点:不装进 magpie、不开 magpie,也能把 purge 目录扫一遍并写出快照。
2
+ // 离线清点:不装进 magpie、不开 magpie,也能列出条目表并写出快照。
3
3
  //
4
- // node tools/scan.mjs # 用默认来源(~/.agent-purge、~/.magpie/purge)
5
- // node tools/scan.mjs --sources "D:\pa,D:\pb" --mode strict --persona anima
6
- // node tools/scan.mjs --json # 只把条目表打到 stdout,不写文件
4
+ // node tools/scan.mjs # 只清点包内内容 + 已导入的文件
5
+ // node tools/scan.mjs --import "D:\a.md" --mode strict --persona anima
6
+ // node tools/scan.mjs --json # 只把快照打到 stdout,不写文件
7
7
  //
8
8
  // 预览(preview/serve.mjs)用的就是它:同一条扫描路径,避免「预览一套、真跑另一套」。
9
9
  import { dirname, join } from 'node:path'
@@ -14,12 +14,15 @@ import { sync } from '../lib/state.mjs'
14
14
  const here = join(dirname(fileURLToPath(import.meta.url)), '..')
15
15
 
16
16
  function parseArgs(argv) {
17
- const out = { sources: [], mode: '', persona: '', json: false, force: true }
17
+ const out = { imports: [], mode: '', persona: '', json: false, force: true }
18
18
  for (let i = 0; i < argv.length; i++) {
19
19
  const a = argv[i]
20
20
  if (a === '--json') out.json = true
21
- else if (a === '--sources') out.sources.push(...String(argv[++i] || '').split(';').map((s) => s.replace(/^,+|,+$/g, '').trim()).filter(Boolean))
22
- else if (a === '--mode') out.mode = String(argv[++i] || '').trim()
21
+ else if (a === '--import') {
22
+ // 每个 --import 一个文件;用合成时间戳让它们都算「待处理的导入请求」。
23
+ const path = String(argv[++i] || '').trim()
24
+ if (path) out.imports.push({ op: 'import', path, at: out.imports.length + 1 })
25
+ } else if (a === '--mode') out.mode = String(argv[++i] || '').trim()
23
26
  else if (a === '--persona') out.persona = String(argv[++i] || '').trim()
24
27
  }
25
28
  return out
@@ -27,10 +30,9 @@ function parseArgs(argv) {
27
30
 
28
31
  const args = parseArgs(process.argv.slice(2))
29
32
  const options = {
30
- sources: args.sources,
31
33
  mode: args.mode || 'off',
32
34
  persona: args.persona,
33
- imports: [],
35
+ imports: args.imports,
34
36
  refreshAt: Date.now(),
35
37
  }
36
38
  const { catalog, snapshot } = sync(here, options, { force: args.force })