dsh-session-history 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 fujingzhai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,165 @@
1
- # Temporary Holding Version
1
+ # Session History
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 让每个 agent 都能查到你在各个 agent 里聊过什么。
4
+
5
+ ## 用法与思路
6
+
7
+ ### 现在的 agent 记忆缺什么
8
+
9
+ - **各记各的。** 每个 agent 把对话存在自己的目录里,格式互不相通。今天在一个 agent 里定下的方案,明天换一个接着做,它一概不知。
10
+ - **只留摘要。** 自带的“记忆”多是模型挑着记下的几条要点:记什么、怎么概括由模型决定,原话、细节和来龙去脉都会丢,记错了也很难发现。
11
+ - **换了就没了。** 记忆只在自家可用,换一个 agent,之前积累的都用不上。
12
+
13
+ ### 本插件的做法:留原文,按需查
14
+
15
+ 1. **整理。** 定时把各家的会话清洗成按天存放的 Markdown 日志:只去掉系统提示、工具调用这类机械内容,你和助手说的话一字不改。整理由程序完成,不调用模型,结果每次都一样。
16
+ 2. **检索。** 为日志建本地全文索引。agent 需要回忆时,先用关键词找到相关的会话,再按需读原文;每次读多少有上限,不会一下子塞满上下文。
17
+ 3. **共用。** 整理结果以一个技能(`session-history`)提供给所有 agent。在任何一个 agent 里,都能查到其他 agent 里的对话。
18
+
19
+ 用的时候什么都不用做:你提到“之前”“上次”或 agent 不清楚来由的事,它会自己去查,并在回答里注明出处(日期、会话、行号)。
20
+
21
+ ### 为什么不做 RAG
22
+
23
+ 很多记忆方案会把对话切块、做向量嵌入,再按语义相似度召回。这里刻意不这样做:
24
+
25
+ - **要找的多是确切的东西。** 一个命令、一个参数、某天定下的决定——关键词能精确命中;语义相似度擅长“意思差不多”,在这类字符串上恰恰最不可靠。
26
+ - **嵌入要用模型。** 放在电脑上占资源,放到云端就得把全部对话发出去。
27
+ - **结果可以核对。** 每条结果都能回到原文;不会把“看起来相关”的片段混进来,让模型误以为是事实。
28
+ - **没有维护负担。** 不用管嵌入模型的版本,不用重新嵌入;日志就是普通文本,不装这个插件也能直接搜。
29
+ - **模型本来就会搜。** 现在的模型会自己挑关键词、换同义词、逐步缩小范围;检索只要做到快、准、输出可控,其余交给模型。
30
+
31
+ ## 功能
32
+
33
+ - **多家 agent**:Claude Code、Codex、Antigravity、Pi、DSH、LobsterAI,以及 WorkBuddy(实验性)。会话格式与其中某一家相同的其他 agent,或同一 agent 的第二套配置,可以手动添加。
34
+ - **检索以会话为单位**:会话标题和你的原话权重最高;命中太多时只列标题,并提示可以加哪些词收窄。繁简、全半角、大小写自动统一。
35
+ - **原始记录兜底**:命令、参数、报错原文多藏在工具调用里,可以在单个会话的原始记录中定点查找。
36
+ - **Claude Code 记忆提示**:检索时顺带列出对题的 Claude Code 记忆(整理过的结论),可先读这些。
37
+ - **技能说明自适应**:SKILL.md 只写你电脑上实际有的 agent,不让模型去查不存在的东西。
38
+ - **数据独立**:日志、索引与设置存在 `~/.session-history`,与插件分开;卸载、更新、重装都不受影响。
39
+ - **全程离线**:不调用模型,不联网。
40
+
41
+ ## 安装与上手
42
+
43
+ 在 DSH **插件 → 添加插件** 填包名:
44
+
45
+ ```text
46
+ dsh-session-history
47
+ ```
48
+
49
+ 或命令行(Web 版把 `desktop` 换成 `web`):
50
+
51
+ ```sh
52
+ dsh plugin --profile desktop add dsh-session-history
53
+ ```
54
+
55
+ 装好后打开插件详情:
56
+
57
+ 1. 启用后约 20 秒会自动做第一次整理,也可以点 **立即整理**。首次要读全部历史会话,几百 MB 约需半分钟到一两分钟;之后只重读有变化的会话,通常一两秒。
58
+ 2. 在 **技能接入** 里点 **建软链**(或 **全部接入**),让各 agent 能用上本技能。
59
+ 3. 新开一个对话,问一句“我们之前……”试试。
60
+
61
+ 不用 DSH 也能用:`npm i -g dsh-session-history`,再运行 `session-history setup`、`session-history refresh`、`session-history link all`。需要 Node 22.15 以上(推荐 24)。
62
+
63
+ ## 插件页
64
+
65
+ - **数据目录**:位置、最近整理时间、会话与日志数量、整理是否出错;可打开目录或立即整理。
66
+ - **Agents**:只列检测到的 agent(以及你添加的)。每家显示会话来源与数量、是否收录、技能是否生效。关掉「收录」只是不再整理它的新会话,已有日志照常检索。
67
+ - **技能接入**:只有检测到、但技能还没生效的 agent 才需要操作。按它们读取的技能目录归组,一组一个按钮,写明点了之后哪些 agent 生效;已建的软链列在这里,可以移除。
68
+ - **添加其他 agent**:见下节。
69
+ - **设置**:整理频率、检索前是否补整理、日志里你的发言标题、日界、时区、不收录的目录、Claude Code 记忆提示、Git 快照。
70
+ - **SKILL.md**:各 agent 实际读到的技能说明,可展开查看。
71
+
72
+ ### 添加其他 agent
73
+
74
+ 用于本插件未内置、但会话记录格式与某一家相同的 agent,或同一 agent 的另一套配置目录(多开、多账号)。要填:
75
+
76
+ | 项 | 填什么 |
77
+ |---|---|
78
+ | 名称 | 日志里助手的名字,也是检索时 `--agent` 用的名字 |
79
+ | 会话格式 | 它的会话记录与哪一家相同 |
80
+ | 会话目录 | 存放会话记录的那一层目录,按格式而定(见下表) |
81
+ | 技能目录(可选) | 它读取技能的文件夹;填了才能接入技能,留空只收录会话 |
82
+
83
+ | 会话格式 | 会话目录选哪一层 | 例子 |
84
+ |---|---|---|
85
+ | Claude Code | `projects`(里面是 `<项目>/<会话>.jsonl`) | Qoder CLI 的 `~/.qoder-cn/projects` |
86
+ | Codex | `sessions`(里面是 `<年>/<月>/<日>/rollout-*.jsonl`) | 另一个 `CODEX_HOME` 下的 `sessions` |
87
+ | Pi | `sessions`(里面是 `<目录>/<会话>.jsonl`) | 另一个 Pi 配置目录下的 `sessions` |
88
+ | DSH | `sessions`(里面是 `<目录>/<会话>/session.vN.jsonl.zstd`) | 另一个 `DSH_HOME` 下的 `sessions` |
89
+ | Antigravity | `brain`(里面是 `<会话>/.system_generated/logs/…`) | 第二个实例的 `antigravity-cli/brain` |
90
+ | LobsterAI(OpenClaw) | `agents`(里面是 `<agent>/sessions/<会话>.jsonl`) | 其他基于 OpenClaw 的客户端 |
91
+ | WorkBuddy(CodeBuddy) | `projects`(里面是 `<项目>/<会话>.jsonl`) | CodeBuddy Code 的 `~/.codebuddy/projects` |
92
+
93
+ 填好后点 **检查目录**,会告诉你按所选格式找到几个会话文件;找不到多半是层级或格式选错了。
94
+
95
+ ## 技能接入是怎么回事
96
+
97
+ 数据目录本身就是技能文件夹(里面有 SKILL.md 和入口 `bin/session-history`)。让某个 agent 用上它,只要在它读取的技能目录里放一条指向数据目录的软链 `session-history`,不拷副本,所以永远只有一份。
98
+
99
+ | Agent | 读取的技能目录 |
100
+ |---|---|
101
+ | Claude Code | `~/.claude/skills` |
102
+ | Codex | `~/.agents/skills`、`~/.codex/skills` |
103
+ | Antigravity | `~/.gemini/config/skills`(命令行)、`~/.gemini/antigravity/skills`(桌面版) |
104
+ | Pi | `~/.pi/agent/skills`、`~/.agents/skills` |
105
+ | DSH | `~/.dsh/skills`、`~/.agents/skills` |
106
+ | LobsterAI | 应用数据目录下的 `LobsterAI/SKILLs`(可能还需在它的技能设置里启用) |
107
+ | WorkBuddy | `~/.workbuddy/skills` |
108
+
109
+ 很多人只维护一个技能文件夹,其余目录用软链指向它。插件按真实路径判断:几家实际读的是同一个文件夹时,只需一条软链,建好后它们一起生效。已有同名的独立文件夹(多半是旧版拷贝)时不会覆盖,会提示冲突。Windows 用目录联接,不需要管理员权限。
110
+
111
+ ## 数据与卸载
112
+
113
+ | 位置 | 内容 | 卸载/更新/重装插件 |
114
+ |---|---|---|
115
+ | 插件包(DSH profile 的 `node_modules`) | 代码 | 随之替换或删除 |
116
+ | `~/.session-history` | `logs/<Agent>/` 日志(唯一的权威数据)、`config.json` 设置、`state/` 索引与缓存、SKILL.md 与入口 | 不动 |
117
+
118
+ - `state/` 可以随时删除,下次检索自动重建;`logs/` 请勿删除。
119
+ - 某个 agent 清理了自己的历史、或者被卸载,已整理的日志照样保留、照常检索。
120
+ - 卸载前可以在面板移除软链;不移也无妨,入口会提示引擎已不在,日志仍可直接用 `rg` 等工具搜索。重装后入口自动恢复。
121
+ - 改数据目录:设环境变量 `SESSION_HISTORY_HOME`,或在 profile 的 `cordis.patch.yml` 给本插件的行加 `config.home`;已有数据请整体搬过去。
122
+
123
+ ## 命令行
124
+
125
+ ```sh
126
+ session-history search 插件 更新失败 # 主体词+事件词;空格=同时出现,词内 | 表示任选
127
+ session-history search "VPN|openconnect" 断线 --agent Codex --since 08-01
128
+ session-history outline 01a06cc6 # 会话提纲:你的每条发言+末轮回复
129
+ session-history get 2ddbae3eed --context 1 # 读原文
130
+ session-history raw 5f3c92de "base_url|api.example" # 在原始记录里查工具调用与返回
131
+ session-history timeline --since 7d
132
+ session-history refresh | status | setup | link all | unlink claude | config
133
+ ```
134
+
135
+ ## 更新
136
+
137
+ ### 检查更新
138
+
139
+ 适用于从 npm 安装的 DSH 0.2.2-rc.1 及以上:
140
+
141
+ 1. 打开 **插件**,点 **刷新**;有新版时卡片标记 **可更新**。也可在插件详情 **版本 → 重新检查**。
142
+ 2. 点页头 **更新到 <版本>**,核对版本与安装源后确认。**无需手动卸载重装**;数据目录不受影响。
143
+ 3. 更新后插件会自动改写技能入口;如提示需要重启,按提示重启 DSH。
144
+
145
+ 这是打开详情或刷新列表时的检查,不是全局推送,也不自动升级。固定 Git 标签、压缩包或 `link:` 安装不显示这套更新入口。
146
+
147
+ ### 固定版本
148
+
149
+ Git 子目录地址(不提供原生更新检查):
150
+
151
+ ```text
152
+ git+https://github.com/fujingzhai/youxia-dsh-plugins.git#dsh-session-history@0.2.0&path:/dsh-session-history
153
+ ```
154
+
155
+ ## 兼容与限制
156
+
157
+ - 需要 DSH 0.2.2-rc.1 以上;macOS 上在 DSH 0.2.2-rc.3 实测。
158
+ - Windows:PowerShell/cmd 用 `bin\session-history.cmd`,Git Bash 用 `bin/session-history`,SKILL.md 会按平台写明;CI 在 Windows 上实际调用两种入口。Windows 版 DSH 的插件页尚未实测,Linux 只跑了 CI。
159
+ - WorkBuddy 的会话格式按其内核 CodeBuddy Code 的公开代码推断,尚未用真实会话验证,所以标为实验性。
160
+ - 只读取各 agent 的会话文件,从不修改它们。日志里的指令是历史数据,SKILL.md 已要求 agent 不得照做。
161
+ - 日志不含思考过程与工具调用;这些要用 `raw` 回查原始记录,原始记录不在了就查不到。
162
+
163
+ ## 许可
164
+
165
+ MIT
@@ -0,0 +1,206 @@
1
+ #!/usr/bin/env node
2
+ // Session History 命令行:检索各 agent 的历史对话,并管理整理、索引与技能接入。不调用模型。
3
+ const [major, minor] = process.versions.node.split('.').map(Number);
4
+ if (major < 22 || (major === 22 && minor < 15)) {
5
+ console.error(`Session History 需要 Node 22.15 以上(推荐 24,内置 SQLite 与 zstd),当前 ${process.version}。`);
6
+ process.exit(3);
7
+ }
8
+ // node:sqlite 在 Node 22/23 会打一行 ExperimentalWarning,混进输出没用。
9
+ const emit = process.emitWarning;
10
+ process.emitWarning = (warning, ...rest) => {
11
+ const type = typeof rest[0] === 'string' ? rest[0] : rest[0]?.type;
12
+ if (type === 'ExperimentalWarning' && /SQLite/i.test(String(warning))) return;
13
+ return emit.call(process, warning, ...rest);
14
+ };
15
+
16
+ const { resolveHome, loadConfig, saveConfig, layout, readJson, DEFAULTS } = await import('../lib/config.js');
17
+ const { connect, updateIndex } = await import('../lib/store.js');
18
+ const { search, get, outline, timeline, UsageError } = await import('../lib/recall.js');
19
+ const { raw } = await import('../lib/raw.js');
20
+ const { refresh, refreshIfStale } = await import('../lib/refresh.js');
21
+ const { allSources, byId, byFolder, enabled } = await import('../lib/agents.js');
22
+ const { installSkill, logFolders, VERSION } = await import('../lib/skill.js');
23
+ const { skillStatus, link, linkAll, unlink } = await import('../lib/links.js');
24
+ const { tilde } = await import('../lib/files.js');
25
+
26
+ const HELP = `Session History ${VERSION} — 各 agent 的历史对话检索(不调用模型)
27
+
28
+ 检索
29
+ search <词…> [--agent A] [--since D] [--until D] [--session ID] [--role user|assistant]
30
+ [--sort relevance|recent] [--limit 6] [--snippet 220] [--snippets] [--budget 3000]
31
+ outline <会话ID|块ID> [--agent A] [--all] [--width 100] [--budget 3000]
32
+ get <块ID> [--context 1] [--budget 4000]
33
+ raw <会话ID|块ID> <词…> [--agent A] [--width 200] [--budget 2000]
34
+ timeline [--since D] [--until D] [--agent A] [--all] [--budget 3000]
35
+
36
+ 管理
37
+ refresh [--agent A] 整理会话为日志并更新索引(只重读变过的会话)
38
+ index 只增量更新索引
39
+ status 数据目录、各 agent 与技能接入情况
40
+ setup 生成技能文件(SKILL.md、入口),首次使用先跑
41
+ link <agent|all> 在 agent 的技能目录里建指向数据目录的软链
42
+ unlink <agent> 移除上述软链
43
+ config [键 [值]] 查看或修改设置
44
+
45
+ 通用:--home DIR(数据目录,默认 ~/.session-history 或 $SESSION_HISTORY_HOME) --no-refresh(检索前不补整理)
46
+ 日期:YYYY-MM-DD、MM-DD、today、7d;--until 含当天。词:空格=AND,词内 | 任选其一。`;
47
+
48
+ const BOOL = new Set(['snippets', 'all', 'no-refresh', 'json', 'help']);
49
+ const NUM = { limit: 6, snippet: 220, budget: null, context: 1, width: null };
50
+
51
+ function parseArgs(argv) {
52
+ const args = { _: [] };
53
+ for (let i = 0; i < argv.length; i++) {
54
+ const a = argv[i];
55
+ if (a === '--') { args._.push(...argv.slice(i + 1)); break; }
56
+ if (a.startsWith('--')) {
57
+ const [key, inline] = a.slice(2).split(/=(.*)/s);
58
+ if (BOOL.has(key)) { args[key] = true; continue; }
59
+ const value = inline ?? argv[++i];
60
+ if (value === undefined) throw new UsageError(`--${key} 需要一个值`);
61
+ args[key] = value;
62
+ } else if (a === '-h') args.help = true;
63
+ else args._.push(a);
64
+ }
65
+ for (const key of Object.keys(NUM)) if (args[key] !== undefined) {
66
+ const n = Number(args[key]);
67
+ if (!Number.isInteger(n)) throw new UsageError(`--${key} 应为整数`);
68
+ args[key] = n;
69
+ }
70
+ return args;
71
+ }
72
+
73
+ /** --agent 收 Claude/claude/Claude Code 等写法,统一成日志文件夹名。 */
74
+ function findSource(value, config) {
75
+ const v = String(value).toLowerCase().replace(/\s+/g, '');
76
+ return allSources(config).find(s => s.id === v || s.folder.toLowerCase() === v || s.name.toLowerCase().replace(/\s+/g, '') === v);
77
+ }
78
+
79
+ function agentFolder(value, home, config) {
80
+ if (!value) return null;
81
+ const v = String(value).toLowerCase().replace(/\s+/g, '');
82
+ const folders = [...new Set([...allSources(config).map(s => s.folder), ...logFolders(home)])];
83
+ const hit = findSource(value, config)?.folder
84
+ || folders.find(f => f.toLowerCase() === v);
85
+ if (!hit) throw new UsageError(`--agent 可选:${folders.join('、')}`);
86
+ return hit;
87
+ }
88
+
89
+ function withIndex(home, config, fn) {
90
+ const db = connect(home);
91
+ try { updateIndex(home, config, db); return fn(db); } finally { db.close(); }
92
+ }
93
+
94
+ function statusText(home) {
95
+ const config = loadConfig(home);
96
+ const last = readJson(layout(home).status, null);
97
+ const { agents, targets, links } = skillStatus(home, config);
98
+ const lines = [`Session History ${VERSION}|数据目录 ${tilde(home)}`];
99
+ lines.push(last ? `最近整理 ${last.run}(${(last.ms / 1000).toFixed(1)} 秒)|索引 ${last.index?.sessions ?? '?'} 个会话、${last.index?.files ?? '?'} 份日志` : '尚未整理过:先跑 refresh');
100
+ for (const a of agents.filter(x => x.installed || x.custom)) {
101
+ const run = last?.agents?.[a.folder];
102
+ const src = !a.installed ? '未检测到' : enabled(byId(a.id), config) ? (run ? (run.ok ? `已整理 ${run.files} 个会话文件` : `整理出错:${run.error}`) : '已启用,待整理') : '已检测到,未启用整理';
103
+ const skill = { ready: `技能已生效(经 ${a.via})`, missing: '技能未生效', conflict: `技能冲突:${a.conflict?.path}`, nodir: '未设技能目录' }[a.state];
104
+ lines.push(` ${a.name.padEnd(12)} ${src}|${skill}`);
105
+ }
106
+ for (const t of targets) lines.push(` → 在 ${t.display} 建软链可让 ${t.agents.join('、')} 生效:session-history link all`);
107
+ for (const l of links) lines.push(` 软链 ${l.entry} → 数据目录(${l.agents.join('、')})`);
108
+ const legacy = logFolders(home).filter(f => !byFolder(f, config));
109
+ if (legacy.length) lines.push(` 已停用来源的旧日志:${legacy.join('、')}`);
110
+ return lines.join('\n');
111
+ }
112
+
113
+ async function main() {
114
+ const argv = process.argv.slice(2);
115
+ const args = parseArgs(argv);
116
+ const [cmd, ...rest] = args._;
117
+ if (!cmd || args.help || cmd === 'help') { console.log(HELP); return; }
118
+ const home = resolveHome(args.home);
119
+ const config = loadConfig(home);
120
+ const log = message => console.error(message);
121
+ const ctx = { config, cmd: 'session-history' };
122
+ const agent = agentFolder(args.agent, home, config);
123
+ const ensure = () => { if (!args['no-refresh']) refreshIfStale({ home }); };
124
+ const budget = d => args.budget ?? d;
125
+ if (args.budget !== undefined && args.budget < 100) throw new UsageError('budget 至少 100');
126
+ if (args.limit !== undefined && args.limit < 1) throw new UsageError('limit 为正数');
127
+ if (args.snippet !== undefined && args.snippet < 20) throw new UsageError('snippet 至少 20');
128
+ switch (cmd) {
129
+ case 'search':
130
+ ensure();
131
+ return console.log(withIndex(home, config, db => search(db, { query: rest, agent, since: args.since, until: args.until, session: args.session,
132
+ role: args.role, sort: args.sort || 'relevance', limit: args.limit ?? 6, snippet: args.snippet ?? 220, snippets: !!args.snippets, budget: budget(3000) }, ctx)));
133
+ case 'get':
134
+ if (!rest[0]) throw new UsageError('用法:get <块ID>');
135
+ ensure();
136
+ return console.log(withIndex(home, config, db => get(db, { id: rest[0], context: args.context ?? 1, budget: budget(4000) }, ctx)));
137
+ case 'outline':
138
+ if (!rest[0]) throw new UsageError('用法:outline <会话ID|块ID>');
139
+ ensure();
140
+ return console.log(withIndex(home, config, db => outline(db, { target: rest[0], agent, all: !!args.all, width: args.width ?? 100, budget: budget(3000) }, ctx)));
141
+ case 'raw':
142
+ if (rest.length < 2) throw new UsageError('用法:raw <会话ID|块ID> <词…>');
143
+ ensure();
144
+ return console.log(withIndex(home, config, db => raw(db, { target: rest[0], query: rest.slice(1), agent, width: args.width ?? 200, budget: budget(2000) }, ctx)));
145
+ case 'timeline':
146
+ ensure();
147
+ return console.log(withIndex(home, config, db => timeline(db, { since: args.since, until: args.until, agent, all: !!args.all, budget: budget(3000) }, ctx)));
148
+ case 'index':
149
+ return console.log(JSON.stringify(updateIndex(home, config)));
150
+ case 'refresh': {
151
+ const only = agent ? [byFolder(agent, config)?.id].filter(Boolean) : null;
152
+ const status = refresh({ home, only, log });
153
+ if (args.json) return console.log(JSON.stringify(status, null, 2));
154
+ if (status.skipped) return console.log(status.reason);
155
+ for (const [name, r] of Object.entries(status.agents)) console.log(`${name}: ${r.ok ? `OK 会话文件 ${r.files}(重读 ${r.parsed})· 日志 ${r.days} 天 · 变更 ${r.changed} 天` : 'ERROR ' + r.error}`);
156
+ console.log(`索引: ${status.index.ok ? `${status.index.sessions} 个会话 · 更新 ${status.index.updated} 份` : 'ERROR ' + status.index.error}|${(status.ms / 1000).toFixed(1)} 秒`);
157
+ const warnings = Object.values(status.agents).flatMap(r => r.warnings || []);
158
+ if (warnings.length) console.error(warnings.slice(0, 20).join('\n') + (warnings.length > 20 ? `\n……另有 ${warnings.length - 20} 条` : ''));
159
+ if (Object.values(status.agents).some(r => !r.ok) || !status.index.ok) process.exitCode = 1;
160
+ return;
161
+ }
162
+ case 'status':
163
+ return console.log(args.json ? JSON.stringify({ home, config, last: readJson(layout(home).status, null), agents: skillStatus(home, config) }, null, 2) : statusText(home));
164
+ case 'setup': {
165
+ const r = installSkill(home);
166
+ console.log(`技能文件已${r.changed.length ? '更新:' + r.changed.join('、') : '是最新'}|${tilde(layout(home).skill)}`);
167
+ console.log(statusText(home));
168
+ if (!readJson(layout(home).status)) console.log('\n下一步:session-history refresh(首次整理全部历史,可能要一两分钟)');
169
+ return;
170
+ }
171
+ case 'link': {
172
+ if (!rest[0]) throw new UsageError('用法:link <agent|all>');
173
+ installSkill(home);
174
+ const results = rest[0] === 'all' ? linkAll(home, config) : [link(home, findSource(rest[0], config)?.id || rest[0], config)];
175
+ if (!results.length) console.log('所有检测到的 agent 技能都已生效。');
176
+ for (const r of results) console.log(r.error ? `失败:${r.error}` : r.changed ? `已建软链 ${r.entry}(${r.agents.join('、')} 生效)` : `已生效(经 ${r.via})`);
177
+ return;
178
+ }
179
+ case 'unlink': {
180
+ if (!rest[0]) throw new UsageError('用法:unlink <agent>');
181
+ const id = findSource(rest[0], config)?.id || rest[0];
182
+ const r = unlink(home, id, config);
183
+ return console.log(`已移除 ${r.removed.join('、')}${r.affects.length ? `;共用该目录的 ${r.affects.join('、')} 也随之看不到` : ''}`);
184
+ }
185
+ case 'config': {
186
+ if (!rest.length) return console.log(JSON.stringify(config, null, 2));
187
+ const [key, ...value] = rest;
188
+ if (!(key in DEFAULTS) || key === 'agents') throw new UsageError(`可改的键:${Object.keys(DEFAULTS).filter(k => k !== 'agents').join('、')}(agents 请直接编辑 config.json)`);
189
+ if (!value.length) return console.log(JSON.stringify(config[key]));
190
+ let parsed = value.join(' ');
191
+ try { parsed = JSON.parse(parsed); } catch { /* 当字符串 */ }
192
+ const next = saveConfig(home, { [key]: parsed });
193
+ installSkill(home);
194
+ return console.log(`${key} = ${JSON.stringify(next[key])}`);
195
+ }
196
+ default:
197
+ throw new UsageError(`未知命令 ${cmd};session-history help 查看用法`);
198
+ }
199
+ }
200
+
201
+ try { await main(); }
202
+ catch (error) {
203
+ if (error instanceof UsageError) { console.error(error.message); process.exit(2); }
204
+ console.error(`Session History 出错:${error.stack || error.message}`);
205
+ process.exit(1);
206
+ }