dsh-session-history 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -7,29 +7,46 @@ window.__ModuleLoader__.load({
7
7
  const API = './youxia-session-history/api';
8
8
 
9
9
  const css = `
10
- .yxsh{font-size:13px;line-height:1.5;color:var(--dsw-alias-label-primary,inherit);display:flex;flex-direction:column;gap:22px;max-width:820px}
10
+ .yxsh{width:100%;font-size:13px;line-height:1.55;color:var(--dsw-alias-label-primary,inherit);display:flex;flex-direction:column;gap:28px}
11
11
  .yxsh *{box-sizing:border-box}.yxsh button,.yxsh input,.yxsh select,.yxsh textarea{font:inherit;color:inherit}
12
- .yxsh h3{margin:0 0 6px;font-size:13px;font-weight:600}.yxsh-muted{color:var(--dsw-alias-label-tertiary,#888);font-size:12px}
13
- .yxsh-row{display:flex;align-items:center;gap:10px;min-width:0;flex-wrap:wrap}.yxsh-grow{flex:1;min-width:0}
14
- .yxsh-btn{appearance:none;cursor:pointer;border:0.5px solid var(--dsw-alias-border-l4,#8884);background:var(--dsw-alias-bg-layer-3,transparent);border-radius:var(--dsw-radius-md,8px);padding:3px 10px;font-size:12px;line-height:1.6;white-space:nowrap}
12
+ .yxsh h3{margin:0;font-size:14px;font-weight:600}.yxsh h4{margin:0 0 2px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary,#666)}
13
+ .yxsh-muted{color:var(--dsw-alias-label-tertiary,#888);font-size:12px}.yxsh-error{color:var(--dsw-alias-label-error,#e44848);font-size:12px;white-space:pre-wrap}
14
+ .yxsh-head{display:flex;align-items:center;gap:10px;margin-bottom:10px}.yxsh-grow{flex:1;min-width:0}
15
+ .yxsh-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
16
+ .yxsh-btn{appearance:none;cursor:pointer;border:0.5px solid var(--dsw-alias-border-l4,#8884);background:var(--dsw-alias-bg-layer-3,transparent);border-radius:var(--dsw-radius-md,8px);padding:3px 11px;font-size:12px;line-height:1.7;white-space:nowrap}
15
17
  .yxsh-btn:disabled{opacity:.5;cursor:default}.yxsh-btn.primary{background:var(--dsw-alias-interactive-bg-primary,#0A84FF);color:#fff;border-color:transparent}
16
- @media (hover:hover){.yxsh-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,#8882)}.yxsh-btn.primary:hover:not(:disabled){filter:brightness(1.08);background:var(--dsw-alias-interactive-bg-primary,#0A84FF)}}
17
- .yxsh-card{border:0.5px solid var(--dsw-alias-border-l2,#8883);border-radius:10px;overflow:hidden}
18
- .yxsh-agent{display:grid;grid-template-columns:minmax(120px,1.1fr) minmax(150px,1.4fr) minmax(170px,2fr) auto;gap:10px;align-items:center;padding:10px 12px;border-top:0.5px solid var(--dsw-alias-border-l2,#8883)}
18
+ .yxsh-link{appearance:none;border:0;background:none;padding:0;cursor:pointer;font-size:12px;color:var(--dsw-alias-label-tertiary,#888);text-decoration:underline;text-underline-offset:2px}
19
+ @media (hover:hover){.yxsh-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,#8882)}.yxsh-btn.primary:hover:not(:disabled){filter:brightness(1.08);background:var(--dsw-alias-interactive-bg-primary,#0A84FF)}.yxsh-link:hover{color:var(--dsw-alias-label-primary,inherit)}}
20
+ .yxsh-card{border:0.5px solid var(--dsw-alias-border-l2,#8883);border-radius:10px;background:var(--dsw-alias-bg-layer-2,transparent)}
21
+ .yxsh-home{padding:14px 16px;display:flex;flex-direction:column;gap:12px}
22
+ .yxsh-path{font-family:var(--dsw-font-mono,ui-monospace,monospace);font-size:13px;word-break:break-all}
23
+ .yxsh-stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px 18px;padding-top:12px;border-top:0.5px solid var(--dsw-alias-border-l2,#8883)}
24
+ .yxsh-stat span{display:block}.yxsh-stat b{font-weight:600;font-size:13px}
25
+ .yxsh-agent{display:grid;grid-template-columns:minmax(130px,1fr) minmax(220px,2.4fr) auto minmax(120px,auto);gap:4px 16px;align-items:center;padding:10px 14px;border-top:0.5px solid var(--dsw-alias-border-l2,#8883)}
19
26
  .yxsh-agent:first-child{border-top:0}.yxsh-agent b{font-weight:500}
20
- .yxsh-chip{display:inline-flex;align-items:center;gap:5px;border-radius:5px;padding:1px 7px;font-size:12px;background:var(--dsw-alias-bg-layer-4,#8881);color:var(--dsw-alias-label-secondary,#666);max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
21
- .yxsh-chip.ok{background:color-mix(in srgb,#34C759 15%,transparent);color:var(--dsw-alias-label-primary,inherit)}
22
- .yxsh-chip.bad{background:color-mix(in srgb,#FF3B30 14%,transparent);color:var(--dsw-alias-label-error,#e44848)}
23
- .yxsh-dot{width:7px;height:7px;border-radius:50%;background:currentColor;flex:none}.yxsh-chip.ok .yxsh-dot{background:#34C759}
24
- .yxsh-switch{display:inline-flex;align-items:center;gap:6px;cursor:pointer}.yxsh-switch input{margin:0}
25
- .yxsh-field{display:grid;grid-template-columns:200px 1fr;gap:12px;align-items:start;padding:9px 0;border-bottom:0.5px solid var(--dsw-alias-border-l2,#8883)}
26
- .yxsh-field:last-of-type{border-bottom:0}.yxsh-field label{padding-top:4px}
27
- .yxsh-input{height:30px;border:0.5px solid var(--dsw-alias-border-l4,#8884);background:var(--dsw-alias-bg-layer-3,transparent);border-radius:var(--dsw-radius-md,8px);padding:0 10px;min-width:0;width:100%;max-width:320px}
28
- .yxsh textarea.yxsh-input{height:64px;padding:6px 10px;resize:vertical;max-width:420px;font-family:var(--dsw-font-mono,ui-monospace,monospace);font-size:12px}
29
- .yxsh-error{color:var(--dsw-alias-label-error,#e44848);font-size:12px;white-space:pre-wrap}
30
- .yxsh-pre{margin:8px 0 0;padding:10px 12px;max-height:320px;overflow:auto;border-radius:8px;background:var(--dsw-alias-bg-layer-4,#8881);font-family:var(--dsw-font-mono,ui-monospace,monospace);font-size:11.5px;line-height:1.55;white-space:pre-wrap}
31
- .yxsh summary{cursor:pointer;font-weight:600}.yxsh code{font-family:var(--dsw-font-mono,ui-monospace,monospace);font-size:12px}
32
- @media (max-width:720px){.yxsh-agent{grid-template-columns:1fr 1fr}.yxsh-field{grid-template-columns:1fr}}
27
+ .yxsh-src{min-width:0}.yxsh-src .yxsh-muted{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
28
+ .yxsh-badge{display:inline-block;margin-left:6px;padding:0 5px;border-radius:4px;font-size:11px;line-height:17px;background:var(--dsw-alias-bg-layer-4,#8881);color:var(--dsw-alias-label-secondary,#666);vertical-align:1px}
29
+ .yxsh-chip{display:inline-flex;align-items:center;gap:6px;border-radius:5px;padding:1px 8px;font-size:12px;white-space:nowrap;justify-self:start}
30
+ .yxsh-chip i{width:7px;height:7px;border-radius:50%;flex:none;background:currentColor}
31
+ .yxsh-chip.ready{background:color-mix(in srgb,#34C759 14%,transparent)}.yxsh-chip.ready i{background:#34C759}
32
+ .yxsh-chip.missing{background:color-mix(in srgb,#FF9500 15%,transparent)}.yxsh-chip.missing i{background:#FF9500}
33
+ .yxsh-chip.conflict{background:color-mix(in srgb,#FF3B30 14%,transparent);color:var(--dsw-alias-label-error,#e44848)}
34
+ .yxsh-chip.nodir{background:var(--dsw-alias-bg-layer-4,#8881);color:var(--dsw-alias-label-tertiary,#888)}.yxsh-chip.nodir i{opacity:.5}
35
+ .yxsh-switch{display:inline-flex;align-items:center;gap:6px;cursor:pointer;white-space:nowrap}.yxsh-switch input{margin:0}
36
+ .yxsh-access{margin-top:12px;padding:12px 14px;display:flex;flex-direction:column;gap:10px}
37
+ .yxsh-item{display:flex;align-items:flex-start;gap:12px}.yxsh-item>div{flex:1;min-width:0}
38
+ .yxsh code{font-family:var(--dsw-font-mono,ui-monospace,monospace);font-size:12px}
39
+ .yxsh-notes{margin-top:8px;display:flex;flex-direction:column;gap:2px}
40
+ .yxsh-form{margin-top:12px;padding:14px 16px;display:grid;grid-template-columns:150px minmax(0,1fr);gap:10px 14px;align-items:start}
41
+ .yxsh-form label{padding-top:5px}.yxsh-form .full{grid-column:1/-1}
42
+ .yxsh-input{height:30px;border:0.5px solid var(--dsw-alias-border-l4,#8884);background:var(--dsw-alias-bg-layer-3,transparent);border-radius:var(--dsw-radius-md,8px);padding:0 10px;width:100%;max-width:440px;min-width:0}
43
+ .yxsh textarea.yxsh-input{height:60px;padding:6px 10px;resize:vertical;font-family:var(--dsw-font-mono,ui-monospace,monospace);font-size:12px}
44
+ .yxsh-group{padding:4px 0 6px}.yxsh-group+.yxsh-group{border-top:0.5px solid var(--dsw-alias-border-l2,#8883);padding-top:12px}
45
+ .yxsh-field{display:grid;grid-template-columns:190px minmax(0,1fr);gap:4px 14px;align-items:start;padding:7px 0}
46
+ .yxsh-field label{padding-top:5px}
47
+ .yxsh-pre{margin:10px 0 0;padding:12px 14px;max-height:360px;overflow:auto;border-radius:8px;background:var(--dsw-alias-bg-layer-4,#8881);font-family:var(--dsw-font-mono,ui-monospace,monospace);font-size:11.5px;line-height:1.6;white-space:pre-wrap}
48
+ .yxsh summary{cursor:pointer;font-size:14px;font-weight:600}
49
+ @media (max-width:760px){.yxsh-agent{grid-template-columns:1fr auto}.yxsh-field,.yxsh-form{grid-template-columns:1fr}.yxsh-form label{padding-top:0}}
33
50
  `;
34
51
 
35
52
  function source(initial) {
@@ -39,33 +56,29 @@ window.__ModuleLoader__.load({
39
56
  set(next) { value = { ...value, ...next }; for (const fn of listeners) fn(); } };
40
57
  }
41
58
 
42
- function fmtRun(last) {
43
- if (!last) return '尚未整理过';
44
- const when = String(last.run || '').replace('T', ' ').slice(0, 16);
45
- const bad = Object.entries(last.agents || {}).filter(([, r]) => !r.ok).map(([k]) => k);
46
- return `${when} · ${(Number(last.ms || 0) / 1000).toFixed(1)} 秒 · ${last.index?.sessions ?? '?'} 个会话` + (bad.length ? ` · 出错:${bad.join('、')}` : '');
59
+ const pad = n => String(n).padStart(2, '0');
60
+ function when(iso) {
61
+ if (!iso) return '尚未整理';
62
+ const [date, time] = [iso.slice(0, 10), iso.slice(11, 16)];
63
+ const d = new Date(), today = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
64
+ const y = new Date(d.getTime() - 86400000), yesterday = `${y.getFullYear()}-${pad(y.getMonth() + 1)}-${pad(y.getDate())}`;
65
+ return (date === today ? '今天 ' : date === yesterday ? '昨天 ' : date.slice(5) + ' ') + time;
47
66
  }
67
+ const num = n => Number(n || 0).toLocaleString('zh-CN');
48
68
 
49
- function skillChip(agent) {
50
- if (agent.visible) return h('span', { className: 'yxsh-chip ok', title: agent.via }, h('span', { className: 'yxsh-dot' }), `技能可用 · 经 ${agent.via}`);
51
- if (agent.conflict) return h('span', { className: 'yxsh-chip bad', title: agent.conflict.path }, `冲突:${agent.conflict.path}`);
52
- return h('span', { className: 'yxsh-chip' }, '技能未接入');
53
- }
54
-
55
- function sourceText(agent, last) {
56
- if (!agent.installed) return h('span', { className: 'yxsh-muted' }, '本机未检测到');
57
- const run = last?.agents?.[agent.folder];
58
- if (!agent.enabled) return h('span', { className: 'yxsh-muted' }, '已检测到,未整理');
59
- if (!run) return h('span', { className: 'yxsh-muted' }, '已检测到,待整理');
60
- return run.ok ? h('span', null, `${run.files} 个会话文件 · ${run.days} 天日志`) : h('span', { className: 'yxsh-error' }, `出错:${run.error}`);
61
- }
69
+ const STATE = {
70
+ ready: ['技能已生效', a => `经 ${a.via}`],
71
+ missing: ['技能未生效', () => '见下方「技能接入」'],
72
+ conflict: ['技能冲突', a => `${a.conflict?.path} 已有同名的其他内容`],
73
+ nodir: ['不接入技能', () => '没有设置技能目录,只收录会话'],
74
+ };
62
75
 
63
76
  return {
64
77
  inject: ['slots'],
65
78
  apply(ctx) {
66
79
  let alive = true;
67
80
  const state = source({ data: null, loading: true, error: '', pending: '' });
68
- const useState = () => React.useSyncExternalStore(state.subscribe, state.getSnapshot, state.getSnapshot);
81
+ const useStore = () => React.useSyncExternalStore(state.subscribe, state.getSnapshot, state.getSnapshot);
69
82
 
70
83
  async function api(command) {
71
84
  const response = await fetch(API, { credentials: 'same-origin', cache: 'no-store',
@@ -86,88 +99,185 @@ window.__ModuleLoader__.load({
86
99
  finally { if (alive) state.set({ pending: '' }); }
87
100
  }
88
101
 
102
+ function Home({ data, pending }) {
103
+ const last = data.last, bad = Object.entries(last?.agents || {}).filter(([, r]) => !r.ok).map(([k]) => k);
104
+ const busy = pending === 'refresh' || data.running;
105
+ return h('section', null,
106
+ h('div', { className: 'yxsh-head' }, h('h3', { className: 'yxsh-grow' }, '数据目录'),
107
+ h('button', { className: 'yxsh-btn', onClick: () => run({ op: 'open' }, 'open'), disabled: !!pending }, '打开'),
108
+ h('button', { className: 'yxsh-btn primary', onClick: () => run({ op: 'refresh' }, 'refresh'), disabled: !!pending || data.running }, busy ? '整理中…' : '立即整理')),
109
+ h('div', { className: 'yxsh-card yxsh-home' },
110
+ h('div', null, h('div', { className: 'yxsh-path' }, data.home),
111
+ h('div', { className: 'yxsh-muted' }, '日志、索引与设置都在这里,与插件分开存放,卸载或更新插件不受影响。')),
112
+ h('div', { className: 'yxsh-stats' },
113
+ h('div', { className: 'yxsh-stat' }, h('span', { className: 'yxsh-muted' }, '最近整理'),
114
+ h('b', null, when(last?.run)), last ? h('span', { className: 'yxsh-muted' }, `用时 ${(Number(last.ms || 0) / 1000).toFixed(1)} 秒`) : null),
115
+ h('div', { className: 'yxsh-stat' }, h('span', { className: 'yxsh-muted' }, '会话'), h('b', null, last?.index ? num(last.index.sessions) : '—'),
116
+ h('span', { className: 'yxsh-muted' }, last?.index ? `${num(last.index.files)} 份日志` : '整理后生成')),
117
+ h('div', { className: 'yxsh-stat' }, h('span', { className: 'yxsh-muted' }, '状态'),
118
+ bad.length ? h('b', { className: 'yxsh-error' }, `${bad.join('、')} 出错`) : h('b', null, last ? '正常' : '等待首次整理'),
119
+ h('span', { className: 'yxsh-muted' }, data.config.refreshMinutes ? `定时:${({ 30: '每 30 分钟', 60: '每小时整点', 120: '每 2 小时', 360: '每 6 小时' })[data.config.refreshMinutes] || `每 ${data.config.refreshMinutes} 分钟`}` : '定时整理已关闭')))));
120
+ }
121
+
122
+ function AgentRow({ a, pending }) {
123
+ const [label, hint] = STATE[a.state];
124
+ const run_ = a.run;
125
+ return h('div', { className: 'yxsh-agent' },
126
+ h('div', null, h('b', null, a.name), a.custom ? h('span', { className: 'yxsh-badge' }, '自定义') : null,
127
+ a.experimental && !a.custom ? h('span', { className: 'yxsh-badge', title: '会话格式按其公开代码推断,尚未用真实会话验证' }, '实验性') : null),
128
+ h('div', { className: 'yxsh-src' },
129
+ !a.enabled ? h('div', null, '未收录') : !run_ ? h('div', null, '待整理')
130
+ : run_.ok ? h('div', null, `${num(run_.files)} 个会话文件 · ${num(run_.days)} 天日志`) : h('div', { className: 'yxsh-error' }, `整理出错:${run_.error}`),
131
+ h('div', { className: 'yxsh-muted', title: a.sessions }, a.sessions)),
132
+ h('label', { className: 'yxsh-switch yxsh-muted', title: '关闭后不再整理它的新会话,已有日志照常检索' },
133
+ h('input', { type: 'checkbox', checked: a.enabled, disabled: !!pending, onChange: e => run({ op: 'enable', agent: a.id, enabled: e.target.checked }, 'enable') }), '收录'),
134
+ h('div', null, h('span', { className: `yxsh-chip ${a.state}`, title: [hint(a), ...a.dirs.map(d => `读取 ${d.display}`)].join('\n') }, h('i'), label),
135
+ a.custom ? h('div', null, h('button', { className: 'yxsh-link', disabled: !!pending, onClick: () => {
136
+ if (globalThis.confirm?.(`移除「${a.name}」?已整理的日志会保留并照常检索。`) !== false) run({ op: 'removeCustom', id: a.id }, 'remove');
137
+ } }, '移除')) : null));
138
+ }
139
+
140
+ function Access({ data, pending }) {
141
+ const { targets, links, conflicts } = data;
142
+ const items = [];
143
+ for (const t of targets) {
144
+ const note = data.agents.find(a => t.agents.includes(a.name) && a.note)?.note;
145
+ items.push(h('div', { className: 'yxsh-item', key: 't' + t.key },
146
+ h('div', null,
147
+ h('div', null, h('b', null, t.agents.join('、')), ' 的技能尚未生效'),
148
+ h('div', { className: 'yxsh-muted' }, t.create ? '将新建技能目录 ' : '在它们读取的技能目录 ', h('code', null, t.display),
149
+ t.realDisplay ? ['(实际位置 ', h('code', { key: 'r' }, t.realDisplay), ')'] : null, t.realDisplay ? '里建一条指向数据目录的软链即可。' : ' 里建一条指向数据目录的软链即可。',
150
+ note ? ` 注意:${note}。` : '')),
151
+ h('button', { className: 'yxsh-btn primary', disabled: !!pending, onClick: () => run({ op: 'linkTarget', key: t.key }, 'link') }, '建软链')));
152
+ }
153
+ for (const l of links) items.push(h('div', { className: 'yxsh-item', key: 'l' + l.key },
154
+ h('div', null,
155
+ h('div', null, '已接入:', h('code', null, l.entry), ' → 数据目录'),
156
+ h('div', { className: 'yxsh-muted' }, `${l.agents.join('、')} 经此读取本技能`)),
157
+ h('button', { className: 'yxsh-btn', disabled: !!pending, title: `移除后 ${l.agents.join('、')} 都将看不到本技能`,
158
+ onClick: () => { if (globalThis.confirm?.(`移除这条软链?${l.agents.join('、')} 将看不到本技能。数据不受影响。`) !== false) run({ op: 'unlinkTarget', key: l.key }, 'unlink'); } }, '移除')));
159
+ for (const c of conflicts) items.push(h('div', { className: 'yxsh-item', key: 'c' + c.path },
160
+ h('div', { className: 'yxsh-error' }, `${c.agent}:${c.path} 已有同名的${c.state === 'copy' ? '旧版副本' : c.state === 'broken' ? '失效软链' : '其他文件'},未覆盖。移走后即可接入。`)));
161
+ return h('div', { className: 'yxsh-card yxsh-access' },
162
+ h('div', { className: 'yxsh-row' }, h('h4', { className: 'yxsh-grow' }, '技能接入'),
163
+ targets.length > 1 ? h('button', { className: 'yxsh-btn primary', disabled: !!pending, onClick: () => run({ op: 'linkAll' }, 'link') }, '全部接入') : null),
164
+ items.length ? items : h('div', { className: 'yxsh-muted' }, '检测到的 agent 都已能使用本技能。'),
165
+ h('div', { className: 'yxsh-muted' }, '技能不拷副本:数据目录本身就是技能文件夹,在各 agent 读取的技能目录里放一条指向它的软链即可。几家共用同一个技能目录时只需一条;按钮只在有 agent 尚未生效时出现。'));
166
+ }
167
+
168
+ function AddAgent({ data, pending }) {
169
+ const [open, setOpen] = React.useState(false);
170
+ const [form, setForm] = React.useState({ name: '', format: 'claude', sessions: '', skills: '' });
171
+ const [check, setCheck] = React.useState(null);
172
+ const fmt = data.formats.find(f => f.id === form.format) || data.formats[0];
173
+ const set = patch => { setForm({ ...form, ...patch }); if ('sessions' in patch || 'format' in patch) setCheck(null); };
174
+ const probe = async () => {
175
+ try { const r = await api({ op: 'probe', format: form.format, sessions: form.sessions }); setCheck(r.probe); }
176
+ catch (error) { setCheck({ error: error.message }); }
177
+ };
178
+ const add = async () => { if (await run({ op: 'addCustom', ...form }, 'add')) { setOpen(false); setForm({ name: '', format: 'claude', sessions: '', skills: '' }); setCheck(null); } };
179
+ if (!open) return h('div', { style: { marginTop: '10px' } }, h('button', { className: 'yxsh-btn', onClick: () => setOpen(true) }, '+ 添加其他 agent'));
180
+ const verdict = !check ? null : check.error ? h('span', { className: 'yxsh-error' }, check.error)
181
+ : !check.exists ? h('span', { className: 'yxsh-error' }, `目录不存在:${check.path}`)
182
+ : check.files && check.turns ? h('span', null, `找到 ${num(check.files)} 个会话文件,格式对得上。如 `, h('code', null, check.sample))
183
+ : check.files ? h('span', { className: 'yxsh-error' }, `找到 ${num(check.files)} 个文件,但按「${fmt.label}」解析不出对话,格式可能选错了。`)
184
+ : h('span', { className: 'yxsh-error' }, `目录存在,但按「${fmt.label}」没找到会话文件。请确认选的是 ${fmt.dir} 这一层、格式选对了。`);
185
+ return h('div', { className: 'yxsh-card yxsh-form' },
186
+ h('div', { className: 'full' }, h('h4', null, '添加其他 agent'),
187
+ h('div', { className: 'yxsh-muted' }, '用于本插件未内置、但会话记录格式与上面某一家相同的 agent,或同一 agent 的另一套配置目录(多开、多账号)。添加后与内置 agent 一样整理、检索,填了技能目录也可接入技能。')),
188
+ h('label', null, '名称'), h('div', null, h('input', { className: 'yxsh-input', value: form.name, maxLength: 24, placeholder: '如 Qoder CLI', onChange: e => set({ name: e.target.value }) }),
189
+ h('div', { className: 'yxsh-muted' }, '日志里助手发言和检索时 --agent 用这个名字。')),
190
+ h('label', null, '会话格式'), h('div', null, h('select', { className: 'yxsh-input', value: form.format, onChange: e => set({ format: e.target.value }) },
191
+ ...data.formats.map(f => h('option', { key: f.id, value: f.id }, f.label))),
192
+ h('div', { className: 'yxsh-muted' }, '它的会话记录与哪一家的格式相同。')),
193
+ h('label', null, '会话目录'), h('div', null, h('input', { className: 'yxsh-input', value: form.sessions, placeholder: `…/${fmt.dir}`, onChange: e => set({ sessions: e.target.value }) }),
194
+ h('div', { className: 'yxsh-muted' }, '填存放会话记录的 ', h('code', null, fmt.dir), ' 这一层,里面是 ', h('code', null, fmt.layout), '。例:', fmt.example, '。'),
195
+ verdict ? h('div', { style: { marginTop: '4px', fontSize: '12px' } }, verdict) : null),
196
+ h('label', null, '技能目录(可选)'), h('div', null, h('input', { className: 'yxsh-input', value: form.skills, placeholder: '如 ~/.qoder-cn/skills', onChange: e => set({ skills: e.target.value }) }),
197
+ h('div', { className: 'yxsh-muted' }, '这个 agent 读取技能的文件夹。填了才会出现在「技能接入」里;留空则只收录它的会话。')),
198
+ h('div', { className: 'full yxsh-row' },
199
+ h('button', { className: 'yxsh-btn', disabled: !form.sessions.trim(), onClick: probe }, '检查目录'),
200
+ h('button', { className: 'yxsh-btn primary', disabled: !!pending || !form.name.trim() || !form.sessions.trim(), onClick: add }, pending === 'add' ? '添加中…' : '添加'),
201
+ h('button', { className: 'yxsh-link', onClick: () => { setOpen(false); setCheck(null); } }, '取消')));
202
+ }
203
+
89
204
  function Agents({ data, pending }) {
90
- const missing = data.agents.filter(a => a.installed && !a.visible && !a.conflict);
205
+ const live = data.agents, ready = live.filter(a => a.state === 'ready').length, linkable = live.filter(a => a.state !== 'nodir').length;
91
206
  return h('section', null,
92
- h('div', { className: 'yxsh-row' },
93
- h('h3', { className: 'yxsh-grow' }, 'Agent 与技能'),
94
- missing.length ? h('button', { className: 'yxsh-btn primary', disabled: !!pending, onClick: () => run({ op: 'linkAll' }, 'link') },
95
- pending === 'link' ? '接入中…' : `一键接入(${missing.map(a => a.name).join('、')})`) : null),
96
- h('p', { className: 'yxsh-muted', style: { margin: '0 0 8px' } },
97
- '技能不拷副本:在各 agent 读取的技能目录里放一个指向数据目录的软链 ', h('code', null, 'session-history'), '。按真实路径识别共用目录——几家共用的目录只需一条软链。'),
98
- h('div', { className: 'yxsh-card' }, ...data.agents.map(a => {
99
- const shared = [...new Set(a.dirs.flatMap(d => d.sharedWith || []))];
100
- const own = a.dirs.some(d => d.state === 'link');
101
- return h('div', { className: 'yxsh-agent', key: a.id },
102
- h('div', null, h('b', null, a.name), shared.length ? h('div', { className: 'yxsh-muted' }, `与 ${shared.join('、')} 共用技能目录`) : null),
103
- h('div', null, sourceText(a, data.last),
104
- a.installed ? h('div', null, h('label', { className: 'yxsh-switch yxsh-muted' },
105
- h('input', { type: 'checkbox', checked: a.enabled, disabled: !!pending, onChange: e => run({ op: 'enable', agent: a.id, enabled: e.target.checked }, 'enable') }), '整理此 agent 的会话')) : null),
106
- h('div', { style: { minWidth: 0 } }, skillChip(a),
107
- h('div', { className: 'yxsh-muted', title: a.dirs.map(d => d.display).join('\n') }, '读取 ', a.dirs.map(d => d.display).join('、'))),
108
- h('div', null,
109
- a.visible ? (own ? h('button', { className: 'yxsh-btn', disabled: !!pending, title: shared.length ? `共用该目录的 ${shared.join('、')} 也会一起看不到` : '',
110
- onClick: () => run({ op: 'unlink', agent: a.id }, 'unlink') }, '移除软链') : null)
111
- : a.conflict ? null
112
- : h('button', { className: 'yxsh-btn', disabled: !!pending, onClick: () => run({ op: 'link', agent: a.id }, 'link') }, '创建软链')));
113
- })),
114
- data.legacy.length ? h('p', { className: 'yxsh-muted', style: { margin: '6px 0 0' } }, `已停用来源的旧日志:${data.legacy.join('、')}(照常检索)`) : null);
207
+ h('div', { className: 'yxsh-head' }, h('h3', { className: 'yxsh-grow' }, 'Agents'),
208
+ linkable ? h('span', { className: 'yxsh-muted' }, `技能已生效 ${ready}/${linkable}`) : null),
209
+ live.length ? h('div', { className: 'yxsh-card' }, ...live.map(a => h(AgentRow, { a, pending, key: a.id })))
210
+ : h('div', { className: 'yxsh-card', style: { padding: '14px' } }, h('span', { className: 'yxsh-muted' }, '还没有检测到支持的 agent。装好后产生过对话就会出现在这里;也可以在下面手动添加。')),
211
+ live.length ? h(Access, { data, pending }) : null,
212
+ h('div', { className: 'yxsh-notes' },
213
+ data.undetected.length ? h('div', { className: 'yxsh-muted' }, `未检测到:${data.undetected.join('、')}(装好后自动出现)`) : null,
214
+ data.legacy.length ? h('div', { className: 'yxsh-muted' }, `仅有旧日志:${data.legacy.join('、')}(照常检索)`) : null),
215
+ h(AddAgent, { data, pending }));
115
216
  }
116
217
 
117
218
  function Settings({ data, pending }) {
118
219
  const c = data.config;
119
- const [draft, setDraft] = React.useState(null);
120
- const d = draft || { userLabel: c.userLabel, timezone: c.timezone, dayStartHour: c.dayStartHour, refreshMinutes: c.refreshMinutes,
220
+ const initial = { userLabel: c.userLabel, timezone: c.timezone, dayStartHour: c.dayStartHour, refreshMinutes: c.refreshMinutes,
121
221
  staleMinutes: c.staleMinutes, memoryHints: c.memoryHints, gitSnapshots: c.gitSnapshots, excludeCwds: (c.excludeCwds || []).join('\n') };
222
+ const [draft, setDraft] = React.useState(null);
223
+ const d = draft || initial;
122
224
  const set = patch => setDraft({ ...d, ...patch });
123
- const field = (label, control, hint) => h('div', { className: 'yxsh-field' }, h('label', null, label), h('div', null, control, hint ? h('div', { className: 'yxsh-muted' }, hint) : null));
225
+ const field = (label, control, hint) => h('div', { className: 'yxsh-field' }, h('label', null, label),
226
+ h('div', null, control, hint ? h('div', { className: 'yxsh-muted' }, hint) : null));
124
227
  const select = (value, options, onChange) => h('select', { className: 'yxsh-input', value, onChange: e => onChange(Number(e.target.value)) },
125
228
  ...options.map(([v, text]) => h('option', { key: v, value: v }, text)));
229
+ const check = (value, text, onChange) => h('label', { className: 'yxsh-switch' }, h('input', { type: 'checkbox', checked: value, onChange: e => onChange(e.target.checked) }), text);
126
230
  const save = async () => {
127
- const ok = await run({ op: 'config', patch: { ...d, excludeCwds: d.excludeCwds.split('\n').map(s => s.trim()).filter(Boolean) } }, 'config');
128
- if (ok) setDraft(null);
231
+ if (await run({ op: 'config', patch: { ...d, excludeCwds: d.excludeCwds.split('\n').map(x => x.trim()).filter(Boolean) } }, 'config')) setDraft(null);
129
232
  };
130
233
  return h('section', null,
131
- h('h3', null, '设置'),
132
- field('日志里用户的称呼', h('input', { className: 'yxsh-input', value: d.userLabel, maxLength: 12, onChange: e => set({ userLabel: e.target.value }) }),
133
- '只影响此后新整理的发言标题;旧日志不改。'),
134
- field('定时整理(DSH 运行时)', select(d.refreshMinutes, [[0, '关闭'], [30, '每 30 分钟'], [60, '每小时整点'], [120, '每 2 小时'], [360, '每 6 小时']], v => set({ refreshMinutes: v })),
135
- '整理在子进程里跑,只重读变过的会话文件。'),
136
- field('检索前自动补整理', select(d.staleMinutes, [[0, '关闭'], [10, '距上次超过 10 分钟'], [30, '距上次超过 30 分钟'], [60, '距上次超过 1 小时']], v => set({ staleMinutes: v })),
137
- 'DSH 没开时,别的 agent 检索也能拿到较新的对话。'),
138
- field('日界', select(d.dayStartHour, Array.from({ length: 24 }, (_, i) => [i, `${i} 点`]), v => set({ dayStartHour: v })), '这个钟点之前的对话算前一天。'),
139
- field('时区', h('input', { className: 'yxsh-input', value: d.timezone, placeholder: '留空跟随系统;或 +08:00、Asia/Shanghai', onChange: e => set({ timezone: e.target.value }) })),
140
- field('检索附 Claude Code 记忆', h('label', { className: 'yxsh-switch' }, h('input', { type: 'checkbox', checked: d.memoryHints, onChange: e => set({ memoryHints: e.target.checked }) }), '对题时列至多 2 条记忆的文件名与描述')),
141
- field('日志 Git 快照', h('label', { className: 'yxsh-switch' }, h('input', { type: 'checkbox', checked: d.gitSnapshots, onChange: e => set({ gitSnapshots: e.target.checked }) }), '每次整理后把 logs/ 提交一次'),
142
- data.git ? '数据目录已是 Git 仓库。' : '开启时在数据目录建 Git 仓库(只收 logs/)。'),
143
- field('不收的工作目录', h('textarea', { className: 'yxsh-input', value: d.excludeCwds, placeholder: '每行一个,如 ~/scratch', onChange: e => set({ excludeCwds: e.target.value }) }),
144
- '临时目录(/tmp 等)本就不收。'),
145
- h('div', { className: 'yxsh-row', style: { paddingTop: '10px' } },
146
- h('button', { className: 'yxsh-btn primary', disabled: !draft || !!pending, onClick: save }, pending === 'config' ? '保存中…' : '保存'),
147
- draft ? h('button', { className: 'yxsh-btn', disabled: !!pending, onClick: () => setDraft(null) }, '还原') : null));
234
+ h('div', { className: 'yxsh-head' }, h('h3', { className: 'yxsh-grow' }, '设置'),
235
+ draft ? h('button', { className: 'yxsh-btn', disabled: !!pending, onClick: () => setDraft(null) }, '还原') : null,
236
+ h('button', { className: 'yxsh-btn primary', disabled: !draft || !!pending, onClick: save }, pending === 'config' ? '保存中…' : '保存')),
237
+ h('div', { className: 'yxsh-card', style: { padding: '6px 16px' } },
238
+ h('div', { className: 'yxsh-group' }, h('h4', null, '整理'),
239
+ field('定时整理', select(d.refreshMinutes, [[0, '关闭'], [30, '每 30 分钟'], [60, '每小时整点'], [120, '每 2 小时'], [360, '每 6 小时']], v => set({ refreshMinutes: v })),
240
+ 'DSH 开着时在后台整理,只重读有变化的会话文件,通常一两秒。'),
241
+ field('检索前补整理', select(d.staleMinutes, [[0, '关闭'], [10, '距上次超过 10 分钟'], [30, '距上次超过 30 分钟'], [60, '距上次超过 1 小时']], v => set({ staleMinutes: v })),
242
+ 'DSH 没开时也能查到较新的对话:任何 agent 检索前,若距上次整理超过所选时长,先补一次。')),
243
+ h('div', { className: 'yxsh-group' }, h('h4', null, '日志'),
244
+ field('你的发言标题', h('input', { className: 'yxsh-input', value: d.userLabel, maxLength: 12, onChange: e => set({ userLabel: e.target.value }) }),
245
+ `日志里你的发言显示为「🧑 ${d.userLabel || '用户'}」。只影响此后整理出的内容,检索新旧写法都认。`),
246
+ field('日界', select(d.dayStartHour, Array.from({ length: 24 }, (_, i) => [i, `${i}:00`]), v => set({ dayStartHour: v })),
247
+ '此时刻之前的对话归入前一天的日志,熬夜的对话不会被拆到两天。'),
248
+ field('时区', h('input', { className: 'yxsh-input', value: d.timezone, placeholder: '跟随系统', onChange: e => set({ timezone: e.target.value }) }),
249
+ '一般留空。可填 +08:00 或 Asia/Shanghai。'),
250
+ field('不收录的工作目录', h('textarea', { className: 'yxsh-input', value: d.excludeCwds, placeholder: '每行一个,如 ~/scratch', onChange: e => set({ excludeCwds: e.target.value }) }),
251
+ '在这些目录里进行的会话不整理。临时目录本就不收。')),
252
+ h('div', { className: 'yxsh-group' }, h('h4', null, '检索'),
253
+ field('Claude Code 记忆', check(d.memoryHints, '检索时附上对题的记忆', v => set({ memoryHints: v })),
254
+ '列出至多 2 条相关记忆的文件名与描述,供 agent 先读这些整理过的结论。')),
255
+ h('div', { className: 'yxsh-group' }, h('h4', null, '备份'),
256
+ field('Git 快照', check(d.gitSnapshots, '每次整理后提交一次日志', v => set({ gitSnapshots: v })),
257
+ data.git ? '数据目录已是 Git 仓库,只提交 logs/。' : '开启时会在数据目录初始化 Git 仓库(只收 logs/);需要装有 Git。'))));
148
258
  }
149
259
 
150
260
  function Panel({ view }) {
151
- const s = useState();
152
- React.useEffect(() => { load(); }, []);
261
+ const s = useStore();
262
+ const busy = !!(s.data?.running || s.pending === 'refresh');
263
+ // 打开期间定时重读:后台定时整理、别的 agent 检索前补整理都会改状态;整理进行中读得更勤。
264
+ React.useEffect(() => {
265
+ load();
266
+ const timer = setInterval(() => { if (!state.getSnapshot().pending) load(); }, busy ? 3000 : 15000);
267
+ return () => clearInterval(timer);
268
+ }, [busy]);
153
269
  if (view && view !== 'page') return null;
154
270
  if (s.loading && !s.data) return h('div', { className: 'yxsh yxsh-muted' }, h('style', null, css), '读取中…');
155
271
  if (!s.data) return h('div', { className: 'yxsh' }, h('style', null, css), h('p', { className: 'yxsh-error' }, s.error || '读取失败'),
156
272
  h('button', { className: 'yxsh-btn', onClick: load }, '重试'));
157
273
  const data = s.data;
158
274
  return h('div', { className: 'yxsh' }, h('style', null, css),
159
- h('section', null,
160
- h('div', { className: 'yxsh-row' },
161
- h('div', { className: 'yxsh-grow' },
162
- h('div', null, '数据目录 ', h('code', null, data.home), h('span', { className: 'yxsh-muted' }, '(日志、索引、设置都在这里,与插件分开存放:卸载、更新、重装都不动它)')),
163
- h('div', { className: 'yxsh-muted' }, '最近整理:', fmtRun(data.last))),
164
- h('button', { className: 'yxsh-btn', onClick: () => run({ op: 'open' }, 'open'), disabled: !!s.pending }, '打开目录'),
165
- h('button', { className: 'yxsh-btn primary', onClick: () => run({ op: 'refresh' }, 'refresh'), disabled: !!s.pending || data.running },
166
- s.pending === 'refresh' || data.running ? '整理中…' : '立即整理')),
167
- s.error ? h('p', { className: 'yxsh-error', role: 'alert' }, s.error) : null),
275
+ s.error ? h('div', { className: 'yxsh-error', role: 'alert' }, s.error) : null,
276
+ h(Home, { data, pending: s.pending }),
168
277
  h(Agents, { data, pending: s.pending }),
169
278
  h(Settings, { data, pending: s.pending, key: JSON.stringify(data.config) }),
170
- h('section', null, h('details', null, h('summary', null, 'SKILL.md(按本机 agent 自动生成)'),
279
+ h('section', null, h('details', null, h('summary', null, 'SKILL.md'),
280
+ h('div', { className: 'yxsh-muted', style: { marginTop: '6px' } }, '按检测到的 agent 自动生成,各 agent 读的就是这一份。'),
171
281
  h('pre', { className: 'yxsh-pre' }, data.skill))));
172
282
  }
173
283
 
package/icon.svg CHANGED
@@ -1,9 +1,7 @@
1
1
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none">
2
- <circle cx="32" cy="32" r="28" fill="#4F46E5"/>
3
- <path d="M19.5 17H44.5A4.5 4.5 0 0 1 49 21.5V37A4.5 4.5 0 0 1 44.5 41.5H31.5L24 47.5V41.5H19.5A4.5 4.5 0 0 1 15 37V21.5A4.5 4.5 0 0 1 19.5 17Z" stroke="#FFFFFF" stroke-width="2.8" stroke-linejoin="round"/>
4
- <g transform="translate(23.6 20.85) scale(0.7)" stroke="#FFFFFF" stroke-width="3.6" stroke-linecap="round" stroke-linejoin="round">
5
- <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/>
6
- <path d="M3 3v5h5"/>
7
- <path d="M12 7v5l4 2"/>
8
- </g>
2
+ <circle cx="32" cy="32" r="28" fill="#1F2A44"/>
3
+ <path d="M27 14H45A4 4 0 0 1 49 18V27A4 4 0 0 1 45 31H27A4 4 0 0 1 23 27V18A4 4 0 0 1 27 14Z" fill="#4285F4"/>
4
+ <path d="M23 21H41A4 4 0 0 1 45 25V34A4 4 0 0 1 41 38H23A4 4 0 0 1 19 34V25A4 4 0 0 1 23 21Z" fill="#10A37F"/>
5
+ <path d="M19 28H37A4 4 0 0 1 41 32V42A4 4 0 0 1 37 46H25L19.5 50.5V46A4 4 0 0 1 15 42V32A4 4 0 0 1 19 28Z" fill="#FFFFFF"/>
6
+ <path d="M20.5 34.5H35.5M20.5 39.5H30" stroke="#1F2A44" stroke-width="2.6" stroke-linecap="round"/>
9
7
  </svg>
package/index.js CHANGED
@@ -4,10 +4,10 @@ import { spawn } from 'node:child_process';
4
4
  import { existsSync, writeFileSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
6
  import { resolveHome, loadConfig, saveConfig, layout, readJson } from './lib/config.js';
7
- import { SOURCES, enabled, byId } from './lib/agents.js';
7
+ import { SOURCES, FORMATS, enabled, byId, allSources, customSource, folderFor } from './lib/agents.js';
8
8
  import { installSkill, skillMarkdown, logFolders, findNode, ENGINE, VERSION } from './lib/skill.js';
9
- import { skillStatus, link, linkAll, unlink } from './lib/links.js';
10
- import { tilde } from './lib/files.js';
9
+ import { skillStatus, linkTarget, linkAll, unlinkTarget } from './lib/links.js';
10
+ import { tilde, expand, isDir } from './lib/files.js';
11
11
 
12
12
  export const name = 'session-history';
13
13
  export const ROUTE = '/youxia-session-history/api';
@@ -75,22 +75,45 @@ export function createRunner(home, { node = findNode(), engine = ENGINE } = {})
75
75
 
76
76
  export function snapshot(home, runner) {
77
77
  const config = loadConfig(home);
78
- const agents = skillStatus(home, config).map(a => ({ ...a, enabled: enabled(byId(a.id), config) }));
79
- const known = new Set(SOURCES.map(s => s.folder));
78
+ const last = readJson(layout(home).status, null);
79
+ const status = skillStatus(home, config);
80
+ const sources = new Map(allSources(config).map(source => [source.id, source]));
81
+ const shown = status.agents.filter(a => a.installed || a.custom).map(a => {
82
+ const source = sources.get(a.id);
83
+ const run = last?.agents?.[a.folder] || null;
84
+ return { ...a, enabled: enabled(source, config), sessions: (roots => roots.filter(isDir).map(tilde).join('、') || tilde(roots[0]))(source.locate(process.env, config.agents?.[a.id] || {}).roots),
85
+ run: run && { ok: run.ok, files: run.files, days: run.days, error: run.error || null },
86
+ ...(a.custom ? { def: config.custom.find(c => c.id === a.id) } : {}) };
87
+ });
88
+ const known = new Set(allSources(config).map(s => s.folder));
80
89
  return {
81
- version: VERSION,
82
- home: tilde(home),
83
- homeAbs: home,
84
- config,
85
- last: readJson(layout(home).status, null),
86
- running: runner?.running ?? false,
87
- agents,
90
+ version: VERSION, home: tilde(home), homeAbs: home, config, last, running: runner?.running ?? false,
91
+ agents: shown,
92
+ undetected: status.agents.filter(a => !a.installed && !a.custom).map(a => a.name),
93
+ targets: status.targets, links: status.links, conflicts: status.conflicts,
88
94
  legacy: logFolders(home).filter(f => !known.has(f)),
95
+ formats: Object.entries(FORMATS).map(([id, f]) => ({ id, label: f.label, dir: f.dir, layout: f.layout, example: f.example })),
89
96
  git: existsSync(join(home, '.git')),
90
97
  skill: skillMarkdown(home, { config }),
91
98
  };
92
99
  }
93
100
 
101
+ /** 检查自定义 agent 的会话目录:存在与否、按所选格式能找到几个会话文件。 */
102
+ export function probe(format, sessions) {
103
+ if (!FORMATS[format]) throw invalid('未知的会话格式');
104
+ const path = expand(String(sessions || '').trim());
105
+ if (!path) throw invalid('请填写会话目录');
106
+ if (!isDir(path)) return { exists: false, files: 0, path: tilde(path) };
107
+ const source = customSource({ id: 'probe', folder: 'probe', name: 'probe', format, sessions: path });
108
+ const files = source.files(source.locate());
109
+ // 只看文件名分不出格式(几家的目录结构相近),抽几个实际解析,能解析出对话才算对。
110
+ let turns = 0;
111
+ for (const file of files.slice(0, 5)) {
112
+ try { const data = source.parse(file); turns += (data.turns || data.records || []).length; } catch { /* 解析失败按 0 计 */ }
113
+ }
114
+ return { exists: true, files: files.length, turns, path: tilde(path), sample: files[0] ? tilde(files[0]) : null };
115
+ }
116
+
94
117
  function gitInit(home) {
95
118
  if (existsSync(join(home, '.git'))) return;
96
119
  return new Promise((resolve, reject) => {
@@ -121,11 +144,28 @@ export async function command(home, runner, input) {
121
144
  if (!r.ok) throw invalid(`整理失败:${r.error || '见状态'}`, 500);
122
145
  return snapshot(home, runner);
123
146
  }
124
- case 'link': link(home, String(input.agent), config); break;
147
+ case 'linkTarget': linkTarget(home, String(input.key), config); break;
125
148
  case 'linkAll': linkAll(home, config); break;
126
- case 'unlink': unlink(home, String(input.agent), config); break;
149
+ case 'unlinkTarget': unlinkTarget(home, String(input.key), config); break;
150
+ case 'probe': return { probe: probe(input.format, input.sessions) };
151
+ case 'addCustom': {
152
+ const name = String(input.name || '').trim();
153
+ if (!name || name.length > 24 || /[\n#]/.test(name)) throw invalid('名称须为 1–24 个字,不含 # 与换行');
154
+ const result = probe(input.format, input.sessions);
155
+ if (!result.exists) throw invalid(`会话目录不存在:${result.path}`);
156
+ const def = { name, format: input.format, sessions: String(input.sessions).trim(), ...(input.skills?.trim() ? { skills: input.skills.trim() } : {}) };
157
+ saveConfig(home, { custom: [...config.custom, def] });
158
+ installSkill(home);
159
+ break;
160
+ }
161
+ case 'removeCustom': {
162
+ if (!config.custom.some(c => c.id === input.id)) throw invalid('没有这个自定义 agent');
163
+ saveConfig(home, { custom: config.custom.filter(c => c.id !== input.id) });
164
+ installSkill(home);
165
+ break;
166
+ }
127
167
  case 'enable': {
128
- if (!byId(input.agent) || typeof input.enabled !== 'boolean') throw invalid('参数无效');
168
+ if (!byId(input.agent, config) || typeof input.enabled !== 'boolean') throw invalid('参数无效');
129
169
  saveConfig(home, { agents: { [input.agent]: { enabled: input.enabled } } });
130
170
  installSkill(home);
131
171
  break;
package/lib/agents.js CHANGED
@@ -1,27 +1,81 @@
1
- // 支持的 agent:会话来源(清洗用)与技能目录(接入技能用)。
1
+ // agent 注册表:内置各家的会话来源(清洗用)与技能目录(接入技能用),外加用户手动添加的同格式 agent。
2
+ import { dirname } from 'node:path';
2
3
  import claude from './sources/claude.js';
3
4
  import codex from './sources/codex.js';
4
5
  import antigravity from './sources/antigravity.js';
5
6
  import pi from './sources/pi.js';
6
7
  import dsh from './sources/dsh.js';
7
- import { isDir } from './files.js';
8
+ import lobsterai from './sources/lobsterai.js';
9
+ import workbuddy from './sources/workbuddy.js';
10
+ import { isDir, expand } from './files.js';
8
11
 
9
- export const SOURCES = [claude, codex, antigravity, pi, dsh];
10
- export const byId = id => SOURCES.find(s => s.id === id);
11
- export const byFolder = folder => SOURCES.find(s => s.folder === folder);
12
+ export const SOURCES = [claude, codex, antigravity, pi, dsh, lobsterai, workbuddy];
13
+
14
+ /**
15
+ * 自定义 agent 可选的会话格式:与哪一家相同,会话目录选哪一层。
16
+ * dir:要填的那一层目录名;layout:它下面的结构;example:常见用法。
17
+ */
18
+ export const FORMATS = {
19
+ claude: { source: claude, label: 'Claude Code 格式', dir: 'projects', layout: '<项目>/<会话>.jsonl',
20
+ example: 'Qoder CLI:~/.qoder-cn/projects;另一套 Claude Code 配置:~/.claude-work/projects' },
21
+ codex: { source: codex, label: 'Codex 格式', dir: 'sessions', layout: '<年>/<月>/<日>/rollout-*.jsonl',
22
+ example: '另一个 CODEX_HOME:~/.codex-work/sessions' },
23
+ pi: { source: pi, label: 'Pi 格式', dir: 'sessions', layout: '<目录>/<会话>.jsonl', example: '另一个 Pi 配置目录下的 sessions' },
24
+ dsh: { source: dsh, label: 'DSH 格式', dir: 'sessions', layout: '<目录>/<会话>/session.vN.jsonl.zstd', example: '另一个 DSH_HOME:~/.dsh-work/sessions' },
25
+ antigravity: { source: antigravity, label: 'Antigravity 格式', dir: 'brain', layout: '<会话>/.system_generated/logs/transcript_full.jsonl',
26
+ example: '第二个实例:~/.gemini-work/antigravity-cli/brain' },
27
+ lobsterai: { source: lobsterai, label: 'LobsterAI(OpenClaw)格式', dir: 'agents', layout: '<agent>/sessions/<会话>.jsonl',
28
+ example: '其他基于 OpenClaw 的客户端的 agents 目录' },
29
+ workbuddy: { source: workbuddy, label: 'WorkBuddy(CodeBuddy)格式', dir: 'projects', layout: '<项目>/<会话>.jsonl',
30
+ example: 'CodeBuddy Code:~/.codebuddy/projects' },
31
+ };
32
+
33
+ const RESERVED = new Set(SOURCES.map(s => s.folder.toLowerCase()));
34
+
35
+ /** 名称 → 日志文件夹名:保留字母(含中文)、数字、- 和 _,其余换成 -;与内置或彼此重名时加序号。 */
36
+ export function folderFor(name, taken = new Set()) {
37
+ const base = String(name).trim().replace(/[^\p{L}\p{N}_-]+/gu, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'Agent';
38
+ let folder = base, n = 2;
39
+ while (RESERVED.has(folder.toLowerCase()) || taken.has(folder.toLowerCase())) folder = `${base}-${n++}`;
40
+ taken.add(folder.toLowerCase());
41
+ return folder;
42
+ }
43
+
44
+ /** 自定义 agent:沿用对应格式的解析与渲染,只换会话目录、技能目录与名称。 */
45
+ export function customSource(def) {
46
+ const format = FORMATS[def.format];
47
+ const base = format.source;
48
+ return {
49
+ ...base, id: def.id, folder: def.folder, name: def.name, custom: true, format: def.format,
50
+ locate() {
51
+ const sessions = expand(def.sessions);
52
+ return { base: dirname(sessions), sessions, projects: sessions, agentsRoot: sessions, roots: [sessions], cowork: null,
53
+ marks: [sessions], skills: def.skills ? [expand(def.skills)] : [] };
54
+ },
55
+ render: (all, clock, userLabel) => base.render(all, clock, userLabel, def.name),
56
+ };
57
+ }
58
+
59
+ /** 内置+自定义。 */
60
+ export function allSources(config = {}) {
61
+ return [...SOURCES, ...(config.custom || []).map(customSource)];
62
+ }
63
+
64
+ export const byId = (id, config = {}) => allSources(config).find(s => s.id === id);
65
+ export const byFolder = (folder, config = {}) => allSources(config).find(s => s.folder === folder);
12
66
 
13
67
  /** 某 agent 在本机的路径(随环境变量与配置变)。 */
14
68
  export function pathsOf(source, config = {}, env = process.env) {
15
69
  return source.locate(env, config.agents?.[source.id] || {});
16
70
  }
17
71
 
18
- /** 是否装过:会话根目录或配置根目录存在。 */
72
+ /** 是否装过:会话根目录或该 agent 的配置根目录存在。 */
19
73
  export function detected(source, config = {}, env = process.env) {
20
74
  const paths = pathsOf(source, config, env);
21
75
  return [...paths.roots, ...(paths.marks || [paths.base])].some(isDir);
22
76
  }
23
77
 
24
- /** 是否清洗:配置里显式开关优先,否则检测到就清洗。 */
78
+ /** 是否收录:配置里显式开关优先,否则检测到就收录。 */
25
79
  export function enabled(source, config = {}, env = process.env) {
26
80
  const flag = config.agents?.[source.id]?.enabled;
27
81
  return typeof flag === 'boolean' ? flag : detected(source, config, env);