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,1398 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* agentTranscript.js — v2.3 会话阅读器后端:六源「会话列表 + 归一化全文」适配器与两条端点
|
|
5
|
+
*
|
|
6
|
+
* 端点(§3,契约冻结;插件态经 /fde-api/* 前缀同源生效):
|
|
7
|
+
* GET /api/agent-sessions?agent=<id>&limit=&cursor= 会话列表(lastActiveAt 倒序 + 键集游标)
|
|
8
|
+
* GET /api/agent-session?ref=<opaque> 会话全文(归一化消息数组,seq 升序)
|
|
9
|
+
*
|
|
10
|
+
* 六源映射(§3.4 + §10 spike 回写,2026-10-20 实测):
|
|
11
|
+
* zcode ~/.zcode/cli/db/db.sqlite(R1:session.id 与 sess_* 目录名同名同形,db 为超集
|
|
12
|
+
* → 列表/全文均以 db session 表为准;id 三形态 sess_<uuid>/session_<hex>/sess_subagent_agent_<uuid>)
|
|
13
|
+
* message/part 按 sequence 列排序(R2:message.data={role,...}、part.data={type:text|tool,...},
|
|
14
|
+
* tool part state.status ∈ completed|error|...、state.input/output)
|
|
15
|
+
* claude ~/.claude/projects <编码项目目录>/<uuid>.jsonl(跳过 isSidechain 与
|
|
16
|
+
* attachment/queue-operation/last-prompt/summary 等非消息行;tool_use→tool 发起、
|
|
17
|
+
* tool_result→role:'tool',按 tool_use_id 配对继承工具名)
|
|
18
|
+
* dsh ~/.dsh/sessions <编码项目目录>/session-N/session*.jsonl.zstd(R3:zstd 为多帧拼接,
|
|
19
|
+
* 单次 sync 解码只出首帧——必须按 0x28B52FFD magic 分帧逐帧解压;行形态 {type,seq,time,data},
|
|
20
|
+
* 消息行 user/message、assistant/message、tool/call、tool/result,其余行跳过不报错;
|
|
21
|
+
* rollout-*.jsonl 明文分支同构解析)
|
|
22
|
+
* codex ~/.codex/sessions YYYY/MM/DD/rollout-*.jsonl(session_meta 头部;response_item
|
|
23
|
+
* message/function_call/function_call_output;跳过 turn_context/world_state/event_msg)
|
|
24
|
+
* opencode ~/.local/share/opencode/opencode.db(session/message/part 三表与 zcode 同构;R2 实测
|
|
25
|
+
* message/part 无 sequence 列——按 time_created,rowid 排序;凭据红线:不碰
|
|
26
|
+
* account/credential 等其余表)
|
|
27
|
+
* workbuddy ~/.workbuddy/workbuddy.db(仅 SELECT sessions 表;transcript 恒降级 D4)
|
|
28
|
+
*
|
|
29
|
+
* 红线(§7):全链路只读(sqlite {readOnly:true}、文件 openSync 只读、zstd 内存解压);
|
|
30
|
+
* 服务端统一脱敏(列表 title 与每条 message.text 组装时过 redact);ref 双闸校验收口
|
|
31
|
+
* lib/sessionRef.js;单源故障隔离(列表按源 try/catch,源故障 → 空页不拖垮服务)。
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
const fs = require('node:fs');
|
|
35
|
+
const path = require('node:path');
|
|
36
|
+
const zlib = require('node:zlib');
|
|
37
|
+
|
|
38
|
+
const { HttpError, sendJSON } = require('./router');
|
|
39
|
+
const redactMod = require('./redact');
|
|
40
|
+
const sessionRef = require('./sessionRef');
|
|
41
|
+
const aa = require('./agentActivity');
|
|
42
|
+
|
|
43
|
+
const {
|
|
44
|
+
normalizeAgentActivity,
|
|
45
|
+
sanitizeText,
|
|
46
|
+
resolveHome,
|
|
47
|
+
defaultRoot,
|
|
48
|
+
readHead,
|
|
49
|
+
readTail,
|
|
50
|
+
parseJsonlBuffer,
|
|
51
|
+
extractLineText,
|
|
52
|
+
toIso,
|
|
53
|
+
toIsoFromValue,
|
|
54
|
+
isPlainObject,
|
|
55
|
+
stateFor,
|
|
56
|
+
} = aa;
|
|
57
|
+
|
|
58
|
+
const SOURCE_IDS = sessionRef.SOURCE_IDS;
|
|
59
|
+
const UNNAMED = '(未命名会话)';
|
|
60
|
+
|
|
61
|
+
// 读入闸(R4):单 jsonl 全文读入上限 4MB,超出截断(truncated:true)
|
|
62
|
+
const TRANSCRIPT_FILE_CAP = 4 * 1024 * 1024;
|
|
63
|
+
// dsh:压缩单文件 8MB 不解(与活动流 DSH_ZSTD_CAP 同口径);解压累计输出 16MB 硬闸
|
|
64
|
+
const DSH_ZSTD_CAP = 8 * 1024 * 1024;
|
|
65
|
+
const DSH_DECOMPRESS_CAP = 16 * 1024 * 1024;
|
|
66
|
+
// dsh 列表标题轻解压:最多解的帧数 / 累计解压字节(找到首条 user 文本即停)
|
|
67
|
+
const DSH_LIST_FRAME_CAP = 64;
|
|
68
|
+
const DSH_LIST_DECOMPRESS_CAP = 256 * 1024;
|
|
69
|
+
|
|
70
|
+
const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
|
|
71
|
+
|
|
72
|
+
// ---------- 通用 ----------
|
|
73
|
+
|
|
74
|
+
function redactText(t) {
|
|
75
|
+
try {
|
|
76
|
+
return redactMod.redact(t);
|
|
77
|
+
} catch (e) {
|
|
78
|
+
return String(t);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 文本管线(§3.2):sanitizeText → 截断(尾部 …[截断])→ redact */
|
|
83
|
+
function finalizeText(raw, maxChars) {
|
|
84
|
+
let t = sanitizeText(raw === null || raw === undefined ? '' : String(raw));
|
|
85
|
+
if (t.length > maxChars) t = t.slice(0, Math.max(0, maxChars)) + '…[截断]';
|
|
86
|
+
return redactText(t);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function normalizeTitle(t) {
|
|
90
|
+
const one = sanitizeText(t === null || t === undefined ? '' : String(t)).replace(/\s+/g, ' ').trim();
|
|
91
|
+
return one ? redactText(one.slice(0, 80)) : UNNAMED;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** 归一化消息收集器:seq 连续递增;ts 缺省 null;tool 形状收敛 */
|
|
95
|
+
function MessageCollector() {
|
|
96
|
+
const items = [];
|
|
97
|
+
return {
|
|
98
|
+
items,
|
|
99
|
+
get length() {
|
|
100
|
+
return items.length;
|
|
101
|
+
},
|
|
102
|
+
push(role, tsMs, text, tool) {
|
|
103
|
+
items.push({
|
|
104
|
+
seq: items.length + 1,
|
|
105
|
+
role: role === 'user' || role === 'assistant' || role === 'tool' ? role : 'assistant',
|
|
106
|
+
ts: toIso(tsMs),
|
|
107
|
+
text: text === null || text === undefined ? '' : String(text),
|
|
108
|
+
tool:
|
|
109
|
+
tool && typeof tool.name === 'string'
|
|
110
|
+
? { name: tool.name, status: ['ok', 'error', 'running'].includes(tool.status) ? tool.status : 'ok' }
|
|
111
|
+
: null,
|
|
112
|
+
});
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 键集游标编解码(base64url(JSON{t,id});非法 → 400 BAD_CURSOR) */
|
|
118
|
+
function encodeCursor(t, id) {
|
|
119
|
+
return Buffer.from(JSON.stringify({ t, id }), 'utf8').toString('base64url');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function decodeCursor(raw) {
|
|
123
|
+
if (typeof raw !== 'string' || !raw) throw new HttpError(400, 'BAD_CURSOR', '游标非法');
|
|
124
|
+
try {
|
|
125
|
+
const o = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'));
|
|
126
|
+
if (isPlainObject(o) && Number.isFinite(o.t) && typeof o.id === 'string') return o;
|
|
127
|
+
} catch (e) { /* 落入下方 400 */ }
|
|
128
|
+
throw new HttpError(400, 'BAD_CURSOR', '游标非法');
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 键集分页:raws 按 (lastActiveMs desc, id asc) 全序;cursor 之后取 limit 条,
|
|
133
|
+
* 多取一条判 nextCursor。listId 为会话唯一键(id 类源=会话 id,路径类源=相对路径)。
|
|
134
|
+
*/
|
|
135
|
+
function paginateRaws(raws, listId, limit, cursor) {
|
|
136
|
+
const arr = (Array.isArray(raws) ? raws : []).slice();
|
|
137
|
+
arr.sort(
|
|
138
|
+
(a, b) =>
|
|
139
|
+
(Number(b.lastActiveMs) || 0) - (Number(a.lastActiveMs) || 0) ||
|
|
140
|
+
String(a[listId] || '').localeCompare(String(b[listId] || ''))
|
|
141
|
+
);
|
|
142
|
+
let start = 0;
|
|
143
|
+
if (cursor) {
|
|
144
|
+
while (
|
|
145
|
+
start < arr.length &&
|
|
146
|
+
!(
|
|
147
|
+
(Number(arr[start].lastActiveMs) || 0) < cursor.t ||
|
|
148
|
+
((Number(arr[start].lastActiveMs) || 0) === cursor.t &&
|
|
149
|
+
String(arr[start][listId] || '').localeCompare(cursor.id) > 0)
|
|
150
|
+
)
|
|
151
|
+
) {
|
|
152
|
+
start += 1;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const page = arr.slice(start, start + limit + 1);
|
|
156
|
+
const hasMore = page.length > limit;
|
|
157
|
+
return { page: page.slice(0, limit), hasMore };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function openReadOnlyDb(dbPath) {
|
|
161
|
+
if (!fs.existsSync(dbPath)) return null;
|
|
162
|
+
const { DatabaseSync } = require('node:sqlite');
|
|
163
|
+
return new DatabaseSync(dbPath, { readOnly: true });
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 表是否带 sequence 列(zcode 有、opencode 无——排序策略分叉,R2) */
|
|
167
|
+
function hasSequenceColumn(db, table) {
|
|
168
|
+
try {
|
|
169
|
+
return db.prepare(`PRAGMA table_info(${table})`).all().some((c) => c.name === 'sequence');
|
|
170
|
+
} catch (e) {
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// ---------- ① zcode(db/db.sqlite 三表) ----------
|
|
176
|
+
|
|
177
|
+
function zcodeDbPath(sourceCfg) {
|
|
178
|
+
const root = resolveHome(sourceCfg.root) || defaultRoot('zcode');
|
|
179
|
+
return path.join(root, 'db', 'db.sqlite');
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function listZcodeSessions(sourceCfg) {
|
|
183
|
+
const dbPath = zcodeDbPath(sourceCfg);
|
|
184
|
+
const db = openReadOnlyDb(dbPath);
|
|
185
|
+
if (!db) return [];
|
|
186
|
+
try {
|
|
187
|
+
const rows = db
|
|
188
|
+
.prepare(
|
|
189
|
+
'SELECT id, title, directory, time_created, time_updated FROM session WHERE time_deleted IS NULL ' +
|
|
190
|
+
'ORDER BY time_updated DESC, id ASC LIMIT 2000'
|
|
191
|
+
)
|
|
192
|
+
.all();
|
|
193
|
+
return (Array.isArray(rows) ? rows : []).map((r) => ({
|
|
194
|
+
id: String(r.id || ''),
|
|
195
|
+
listId: String(r.id || ''),
|
|
196
|
+
title: typeof r.title === 'string' ? r.title : '',
|
|
197
|
+
projectId: typeof r.directory === 'string' ? r.directory : '',
|
|
198
|
+
startedMs: r.time_created,
|
|
199
|
+
lastActiveMs: r.time_updated,
|
|
200
|
+
locator: { s: 'zcode', k: 'session', v: { id: String(r.id || '') } },
|
|
201
|
+
}));
|
|
202
|
+
} finally {
|
|
203
|
+
try { db.close(); } catch (e) { /* 收尾互不阻塞 */ }
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** zcode/opencode 共用三表全文装配(构型同构;排序差异由 orderMsg/orderPart SQL 表达) */
|
|
208
|
+
function threeTableTranscript(db, sessionId, collect, opts) {
|
|
209
|
+
const msgOrder = opts.msgOrder || 'sequence';
|
|
210
|
+
const partOrder = opts.partOrder || 'sequence';
|
|
211
|
+
const cols = opts.hasDeleted ? 'id, title, directory, time_created, time_updated, time_deleted' : 'id, title, directory, time_created, time_updated';
|
|
212
|
+
const sess = db.prepare(`SELECT ${cols} FROM session WHERE id = ?`).get(sessionId);
|
|
213
|
+
if (!sess) throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在');
|
|
214
|
+
if (sess.time_deleted) throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在'); // 已删会话(zcode;opencode 无此列不查)
|
|
215
|
+
const messages = db
|
|
216
|
+
.prepare(`SELECT id, data, time_created FROM message WHERE session_id = ? ORDER BY ${msgOrder}`)
|
|
217
|
+
.all(sessionId);
|
|
218
|
+
const parts = db
|
|
219
|
+
.prepare(`SELECT message_id, data FROM part WHERE session_id = ? ORDER BY ${partOrder}`)
|
|
220
|
+
.all(sessionId);
|
|
221
|
+
const byMessage = new Map();
|
|
222
|
+
for (const p of Array.isArray(parts) ? parts : []) {
|
|
223
|
+
if (!byMessage.has(p.message_id)) byMessage.set(p.message_id, []);
|
|
224
|
+
byMessage.get(p.message_id).push(p);
|
|
225
|
+
}
|
|
226
|
+
let head = null;
|
|
227
|
+
try {
|
|
228
|
+
head = messages.length > 0 && typeof messages[0].data === 'string' ? JSON.parse(messages[0].data) : null;
|
|
229
|
+
} catch (e) { /* 容错 */ }
|
|
230
|
+
for (const m of Array.isArray(messages) ? messages : []) {
|
|
231
|
+
let mdata = null;
|
|
232
|
+
try {
|
|
233
|
+
mdata = typeof m.data === 'string' ? JSON.parse(m.data) : null;
|
|
234
|
+
} catch (e) { /* 坏行跳过 */ }
|
|
235
|
+
const role = mdata && mdata.role === 'user' ? 'user' : 'assistant';
|
|
236
|
+
const tsMs =
|
|
237
|
+
mdata && mdata.time && Number.isFinite(mdata.time.start)
|
|
238
|
+
? mdata.time.start
|
|
239
|
+
: Number.isFinite(m.time_created)
|
|
240
|
+
? m.time_created
|
|
241
|
+
: null;
|
|
242
|
+
for (const p of byMessage.get(m.id) || []) {
|
|
243
|
+
let pdata = null;
|
|
244
|
+
try {
|
|
245
|
+
pdata = typeof p.data === 'string' ? JSON.parse(p.data) : null;
|
|
246
|
+
} catch (e) { continue; }
|
|
247
|
+
if (!pdata || typeof pdata.type !== 'string') continue;
|
|
248
|
+
if (pdata.type === 'text' && typeof pdata.text === 'string' && pdata.text.trim()) {
|
|
249
|
+
collect.push(role, tsMs, pdata.text, null);
|
|
250
|
+
} else if (pdata.type === 'tool') {
|
|
251
|
+
const st = pdata.state && isPlainObject(pdata.state) ? pdata.state : {};
|
|
252
|
+
const status = st.status === 'error' ? 'error' : st.status === 'completed' ? 'ok' : 'running';
|
|
253
|
+
const chunks = [];
|
|
254
|
+
if (st.input !== undefined && st.input !== null) {
|
|
255
|
+
try { chunks.push('入参 ' + JSON.stringify(st.input)); } catch (e) { /* 循环引用容错 */ }
|
|
256
|
+
}
|
|
257
|
+
if (typeof st.output === 'string' && st.output) chunks.push(st.output);
|
|
258
|
+
collect.push('tool', tsMs, chunks.join('\n'), { name: String(pdata.tool || ''), status });
|
|
259
|
+
}
|
|
260
|
+
// 其余 part 形态(step-start/step-finish/reasoning/patch/file)不属于阅读正文,跳过
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
return {
|
|
264
|
+
title: typeof sess.title === 'string' ? sess.title : '',
|
|
265
|
+
projectId: typeof sess.directory === 'string' ? sess.directory : '',
|
|
266
|
+
startedMs: sess.time_created,
|
|
267
|
+
lastActiveMs: sess.time_updated,
|
|
268
|
+
head,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function transcriptZcode(sourceCfg, locator, collect) {
|
|
273
|
+
const db = openReadOnlyDb(zcodeDbPath(sourceCfg));
|
|
274
|
+
if (!db) throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在');
|
|
275
|
+
try {
|
|
276
|
+
return threeTableTranscript(db, locator.v.id, collect, {
|
|
277
|
+
msgOrder: 'sequence',
|
|
278
|
+
partOrder: 'sequence',
|
|
279
|
+
hasDeleted: true,
|
|
280
|
+
});
|
|
281
|
+
} finally {
|
|
282
|
+
try { db.close(); } catch (e) { /* 收尾互不阻塞 */ }
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// ---------- ② opencode(opencode.db 三表,无 sequence 列) ----------
|
|
287
|
+
|
|
288
|
+
function opencodeDbPath(sourceCfg) {
|
|
289
|
+
return resolveHome(sourceCfg.dbPath) || defaultRoot('opencode');
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function listOpencodeSessions(sourceCfg) {
|
|
293
|
+
const dbPath = opencodeDbPath(sourceCfg);
|
|
294
|
+
const db = openReadOnlyDb(dbPath);
|
|
295
|
+
if (!db) return [];
|
|
296
|
+
try {
|
|
297
|
+
const rows = db
|
|
298
|
+
.prepare(
|
|
299
|
+
'SELECT id, directory, title, time_created, time_updated FROM session ' +
|
|
300
|
+
'ORDER BY time_updated DESC, id ASC LIMIT 2000'
|
|
301
|
+
)
|
|
302
|
+
.all();
|
|
303
|
+
return (Array.isArray(rows) ? rows : []).map((r) => ({
|
|
304
|
+
id: String(r.id || ''),
|
|
305
|
+
listId: String(r.id || ''),
|
|
306
|
+
title: typeof r.title === 'string' ? r.title : '',
|
|
307
|
+
projectId: typeof r.directory === 'string' ? r.directory : '',
|
|
308
|
+
startedMs: r.time_created,
|
|
309
|
+
lastActiveMs: r.time_updated,
|
|
310
|
+
locator: { s: 'opencode', k: 'session', v: { id: String(r.id || '') } },
|
|
311
|
+
}));
|
|
312
|
+
} finally {
|
|
313
|
+
try { db.close(); } catch (e) { /* 收尾互不阻塞 */ }
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function transcriptOpencode(sourceCfg, locator, collect) {
|
|
318
|
+
const db = openReadOnlyDb(opencodeDbPath(sourceCfg));
|
|
319
|
+
if (!db) throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在');
|
|
320
|
+
try {
|
|
321
|
+
const useSeq = hasSequenceColumn(db, 'message') && hasSequenceColumn(db, 'part');
|
|
322
|
+
return threeTableTranscript(db, locator.v.id, collect, {
|
|
323
|
+
msgOrder: useSeq ? 'sequence' : 'time_created, rowid',
|
|
324
|
+
partOrder: useSeq ? 'sequence' : 'time_created, rowid',
|
|
325
|
+
hasDeleted: false,
|
|
326
|
+
});
|
|
327
|
+
} finally {
|
|
328
|
+
try { db.close(); } catch (e) { /* 收尾互不阻塞 */ }
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// ---------- ③ workbuddy(sessions 表;全文恒降级 D4) ----------
|
|
333
|
+
|
|
334
|
+
function workbuddyDbPath(sourceCfg) {
|
|
335
|
+
return resolveHome(sourceCfg.dbPath) || defaultRoot('workbuddy');
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function listWorkbuddySessions(sourceCfg) {
|
|
339
|
+
const dbPath = workbuddyDbPath(sourceCfg);
|
|
340
|
+
const db = openReadOnlyDb(dbPath);
|
|
341
|
+
if (!db) return [];
|
|
342
|
+
try {
|
|
343
|
+
// 凭据红线:仅 SELECT sessions 表所需列
|
|
344
|
+
const rows = db
|
|
345
|
+
.prepare(
|
|
346
|
+
'SELECT id, cwd, title, status, created_at, last_activity_at FROM sessions ' +
|
|
347
|
+
'ORDER BY last_activity_at DESC, id ASC LIMIT 2000'
|
|
348
|
+
)
|
|
349
|
+
.all();
|
|
350
|
+
const stateMap = {
|
|
351
|
+
running: 'active',
|
|
352
|
+
'in_progress': 'active',
|
|
353
|
+
'in-progress': 'active',
|
|
354
|
+
completed: 'completed',
|
|
355
|
+
complete: 'completed',
|
|
356
|
+
done: 'completed',
|
|
357
|
+
failed: 'failed',
|
|
358
|
+
error: 'failed',
|
|
359
|
+
cancelled: 'cancelled',
|
|
360
|
+
canceled: 'cancelled',
|
|
361
|
+
};
|
|
362
|
+
return (Array.isArray(rows) ? rows : []).map((r) => ({
|
|
363
|
+
id: String(r.id === null || r.id === undefined ? '' : r.id),
|
|
364
|
+
listId: String(r.id === null || r.id === undefined ? '' : r.id),
|
|
365
|
+
title: typeof r.title === 'string' ? r.title : '',
|
|
366
|
+
projectId: typeof r.cwd === 'string' ? r.cwd : '',
|
|
367
|
+
startedMs: r.created_at,
|
|
368
|
+
lastActiveMs: r.last_activity_at,
|
|
369
|
+
state: stateMap[String(r.status || '').toLowerCase()] || 'idle',
|
|
370
|
+
locator: { s: 'workbuddy', k: 'session', v: { id: String(r.id === null || r.id === undefined ? '' : r.id) } },
|
|
371
|
+
}));
|
|
372
|
+
} finally {
|
|
373
|
+
try { db.close(); } catch (e) { /* 收尾互不阻塞 */ }
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function transcriptWorkbuddy(sourceCfg, locator) {
|
|
378
|
+
const db = openReadOnlyDb(workbuddyDbPath(sourceCfg));
|
|
379
|
+
if (!db) throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在');
|
|
380
|
+
try {
|
|
381
|
+
const row = db.prepare('SELECT id, cwd, title, created_at, last_activity_at FROM sessions WHERE id = ?').get(locator.v.id);
|
|
382
|
+
if (!row) throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在');
|
|
383
|
+
return {
|
|
384
|
+
degraded: true,
|
|
385
|
+
reason: 'SOURCE_NO_TRANSCRIPT',
|
|
386
|
+
title: typeof row.title === 'string' ? row.title : '',
|
|
387
|
+
projectId: typeof row.cwd === 'string' ? row.cwd : '',
|
|
388
|
+
startedMs: row.created_at,
|
|
389
|
+
lastActiveMs: row.last_activity_at,
|
|
390
|
+
};
|
|
391
|
+
} finally {
|
|
392
|
+
try { db.close(); } catch (e) { /* 收尾互不阻塞 */ }
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// ---------- ⑤ hermes(%LOCALAPPDATA%/hermes/state.db,2026-11-03 第七源) ----------
|
|
397
|
+
|
|
398
|
+
function hermesDbPath(sourceCfg) {
|
|
399
|
+
return resolveHome(sourceCfg.dbPath) || defaultRoot('hermes');
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** Unix 秒浮点(hermes 时间戳口径)→ ms 整数;无效返回 null */
|
|
403
|
+
function hermesSecToMs(v) {
|
|
404
|
+
const n = Number(v);
|
|
405
|
+
return Number.isFinite(n) && n > 0 ? Math.round(n * 1000) : null;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function listHermesSessions(sourceCfg) {
|
|
409
|
+
const db = openReadOnlyDb(hermesDbPath(sourceCfg));
|
|
410
|
+
if (!db) return [];
|
|
411
|
+
try {
|
|
412
|
+
// 凭据红线:仅 SELECT sessions 表所需列;archived/hidden 会话出局
|
|
413
|
+
const rows = db
|
|
414
|
+
.prepare(
|
|
415
|
+
'SELECT id, title, cwd, started_at, last_activity_at FROM sessions ' +
|
|
416
|
+
'WHERE archived = 0 AND hidden = 0 ORDER BY last_activity_at DESC, id ASC LIMIT 2000'
|
|
417
|
+
)
|
|
418
|
+
.all();
|
|
419
|
+
return (Array.isArray(rows) ? rows : []).map((r) => ({
|
|
420
|
+
id: String(r.id === null || r.id === undefined ? '' : r.id),
|
|
421
|
+
listId: String(r.id === null || r.id === undefined ? '' : r.id),
|
|
422
|
+
title: typeof r.title === 'string' ? r.title : '',
|
|
423
|
+
projectId: typeof r.cwd === 'string' ? r.cwd : '',
|
|
424
|
+
startedMs: hermesSecToMs(r.started_at),
|
|
425
|
+
lastActiveMs: hermesSecToMs(r.last_activity_at),
|
|
426
|
+
locator: { s: 'hermes', k: 'session', v: { id: String(r.id === null || r.id === undefined ? '' : r.id) } },
|
|
427
|
+
}));
|
|
428
|
+
} finally {
|
|
429
|
+
try { db.close(); } catch (e) { /* 收尾互不阻塞 */ }
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* hermes 全文阅读器:messages 表按 display_order 装配(真全文,非降级——
|
|
435
|
+
* workbuddy 式 SOURCE_NO_TRANSCRIPT 不适用于 hermes,其 messages 列 content 即消息文本)。
|
|
436
|
+
* 只取 active=1 且未 compacted 的 user/assistant/tool 三种角色(与六源阅读器三分类对齐)。
|
|
437
|
+
*/
|
|
438
|
+
function transcriptHermes(sourceCfg, locator, collect) {
|
|
439
|
+
const db = openReadOnlyDb(hermesDbPath(sourceCfg));
|
|
440
|
+
if (!db) throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在');
|
|
441
|
+
try {
|
|
442
|
+
const row = db
|
|
443
|
+
.prepare('SELECT id, cwd, title, started_at, last_activity_at FROM sessions WHERE id = ? AND archived = 0 AND hidden = 0')
|
|
444
|
+
.get(locator.v.id);
|
|
445
|
+
if (!row) throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在');
|
|
446
|
+
const msgs = db
|
|
447
|
+
.prepare(
|
|
448
|
+
"SELECT role, content, timestamp FROM messages WHERE session_id = ? AND active = 1 AND compacted = 0 " +
|
|
449
|
+
"AND role IN ('user','assistant','tool') ORDER BY display_order ASC"
|
|
450
|
+
)
|
|
451
|
+
.all(locator.v.id);
|
|
452
|
+
for (const m of Array.isArray(msgs) ? msgs : []) {
|
|
453
|
+
const text = typeof m.content === 'string' ? m.content : '';
|
|
454
|
+
if (!text) continue; // 空内容行(如纯 reasoning 的 assistant 占位)跳过
|
|
455
|
+
const tsMs = hermesSecToMs(m.timestamp);
|
|
456
|
+
collect.push(m.role, tsMs, text, m.role === 'tool' ? { name: '', status: 'ok' } : null);
|
|
457
|
+
}
|
|
458
|
+
return {
|
|
459
|
+
title: typeof row.title === 'string' ? row.title : '',
|
|
460
|
+
projectId: typeof row.cwd === 'string' ? row.cwd : '',
|
|
461
|
+
startedMs: hermesSecToMs(row.started_at),
|
|
462
|
+
lastActiveMs: hermesSecToMs(row.last_activity_at),
|
|
463
|
+
};
|
|
464
|
+
} finally {
|
|
465
|
+
try { db.close(); } catch (e) { /* 收尾互不阻塞 */ }
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// ---------- ④ claude(projects/<编码目录>/<uuid>.jsonl) ----------
|
|
470
|
+
|
|
471
|
+
/** 扫描全部会话 jsonl(列表按 (mtimeMs desc, 相对键 asc) 键集分页) */
|
|
472
|
+
function scanClaudeFiles(sourceCfg) {
|
|
473
|
+
const root = resolveHome(sourceCfg.root) || defaultRoot('claude');
|
|
474
|
+
if (!isDir(root)) return { root, files: [] };
|
|
475
|
+
const files = [];
|
|
476
|
+
let projectDirs;
|
|
477
|
+
try {
|
|
478
|
+
projectDirs = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory());
|
|
479
|
+
} catch (e) {
|
|
480
|
+
return { root, files: [] };
|
|
481
|
+
}
|
|
482
|
+
for (const pd of projectDirs) {
|
|
483
|
+
const pdir = path.join(root, pd.name);
|
|
484
|
+
let entries;
|
|
485
|
+
try {
|
|
486
|
+
entries = fs.readdirSync(pdir, { withFileTypes: true });
|
|
487
|
+
} catch (e) {
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
for (const ent of entries) {
|
|
491
|
+
if (!ent.isFile() || !ent.name.endsWith('.jsonl')) continue;
|
|
492
|
+
try {
|
|
493
|
+
const st = fs.statSync(path.join(pdir, ent.name));
|
|
494
|
+
files.push({ dirName: pd.name, file: ent.name, mtimeMs: st.mtimeMs, birthtimeMs: st.birthtimeMs });
|
|
495
|
+
} catch (e) { /* 竞态删除容忍 */ }
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
return { root, files };
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function isDir(p) {
|
|
502
|
+
try {
|
|
503
|
+
return fs.statSync(p).isDirectory();
|
|
504
|
+
} catch (e) {
|
|
505
|
+
return false;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function claudeFileMeta(f, root) {
|
|
510
|
+
const full = path.join(root, f.dirName, f.file);
|
|
511
|
+
const head = parseJsonlBuffer(readHead(full, 32 * 1024));
|
|
512
|
+
const titleText = firstTextOf(head);
|
|
513
|
+
const cwd = cwdFromBuffer(readTail(full, 32 * 1024)) || aa.decodeProjectDirName(f.dirName);
|
|
514
|
+
return { title: titleText || '', projectId: cwd, full };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** 复用活动流同款取法:第一条有文本行(content/lastPrompt/message/text 多形态) */
|
|
518
|
+
function firstTextOf(objs) {
|
|
519
|
+
for (const o of objs || []) {
|
|
520
|
+
const t = extractLineText(o);
|
|
521
|
+
if (t) return t;
|
|
522
|
+
}
|
|
523
|
+
return null;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** tail 缓冲抓最后一个 "cwd":"..."(与 agentActivity.cwdFromBuffer 同构) */
|
|
527
|
+
function cwdFromBuffer(r) {
|
|
528
|
+
if (!r) return '';
|
|
529
|
+
const text = r.buf.toString('utf8');
|
|
530
|
+
const re = /"cwd"\s*:\s*"((?:[^"\\]|\\.)*)"/g;
|
|
531
|
+
let m;
|
|
532
|
+
let last = null;
|
|
533
|
+
while ((m = re.exec(text)) !== null) last = m[1];
|
|
534
|
+
if (last === null) return '';
|
|
535
|
+
try {
|
|
536
|
+
return JSON.parse(`"${last}"`);
|
|
537
|
+
} catch (e) {
|
|
538
|
+
return '';
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
function listClaudeSessions(sourceCfg) {
|
|
543
|
+
const { root, files } = scanClaudeFiles(sourceCfg);
|
|
544
|
+
return files.map((f) => {
|
|
545
|
+
const meta = claudeFileMeta(f, root);
|
|
546
|
+
return {
|
|
547
|
+
id: `${f.dirName}/${f.file}`,
|
|
548
|
+
listId: `${f.dirName}/${f.file}`,
|
|
549
|
+
title: meta.title,
|
|
550
|
+
projectId: meta.projectId,
|
|
551
|
+
startedMs: f.birthtimeMs,
|
|
552
|
+
lastActiveMs: f.mtimeMs,
|
|
553
|
+
locator: { s: 'claude', k: 'project', v: { dir: f.dirName, file: f.file } },
|
|
554
|
+
};
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/** claude 单行 → 0..n 条归一化消息(text/tool_use/tool_result 块拆分;isSidechain 与非消息行跳过) */
|
|
559
|
+
function claudeLineToMessages(o, collect, callNames) {
|
|
560
|
+
if (!isPlainObject(o) || o.isSidechain === true) return;
|
|
561
|
+
if (o.type !== 'user' && o.type !== 'assistant') return; // attachment/queue-operation/last-prompt/summary 等跳过
|
|
562
|
+
const tsMs = toIsoFromValueMs(o.timestamp);
|
|
563
|
+
const lineRole = o.type === 'user' ? 'user' : 'assistant';
|
|
564
|
+
const m = o.message;
|
|
565
|
+
const content = isPlainObject(m) ? m.content : undefined;
|
|
566
|
+
if (typeof content === 'string') {
|
|
567
|
+
if (content.trim()) collect.push(lineRole, tsMs, content, null);
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
if (!Array.isArray(content)) return;
|
|
571
|
+
for (const block of content) {
|
|
572
|
+
if (!isPlainObject(block)) continue;
|
|
573
|
+
if (block.type === 'text') {
|
|
574
|
+
if (typeof block.text === 'string' && block.text.trim()) collect.push(lineRole, tsMs, block.text, null);
|
|
575
|
+
} else if (block.type === 'tool_use') {
|
|
576
|
+
if (typeof block.id === 'string' && block.id && typeof block.name === 'string') {
|
|
577
|
+
callNames.set(block.id, block.name);
|
|
578
|
+
}
|
|
579
|
+
let inputText = '';
|
|
580
|
+
try {
|
|
581
|
+
inputText = block.input === undefined ? '' : JSON.stringify(block.input);
|
|
582
|
+
} catch (e) { /* 循环引用容错 */ }
|
|
583
|
+
collect.push('tool', tsMs, inputText, { name: String(block.name || ''), status: 'ok' }); // §3.4:tool_use → 发起(status ok)
|
|
584
|
+
} else if (block.type === 'tool_result') {
|
|
585
|
+
const name = typeof block.tool_use_id === 'string' ? callNames.get(block.tool_use_id) || '' : '';
|
|
586
|
+
const status = block.is_error === true ? 'error' : 'ok';
|
|
587
|
+
let text = '';
|
|
588
|
+
if (typeof block.content === 'string') text = block.content;
|
|
589
|
+
else if (Array.isArray(block.content)) {
|
|
590
|
+
text = block.content
|
|
591
|
+
.filter((b) => isPlainObject(b) && typeof b.text === 'string')
|
|
592
|
+
.map((b) => b.text)
|
|
593
|
+
.join('\n');
|
|
594
|
+
}
|
|
595
|
+
collect.push('tool', tsMs, text, { name, status });
|
|
596
|
+
}
|
|
597
|
+
// thinking 等其余块跳过
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
function toIsoFromValueMs(v) {
|
|
602
|
+
const t = toIsoFromValue(v);
|
|
603
|
+
return t === null ? null : Date.parse(t);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
function transcriptClaude(sourceCfg, locator, collect) {
|
|
607
|
+
const { absolute } = (() => sessionRef.resolveLocatorPath(locator, sourceCfgFullOf(sourceCfg)))();
|
|
608
|
+
const r = readHead(absolute, TRANSCRIPT_FILE_CAP);
|
|
609
|
+
if (!r) throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在');
|
|
610
|
+
const st = fs.statSync(absolute);
|
|
611
|
+
const callNames = new Map();
|
|
612
|
+
const lines = parseJsonlBuffer(r);
|
|
613
|
+
for (const o of lines) claudeLineToMessages(o, collect, callNames);
|
|
614
|
+
const cwd = cwdFromBuffer(readTail(absolute, 32 * 1024)) || '';
|
|
615
|
+
return {
|
|
616
|
+
title: firstTextOf(lines) || '',
|
|
617
|
+
projectId: cwd,
|
|
618
|
+
startedMs: st.birthtimeMs,
|
|
619
|
+
lastActiveMs: st.mtimeMs,
|
|
620
|
+
readTruncated: r.truncated || st.size > TRANSCRIPT_FILE_CAP,
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/** resolveLocatorPath 需要 config 形状:把单源 sources 节包成全量形(路径类三源共用) */
|
|
625
|
+
function sourceCfgFullOf(sourceCfg) {
|
|
626
|
+
return { agentActivity: { sources: { claude: sourceCfg, dsh: sourceCfg, codex: sourceCfg } } };
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// ---------- ⑤ dsh(session*.jsonl.zstd 多帧 / rollout-*.jsonl 明文) ----------
|
|
630
|
+
|
|
631
|
+
/** zstd 多帧分帧解压(R3:单次 sync 只出首帧,必须按 magic 逐帧);超过 decompressCap 停止 → truncated */
|
|
632
|
+
function zstdDecompressFrames(buf, decompressCap) {
|
|
633
|
+
const caps = decompressCap || DSH_DECOMPRESS_CAP;
|
|
634
|
+
const outs = [];
|
|
635
|
+
let total = 0;
|
|
636
|
+
let truncated = false;
|
|
637
|
+
const offs = [];
|
|
638
|
+
let i = 0;
|
|
639
|
+
while ((i = buf.indexOf(ZSTD_MAGIC, i)) !== -1) {
|
|
640
|
+
offs.push(i);
|
|
641
|
+
i += ZSTD_MAGIC.length;
|
|
642
|
+
if (offs.length > 200000) break; // 防御:异常巨型帧表
|
|
643
|
+
}
|
|
644
|
+
for (let k = 0; k < offs.length; k++) {
|
|
645
|
+
if (total > caps) {
|
|
646
|
+
truncated = true;
|
|
647
|
+
break;
|
|
648
|
+
}
|
|
649
|
+
const chunk = buf.subarray(offs[k], k + 1 < offs.length ? offs[k + 1] : buf.length);
|
|
650
|
+
try {
|
|
651
|
+
const out = zlib.zstdDecompressSync(chunk);
|
|
652
|
+
total += out.length;
|
|
653
|
+
outs.push(out);
|
|
654
|
+
} catch (e) { /* 伪 magic/损坏帧跳过(列表标题/全文均降级容忍) */ }
|
|
655
|
+
}
|
|
656
|
+
return { text: Buffer.concat(outs).toString('utf8'), truncated: truncated || total > caps };
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/** 扫描 dsh 会话文件(两层布局兼容,同活动流 dshAdapter) */
|
|
660
|
+
function scanDshFiles(sourceCfg) {
|
|
661
|
+
const root = resolveHome(sourceCfg.root) || defaultRoot('dsh');
|
|
662
|
+
const files = [];
|
|
663
|
+
if (!isDir(root)) return { root, files };
|
|
664
|
+
let projectDirs;
|
|
665
|
+
try {
|
|
666
|
+
projectDirs = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory());
|
|
667
|
+
} catch (e) {
|
|
668
|
+
return { root, files };
|
|
669
|
+
}
|
|
670
|
+
for (const pd of projectDirs) {
|
|
671
|
+
const pdir = path.join(root, pd.name);
|
|
672
|
+
let entries;
|
|
673
|
+
try {
|
|
674
|
+
entries = fs.readdirSync(pdir, { withFileTypes: true });
|
|
675
|
+
} catch (e) {
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
for (const ent of entries) {
|
|
679
|
+
const rel1 = (n) => /^rollout-.*\.jsonl$/.test(n);
|
|
680
|
+
if (ent.isFile() && rel1(ent.name)) {
|
|
681
|
+
pushDshFile(files, root, pd.name, pd.name, 'rollout', ent.name);
|
|
682
|
+
continue;
|
|
683
|
+
}
|
|
684
|
+
if (!ent.isDirectory()) continue;
|
|
685
|
+
let inner;
|
|
686
|
+
try {
|
|
687
|
+
inner = fs.readdirSync(path.join(pdir, ent.name), { withFileTypes: true });
|
|
688
|
+
} catch (e) {
|
|
689
|
+
continue;
|
|
690
|
+
}
|
|
691
|
+
for (const f2 of inner) {
|
|
692
|
+
if (!f2.isFile()) continue;
|
|
693
|
+
if (/^session.*\.jsonl\.zstd$/.test(f2.name)) pushDshFile(files, root, pd.name, ent.name, 'zstd', f2.name);
|
|
694
|
+
else if (/^rollout-.*\.jsonl$/.test(f2.name)) pushDshFile(files, root, pd.name, ent.name, 'rollout', f2.name);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
return { root, files };
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
function pushDshFile(files, root, dirName, sessDirName, kind, fileName) {
|
|
702
|
+
const rel = `${dirName}/${sessDirName}/${fileName}`;
|
|
703
|
+
try {
|
|
704
|
+
const st = fs.statSync(path.join(root, dirName, sessDirName, fileName));
|
|
705
|
+
files.push({ dirName, sessDirName, kind, file: fileName, rel, mtimeMs: st.mtimeMs, birthtimeMs: st.birthtimeMs });
|
|
706
|
+
} catch (e) { /* 竞态删除容忍 */ }
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
/** dsh 标题:首条 user 文本前 60 字(§3.1);zstd 轻解压(帧数/字节双帽)找首个 user/message */
|
|
710
|
+
function dshTitleOf(root, f) {
|
|
711
|
+
const full = path.join(root, f.dirName, f.sessDirName, f.file);
|
|
712
|
+
let lines = [];
|
|
713
|
+
let header = null;
|
|
714
|
+
if (f.kind === 'zstd') {
|
|
715
|
+
let buf;
|
|
716
|
+
try {
|
|
717
|
+
if (fs.statSync(full).size > DSH_ZSTD_CAP) return { title: '', header: null };
|
|
718
|
+
buf = fs.readFileSync(full);
|
|
719
|
+
} catch (e) {
|
|
720
|
+
return { title: '', header: null };
|
|
721
|
+
}
|
|
722
|
+
const dec = zstdDecompressFrames(buf, DSH_LIST_DECOMPRESS_CAP);
|
|
723
|
+
let acc = 0;
|
|
724
|
+
for (const line of dec.text.split('\n')) {
|
|
725
|
+
const t = line.trim();
|
|
726
|
+
if (!t) continue;
|
|
727
|
+
let o = null;
|
|
728
|
+
try {
|
|
729
|
+
o = JSON.parse(t);
|
|
730
|
+
} catch (e) { continue; }
|
|
731
|
+
if (!isPlainObject(o)) continue;
|
|
732
|
+
if (!header && o.type === 'session') header = o;
|
|
733
|
+
if (o.type === 'user/message') {
|
|
734
|
+
const txt = dshContentText(o.data && o.data.content);
|
|
735
|
+
if (txt) {
|
|
736
|
+
lines = [txt];
|
|
737
|
+
break;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
acc += 1;
|
|
741
|
+
if (acc >= DSH_LIST_FRAME_CAP) break;
|
|
742
|
+
}
|
|
743
|
+
} else {
|
|
744
|
+
const head = parseJsonlBuffer(readHead(full, 32 * 1024));
|
|
745
|
+
for (const o of head) {
|
|
746
|
+
if (isPlainObject(o) && o.type === 'session') header = o;
|
|
747
|
+
if (isPlainObject(o) && o.type === 'user/message') {
|
|
748
|
+
const txt = dshContentText(o.data && o.data.content);
|
|
749
|
+
if (txt) {
|
|
750
|
+
lines = [txt];
|
|
751
|
+
break;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
if (lines.length === 0) {
|
|
756
|
+
const t = firstTextOf(head.filter((o) => !(isPlainObject(o) && o.type === 'session')));
|
|
757
|
+
if (t) lines = [t];
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
const raw = lines[0] || '';
|
|
761
|
+
return { title: raw.replace(/\s+/g, ' ').trim().slice(0, 60), header };
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
function dshContentText(content) {
|
|
765
|
+
if (!Array.isArray(content)) return '';
|
|
766
|
+
return content
|
|
767
|
+
.filter((b) => isPlainObject(b) && b.type === 'text' && typeof b.text === 'string')
|
|
768
|
+
.map((b) => b.text)
|
|
769
|
+
.join('')
|
|
770
|
+
.trim();
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
function listDshSessions(sourceCfg) {
|
|
774
|
+
const { root, files } = scanDshFiles(sourceCfg);
|
|
775
|
+
return files.map((f) => {
|
|
776
|
+
const { title, header } = dshTitleOf(root, f);
|
|
777
|
+
return {
|
|
778
|
+
id: f.rel,
|
|
779
|
+
listId: f.rel,
|
|
780
|
+
title,
|
|
781
|
+
projectId: (header && typeof header.cwd === 'string' && header.cwd) || aa.decodeProjectDirName(f.dirName),
|
|
782
|
+
startedMs: header && Number.isFinite(header.createdAt) ? header.createdAt : f.birthtimeMs,
|
|
783
|
+
lastActiveMs: f.mtimeMs,
|
|
784
|
+
locator: { s: 'dsh', k: 'file', v: { path: f.rel } },
|
|
785
|
+
};
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/** dsh 行 → 归一化消息(R3 形态;解析不出文本的行跳过不报错) */
|
|
790
|
+
function dshLineToMessages(o, collect, callNames) {
|
|
791
|
+
if (!isPlainObject(o) || typeof o.type !== 'string') return;
|
|
792
|
+
const tsMs = Number.isFinite(o.time) ? o.time : null;
|
|
793
|
+
const d = o.data;
|
|
794
|
+
switch (o.type) {
|
|
795
|
+
case 'user/message':
|
|
796
|
+
case 'assistant/message': {
|
|
797
|
+
const role = o.type === 'user/message' ? 'user' : 'assistant';
|
|
798
|
+
const content =
|
|
799
|
+
role === 'user' ? (isPlainObject(d) ? d.content : undefined) : isPlainObject(d) && isPlainObject(d.message) ? d.message.content : undefined;
|
|
800
|
+
const text = dshContentText(content);
|
|
801
|
+
if (text) collect.push(role, tsMs, text, null);
|
|
802
|
+
break;
|
|
803
|
+
}
|
|
804
|
+
case 'tool/call': {
|
|
805
|
+
if (!isPlainObject(d)) break;
|
|
806
|
+
if (typeof d.callId === 'string' && d.callId && typeof d.name === 'string') {
|
|
807
|
+
callNames.set(d.callId, d.name);
|
|
808
|
+
}
|
|
809
|
+
collect.push('tool', tsMs, typeof d.arguments === 'string' ? d.arguments : '', {
|
|
810
|
+
name: String(d.name || ''),
|
|
811
|
+
status: 'running',
|
|
812
|
+
});
|
|
813
|
+
break;
|
|
814
|
+
}
|
|
815
|
+
case 'tool/result': {
|
|
816
|
+
if (!isPlainObject(d)) break;
|
|
817
|
+
const msg = isPlainObject(d.message) ? d.message : {};
|
|
818
|
+
const callId = isPlainObject(msg.source) && typeof msg.source.callId === 'string' ? msg.source.callId : '';
|
|
819
|
+
const chunks = [];
|
|
820
|
+
let isError = false;
|
|
821
|
+
if (Array.isArray(msg.content)) {
|
|
822
|
+
for (const block of msg.content) {
|
|
823
|
+
if (!isPlainObject(block) || block.type !== 'tool-result') continue;
|
|
824
|
+
if (block.isError === true) isError = true;
|
|
825
|
+
if (Array.isArray(block.content)) {
|
|
826
|
+
for (const inner of block.content) {
|
|
827
|
+
if (isPlainObject(inner) && inner.type === 'text' && typeof inner.text === 'string') chunks.push(inner.text);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
collect.push('tool', tsMs, chunks.join('\n'), {
|
|
833
|
+
name: callId ? callNames.get(callId) || '' : '',
|
|
834
|
+
status: isError ? 'error' : 'ok',
|
|
835
|
+
});
|
|
836
|
+
break;
|
|
837
|
+
}
|
|
838
|
+
default:
|
|
839
|
+
break; // session 元数据/标题/step/turn/请求头/chunks 流水行等一概跳过
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
function transcriptDsh(sourceCfg, locator, collect) {
|
|
844
|
+
sessionRef.resolveLocatorPath(locator, sourceCfgFullOf(sourceCfg));
|
|
845
|
+
const root = resolveHome(sourceCfg.root) || defaultRoot('dsh');
|
|
846
|
+
const rel = String(locator.v.path).split(/[\\/]/).join(path.sep);
|
|
847
|
+
const full = path.join(root, rel);
|
|
848
|
+
let st;
|
|
849
|
+
try {
|
|
850
|
+
st = fs.statSync(full);
|
|
851
|
+
} catch (e) {
|
|
852
|
+
throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在');
|
|
853
|
+
}
|
|
854
|
+
let header = null;
|
|
855
|
+
let readTruncated = false;
|
|
856
|
+
const callNames = new Map();
|
|
857
|
+
if (st.size > DSH_ZSTD_CAP) {
|
|
858
|
+
// 超限不解压(R4 读入闸):正文空、truncated 标记,头部信息尽力从活动流同款来源补
|
|
859
|
+
return { title: '', projectId: '', startedMs: st.birthtimeMs, lastActiveMs: st.mtimeMs, readTruncated: true };
|
|
860
|
+
}
|
|
861
|
+
if (/\.zstd$/.test(full)) {
|
|
862
|
+
let buf;
|
|
863
|
+
try {
|
|
864
|
+
buf = fs.readFileSync(full);
|
|
865
|
+
} catch (e) {
|
|
866
|
+
throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在');
|
|
867
|
+
}
|
|
868
|
+
const dec = zstdDecompressFrames(buf, DSH_DECOMPRESS_CAP);
|
|
869
|
+
readTruncated = dec.truncated;
|
|
870
|
+
for (const line of dec.text.split('\n')) {
|
|
871
|
+
const t = line.trim();
|
|
872
|
+
if (!t) continue;
|
|
873
|
+
let o = null;
|
|
874
|
+
try {
|
|
875
|
+
o = JSON.parse(t);
|
|
876
|
+
} catch (e) { continue; }
|
|
877
|
+
if (isPlainObject(o) && o.type === 'session') {
|
|
878
|
+
header = o;
|
|
879
|
+
continue;
|
|
880
|
+
}
|
|
881
|
+
dshLineToMessages(o, collect, callNames);
|
|
882
|
+
}
|
|
883
|
+
} else {
|
|
884
|
+
const r = readHead(full, TRANSCRIPT_FILE_CAP);
|
|
885
|
+
if (!r) throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在');
|
|
886
|
+
readTruncated = st.size > TRANSCRIPT_FILE_CAP;
|
|
887
|
+
for (const o of parseJsonlBuffer(r)) {
|
|
888
|
+
if (isPlainObject(o) && o.type === 'session') {
|
|
889
|
+
header = o;
|
|
890
|
+
continue;
|
|
891
|
+
}
|
|
892
|
+
dshLineToMessages(o, collect, callNames);
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
return {
|
|
896
|
+
title: collectFirstUserText(collect), // §3.1:dsh 标题=首条 user 文本前 60 字(与列表同源)
|
|
897
|
+
projectId: (header && typeof header.cwd === 'string' && header.cwd) || '',
|
|
898
|
+
startedMs: header && Number.isFinite(header.createdAt) ? header.createdAt : st.birthtimeMs,
|
|
899
|
+
lastActiveMs: st.mtimeMs,
|
|
900
|
+
readTruncated,
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
function collectFirstUserText(collect) {
|
|
905
|
+
for (const m of collect.items) {
|
|
906
|
+
if (m.role === 'user' && m.text.trim()) return m.text.replace(/\s+/g, ' ').trim().slice(0, 60);
|
|
907
|
+
}
|
|
908
|
+
return '';
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
// ---------- ⑥ codex(YYYY/MM/DD/rollout-*.jsonl) ----------
|
|
912
|
+
|
|
913
|
+
function scanCodexFiles(sourceCfg) {
|
|
914
|
+
const root = resolveHome(sourceCfg.root) || defaultRoot('codex');
|
|
915
|
+
const files = [];
|
|
916
|
+
if (!isDir(root)) return { root, files };
|
|
917
|
+
const listDirs = (dir) => {
|
|
918
|
+
try {
|
|
919
|
+
return fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory());
|
|
920
|
+
} catch (e) {
|
|
921
|
+
return [];
|
|
922
|
+
}
|
|
923
|
+
};
|
|
924
|
+
let yearDirs;
|
|
925
|
+
try {
|
|
926
|
+
yearDirs = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory());
|
|
927
|
+
} catch (e) {
|
|
928
|
+
return { root, files };
|
|
929
|
+
}
|
|
930
|
+
for (const yd of yearDirs) {
|
|
931
|
+
for (const md of listDirs(path.join(root, yd.name))) {
|
|
932
|
+
for (const dd of listDirs(path.join(root, yd.name, md.name))) {
|
|
933
|
+
const dayDir = path.join(root, yd.name, md.name, dd.name);
|
|
934
|
+
let entries;
|
|
935
|
+
try {
|
|
936
|
+
entries = fs.readdirSync(dayDir, { withFileTypes: true });
|
|
937
|
+
} catch (e) {
|
|
938
|
+
continue;
|
|
939
|
+
}
|
|
940
|
+
for (const ent of entries) {
|
|
941
|
+
if (!ent.isFile() || !/^rollout-.*\.jsonl$/.test(ent.name)) continue;
|
|
942
|
+
try {
|
|
943
|
+
const st = fs.statSync(path.join(dayDir, ent.name));
|
|
944
|
+
files.push({
|
|
945
|
+
rel: `${yd.name}/${md.name}/${dd.name}/${ent.name}`,
|
|
946
|
+
mtimeMs: st.mtimeMs,
|
|
947
|
+
birthtimeMs: st.birthtimeMs,
|
|
948
|
+
});
|
|
949
|
+
} catch (e) { /* 竞态删除容忍 */ }
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
return { root, files };
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
function listCodexSessions(sourceCfg) {
|
|
958
|
+
const { root, files } = scanCodexFiles(sourceCfg);
|
|
959
|
+
return files.map((f) => {
|
|
960
|
+
const head = parseJsonlBuffer(readHead(path.join(root, f.rel.split('/').join(path.sep)), 64 * 1024));
|
|
961
|
+
const metaRec = head.find((o) => o && o.type === 'session_meta' && isPlainObject(o.payload));
|
|
962
|
+
const meta = (metaRec && metaRec.payload) || {};
|
|
963
|
+
const firstUser = codexUserTextOf(head);
|
|
964
|
+
return {
|
|
965
|
+
id: f.rel,
|
|
966
|
+
listId: f.rel,
|
|
967
|
+
title: firstUser ? firstUser.replace(/\s+/g, ' ').trim().slice(0, 60) : '',
|
|
968
|
+
projectId: typeof meta.cwd === 'string' ? meta.cwd : '',
|
|
969
|
+
startedMs: Date.parse(meta.timestamp) || f.birthtimeMs,
|
|
970
|
+
lastActiveMs: f.mtimeMs,
|
|
971
|
+
locator: { s: 'codex', k: 'file', v: { path: f.rel } },
|
|
972
|
+
};
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
function codexTextOf(payload) {
|
|
977
|
+
if (!isPlainObject(payload)) return null;
|
|
978
|
+
if (Array.isArray(payload.content)) {
|
|
979
|
+
const t = payload.content
|
|
980
|
+
.filter((b) => b && typeof b.text === 'string' && b.text)
|
|
981
|
+
.map((b) => b.text)
|
|
982
|
+
.join('');
|
|
983
|
+
if (t) return t;
|
|
984
|
+
}
|
|
985
|
+
if (typeof payload.message === 'string' && payload.message) return payload.message;
|
|
986
|
+
return null;
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
function codexUserTextOf(objs) {
|
|
990
|
+
for (const o of objs || []) {
|
|
991
|
+
if (o && o.type === 'response_item' && isPlainObject(o.payload) && o.payload.type === 'message' && o.payload.role === 'user') {
|
|
992
|
+
const t = codexTextOf(o.payload);
|
|
993
|
+
if (t) return t;
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
return null;
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
function transcriptCodex(sourceCfg, locator, collect) {
|
|
1000
|
+
sessionRef.resolveLocatorPath(locator, sourceCfgFullOf(sourceCfg));
|
|
1001
|
+
const root = resolveHome(sourceCfg.root) || defaultRoot('codex');
|
|
1002
|
+
const rel = String(locator.v.path).split(/[\\/]/).join(path.sep);
|
|
1003
|
+
const full = path.join(root, rel);
|
|
1004
|
+
let st;
|
|
1005
|
+
try {
|
|
1006
|
+
st = fs.statSync(full);
|
|
1007
|
+
} catch (e) {
|
|
1008
|
+
throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在');
|
|
1009
|
+
}
|
|
1010
|
+
const r = readHead(full, TRANSCRIPT_FILE_CAP);
|
|
1011
|
+
if (!r) throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在');
|
|
1012
|
+
const callNames = new Map();
|
|
1013
|
+
let meta = {};
|
|
1014
|
+
const lines = parseJsonlBuffer(r);
|
|
1015
|
+
for (const o of lines) {
|
|
1016
|
+
if (!isPlainObject(o)) continue;
|
|
1017
|
+
const tsMs = toIsoFromValueMs(o.timestamp);
|
|
1018
|
+
if (o.type === 'session_meta' && isPlainObject(o.payload)) {
|
|
1019
|
+
meta = o.payload;
|
|
1020
|
+
continue;
|
|
1021
|
+
}
|
|
1022
|
+
if (o.type !== 'response_item' || !isPlainObject(o.payload)) continue; // turn_context/world_state/event_msg 跳过
|
|
1023
|
+
const p = o.payload;
|
|
1024
|
+
if (p.type === 'message') {
|
|
1025
|
+
const text = codexTextOf(p);
|
|
1026
|
+
if (text && (p.role === 'user' || p.role === 'assistant')) collect.push(p.role, tsMs, text, null);
|
|
1027
|
+
} else if (p.type === 'function_call') {
|
|
1028
|
+
if (typeof p.call_id === 'string' && p.call_id && typeof p.name === 'string') callNames.set(p.call_id, p.name);
|
|
1029
|
+
collect.push('tool', tsMs, typeof p.arguments === 'string' ? p.arguments : '', { name: String(p.name || ''), status: 'running' });
|
|
1030
|
+
} else if (p.type === 'function_call_output') {
|
|
1031
|
+
collect.push('tool', tsMs, typeof p.output === 'string' ? p.output : '', {
|
|
1032
|
+
name: typeof p.call_id === 'string' ? callNames.get(p.call_id) || '' : '',
|
|
1033
|
+
status: 'ok',
|
|
1034
|
+
});
|
|
1035
|
+
}
|
|
1036
|
+
// reasoning 等其余 payload 跳过
|
|
1037
|
+
}
|
|
1038
|
+
return {
|
|
1039
|
+
title: codexUserTextOf(lines) ? codexUserTextOf(lines).replace(/\s+/g, ' ').trim().slice(0, 60) : '',
|
|
1040
|
+
projectId: typeof meta.cwd === 'string' ? meta.cwd : '',
|
|
1041
|
+
startedMs: Date.parse(meta.timestamp) || st.birthtimeMs,
|
|
1042
|
+
lastActiveMs: st.mtimeMs,
|
|
1043
|
+
readTruncated: r.truncated || st.size > TRANSCRIPT_FILE_CAP,
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
// ---------- ⑦ 派工词(v2.9.21):会话首条「真人指令」 ----------
|
|
1048
|
+
|
|
1049
|
+
/**
|
|
1050
|
+
* 派工词 = 归一化转录里第一条非注入的 user 文本(复用六源全文适配器,含脱敏/截断/读入闸)。
|
|
1051
|
+
* 实证(2026-10-29 真机抽样):zcode db 首条 user part 即派工词;codex 前几条 user 是注入包裹
|
|
1052
|
+
* (AGENTS.md 指令块 / # Files mentioned 文件引用 / <environment_context>),真指令在后;
|
|
1053
|
+
* claude 首条基本干净但偶有 <system-reminder> 注入。故清洗分两层:全源标签块剔除 + codex 专属跳过。
|
|
1054
|
+
*/
|
|
1055
|
+
|
|
1056
|
+
const DISPATCH_TEXT_CAP = 800; // 派工词返回上限(超出尾部 …[截断];展示侧另做钳制)
|
|
1057
|
+
const DISPATCH_SOURCES = ['zcode', 'claude', 'codex']; // v2.9.21 首批三源(dsh/opencode 按需扩)
|
|
1058
|
+
const DISPATCH_CACHE_TTL_MS = 120 * 1000; // ref → 派工词 内存缓存(会话首条不变,TTL 防长驻陈旧)
|
|
1059
|
+
const DISPATCH_CACHE_MAX = 200;
|
|
1060
|
+
const dispatchCache = new Map(); // ref -> { at, item }(Map 保序,超帽删最旧)
|
|
1061
|
+
|
|
1062
|
+
// 注入标签块整段剔除(DOTALL 多行);剔除后剩空 → 该条不算派工词,继续找下一条 user
|
|
1063
|
+
const DISPATCH_NOISE_BLOCK_RES = [
|
|
1064
|
+
/<system-reminder>[\s\S]*?<\/system-reminder>/g,
|
|
1065
|
+
/<environment_context>[\s\S]*?<\/environment_context>/g,
|
|
1066
|
+
/<untrusted_gen_ui_state>[\s\S]*?<\/untrusted_gen_ui_state>/g,
|
|
1067
|
+
];
|
|
1068
|
+
|
|
1069
|
+
/**
|
|
1070
|
+
* 单条 user 文本 → 派工词候选('' = 纯注入,跳过)。
|
|
1071
|
+
* @param {string} agent 源 id(codex 有专属包裹规则)
|
|
1072
|
+
* @param {string} raw 归一化 user 文本(未 finalize)
|
|
1073
|
+
*/
|
|
1074
|
+
function dispatchTextOf(agent, raw) {
|
|
1075
|
+
let t = String(raw || '');
|
|
1076
|
+
for (const re of DISPATCH_NOISE_BLOCK_RES) t = t.replace(re, '');
|
|
1077
|
+
t = t.trim();
|
|
1078
|
+
if (!t) return '';
|
|
1079
|
+
if (agent === 'codex') {
|
|
1080
|
+
const s = t.replace(/^\s+/, '');
|
|
1081
|
+
if (s.startsWith('# AGENTS.md instructions') || s.startsWith('<user_instructions>')) return '';
|
|
1082
|
+
if (s.startsWith('# Files mentioned by the user:')) {
|
|
1083
|
+
// 文件引用包裹块:真指令在最后一个 ## 文件条目之后;取不到即纯引用,跳过
|
|
1084
|
+
const lines = s.split(/\r?\n/);
|
|
1085
|
+
let last = -1;
|
|
1086
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1087
|
+
if (lines[i].startsWith('## ')) last = i;
|
|
1088
|
+
}
|
|
1089
|
+
if (last >= 0) t = lines.slice(last + 1).join('\n').trim();
|
|
1090
|
+
if (!t) return '';
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
return t;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
/** ref → 首条真人指令。响应 {found,text,ts,agent,ref,startedAt,lastActiveAt};会话不存在 404。 */
|
|
1097
|
+
function getDispatchPrompt(config, ref, opts) {
|
|
1098
|
+
const o = opts || {};
|
|
1099
|
+
const loc = sessionRef.validateRef(ref, config);
|
|
1100
|
+
const agent = loc.s;
|
|
1101
|
+
const sec = normalizeAgentActivity(isPlainObject(config) ? config.agentActivity : null);
|
|
1102
|
+
const src = sec.sources[agent] || {};
|
|
1103
|
+
if (sec.enabled === false || src.enabled === false) {
|
|
1104
|
+
throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在');
|
|
1105
|
+
}
|
|
1106
|
+
const adapters = o.adapters && isPlainObject(o.adapters) ? o.adapters : TRANSCRIPT_SOURCES;
|
|
1107
|
+
const fn = adapters[agent];
|
|
1108
|
+
if (typeof fn !== 'function') throw new HttpError(400, 'BAD_AGENT', '该源不支持派工词读取');
|
|
1109
|
+
const collect = MessageCollector();
|
|
1110
|
+
let meta;
|
|
1111
|
+
try {
|
|
1112
|
+
meta = fn(src, loc, collect) || {};
|
|
1113
|
+
} catch (e) {
|
|
1114
|
+
if (e instanceof HttpError) throw e;
|
|
1115
|
+
throw new HttpError(500, 'INTERNAL', '服务器内部错误');
|
|
1116
|
+
}
|
|
1117
|
+
let first = null;
|
|
1118
|
+
for (const m of collect.items) {
|
|
1119
|
+
if (m.role !== 'user' || !m.text.trim()) continue;
|
|
1120
|
+
const cleaned = dispatchTextOf(agent, m.text);
|
|
1121
|
+
if (cleaned) {
|
|
1122
|
+
first = { text: cleaned, ts: m.ts };
|
|
1123
|
+
break;
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
return {
|
|
1127
|
+
ref,
|
|
1128
|
+
agent,
|
|
1129
|
+
found: !!first,
|
|
1130
|
+
text: first ? finalizeText(first.text, o.maxChars || DISPATCH_TEXT_CAP) : '',
|
|
1131
|
+
ts: first ? first.ts : null,
|
|
1132
|
+
startedAt: toIso(meta.startedMs),
|
|
1133
|
+
lastActiveAt: toIso(meta.lastActiveMs),
|
|
1134
|
+
};
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
function dispatchCacheGet(ref, now) {
|
|
1138
|
+
const hit = dispatchCache.get(ref);
|
|
1139
|
+
if (!hit) return null;
|
|
1140
|
+
if (now - hit.at > DISPATCH_CACHE_TTL_MS) {
|
|
1141
|
+
dispatchCache.delete(ref);
|
|
1142
|
+
return null;
|
|
1143
|
+
}
|
|
1144
|
+
return hit.item;
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
function dispatchCachePut(ref, item, now) {
|
|
1148
|
+
if (dispatchCache.size >= DISPATCH_CACHE_MAX) {
|
|
1149
|
+
const oldest = dispatchCache.keys().next().value;
|
|
1150
|
+
if (oldest !== undefined) dispatchCache.delete(oldest);
|
|
1151
|
+
}
|
|
1152
|
+
dispatchCache.set(ref, { at: now, item });
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
/**
|
|
1156
|
+
* 按绑定项目列派工词:首批三源各取最近 perSource 条有真人指令的会话(startedAt 倒序合并)。
|
|
1157
|
+
* project 为空直接空返回(未绑定项目的任务没有会话归属,零扫描零出网)。
|
|
1158
|
+
* 单源故障隔离:列表/转录失败该源跳过,不拖垮整体(与六源阅读器同纪律)。
|
|
1159
|
+
* 代价注记:每会话一次全文读入(≤4MB 闸),经 dispatchCache TTL 缓存兜底重复打开。
|
|
1160
|
+
* @param {{project:string, perSource?:number, agents?:string[], noCache?:boolean, now?:number, adapters?:object}} opts
|
|
1161
|
+
*/
|
|
1162
|
+
function listDispatchPrompts(config, opts) {
|
|
1163
|
+
const o = opts || {};
|
|
1164
|
+
const project = typeof o.project === 'string' ? o.project.trim() : '';
|
|
1165
|
+
const now = Number.isFinite(o.now) ? o.now : Date.now();
|
|
1166
|
+
const perSource = Math.min(Math.max(Number(o.perSource) || 2, 1), 3);
|
|
1167
|
+
const agents = Array.isArray(o.agents) && o.agents.length ? o.agents : DISPATCH_SOURCES;
|
|
1168
|
+
const items = [];
|
|
1169
|
+
if (!project) return { project, items };
|
|
1170
|
+
for (const agent of agents) {
|
|
1171
|
+
let page;
|
|
1172
|
+
try {
|
|
1173
|
+
page = listAgentSessions(config, { agent, limit: perSource * 4, project, now });
|
|
1174
|
+
} catch (e) {
|
|
1175
|
+
continue; // 单源隔离:未知源/源故障该源跳过
|
|
1176
|
+
}
|
|
1177
|
+
let got = 0;
|
|
1178
|
+
for (const it of page.items) {
|
|
1179
|
+
if (got >= perSource) break;
|
|
1180
|
+
const cached = o.noCache ? null : dispatchCacheGet(it.ref, now);
|
|
1181
|
+
if (cached) {
|
|
1182
|
+
items.push(cached);
|
|
1183
|
+
got += 1;
|
|
1184
|
+
continue;
|
|
1185
|
+
}
|
|
1186
|
+
let d;
|
|
1187
|
+
try {
|
|
1188
|
+
d = getDispatchPrompt(config, it.ref, { now, adapters: o.adapters });
|
|
1189
|
+
} catch (e) {
|
|
1190
|
+
continue; // 404(会话消失/已删)/源故障:跳过该会话
|
|
1191
|
+
}
|
|
1192
|
+
if (!d.found) continue; // 全注入无真人指令 → 不展示
|
|
1193
|
+
const item = { agent, ref: d.ref, startedAt: d.startedAt, lastActiveAt: it.lastActiveAt, text: d.text };
|
|
1194
|
+
if (!o.noCache) dispatchCachePut(d.ref, item, now);
|
|
1195
|
+
items.push(item);
|
|
1196
|
+
got += 1;
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
items.sort((a, b) => String(b.startedAt || '').localeCompare(String(a.startedAt || '')));
|
|
1200
|
+
return { project, items: items.slice(0, perSource * DISPATCH_SOURCES.length) };
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
// ---------- 聚合入口 ----------
|
|
1204
|
+
|
|
1205
|
+
const LIST_SOURCES = {
|
|
1206
|
+
zcode: listZcodeSessions,
|
|
1207
|
+
claude: listClaudeSessions,
|
|
1208
|
+
dsh: listDshSessions,
|
|
1209
|
+
codex: listCodexSessions,
|
|
1210
|
+
opencode: listOpencodeSessions,
|
|
1211
|
+
workbuddy: listWorkbuddySessions,
|
|
1212
|
+
hermes: listHermesSessions,
|
|
1213
|
+
};
|
|
1214
|
+
|
|
1215
|
+
/**
|
|
1216
|
+
* listAgentSessions(config, {agent, limit, cursor, now})
|
|
1217
|
+
* → {agent, items:[{ref,id,title,projectId,startedAt,lastActiveAt,state}], nextCursor}
|
|
1218
|
+
* 单源故障隔离:该源适配器异常 → 空页(不拖垮服务,§7-5 暴露面零新增语义内收敛)。
|
|
1219
|
+
*/
|
|
1220
|
+
/** v2.9.3 项目归一化键(与前端 actGroupKey 同口径):去尾分隔符 + 分隔符统一为 \ + 小写 */
|
|
1221
|
+
function normalizeProjectKey(p) {
|
|
1222
|
+
return String(p || '').trim().replace(/[\\/]+$/, '').toLowerCase().replace(/[\\/]+/g, '\\');
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
function listAgentSessions(config, opts) {
|
|
1226
|
+
const o = opts || {};
|
|
1227
|
+
const agent = typeof o.agent === 'string' ? o.agent.trim().toLowerCase() : '';
|
|
1228
|
+
if (!SOURCE_IDS.includes(agent)) throw new HttpError(400, 'BAD_AGENT', 'agent 必须为七源 id 之一');
|
|
1229
|
+
const sec = normalizeAgentActivity(isPlainObject(config) ? config.agentActivity : null);
|
|
1230
|
+
const limitDef = sec.sessionList;
|
|
1231
|
+
let limit = Number.isInteger(o.limit) && o.limit > 0 ? o.limit : limitDef.limit;
|
|
1232
|
+
if (limit > limitDef.maxLimit) limit = limitDef.maxLimit;
|
|
1233
|
+
const cursor = o.cursor ? decodeCursor(o.cursor) : null;
|
|
1234
|
+
const now = Number.isFinite(o.now) ? o.now : Date.now();
|
|
1235
|
+
|
|
1236
|
+
const src = sec.sources[agent] || {};
|
|
1237
|
+
let raws = [];
|
|
1238
|
+
if (sec.enabled !== false && src.enabled !== false) {
|
|
1239
|
+
try {
|
|
1240
|
+
raws = LIST_SOURCES[agent](src) || [];
|
|
1241
|
+
} catch (e) {
|
|
1242
|
+
if (e instanceof HttpError) throw e;
|
|
1243
|
+
console.error(`[agent-sessions] ${agent} 列表失败(单源隔离):`, (e && e.message) || e);
|
|
1244
|
+
raws = [];
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
// v2.9.3:项目过滤(智能体动态按项目分组钻取时,会话列表只出该项目)——
|
|
1249
|
+
// project 参数存在即过滤(含空串=「未知项目」组),缺省不过滤;必须先滤后分页,游标分页才不串组
|
|
1250
|
+
if (o.project !== undefined && o.project !== null) {
|
|
1251
|
+
const want = normalizeProjectKey(o.project);
|
|
1252
|
+
raws = raws.filter((r) => normalizeProjectKey(r.projectId) === want);
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
const { page, hasMore } = paginateRaws(raws, 'listId', limit, cursor);
|
|
1256
|
+
const items = page.map((r) => {
|
|
1257
|
+
const lastMs = Number(r.lastActiveMs) || 0;
|
|
1258
|
+
const ref = sessionRef.encodeRef(r.locator);
|
|
1259
|
+
return {
|
|
1260
|
+
ref,
|
|
1261
|
+
id: String(r.id || ''),
|
|
1262
|
+
title: normalizeTitle(r.title),
|
|
1263
|
+
projectId: typeof r.projectId === 'string' ? r.projectId : '',
|
|
1264
|
+
startedAt: toIso(r.startedMs) || toIso(lastMs) || toIso(now),
|
|
1265
|
+
lastActiveAt: toIso(lastMs) || toIso(now),
|
|
1266
|
+
state: r.state || stateFor(lastMs, now),
|
|
1267
|
+
};
|
|
1268
|
+
});
|
|
1269
|
+
const last = page[page.length - 1];
|
|
1270
|
+
return {
|
|
1271
|
+
agent,
|
|
1272
|
+
items,
|
|
1273
|
+
nextCursor: hasMore && last ? encodeCursor(Number(last.lastActiveMs) || 0, String(last.listId || '')) : null,
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
const TRANSCRIPT_SOURCES = {
|
|
1278
|
+
zcode: transcriptZcode,
|
|
1279
|
+
claude: transcriptClaude,
|
|
1280
|
+
dsh: transcriptDsh,
|
|
1281
|
+
codex: transcriptCodex,
|
|
1282
|
+
opencode: transcriptOpencode,
|
|
1283
|
+
workbuddy: transcriptWorkbuddy,
|
|
1284
|
+
hermes: transcriptHermes,
|
|
1285
|
+
};
|
|
1286
|
+
|
|
1287
|
+
/**
|
|
1288
|
+
* getAgentTranscript(config, ref, {now})
|
|
1289
|
+
* → §3.2 响应对象(正常/降级);ref 非法 400 BAD_REF、会话不存在 404 SESSION_NOT_FOUND。
|
|
1290
|
+
*/
|
|
1291
|
+
function getAgentTranscript(config, ref, opts) {
|
|
1292
|
+
const o = opts || {};
|
|
1293
|
+
const loc = sessionRef.validateRef(ref, config);
|
|
1294
|
+
const agent = loc.s;
|
|
1295
|
+
const sec = normalizeAgentActivity(isPlainObject(config) ? config.agentActivity : null);
|
|
1296
|
+
const now = Number.isFinite(o.now) ? o.now : Date.now();
|
|
1297
|
+
const limits = sec.transcript;
|
|
1298
|
+
const src = sec.sources[agent] || {};
|
|
1299
|
+
if (sec.enabled === false || src.enabled === false) {
|
|
1300
|
+
throw new HttpError(404, 'SESSION_NOT_FOUND', '会话不存在');
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
const collect = MessageCollector();
|
|
1304
|
+
let meta;
|
|
1305
|
+
try {
|
|
1306
|
+
meta = TRANSCRIPT_SOURCES[agent](src, loc, collect) || {};
|
|
1307
|
+
} catch (e) {
|
|
1308
|
+
if (e instanceof HttpError) throw e;
|
|
1309
|
+
throw new HttpError(500, 'INTERNAL', '服务器内部错误');
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
const base = {
|
|
1313
|
+
ref,
|
|
1314
|
+
agent,
|
|
1315
|
+
title: normalizeTitle(meta.title),
|
|
1316
|
+
projectId: typeof meta.projectId === 'string' ? meta.projectId : '',
|
|
1317
|
+
startedAt: toIso(meta.startedMs),
|
|
1318
|
+
lastActiveAt: toIso(meta.lastActiveMs) || toIso(now),
|
|
1319
|
+
};
|
|
1320
|
+
|
|
1321
|
+
if (meta.degraded) {
|
|
1322
|
+
return Object.assign(base, { degraded: true, reason: meta.reason || 'SOURCE_NO_TRANSCRIPT', messages: [] });
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
const total = collect.length;
|
|
1326
|
+
const truncatedByCount = total > limits.maxMessages;
|
|
1327
|
+
const capped = truncatedByCount ? collect.items.slice(0, limits.maxMessages) : collect.items;
|
|
1328
|
+
const messages = capped.map((m) => ({
|
|
1329
|
+
seq: m.seq,
|
|
1330
|
+
role: m.role,
|
|
1331
|
+
ts: m.ts,
|
|
1332
|
+
text: finalizeText(m.text, limits.maxCharsPerMessage),
|
|
1333
|
+
tool: m.tool,
|
|
1334
|
+
}));
|
|
1335
|
+
return Object.assign(base, {
|
|
1336
|
+
degraded: false,
|
|
1337
|
+
total,
|
|
1338
|
+
truncated: truncatedByCount || !!meta.readTruncated,
|
|
1339
|
+
messages,
|
|
1340
|
+
});
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
// ---------- 路由挂载 ----------
|
|
1344
|
+
|
|
1345
|
+
/** 两条新端点(§3):GET /api/agent-sessions、GET /api/agent-session */
|
|
1346
|
+
function registerAgentSessionRoutes(router, ctx) {
|
|
1347
|
+
router.add('GET', '/api/agent-sessions', (c) => {
|
|
1348
|
+
const limitRaw = c.query.get('limit');
|
|
1349
|
+
const limit = limitRaw === null || limitRaw === '' ? undefined : Number(limitRaw);
|
|
1350
|
+
const result = listAgentSessions(ctx.config, {
|
|
1351
|
+
agent: c.query.get('agent') || '',
|
|
1352
|
+
limit: Number.isInteger(limit) ? limit : undefined,
|
|
1353
|
+
cursor: c.query.get('cursor') || null,
|
|
1354
|
+
// v2.9.3:project 参数存在即过滤(含空串=未知项目组),缺省不过滤
|
|
1355
|
+
project: c.query.has('project') ? (c.query.get('project') || '') : undefined,
|
|
1356
|
+
});
|
|
1357
|
+
sendJSON(c.res, 200, result);
|
|
1358
|
+
});
|
|
1359
|
+
|
|
1360
|
+
router.add('GET', '/api/agent-session', (c) => {
|
|
1361
|
+
const ref = c.query.get('ref') || '';
|
|
1362
|
+
sendJSON(c.res, 200, getAgentTranscript(ctx.config, ref, {}));
|
|
1363
|
+
});
|
|
1364
|
+
|
|
1365
|
+
// v2.9.21 派工词:GET /api/agent-dispatch?project=<绑定项目>(project 缺省/空 → 空列表,不扫源)
|
|
1366
|
+
router.add('GET', '/api/agent-dispatch', (c) => {
|
|
1367
|
+
sendJSON(c.res, 200, listDispatchPrompts(ctx.config, { project: c.query.get('project') || '' }));
|
|
1368
|
+
});
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
// 供测试直通的适配器单测口
|
|
1372
|
+
module.exports = {
|
|
1373
|
+
SOURCE_IDS,
|
|
1374
|
+
listAgentSessions,
|
|
1375
|
+
normalizeProjectKey,
|
|
1376
|
+
getAgentTranscript,
|
|
1377
|
+
registerAgentSessionRoutes,
|
|
1378
|
+
// v2.9.21 派工词
|
|
1379
|
+
DISPATCH_SOURCES,
|
|
1380
|
+
dispatchTextOf,
|
|
1381
|
+
getDispatchPrompt,
|
|
1382
|
+
listDispatchPrompts,
|
|
1383
|
+
// 内部实现直通(测试用)
|
|
1384
|
+
listZcodeSessions,
|
|
1385
|
+
listClaudeSessions,
|
|
1386
|
+
listDshSessions,
|
|
1387
|
+
listCodexSessions,
|
|
1388
|
+
listOpencodeSessions,
|
|
1389
|
+
listWorkbuddySessions,
|
|
1390
|
+
transcriptZcode,
|
|
1391
|
+
transcriptClaude,
|
|
1392
|
+
transcriptDsh,
|
|
1393
|
+
transcriptCodex,
|
|
1394
|
+
transcriptOpencode,
|
|
1395
|
+
transcriptWorkbuddy,
|
|
1396
|
+
zstdDecompressFrames,
|
|
1397
|
+
finalizeText,
|
|
1398
|
+
};
|