dsh-mobile-plugin 0.5.35 → 0.5.36

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.
Files changed (34) hide show
  1. package/lib/impl.js +0 -7
  2. package/lib/mobile/answer-sources.js +223 -0
  3. package/lib/mobile/approval-memory.js +1 -1
  4. package/lib/mobile/events.js +0 -20
  5. package/lib/mobile/extension-data.js +105 -5
  6. package/lib/mobile/history-derive.js +54 -1
  7. package/lib/mobile/notification-prefs.js +2 -2
  8. package/lib/mobile/permissions.js +8 -5
  9. package/lib/mobile/plugin-market.js +103 -4
  10. package/lib/mobile/run-timeline.js +317 -0
  11. package/lib/mobile/session-stop-summary.js +122 -0
  12. package/lib/mobile/stats-ledger.cjs +45 -0
  13. package/lib/mobile/stop-summary.js +146 -0
  14. package/lib/mobile/third-party-extensions.js +86 -0
  15. package/lib/mobile/tool-result-cache.js +30 -2
  16. package/lib/panel/index.html +15 -15
  17. package/lib/relay/lan-proxy.js +20 -11
  18. package/lib/relay/tunnel.js +28 -12
  19. package/lib/routes/mobile-api.js +25 -19
  20. package/lib/shared/derived-cache.js +121 -0
  21. package/lib/shared/http-util.js +55 -18
  22. package/package.json +1 -2
  23. package/config/agent-presets/supervisor/agent.cordis.yml +0 -237
  24. package/config/agent-presets/supervisor/preset.yml +0 -3
  25. package/lib/mobile/auto-review-log.js +0 -160
  26. package/lib/mobile/knowledge-base.js +0 -481
  27. package/lib/mobile/mail.js +0 -621
  28. package/lib/mobile/supervisor-broadcast.js +0 -503
  29. package/lib/mobile/supervisor-memory/index.js +0 -305
  30. package/lib/mobile/supervisor-runtime/index.js +0 -54
  31. package/lib/mobile/supervisor-runtime/inject.js +0 -218
  32. package/lib/mobile/supervisor-runtime/judgment.js +0 -113
  33. package/lib/mobile/supervisor-tools.js +0 -419
  34. package/lib/mobile/task-ledger.js +0 -381
@@ -10,16 +10,18 @@
10
10
  *
11
11
  * 能力面收在三条上(与桌面端同一个判据,不另开):
12
12
  * 1. **只经 typertGateway 走 `pluginManager`**,不走 shell、不碰系统设置;
13
- * 2. **没有卸载入口**:卸载要重启电脑上的 DSH,而手机没有在电脑前的那双手;承载本 App
14
- * 连接的那个包(dsh-mobile-plugin)另外**不给停用**,停掉它等于把这台手机变成砖。它的
15
- * 更新仍走原有的 `/plugin/update/*`(那条有装后自检与回滚,比通用卸载可靠)。「升级 =
16
- * 卸载再装」那条照旧由宿主自己的 `removeBundle` 完成,不是这里开的口子;
13
+ * 2. **卸载只对「宿主说它可卸」的包开放**:`/plugin/market/remove` 转 `removeBundle`,但
14
+ * 承载本 App 连接的那个包(dsh-mobile-plugin)与 DSH 自带 / 按需安装的官方包一律不给
15
+ * (它们要么把这台手机变成砖,要么本来就不可卸);界面先问 `removable`,按钮摆不摆由它定。
16
+ * 卸完要等电脑上下次启动 DSH 才真的不在,这条代价写在界面确认框里;
17
17
  * 3. 安装/启用**不改 DSH 的启动方式**:新装的插件要不要重启才生效由宿主自己回报,界面照实说。
18
18
  *
19
19
  * 接口(都挂 `/api/mobile/v1/plugin/market`,走 token 守卫):
20
20
  * GET `/plugin/market` → { bundles }
21
21
  * GET `/plugin/market/registries` → { registry, fallbackRegistries, resolved }:安装时能选的 npm 源
22
22
  * POST `/plugin/market/inspect` { spec } → 读一下这个包是什么
23
+ * GET `/plugin/market/detail?name=&language=` → { status, markdown, origin }:插件说明文档
24
+ * POST `/plugin/market/remove` { name, requestId? } → 卸载(立即返回,结果看 progress)
23
25
  * POST `/plugin/market/install` { spec, registry?, requestId?, approvedBuilds? } → 开始装(立即返回)
24
26
  * POST `/plugin/market/update` { name, requestId? } → 卸载后重装成最新 / 官方给的目标版本
25
27
  * POST `/plugin/market/cancel` { requestId } → 停一次正在跑的安装
@@ -47,6 +49,10 @@ const BUNDLES_MAX_ITEMS = 300;
47
49
  /** npm 源是一个 URL,与 spec 同一个量级;备用源按顺序全报,20 条封顶。 */
48
50
  const REGISTRY_MAX_CHARS = 300;
49
51
  const REGISTRIES_MAX_ITEMS = 20;
52
+ /** 插件图标是一张内联 data URL;按 40KB 封顶(正常一张 16~48px 的图远小于这个)。 */
53
+ const ICON_MAX_CHARS = 40 * 1024;
54
+ /** 说明文档可能很长,但手机只画一段:64KB 封顶,超出截断并保留「已截断」语义。 */
55
+ const DETAIL_MAX_CHARS = 64 * 1024;
50
56
  /** 内存里最多留几条安装记录:手机只会盯手上这一条,多的是断线前留下的。 */
51
57
  const TASKS_MAX = 20;
52
58
  const BODY_MAX_BYTES = 8 * 1024;
@@ -141,9 +147,15 @@ function normalizeBundle(row) {
141
147
  : '',
142
148
  }
143
149
  : null;
150
+ // icon 是宿主给的**图片 data URL**(包根 manifest 的 icon,或 `<specifier>/icon` 导出),
151
+ // 原样转给 App 当图片画;不要拼进文案、也不是 SVG 标记。只有部分插件有。
152
+ const icon = meta && typeof meta.icon === 'string' && /^data:image\//.test(meta.icon)
153
+ ? meta.icon.slice(0, ICON_MAX_CHARS)
154
+ : null;
144
155
  return {
145
156
  name,
146
157
  version: textOrNull(row.version, 64),
158
+ icon,
147
159
  title: meta ? displayField(meta.title) : null,
148
160
  description: (meta ? displayField(meta.description) : null) || textOrNull(row.description, 400),
149
161
  source: textOrNull(row.source, SPEC_MAX_CHARS),
@@ -451,9 +463,96 @@ async function handlePluginMarketEnabled(ctx, req, res) {
451
463
  sendJson(res, 200, { ok: true, operation: operationView(result.value) });
452
464
  }
453
465
 
466
+ /**
467
+ * GET /api/mobile/v1/plugin/market/detail?name=&language=
468
+ *
469
+ * 一个插件的说明文档:宿主先找它 `meta.detail` 指着的那份本地化文档、找不到退回包里的
470
+ * README;已装的从包目录读(不联网),没装的官方按需插件从 npm 文件 CDN 读。**原文就是
471
+ * Markdown**,手机自己渲染 —— 别在插件侧把它转成 HTML,那会把链接、代码块与图片一起做坏。
472
+ *
473
+ * `status: 'none'` 表示这个包没有文档,不是错。
474
+ */
475
+ async function handlePluginMarketDetail(ctx, req, res) {
476
+ const params = new URL(req.url || '/', 'http://x').searchParams;
477
+ const name = normalizeName(params.get('name'));
478
+ if (!name.value) return badRequest(res, name.problem);
479
+ const language = textOrNull(params.get('language'), 16)
480
+ || textOrNull(req.headers && req.headers['accept-language'], 16)
481
+ || 'en';
482
+ const result = await call(ctx, 'readBundleDetail', { name: name.value, language });
483
+ if (result.error) return sendJson(res, statusOf(result.error), { ok: false, error: result.error });
484
+ const value = result.value && typeof result.value === 'object' ? result.value : {};
485
+ if (value.status !== 'found') {
486
+ return sendJson(res, 200, { ok: true, status: 'none', name: name.value });
487
+ }
488
+ const markdown = typeof value.markdown === 'string' ? value.markdown : '';
489
+ sendJson(res, 200, {
490
+ ok: true,
491
+ status: 'found',
492
+ name: name.value,
493
+ // `locale` 是包里那份本地化文档,`readme` 是 README;界面不用它,留着排查用。
494
+ origin: textOrNull(value.origin, 16),
495
+ path: textOrNull(value.path, 300),
496
+ // 太长就截断:手机只画一段说明,64KB 已经远超一屏能读的量。
497
+ markdown: markdown.length > DETAIL_MAX_CHARS
498
+ ? `${markdown.slice(0, DETAIL_MAX_CHARS)}\n\n…`
499
+ : markdown,
500
+ });
501
+ }
502
+
503
+ /**
504
+ * POST /api/mobile/v1/plugin/market/remove { name, requestId? }
505
+ *
506
+ * 卸载一个插件:转给宿主的 `removeBundle`(它拿到 pnpm 那条路去删依赖、卸层),与桌面
507
+ * 设置 → 插件里那颗「卸载」是同一条实现。**立即返回 202 + requestId**,结果看 progress。
508
+ *
509
+ * 三道闸:承载手机连接的那个包一律拒(卸了这台手机就再也连不上)、没装上的行拒、
510
+ * 宿主说 `removable:false` 的(自带 / 安装提供的官方包)拒。判据都以宿主清单为准,
511
+ * 不在这里另立一份白名单。
512
+ */
513
+ async function handlePluginMarketRemove(ctx, req, res) {
514
+ const body = await readJsonBody(req, BODY_MAX_BYTES);
515
+ const name = normalizeName(body && body.name);
516
+ if (!name.value) return badRequest(res, name.problem);
517
+ if (name.value === SELF_NAME) {
518
+ return sendJson(res, 403, {
519
+ ok: false,
520
+ error: {
521
+ code: 'self-protected',
522
+ message: '卸掉这个插件等于断开这台手机;要卸载请到电脑上的 DSH 里操作',
523
+ },
524
+ });
525
+ }
526
+ const listed = await call(ctx, 'listBundles', {});
527
+ if (listed.error) return sendJson(res, statusOf(listed.error), { ok: false, error: listed.error });
528
+ const bundle = Array.isArray(listed.value)
529
+ ? listed.value.map(normalizeBundle).find((item) => item && item.name === name.value)
530
+ : null;
531
+ if (!bundle) {
532
+ return sendJson(res, 404, { ok: false, error: { code: 'unknown-plugin', message: '这台宿主上没有这个插件' } });
533
+ }
534
+ if (bundle.removable !== true) {
535
+ return sendJson(res, 400, {
536
+ ok: false,
537
+ error: { code: 'not-removable', message: '这个插件是 DSH 自带或安装提供的,不能在手机上卸载' },
538
+ });
539
+ }
540
+ const requestId = readRequestId(body && body.requestId, () => localRequestId('remove'));
541
+ beginTask(requestId, 'remove', name.value);
542
+ void (async () => {
543
+ const removed = await call(ctx, 'removeBundle', { name: name.value });
544
+ finishTask(requestId, removed.error
545
+ ? { ok: false, error: removed.error }
546
+ : { ok: true, operation: operationView(removed.value), spec: name.value });
547
+ })();
548
+ sendJson(res, 202, { ok: true, requestId });
549
+ }
550
+
454
551
  module.exports = {
455
552
  handlePluginMarket,
456
553
  handlePluginMarketRegistries,
554
+ handlePluginMarketDetail,
555
+ handlePluginMarketRemove,
457
556
  handlePluginMarketInspect,
458
557
  handlePluginMarketInstall,
459
558
  handlePluginMarketUpdate,
@@ -0,0 +1,317 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 「运行时间线」:把**一轮**跑过的步骤折成 App 侧 `RunTimelineView`(整页时间线的数据)。
5
+ *
6
+ * 这是什么:手机上那条「过程 · 已跑 N 步」点开是一份清单,这一页是同一份清单的整页版 ——
7
+ * 一步一行,带状态、耗时、发生时刻。数据只有两个来源,都是**已经存在**的:
8
+ * - 还在跑的那一轮:`live-steps.js` 留在内存里的直播副本(`{ key, step }`);
9
+ * - 已经落定的轮:按 `turn` 去宿主回拉一小窗事件,再用 `step-index` 的同一批纯函数重算摘要
10
+ * 与状态(与 `history-derive` 的 `turnProcess.steps` 同源同口径)。
11
+ *
12
+ * 为什么是纯函数、为什么不造后端:宿主从来没有「运行记录」这个后端(它原本随「操作手机」
13
+ * 那批一起长、从没接线)。这一页要的是**回看一份已经发生过的东西**,不需要新存储 —— 直播
14
+ * 副本还有就直接读,落定了就按轮回拉一次。路由层(`routes/mobile-api.js`)只负责取数,
15
+ * 折叠全在这里,守卫可以在裸 Node 里直接加载真实现。
16
+ *
17
+ * 两个字段刻意没有生产者(不是忘了写):
18
+ * - `screenshotUrl`:原来靠「操作手机」的读屏截屏留档,那套能力已整块下线。为它另造一条
19
+ * 截屏链路是扩能力面、原生改动也大,不值得;页面本来就按「没有就不画缩略图」处理。
20
+ * - `tags`(`guard` / `verify` / `confirm` / `takeover`):同样是那套能力的产物,一起下线了。
21
+ * App 侧的类型把这两格留着,将来真需要时再补生产者;这里**不产出**它们。
22
+ */
23
+
24
+ const { sendJson } = require('../shared/http-util');
25
+ const { unwrap } = require('./envelope.js');
26
+ const { callSessions } = require('./rpc.js');
27
+ const { liveStepsOf, liveStepsTurnOf } = require('./live-steps.js');
28
+ const { buildToolResultMap, parseBlocks, blocksToText } = require('./history-derive.js');
29
+ const { reasoningText, reasoningStepSummary, toolStepSummary, toolStepState } = require('./step-index.js');
30
+
31
+ /**
32
+ * 回拉历史时一次读多少条事件。
33
+ *
34
+ * 宿主一步一条 assistant 消息,一轮长回合能到几百条;这个窗口要能兜住「一轮跑完 + 它的工具
35
+ * 结果」,又不是把整份会话搬回手机(回拉本身在电脑本地走 RPC,不占手机流量)。取不到的轮
36
+ * 由路由如实回 404,让 App 落空态,不猜。
37
+ */
38
+ const HISTORY_TURN_MAX_MESSAGES = 600;
39
+
40
+ /** App 侧认的那三档步骤类型里,宿主**真的会产**的只有两档(`say` 没有生产者,见文件头)。 */
41
+ const STEP_KIND = { think: 'think', tool: 'tool' };
42
+
43
+ /** App 侧认的四档步骤状态;宿主的词本来就是这四档,认不出的不写(页面按「没有就不画」处理)。 */
44
+ const STEP_STATE = new Set(['running', 'ok', 'error', 'stopped']);
45
+
46
+ /** 整次运行的结局,与 App 侧 `RunStatus` 同一套词。 */
47
+ const RUN_STATUS = new Set(['running', 'done', 'partial', 'failed', 'stopped']);
48
+
49
+ /** 认不出的 `step.kind` 一律按工具步处理:宿主只会发 `think` / `tool` 两种,这是兜底不是映射。 */
50
+ function kindOfStep(step) {
51
+ return STEP_KIND[step && step.kind] || 'tool';
52
+ }
53
+
54
+ /** 一步的主行:思考看摘要,工具看「摘要,没有摘要就用工具名」。 */
55
+ function titleOfStep(step, kind) {
56
+ const summary = typeof step.summary === 'string' ? step.summary : '';
57
+ if (summary !== '') return summary;
58
+ if (kind === 'tool' && typeof step.name === 'string') return step.name;
59
+ return '';
60
+ }
61
+
62
+ /**
63
+ * `{ key, step }` → App 侧的一步。
64
+ *
65
+ * `id` 直接用宿主的 `key`(直播侧是 `tool:<callId>` / `think:<序号>`,历史侧由这里按位置补),
66
+ * 它在一轮内稳定,正好当列表 key。`durationMs` / `at` 是**读得到才带**:直播副本里没有时刻,
67
+ * 历史事件里有 `time`;读不到就不写,绝不用「现在」或「这一轮起点」凑一个出来。
68
+ */
69
+ function stepOfEntry(entry) {
70
+ const step = entry && entry.step ? entry.step : {};
71
+ const kind = kindOfStep(step);
72
+ return {
73
+ id: String(entry.key),
74
+ kind,
75
+ title: titleOfStep(step, kind),
76
+ ...(kind === 'tool' && typeof step.name === 'string' && step.name !== '' ? { tool: step.name } : {}),
77
+ ...(STEP_STATE.has(step.state) ? { state: step.state } : {}),
78
+ ...(typeof step.durationMs === 'number' && Number.isFinite(step.durationMs) && step.durationMs >= 0
79
+ ? { durationMs: step.durationMs } : {}),
80
+ ...(typeof step.at === 'number' && Number.isFinite(step.at) ? { at: step.at } : {}),
81
+ };
82
+ }
83
+
84
+ /**
85
+ * 折成 App 侧的一次运行视图。
86
+ *
87
+ * @param {{ sessionId: string, turn?: number|null, entries: {key: string, step: object}[],
88
+ * title?: string, startedAt?: number, endedAt?: number, outcome?: string }} input
89
+ * @returns {{ id: string, title: string, status: string, startedAt?: number, endedAt?: number, steps: object[] }}
90
+ */
91
+ function buildRunTimeline(input) {
92
+ const { sessionId, turn = null, entries = [], title = '', startedAt, endedAt, outcome } = input || {};
93
+ const steps = entries.map(stepOfEntry);
94
+ const status = RUN_STATUS.has(outcome) ? outcome : 'done';
95
+ return {
96
+ id: `${sessionId}:${turn === null || turn === undefined ? 'latest' : turn}`,
97
+ title: typeof title === 'string' ? title : '',
98
+ status,
99
+ ...(typeof startedAt === 'number' && Number.isFinite(startedAt) ? { startedAt } : {}),
100
+ ...(typeof endedAt === 'number' && Number.isFinite(endedAt) ? { endedAt } : {}),
101
+ steps,
102
+ };
103
+ }
104
+
105
+ /**
106
+ * 直播副本 → 运行视图。
107
+ *
108
+ * 这份副本里没有起止时刻(`live-steps` 只管这一轮的步骤,不管钟),所以 `startedAt` /
109
+ * `endedAt` 不带上 —— 页头就不画时长,比编一个出来诚实。结局只能从步骤状态推:还有
110
+ * `running` 的就在跑,全收口了就当这一轮跑完了(宿主换轮时这份副本会被整份替换)。
111
+ */
112
+ function runTimelineFromLiveSteps({ sessionId, turn = null, entries = [] }) {
113
+ const running = entries.some((entry) => entry && entry.step && entry.step.state === 'running');
114
+ return buildRunTimeline({ sessionId, turn, entries, outcome: running ? 'running' : 'done' });
115
+ }
116
+
117
+ /** 一条事件属于哪一轮(没有轮号的一律不算)。 */
118
+ function turnOfEvent(event) {
119
+ const turn = event && event.data && event.data.turn;
120
+ return typeof turn === 'number' ? turn : undefined;
121
+ }
122
+
123
+ /**
124
+ * 把这一轮的助手消息折成 `{ key, step }`(与直播副本同一形状,摘要与状态取 `step-index`)。
125
+ *
126
+ * 与 `history-derive` 的 `collectSteps` 同一套判据:空推理块不算一步(点开一行什么都没有
127
+ * 没有意义);工具步的状态由结果事件反推(没有结果就是还在跑)。
128
+ */
129
+ function stepsFromEvents(events, turn) {
130
+ const toolResults = buildToolResultMap(events);
131
+ const entries = [];
132
+ for (const item of events) {
133
+ const event = item && item.event ? item.event : item;
134
+ if (!event || event.type !== 'assistant/message') continue;
135
+ if (turnOfEvent(event) !== turn) continue;
136
+ const message = event.data && event.data.message;
137
+ const content = message && Array.isArray(message.content) ? message.content : [];
138
+ content.forEach((block, index) => {
139
+ if (!block || typeof block !== 'object') return;
140
+ if (block.type === 'reasoning') {
141
+ const text = reasoningText(block.text);
142
+ // 只剩签名块的那一段等于没有推理,不算一步。
143
+ if (text.trim() === '') return;
144
+ entries.push({
145
+ key: `think:${event.seq}:${index}`,
146
+ step: {
147
+ kind: 'think',
148
+ summary: reasoningStepSummary(text),
149
+ state: 'ok',
150
+ ...(typeof event.time === 'number' ? { at: event.time } : {}),
151
+ },
152
+ });
153
+ return;
154
+ }
155
+ if (block.type !== 'tool-call') return;
156
+ const callId = block.id != null ? String(block.id) : '';
157
+ const result = callId ? toolResults.get(callId) : undefined;
158
+ const rawArgs = typeof block.arguments === 'string'
159
+ ? block.arguments
160
+ : (block.arguments != null ? JSON.stringify(block.arguments) : '');
161
+ entries.push({
162
+ key: callId ? `tool:${callId}` : `tool:${event.seq}:${index}`,
163
+ step: {
164
+ kind: 'tool',
165
+ ...(callId ? { callId } : {}),
166
+ ...(typeof block.name === 'string' && block.name !== '' ? { name: block.name } : {}),
167
+ summary: toolStepSummary(block.name, rawArgs),
168
+ state: toolStepState(result),
169
+ ...(typeof event.time === 'number' ? { at: event.time } : {}),
170
+ },
171
+ });
172
+ });
173
+ }
174
+ return entries;
175
+ }
176
+
177
+ /**
178
+ * 这一轮的元信息:起止时刻、结局、标题(用户那句话)。
179
+ *
180
+ * 结局按 `turn/end` 的 `reason.kind` 分:`error` → 失败、`aborted` → 已停止、`max-tokens` →
181
+ * 部分完成(输出被上限截断,确实没跑完),其余算正常收口。没有 `turn/end` 就是还在跑。
182
+ */
183
+ function turnMetaOf(events, turn) {
184
+ const toolResults = buildToolResultMap(events);
185
+ let startedAt;
186
+ let endedAt;
187
+ let outcome = 'running';
188
+ let title = '';
189
+ for (const item of events) {
190
+ const event = item && item.event ? item.event : item;
191
+ if (!event || turnOfEvent(event) !== turn) continue;
192
+ if (event.type === 'turn/start' && typeof event.time === 'number') startedAt = event.time;
193
+ if (event.type === 'user/message') {
194
+ const content = event.data && Array.isArray(event.data.content) ? event.data.content : [];
195
+ const text = blocksToText(parseBlocks(content, toolResults)).trim();
196
+ if (text !== '' && title === '') title = text.length > 120 ? `${text.slice(0, 119)}…` : text;
197
+ }
198
+ if (event.type === 'turn/end') {
199
+ if (typeof event.time === 'number') endedAt = event.time;
200
+ const reason = event.data && event.data.reason;
201
+ const kind = reason && typeof reason.kind === 'string' ? reason.kind : '';
202
+ outcome = kind === 'error' ? 'failed'
203
+ : kind === 'aborted' ? 'stopped'
204
+ : kind === 'max-tokens' ? 'partial'
205
+ : 'done';
206
+ }
207
+ }
208
+ return { startedAt, endedAt, outcome, title };
209
+ }
210
+
211
+ /** 事件里出现过的最后一轮(调用方没点名轮次时用它)。 */
212
+ function latestTurnOf(events) {
213
+ let latest = null;
214
+ for (const item of events) {
215
+ const event = item && item.event ? item.event : item;
216
+ const turn = turnOfEvent(event);
217
+ if (turn !== undefined) latest = turn;
218
+ }
219
+ return latest;
220
+ }
221
+
222
+ /**
223
+ * 历史事件 → 运行视图;这一轮在窗口里一条事件都没有时返回 null(由调用方回 404)。
224
+ */
225
+ function runTimelineFromEvents(events, { sessionId, turn = null }) {
226
+ const target = typeof turn === 'number' ? turn : latestTurnOf(events);
227
+ if (target === null) return null;
228
+ const entries = stepsFromEvents(events, target);
229
+ const meta = turnMetaOf(events, target);
230
+ // 窗口里既没有这一轮的步、也没有它的起止:说明这一轮已经在窗口之外了,别回一份空壳。
231
+ if (entries.length === 0 && meta.startedAt === undefined && meta.endedAt === undefined) return null;
232
+ return buildRunTimeline({ sessionId, turn: target, entries, ...meta });
233
+ }
234
+
235
+ function intParam(url, name) {
236
+ const raw = url.searchParams.get(name);
237
+ if (raw === null || raw === '') return null;
238
+ if (!/^\d+$/.test(raw)) return null;
239
+ const value = Number(raw);
240
+ return Number.isSafeInteger(value) ? value : null;
241
+ }
242
+
243
+ /** 宿主错误 → HTTP 码(与 `session-step` 同一套口径)。 */
244
+ function historyStatus(error) {
245
+ switch (error && error.code) {
246
+ case 'bad-request': return 400;
247
+ case 'session-not-found':
248
+ case 'subagent-not-found': return 404;
249
+ case 'subagent-unauthorized': return 403;
250
+ case 'host-unavailable': return 503;
251
+ default: return 502;
252
+ }
253
+ }
254
+
255
+ /**
256
+ * `GET /api/mobile/v1/session/run-timeline?sessionId=…&turn=…`(token)。
257
+ *
258
+ * 只读:先看还在跑的那一轮的直播副本,没有再按轮回拉一小窗历史。**不新增任何读屏 / 截屏 /
259
+ * 执行能力** —— 它读的就是对话页本来就能看到的那些事件与步骤。
260
+ */
261
+ async function handleRunTimeline(ctx, req, res) {
262
+ const url = new URL(req.url, 'http://x');
263
+ const sessionId = url.searchParams.get('sessionId');
264
+ if (!sessionId) return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '缺少 sessionId' } });
265
+ const turn = intParam(url, 'turn');
266
+
267
+ const liveEntries = liveStepsOf(ctx, sessionId);
268
+ const liveTurn = liveStepsTurnOf(ctx, sessionId);
269
+ // 直播副本只代表**当前这一轮**:点了上一轮就老老实实走历史。
270
+ if (liveEntries.length > 0 && (turn === null || liveTurn === null || liveTurn === turn)) {
271
+ return sendJson(res, 200, {
272
+ ok: true,
273
+ run: runTimelineFromLiveSteps({ sessionId, turn: liveTurn, entries: liveEntries }),
274
+ });
275
+ }
276
+
277
+ let value;
278
+ let error;
279
+ try {
280
+ ({ value, error } = unwrap(await callSessions(ctx, 'history', {
281
+ sessionId,
282
+ maxMessages: HISTORY_TURN_MAX_MESSAGES,
283
+ })));
284
+ } catch (thrown) {
285
+ error = thrown && typeof thrown === 'object' ? thrown : { code: 'host-call-failed', message: String(thrown) };
286
+ }
287
+ if (error) {
288
+ return sendJson(res, historyStatus(error), {
289
+ ok: false,
290
+ error: {
291
+ code: typeof error.code === 'string' ? error.code : 'host-call-failed',
292
+ message: typeof error.message === 'string' && error.message ? error.message : '取这一轮的过程失败',
293
+ },
294
+ });
295
+ }
296
+ const events = (value && Array.isArray(value.events)) ? value.events : [];
297
+ const run = runTimelineFromEvents(events, { sessionId, turn });
298
+ if (!run) {
299
+ return sendJson(res, 404, {
300
+ ok: false,
301
+ error: { code: 'run-not-found', message: '这一轮的过程已经不在电脑上了' },
302
+ });
303
+ }
304
+ return sendJson(res, 200, { ok: true, run });
305
+ }
306
+
307
+ module.exports = {
308
+ HISTORY_TURN_MAX_MESSAGES,
309
+ buildRunTimeline,
310
+ stepOfEntry,
311
+ stepsFromEvents,
312
+ turnMetaOf,
313
+ latestTurnOf,
314
+ runTimelineFromLiveSteps,
315
+ runTimelineFromEvents,
316
+ handleRunTimeline,
317
+ };
@@ -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 };