zcode-pro 1.6.2 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +3 -2
- package/README.md +3 -2
- package/dist/inject.js +1428 -240
- package/package.json +2 -2
- package/src/host/helper.mjs +360 -37
- package/src/host/mcp-bridge.mjs +488 -0
- package/src/host/session-import/index.mjs +140 -0
- package/src/host/session-import/sources.mjs +839 -0
- package/src/host/session-import/util.mjs +239 -0
- package/src/host/session-import/write.mjs +405 -0
- package/src/host/session-import/zstd.mjs +68 -0
- package/src/host/taskIndex.mjs +374 -0
- package/src/inject/core.js +118 -13
- package/src/inject/features/idle-reclaim.js +48 -23
- package/src/inject/features/plugin-updates.js +58 -0
- package/src/inject/features/session-import.js +367 -0
- package/src/inject/features/session-link.js +3 -1
- package/src/inject/features/session-switch.js +10 -7
- package/src/inject/features/settings-dialog.js +92 -15
- package/src/inject/features/status-bar.js +88 -36
- package/src/inject/features/subagent-icon.js +472 -0
- package/src/inject/features/turn-usage.js +89 -32
- package/src/inject/features/ws-running.js +40 -10
- package/src/inject/index.js +2 -0
- package/src/inject/ui.js +10 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// dsh 的会话文件由多个 zstd frame 追加写而成。Node 自带的 zstdDecompress 只解
|
|
2
|
+
// 第一个 frame,这里按帧头切分后逐个解压,再按顺序拼起来。
|
|
3
|
+
import * as zlib from 'node:zlib';
|
|
4
|
+
|
|
5
|
+
const { zstdDecompressSync } = zlib;
|
|
6
|
+
|
|
7
|
+
const ZSTD_MAGIC = 0xfd2fb528;
|
|
8
|
+
const SKIPPABLE_MASK = 0xfffffff0;
|
|
9
|
+
const SKIPPABLE_MAGIC = 0x184d2a50;
|
|
10
|
+
|
|
11
|
+
function frameEnd(buf, off) {
|
|
12
|
+
if (off + 4 > buf.length) throw new Error('zstd 文件被截断');
|
|
13
|
+
let p = off;
|
|
14
|
+
const magic = buf.readUInt32LE(p);
|
|
15
|
+
p += 4;
|
|
16
|
+
if ((magic & SKIPPABLE_MASK) === SKIPPABLE_MAGIC) {
|
|
17
|
+
if (p + 4 > buf.length) throw new Error('zstd 跳过帧被截断');
|
|
18
|
+
const size = buf.readUInt32LE(p);
|
|
19
|
+
p += 4;
|
|
20
|
+
if (p + size > buf.length) throw new Error('zstd 跳过帧长度越界');
|
|
21
|
+
return p + size;
|
|
22
|
+
}
|
|
23
|
+
if (magic !== ZSTD_MAGIC) throw new Error('不是 zstd 文件');
|
|
24
|
+
|
|
25
|
+
if (p >= buf.length) throw new Error('zstd 帧头被截断');
|
|
26
|
+
const fhd = buf[p++];
|
|
27
|
+
const fcsFlag = fhd >> 6;
|
|
28
|
+
const singleSegment = (fhd >> 5) & 1;
|
|
29
|
+
const checksum = (fhd >> 2) & 1;
|
|
30
|
+
const dictFlag = fhd & 3;
|
|
31
|
+
if (!singleSegment) p += 1;
|
|
32
|
+
p += [0, 1, 2, 4][dictFlag];
|
|
33
|
+
p += fcsFlag === 0 ? (singleSegment ? 1 : 0) : [2, 4, 8][fcsFlag - 1];
|
|
34
|
+
if (p > buf.length) throw new Error('zstd 帧头长度越界');
|
|
35
|
+
|
|
36
|
+
for (;;) {
|
|
37
|
+
if (p + 3 > buf.length) throw new Error('zstd 块头被截断');
|
|
38
|
+
const head = buf[p] | (buf[p + 1] << 8) | (buf[p + 2] << 16);
|
|
39
|
+
p += 3;
|
|
40
|
+
const last = head & 1;
|
|
41
|
+
const type = (head >> 1) & 3;
|
|
42
|
+
const size = head >>> 3;
|
|
43
|
+
if (type === 3) throw new Error('zstd 块类型无效');
|
|
44
|
+
p += type === 1 ? 1 : size;
|
|
45
|
+
if (p > buf.length) throw new Error('zstd 块长度越界');
|
|
46
|
+
if (last) break;
|
|
47
|
+
}
|
|
48
|
+
if (checksum) p += 4;
|
|
49
|
+
if (p > buf.length) throw new Error('zstd 校验长度越界');
|
|
50
|
+
return p;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function zstdDecompressAll(buf) {
|
|
54
|
+
if (typeof zstdDecompressSync !== 'function') {
|
|
55
|
+
const err = new Error('当前 Node 不支持 zstd 解压(需要 22.15 及以上)');
|
|
56
|
+
err.code = 'zstd-unavailable';
|
|
57
|
+
throw err;
|
|
58
|
+
}
|
|
59
|
+
const chunks = [];
|
|
60
|
+
let off = 0;
|
|
61
|
+
while (off < buf.length) {
|
|
62
|
+
const end = frameEnd(buf, off);
|
|
63
|
+
if (end <= off) throw new Error('zstd 帧长度无效');
|
|
64
|
+
chunks.push(zstdDecompressSync(buf.subarray(off, end)));
|
|
65
|
+
off = end;
|
|
66
|
+
}
|
|
67
|
+
return Buffer.concat(chunks);
|
|
68
|
+
}
|
package/src/host/taskIndex.mjs
CHANGED
|
@@ -317,6 +317,380 @@ export async function listTaskStatuses(dataRoot, ids) {
|
|
|
317
317
|
}
|
|
318
318
|
}
|
|
319
319
|
|
|
320
|
+
// 批量查会话最近活动时间:id → time_updated(毫秒,查不到记 0)。子代理运行状态
|
|
321
|
+
// 的新鲜度校验用——应用的 running 记录崩溃/重启后不清理(实测残留数月的僵死记录),
|
|
322
|
+
// 子代理运行时消息不断写入会话库,长时间无动静的按僵死处理(subagent-icon.js)
|
|
323
|
+
export async function listSessionsActivity(dataRoot, ids) {
|
|
324
|
+
const out = {};
|
|
325
|
+
const wanted = [...new Set((ids || []).map(String).filter(Boolean))];
|
|
326
|
+
if (!wanted.length) return out;
|
|
327
|
+
const dbFile = join(dataRoot, 'cli', 'db', 'db.sqlite');
|
|
328
|
+
if (!existsSync(dbFile)) return out;
|
|
329
|
+
const driver = await loadDriver();
|
|
330
|
+
if (!driver) return out;
|
|
331
|
+
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
332
|
+
const inList = wanted.map((id) => esc(id)).join(', ');
|
|
333
|
+
try {
|
|
334
|
+
let rows;
|
|
335
|
+
if (driver.kind === 'node') {
|
|
336
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
337
|
+
try { rows = db.prepare(`SELECT id, time_updated FROM session WHERE id IN (${inList})`).all(); } finally { db.close(); }
|
|
338
|
+
} else {
|
|
339
|
+
const agg = runCli(dbFile,
|
|
340
|
+
`SELECT coalesce(json_group_array(json_object('id', id, 'time_updated', time_updated)), '[]') FROM session WHERE id IN (${inList});`);
|
|
341
|
+
rows = JSON.parse(agg.stdout.trim() || '[]');
|
|
342
|
+
}
|
|
343
|
+
for (const r of rows) out[String(r.id)] = Number(r.time_updated) || 0;
|
|
344
|
+
return out;
|
|
345
|
+
} catch {
|
|
346
|
+
return out; // 读取失败按无活动处理(调用方视为僵死,不亮图标)
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// 指定会话的子代理会话及最近活动时间(含嵌套子代理,根归属到最初的那个会话):
|
|
351
|
+
// [{ id, root, at }]。子代理判活以这里写入会话库的活动时间为准——应用的运行记录两头都
|
|
352
|
+
// 不可靠:长跑子代理会被误记为失败/结束(实测 48 分钟、60 分钟的都在跑着时被
|
|
353
|
+
// 记 end),崩溃残留的又永远挂"运行中"(subagent-icon.js)
|
|
354
|
+
export async function listSubagentChildrenActivity(dataRoot, ids) {
|
|
355
|
+
const out = [];
|
|
356
|
+
const wanted = [...new Set((ids || []).map(String).filter(Boolean))];
|
|
357
|
+
if (!wanted.length) return out;
|
|
358
|
+
const dbFile = join(dataRoot, 'cli', 'db', 'db.sqlite');
|
|
359
|
+
if (!existsSync(dbFile)) return out;
|
|
360
|
+
const driver = await loadDriver();
|
|
361
|
+
if (!driver) return out;
|
|
362
|
+
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
363
|
+
const inList = wanted.map((id) => esc(id)).join(', ');
|
|
364
|
+
const sql = `WITH RECURSIVE fam(id, root) AS (
|
|
365
|
+
SELECT id, parent_id FROM session WHERE parent_id IN (${inList})
|
|
366
|
+
UNION
|
|
367
|
+
SELECT s.id, f.root FROM session s JOIN fam f ON s.parent_id = f.id
|
|
368
|
+
) SELECT fam.root AS root, s.id AS id, s.time_updated AS at
|
|
369
|
+
FROM session s JOIN fam ON s.id = fam.id
|
|
370
|
+
WHERE s.task_type = 'subagent_child'`;
|
|
371
|
+
try {
|
|
372
|
+
let rows;
|
|
373
|
+
if (driver.kind === 'node') {
|
|
374
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
375
|
+
try { rows = db.prepare(sql).all(); } finally { db.close(); }
|
|
376
|
+
} else {
|
|
377
|
+
const agg = runCli(dbFile,
|
|
378
|
+
`SELECT coalesce(json_group_array(json_object('root', root, 'id', id, 'at', at)), '[]') FROM (${sql});`);
|
|
379
|
+
rows = JSON.parse(agg.stdout.trim() || '[]');
|
|
380
|
+
}
|
|
381
|
+
for (const r of rows) out.push({ id: String(r.id), root: String(r.root), at: Number(r.at) || 0 });
|
|
382
|
+
return out;
|
|
383
|
+
} catch {
|
|
384
|
+
return out;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// 状态栏统计用:会话 → trace_id。父子会话(含子代理)共享同一 trace,
|
|
389
|
+
// 状态栏据此把子代理的模型调用算进父会话的输出速率
|
|
390
|
+
export async function listSessionsTrace(dataRoot, ids) {
|
|
391
|
+
const out = {};
|
|
392
|
+
const wanted = [...new Set((ids || []).map(String).filter(Boolean))];
|
|
393
|
+
if (!wanted.length) return out;
|
|
394
|
+
const dbFile = join(dataRoot, 'cli', 'db', 'db.sqlite');
|
|
395
|
+
if (!existsSync(dbFile)) return out;
|
|
396
|
+
const driver = await loadDriver();
|
|
397
|
+
if (!driver) return out;
|
|
398
|
+
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
399
|
+
const inList = wanted.map((id) => esc(id)).join(', ');
|
|
400
|
+
try {
|
|
401
|
+
let rows;
|
|
402
|
+
if (driver.kind === 'node') {
|
|
403
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
404
|
+
try { rows = db.prepare(`SELECT id, trace_id FROM session WHERE id IN (${inList})`).all(); } finally { db.close(); }
|
|
405
|
+
} else {
|
|
406
|
+
const agg = runCli(dbFile,
|
|
407
|
+
`SELECT coalesce(json_group_array(json_object('id', id, 'trace_id', trace_id)), '[]') FROM session WHERE id IN (${inList});`);
|
|
408
|
+
rows = JSON.parse(agg.stdout.trim() || '[]');
|
|
409
|
+
}
|
|
410
|
+
for (const r of rows) out[String(r.id)] = String(r.trace_id || '');
|
|
411
|
+
return out;
|
|
412
|
+
} catch {
|
|
413
|
+
return out; // 读取失败按无 trace 处理(速率退化为只算本会话)
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// 官方口径的每轮用量(Token 调试同源数据与公式):主轮请求逐条返回 + 会话汇总。
|
|
418
|
+
// TPS = 输出 ÷(耗时 − 首 token 时机)= 官方“Output tokens ÷ 首个输出 token 到
|
|
419
|
+
// 请求结束的秒数”;命中率 = 缓存读 ÷ 输入(输入含缓存读,官方同语义)。
|
|
420
|
+
// query_source 只算 main_turn:起名等辅助小调用不进主轮统计(官方同款口径)。
|
|
421
|
+
// treeTrace 给出时 summary.tps 按会话树(本会话+同 trace 子代理)的最近请求算
|
|
422
|
+
// 60 秒窗净生成速率(窗口锚定最近一笔完成,锚不随请求时刻移动)
|
|
423
|
+
export async function listSessionModelUsage(dataRoot, sessionId, treeTrace = '') {
|
|
424
|
+
const empty = { rounds: [], summary: { requests: 0, totalIn: 0, totalOut: 0, totalCacheRead: 0, hitRate: null, tps: null } };
|
|
425
|
+
const sid = String(sessionId || '');
|
|
426
|
+
if (!sid) return empty;
|
|
427
|
+
const dbFile = join(dataRoot, 'cli', 'db', 'db.sqlite');
|
|
428
|
+
if (!existsSync(dbFile)) return empty;
|
|
429
|
+
const driver = await loadDriver();
|
|
430
|
+
if (!driver) return empty;
|
|
431
|
+
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
432
|
+
const sql = `SELECT completed_at, duration_ms, time_to_first_token_ms, input_tokens, output_tokens,`
|
|
433
|
+
+ ` reasoning_tokens, cache_read_input_tokens, cache_creation_input_tokens, computed_total_tokens`
|
|
434
|
+
+ ` FROM model_usage WHERE session_id = ${esc(sid)} AND query_source = 'main_turn'`
|
|
435
|
+
+ ` AND status = 'completed' AND completed_at IS NOT NULL ORDER BY completed_at ASC`;
|
|
436
|
+
try {
|
|
437
|
+
let rows;
|
|
438
|
+
if (driver.kind === 'node') {
|
|
439
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
440
|
+
try { rows = db.prepare(sql).all(); } finally { db.close(); }
|
|
441
|
+
} else {
|
|
442
|
+
const agg = runCli(dbFile,
|
|
443
|
+
`SELECT coalesce(json_group_array(json_object('completed_at', completed_at, 'duration_ms', duration_ms,`
|
|
444
|
+
+ ` 'time_to_first_token_ms', time_to_first_token_ms, 'input_tokens', input_tokens, 'output_tokens', output_tokens,`
|
|
445
|
+
+ ` 'reasoning_tokens', reasoning_tokens, 'cache_read_input_tokens', cache_read_input_tokens,`
|
|
446
|
+
+ ` 'cache_creation_input_tokens', cache_creation_input_tokens, 'computed_total_tokens', computed_total_tokens)), '[]')`
|
|
447
|
+
+ ` FROM (${sql});`);
|
|
448
|
+
rows = JSON.parse(agg.stdout.trim() || '[]');
|
|
449
|
+
}
|
|
450
|
+
const num = (v) => Number(v) || 0;
|
|
451
|
+
// 净生成时长 = 耗时 − 首 token 时机。两种情形按全程(耗时)算生成时长:
|
|
452
|
+
// 1. 非流式/整段返回:首 token 时机贴着结束(实测只差 20-30ms),扣出来是
|
|
453
|
+
// 毫秒级会把速率顶到几万 tok/s(首 token 占耗时 8 成以上即判定);
|
|
454
|
+
// 2. 首 token 时机缺失(部分供应商不回传,如 glm-5.3 占近三成):排除掉会
|
|
455
|
+
// 让整段速率消失。只有耗时也没有时留 null
|
|
456
|
+
const genMsOf = (dur, ttft) => (dur > 0 ? (ttft > 0 && ttft < dur * 0.8 ? dur - ttft : dur) : null);
|
|
457
|
+
const rounds = rows.map((r, i) => {
|
|
458
|
+
const inp = num(r.input_tokens);
|
|
459
|
+
const cacheRead = num(r.cache_read_input_tokens);
|
|
460
|
+
const ttft = num(r.time_to_first_token_ms);
|
|
461
|
+
const dur = num(r.duration_ms);
|
|
462
|
+
const genMs = genMsOf(dur, ttft);
|
|
463
|
+
const out = num(r.output_tokens);
|
|
464
|
+
return {
|
|
465
|
+
idx: i + 1,
|
|
466
|
+
at: num(r.completed_at),
|
|
467
|
+
in: inp,
|
|
468
|
+
out,
|
|
469
|
+
total: num(r.computed_total_tokens),
|
|
470
|
+
reasoning: num(r.reasoning_tokens),
|
|
471
|
+
cacheRead,
|
|
472
|
+
cacheWrite: num(r.cache_creation_input_tokens),
|
|
473
|
+
hitRate: inp > 0 ? cacheRead / inp : null,
|
|
474
|
+
genMs,
|
|
475
|
+
tps: genMs ? out / (genMs / 1000) : null,
|
|
476
|
+
};
|
|
477
|
+
});
|
|
478
|
+
const summary = { requests: rounds.length, totalIn: 0, totalOut: 0, totalCacheRead: 0, hitRate: null };
|
|
479
|
+
for (const r of rounds) {
|
|
480
|
+
summary.totalIn += r.in;
|
|
481
|
+
summary.totalOut += r.out;
|
|
482
|
+
summary.totalCacheRead += r.cacheRead;
|
|
483
|
+
}
|
|
484
|
+
summary.hitRate = summary.totalIn > 0 ? summary.totalCacheRead / summary.totalIn : null;
|
|
485
|
+
// 会话树最近请求的净生成速率:单独一条查询(trace 索引),取最近 30 笔里落在
|
|
486
|
+
// “最近完成时刻前 60 秒”的请求,Σ输出 ÷ Σ净生成秒数;没有可用行留 null
|
|
487
|
+
summary.tps = null;
|
|
488
|
+
try {
|
|
489
|
+
const tSql = `SELECT output_tokens, duration_ms, time_to_first_token_ms, completed_at FROM model_usage`
|
|
490
|
+
+ ` WHERE (session_id = ${esc(sid)}${treeTrace ? ` OR trace_id = ${esc(treeTrace)}` : ''})`
|
|
491
|
+
+ ` AND query_source = 'main_turn' AND status = 'completed' AND completed_at IS NOT NULL`
|
|
492
|
+
+ ` ORDER BY completed_at DESC LIMIT 30`;
|
|
493
|
+
let tRows;
|
|
494
|
+
if (driver.kind === 'node') {
|
|
495
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
496
|
+
try { tRows = db.prepare(tSql).all(); } finally { db.close(); }
|
|
497
|
+
} else {
|
|
498
|
+
const agg = runCli(dbFile,
|
|
499
|
+
`SELECT coalesce(json_group_array(json_object('output_tokens', output_tokens, 'duration_ms', duration_ms,`
|
|
500
|
+
+ ` 'time_to_first_token_ms', time_to_first_token_ms, 'completed_at', completed_at)), '[]') FROM (${tSql});`);
|
|
501
|
+
tRows = JSON.parse(agg.stdout.trim() || '[]');
|
|
502
|
+
}
|
|
503
|
+
if (tRows.length) {
|
|
504
|
+
const anchorT = num(tRows[0].completed_at);
|
|
505
|
+
let outSum = 0;
|
|
506
|
+
let genSum = 0;
|
|
507
|
+
for (const r of tRows) {
|
|
508
|
+
if (num(r.completed_at) < anchorT - 60_000) break;
|
|
509
|
+
const genMs = genMsOf(num(r.duration_ms), num(r.time_to_first_token_ms));
|
|
510
|
+
if (genMs) { outSum += num(r.output_tokens); genSum += genMs; }
|
|
511
|
+
}
|
|
512
|
+
if (genSum > 0) summary.tps = outSum / (genSum / 1000);
|
|
513
|
+
}
|
|
514
|
+
} catch { /* 速率取不到留 null,其它汇总不受影响 */ }
|
|
515
|
+
return { rounds, summary };
|
|
516
|
+
} catch {
|
|
517
|
+
return empty; // 读取失败按无数据处理(每轮标注与状态栏项自然隐藏)
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// 每轮官方汇总(turn_usage):一轮里的多个模型请求、工具循环、重试都算在同一轮,
|
|
522
|
+
// 比按 model_usage 行 + 可见回答行分桶稳定。返回 null = 当前 ZCode 版本没有这张表
|
|
523
|
+
// (调用方回退到按 model_usage 行分桶的旧算法)。
|
|
524
|
+
export async function listSessionTurnUsage(dataRoot, sessionId) {
|
|
525
|
+
const sid = String(sessionId || '');
|
|
526
|
+
if (!sid) return null;
|
|
527
|
+
const dbFile = join(dataRoot, 'cli', 'db', 'db.sqlite');
|
|
528
|
+
if (!existsSync(dbFile)) return null;
|
|
529
|
+
const driver = await loadDriver();
|
|
530
|
+
if (!driver) return null;
|
|
531
|
+
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
532
|
+
const tableSql = "SELECT name FROM sqlite_master WHERE type='table' AND name='turn_usage'";
|
|
533
|
+
const turnSql = `SELECT turn_id, started_at, completed_at, duration_ms, time_to_first_token_ms,`
|
|
534
|
+
+ ` input_tokens, output_tokens, reasoning_tokens, cache_read_input_tokens, cache_creation_input_tokens, computed_total_tokens`
|
|
535
|
+
+ ` FROM turn_usage WHERE session_id = ${esc(sid)} AND status = 'completed' AND completed_at IS NOT NULL`
|
|
536
|
+
+ ` AND (coalesce(input_tokens, 0) + coalesce(output_tokens, 0)) > 0 ORDER BY started_at ASC`;
|
|
537
|
+
const useSql = `SELECT completed_at, duration_ms, time_to_first_token_ms, input_tokens, output_tokens, cache_read_input_tokens`
|
|
538
|
+
+ ` FROM model_usage WHERE session_id = ${esc(sid)} AND query_source = 'main_turn'`
|
|
539
|
+
+ ` AND status = 'completed' AND completed_at IS NOT NULL ORDER BY completed_at ASC`;
|
|
540
|
+
try {
|
|
541
|
+
let turns;
|
|
542
|
+
let usages;
|
|
543
|
+
if (driver.kind === 'node') {
|
|
544
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
545
|
+
try {
|
|
546
|
+
if (!db.prepare(tableSql).all().length) return null;
|
|
547
|
+
turns = db.prepare(turnSql).all();
|
|
548
|
+
usages = db.prepare(useSql).all();
|
|
549
|
+
} finally { db.close(); }
|
|
550
|
+
} else {
|
|
551
|
+
if (!runCli(dbFile, tableSql + ';').stdout.trim()) return null;
|
|
552
|
+
turns = JSON.parse(runCli(dbFile,
|
|
553
|
+
`SELECT coalesce(json_group_array(json_object('turn_id', turn_id, 'started_at', started_at,`
|
|
554
|
+
+ ` 'completed_at', completed_at, 'duration_ms', duration_ms, 'time_to_first_token_ms', time_to_first_token_ms,`
|
|
555
|
+
+ ` 'input_tokens', input_tokens, 'output_tokens', output_tokens, 'reasoning_tokens', reasoning_tokens,`
|
|
556
|
+
+ ` 'cache_read_input_tokens', cache_read_input_tokens, 'cache_creation_input_tokens', cache_creation_input_tokens,`
|
|
557
|
+
+ ` 'computed_total_tokens', computed_total_tokens)), '[]') FROM (${turnSql});`).stdout.trim() || '[]');
|
|
558
|
+
usages = JSON.parse(runCli(dbFile,
|
|
559
|
+
`SELECT coalesce(json_group_array(json_object('completed_at', completed_at, 'duration_ms', duration_ms,`
|
|
560
|
+
+ ` 'time_to_first_token_ms', time_to_first_token_ms, 'input_tokens', input_tokens, 'output_tokens', output_tokens,`
|
|
561
|
+
+ ` 'cache_read_input_tokens', cache_read_input_tokens)), '[]') FROM (${useSql});`
|
|
562
|
+
).stdout.trim() || '[]');
|
|
563
|
+
}
|
|
564
|
+
if (!turns.length) return null;
|
|
565
|
+
const num = (v) => Number(v) || 0;
|
|
566
|
+
const genMsOf = (dur, ttft) => (dur > 0 ? (ttft > 0 && ttft < dur * 0.8 ? dur - ttft : dur) : null);
|
|
567
|
+
const rounds = turns.map((t, i) => {
|
|
568
|
+
const inp = num(t.input_tokens);
|
|
569
|
+
const cacheRead = num(t.cache_read_input_tokens);
|
|
570
|
+
return {
|
|
571
|
+
idx: i + 1,
|
|
572
|
+
startAt: num(t.started_at) || num(t.completed_at),
|
|
573
|
+
at: num(t.completed_at),
|
|
574
|
+
in: inp,
|
|
575
|
+
out: num(t.output_tokens),
|
|
576
|
+
total: num(t.computed_total_tokens),
|
|
577
|
+
reasoning: num(t.reasoning_tokens),
|
|
578
|
+
cacheRead,
|
|
579
|
+
cacheWrite: num(t.cache_creation_input_tokens),
|
|
580
|
+
hitRate: inp > 0 ? cacheRead / inp : null,
|
|
581
|
+
genMs: 0,
|
|
582
|
+
tps: null,
|
|
583
|
+
};
|
|
584
|
+
});
|
|
585
|
+
// 一轮的生成时长按落在该轮起止时间内的 model_usage 行累加:包含工具循环的
|
|
586
|
+
// 轮次也能算净生成速率,且与旧算法同一公式。
|
|
587
|
+
let ti = 0;
|
|
588
|
+
for (const u of usages) {
|
|
589
|
+
const at = num(u.completed_at);
|
|
590
|
+
while (ti < rounds.length && at > rounds[ti].at) ti += 1;
|
|
591
|
+
const turn = rounds[ti];
|
|
592
|
+
if (!turn || at < turn.startAt || at > turn.at) continue;
|
|
593
|
+
const genMs = genMsOf(num(u.duration_ms), num(u.time_to_first_token_ms));
|
|
594
|
+
if (genMs) turn.genMs += genMs;
|
|
595
|
+
}
|
|
596
|
+
for (const turn of rounds) {
|
|
597
|
+
turn.tps = turn.genMs > 0 ? turn.out / (turn.genMs / 1000) : null;
|
|
598
|
+
}
|
|
599
|
+
const summary = { requests: rounds.length, totalIn: 0, totalOut: 0, totalCacheRead: 0, hitRate: null, tps: null };
|
|
600
|
+
for (const r of rounds) {
|
|
601
|
+
summary.totalIn += r.in;
|
|
602
|
+
summary.totalOut += r.out;
|
|
603
|
+
summary.totalCacheRead += r.cacheRead;
|
|
604
|
+
}
|
|
605
|
+
summary.hitRate = summary.totalIn > 0 ? summary.totalCacheRead / summary.totalIn : null;
|
|
606
|
+
// 进行中的轮次还没有 turn_usage 行:把最后一条已完成轮次之后的 model_usage
|
|
607
|
+
// 行作为 live 返回,注入层挂到最新一条可见回答上,长回合也能实时看到用量。
|
|
608
|
+
const lastAt = rounds.length ? rounds[rounds.length - 1].at : 0;
|
|
609
|
+
const live = [];
|
|
610
|
+
for (const u of usages) {
|
|
611
|
+
const at = num(u.completed_at);
|
|
612
|
+
if (at <= lastAt) continue;
|
|
613
|
+
const genMs = genMsOf(num(u.duration_ms), num(u.time_to_first_token_ms));
|
|
614
|
+
live.push({
|
|
615
|
+
at,
|
|
616
|
+
in: num(u.input_tokens),
|
|
617
|
+
out: num(u.output_tokens),
|
|
618
|
+
cacheRead: num(u.cache_read_input_tokens),
|
|
619
|
+
genMs: genMs || 0,
|
|
620
|
+
tpsOut: genMs ? num(u.output_tokens) : 0,
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
return { rounds, summary, turnMode: true, live };
|
|
624
|
+
} catch {
|
|
625
|
+
return null;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// 项目里"真未读"的任务数(未读但排除错误态):项目行蓝色未读徽标的判据——
|
|
630
|
+
// 错误态任务行显示的是红色错误点(应用图标优先级 错误>未读),它的未读不该再
|
|
631
|
+
// 把项目徽标点亮成蓝色(subagent-icon.js)
|
|
632
|
+
export async function listProjectsUnread(dataRoot, projectIds) {
|
|
633
|
+
const out = {};
|
|
634
|
+
const wanted = [...new Set((projectIds || []).map(String).filter(Boolean))];
|
|
635
|
+
if (!wanted.length) return out;
|
|
636
|
+
const dbFile = taskIndexPath(dataRoot);
|
|
637
|
+
if (!existsSync(dbFile)) return out;
|
|
638
|
+
const driver = await loadDriver();
|
|
639
|
+
if (!driver) return out;
|
|
640
|
+
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
641
|
+
const inList = wanted.map((id) => esc(id)).join(', ');
|
|
642
|
+
const sql = `SELECT project_id, sum(CASE WHEN task_status = 'error' THEN 0 ELSE 1 END) AS n
|
|
643
|
+
FROM tasks WHERE project_id IN (${inList}) AND unread_at IS NOT NULL
|
|
644
|
+
AND deleted = 0 AND coalesce(cli_deleted, 0) = 0
|
|
645
|
+
GROUP BY project_id`;
|
|
646
|
+
try {
|
|
647
|
+
let rows;
|
|
648
|
+
if (driver.kind === 'node') {
|
|
649
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
650
|
+
try { rows = db.prepare(sql).all(); } finally { db.close(); }
|
|
651
|
+
} else {
|
|
652
|
+
const agg = runCli(dbFile,
|
|
653
|
+
`SELECT coalesce(json_group_array(json_object('project_id', project_id, 'n', n)), '[]') FROM (${sql});`);
|
|
654
|
+
rows = JSON.parse(agg.stdout.trim() || '[]');
|
|
655
|
+
}
|
|
656
|
+
for (const r of rows) out[String(r.project_id)] = Number(r.n) || 0;
|
|
657
|
+
return out;
|
|
658
|
+
} catch {
|
|
659
|
+
return null; // 读取失败返回 null,调用方不干预徽标
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// 某工作区的任务会话 id(最近更新在前,7 天内有动静的取 30 个):折叠项目行扫
|
|
664
|
+
// 子代理运行状态的候选清单——行折叠后会话 id 不在 DOM 里,只能从任务索引反查。
|
|
665
|
+
// 7 天窗:长跑子代理的父会话最晚在派出子代理那一趟被写过,超过 7 天的会话里
|
|
666
|
+
// 还挂着子代理的实测都是僵死记录(shortcut: 超长后台子代理会漏,等用户反馈再放宽)
|
|
667
|
+
export async function listWorkspaceTaskIds(dataRoot, wsPath) {
|
|
668
|
+
const dbFile = taskIndexPath(dataRoot);
|
|
669
|
+
if (!existsSync(dbFile)) return [];
|
|
670
|
+
const driver = await loadDriver();
|
|
671
|
+
if (!driver) return [];
|
|
672
|
+
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
673
|
+
// 任务行的工作区路径可能带尾分隔符(实测两种都有),两侧都归一后比较
|
|
674
|
+
const target = esc(String(wsPath || '').replace(/[\\/]+$/, ''));
|
|
675
|
+
const where = `rtrim(rtrim(workspace_path, '/'), char(92)) = ${target}`;
|
|
676
|
+
const since = Date.now() - 7 * 86400_000;
|
|
677
|
+
const sql = `SELECT task_id FROM tasks WHERE ${where} AND deleted = 0 AND updated_at >= ${since} ORDER BY updated_at DESC LIMIT 30`;
|
|
678
|
+
try {
|
|
679
|
+
let rows;
|
|
680
|
+
if (driver.kind === 'node') {
|
|
681
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
682
|
+
try { rows = db.prepare(sql).all(); } finally { db.close(); }
|
|
683
|
+
} else {
|
|
684
|
+
const agg = runCli(dbFile,
|
|
685
|
+
`SELECT coalesce(json_group_array(json_object('task_id', task_id)), '[]') FROM (${sql});`);
|
|
686
|
+
rows = JSON.parse(agg.stdout.trim() || '[]');
|
|
687
|
+
}
|
|
688
|
+
return rows.map((r) => String(r.task_id)).filter(Boolean);
|
|
689
|
+
} catch {
|
|
690
|
+
return [];
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
320
694
|
// 状态栏统计用:任务总数(未删除的会话行)
|
|
321
695
|
export async function countTasks(dataRoot) {
|
|
322
696
|
const dbFile = taskIndexPath(dataRoot);
|