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.
Files changed (42) 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/extension-dev.js +42 -0
  7. package/lib/mobile/history-derive.js +54 -1
  8. package/lib/mobile/model-meta-table.cjs +1 -1
  9. package/lib/mobile/model-meta.js +1 -1
  10. package/lib/mobile/monitor.js +8 -2
  11. package/lib/mobile/notification-prefs.js +2 -2
  12. package/lib/mobile/permissions.js +8 -5
  13. package/lib/mobile/plugin-market.js +103 -4
  14. package/lib/mobile/run-timeline.js +317 -0
  15. package/lib/mobile/session-active.js +66 -0
  16. package/lib/mobile/session-stop-summary.js +122 -0
  17. package/lib/mobile/sessions.js +8 -2
  18. package/lib/mobile/stats-ledger.cjs +45 -37
  19. package/lib/mobile/stop-summary.js +292 -0
  20. package/lib/mobile/third-party-extensions.js +86 -0
  21. package/lib/mobile/tool-result-cache.js +30 -2
  22. package/lib/panel/index.html +15 -15
  23. package/lib/relay/lan-proxy.js +20 -11
  24. package/lib/relay/tunnel.js +28 -12
  25. package/lib/routes/mobile-api.js +25 -19
  26. package/lib/shared/derived-cache.js +121 -0
  27. package/lib/shared/http-util.js +55 -18
  28. package/package.json +1 -2
  29. package/config/agent-presets/supervisor/agent.cordis.yml +0 -237
  30. package/config/agent-presets/supervisor/preset.yml +0 -3
  31. package/lib/mobile/auto-review-log.js +0 -160
  32. package/lib/mobile/knowledge-base.js +0 -481
  33. package/lib/mobile/mail.js +0 -621
  34. package/lib/mobile/model-prices-table.cjs +0 -23
  35. package/lib/mobile/model-prices.cjs +0 -88
  36. package/lib/mobile/supervisor-broadcast.js +0 -503
  37. package/lib/mobile/supervisor-memory/index.js +0 -305
  38. package/lib/mobile/supervisor-runtime/index.js +0 -54
  39. package/lib/mobile/supervisor-runtime/inject.js +0 -218
  40. package/lib/mobile/supervisor-runtime/judgment.js +0 -113
  41. package/lib/mobile/supervisor-tools.js +0 -419
  42. package/lib/mobile/task-ledger.js +0 -381
@@ -143,6 +143,12 @@ const MAP = Object.freeze({
143
143
  // 历史 blob 的实例密钥(HK):已配对设备的按需补发,纯只读。
144
144
  '/api/mobile/v1/history-key': V.VIEW,
145
145
  '/api/mobile/v1/session/step': V.VIEW,
146
+ // 停止后的「本轮交代」:只读这一轮的步骤流、只算展示结构,能力面同 session/step。
147
+ '/api/mobile/v1/session/stop-summary': V.VIEW,
148
+ // 运行时间线:一轮跑过的每一步,只读历史与直播副本现折,不新增任何能力面。
149
+ '/api/mobile/v1/session/run-timeline': V.VIEW,
150
+ // 回答下面的来源行:只从这一轮的工具步里取网址 / 路径 / 查询词,只给指针不带正文。
151
+ '/api/mobile/v1/session/answer-sources': V.VIEW,
146
152
  '/api/mobile/v1/session/delivery': V.VIEW,
147
153
  '/api/mobile/v1/session/head': V.VIEW,
148
154
  '/api/mobile/v1/session/models': V.VIEW,
@@ -160,9 +166,6 @@ const MAP = Object.freeze({
160
166
  '/api/mobile/v1/schedule/catalog': V.VIEW,
161
167
  '/api/mobile/v1/schedule/list': V.VIEW,
162
168
  '/api/mobile/v1/schedule/history': V.VIEW,
163
- '/api/mobile/v1/mail': { GET: V.VIEW, POST: V.CONFIG },
164
- '/api/mobile/v1/mail/status': V.VIEW,
165
- '/api/mobile/v1/mail/draft': V.CONFIG,
166
169
  '/api/mobile/v1/inbox/status': V.VIEW,
167
170
  '/api/mobile/v1/inbox/clear': V.FILES_WRITE,
168
171
  '/api/mobile/v1/inbox/auto': V.CONFIG,
@@ -182,8 +185,6 @@ const MAP = Object.freeze({
182
185
  '/api/mobile/v1/plugins': V.VIEW,
183
186
  '/api/mobile/v1/skills': V.VIEW,
184
187
  '/api/mobile/v1/narration': { GET: V.VIEW, POST: V.FILES_WRITE },
185
- '/api/mobile/v1/supervisor/tasks': { GET: V.VIEW, POST: V.FILES_WRITE },
186
- '/api/mobile/v1/supervisor/knowledge': { GET: V.VIEW, POST: V.FILES_WRITE, DELETE: V.FILES_WRITE },
187
188
  '/api/mobile/v1/extension/cards': V.VIEW,
188
189
  '/api/mobile/v1/extension/card-state': { GET: V.VIEW, POST: V.FILES_WRITE },
189
190
  '/api/mobile/v1/extension/data': V.VIEW,
@@ -209,6 +210,7 @@ const MAP = Object.freeze({
209
210
  // 插件市场只读浏览
210
211
  '/api/mobile/v1/plugin/market': V.VIEW,
211
212
  '/api/mobile/v1/plugin/market/registries': V.VIEW,
213
+ '/api/mobile/v1/plugin/market/detail': V.VIEW,
212
214
  '/api/mobile/v1/plugin/market/inspect': V.VIEW,
213
215
  '/api/mobile/v1/plugin/market/progress': V.VIEW,
214
216
  '/api/mobile/v1/plugin/update/status': V.VIEW,
@@ -335,6 +337,7 @@ const MAP = Object.freeze({
335
337
  '/api/mobile/v1/credentials': { GET: V.VIEW, POST: V.CONFIG },
336
338
  '/api/mobile/v1/plugin/self/auto': V.CONFIG,
337
339
  '/api/mobile/v1/plugin/market/install': V.CONFIG,
340
+ '/api/mobile/v1/plugin/market/remove': V.CONFIG,
338
341
  '/api/mobile/v1/plugin/market/update': V.CONFIG,
339
342
  '/api/mobile/v1/plugin/market/cancel': V.CONFIG,
340
343
  '/api/mobile/v1/plugin/market/enabled': V.CONFIG,
@@ -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,66 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 「这条会话还在跑」的最终判据:自己的主轮在跑,**或者**它派出去的子代理还有在跑的。
5
+ *
6
+ * 宿主只按自己的主轮报 `running`:主对话把正文输出完、`turn/end` 一落,它就报 false,
7
+ * 哪怕派出去的子代理还要跑几十秒。手机侧栏据此把这一行标成「已完成待读」、后台还会弹一条
8
+ * 「跑完了」—— 而那个对话明明还有活没干完。桌面端不看 `running` 翻面,看的是整棵会话树
9
+ * 还有没有活动,所以两侧对同一时刻给出不同答案。
10
+ *
11
+ * 判据只用会话列表本身就有的两格:子会话的 `origin === 'subagent'` + `parentSessionId`,
12
+ * 以及每条会话的 `running`。不去读投影基线(那要多开一条流、3 秒预算,而这里每 10 秒
13
+ * 重建一次列表),也不逐条查子代理目录(一条会话几十个 child,等于每轮几十次往返)。
14
+ *
15
+ * 只往上顶一层是不够的:子代理还能再派子代理,所以整条祖先链都要跟着变「在跑」,
16
+ * 否则「孙代理在跑、父会话显示已完成」又会出现同一个现象。链上有环时停手(宿主数据
17
+ * 异常时宁可少标一条,也不能死循环把列表请求挂住)。
18
+ */
19
+
20
+ /**
21
+ * 会话列表 → 顶过的列表(只有需要改的那几行是新对象,其余原样返回)。
22
+ *
23
+ * @param {unknown} items 宿主 `session.list` 的 items(或插件归一化后的同形数组)
24
+ * @returns {unknown} 同一个数组或一份浅拷贝;形状不对时原样返回
25
+ */
26
+ function withActiveParents(items) {
27
+ if (!Array.isArray(items) || items.length === 0) return items;
28
+
29
+ const parentOf = new Map();
30
+ const runningIds = [];
31
+ for (const item of items) {
32
+ if (!item || typeof item !== 'object') continue;
33
+ const sessionId = typeof item.sessionId === 'string' ? item.sessionId : '';
34
+ if (!sessionId) continue;
35
+ // 只有子代理会带 parentSessionId;普通会话即便带了也不该把别人顶起来。
36
+ if (item.origin === 'subagent' && typeof item.parentSessionId === 'string' && item.parentSessionId) {
37
+ parentOf.set(sessionId, item.parentSessionId);
38
+ }
39
+ if (item.running === true) runningIds.push(sessionId);
40
+ }
41
+ if (parentOf.size === 0 || runningIds.length === 0) return items;
42
+
43
+ const busy = new Set();
44
+ for (const sessionId of runningIds) {
45
+ const seen = new Set([sessionId]);
46
+ let current = sessionId;
47
+ for (;;) {
48
+ const parent = parentOf.get(current);
49
+ if (!parent || seen.has(parent)) break;
50
+ seen.add(parent);
51
+ // 已经标过的祖先,其更上层上一轮也标过了。
52
+ if (busy.has(parent)) break;
53
+ busy.add(parent);
54
+ current = parent;
55
+ }
56
+ }
57
+ if (busy.size === 0) return items;
58
+
59
+ return items.map((item) => {
60
+ if (!item || typeof item !== 'object') return item;
61
+ if (item.running === true || !busy.has(item.sessionId)) return item;
62
+ return { ...item, running: true };
63
+ });
64
+ }
65
+
66
+ module.exports = { withActiveParents };