dsh-mobile-plugin 0.5.47 → 0.5.49

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.
@@ -109,20 +109,23 @@ function sendFailure(res, error) {
109
109
  }
110
110
 
111
111
  /**
112
- * POST /api/mobile/v1/file/create
113
- * body { path(绝对), sessionId?, content?, overwrite? }
112
+ * 一段正文落到**已校验的落点**上:`file/create` 与 `session/write-body` 共用这一段。
113
+ *
114
+ * 两处共用是因为这里只有一份正确顺序 —— 按项目排队 → 判重 / 拒符号链接与目录 →
115
+ * 落盘 → 出包。抄第二份迟早会出现「一条路由拒软链、另一条顺着写」这类只在一边成立的
116
+ * 边界,而两条路由的落点判定本来就是同一份 `preparePath`。
117
+ *
118
+ * @param {{ target: string, roots: string[] }} prepared `preparePath` 的结果
119
+ * @param {object} body 请求体(只读 `overwrite`)
120
+ * @param {string} content 正文
121
+ * @param {object} res node:http ServerResponse
122
+ * @param {Record<string, unknown>} [extra] 回包里额外带的格子(写路由自己的字段)
114
123
  */
115
- async function handleFileCreate(ctx, req, res) {
116
- const body = (await readJsonBody(req)) || {};
117
- const prepared = await preparePath(ctx, body, res);
118
- if (!prepared) return;
124
+ async function writeContentAt(prepared, body, content, res, extra) {
119
125
  const { target, roots } = prepared;
120
-
121
- const content = typeof body.content === 'string' ? body.content : (body.content == null ? '' : null);
122
- if (content === null) return sendError(res, 400, 'invalid-content', 'content 必须是字符串');
123
126
  const bytes = Buffer.byteLength(content, 'utf8');
124
127
  if (bytes > FILE_MAX_CONTENT_BYTES) {
125
- return sendError(res, 413, 'too-large', '文件太大,手机这边不支持一次性新建这么大的文件');
128
+ return sendError(res, 413, 'too-large', '文件太大,手机这边不支持一次性写这么大的文件');
126
129
  }
127
130
 
128
131
  // 落盘这一段按项目串行:判重与写入必须在同一个独占窗口里,否则两条并发请求会都判「不存在」。
@@ -152,10 +155,25 @@ async function handleFileCreate(ctx, req, res) {
152
155
  created: !existing,
153
156
  overwritten: !!existing,
154
157
  bytes,
158
+ ...extra,
155
159
  });
156
160
  });
157
161
  }
158
162
 
163
+ /**
164
+ * POST /api/mobile/v1/file/create
165
+ * body { path(绝对), sessionId?, content?, overwrite? }
166
+ */
167
+ async function handleFileCreate(ctx, req, res) {
168
+ const body = (await readJsonBody(req)) || {};
169
+ const prepared = await preparePath(ctx, body, res);
170
+ if (!prepared) return;
171
+
172
+ const content = typeof body.content === 'string' ? body.content : (body.content == null ? '' : null);
173
+ if (content === null) return sendError(res, 400, 'invalid-content', 'content 必须是字符串');
174
+ await writeContentAt(prepared, body, content, res);
175
+ }
176
+
159
177
  /**
160
178
  * POST /api/mobile/v1/file/delete
161
179
  * body { path(绝对), sessionId? }
@@ -259,6 +277,11 @@ module.exports = {
259
277
  FILE_NAME_MAX,
260
278
  FILE_MAX_CONTENT_BYTES,
261
279
  validSegment,
280
+ // 「一段正文落成文件」那条路由(`session-write-body.js`)与 `file/create` 共用这三份:
281
+ // 落点判定、错误体、带内容写入。抄第二份就等于让两条路各有一套允许区判据。
282
+ preparePath,
283
+ sendError,
284
+ writeContentAt,
262
285
  handleFileCreate,
263
286
  handleFileDelete,
264
287
  handleFileRename,
@@ -9,7 +9,8 @@
9
9
  *
10
10
  * 三条边界:
11
11
  * 1. `path` 必须是绝对路径 —— 这条路由没有可信的解析基准,相对路径直接 400,不去猜谁当基准。
12
- * 判定用的是 resolve 之后的落点,`..` 爬出允许区一律不认(403 `outside-allowed`)。
12
+ * 判定用的是 resolve 之后的落点,并对 `realpath` 之后的物理落点再判一次(堵软链逃逸),
13
+ * `..` 爬出允许区一律不认(403 `outside-allowed`)。
13
14
  * 2. 认出允许区之后的失败分开报:盘上没有 404 `missing`、不是普通文件 400 `not-a-file`、
14
15
  * 超过 512MB 413 `too-large`。码与文案跟 `/session/file` 同一套,App 那边一套分支就够。
15
16
  * 3. 字节流式回写,不在插件进程里缓冲。响应那一半(明文的整份 / 206 一段、协议 v2 的分块
@@ -17,13 +18,19 @@
17
18
  * 必然漂,而漂了的症状是「手机上永远下载中」或「取回来的那段解不开」,没有报错。
18
19
  */
19
20
 
20
- const { stat } = require('node:fs/promises');
21
+ const { stat, realpath } = require('node:fs/promises');
21
22
  const path = require('node:path');
22
23
 
23
24
  const { sendJson, readJsonBody } = require('../shared/http-util');
24
25
  const { allowedRoots, inAllowedZone } = require('./allowed-zone.js');
25
26
  const { sendFileBytes, SESSION_FILE_MAX_BYTES } = require('./session-file.js');
26
27
 
28
+ /** 允许区每个根 realpath 之后的样子;解析不了的根直接跳过(跳过是缩小范围)。 */
29
+ async function realRootsOf(roots) {
30
+ const resolved = await Promise.all(roots.map((root) => realpath(root).catch(() => null)));
31
+ return resolved.filter((root) => typeof root === 'string');
32
+ }
33
+
27
34
  /**
28
35
  * 扩展名 → 内容类型。与 `session-file.js` 那张表逐条相同:两条路给同一个文件必须给出同一个
29
36
  * `content-type`,否则 App 那边「按类型决定怎么预览」的分支会看端点选,等于多一种行为。
@@ -114,9 +121,23 @@ async function handleFileRead(ctx, req, res) {
114
121
  });
115
122
  }
116
123
 
124
+ // 字符串落点在允许区里还不够:工作区里的软链可能指到区外。与写侧(`file-ops.js` 的
125
+ // `preparePath`)同一条判据 —— 按 `realpath` 之后的物理落点再判一次。
126
+ const realTarget = await realpath(target).catch(() => null);
127
+ if (!realTarget) {
128
+ // realpath 失败 = 盘上没有了(或断了):与 stat 失败同一个 404 口子。
129
+ return sendJson(res, 404, { ok: false, error: { code: 'missing', message: '文件已经不在这台电脑上了' } });
130
+ }
131
+ if (!inAllowedZone(await realRootsOf(roots), realTarget)) {
132
+ return sendJson(res, 403, {
133
+ ok: false,
134
+ error: { code: 'outside-allowed', message: '这个文件的物理位置不在能看的范围里(可能经过了符号链接)' },
135
+ });
136
+ }
137
+
117
138
  let info;
118
139
  try {
119
- info = await stat(target);
140
+ info = await stat(realTarget);
120
141
  } catch {
121
142
  return sendJson(res, 404, { ok: false, error: { code: 'missing', message: '文件已经不在这台电脑上了' } });
122
143
  }
@@ -131,15 +152,15 @@ async function handleFileRead(ctx, req, res) {
131
152
  }
132
153
 
133
154
  const header = {
134
- 'content-type': mediaTypeOf(target),
135
- 'content-disposition': dispositionOf(path.basename(target)),
155
+ 'content-type': mediaTypeOf(realTarget),
156
+ 'content-disposition': dispositionOf(path.basename(realTarget)),
136
157
  'cache-control': 'no-store',
137
158
  };
138
159
 
139
160
  // 响应那一半(明文的整份 / 206 一段、协议 v2 的分块信封)与 `/session/file` 是**同一份**
140
161
  // 实现:两条路给同一个文件必须给出同一组头、同一种块形状、同一个起始序号口径。
141
162
  await sendFileBytes(req, res, {
142
- target,
163
+ target: realTarget,
143
164
  size: info.size,
144
165
  header,
145
166
  rawOffset: body && body.offset,
@@ -15,6 +15,7 @@ const { cutAssistantBlock, cutToolResultEvent, createToolNameIndex } = require('
15
15
  const { rememberToolResults, toolResultsFor, toolResultsVersionFor } = require('./tool-result-cache.js');
16
16
  const crypto = require('node:crypto');
17
17
  const { derivedCache } = require('../shared/derived-cache.js');
18
+ const { foldTurnFacts, turnFactsSnapshot } = require('./turn-facts.js');
18
19
 
19
20
  /** 每一轮出过的图(工具结果里的图片块),轮号 → 图。`lookback` 也扫:它才装得下更早那一页。 */
20
21
  function collectTurnImages(entries, lookbackEntries) {
@@ -97,6 +98,11 @@ function toolResultParts(msg) {
97
98
  *
98
99
  * 宽高两格见 `imageDimsOf`:那是「手机能不能在挂载那一帧就占好位置」的前提。
99
100
  *
101
+ * `bytes` 来自宿主附件记账(`attachment.bytes`,宿主 `ImageAttachmentRef` 本来就有这一格):
102
+ * App 的事实条靠它写体积,没有它就只能对内联形状按 base64 长度估。`mediaIds` 是宿主在图片
103
+ * 块上标的「这次生成的批编号」:有就原样透传,手机侧据此把同一次生成的几张认成一组候选;
104
+ * 老宿主不给这一格,手机侧按「这一轮的图算一批」兜底,插件不另造编号。
105
+ *
100
106
  * 两条都要求 mediaType 可读(块上没有就退到 attachment 上的),否则 App 认不出来、
101
107
  * 也没有可显示的动作,返回 null 让调用方丢掉它。
102
108
  */
@@ -112,11 +118,45 @@ function imageEntryOf(block) {
112
118
  ? block.name
113
119
  : (typeof attachment.name === 'string' ? attachment.name : undefined);
114
120
  const dims = imageDimsOf(block, attachment);
115
- if (attachmentId) return { mediaType, ...(name !== undefined ? { name } : {}), ...dims, attachmentId };
116
- if (typeof block.data === 'string' && block.data) return { mediaType, data: block.data, ...(name !== undefined ? { name } : {}), ...dims };
121
+ const bytes = imageBytesOf(block, attachment);
122
+ const mediaIds = imageMediaIdsOf(block, attachment);
123
+ const extra = {
124
+ ...(name !== undefined ? { name } : {}),
125
+ ...dims,
126
+ ...(bytes === undefined ? {} : { bytes }),
127
+ ...(mediaIds.length === 0 ? {} : { mediaIds }),
128
+ };
129
+ if (attachmentId) return { mediaType, ...extra, attachmentId };
130
+ if (typeof block.data === 'string' && block.data) return { mediaType, data: block.data, ...extra };
117
131
  return null;
118
132
  }
119
133
 
134
+ /**
135
+ * 图片的字节数:宿主附件记账里的 `bytes`(块上或 attachment 上都认)。
136
+ *
137
+ * 不是正数的当没有:体积那一格宁可整截不写,也不摆一个「0 B」。
138
+ */
139
+ function imageBytesOf(block, attachment) {
140
+ const pick = (value) => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined);
141
+ return pick(block.bytes) ?? pick(attachment.bytes);
142
+ }
143
+
144
+ /**
145
+ * 这次生成的批编号(宿主在图片块上标的 `mediaIds`):去重后升序,没有就回空数组。
146
+ *
147
+ * **不新造编号**:手机侧对没有批号的图按「这一轮算一批」归组,插件补一个跨轮唯一号只会
148
+ * 让同一轮里的图被拆成多组。
149
+ */
150
+ function imageMediaIdsOf(block, attachment) {
151
+ const source = Array.isArray(block.mediaIds) ? block.mediaIds
152
+ : (Array.isArray(attachment.mediaIds) ? attachment.mediaIds : []);
153
+ const ids = new Set();
154
+ for (const value of source) {
155
+ if (typeof value === 'number' && Number.isFinite(value)) ids.add(value);
156
+ }
157
+ return [...ids].sort((left, right) => left - right);
158
+ }
159
+
120
160
  /**
121
161
  * 图片的原始宽高 —— 宿主的附件里本来就有(`attachment.width` / `attachment.height`)。
122
162
  *
@@ -171,7 +211,7 @@ function buildToolResultMap(events) {
171
211
  const images = toolResultImages(parts);
172
212
  // `seq` 只给「按需取详情」用:手机点开这一步时拿它去回拉那一小窗事件。
173
213
  map.set(src.callId, {
174
- isError,
214
+ isError: isError || kept.data.error != null,
175
215
  code,
176
216
  ...(Number.isSafeInteger(e.seq) ? { seq: e.seq } : {}),
177
217
  ...(output ? { output } : {}),
@@ -275,31 +315,6 @@ function parseBlocks(blocks, toolResults) {
275
315
  return out;
276
316
  }
277
317
 
278
- /**
279
- * 一条消息里 write/edit 成功写过的文件路径。
280
- *
281
- * 参数不下发手机(见 `wire-cut.js`),但「这一轮动过哪些文件」仍要在本机从**原始**块的
282
- * `arguments` 里派生出来:App 拿这份清单解析收尾正文里的行内文件引用。
283
- */
284
- function writtenPaths(content, toolResults) {
285
- if (!Array.isArray(content)) return [];
286
- const out = [];
287
- for (const b of content) {
288
- if (!b || typeof b !== 'object' || b.type !== 'tool-call') continue;
289
- if (b.name !== 'write' && b.name !== 'edit') continue;
290
- const callId = b.id != null ? String(b.id) : undefined;
291
- const result = callId && toolResults ? toolResults.get(callId) : undefined;
292
- if (!result || result.isError) continue;
293
- const raw = typeof b.arguments === 'string' ? b.arguments : (b.arguments != null ? JSON.stringify(b.arguments) : '');
294
- try {
295
- const args = JSON.parse(raw || '{}');
296
- const path = typeof args.path === 'string' ? args.path : typeof args.file_path === 'string' ? args.file_path : null;
297
- if (typeof path === 'string' && path) out.push(path);
298
- } catch { /* 参数不是 JSON:这条调用不算产出,与「没有参数」同处理 */ }
299
- }
300
- return out;
301
- }
302
-
303
318
  /** 从结构块里拼接纯文本(列表预览/标题回退用,仍只取 text 块)。 */
304
319
  function blocksToText(blocks) {
305
320
  return blocks.filter((b) => b.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n');
@@ -581,16 +596,8 @@ function deriveMessages(events, sessionId, lookbackEvents) {
581
596
  if (bucket.length > 0) presentedByTurn.set(data.turn, bucket);
582
597
  }
583
598
 
584
- /**
585
- * 这一轮**被 write / edit 动过**的文件,按轮攒。
586
- *
587
- * 为什么按轮而不是按单条消息:一份文件是一轮里某一步写的,而收尾答复那条消息自己一个
588
- * 写操作都没有 —— 按消息算的话,正文里提到刚写好的文件时那份清单永远是空的。
589
- * 桌面 `dsh-client-ui-deliverables` 的 `selectProducedFiles(owner)` 也是按**整轮**取。
590
- *
591
- * 攒完在循环之后回填:同一轮里先发的消息也要能看到这一轮后几步才写出来的文件。
592
- */
593
- const producedByTurn = new Map();
599
+ // 模型归因、成功产出与净改动和直播同源;原始参数与 diff 只在本机折叠。
600
+ const factsByTurn = foldTurnFacts((lookbackEvents || []).concat(events));
594
601
  const producedItems = [];
595
602
 
596
603
  // 单步计时预扫描:为每条 assistant 消息派生「本轮」的 ttft / decode / 输出 token
@@ -741,10 +748,12 @@ function deriveMessages(events, sessionId, lookbackEvents) {
741
748
  const images = [
742
749
  ...blocks.filter((b) => b.type === 'image'),
743
750
  ...toolImages,
744
- ].map(({ mediaType, data, name, attachmentId, width, height }) => ({
751
+ ].map(({ mediaType, data, name, attachmentId, width, height, bytes, mediaIds }) => ({
745
752
  mediaType,
746
753
  ...(typeof name === 'string' ? { name } : {}),
747
754
  ...(Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0 ? { width, height } : {}),
755
+ ...(typeof bytes === 'number' && Number.isFinite(bytes) && bytes > 0 ? { bytes } : {}),
756
+ ...(Array.isArray(mediaIds) && mediaIds.length > 0 ? { mediaIds } : {}),
748
757
  ...(typeof attachmentId === 'string' && attachmentId ? { attachmentId } : {}),
749
758
  ...(typeof attachmentId === 'string' && attachmentId ? {} : { data }),
750
759
  }));
@@ -781,14 +790,6 @@ function deriveMessages(events, sessionId, lookbackEvents) {
781
790
  time: e.time,
782
791
  ...(turn !== undefined ? { turn } : {}),
783
792
  };
784
- // 本条消息自己写 / 改过的文件:并进**这一轮**的那一份,不单独挂在它自己头上。
785
- // 从原始块的 arguments 算(那些参数不下发手机)。
786
- const ownWrites = writtenPaths(msg.content, toolResults);
787
- if (turn !== undefined && ownWrites.length > 0) {
788
- const bucket = producedByTurn.get(turn) || new Set();
789
- for (const path of ownWrites) bucket.add(path);
790
- producedByTurn.set(turn, bucket);
791
- }
792
793
  // 回填要等循环跑完(这一轮后面几步写的也要算进来),先把这条记下来。
793
794
  if (turn !== undefined) producedItems.push({ item, turn });
794
795
  // 这一轮模型显式声明的交付文件:轮尾那张交付卡的唯一依据(与产出的清单分开)。
@@ -1133,15 +1134,13 @@ function deriveMessages(events, sessionId, lookbackEvents) {
1133
1134
  if (last) last.item.images = images;
1134
1135
  }
1135
1136
  }
1136
- // 产出清单按轮回填:这一轮所有 write / edit 的并集,挂到这一轮每条 assistant 消息上。
1137
- // 挂「整轮」而不是「从写那一刻起」,与桌面 `selectProducedFiles(owner)` 同口径;正文里
1138
- // 提到这一轮写的文件就能解析成可点(App 侧按文件名或整条路径唯一命中才画,见
1139
- // `viewmodels/file-mentions`)。
1140
- if (producedItems.length > 0) {
1141
- for (const { item, turn } of producedItems) {
1142
- const bucket = producedByTurn.get(turn);
1143
- if (bucket && bucket.size > 0) item.producedFiles = [...bucket];
1144
- }
1137
+ // 所属轮每个可见载体都带轻量事实,薄入口即使只剩用户行/失败行也不会丢产出。
1138
+ for (const item of out) {
1139
+ const turn = typeof item.turn === 'number' ? item.turn : turnOfSeq(item.seq, turnIndex.bySeq, turnIndex.starts);
1140
+ const facts = factsByTurn.get(turn);
1141
+ if (!facts) continue;
1142
+ if (turn !== null && turn !== undefined) item.turn = turn;
1143
+ Object.assign(item, turnFactsSnapshot(facts));
1145
1144
  }
1146
1145
  // 手动 `/compact` 在桌面上是**一件事**:`CompactionCommandCard` 只画一个 `CompactionItem`
1147
1146
  // (标题取命令名,摘要位放条数与 token 数,条数不齐时放命令结果原文),命令行那块根本不出现。
@@ -24,6 +24,7 @@ const TEXT_MAX = 200_000;
24
24
 
25
25
  const { liveStepTurnOf, liveStepWriterOf, liveStepSinkOf } = require('./session-cache.js');
26
26
  const { reasoningText, reasoningStepSummary, toolStepSummary } = require('./step-index.js');
27
+ const { createTurnFacts, absorbTurnFact, rebuildTurnFacts, turnFactsSnapshot, turnChangesSnapshot, resultCallId } = require('./turn-facts.js');
27
28
 
28
29
  function bucketOf(ctx) {
29
30
  return liveStepTurnOf(ctx);
@@ -135,6 +136,10 @@ function turnOf(ctx, sessionId) {
135
136
  ended: false,
136
137
  /** 这份副本属于哪一轮(宿主 turn 号):换轮就整份作废,见 `turnForEvent`。 */
137
138
  turnNo: null,
139
+ /** 事实与详情同桶、同写入者;断流只释放写入权,下一轮才替换这份事实。 */
140
+ facts: createTurnFacts(),
141
+ factsSentRevision: -1,
142
+ factsSentSnapshot: null,
138
143
  };
139
144
  bucket.delete(sessionId);
140
145
  bucket.set(sessionId, turn);
@@ -157,6 +162,7 @@ function turnForEvent(ctx, sessionId, data) {
157
162
  const bucket = bucketOf(ctx);
158
163
  const explicitTurn = data && typeof data.turn === 'number' ? data.turn : null;
159
164
  let turn = bucket.get(sessionId);
165
+ if (turn && explicitTurn !== null && turn.turnNo !== null && turn.turnNo > explicitTurn) return null;
160
166
  if (turn && explicitTurn !== null && turn.turnNo !== null && turn.turnNo !== explicitTurn) {
161
167
  bucket.delete(sessionId);
162
168
  turn = undefined;
@@ -270,14 +276,23 @@ function noteLiveEvent(ctx, sessionId, event, writerId) {
270
276
  if (!writerAllows(ctx, sessionId, writerId)) return;
271
277
  const data = event.data && typeof event.data === 'object' ? event.data : null;
272
278
  if (event.type === 'turn/start') {
279
+ const existing = bucketOf(ctx).get(sessionId);
280
+ if (existing && data && typeof data.turn === 'number' && existing.turnNo > data.turn) return;
281
+ if (existing && existing.turnNo === (data && data.turn)) {
282
+ absorbTurnFact(existing.facts, event);
283
+ return;
284
+ }
273
285
  // 新的一轮开始:上一轮的过程副本作废(换掉了,就别再让人点开旧内容)。
274
286
  bucketOf(ctx).delete(sessionId);
275
287
  const started = turnOf(ctx, sessionId);
276
288
  if (data && typeof data.turn === 'number') started.turnNo = data.turn;
289
+ absorbTurnFact(started.facts, event);
277
290
  return;
278
291
  }
279
292
  if (!data) return;
280
293
  const turn = turnForEvent(ctx, sessionId, data);
294
+ if (!turn) return;
295
+ absorbTurnFact(turn.facts, event);
281
296
  if (event.type === 'assistant/message') {
282
297
  // 一步落定:这一步的思考按块序号收尾(后面那一步的块序号从 0 重新数)。
283
298
  closeThoughtsOfStep(turn);
@@ -294,6 +309,7 @@ function noteLiveEvent(ctx, sessionId, event, writerId) {
294
309
  // 参数到这里是齐的 —— 摘要该按它拼出来了。身份帧可能在断线 / 合并里丢过,
295
310
  // 所以这里也顺手把这一步补进清单(有就只更新)。
296
311
  turn.tools.set(callId, {
312
+ ...current,
297
313
  name: typeof block.name === 'string' && block.name ? block.name : current.name,
298
314
  argsRaw: typeof block.arguments === 'string'
299
315
  ? block.arguments
@@ -373,9 +389,9 @@ function noteLiveEvent(ctx, sessionId, event, writerId) {
373
389
  }
374
390
  if (event.type === 'tool/result') {
375
391
  const message = data.message;
376
- const src = message && message.source;
377
- if (!src || typeof src.callId !== 'string') return;
378
- const current = turn.tools.get(src.callId) || { name: '', argsRaw: '' };
392
+ const callId = resultCallId(event);
393
+ if (!callId || !message) return;
394
+ const current = turn.tools.get(callId) || { name: '', argsRaw: '' };
379
395
  const { parts, isError } = resultParts(message);
380
396
  const output = parts
381
397
  .map((part) => (part && typeof part.text === 'string' ? part.text : ''))
@@ -385,13 +401,13 @@ function noteLiveEvent(ctx, sessionId, event, writerId) {
385
401
  const code = data.error && typeof data.error.code === 'string' ? data.error.code : undefined;
386
402
  // 失败有两种写法:`message.isError` 与 `data.error.code`(宿主两种都发过),任一都算失败。
387
403
  const failed = isError || code !== undefined;
388
- turn.tools.set(src.callId, {
404
+ turn.tools.set(callId, {
389
405
  ...current,
390
406
  output: output.length > TEXT_MAX ? output.slice(0, TEXT_MAX) : output,
391
407
  ...(failed ? { error: code === 'interrupted' ? 'stopped' : 'error' } : { error: null }),
392
408
  ...(diffs ? { diffs } : {}),
393
409
  });
394
- refreshToolStep(turn, src.callId);
410
+ refreshToolStep(turn, callId);
395
411
  return;
396
412
  }
397
413
  if (event.type === 'turn/end') {
@@ -423,6 +439,64 @@ function liveStepsTurnOf(ctx, sessionId) {
423
439
  return turn && typeof turn.turnNo === 'number' ? turn.turnNo : null;
424
440
  }
425
441
 
442
+ /** 按需读取当前轮的完整事实;没有轮号时不把空壳发给客户端。 */
443
+ function liveTurnFactsOf(ctx, sessionId) {
444
+ if (!ctx || !sessionId) return null;
445
+ const turn = liveStepTurnOf(ctx).get(sessionId);
446
+ if (!turn || typeof turn.turnNo !== 'number') return null;
447
+ const facts = turnFactsSnapshot(turn.facts);
448
+ // 没有新事实不增加空控制帧;曾发过产出的轮撤销回空时仍必须发快照清除旧状态。
449
+ if (!turn.factsSentSnapshot && !facts.actualModel && !facts.modelTrail.length && !facts.producedFiles.length) return null;
450
+ return { turn: turn.turnNo, ...facts };
451
+ }
452
+
453
+ function liveTurnChangesOf(ctx, sessionId, wantedTurn, historyEntries) {
454
+ if (!ctx || !sessionId) return null;
455
+ const turn = liveStepTurnOf(ctx).get(sessionId);
456
+ if (!turn || turn.turnNo !== wantedTurn) return null;
457
+ if (!historyEntries) return turnChangesSnapshot(turn.facts);
458
+ // 仅为本次读取建临时副本,按 seq 合并授权历史;不抢直播单写者的写入权。
459
+ const merged = createTurnFacts();
460
+ for (const entry of historyEntries) {
461
+ const event = entry && entry.event ? entry.event : entry;
462
+ if (event && event.data && event.data.turn === wantedTurn) absorbTurnFact(merged, event);
463
+ }
464
+ for (const [key, fact] of turn.facts.events) {
465
+ if (!merged.events.has(key)) merged.events.set(key, fact);
466
+ }
467
+ rebuildTurnFacts(merged);
468
+ merged.truncated = merged.truncated || turn.facts.truncated;
469
+ return turnChangesSnapshot(merged);
470
+ }
471
+
472
+ function drainLiveTurnFacts(ctx, sessionId, writerId) {
473
+ if (!ctx || !sessionId || !writerAllows(ctx, sessionId, writerId)) return null;
474
+ const turn = liveStepTurnOf(ctx).get(sessionId);
475
+ if (!turn || turn.factsSentRevision === turn.facts.revision || typeof turn.turnNo !== 'number') return null;
476
+ turn.factsSentRevision = turn.facts.revision;
477
+ const snapshot = liveTurnFactsOf(ctx, sessionId);
478
+ if (!snapshot) return null;
479
+ const serialized = JSON.stringify(snapshot);
480
+ if (serialized === turn.factsSentSnapshot) return null;
481
+ turn.factsSentSnapshot = serialized;
482
+ return snapshot;
483
+ }
484
+
485
+ /** 从已授权的历史窗补齐直播事实,只吸游标之后的事件,不回放推理或参数增量。 */
486
+ function seedLiveTurnFacts(ctx, sessionId, entries, writerId) {
487
+ if (!ctx || !sessionId || !writerAllows(ctx, sessionId, writerId)) return;
488
+ const events = (entries || []).map((entry) => entry && entry.event ? entry.event : entry)
489
+ .filter(Boolean).sort((a, b) => (a.seq ?? Infinity) - (b.seq ?? Infinity));
490
+ for (const event of events) {
491
+ const data = event.data;
492
+ if (!data || typeof data.turn !== 'number') continue;
493
+ const existing = liveStepTurnOf(ctx).get(sessionId);
494
+ if (existing && existing.turnNo !== null && data.turn < existing.turnNo) continue;
495
+ const turn = turnForEvent(ctx, sessionId, data);
496
+ absorbTurnFact(turn.facts, event);
497
+ }
498
+ }
499
+
426
500
  /**
427
501
  * 取走「还没告诉过手机」的那几步。
428
502
  *
@@ -483,6 +557,10 @@ module.exports = {
483
557
  liveStepOf,
484
558
  liveStepsOf,
485
559
  liveStepsTurnOf,
560
+ liveTurnFactsOf,
561
+ liveTurnChangesOf,
562
+ drainLiveTurnFacts,
563
+ seedLiveTurnFacts,
486
564
  drainLiveSteps,
487
565
  clearLiveSteps,
488
566
  claimLiveWriter,
@@ -0,0 +1,183 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 移动端「这台电脑上还连着哪些手机」:只读清单 + 单台吊销,外加凭据时效投影。
5
+ *
6
+ * 真源是宿主的每设备凭据库(`dsh-mobile-credentials` 的 `listDevices` / `revokeDevice`)。
7
+ * 这里只做两件事:把一行设备压成手机要画的东西,以及按设备标识吊销一台。控制面那条
8
+ * `/api/relay/devices` 只认本机,手机打不到;移动端此前也只能看到自己这一台,所以要
9
+ * 单开这两条。清单里的 `hash` / `hostToken` / `deviceKey` 一律不回,跟控制面同一口径。
10
+ *
11
+ * 吊销按 `deviceId` 整台做(该名下所有活记录一起收),不是只收出示的那一枚 —— 同一台
12
+ * 手机重配、升级会留下好几条活凭据,只吊一条等于旧的那枚还能用。被吊销的设备下一次请求
13
+ * 由守卫回 `device-revoked`(「请重新扫码」),这条不用在这里再拼文案。
14
+ *
15
+ * 时效投影(第 54 条):凭据库记录里只有 `createdAt` / `expiresAt`,续期是「剩余不足一半
16
+ * 就把 `expiresAt` 后推一个 TTL」,所以「最近一次续期」= `expiresAt - TTL`(早于签发时刻
17
+ * 就是从未续期,不回这一格)。这几格只从记录算,不改凭据库本身。
18
+ */
19
+
20
+ const { sendJson, readJsonBody } = require('../shared/http-util.js');
21
+
22
+ const DEVICE_ID_MAX = 128; // 与凭据库签发时同一个截断长度
23
+ const FALLBACK_TTL_MS = 365 * 24 * 3600 * 1000; // 凭据库默认有效期(`DEFAULT_TTL_MS` 的兜底)
24
+ const RENEW_EPSILON_MS = 60 * 1000; // 续期时刻与签发时刻差不到一分钟,按「从未续期」处理
25
+
26
+ /** 凭据库的默认 TTL;拿不到就用本文件的兜底,保证时效投影总能算出一个结果。 */
27
+ function ttlOf(store) {
28
+ const ttl = store && Number(store.DEFAULT_TTL_MS);
29
+ return Number.isFinite(ttl) && ttl > 0 ? ttl : FALLBACK_TTL_MS;
30
+ }
31
+
32
+ /**
33
+ * 一条凭据(或一台设备聚合后)的时效投影。
34
+ *
35
+ * @param {{ createdAt?: number, boundAt?: number, expiresAt?: number }} record
36
+ * @param {object} store 凭据库(用来读默认 TTL)
37
+ * @returns {{ authorizedAt: number|null, renewedAt: number|null, expiresAt: number|null } | null}
38
+ */
39
+ function credentialTiming(record, store) {
40
+ if (!record || typeof record !== 'object') return null;
41
+ const authorizedAt = Number(record.createdAt ?? record.boundAt) || 0;
42
+ const expiresAt = Number(record.expiresAt) || 0;
43
+ if (!authorizedAt && !expiresAt) return null;
44
+ let renewedAt = 0;
45
+ if (expiresAt) {
46
+ const renewed = expiresAt - ttlOf(store);
47
+ if (authorizedAt && renewed > authorizedAt + RENEW_EPSILON_MS) renewedAt = renewed;
48
+ }
49
+ return {
50
+ authorizedAt: authorizedAt || null,
51
+ renewedAt: renewedAt || null,
52
+ expiresAt: expiresAt || null,
53
+ };
54
+ }
55
+
56
+ /**
57
+ * 本机这枚凭据的时效投影(`GET /api/mobile/v1/status` 的 `credential` 那一格用它)。
58
+ *
59
+ * 传请求对象:从它出示的那枚凭据查记录。查不到记录(升级前的无状态 HMAC 通行证)就回
60
+ * null —— 那种凭据本来就没有记录,也就没有签发 / 到期时刻可报。
61
+ */
62
+ function credentialTimingFor(store, instanceId, req) {
63
+ if (!store || typeof store.lookup !== 'function' || !req) return null;
64
+ const headers = req.headers || {};
65
+ const header = headers['x-dsh-device-credential'];
66
+ const presented = typeof header === 'string' && header.trim()
67
+ ? header.trim()
68
+ : ((/^Bearer\s+([^\s]+)$/.exec(String(headers.authorization || '')) || [])[1] || null);
69
+ if (!presented) return null;
70
+ const record = store.lookup(presented, String(instanceId || ''));
71
+ return record ? credentialTiming(record, store) : null;
72
+ }
73
+
74
+ /** 设备标识清洗:只留短串,畸形的一律拒绝,别拿垃圾去碰凭据库。 */
75
+ function normalizeDeviceId(value) {
76
+ if (typeof value !== 'string') return null;
77
+ const deviceId = value.trim();
78
+ if (!deviceId || deviceId.length > DEVICE_ID_MAX) return null;
79
+ return deviceId;
80
+ }
81
+
82
+ /** 一台设备的一行(`listDevices` 的活动行 → 手机要的形状)。 */
83
+ function toPairedDevice(row, store, latest) {
84
+ return {
85
+ deviceId: String(row.deviceId || ''),
86
+ name: typeof row.name === 'string' ? row.name : '',
87
+ model: typeof row.model === 'string' ? row.model : '',
88
+ platform: typeof row.platform === 'string' ? row.platform : '',
89
+ osVersion: typeof row.osVersion === 'string' ? row.osVersion : '',
90
+ appVersion: typeof row.appVersion === 'string' ? row.appVersion : '',
91
+ boundAt: Number(row.boundAt) || 0,
92
+ lastSeenAt: Number(row.lastSeenAt) || 0,
93
+ bindings: Number(row.bindings) || 0,
94
+ legacy: row.legacy === true,
95
+ encrypted: row.encrypted === true,
96
+ // 时效取**这一台最新签发的那条**:聚合行只给「最早的绑定时刻 + 最晚的到期时刻」,
97
+ // 拿它俩相减会把「重配过一次」说成「续期过」。续期只发生在单条记录上。
98
+ credential: credentialTiming(latest || { createdAt: row.boundAt, expiresAt: row.expiresAt }, store),
99
+ };
100
+ }
101
+
102
+ /**
103
+ * 每台设备最新签发的那条活记录(按 `deviceId`)。
104
+ *
105
+ * `listActive` 一条记录一行,这里按签发时刻取最大 —— 时效要算在它上面,见 `toPairedDevice`。
106
+ * 老凭据库没有 `listActive` 就回空表,调用方退回聚合行那两格。
107
+ */
108
+ function latestRecords(store, instanceId) {
109
+ const out = new Map();
110
+ if (typeof store.listActive !== 'function') return out;
111
+ for (const record of store.listActive(instanceId) || []) {
112
+ const key = String(record.deviceId || '');
113
+ if (!key) continue;
114
+ const previous = out.get(key);
115
+ if (!previous || (Number(record.createdAt) || 0) > (Number(previous.createdAt) || 0)) out.set(key, record);
116
+ }
117
+ return out;
118
+ }
119
+
120
+ /**
121
+ * `GET /api/mobile/v1/paired-devices` —— 这台电脑上仍有效的设备清单(只读)。
122
+ *
123
+ * `serverNow` 给手机算「几分钟前」用(手机与宿主的时钟可能差得多,但都是同一台机器的基准)。
124
+ */
125
+ async function handlePairedDevices(_req, res, deps) {
126
+ const instanceId = String((deps && deps.instanceId) || '');
127
+ const store = deps && deps.store;
128
+ if (!store || typeof store.listDevices !== 'function') {
129
+ return sendJson(res, 503, { ok: false, error: { code: 'unavailable', message: '凭据库不可用' } });
130
+ }
131
+ try {
132
+ const now = Date.now();
133
+ const latest = latestRecords(store, instanceId);
134
+ const devices = (store.listDevices(instanceId) || [])
135
+ .map((row) => toPairedDevice(row, store, latest.get(String(row.deviceId || ''))));
136
+ return sendJson(res, 200, { ok: true, serverNow: now, devices });
137
+ } catch (error) {
138
+ return sendJson(res, 500, { ok: false, error: { code: 'internal', message: String(error && error.message ? error.message : error) } });
139
+ }
140
+ }
141
+
142
+ /**
143
+ * `POST /api/mobile/v1/paired-devices/revoke` —— body `{ deviceId }`,吊销一台设备。
144
+ *
145
+ * 尽力而为地主动收掉这台设备已开着的流(`dropDeviceStreams`,装配层可选注入):token 换了
146
+ * 只保证「下一次请求」被拒,一条已经开着的 SSE 不会自己停。
147
+ */
148
+ async function handlePairedDevicesRevoke(req, res, deps) {
149
+ const instanceId = String((deps && deps.instanceId) || '');
150
+ const store = deps && deps.store;
151
+ if (!store || typeof store.revokeDevice !== 'function') {
152
+ return sendJson(res, 503, { ok: false, error: { code: 'unavailable', message: '凭据库不可用' } });
153
+ }
154
+ // 协议 v2 的 body 由守卫解好后放在 req.body;明文老会话的 body 还挂在流上,现读。
155
+ const body = req.body && typeof req.body === 'object'
156
+ ? req.body
157
+ : ((await readJsonBody(req, 16 * 1024)) || {});
158
+ const deviceId = normalizeDeviceId(body.deviceId);
159
+ if (!deviceId) {
160
+ return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '需要 { deviceId }' } });
161
+ }
162
+ let revoked = 0;
163
+ try {
164
+ revoked = store.revokeDevice(instanceId, deviceId);
165
+ } catch (error) {
166
+ return sendJson(res, 500, { ok: false, error: { code: 'internal', message: String(error && error.message ? error.message : error) } });
167
+ }
168
+ let closed = 0;
169
+ try {
170
+ closed = typeof deps.dropDeviceStreams === 'function' ? deps.dropDeviceStreams(deviceId) : 0;
171
+ } catch { /* 尽力:断流失败不影响吊销已经落地 */ }
172
+ return sendJson(res, 200, { ok: true, revoked, closed });
173
+ }
174
+
175
+ module.exports = {
176
+ handlePairedDevices,
177
+ handlePairedDevicesRevoke,
178
+ credentialTiming,
179
+ credentialTimingFor,
180
+ normalizeDeviceId,
181
+ toPairedDevice,
182
+ latestRecords,
183
+ };