dsh-mobile-plugin 0.5.35 → 0.5.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/impl.js +0 -7
- package/lib/mobile/answer-sources.js +223 -0
- package/lib/mobile/approval-memory.js +1 -1
- package/lib/mobile/events.js +0 -20
- package/lib/mobile/extension-data.js +105 -5
- package/lib/mobile/extension-dev.js +42 -0
- package/lib/mobile/history-derive.js +54 -1
- package/lib/mobile/model-meta-table.cjs +1 -1
- package/lib/mobile/model-meta.js +1 -1
- package/lib/mobile/monitor.js +8 -2
- package/lib/mobile/notification-prefs.js +2 -2
- package/lib/mobile/permissions.js +8 -5
- package/lib/mobile/plugin-market.js +103 -4
- package/lib/mobile/run-timeline.js +317 -0
- package/lib/mobile/session-active.js +66 -0
- package/lib/mobile/session-stop-summary.js +122 -0
- package/lib/mobile/sessions.js +8 -2
- package/lib/mobile/stats-ledger.cjs +45 -37
- package/lib/mobile/stop-summary.js +292 -0
- package/lib/mobile/third-party-extensions.js +86 -0
- package/lib/mobile/tool-result-cache.js +30 -2
- package/lib/panel/index.html +15 -15
- package/lib/relay/lan-proxy.js +20 -11
- package/lib/relay/tunnel.js +28 -12
- package/lib/routes/mobile-api.js +25 -19
- package/lib/shared/derived-cache.js +121 -0
- package/lib/shared/http-util.js +55 -18
- package/package.json +1 -2
- package/config/agent-presets/supervisor/agent.cordis.yml +0 -237
- package/config/agent-presets/supervisor/preset.yml +0 -3
- package/lib/mobile/auto-review-log.js +0 -160
- package/lib/mobile/knowledge-base.js +0 -481
- package/lib/mobile/mail.js +0 -621
- package/lib/mobile/model-prices-table.cjs +0 -23
- package/lib/mobile/model-prices.cjs +0 -88
- package/lib/mobile/supervisor-broadcast.js +0 -503
- package/lib/mobile/supervisor-memory/index.js +0 -305
- package/lib/mobile/supervisor-runtime/index.js +0 -54
- package/lib/mobile/supervisor-runtime/inject.js +0 -218
- package/lib/mobile/supervisor-runtime/judgment.js +0 -113
- package/lib/mobile/supervisor-tools.js +0 -419
- package/lib/mobile/task-ledger.js +0 -381
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 停止交代的出口:`GET /api/mobile/v1/session/stop-summary?sessionId=…[&turn=N]`。
|
|
5
|
+
*
|
|
6
|
+
* 用户点了停止之后,手机上那一轮不该只剩「已停止」三个字。这条路由把**这一轮跑过的步骤**
|
|
7
|
+
* 折成一句句看得懂的话(做了什么 / 看到了什么 / 没做完什么 / 对外发出几次),交给 App 的
|
|
8
|
+
* `StopSummaryCard` 画在被停止的那一轮末尾。
|
|
9
|
+
*
|
|
10
|
+
* 两个数据源,先内存后历史:还在跑(或刚停下)的那一轮在宿主的直播副本里
|
|
11
|
+
*(`live-steps.js`),历史里还没有;已经落定的轮按 `turnProcess.steps` 从会话历史折出来。
|
|
12
|
+
* 两处都是 `{ key, step }`,折叠逻辑只有一份(`stop-summary.js`,纯函数)。
|
|
13
|
+
*
|
|
14
|
+
* **按轮次答**(`?turn=N`,重新打开一条老会话时 App 补那一发用):
|
|
15
|
+
* - 不带 `turn`:最近一轮,先直播副本后历史(向后兼容,刚按停止那一刻走的就是这条);
|
|
16
|
+
* - 带 `turn`:只要那一轮。直播副本只有在它自己就是那一轮时才算数,否则一律回历史;
|
|
17
|
+
* - 那一轮在窗口里找不到:回**空交代**(不是报错),App 那边不出卡。
|
|
18
|
+
*
|
|
19
|
+
* 判据(为什么不能按消息上的 turn 号找那一轮):历史派生的普通消息(user / assistant / wake)
|
|
20
|
+
* **不带 turn 号** —— `history-derive.js` 的 `pushMessage` 收到 `data.turn` 后只拿它归并
|
|
21
|
+
* 产出清单与交付声明,从没写回 `item.turn`;全篇只有压缩行带 `item.turn`(`:754/:764/:786`),
|
|
22
|
+
* `:335` 那个 `turn` 在重试行上、`:660` 在读压缩行的轮号,都不是开轮消息。而
|
|
23
|
+
* `turnProcess.steps` 恰恰挂在**开轮那条消息**上(`openerByTurn`,`:923-932`)。
|
|
24
|
+
* 所以改用两个确实存在的锚点定位:这一轮收口那条结构行的 id 是 `turn-<轮号>`(`:916` 的
|
|
25
|
+
* `turn-aborted`,`turn-error` / `max-tokens` 同形)、带这一轮的收口 `seq`;开轮消息的
|
|
26
|
+
* `turnProcess.startSeq` 就是它自己的 `seq`(`:930`)。取「`startSeq` 最大、且小于那条
|
|
27
|
+
* 收口行的 `seq`」的 `turnProcess`,就是这一轮的过程。
|
|
28
|
+
*
|
|
29
|
+
* 只读、只算展示结构:不碰 shell、不读任意文件,也没有写操作。取不到就回空交代,让 App
|
|
30
|
+
* 不出那张卡,不报错。
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
const { sendJson } = require('../shared/http-util');
|
|
34
|
+
const { unwrap } = require('./envelope.js');
|
|
35
|
+
const { callSessions } = require('./rpc.js');
|
|
36
|
+
const { liveStepsOf, liveStepsTurnOf } = require('./live-steps.js');
|
|
37
|
+
const { deriveMessages } = require('./history-derive.js');
|
|
38
|
+
const { summarize } = require('./stop-summary.js');
|
|
39
|
+
|
|
40
|
+
/** 回落到历史时取多少条事件:够覆盖最近一轮的步骤与开场消息即可。 */
|
|
41
|
+
const HISTORY_WINDOW = 200;
|
|
42
|
+
|
|
43
|
+
/** 历史里最近一轮的过程清单(`turnProcess.steps` 挂在开轮那条消息上)。 */
|
|
44
|
+
function lastTurnSteps(messages) {
|
|
45
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
46
|
+
const item = messages[index];
|
|
47
|
+
const steps = item && item.turnProcess && Array.isArray(item.turnProcess.steps)
|
|
48
|
+
? item.turnProcess.steps
|
|
49
|
+
: null;
|
|
50
|
+
if (steps && steps.length > 0) return steps;
|
|
51
|
+
}
|
|
52
|
+
return [];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* 历史里**指定那一轮**的过程清单(判据见文件头)。
|
|
57
|
+
*
|
|
58
|
+
* 锚点是这一轮收口那条结构行(`turn-aborted` / `turn-error` / `max-tokens`,id 都是
|
|
59
|
+
* `turn-<轮号>`,带这一轮收口的 `seq`):它不在窗口里就说明这一轮已经翻出去了,回空。
|
|
60
|
+
* 有了它的 `seq`,再挑 `startSeq` 最大且更早的那份 `turnProcess` —— 那就是开启这一轮的消息。
|
|
61
|
+
*/
|
|
62
|
+
function turnSteps(messages, turn) {
|
|
63
|
+
const endId = `turn-${turn}`;
|
|
64
|
+
let endSeq = null;
|
|
65
|
+
for (const item of messages) {
|
|
66
|
+
if (!item || item.id !== endId) continue;
|
|
67
|
+
if (typeof item.seq !== 'number') continue;
|
|
68
|
+
endSeq = item.seq;
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
if (endSeq === null) return [];
|
|
72
|
+
let best = null;
|
|
73
|
+
for (const item of messages) {
|
|
74
|
+
const process = item && item.turnProcess;
|
|
75
|
+
if (!process || !Array.isArray(process.steps) || process.steps.length === 0) continue;
|
|
76
|
+
const startSeq = typeof process.startSeq === 'number' ? process.startSeq : item.seq;
|
|
77
|
+
if (typeof startSeq !== 'number' || startSeq >= endSeq) continue;
|
|
78
|
+
if (best === null || startSeq > best.startSeq) best = { startSeq, steps: process.steps };
|
|
79
|
+
}
|
|
80
|
+
return best === null ? [] : best.steps;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** 非负整数查询参数(与 `/session/step`、`/session/run-timeline` 同一套口径)。 */
|
|
84
|
+
function intParam(url, name) {
|
|
85
|
+
const raw = url.searchParams.get(name);
|
|
86
|
+
if (raw === null || raw === '') return null;
|
|
87
|
+
if (!/^\d+$/.test(raw)) return null;
|
|
88
|
+
const value = Number(raw);
|
|
89
|
+
return Number.isSafeInteger(value) ? value : null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** GET /api/mobile/v1/session/stop-summary?sessionId=…[&turn=N](token) */
|
|
93
|
+
async function handleStopSummary(ctx, req, res) {
|
|
94
|
+
const url = new URL(req.url, 'http://x');
|
|
95
|
+
const sessionId = url.searchParams.get('sessionId');
|
|
96
|
+
if (!sessionId) {
|
|
97
|
+
return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '缺少 sessionId' } });
|
|
98
|
+
}
|
|
99
|
+
const turn = intParam(url, 'turn');
|
|
100
|
+
const live = liveStepsOf(ctx, sessionId);
|
|
101
|
+
if (live.length > 0) {
|
|
102
|
+
// 直播副本只代表**当前这一轮**:点名了别的轮就老老实实走历史。
|
|
103
|
+
const liveTurn = liveStepsTurnOf(ctx, sessionId);
|
|
104
|
+
if (turn === null || liveTurn === null || liveTurn === turn) {
|
|
105
|
+
return sendJson(res, 200, { ok: true, summary: summarize(live), source: 'live' });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
let steps = [];
|
|
109
|
+
try {
|
|
110
|
+
const { value, error } = unwrap(await callSessions(ctx, 'history', { sessionId, maxMessages: HISTORY_WINDOW }));
|
|
111
|
+
if (!error) {
|
|
112
|
+
const events = (value && Array.isArray(value.events)) ? value.events : [];
|
|
113
|
+
const messages = deriveMessages(events, sessionId);
|
|
114
|
+
steps = turn === null ? lastTurnSteps(messages) : turnSteps(messages, turn);
|
|
115
|
+
}
|
|
116
|
+
} catch {
|
|
117
|
+
// 读不到历史就当没有可交代的东西:卡不出,不把它变成一次报错。
|
|
118
|
+
}
|
|
119
|
+
return sendJson(res, 200, { ok: true, summary: summarize(steps), source: 'history' });
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
module.exports = { handleStopSummary, HISTORY_WINDOW, lastTurnSteps, turnSteps };
|
package/lib/mobile/sessions.js
CHANGED
|
@@ -51,6 +51,7 @@ const { handleSessionHead } = require('./session-head.js');
|
|
|
51
51
|
const { handleNew } = require('./session-new.js');
|
|
52
52
|
// 隔离工作树的自动回收:会话归档 / 被删 / 从宿主清单消失时把树收掉(见该文件头)。
|
|
53
53
|
const { sweepIsolationWorktrees } = require('./worktree-lifecycle.js');
|
|
54
|
+
const { withActiveParents } = require('./session-active.js');
|
|
54
55
|
|
|
55
56
|
const SESSIONS_PREVIEW_LIMIT = 20; // 仅为最近/运行中的会话补最后消息预览
|
|
56
57
|
const SESSION_LIST_CACHE_MS = 10000; // 会话列表增料缓存(降低手机轮询对桌面的冲击)
|
|
@@ -155,8 +156,8 @@ async function buildSessionsResponse(ctx, deviceKey = 'legacy', generation = com
|
|
|
155
156
|
// 都会把它当权威数据,把好的会话清单整个覆盖掉。
|
|
156
157
|
// 用 500 而不是 400:中转对 >=500 的小响应会退回上一份好副本(stale:true),
|
|
157
158
|
// 手机上因此表现为「短暂用旧列表」而不是「列表清空」。
|
|
158
|
-
const
|
|
159
|
-
if (
|
|
159
|
+
const rawSummaries = Array.isArray(value) ? value : (value && Array.isArray(value.items) ? value.items : null);
|
|
160
|
+
if (rawSummaries === null) {
|
|
160
161
|
return {
|
|
161
162
|
status: 500,
|
|
162
163
|
body: {
|
|
@@ -165,6 +166,11 @@ async function buildSessionsResponse(ctx, deviceKey = 'legacy', generation = com
|
|
|
165
166
|
},
|
|
166
167
|
};
|
|
167
168
|
}
|
|
169
|
+
// 宿主只按主轮报 running:主对话的 turn/end 一落、子代理还在跑的那一段,它给的是
|
|
170
|
+
// false。手机上那一行于是显示成「已完成待读」,后台还会为它响一声 —— 见
|
|
171
|
+
// session-active.js。这里是所有下发给手机的列表(侧栏、镜像快照、条件刷新)的唯一入口,
|
|
172
|
+
// 所以顶起来这件事只在这一处做。
|
|
173
|
+
const summaries = withActiveParents(rawSummaries);
|
|
168
174
|
// 归档会话在这里剔除,与桌面端侧边栏行为一致:宿主 sessions.list 自己不过滤归档,
|
|
169
175
|
// 「哪些会话已归档」只存在于 workspaceRegistry.archivedSessionIds(见 workspaceSessionFlags)。
|
|
170
176
|
// 清理时已删日志的 ID 也要压住:宿主 list 或 workspace.list 的短暂旧快照不能让它们复活。
|
|
@@ -21,7 +21,6 @@ const path = require('node:path');
|
|
|
21
21
|
|
|
22
22
|
const paths = require('../shared/paths');
|
|
23
23
|
const { identifyVendor, vendorLogoOf } = require('./model-vendors.js');
|
|
24
|
-
const { AS_OF, costOfUsage, priceOf } = require('./model-prices.cjs');
|
|
25
24
|
|
|
26
25
|
/** 账本格式版本:将来改结构时据此决定是丢弃还是迁移。 */
|
|
27
26
|
const VERSION = 1;
|
|
@@ -150,6 +149,21 @@ function stateFile() {
|
|
|
150
149
|
/** 内存缓存;null = 还没读过盘。 */
|
|
151
150
|
let cached = null;
|
|
152
151
|
|
|
152
|
+
/**
|
|
153
|
+
* 账本内容的版本号:**每一处改账本的地方都抬它**(`saveLedger` 与下面三个写函数)。
|
|
154
|
+
*
|
|
155
|
+
* `summarize` 把它和范围、当天日期一起当缓存键(见 `summarize` 的注释):账本一动,版本
|
|
156
|
+
* 就变,上那份 projections 自然失效。用自增序号而不是内容哈希:账本能到四千条记录、三年
|
|
157
|
+
* 按天账,整份哈希每次都比 `summarize` 本身还贵(2026-11-10 实测:4000 条 × 62 天,
|
|
158
|
+
* 折一次 13ms,整份 sha1 要 20ms),而这里要回答的只是「还是不是同一本账」。
|
|
159
|
+
*/
|
|
160
|
+
let ledgerVersion = 0;
|
|
161
|
+
|
|
162
|
+
/** 记一次改动(三张表任何一处动了都要抬,见上面那段)。 */
|
|
163
|
+
function markLedgerChanged() {
|
|
164
|
+
ledgerVersion += 1;
|
|
165
|
+
}
|
|
166
|
+
|
|
153
167
|
function num(value) {
|
|
154
168
|
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
|
|
155
169
|
}
|
|
@@ -367,6 +381,7 @@ function readLedger() {
|
|
|
367
381
|
/** 原子写:先写临时文件再 rename,写一半断电也不会留下半份 JSON。 */
|
|
368
382
|
function saveLedger(ledger) {
|
|
369
383
|
cached = ledger;
|
|
384
|
+
markLedgerChanged();
|
|
370
385
|
ledger.updatedAt = Date.now();
|
|
371
386
|
const file = stateFile();
|
|
372
387
|
try {
|
|
@@ -382,6 +397,7 @@ function saveLedger(ledger) {
|
|
|
382
397
|
/** 测试与「换个 DSH_HOME 重读」用。 */
|
|
383
398
|
function forgetLedger() {
|
|
384
399
|
cached = null;
|
|
400
|
+
markLedgerChanged();
|
|
385
401
|
}
|
|
386
402
|
|
|
387
403
|
/**
|
|
@@ -398,6 +414,7 @@ function forgetLedger() {
|
|
|
398
414
|
* 被当成首采、把整段历史重记一遍 —— 所以档位要抬到几年也用不完,别拿它当展示上限。
|
|
399
415
|
*/
|
|
400
416
|
function trim(ledger) {
|
|
417
|
+
markLedgerChanged();
|
|
401
418
|
const staleBefore = addDays(dayKeyOf(Date.now()), -MAX_DAILY_DAYS);
|
|
402
419
|
for (const record of Object.values(ledger.sessions)) {
|
|
403
420
|
if (record.daily) {
|
|
@@ -513,6 +530,7 @@ function emptySession(at) {
|
|
|
513
530
|
* `daily` —— 凭一个「最后活动日」给它编一天,模型卡在窄范围里就会比整页 KPI 还大。
|
|
514
531
|
*/
|
|
515
532
|
function applyModelUsage(ledger, entry) {
|
|
533
|
+
markLedgerChanged();
|
|
516
534
|
const selection = sanitizeModelSelection(entry && entry.model);
|
|
517
535
|
if (!selection) return ledger;
|
|
518
536
|
const key = modelKeyOf(selection.provider, selection.model);
|
|
@@ -551,6 +569,7 @@ function applyModelUsage(ledger, entry) {
|
|
|
551
569
|
* 时就只补累计:那一档范围里卡片同样是空的,两边一致。
|
|
552
570
|
*/
|
|
553
571
|
function applyModelBackfill(ledger, entry) {
|
|
572
|
+
markLedgerChanged();
|
|
554
573
|
const selection = sanitizeModelSelection(entry && entry.model);
|
|
555
574
|
if (!selection) return ledger;
|
|
556
575
|
const key = modelKeyOf(selection.provider, selection.model);
|
|
@@ -587,6 +606,7 @@ function applyModelBackfill(ledger, entry) {
|
|
|
587
606
|
* 增量也记进模型桶(无日期那笔同样按无日期记,见 `applyModelUsage`)。
|
|
588
607
|
*/
|
|
589
608
|
function applyDelta(ledger, entry) {
|
|
609
|
+
markLedgerChanged();
|
|
590
610
|
const sessionId = entry.sessionId;
|
|
591
611
|
const delta = sanitizeUsage(entry.delta);
|
|
592
612
|
const at = num(entry.at) || Date.now();
|
|
@@ -639,6 +659,7 @@ function applyDelta(ledger, entry) {
|
|
|
639
659
|
* 把「翻不到的历史差额」补进 `history`。**不做叠加**,是这一步的全部目的。
|
|
640
660
|
*/
|
|
641
661
|
function resetSessionUsage(ledger, sessionId) {
|
|
662
|
+
markLedgerChanged();
|
|
642
663
|
const record = ledger.sessions[sessionId];
|
|
643
664
|
if (!record) return null;
|
|
644
665
|
const daily = record.daily && typeof record.daily === 'object' ? record.daily : {};
|
|
@@ -673,16 +694,6 @@ function billedOf(usage) {
|
|
|
673
694
|
return num(usage.uncachedInputTokens) + num(usage.cacheReadTokens) + num(usage.cacheWriteTokens) + num(usage.outputTokens);
|
|
674
695
|
}
|
|
675
696
|
|
|
676
|
-
/**
|
|
677
|
-
* 金额取到六位小数。
|
|
678
|
-
*
|
|
679
|
-
* 逐行先取整再加会和合计对不上(一条几十万 token 的行差几厘,几十行就有分位上的差),
|
|
680
|
-
* 所以行与合计都从原值算、最后各自取整;六位是「十万 token 的一档价」还看得见的精度。
|
|
681
|
-
*/
|
|
682
|
-
function moneyOf(value) {
|
|
683
|
-
return Math.round(num(value) * 1e6) / 1e6;
|
|
684
|
-
}
|
|
685
|
-
|
|
686
697
|
/**
|
|
687
698
|
* 一条会话在 [startDay, endDay] 里的用量。
|
|
688
699
|
*
|
|
@@ -717,6 +728,28 @@ function usageInRange(record, startDay, endDay) {
|
|
|
717
728
|
*/
|
|
718
729
|
function summarize(ledger, range, now) {
|
|
719
730
|
const today = dayKeyOf(now);
|
|
731
|
+
// 同一本账、同一个范围、同一天再折一次就是在白算:统计页 1.5 秒轮询一次、App 切范围时
|
|
732
|
+
// 也只换一个词,而账本大多时候一秒都没动。判据三格一起看 —— 账本**对象身份**、改动版本
|
|
733
|
+
// (见 `ledgerVersion`)、范围 + 当天日期(跨零点要换一份逐日序列)。
|
|
734
|
+
//
|
|
735
|
+
// 只留最近一份:页面一次只看一个范围,留一份就够,也省掉一张要自己淘汰的表。
|
|
736
|
+
if (summaryCache
|
|
737
|
+
&& summaryCache.ledger === ledger
|
|
738
|
+
&& summaryCache.version === ledgerVersion
|
|
739
|
+
&& summaryCache.range === range
|
|
740
|
+
&& summaryCache.today === today) {
|
|
741
|
+
return summaryCache.result;
|
|
742
|
+
}
|
|
743
|
+
const result = summarizeUncached(ledger, range, now, today);
|
|
744
|
+
summaryCache = { ledger, version: ledgerVersion, range, today, result };
|
|
745
|
+
return result;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/** `summarize` 的缓存槽(只留最近一次;见上面那段注释)。 */
|
|
749
|
+
let summaryCache = null;
|
|
750
|
+
|
|
751
|
+
/** 真正折一份出来(`summarize` 在缓存没命中时调它)。 */
|
|
752
|
+
function summarizeUncached(ledger, range, now, today) {
|
|
720
753
|
const startDay = startDayOf(range, now);
|
|
721
754
|
const endDay = endDayOf(range, now);
|
|
722
755
|
const allDays = Object.keys(ledger.days).sort();
|
|
@@ -841,10 +874,6 @@ function summarize(ledger, range, now) {
|
|
|
841
874
|
// 这一份里认出来的厂商,只带**用到的那几个**图标(`icon` 是一段 SVG 标记,App 用 SvgXml
|
|
842
875
|
// 直接画):一次响应几十条模型行各自背一份图标没有意义。
|
|
843
876
|
const vendors = {};
|
|
844
|
-
/** 有价的那几行加起来:金额、它们覆盖的 token、行数(0 行就整项不给,页面不画)。 */
|
|
845
|
-
let costTotal = 0;
|
|
846
|
-
let costPricedBilled = 0;
|
|
847
|
-
let costPricedRows = 0;
|
|
848
877
|
for (const bucket of Object.values(ledger.models || {})) {
|
|
849
878
|
if (!bucket || typeof bucket !== 'object') continue;
|
|
850
879
|
const usage = usageInRange(bucket, startDay, endDay);
|
|
@@ -857,13 +886,6 @@ function summarize(ledger, range, now) {
|
|
|
857
886
|
const vendor = identifyVendor(bucket);
|
|
858
887
|
const logo = vendor ? vendorLogoOf(vendor) : null;
|
|
859
888
|
if (logo) vendors[vendor] = logo;
|
|
860
|
-
// 金额只在查得到单价时给:查不到不画 0,那一截 token 由下面的 `unpricedBilled` 交代。
|
|
861
|
-
const cost = costOfUsage(usage, priceOf(bucket.provider, bucket.model));
|
|
862
|
-
if (cost !== null) {
|
|
863
|
-
costTotal += cost;
|
|
864
|
-
costPricedBilled += billedTokens;
|
|
865
|
-
costPricedRows += 1;
|
|
866
|
-
}
|
|
867
889
|
models.push({
|
|
868
890
|
provider: bucket.provider || '',
|
|
869
891
|
providerName: bucket.providerName || '',
|
|
@@ -879,7 +901,6 @@ function summarize(ledger, range, now) {
|
|
|
879
901
|
// 请求数取 `usage.steps`,与按天账同一个口径(见 applyDelta 里的那条注释)。
|
|
880
902
|
requests: num(usage.steps),
|
|
881
903
|
lastAt: num(bucket.lastAt),
|
|
882
|
-
...(cost === null ? {} : { cost: moneyOf(cost) }),
|
|
883
904
|
});
|
|
884
905
|
}
|
|
885
906
|
models.sort((a, b) => (b.billedTokens !== a.billedTokens ? b.billedTokens - a.billedTokens : b.lastAt - a.lastAt));
|
|
@@ -901,20 +922,6 @@ function summarize(ledger, range, now) {
|
|
|
901
922
|
models,
|
|
902
923
|
// 一个厂商都没认出来时整项不出:老 App 不认识这个字段,新 App 缺它就是「没有图标」。
|
|
903
924
|
...(Object.keys(vendors).length > 0 ? { vendors } : {}),
|
|
904
|
-
// 成本合计只加「查得到单价」的那几行:一行都没有就整项不给 —— 缺这个字段,页面就不画
|
|
905
|
-
// 这一条(与 `models` 同一条规矩),比画一个 $0 强。`unpricedBilled` 是第 4 档:
|
|
906
|
-
// 范围内有量、但这台机器没有价(自建路由 / 免费渠道 / 老账本)的那一截。
|
|
907
|
-
...(costPricedRows > 0
|
|
908
|
-
? {
|
|
909
|
-
cost: {
|
|
910
|
-
currency: 'USD',
|
|
911
|
-
total: moneyOf(costTotal),
|
|
912
|
-
pricedBilled: costPricedBilled,
|
|
913
|
-
unpricedBilled: Math.max(0, rangeBilled - costPricedBilled),
|
|
914
|
-
asOf: AS_OF,
|
|
915
|
-
},
|
|
916
|
-
}
|
|
917
|
-
: {}),
|
|
918
925
|
};
|
|
919
926
|
}
|
|
920
927
|
|
|
@@ -937,6 +944,7 @@ module.exports = {
|
|
|
937
944
|
emptySession,
|
|
938
945
|
summarize,
|
|
939
946
|
trim,
|
|
947
|
+
markLedgerChanged,
|
|
940
948
|
dayKeyOf,
|
|
941
949
|
addDays,
|
|
942
950
|
startDayOf,
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 用户按停止后补在对话里的那份「本轮交代」:从**一次运行的步骤流**折成 App 侧
|
|
5
|
+
* `StopSummaryView` 那个形状(做了什么 / 看到了什么 / 没做完的部分 / 对外发出几次)。
|
|
6
|
+
*
|
|
7
|
+
* 为什么是纯函数、不调模型:停止那一刻要立刻给用户一句看得懂的话,不该再等一次模型往返。
|
|
8
|
+
* 输入复用直播清单与历史清单同一份形状(`live-steps.js` 的 `liveStepsOf` 与
|
|
9
|
+
* `history-derive.js` 的 `turnProcess.steps` 都是 `{ key, step }`,`step` 带
|
|
10
|
+
* `kind` / `name` / `summary` / `state`),所以两条数据源都能直接喂进来。
|
|
11
|
+
*
|
|
12
|
+
* 信息量口径:只陈述**能从那一步本身读到的东西**。状态只认步骤自己的 `state`
|
|
13
|
+
* (`ok` / `error` / `stopped`,缺省即「还在跑」),读不到就不写那一句 —— 宁可少写一行,
|
|
14
|
+
* 也不要把「已发出」写在一次其实失败了的动作上。「对外发出几次」同理:只认步骤上显式的
|
|
15
|
+
* `outward` / `irreversible` 标记,不按工具名或文案猜。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** 交代里每一段的条数上限:行再多也看不完,白占篇幅。 */
|
|
19
|
+
const MAX_DONE = 12;
|
|
20
|
+
const MAX_SEEN = 8;
|
|
21
|
+
const MAX_UNFINISHED = 12;
|
|
22
|
+
|
|
23
|
+
/** 单条摘要的字数上限。 */
|
|
24
|
+
const CLIP = 80;
|
|
25
|
+
|
|
26
|
+
/** 读类工具:这一步是「看到了什么」,不是「做了什么改动」。 */
|
|
27
|
+
const READ_TOOLS = new Set([
|
|
28
|
+
'read', 'read_image', 'web_fetch', 'web_search', 'grep', 'glob',
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 只读命令白名单:`bash` 这一步到底动没动手,只看命令本身。
|
|
33
|
+
*
|
|
34
|
+
* 为什么需要它:手机上一轮活里绝大多数步骤是 `bash`,而 `bash` 既可能是
|
|
35
|
+
* `grep -n "ota" docs/` 也可能是 `npm run build`。全算「做了什么」,交代里就是十几行
|
|
36
|
+
* 「做了什么」,其实一件东西都没改 —— 用户按停止时最想知道的「改了没有」反而读不出来。
|
|
37
|
+
*
|
|
38
|
+
* 口径刻意收得很紧:**只认白名单里的命令词,任何一段不认得就退回「做了什么」**。
|
|
39
|
+
* 判错的方向不对称 —— 把读算成做,是把没发生的事写成发生了;把做算成读,是把真做了的事
|
|
40
|
+
* 藏起来。所以宁可按旧口径写「做了什么」。
|
|
41
|
+
*/
|
|
42
|
+
const READ_ONLY_COMMANDS = new Set([
|
|
43
|
+
'cd', 'grep', 'rg', 'cat', 'ls', 'head', 'tail', 'wc', 'find', 'fd', 'jq',
|
|
44
|
+
'diff', 'stat', 'file', 'tree', 'pwd', 'sed', 'awk', 'echo', 'which', 'type',
|
|
45
|
+
'basename', 'dirname', 'realpath', 'sort', 'uniq', 'cut', 'tr', 'xargs',
|
|
46
|
+
]);
|
|
47
|
+
|
|
48
|
+
/** 这些词一出现就是真动手了(写文件 / 装依赖 / 改版本库),整条命令按「做了什么」算。 */
|
|
49
|
+
const WRITE_WORDS = new Set([
|
|
50
|
+
'rm', 'mv', 'cp', 'tee', 'mkdir', 'touch', 'chmod', 'chown', 'ln', 'dd',
|
|
51
|
+
'truncate', 'npm', 'pnpm', 'yarn', 'npx', 'cargo', 'docker', 'make', 'kill',
|
|
52
|
+
'curl', 'wget', 'git-add', 'install', 'patch',
|
|
53
|
+
]);
|
|
54
|
+
|
|
55
|
+
/** 把一段命令切成若干「子命令」:只切 `&&` 与 `;`,**不切 `|`**(正则里的 `\|` 是转义,不是管道)。 */
|
|
56
|
+
function commandSegments(command) {
|
|
57
|
+
return String(command || '')
|
|
58
|
+
.split(/&&|;/)
|
|
59
|
+
.map((part) => part.trim())
|
|
60
|
+
.filter(Boolean);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 一段命令的词:去掉 `VAR=value` 前缀与环境变量,取前两个词判断。 */
|
|
64
|
+
function wordsOf(segment) {
|
|
65
|
+
return segment
|
|
66
|
+
.replace(/[0-9]?>\s*\/dev\/null/g, ' ')
|
|
67
|
+
.replace(/2>&1/g, ' ')
|
|
68
|
+
.replace(/^\s*[A-Za-z_][A-Za-z0-9_]*=\S*\s+/, '')
|
|
69
|
+
.split(/\s+/)
|
|
70
|
+
.filter(Boolean);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 这一段是不是纯读取(白名单命令 + 不含任何写词;`git` 只放行只读子命令)。 */
|
|
74
|
+
function segmentIsRead(segment) {
|
|
75
|
+
// 先把「丢掉输出」这类无害重定向抹掉,再查还有没有 `>` —— 剩下的每一个都是真在写文件。
|
|
76
|
+
const cleaned = String(segment)
|
|
77
|
+
.replace(/[0-9]?>\s*\/dev\/null/g, ' ')
|
|
78
|
+
.replace(/[0-9]?>&[0-9]/g, ' ');
|
|
79
|
+
if (/>/.test(cleaned)) return false;
|
|
80
|
+
const words = wordsOf(segment);
|
|
81
|
+
if (words.length === 0) return false;
|
|
82
|
+
const head = words[0].replace(/^[-("']+/, '').replace(/["').]+$/, '');
|
|
83
|
+
if (head === 'git') {
|
|
84
|
+
const sub = (words[1] || '').replace(/["']/g, '');
|
|
85
|
+
if (!/^(log|status|diff|show|blame|rev-parse|ls-files|grep|shortlog|describe|branch|remote|tag)$/.test(sub)) {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
} else if (!READ_ONLY_COMMANDS.has(head)) {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
if (head === 'sed' && /(^|\s)-i/.test(segment)) return false;
|
|
92
|
+
for (const word of words) {
|
|
93
|
+
if (WRITE_WORDS.has(word.replace(/["']/g, ''))) return false;
|
|
94
|
+
}
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 整条命令里有没有看得出来是写的痕迹。 */
|
|
99
|
+
function commandLooksReadOnly(command) {
|
|
100
|
+
const segments = commandSegments(command);
|
|
101
|
+
if (segments.length === 0) return false;
|
|
102
|
+
return segments.every(segmentIsRead);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 摘要里那截**每次都一样**的目录前缀剥掉:`cd "/Volumes/…" && grep …` → `grep …`。
|
|
107
|
+
*
|
|
108
|
+
* 为什么:Agent 每一条命令都从 `cd <项目根>` 起手,而摘要只给 80 个字 —— 前缀吃掉之后
|
|
109
|
+
* 十几行显示出来几乎一模一样,真正的动作全落在省略号后面。剥掉之后同一个前缀不再重复十几遍。
|
|
110
|
+
*/
|
|
111
|
+
function stripCdPrefix(command) {
|
|
112
|
+
const segments = commandSegments(command);
|
|
113
|
+
const kept = segments.filter((part) => !/^cd\s/.test(part));
|
|
114
|
+
const value = (kept.length > 0 ? kept : segments).join(' && ').trim();
|
|
115
|
+
return value || String(command || '').trim();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
/** 思考步不是「做的事」,但可以是「最后想到哪 / 写了一半的字」。 */
|
|
120
|
+
function isThink(step) {
|
|
121
|
+
return step && step.kind === 'think';
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** 把一个清单条目摊成裸 step:`{ key, step }` 去掉壳,裸 step 原样返回。 */
|
|
125
|
+
function normalizeEntry(entry) {
|
|
126
|
+
if (!entry || typeof entry !== 'object') return {};
|
|
127
|
+
return entry.step && typeof entry.step === 'object'
|
|
128
|
+
? { key: entry.key, ...entry.step }
|
|
129
|
+
: entry;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** 摊平步骤数组:认 `{ steps: [...] }` 与裸数组两种形状。 */
|
|
133
|
+
function toStepList(run) {
|
|
134
|
+
const list = Array.isArray(run)
|
|
135
|
+
? run
|
|
136
|
+
: (run && typeof run === 'object' && Array.isArray(run.steps) ? run.steps : null);
|
|
137
|
+
return list ? list.map(normalizeEntry) : [];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function clip(text, max = CLIP) {
|
|
141
|
+
const value = String(text == null ? '' : text).replace(/\s+/g, ' ').trim();
|
|
142
|
+
if (value.length <= max) return value;
|
|
143
|
+
return `${value.slice(0, max - 1)}…`;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** 这一步行给人看的标签:优先现成摘要,没有就从参数里挑一个最像「这一步是干嘛的」字段。 */
|
|
147
|
+
function labelOf(step) {
|
|
148
|
+
if (!step || typeof step !== 'object') return '';
|
|
149
|
+
if (typeof step.summary === 'string' && step.summary.trim() !== '') {
|
|
150
|
+
return clip(cleanLabel(step.summary, step.name));
|
|
151
|
+
}
|
|
152
|
+
const args = step.args && typeof step.args === 'object' ? step.args : {};
|
|
153
|
+
const candidates = ['target', 'text', 'description', 'query', 'command', 'file_path', 'path', 'ref', 'url'];
|
|
154
|
+
for (const key of candidates) {
|
|
155
|
+
const value = args[key];
|
|
156
|
+
if (typeof value === 'string' && value.trim() !== '') return clip(cleanLabel(value, step.name));
|
|
157
|
+
}
|
|
158
|
+
return clip(step.name || step.kind || '');
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* 摘要显示前先收拾一遍:`bash` 类摘要把 `cd <项目根> &&` 那截前缀剥掉。
|
|
163
|
+
*
|
|
164
|
+
* 只剥 `bash` / `pwsh` / `terminal_send`(它们的摘要就是命令行),别的工具的原样留着 ——
|
|
165
|
+
* `read` 的摘要是路径、`grep` 的是模式,本来就不带 `cd`。
|
|
166
|
+
*/
|
|
167
|
+
function cleanLabel(text, name) {
|
|
168
|
+
const value = String(text == null ? '' : text);
|
|
169
|
+
if (name === 'bash' || name === 'pwsh' || name === 'terminal_send') {
|
|
170
|
+
return stripCdPrefixClip(value);
|
|
171
|
+
}
|
|
172
|
+
return value;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* 剥前缀之后再截断:先剥再截,才能让剩下的字更多。
|
|
177
|
+
*
|
|
178
|
+
* 摘要本身在插件上游已经被 `clampSummary` 截到 72 字了,这里拿到的可能已经是
|
|
179
|
+
* `cd "…" && grep -n "ota" docs/dev-map…`(末尾带省略号)。剥掉前缀之后留个尾巴上的
|
|
180
|
+
* 省略号就够了,不必再补。
|
|
181
|
+
*/
|
|
182
|
+
function stripCdPrefixClip(value) {
|
|
183
|
+
if (!/(^|\s)cd\s/.test(value)) return value;
|
|
184
|
+
const stripped = stripCdPrefix(value);
|
|
185
|
+
return stripped || value;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** 一步是不是「纯读取」:读类工具,或命令看起只读的 bash。 */
|
|
189
|
+
function looksReadOnly(step) {
|
|
190
|
+
if (READ_TOOLS.has(step.name)) return true;
|
|
191
|
+
if (step.name === 'bash' || step.name === 'pwsh' || step.name === 'terminal_send') {
|
|
192
|
+
const command = typeof step.summary === 'string' ? step.summary : '';
|
|
193
|
+
return commandLooksReadOnly(stripCdPrefix(command));
|
|
194
|
+
}
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** 一步的状态归成三种:成功 / 没用成 / 还在跑(读不到就是还在跑)。 */
|
|
199
|
+
function stateOf(step) {
|
|
200
|
+
const state = step && typeof step.state === 'string' ? step.state : '';
|
|
201
|
+
if (state === 'ok') return 'ok';
|
|
202
|
+
if (state === 'error') return 'error';
|
|
203
|
+
if (state === 'stopped') return 'stopped';
|
|
204
|
+
return 'running';
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** 这一步有没有显式标成「对外发出」(发送 / 提交 / 下单这类收不回来的动作)。 */
|
|
208
|
+
function outwardOf(step) {
|
|
209
|
+
if (!step || typeof step !== 'object') return false;
|
|
210
|
+
return step.outward === true || step.irreversible === true
|
|
211
|
+
|| (typeof step.outward === 'string' && step.outward !== '');
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* 从一次运行生成交代。
|
|
216
|
+
*
|
|
217
|
+
* @param {object|Array} run 步骤流(`{ steps: [{key, step}] }` 或裸数组)。
|
|
218
|
+
* @returns {{did: string[], saw: string[], outboundCount?: number, unfinished?: string[], closing?: string}}
|
|
219
|
+
*/
|
|
220
|
+
function summarize(run) {
|
|
221
|
+
const steps = toStepList(run);
|
|
222
|
+
const did = [];
|
|
223
|
+
const seen = [];
|
|
224
|
+
const unfinished = [];
|
|
225
|
+
let outboundCount = 0;
|
|
226
|
+
let closing = '';
|
|
227
|
+
|
|
228
|
+
for (const step of steps) {
|
|
229
|
+
if (!step || typeof step !== 'object') continue;
|
|
230
|
+
const label = labelOf(step);
|
|
231
|
+
const state = stateOf(step);
|
|
232
|
+
|
|
233
|
+
if (isThink(step)) {
|
|
234
|
+
// 思考步不进「做了什么」;只记最后一段有内容的思考。
|
|
235
|
+
if (label) closing = label;
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
if (!step.name && !label) continue;
|
|
239
|
+
|
|
240
|
+
if (state !== 'ok') {
|
|
241
|
+
unfinished.push(label || String(step.name || '一步动作'));
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (looksReadOnly(step)) {
|
|
246
|
+
if (label) seen.push(label);
|
|
247
|
+
} else if (label) {
|
|
248
|
+
did.push(label);
|
|
249
|
+
}
|
|
250
|
+
if (outwardOf(step)) outboundCount += 1;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const view = {
|
|
254
|
+
did: dedupe(did).slice(-MAX_DONE),
|
|
255
|
+
saw: dedupe(seen).slice(-MAX_SEEN),
|
|
256
|
+
};
|
|
257
|
+
if (outboundCount > 0) view.outboundCount = outboundCount;
|
|
258
|
+
if (unfinished.length > 0) view.unfinished = dedupe(unfinished).slice(0, MAX_UNFINISHED);
|
|
259
|
+
if (closing) view.closing = closing;
|
|
260
|
+
return view;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* 同一个标签只留一条:`grep` 同一个模式搜两次、`read` 同一个文件读两遍,
|
|
265
|
+
* 在交代里并列两行不增加任何信息,只把篇幅撑长。
|
|
266
|
+
*/
|
|
267
|
+
function dedupe(items) {
|
|
268
|
+
const out = [];
|
|
269
|
+
const seen = new Set();
|
|
270
|
+
for (const item of items) {
|
|
271
|
+
const key = String(item || '').trim();
|
|
272
|
+
if (!key || seen.has(key)) continue;
|
|
273
|
+
seen.add(key);
|
|
274
|
+
out.push(item);
|
|
275
|
+
}
|
|
276
|
+
return out;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
module.exports = {
|
|
280
|
+
summarize,
|
|
281
|
+
// 给守卫与接线方直接用的纯函数:
|
|
282
|
+
toStepList,
|
|
283
|
+
labelOf,
|
|
284
|
+
stateOf,
|
|
285
|
+
outwardOf,
|
|
286
|
+
looksReadOnly,
|
|
287
|
+
commandLooksReadOnly,
|
|
288
|
+
stripCdPrefix,
|
|
289
|
+
MAX_DONE,
|
|
290
|
+
MAX_SEEN,
|
|
291
|
+
MAX_UNFINISHED,
|
|
292
|
+
};
|