fde-console 0.0.0-stage → 2.9.68
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 +21 -0
- package/README.md +128 -2
- package/README.zh-CN.md +130 -0
- package/assets/icon.svg +9 -0
- package/cordis.patch.yml +7 -0
- package/lib/agentActivity.js +1180 -0
- package/lib/agentContext.js +146 -0
- package/lib/agentTranscript.js +1398 -0
- package/lib/analyze.js +625 -0
- package/lib/attribute.js +205 -0
- package/lib/backup.js +366 -0
- package/lib/desktopAgents.js +123 -0
- package/lib/diary.js +333 -0
- package/lib/dingtalk.js +412 -0
- package/lib/feishu.js +580 -0
- package/lib/giteaClient.js +810 -0
- package/lib/giteeClient.js +372 -0
- package/lib/githubClient.js +361 -0
- package/lib/heatmap.js +99 -0
- package/lib/imNotify.js +378 -0
- package/lib/inbox.js +438 -0
- package/lib/instanceLock.js +122 -0
- package/lib/jobs.js +56 -0
- package/lib/learn.js +1388 -0
- package/lib/learnImport.js +283 -0
- package/lib/learnSeeds.js +97 -0
- package/lib/learnSeedsAiEng.js +77 -0
- package/lib/mcpCore.js +135 -0
- package/lib/members.js +160 -0
- package/lib/migration.js +403 -0
- package/lib/overview.js +376 -0
- package/lib/postmortem.js +148 -0
- package/lib/radarIgnore.js +134 -0
- package/lib/redact.js +76 -0
- package/lib/router.js +246 -0
- package/lib/routes-gitea.js +262 -0
- package/lib/routes-setup.js +40 -0
- package/lib/scorecard.js +111 -0
- package/lib/sessionRef.js +227 -0
- package/lib/sessionSnapshot.js +67 -0
- package/lib/sessionSuggest.js +186 -0
- package/lib/settings.js +783 -0
- package/lib/setupCheck.js +330 -0
- package/lib/ssrfGuard.js +145 -0
- package/lib/store.js +564 -0
- package/lib/storeDb.js +418 -0
- package/lib/taskEvents.js +243 -0
- package/lib/webhookOut.js +125 -0
- package/lib/weekly.js +439 -0
- package/lib/workSearch.js +220 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +46 -4
- package/plugin/adapter.js +157 -0
- package/plugin/client.js +282 -0
- package/plugin/index.mjs +116 -0
- package/plugin/static.js +99 -0
- package/scripts/backup-data.js +41 -0
- package/scripts/mcp-server.mjs +68 -0
- package/scripts/migrate-data.js +301 -0
- package/scripts/migrate-storage.js +47 -0
- package/scripts/seed-demo.js +200 -0
- package/scripts/write-agent-context.js +43 -0
- package/test/helpers/appAssembler.js +1078 -0
- package/web/client/fde-client.js +292 -0
- package/web/css/app.css +1510 -0
- package/web/index.html +69 -0
- package/web/js/api.js +72 -0
- package/web/js/app.js +313 -0
- package/web/js/icons.js +48 -0
- package/web/js/mock.js +1150 -0
- package/web/js/state.js +7 -0
- package/web/js/ui.js +276 -0
- package/web/js/views/activity.js +410 -0
- package/web/js/views/agents.js +892 -0
- package/web/js/views/board.js +1656 -0
- package/web/js/views/learn.js +530 -0
- package/web/js/views/members.js +344 -0
- package/web/js/views/onboarding.js +103 -0
- package/web/js/views/overview.js +508 -0
- package/web/js/views/radar.js +1359 -0
- package/web/js/views/search.js +149 -0
- package/web/js/views/settings.js +1351 -0
- package/web/js/views/topology.js +471 -0
- package/web/mock.json +2363 -0
|
@@ -0,0 +1,1180 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* agentActivity.js — 智能体工作观测(v2.6):五数据源适配器 + 聚合
|
|
5
|
+
*
|
|
6
|
+
* 让业主看到每个 AI 智能体「在干什么、哪个项目、产出内容预览」。五个数据源(全部只读):
|
|
7
|
+
* - zcode ~/.zcode/cli db/db.sqlite 的 session 表(新版主源:id/title/directory/时间/last_outcome)
|
|
8
|
+
* + 旧格式兜底:agents/sess_<uuid>/agent_xxx/metadata.json 与 exec/ 下 call_*.log
|
|
9
|
+
* - claude ~/.claude/projects <编码项目路径> 目录下各 jsonl(每行一个 JSON:queue-operation.content /
|
|
10
|
+
* last-prompt.lastPrompt / cwd 字段)
|
|
11
|
+
* - dsh ~/.dsh/sessions <编码项目路径> 下 session-N 目录内 session*.jsonl.zstd(首行 session 元数据含
|
|
12
|
+
* cwd/createdAt;node:zlib zstd 解压,大小封顶)+ 兼容 rollout-N.jsonl 明文
|
|
13
|
+
* - workbuddy ~/.workbuddy/workbuddy.db(node:sqlite DatabaseSync {readOnly:true},仅 SELECT sessions 表
|
|
14
|
+
* id/cwd/title/status/created_at/last_activity_at 五列,凭据红线不碰其余表)
|
|
15
|
+
* - codex ~/.codex/sessions YYYY/MM/DD/rollout-*.jsonl(首行 session_meta 的 id/cwd/timestamp;
|
|
16
|
+
* 标题取首条 user response_item,预览取尾部最后一条文本)
|
|
17
|
+
*
|
|
18
|
+
* 另有 opencode = node:sqlite 只读 session 表五列,仅服务桌面成员册派生(不进活动面板)。
|
|
19
|
+
*
|
|
20
|
+
* 统一规则:每源取最近 perSourceLimit(10) 条;合并按 lastActiveAt 倒序;总数 ≤ maxItems(40);
|
|
21
|
+
* preview = 该会话最后一条消息/输出的前 previewChars(200) 字(读文件尾部实现,不全文读大文件)。
|
|
22
|
+
* 全部路径可配置(config.agentActivity,空串 = 回退本机默认位置);某源目录不存在 → 该源
|
|
23
|
+
* ok:false 跳过不报错;每源独立 try/catch,单源故障不影响其他源。
|
|
24
|
+
*
|
|
25
|
+
* 红线:对所有数据源一律只读(sqlite {readOnly:true}、文件只 openSync 读、绝不写);凭据文件
|
|
26
|
+
* (.env/.credentials 等)一律不读不碰;运行中服务不碰。
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
const fs = require('node:fs');
|
|
30
|
+
const os = require('node:os');
|
|
31
|
+
const path = require('node:path');
|
|
32
|
+
const zlib = require('node:zlib');
|
|
33
|
+
|
|
34
|
+
const { encodeRef, locatorShapeOk } = require('./sessionRef');
|
|
35
|
+
|
|
36
|
+
/** v2.3(D5):形状合法才发 ref(不透明引用)——可回查的源才填,防死引用进活动流 */
|
|
37
|
+
function refOf(loc) {
|
|
38
|
+
try {
|
|
39
|
+
return locatorShapeOk(loc) ? encodeRef(loc) : '';
|
|
40
|
+
} catch (e) {
|
|
41
|
+
return '';
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ---------- 配置默认值与归一化 ----------
|
|
46
|
+
|
|
47
|
+
const SOURCE_IDS = ['zcode', 'claude', 'dsh', 'workbuddy', 'codex'];
|
|
48
|
+
|
|
49
|
+
// v2.6 桌面成员册专用源:参与 normalize 回填与 settings 校验(codex 已升为活动面板正式源,见 SOURCE_IDS)
|
|
50
|
+
// hermes(2026-11-03 第七源)同 opencode 口径:成员册/设置/阅读器,不进活动面板聚合
|
|
51
|
+
const ALL_SOURCE_IDS = [...SOURCE_IDS, 'opencode', 'hermes'];
|
|
52
|
+
|
|
53
|
+
const SOURCE_DEFAULTS = {
|
|
54
|
+
zcode: { enabled: true, root: '' }, // '' = ~/.zcode/cli
|
|
55
|
+
claude: { enabled: true, root: '' }, // '' = ~/.claude/projects
|
|
56
|
+
dsh: { enabled: true, root: '' }, // '' = ~/.dsh/sessions
|
|
57
|
+
workbuddy: { enabled: true, dbPath: '' }, // '' = ~/.workbuddy/workbuddy.db
|
|
58
|
+
codex: { enabled: true, root: '' }, // '' = ~/.codex/sessions(ChatGPT 桌面 rollout 会话)
|
|
59
|
+
opencode: { enabled: true, dbPath: '' }, // '' = ~/.local/share/opencode/opencode.db
|
|
60
|
+
// hermes(2026-11-03 第七源,opencode 同款待遇):桌面成员册+阅读器,不进活动面板五源
|
|
61
|
+
//(aggregate/snapshot/heatmap/agentContext 走 SOURCE_IDS,见各处注释);'' = %LOCALAPPDATA%/hermes/state.db
|
|
62
|
+
hermes: { enabled: true, dbPath: '' },
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// v2.3 会话阅读器:会话列表与全文的限额(normalizeAgentActivity 兜底,F1)
|
|
66
|
+
const DEFAULT_SESSION_LIST_LIMITS = { limit: 20, maxLimit: 50 };
|
|
67
|
+
const DEFAULT_TRANSCRIPT_LIMITS = { maxMessages: 1000, maxCharsPerMessage: 20000 };
|
|
68
|
+
|
|
69
|
+
const DEFAULT_AGENT_ACTIVITY = {
|
|
70
|
+
enabled: true,
|
|
71
|
+
perSourceLimit: 10,
|
|
72
|
+
maxItems: 40,
|
|
73
|
+
previewChars: 200,
|
|
74
|
+
sessionList: clone(DEFAULT_SESSION_LIST_LIMITS),
|
|
75
|
+
transcript: clone(DEFAULT_TRANSCRIPT_LIMITS),
|
|
76
|
+
sources: clone(SOURCE_DEFAULTS),
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
function clone(v) {
|
|
80
|
+
return v === undefined ? v : JSON.parse(JSON.stringify(v));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function isPlainObject(v) {
|
|
84
|
+
return v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 节归一化:缺省键回填默认值(store.mergeConfigDefaults / settings PATCH 回填共用,防部分 PATCH 抹默认) */
|
|
88
|
+
function normalizeAgentActivity(section) {
|
|
89
|
+
const src = isPlainObject(section) ? section : {};
|
|
90
|
+
const out = clone(DEFAULT_AGENT_ACTIVITY);
|
|
91
|
+
if (src.enabled !== undefined) out.enabled = src.enabled === true;
|
|
92
|
+
for (const k of ['perSourceLimit', 'maxItems', 'previewChars']) {
|
|
93
|
+
if (Number.isInteger(src[k]) && src[k] > 0) out[k] = src[k];
|
|
94
|
+
}
|
|
95
|
+
out.sources = {};
|
|
96
|
+
for (const id of ALL_SOURCE_IDS) {
|
|
97
|
+
out.sources[id] = Object.assign(
|
|
98
|
+
clone(SOURCE_DEFAULTS[id]),
|
|
99
|
+
isPlainObject(src.sources) && isPlainObject(src.sources[id]) ? src.sources[id] : {}
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
// v2.3 会话阅读器限额:子节兜底(非法/缺失回默认,防手改坏值进运行期)
|
|
103
|
+
for (const [key, def] of [['sessionList', DEFAULT_SESSION_LIST_LIMITS], ['transcript', DEFAULT_TRANSCRIPT_LIMITS]]) {
|
|
104
|
+
const sub = isPlainObject(src[key]) ? src[key] : {};
|
|
105
|
+
out[key] = {};
|
|
106
|
+
for (const k of Object.keys(def)) {
|
|
107
|
+
out[key][k] = Number.isInteger(sub[k]) && sub[k] > 0 ? sub[k] : def[k];
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** '~' 展开为用户主目录;空串返回 ''(由调用方回退默认位置) */
|
|
114
|
+
function resolveHome(p) {
|
|
115
|
+
if (typeof p !== 'string' || p.trim() === '') return '';
|
|
116
|
+
if (p === '~') return os.homedir();
|
|
117
|
+
if (p.startsWith('~/') || p.startsWith('~\\')) return path.join(os.homedir(), p.slice(2));
|
|
118
|
+
return p;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function defaultRoot(id) {
|
|
122
|
+
const h = os.homedir();
|
|
123
|
+
switch (id) {
|
|
124
|
+
case 'zcode':
|
|
125
|
+
return path.join(h, '.zcode', 'cli');
|
|
126
|
+
case 'claude':
|
|
127
|
+
return path.join(h, '.claude', 'projects');
|
|
128
|
+
case 'dsh':
|
|
129
|
+
return path.join(h, '.dsh', 'sessions');
|
|
130
|
+
case 'workbuddy':
|
|
131
|
+
return path.join(h, '.workbuddy', 'workbuddy.db');
|
|
132
|
+
case 'codex':
|
|
133
|
+
return path.join(h, '.codex', 'sessions');
|
|
134
|
+
case 'opencode':
|
|
135
|
+
return path.join(h, '.local', 'share', 'opencode', 'opencode.db');
|
|
136
|
+
case 'hermes': {
|
|
137
|
+
// Hermes Agent 数据目录在本机 %LOCALAPPDATA%\hermes(~/.hermes 只有 skills,考古结论见评审)
|
|
138
|
+
const lad = process.env.LOCALAPPDATA && String(process.env.LOCALAPPDATA).trim();
|
|
139
|
+
return path.join(lad || path.join(h, 'AppData', 'Local'), 'hermes', 'state.db');
|
|
140
|
+
}
|
|
141
|
+
default:
|
|
142
|
+
return '';
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ---------- 小工具 ----------
|
|
147
|
+
|
|
148
|
+
/** 文本净化:控制字符(保留换行/制表)替换为空格 + ANSI 转义剔除 */
|
|
149
|
+
function sanitizeText(s) {
|
|
150
|
+
return String(s)
|
|
151
|
+
.replace(/\x1b\[[0-9;]*[A-Za-z]/g, '')
|
|
152
|
+
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, ' ');
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 压成单行并截断到 max 字符(中间不省略,尾部截断) */
|
|
156
|
+
function truncateOneLine(s, max) {
|
|
157
|
+
const one = sanitizeText(s).replace(/\s+/g, ' ').trim();
|
|
158
|
+
if (one.length <= max) return one;
|
|
159
|
+
return one.slice(0, Math.max(0, max));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** 读文件尾部 maxBytes 字节(openSync 只读;小文件全文)。文件缺失/异常返回 null */
|
|
163
|
+
function readTail(file, maxBytes) {
|
|
164
|
+
let fd;
|
|
165
|
+
try {
|
|
166
|
+
const st = fs.statSync(file);
|
|
167
|
+
if (!st.isFile()) return null;
|
|
168
|
+
fd = fs.openSync(file, 'r');
|
|
169
|
+
const size = st.size;
|
|
170
|
+
const start = size > maxBytes ? size - maxBytes : 0;
|
|
171
|
+
const len = size - start;
|
|
172
|
+
const buf = Buffer.alloc(len);
|
|
173
|
+
const got = fs.readSync(fd, buf, 0, len, start);
|
|
174
|
+
return { buf: buf.subarray(0, got), truncated: start > 0, size };
|
|
175
|
+
} catch (e) {
|
|
176
|
+
return null;
|
|
177
|
+
} finally {
|
|
178
|
+
if (fd !== undefined) {
|
|
179
|
+
try { fs.closeSync(fd); } catch (e) { /* 收尾互不阻塞 */ }
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** 读文件头部 maxBytes 字节(标题取首条用户消息用) */
|
|
185
|
+
function readHead(file, maxBytes) {
|
|
186
|
+
let fd;
|
|
187
|
+
try {
|
|
188
|
+
const st = fs.statSync(file);
|
|
189
|
+
if (!st.isFile()) return null;
|
|
190
|
+
fd = fs.openSync(file, 'r');
|
|
191
|
+
const len = Math.min(st.size, maxBytes);
|
|
192
|
+
const buf = Buffer.alloc(len);
|
|
193
|
+
const got = fs.readSync(fd, buf, 0, len, 0);
|
|
194
|
+
return { buf: buf.subarray(0, got), truncated: st.size > maxBytes, size: st.size };
|
|
195
|
+
} catch (e) {
|
|
196
|
+
return null;
|
|
197
|
+
} finally {
|
|
198
|
+
if (fd !== undefined) {
|
|
199
|
+
try { fs.closeSync(fd); } catch (e) { /* 收尾互不阻塞 */ }
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** JSONL 缓冲 → 逐行 try-parse(截断头的首行丢弃,防半行 JSON) */
|
|
205
|
+
function parseJsonlBuffer(r) {
|
|
206
|
+
if (!r) return [];
|
|
207
|
+
let text = r.buf.toString('utf8');
|
|
208
|
+
if (r.truncated) {
|
|
209
|
+
const nl = text.indexOf('\n');
|
|
210
|
+
if (nl >= 0) text = text.slice(nl + 1);
|
|
211
|
+
else return [];
|
|
212
|
+
}
|
|
213
|
+
const out = [];
|
|
214
|
+
for (const line of text.split('\n')) {
|
|
215
|
+
const t = line.trim();
|
|
216
|
+
if (!t) continue;
|
|
217
|
+
try {
|
|
218
|
+
out.push(JSON.parse(t));
|
|
219
|
+
} catch (e) { /* 半行/非 JSON 行跳过 */ }
|
|
220
|
+
}
|
|
221
|
+
return out;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** 从一条 JSONL 记录提取人类可读文本(claude/dsh 家族通用:content/lastPrompt/message/text) */
|
|
225
|
+
function extractLineText(o) {
|
|
226
|
+
if (!isPlainObject(o)) return null;
|
|
227
|
+
if (typeof o.content === 'string' && o.content.trim()) return o.content;
|
|
228
|
+
if (typeof o.lastPrompt === 'string' && o.lastPrompt.trim()) return o.lastPrompt;
|
|
229
|
+
const m = o.message;
|
|
230
|
+
if (typeof m === 'string' && m.trim()) return m;
|
|
231
|
+
if (isPlainObject(m)) {
|
|
232
|
+
if (typeof m.content === 'string' && m.content.trim()) return m.content;
|
|
233
|
+
if (Array.isArray(m.content)) {
|
|
234
|
+
const t = m.content
|
|
235
|
+
.filter((b) => isPlainObject(b) && typeof b.text === 'string' && b.text.trim())
|
|
236
|
+
.map((b) => b.text)
|
|
237
|
+
.join(' ');
|
|
238
|
+
if (t.trim()) return t;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (typeof o.text === 'string' && o.text.trim()) return o.text;
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** 从 JSONL 记录数组中取最后一条有文本的记录文本 */
|
|
246
|
+
function lastText(objs) {
|
|
247
|
+
for (let i = objs.length - 1; i >= 0; i--) {
|
|
248
|
+
const t = extractLineText(objs[i]);
|
|
249
|
+
if (t) return t;
|
|
250
|
+
}
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** 取第一条有文本的记录文本 */
|
|
255
|
+
function firstText(objs) {
|
|
256
|
+
for (const o of objs) {
|
|
257
|
+
const t = extractLineText(o);
|
|
258
|
+
if (t) return t;
|
|
259
|
+
}
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** tail 缓冲里抓最后一个 "cwd":"..." 字段值(claude jsonl 家族;JSON 转义反转) */
|
|
264
|
+
function cwdFromBuffer(r) {
|
|
265
|
+
if (!r) return '';
|
|
266
|
+
const text = r.buf.toString('utf8');
|
|
267
|
+
const re = /"cwd"\s*:\s*"((?:[^"\\]|\\.)*)"/g;
|
|
268
|
+
let m;
|
|
269
|
+
let last = null;
|
|
270
|
+
while ((m = re.exec(text)) !== null) last = m[1];
|
|
271
|
+
if (last === null) return '';
|
|
272
|
+
try {
|
|
273
|
+
return JSON.parse(`"${last}"`);
|
|
274
|
+
} catch (e) {
|
|
275
|
+
return '';
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* 编码项目目录名 → 项目路径(尽力解码)。实测 dsh 编码:不安全字符 → `~HEX4`(仅前导波浪号,
|
|
281
|
+
* 连续转义共享分隔,如 `开发` → `~5F00~53D1`),路径分隔符 → `-`,目录名两端 `--` 包裹;
|
|
282
|
+
* 首段单字符视作 Windows 盘符。claude 的编码对项目名里的 `-` 有歧义(有损),
|
|
283
|
+
* 仅作 cwd 字段缺失时的兜底。
|
|
284
|
+
*/
|
|
285
|
+
function decodeProjectDirName(name) {
|
|
286
|
+
if (typeof name !== 'string' || !name) return '';
|
|
287
|
+
const decoded = name.replace(/~([0-9A-Fa-f]{4})/g, (_, h) => {
|
|
288
|
+
try { return String.fromCharCode(parseInt(h, 16)); } catch (e) { return '-'; }
|
|
289
|
+
});
|
|
290
|
+
const trimmed = decoded.replace(/^-+|-+$/g, '');
|
|
291
|
+
const segs = trimmed.split('-').filter((s) => s.length > 0);
|
|
292
|
+
if (segs.length === 0) return '';
|
|
293
|
+
if (segs[0].length === 1 && segs.length > 1) return `${segs[0]}:\\${segs.slice(1).join('\\')}`;
|
|
294
|
+
return segs.join(path.sep);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function toIso(ms) {
|
|
298
|
+
const t = Number(ms);
|
|
299
|
+
if (!Number.isFinite(t) || t <= 0) return null;
|
|
300
|
+
try {
|
|
301
|
+
return new Date(t).toISOString();
|
|
302
|
+
} catch (e) {
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function toIsoFromValue(v) {
|
|
308
|
+
if (v === null || v === undefined || v === '') return null;
|
|
309
|
+
if (typeof v === 'number' && Number.isFinite(v)) return toIso(v < 1e12 ? v * 1000 : v); // 秒/毫秒自适应
|
|
310
|
+
if (typeof v === 'string') {
|
|
311
|
+
const n = Number(v);
|
|
312
|
+
if (Number.isFinite(n) && n > 0 && /^\d+$/.test(v.trim())) return toIso(n < 1e12 ? n * 1000 : n);
|
|
313
|
+
const t = Date.parse(v);
|
|
314
|
+
if (Number.isFinite(t)) return new Date(t).toISOString();
|
|
315
|
+
}
|
|
316
|
+
return null;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** 最近活动距今 < ACTIVE_WINDOW_MS 视作运行中 */
|
|
320
|
+
const ACTIVE_WINDOW_MS = 10 * 60 * 1000;
|
|
321
|
+
|
|
322
|
+
function stateFor(lastActiveMs, now, explicit) {
|
|
323
|
+
if (typeof explicit === 'string' && explicit) return explicit;
|
|
324
|
+
if (Number.isFinite(lastActiveMs) && now - lastActiveMs >= 0 && now - lastActiveMs < ACTIVE_WINDOW_MS) {
|
|
325
|
+
return 'active';
|
|
326
|
+
}
|
|
327
|
+
return 'idle';
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** 统一条目形状(缺字段容错 + preview/title 截断);id=来源会话标识(workbuddy 透传主键,其余源暂空) */
|
|
331
|
+
function makeItem(partial, opts) {
|
|
332
|
+
const o = partial || {};
|
|
333
|
+
const previewChars = (opts && opts.previewChars) || 200;
|
|
334
|
+
const now = (opts && opts.now) || Date.now();
|
|
335
|
+
const lastMs = o.lastActiveMs;
|
|
336
|
+
const item = {
|
|
337
|
+
id: String(o.id || ''),
|
|
338
|
+
agent: String(o.agent || ''),
|
|
339
|
+
agentName: String(o.agentName || o.agent || ''),
|
|
340
|
+
projectId: typeof o.projectId === 'string' ? o.projectId : '',
|
|
341
|
+
title: truncateOneLine(o.title || '', 80),
|
|
342
|
+
preview: truncateOneLine(o.preview || '', previewChars),
|
|
343
|
+
startedAt: toIso(o.startedMs) || toIso(lastMs) || toIso(now),
|
|
344
|
+
lastActiveAt: toIso(lastMs) || toIso(now),
|
|
345
|
+
state: stateFor(lastMs, now, o.state),
|
|
346
|
+
};
|
|
347
|
+
// v2.3(D5):可回查源增可选 ref(不透明引用,lib/sessionRef.js 编码)——无则不出键,形状兼容
|
|
348
|
+
if (typeof o.ref === 'string' && o.ref) item.ref = o.ref;
|
|
349
|
+
return item;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** 目录 mtime(不存在返回 null) */
|
|
353
|
+
function dirMtime(dir) {
|
|
354
|
+
try {
|
|
355
|
+
return fs.statSync(dir).mtimeMs;
|
|
356
|
+
} catch (e) {
|
|
357
|
+
return null;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** 目录是否存在 */
|
|
362
|
+
function isDir(p) {
|
|
363
|
+
try {
|
|
364
|
+
return fs.statSync(p).isDirectory();
|
|
365
|
+
} catch (e) {
|
|
366
|
+
return false;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// ---------- 适配器①:ZCode(~/.zcode/cli) ----------
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* ZCode 新版把会话迁进 db/db.sqlite(session 表与 opencode 同构),旧的 sess_* 目录只剩残留。
|
|
374
|
+
* 只 SELECT session 表所需列(凭据红线:不碰 message/part 之外的任何表也不写库)。
|
|
375
|
+
* 返回 null = 该库不可用(无 node:sqlite / 打不开 / 查询失败),由文件兜底。
|
|
376
|
+
*/
|
|
377
|
+
function zcodeDbItems(dbPath, limit, opts) {
|
|
378
|
+
let DatabaseSync;
|
|
379
|
+
try {
|
|
380
|
+
({ DatabaseSync } = require('node:sqlite'));
|
|
381
|
+
} catch (e) {
|
|
382
|
+
return null;
|
|
383
|
+
}
|
|
384
|
+
let db;
|
|
385
|
+
try {
|
|
386
|
+
db = new DatabaseSync(dbPath, { readOnly: true });
|
|
387
|
+
} catch (e) {
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
try {
|
|
391
|
+
let rows;
|
|
392
|
+
try {
|
|
393
|
+
rows = db
|
|
394
|
+
.prepare(
|
|
395
|
+
'SELECT id, directory, title, time_created, time_updated, last_outcome FROM session WHERE time_deleted IS NULL ORDER BY time_updated DESC LIMIT ?'
|
|
396
|
+
)
|
|
397
|
+
.all(limit);
|
|
398
|
+
} catch (e) {
|
|
399
|
+
// 老库无 time_deleted/last_outcome 列 → 退到最小列集
|
|
400
|
+
rows = db
|
|
401
|
+
.prepare('SELECT id, directory, title, time_created, time_updated FROM session ORDER BY time_updated DESC LIMIT ?')
|
|
402
|
+
.all(limit);
|
|
403
|
+
}
|
|
404
|
+
return (Array.isArray(rows) ? rows : []).map((r) =>
|
|
405
|
+
makeItem(
|
|
406
|
+
{
|
|
407
|
+
id: String(r.id === null || r.id === undefined ? '' : r.id),
|
|
408
|
+
agent: 'zcode',
|
|
409
|
+
agentName: 'ZCode',
|
|
410
|
+
projectId: typeof r.directory === 'string' ? r.directory : '',
|
|
411
|
+
title: (typeof r.title === 'string' && r.title.trim()) || `ZCode 会话 ${String(r.id || '').slice(0, 8)}`,
|
|
412
|
+
preview: '',
|
|
413
|
+
startedMs: r.time_created,
|
|
414
|
+
lastActiveMs: r.time_updated,
|
|
415
|
+
// v2.9.21 合并修正:last_outcome 为空(运行中/未知)不传 explicit,stateFor 按时间窗判 active——
|
|
416
|
+
// 远端原实现强制 idle 会把正在工作的 ZCode 打回「空闲」(业主最初报的缺陷回归)
|
|
417
|
+
state: r.last_outcome === 'error' ? 'failed' : r.last_outcome === 'completed' ? 'completed' : undefined,
|
|
418
|
+
ref: refOf({ s: 'zcode', k: 'session', v: { id: String(r.id === null || r.id === undefined ? '' : r.id) } }),
|
|
419
|
+
},
|
|
420
|
+
opts
|
|
421
|
+
)
|
|
422
|
+
);
|
|
423
|
+
} catch (e) {
|
|
424
|
+
return null;
|
|
425
|
+
} finally {
|
|
426
|
+
try { db.close(); } catch (e) { /* 收尾互不阻塞 */ }
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* zcode:db.sqlite 为主、旧 sess_* 目录兜底(两者同 id 视作同一会话,db 优先)。
|
|
432
|
+
* 旧格式(无 db 目录 / db 打不开 / 空库)行为与原实现完全一致。
|
|
433
|
+
*/
|
|
434
|
+
function zcodeAdapter(sourceCfg, opts) {
|
|
435
|
+
const limit = (opts && opts.limit) || 10;
|
|
436
|
+
// 测试注入缝(v2.9.21 合并保留):opts.listSessions(sourceCfg, limit) → { ok, detail, rows },
|
|
437
|
+
// 行形状 = db session 表列;提供时跳过 db/目录双源(AGENTS.md 坑 5:测试不建 sqlite 夹具)
|
|
438
|
+
const injected = opts && typeof opts.listSessions === 'function' ? opts.listSessions(sourceCfg, limit) : null;
|
|
439
|
+
if (injected) {
|
|
440
|
+
if (!injected || injected.ok === false) return { ok: false, detail: (injected && injected.detail) || '会话清单不可用', items: [] };
|
|
441
|
+
const items = (Array.isArray(injected.rows) ? injected.rows : []).map((r) =>
|
|
442
|
+
makeItem(
|
|
443
|
+
{
|
|
444
|
+
id: String(r.id === null || r.id === undefined ? '' : r.id),
|
|
445
|
+
agent: 'zcode',
|
|
446
|
+
agentName: 'ZCode',
|
|
447
|
+
projectId: typeof r.directory === 'string' ? r.directory : '',
|
|
448
|
+
title: (typeof r.title === 'string' && r.title.trim()) || `ZCode 会话 ${String(r.id || '').slice(0, 8)}`,
|
|
449
|
+
preview: '',
|
|
450
|
+
startedMs: r.time_created,
|
|
451
|
+
lastActiveMs: r.time_updated,
|
|
452
|
+
ref: refOf({ s: 'zcode', k: 'session', v: { id: String(r.id === null || r.id === undefined ? '' : r.id) } }),
|
|
453
|
+
},
|
|
454
|
+
opts
|
|
455
|
+
)
|
|
456
|
+
);
|
|
457
|
+
return { ok: true, detail: `${items.length} 会话`, items };
|
|
458
|
+
}
|
|
459
|
+
const root = resolveHome(sourceCfg.root) || defaultRoot('zcode');
|
|
460
|
+
if (!isDir(root)) return { ok: false, detail: `目录不存在: ${root}`, items: [] };
|
|
461
|
+
|
|
462
|
+
const legacy = zcodeLegacyAdapter(root, limit, opts);
|
|
463
|
+
const dbPath = path.join(root, 'db', 'db.sqlite');
|
|
464
|
+
if (!fs.existsSync(dbPath)) return legacy;
|
|
465
|
+
|
|
466
|
+
const dbItems = zcodeDbItems(dbPath, limit, opts);
|
|
467
|
+
if (!dbItems || dbItems.length === 0) return legacy;
|
|
468
|
+
|
|
469
|
+
const seen = new Set(dbItems.map((it) => it.id));
|
|
470
|
+
const merged = dbItems.concat(legacy.items.filter((it) => !seen.has(it.id)));
|
|
471
|
+
merged.sort((a, b) => (Date.parse(b.lastActiveAt) || 0) - (Date.parse(a.lastActiveAt) || 0));
|
|
472
|
+
return { ok: true, detail: `${merged.length} 会话`, items: merged.slice(0, limit) };
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* sess_* 目录散布在 root/sess_*、root/agents/sess_*、root/exec/sess_*(同 id 视作同一会话合并)。
|
|
477
|
+
* 标题/项目:agents 下 agent_N 目录 metadata.json 的 description/cwd/createdAt(实测含中文描述);
|
|
478
|
+
* 预览:exec/<id>/ 最新 call_N-stdout.log 尾部(缺则 agent_N 目录 output.txt 尾部)。
|
|
479
|
+
*/
|
|
480
|
+
function zcodeLegacyAdapter(root, limit, opts) {
|
|
481
|
+
const candidates = new Map(); // sessId → { dirs:[], mtimeMs }
|
|
482
|
+
const scanDir = (dir) => {
|
|
483
|
+
let entries;
|
|
484
|
+
try {
|
|
485
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
486
|
+
} catch (e) {
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
for (const ent of entries) {
|
|
490
|
+
if (!ent.isDirectory() || !ent.name.startsWith('sess_')) continue;
|
|
491
|
+
const full = path.join(dir, ent.name);
|
|
492
|
+
const mt = dirMtime(full);
|
|
493
|
+
const prev = candidates.get(ent.name) || { dirs: [], mtimeMs: 0 };
|
|
494
|
+
prev.dirs.push(full);
|
|
495
|
+
if (mt !== null && mt > prev.mtimeMs) prev.mtimeMs = mt;
|
|
496
|
+
candidates.set(ent.name, prev);
|
|
497
|
+
}
|
|
498
|
+
};
|
|
499
|
+
scanDir(root);
|
|
500
|
+
scanDir(path.join(root, 'agents'));
|
|
501
|
+
scanDir(path.join(root, 'exec'));
|
|
502
|
+
|
|
503
|
+
const sorted = [...candidates.entries()].sort((a, b) => b[1].mtimeMs - a[1].mtimeMs).slice(0, limit);
|
|
504
|
+
|
|
505
|
+
const items = [];
|
|
506
|
+
for (const [sessId, info] of sorted) {
|
|
507
|
+
const agentsDir = path.join(root, 'agents', sessId);
|
|
508
|
+
const execDir = path.join(root, 'exec', sessId);
|
|
509
|
+
|
|
510
|
+
// 元数据:agents/<id>/agent_*/metadata.json(取 mtime 最新的一个)
|
|
511
|
+
let meta = null;
|
|
512
|
+
let newestAgentDir = null;
|
|
513
|
+
let newestAgentMtime = -1;
|
|
514
|
+
try {
|
|
515
|
+
for (const ent of fs.readdirSync(agentsDir, { withFileTypes: true })) {
|
|
516
|
+
if (!ent.isDirectory() || !ent.name.startsWith('agent_')) continue;
|
|
517
|
+
const ad = path.join(agentsDir, ent.name);
|
|
518
|
+
const mt = dirMtime(ad);
|
|
519
|
+
if (mt !== null && mt > newestAgentMtime) {
|
|
520
|
+
newestAgentMtime = mt;
|
|
521
|
+
newestAgentDir = ad;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
} catch (e) { /* 无 agents 目录 */ }
|
|
525
|
+
if (newestAgentDir) {
|
|
526
|
+
const r = readHead(path.join(newestAgentDir, 'metadata.json'), 64 * 1024);
|
|
527
|
+
if (r) {
|
|
528
|
+
try {
|
|
529
|
+
meta = JSON.parse(r.buf.toString('utf8'));
|
|
530
|
+
} catch (e) { /* 半截元数据容错 */ }
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// 预览:exec/<id>/ 最新 call_*-stdout.log 尾部 → 兜底 agent_*/output.txt 尾部
|
|
535
|
+
let previewText = null;
|
|
536
|
+
const execFiles = [];
|
|
537
|
+
try {
|
|
538
|
+
for (const ent of fs.readdirSync(execDir, { withFileTypes: true })) {
|
|
539
|
+
if (ent.isFile() && ent.name.startsWith('call_') && ent.name.endsWith('.log')) {
|
|
540
|
+
const f = path.join(execDir, ent.name);
|
|
541
|
+
try {
|
|
542
|
+
execFiles.push({ f, mt: fs.statSync(f).mtimeMs });
|
|
543
|
+
} catch (e) { /* 竞态删除容忍 */ }
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
} catch (e) { /* 无 exec 目录 */ }
|
|
547
|
+
execFiles.sort((a, b) => b.mt - a.mt);
|
|
548
|
+
if (execFiles.length > 0) {
|
|
549
|
+
const r = readTail(execFiles[0].f, 4 * 1024);
|
|
550
|
+
if (r) {
|
|
551
|
+
const lines = r.buf.toString('utf8').split('\n').map((l) => l.trim()).filter(Boolean);
|
|
552
|
+
if (lines.length > 0) previewText = lines[lines.length - 1];
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
if (previewText === null && newestAgentDir) {
|
|
556
|
+
const r = readTail(path.join(newestAgentDir, 'output.txt'), 4 * 1024);
|
|
557
|
+
if (r) {
|
|
558
|
+
const lines = r.buf.toString('utf8').split('\n').map((l) => l.trim()).filter(Boolean);
|
|
559
|
+
if (lines.length > 0) previewText = lines[lines.length - 1];
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
const core = sessId.replace(/^sess_/, '').replace(/^subagent_agent_/, 'subagent-');
|
|
564
|
+
const shortId = core.slice(0, 8);
|
|
565
|
+
const metaCwd = meta && typeof meta.cwd === 'string' ? meta.cwd : '';
|
|
566
|
+
const metaDesc = meta && typeof meta.description === 'string' && meta.description.trim() ? meta.description : '';
|
|
567
|
+
items.push(
|
|
568
|
+
makeItem(
|
|
569
|
+
{
|
|
570
|
+
agent: 'zcode',
|
|
571
|
+
agentName: 'ZCode',
|
|
572
|
+
id: sessId, // v2.3 spike R1:db.sqlite session.id 与目录名同名同形(db 为超集),透传即回查主键
|
|
573
|
+
projectId: metaCwd,
|
|
574
|
+
title: metaDesc || `ZCode 会话 ${shortId}`,
|
|
575
|
+
preview: previewText || '',
|
|
576
|
+
startedMs: meta && meta.createdAt ? Date.parse(meta.createdAt) : info.mtimeMs,
|
|
577
|
+
lastActiveMs: info.mtimeMs,
|
|
578
|
+
ref: refOf({ s: 'zcode', k: 'session', v: { id: sessId } }),
|
|
579
|
+
},
|
|
580
|
+
opts
|
|
581
|
+
)
|
|
582
|
+
);
|
|
583
|
+
}
|
|
584
|
+
return { ok: true, detail: `${items.length} 会话`, items };
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// ---------- 适配器②:claude(~/.claude/projects) ----------
|
|
588
|
+
|
|
589
|
+
/** <编码项目路径>/*.jsonl,mtime 排序取最近 N;标题=首条有文本行,预览=末条有文本行,项目=文件内 cwd */
|
|
590
|
+
function claudeAdapter(sourceCfg, opts) {
|
|
591
|
+
const limit = (opts && opts.limit) || 10;
|
|
592
|
+
const root = resolveHome(sourceCfg.root) || defaultRoot('claude');
|
|
593
|
+
if (!isDir(root)) return { ok: false, detail: `目录不存在: ${root}`, items: [] };
|
|
594
|
+
|
|
595
|
+
const files = [];
|
|
596
|
+
let projectDirs;
|
|
597
|
+
try {
|
|
598
|
+
projectDirs = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory());
|
|
599
|
+
} catch (e) {
|
|
600
|
+
return { ok: false, detail: `目录读取失败: ${e.message}`, items: [] };
|
|
601
|
+
}
|
|
602
|
+
for (const pd of projectDirs) {
|
|
603
|
+
const pdir = path.join(root, pd.name);
|
|
604
|
+
let entries;
|
|
605
|
+
try {
|
|
606
|
+
entries = fs.readdirSync(pdir, { withFileTypes: true });
|
|
607
|
+
} catch (e) {
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
for (const ent of entries) {
|
|
611
|
+
if (!ent.isFile() || !ent.name.endsWith('.jsonl')) continue;
|
|
612
|
+
const full = path.join(pdir, ent.name);
|
|
613
|
+
try {
|
|
614
|
+
const st = fs.statSync(full);
|
|
615
|
+
files.push({ full, dirName: pd.name, mtimeMs: st.mtimeMs, birthtimeMs: st.birthtimeMs, size: st.size });
|
|
616
|
+
} catch (e) { /* 竞态删除容忍 */ }
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
files.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
620
|
+
|
|
621
|
+
const items = [];
|
|
622
|
+
for (const f of files.slice(0, limit)) {
|
|
623
|
+
const head = parseJsonlBuffer(readHead(f.full, 32 * 1024));
|
|
624
|
+
const tail = parseJsonlBuffer(readTail(f.full, 32 * 1024));
|
|
625
|
+
const titleText = firstText(head);
|
|
626
|
+
const previewText = lastText(tail);
|
|
627
|
+
const cwd = cwdFromBuffer(readTail(f.full, 32 * 1024)) || decodeProjectDirName(f.dirName);
|
|
628
|
+
const sessionId = (f.full.match(/([0-9a-f-]{16,})\.jsonl$/i) || [])[1] || path.basename(f.full, '.jsonl');
|
|
629
|
+
items.push(
|
|
630
|
+
makeItem(
|
|
631
|
+
{
|
|
632
|
+
agent: 'claude',
|
|
633
|
+
agentName: 'claude',
|
|
634
|
+
id: sessionId,
|
|
635
|
+
projectId: cwd,
|
|
636
|
+
title: titleText || `claude 会话 ${sessionId.slice(0, 8)}`,
|
|
637
|
+
preview: previewText || '',
|
|
638
|
+
startedMs: f.birthtimeMs,
|
|
639
|
+
lastActiveMs: f.mtimeMs,
|
|
640
|
+
ref: refOf({ s: 'claude', k: 'project', v: { dir: f.dirName, file: path.basename(f.full) } }),
|
|
641
|
+
},
|
|
642
|
+
opts
|
|
643
|
+
)
|
|
644
|
+
);
|
|
645
|
+
}
|
|
646
|
+
return { ok: true, detail: `${items.length} 会话`, items };
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
// ---------- 适配器③:dsh(~/.dsh/sessions) ----------
|
|
650
|
+
|
|
651
|
+
const DSH_ZSTD_CAP = 8 * 1024 * 1024; // 超过 8MB 的 zstd 不解压(预览留空,条目照常输出)
|
|
652
|
+
|
|
653
|
+
/** dsh 解压单文件 → {header, previewText};zstd 不可用/超限/损坏降级为 null 字段 */
|
|
654
|
+
function dshDecompressSession(file) {
|
|
655
|
+
let st;
|
|
656
|
+
try {
|
|
657
|
+
st = fs.statSync(file);
|
|
658
|
+
} catch (e) {
|
|
659
|
+
return {};
|
|
660
|
+
}
|
|
661
|
+
if (st.size > DSH_ZSTD_CAP) return {};
|
|
662
|
+
let buf;
|
|
663
|
+
try {
|
|
664
|
+
buf = fs.readFileSync(file);
|
|
665
|
+
} catch (e) {
|
|
666
|
+
return {};
|
|
667
|
+
}
|
|
668
|
+
let out;
|
|
669
|
+
try {
|
|
670
|
+
out = zlib.zstdDecompressSync(buf);
|
|
671
|
+
} catch (e) {
|
|
672
|
+
return {}; // 非 zstd/损坏 → 降级,不致命
|
|
673
|
+
}
|
|
674
|
+
const lines = out.toString('utf8').split('\n');
|
|
675
|
+
let header = null;
|
|
676
|
+
let previewText = null;
|
|
677
|
+
for (let i = 0; i < lines.length && i < 5; i++) {
|
|
678
|
+
const t = lines[i].trim();
|
|
679
|
+
if (!t) continue;
|
|
680
|
+
try {
|
|
681
|
+
header = JSON.parse(t);
|
|
682
|
+
break;
|
|
683
|
+
} catch (e) { /* 首行半截继续 */ }
|
|
684
|
+
}
|
|
685
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
686
|
+
const t = lines[i].trim();
|
|
687
|
+
if (!t) continue;
|
|
688
|
+
try {
|
|
689
|
+
const o = JSON.parse(t);
|
|
690
|
+
if (o && o.type === 'session') continue; // 元数据行不当预览
|
|
691
|
+
const txt = extractLineText(o);
|
|
692
|
+
if (txt) {
|
|
693
|
+
previewText = txt;
|
|
694
|
+
break;
|
|
695
|
+
}
|
|
696
|
+
} catch (e) { /* 跳过坏行 */ }
|
|
697
|
+
}
|
|
698
|
+
return { header, previewText };
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/**
|
|
702
|
+
* <编码项目路径> 下 session-N 目录内 sessionN.jsonl.zstd(实测;zstd 解压读首行元数据 cwd/createdAt)
|
|
703
|
+
* + 兼容 rollout-N.jsonl 明文(briefing 情报的旧布局,向前兼容不破坏)。
|
|
704
|
+
*/
|
|
705
|
+
function dshAdapter(sourceCfg, opts) {
|
|
706
|
+
const limit = (opts && opts.limit) || 10;
|
|
707
|
+
const root = resolveHome(sourceCfg.root) || defaultRoot('dsh');
|
|
708
|
+
if (!isDir(root)) return { ok: false, detail: `目录不存在: ${root}`, items: [] };
|
|
709
|
+
|
|
710
|
+
const files = [];
|
|
711
|
+
let projectDirs;
|
|
712
|
+
try {
|
|
713
|
+
projectDirs = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory());
|
|
714
|
+
} catch (e) {
|
|
715
|
+
return { ok: false, detail: `目录读取失败: ${e.message}`, items: [] };
|
|
716
|
+
}
|
|
717
|
+
for (const pd of projectDirs) {
|
|
718
|
+
const pdir = path.join(root, pd.name);
|
|
719
|
+
let entries;
|
|
720
|
+
try {
|
|
721
|
+
entries = fs.readdirSync(pdir, { withFileTypes: true });
|
|
722
|
+
} catch (e) {
|
|
723
|
+
continue;
|
|
724
|
+
}
|
|
725
|
+
// 两层布局兼容:rollout-*.jsonl 直接位于项目目录(旧年/月/日布局)或 session-N 目录
|
|
726
|
+
for (const ent of entries) {
|
|
727
|
+
if (ent.isFile() && /^rollout-.*\.jsonl$/.test(ent.name)) {
|
|
728
|
+
const full = path.join(pdir, ent.name);
|
|
729
|
+
try {
|
|
730
|
+
const st = fs.statSync(full);
|
|
731
|
+
files.push({
|
|
732
|
+
full,
|
|
733
|
+
dirName: pd.name,
|
|
734
|
+
sessDirName: pd.name,
|
|
735
|
+
kind: 'rollout',
|
|
736
|
+
mtimeMs: st.mtimeMs,
|
|
737
|
+
birthtimeMs: st.birthtimeMs,
|
|
738
|
+
});
|
|
739
|
+
} catch (e) { /* 竞态删除容忍 */ }
|
|
740
|
+
continue;
|
|
741
|
+
}
|
|
742
|
+
if (!ent.isDirectory()) continue;
|
|
743
|
+
const sdir = path.join(pdir, ent.name);
|
|
744
|
+
let inner;
|
|
745
|
+
try {
|
|
746
|
+
inner = fs.readdirSync(sdir, { withFileTypes: true });
|
|
747
|
+
} catch (e) {
|
|
748
|
+
continue;
|
|
749
|
+
}
|
|
750
|
+
for (const f2 of inner) {
|
|
751
|
+
if (!f2.isFile()) continue;
|
|
752
|
+
const isZstd = /^session.*\.jsonl\.zstd$/.test(f2.name);
|
|
753
|
+
const isRollout = /^rollout-.*\.jsonl$/.test(f2.name);
|
|
754
|
+
if (!isZstd && !isRollout) continue;
|
|
755
|
+
const full = path.join(sdir, f2.name);
|
|
756
|
+
try {
|
|
757
|
+
const st = fs.statSync(full);
|
|
758
|
+
files.push({
|
|
759
|
+
full,
|
|
760
|
+
dirName: pd.name,
|
|
761
|
+
sessDirName: ent.name,
|
|
762
|
+
kind: isZstd ? 'zstd' : 'rollout',
|
|
763
|
+
mtimeMs: st.mtimeMs,
|
|
764
|
+
birthtimeMs: st.birthtimeMs,
|
|
765
|
+
});
|
|
766
|
+
} catch (e) { /* 竞态删除容忍 */ }
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
files.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
771
|
+
|
|
772
|
+
const items = [];
|
|
773
|
+
for (const f of files.slice(0, limit)) {
|
|
774
|
+
let header = null;
|
|
775
|
+
let previewText = null;
|
|
776
|
+
if (f.kind === 'zstd') {
|
|
777
|
+
({ header = null, previewText = null } = dshDecompressSession(f.full));
|
|
778
|
+
} else {
|
|
779
|
+
const head = parseJsonlBuffer(readHead(f.full, 32 * 1024));
|
|
780
|
+
const tail = parseJsonlBuffer(readTail(f.full, 32 * 1024));
|
|
781
|
+
header = head[0] || null;
|
|
782
|
+
previewText = lastText(tail);
|
|
783
|
+
}
|
|
784
|
+
const cwd =
|
|
785
|
+
(header && typeof header.cwd === 'string' && header.cwd) || decodeProjectDirName(f.dirName);
|
|
786
|
+
const m = f.sessDirName.match(/session-([0-9a-f-]+)/i);
|
|
787
|
+
const shortId = (m ? m[1] : f.sessDirName).slice(0, 8);
|
|
788
|
+
items.push(
|
|
789
|
+
makeItem(
|
|
790
|
+
{
|
|
791
|
+
agent: 'dsh',
|
|
792
|
+
agentName: 'DSH',
|
|
793
|
+
id: f.full, // v2.3:全文回查主键 = 相对路径(locator file.path)
|
|
794
|
+
projectId: cwd,
|
|
795
|
+
title: `DSH 会话 ${shortId}`,
|
|
796
|
+
preview: previewText || '',
|
|
797
|
+
startedMs: header && Number.isFinite(header.createdAt) ? header.createdAt : f.birthtimeMs,
|
|
798
|
+
lastActiveMs: f.mtimeMs,
|
|
799
|
+
ref: refOf({
|
|
800
|
+
s: 'dsh',
|
|
801
|
+
k: 'file',
|
|
802
|
+
v: { path: path.relative(root, f.full).split(path.sep).join('/') },
|
|
803
|
+
}),
|
|
804
|
+
},
|
|
805
|
+
opts
|
|
806
|
+
)
|
|
807
|
+
);
|
|
808
|
+
}
|
|
809
|
+
return { ok: true, detail: `${items.length} 会话`, items };
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
// ---------- 适配器④:WorkBuddy(~/.workbuddy/workbuddy.db,node:sqlite 只读) ----------
|
|
813
|
+
|
|
814
|
+
const WORKBUDDY_STATE_MAP = {
|
|
815
|
+
running: 'active',
|
|
816
|
+
'in_progress': 'active',
|
|
817
|
+
'in-progress': 'active',
|
|
818
|
+
completed: 'completed',
|
|
819
|
+
complete: 'completed',
|
|
820
|
+
done: 'completed',
|
|
821
|
+
failed: 'failed',
|
|
822
|
+
error: 'failed',
|
|
823
|
+
cancelled: 'cancelled',
|
|
824
|
+
canceled: 'cancelled',
|
|
825
|
+
};
|
|
826
|
+
|
|
827
|
+
/** 仅 SELECT sessions 表所需列;{readOnly:true} 打开(实测可用);node:sqlite 缺位降级 ok:false */
|
|
828
|
+
function workbuddyAdapter(sourceCfg, opts) {
|
|
829
|
+
const limit = (opts && opts.limit) || 10;
|
|
830
|
+
const dbPath = resolveHome(sourceCfg.dbPath) || defaultRoot('workbuddy');
|
|
831
|
+
if (!fs.existsSync(dbPath)) return { ok: false, detail: `数据库不存在: ${dbPath}`, items: [] };
|
|
832
|
+
|
|
833
|
+
let DatabaseSync;
|
|
834
|
+
try {
|
|
835
|
+
({ DatabaseSync } = require('node:sqlite'));
|
|
836
|
+
} catch (e) {
|
|
837
|
+
return { ok: false, detail: `node:sqlite 不可用: ${e.message}`, items: [] };
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
let db;
|
|
841
|
+
try {
|
|
842
|
+
db = new DatabaseSync(dbPath, { readOnly: true });
|
|
843
|
+
} catch (e) {
|
|
844
|
+
return { ok: false, detail: `数据库打开失败(只读): ${e.message}`, items: [] };
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
try {
|
|
848
|
+
const rows = db
|
|
849
|
+
.prepare(
|
|
850
|
+
'SELECT id, cwd, title, status, created_at, last_activity_at FROM sessions ORDER BY last_activity_at DESC LIMIT ?'
|
|
851
|
+
)
|
|
852
|
+
.all(limit);
|
|
853
|
+
const items = (Array.isArray(rows) ? rows : []).map((r) =>
|
|
854
|
+
makeItem(
|
|
855
|
+
{
|
|
856
|
+
id: String(r.id === null || r.id === undefined ? '' : r.id),
|
|
857
|
+
agent: 'workbuddy',
|
|
858
|
+
agentName: 'WorkBuddy',
|
|
859
|
+
projectId: typeof r.cwd === 'string' ? r.cwd : '',
|
|
860
|
+
title: (typeof r.title === 'string' && r.title.trim()) || `WorkBuddy 会话 ${String(r.id || '').slice(0, 8)}`,
|
|
861
|
+
preview: '', // 凭据红线:只 SELECT sessions 表所需列,不读消息表
|
|
862
|
+
startedMs: r.created_at,
|
|
863
|
+
lastActiveMs: r.last_activity_at,
|
|
864
|
+
state: WORKBUDDY_STATE_MAP[String(r.status || '').toLowerCase()] || 'idle',
|
|
865
|
+
ref: refOf({ s: 'workbuddy', k: 'session', v: { id: String(r.id === null || r.id === undefined ? '' : r.id) } }),
|
|
866
|
+
},
|
|
867
|
+
opts
|
|
868
|
+
)
|
|
869
|
+
);
|
|
870
|
+
return { ok: true, detail: `${items.length} 会话`, items };
|
|
871
|
+
} catch (e) {
|
|
872
|
+
return { ok: false, detail: `sessions 查询失败: ${e.message}`, items: [] };
|
|
873
|
+
} finally {
|
|
874
|
+
try { db.close(); } catch (e) { /* 收尾互不阻塞 */ }
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
// ---------- 适配器⑤:codex(~/.codex/sessions,ChatGPT 桌面 rollout 会话;v2.6 桌面成员册专用) ----------
|
|
879
|
+
|
|
880
|
+
/** 列子目录(withFileTypes 过滤 isDirectory;异常返回 []) */
|
|
881
|
+
function listDirs(dir) {
|
|
882
|
+
try {
|
|
883
|
+
return fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory());
|
|
884
|
+
} catch (e) {
|
|
885
|
+
return [];
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/** codex rollout payload → 人类可读文本:content 数组各元素 .text 拼接 / message 字符串;取不到返回 null */
|
|
890
|
+
function codexTextOf(payload) {
|
|
891
|
+
if (!isPlainObject(payload)) return null;
|
|
892
|
+
if (Array.isArray(payload.content)) {
|
|
893
|
+
const t = payload.content
|
|
894
|
+
.filter((b) => b && typeof b.text === 'string' && b.text)
|
|
895
|
+
.map((b) => b.text)
|
|
896
|
+
.join('');
|
|
897
|
+
if (t) return t;
|
|
898
|
+
}
|
|
899
|
+
if (typeof payload.message === 'string' && payload.message) return payload.message;
|
|
900
|
+
return null;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/** codex 会话开头常被注入环境上下文(<environment_context>/<INSTRUCTIONS>/AGENTS.md 说明),不能当标题 */
|
|
904
|
+
const CODEX_INJECTED_PREFIX = /^\s*(?:<environment_context>|<INSTRUCTIONS>|# AGENTS\.md instructions|# Files mentioned by the user:)/i;
|
|
905
|
+
|
|
906
|
+
/** codex head 记录中首条 user response_item 的文本(跳过注入上下文;全是注入时返回 null 交给 id 兜底) */
|
|
907
|
+
function codexUserText(objs) {
|
|
908
|
+
for (const o of objs) {
|
|
909
|
+
if (
|
|
910
|
+
o &&
|
|
911
|
+
o.type === 'response_item' &&
|
|
912
|
+
isPlainObject(o.payload) &&
|
|
913
|
+
o.payload.type === 'message' &&
|
|
914
|
+
o.payload.role === 'user'
|
|
915
|
+
) {
|
|
916
|
+
const t = codexTextOf(o.payload);
|
|
917
|
+
if (!t) continue;
|
|
918
|
+
if (!CODEX_INJECTED_PREFIX.test(t)) return t;
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
return null;
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
/** codex tail 记录倒序取最后一条文本(跳过 session_meta/turn_context/world_state 元数据行) */
|
|
925
|
+
function codexLastText(objs) {
|
|
926
|
+
for (let i = objs.length - 1; i >= 0; i--) {
|
|
927
|
+
const o = objs[i];
|
|
928
|
+
if (o && (o.type === 'session_meta' || o.type === 'turn_context' || o.type === 'world_state')) continue;
|
|
929
|
+
const t = codexTextOf(o && o.payload);
|
|
930
|
+
if (t) return t;
|
|
931
|
+
}
|
|
932
|
+
return null;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
/**
|
|
936
|
+
* root/YYYY/MM/DD/rollout-*.jsonl,mtime 排序取最近 N;首行 session_meta 提供 id/cwd/timestamp。
|
|
937
|
+
* 标题 = 首条 user response_item 文本,预览 = 尾部最后一条文本。v2.9.14 起进 ADAPTERS(活动面板第五源)。
|
|
938
|
+
*/
|
|
939
|
+
function codexAdapter(sourceCfg, opts) {
|
|
940
|
+
const limit = (opts && opts.limit) || 10;
|
|
941
|
+
const root = resolveHome(sourceCfg.root) || defaultRoot('codex');
|
|
942
|
+
if (!isDir(root)) return { ok: false, detail: `目录不存在: ${root}`, items: [] };
|
|
943
|
+
const files = [];
|
|
944
|
+
let yearDirs;
|
|
945
|
+
try { yearDirs = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory()); } catch (e) { return { ok: false, detail: `目录读取失败: ${e.message}`, items: [] }; }
|
|
946
|
+
for (const yd of yearDirs) {
|
|
947
|
+
for (const md of listDirs(path.join(root, yd.name))) {
|
|
948
|
+
for (const dd of listDirs(path.join(root, yd.name, md.name))) {
|
|
949
|
+
const dayDir = path.join(root, yd.name, md.name, dd.name);
|
|
950
|
+
let entries;
|
|
951
|
+
try { entries = fs.readdirSync(dayDir, { withFileTypes: true }); } catch (e) { continue; }
|
|
952
|
+
for (const ent of entries) {
|
|
953
|
+
if (!ent.isFile() || !/^rollout-.*\.jsonl$/.test(ent.name)) continue;
|
|
954
|
+
const full = path.join(dayDir, ent.name);
|
|
955
|
+
try { const st = fs.statSync(full); files.push({ full, mtimeMs: st.mtimeMs, birthtimeMs: st.birthtimeMs }); } catch (e) { /* 竞态删除容忍 */ }
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
files.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
961
|
+
const items = [];
|
|
962
|
+
for (const f of files.slice(0, limit)) {
|
|
963
|
+
const head = parseJsonlBuffer(readHead(f.full, 256 * 1024));
|
|
964
|
+
const metaRec = head.find((o) => o && o.type === 'session_meta' && isPlainObject(o.payload));
|
|
965
|
+
const meta = (metaRec && metaRec.payload) || {};
|
|
966
|
+
const title = codexUserText(head) || `Codex 会话 ${String(meta.id || meta.session_id || '').slice(0, 8)}`;
|
|
967
|
+
const preview = codexLastText(parseJsonlBuffer(readTail(f.full, 32 * 1024)));
|
|
968
|
+
items.push(makeItem({
|
|
969
|
+
id: String(meta.id || meta.session_id || ''),
|
|
970
|
+
agent: 'codex',
|
|
971
|
+
agentName: 'Codex (ChatGPT 桌面)',
|
|
972
|
+
projectId: typeof meta.cwd === 'string' ? meta.cwd : '',
|
|
973
|
+
title,
|
|
974
|
+
preview: preview || '',
|
|
975
|
+
startedMs: Date.parse(meta.timestamp) || f.birthtimeMs,
|
|
976
|
+
lastActiveMs: f.mtimeMs,
|
|
977
|
+
ref: refOf({ s: 'codex', k: 'file', v: { path: path.relative(root, f.full).split(path.sep).join('/') } }),
|
|
978
|
+
}, opts));
|
|
979
|
+
}
|
|
980
|
+
return { ok: true, detail: `${items.length} 会话`, items };
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
// ---------- 适配器⑥:opencode(~/.local/share/opencode/opencode.db,node:sqlite 只读;v2.6 桌面成员册专用) ----------
|
|
984
|
+
|
|
985
|
+
/** 仅 SELECT session 表五列(凭据红线不碰 account/credential 等其余表);node:sqlite 缺位降级 ok:false */
|
|
986
|
+
function opencodeAdapter(sourceCfg, opts) {
|
|
987
|
+
const limit = (opts && opts.limit) || 10;
|
|
988
|
+
const dbPath = resolveHome(sourceCfg.dbPath) || defaultRoot('opencode');
|
|
989
|
+
if (!fs.existsSync(dbPath)) return { ok: false, detail: `数据库不存在: ${dbPath}`, items: [] };
|
|
990
|
+
let DatabaseSync;
|
|
991
|
+
try { ({ DatabaseSync } = require('node:sqlite')); } catch (e) { return { ok: false, detail: `node:sqlite 不可用: ${e.message}`, items: [] }; }
|
|
992
|
+
let db;
|
|
993
|
+
try { db = new DatabaseSync(dbPath, { readOnly: true }); } catch (e) { return { ok: false, detail: `数据库打开失败(只读): ${e.message}`, items: [] }; }
|
|
994
|
+
try {
|
|
995
|
+
// 凭据红线:仅 SELECT session 表五列,不碰 account/credential 等其余表
|
|
996
|
+
const rows = db
|
|
997
|
+
.prepare('SELECT id, directory, title, time_created, time_updated FROM session ORDER BY time_updated DESC LIMIT ?')
|
|
998
|
+
.all(limit);
|
|
999
|
+
const items = (Array.isArray(rows) ? rows : []).map((r) =>
|
|
1000
|
+
makeItem({
|
|
1001
|
+
id: String(r.id === null || r.id === undefined ? '' : r.id),
|
|
1002
|
+
agent: 'opencode',
|
|
1003
|
+
agentName: 'OpenCode',
|
|
1004
|
+
projectId: typeof r.directory === 'string' ? r.directory : '',
|
|
1005
|
+
title: (typeof r.title === 'string' && r.title.trim()) || `OpenCode 会话 ${String(r.id || '').slice(0, 8)}`,
|
|
1006
|
+
preview: '',
|
|
1007
|
+
startedMs: r.time_created,
|
|
1008
|
+
lastActiveMs: r.time_updated,
|
|
1009
|
+
ref: refOf({ s: 'opencode', k: 'session', v: { id: String(r.id === null || r.id === undefined ? '' : r.id) } }),
|
|
1010
|
+
}, opts)
|
|
1011
|
+
);
|
|
1012
|
+
return { ok: true, detail: `${items.length} 会话`, items };
|
|
1013
|
+
} catch (e) {
|
|
1014
|
+
return { ok: false, detail: `session 查询失败: ${e.message}`, items: [] };
|
|
1015
|
+
} finally {
|
|
1016
|
+
try { db.close(); } catch (e) { /* 收尾互不阻塞 */ }
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
// ---------- 聚合 ----------
|
|
1021
|
+
|
|
1022
|
+
const ADAPTERS = {
|
|
1023
|
+
zcode: zcodeAdapter,
|
|
1024
|
+
claude: claudeAdapter,
|
|
1025
|
+
dsh: dshAdapter,
|
|
1026
|
+
workbuddy: workbuddyAdapter,
|
|
1027
|
+
codex: codexAdapter,
|
|
1028
|
+
};
|
|
1029
|
+
|
|
1030
|
+
/**
|
|
1031
|
+
* aggregateAgentActivity(config, opts)
|
|
1032
|
+
* config 全量配置(读 config.agentActivity 节,缺省回默认);
|
|
1033
|
+
* opts.agent 过滤(agent id 精确匹配,忽略大小写);
|
|
1034
|
+
* opts.now 时间原点(测试注入)。
|
|
1035
|
+
* → { items:[{id,agent,agentName,projectId,title,preview,startedAt,lastActiveAt,state}],
|
|
1036
|
+
* sources:[{id,ok,detail}], checkedAt }
|
|
1037
|
+
*/
|
|
1038
|
+
function aggregateAgentActivity(config, opts) {
|
|
1039
|
+
const o = opts || {};
|
|
1040
|
+
const sec = normalizeAgentActivity(isPlainObject(config) ? config.agentActivity : null);
|
|
1041
|
+
const now = Number.isFinite(o.now) ? o.now : Date.now();
|
|
1042
|
+
const sources = [];
|
|
1043
|
+
const items = [];
|
|
1044
|
+
|
|
1045
|
+
for (const id of SOURCE_IDS) {
|
|
1046
|
+
const s = sec.sources[id] || {};
|
|
1047
|
+
if (sec.enabled === false || s.enabled === false) {
|
|
1048
|
+
sources.push({ id, ok: false, detail: 'disabled(未启用)' });
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1051
|
+
try {
|
|
1052
|
+
const r = ADAPTERS[id](s, { limit: sec.perSourceLimit, previewChars: sec.previewChars, now });
|
|
1053
|
+
sources.push({ id, ok: r.ok !== false, detail: r.detail || '' });
|
|
1054
|
+
if (Array.isArray(r.items)) items.push(...r.items);
|
|
1055
|
+
} catch (e) {
|
|
1056
|
+
// 单源故障隔离:记录后继续下一源,绝不影响其他源与整体响应
|
|
1057
|
+
sources.push({ id, ok: false, detail: `适配器异常: ${(e && e.message) || e}` });
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
items.sort((a, b) => {
|
|
1062
|
+
const ta = Date.parse(a.lastActiveAt) || 0;
|
|
1063
|
+
const tb = Date.parse(b.lastActiveAt) || 0;
|
|
1064
|
+
return tb - ta;
|
|
1065
|
+
});
|
|
1066
|
+
let out = items.slice(0, sec.maxItems);
|
|
1067
|
+
const agent = typeof o.agent === 'string' ? o.agent.trim().toLowerCase() : '';
|
|
1068
|
+
if (agent) out = out.filter((it) => String(it.agent).toLowerCase() === agent);
|
|
1069
|
+
|
|
1070
|
+
// v2.2 契约补齐:allOk = 全部启用源探测成功(前端健康徽标备用品;当前徽标用 sources 计数)
|
|
1071
|
+
const allOk = sources.length > 0 && sources.every((s) => s.ok);
|
|
1072
|
+
return { allOk, items: out, sources, checkedAt: new Date(now).toISOString() };
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
// ---------- 路由挂载 ----------
|
|
1076
|
+
|
|
1077
|
+
/** GET /api/agent-activity(?agent= 过滤)— 独立版/插件态经 appAssembler 同源生效 */
|
|
1078
|
+
function registerAgentActivityRoutes(router, ctx) {
|
|
1079
|
+
const { sendJSON } = require('./router');
|
|
1080
|
+
router.add('GET', '/api/agent-activity', (c) => {
|
|
1081
|
+
sendJSON(c.res, 200, aggregateAgentActivity(ctx.config, { agent: c.query.get('agent') || '' }));
|
|
1082
|
+
});
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/**
|
|
1086
|
+
* hermes(2026-11-03 第七源,opencode 同款待遇):%LOCALAPPDATA%/hermes/state.db sessions 表
|
|
1087
|
+
* (明文 SQLite,只读;活库带 auto-maintenance lock——readOnly 打开+失败按源故障返回,绝不写)。
|
|
1088
|
+
* 时间戳 Unix 秒浮点(×1000 转 ms);archived/hidden 会话出局;title 为 LLM 生成。
|
|
1089
|
+
* 测试注入缝与 zcode 同款:opts.listSessions(sourceCfg, limit) → { ok, detail, rows }。
|
|
1090
|
+
*/
|
|
1091
|
+
function hermesAdapter(sourceCfg, opts) {
|
|
1092
|
+
const limit = (opts && opts.limit) || 10;
|
|
1093
|
+
const secToMs = (v) => {
|
|
1094
|
+
const n = Number(v);
|
|
1095
|
+
return Number.isFinite(n) && n > 0 ? Math.round(n * 1000) : null;
|
|
1096
|
+
};
|
|
1097
|
+
const mapRow = (r) =>
|
|
1098
|
+
makeItem(
|
|
1099
|
+
{
|
|
1100
|
+
id: String(r.id === null || r.id === undefined ? '' : r.id),
|
|
1101
|
+
agent: 'hermes',
|
|
1102
|
+
agentName: 'Hermes',
|
|
1103
|
+
projectId: typeof r.cwd === 'string' ? r.cwd : '',
|
|
1104
|
+
title: (typeof r.title === 'string' && r.title.trim()) || `Hermes 会话 ${String(r.id || '').slice(0, 8)}`,
|
|
1105
|
+
preview: '',
|
|
1106
|
+
startedMs: secToMs(r.started_at),
|
|
1107
|
+
lastActiveMs: secToMs(r.last_activity_at),
|
|
1108
|
+
ref: refOf({ s: 'hermes', k: 'session', v: { id: String(r.id === null || r.id === undefined ? '' : r.id) } }),
|
|
1109
|
+
},
|
|
1110
|
+
opts
|
|
1111
|
+
);
|
|
1112
|
+
// 测试注入缝(AGENTS.md 坑 5:sqlite 夹具走注入,不落 fs 夹具)
|
|
1113
|
+
const injected = opts && typeof opts.listSessions === 'function' ? opts.listSessions(sourceCfg, limit) : null;
|
|
1114
|
+
if (injected) {
|
|
1115
|
+
if (injected.ok === false) return { ok: false, detail: injected.detail || '会话清单不可用', items: [] };
|
|
1116
|
+
const items = (Array.isArray(injected.rows) ? injected.rows : []).map(mapRow);
|
|
1117
|
+
return { ok: true, detail: `${items.length} 会话`, items };
|
|
1118
|
+
}
|
|
1119
|
+
const dbPath = resolveHome(sourceCfg.dbPath) || defaultRoot('hermes');
|
|
1120
|
+
if (!fs.existsSync(dbPath)) return { ok: false, detail: `数据库不存在: ${dbPath}`, items: [] };
|
|
1121
|
+
let DatabaseSync;
|
|
1122
|
+
try {
|
|
1123
|
+
({ DatabaseSync } = require('node:sqlite'));
|
|
1124
|
+
} catch (e) {
|
|
1125
|
+
return { ok: false, detail: `node:sqlite 不可用: ${e.message}`, items: [] };
|
|
1126
|
+
}
|
|
1127
|
+
let db;
|
|
1128
|
+
try {
|
|
1129
|
+
db = new DatabaseSync(dbPath, { readOnly: true });
|
|
1130
|
+
} catch (e) {
|
|
1131
|
+
return { ok: false, detail: `数据库打开失败(只读): ${e.message}`, items: [] };
|
|
1132
|
+
}
|
|
1133
|
+
try {
|
|
1134
|
+
const rows = db
|
|
1135
|
+
.prepare(
|
|
1136
|
+
'SELECT id, title, cwd, started_at, last_activity_at FROM sessions WHERE archived = 0 AND hidden = 0 ' +
|
|
1137
|
+
'ORDER BY last_activity_at DESC LIMIT ?'
|
|
1138
|
+
)
|
|
1139
|
+
.all(limit);
|
|
1140
|
+
const items = (Array.isArray(rows) ? rows : []).map(mapRow);
|
|
1141
|
+
return { ok: true, detail: `${items.length} 会话`, items };
|
|
1142
|
+
} catch (e) {
|
|
1143
|
+
return { ok: false, detail: `sessions 查询失败: ${e.message}`, items: [] };
|
|
1144
|
+
} finally {
|
|
1145
|
+
try { db.close(); } catch (e) { /* 收尾互不阻塞 */ }
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
module.exports = {
|
|
1150
|
+
DEFAULT_AGENT_ACTIVITY,
|
|
1151
|
+
SOURCE_IDS,
|
|
1152
|
+
ALL_SOURCE_IDS,
|
|
1153
|
+
normalizeAgentActivity,
|
|
1154
|
+
aggregateAgentActivity,
|
|
1155
|
+
registerAgentActivityRoutes,
|
|
1156
|
+
// 适配器单测直通
|
|
1157
|
+
zcodeAdapter,
|
|
1158
|
+
claudeAdapter,
|
|
1159
|
+
dshAdapter,
|
|
1160
|
+
workbuddyAdapter,
|
|
1161
|
+
codexAdapter,
|
|
1162
|
+
opencodeAdapter,
|
|
1163
|
+
hermesAdapter,
|
|
1164
|
+
// 工具导出(测试复用)
|
|
1165
|
+
decodeProjectDirName,
|
|
1166
|
+
truncateOneLine,
|
|
1167
|
+
// v2.3 会话阅读器复用(lib/agentTranscript.js;避免同款实现两份漂移)
|
|
1168
|
+
sanitizeText,
|
|
1169
|
+
resolveHome,
|
|
1170
|
+
defaultRoot,
|
|
1171
|
+
readHead,
|
|
1172
|
+
readTail,
|
|
1173
|
+
parseJsonlBuffer,
|
|
1174
|
+
extractLineText,
|
|
1175
|
+
toIso,
|
|
1176
|
+
toIsoFromValue,
|
|
1177
|
+
isPlainObject,
|
|
1178
|
+
stateFor,
|
|
1179
|
+
refOf,
|
|
1180
|
+
};
|