dsh-mobile-plugin 0.5.34 → 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 (112) hide show
  1. package/lib/impl.js +0 -11
  2. package/lib/mobile/answer-sources.js +223 -0
  3. package/lib/mobile/approval-facts.js +0 -13
  4. package/lib/mobile/approval-memory.js +1 -1
  5. package/lib/mobile/events.js +0 -20
  6. package/lib/mobile/extension-data.js +105 -5
  7. package/lib/mobile/history-derive.js +54 -1
  8. package/lib/mobile/notification-prefs.js +2 -2
  9. package/lib/mobile/permissions.js +13 -24
  10. package/lib/mobile/plugin-market.js +103 -4
  11. package/lib/mobile/run-timeline.js +317 -0
  12. package/lib/mobile/session-send.js +0 -1
  13. package/lib/mobile/session-stop-summary.js +122 -0
  14. package/lib/mobile/stats-ledger.cjs +45 -0
  15. package/lib/mobile/stop-summary.js +146 -0
  16. package/lib/mobile/third-party-extensions.js +86 -0
  17. package/lib/mobile/tool-result-cache.js +30 -2
  18. package/lib/panel/index.html +15 -15
  19. package/lib/relay/lan-proxy.js +20 -11
  20. package/lib/relay/tunnel.js +28 -12
  21. package/lib/routes/mobile-api.js +26 -58
  22. package/lib/shared/derived-cache.js +121 -0
  23. package/lib/shared/http-util.js +55 -18
  24. package/package.json +1 -3
  25. package/assets/pets/README.md +0 -9
  26. package/assets/pets/deepy-whale/attention.gif +0 -0
  27. package/assets/pets/deepy-whale/done.gif +0 -0
  28. package/assets/pets/deepy-whale/error.gif +0 -0
  29. package/assets/pets/deepy-whale/idle.gif +0 -0
  30. package/assets/pets/deepy-whale/pack.json +0 -54
  31. package/assets/pets/deepy-whale/sleeping.gif +0 -0
  32. package/assets/pets/deepy-whale/working-3.gif +0 -0
  33. package/assets/pets/deepy-whale/working.gif +0 -0
  34. package/config/agent-presets/supervisor/agent.cordis.yml +0 -237
  35. package/config/agent-presets/supervisor/preset.yml +0 -3
  36. package/knowledge/apps/alipay.md +0 -30
  37. package/knowledge/apps/android-settings.md +0 -30
  38. package/knowledge/apps/baijiahao.md +0 -30
  39. package/knowledge/apps/bilibili.md +0 -31
  40. package/knowledge/apps/boss-zhipin.md +0 -32
  41. package/knowledge/apps/dedao.md +0 -33
  42. package/knowledge/apps/douyin.md +0 -32
  43. package/knowledge/apps/feishu.md +0 -35
  44. package/knowledge/apps/gmail.md +0 -33
  45. package/knowledge/apps/jike.md +0 -31
  46. package/knowledge/apps/kuaishou.md +0 -34
  47. package/knowledge/apps/linkedin.md +0 -33
  48. package/knowledge/apps/qqmail.md +0 -30
  49. package/knowledge/apps/taobao.md +0 -33
  50. package/knowledge/apps/telegram.md +0 -27
  51. package/knowledge/apps/toutiao.md +0 -32
  52. package/knowledge/apps/uber-eats.md +0 -26
  53. package/knowledge/apps/uber.md +0 -27
  54. package/knowledge/apps/wechat.md +0 -33
  55. package/knowledge/apps/weibo.md +0 -31
  56. package/knowledge/apps/whatsapp.md +0 -27
  57. package/knowledge/apps/x.md +0 -32
  58. package/knowledge/apps/xiaohongshu.md +0 -30
  59. package/knowledge/apps/zhihu.md +0 -31
  60. package/knowledge/sites/bilibili.com/SITE.md +0 -50
  61. package/knowledge/sites/bilibili.com/references/view-fields.md +0 -17
  62. package/knowledge/sites/github.com/SITE.md +0 -51
  63. package/knowledge/sites/github.com/references/repo-fields.md +0 -13
  64. package/knowledge/sites/x.com/SITE.md +0 -47
  65. package/knowledge/sites/xiaohongshu.com/SITE.md +0 -48
  66. package/knowledge/sites/xiaohongshu.com/references/note-fields.md +0 -18
  67. package/knowledge/sites/youtube.com/SITE.md +0 -49
  68. package/knowledge/sites/youtube.com/references/innertube-fields.md +0 -14
  69. package/knowledge/sites/zhihu.com/SITE.md +0 -47
  70. package/knowledge/sites/zhihu.com/references/api-fields.md +0 -21
  71. package/lib/mobile/auto-review-log.js +0 -160
  72. package/lib/mobile/knowledge-base.js +0 -481
  73. package/lib/mobile/mail.js +0 -621
  74. package/lib/mobile/pet-tools.js +0 -261
  75. package/lib/mobile/pets.js +0 -755
  76. package/lib/mobile/phone/access.js +0 -140
  77. package/lib/mobile/phone/binding.js +0 -247
  78. package/lib/mobile/phone/confirm.js +0 -190
  79. package/lib/mobile/phone/evidence.js +0 -228
  80. package/lib/mobile/phone/gate.js +0 -290
  81. package/lib/mobile/phone/grounding.js +0 -314
  82. package/lib/mobile/phone/guard.js +0 -465
  83. package/lib/mobile/phone/guarded.js +0 -86
  84. package/lib/mobile/phone/index.js +0 -114
  85. package/lib/mobile/phone/irreversible.js +0 -226
  86. package/lib/mobile/phone/knowledge-tools.js +0 -665
  87. package/lib/mobile/phone/learn.js +0 -329
  88. package/lib/mobile/phone/pacing.js +0 -173
  89. package/lib/mobile/phone/redact.js +0 -237
  90. package/lib/mobile/phone/risk.js +0 -95
  91. package/lib/mobile/phone/route-extract.js +0 -460
  92. package/lib/mobile/phone/route-hint.js +0 -164
  93. package/lib/mobile/phone/routes-memory.js +0 -133
  94. package/lib/mobile/phone/routes.js +0 -287
  95. package/lib/mobile/phone/service.js +0 -520
  96. package/lib/mobile/phone/site-commands.js +0 -271
  97. package/lib/mobile/phone/skill-recall.js +0 -246
  98. package/lib/mobile/phone/skill-routes.js +0 -106
  99. package/lib/mobile/phone/step-summary.js +0 -201
  100. package/lib/mobile/phone/stop-summary.js +0 -235
  101. package/lib/mobile/phone/tool-groups.js +0 -125
  102. package/lib/mobile/phone/tools.js +0 -2590
  103. package/lib/mobile/phone/untrusted.js +0 -65
  104. package/lib/mobile/phone-knowledge.js +0 -317
  105. package/lib/mobile/route-store.js +0 -266
  106. package/lib/mobile/supervisor-broadcast.js +0 -503
  107. package/lib/mobile/supervisor-memory/index.js +0 -305
  108. package/lib/mobile/supervisor-runtime/index.js +0 -54
  109. package/lib/mobile/supervisor-runtime/inject.js +0 -218
  110. package/lib/mobile/supervisor-runtime/judgment.js +0 -113
  111. package/lib/mobile/supervisor-tools.js +0 -419
  112. 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,16 +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
- '/api/mobile/v1/phone/status': V.VIEW,
167
- '/api/mobile/v1/phone/devices': V.VIEW,
168
- '/api/mobile/v1/phone/knowledge': V.VIEW,
169
- // 「学成的手机操作路线」草稿清单:只读账本,收下 / 丢弃是下面那条。
170
- '/api/mobile/v1/phone/skill/routes': V.VIEW,
171
- '/api/mobile/v1/phone/app-access': { GET: V.VIEW, POST: V.OPERATE },
172
- '/api/mobile/v1/phone/pacing': V.OPERATE,
173
169
  '/api/mobile/v1/inbox/status': V.VIEW,
174
170
  '/api/mobile/v1/inbox/clear': V.FILES_WRITE,
175
171
  '/api/mobile/v1/inbox/auto': V.CONFIG,
@@ -189,8 +185,6 @@ const MAP = Object.freeze({
189
185
  '/api/mobile/v1/plugins': V.VIEW,
190
186
  '/api/mobile/v1/skills': V.VIEW,
191
187
  '/api/mobile/v1/narration': { GET: V.VIEW, POST: V.FILES_WRITE },
192
- '/api/mobile/v1/supervisor/tasks': { GET: V.VIEW, POST: V.FILES_WRITE },
193
- '/api/mobile/v1/supervisor/knowledge': { GET: V.VIEW, POST: V.FILES_WRITE, DELETE: V.FILES_WRITE },
194
188
  '/api/mobile/v1/extension/cards': V.VIEW,
195
189
  '/api/mobile/v1/extension/card-state': { GET: V.VIEW, POST: V.FILES_WRITE },
196
190
  '/api/mobile/v1/extension/data': V.VIEW,
@@ -216,6 +210,7 @@ const MAP = Object.freeze({
216
210
  // 插件市场只读浏览
217
211
  '/api/mobile/v1/plugin/market': V.VIEW,
218
212
  '/api/mobile/v1/plugin/market/registries': V.VIEW,
213
+ '/api/mobile/v1/plugin/market/detail': V.VIEW,
219
214
  '/api/mobile/v1/plugin/market/inspect': V.VIEW,
220
215
  '/api/mobile/v1/plugin/market/progress': V.VIEW,
221
216
  '/api/mobile/v1/plugin/update/status': V.VIEW,
@@ -281,15 +276,10 @@ const MAP = Object.freeze({
281
276
  '/api/mobile/v1/approval/rules': { GET: V.VIEW, POST: V.APPROVE },
282
277
  '/api/mobile/v1/approval/rules/revoke': V.APPROVE,
283
278
 
284
- // ── operate:让 AI 操作手机 ────────────────────────────────────
285
- '/api/mobile/v1/phone/unbind': V.OPERATE,
286
- // 两条 **WebSocket 升级**路由。它们不经过 `guarded`(升级请求要的是一次拒绝或一次握手,
287
- // 不是 JSON 信封),所以校验写在各自的服务里,用的仍是这张表(见 phone/service.js 的
288
- // `handleUpgrade` 与 relay/preview.js 的 `handleUpgrade`)。登记在这里,是为了让
289
- // 「每条注册的路由都被权限表覆盖」那条守卫能看见它们。
290
- //
291
- // 动作通道:手机在这条连接上收执行动作,等于「这台手机能被 AI 操作」,需要 operate。
292
- '/api/mobile/v1/phone/control': V.OPERATE,
279
+ // ── 预览:WebSocket 升级路由 ─────────────────────────────────
280
+ // 它不经过 `guarded`(升级请求要的是一次拒绝或一次握手,不是 JSON 信封),校验写在
281
+ // relay/preview.js 的 `handleUpgrade` 里,用的仍是这张表。登记在这里,是为了让
282
+ // 「每条注册的路由都被权限表覆盖」那条守卫能看见它。
293
283
  // 内置浏览器预览:手机点一个 localhost 链接、把这台电脑上的某个本地端口接进内置浏览器。
294
284
  // 它是**看**(用户点开一页),归 view:三档里只读与可答审批都带 view,行为不变;真正被
295
285
  // 这条关掉的是 `permissions: []` 那种「明确什么都不给」的设备 —— 它们原来也能连上来。
@@ -319,8 +309,6 @@ const MAP = Object.freeze({
319
309
  '/api/mobile/v1/git/commit': V.FILES_WRITE,
320
310
  '/api/mobile/v1/git/checkout': V.FILES_WRITE,
321
311
  '/api/mobile/v1/git/push': V.FILES_WRITE,
322
- // 收下 / 丢弃一条学成的路线:会往技能目录里落文件,与 skill/create 同一档。
323
- '/api/mobile/v1/phone/skill/keep': V.FILES_WRITE,
324
312
  '/api/mobile/v1/skill/create': V.FILES_WRITE,
325
313
  '/api/mobile/v1/skill/save': V.FILES_WRITE,
326
314
  '/api/mobile/v1/skill/delete': V.FILES_WRITE,
@@ -349,6 +337,7 @@ const MAP = Object.freeze({
349
337
  '/api/mobile/v1/credentials': { GET: V.VIEW, POST: V.CONFIG },
350
338
  '/api/mobile/v1/plugin/self/auto': V.CONFIG,
351
339
  '/api/mobile/v1/plugin/market/install': V.CONFIG,
340
+ '/api/mobile/v1/plugin/market/remove': V.CONFIG,
352
341
  '/api/mobile/v1/plugin/market/update': V.CONFIG,
353
342
  '/api/mobile/v1/plugin/market/cancel': V.CONFIG,
354
343
  '/api/mobile/v1/plugin/market/enabled': V.CONFIG,
@@ -400,7 +389,7 @@ function resolvePermission(path, method = 'GET') {
400
389
  }
401
390
 
402
391
  /**
403
- * 升级路由(`/phone/control`、`/preview`)用的权限判定三件套。
392
+ * 预览这条 WebSocket 升级路由用的权限判定三件套。
404
393
  *
405
394
  * 这两条是 WebSocket 升级,不过 `guarded`(升级请求要的是一次拒绝或一次握手,不是 JSON
406
395
  * 信封),但「谁都能连」不是选项。所以把 `guarded` 里同一套判定(同一个 `resolve` /
@@ -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
+ };
@@ -170,7 +170,6 @@ async function handleSend(ctx, req, res) {
170
170
  if (normalized.code === MODEL_UNAVAILABLE_ERROR.code) invalidateSessionModels(ctx, req, body.sessionId);
171
171
  return sendJson(res, 400, { ok: false, error: continuation ? continuationError(normalized) : normalized });
172
172
  }
173
- require('./phone/binding.js').noteRequestSender(req, body.sessionId);
174
173
  sendJson(res, 200, { ok: true, accepted: true });
175
174
  }
176
175