dsh-mobile-plugin 0.5.90 → 0.5.92

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 (48) hide show
  1. package/config/agent-presets/standard/skills/dsh-mobile-kb/SKILL.md +14 -3
  2. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/ipv4.md +38 -0
  3. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/ipv6.md +36 -0
  4. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/selfhost-common.md +44 -0
  5. package/docs/extension-authoring.md +4 -4
  6. package/extension-registry/index.json +5 -1
  7. package/host.js +7 -15
  8. package/lib/client.js +20 -12
  9. package/lib/host-compat.cjs +4 -1
  10. package/lib/host-preset-patches.cjs +40 -0
  11. package/lib/http/routing.js +5 -36
  12. package/lib/impl.js +38 -22
  13. package/lib/index.js +3 -0
  14. package/lib/mobile/agent-presets.js +12 -0
  15. package/lib/mobile/answer-sources.js +3 -2
  16. package/lib/mobile/archive-clean.js +5 -0
  17. package/lib/mobile/history-derive.js +3 -7
  18. package/lib/mobile/host-bridge/shims.js +20 -3
  19. package/lib/mobile/host-bridge.js +30 -1
  20. package/lib/mobile/live-steps.js +4 -3
  21. package/lib/mobile/plugin-self.js +4 -0
  22. package/lib/mobile/relay-control.js +76 -5
  23. package/lib/mobile/session-cache.js +12 -1
  24. package/lib/mobile/session-models.js +1 -1
  25. package/lib/mobile/session-presets.js +5 -2
  26. package/lib/mobile/session-send.js +0 -4
  27. package/lib/mobile/session-step.js +3 -2
  28. package/lib/mobile/stats-collect.cjs +26 -8
  29. package/lib/mobile/step-index.js +4 -3
  30. package/lib/mobile/subagents.js +0 -5
  31. package/lib/mobile/tool-result-state.js +12 -0
  32. package/lib/panel/index.html +27 -28
  33. package/lib/relay/control.js +53 -1
  34. package/lib/relay/lan-discovery.cjs +18 -3
  35. package/lib/relay/lan-proxy.js +22 -2
  36. package/lib/remote/routes.cjs +3 -2
  37. package/lib/routes/control-plane.js +30 -25
  38. package/lib/routes/mobile-api.js +2 -0
  39. package/lib/session-cleanup.cjs +17 -0
  40. package/lib/shared/session-storage.cjs +82 -0
  41. package/lib/shell/first-install.js +102 -0
  42. package/lib/shell/transport-host.js +3 -0
  43. package/lib/shell/updater.js +6 -5
  44. package/lib/sidecar-facade-worker.cjs +2 -0
  45. package/lib/tailcat/wiring.cjs +2 -2
  46. package/lib/update-install.cjs +88 -0
  47. package/package.json +2 -2
  48. package/lib/mobile/ai-recipient.cjs +0 -61
package/lib/impl.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // 身份变更同时迁移三类连接登记,主动重连独立于普通配置同步。
2
+ // apiProxy 兼容服务启动即提供(宿主那份晚到则自动接管),会话列表不再在启动瞬间报缺服务。
2
3
  // 真实监听状态同步总控和穿透,固定入口约束自动换号。
3
4
  // 配置 schema 与投影拆到 lib/relay/config-store.js,装配层只留装配与状态仓外壳(行数兜底)。
4
5
  // 装配移动 API、设备吊销与独立直连生命周期,并向本机面板提供真实上报目的地。
@@ -55,7 +56,7 @@ const hostWeb = require('./mobile/host-web.js')
55
56
  // 否则「撤销全部授权」只清了中转侧,同网设备仍能用旧凭据直连宿主。
56
57
  // 入口按两条盘上布局分别找(嵌在插件包内 / 与插件包同级),见 shared/credentials-entry.js。
57
58
  const credentials = require('./shared/credentials-entry.js').credentialsEntry()
58
- const { createApiProxy, runtimeProvidesApiProxy } = require('./mobile/host-bridge.js')
59
+ const { createApiProxyService, runtimeProvidesApiProxy } = require('./mobile/host-bridge.js')
59
60
  const { installApprovalBridge, setPushNotifier: setApprovalPushNotifier } = require('./mobile/approvals.js')
60
61
  const { installQuestionBridge, setPushNotifier: setQuestionPushNotifier } = require('./mobile/questions.js')
61
62
  const { createPushNotifier } = require('./mobile/push-notify.js')
@@ -200,11 +201,11 @@ function apply(ctx) {
200
201
  // ApiProxyService,由 dsh-web-app 那一层供给),这时再 provide 一次会让整棵树加载
201
202
  // 失败:`service "apiProxy" has been registered at <dsh-mobile-plugin>`,报错挂在
202
203
  // 后到的 api-gateway 入口上,服务器宿主曾因此完全起不来。而且旧运行时的桥也翻译不动
203
- // —— host-bridge.js 是翻译到 0.2.0 的 `ctx.get('typertGateway')` 的。所以按运行时
204
- // 有没有这个包二选一:有就用宿主那份真 apiProxy,没有才装兼容服务。
205
- // (不能靠 `ctx.get('apiProxy')` 判断:宿主是后于本插件装载的,那时它还不在。)
206
- // 这两条二选一,判据同源:0.1.x 宿主自带真 apiProxy(审批帧与回答都还走得通),
207
- // 0.2.x 才需要兼容桥,也才需要审批桥(见 mobile/approvals.js 的文件头)。
204
+ // —— host-bridge.js 是翻译到 0.2.0 的 `ctx.get('typertGateway')` 的。因为兼容服务建在
205
+ // 本代独立作用域里(`ctx.isolate`),和宿主的根作用域互不冲突,所以可以**启动即提供**,
206
+ // 不必再等宿主那份出现:提供的对象优先取宿主的真 apiProxy,取不到才走兼容桥。
207
+ // 判据仍同源:0.1.x 宿主自带真 apiProxy(审批帧与回答都还走得通),0.2.x 才需要兼容桥,
208
+ // 也才需要审批桥(见 mobile/approvals.js 的文件头)。
208
209
  const hasHostApiProxy = runtimeProvidesApiProxy()
209
210
  /** 装配层自己的告警出口:拿不到 logger 也照样往下走,不打日志不是失败。 */
210
211
  const warn = (message, ...rest) => {
@@ -227,31 +228,36 @@ function apply(ctx) {
227
228
  const notifyInteraction = (sessionId, card, hints) => { if (pushNotify) { try { void pushNotify.notifyInteraction(sessionId, card, { ...(hints && typeof hints === 'object' ? hints : {}), title: mirror?.sessionTitleOf?.(sessionId) }) } catch { /* ignore */ } } }
228
229
  setApprovalPushNotifier(notifyInteraction); setQuestionPushNotifier(notifyInteraction)
229
230
  /**
230
- * 装兼容桥与两条帧桥(审批 / 提问)。
231
+ * 取宿主自己那份 apiProxy(旧运行时)。新版宿主上没有这个服务,取不到就回 null。
231
232
  *
232
- * 三者都只在「宿主这一代没有真 apiProxy」时才装:旧宿主自带真服务,多 provide 一次会让
233
- * 整棵树加载失败(`service "apiProxy" has been registered at <dsh-mobile-plugin>`)。
234
- * 兼容服务只在本代作用域可见;蓝绿换代时旧代仍在服务,新代也能独立完成装配。
233
+ * 必须判 `typeof hostContext.get === 'function'`:老宿主上的 cordis 未必有 `ctx.get`,
234
+ * 裸调会在定时器回调里抛出去(被进程级错误边界吞掉、进程不死),apiProxy 就再也补不上,
235
+ * 手机侧会永久报「without inject」。本文件其它取宿主服务的地方都这么判。
235
236
  */
236
- const installCompatBridges = () => {
237
- mount('apiProxy 兼容桥', () => ctx.reflect.provide('apiProxy', createApiProxy(ctx)))
237
+ const hostApiProxy = () => {
238
+ try { return typeof hostContext.get === 'function' ? hostContext.get('apiProxy') : null } catch { return null }
239
+ }
240
+ /**
241
+ * apiProxy **启动即提供**;走宿主真服务还是网关兼容桥由 host-bridge 的 createApiProxyService
242
+ * 推迟到调用那一刻决定。插件刚启动 / 刚换代的瞬间被打到也不会读到「还没提供的服务」,不会抛
243
+ * `cannot get property "apiProxy" without inject`(「加载会话列表失败」就是这条)。
244
+ */
245
+ const provideApiProxy = () => mount('apiProxy 兼容桥', () => ctx.reflect.provide('apiProxy', createApiProxyService(ctx, hostApiProxy)))
246
+ /** 两条帧桥(审批 / 提问):旧宿主自带真服务时由它处理、不装;新版宿主才补上。 */
247
+ const installFrameBridges = () => {
238
248
  mount('审批桥', () => ctx.effect(() => installApprovalBridge(ctx), `${name}: host approval bridge`))
239
249
  mount('提问桥', () => ctx.effect(() => installQuestionBridge(ctx), `${name}: host question bridge`))
240
250
  }
241
- if (!hasHostApiProxy) installCompatBridges()
251
+ provideApiProxy()
252
+ if (!hasHostApiProxy) installFrameBridges()
242
253
  else {
243
254
  // 解析到包只说明「宿主可能是旧版」:新版宿主上包名还在、`apiProxy` 服务已经没了
244
- // (2026-11-02 反馈 #11)。先给它一会儿把真服务 provide 出来(旧宿主在本插件装配
245
- // 前后就会挂上),到点还没有就当作新版宿主,自己把兼容桥与两条帧桥装上 —— 否则
246
- // 十几个移动端模块读到的是一个永远不来的服务,手机侧全程静默失败。
255
+ // (2026-11-02 反馈 #11)。给它一会儿把真服务 provide 出来;到点还没有,就按新版宿主
256
+ // 补上两条帧桥(apiProxy 本身上面已经提供,届时自动走兼容桥)。
247
257
  const timer = setTimeout(() => {
248
- const hostProxy = hostContext.get('apiProxy')
249
- if (hostProxy) {
250
- ctx.reflect.provide('apiProxy', hostProxy)
251
- return
252
- }
258
+ if (hostApiProxy()) return
253
259
  warn('等不到宿主的 apiProxy,按新版宿主装配兼容桥')
254
- installCompatBridges()
260
+ installFrameBridges()
255
261
  }, API_PROXY_GRACE_MS)
256
262
  timer.unref?.()
257
263
  ctx.effect(() => () => clearTimeout(timer), `${name}: host apiProxy grace timer`)
@@ -364,6 +370,10 @@ function apply(ctx) {
364
370
  // getPort 依赖上面刚就位的 sidecar/advertisedLanPort,所以放在这里建。
365
371
  let controlHost = null
366
372
  try { controlHost = typeof ctx.get === 'function' ? ctx.get('dshMobileTransportControl') || null : null } catch { controlHost = null }
373
+ // 总控转达的「请自检」要回的那份诊断:实例在移动端路由表里造(同一份内容,不另算一套),
374
+ // 这里先留一个取值器,路由装好之后才接上。
375
+ let relayDiagnosticsOf = null
376
+ const controlDiagnostics = () => (typeof relayDiagnosticsOf === 'function' ? relayDiagnosticsOf() : null)
367
377
  const control = controlHost && controlHost.client ? controlHost.client : createControlClient({
368
378
  state,
369
379
  persist: () => core.saveState(state),
@@ -371,6 +381,7 @@ function apply(ctx) {
371
381
  getHistoryKey: () => core.ensureHistoryKey(state),
372
382
  getRelayConnected: () => relayConnectedOf(),
373
383
  getConnectedRelay: () => { const tunnel = sidecarLifecycle.getSnapshot()?.tunnel; return tunnel?.state === 'connected' ? tunnel.relayUrl || tunnel.route?.url || '' : '' },
384
+ getDiagnostics: controlDiagnostics,
374
385
  log: warn,
375
386
  onIdentityConflict: rotateNow,
376
387
  })
@@ -382,6 +393,7 @@ function apply(ctx) {
382
393
  getHistoryKey: () => core.ensureHistoryKey(state),
383
394
  getRelayConnected: () => relayConnectedOf(),
384
395
  getConnectedRelay: () => { const tunnel = sidecarLifecycle.getSnapshot()?.tunnel; return tunnel?.state === 'connected' ? tunnel.relayUrl || tunnel.route?.url || '' : '' },
396
+ getDiagnostics: controlDiagnostics,
385
397
  onIdentityConflict: rotateNow,
386
398
  })
387
399
  }
@@ -675,6 +687,8 @@ function apply(ctx) {
675
687
  // 核对的「路径 → handler」表,不用在 1000 行装配代码里翻。
676
688
  mount('移动端路由', () => registerMobileRoutes({
677
689
  registerRoute,
690
+ // 同一份诊断的第二个出口(总控转达的「请自检」):拿到实例就接到上面那个取值器上。
691
+ bindRelayControl: (handlers) => { relayDiagnosticsOf = handlers && typeof handlers.diagnostics === 'function' ? handlers.diagnostics : null },
678
692
  remoteComputers,
679
693
  // 直连隧道:已配对的手机走这条拿到自己的入口地址,不用重新扫码。
680
694
  tailcat,
@@ -743,6 +757,8 @@ function apply(ctx) {
743
757
  getControl: () => control.snapshot(),
744
758
  syncControl: () => control.sync(),
745
759
  controlAddresses: () => control.addresses(),
760
+ // 让「立即同步」在电脑端把总控存的那份也解开一并回给手机(见 relay-control.handleControlSync)。
761
+ getHistoryKey,
746
762
  },
747
763
  }))
748
764
  mount('服务同步', () => ctx.effect(() => {
package/lib/index.js CHANGED
@@ -31,6 +31,7 @@ import { installedPackageDir, installedVersion, profileNodeModules, snapshotRunn
31
31
  import { createDeviceOta } from './shell/device-ota.js'
32
32
  import { installHostHalf } from './shell/half-route.js'
33
33
  import { installTransportHosts } from './shell/transport-host.js'
34
+ import { firstInstallNeedsRestart } from './shell/first-install.js'
34
35
 
35
36
  export const name = 'dsh-mobile-plugin'
36
37
  // 外壳同样只等 `webServer`:它不读 `sessions`,多注一个只是多一种「整行 pending」的理由。
@@ -203,6 +204,8 @@ export function apply(ctx) {
203
204
  marketResult: updateState.result,
204
205
  lastApply: updateState.lastApply,
205
206
  appliedAt: updateState.appliedAt,
207
+ /** 第一次装进一台正在跑的 DSH、还没重启过:手机端据此要求重启一次(见 shell/first-install.js)。 */
208
+ firstInstallPendingRestart: firstInstallNeedsRestart(),
206
209
  }),
207
210
  check,
208
211
  apply: applyUpdate,
@@ -1,3 +1,4 @@
1
+ // 默认预设写入前拒绝激活失败的条目,并保留宿主诊断原因。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -177,6 +178,17 @@ async function handleAgentPresetDefault(ctx, req, res) {
177
178
  },
178
179
  });
179
180
  }
181
+ const reason = typeof row.broken === 'string' && row.broken.trim() ? row.broken : undefined;
182
+ if (row.broken === true || reason !== undefined) {
183
+ return sendJson(res, 400, {
184
+ ok: false,
185
+ error: {
186
+ code: 'agent-preset-invalid',
187
+ message: '这个 Agent 预设加载失败,不能设为默认',
188
+ details: { agentPreset: id.value, ...(reason === undefined ? {} : { reason }) },
189
+ },
190
+ });
191
+ }
180
192
  // 已经是默认档就不再写:settings.mutate 一次就推进一次 revision,白写等于让别处正在
181
193
  // 改设置的人撞上冲突。
182
194
  if (row.isDefault === true) return sendJson(res, 200, { ok: true, agentPreset: id.value });
@@ -1,3 +1,4 @@
1
+ // 回答来源与实时、历史步骤共用工具结果状态。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -30,6 +31,7 @@ const { parseArgs } = require('./step-index.js');
30
31
  const { liveStepOf, liveStepsOf, liveStepsTurnOf } = require('./live-steps.js');
31
32
  const { readTurnEvents } = require('./session-changes.js');
32
33
  const { resultCallId, successfulResult } = require('./turn-facts.js');
34
+ const { toolResultState } = require('./tool-result-state.js');
33
35
 
34
36
  /** 来源条数的极端兜底:一轮读到的材料照单全出,这里只防回包被几百份材料撑爆。 */
35
37
  const MAX_SOURCES = 60;
@@ -134,8 +136,7 @@ function stepsByTurnOf(events) {
134
136
  if (event?.type !== 'tool/result') continue;
135
137
  const id = resultCallId(event);
136
138
  if (!id) continue;
137
- const interrupted = event.data?.error?.code === 'interrupted';
138
- results.set(id, successfulResult(event) ? 'ok' : interrupted ? 'stopped' : 'error');
139
+ results.set(id, toolResultState({ isError: !successfulResult(event), code: event.data?.error?.code }));
139
140
  }
140
141
  const push = (turn, entry) => {
141
142
  if (!byTurn.has(turn)) {
@@ -1,3 +1,4 @@
1
+ // 归档清理在确认 JSONL 路由后才入队,SQLite 失败沿既有错误响应返回。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -18,6 +19,7 @@ const { invalidateSessionList } = require('./sessions.js');
18
19
  const { unwrap } = require('./envelope.js');
19
20
  const { collectStats, DELETING_COLLECT_BUDGET_MS } = require('./stats-collect.cjs');
20
21
  const { queueArchivedClearIds } = require('../session-cleanup.cjs');
22
+ const { assertSessionCleanupSupported, assertSessionCleanupStillJsonl } = require('../shared/session-storage.cjs');
21
23
 
22
24
  /**
23
25
  * 清理前这次补采的预算。
@@ -53,6 +55,8 @@ async function handleClearArchived(ctx, req, res) {
53
55
  const archivedIds = Array.isArray(workspaceResponse.value?.archivedSessionIds) ? workspaceResponse.value.archivedSessionIds : [];
54
56
  const selected = archivedIds.filter((id) => typeof id === 'string' && id);
55
57
  if (selected.length === 0) return { status: 200, body: { ok: true, deleted: 0 } };
58
+ const storageFailure = (error) => ({ status: 409, body: { ok: false, error: { code: error.code || 'session-cleanup-unsupported', message: error.message } } });
59
+ try { await assertSessionCleanupSupported(ctx, selected); } catch (error) { return storageFailure(error); }
56
60
  // 清理之前先把这批会话的用量最后采一次:之后再读它们的统计就没了(日志要删),
57
61
  // 而统计账本要保留历史 —— 漏掉这一刀,最后一段用量会凭空消失。
58
62
  // 采不上不挡清理:统计偏旧好过用户点不动这个按钮。
@@ -66,6 +70,7 @@ async function handleClearArchived(ctx, req, res) {
66
70
  } catch {
67
71
  /* 旁路 */
68
72
  }
73
+ try { await assertSessionCleanupStillJsonl(ctx, selected); } catch (error) { return storageFailure(error); }
69
74
  // 排不进队列就整次失败(路由回 500):回「已清理」却没排上,重启之后它们原样回来。
70
75
  queueArchivedClearIds(selected);
71
76
  // 宿主那份快照可能还带着它们,先在本进程压住:手机列表与归档列表立刻看不到。
@@ -1,3 +1,4 @@
1
+ // 历史工具卡、过程清单和补丁共用工具结果状态。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -246,7 +247,7 @@ function toolResultPatchesFor(events, items, options = {}) {
246
247
  }
247
248
  }
248
249
  return [...buildToolResultMap(events).entries()].map(([callId, result]) => {
249
- const state = result.isError ? (result.code === 'interrupted' ? 'stopped' : 'error') : 'ok';
250
+ const state = toolStepState(result);
250
251
  if (!bodies || delivered.has(callId)) return { callId, state };
251
252
  return {
252
253
  callId,
@@ -289,12 +290,7 @@ function parseBlocks(blocks, toolResults) {
289
290
  if (result) {
290
291
  output = result.output;
291
292
  images = result.images;
292
- // 对齐桌面 toolRowModel 状态派生:error.code === 'interrupted' → stopped, isError → error, ok
293
- if (result.isError) {
294
- state = result.code === 'interrupted' ? 'stopped' : 'error';
295
- } else {
296
- state = 'ok';
297
- }
293
+ state = toolStepState(result);
298
294
  }
299
295
  }
300
296
  out.push({
@@ -1,3 +1,4 @@
1
+ // 工作区快照读取已激活的宿主登记服务,缺服务时才取 Remote 跟随流。
1
2
  // 子代理目录保留 rc.5 名字与关系,根可用性由已验证的 catalog 创建链决定。
2
3
  'use strict';
3
4
  /** 没有 1:1 端点、需要跨端点合成或翻译的几处(翻页游标、模型目录、跟随流、投影基线)。 */
@@ -117,13 +118,29 @@ async function modelCatalog(ctx, payload, signal) {
117
118
  }
118
119
 
119
120
  /**
120
- * `workspace.list` → `workspace.follow` 的首帧 baseline。
121
+ * `workspace.list` 读取 Host 的完整工作区投影,缺登记服务时取 `workspace.follow` 首帧。
121
122
  *
122
- * 0.2.0 的 workspace 只有 follow(流),没有一次性 list;但它的 baseline 值恰好就是
123
- * 旧 list 的返回体(items + archivedSessionIds + pinnedSessionIds),所以取首帧即可。
123
+ * `ctx.get` 默认只返回已激活的服务,登记服务完成持久化加载与历史引导后才可读。
124
+ * 字段与宿主 WorkspaceFeed.baseline / workspaceView 一致,不依赖另行挂载的 Remote controller。
124
125
  */
125
126
  async function workspaceListViaFollow(ctx, signal) {
126
127
  try {
128
+ if (signal) signal.throwIfAborted();
129
+ const registry = ctx.get && ctx.get('workspaceRegistry');
130
+ if (registry) {
131
+ return ok({
132
+ items: registry.list().map(workspace => ({
133
+ workspaceId: workspace.id,
134
+ path: workspace.path,
135
+ title: workspace.title,
136
+ sessionIds: [...workspace.sessionIds],
137
+ createdAt: workspace.createdAt,
138
+ updatedAt: workspace.updatedAt,
139
+ })),
140
+ archivedSessionIds: [...registry.archivedSessionIds],
141
+ pinnedSessionIds: [...registry.pinnedSessionIds],
142
+ });
143
+ }
127
144
  const frames = await openStream(ctx, 'workspace', 'follow', {}, deadline(signal, SYNTHETIC_DEADLINE_MS));
128
145
  for await (const frame of frames) {
129
146
  if (frame && frame.type === 'baseline' && frame.value) return ok(frame.value);
@@ -57,6 +57,35 @@ function createApiProxy(ctx) {
57
57
  };
58
58
  }
59
59
 
60
+ /**
61
+ * apiProxy 服务本体:**启动即提供**、方法被调用时才决定走哪条路——
62
+ * 宿主自己的真服务在(旧运行时)就用它,不在(新运行时)就用上面那份网关兼容桥。
63
+ *
64
+ * 为什么要这样推迟判据:宿主的服务可能晚于本插件出现,而 App 打开后第一批接口
65
+ * (会话列表)随时可能打进来。若在服务尚未提供时读 `ctx.apiProxy`,cordis 会抛
66
+ * `cannot get property "apiProxy" without inject`——手机侧就是「加载会话列表失败」。
67
+ * 返回的代理让这个空档不存在:先有个可用对象,宿主那份一出现,下一次调用自动接上。
68
+ *
69
+ * @param {object} ctx 本代隔离上下文
70
+ * @param {() => object|null} hostProxyOf 取宿主真服务的取值器(取不到返回 null)
71
+ */
72
+ function createApiProxyService(ctx, hostProxyOf) {
73
+ const compat = createApiProxy(ctx);
74
+ return new Proxy(compat, {
75
+ get(target, prop, receiver) {
76
+ if (typeof prop !== 'symbol') {
77
+ const host = hostProxyOf();
78
+ if (host && prop in host) return host[prop];
79
+ }
80
+ return Reflect.get(target, prop, receiver);
81
+ },
82
+ has(target, prop) {
83
+ const host = hostProxyOf();
84
+ return (host != null && prop in host) || prop in target;
85
+ },
86
+ });
87
+ }
88
+
60
89
  /** 包存在时先等宿主提供旧协议服务,包缺席时直接使用网关兼容桥。 */
61
90
  function runtimeProvidesApiProxy() {
62
91
  try {
@@ -67,4 +96,4 @@ function runtimeProvidesApiProxy() {
67
96
  }
68
97
  }
69
98
 
70
- module.exports = { createApiProxy, runtimeProvidesApiProxy, UNAVAILABLE };
99
+ module.exports = { createApiProxy, createApiProxyService, runtimeProvidesApiProxy, UNAVAILABLE };
@@ -1,3 +1,4 @@
1
+ // 实时工具清单和详情共用持久化工具结果的状态口径。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -24,6 +25,7 @@ const TEXT_MAX = 200_000;
24
25
 
25
26
  const { liveStepTurnOf, liveStepWriterOf, liveStepSinkOf } = require('./session-cache.js');
26
27
  const { reasoningText, reasoningStepSummary, toolStepSummary } = require('./step-index.js');
28
+ const { toolResultState } = require('./tool-result-state.js');
27
29
  const { createTurnFacts, absorbTurnFact, rebuildTurnFacts, turnFactsSnapshot, turnChangesSnapshot, resultCallId } = require('./turn-facts.js');
28
30
 
29
31
  function bucketOf(ctx) {
@@ -399,12 +401,11 @@ function noteLiveEvent(ctx, sessionId, event, writerId) {
399
401
  .join('');
400
402
  const diffs = data.meta && Array.isArray(data.meta.diffs) ? data.meta.diffs : undefined;
401
403
  const code = data.error && typeof data.error.code === 'string' ? data.error.code : undefined;
402
- // 失败有两种写法:`message.isError` 与 `data.error.code`(宿主两种都发过),任一都算失败。
403
- const failed = isError || code !== undefined;
404
+ const state = toolResultState({ isError: isError || data.error != null, code });
404
405
  turn.tools.set(callId, {
405
406
  ...current,
406
407
  output: output.length > TEXT_MAX ? output.slice(0, TEXT_MAX) : output,
407
- ...(failed ? { error: code === 'interrupted' ? 'stopped' : 'error' } : { error: null }),
408
+ error: state === 'ok' ? null : state,
408
409
  ...(diffs ? { diffs } : {}),
409
410
  });
410
411
  refreshToolStep(turn, callId);
@@ -94,6 +94,8 @@ function snapshot(ctx) {
94
94
  shellChanged: false,
95
95
  autoUpdate: false,
96
96
  autoIntervalMs: null,
97
+ /** 没有外壳就读不到这个标记;按「不用提示」处理。 */
98
+ firstInstallPendingRestart: false,
97
99
  };
98
100
  }
99
101
  let raw = {};
@@ -114,6 +116,8 @@ function snapshot(ctx) {
114
116
  shellChanged: raw.shellChanged === true,
115
117
  autoUpdate: raw.autoUpdate === true,
116
118
  autoIntervalMs: typeof raw.autoIntervalMs === 'number' && Number.isFinite(raw.autoIntervalMs) ? raw.autoIntervalMs : null,
119
+ /** 第一次装进一台正在跑的 DSH、还没重启过:App 据此要求用户回电脑重启一次。 */
120
+ firstInstallPendingRestart: raw.firstInstallPendingRestart === true,
117
121
  };
118
122
  }
119
123
 
@@ -32,6 +32,51 @@ const { probeRelayHealth, relayFailureMessage } = require('../relay/relay-probe.
32
32
  const { canListen } = require('../relay/port-allocator.cjs');
33
33
  const { lanCandidates, publicCandidates, ipv6Candidates, withManualIpv6Candidate } = require('../relay/lan-network.cjs');
34
34
  const { sendJson, readJsonBody } = require('../shared/http-util');
35
+ const WebSocket = require('ws');
36
+ const { controlWsUrl } = require('../relay/control.js');
37
+ const { openHistoryBlob } = require('../mirror/history-blob.cjs');
38
+
39
+ /**
40
+ * 让**电脑自己**去总控取一份「总控此刻存着的地址」并解开(用本机 HK),供「立即同步」直接比。
41
+ *
42
+ * 手机原来是自己连总控取这份——那就得先攥着总控令牌,重开 / 令牌换了就取不到,于是「立即同步」
43
+ * 恰在最需要它的场景失灵。电脑本来就握着令牌和 HK,让它顺手取回来交给手机比,手机就只需要
44
+ * 能连上插件这一件事。
45
+ *
46
+ * 取不到(没开上报 / 没令牌 / 没 HK / 暂离线 / 解不开)一律回 null,由上层如实说「没比成」。
47
+ */
48
+ function queryControlDirectory(url, token, instanceId, historyKey, timeoutMs = 4000) {
49
+ return new Promise((resolve) => {
50
+ if (!url || !token || !instanceId || !historyKey) return resolve(null);
51
+ let settled = false;
52
+ let ws = null;
53
+ const finish = (value) => {
54
+ if (settled) return;
55
+ settled = true;
56
+ clearTimeout(timer);
57
+ try { ws?.close(); } catch { /* 已关 */ }
58
+ resolve(value);
59
+ };
60
+ const timer = setTimeout(() => finish(null), timeoutMs);
61
+ timer.unref?.();
62
+ try {
63
+ const base = controlWsUrl(url);
64
+ ws = new WebSocket(`${base}/ws/app?instanceId=${encodeURIComponent(instanceId)}&token=${encodeURIComponent(token)}`);
65
+ ws.on('open', () => { try { ws.send(JSON.stringify({ type: 'watch' })); } catch { finish(null); } });
66
+ ws.on('message', (raw) => {
67
+ let msg;
68
+ try { msg = JSON.parse(typeof raw === 'string' ? raw : Buffer.from(raw).toString('utf8')); } catch { return; }
69
+ if (msg && msg.type === 'snapshot' && msg.online === false) return finish(null);
70
+ if (!msg || (msg.type !== 'snapshot' && msg.type !== 'update')) return;
71
+ const payload = typeof msg.payload === 'string' ? msg.payload : '';
72
+ if (!payload) return finish(null);
73
+ try { finish(openHistoryBlob(historyKey, 'control', instanceId, payload)); } catch { finish(null); }
74
+ });
75
+ ws.on('error', () => finish(null));
76
+ ws.on('close', () => finish(null));
77
+ } catch { finish(null); }
78
+ });
79
+ }
35
80
 
36
81
  /** 改配置的请求体上限:几个短字符串,4KB 很宽。 */
37
82
  const CONFIG_BODY_MAX = 4 * 1024;
@@ -217,6 +262,7 @@ function createRelayControlHandlers(deps) {
217
262
  getControl = null,
218
263
  syncControl = null,
219
264
  controlAddresses = null,
265
+ getHistoryKey = null,
220
266
  } = deps || {};
221
267
 
222
268
  /**
@@ -638,6 +684,21 @@ function createRelayControlHandlers(deps) {
638
684
  await new Promise((resolve) => setTimeout(resolve, CONTROL_SYNC_POLL_MS));
639
685
  snapshot = getControl() || {};
640
686
  }
687
+ // 让电脑自己把「总控此刻存着的地址」取回来、解开,一并发给手机:手机据此直接比对,
688
+ // 不再需要自己攥着总控令牌(那正是「重开 / 令牌失效就同步不了」的根源)。取不到就 null,
689
+ // 手机回退到老路径(自己连总控),行为不变。
690
+ let stored = null;
691
+ if (snapshot.published === true && snapshot.connected === true && typeof getHistoryKey === 'function') {
692
+ try {
693
+ const historyKey = getHistoryKey() || '';
694
+ const plain = await queryControlDirectory(snapshot.url, snapshot.token, state && state.instanceId, historyKey);
695
+ if (plain && Array.isArray(plain.addresses)) {
696
+ stored = plain.addresses
697
+ .map((item) => ({ kind: typeof item?.kind === 'string' ? item.kind : '', url: String(item?.url || '').trim() }))
698
+ .filter((item) => item.url);
699
+ }
700
+ } catch { stored = null; }
701
+ }
641
702
  sendJson(res, 200, {
642
703
  ok: true,
643
704
  control: {
@@ -646,6 +707,8 @@ function createRelayControlHandlers(deps) {
646
707
  published: snapshot.published === true,
647
708
  },
648
709
  addresses: typeof controlAddresses === 'function' ? controlAddresses() : [],
710
+ // 总控此刻存着的地址明文(电脑解好给手机比的);取不到为 null。
711
+ stored,
649
712
  at: Date.now(),
650
713
  });
651
714
  }
@@ -735,7 +798,9 @@ function createRelayControlHandlers(deps) {
735
798
  }
736
799
 
737
800
  /**
738
- * `GET /api/mobile/v1/relay/diagnostics` —— 只读诊断:故障台账 + 地址候选的端口细节。
801
+ * 只读诊断:故障台账 + 地址候选的端口细节。两张嘴共用这一份 —— 手机上那条链路还通时走
802
+ * `GET /api/mobile/v1/relay/diagnostics`,连不上时由总控转达、经 `lib/relay/control.js`
803
+ * 的 `diagnostics` 出口回给手机。
739
804
  *
740
805
  * 隧道为什么断、局域网为什么没起来,答案在故障台账与端口自检这两处;两条一起给,
741
806
  * 手机上一页就能回答「这台到底怎么了」。
@@ -751,11 +816,10 @@ function createRelayControlHandlers(deps) {
751
816
  * 答不了「插件是哪一版、后台服务重启过几回、镜像还推不推得动」。
752
817
  * **仍然只读、仍然只进不出**:注册密钥、配对码、`lanSecret`、访问 token 一格都不出现。
753
818
  */
754
- async function handleRelayDiagnostics(_ctx, _req, res) {
755
- if (!wired) return unavailable(res);
819
+ function buildDiagnostics() {
756
820
  const snapshot = typeof status === 'function' ? status() : {};
757
821
  const text = (value) => (typeof value === 'string' ? value : '');
758
- sendJson(res, 200, {
822
+ return {
759
823
  ok: true,
760
824
  faults: faultsView(),
761
825
  /** 最近一次「按新配置重建隧道失败」的错误与时间(见上方说明)。 */
@@ -791,7 +855,12 @@ function createRelayControlHandlers(deps) {
791
855
  ok: snapshot?.mirror?.ok === undefined ? null : snapshot.mirror.ok === true,
792
856
  error: text(snapshot?.mirror?.error) || null,
793
857
  },
794
- });
858
+ };
859
+ }
860
+
861
+ async function handleRelayDiagnostics(_ctx, _req, res) {
862
+ if (!wired) return unavailable(res);
863
+ sendJson(res, 200, buildDiagnostics());
795
864
  }
796
865
 
797
866
  return {
@@ -806,6 +875,8 @@ function createRelayControlHandlers(deps) {
806
875
  handleRelayCheckPort,
807
876
  handleRelayProbe,
808
877
  handleRelayDiagnostics,
878
+ // 同一份诊断的第二个出口:总控转达的「请自检」(见 lib/relay/control.js)。
879
+ diagnostics: buildDiagnostics,
809
880
  };
810
881
  }
811
882
 
@@ -1,3 +1,4 @@
1
+ // 会话缓存集中保存按 ctx 隔离的状态,持久化修订随服务身份换代。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -143,12 +144,21 @@ function sessionListResponseState(ctx, deviceKey = 'legacy') {
143
144
  function sessionCleanupStateOf(ctx) {
144
145
  let state = deletedSessionState.get(ctx);
145
146
  if (!state) {
146
- state = { deleted: new Set() };
147
+ state = { deleted: new Set(), persistenceRevision: null };
147
148
  deletedSessionState.set(ctx, state);
148
149
  }
149
150
  return state;
150
151
  }
151
152
 
153
+ /** 会话存储观测状态:修订只在同一持久化服务身份内比较,不写进跨进程账本。 */
154
+ function sessionPersistenceRevisionStateOf(ctx, identity) {
155
+ const state = sessionCleanupStateOf(ctx);
156
+ if (!state.persistenceRevision || state.persistenceRevision.identity !== identity) {
157
+ state.persistenceRevision = { identity, sessions: new Map() };
158
+ }
159
+ return state.persistenceRevision;
160
+ }
161
+
152
162
  function rememberDeletedSessionIds(ctx, sessionIds) {
153
163
  const state = sessionCleanupStateOf(ctx);
154
164
  for (const sessionId of sessionIds) {
@@ -520,6 +530,7 @@ module.exports = {
520
530
  invalidateSessionList,
521
531
  rememberDeletedSessionIds,
522
532
  deletedSessionIdsOf,
533
+ sessionPersistenceRevisionStateOf,
523
534
  dropSessionListCache,
524
535
  sessionPreviewStateOf,
525
536
  sessionPreviewInFlightStateOf,
@@ -109,7 +109,7 @@ function safeModelsValue(value, language = 'en') {
109
109
  }
110
110
 
111
111
  function modelsBody(value, fetchedAt, language = 'en') {
112
- const result = { ok: true, ...safeModelsValue(value, language), capabilities: { expectedAiRecipient: true } };
112
+ const result = { ok: true, ...safeModelsValue(value, language) };
113
113
  const revision = result.revision;
114
114
  result.meta = {
115
115
  ...(result.meta && typeof result.meta === 'object' ? result.meta : {}),
@@ -1,3 +1,4 @@
1
+ // 预设清单保留宿主的异常诊断字符串,兼容旧版布尔状态。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -37,13 +38,15 @@ async function handleAgentPresets(ctx, req, res) {
37
38
  isDefault: item.isDefault === true,
38
39
  ...(typeof item.name === 'string' && item.name ? { name: item.name } : {}),
39
40
  ...(typeof item.description === 'string' && item.description ? { description: item.description } : {}),
40
- ...(item.broken === true ? { broken: true } : {}),
41
+ ...(typeof item.broken === 'string' && item.broken.trim()
42
+ ? { broken: item.broken }
43
+ : item.broken === true ? { broken: true } : {}),
41
44
  });
42
45
  }
43
46
  const body = {
44
47
  ok: true,
45
48
  presets,
46
- // 与条目内的 isDefault / broken 同口径:宿主只该给布尔,非布尔一律当 false,
49
+ // authorable / hasDocument 与 isDefault 只认布尔;broken 另有诊断字符串契约,
47
50
  // 不让 'yes' / 1 这种值被 App 当成「可以自己写预设」。
48
51
  authorable: value != null && value.authorable === true,
49
52
  hasDocument: value != null && value.hasDocument === true,
@@ -31,7 +31,6 @@ const { promptErrorObject, MODEL_UNAVAILABLE_ERROR } = require('./history-derive
31
31
  const { withIdempotency, requestIdOf } = require('./idempotency.js');
32
32
  const { invoke, UNAVAILABLE: GATEWAY_UNAVAILABLE } = require('./host-bridge/transport.js');
33
33
  const { selectSessionModel } = require('./host-bridge/session-model.js');
34
- const { expectedAiRecipientError } = require('./ai-recipient.cjs');
35
34
  const { recordSessionRead } = require('./session-last-turn.js');
36
35
  const { imageSizeOf } = require('./local-images.js');
37
36
  const attachmentStore = require('./attachment-store.js');
@@ -199,9 +198,6 @@ async function handleSend(ctx, req, res) {
199
198
  }
200
199
  }
201
200
 
202
- const recipientError = await expectedAiRecipientError(ctx, { sessionId: body.sessionId, expected: body.expectedAiRecipient, selection: modelSelection });
203
- if (recipientError) return sendJson(res, 400, { ok: false, error: recipientError });
204
-
205
201
  let promptResponse;
206
202
  try {
207
203
  promptResponse = await promptOnce(ctx, typeof body.clientMessageId === 'string' ? body.clientMessageId : '', {
@@ -1,4 +1,4 @@
1
- // 按步骤定位历史详情,并将连接取消传入所有回拉窗口。
1
+ // 按步骤定位详情、透传连接取消,并与历史清单共用工具状态。
2
2
  'use strict';
3
3
 
4
4
  /**
@@ -23,6 +23,7 @@ const { callSessions } = require('./rpc.js');
23
23
  const { requestSignal } = require('../shared/fresh-request');
24
24
  const { liveStepOf } = require('./live-steps.js');
25
25
  const { reasoningText, textOfParts } = require('./step-index.js');
26
+ const { toolResultState } = require('./tool-result-state.js');
26
27
 
27
28
  /** 详情单段文本的上限(参数 / 输出 / 思考全文各自适用)。 */
28
29
  const DETAIL_MAX_CHARS = 200_000;
@@ -155,7 +156,7 @@ async function historyStep(ctx, { sessionId, kind, callId, seq, index, resultSeq
155
156
  const failed = (envelope ? envelope.isError === true : false) || (message && message.isError === true);
156
157
  const code = result.data && result.data.error && typeof result.data.error.code === 'string'
157
158
  ? result.data.error.code : undefined;
158
- state = failed ? (code === 'interrupted' ? 'stopped' : 'error') : 'ok';
159
+ state = toolResultState({ isError: failed || result.data.error != null, code });
159
160
  const text = capText(textOfParts(parts));
160
161
  output = text.text;
161
162
  if (text.truncated) diffs = undefined;