@marktrue/dsh-mobile-remote 3.2.4-alpha.1 → 3.2.4-alpha.10

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.
package/lib/index.js CHANGED
@@ -10,8 +10,8 @@
10
10
  import { networkInterfaces, homedir } from "node:os";
11
11
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
12
12
  import {
13
- accessSync, closeSync, constants, createReadStream, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, renameSync,
14
- rmSync, statSync, writeFileSync,
13
+ accessSync, closeSync, constants, createReadStream, existsSync, fstatSync, linkSync, mkdirSync, openSync,
14
+ readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, unlinkSync,
15
15
  } from "node:fs";
16
16
  import { readdir } from "node:fs/promises";
17
17
  import { join, sep, resolve, relative, isAbsolute, basename, dirname, extname } from "node:path";
@@ -51,6 +51,16 @@ import {
51
51
  selectBridgeEndpoint,
52
52
  } from "./desktop-form.js";
53
53
  import { detectInstallShape } from "./plugin-update.js";
54
+ import {
55
+ chooseUpdateChannel,
56
+ describeUpdateChannel,
57
+ detectHostUpdateCapabilities,
58
+ HOST_MANAGER_REASON,
59
+ HOST_MANAGER_STATE,
60
+ probeHostPluginManager,
61
+ UPDATE_CHANNEL,
62
+ } from "./host-update-capabilities.js";
63
+ import { runHostManagerUpdate } from "./host-manager-update.js";
54
64
  import {
55
65
  TRANSACTION_PHASE,
56
66
  checkForUpdate,
@@ -61,6 +71,7 @@ import {
61
71
  resolvePluginUpdateSource,
62
72
  resolvePluginUrl,
63
73
  restartPlan,
74
+ respawnCommandOf,
64
75
  runRestart,
65
76
  runSelfUpdate,
66
77
  UPDATE_SOURCE_KIND,
@@ -332,6 +343,64 @@ export function pluginStateDir(home = homedir()) {
332
343
  export function generatedAuthTokenFile(home = homedir()) {
333
344
  return join(pluginStateDir(home), "auth-token");
334
345
  }
346
+ /**
347
+ * 宿主的**稳定身份**文件(issue #60 R15):随机 UUID 持久化到插件状态目录。
348
+ * 与访问口令解耦:口令可被用户显式配置成相同值,不能拿它当宿主身份;同一宿主跨
349
+ * 重启/地址轮换保持不变,不同宿主(不同 home/状态目录)必然不同。
350
+ */
351
+ export function hostIdentityFile(home = homedir()) {
352
+ return join(pluginStateDir(home), "host-identity");
353
+ }
354
+
355
+ /**
356
+ * 发布稳定宿主身份:先完整写私有文件,再以 hard link 原子、不可覆盖地发布。
357
+ * 已存在但无效的身份可能属于暂停的旧写入者;无法安全判定其死亡,绝不自动删除。
358
+ * 所有实例切换到本协议前须停止旧版宿主;恢复损坏文件前也须停止所有宿主并先备份。
359
+ * 首次发布要求同一文件系统支持 hard link;不可用时显式拒绝启动而非伪造稳定身份。
360
+ */
361
+ export function resolveHostIdentity({ home = homedir(), onBeforePublish } = {}) {
362
+ const file = hostIdentityFile(home);
363
+ const valid = value => typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value.trim());
364
+ const readIdentity = () => {
365
+ try { const value = readFileSync(file, "utf8").trim(); return valid(value) ? value : null; }
366
+ catch { return null; }
367
+ };
368
+ const unavailable = () => Object.assign(new Error("host identity unavailable; stop all hosts and inspect the identity file"), { code: "HOST_IDENTITY_LOCK_UNAVAILABLE" });
369
+ const existing = readIdentity();
370
+ if (existing !== null) return existing;
371
+ let temporary;
372
+ try {
373
+ mkdirSync(pluginStateDir(home), { recursive: true, mode: 0o700 });
374
+ temporary = `${file}.candidate.${process.pid}.${randomBytes(12).toString("hex")}`;
375
+ const identity = randomUUID();
376
+ writeFileSync(temporary, `${identity}\n`, { flag: "wx", mode: 0o600 });
377
+ onBeforePublish?.();
378
+ try { linkSync(temporary, file); }
379
+ catch (err) {
380
+ if (err?.code !== "EEXIST") throw err;
381
+ // 旧版进程可能刚以 wx 创建空文件,给它有限时间写入;绝不清理占位。
382
+ const deadline = Date.now() + 3000;
383
+ while (Date.now() < deadline) {
384
+ const published = readIdentity();
385
+ if (published !== null) return published;
386
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
387
+ }
388
+ throw unavailable();
389
+ }
390
+ const published = readIdentity();
391
+ if (published !== null) return published;
392
+ throw unavailable();
393
+ } catch (err) {
394
+ const published = readIdentity();
395
+ if (published !== null) return published;
396
+ if (err?.code === "HOST_IDENTITY_LOCK_UNAVAILABLE") throw err;
397
+ // 只暴露固定错误码,不把宿主路径等系统错误正文写入日志。
398
+ throw Object.assign(new Error("host identity storage cannot publish an atomic hard link"), { code: "HOST_IDENTITY_STORAGE_UNAVAILABLE" });
399
+ } finally {
400
+ if (temporary) { try { unlinkSync(temporary); } catch { /* private candidate only */ } }
401
+ }
402
+ }
403
+
335
404
  /** randomBytes(32) 的 base64url 恰好 43 个 URL-safe 字符。 */
336
405
  const GENERATED_TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
337
406
 
@@ -723,6 +792,95 @@ const TURN_OUTLINE_CAPABILITIES = {
723
792
  /** 宿主未挂载该投影时的能力声明:必须与"可用"区分,App 据此退回一期行为。 */
724
793
  const TURN_OUTLINE_CAPABILITY_MISSING = { version: 1, supported: false };
725
794
 
795
+ /**
796
+ * 轮末产出物能力位(v3.3,issue #53 / docs/03-api.md §6.20)。
797
+ *
798
+ * `presented` 恒为真(本插件负责投影 `deliverables/presented` 声明);
799
+ * `changed`/`changesDiff` 只在宿主**真的注册**了 `workspaceChanges` 服务时为真,
800
+ * 不按宿主版本推断(ADR 0017 三态探测)。
801
+ */
802
+ const TURN_TAIL_CAPABILITY_VERSION = 1;
803
+ /** 摘要文件列表的移动端上限(§6.21;超出的部分展示 `truncated`,`total` 仍是全量)。 */
804
+ export const TURN_TAIL_MAX_FILES = 200;
805
+ /** 统一 diff 文本体积上限(§6.22):超出按行边界截断并置 `truncated`。 */
806
+ export const TURN_TAIL_DIFF_MAX_BYTES = 512 * 1024;
807
+
808
+ /**
809
+ * M3(issue #54 Batch 1 / issue #66 Batch 2-A):本插件实际投影的工具集合与能力位。
810
+ *
811
+ * App 以 `capabilities.toolCards.tools` 决定哪些工具用专用卡;未列入的工具(未知/自定义)
812
+ * 一律回退现有通用卡。声明按**本插件实现**给出,不按宿主版本推断(ADR 0017)。
813
+ * issue #66:追加 todo_write / ask_user_question / skill 三个非文件工具(只增集合、version 不变)。
814
+ */
815
+ export const TOOL_CARD_TOOLS = Object.freeze([
816
+ "bash",
817
+ "pwsh",
818
+ "read",
819
+ "write",
820
+ "edit",
821
+ "grep",
822
+ "glob",
823
+ "web_fetch",
824
+ "web_search",
825
+ "read_image",
826
+ "todo_write",
827
+ "ask_user_question",
828
+ "skill",
829
+ ]);
830
+ /** 工具卡结构化投影版本(只增不改)。 */
831
+ export const TOOL_CARDS_CAPABILITY_VERSION = 1;
832
+ /** PTC 子调用树的工具卡能力版本(issue #68,只增不改)。 */
833
+ export const TOOL_CARDS_PTC_VERSION = 1;
834
+ /** PTC 子调用投影上限(issue #68 契约 §1.6):同一 root 最多 50 个子调用。 */
835
+ const PTC_MAX_SUBCALLS = 50;
836
+ /** 单个子调用 summary 的 JSON 体积预算(issue #68 契约 §1.4,超出整份降级)。 */
837
+ const PTC_MAX_SUMMARY_BYTES = 2048;
838
+ /** PTC 事件 id 长度上限(rootCallId/parentCallId/callId);超长一律视为非法。 */
839
+ const PTC_MAX_ID_LENGTH = 300;
840
+ /** write/edit 摘要内联 diff 的体积上限(§issue #54 note 1761):超出缺省并标 diffTruncated。 */
841
+ export const TOOL_CARD_DIFF_MAX_BYTES = 8 * 1024;
842
+ /**
843
+ * issue #67:工具卡路径可预览的 cwd 相对路径上限(§6.24)。
844
+ * 超长**整段缺省**,绝不截断——截断后的路径会指向另一个文件。
845
+ */
846
+ export const TOOL_CARD_PREVIEW_PATH_MAX = 300;
847
+ /** 工具名 → 卡片 kind(未列入即通用卡)。 */
848
+ const TOOL_CARD_KIND = Object.freeze({
849
+ bash: "command",
850
+ pwsh: "command",
851
+ read: "file",
852
+ write: "file",
853
+ edit: "file",
854
+ grep: "search",
855
+ glob: "search",
856
+ web_fetch: "web",
857
+ web_search: "web",
858
+ read_image: "image",
859
+ todo_write: "todo",
860
+ ask_user_question: "question",
861
+ skill: "skill",
862
+ });
863
+
864
+ /**
865
+ * issue #66(M3 Batch 2-A)非文件工具投影上限(团队契约 /tmp/issue66-contract.md §1.2–§1.3)。
866
+ * 全部只影响摘要体积,超限按契约截断/丢弃,绝不抛错。
867
+ */
868
+ const TOOL_CARD_MAX_TODO_ITEMS = 50;
869
+ const TOOL_CARD_MAX_TODO_CONTENT = 200;
870
+ const TOOL_CARD_MAX_QUESTIONS = 10;
871
+ const TOOL_CARD_MAX_QUESTION_ID = 120;
872
+ const TOOL_CARD_MAX_QUESTION_TEXT = 300;
873
+ const TOOL_CARD_MAX_QUESTION_HEADER = 80;
874
+ const TOOL_CARD_MAX_QUESTION_OPTIONS = 20;
875
+ const TOOL_CARD_MAX_OPTION_LABEL = 120;
876
+ const TOOL_CARD_MAX_OPTION_DESCRIPTION = 200;
877
+ const TOOL_CARD_MAX_SKILL_NAME = 120;
878
+ const TOOL_CARD_MAX_ANSWER_ITEMS = 10;
879
+ const TOOL_CARD_MAX_ANSWER_VALUES = 20;
880
+ const TOOL_CARD_MAX_ANSWER_TEXT = 200;
881
+ /** todo 状态的宿主枚举(与 `todo/write` 事件投影同口径)。 */
882
+ const TOOL_CARD_TODO_STATUSES = Object.freeze(["pending", "in_progress", "completed"]);
883
+
726
884
  /**
727
885
  * 冷折叠有界等待上限(issue #25 性能前置实测,2026-10-09):单会话最坏实测 1.8 s
728
886
  * (证据见 reports/25-cold-fold-20261009.md),并发时单会话仍 ≤1.8 s;5 s ≈3× 余量。
@@ -891,6 +1049,47 @@ export function turnOutlineCapabilityOf(ctx) {
891
1049
  return registered && observable ? TURN_OUTLINE_CAPABILITIES : TURN_OUTLINE_CAPABILITY_MISSING;
892
1050
  }
893
1051
 
1052
+ /**
1053
+ * 轮末产出物能力探测(issue #53):bootstrap、SSE hello 与三个端点必须使用同一判据。
1054
+ * 宿主没有 `workspaceChanges` 时仍声明 `presented: true`(交付文件来自会话日志),
1055
+ * 但 `changed`/`changesDiff` 为假,App 据此不渲染改动卡。
1056
+ * @param {any} ctx 插件上下文。
1057
+ * @returns {{version: number, presented: boolean, changed: boolean, changesDiff: boolean}}
1058
+ */
1059
+ export function turnTailCapabilityOf(ctx) {
1060
+ const service = ctx.get("workspaceChanges");
1061
+ let readable = false;
1062
+ let diffable = false;
1063
+ try {
1064
+ readable = typeof service?.summary === "function";
1065
+ diffable = typeof service?.diff === "function";
1066
+ } catch {
1067
+ readable = false;
1068
+ diffable = false;
1069
+ }
1070
+ return {
1071
+ version: TURN_TAIL_CAPABILITY_VERSION,
1072
+ presented: true,
1073
+ changed: readable,
1074
+ changesDiff: readable && diffable,
1075
+ };
1076
+ }
1077
+
1078
+ /**
1079
+ * 工具卡能力位(issue #54):始终声明本插件实际投影的工具集合。
1080
+ * bootstrap 与 SSE hello 同判据、同形状;旧插件不下发 → App 全部回退通用卡。
1081
+ * issue #68:追加 `ptc: { version: 1 }`(子调用树);键序保持 version→tools→ptc,
1082
+ * 既有 `"toolCards":{"version":1,"tools":` 文本断言不受影响。
1083
+ * @returns {{version: number, tools: string[], ptc: {version: number}}}
1084
+ */
1085
+ export function toolCardsCapabilityOf() {
1086
+ return {
1087
+ version: TOOL_CARDS_CAPABILITY_VERSION,
1088
+ tools: [...TOOL_CARD_TOOLS],
1089
+ ptc: { version: TOOL_CARDS_PTC_VERSION },
1090
+ };
1091
+ }
1092
+
894
1093
  /**
895
1094
  * 新端点专用的失败分类:在通用分类之上,**先**识别整条 cause 链里的 seeded 前缀缺陷。
896
1095
  * 真实宿主的 `observeSession` 会把这个已知兼容缺陷包进
@@ -990,6 +1189,10 @@ const REPLAY_IGNORED_TYPES = new Set([
990
1189
  "compaction/summary",
991
1190
  "compaction/prune",
992
1191
  "compaction/end",
1192
+ // issue #53(ADR 0027 §4):`workspace/changes` 只携带轮号,对移动时间线没有呈现价值;
1193
+ // 移出移动时间线投影(历史、实时、/event-detail 三处同规则),会话日志仍是宿主事实。
1194
+ // 这不是丢未知事件(对照 ADR 0006):已知且不具呈现价值的事件不进移动时间线。
1195
+ "workspace/changes",
993
1196
  ]);
994
1197
  /** 请求快照的命名约定:类型以 `llm-request` 结尾,前一段分隔符为 `/` 或 `-`
995
1198
  * (内核现实形态:`session/title-llm-request`、`web/deepseek-search-llm-request`;
@@ -1166,6 +1369,16 @@ const FILE_MIME = {
1166
1369
  };
1167
1370
  const fileMimeOf = (name) => FILE_MIME[extname(name).toLowerCase()] ?? "application/octet-stream";
1168
1371
 
1372
+ /**
1373
+ * `GET /m/api/directories` 条目可见性(issue #45)。
1374
+ *
1375
+ * 默认隐藏所有点开头条目;`includeHidden=1` 时保留点开头文件/目录。
1376
+ * 名称恰为 `.git` 的条目(文件或目录)**永远排除**:既避免把对象库/可能含
1377
+ * 凭据的 `.git/config` 暴露给文件浏览,也不提供进入其内部的入口。
1378
+ * dirs / files / fileEntries 三条列表共用这一条规则,避免实现分叉。
1379
+ */
1380
+ const directoryEntryVisible = (name, includeHidden) => name !== ".git" && (includeHidden || !String(name).startsWith("."));
1381
+
1169
1382
  /** 旧宿主逐个标题兜底的读取宽度:与宿主 `persistedReadConcurrency` 默认值一致(≤4)。 */
1170
1383
  const TITLE_FALLBACK_READ_WIDTH = DEFAULT_TITLE_REFRESH_CONCURRENCY;
1171
1384
  /**
@@ -1668,11 +1881,1046 @@ function sniffImageType(data) {
1668
1881
  return null;
1669
1882
  }
1670
1883
 
1884
+ /** 把路径统一成 POSIX 斜杠文本(`display` 契约始终用 `/` 分隔,§6.21)。 */
1885
+ const posixPathText = (value) => String(value ?? "").replaceAll("\\", "/");
1886
+ /** 是否绝对路径(POSIX 根 / Windows 盘符);`display` 派生只看文本,不依赖宿主平台。 */
1887
+ const isAbsolutePathText = (value) => value.startsWith("/") || /^[A-Za-z]:\//.test(value);
1888
+ /**
1889
+ * issue #60 round7(F2):把「记录路径 + 会话 cwd」归一到同一规范绝对路径。
1890
+ * 宿主两条投影的路径形状可能不同:presented 常是 realpath 绝对路径(或相对),
1891
+ * changed 常是相对路径;两处 cwd 文本也可能不同(header.cwd 含 symlink 别名、
1892
+ * summary.cwd 是 realpath 或子目录)。只靠文本 resolve 会发散,故哈希/派生前统一:
1893
+ * 1) 仅对会话 cwd 做 realpath,合并同一工作目录的符号链接别名;
1894
+ * 2) 记录路径按 cwd 词法展开,保留各路径段(包括符号链接条目)作为文件身份。
1895
+ * 任何失败都 try/catch 兜底退回纯文本 resolve,**绝不因 realpath 抛错**、
1896
+ * 也绝不改变 id 的格式(仍是 sha256 前 16 hex、不可逆、不含可拼路径)。
1897
+ * 注意:本函数只在服务端内部用于派生 id / display,规范绝对路径绝不下发到任何响应。
1898
+ * @returns {string} 规范绝对路径文本;path 非法时返回空串。
1899
+ */
1900
+ const canonicalWorkspacePath = (path, cwd) => {
1901
+ const text = normalizeServerPath(path);
1902
+ if (typeof text !== "string" || text === "") return "";
1903
+ if (typeof cwd !== "string" || cwd === "") return isAbsolute(text) ? resolve(text) : text;
1904
+ const lexicalCwd = resolve(normalizeServerPath(cwd));
1905
+ let canonicalCwd = lexicalCwd;
1906
+ try { canonicalCwd = realpathSync(lexicalCwd); } catch { /* unavailable cwd */ }
1907
+ const absolute = isAbsolute(text) ? resolve(text) : resolve(lexicalCwd, text);
1908
+ const within = (root, target) => {
1909
+ const rel = relative(root, target);
1910
+ return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
1911
+ };
1912
+ // 只解析 cwd 本身的别名;保留记录相对路径每一段,包括末级/中间符号链接。
1913
+ // Git 工作区中符号链接条目和目标是不同记录,不能对文件全路径调用 realpath。
1914
+ if (within(lexicalCwd, absolute)) return resolve(canonicalCwd, relative(lexicalCwd, absolute));
1915
+ if (within(canonicalCwd, absolute)) return absolute;
1916
+ // 绝对路径可能通过 cwd 的另一别名进入工作区(如 /var/run 与 /run)。
1917
+ // 只寻找真实指向 cwd 的祖先;保留其后的每一段,即使中间条目是符号链接或不存在。
1918
+ let head = dirname(absolute);
1919
+ const suffix = [basename(absolute)];
1920
+ let entryPath = null;
1921
+ while (true) {
1922
+ // 取最外层 cwd 别名。内层 symlink 也可能恰好指回 cwd,不能把它当别名吞掉。
1923
+ try { if (realpathSync(head) === canonicalCwd) entryPath = resolve(canonicalCwd, ...suffix); }
1924
+ catch { /* 尚不存在或不可读:继续寻找更高祖先 */ }
1925
+ const parent = dirname(head);
1926
+ if (parent === head) break;
1927
+ suffix.unshift(basename(head));
1928
+ head = parent;
1929
+ }
1930
+ return entryPath ?? absolute;
1931
+ };
1932
+ /**
1933
+ * 记录内文件的**不泄路径稳定身份**(issue #60 round4-2 / R08):
1934
+ * 路径 SHA-256 前 16 位十六进制。presented 与 changed 两条投影必须使用同一 helper,
1935
+ * App 才能把同一逻辑文件在两种来源下合并(不可逆、不含主机前缀)。
1936
+ * @param {unknown} path 记录内的路径(绝对或相对)。
1937
+ * @param {unknown} cwd 会话工作目录(两处调用须同源,见 /changes/summary 的 idBase)。
1938
+ * @returns {string} 16 位 hex;path 非法时返回空串。
1939
+ */
1940
+ export function recordFileId(path, cwd) {
1941
+ if (typeof path !== "string" || path === "") return "";
1942
+ const canonical = canonicalWorkspacePath(path, cwd);
1943
+ if (canonical === "") return "";
1944
+ return createHash("sha256").update(canonical).digest("hex").slice(0, 16);
1945
+ }
1946
+
1947
+ /** 不依赖宿主平台的 basename(`basename()` 在 Windows 路径上会保留反斜杠段)。 */
1948
+ const posixBasenameOf = (value) => {
1949
+ const text = posixPathText(value).replace(/\/+$/, "");
1950
+ const index = text.lastIndexOf("/");
1951
+ const base = index >= 0 ? text.slice(index + 1) : text;
1952
+ return base === "" ? "file" : base;
1953
+ };
1954
+
1955
+ /**
1956
+ * `deliverables/presented` 的 `display` 派生(issue #53 / §6.20):
1957
+ * 工作目录内给相对路径,家目录下给 `~/…`,其余**只给 basename**——绝不把主机绝对
1958
+ * 路径交给客户端。`cwd` 未知(休眠会话/旧宿主)时退化为 basename。
1959
+ * @param {unknown} path 记录里的原始路径。
1960
+ * @param {unknown} cwd 会话工作目录(宿主侧事实,只用于派生,不下发)。
1961
+ * @returns {string} 可展示路径(永不包含可拼接的绝对路径)。
1962
+ */
1963
+ export function mobileDisplayPath(path, cwd) {
1964
+ const text = posixPathText(path).trim();
1965
+ if (text === "") return "";
1966
+ if (!isAbsolutePathText(text)) return text.replace(/^\.\//, "");
1967
+ // issue #60(F2):规范 cwd 及其别名、保留工作区内的词法条目后再比较,避免
1968
+ // presented 绝对路径落在 symlink 别名 cwd 的「文本之外」而退化成 basename,
1969
+ // changed 却是 `src/a.ts`(display 不一致 → App 精确链接丢失)。
1970
+ // canonicalWorkspacePath 只在服务端内部使用;返回的相对/`~/`/basename 满足 R05,
1971
+ // 绝不把规范绝对路径写进响应。
1972
+ const canonicalPath = posixPathText(canonicalWorkspacePath(text, cwd));
1973
+ let cwdText = typeof cwd === "string" && cwd !== "" ? posixPathText(cwd).replace(/\/+$/, "") : "";
1974
+ if (cwdText !== "") {
1975
+ try { cwdText = realpathSync(cwdText); } catch { /* cwd 不存在:退回原文本 */ }
1976
+ cwdText = posixPathText(cwdText).replace(/\/+$/, "");
1977
+ }
1978
+ if (cwdText !== "" && (canonicalPath === cwdText || canonicalPath.startsWith(`${cwdText}/`))) {
1979
+ const rel = canonicalPath.slice(cwdText.length).replace(/^\/+/, "");
1980
+ return rel === "" ? posixBasenameOf(canonicalPath) : rel;
1981
+ }
1982
+ const homeText = posixPathText(homedir()).replace(/\/+$/, "");
1983
+ if (homeText !== "" && canonicalPath.startsWith(`${homeText}/`)) return `~/${canonicalPath.slice(homeText.length + 1)}`;
1984
+ return posixBasenameOf(canonicalPath);
1985
+ }
1986
+
1987
+ /** 词法包含判定(与 `canonicalWorkspacePath` 内的 `within` 同式;issue #67 独立实现,不重构既有函数)。 */
1988
+ const isWithinDir = (root, target) => {
1989
+ const rel = relative(root, target);
1990
+ return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
1991
+ };
1992
+
1993
+ /**
1994
+ * issue #67(M3 Batch 2-B):工具卡路径的**可预览目标**(§6.24)。
1995
+ *
1996
+ * 输入是工具原始参数里的 `file_path`/`filePath` 与**会话 cwd**,输出仅
1997
+ * `{ relative, previewable: true }` 或 `null`(两字段一起缺省)。语义是 fail-closed:
1998
+ * - **本函数的判定**全部词法校验先做、零 fs 调用;cwd 之外的绝对路径**绝不**触发
1999
+ * realpath/stat(否则判定会变成对任意敏感目录的存在性探测器);
2000
+ * - 只有词法已在 cwd 内的候选才做 realpath containment(拒绝符号链接逃逸)
2001
+ * 与 isFile / R_OK 验证;
2002
+ * - 输出恒为 cwd 相对 POSIX 路径(无前导 `/`、无盘符、无 `.`/`..`/空段,
2003
+ * ≤300 字且**绝不截断**——截断会指向另一个文件)。
2004
+ * 边界(reviewer P1):同一条 `tool/call` 摘要里的 `display`(`filePath` 等)由
2005
+ * `mobileDisplayPath` → `canonicalWorkspacePath`(issue #60 F2)派生,它会为合并
2006
+ * cwd 符号链接别名而对**已给出的绝对路径祖先**做 realpath;那是 #54/#60 既有行为,
2007
+ * 不属于 #67 新增的探测面,且本 issue 不修改它。即:**preview 判定零探测,整条摘要
2008
+ * 链路不承诺零探测**(绝对路径祖先的 realpath 由 display 派生承担)。
2009
+ * 只供摘要投影使用;不改变 `mobileDisplayPath`/`display` 语义,也不下发任何绝对路径。
2010
+ * @param {unknown} rawPath 工具原始参数里的路径。
2011
+ * @param {unknown} cwd 会话工作目录(宿主侧事实,不下发)。
2012
+ * @returns {{relative: string, previewable: true} | null}
2013
+ */
2014
+ export function previewTargetOf(rawPath, cwd) {
2015
+ // A. 词法(零 fs 调用)
2016
+ if (typeof rawPath !== "string" || rawPath === "") return null;
2017
+ if (rawPath.length > 4096) return null;
2018
+ if (rawPath.includes("\0")) return null;
2019
+ // display 会 trim;保留首尾空白会让「显示的目标」与「跳转的目标」不一致,直接拒绝。
2020
+ if (rawPath !== rawPath.trim()) return null;
2021
+ // reviewer P2:POSIX 上 `\` 是合法文件名字符,不是分隔符。若把它归一成 `/`,
2022
+ // 字面文件 `dir\a` 与 `dir/a` 同时存在时摘要会指向**另一份文件**(点击打开错文件)。
2023
+ // 因此只有 cwd 呈 Windows 形态(那里 `\` 是分隔符、不存在字面反斜杠文件名)才保留
2024
+ // `\`→`/` 归一;检测必须用**原始 cwd 字符串**,不能用 posixPathText 归一后的值。
2025
+ const windowsCwd =
2026
+ typeof cwd === "string" &&
2027
+ (/^[A-Za-z]:[\\/]/.test(cwd) || (cwd.includes("\\") && !cwd.startsWith("/")));
2028
+ if (!windowsCwd && rawPath.includes("\\")) return null;
2029
+ const text = posixPathText(rawPath).replace(/^\.\//, "");
2030
+ if (text === "") return null;
2031
+ const absolute = isAbsolutePathText(text);
2032
+ let segments;
2033
+ if (absolute) {
2034
+ // 剥盘符前缀与一个前导 `/`;剥掉的前缀不参与输出(Windows 盘符绝对路径在 cwd 内时仍可换算)。
2035
+ let rest = text.replace(/^[A-Za-z]:/, "");
2036
+ if (rest.startsWith("/")) rest = rest.slice(1);
2037
+ segments = rest === "" ? [] : rest.split("/");
2038
+ } else {
2039
+ segments = text.split("/");
2040
+ }
2041
+ // 空段 / `.` / `..` / 含 `:` 段一律拒绝;只剥一次前导 `./`(与 display 同式)。
2042
+ if (segments.length === 0) return null;
2043
+ for (const segment of segments) {
2044
+ if (segment === "" || segment === "." || segment === ".." || segment.includes(":")) return null;
2045
+ }
2046
+ // B. cwd(fs 只碰 cwd 自身)
2047
+ if (typeof cwd !== "string" || cwd === "") return null;
2048
+ if (!isAbsolutePathText(posixPathText(cwd))) return null;
2049
+ const rootLex = resolve(normalizeServerPath(cwd));
2050
+ let rootReal;
2051
+ try { rootReal = realpathSync(rootLex); } catch { return null; }
2052
+ let rootStat;
2053
+ try { rootStat = statSync(rootReal); } catch { return null; }
2054
+ if (!rootStat.isDirectory()) return null;
2055
+ // C. 词法夹取(fs 之前完成)
2056
+ let targetAbs;
2057
+ if (absolute) {
2058
+ targetAbs = resolve(normalizeServerPath(text));
2059
+ // cwd 外的绝对路径在这里就返回:绝不 realpath/stat 候选。
2060
+ if (!isWithinDir(rootLex, targetAbs) && !isWithinDir(rootReal, targetAbs)) return null;
2061
+ } else {
2062
+ targetAbs = resolve(rootLex, ...segments);
2063
+ }
2064
+ // D. 相对文本(取用户路径的词法形状,realpath 只当闸门)
2065
+ const base = isWithinDir(rootLex, targetAbs) ? rootLex : rootReal;
2066
+ const rel = posixPathText(relative(base, targetAbs));
2067
+ if (rel === "" || isAbsolutePathText(rel)) return null;
2068
+ for (const segment of rel.split("/")) {
2069
+ if (segment === "" || segment === "." || segment === ".." || segment.includes(":")) return null;
2070
+ }
2071
+ if (rel.length > TOOL_CARD_PREVIEW_PATH_MAX) return null;
2072
+ // E. 目标验证(fs 只碰候选)
2073
+ let realTarget;
2074
+ try { realTarget = realpathSync(targetAbs); } catch { return null; }
2075
+ if (!isWithinDir(rootReal, realTarget)) return null; // 符号链接逃逸
2076
+ let targetStat;
2077
+ try { targetStat = statSync(realTarget); } catch { return null; }
2078
+ if (!targetStat.isFile()) return null; // 目录 / FIFO / socket / 设备
2079
+ try { accessSync(realTarget, constants.R_OK); } catch { return null; }
2080
+ return { relative: rel, previewable: true };
2081
+ }
2082
+
2083
+ /**
2084
+ * 从会话事件折叠 `callId → tool/call.name`(issue #60 R14):结果事件通常不带工具名,
2085
+ * 调用方用它在投影前解析"这次调用是什么工具",避免无名字时从内容猜终止状态。
2086
+ * @param {any[]} events 会话原始事件。
2087
+ * @returns {Map<string, string>}
2088
+ */
2089
+ export function toolNamesOf(events) {
2090
+ const names = new Map();
2091
+ for (const event of events ?? []) {
2092
+ if (event?.type !== "tool/call") continue;
2093
+ const callId = event?.data?.callId;
2094
+ const name = event?.data?.name;
2095
+ if (typeof callId === "string" && callId !== "" && typeof name === "string" && name !== "") {
2096
+ names.set(callId, name);
2097
+ }
2098
+ }
2099
+ return names;
2100
+ }
2101
+
2102
+ /**
2103
+ * `tool/result` 的真实调用坐标(issue #60 recheck-4 / R14):
2104
+ * 当前内核把 callId 放在 `message.source.callId`、`message.toolCallId` 或
2105
+ * `message.content[].toolCallId`,**不在** `event.data.callId`。统一从这些位置提取,
2106
+ * 供摘要 callId、toolNamesOf 关联(history/SSE)与 App 生命周期合并共用。
2107
+ * @param {any} event tool/result 事件。
2108
+ * @returns {string} callId;无法确定时为空串。
2109
+ */
2110
+ export function toolResultCallIdOf(event) {
2111
+ const data = event?.data ?? {};
2112
+ const message = data.message;
2113
+ const content = Array.isArray(message?.content) ? message.content : [];
2114
+ const candidates = [
2115
+ data.callId,
2116
+ data.toolCallId,
2117
+ message?.toolCallId,
2118
+ message?.source?.callId,
2119
+ ];
2120
+ for (const block of content) {
2121
+ if (!block || typeof block !== "object") continue;
2122
+ candidates.push(block.toolCallId);
2123
+ if (Array.isArray(block.content)) {
2124
+ for (const inner of block.content) candidates.push(inner?.toolCallId);
2125
+ }
2126
+ }
2127
+ return candidates.find((value) => typeof value === "string" && value !== "") ?? "";
2128
+ }
2129
+
2130
+ /** 工具参数解析(issue #54):只接受 JSON 对象;非法/非对象一律 fail-open 返回 null。 */
2131
+ function parseToolArguments(raw) {
2132
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) return raw;
2133
+ if (typeof raw !== "string" || raw.trim() === "") return null;
2134
+ try {
2135
+ const parsed = JSON.parse(raw);
2136
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
2137
+ } catch {
2138
+ return null;
2139
+ }
2140
+ }
2141
+
2142
+ /** 折叠行/字段单行化(换行压成空格,避免破坏卡片布局)。 */
2143
+ const singleLineText = (value) => String(value ?? "").replace(/\s+/g, " ").trim();
2144
+
2145
+ /** 正整数参数(offset/limit):非正/非整数忽略(fail-open)。 */
2146
+ const positiveIntArg = (value) =>
2147
+ typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
2148
+
2149
+ /** 按行切分,同时忽略末尾换行产生的空哨兵(与桌面 diff 行数口径一致)。 */
2150
+ function diffLinesOf(text) {
2151
+ if (typeof text !== "string" || text === "") return [];
2152
+ const lines = text.split("\n");
2153
+ if (text.endsWith("\n")) lines.pop();
2154
+ return lines;
2155
+ }
2156
+
2157
+ /**
2158
+ * 统一 diff 体积上限保护(issue #54 note 1761):≤8 KiB 原样返回,超出**整段缺省**并
2159
+ * 标记 diffTruncated(不截半段,避免 App 的 diff 解析错位)。
2160
+ * @returns {{diff?: string, diffTruncated?: true}}
2161
+ */
2162
+ function boundedDiff(headerLines, bodyLines) {
2163
+ const text = `${[...headerLines, ...bodyLines].join("\n")}\n`;
2164
+ if (Buffer.byteLength(text, "utf8") > TOOL_CARD_DIFF_MAX_BYTES) return { diffTruncated: true };
2165
+ return { diff: text };
2166
+ }
2167
+
2168
+ /** write 的「全新增」统一 diff(display 已派生,不含主机路径)。 */
2169
+ function addedFileDiff(display, content) {
2170
+ const lines = diffLinesOf(content);
2171
+ if (lines.length === 0) return {};
2172
+ return boundedDiff(
2173
+ ["--- /dev/null", `+++ b/${display}`, `@@ -0,0 +1,${lines.length} @@`],
2174
+ lines.map((line) => `+${line}`),
2175
+ );
2176
+ }
2177
+
2178
+ /**
2179
+ * edit 的近似统一 diff(issue #54 note 1761 允许近似):
2180
+ * 不做上下文/位置搜索,直接把 old_string 全部列为删除行、new_string 全部列为新增行;
2181
+ * `added`/`deleted` 也按行数近似(含省略末尾空行),仅用于折叠行统计。
2182
+ */
2183
+ function editedFileDiff(display, oldText, newText) {
2184
+ const oldLines = diffLinesOf(oldText);
2185
+ const newLines = diffLinesOf(newText);
2186
+ const header = [
2187
+ oldLines.length === 0 ? "--- /dev/null" : `--- a/${display}`,
2188
+ newLines.length === 0 ? "+++ /dev/null" : `+++ b/${display}`,
2189
+ `@@ -1,${oldLines.length} +1,${newLines.length} @@`,
2190
+ ];
2191
+ const body = [
2192
+ ...oldLines.map((line) => `-${line}`),
2193
+ ...newLines.map((line) => `+${line}`),
2194
+ ];
2195
+ const bounded = boundedDiff(header, body);
2196
+ return {
2197
+ ...bounded,
2198
+ added: newLines.length,
2199
+ deleted: oldLines.length,
2200
+ };
2201
+ }
2202
+
2203
+ /**
2204
+ * `tool/call` 的结构化摘要(issue #54 §2):从**原始** `data.arguments` 解析,先解析后
2205
+ * clamp;路径一律经 `mobileDisplayPath` 派生,**绝不下发绝对路径**。未知工具/非法参数
2206
+ * 返回 undefined 或只带 kind/tool 的最小摘要,绝不抛错(fail-open 到通用卡)。
2207
+ * @param {unknown} toolName 工具名。
2208
+ * @param {unknown} rawArguments 原始 arguments(JSON 字符串或对象)。
2209
+ * @param {unknown} cwd 会话工作目录(仅用于 display 派生,不下发)。
2210
+ * @returns {object|undefined}
2211
+ */
2212
+ export function toolCallSummaryOf(toolName, rawArguments, cwd) {
2213
+ const tool = typeof toolName === "string" ? toolName : "";
2214
+ const kind = TOOL_CARD_KIND[tool];
2215
+ if (kind === undefined) return undefined;
2216
+ const summary = { kind, tool };
2217
+ const args = parseToolArguments(rawArguments);
2218
+ if (args === null) return summary;
2219
+ // 注意(reviewer P1):`displayOf` 沿用既有 `mobileDisplayPath` → `canonicalWorkspacePath`
2220
+ // 派生,可能为对齐 cwd 符号链接别名而对**已给出的绝对路径祖先**做 realpath;那是
2221
+ // #54/#60 的 display 语义、语义未改,也不是 #67 新增的探测面。issue #67 的
2222
+ // `previewTargetOf` 判定本身对 cwd 外绝对路径零 fs 探测(见其头注释)。
2223
+ const displayOf = (value) => {
2224
+ if (typeof value !== "string" || value.trim() === "") return undefined;
2225
+ return clampText(mobileDisplayPath(value, cwd), 300);
2226
+ };
2227
+ const toolFilePath = displayOf(args.file_path ?? args.filePath);
2228
+ // issue #67:仅 read/write/edit/read_image 的原始路径参与可预览判定;两字段严格同现/同缺。
2229
+ // 其它工具即便参数里带了 file_path 也不做任何 fs 探测(grep/glob 的 path 不扩到本能力)。
2230
+ const preview = tool === "read" || tool === "write" || tool === "edit" || tool === "read_image"
2231
+ ? previewTargetOf(args.file_path ?? args.filePath, cwd)
2232
+ : null;
2233
+ switch (tool) {
2234
+ case "bash":
2235
+ case "pwsh": {
2236
+ if (typeof args.command === "string" && args.command.trim() !== "") {
2237
+ summary.command = clampText(singleLineText(args.command), 200);
2238
+ }
2239
+ const workdir = displayOf(args.workdir);
2240
+ if (workdir !== undefined) summary.workdir = workdir;
2241
+ if (args.run_in_background === true) summary.background = true;
2242
+ if (typeof args.description === "string" && args.description.trim() !== "") {
2243
+ summary.description = clampText(singleLineText(args.description), 120);
2244
+ }
2245
+ break;
2246
+ }
2247
+ case "read": {
2248
+ if (toolFilePath !== undefined) summary.filePath = toolFilePath;
2249
+ if (preview !== null) Object.assign(summary, preview);
2250
+ const offset = positiveIntArg(args.offset);
2251
+ if (offset !== undefined) summary.offset = offset;
2252
+ const limit = positiveIntArg(args.limit);
2253
+ if (limit !== undefined) summary.limit = limit;
2254
+ break;
2255
+ }
2256
+ case "write": {
2257
+ if (toolFilePath !== undefined) summary.filePath = toolFilePath;
2258
+ if (preview !== null) Object.assign(summary, preview);
2259
+ if (typeof args.content === "string") {
2260
+ // 与桌面 `NKB` 同口径:UTF-16 code unit 长度 / 1024 向上取整。
2261
+ summary.sizeKb = Math.ceil(args.content.length / 1024);
2262
+ if (toolFilePath !== undefined) {
2263
+ Object.assign(summary, addedFileDiff(toolFilePath, args.content));
2264
+ }
2265
+ }
2266
+ break;
2267
+ }
2268
+ case "edit": {
2269
+ if (toolFilePath !== undefined) summary.filePath = toolFilePath;
2270
+ if (preview !== null) Object.assign(summary, preview);
2271
+ const oldText = typeof args.old_string === "string" ? args.old_string : typeof args.oldString === "string" ? args.oldString : "";
2272
+ const newText = typeof args.new_string === "string" ? args.new_string : typeof args.newString === "string" ? args.newString : "";
2273
+ summary.sizeKb = Math.ceil((oldText.length + newText.length) / 1024);
2274
+ if (toolFilePath !== undefined) {
2275
+ Object.assign(summary, editedFileDiff(toolFilePath, oldText, newText));
2276
+ } else {
2277
+ summary.added = diffLinesOf(newText).length;
2278
+ summary.deleted = diffLinesOf(oldText).length;
2279
+ }
2280
+ break;
2281
+ }
2282
+ case "grep":
2283
+ case "glob": {
2284
+ if (typeof args.pattern === "string" && args.pattern.trim() !== "") {
2285
+ summary.pattern = clampText(singleLineText(args.pattern), 200);
2286
+ }
2287
+ const searchPath = displayOf(args.path);
2288
+ if (searchPath !== undefined) summary.path = searchPath;
2289
+ if (tool === "grep" && typeof args.include === "string" && args.include.trim() !== "") {
2290
+ summary.include = clampText(singleLineText(args.include), 200);
2291
+ }
2292
+ break;
2293
+ }
2294
+ case "web_fetch": {
2295
+ if (typeof args.url === "string" && args.url.trim() !== "") summary.url = clampText(args.url.trim(), 500);
2296
+ break;
2297
+ }
2298
+ case "web_search": {
2299
+ const first = Array.isArray(args.queries) ? args.queries.find((value) => typeof value === "string" && value.trim() !== "") : undefined;
2300
+ if (typeof first === "string") summary.query = clampText(singleLineText(first), 200);
2301
+ break;
2302
+ }
2303
+ case "read_image": {
2304
+ if (toolFilePath !== undefined) summary.filePath = toolFilePath;
2305
+ if (preview !== null) Object.assign(summary, preview);
2306
+ break;
2307
+ }
2308
+ case "todo_write": {
2309
+ // issue #66(契约 §1.2):`todos` 必须是数组;非数组不猜,只回 kind/tool(App 回退通用卡)。
2310
+ // 空数组是合法快照(可渲染 0 项);status 不在宿主枚举内一律归 pending,
2311
+ // counts 恒带三键且由**归一后**的 items 统计(三项和 = items.length)。
2312
+ // R2(评审):与 App 逐项降级口径一致——非对象 / content 非 string 的元素直接跳过
2313
+ // (App 会丢弃它们),counts 只统计保留下来的 items,避免折叠行「N 项任务」与展开
2314
+ // 清单的项数/完成数对不上(此前 map 会把 42/"x" 变成空 content 的伪 item)。
2315
+ if (!Array.isArray(args.todos)) break;
2316
+ const items = [];
2317
+ for (const todo of args.todos) {
2318
+ if (items.length >= TOOL_CARD_MAX_TODO_ITEMS) break;
2319
+ if (!todo || typeof todo !== "object" || typeof todo.content !== "string") continue;
2320
+ items.push({
2321
+ content: clampText(singleLineText(todo.content), TOOL_CARD_MAX_TODO_CONTENT),
2322
+ status: TOOL_CARD_TODO_STATUSES.includes(todo.status) ? todo.status : "pending",
2323
+ });
2324
+ }
2325
+ const counts = { pending: 0, inProgress: 0, completed: 0 };
2326
+ for (const item of items) {
2327
+ if (item.status === "in_progress") counts.inProgress++;
2328
+ else if (item.status === "completed") counts.completed++;
2329
+ else counts.pending++;
2330
+ }
2331
+ summary.items = items;
2332
+ summary.counts = counts;
2333
+ break;
2334
+ }
2335
+ case "ask_user_question": {
2336
+ // issue #66(契约 §1.2):questions 非数组/无有效题 → 只回 kind/tool(不可渲染)。
2337
+ // `question` 是渲染必需字段,缺失/空白的题整题丢弃;`id` 是 App 关联"待答"的
2338
+ // 唯一依据,必须保留(只 clamp,不做单行化,保证与 tool/result 回放的 echo 一致)。
2339
+ if (!Array.isArray(args.questions)) break;
2340
+ const questions = [];
2341
+ for (const raw of args.questions) {
2342
+ if (questions.length >= TOOL_CARD_MAX_QUESTIONS) break;
2343
+ if (!raw || typeof raw !== "object") continue;
2344
+ // 契约要求 question 必须是字符串;非字符串/空白一律整题丢弃。
2345
+ const questionText = typeof raw.question === "string" ? singleLineText(raw.question) : "";
2346
+ if (questionText === "") continue;
2347
+ const entry = { question: clampText(questionText, TOOL_CARD_MAX_QUESTION_TEXT) };
2348
+ if (typeof raw.id === "string" && raw.id.trim() !== "") entry.id = clampText(raw.id, TOOL_CARD_MAX_QUESTION_ID);
2349
+ const header = typeof raw.header === "string" ? singleLineText(raw.header) : "";
2350
+ if (header !== "") entry.header = clampText(header, TOOL_CARD_MAX_QUESTION_HEADER);
2351
+ if (Array.isArray(raw.options)) {
2352
+ const options = [];
2353
+ for (const rawOption of raw.options) {
2354
+ if (options.length >= TOOL_CARD_MAX_QUESTION_OPTIONS) break;
2355
+ if (!rawOption || typeof rawOption !== "object") continue;
2356
+ const label = typeof rawOption.label === "string" ? singleLineText(rawOption.label) : "";
2357
+ if (label === "") continue; // 无 label 的 option 逐项丢弃
2358
+ const option = { label: clampText(label, TOOL_CARD_MAX_OPTION_LABEL) };
2359
+ const description = typeof rawOption.description === "string" ? singleLineText(rawOption.description) : "";
2360
+ if (description !== "") option.description = clampText(description, TOOL_CARD_MAX_OPTION_DESCRIPTION);
2361
+ options.push(option);
2362
+ }
2363
+ // 处理后为空 → 不下发该字段(契约 §1.2)。
2364
+ if (options.length > 0) entry.options = options;
2365
+ }
2366
+ // 宿主参数是 snake_case 的 multi_select;同时接受 camelCase(两种形状都只认 true)。
2367
+ if (raw.multi_select === true || raw.multiSelect === true) entry.multiSelect = true;
2368
+ questions.push(entry);
2369
+ }
2370
+ if (questions.length > 0) summary.questions = questions;
2371
+ break;
2372
+ }
2373
+ case "skill": {
2374
+ // issue #66(契约 §1.2):只下发 skill 名;resourceBase/provider/content 等一律不带。
2375
+ if (typeof args.name === "string" && args.name.trim() !== "") {
2376
+ summary.name = clampText(args.name, TOOL_CARD_MAX_SKILL_NAME);
2377
+ }
2378
+ break;
2379
+ }
2380
+ }
2381
+ return summary;
2382
+ }
2383
+
2384
+ /**
2385
+ * PTC 子调用事件类型(issue #68):`run_code` 内被调度工具的执行前/落定事件。
2386
+ * 两个类型共用同一投影分支,App 以 `callId` 合并 start→result。
2387
+ */
2388
+ const PTC_DISPATCH_EVENT_TYPES = Object.freeze(["tool/ptc-dispatch-start", "tool/ptc-dispatch"]);
2389
+ /** 是否为 PTC 子调用事件(投影/接线共用判据,避免两处分叉)。 */
2390
+ function isPtcDispatchEvent(event) {
2391
+ return event !== null && typeof event === "object" && PTC_DISPATCH_EVENT_TYPES.includes(event.type);
2392
+ }
2393
+
2394
+ /** PTC 事件 id 防御:非空字符串且 ≤300 才接受;非法 → undefined(整条投影降级为无 data)。 */
2395
+ function ptcIdOf(value) {
2396
+ return typeof value === "string" && value.length > 0 && value.length <= PTC_MAX_ID_LENGTH ? value : undefined;
2397
+ }
2398
+
2399
+ /**
2400
+ * L2-2:PTC `text`/`error` 只接受安全码语法(`FS_NOT_FOUND`/`EACCES`/`FsError`/
2401
+ * `ToolArgsError` 等);任意自由文本(路径/栈/注入字符)一律拒绝。
2402
+ */
2403
+ // 注意:不用 `$`(JS 的 `$` 会放过末尾换行),用否定任意字符收尾;且**不 trim**——含
2404
+ // 空格/换行/制表符的原串一律不是安全码(L2-8 严格验证)。
2405
+ const PTC_SAFE_CODE_PATTERN = /^[A-Za-z][A-Za-z0-9_.-]{0,63}(?![\s\S])/;
2406
+ function ptcSafeCodeOf(value) {
2407
+ return typeof value === "string" && PTC_SAFE_CODE_PATTERN.test(value)
2408
+ ? value
2409
+ : undefined;
2410
+ }
2411
+
2412
+ /** http(s) URL 在路径脱敏时先整体占位保护(URL 不是主机路径,不得被改写)。 */
2413
+ const PTC_SCRUB_URL_PATTERN = /\bhttps?:\/\/[^\s"'`)\]]+/gi;
2414
+
2415
+ /**
2416
+ * 路径 token 的 basename:去掉尾部 `/`/`\`,取最后一个非空段(Windows/POSIX/file URL 通用)。
2417
+ */
2418
+ function ptcBasenameOfPathToken(token) {
2419
+ const clean = String(token).replace(/[\\/]+$/, "");
2420
+ const segments = clean.split(/[\\/]+/).filter((segment) => segment !== "" && segment !== "file:");
2421
+ return segments[segments.length - 1];
2422
+ }
2423
+
2424
+ /**
2425
+ * L2-1/L2-7:PTC summary 自由文本(command/description)的主机路径脱敏。
2426
+ * - 先保护 `http(s)://` URL(URL 不是主机路径,原样保留);
2427
+ * - 已知根前缀(cwd / cwd realpath / homedir,先长后短)→ `.` / `~`;
2428
+ * - 引用段 `"..."`/`'...'`:内容为绝对路径(POSIX/Windows/file://)→ 整体 `…/<basename>`,
2429
+ * 保留引号;引用段内是 URL 或非路径内容则原样;
2430
+ * - 剩余绝对路径 token(含反斜杠转义空格,如 `/home/a\ b/c`)→ `…/<basename>`;
2431
+ * - 结构字段 filePath/workdir/path 已由 mobileDisplayPath 派生,不经此函数。
2432
+ */
2433
+ function ptcScrubPathsOf(value, cwd) {
2434
+ if (typeof value !== "string" || value === "") return value;
2435
+ const urls = [];
2436
+ let text = value.replace(PTC_SCRUB_URL_PATTERN, (match) => {
2437
+ const token = `\u0000PTcurl${urls.length}\u0000`;
2438
+ urls.push(match);
2439
+ return token;
2440
+ });
2441
+ const home = homedir();
2442
+ const prefixes = [];
2443
+ for (const prefix of [cwd, ...(typeof cwd === "string" && cwd !== "" ? [(() => {
2444
+ try {
2445
+ return realpathSync(cwd);
2446
+ } catch {
2447
+ return undefined;
2448
+ }
2449
+ })()] : []), home]) {
2450
+ if (typeof prefix === "string" && prefix.length > 1 && prefix !== "/") prefixes.push(prefix);
2451
+ }
2452
+ prefixes.sort((a, b) => b.length - a.length);
2453
+ const seen = new Set();
2454
+ for (const prefix of prefixes) {
2455
+ if (seen.has(prefix)) continue;
2456
+ seen.add(prefix);
2457
+ const replacement = prefix === home ? "~" : ".";
2458
+ const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2459
+ // 仅替换作为路径起始出现的前缀(前一个字符不是路径字符),避免误伤子串。
2460
+ text = text.replace(
2461
+ new RegExp(`(^|[\\s"'\`(=,;:])${escaped}(?=$|[\\\\/\\s"'\`)\\]}])`, "g"),
2462
+ (_match, lead) => `${lead}${replacement}`,
2463
+ );
2464
+ }
2465
+ // L2-7:引用段整体处理(含空格的绝对路径不再被空格截断而残留层级)。
2466
+ text = text.replace(/(["'])((?:(?!\1)[\s\S])*)\1/g, (match, quote, inner) => {
2467
+ const trimmed = inner.trim();
2468
+ if (trimmed === "" || /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(trimmed)) return match; // URL/占位符/空串不动
2469
+ const absolute = /^(?:file:\/\/\/|[A-Za-z]:[\\/]|[\\/])/.test(trimmed);
2470
+ if (!absolute) return match;
2471
+ const base = ptcBasenameOfPathToken(trimmed);
2472
+ return base === undefined || base === "" ? match : `${quote}…/${base}${quote}`;
2473
+ });
2474
+ // 剩余绝对路径 token:允许反斜杠转义空格(`\ `),按整体取 basename,不保留主机层级。
2475
+ text = text.replace(
2476
+ /(?:file:\/\/\/(?:[^\s"'`)\],;\\]|\\.)+)|(?<![A-Za-z0-9_…])[A-Za-z]:[\\/](?:[^\s"'`)\],;\\]|\\.)+|(?<![\w.~…])[/](?:[^\s"'`)\],;\\]|\\.)+/g,
2477
+ (match) => {
2478
+ const base = ptcBasenameOfPathToken(match);
2479
+ return base === undefined || base === "" ? match : `…/${base}`;
2480
+ },
2481
+ );
2482
+ return text.replace(/\u0000PTcurl(\d+)\u0000/g, (_match, index) => urls[Number(index)]);
2483
+ }
2484
+
2485
+ /**
2486
+ * 50 子调用预算(issue #68 契约 §1.6):`/history` 每响应一个、SSE 每会话一个。
2487
+ * `roots` 按 rootCallId 分组(缺省根用空串),组内 `seen` 按 callId 去重计数。
2488
+ * 同一 callId 的 start/result 共享 1 个名额;预算不持久化,也不是新事实源。
2489
+ * @returns {{roots: Map<string, {seen: Set<string>, noticeSent: boolean}>}}
2490
+ */
2491
+ export function createPtcBudget() {
2492
+ return { roots: new Map() };
2493
+ }
2494
+
2495
+ /**
2496
+ * 50 上限 gate(issue #68 契约 §1.6):`"full"` 正常投影;`"notice"` 超限时每个
2497
+ * 计数作用域只发一条最小截断信号;`"drop"` 其余超限事件只留 `{seq,type}`。
2498
+ * 无 budget(纯函数测试模式)永不截断。
2499
+ * @param {{roots: Map}|undefined} budget
2500
+ * @param {unknown} data 原始 PTC 事件 data。
2501
+ * @returns {"full" | "notice" | "drop"}
2502
+ */
2503
+ export function ptcGateOf(budget, data) {
2504
+ if (!budget || !(budget.roots instanceof Map)) return "full";
2505
+ const callId = data?.subCallId;
2506
+ // 非法 id 在 ptcProjectionOf 已整条降级;这里不计数,避免坏数据污染预算。
2507
+ if (typeof callId !== "string" || callId === "") return "full";
2508
+ const rootKey = ptcIdOf(data?.rootCallId) ?? "";
2509
+ let state = budget.roots.get(rootKey);
2510
+ if (state === undefined) {
2511
+ state = { seen: new Set(), noticeSent: false };
2512
+ budget.roots.set(rootKey, state);
2513
+ // L2-5:有界 FIFO——按插入序逐出最旧 root,不做触碰刷新,仅作内存上界。
2514
+ if (budget.roots.size > 1000) budget.roots.delete(budget.roots.keys().next().value);
2515
+ }
2516
+ if (state.seen.has(callId)) return "full";
2517
+ if (state.seen.size < PTC_MAX_SUBCALLS) {
2518
+ state.seen.add(callId);
2519
+ return "full";
2520
+ }
2521
+ if (!state.noticeSent) {
2522
+ state.noticeSent = true;
2523
+ return "notice";
2524
+ }
2525
+ return "drop";
2526
+ }
2527
+
2528
+ /**
2529
+ * PTC 子调用的折叠行摘要(issue #68 契约 §1.4):复用 `toolCallSummaryOf` 的安全
2530
+ * display 摘要(路径已由 `mobileDisplayPath` 派生,绝不下发绝对路径),按 App
2531
+ * 折叠行白名单裁剪后限制 2KiB;超预算整份降级为 `{kind, tool}`,绝不抛错。
2532
+ * 明确丢弃仅为二级详情设计的 `diff`/`diffTruncated`/`relative`/`previewable`。
2533
+ */
2534
+ function ptcSummaryOf(name, rawArguments, cwd) {
2535
+ const full = toolCallSummaryOf(name, rawArguments, cwd);
2536
+ if (full === undefined) return undefined;
2537
+ const compact = { kind: full.kind, tool: full.tool };
2538
+ const whitelist = {
2539
+ command: ["command", "workdir", "background", "description"],
2540
+ file: ["filePath", "offset", "limit", "sizeKb", "added", "deleted"],
2541
+ search: ["pattern", "path", "include"],
2542
+ web: ["url", "query"],
2543
+ image: ["filePath"],
2544
+ todo: ["items", "counts"],
2545
+ question: ["questions"],
2546
+ skill: ["name"],
2547
+ }[full.kind];
2548
+ for (const key of whitelist ?? []) {
2549
+ if (full[key] !== undefined) compact[key] = full[key];
2550
+ }
2551
+ // L2-1:command/description 是自由文本(可能夹带主机绝对路径),PTC 专属脱敏;
2552
+ // 结构字段 filePath/workdir/path 已由 mobileDisplayPath 派生,不在此重复处理。
2553
+ for (const key of ["command", "description"]) {
2554
+ if (typeof compact[key] === "string") compact[key] = ptcScrubPathsOf(compact[key], cwd);
2555
+ }
2556
+ let bytes;
2557
+ try {
2558
+ bytes = Buffer.byteLength(JSON.stringify(compact), "utf8");
2559
+ } catch {
2560
+ bytes = Number.POSITIVE_INFINITY;
2561
+ }
2562
+ return bytes <= PTC_MAX_SUMMARY_BYTES ? compact : { kind: full.kind, tool: full.tool };
2563
+ }
2564
+
2565
+ /**
2566
+ * 失败子调用的安全 `text`(issue #68 契约 §1.5,lead 裁定 L1):
2567
+ * **只**取安全错误码 —— `error.code` 优先、缺失时 `error.name`,各自 clamp ≤120;
2568
+ * **绝不**使用 `content`/`arguments`/`meta`/`error.reason`(真实夹具的失败 content
2569
+ * 含绝对工作目录路径)。两人都缺 → 省略 text。
2570
+ */
2571
+ function ptcFailureTextOf(data) {
2572
+ const error = data?.error;
2573
+ const err = error !== null && typeof error === "object" && !Array.isArray(error) ? error : undefined;
2574
+ const raw = ptcSafeCodeOf(err?.code) ?? ptcSafeCodeOf(err?.name);
2575
+ return raw === undefined ? undefined : clampText(raw, 500);
2576
+ }
2577
+
2578
+ /** PTC 失败事件的 error 白名单(issue #68 契约 §1.3/D5):只下发 name+code,无 reason。 */
2579
+ function ptcErrorOf(data) {
2580
+ const error = data?.error;
2581
+ const err = error !== null && typeof error === "object" && !Array.isArray(error) ? error : undefined;
2582
+ const name = ptcSafeCodeOf(err?.name);
2583
+ const code = ptcSafeCodeOf(err?.code);
2584
+ // L2-2:name 与 code 都必须合法才整对象下发;任一不合法(路径/注入字符)→ 省略。
2585
+ return name === undefined || code === undefined
2586
+ ? undefined
2587
+ : { name: clampText(name, 120), code: clampText(code, 120) };
2588
+ }
2589
+
2590
+ /**
2591
+ * PTC 事件的 turn/step 派生(issue #68 契约 §1.7):内核 PTC data 不带位置,
2592
+ * 由原始会话事件(含被 timeline 过滤的 `step/start`)扫描到目标 seq 为止。
2593
+ * 派生不到就省略,**禁止用 0 伪造**;App 不依赖该字段排序。
2594
+ * @param {unknown} events 原始会话事件数组。
2595
+ * @param {unknown} seq 目标事件 seq。
2596
+ * @returns {{turn?: number, step?: number}}
2597
+ */
2598
+ function ptcLocationOf(events, seq) {
2599
+ if (!Array.isArray(events) || !Number.isSafeInteger(seq)) return {};
2600
+ let turn;
2601
+ let step;
2602
+ for (const event of events) {
2603
+ if (Number.isSafeInteger(event?.seq) && event.seq > seq) break;
2604
+ if (event?.type === "turn/start" && Number.isSafeInteger(event?.data?.turn)) {
2605
+ turn = event.data.turn;
2606
+ step = undefined;
2607
+ } else if (event?.type === "step/start" && Number.isSafeInteger(event?.data?.step)) {
2608
+ step = event.data.step;
2609
+ }
2610
+ }
2611
+ return {
2612
+ ...(turn === undefined || turn < 1 ? {} : { turn }),
2613
+ ...(step === undefined || step < 0 ? {} : { step }),
2614
+ };
2615
+ }
2616
+
2617
+ /**
2618
+ * PTC 子调用事件投影(issue #68 契约 §1.3):start → `status:"running"`,
2619
+ * result → `status:"success"|"failed"` + `isError`;同一 `callId` 原地更新由 App 负责。
2620
+ * - `summary` 来自本事件自己的 `arguments`(安全 display,≤2KiB);
2621
+ * - `text` **仅失败结果**、只含安全错误码(L1);
2622
+ * - 永不下发 `arguments` 原文 / `meta` / `content` / `images` / `error.reason`;
2623
+ * - id 缺失/非法 → `{seq,type}`(事件仍在,无 data);50 超限见 ptcGateOf。
2624
+ * @param {{seq:unknown, type:string, data:unknown}} event
2625
+ * @param {{cwd?:unknown, turn?:unknown, step?:unknown, ptcBudget?:unknown}} options
2626
+ * @returns {{seq: unknown, type: string, data?: object}}
2627
+ */
2628
+ function ptcProjectionOf(event, options = {}) {
2629
+ const { seq, type } = event;
2630
+ const data = event.data;
2631
+ if (data === null || typeof data !== "object" || Array.isArray(data)) return { seq, type };
2632
+ const callId = ptcIdOf(data.subCallId);
2633
+ const parentCallId = ptcIdOf(data.parentCallId);
2634
+ if (callId === undefined || parentCallId === undefined) return { seq, type };
2635
+ const isStart = type === "tool/ptc-dispatch-start";
2636
+ const isError = isStart ? false : data.isError === true;
2637
+ const status = isStart ? "running" : isError ? "failed" : "success";
2638
+ const gate = ptcGateOf(options.ptcBudget, data);
2639
+ if (gate === "drop") return { seq, type };
2640
+ const rootCallId = ptcIdOf(data.rootCallId);
2641
+ const name = typeof data.name === "string" && data.name.trim() !== "" ? clampText(data.name, 120) : undefined;
2642
+ const turn = Number.isSafeInteger(options.turn) && options.turn >= 1 ? options.turn : undefined;
2643
+ const step = Number.isSafeInteger(options.step) && options.step >= 0 ? options.step : undefined;
2644
+ const base = {
2645
+ ...(turn === undefined ? {} : { turn }),
2646
+ ...(step === undefined ? {} : { step }),
2647
+ ...(rootCallId === undefined ? {} : { rootCallId }),
2648
+ parentCallId,
2649
+ callId,
2650
+ ...(name === undefined ? {} : { name }),
2651
+ status,
2652
+ };
2653
+ // L2-3:截断通知单独构造,**不展开**含 turn/step 的 base;
2654
+ // 只保留 rootCallId?/parentCallId/callId/name?/status + truncated。
2655
+ if (gate === "notice") {
2656
+ return {
2657
+ seq,
2658
+ type,
2659
+ data: {
2660
+ ...(rootCallId === undefined ? {} : { rootCallId }),
2661
+ parentCallId,
2662
+ callId,
2663
+ ...(name === undefined ? {} : { name }),
2664
+ status,
2665
+ truncated: true,
2666
+ },
2667
+ };
2668
+ }
2669
+ const summary = ptcSummaryOf(data.name, data.arguments, options.cwd);
2670
+ if (isStart) {
2671
+ return { seq, type, data: { ...base, ...(summary === undefined ? {} : { summary }) } };
2672
+ }
2673
+ const text = isError ? ptcFailureTextOf(data) : undefined;
2674
+ const error = isError ? ptcErrorOf(data) : undefined;
2675
+ return {
2676
+ seq,
2677
+ type,
2678
+ data: {
2679
+ ...base,
2680
+ ...(summary === undefined ? {} : { summary }),
2681
+ ...(text === undefined || text === "" ? {} : { text }),
2682
+ isError,
2683
+ ...(error === undefined ? {} : { error }),
2684
+ },
2685
+ };
2686
+ }
2687
+
2688
+ /**
2689
+ * 宿主的命令终止 trailer:`[exit code: N]` / `[killed by signal: X]` / `[stopped: …]`。
2690
+ *
2691
+ * issue #60 R13:这些标记由 bash/pwsh 在结果**末尾**追加;stdout 正文可能碰巧包含同样的
2692
+ * 字符串。因此只接受**最后一条**且其后仅剩空白(换行)的标记;signal/stopped/exit 三者
2693
+ * 互斥,按宿主追加顺序取最后一条(signal 优先于 stopped,二者都优先于 exit)。
2694
+ * @param {string} text 未 clamp 的结果文本。
2695
+ * @returns {{kind: "exit", exitCode: number} | {kind: "signal", signal: string} | {kind: "stopped", stopped: string} | null}
2696
+ */
2697
+ function terminalTrailerOf(text) {
2698
+ if (typeof text !== "string" || text === "") return null;
2699
+ const pattern = /\[(exit code: (-?\d+)|killed by signal: ([^\]\n]+)|stopped: ([^\]\n]+))\]/g;
2700
+ let last = null;
2701
+ let match;
2702
+ while ((match = pattern.exec(text)) !== null) last = match;
2703
+ if (last === null) return null;
2704
+ // marker 必须位于结果末尾(允许尾随空白/换行);正文中间的类似文本一律不算。
2705
+ if (text.slice(last.index + last[0].length).trim() !== "") return null;
2706
+ if (matchPrefixSignal(last[3])) return { kind: "signal", signal: clampText(last[3].trim(), 40) };
2707
+ if (matchPrefixStopped(last[4])) return { kind: "stopped", stopped: clampText(last[4].trim(), 120) };
2708
+ return { kind: "exit", exitCode: Number(last[2]) };
2709
+ }
2710
+
2711
+ const matchPrefixSignal = (value) => typeof value === "string" && value !== "";
2712
+ const matchPrefixStopped = (value) => typeof value === "string" && value !== "";
2713
+
2714
+ /**
2715
+ * `tool/result` 的结构化摘要(issue #54 §3):只从结果**文本标记**与宿主 `meta` 解析,
2716
+ * 解析不到就缺省(不猜)。exit/signal 标记只由 bash/pwsh 输出;grep/glob 的匹配总数优先
2717
+ * 取 `meta.total`(宿主 presentationMeta),缺失时按结果文本的稳定句式解析。
2718
+ * @param {unknown} toolName 工具名(可为空:结果事件常不带名字)。
2719
+ * @param {unknown} rawResultText 未 clamp 的结果文本。
2720
+ * @param {unknown} meta 宿主 tool/result 的 presentationMeta(不透传给 App)。
2721
+ * @returns {object|undefined}
2722
+ */
2723
+ export function toolResultSummaryOf(toolName, rawResultText, meta) {
2724
+ const summary = {};
2725
+ const text = typeof rawResultText === "string" ? rawResultText : "";
2726
+ const tool = typeof toolName === "string" ? toolName : "";
2727
+ // issue #60 R14:终止状态只对**已确定是 bash/pwsh** 的结果下发;无工具名时不得从内容猜
2728
+ // (调用方应按 callId→tool/call.name 关联后再传 resolvedToolName)。
2729
+ if (tool === "bash" || tool === "pwsh") {
2730
+ // issue #60 R13:只认宿主在**结果末尾**追加的终止 trailer,且取最后一条;
2731
+ // stdout 里碰巧出现的 `[exit code: N]` 不得覆盖真实终止状态。
2732
+ const trailer = terminalTrailerOf(text);
2733
+ if (trailer?.kind === "exit") summary.exitCode = trailer.exitCode;
2734
+ else if (trailer?.kind === "signal") summary.signal = trailer.signal;
2735
+ else if (trailer?.kind === "stopped") summary.stopped = trailer.stopped;
2736
+ }
2737
+ // issue #66(契约 §1.3):只有确定是 ask_user_question 才回放 answers;结果文本缺失/
2738
+ // 非 JSON/pending 形状一律缺省,绝不从文本猜(名字由调用方按 callId→name 解析后传入)。
2739
+ if (tool === "ask_user_question") {
2740
+ const answers = answerSummaryOf(text);
2741
+ if (answers !== undefined) summary.answers = answers;
2742
+ }
2743
+ const metaShape = meta && typeof meta === "object" ? meta.shape : undefined;
2744
+ const searchShaped = metaShape === "matches" || metaShape === "paths";
2745
+ const searchTool = tool === "grep" || tool === "glob";
2746
+ if (searchShaped || searchTool || tool === "") {
2747
+ const metaTotal = meta && typeof meta === "object" && Number.isSafeInteger(meta.total) ? meta.total : undefined;
2748
+ if (metaTotal !== undefined && metaTotal >= 0) {
2749
+ summary.resultCount = metaTotal;
2750
+ } else if (searchTool || searchShaped || tool === "") {
2751
+ const count = parseSearchResultCount(text, tool);
2752
+ if (count !== undefined) summary.resultCount = count;
2753
+ }
2754
+ }
2755
+ return Object.keys(summary).length > 0 ? summary : undefined;
2756
+ }
2757
+
2758
+ /**
2759
+ * `ask_user_question` 结果文本 → `answers` 只读回放(issue #66 契约 §1.3)。
2760
+ *
2761
+ * 宿主 `render` 把结果 value 原样 `JSON.stringify`:成功批次是
2762
+ * `{answers:[{id,selected,custom?}]}`,超时 pending 是 `{pending:true,callId,message}`。
2763
+ * 只认 JSON 对象里的 `answers` 数组;无效 answer 项(缺/空 id)逐项丢弃,
2764
+ * 最终没有有效项或形状不符时返回 undefined(调用方缺省,不猜)。
2765
+ * @param {string} text 未 clamp 的结果文本。
2766
+ * @returns {{questionId: string, values: string[]}[]|undefined}
2767
+ */
2768
+ function answerSummaryOf(text) {
2769
+ let parsed;
2770
+ try {
2771
+ parsed = JSON.parse(text);
2772
+ } catch {
2773
+ return undefined;
2774
+ }
2775
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Array.isArray(parsed.answers)) return undefined;
2776
+ const answers = [];
2777
+ for (const raw of parsed.answers) {
2778
+ if (answers.length >= TOOL_CARD_MAX_ANSWER_ITEMS) break;
2779
+ if (!raw || typeof raw !== "object") continue;
2780
+ // questionId 是 App 关联「这道题答了什么」的唯一键;缺失/空白的项无法回放,丢弃。
2781
+ if (typeof raw.id !== "string" || raw.id.trim() === "") continue;
2782
+ const values = [];
2783
+ if (Array.isArray(raw.selected)) {
2784
+ for (const selected of raw.selected) {
2785
+ if (values.length >= TOOL_CARD_MAX_ANSWER_VALUES) break;
2786
+ if (typeof selected !== "string") continue;
2787
+ values.push(clampText(selected, TOOL_CARD_MAX_ANSWER_TEXT));
2788
+ }
2789
+ }
2790
+ // 自定义答案与选项 label 同列回放:追加在 values 末尾(自定义答案在语义上是最后一项)。
2791
+ if (values.length < TOOL_CARD_MAX_ANSWER_VALUES && typeof raw.custom === "string" && raw.custom.trim() !== "") {
2792
+ values.push(clampText(raw.custom, TOOL_CARD_MAX_ANSWER_TEXT));
2793
+ }
2794
+ answers.push({ questionId: clampText(raw.id, TOOL_CARD_MAX_QUESTION_ID), values });
2795
+ }
2796
+ return answers.length > 0 ? answers : undefined;
2797
+ }
2798
+
2799
+ /** 从 grep/glob 的结果文本解析匹配总数;解析不到返回 undefined(不猜)。 */
2800
+ function parseSearchResultCount(text, tool) {
2801
+ if (text === "") return undefined;
2802
+ const found = /(?:^|\n)Found (\d+)(?: of (\d+))? match(?:es)?(?:\n|$)/.exec(text);
2803
+ if (found) return Number(found[2] ?? found[1]);
2804
+ if (/^No matches found\b/.test(text)) return 0;
2805
+ const showing = /\(Showing \d+ of (\d+) paths/.exec(text);
2806
+ if (showing) return Number(showing[1]);
2807
+ if (/^No files found\b/.test(text)) return 0;
2808
+ // glob 在 cap 内直接输出路径列表(每行一条);仅当工具名已知且没有分页/落盘提示时计数。
2809
+ if (tool === "glob" && !text.includes("(Showing") && !text.includes("Full sorted result")) {
2810
+ const count = text.split("\n").filter((line) => line.trim() !== "").length;
2811
+ return count > 0 ? count : undefined;
2812
+ }
2813
+ return undefined;
2814
+ }
2815
+
2816
+ /**
2817
+ * 单轮轮末信号(`turn/end` 的 `tail`);无任何产出物时返回 null(字段不出现)。
2818
+ * @param {any[]} events 会话原始事件(含被移动时间线过滤的 `workspace/changes`)。
2819
+ * @param {unknown} turn 轮号。
2820
+ * @returns {{changes: boolean, presented: boolean} | null}
2821
+ */
2822
+ export function turnTailOf(events, turn) {
2823
+ if (!Number.isSafeInteger(turn) || turn < 1) return null;
2824
+ let changes = false;
2825
+ let presented = false;
2826
+ for (const event of events ?? []) {
2827
+ const eventTurn = event?.data?.turn;
2828
+ if (Number(eventTurn) !== turn) continue;
2829
+ if (event?.type === "workspace/changes") changes = true;
2830
+ else if (event?.type === "deliverables/presented" && Array.isArray(event?.data?.files) && event.data.files.length > 0) presented = true;
2831
+ }
2832
+ if (!changes && !presented) return null;
2833
+ return { changes, presented };
2834
+ }
2835
+
2836
+ /**
2837
+ * `/history` 响应增量 `turnTails`(§6.20):**单次遍历**已加载事件得出,不调用宿主服务;
2838
+ * 只包含有产出物的轮次。key 为轮号字符串。
2839
+ * @param {any[]} events 会话原始事件。
2840
+ * @returns {Record<string, {changes: boolean, presented: boolean}>}
2841
+ */
2842
+ export function turnTailsOf(events) {
2843
+ const flags = new Map();
2844
+ for (const event of events ?? []) {
2845
+ const turn = event?.data?.turn;
2846
+ if (!Number.isSafeInteger(turn) || turn < 1) continue;
2847
+ if (event?.type === "workspace/changes") {
2848
+ const tail = flags.get(turn) ?? { changes: false, presented: false };
2849
+ tail.changes = true;
2850
+ flags.set(turn, tail);
2851
+ } else if (event?.type === "deliverables/presented" && Array.isArray(event?.data?.files) && event.data.files.length > 0) {
2852
+ const tail = flags.get(turn) ?? { changes: false, presented: false };
2853
+ tail.presented = true;
2854
+ flags.set(turn, tail);
2855
+ }
2856
+ }
2857
+ const out = {};
2858
+ for (const turn of [...flags.keys()].sort((a, b) => a - b)) out[String(turn)] = flags.get(turn);
2859
+ return out;
2860
+ }
2861
+
2862
+ /**
2863
+ * 把宿主 `workspaceChanges.diff()` 的 hunks 渲染成统一 diff 文本(§6.22),供 App 的
2864
+ * `GitFileViewer` 差异模式直接消费。按**行边界**截断到体积上限,避免切断一行导致解析错位。
2865
+ * @param {any} diff 宿主返回的对比结果(text 形态)。
2866
+ * @returns {{text: string, truncated: boolean}}
2867
+ */
2868
+ export function renderUnifiedDiffText(diff, displayOverride) {
2869
+ // issue #60 R05:展示值必须由调用方用 mobileDisplayPath 重派生后传入;未传时退回
2870
+ // 宿主 display/路径的 basename,绝不把可拼接的绝对路径写进 diff 标头。
2871
+ const display = typeof displayOverride === "string" && displayOverride !== ""
2872
+ ? displayOverride
2873
+ : posixBasenameOf(diff?.path ?? diff?.display);
2874
+ const lines = [
2875
+ diff?.before === false ? "--- /dev/null" : `--- a/${display}`,
2876
+ diff?.after === false ? "+++ /dev/null" : `+++ b/${display}`,
2877
+ ];
2878
+ for (const hunk of Array.isArray(diff?.hunks) ? diff.hunks : []) {
2879
+ if (!hunk) continue;
2880
+ const oldStart = Number.isSafeInteger(hunk.oldStart) ? hunk.oldStart : 0;
2881
+ const oldLines = Number.isSafeInteger(hunk.oldLines) ? hunk.oldLines : 0;
2882
+ const newStart = Number.isSafeInteger(hunk.newStart) ? hunk.newStart : 0;
2883
+ const newLines = Number.isSafeInteger(hunk.newLines) ? hunk.newLines : 0;
2884
+ lines.push(`@@ -${oldStart},${oldLines} +${newStart},${newLines} @@`);
2885
+ for (const line of Array.isArray(hunk.lines) ? hunk.lines : []) lines.push(String(line));
2886
+ }
2887
+ let text = `${lines.join("\n")}\n`;
2888
+ if (Buffer.byteLength(text, "utf8") <= TURN_TAIL_DIFF_MAX_BYTES) return { text, truncated: false };
2889
+ const kept = [];
2890
+ let used = 0;
2891
+ for (const line of lines) {
2892
+ const cost = Buffer.byteLength(line, "utf8") + 1;
2893
+ if (used + cost > TURN_TAIL_DIFF_MAX_BYTES) break;
2894
+ kept.push(line);
2895
+ used += cost;
2896
+ }
2897
+ return { text: kept.length ? `${kept.join("\n")}\n` : "", truncated: true };
2898
+ }
2899
+
2900
+ /**
2901
+ * 事件时间戳(issue #52,docs/03-api.md §6.20):只接受 SessionEvent.time 里
2902
+ * **有限非负数字**的 Unix 毫秒值,其余(缺失/字符串/NaN/负数)一律不下发——
2903
+ * App 不得用本地接收时间推算耗时,因此宁缺毋滥。
2904
+ */
2905
+ function eventTimeOf(event) {
2906
+ const time = event?.time;
2907
+ return typeof time === "number" && Number.isSafeInteger(time) && time >= 0 ? time : undefined;
2908
+ }
2909
+
1671
2910
  /**
1672
2911
  * 把 SessionEvent 转成移动端摘要(docs/03-api.md §3.6)。
1673
- * 返回 { seq, type, data?, detail? };未识别类型保留 type/seq,详情按需读取。
2912
+ * 返回 { seq, type, time?, data?, detail? };未识别类型保留 type/seq,详情按需读取。
2913
+ * v3.3(issue #52):顶层 `time` 为所有时间线事件摘要的增量字段(只增不改),
2914
+ * 供 App 计算轮次/过程组用时;旧字段形状不变。
1674
2915
  */
1675
- function summarizeEventCore(event) {
2916
+ function summarizeEventCore(event, options = {}) {
2917
+ const summary = summarizeEventCoreBody(event, options);
2918
+ const time = eventTimeOf(event);
2919
+ return time === undefined ? summary : { ...summary, time };
2920
+ }
2921
+
2922
+ /** summarizeEventCore 的原有逐类型摘要实现(issue #52 起由上面的包装补顶层 time)。 */
2923
+ function summarizeEventCoreBody(event, options = {}) {
1676
2924
  const { seq, type, data } = event;
1677
2925
  // review:内核实参可能缺 data(防御,避免 TypeError 打崩事件发射器)
1678
2926
  if (data === undefined) return { seq, type };
@@ -1751,7 +2999,21 @@ function summarizeEventCore(event) {
1751
2999
  if (typeof argumentsText !== "string") {
1752
3000
  try { argumentsText = JSON.stringify(argumentsText ?? {}); } catch { argumentsText = String(argumentsText ?? ""); }
1753
3001
  }
1754
- return { seq, type, data: { turn: data.turn, step: data.step, callId: data.callId, name: data.name, arguments: clampText(argumentsText, 2000) } };
3002
+ // issue #54:summary 从**原始** arguments 解析(先解析后 clamp);解析失败只降级,
3003
+ // 绝不让摘要/历史/SSE 抛错。
3004
+ const summary = toolCallSummaryOf(data.name, data.arguments, options.cwd);
3005
+ return {
3006
+ seq,
3007
+ type,
3008
+ data: {
3009
+ turn: data.turn,
3010
+ step: data.step,
3011
+ callId: data.callId,
3012
+ name: data.name,
3013
+ arguments: clampText(argumentsText, 2000),
3014
+ ...(summary === undefined ? {} : { summary }),
3015
+ },
3016
+ };
1755
3017
  }
1756
3018
  case "tool/result": {
1757
3019
  // v3.0.0(版本二):对齐 PC contentParts 语义——content 为 tool-result 块数组,
@@ -1759,7 +3021,9 @@ function summarizeEventCore(event) {
1759
3021
  const message = data.message;
1760
3022
  const blocks = Array.isArray(message?.content) ? message.content : [];
1761
3023
  // 兼容旧宿主/测试夹具直接提供的 { callId, name, text, isError } wire 形态。
1762
- let callId = typeof data.callId === "string" ? data.callId : typeof data.toolCallId === "string" ? data.toolCallId : "";
3024
+ // issue #60 recheck-4:真实结果形状的 callId 在 message.source.callId /
3025
+ // message.toolCallId / content[].toolCallId,不在 event.data.callId。
3026
+ let callId = toolResultCallIdOf(event);
1763
3027
  let isError = data.error !== undefined || data.isError === true;
1764
3028
  let text = typeof data.text === "string" ? data.text : "";
1765
3029
  const images = Array.isArray(data.images)
@@ -1781,6 +3045,12 @@ function summarizeEventCore(event) {
1781
3045
  // 学到的真名,于是已结束的工具卡标题变成裸 `call_00_...`(进行中的那张正常)。
1782
3046
  // 名字未知就不下发该字段,由消费端自行兜底显示「工具」。
1783
3047
  const resultName = directName || errName;
3048
+ // issue #54:结果摘要从**未 clamp 的原始文本**与宿主 meta 解析(exit/signal 标记
3049
+ // 通常在输出末尾,clamp 后可能被截掉;meta 只用来取匹配总数,不透传)。
3050
+ // issue #60 R14:结果事件常不带工具名;调用方通过 callId→tool/call.name 解析出
3051
+ // resolvedToolName 后再传进来,只有确定是 bash/pwsh 时才下发命令终止状态。
3052
+ const resolvedToolName = typeof options.resolvedToolName === "string" ? options.resolvedToolName : resultName;
3053
+ const resultSummary = toolResultSummaryOf(resolvedToolName, text, data.meta);
1784
3054
  return {
1785
3055
  seq,
1786
3056
  type,
@@ -1791,10 +3061,18 @@ function summarizeEventCore(event) {
1791
3061
  ...(resultName ? { name: resultName } : {}),
1792
3062
  isError,
1793
3063
  text: clampText(text, 2000),
3064
+ ...(resultSummary === undefined ? {} : { summary: resultSummary }),
1794
3065
  ...(images.length ? { images: images.slice(0, 20) } : {}),
1795
3066
  },
1796
3067
  };
1797
3068
  }
3069
+ case "tool/ptc-dispatch-start":
3070
+ case "tool/ptc-dispatch": {
3071
+ // issue #68(M3 Batch 2-C):PTC 子调用结构化投影。start → running,
3072
+ // result → success/failed;`callId` 来自内核 `subCallId`,`arguments`
3073
+ // 原文/`meta`/`content`/`error.reason` 永不下发(安全见投影 helper)。
3074
+ return ptcProjectionOf(event, options);
3075
+ }
1798
3076
  case "todo/write": {
1799
3077
  // v3.1.4(issue #12 姊妹需求):内核 dsh-tool-todo 每次调用写入**整份清单快照**
1800
3078
  // ({ todos: [{ content, status }] },status ∈ pending / in_progress / completed)。
@@ -1815,6 +3093,39 @@ function summarizeEventCore(event) {
1815
3093
  return { seq, type, data: { turn: data.turn } };
1816
3094
  case "turn/end":
1817
3095
  return { seq, type, data: { turn: data.turn, reason: data.reason } };
3096
+ case "deliverables/presented": {
3097
+ // issue #53(§6.20):交付文件声明只下发 name/display/description,**不下发主机
3098
+ // 绝对路径**;display 由本插件按会话工作目录派生(cwd 是宿主事实,随摘要上下文传入)。
3099
+ const files = Array.isArray(data.files) ? data.files : [];
3100
+ const cwd = options.cwd;
3101
+ const mapped = [];
3102
+ for (const file of files.slice(0, TURN_TAIL_MAX_FILES)) {
3103
+ const path = typeof file?.path === "string" ? file.path : "";
3104
+ if (path === "") continue;
3105
+ // issue #60 R08:服务端 display 是**脱敏后的展示值**,不同目录的同名文件会
3106
+ // 得到相同 display;再下发一个不泄路径的稳定身份(路径摘要)供 App 去重。
3107
+ // 该 id 不含可逆路径/主机前缀,只用于同一轮内跨 present 事件的同一文件合并。
3108
+ const identity = recordFileId(path, cwd);
3109
+ const entry = {
3110
+ id: identity,
3111
+ name: posixBasenameOf(path),
3112
+ display: mobileDisplayPath(path, cwd),
3113
+ };
3114
+ if (typeof file.description === "string" && file.description.trim() !== "") entry.description = clampText(file.description, 200);
3115
+ mapped.push(entry);
3116
+ }
3117
+ const turn = Number.isSafeInteger(data.turn) && data.turn >= 1 ? data.turn : undefined;
3118
+ const callId = typeof data.callId === "string" && data.callId !== "" ? data.callId : undefined;
3119
+ return {
3120
+ seq,
3121
+ type,
3122
+ data: {
3123
+ ...(turn === undefined ? {} : { turn }),
3124
+ ...(callId === undefined ? {} : { callId }),
3125
+ files: mapped,
3126
+ },
3127
+ };
3128
+ }
1818
3129
  default:
1819
3130
  return { seq, type };
1820
3131
  }
@@ -1855,8 +3166,8 @@ export function detailEventFor(event) {
1855
3166
  * 移动端事件摘要:保留轻量 data,同时声明可通过 seq 读取无损详情。
1856
3167
  * 老客户端只会忽略新增的 detail 字段,保持向后兼容。
1857
3168
  */
1858
- export function summarizeEvent(event) {
1859
- const summary = summarizeEventCore(event);
3169
+ export function summarizeEvent(event, options = {}) {
3170
+ const summary = summarizeEventCore(event, options);
1860
3171
  if (event?.seq === undefined || event?.seq === null) return summary;
1861
3172
  // 只对详情端点真的能取回的事件声明指针:token delta / 内部记录会被 /event-detail
1862
3173
  // 拒绝(isTimelineRecord),未列入 allow-list 的类型同样会被拒(fail-closed)。
@@ -2250,6 +3561,8 @@ export function apply(ctx, config, runtime = {}) {
2250
3561
  ? { token: String(runtime.authToken.token ?? ""), source: String(runtime.authToken.source ?? "runtime") }
2251
3562
  : resolvePluginAuthToken({ home: homedir(), configured: config.authToken });
2252
3563
  const authToken = authTokenState.token;
3564
+ // 不能把临时 UUID 宣告为稳定身份:身份不可用时阻止插件启动,保留现场供人工恢复。
3565
+ const hostIdentity = resolveHostIdentity();
2253
3566
  const authEnabled = authToken !== "";
2254
3567
  const authGenerated = authTokenState.source === "generated";
2255
3568
  // ── LAN 桥三态(#36 S1)配置归一(bootstrap/qr-config/diagnostics 在请求期读这些)──
@@ -2321,12 +3634,17 @@ export function apply(ctx, config, runtime = {}) {
2321
3634
  const pluginUpdateStatus = { state: "unknown", reason: "not-checked" };
2322
3635
  // 是否由 systemd 托管:决定"终止宿主后有没有人把它拉起来"。INVOCATION_ID 只有服务单元里才有。
2323
3636
  const systemdManaged = () => existsSync("/run/systemd/system") && Boolean(process.env.INVOCATION_ID);
2324
- const restartFormOf = runtime.pluginUpdates?.restartForm ?? (() => detectRestartForm({ hasSystemdUnit: systemdManaged }));
3637
+ // 前台 web 形态的重启必须复用**本进程原命令行**:容器/自定义启动常见 `dsh web --port 3082`,
3638
+ // 拼一个默认的 `dsh web --profile web` 会丢掉端口等参数(重启后监听面就变了)。
3639
+ const respawnCommand = respawnCommandOf(process.argv);
3640
+ const restartFormOf = runtime.pluginUpdates?.restartForm
3641
+ ?? (() => detectRestartForm({ hasSystemdUnit: systemdManaged, commandLine: process.argv }));
2325
3642
  const restartContext = () => ({
2326
3643
  plan: restartPlan({
2327
3644
  form: restartFormOf(),
2328
3645
  pid: process.pid,
2329
3646
  profile: process.env.DSH_PROFILE || "web",
3647
+ respawnCommand,
2330
3648
  }),
2331
3649
  pid: process.pid,
2332
3650
  });
@@ -2362,20 +3680,101 @@ export function apply(ctx, config, runtime = {}) {
2362
3680
  .catch((e) => Object.assign(pluginUpdateStatus, { state: "unavailable", reason: String(e?.message ?? e) }));
2363
3681
  };
2364
3682
  // 自更新能力与降级指引:内容状态驱动"能不能一键",版本号只管文案(评审 R11)。
3683
+ //
3684
+ // 通道选择(v3.5 / DSH 0.2.2+):宿主若提供 `pluginManager.updateBundle()`,就优先
3685
+ // 委托它在**进程内**更新——不重启宿主,也不依赖我们能否重启。传统「改依赖 →
3686
+ // pnpm install → 重启 → 健康确认」通道保留给旧宿主(<0.2.2)以及宿主管理器不可用的
3687
+ // 形态。两条通道都不可用时才退回人工指引。
3688
+ const hostUpdateState = {
3689
+ // 探测结果缓存:`listBundles()` 会读 profile 清单,不必每次请求都跑一遍。
3690
+ at: 0,
3691
+ result: null,
3692
+ // 探测失败/不可用时也为 true,避免每个请求都重试。
3693
+ settled: false,
3694
+ };
3695
+ const hostUpdateCacheMs = Number.isFinite(runtime.pluginUpdates?.hostCapabilityTtlMs)
3696
+ ? runtime.pluginUpdates.hostCapabilityTtlMs
3697
+ : 30_000;
3698
+ /**
3699
+ * 探测宿主原生更新能力(同步读缓存,异步刷新)。
3700
+ *
3701
+ * 首次调用返回「尚未探测」的中性结论,同时排一次探测;下一次请求就能拿到结论。
3702
+ * 这样 bootstrap 路径不会被 `listBundles()`(可能读盘、可能等锁)拖慢。
3703
+ */
3704
+ function hostUpdateCapabilities() {
3705
+ // 测试/定制注入优先:给了结论就不再去探测(生产不传)。
3706
+ if (runtime.pluginUpdates?.hostCapabilities !== undefined) {
3707
+ return runtime.pluginUpdates.hostCapabilities;
3708
+ }
3709
+ const cached = hostUpdateState.result;
3710
+ const fresh = cached && Date.now() - hostUpdateState.at < hostUpdateCacheMs;
3711
+ if (!fresh) {
3712
+ detectHostUpdateCapabilities({
3713
+ ctx,
3714
+ packageName: pluginPackageName,
3715
+ // 探测失败一律收敛成 unavailable,绝不向上抛;结论只影响通道选择。
3716
+ }).then((r) => {
3717
+ hostUpdateState.result = r;
3718
+ hostUpdateState.at = Date.now();
3719
+ hostUpdateState.settled = true;
3720
+ return r;
3721
+ }).catch(() => {
3722
+ hostUpdateState.result = {
3723
+ packageName: pluginPackageName, managerAvailable: false, managerReason: HOST_MANAGER_REASON.PROBE_FAILED,
3724
+ hmrAvailable: false, hmrReason: "", updatable: false,
3725
+ state: HOST_MANAGER_STATE.UNSUPPORTED, channel: UPDATE_CHANNEL.GUIDANCE, installedVersion: "",
3726
+ };
3727
+ hostUpdateState.at = Date.now();
3728
+ hostUpdateState.settled = true;
3729
+ return hostUpdateState.result;
3730
+ });
3731
+ }
3732
+ return hostUpdateState.result;
3733
+ }
3734
+ /** 宿主管理器当前是否可用于本插件(探测结论 + 目标可被它更新)。 */
3735
+ function hostManagerUsable() {
3736
+ const caps = hostUpdateCapabilities();
3737
+ return Boolean(caps && caps.managerAvailable && caps.updatable);
3738
+ }
2365
3739
  function pluginUpdateCapabilities() {
2366
3740
  const form = restartFormOf();
2367
3741
  const specifier = profileSpecifierOf(pluginProfileDir, { keys: pluginDependencyKeys });
2368
3742
  const specPath = specifier.startsWith("file:") ? specifier.slice("file:".length) : "";
2369
3743
  const isGitRepo = specPath !== "" && existsSync(join(specPath, ".git"));
2370
3744
  const installShape = detectInstallShape({ specifier, dirPath: specPath, isGitRepo: () => isGitRepo });
2371
- const canSelfUpdate = Boolean(pluginProfileDir) && form !== "unsupported";
3745
+ // 「能自动完成」由**通道**决定,不再只由重启形态决定:宿主管理器可用时,
3746
+ // 即使我们判断不出重启方式(容器、无 systemd、进程无 DSH_PROFILE)也能自动更新。
3747
+ const canRestart = Boolean(pluginProfileDir) && form !== "unsupported";
3748
+ const hostCaps = hostUpdateCapabilities();
3749
+ const channel = chooseUpdateChannel({
3750
+ hostManagerAvailable: hostManagerUsable(),
3751
+ canRestart,
3752
+ });
3753
+ const canSelfUpdate = channel.channel !== UPDATE_CHANNEL.GUIDANCE;
2372
3754
  const plan = planForShape(installShape, {
2373
3755
  specifier,
2374
3756
  dirPath: specPath,
2375
3757
  canSelfUpdate,
2376
3758
  reason: canSelfUpdate ? "" : pluginProfileDir ? `restart-form-${form}` : "profile-not-found",
3759
+ channel: channel.channel,
2377
3760
  });
2378
- return { installShape, canSelfUpdate, restartForm: form, guidance: plan };
3761
+ return {
3762
+ installShape,
3763
+ canSelfUpdate,
3764
+ restartForm: form,
3765
+ guidance: plan,
3766
+ // 通道与宿主动更能力(手机/桌面据此显示「不重启更新」还是「会重启」)。
3767
+ updateChannel: channel.channel,
3768
+ updateChannelDescription: describeUpdateChannel(channel.channel),
3769
+ hostManager: hostCaps ? {
3770
+ available: Boolean(hostCaps.managerAvailable && hostCaps.updatable),
3771
+ state: hostCaps.state,
3772
+ reason: hostCaps.managerReason || "",
3773
+ hmrAvailable: Boolean(hostCaps.hmrAvailable),
3774
+ } : null,
3775
+ // 兼容旧字段语义:`canSelfUpdate` 曾经等价于「能重启」,现在由通道决定。
3776
+ canRestartHost: canRestart,
3777
+ };
2379
3778
  }
2380
3779
  /** 客户端视图参数:公开基址只取 actual endpoint 视图(W1;Host/trustedHosts 不能证明监听)。 */
2381
3780
  function clientViewFor(_req) {
@@ -2411,6 +3810,17 @@ export function apply(ctx, config, runtime = {}) {
2411
3810
  workerOptions: { installedRoot: pluginRootDir, pluginRoot: pluginRootDir, needsEscape: systemdManaged(),
2412
3811
  restartForm: restartFormOf(), hostPid: process.pid, port: ctx.webServer.port, basePath,
2413
3812
  token: authToken, profile: process.env.DSH_PROFILE || "web", dshCommand: process.env.DSH_BIN || "dsh" },
3813
+ // DSH 0.2.2+:宿主原生插件管理器可用时,更新走「进程内卸载→安装」,不重启宿主。
3814
+ // 不提供该执行器的宿主(<0.2.2 或服务未挂载)自动回落到下面的重启通道。
3815
+ runHostUpdate: ({ targetVersion, installedVersion, onStep, log }) => runHostManagerUpdate({
3816
+ service: probeHostPluginManager(ctx).service,
3817
+ packageName: pluginPackageName,
3818
+ targetVersion,
3819
+ installedVersion,
3820
+ requestId: `mobile-remote-${targetVersion}`,
3821
+ onProgress: (progress) => onStep?.(progress.step === 'installing' ? 'installing' : 'staging'),
3822
+ log: { stage: (stage, message) => { onStep?.(stage); log?.(message); } },
3823
+ }),
2414
3824
  ...runtime.pluginUpdates,
2415
3825
  });
2416
3826
  // 实际监听成功才算可用(绑定失败时 QR/地址回退回环,不指向死端口)
@@ -3290,6 +4700,36 @@ export function apply(ctx, config, runtime = {}) {
3290
4700
  if (!Number.isSafeInteger(n) || n < 0) return null;
3291
4701
  return eventsOf(session).find((event) => Number(event?.seq) === n) ?? null;
3292
4702
  };
4703
+ /** 会话工作目录(宿主事实):live 会话在 header,休眠快照在 snapshot.session。 */
4704
+ const sessionCwdOf = (session) => {
4705
+ const cwd = session?.header?.cwd;
4706
+ return typeof cwd === "string" && cwd !== "" ? cwd : undefined;
4707
+ };
4708
+ /** 该轮**最新**一条 `workspace/changes` 事件(摘要与预览的 seq 坐标来源)。 */
4709
+ const latestWorkspaceChangesEvent = (session, turn) => {
4710
+ const events = eventsOf(session);
4711
+ for (let index = events.length - 1; index >= 0; index -= 1) {
4712
+ const event = events[index];
4713
+ if (event?.type === "workspace/changes" && Number(event?.data?.turn) === turn) return event;
4714
+ }
4715
+ return null;
4716
+ };
4717
+ /** 单个事件是否属于该会话的指定轮/类型(presented 坐标校验)。 */
4718
+ const presentedEventFilesOf = (event, index) => {
4719
+ if (!event || event.type !== "deliverables/presented") return null;
4720
+ const files = event?.data?.files;
4721
+ if (!Array.isArray(files) || index < 0 || index >= files.length) return null;
4722
+ const file = files[index];
4723
+ return typeof file?.path === "string" && file.path !== "" ? file : null;
4724
+ };
4725
+ /** 从记录里的路径解析出**只读目标**:相对路径按记录所属会话的工作目录展开。 */
4726
+ const resolveRecordedPath = (recordedPath, cwd) => {
4727
+ const text = normalizeServerPath(recordedPath);
4728
+ if (text === "") return null;
4729
+ if (isAbsolute(text)) return resolve(text);
4730
+ if (typeof cwd !== "string" || cwd === "") return null;
4731
+ return resolve(normalizeServerPath(cwd), text);
4732
+ };
3293
4733
  /** v3.1.2:从事件数组折叠会话配置(休眠会话读取用——0.1.2 模型选择事件为 model/selection)。 */
3294
4734
  const foldFromEvents = (events) => {
3295
4735
  const out = { model: undefined, provider: undefined, reasoningEffort: undefined, permissionPreset: undefined, agentPreset: undefined };
@@ -4809,6 +6249,19 @@ export function apply(ctx, config, runtime = {}) {
4809
6249
  pendingFrames.delete(oldest);
4810
6250
  }
4811
6251
  };
6252
+ // issue #68:PTC 50 子调用预算在 SSE 侧按会话维护(契约 §1.6/D8);会话数上限 200,
6253
+ // L2-5:超限按插入序 FIFO 逐出最旧(不做触碰刷新)。/history 每个响应各建一个,
6254
+ // 两处共用同一投影分支与 gate。
6255
+ const ptcBudgets = new Map(); // sessionId -> createPtcBudget()
6256
+ const ptcBudgetFor = (sessionId) => {
6257
+ let budget = ptcBudgets.get(sessionId);
6258
+ if (budget === undefined) {
6259
+ budget = createPtcBudget();
6260
+ ptcBudgets.set(sessionId, budget);
6261
+ if (ptcBudgets.size > 200) ptcBudgets.delete(ptcBudgets.keys().next().value);
6262
+ }
6263
+ return budget;
6264
+ };
4812
6265
  const connect = (res) => {
4813
6266
  if (connections.size >= config.maxConnections) {
4814
6267
  res.writeHead(503, { "content-type": "application/json; charset=utf-8" });
@@ -4826,7 +6279,7 @@ export function apply(ctx, config, runtime = {}) {
4826
6279
  "connection": "keep-alive",
4827
6280
  });
4828
6281
  res.write(": connected\n\n");
4829
- res.write(`data: ${JSON.stringify({ type: "hello", serverTime: Date.now(), capabilities: { eventTimeline: EVENT_TIMELINE_CAPABILITIES, turnOutline: turnOutlineCapabilityOf(ctx), fileRange: FILE_RANGE_CAPABILITIES, hold: { version: 1, onlineMs: Math.max(0, Number(config.pendingTimeoutMs ?? DEFAULT_PENDING_TIMEOUT_MS) || 0), offlineMs: Math.max(0, Number(config.offlineHoldMs ?? 300_000) || 0) } } })}\n\n`);
6282
+ res.write(`data: ${JSON.stringify({ type: "hello", serverTime: Date.now(), capabilities: { eventTimeline: EVENT_TIMELINE_CAPABILITIES, turnOutline: turnOutlineCapabilityOf(ctx), fileRange: FILE_RANGE_CAPABILITIES, turnTail: turnTailCapabilityOf(ctx), toolCards: toolCardsCapabilityOf(), hold: { version: 1, onlineMs: Math.max(0, Number(config.pendingTimeoutMs ?? DEFAULT_PENDING_TIMEOUT_MS) || 0), offlineMs: Math.max(0, Number(config.offlineHoldMs ?? 300_000) || 0) } } })}\n\n`);
4830
6283
  connections.add(res);
4831
6284
  // 补发断线期间挂起的问询/审批(与 PC 端 GUI 连接时的 pending 回放一致;超 TTL 的僵尸帧先清掉)
4832
6285
  for (const [key, f] of pendingFrames) {
@@ -4836,6 +6289,14 @@ export function apply(ctx, config, runtime = {}) {
4836
6289
  }
4837
6290
  res.write(`data: ${JSON.stringify({ type: "mobile/frame", frame: f })}\n\n`);
4838
6291
  }
6292
+ // v3.3(吸收上游 #64):同一有序流上,回放后追加完整待办快照边界。
6293
+ // 客户端只据此撤销本宿主已不在 pending 中的业务通知(其它宿主/常驻通知不受影响)。
6294
+ res.write(`data: ${JSON.stringify({ type: "attention/snapshot", version: 1,
6295
+ pending: [...pendingFrames.values()].flatMap((f) => {
6296
+ const kind = f.type === "approval/requested" ? "approval" : f.type === "question/requested" ? "question" : null;
6297
+ const identity = kind === "approval" ? f.approvalId || f.rpcId : f.rpcId;
6298
+ return kind && identity && f.sessionId ? [{ kind, identity, sessionId: f.sessionId }] : [];
6299
+ }) })}\n\n`);
4839
6300
  // v2.7:连接回放各会话任务视图(与 PC 端 GUI 同源)
4840
6301
  for (const f of sessionJobsFrames()) {
4841
6302
  res.write(`data: ${JSON.stringify(f)}\n\n`);
@@ -4843,7 +6304,26 @@ export function apply(ctx, config, runtime = {}) {
4843
6304
  };
4844
6305
  const onSessionEvent = (session, event) => {
4845
6306
  if (isLiveTimelineRecord(event)) {
4846
- broadcast({ type: "session/event", sessionId: session.id, event: summarizeEvent(event) });
6307
+ // issue #53:交付文件声明的 display 需要会话工作目录才能派生;turn/end 额外带
6308
+ // 轮末信号 `tail`(§6.20),供 App 决定是否渲染改动卡/交付卡。
6309
+ // issue #60 R14:实时 tool/result 同样按 callId→name 解析命令工具身份。
6310
+ const resolvedToolName = event.type === "tool/result"
6311
+ ? toolNamesOf(eventsOf(session)).get(toolResultCallIdOf(event))
6312
+ : undefined;
6313
+ const summary = summarizeEvent(event, {
6314
+ cwd: sessionCwdOf(session),
6315
+ resolvedToolName,
6316
+ // issue #68:PTC 事件的 turn/step 由原始会话事件派生(派生不到省略),
6317
+ // 50 预算按会话复用;两处 options 与 /history 同构。
6318
+ ...(isPtcDispatchEvent(event)
6319
+ ? { ...ptcLocationOf(eventsOf(session), event.seq), ptcBudget: ptcBudgetFor(session.id) }
6320
+ : {}),
6321
+ });
6322
+ if (event.type === "turn/end") {
6323
+ const tail = turnTailOf(eventsOf(session), event.data?.turn);
6324
+ if (tail) summary.data = { ...(summary.data ?? {}), tail };
6325
+ }
6326
+ broadcast({ type: "session/event", sessionId: session.id, event: summary });
4847
6327
  }
4848
6328
  // 会话有动静 = 标题可能变化:使该会话的标题缓存失效(活跃会话本就实时取标题,
4849
6329
  // 休眠会话不受影响——它没有实时事件流)
@@ -5560,12 +7040,17 @@ export function apply(ctx, config, runtime = {}) {
5560
7040
  // contentSha256 = **当前正在运行的代码**的内容标识:监督器与手机据此确认
5561
7041
  // "新实例已健康生效",而不是只看磁盘字节或版本号(评审 R1/R7)
5562
7042
  // instanceId = 本服务实例身份:换实例后旧健康结论不能冒充新的(§5.3)。
5563
- plugin: { name: "dsh-mobile-remote", version: pluginVersion(), contentSha256: selfContentSha256, pid: process.pid, instanceId: pluginInstanceId },
7043
+ plugin: { name: "dsh-mobile-remote", version: pluginVersion(), contentSha256: selfContentSha256, pid: process.pid, instanceId: pluginInstanceId, hostId: hostIdentity },
5564
7044
  capabilities: {
5565
7045
  eventTimeline: EVENT_TIMELINE_CAPABILITIES,
5566
7046
  // 宿主是否**真的**挂了 `turnOutline` 投影单元、且观察接口可用,决定声明是
5567
7047
  // "支持"还是"能力缺失"——App 先读声明再决定是否渲染未加载刻度(不按宿主版本推断)。
5568
7048
  turnOutline: turnOutlineCapabilityOf(ctx),
7049
+ // v3.3(issue #53):轮末产出物能力位;`changed/changesDiff` 只按宿主是否真的
7050
+ // 注册 `workspaceChanges` 判定(ADR 0017),SSE hello 同判据同形状。
7051
+ turnTail: turnTailCapabilityOf(ctx),
7052
+ // v3.4(issue #54):工具卡结构化投影能力位(按本插件实际投影的工具集合声明)。
7053
+ toolCards: toolCardsCapabilityOf(),
5569
7054
  // v3.2.3:普通文件下载支持 Range/HEAD/ETag(大文件续传 + 前缀预览)。
5570
7055
  fileRange: FILE_RANGE_CAPABILITIES,
5571
7056
  // v3.2.4(issue #55):手机端待办等待上限(仅供显示剩余时间,结算仍以服务端为准)。
@@ -6633,7 +8118,9 @@ export function apply(ctx, config, runtime = {}) {
6633
8118
  return error(res, 500, "session-read-failed", "会话存在但历史读取失败");
6634
8119
  }
6635
8120
  if (loaded.ok) {
6636
- session = { events: loaded.snapshot.events };
8121
+ // issue #53:保留会话头(工作目录)——交付文件 display 派生与
8122
+ // turn-file 的相对路径解析都需要它;事件本身仍走同一过滤。
8123
+ session = { events: loaded.snapshot.events, header: loaded.snapshot.session ?? loaded.snapshot.header };
6637
8124
  degraded = loaded.degraded === true;
6638
8125
  }
6639
8126
  }
@@ -6669,7 +8156,14 @@ export function apply(ctx, config, runtime = {}) {
6669
8156
  // seq 不连续(非完整日志),before/after 分页只在 surface 范围内有效——
6670
8157
  // 上翻到被 surface 替换的 log-only 历史区域时可能返回空页,属预期;
6671
8158
  // 客户端应结合 historyMode="current-surface" 提示"部分历史不可上翻"。
6672
- const surface = eventsOf(session).filter(isTimelineRecord);
8159
+ const rawEvents = eventsOf(session);
8160
+ const surface = rawEvents.filter(isTimelineRecord);
8161
+ // issue #53(§6.20):轮末信号 `turnTails` 由**一次遍历原始事件**得出(会话日志
8162
+ // 仍含被过滤的 `workspace/changes`),不额外调用宿主服务;只含有产出物的轮次。
8163
+ const turnTails = turnTailsOf(eventsOf(session));
8164
+ const cwd = sessionCwdOf(session);
8165
+ // issue #60 R14:结果事件通常无工具名,用 callId→name 关联后再解析终止状态。
8166
+ const toolNames = toolNamesOf(eventsOf(session));
6673
8167
  let events;
6674
8168
  let hasMore = false;
6675
8169
  if (afterParam !== null) {
@@ -6689,6 +8183,15 @@ export function apply(ctx, config, runtime = {}) {
6689
8183
  hasMore = surface.length > limit;
6690
8184
  events = surface.slice(-limit);
6691
8185
  }
8186
+ // issue #68(M3 Batch 2-C):PTC 子调用投影与 SSE 共用同一 summarizeEvent
8187
+ // 分支;50 预算按**本响应**新建(契约 §1.6/D8),turn/step 从原始事件
8188
+ // (不是过滤后的 surface,否则拿不到 step/start)派生,派生不到就省略。
8189
+ const ptcBudget = createPtcBudget();
8190
+ const summarizeForMobile = (event) => summarizeEvent(event, {
8191
+ cwd,
8192
+ resolvedToolName: event?.type === "tool/result" ? toolNames.get(toolResultCallIdOf(event)) : undefined,
8193
+ ...(isPtcDispatchEvent(event) ? { ...ptcLocationOf(rawEvents, event.seq), ptcBudget } : {}),
8194
+ });
6692
8195
  sendJson(res, 200, {
6693
8196
  ok: true,
6694
8197
  sessionId,
@@ -6697,7 +8200,8 @@ export function apply(ctx, config, runtime = {}) {
6697
8200
  ...(degraded ? { degraded: true, historyMode: "current-surface" } : {}),
6698
8201
  after: events.length ? events[events.length - 1].seq : 0,
6699
8202
  hasMore,
6700
- events: events.map(summarizeEvent),
8203
+ turnTails,
8204
+ events: events.map(summarizeForMobile),
6701
8205
  });
6702
8206
  return;
6703
8207
  }
@@ -7595,6 +9099,9 @@ export function apply(ctx, config, runtime = {}) {
7595
9099
  credentials: probe("credentials"),
7596
9100
  messageFeedback: probe("messageFeedback"),
7597
9101
  userQuestions: probe("userQuestions"),
9102
+ // DSH 0.2.2+:宿主原生插件管理能力(决定更新是否免重启)。能力看声明,不看版本号。
9103
+ pluginManager: probe("pluginManager"),
9104
+ hmr: probe("hmr"),
7598
9105
  };
7599
9106
  const checks = { modelsRpc: false, sessionsList: false, directories: false, workspaces: false, notifications: false, actions: false };
7600
9107
  try {
@@ -7767,7 +9274,7 @@ export function apply(ctx, config, runtime = {}) {
7767
9274
  checks.updateDir = `${updateDirState.source}${updateDirState.ready ? "" : `(${updateDirState.reason || "not-ready"})`}`;
7768
9275
  sendJson(res, 200, {
7769
9276
  ok: true,
7770
- plugin: { name: "dsh-mobile-remote", version: pluginVersion(), contentSha256: selfContentSha256, instanceId: pluginInstanceId },
9277
+ plugin: { name: "dsh-mobile-remote", version: pluginVersion(), contentSha256: selfContentSha256, instanceId: pluginInstanceId, hostId: hostIdentity },
7771
9278
  runtime: {
7772
9279
  // #36 follow-up(note 1509 §3/§4):form 取**桥启动决策时的同一份形态快照**,
7773
9280
  // 不再按请求重新探测(避免"诊断 desktop、启动 form-unknown"不一致);
@@ -7868,20 +9375,23 @@ export function apply(ctx, config, runtime = {}) {
7868
9375
  }
7869
9376
  // v3.1.1(issue #5):兜底兼容旧版 App 的 `\` 拼接(WSL 上 `/\home` 归一为 `/home`)
7870
9377
  const base = normalizeServerPath(path);
9378
+ // issue #45:`includeHidden=1` 时显示点开头条目;默认(含旧客户端不传参)
9379
+ // 保持旧行为,全部隐藏。无论开关如何,名称恰为 `.git` 的条目永不出现。
9380
+ const includeHidden = url.searchParams.get("includeHidden") === "1";
7871
9381
  try {
7872
9382
  const entries = await readdir(base, { withFileTypes: true });
7873
9383
  const dirs = entries
7874
- .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
9384
+ .filter((entry) => entry.isDirectory() && directoryEntryVisible(entry.name, includeHidden))
7875
9385
  .map((entry) => entry.name)
7876
9386
  .sort((a, b) => a.localeCompare(b, "zh-CN"));
7877
9387
  // v3.1.2:文件列表(文件选择器用;纯增量字段,旧版 App 忽略)
7878
9388
  const files = entries
7879
- .filter((entry) => entry.isFile() && !entry.name.startsWith("."))
9389
+ .filter((entry) => entry.isFile() && directoryEntryVisible(entry.name, includeHidden))
7880
9390
  .map((entry) => entry.name)
7881
9391
  .sort((a, b) => a.localeCompare(b, "zh-CN"));
7882
9392
  // v3.2.3:文件元数据(大小/修改时间/MIME);files 保持纯字符串以兼容旧 App。
7883
9393
  const fileEntries = entries
7884
- .filter((entry) => entry.isFile() && !entry.name.startsWith("."))
9394
+ .filter((entry) => entry.isFile() && directoryEntryVisible(entry.name, includeHidden))
7885
9395
  .map((entry) => {
7886
9396
  let size = null;
7887
9397
  let mtimeMs = null;
@@ -7940,74 +9450,285 @@ export function apply(ctx, config, runtime = {}) {
7940
9450
  .some((part) => part === "*" || part === etag);
7941
9451
  };
7942
9452
 
7943
- if (rest === "/files" && (method === "GET" || method === "HEAD")) {
7944
- const path = url.searchParams.get("path");
7945
- if (!path || path === "") return error(res, 400, "bad-request", "missing path");
7946
- const target = resolve(normalizeServerPath(path));
7947
- try {
7948
- const st = statSync(target);
7949
- if (!st.isFile()) return error(res, 400, "not-a-file", "path is not a file");
7950
- const name = basename(target);
7951
- // ETag 由「大小 + mtime」组成:文件被改写就变,够用且不用读内容。
7952
- const etag = `"${st.size.toString(16)}-${Math.floor(st.mtimeMs).toString(16)}"`;
7953
- const lastModified = new Date(st.mtimeMs).toUTCString();
7954
- guardRes(res);
7955
- if (ifNoneMatch(req, etag)) {
7956
- res.writeHead(304, { etag, "cache-control": "no-store", connection: "close" });
7957
- res.end();
7958
- return;
7959
- }
7960
- const range = parseByteRange(requestHeaderText(req, "range"), st.size);
7961
- if (range && range.invalid) {
7962
- res.writeHead(416, {
7963
- "accept-ranges": "bytes",
7964
- "content-range": `bytes */${st.size}`,
7965
- "content-length": "0",
7966
- etag,
7967
- "cache-control": "no-store",
7968
- connection: "close",
7969
- });
7970
- res.end();
7971
- return;
7972
- }
7973
- const start = range ? range.start : 0;
7974
- const end = range ? range.end : st.size - 1;
7975
- const length = st.size === 0 ? 0 : end - start + 1;
7976
- const headers = {
7977
- "content-type": fileMimeOf(name),
7978
- "content-length": String(length),
7979
- "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
7980
- "cache-control": "no-store",
9453
+ /**
9454
+ * 文件字节响应(v3.2.3 语义):Range/HEAD/ETag/If-None-Match/304/416 +
9455
+ * `connection: close`。`/files` 与 `/turn-file` 共用同一实现,避免头部语义漂移。
9456
+ * 文件不可读时抛错,由调用方映射成各自的稳定错误码。
9457
+ * @returns {true} 已写出响应(调用方仍应 return)。
9458
+ */
9459
+ const serveFileBytes = (req, res, target, { method }) => {
9460
+ const st = statSync(target);
9461
+ if (!st.isFile()) throw Object.assign(new Error("not-a-file"), { code: "not-a-file" });
9462
+ const name = basename(target);
9463
+ // 保留时间精度并纳入 ctime,避免同大小改写且恢复 mtime 后沿用旧断点。
9464
+ const etag = `"${st.size.toString(16)}-${st.mtimeMs.toString(16)}-${st.ctimeMs.toString(16)}"`;
9465
+ const lastModified = new Date(st.mtimeMs).toUTCString();
9466
+ guardRes(res);
9467
+ if (ifNoneMatch(req, etag)) {
9468
+ res.writeHead(304, { etag, "cache-control": "no-store", connection: "close" });
9469
+ res.end();
9470
+ return true;
9471
+ }
9472
+ // 断点属于旧文件时从头返回,不能把旧前缀和新后缀拼在一起。
9473
+ // 只认可当前强 ETag;旧标记/弱 ETag/日期统一退回完整响应。
9474
+ const ifRange = requestHeaderText(req, "if-range").trim();
9475
+ const range = parseByteRange(ifRange && ifRange !== etag ? "" : requestHeaderText(req, "range"), st.size);
9476
+ if (range && range.invalid) {
9477
+ res.writeHead(416, {
7981
9478
  "accept-ranges": "bytes",
9479
+ "content-range": `bytes */${st.size}`,
9480
+ "content-length": "0",
7982
9481
  etag,
7983
- "last-modified": lastModified,
7984
- // v3.1.5+39:取完即断(半关连接复用会让手机侧等满超时)
9482
+ "cache-control": "no-store",
7985
9483
  connection: "close",
7986
- ...(range ? { "content-range": `bytes ${start}-${end}/${st.size}` } : {}),
7987
- };
7988
- res.writeHead(range ? 206 : 200, headers);
7989
- if (method === "HEAD" || st.size === 0) {
7990
- res.end();
7991
- return;
9484
+ });
9485
+ res.end();
9486
+ return true;
9487
+ }
9488
+ const start = range ? range.start : 0;
9489
+ const end = range ? range.end : st.size - 1;
9490
+ const length = st.size === 0 ? 0 : end - start + 1;
9491
+ const headers = {
9492
+ "content-type": fileMimeOf(name),
9493
+ "content-length": String(length),
9494
+ "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
9495
+ "cache-control": "no-store",
9496
+ "accept-ranges": "bytes",
9497
+ etag,
9498
+ "last-modified": lastModified,
9499
+ // v3.1.5+39:取完即断(半关连接复用会让手机侧等满超时)
9500
+ connection: "close",
9501
+ ...(range ? { "content-range": `bytes ${start}-${end}/${st.size}` } : {}),
9502
+ };
9503
+ res.writeHead(range ? 206 : 200, headers);
9504
+ if (method === "HEAD" || st.size === 0) {
9505
+ res.end();
9506
+ return true;
9507
+ }
9508
+ const source = createReadStream(target, { start, end });
9509
+ // 客户端取消/断开时销毁文件流,避免 fd 泄漏。
9510
+ res.on("close", () => {
9511
+ try {
9512
+ source.destroy();
9513
+ } catch {
9514
+ // 已销毁
9515
+ }
9516
+ });
9517
+ source.on("error", () => {
9518
+ try {
9519
+ res.destroy();
9520
+ } catch {
9521
+ // 已销毁
7992
9522
  }
7993
- const source = createReadStream(target, { start, end });
7994
- // 客户端取消/断开时销毁文件流,避免 fd 泄漏。
7995
- res.on("close", () => {
9523
+ });
9524
+ source.pipe(res);
9525
+ return true;
9526
+ };
9527
+ /** 非负整数查询参数;缺失/非法都返回 null(调用方按 400 处理)。 */
9528
+ const nonNegativeIntParam = (raw) => {
9529
+ if (raw === null) return null;
9530
+ if (raw.trim() === "") return null;
9531
+ const value = Number(raw);
9532
+ if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) return null;
9533
+ return value;
9534
+ };
9535
+
9536
+ // ── v3.3(issue #53):轮末产出物(改动摘要 / 单文件对比 / 按坐标取文件) ──
9537
+ if (rest === "/changes/summary") {
9538
+ if (requireGet(method, res)) return;
9539
+ const sessionId = url.searchParams.get("sessionId");
9540
+ const turn = nonNegativeIntParam(url.searchParams.get("turn"));
9541
+ if (!sessionId) return error(res, 400, "bad-request", "missing sessionId or turn");
9542
+ if (turn === null) return error(res, 400, "bad-request", "turn must be a non-negative integer");
9543
+ const sessions = ctx.get("sessions");
9544
+ if (!sessions) return error(res, 503, "sessions-unavailable");
9545
+ // 服务不可用/会话休眠/摘要失效统一按 state 返回(不 5xx),App 统一降级不占位。
9546
+ const unavailable = { ok: true, state: "unavailable", turn, files: [], total: 0, added: 0, deleted: 0, truncated: false };
9547
+ const workspaceChanges = ctx.get("workspaceChanges");
9548
+ if (!workspaceChanges || typeof workspaceChanges.summary !== "function") return sendJson(res, 200, unavailable);
9549
+ const session = sessions.get(sessionId);
9550
+ if (!session) return sendJson(res, 200, unavailable);
9551
+ const source = latestWorkspaceChangesEvent(session, turn);
9552
+ if (!source) return sendJson(res, 200, { ...unavailable, state: "absent" });
9553
+ let summary;
9554
+ try {
9555
+ summary = workspaceChanges.summary(sessionId, source.seq);
9556
+ } catch (err) {
9557
+ ctx.logger.warn?.(`mobile-remote: changes.summary 读取失败(${sessionId}/${turn}):${failureDetail(err)}`);
9558
+ return sendJson(res, 200, unavailable);
9559
+ }
9560
+ if (!summary || !Array.isArray(summary.files)) return sendJson(res, 200, unavailable);
9561
+ const allFiles = summary.files;
9562
+ // issue #60 round7(F2):presented 的 cwd 来自 sessionCwdOf(session)(header.cwd),
9563
+ // changed 的 cwd 来自宿主 workspaceChanges.summary().cwd,**两者文本/基准不保证相同**
9564
+ // (同一 display 下会算出两个逻辑 id → App 行内/basename 链接丢失)。两条投影统一用
9565
+ // 「会话 base」:会话 cwd 优先、宿主摘要 cwd 兜底,再交给 canonicalWorkspacePath
9566
+ // 按 realpath 归一(消掉 symlink 别名 / 绝对路径形状差异)。绝不把 cwd 写进响应。
9567
+ // 真宿主 dsh-workspace-changes 的 recorderFor(session, cwd) 冻结 cwd=session.header.cwd
9568
+ // 并作为 summary.cwd 返回,故生产里两者本就相同;这里用会话 base 兜底裁剪/旧宿主。
9569
+ // 已知 P3 接受:① 裁剪宿主把 header.cwd 与 summary.cwd 指向不同子目录、且两处
9570
+ // 记录各自相对该 cwd 的文本时,单一 base 无法同时对齐(非真宿主形状);
9571
+ // ② 两处 cwd 都缺失且绝对/相对混排时无基准可归一(live 会话 header.cwd 必存在)。
9572
+ const idBase = sessionCwdOf(session) ?? summary.cwd;
9573
+ const files = allFiles.slice(0, TURN_TAIL_MAX_FILES).map((file, index) => {
9574
+ const recordedPath = typeof file?.path === "string" ? file.path : "";
9575
+ // issue #60 R05:宿主 display 可能是 cwd/home 外的**绝对路径**(合法宿主形状);
9576
+ // 一律从记录路径 + 会话 cwd 重新派生安全 display,绝不直通宿主 display。
9577
+ const displaySource = recordedPath !== "" ? recordedPath : (typeof file?.display === "string" ? file.display : "");
9578
+ const display = mobileDisplayPath(displaySource, idBase) || posixBasenameOf(displaySource);
9579
+ return {
9580
+ seq: source.seq,
9581
+ index,
9582
+ // round4-2:与 presented 共用同一路径摘要,供 App 按逻辑身份合并
9583
+ // delivered/changed;不含可拼路径。
9584
+ id: recordFileId(recordedPath, idBase),
9585
+ display,
9586
+ name: posixBasenameOf(recordedPath || display),
9587
+ added: Number.isFinite(file?.added) ? Math.max(0, Math.trunc(file.added)) : 0,
9588
+ deleted: Number.isFinite(file?.deleted) ? Math.max(0, Math.trunc(file.deleted)) : 0,
9589
+ binary: file?.binary === true,
9590
+ oversized: file?.oversized === true,
9591
+ };
9592
+ });
9593
+ return sendJson(res, 200, {
9594
+ ok: true,
9595
+ state: "available",
9596
+ turn,
9597
+ files,
9598
+ total: Number.isFinite(summary.total) ? Math.max(0, Math.trunc(summary.total)) : allFiles.length,
9599
+ added: Number.isFinite(summary.added) ? Math.max(0, Math.trunc(summary.added)) : 0,
9600
+ deleted: Number.isFinite(summary.deleted) ? Math.max(0, Math.trunc(summary.deleted)) : 0,
9601
+ // 宿主 maxFiles 或移动端 200 上限任一截断都显式标记;total 仍是全量计数。
9602
+ truncated: allFiles.length > TURN_TAIL_MAX_FILES || (Number.isFinite(summary.total) && summary.total > allFiles.length),
9603
+ });
9604
+ }
9605
+ if (rest === "/changes/diff") {
9606
+ if (requireGet(method, res)) return;
9607
+ const sessionId = url.searchParams.get("sessionId");
9608
+ const turn = nonNegativeIntParam(url.searchParams.get("turn"));
9609
+ const index = nonNegativeIntParam(url.searchParams.get("index"));
9610
+ if (!sessionId) return error(res, 400, "bad-request", "missing sessionId, turn or index");
9611
+ if (turn === null || index === null) return error(res, 400, "bad-request", "turn/index must be non-negative integers");
9612
+ const sessions = ctx.get("sessions");
9613
+ if (!sessions) return error(res, 503, "changes-unavailable");
9614
+ const workspaceChanges = ctx.get("workspaceChanges");
9615
+ if (!workspaceChanges || typeof workspaceChanges.diff !== "function") return error(res, 503, "changes-unavailable");
9616
+ // 摘要只随 live 会话存在:休眠/重启后没有可对比内容(§6.22)。
9617
+ const session = sessions.get(sessionId);
9618
+ const source = session ? latestWorkspaceChangesEvent(session, turn) : null;
9619
+ if (!source) return error(res, 404, "diff-not-found");
9620
+ let diff;
9621
+ try {
9622
+ diff = await workspaceChanges.diff(sessionId, source.seq, index, requestAbort(res));
9623
+ } catch (err) {
9624
+ if (res.destroyed || res.writableEnded) return;
9625
+ ctx.logger.warn?.(`mobile-remote: changes.diff 读取失败(${sessionId}/${turn}/${index}):${failureDetail(err)}`);
9626
+ return error(res, 503, "changes-unavailable");
9627
+ }
9628
+ if (!diff) return error(res, 404, "diff-not-found");
9629
+ // issue #60 R05:diff 的 display 同样不得直通宿主(可能是绝对路径);从 diff.path
9630
+ // 与会话 cwd 重新派生,并让统一 diff 的 ---/+++ 标头使用同一安全值。
9631
+ const diffPathSource = typeof diff.path === "string" && diff.path !== "" ? diff.path : (typeof diff.display === "string" ? diff.display : "");
9632
+ const safeDisplay = mobileDisplayPath(diffPathSource, sessionCwdOf(session)) || posixBasenameOf(diffPathSource);
9633
+ if (diff.kind === "binary" || diff.kind === "oversized") {
9634
+ return sendJson(res, 200, {
9635
+ ok: true,
9636
+ state: "available",
9637
+ diff: { kind: diff.kind, display: safeDisplay },
9638
+ });
9639
+ }
9640
+ const rendered = renderUnifiedDiffText(diff, safeDisplay);
9641
+ return sendJson(res, 200, {
9642
+ ok: true,
9643
+ state: "available",
9644
+ diff: {
9645
+ kind: "text",
9646
+ display: safeDisplay,
9647
+ before: diff.before !== false,
9648
+ after: diff.after !== false,
9649
+ coarse: diff.coarse === true,
9650
+ diff: rendered.text,
9651
+ truncated: rendered.truncated,
9652
+ },
9653
+ });
9654
+ }
9655
+ if (rest === "/turn-file" && (method === "GET" || method === "HEAD")) {
9656
+ const sessionId = url.searchParams.get("sessionId");
9657
+ const kind = url.searchParams.get("kind");
9658
+ const seq = nonNegativeIntParam(url.searchParams.get("seq"));
9659
+ const index = nonNegativeIntParam(url.searchParams.get("index"));
9660
+ if (!sessionId || (kind !== "presented" && kind !== "changed")) return error(res, 400, "bad-request", "missing sessionId or invalid kind");
9661
+ if (seq === null || index === null) return error(res, 400, "bad-request", "seq/index must be non-negative integers");
9662
+ const sessions = ctx.get("sessions");
9663
+ if (!sessions) return error(res, 503, "sessions-unavailable");
9664
+ let target = null;
9665
+ if (kind === "presented") {
9666
+ // 路径只从会话记录里解析:客户端只给坐标,不能指定路径(GitLab #16 收紧方向)。
9667
+ const query = ctx.get("sessionQuery");
9668
+ let event = null;
9669
+ let cwd;
9670
+ if (typeof query?.readEvent === "function") {
7996
9671
  try {
7997
- source.destroy();
9672
+ const read = await query.readEvent({ sessionId, seq });
9673
+ event = read?.target ?? read?.event ?? read?.value ?? null;
9674
+ cwd = read?.session?.cwd ?? read?.header?.cwd;
7998
9675
  } catch {
7999
- // 已销毁
9676
+ event = null;
8000
9677
  }
8001
- });
8002
- source.on("error", () => {
9678
+ }
9679
+ const liveSession = sessions.get(sessionId);
9680
+ if (!event && liveSession) {
9681
+ event = eventBySeq(liveSession, seq);
9682
+ cwd ??= sessionCwdOf(liveSession);
9683
+ }
9684
+ if (!event && typeof query?.readSession === "function") {
8003
9685
  try {
8004
- res.destroy();
9686
+ const snapshot = await query.readSession(sessionId);
9687
+ event = (snapshot?.events ?? []).find((candidate) => Number(candidate?.seq) === seq) ?? null;
9688
+ cwd ??= snapshot?.session?.cwd ?? snapshot?.header?.cwd;
8005
9689
  } catch {
8006
- // 已销毁
9690
+ event = null;
8007
9691
  }
8008
- });
8009
- source.pipe(res);
9692
+ }
9693
+ const file = presentedEventFilesOf(event, index);
9694
+ if (!file) return error(res, 404, "record-not-found");
9695
+ cwd ??= sessionCwdOf(liveSession);
9696
+ target = resolveRecordedPath(file.path, cwd);
9697
+ if (!target) return error(res, 404, "record-not-found");
9698
+ } else {
9699
+ const workspaceChanges = ctx.get("workspaceChanges");
9700
+ if (!workspaceChanges || typeof workspaceChanges.summary !== "function") return error(res, 503, "changes-unavailable");
9701
+ const session = sessions.get(sessionId);
9702
+ // 改动摘要只随 live 会话存在:休眠/重启后没有可解析的路径(§6.23)。
9703
+ if (!session) return error(res, 503, "changes-unavailable");
9704
+ let summary;
9705
+ try {
9706
+ summary = workspaceChanges.summary(sessionId, seq);
9707
+ } catch {
9708
+ summary = undefined;
9709
+ }
9710
+ if (!summary || !Array.isArray(summary.files)) return error(res, 503, "changes-unavailable");
9711
+ const file = summary.files[index];
9712
+ if (!file || typeof file?.path !== "string" || file.path === "") return error(res, 404, "record-not-found");
9713
+ target = resolveRecordedPath(file.path, summary.cwd);
9714
+ if (!target) return error(res, 404, "record-not-found");
9715
+ }
9716
+ try {
9717
+ serveFileBytes(req, res, target, { method });
9718
+ } catch {
9719
+ // 记录里的文件已被删除/不可读:不泄露主机路径。
9720
+ return error(res, 404, "file-not-found");
9721
+ }
9722
+ return;
9723
+ }
9724
+ if (rest === "/files" && (method === "GET" || method === "HEAD")) {
9725
+ const path = url.searchParams.get("path");
9726
+ if (!path || path === "") return error(res, 400, "bad-request", "missing path");
9727
+ const target = resolve(normalizeServerPath(path));
9728
+ try {
9729
+ serveFileBytes(req, res, target, { method });
8010
9730
  } catch (err) {
9731
+ if (err?.code === "not-a-file") return error(res, 400, "not-a-file", "path is not a file");
8011
9732
  return error(res, 404, "file-not-found", failureDetail(err)); // v3.1.5 S7:不再回主机绝对路径(含进程 cwd)
8012
9733
  }
8013
9734
  return;
@@ -8611,9 +10332,14 @@ export function apply(ctx, config, runtime = {}) {
8611
10332
  // 旧值空串让服务端只能靠 `find(e => e.rpcId === "")` 命中"第一个"条目——
8612
10333
  // 多会话并发接管时会张冠李戴。
8613
10334
  const holdApproval = (req, sessionId) => {
8614
- const phoneKey = `${sessionId}:${typeof req?.callId === "string" && req.callId !== ""
10335
+ // issue #60 R16:审批身份必须标识**这一次审批请求**,callId 只作关联。同一工具在
10336
+ // pre-execute 与工具体内 sandbox escalation 会复用 callId;若用 sessionId:callId
10337
+ // 作身份,App 会把第二次新审批误当成已解决请求重放而永久静默。
10338
+ // 因此每次实际请求生成唯一 approvalId;断线重连回放同一 entry 时 id 不变。
10339
+ const callRef = typeof req?.callId === "string" && req.callId !== ""
8615
10340
  ? req.callId
8616
- : Date.now().toString(36)}`;
10341
+ : Date.now().toString(36);
10342
+ const phoneKey = `${sessionId}:${callRef}:${randomUUID()}`;
8617
10343
  const phoneOnline = connections.size > 0;
8618
10344
  const holdMs = phoneOnline ? PENDING_TIMEOUT_MS : OFFLINE_HOLD_MS;
8619
10345
  ctx.logger.info?.(`mobile-remote: approval/request 手机接管(${sessionId} tool=${req?.toolName}${phoneOnline ? "" : `,手机离线,最多等待 ${Math.round(holdMs / 1000)}s`})`);
@@ -8689,14 +10415,11 @@ export function apply(ctx, config, runtime = {}) {
8689
10415
  if (!sessionId || !eventId) return;
8690
10416
  const request = frame.request ?? {};
8691
10417
  if (frame.event === "approval/request") {
8692
- const phoneKey = `${sessionId}:${typeof request.callId === "string" && request.callId !== ""
8693
- ? request.callId
8694
- // 评审 WARNING 2:`callId` 缺失时**不能**回退到时间戳——宿主在新连接建立时会
8695
- // 重放尚未结算的事件(dsh-api-gateway 的 remoteEventClients 交付逻辑),
8696
- // 时间戳身份会让同一次回放生成第二个待办,于是「按 rpcId 查到旧条目、按最新
8697
- // questionId 查到新条目」,合法回答被判 400。`eventId` 稳定且已是本条的 rpcId,
8698
- // 用它兜底可让上面的 has() 去重真正生效。
8699
- : eventId}`;
10418
+ // issue #60 R16:$events 路径的身份必须标识**这一次实际审批请求**,callId 只作
10419
+ // 关联(同一工具 pre-execute 与 sandbox escalation 会复用同一个 callId)。
10420
+ // eventId 每次实际请求唯一,且宿主断线重放同一事件时保持不变——既不会让第二次
10421
+ // 新审批被第一次的 resolved 身份拦截,又保留重放去重(下面的 has())。
10422
+ const phoneKey = `${sessionId}:${eventId}`;
8700
10423
  if (pendingApprovals.has(phoneKey)) return;
8701
10424
  ctx.logger.info?.(`mobile-remote: approval/request 双端呈现(${sessionId} tool=${request?.toolName}${phoneOnline ? "" : ",手机离线→记账待回放"})`);
8702
10425
  const entry = {