@dsh-mobile/mobile-remote 3.3.1 → 3.4.0

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 (58) hide show
  1. package/README.md +9 -5
  2. package/docs/PRIVACY-POLICY.en.md +10 -3
  3. package/docs/PRIVACY-POLICY.md +10 -3
  4. package/docs/USER-GUIDE.zh-CN.md +1 -0
  5. package/lib/account-usage-query.js +60 -60
  6. package/lib/account-usage.js +10 -10
  7. package/lib/api-helpers.js +109 -109
  8. package/lib/assistant-prefs.js +82 -59
  9. package/lib/auto-config.js +65 -65
  10. package/lib/backup.js +117 -117
  11. package/lib/break-reminder.js +45 -45
  12. package/lib/client.js +93 -93
  13. package/lib/config.js +232 -218
  14. package/lib/git-read-bundled-provider.js +12 -12
  15. package/lib/git-read-service.js +5 -5
  16. package/lib/host-compat.js +84 -84
  17. package/lib/http-util.js +17 -17
  18. package/lib/index.js +1534 -1534
  19. package/lib/memory/context.js +44 -44
  20. package/lib/memory/decay.js +93 -93
  21. package/lib/memory/extract.js +77 -77
  22. package/lib/memory/routes.js +33 -33
  23. package/lib/memory/store.js +196 -196
  24. package/lib/notify-copy.js +93 -93
  25. package/lib/permission-guide.js +86 -86
  26. package/lib/persona-cards.js +73 -65
  27. package/lib/phone-action-args.js +175 -0
  28. package/lib/phone-actions.js +227 -0
  29. package/lib/phone-announce.js +58 -0
  30. package/lib/proactive-material.js +42 -42
  31. package/lib/proactive.js +121 -121
  32. package/lib/protected-paths.js +79 -79
  33. package/lib/protocol.js +61 -26
  34. package/lib/push.js +29 -29
  35. package/lib/rate-limit.js +16 -16
  36. package/lib/relay/connector.js +246 -102
  37. package/lib/relay/crypto.js +15 -15
  38. package/lib/relay/devices.js +36 -36
  39. package/lib/relay/fingerprint.js +34 -34
  40. package/lib/relay/identity.js +26 -26
  41. package/lib/relay/mux.js +60 -46
  42. package/lib/relay/noise.js +40 -40
  43. package/lib/relay/on-demand.js +33 -33
  44. package/lib/relay/p2p.js +239 -0
  45. package/lib/relay/pairing.js +24 -24
  46. package/lib/relay/phone.js +62 -40
  47. package/lib/relay/serve.js +21 -21
  48. package/lib/relay/signal.js +69 -0
  49. package/lib/relay/ws-server.js +32 -32
  50. package/lib/reminders.js +15 -15
  51. package/lib/rpc-adapter.js +43 -43
  52. package/lib/session-list.js +31 -31
  53. package/lib/session-rotation.js +95 -95
  54. package/lib/session-title-cache.js +35 -35
  55. package/lib/session-title-refresh.js +51 -51
  56. package/lib/timeline.js +140 -140
  57. package/lib/turn-outline.js +104 -104
  58. package/package.json +6 -13
@@ -1,32 +1,32 @@
1
1
  export const DEFAULT_TITLE_REFRESH_BUDGET_MS = 1500;
2
2
  export const DEFAULT_TITLE_REFRESH_CONCURRENCY = 4;
3
3
 
4
- /**
5
- * Coalesce title refreshes for one corpus pass.
6
- *
7
- * Why a pass folds in **one** host call (issue #20 review, 2026-10-07):
8
- * `sessionQuery.readTitleSnapshots(ids)` is not a point read. The installed
9
- * `0.2.0-rc.2` chain is
10
- *
11
- * readTitleSnapshots → SessionCorpus.projectMany → listPersisted → persistence.list()
12
- *
13
- * and `persistence.list()` walks the whole corpus (per-file header + stat, plus
14
- * a corpus-wide revision hash while a historical generation is present). Batch
15
- * size therefore multiplies corpus enumerations: folding four ids at a time
16
- * cost ceil(N/4) full enumerations on top of the pass. The pass now hands every
17
- * pending id to one call, so the enumeration count stays constant as N grows;
18
- * read width inside that call is the host's own `persistedReadConcurrency`
19
- * (default 4, `SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY`, bounded by
20
- * `projectMany`'s worker pool), and this module adds no per-id fan-out on top of
21
- * it. Only the plugin's own revision scan is bounded here — it reads no logs.
22
- *
23
- * Waiters may leave independently; the shared pass is cancelled only after its
24
- * last waiter leaves, unless a timed-out response promoted it to deliberate
25
- * background warm-up. A cancelled pass is retired immediately so the next
26
- * request starts a live successor instead of feeding the dead queue, while the
27
- * fold gate keeps a retired pass and its successor from overlapping — an
28
- * overlap would double the host's read width during cancellation cleanup.
29
- */
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
30
  export const createSessionTitleRefresher = ({
31
31
  readRevision,
32
32
  readTitles,
@@ -39,8 +39,8 @@ export const createSessionTitleRefresher = ({
39
39
  if (!Number.isSafeInteger(concurrency) || concurrency < 1) throw new RangeError("concurrency must be a positive safe integer");
40
40
  let currentRun = null;
41
41
  let disposed = false;
42
- // Serializes fold calls across runs: at most one host title call is in flight
43
- // per refresher, so cancellation cleanup cannot overlap fresh read work.
42
+
43
+
44
44
  let foldTail = Promise.resolve();
45
45
 
46
46
  const foldAll = (ids, signal) => {
@@ -69,10 +69,10 @@ export const createSessionTitleRefresher = ({
69
69
  run.resolve();
70
70
  };
71
71
 
72
- // issue #28 复核 2:**run 级**有限寿命(源级政策)。
73
- // 调用者级的 `backgroundOnBudget: false` 只约束「谁不提升」——挡不住后来加入的 HTTP 调用者
74
- // 在自己的响应预算到点时把 run 提升为**永久后台**;坏源一旦永生,之后健康的请求会一直 join 它
75
- // (只拿到短码),失败隔离就没有闭环。故把截止放在 run 上:到点即中止并退休,**不看 background**。
72
+
73
+
74
+
75
+
76
76
  const armRunDeadline = (run) => {
77
77
  if (!Number.isFinite(run.deadlineAt) || run.deadlineTimer) return;
78
78
  const remaining = Math.max(0, run.deadlineAt - performance.now());
@@ -89,8 +89,8 @@ export const createSessionTitleRefresher = ({
89
89
  const { signal } = run.controller;
90
90
  try {
91
91
  while (!disposed && !signal.aborted && run.queue.length > 0) {
92
- // Drain everything queued so far into this round: revisions first
93
- // (bounded workers, no log reads), then a single fold call.
92
+
93
+
94
94
  const pending = run.queue.splice(0, run.queue.length);
95
95
  const misses = [];
96
96
  let cursor = 0;
@@ -121,8 +121,8 @@ export const createSessionTitleRefresher = ({
121
121
  () => scanRevisions(),
122
122
  ));
123
123
  if (disposed || signal.aborted) break;
124
- // Worker completion order is not the request order; keep the fold
125
- // deterministic (and stable for the host's first-occurrence ordering).
124
+
125
+
126
126
  misses.sort((a, b) => a.index - b.index);
127
127
 
128
128
  if (misses.length > 0) {
@@ -145,7 +145,7 @@ export const createSessionTitleRefresher = ({
145
145
  onCacheChange();
146
146
  }
147
147
  } catch {
148
- // An aborted or faulty refresh is a cache miss, never an endpoint failure.
148
+
149
149
  } finally {
150
150
  finishRun(run);
151
151
  }
@@ -187,22 +187,22 @@ export const createSessionTitleRefresher = ({
187
187
  if (uniqueIds.length === 0) return new Map();
188
188
  if (!Number.isFinite(budgetMs) || budgetMs < 0) throw new RangeError("budgetMs must be a non-negative finite number");
189
189
 
190
- // A run whose upstream was already aborted can no longer consume its queue:
191
- // joining it would park this request's ids in a dead queue and hand back a
192
- // partial result. Retire it and start a live successor instead; the fold
193
- // gate keeps the successor's work behind the retiring pass's cleanup.
190
+
191
+
192
+
193
+
194
194
  let run = currentRun;
195
195
  if (!run || run.done || run.controller.signal.aborted) run = createRun(uniqueIds);
196
196
  else addIds(run, uniqueIds);
197
- // issue #28 复核 2:run 级截止(取所有声明中**最早**者——只收紧、不放松)。
198
- // 它不因后来调用者的 background promotion 而失效:到点由 armRunDeadline 退休该 run。
197
+
198
+
199
199
  if (Number.isFinite(runDeadlineMs) && runDeadlineMs >= 0) {
200
200
  const nextAt = performance.now() + runDeadlineMs;
201
- // 只在**收紧**时重设:后来者更晚的声明不得延长期限(issue #28 复核 3)。
201
+
202
202
  if (nextAt < run.deadlineAt) {
203
203
  run.deadlineAt = nextAt;
204
- // 旧 timer 必须先清掉再重设——armRunDeadline 见到已有 deadlineTimer 会直接返回,
205
- // 那样「收紧」就静默失效(评审实测:先声明 300ms、后声明 20ms,源仍按 300ms 才取消)。
204
+
205
+
206
206
  if (run.deadlineTimer) {
207
207
  clearTimeout(run.deadlineTimer);
208
208
  run.deadlineTimer = null;
@@ -237,10 +237,10 @@ export const createSessionTitleRefresher = ({
237
237
  clearTimeout(timer);
238
238
  if (signal && abortHandler) signal.removeEventListener("abort", abortHandler);
239
239
 
240
- // issue #28 复核 BLOCKING 2:调用方可以要求**有限生命期**。默认(响应路径)预算到点会把
241
- // run 提升为「后台预热」并长期存活;但启动预热**不能**这样——否则一次挂住的预热会让之后
242
- // 健康的请求一直 join 这个坏 run、只拿到短码。传 `backgroundOnBudget: false` 时不做提升,
243
- // 于是下面的 release() 在没有其它等待者时会中止该 run(退休),健康请求随后可重新开始。
240
+
241
+
242
+
243
+
244
244
  if (outcome === "budget" && backgroundOnBudget && !signal?.aborted && !run.done) run.background = true;
245
245
  const aborted = signal?.aborted === true;
246
246
  release();
@@ -253,7 +253,7 @@ export const createSessionTitleRefresher = ({
253
253
  disposed = true;
254
254
  currentRun?.controller.abort(new Error("session-title refresher disposed"));
255
255
  },
256
- /** Test seam: resolve when the current single-flight pass settles. */
256
+
257
257
  whenIdle() {
258
258
  return currentRun?.promise ?? Promise.resolve();
259
259
  },
package/lib/timeline.js CHANGED
@@ -1,7 +1,7 @@
1
- /**
2
- * 对话时间线:哪些内核事件算「可见时间线记录」、事件摘要/详情的纯函数投影(文本、图片、文件、推理、工具调用)。
3
- * 从 lib/index.js 原样拆出(行为不变)。
4
- */
1
+
2
+
3
+
4
+
5
5
  import { clampText } from "./api-helpers.js";
6
6
 
7
7
  export const EVENT_TIMELINE_CAPABILITIES = {
@@ -13,24 +13,24 @@ export const EVENT_TIMELINE_CAPABILITIES = {
13
13
  callCorrelation: true,
14
14
  };
15
15
 
16
- // 这些是明确的运行时/重建/快照日志,不是移动端 Conversation timeline 节点,
17
- // 历史、实时与 /event-detail 三处都不得返回(事件保真契约):
18
- // - assistant/chunk:实时草稿 delta;
19
- // - assistant/attempt:重试/中断时落盘的一次尝试的原始 stream 记录(重建元数据);
20
- // - request/header:含 system prompt/tool schema 的请求快照,不能进入 App 原始详情;
21
- // - request/context、session/end-seed、step 边界:重建/生命周期元数据;
22
- // - compaction/end:不落时间线卡片,但作为实时控制帧通知 App 重载快照;
23
- // - compaction/start、compaction/summary、compaction/prune:压缩生命周期与摘要正文——
24
- // summary 就是替换 shadowed 区间后的上下文快照(还带 rawOutput),永不呈现;
25
- // - agent/inbox/spliced:队列投影,单独经 mobile/queue 回放;
26
- // - system/message:DSH surface 的系统提示词,产品约定即使 debug 也隐藏。
27
- // - `llm-request` 结尾的 LLM 请求快照(session/title-llm-request、
28
- // web/deepseek-search-llm-request …):完整的 LLM 请求——system prompt、messages 正文、
29
- // route/endpoint 全在 data 里。它们**不是**内核的"内部记录",而是 provider 落盘的 required
30
- // 事件,所以逐个枚举的黑名单漏过一次:PR #24 复核实测这两类事件曾随 /history 声明 detail
31
- // 指针、再被 /event-detail 原样 200 返回(含 systemPrompt 与主机路径)。此处改按命名约定
32
- // 拦截(LLM_REQUEST_TYPE_PATTERN),未来任何 provider 记录请求快照都不会因为漏登记而泄露。
33
- // 其余未知 required 事件保留,避免新版本的用户可见事件被旧白名单静默吞掉。
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
34
  const REPLAY_IGNORED_TYPES = new Set([
35
35
  "assistant/chunk",
36
36
  "assistant/live-chunk",
@@ -48,11 +48,11 @@ const REPLAY_IGNORED_TYPES = new Set([
48
48
  "compaction/end",
49
49
  ]);
50
50
 
51
- /** 请求快照的命名约定:类型以 `llm-request` 结尾,前一段分隔符为 `/` 或 `-`
52
- * (内核现实形态:`session/title-llm-request`、`web/deepseek-search-llm-request`;
53
- * 未来也可能是 `<scope>/llm-request`)。data 是发往模型的完整请求
54
- * (system prompt + messages + route),永不呈现。规则只在 isTimelineRecord 一处生效,
55
- * 历史、实时与 /event-detail 三处同时收口(不逐个登记类型名,避免新增 provider 时漏登记)。 */
51
+
52
+
53
+
54
+
55
+
56
56
  const LLM_REQUEST_TYPE_PATTERN = /(?:^|[/-])llm-request$/;
57
57
 
58
58
  export const isTimelineRecord = (event) => Boolean(
@@ -62,30 +62,30 @@ export const isTimelineRecord = (event) => Boolean(
62
62
  && !LLM_REQUEST_TYPE_PATTERN.test(event.type)
63
63
  );
64
64
 
65
- // 实时草稿必须保留 token delta;它不进入 durable history,但同一 session/event
66
- // envelope 仍让 App 以 seq 去重。其它内部记录不要只在 live 出现,否则重连后会消失。
65
+
66
+
67
67
  const LIVE_ONLY_TYPES = new Set(["assistant/chunk", "assistant/live-chunk"]);
68
68
 
69
- // Projection-only controls are not timeline cards, but must reach an active App so
70
- // it can discard stale projections and reload the durable snapshot after compaction.
69
+
70
+
71
71
  const LIVE_CONTROL_TYPES = new Set(["compaction/end"]);
72
72
 
73
73
  export const isLiveTimelineRecord = (event) => Boolean(
74
74
  event && typeof event.type === "string" && (isTimelineRecord(event) || LIVE_ONLY_TYPES.has(event.type) || LIVE_CONTROL_TYPES.has(event.type))
75
75
  );
76
76
 
77
- /**
78
- * `/event-detail` 的**类型 allow-list(fail-closed)**:只有列在这里的类型才允许经详情端点
79
- * 取回原始事件;其余(内核新增类型、插件自定义类型、未命名/未知类型)一律 404
80
- * `event-not-found`,不再把原始 data 交出去。
81
- *
82
- * 清单依据(不是随手挑的):这正是 `summarizeEventCore` **逐个类型显式审过载荷**并下发给
83
- * App 的类型——其余类型走 default 分支只下发 `{seq,type}`(无 data),App 从来不消费它们的
84
- * data,因此详情端点也不该借「调试查看原始事件」入口把 system prompt / messages / 请求快照 /
85
- * 生命周期内部记录原样交出去。`assistant/chunk` / `assistant/live-chunk` 虽被 App 消费,但它们是
86
- * 实时草稿(isTimelineRecord=false、不落 durable history),没有可取的详情,故不在清单内。
87
- * 收紧详情面**不影响** `/history`:未知可见事件依旧保留(事件保真契约)。
88
- */
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
89
  const DETAIL_VISIBLE_TYPES = new Set([
90
90
  "user/message",
91
91
  "assistant/message",
@@ -96,47 +96,47 @@ const DETAIL_VISIBLE_TYPES = new Set([
96
96
  "turn/end",
97
97
  ]);
98
98
 
99
- /** 纯函数导出:供契约自检(tools/timeline-contract-check.mjs)直接断言 allow-list 边界。 */
99
+
100
100
  export const isDetailVisibleType = (type) => typeof type === "string" && DETAIL_VISIBLE_TYPES.has(type);
101
101
 
102
- /**
103
- * 「最新消息时间」(`lastMessageAt`,ADR 0013)只承认**用户/助手可见对话消息**。
104
- * 这是唯一判定点:实时事件流与会话日志回填共用同一集合,避免两处规则漂移。
105
- * 工具活动、生命周期、协议元数据、系统注入都不算——它们不代表"最近有对话"。
106
- */
102
+
103
+
104
+
105
+
106
+
107
107
  export const MESSAGE_EVENT_TYPES = new Set(["user/message", "assistant/message"]);
108
108
 
109
- /** 纯函数导出:供路由测试与契约自检直接断言。 */
109
+
110
110
  export const isMessageEventType = (type) => typeof type === "string" && MESSAGE_EVENT_TYPES.has(type);
111
111
 
112
- /**
113
- * 该事件是否**更新 `lastMessageAt`** ——即"这是一条用户能看到的对话消息"。
114
- *
115
- * 只按事件类型判定是不够的(issue #14 复核发现):
116
- * - `user/message` 也承载系统注入(`source.kind` 为 `plugin` / `tool` / `model` 等,
117
- * 摘要层同样透出 `sourceKind`),App 在普通模式下**不渲染**这些注入;
118
- * - `assistant/message` 含**正文为空**的工具阶段中间产物,App 显式跳过不渲染。
119
- *
120
- * 若把它们计入,一次插件上下文注入或一次纯工具调用就会把会话顶到列表最前——
121
- * 但那并不是「最近有对话」,与 ADR/CONTEXT 的「可见对话消息」定义相悖。
122
- * 实时流(onSessionEvent)与日志回填(latestMessageTimeOf)共用本谓词,保证口径一致。
123
- */
112
+
113
+
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
124
  export const isVisibleConversationMessage = (event) => {
125
125
  const type = event?.type;
126
126
  if (!isMessageEventType(type)) return false;
127
127
  if (type === "assistant/message") {
128
- // 与 App 渲染口径一致:正文为空的多步中间产物不构成可见消息。
129
- // 图片不作为可见性依据——App 对空正文的 assistant 消息整条跳过(含其图片)。
128
+
129
+
130
130
  const message = event?.data?.message;
131
131
  if (!message || typeof message !== "object") return false;
132
132
  return blocksToText(message.content).trim() !== "";
133
133
  }
134
- // user/message:只认真人发言(source.kind === "user" 或无 source 的旧内核)
134
+
135
135
  const kind = event?.data?.source?.kind;
136
136
  return kind === undefined || kind === null || kind === "user";
137
137
  };
138
138
 
139
- /** 从 ContentBlock[] 提取纯文本(默认过滤 tool-call;user 消息的 image 保留占位)。 */
139
+
140
140
  export function blocksToText(blocks, { includeToolCalls = false, imagePlaceholder = true } = {}) {
141
141
  let out = "";
142
142
  for (const block of blocks ?? []) {
@@ -147,14 +147,14 @@ export function blocksToText(blocks, { includeToolCalls = false, imagePlaceholde
147
147
  return out;
148
148
  }
149
149
 
150
- /** 统计 reasoning 字符数。 */
150
+
151
151
  function reasoningChars(blocks) {
152
152
  let n = 0;
153
153
  for (const block of blocks ?? []) if (block?.type === "reasoning") n += block.text.length;
154
154
  return n;
155
155
  }
156
156
 
157
- /** 提取 thinking-chain(reasoning)正文:拼接全部 reasoning 类型 content block 的文本。 */
157
+
158
158
  function reasoningText(blocks) {
159
159
  let out = "";
160
160
  for (const block of blocks ?? []) {
@@ -163,11 +163,11 @@ function reasoningText(blocks) {
163
163
  return out;
164
164
  }
165
165
 
166
- /** image attachment 引用 → 移动端图片元数据(仅引用不含字节;渲染时 App 按 attachmentId 走 /attachment 端点拉取)。 */
166
+
167
167
  function imageMetaOf(ref) {
168
168
  if (!ref || typeof ref !== "object") return null;
169
- // 内核不同路径产出的附件引用字段并不统一:桌面端历史里可能是 `{ id }`,
170
- // 移动端上传是 `{ attachmentId }`,媒体类型也有 mediaType/mimeType 两种写法。
169
+
170
+
171
171
  const attachment = ref.attachment && typeof ref.attachment === "object" ? ref.attachment : ref;
172
172
  const id = attachment.attachmentId ?? attachment.id;
173
173
  if (id === undefined || id === null || String(id) === "") return null;
@@ -187,12 +187,12 @@ function imageMetaOf(ref) {
187
187
  };
188
188
  }
189
189
 
190
- /** ContentBlock[] → 顶层图片元数据。 */
190
+
191
191
  function imagesOf(blocks) {
192
192
  const out = [];
193
193
  for (const block of blocks ?? []) {
194
194
  if (!block || typeof block !== "object") continue;
195
- // image block 既可能把引用放在 `attachment` 里,也可能直接平铺在 block 上。
195
+
196
196
  if (block.type === "image") {
197
197
  const meta = imageMetaOf(block.attachment ?? block);
198
198
  if (meta) out.push(meta);
@@ -201,18 +201,18 @@ function imagesOf(blocks) {
201
201
  return out;
202
202
  }
203
203
 
204
- /**
205
- * v3.0.0(版本二):递归收集图片引用——内核 read_image 等工具结果的图片块**嵌套在
206
- * tool-result.content 内**(实测事件结构),PC 端 contentParts 对消息内容通用收集;
207
- * 此处与 PC 同构展开,assistant/message 与 tool/result 摘要即可带出嵌套图片。
208
- */
204
+
205
+
206
+
207
+
208
+
209
209
  function imagesOfNested(blocks) {
210
210
  const out = [];
211
211
  const walk = (list) => {
212
212
  for (const block of list ?? []) {
213
213
  if (!block || typeof block !== "object") continue;
214
214
  if (block.type === "image") {
215
- // 与 imagesOf 一致:引用可能在 attachment 里,也可能直接平铺在 block 上。
215
+
216
216
  const meta = imageMetaOf(block.attachment ?? block);
217
217
  if (meta) out.push(meta);
218
218
  } else if (block.type === "tool-result" && Array.isArray(block.content)) {
@@ -224,7 +224,7 @@ function imagesOfNested(blocks) {
224
224
  return out;
225
225
  }
226
226
 
227
- /** 文件结果引用 → 移动端可下载元数据(不携带文件字节)。 */
227
+
228
228
  function fileMetaOf(ref) {
229
229
  if (!ref || typeof ref !== "object") return null;
230
230
  const mediaType = typeof ref.mediaType === "string" ? ref.mediaType : typeof ref.mimeType === "string" ? ref.mimeType : "";
@@ -242,7 +242,7 @@ function fileMetaOf(ref) {
242
242
  };
243
243
  }
244
244
 
245
- /** 递归收集工具结果中的文件引用,兼容 file/file-result 与 files 数组形态。 */
245
+
246
246
  function filesOfNested(blocks, explicit = false) {
247
247
  const out = [];
248
248
  const seen = new Set();
@@ -269,12 +269,12 @@ function filesOfNested(blocks, explicit = false) {
269
269
  return out;
270
270
  }
271
271
 
272
- /**
273
- * v3.0.0(热修 02):按字节魔数嗅探图片真实类型(仅解码 base64 前 40 字符,开销可忽略)。
274
- * 返回真实 mediaType;无法识别返回 null(交给内核原样校验)。
275
- * 背景:App 按文件扩展名声明类型,微信/浏览器保存的 WebP 常带 .jpg/.png 名字,
276
- * 与真实字节不符时内核报 "Declared image type does not match its bytes" → /send 自动纠正。
277
- */
272
+
273
+
274
+
275
+
276
+
277
+
278
278
  export function sniffImageType(data) {
279
279
  if (typeof data !== "string" || data.length === 0) return null;
280
280
  const head = Buffer.from(data.slice(0, 40), "base64");
@@ -284,20 +284,20 @@ export function sniffImageType(data) {
284
284
  if (bytes(0, 3) === "ffd8ff") return "image/jpeg";
285
285
  if (bytes(0, 4) === "47494638") return "image/gif";
286
286
  if (bytes(0, 4) === "52494646" && bytes(8, 4) === "57454250") return "image/webp";
287
- // HEIC/HEIF:`ftyp` 容器(品牌 heic/heix/hevc/mif1)——识别出 image/heic 后交内核裁决
288
- // (内核媒体白名单仅 png/jpeg/webp/gif,会以不支持类型拒绝并给出明确错误)
287
+
288
+
289
289
  const containerBrand = bytes(4, 4) === "66747970" ? bytes(8, 4) : "";
290
290
  if (["68656963", "68656978", "68657663", "6d696631"].includes(containerBrand)) return "image/heic";
291
291
  return null;
292
292
  }
293
293
 
294
- /**
295
- * 把 SessionEvent 转成移动端摘要(docs/CONSOLIDATED-DOCUMENTATION.en.md Part 03 §3.6)。
296
- * 返回 { seq, type, data?, detail? };未识别类型保留 type/seq,详情按需读取。
297
- */
294
+
295
+
296
+
297
+
298
298
  function summarizeEventCore(event) {
299
299
  const { seq, type, data } = event;
300
- // review:内核实参可能缺 data(防御,避免 TypeError 打崩事件发射器)
300
+
301
301
  if (data === undefined) return { seq, type };
302
302
  switch (type) {
303
303
  case "user/message": {
@@ -309,13 +309,13 @@ function summarizeEventCore(event) {
309
309
  type,
310
310
  data: {
311
311
  messageId: message.id,
312
- // v3.0.0(热修 07):user 摘要文本不再掺「[图片]」占位——图片由 images[] 图卡渲染,
313
- // 客户端不再需要剥离占位(剥离会误删用户手打的 [图片],见 Codex review)。
312
+
313
+
314
314
  text: clampText(blocksToText(message.content, { imagePlaceholder: false }), 2000),
315
- // v3.1.4(issue #12):来源标记——内核 `createUserMessage({ source })` 区分
316
- // 真人发言(kind: "user")与系统注入(plugin / agent-instructions / tool / …)。
317
- // App 据此把注入渲染成**可折叠块**,而不是当普通气泡铺满屏幕;
318
- // 旧内核无 source 时不下发该字段,App 退回关键词启发式。
315
+
316
+
317
+
318
+
319
319
  ...(typeof message.source?.kind === "string" && message.source.kind !== ""
320
320
  ? { sourceKind: message.source.kind }
321
321
  : {}),
@@ -326,13 +326,13 @@ function summarizeEventCore(event) {
326
326
  }
327
327
  case "assistant/message": {
328
328
  const message = data.message;
329
- // review:深层字段缺失守卫(message 缺失时返回空摘要而非 TypeError)
329
+
330
330
  if (!message || typeof message !== "object") return { seq, type };
331
- // v3.0.0(版本二):嵌套收集——tool-result 内的图片块(read_image 等工具结果)也要带出
331
+
332
332
  const images = imagesOfNested(message.content);
333
- // 需求变更(issue #1):assistant 产出文件的元数据不再下发——时间线不提供该下载入口。
334
- // 用户自己的附件仍走 user/message 分支的 files(保留)。
335
- // 思维链正文:下发给移动端做可折叠「思维链」块(空则不发送该字段)
333
+
334
+
335
+
336
336
  const reasoning = reasoningText(message.content);
337
337
  return {
338
338
  seq,
@@ -340,7 +340,7 @@ function summarizeEventCore(event) {
340
340
  data: {
341
341
  turn: data.turn,
342
342
  step: data.step,
343
- // messageId 供消息反馈(👍/👎,对齐 PC 端 messageFeedback 服务)
343
+
344
344
  messageId: message.id,
345
345
  text: clampText(blocksToText(message.content), 20000),
346
346
  reasoningChars: reasoningChars(message.content),
@@ -367,7 +367,7 @@ function summarizeEventCore(event) {
367
367
  argumentsDelta: clampText(String(chunk.argumentsDelta ?? ""), 2000),
368
368
  },
369
369
  };
370
- return { seq, type, data: null }; // block-start/block-end/usage/finish:前端忽略
370
+ return { seq, type, data: null };
371
371
  }
372
372
  case "tool/call": {
373
373
  let argumentsText = data.arguments;
@@ -377,18 +377,18 @@ function summarizeEventCore(event) {
377
377
  return { seq, type, data: { turn: data.turn, step: data.step, callId: data.callId, name: data.name, arguments: clampText(argumentsText, 2000) } };
378
378
  }
379
379
  case "tool/result": {
380
- // v3.0.0(版本二):对齐 PC contentParts 语义——content 为 tool-result 块数组,
381
- // 图片嵌套在其 content 内;文本跨全部块合并(此前仅取 content[0] 单块)
380
+
381
+
382
382
  const message = data.message;
383
383
  const blocks = Array.isArray(message?.content) ? message.content : [];
384
- // 兼容旧宿主/测试夹具直接提供的 { callId, name, text, isError } wire 形态。
384
+
385
385
  let callId = typeof data.callId === "string" ? data.callId : typeof data.toolCallId === "string" ? data.toolCallId : "";
386
386
  let isError = data.error !== undefined || data.isError === true;
387
387
  let text = typeof data.text === "string" ? data.text : "";
388
388
  const images = Array.isArray(data.images)
389
389
  ? data.images.map(imageMetaOf).filter(Boolean).slice(0, 20)
390
390
  : [];
391
- // 需求变更(issue #1):工具产出文件的元数据不再下发(时间线不提供该下载入口)。
391
+
392
392
  for (const b of blocks) {
393
393
  if (!b || typeof b !== "object") continue;
394
394
  const inner = Array.isArray(b.content) ? b.content : [b];
@@ -399,10 +399,10 @@ function summarizeEventCore(event) {
399
399
  }
400
400
  const errName = typeof data.error?.name === "string" && data.error?.name !== "" ? data.error.name : "";
401
401
  const directName = typeof data.name === "string" && data.name !== "" ? data.name : "";
402
- // v3.1.5 修复:结果事件缺工具名时**不再用 callId 兜底**。callId 是关联 id,
403
- // 不是工具名——历史回放里 App 的合并规则会让结果事件的名字覆盖 `tool/call`
404
- // 学到的真名,于是已结束的工具卡标题变成裸 `call_00_...`(进行中的那张正常)。
405
- // 名字未知就不下发该字段,由消费端自行兜底显示「工具」。
402
+
403
+
404
+
405
+
406
406
  const resultName = directName || errName;
407
407
  return {
408
408
  seq,
@@ -419,9 +419,9 @@ function summarizeEventCore(event) {
419
419
  };
420
420
  }
421
421
  case "todo/write": {
422
- // v3.1.4(issue #12 姊妹需求):内核 dsh-tool-todo 每次调用写入**整份清单快照**
423
- // ({ todos: [{ content, status }] },status ∈ pending / in_progress / completed)。
424
- // 投影语义:最新一份覆盖,`turn/start` 清空——App 任务面板按同一语义折叠。
422
+
423
+
424
+
425
425
  const list = Array.isArray(data.todos) ? data.todos : [];
426
426
  return {
427
427
  seq,
@@ -443,11 +443,11 @@ function summarizeEventCore(event) {
443
443
  }
444
444
  }
445
445
 
446
- /**
447
- * 详情正文长度提示:仅 `assistant/message` 提供,值为**与摘要同一 `blocksToText`** 提取的
448
- * 正文长度(未截断、不含 reasoning/内部块)。客户端据此判断「详情是否真有正文增量」,
449
- * 从而只在有增量时才显示加载按钮(issue #1 需求变更)。
450
- */
446
+
447
+
448
+
449
+
450
+
451
451
  function detailTextCharsHint(event) {
452
452
  if (event?.type !== "assistant/message") return {};
453
453
  const content = event?.data?.message?.content;
@@ -455,16 +455,16 @@ function detailTextCharsHint(event) {
455
455
  return { textChars: blocksToText(content).length };
456
456
  }
457
457
 
458
- /**
459
- * 详情响应体:原始事件 + 规范化正文。
460
- *
461
- * `assistant/message` 额外附 `data.text`——用**与事件摘要同一个 `blocksToText`** 提取
462
- * (只拼 `text` 块,跳过 `reasoning` 与内部块)。客户端必须直接采用该字段,不得自行递归
463
- * 拼接 `message.content`(那会把 reasoning 并进正文,使思维链在折叠块之外重复出现——
464
- * issue #1 需求变更)。原始 `message` 块原样保留,无损详情语义不变。
465
- *
466
- * 导出为纯函数,供契约自检直接断言(tools/timeline-contract-check.mjs)。
467
- */
458
+
459
+
460
+
461
+
462
+
463
+
464
+
465
+
466
+
467
+
468
468
  export function detailEventFor(event) {
469
469
  const detailEvent = { ...event };
470
470
  if (event?.type === "assistant/message" && event.data && typeof event.data === "object") {
@@ -474,16 +474,16 @@ export function detailEventFor(event) {
474
474
  return detailEvent;
475
475
  }
476
476
 
477
- /**
478
- * 移动端事件摘要:保留轻量 data,同时声明可通过 seq 读取无损详情。
479
- * 老客户端只会忽略新增的 detail 字段,保持向后兼容。
480
- */
477
+
478
+
479
+
480
+
481
481
  export function summarizeEvent(event) {
482
482
  const summary = summarizeEventCore(event);
483
483
  if (event?.seq === undefined || event?.seq === null) return summary;
484
- // 只对详情端点真的能取回的事件声明指针:token delta / 内部记录会被 /event-detail
485
- // 拒绝(isTimelineRecord),未列入 allow-list 的类型同样会被拒(fail-closed)。
486
- // 声明 available 只会让 App 显示一个必然 404 的按钮,所以两重判据都要过。
484
+
485
+
486
+
487
487
  if (!isTimelineRecord(event) || !isDetailVisibleType(event.type)) return summary;
488
488
  return {
489
489
  ...summary,