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/lib/config.js CHANGED
@@ -4,7 +4,7 @@ import { readFileSync, existsSync } from 'node:fs';
4
4
  import { isAbsolute, join, resolve } from 'node:path';
5
5
  import { expand } from './files.js';
6
6
  import { atomicWrite } from './markdown.js';
7
- import { SOURCES } from './agents.js';
7
+ import { SOURCES, FORMATS, folderFor } from './agents.js';
8
8
 
9
9
  export const SKILL_NAME = 'session-history';
10
10
  export const DEFAULT_HOME = '~/.session-history';
@@ -46,6 +46,7 @@ export const DEFAULTS = Object.freeze({
46
46
  gitSnapshots: false, // 整理后把 logs/ 提交成 Git 快照(数据目录须是 Git 仓库)
47
47
  excludeCwds: [], // 这些工作目录下的会话不收
48
48
  agents: {}, // { claude: { enabled, onlyCwds, since, extraRoots } … }
49
+ custom: [], // 手动添加的 agent:[{ name, format, sessions, skills? }]
49
50
  });
50
51
 
51
52
  const strings = (value, fallback = []) => Array.isArray(value) ? value.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()) : fallback;
@@ -54,8 +55,20 @@ const int = (value, fallback, min, max) => Number.isInteger(value) && value >= m
54
55
  /** 校验并补默认值;非法值回落默认,不抛错(设置文件可能被手改)。 */
55
56
  export function normalizeConfig(raw = {}) {
56
57
  const r = raw && typeof raw === 'object' ? raw : {};
58
+ // 自定义 agent:名称、格式、会话目录必填;技能目录可选。id 与日志文件夹由名称导出。
59
+ const taken = new Set(), custom = [];
60
+ for (const c of Array.isArray(r.custom) ? r.custom : []) {
61
+ if (!c || typeof c !== 'object' || !FORMATS[c.format]) continue;
62
+ const name = typeof c.name === 'string' ? c.name.trim().slice(0, 24) : '';
63
+ const sessions = typeof c.sessions === 'string' ? c.sessions.trim() : '';
64
+ if (!name || !sessions || /[\n#]/.test(name)) continue;
65
+ const folder = folderFor(name, taken);
66
+ const item = { name, format: c.format, sessions, id: `custom-${folder.toLowerCase()}`, folder };
67
+ if (typeof c.skills === 'string' && c.skills.trim()) item.skills = c.skills.trim();
68
+ custom.push(item);
69
+ }
57
70
  const agents = {};
58
- for (const { id } of SOURCES) {
71
+ for (const id of [...SOURCES.map(s => s.id), ...custom.map(c => c.id)]) {
59
72
  const a = r.agents?.[id];
60
73
  if (!a || typeof a !== 'object') continue;
61
74
  const item = {};
@@ -76,6 +89,7 @@ export function normalizeConfig(raw = {}) {
76
89
  gitSnapshots: typeof r.gitSnapshots === 'boolean' ? r.gitSnapshots : DEFAULTS.gitSnapshots,
77
90
  excludeCwds: strings(r.excludeCwds),
78
91
  agents,
92
+ custom,
79
93
  };
80
94
  }
81
95
 
@@ -92,7 +106,8 @@ export function saveConfig(home, patch = {}) {
92
106
  const agents = { ...current.agents };
93
107
  for (const [id, value] of Object.entries(patch.agents || {})) agents[id] = { ...(agents[id] || {}), ...(value || {}) };
94
108
  const next = normalizeConfig({ ...current, ...patch, agents });
95
- atomicWrite(layout(home).config, JSON.stringify(next, null, 2) + '\n');
109
+ const stored = { ...next, custom: next.custom.map(({ name, format, sessions, skills }) => ({ name, format, sessions, ...(skills ? { skills } : {}) })) };
110
+ atomicWrite(layout(home).config, JSON.stringify(stored, null, 2) + '\n');
96
111
  return next;
97
112
  }
98
113
 
package/lib/links.js CHANGED
@@ -1,14 +1,22 @@
1
- // 技能接入:不往各 agent 拷副本,而是在它读的技能目录里放一个指向数据目录的软链 session-history。
2
- // 很多人只管一个技能目录、其余用软链共用(如 ~/.claude/skills → ~/my-skills),所以按真实路径归并:
3
- // 同一个真实目录只需一条软链,共用它的 agent 自动都能看到。
1
+ // 技能接入:不往各 agent 拷副本,而是在它读取的技能目录里放一条指向数据目录的软链 session-history。
2
+ // 很多人只维护一个技能文件夹,其余用软链共用(如 ~/.claude/skills → ~/my-skills),所以一律按真实路径归并:
3
+ // 同一个真实目录只需一条软链,读它的 agent 都会生效。
4
+ //
5
+ // 每个 agent 的技能状态:
6
+ // ready 已生效:它读取的某个技能目录里已有指向数据目录的 session-history
7
+ // missing 未生效:需要在它的技能目录里建软链(按目标目录归组,一组一个操作)
8
+ // conflict 有冲突:技能目录里已有同名的其他东西(旧版副本、失效软链……),不覆盖
9
+ // nodir 不接入:没有可用的技能目录(自定义 agent 未填技能目录)
4
10
  import { lstatSync, readlinkSync, realpathSync, symlinkSync, mkdirSync, readFileSync, unlinkSync, existsSync } from 'node:fs';
5
- import { dirname, join, resolve } from 'node:path';
6
- import { SOURCES, byId, pathsOf, detected } from './agents.js';
11
+ import { join, resolve } from 'node:path';
12
+ import { allSources, byId, pathsOf, detected } from './agents.js';
7
13
  import { SKILL_NAME } from './config.js';
8
14
  import { tilde } from './files.js';
9
15
 
16
+ const win = process.platform === 'win32';
10
17
  // Windows 路径不分大小写;realpath 结果统一成小写再比。
11
- const real = path => { try { const r = realpathSync(path); return process.platform === 'win32' ? r.toLowerCase() : r; } catch { return null; } };
18
+ const real = path => { try { const r = realpathSync(path); return win ? r.toLowerCase() : r; } catch { return null; } };
19
+ const key = path => (win ? resolve(path).toLowerCase() : resolve(path));
12
20
 
13
21
  function skillName(folder) {
14
22
  try {
@@ -17,11 +25,7 @@ function skillName(folder) {
17
25
  } catch { return null; }
18
26
  }
19
27
 
20
- /**
21
- * 某技能目录里 session-history 的状态:
22
- * none 没有|link 我们的软链|shared 目录本身就在数据目录里(或别的软链也指向它)|
23
- * copy 同名技能的独立副本(旧版拷贝)|broken 失效软链|other 别的同名东西
24
- */
28
+ /** 技能目录里 session-history 这一项的状态:none/link(我们的软链)/shared(目录就在数据目录里)/copy/broken/other。 */
25
29
  export function entryState(dir, home) {
26
30
  const entry = join(dir, SKILL_NAME);
27
31
  let st;
@@ -35,64 +39,107 @@ export function entryState(dir, home) {
35
39
  return { state: st.isDirectory() && skillName(entry) === SKILL_NAME ? 'copy' : 'other', entry, target };
36
40
  }
37
41
 
38
- /** 各 agent 的技能目录与可见性;dirs 里 real 相同者是同一个目录。 */
39
- export function skillStatus(home, config = {}) {
40
- const agents = SOURCES.map(source => {
41
- const dirs = pathsOf(source, config).skills.map(path => {
42
- const exists = existsSync(path);
43
- return { path, display: tilde(path), exists, real: exists ? real(path) : null, ...(exists ? entryState(path, home) : { state: 'none' }) };
44
- });
45
- const via = dirs.find(d => d.state === 'link' || d.state === 'shared');
46
- const blocked = dirs.find(d => ['copy', 'other', 'broken'].includes(d.state));
47
- return { id: source.id, name: source.name, folder: source.folder, installed: detected(source, config), visible: !!via,
48
- via: via ? via.display : null, conflict: !via && blocked ? { path: tilde(blocked.entry), state: blocked.state } : null, dirs };
42
+ function agentStatus(source, home, config) {
43
+ const paths = pathsOf(source, config);
44
+ const dirs = (paths.skills || []).map(path => {
45
+ const exists = existsSync(path);
46
+ return { path, display: tilde(path), exists, real: exists ? real(path) : null, ...(exists ? entryState(path, home) : { state: 'none', entry: join(path, SKILL_NAME) }) };
49
47
  });
50
- // 共用:同一真实目录被几家读。
51
- const byReal = new Map();
52
- for (const a of agents) for (const d of a.dirs) if (d.real) {
53
- if (!byReal.has(d.real)) byReal.set(d.real, new Set());
54
- byReal.get(d.real).add(a.name);
55
- }
56
- for (const a of agents) for (const d of a.dirs) d.sharedWith = d.real ? [...byReal.get(d.real)].filter(n => n !== a.name) : [];
57
- return agents;
48
+ const via = dirs.find(d => d.state === 'link' || d.state === 'shared');
49
+ const blocked = dirs.find(d => ['copy', 'other', 'broken'].includes(d.state));
50
+ const state = !dirs.length ? 'nodir' : via ? 'ready' : blocked ? 'conflict' : 'missing';
51
+ // 建软链的位置:第一个已存在的技能目录;都不存在就用首选目录(届时新建)。
52
+ const first = dirs.find(d => d.exists) || dirs[0];
53
+ return {
54
+ id: source.id, name: source.name, folder: source.folder, custom: !!source.custom, experimental: !!source.experimental,
55
+ format: source.format, installed: detected(source, config), state, dirs, note: paths.skillNote || null,
56
+ via: via ? via.display : null,
57
+ conflict: state === 'conflict' ? { path: tilde(blocked.entry), state: blocked.state } : null,
58
+ target: state === 'missing' && first ? { path: first.path, display: first.display, key: first.real || key(first.path), create: !first.exists } : null,
59
+ };
58
60
  }
59
61
 
60
- /** 给某 agent 接入:已可见就不动;否则在它第一个已存在的技能目录(都不在就建首选目录)里建软链。 */
61
- export function link(home, id, config = {}) {
62
- const source = byId(id);
63
- if (!source) throw new Error(`未知 agent:${id}`);
64
- const status = skillStatus(home, config).find(a => a.id === id);
65
- if (status.visible) return { changed: false, via: status.via };
66
- if (status.conflict) {
67
- const why = { copy: '已有同名技能的独立副本(多半是旧版拷贝)', other: '已有同名的其他文件', broken: '已有失效的同名软链' }[status.conflict.state];
68
- throw new Error(`${status.conflict.path} ${why},请先移走再接入。`);
62
+ /** 全部状态:各 agent、待建的软链(按目标目录归组)、已建的软链、冲突。 */
63
+ export function skillStatus(home, config = {}) {
64
+ const agents = allSources(config).map(source => agentStatus(source, home, config));
65
+ const live = agents.filter(a => a.installed || a.custom);
66
+ const reads = dir => live.filter(a => a.dirs.some(d => d.real === dir)).map(a => a.name);
67
+ const groups = new Map();
68
+ for (const a of live.filter(x => x.state === 'missing' && x.target)) {
69
+ const g = groups.get(a.target.key) || { key: a.target.key, path: a.target.path, display: a.target.display, create: a.target.create, agents: [] };
70
+ g.agents.push(a.name);
71
+ groups.set(a.target.key, g);
72
+ }
73
+ // 同一目录还被别的未生效 agent 读到的,一并算进受益者。
74
+ for (const g of groups.values()) {
75
+ for (const a of live.filter(x => x.state === 'missing' && !g.agents.includes(x.name))) if (a.dirs.some(d => d.real === g.key)) g.agents.push(a.name);
76
+ const realPath = g.create ? null : realpathSafe(g.path);
77
+ g.realDisplay = realPath && key(realPath) !== key(g.path) ? tilde(realPath) : null;
69
78
  }
70
- const dir = status.dirs.find(d => d.exists) || status.dirs[0];
71
- mkdirSync(dir.path, { recursive: true });
72
- const entry = join(dir.path, SKILL_NAME);
73
- symlinkSync(resolve(home), entry, process.platform === 'win32' ? 'junction' : 'dir');
74
- return { changed: true, via: tilde(dir.path), entry: tilde(entry) };
79
+ const links = new Map();
80
+ for (const a of live) for (const d of a.dirs) if (d.state === 'link' && d.real && !links.has(d.real)) {
81
+ links.set(d.real, { key: d.real, entry: tilde(join(realpathSafe(d.path) || d.path, SKILL_NAME)), agents: reads(d.real) });
82
+ }
83
+ const conflicts = live.filter(a => a.state === 'conflict').map(a => ({ agent: a.name, ...a.conflict }));
84
+ return { agents, targets: [...groups.values()], links: [...links.values()], conflicts };
85
+ }
86
+
87
+ const realpathSafe = path => { try { return realpathSync(path); } catch { return null; } };
88
+
89
+ function makeLink(home, dirPath) {
90
+ mkdirSync(dirPath, { recursive: true });
91
+ const entry = join(dirPath, SKILL_NAME);
92
+ symlinkSync(resolve(home), entry, win ? 'junction' : 'dir');
93
+ return tilde(entry);
75
94
  }
76
95
 
77
- /** 一键接入:逐个接,前一个建的软链若被后一个共用就不重复建。 */
96
+ /** 按归组的目标目录建软链;只接受当前算出来的目标,防止被指向任意位置。 */
97
+ export function linkTarget(home, targetKey, config = {}) {
98
+ const group = skillStatus(home, config).targets.find(g => g.key === targetKey);
99
+ if (!group) throw new Error('该目录已无需建软链,或不是任何 agent 的技能目录。');
100
+ return { changed: true, entry: makeLink(home, group.path), agents: group.agents };
101
+ }
102
+
103
+ /** 一键接入:逐组建,前一组建好后若别的组已被覆盖就跳过。 */
78
104
  export function linkAll(home, config = {}) {
79
105
  const results = [];
80
- for (const a of skillStatus(home, config)) {
81
- if (!a.installed) continue;
82
- try { results.push({ id: a.id, ...link(home, a.id, config) }); }
83
- catch (error) { results.push({ id: a.id, error: error.message }); }
106
+ for (let guard = 0; guard < 20; guard++) {
107
+ const next = skillStatus(home, config).targets[0];
108
+ if (!next) break;
109
+ try { results.push(linkTarget(home, next.key, config)); } catch (error) { results.push({ error: error.message }); break; }
84
110
  }
85
111
  return results;
86
112
  }
87
113
 
88
- /** 只移除我们自己的软链(指向数据目录的),不碰真实文件夹。共用同一目录的 agent 会一起看不到。 */
89
- export function unlink(home, id, config = {}) {
90
- const status = skillStatus(home, config).find(a => a.id === id);
91
- if (!status) throw new Error(`未知 agent:${id}`);
92
- const own = status.dirs.filter(d => d.state === 'link');
93
- if (!own.length) throw new Error(status.dirs.some(d => d.state === 'shared') ? '技能文件夹本身就在该技能目录里(不是软链),不移除。' : '没有可移除的软链。');
94
- for (const d of own) unlinkSync(d.entry);
95
- return { changed: true, removed: own.map(d => tilde(d.entry)), affects: [...new Set(own.flatMap(d => d.sharedWith))] };
114
+ /** 移除一条我们建的软链(只动指向数据目录的软链,不碰真实文件夹)。 */
115
+ export function unlinkTarget(home, linkKey, config = {}) {
116
+ const link = skillStatus(home, config).links.find(l => l.key === linkKey);
117
+ if (!link) throw new Error('没有找到这条软链。');
118
+ const entry = join(linkKey, SKILL_NAME);
119
+ const st = lstatSync(entry);
120
+ if (!st.isSymbolicLink() || real(entry) !== real(home)) throw new Error('该位置不是指向数据目录的软链,未移除。');
121
+ unlinkSync(entry);
122
+ return { changed: true, removed: link.entry, affects: link.agents };
123
+ }
124
+
125
+ /** 命令行用:给某 agent 接入(已生效就不动)。 */
126
+ export function link(home, id, config = {}) {
127
+ if (!byId(id, config)) throw new Error(`未知 agent:${id}`);
128
+ const status = skillStatus(home, config);
129
+ const a = status.agents.find(x => x.id === id);
130
+ if (a.state === 'ready') return { changed: false, via: a.via };
131
+ if (a.state === 'nodir') throw new Error(`${a.name} 没有可用的技能目录。`);
132
+ if (a.state === 'conflict') throw new Error(`${a.conflict.path} 已有同名的其他文件或旧版副本,请先移走再接入。`);
133
+ return linkTarget(home, a.target.key, config);
96
134
  }
97
135
 
98
- export const _dirname = dirname;
136
+ /** 命令行用:移除某 agent 能读到的我们的软链。 */
137
+ export function unlink(home, id, config = {}) {
138
+ const status = skillStatus(home, config);
139
+ const a = status.agents.find(x => x.id === id);
140
+ if (!a) throw new Error(`未知 agent:${id}`);
141
+ const own = status.links.filter(l => a.dirs.some(d => d.real === l.key));
142
+ if (!own.length) throw new Error(a.dirs.some(d => d.state === 'shared') ? '数据目录本身就在该技能目录里(不是软链),不移除。' : '没有可移除的软链。');
143
+ const removed = own.map(l => unlinkTarget(home, l.key, config));
144
+ return { changed: true, removed: removed.map(r => r.removed), affects: [...new Set(removed.flatMap(r => r.affects))].filter(n => n !== a.name) };
145
+ }
package/lib/raw.js CHANGED
@@ -24,10 +24,10 @@ const pick = (o, keys) => Object.fromEntries(Object.entries(o).filter(([k]) => k
24
24
  const omit = (o, keys) => Object.fromEntries(Object.entries(o).filter(([k]) => !keys.includes(k)));
25
25
 
26
26
  /** 原始记录的一行拆成 [类别, 文本]。CC 的请求快照、Codex 的配置与计量等跳过,否则查什么都是噪声。 */
27
- export function* rawItems(folder, e) {
27
+ export function* rawItems(kind, e) {
28
28
  if (!isObject(e)) return;
29
- if (folder === 'Antigravity') { yield [AGY[e.type] || '工具返回', joined(pick(e, ['content', 'tool_calls']))]; return; }
30
- if (folder === 'DSH') {
29
+ if (kind === 'antigravity') { yield [AGY[e.type] || '工具返回', joined(pick(e, ['content', 'tool_calls']))]; return; }
30
+ if (kind === 'dsh') {
31
31
  const kind = e.type || '', d = isObject(e.data) ? e.data : {};
32
32
  if (kind === 'user/message' && [undefined, null, 'user'].includes(isObject(d.source) ? d.source.kind : undefined)) yield ['用户', joined(d.content)];
33
33
  else if (kind === 'assistant/message') {
@@ -41,7 +41,15 @@ export function* rawItems(folder, e) {
41
41
  else if (kind.includes('error')) yield ['报错', joined(d)];
42
42
  return;
43
43
  }
44
- if (folder === 'Codex') {
44
+ if (kind === 'workbuddy') {
45
+ const p = isObject(e.providerData) ? e.providerData : {};
46
+ if (e.type === 'message' && ['user', 'assistant'].includes(e.role) && !p.isMeta && !p.skipRun) yield [e.role === 'user' ? '用户' : '助手', joined(e.content)];
47
+ else if (e.type === 'reasoning') yield ['思考', joined(e.content ?? e.summary)];
48
+ else if (e.type === 'function_call') yield ['工具调用', joined(pick(e, ['name', 'arguments']))];
49
+ else if (e.type === 'function_call_result') yield ['工具返回', joined(e.output)];
50
+ return;
51
+ }
52
+ if (kind === 'codex') {
45
53
  const p = isObject(e.payload) ? e.payload : {};
46
54
  const kind = e.type === 'response_item' ? (p.type || '') : '';
47
55
  if (kind === 'message' && ['user', 'assistant'].includes(p.role)) yield [p.role === 'user' ? '用户' : '助手', joined(p.content)];
@@ -75,9 +83,10 @@ export function raw(db, args, ctx) {
75
83
  const [about, message] = pickSession(db, args.target, args.agent);
76
84
  if (!about) return message;
77
85
  const tag = `${about.agent} ${shortSid(about.session)}「${about.title}」`;
78
- const source = byFolder(about.agent);
86
+ const source = byFolder(about.agent, config);
79
87
  const key = about.session.startsWith('session-') ? about.session.slice(8) : about.session;
80
88
  const files = source ? source.rawFiles(pathsOf(source, config), key) : [];
89
+ const kind = source ? (source.custom ? source.format : source.id) : '';
81
90
  if (!files.length) return `${tag}的原始记录已不在(已删除、来源已停用或不支持),只能查清洗日志。`;
82
91
  const groups = parseQuery(args.query);
83
92
  if (!groups.length) throw new UsageError('请提供至少一个关键词。');
@@ -92,7 +101,7 @@ export function raw(db, args, ctx) {
92
101
  if (!probes.some(p => low.includes(p))) return;
93
102
  const e = parseJson(line);
94
103
  if (e === undefined) return;
95
- for (const [label, value] of rawItems(about.agent, e)) {
104
+ for (const [label, value] of rawItems(kind, e)) {
96
105
  const text = value.replaceAll('\\n', '\n'); // 工具返回常是二次编码的 JSON 字符串
97
106
  const normalized = norm(text);
98
107
  const found = groups.filter(([, alts]) => alts.some(a => occurrences(normalized, a))).length;
package/lib/refresh.js CHANGED
@@ -5,7 +5,7 @@ import { mkdirSync, openSync, closeSync, writeSync, readFileSync, unlinkSync, ex
5
5
  import { join } from 'node:path';
6
6
  import { spawnSync } from 'node:child_process';
7
7
  import { DatabaseSync } from 'node:sqlite';
8
- import { SOURCES, pathsOf, enabled } from './agents.js';
8
+ import { allSources, pathsOf, enabled } from './agents.js';
9
9
  import { layout, loadConfig, readJson } from './config.js';
10
10
  import { createClock } from './clock.js';
11
11
  import { retitle, preserveMissing, atomicWrite } from './markdown.js';
@@ -140,7 +140,7 @@ export function refresh({ home, only = null, log = () => {}, engine = null } = {
140
140
  const cache = openCache(dirs.cache);
141
141
  const agents = {};
142
142
  try {
143
- for (const source of SOURCES) {
143
+ for (const source of allSources(config)) {
144
144
  if (only && !only.includes(source.id)) continue;
145
145
  if (!enabled(source, config)) continue;
146
146
  const t = Date.now();
package/lib/skill.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { readFileSync, existsSync, chmodSync, statSync, mkdirSync } from 'node:fs';
3
3
  import { basename, dirname, join, resolve } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
- import { SOURCES, enabled } from './agents.js';
5
+ import { allSources, enabled } from './agents.js';
6
6
  import { layout, loadConfig, SKILL_NAME } from './config.js';
7
7
  import { atomicWrite } from './markdown.js';
8
8
  import { entries, isDir, tilde, exists, home } from './files.js';
@@ -33,7 +33,7 @@ export function logFolders(home) {
33
33
 
34
34
  /** 生成 SKILL.md 要用的事实:哪些在用、哪些只剩旧日志。 */
35
35
  export function inventory(home, config = loadConfig(home)) {
36
- const active = SOURCES.filter(s => enabled(s, config));
36
+ const active = allSources(config).filter(s => enabled(s, config));
37
37
  const folders = logFolders(home);
38
38
  const legacy = folders.filter(f => !active.some(s => s.folder === f));
39
39
  return { active, legacy, folders: [...new Set([...active.map(s => s.folder), ...folders])] };
@@ -55,12 +55,12 @@ export function skillMarkdown(home, { config = loadConfig(home), platform = proc
55
55
  const first = active[0]?.folder || folders[0] || 'Claude';
56
56
  const scope = names.length
57
57
  ? `${list(names)}${legacy.length ? `,以及已停用的 ${list(legacy)}(旧日志照常检索)` : ''}`
58
- : legacy.length ? `已停用的 ${list(legacy)}(只剩旧日志)` : '本机 agent(尚未检测到会话来源)';
58
+ : legacy.length ? `已停用的 ${list(legacy)}(只剩旧日志)` : '各 agent(尚未检测到会话来源)';
59
59
  const cmd = 'session-history';
60
60
  const lines = [
61
61
  '---',
62
62
  `name: ${SKILL_NAME}`,
63
- `description: 查本机 agent(${list(names.length ? names : legacy) || '各家'})的历史对话。用户提起过往,或提到你不清楚来由的事时使用;上下文和记忆里能找到就不查,同一件事每个会话最多查一次。`,
63
+ `description: 查各 agent(${list(names.length ? names : legacy) || '各家'})的历史对话。用户提起过往,或提到你不清楚来由的事时使用;上下文和记忆里能找到就不查,同一件事每个会话最多查一次。`,
64
64
  '---',
65
65
  '',
66
66
  '# Session History',
@@ -99,7 +99,7 @@ export function skillMarkdown(home, { config = loadConfig(home), platform = proc
99
99
  '',
100
100
  `每次命令自动增量更新索引${config.staleMinutes ? `;距上次整理超过 ${config.staleMinutes} 分钟会先补整理(只重读变过的会话,通常几秒)` : ''}。要查刚刚的对话可先跑一次 \`${cmd} refresh\`,别反复跑。依赖或索引报错时别当无命中:先报告,再按日志路径兜底(兼顾繁简):\`rg -n -m 5 '关键词|關鍵詞' ${platform === 'win32' ? layout(home).logs.replaceAll('\\', '/') : tilde(layout(home).logs)}/${first}/2026-08-*-log.md\``,
101
101
  '',
102
- '除非用户要求维护本技能,不改日志正文。本文件由 Session History 按本机检测到的 agent 自动生成,手改会被覆盖。',
102
+ '除非用户要求维护本技能,不改日志正文。本文件由 Session History 按检测到的 agent 自动生成,手改会被覆盖。',
103
103
  '',
104
104
  ];
105
105
  return lines.join('\n');
@@ -160,7 +160,7 @@ function readme(home) {
160
160
  - \`logs/<Agent>/\`:每天一份的清洗日志(只留问答原文),是唯一的权威数据,请勿删除。
161
161
  - \`config.json\`:设置(DSH 插件页可改)。
162
162
  - \`state/\`:索引、解析缓存与运行状态,可随时删掉,下次检索自动重建。
163
- - \`SKILL.md\`、\`bin/\`:给各 agent 用的技能与入口,按本机检测到的 agent 自动生成。
163
+ - \`SKILL.md\`、\`bin/\`:给各 agent 用的技能与入口,按检测到的 agent 自动生成。
164
164
 
165
165
  各 agent 的技能目录里放的是指向本目录的软链(名为 \`${SKILL_NAME}\`),不是副本。
166
166
  `;
@@ -9,7 +9,7 @@ import { renderDays, tmpPrefix, excluded } from './common.js';
9
9
  export function locate(env = process.env, options = {}) {
10
10
  const base = join(home(), '.gemini');
11
11
  const roots = [join(base, 'antigravity/brain'), join(base, 'antigravity-cli/brain'), ...(options.extraRoots || []).map(expand)];
12
- return { base, roots, marks: [join(base, 'antigravity'), join(base, 'antigravity-cli')], skills: [join(base, 'config/skills')] };
12
+ return { base, roots, marks: [join(base, 'antigravity'), join(base, 'antigravity-cli')], skills: [join(base, 'config/skills'), join(base, 'antigravity/skills')] };
13
13
  }
14
14
 
15
15
  const size = path => { try { return statSync(path).size; } catch { return 0; } };
@@ -119,8 +119,8 @@ export function build(entriesList, options = {}, paths) {
119
119
  return { turns: all, titles: paths ? annotationTitles(paths) : {}, count: all.length };
120
120
  }
121
121
 
122
- export function render(all, clock, userLabel) {
123
- return renderDays(all, clock, { user: `🧑 ${userLabel}`, assistant: '🤖 Antigravity' });
122
+ export function render(all, clock, userLabel, name = 'Antigravity') {
123
+ return renderDays(all, clock, { user: `🧑 ${userLabel}`, assistant: `🤖 ${name}` });
124
124
  }
125
125
 
126
126
  export function rawFiles(paths, key) {
@@ -110,8 +110,8 @@ export function build(entries, options = {}) {
110
110
  return { turns: all, titles, count: all.length };
111
111
  }
112
112
 
113
- export function render(all, clock, userLabel) {
114
- return renderDays(all, clock, { user: `🧑 ${userLabel}`, assistant: '🤖 Claude' });
113
+ export function render(all, clock, userLabel, name = 'Claude') {
114
+ return renderDays(all, clock, { user: `🧑 ${userLabel}`, assistant: `🤖 ${name}` });
115
115
  }
116
116
 
117
117
  export function rawFiles(paths, key) {
@@ -104,8 +104,8 @@ export function build(entries, options = {}, paths) {
104
104
  return { turns: all, titles, count: all.length };
105
105
  }
106
106
 
107
- export function render(all, clock, userLabel) {
108
- return renderDays(all, clock, { user: userLabel, assistant: 'Codex' });
107
+ export function render(all, clock, userLabel, name = 'Codex') {
108
+ return renderDays(all, clock, { user: userLabel, assistant: name });
109
109
  }
110
110
 
111
111
  export function rawFiles(paths, key) {
@@ -102,8 +102,8 @@ export function build(entriesList, options = {}) {
102
102
  return { turns: all, titles, count: all.length, skipped: notes.length };
103
103
  }
104
104
 
105
- export function render(all, clock, userLabel) {
106
- return renderDays(all, clock, { user: `🧑 ${userLabel}`, assistant: '🤖 DSH' });
105
+ export function render(all, clock, userLabel, name = 'DSH') {
106
+ return renderDays(all, clock, { user: `🧑 ${userLabel}`, assistant: `🤖 ${name}` });
107
107
  }
108
108
 
109
109
  export function rawFiles(paths, key) {
@@ -0,0 +1,142 @@
1
+ // LobsterAI(基于 OpenClaw):<应用数据>/LobsterAI/openclaw/state/agents/*/sessions/*.jsonl*。
2
+ import { basename, join } from 'node:path';
3
+ import { readFileSync } from 'node:fs';
4
+ import { home, expand, entries, isDir, isFile } from '../files.js';
5
+ import { jsonLines, parseJson, sortPaths, strip, isObject } from '../py.js';
6
+ import { demote } from '../markdown.js';
7
+ import { excluded, str } from './common.js';
8
+ import { toMs } from '../clock.js';
9
+
10
+ const MACHINERY = ['[LobsterAI system instructions]', '[cron:', '[OpenClaw heartbeat poll]', '<<<BEGIN_OPENCLAW_INTERNAL_CONTEXT>>>',
11
+ '[Subagent Context]', '[Subagent Task]', '[Session info]', 'Sender (untrusted metadata)'];
12
+ const REQUEST_MARKER = /^\[(?:Current|Scheduled) user request\]\s*$/;
13
+
14
+ /** Electron 应用数据目录:macOS ~/Library/Application Support,Windows %APPDATA%,Linux ~/.config。 */
15
+ function appData(env) {
16
+ if (process.platform === 'darwin') return join(home(), 'Library/Application Support');
17
+ if (process.platform === 'win32') return env.APPDATA || join(home(), 'AppData/Roaming');
18
+ return env.XDG_CONFIG_HOME ? expand(env.XDG_CONFIG_HOME) : join(home(), '.config');
19
+ }
20
+
21
+ export function locate(env = process.env) {
22
+ const base = join(appData(env), 'LobsterAI');
23
+ const agentsRoot = join(base, 'openclaw/state/agents');
24
+ return { base, agentsRoot, roots: [agentsRoot], marks: [base], skills: [join(base, 'SKILLs')],
25
+ skillNote: 'LobsterAI 可能还要在自己的技能设置里启用新技能' };
26
+ }
27
+
28
+ export function files(paths) {
29
+ const out = [];
30
+ for (const sessDir of sortPaths(entries(paths.agentsRoot).map(d => join(paths.agentsRoot, d.name, 'sessions')).filter(isDir))) {
31
+ for (const path of sortPaths(entries(sessDir).map(d => join(sessDir, d.name)))) {
32
+ const name = basename(path);
33
+ if (!name.includes('.jsonl') || name.includes('.trajectory') || name.includes('.deleted.')) continue;
34
+ if (!(name.endsWith('.jsonl') || name.includes('.jsonl.reset.')) || !isFile(path)) continue;
35
+ out.push(path);
36
+ }
37
+ }
38
+ return out;
39
+ }
40
+
41
+ /** 系统信封以 [Current user request] 结尾,真实请求在最后一个标记之后;无标记按机械前缀丢弃。 */
42
+ function cleanUserText(text) {
43
+ const t = strip(text);
44
+ if (!t) return '';
45
+ const lines = t.split('\n');
46
+ let keep = null;
47
+ for (const line of lines) {
48
+ if (REQUEST_MARKER.test(strip(line))) { keep = []; continue; }
49
+ if (keep) keep.push(line);
50
+ }
51
+ if (keep) { const s = strip(keep.join('\n')); if (s) return s; }
52
+ if (MACHINERY.some(p => t.startsWith(p)) || t.startsWith('[Request interrupted')) return '';
53
+ return t;
54
+ }
55
+
56
+ export function parse(path) {
57
+ const turns = [];
58
+ for (const line of jsonLines(readFileSync(path, 'utf8'))) {
59
+ if (!strip(line)) continue;
60
+ const ev = parseJson(line);
61
+ if (!isObject(ev) || ev.type !== 'message') continue; // session / model_change / custom_message 等内部事件
62
+ const ts = ev.timestamp;
63
+ const msg = isObject(ev.message) ? ev.message : {};
64
+ const content = msg.content, pieces = [];
65
+ if (msg.role === 'user') {
66
+ if (typeof content === 'string') { const t = cleanUserText(content); if (t) pieces.push(t); }
67
+ else if (Array.isArray(content)) for (const b of content) {
68
+ if (!isObject(b)) continue;
69
+ if (b.type === 'text') { const t = cleanUserText(str(b.text)); if (t) pieces.push(t); }
70
+ else if (b.type === 'image') pieces.push('[🖼️ 图片]');
71
+ }
72
+ if (pieces.length) turns.push([ts, 'user', pieces.join('\n\n')]);
73
+ } else if (msg.role === 'assistant' && Array.isArray(content)) {
74
+ for (const b of content) {
75
+ if (!isObject(b)) continue;
76
+ if (b.type === 'text') { const t = strip(str(b.text)); if (t) pieces.push(t); }
77
+ else if (b.type === 'image') pieces.push('[🖼️ 已生成图片]');
78
+ }
79
+ if (pieces.length) turns.push([ts, 'assistant', pieces.join('\n\n')]);
80
+ }
81
+ }
82
+ // Path.stem 只去最后一个后缀(x.jsonl.reset.N → x.jsonl.reset),取前 8 位即会话 ID 前缀。
83
+ return { sid: basename(path).replace(/\.[^.]*$/, '').slice(0, 8), turns };
84
+ }
85
+
86
+ export function build(entriesList, options = {}) {
87
+ const all = [];
88
+ for (const { data } of entriesList) {
89
+ if (!data.turns.some(t => t[1] === 'user')) continue;
90
+ for (const [ts, role, text] of data.turns) if (ts) all.push([ts, role, text, data.sid]);
91
+ }
92
+ return { turns: all, titles: {}, count: all.length };
93
+ }
94
+
95
+ // 同一最终回复的两个版本(带/不带 MEDIA 行、图片标记)在合并时去重。
96
+ function core(text) {
97
+ return text.split('\n').map(l => strip(l)).filter(s => s && !s.startsWith('MEDIA:') && !s.startsWith('[🖼️') && !s.startsWith('[📎')).join('\n');
98
+ }
99
+ function mergeConsecutive(turns) {
100
+ const merged = [];
101
+ for (const [ts, role, text] of turns) {
102
+ const last = merged[merged.length - 1];
103
+ if (last && last[1] === role) {
104
+ const prev = core(last[2]), cur = core(text);
105
+ if (cur === prev || (cur && prev.includes(cur))) continue;
106
+ if (prev && cur.includes(prev)) { last[2] = text; continue; }
107
+ last[2] = last[2] + '\n\n' + text;
108
+ } else merged.push([ts, role, text]);
109
+ }
110
+ return merged;
111
+ }
112
+
113
+ export function render(all, clock, userLabel, name = 'LobsterAI') {
114
+ const days = new Map();
115
+ for (const [ts, role, text, sid] of all) {
116
+ const day = clock.day(ts);
117
+ if (!days.has(day)) days.set(day, new Map());
118
+ const sessions = days.get(day);
119
+ if (!sessions.has(sid)) sessions.set(sid, []);
120
+ sessions.get(sid).push([ts, role, text]);
121
+ }
122
+ const bodies = new Map();
123
+ for (const [day, sessions] of days) {
124
+ const out = [];
125
+ for (const [sid, turns] of [...sessions].sort((a, b) => (a[1][0][0] < b[1][0][0] ? -1 : a[1][0][0] > b[1][0][0] ? 1 : 0))) {
126
+ out.push(`# ${sid}\n`);
127
+ for (const [ts, role, text] of mergeConsecutive(turns)) {
128
+ out.push(`## ${clock.hm(ts)} ${role === 'user' ? `🧑 ${userLabel}` : `🤖 ${name}`}\n`);
129
+ out.push(demote(text) + '\n');
130
+ }
131
+ }
132
+ bodies.set(day, out.join('\n'));
133
+ }
134
+ return bodies;
135
+ }
136
+
137
+ export function rawFiles(paths, key) {
138
+ return files(paths).filter(p => basename(p).startsWith(key));
139
+ }
140
+
141
+ export const _ms = toMs;
142
+ export default { id: 'lobsterai', folder: 'LobsterAI', name: 'LobsterAI', version: 1, locate, files, parse, build, render, rawFiles };
package/lib/sources/pi.js CHANGED
@@ -64,7 +64,7 @@ export function build(entries, options = {}) {
64
64
  }
65
65
 
66
66
  /** 每天一份;会话按首次出现的顺序,不重排、不合并不同消息。 */
67
- export function render(turns, clock, userLabel) {
67
+ export function render(turns, clock, userLabel, name = 'Pi') {
68
68
  const days = new Map();
69
69
  for (const [ts, role, text, eid, parent, n, stop, sid, source] of turns) {
70
70
  const day = clock.day(ts);
@@ -80,7 +80,7 @@ export function render(turns, clock, userLabel) {
80
80
  for (const { sid, source, turns: list } of sessions.values()) {
81
81
  out.push(`# ${sid}\n\n<!-- source: ${source} -->\n`);
82
82
  for (const [ts, role, text, eid, parent, n, stop] of list) {
83
- const label = role === 'user' ? userLabel : 'Pi';
83
+ const label = role === 'user' ? userLabel : name;
84
84
  out.push(`## ${clock.hm(ts)} ${label}\n\n<!-- id: ${show(eid)}; parent: ${show(parent)}; source-line: ${n}; stop: ${stop} -->\n\n${demote(text)}\n`);
85
85
  }
86
86
  }