@marktrue/dsh-mobile-remote 3.2.4-alpha.6 → 3.2.4-alpha.7

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/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## v3.2.4-alpha.7(build 39,issues #52 / #53 / #54)— 轮末两卡与工具卡结构化
4
+
5
+ > 插件 `3.2.4-alpha.7` / App `3.2.4+39` / 载体 `3.2.4-alpha.7-app`。
6
+
7
+ ### 服务端:轮末产出物契约与三端点(#53 / M2)
8
+
9
+ - 新增 `capabilities.turnTail`:`{ version: 1, presented, changed, changesDiff }`;`changed` / `changesDiff` 仅当宿主**真的注册** `workspaceChanges` 服务时为真(bootstrap 与 SSE `hello` 同判据、同形状),旧宿主按缺失能力位降级。
10
+ - `GET /m/api/history` 增量 `turnTails`(按轮摘要 `changes/presented`,单次遍历已加载事件得出,不调用宿主服务)。
11
+ - 新增三端点:`GET /m/api/changes/summary`(本轮改动摘要)、`GET /m/api/changes/diff`(单文件最小闭环 diff)、`GET /m/api/turn-file`(按轮末记录坐标预览/下载,支持 HEAD/区间读取)。
12
+ - `workspace/changes` 事件不再进入移动时间线(由轮末两卡承载),旧 App 不会渲染裸类型空卡。
13
+
14
+ ### App:轮末两卡、按坐标预览与展示模式(#52 / #53 / M1+M2)
15
+
16
+ - 轮末新增「产出物 / 改动」两卡:产出物卡按宿主记录坐标打开预览,改动卡展示本轮变更文件与 diff;无 `turnTail` 能力位时两卡与相关设置不渲染。
17
+ - 新增按坐标文件预览(`/turn-file`)与改动 diff 预览入口,沿用既有只读、鉴权与路径校验边界。
18
+ - 补全四档展示策略表(简洁 / 标准 / 详细 / 完全展开)的折叠与步骤分组语义,与桌面 `presentation-policy.js` 同构(ADR 0027 增补)。
19
+
20
+ ### 服务端 + App:工具卡结构化(#54 / M3 Batch 1)
21
+
22
+ - 能力位 `capabilities.toolCards = { version: 1, tools: [...] }`,声明本插件实际投影的 10 类工具(bash/pwsh/read/write/edit/grep/glob/web_fetch/web_search/read_image);App 逐工具决定专用卡,未列入或字段异常一律回退通用卡。
23
+ - `tool/call` 摘要派生命名参数:`kind`(command/file/search/web/image)、命令、显示路径、`sizeKb`、行范围、pattern、URL、查询、后台标志、write/edit 内联 diff(≤ 8 KiB,超出标记 `diffTruncated`);路径统一经 `mobileDisplayPath`,**不下发绝对路径**。
24
+ - `tool/result` 摘要从原始未截断文本解析 `exitCode` / `signal` / `stopped` / `resultCount`(长输出尾部标记不被摘要截断吃掉);解析不到时缺省,不猜。
25
+ - 全部字段 fail-open:非法 JSON、未知工具、异常字段忽略并回退通用卡,不影响事件摘要/历史/SSE。
26
+
27
+ ### 工具链
28
+
29
+ - `tools/proxy-env.sh` 增加 `NO_PROXY` 注入,修复 `flutter-test` 门禁在代理环境下卡死;`worktree.sh` / 自测同步调整。
30
+ - `tools/timeline-contract-check.mjs` 扩展轮末与工具卡契约断言(turn-tail / tool-cards 路由与投影测试同时入库)。
31
+ - 补齐 `/changes/summary`、`/changes/diff`、`/turn-file` 的端点登记(ADR 0019 登记强制化),并把 `proxy-env` 门禁测试指向重构后的 `tools/proxy-env.sh`;Node 全量门禁恢复无真实失败。
32
+
3
33
  ## v3.2.4-alpha.6(build 38,issues #40 / #52 / #53 / #56 / #59)— 吸收上游 main、轮次过程折叠与兼容性 canary
4
34
 
5
35
  > 插件 `3.2.4-alpha.6` / App `3.2.4+38` / 载体 `3.2.4-alpha.6-app`。
package/docs/03-api.md CHANGED
@@ -127,6 +127,7 @@
127
127
  - `capabilities.turnOutline`:轮次大纲能力位(轮次导航)。宿主**真的注册了** `turnOutline` 投影单元、且投影感知观察面(`sessionQuery.observeSession`)可用时,返回 `{ "version": 1, "supported": true, "unloaded": true, "truncated": true }`——`unloaded` 表示未加载轮次也可跳转、`truncated` 表示超过体积上限会显式截断;否则返回 `{ "version": 1, "supported": false }`。**不按宿主版本号推断**:旧宿主/裁剪宿主显式声明不支持,App 据此退回「只用已加载轮次」的降级行为。SSE hello 的同名字段与该处**同判据、同形状**(见 §3.6 与 §6.18)。
128
128
 
129
129
  - `capabilities.turnTail`:轮末页脚能力位(v3.3,issue #52/#53):宿主注册了 `workspaceChanges` 服务时返回 `{ "version": 1, "presented": true, "changed": true, "changesDiff": true }`,否则 `presented` 仍可为真而 `changed`/`changesDiff` 为假;旧插件不下发该字段,App 据此不渲染轮末卡片与展示模式设置。判据与字段详见 §6.20,SSE hello 同名字段与之同判据、同形状。
130
+ - `capabilities.toolCards`:工具卡结构化能力位(v3.3,issue #54):`{ "version": 1, "tools": [本插件实际投影的工具名…] }`;bootstrap 与 SSE hello 同判据,App 逐工具决定专用卡或通用卡,缺失时全部通用卡(见 §6.24)。
130
131
 
131
132
  - 未认证:`401`(见通用约定)。
132
133
  ### 3.2 POST /m/api/send
@@ -1279,3 +1280,57 @@ graph 的每个提交与 commit 详情都**保留旧的** `refs: string[]`(dep
1279
1280
  **与 `/m/api/files` 的边界**:本端点**不接受客户端指定路径**,路径由服务端从会话记录解析;只允许该记录内的文件(GitLab #16 的收紧方向)。读取失败不泄露主机路径。
1280
1281
 
1281
1282
  - 稳定错误:`400 bad-request`、`404 record-not-found`(事件不存在/不属于该会话/下标越界)、`404 file-not-found`(记录内的文件已被删除)、`503 changes-unavailable`(改动摘要已失效)。
1283
+
1284
+ ### 6.24 工具卡结构化投影(v3.3,issue #54 / M3 Batch 1)
1285
+
1286
+ 手机端工具卡从「通用卡」升级为「按工具类型专用卡」。服务端只做**结构化投影**,不改变工具执行语义;所有字段只增不改,旧 App 忽略。
1287
+
1288
+ **能力位**(`GET /m/api/bootstrap` 与 SSE `hello` 同判据、同形状):
1289
+
1290
+ ```json
1291
+ "capabilities": {
1292
+ "toolCards": { "version": 1, "tools": ["bash","pwsh","read","write","edit","grep","glob","web_fetch","web_search","read_image"] }
1293
+ }
1294
+ ```
1295
+
1296
+ - `tools` 是本插件**实际能投影**的工具名集合;App 逐工具决定是否使用专用卡,不在集合内一律回退通用卡。
1297
+ - 旧插件不下发该字段 → 新 App 全部通用卡(不按版本号推断,ADR 0017)。
1298
+
1299
+ **`tool/call` 摘要增量 `summary`**(从原始 `arguments` 解析,先解析后 clamp;非法 JSON/未知工具 fail-open):
1300
+
1301
+ | 字段 | 类型 | 适用 | 说明 |
1302
+ |---|---|---|---|
1303
+ | `kind` | string | 全部 | `command` / `file` / `search` / `web` / `image` |
1304
+ | `tool` | string | 全部 | 工具名 |
1305
+ | `command` | string | bash/pwsh | 单行化命令,≤200 字 |
1306
+ | `workdir` | string? | bash/pwsh | 显示用目录(`mobileDisplayPath`),非绝对路径 |
1307
+ | `background` | bool? | bash/pwsh | 后台调用标志 |
1308
+ | `description` | string? | bash/pwsh | 工具自带的说明,≤120 字 |
1309
+ | `filePath` | string | read/write/edit/read_image | 显示用路径,**绝不下发可拼接绝对路径** |
1310
+ | `offset` / `limit` | number? | read | 行范围(正整数,可缺省) |
1311
+ | `sizeKb` | number? | write/edit | `ceil(UTF-16 长度/1024)`,与桌面 `NKB` 同口径 |
1312
+ | `added` / `deleted` | number? | write/edit | 折叠行行数统计;write 为新增行数,edit 为**行数近似**(见口径) |
1313
+ | `diff` | string? | write/edit | 统一 diff 文本,仅 ≤8 KiB 时下发 |
1314
+ | `diffTruncated` | bool? | write/edit | diff 超过上限而为缺省时为 `true`(不截半段) |
1315
+ | `pattern` | string | grep/glob | 搜索模式,≤200 字 |
1316
+ | `path` | string? | grep/glob | 搜索路径显示名 |
1317
+ | `include` | string? | grep | include 过滤 |
1318
+ | `url` | string? | web_fetch | 目标 URL |
1319
+ | `query` | string? | web_search | 首个查询词 |
1320
+
1321
+ **`tool/result` 摘要增量 `summary`**(从未 clamp 的原始结果文本/宿主 meta 解析,解析不到缺省):
1322
+
1323
+ | 字段 | 类型 | 适用 | 说明 |
1324
+ |---|---|---|---|
1325
+ | `exitCode` | number? | bash/pwsh | 从结果文本 `[exit code: N]` 标记解析 |
1326
+ | `signal` | string? | bash/pwsh | 从 `[killed by signal: X]` 解析 |
1327
+ | `stopped` | string? | bash/pwsh | 从 `[stopped: …]` 解析;App 显示「已停止」胶囊 |
1328
+ | `resultCount` | number? | grep/glob | 匹配总数:优先宿主 `meta.total`(meta 本身不透传),缺失时按稳定文本句式解析 |
1329
+
1330
+ **显式口径**:
1331
+
1332
+ 1. `summary.stopped` 为契约外新增的**可选**字段(需求只要求解析 `[stopped: …]`),保留并作为「已停止」语义。
1333
+ 2. write 的 `diff` 为「全新增」统一 diff;edit 的 `added`/`deleted` 是 **old/new 行数近似**,不承诺与宿主精确行级统计一致。
1334
+ 3. `resultCount` 的文本兜底是启发式(如 glob 在结果上限内按非空行计数);无 meta 且无工具名时保守缺省,不猜。
1335
+ 4. 全部字段 fail-open:字段异常/超长/非法 JSON 一律忽略并回退通用卡,不得让摘要、历史或 SSE 出错。
1336
+ 5. 路径安全:`filePath`/`workdir`/`path` 只下发 `mobileDisplayPath` 派生结果,不提供可直接读取的主机路径。
@@ -109,6 +109,8 @@ export const REGISTERED_ENDPOINTS = Object.freeze([
109
109
  { path: "/balance", methods: "GET", capability: null, why: NO_CAPABILITY_NEEDED },
110
110
  { path: "/bootstrap", methods: "GET", capability: null, why: NO_CAPABILITY_NEEDED },
111
111
  { path: "/catalog", methods: "GET", capability: null, why: NO_CAPABILITY_NEEDED },
112
+ { path: "/changes/diff", methods: "GET", capability: "turnTail" },
113
+ { path: "/changes/summary", methods: "GET", capability: "turnTail" },
112
114
  { path: "/commands", methods: "GET/POST", capability: null, why: NO_CAPABILITY_NEEDED },
113
115
  { path: "/defaults", methods: "GET/POST", capability: null, why: NO_CAPABILITY_NEEDED },
114
116
  { path: "/dev/approval-test", methods: "GET/POST", capability: null, why: NO_CAPABILITY_NEEDED },
@@ -158,6 +160,7 @@ export const REGISTERED_ENDPOINTS = Object.freeze([
158
160
  { path: "/subagents", methods: "GET", capability: null, why: NO_CAPABILITY_NEEDED },
159
161
  { path: "/subagents/interrupt", methods: "GET/POST", capability: null, why: NO_CAPABILITY_NEEDED },
160
162
  { path: "/todos", methods: "GET", capability: null, why: NO_CAPABILITY_NEEDED },
163
+ { path: "/turn-file", methods: "GET/POST", capability: "turnTail" },
161
164
  { path: "/turn-outline", methods: "GET", capability: "turnOutline" },
162
165
  { path: "/update/apk", methods: "GET", capability: null, auth: "anonymous", why: NO_CAPABILITY_NEEDED },
163
166
  { path: "/update/manifest", methods: "GET", capability: null, auth: "required", why: NO_CAPABILITY_NEEDED },
package/lib/index.js CHANGED
@@ -723,6 +723,55 @@ const TURN_OUTLINE_CAPABILITIES = {
723
723
  /** 宿主未挂载该投影时的能力声明:必须与"可用"区分,App 据此退回一期行为。 */
724
724
  const TURN_OUTLINE_CAPABILITY_MISSING = { version: 1, supported: false };
725
725
 
726
+ /**
727
+ * 轮末产出物能力位(v3.3,issue #53 / docs/03-api.md §6.20)。
728
+ *
729
+ * `presented` 恒为真(本插件负责投影 `deliverables/presented` 声明);
730
+ * `changed`/`changesDiff` 只在宿主**真的注册**了 `workspaceChanges` 服务时为真,
731
+ * 不按宿主版本推断(ADR 0017 三态探测)。
732
+ */
733
+ const TURN_TAIL_CAPABILITY_VERSION = 1;
734
+ /** 摘要文件列表的移动端上限(§6.21;超出的部分展示 `truncated`,`total` 仍是全量)。 */
735
+ export const TURN_TAIL_MAX_FILES = 200;
736
+ /** 统一 diff 文本体积上限(§6.22):超出按行边界截断并置 `truncated`。 */
737
+ export const TURN_TAIL_DIFF_MAX_BYTES = 512 * 1024;
738
+
739
+ /**
740
+ * M3(issue #54 Batch 1):本插件实际投影的工具集合与能力位。
741
+ *
742
+ * App 以 `capabilities.toolCards.tools` 决定哪些工具用专用卡;未列入的工具(未知/自定义)
743
+ * 一律回退现有通用卡。声明按**本插件实现**给出,不按宿主版本推断(ADR 0017)。
744
+ */
745
+ export const TOOL_CARD_TOOLS = Object.freeze([
746
+ "bash",
747
+ "pwsh",
748
+ "read",
749
+ "write",
750
+ "edit",
751
+ "grep",
752
+ "glob",
753
+ "web_fetch",
754
+ "web_search",
755
+ "read_image",
756
+ ]);
757
+ /** 工具卡结构化投影版本(只增不改)。 */
758
+ export const TOOL_CARDS_CAPABILITY_VERSION = 1;
759
+ /** write/edit 摘要内联 diff 的体积上限(§issue #54 note 1761):超出缺省并标 diffTruncated。 */
760
+ export const TOOL_CARD_DIFF_MAX_BYTES = 8 * 1024;
761
+ /** 工具名 → 卡片 kind(未列入即通用卡)。 */
762
+ const TOOL_CARD_KIND = Object.freeze({
763
+ bash: "command",
764
+ pwsh: "command",
765
+ read: "file",
766
+ write: "file",
767
+ edit: "file",
768
+ grep: "search",
769
+ glob: "search",
770
+ web_fetch: "web",
771
+ web_search: "web",
772
+ read_image: "image",
773
+ });
774
+
726
775
  /**
727
776
  * 冷折叠有界等待上限(issue #25 性能前置实测,2026-10-09):单会话最坏实测 1.8 s
728
777
  * (证据见 reports/25-cold-fold-20261009.md),并发时单会话仍 ≤1.8 s;5 s ≈3× 余量。
@@ -891,6 +940,41 @@ export function turnOutlineCapabilityOf(ctx) {
891
940
  return registered && observable ? TURN_OUTLINE_CAPABILITIES : TURN_OUTLINE_CAPABILITY_MISSING;
892
941
  }
893
942
 
943
+ /**
944
+ * 轮末产出物能力探测(issue #53):bootstrap、SSE hello 与三个端点必须使用同一判据。
945
+ * 宿主没有 `workspaceChanges` 时仍声明 `presented: true`(交付文件来自会话日志),
946
+ * 但 `changed`/`changesDiff` 为假,App 据此不渲染改动卡。
947
+ * @param {any} ctx 插件上下文。
948
+ * @returns {{version: number, presented: boolean, changed: boolean, changesDiff: boolean}}
949
+ */
950
+ export function turnTailCapabilityOf(ctx) {
951
+ const service = ctx.get("workspaceChanges");
952
+ let readable = false;
953
+ let diffable = false;
954
+ try {
955
+ readable = typeof service?.summary === "function";
956
+ diffable = typeof service?.diff === "function";
957
+ } catch {
958
+ readable = false;
959
+ diffable = false;
960
+ }
961
+ return {
962
+ version: TURN_TAIL_CAPABILITY_VERSION,
963
+ presented: true,
964
+ changed: readable,
965
+ changesDiff: readable && diffable,
966
+ };
967
+ }
968
+
969
+ /**
970
+ * 工具卡能力位(issue #54):始终声明本插件实际投影的工具集合。
971
+ * bootstrap 与 SSE hello 同判据、同形状;旧插件不下发 → App 全部回退通用卡。
972
+ * @returns {{version: number, tools: string[]}}
973
+ */
974
+ export function toolCardsCapabilityOf() {
975
+ return { version: TOOL_CARDS_CAPABILITY_VERSION, tools: [...TOOL_CARD_TOOLS] };
976
+ }
977
+
894
978
  /**
895
979
  * 新端点专用的失败分类:在通用分类之上,**先**识别整条 cause 链里的 seeded 前缀缺陷。
896
980
  * 真实宿主的 `observeSession` 会把这个已知兼容缺陷包进
@@ -990,6 +1074,10 @@ const REPLAY_IGNORED_TYPES = new Set([
990
1074
  "compaction/summary",
991
1075
  "compaction/prune",
992
1076
  "compaction/end",
1077
+ // issue #53(ADR 0027 §4):`workspace/changes` 只携带轮号,对移动时间线没有呈现价值;
1078
+ // 移出移动时间线投影(历史、实时、/event-detail 三处同规则),会话日志仍是宿主事实。
1079
+ // 这不是丢未知事件(对照 ADR 0006):已知且不具呈现价值的事件不进移动时间线。
1080
+ "workspace/changes",
993
1081
  ]);
994
1082
  /** 请求快照的命名约定:类型以 `llm-request` 结尾,前一段分隔符为 `/` 或 `-`
995
1083
  * (内核现实形态:`session/title-llm-request`、`web/deepseek-search-llm-request`;
@@ -1678,6 +1766,342 @@ function sniffImageType(data) {
1678
1766
  return null;
1679
1767
  }
1680
1768
 
1769
+ /** 把路径统一成 POSIX 斜杠文本(`display` 契约始终用 `/` 分隔,§6.21)。 */
1770
+ const posixPathText = (value) => String(value ?? "").replaceAll("\\", "/");
1771
+ /** 是否绝对路径(POSIX 根 / Windows 盘符);`display` 派生只看文本,不依赖宿主平台。 */
1772
+ const isAbsolutePathText = (value) => value.startsWith("/") || /^[A-Za-z]:\//.test(value);
1773
+ /** 不依赖宿主平台的 basename(`basename()` 在 Windows 路径上会保留反斜杠段)。 */
1774
+ const posixBasenameOf = (value) => {
1775
+ const text = posixPathText(value).replace(/\/+$/, "");
1776
+ const index = text.lastIndexOf("/");
1777
+ const base = index >= 0 ? text.slice(index + 1) : text;
1778
+ return base === "" ? "file" : base;
1779
+ };
1780
+
1781
+ /**
1782
+ * `deliverables/presented` 的 `display` 派生(issue #53 / §6.20):
1783
+ * 工作目录内给相对路径,家目录下给 `~/…`,其余**只给 basename**——绝不把主机绝对
1784
+ * 路径交给客户端。`cwd` 未知(休眠会话/旧宿主)时退化为 basename。
1785
+ * @param {unknown} path 记录里的原始路径。
1786
+ * @param {unknown} cwd 会话工作目录(宿主侧事实,只用于派生,不下发)。
1787
+ * @returns {string} 可展示路径(永不包含可拼接的绝对路径)。
1788
+ */
1789
+ export function mobileDisplayPath(path, cwd) {
1790
+ const text = posixPathText(path).trim();
1791
+ if (text === "") return "";
1792
+ if (!isAbsolutePathText(text)) return text.replace(/^\.\//, "");
1793
+ const cwdText = typeof cwd === "string" && cwd !== "" ? posixPathText(cwd).replace(/\/+$/, "") : "";
1794
+ if (cwdText !== "" && (text === cwdText || text.startsWith(`${cwdText}/`))) {
1795
+ const rel = text.slice(cwdText.length).replace(/^\/+/, "");
1796
+ return rel === "" ? posixBasenameOf(text) : rel;
1797
+ }
1798
+ const homeText = posixPathText(homedir()).replace(/\/+$/, "");
1799
+ if (homeText !== "" && text.startsWith(`${homeText}/`)) return `~/${text.slice(homeText.length + 1)}`;
1800
+ return posixBasenameOf(text);
1801
+ }
1802
+
1803
+ /** 工具参数解析(issue #54):只接受 JSON 对象;非法/非对象一律 fail-open 返回 null。 */
1804
+ function parseToolArguments(raw) {
1805
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) return raw;
1806
+ if (typeof raw !== "string" || raw.trim() === "") return null;
1807
+ try {
1808
+ const parsed = JSON.parse(raw);
1809
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
1810
+ } catch {
1811
+ return null;
1812
+ }
1813
+ }
1814
+
1815
+ /** 折叠行/字段单行化(换行压成空格,避免破坏卡片布局)。 */
1816
+ const singleLineText = (value) => String(value ?? "").replace(/\s+/g, " ").trim();
1817
+
1818
+ /** 正整数参数(offset/limit):非正/非整数忽略(fail-open)。 */
1819
+ const positiveIntArg = (value) =>
1820
+ typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
1821
+
1822
+ /** 按行切分,同时忽略末尾换行产生的空哨兵(与桌面 diff 行数口径一致)。 */
1823
+ function diffLinesOf(text) {
1824
+ if (typeof text !== "string" || text === "") return [];
1825
+ const lines = text.split("\n");
1826
+ if (text.endsWith("\n")) lines.pop();
1827
+ return lines;
1828
+ }
1829
+
1830
+ /**
1831
+ * 统一 diff 体积上限保护(issue #54 note 1761):≤8 KiB 原样返回,超出**整段缺省**并
1832
+ * 标记 diffTruncated(不截半段,避免 App 的 diff 解析错位)。
1833
+ * @returns {{diff?: string, diffTruncated?: true}}
1834
+ */
1835
+ function boundedDiff(headerLines, bodyLines) {
1836
+ const text = `${[...headerLines, ...bodyLines].join("\n")}\n`;
1837
+ if (Buffer.byteLength(text, "utf8") > TOOL_CARD_DIFF_MAX_BYTES) return { diffTruncated: true };
1838
+ return { diff: text };
1839
+ }
1840
+
1841
+ /** write 的「全新增」统一 diff(display 已派生,不含主机路径)。 */
1842
+ function addedFileDiff(display, content) {
1843
+ const lines = diffLinesOf(content);
1844
+ if (lines.length === 0) return {};
1845
+ return boundedDiff(
1846
+ ["--- /dev/null", `+++ b/${display}`, `@@ -0,0 +1,${lines.length} @@`],
1847
+ lines.map((line) => `+${line}`),
1848
+ );
1849
+ }
1850
+
1851
+ /**
1852
+ * edit 的近似统一 diff(issue #54 note 1761 允许近似):
1853
+ * 不做上下文/位置搜索,直接把 old_string 全部列为删除行、new_string 全部列为新增行;
1854
+ * `added`/`deleted` 也按行数近似(含省略末尾空行),仅用于折叠行统计。
1855
+ */
1856
+ function editedFileDiff(display, oldText, newText) {
1857
+ const oldLines = diffLinesOf(oldText);
1858
+ const newLines = diffLinesOf(newText);
1859
+ const header = [
1860
+ oldLines.length === 0 ? "--- /dev/null" : `--- a/${display}`,
1861
+ newLines.length === 0 ? "+++ /dev/null" : `+++ b/${display}`,
1862
+ `@@ -1,${oldLines.length} +1,${newLines.length} @@`,
1863
+ ];
1864
+ const body = [
1865
+ ...oldLines.map((line) => `-${line}`),
1866
+ ...newLines.map((line) => `+${line}`),
1867
+ ];
1868
+ const bounded = boundedDiff(header, body);
1869
+ return {
1870
+ ...bounded,
1871
+ added: newLines.length,
1872
+ deleted: oldLines.length,
1873
+ };
1874
+ }
1875
+
1876
+ /**
1877
+ * `tool/call` 的结构化摘要(issue #54 §2):从**原始** `data.arguments` 解析,先解析后
1878
+ * clamp;路径一律经 `mobileDisplayPath` 派生,**绝不下发绝对路径**。未知工具/非法参数
1879
+ * 返回 undefined 或只带 kind/tool 的最小摘要,绝不抛错(fail-open 到通用卡)。
1880
+ * @param {unknown} toolName 工具名。
1881
+ * @param {unknown} rawArguments 原始 arguments(JSON 字符串或对象)。
1882
+ * @param {unknown} cwd 会话工作目录(仅用于 display 派生,不下发)。
1883
+ * @returns {object|undefined}
1884
+ */
1885
+ export function toolCallSummaryOf(toolName, rawArguments, cwd) {
1886
+ const tool = typeof toolName === "string" ? toolName : "";
1887
+ const kind = TOOL_CARD_KIND[tool];
1888
+ if (kind === undefined) return undefined;
1889
+ const summary = { kind, tool };
1890
+ const args = parseToolArguments(rawArguments);
1891
+ if (args === null) return summary;
1892
+ const displayOf = (value) => {
1893
+ if (typeof value !== "string" || value.trim() === "") return undefined;
1894
+ return clampText(mobileDisplayPath(value, cwd), 300);
1895
+ };
1896
+ const toolFilePath = displayOf(args.file_path ?? args.filePath);
1897
+ switch (tool) {
1898
+ case "bash":
1899
+ case "pwsh": {
1900
+ if (typeof args.command === "string" && args.command.trim() !== "") {
1901
+ summary.command = clampText(singleLineText(args.command), 200);
1902
+ }
1903
+ const workdir = displayOf(args.workdir);
1904
+ if (workdir !== undefined) summary.workdir = workdir;
1905
+ if (args.run_in_background === true) summary.background = true;
1906
+ if (typeof args.description === "string" && args.description.trim() !== "") {
1907
+ summary.description = clampText(singleLineText(args.description), 120);
1908
+ }
1909
+ break;
1910
+ }
1911
+ case "read": {
1912
+ if (toolFilePath !== undefined) summary.filePath = toolFilePath;
1913
+ const offset = positiveIntArg(args.offset);
1914
+ if (offset !== undefined) summary.offset = offset;
1915
+ const limit = positiveIntArg(args.limit);
1916
+ if (limit !== undefined) summary.limit = limit;
1917
+ break;
1918
+ }
1919
+ case "write": {
1920
+ if (toolFilePath !== undefined) summary.filePath = toolFilePath;
1921
+ if (typeof args.content === "string") {
1922
+ // 与桌面 `NKB` 同口径:UTF-16 code unit 长度 / 1024 向上取整。
1923
+ summary.sizeKb = Math.ceil(args.content.length / 1024);
1924
+ if (toolFilePath !== undefined) {
1925
+ Object.assign(summary, addedFileDiff(toolFilePath, args.content));
1926
+ }
1927
+ }
1928
+ break;
1929
+ }
1930
+ case "edit": {
1931
+ if (toolFilePath !== undefined) summary.filePath = toolFilePath;
1932
+ const oldText = typeof args.old_string === "string" ? args.old_string : typeof args.oldString === "string" ? args.oldString : "";
1933
+ const newText = typeof args.new_string === "string" ? args.new_string : typeof args.newString === "string" ? args.newString : "";
1934
+ summary.sizeKb = Math.ceil((oldText.length + newText.length) / 1024);
1935
+ if (toolFilePath !== undefined) {
1936
+ Object.assign(summary, editedFileDiff(toolFilePath, oldText, newText));
1937
+ } else {
1938
+ summary.added = diffLinesOf(newText).length;
1939
+ summary.deleted = diffLinesOf(oldText).length;
1940
+ }
1941
+ break;
1942
+ }
1943
+ case "grep":
1944
+ case "glob": {
1945
+ if (typeof args.pattern === "string" && args.pattern.trim() !== "") {
1946
+ summary.pattern = clampText(singleLineText(args.pattern), 200);
1947
+ }
1948
+ const searchPath = displayOf(args.path);
1949
+ if (searchPath !== undefined) summary.path = searchPath;
1950
+ if (tool === "grep" && typeof args.include === "string" && args.include.trim() !== "") {
1951
+ summary.include = clampText(singleLineText(args.include), 200);
1952
+ }
1953
+ break;
1954
+ }
1955
+ case "web_fetch": {
1956
+ if (typeof args.url === "string" && args.url.trim() !== "") summary.url = clampText(args.url.trim(), 500);
1957
+ break;
1958
+ }
1959
+ case "web_search": {
1960
+ const first = Array.isArray(args.queries) ? args.queries.find((value) => typeof value === "string" && value.trim() !== "") : undefined;
1961
+ if (typeof first === "string") summary.query = clampText(singleLineText(first), 200);
1962
+ break;
1963
+ }
1964
+ case "read_image": {
1965
+ if (toolFilePath !== undefined) summary.filePath = toolFilePath;
1966
+ break;
1967
+ }
1968
+ }
1969
+ return summary;
1970
+ }
1971
+
1972
+ /**
1973
+ * `tool/result` 的结构化摘要(issue #54 §3):只从结果**文本标记**与宿主 `meta` 解析,
1974
+ * 解析不到就缺省(不猜)。exit/signal 标记只由 bash/pwsh 输出;grep/glob 的匹配总数优先
1975
+ * 取 `meta.total`(宿主 presentationMeta),缺失时按结果文本的稳定句式解析。
1976
+ * @param {unknown} toolName 工具名(可为空:结果事件常不带名字)。
1977
+ * @param {unknown} rawResultText 未 clamp 的结果文本。
1978
+ * @param {unknown} meta 宿主 tool/result 的 presentationMeta(不透传给 App)。
1979
+ * @returns {object|undefined}
1980
+ */
1981
+ export function toolResultSummaryOf(toolName, rawResultText, meta) {
1982
+ const summary = {};
1983
+ const text = typeof rawResultText === "string" ? rawResultText : "";
1984
+ const tool = typeof toolName === "string" ? toolName : "";
1985
+ if (tool === "" || tool === "bash" || tool === "pwsh") {
1986
+ const exit = /\[exit code: (-?\d+)\]/.exec(text);
1987
+ if (exit) summary.exitCode = Number(exit[1]);
1988
+ const signal = /\[killed by signal: ([^\]\n]+)\]/.exec(text);
1989
+ if (signal) summary.signal = clampText(signal[1].trim(), 40);
1990
+ const stopped = /\[stopped: ([^\]\n]+)\]/.exec(text);
1991
+ if (stopped) summary.stopped = clampText(stopped[1].trim(), 120);
1992
+ }
1993
+ const metaShape = meta && typeof meta === "object" ? meta.shape : undefined;
1994
+ const searchShaped = metaShape === "matches" || metaShape === "paths";
1995
+ const searchTool = tool === "grep" || tool === "glob";
1996
+ if (searchShaped || searchTool || tool === "") {
1997
+ const metaTotal = meta && typeof meta === "object" && Number.isSafeInteger(meta.total) ? meta.total : undefined;
1998
+ if (metaTotal !== undefined && metaTotal >= 0) {
1999
+ summary.resultCount = metaTotal;
2000
+ } else if (searchTool || searchShaped || tool === "") {
2001
+ const count = parseSearchResultCount(text, tool);
2002
+ if (count !== undefined) summary.resultCount = count;
2003
+ }
2004
+ }
2005
+ return Object.keys(summary).length > 0 ? summary : undefined;
2006
+ }
2007
+
2008
+ /** 从 grep/glob 的结果文本解析匹配总数;解析不到返回 undefined(不猜)。 */
2009
+ function parseSearchResultCount(text, tool) {
2010
+ if (text === "") return undefined;
2011
+ const found = /(?:^|\n)Found (\d+)(?: of (\d+))? match(?:es)?(?:\n|$)/.exec(text);
2012
+ if (found) return Number(found[2] ?? found[1]);
2013
+ if (/^No matches found\b/.test(text)) return 0;
2014
+ const showing = /\(Showing \d+ of (\d+) paths/.exec(text);
2015
+ if (showing) return Number(showing[1]);
2016
+ if (/^No files found\b/.test(text)) return 0;
2017
+ // glob 在 cap 内直接输出路径列表(每行一条);仅当工具名已知且没有分页/落盘提示时计数。
2018
+ if (tool === "glob" && !text.includes("(Showing") && !text.includes("Full sorted result")) {
2019
+ const count = text.split("\n").filter((line) => line.trim() !== "").length;
2020
+ return count > 0 ? count : undefined;
2021
+ }
2022
+ return undefined;
2023
+ }
2024
+
2025
+ /**
2026
+ * 单轮轮末信号(`turn/end` 的 `tail`);无任何产出物时返回 null(字段不出现)。
2027
+ * @param {any[]} events 会话原始事件(含被移动时间线过滤的 `workspace/changes`)。
2028
+ * @param {unknown} turn 轮号。
2029
+ * @returns {{changes: boolean, presented: boolean} | null}
2030
+ */
2031
+ export function turnTailOf(events, turn) {
2032
+ if (!Number.isSafeInteger(turn) || turn < 1) return null;
2033
+ let changes = false;
2034
+ let presented = false;
2035
+ for (const event of events ?? []) {
2036
+ const eventTurn = event?.data?.turn;
2037
+ if (Number(eventTurn) !== turn) continue;
2038
+ if (event?.type === "workspace/changes") changes = true;
2039
+ else if (event?.type === "deliverables/presented" && Array.isArray(event?.data?.files) && event.data.files.length > 0) presented = true;
2040
+ }
2041
+ if (!changes && !presented) return null;
2042
+ return { changes, presented };
2043
+ }
2044
+
2045
+ /**
2046
+ * `/history` 响应增量 `turnTails`(§6.20):**单次遍历**已加载事件得出,不调用宿主服务;
2047
+ * 只包含有产出物的轮次。key 为轮号字符串。
2048
+ * @param {any[]} events 会话原始事件。
2049
+ * @returns {Record<string, {changes: boolean, presented: boolean}>}
2050
+ */
2051
+ export function turnTailsOf(events) {
2052
+ const flags = new Map();
2053
+ for (const event of events ?? []) {
2054
+ const turn = event?.data?.turn;
2055
+ if (!Number.isSafeInteger(turn) || turn < 1) continue;
2056
+ if (event?.type === "workspace/changes") {
2057
+ const tail = flags.get(turn) ?? { changes: false, presented: false };
2058
+ tail.changes = true;
2059
+ flags.set(turn, tail);
2060
+ } else if (event?.type === "deliverables/presented" && Array.isArray(event?.data?.files) && event.data.files.length > 0) {
2061
+ const tail = flags.get(turn) ?? { changes: false, presented: false };
2062
+ tail.presented = true;
2063
+ flags.set(turn, tail);
2064
+ }
2065
+ }
2066
+ const out = {};
2067
+ for (const turn of [...flags.keys()].sort((a, b) => a - b)) out[String(turn)] = flags.get(turn);
2068
+ return out;
2069
+ }
2070
+
2071
+ /**
2072
+ * 把宿主 `workspaceChanges.diff()` 的 hunks 渲染成统一 diff 文本(§6.22),供 App 的
2073
+ * `GitFileViewer` 差异模式直接消费。按**行边界**截断到体积上限,避免切断一行导致解析错位。
2074
+ * @param {any} diff 宿主返回的对比结果(text 形态)。
2075
+ * @returns {{text: string, truncated: boolean}}
2076
+ */
2077
+ export function renderUnifiedDiffText(diff) {
2078
+ const display = typeof diff?.display === "string" && diff.display !== "" ? diff.display : posixBasenameOf(diff?.path);
2079
+ const lines = [
2080
+ diff?.before === false ? "--- /dev/null" : `--- a/${display}`,
2081
+ diff?.after === false ? "+++ /dev/null" : `+++ b/${display}`,
2082
+ ];
2083
+ for (const hunk of Array.isArray(diff?.hunks) ? diff.hunks : []) {
2084
+ if (!hunk) continue;
2085
+ const oldStart = Number.isSafeInteger(hunk.oldStart) ? hunk.oldStart : 0;
2086
+ const oldLines = Number.isSafeInteger(hunk.oldLines) ? hunk.oldLines : 0;
2087
+ const newStart = Number.isSafeInteger(hunk.newStart) ? hunk.newStart : 0;
2088
+ const newLines = Number.isSafeInteger(hunk.newLines) ? hunk.newLines : 0;
2089
+ lines.push(`@@ -${oldStart},${oldLines} +${newStart},${newLines} @@`);
2090
+ for (const line of Array.isArray(hunk.lines) ? hunk.lines : []) lines.push(String(line));
2091
+ }
2092
+ let text = `${lines.join("\n")}\n`;
2093
+ if (Buffer.byteLength(text, "utf8") <= TURN_TAIL_DIFF_MAX_BYTES) return { text, truncated: false };
2094
+ const kept = [];
2095
+ let used = 0;
2096
+ for (const line of lines) {
2097
+ const cost = Buffer.byteLength(line, "utf8") + 1;
2098
+ if (used + cost > TURN_TAIL_DIFF_MAX_BYTES) break;
2099
+ kept.push(line);
2100
+ used += cost;
2101
+ }
2102
+ return { text: kept.length ? `${kept.join("\n")}\n` : "", truncated: true };
2103
+ }
2104
+
1681
2105
  /**
1682
2106
  * 事件时间戳(issue #52,docs/03-api.md §6.20):只接受 SessionEvent.time 里
1683
2107
  * **有限非负数字**的 Unix 毫秒值,其余(缺失/字符串/NaN/负数)一律不下发——
@@ -1694,14 +2118,14 @@ function eventTimeOf(event) {
1694
2118
  * v3.3(issue #52):顶层 `time` 为所有时间线事件摘要的增量字段(只增不改),
1695
2119
  * 供 App 计算轮次/过程组用时;旧字段形状不变。
1696
2120
  */
1697
- function summarizeEventCore(event) {
1698
- const summary = summarizeEventCoreBody(event);
2121
+ function summarizeEventCore(event, options = {}) {
2122
+ const summary = summarizeEventCoreBody(event, options);
1699
2123
  const time = eventTimeOf(event);
1700
2124
  return time === undefined ? summary : { ...summary, time };
1701
2125
  }
1702
2126
 
1703
2127
  /** summarizeEventCore 的原有逐类型摘要实现(issue #52 起由上面的包装补顶层 time)。 */
1704
- function summarizeEventCoreBody(event) {
2128
+ function summarizeEventCoreBody(event, options = {}) {
1705
2129
  const { seq, type, data } = event;
1706
2130
  // review:内核实参可能缺 data(防御,避免 TypeError 打崩事件发射器)
1707
2131
  if (data === undefined) return { seq, type };
@@ -1780,7 +2204,21 @@ function summarizeEventCoreBody(event) {
1780
2204
  if (typeof argumentsText !== "string") {
1781
2205
  try { argumentsText = JSON.stringify(argumentsText ?? {}); } catch { argumentsText = String(argumentsText ?? ""); }
1782
2206
  }
1783
- return { seq, type, data: { turn: data.turn, step: data.step, callId: data.callId, name: data.name, arguments: clampText(argumentsText, 2000) } };
2207
+ // issue #54:summary 从**原始** arguments 解析(先解析后 clamp);解析失败只降级,
2208
+ // 绝不让摘要/历史/SSE 抛错。
2209
+ const summary = toolCallSummaryOf(data.name, data.arguments, options.cwd);
2210
+ return {
2211
+ seq,
2212
+ type,
2213
+ data: {
2214
+ turn: data.turn,
2215
+ step: data.step,
2216
+ callId: data.callId,
2217
+ name: data.name,
2218
+ arguments: clampText(argumentsText, 2000),
2219
+ ...(summary === undefined ? {} : { summary }),
2220
+ },
2221
+ };
1784
2222
  }
1785
2223
  case "tool/result": {
1786
2224
  // v3.0.0(版本二):对齐 PC contentParts 语义——content 为 tool-result 块数组,
@@ -1810,6 +2248,9 @@ function summarizeEventCoreBody(event) {
1810
2248
  // 学到的真名,于是已结束的工具卡标题变成裸 `call_00_...`(进行中的那张正常)。
1811
2249
  // 名字未知就不下发该字段,由消费端自行兜底显示「工具」。
1812
2250
  const resultName = directName || errName;
2251
+ // issue #54:结果摘要从**未 clamp 的原始文本**与宿主 meta 解析(exit/signal 标记
2252
+ // 通常在输出末尾,clamp 后可能被截掉;meta 只用来取匹配总数,不透传)。
2253
+ const resultSummary = toolResultSummaryOf(resultName, text, data.meta);
1813
2254
  return {
1814
2255
  seq,
1815
2256
  type,
@@ -1820,6 +2261,7 @@ function summarizeEventCoreBody(event) {
1820
2261
  ...(resultName ? { name: resultName } : {}),
1821
2262
  isError,
1822
2263
  text: clampText(text, 2000),
2264
+ ...(resultSummary === undefined ? {} : { summary: resultSummary }),
1823
2265
  ...(images.length ? { images: images.slice(0, 20) } : {}),
1824
2266
  },
1825
2267
  };
@@ -1844,6 +2286,31 @@ function summarizeEventCoreBody(event) {
1844
2286
  return { seq, type, data: { turn: data.turn } };
1845
2287
  case "turn/end":
1846
2288
  return { seq, type, data: { turn: data.turn, reason: data.reason } };
2289
+ case "deliverables/presented": {
2290
+ // issue #53(§6.20):交付文件声明只下发 name/display/description,**不下发主机
2291
+ // 绝对路径**;display 由本插件按会话工作目录派生(cwd 是宿主事实,随摘要上下文传入)。
2292
+ const files = Array.isArray(data.files) ? data.files : [];
2293
+ const cwd = options.cwd;
2294
+ const mapped = [];
2295
+ for (const file of files.slice(0, TURN_TAIL_MAX_FILES)) {
2296
+ const path = typeof file?.path === "string" ? file.path : "";
2297
+ if (path === "") continue;
2298
+ const entry = { name: posixBasenameOf(path), display: mobileDisplayPath(path, cwd) };
2299
+ if (typeof file.description === "string" && file.description.trim() !== "") entry.description = clampText(file.description, 200);
2300
+ mapped.push(entry);
2301
+ }
2302
+ const turn = Number.isSafeInteger(data.turn) && data.turn >= 1 ? data.turn : undefined;
2303
+ const callId = typeof data.callId === "string" && data.callId !== "" ? data.callId : undefined;
2304
+ return {
2305
+ seq,
2306
+ type,
2307
+ data: {
2308
+ ...(turn === undefined ? {} : { turn }),
2309
+ ...(callId === undefined ? {} : { callId }),
2310
+ files: mapped,
2311
+ },
2312
+ };
2313
+ }
1847
2314
  default:
1848
2315
  return { seq, type };
1849
2316
  }
@@ -1884,8 +2351,8 @@ export function detailEventFor(event) {
1884
2351
  * 移动端事件摘要:保留轻量 data,同时声明可通过 seq 读取无损详情。
1885
2352
  * 老客户端只会忽略新增的 detail 字段,保持向后兼容。
1886
2353
  */
1887
- export function summarizeEvent(event) {
1888
- const summary = summarizeEventCore(event);
2354
+ export function summarizeEvent(event, options = {}) {
2355
+ const summary = summarizeEventCore(event, options);
1889
2356
  if (event?.seq === undefined || event?.seq === null) return summary;
1890
2357
  // 只对详情端点真的能取回的事件声明指针:token delta / 内部记录会被 /event-detail
1891
2358
  // 拒绝(isTimelineRecord),未列入 allow-list 的类型同样会被拒(fail-closed)。
@@ -3319,6 +3786,36 @@ export function apply(ctx, config, runtime = {}) {
3319
3786
  if (!Number.isSafeInteger(n) || n < 0) return null;
3320
3787
  return eventsOf(session).find((event) => Number(event?.seq) === n) ?? null;
3321
3788
  };
3789
+ /** 会话工作目录(宿主事实):live 会话在 header,休眠快照在 snapshot.session。 */
3790
+ const sessionCwdOf = (session) => {
3791
+ const cwd = session?.header?.cwd;
3792
+ return typeof cwd === "string" && cwd !== "" ? cwd : undefined;
3793
+ };
3794
+ /** 该轮**最新**一条 `workspace/changes` 事件(摘要与预览的 seq 坐标来源)。 */
3795
+ const latestWorkspaceChangesEvent = (session, turn) => {
3796
+ const events = eventsOf(session);
3797
+ for (let index = events.length - 1; index >= 0; index -= 1) {
3798
+ const event = events[index];
3799
+ if (event?.type === "workspace/changes" && Number(event?.data?.turn) === turn) return event;
3800
+ }
3801
+ return null;
3802
+ };
3803
+ /** 单个事件是否属于该会话的指定轮/类型(presented 坐标校验)。 */
3804
+ const presentedEventFilesOf = (event, index) => {
3805
+ if (!event || event.type !== "deliverables/presented") return null;
3806
+ const files = event?.data?.files;
3807
+ if (!Array.isArray(files) || index < 0 || index >= files.length) return null;
3808
+ const file = files[index];
3809
+ return typeof file?.path === "string" && file.path !== "" ? file : null;
3810
+ };
3811
+ /** 从记录里的路径解析出**只读目标**:相对路径按记录所属会话的工作目录展开。 */
3812
+ const resolveRecordedPath = (recordedPath, cwd) => {
3813
+ const text = normalizeServerPath(recordedPath);
3814
+ if (text === "") return null;
3815
+ if (isAbsolute(text)) return resolve(text);
3816
+ if (typeof cwd !== "string" || cwd === "") return null;
3817
+ return resolve(normalizeServerPath(cwd), text);
3818
+ };
3322
3819
  /** v3.1.2:从事件数组折叠会话配置(休眠会话读取用——0.1.2 模型选择事件为 model/selection)。 */
3323
3820
  const foldFromEvents = (events) => {
3324
3821
  const out = { model: undefined, provider: undefined, reasoningEffort: undefined, permissionPreset: undefined, agentPreset: undefined };
@@ -4855,7 +5352,7 @@ export function apply(ctx, config, runtime = {}) {
4855
5352
  "connection": "keep-alive",
4856
5353
  });
4857
5354
  res.write(": connected\n\n");
4858
- 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`);
5355
+ 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`);
4859
5356
  connections.add(res);
4860
5357
  // 补发断线期间挂起的问询/审批(与 PC 端 GUI 连接时的 pending 回放一致;超 TTL 的僵尸帧先清掉)
4861
5358
  for (const [key, f] of pendingFrames) {
@@ -4880,7 +5377,14 @@ export function apply(ctx, config, runtime = {}) {
4880
5377
  };
4881
5378
  const onSessionEvent = (session, event) => {
4882
5379
  if (isLiveTimelineRecord(event)) {
4883
- broadcast({ type: "session/event", sessionId: session.id, event: summarizeEvent(event) });
5380
+ // issue #53:交付文件声明的 display 需要会话工作目录才能派生;turn/end 额外带
5381
+ // 轮末信号 `tail`(§6.20),供 App 决定是否渲染改动卡/交付卡。
5382
+ const summary = summarizeEvent(event, { cwd: sessionCwdOf(session) });
5383
+ if (event.type === "turn/end") {
5384
+ const tail = turnTailOf(eventsOf(session), event.data?.turn);
5385
+ if (tail) summary.data = { ...(summary.data ?? {}), tail };
5386
+ }
5387
+ broadcast({ type: "session/event", sessionId: session.id, event: summary });
4884
5388
  }
4885
5389
  // 会话有动静 = 标题可能变化:使该会话的标题缓存失效(活跃会话本就实时取标题,
4886
5390
  // 休眠会话不受影响——它没有实时事件流)
@@ -5603,6 +6107,11 @@ export function apply(ctx, config, runtime = {}) {
5603
6107
  // 宿主是否**真的**挂了 `turnOutline` 投影单元、且观察接口可用,决定声明是
5604
6108
  // "支持"还是"能力缺失"——App 先读声明再决定是否渲染未加载刻度(不按宿主版本推断)。
5605
6109
  turnOutline: turnOutlineCapabilityOf(ctx),
6110
+ // v3.3(issue #53):轮末产出物能力位;`changed/changesDiff` 只按宿主是否真的
6111
+ // 注册 `workspaceChanges` 判定(ADR 0017),SSE hello 同判据同形状。
6112
+ turnTail: turnTailCapabilityOf(ctx),
6113
+ // v3.4(issue #54):工具卡结构化投影能力位(按本插件实际投影的工具集合声明)。
6114
+ toolCards: toolCardsCapabilityOf(),
5606
6115
  // v3.2.3:普通文件下载支持 Range/HEAD/ETag(大文件续传 + 前缀预览)。
5607
6116
  fileRange: FILE_RANGE_CAPABILITIES,
5608
6117
  // v3.2.4(issue #55):手机端待办等待上限(仅供显示剩余时间,结算仍以服务端为准)。
@@ -6670,7 +7179,9 @@ export function apply(ctx, config, runtime = {}) {
6670
7179
  return error(res, 500, "session-read-failed", "会话存在但历史读取失败");
6671
7180
  }
6672
7181
  if (loaded.ok) {
6673
- session = { events: loaded.snapshot.events };
7182
+ // issue #53:保留会话头(工作目录)——交付文件 display 派生与
7183
+ // turn-file 的相对路径解析都需要它;事件本身仍走同一过滤。
7184
+ session = { events: loaded.snapshot.events, header: loaded.snapshot.session ?? loaded.snapshot.header };
6674
7185
  degraded = loaded.degraded === true;
6675
7186
  }
6676
7187
  }
@@ -6707,6 +7218,10 @@ export function apply(ctx, config, runtime = {}) {
6707
7218
  // 上翻到被 surface 替换的 log-only 历史区域时可能返回空页,属预期;
6708
7219
  // 客户端应结合 historyMode="current-surface" 提示"部分历史不可上翻"。
6709
7220
  const surface = eventsOf(session).filter(isTimelineRecord);
7221
+ // issue #53(§6.20):轮末信号 `turnTails` 由**一次遍历原始事件**得出(会话日志
7222
+ // 仍含被过滤的 `workspace/changes`),不额外调用宿主服务;只含有产出物的轮次。
7223
+ const turnTails = turnTailsOf(eventsOf(session));
7224
+ const cwd = sessionCwdOf(session);
6710
7225
  let events;
6711
7226
  let hasMore = false;
6712
7227
  if (afterParam !== null) {
@@ -6734,7 +7249,8 @@ export function apply(ctx, config, runtime = {}) {
6734
7249
  ...(degraded ? { degraded: true, historyMode: "current-surface" } : {}),
6735
7250
  after: events.length ? events[events.length - 1].seq : 0,
6736
7251
  hasMore,
6737
- events: events.map(summarizeEvent),
7252
+ turnTails,
7253
+ events: events.map((event) => summarizeEvent(event, { cwd })),
6738
7254
  });
6739
7255
  return;
6740
7256
  }
@@ -7980,77 +8496,264 @@ export function apply(ctx, config, runtime = {}) {
7980
8496
  .some((part) => part === "*" || part === etag);
7981
8497
  };
7982
8498
 
7983
- if (rest === "/files" && (method === "GET" || method === "HEAD")) {
7984
- const path = url.searchParams.get("path");
7985
- if (!path || path === "") return error(res, 400, "bad-request", "missing path");
7986
- const target = resolve(normalizeServerPath(path));
7987
- try {
7988
- const st = statSync(target);
7989
- if (!st.isFile()) return error(res, 400, "not-a-file", "path is not a file");
7990
- const name = basename(target);
7991
- // 保留时间精度并纳入 ctime,避免同大小改写且恢复 mtime 后沿用旧断点。
7992
- const etag = `"${st.size.toString(16)}-${st.mtimeMs.toString(16)}-${st.ctimeMs.toString(16)}"`;
7993
- const lastModified = new Date(st.mtimeMs).toUTCString();
7994
- guardRes(res);
7995
- if (ifNoneMatch(req, etag)) {
7996
- res.writeHead(304, { etag, "cache-control": "no-store", connection: "close" });
7997
- res.end();
7998
- return;
7999
- }
8000
- // 断点属于旧文件时从头返回,不能把旧前缀和新后缀拼在一起。
8001
- // 只认可当前强 ETag;旧标记/弱 ETag/日期统一退回完整响应。
8002
- const ifRange = requestHeaderText(req, "if-range").trim();
8003
- const range = parseByteRange(ifRange && ifRange !== etag ? "" : requestHeaderText(req, "range"), st.size);
8004
- if (range && range.invalid) {
8005
- res.writeHead(416, {
8006
- "accept-ranges": "bytes",
8007
- "content-range": `bytes */${st.size}`,
8008
- "content-length": "0",
8009
- etag,
8010
- "cache-control": "no-store",
8011
- connection: "close",
8012
- });
8013
- res.end();
8014
- return;
8015
- }
8016
- const start = range ? range.start : 0;
8017
- const end = range ? range.end : st.size - 1;
8018
- const length = st.size === 0 ? 0 : end - start + 1;
8019
- const headers = {
8020
- "content-type": fileMimeOf(name),
8021
- "content-length": String(length),
8022
- "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
8023
- "cache-control": "no-store",
8499
+ /**
8500
+ * 文件字节响应(v3.2.3 语义):Range/HEAD/ETag/If-None-Match/304/416 +
8501
+ * `connection: close`。`/files` 与 `/turn-file` 共用同一实现,避免头部语义漂移。
8502
+ * 文件不可读时抛错,由调用方映射成各自的稳定错误码。
8503
+ * @returns {true} 已写出响应(调用方仍应 return)。
8504
+ */
8505
+ const serveFileBytes = (req, res, target, { method }) => {
8506
+ const st = statSync(target);
8507
+ if (!st.isFile()) throw Object.assign(new Error("not-a-file"), { code: "not-a-file" });
8508
+ const name = basename(target);
8509
+ // 保留时间精度并纳入 ctime,避免同大小改写且恢复 mtime 后沿用旧断点。
8510
+ const etag = `"${st.size.toString(16)}-${st.mtimeMs.toString(16)}-${st.ctimeMs.toString(16)}"`;
8511
+ const lastModified = new Date(st.mtimeMs).toUTCString();
8512
+ guardRes(res);
8513
+ if (ifNoneMatch(req, etag)) {
8514
+ res.writeHead(304, { etag, "cache-control": "no-store", connection: "close" });
8515
+ res.end();
8516
+ return true;
8517
+ }
8518
+ // 断点属于旧文件时从头返回,不能把旧前缀和新后缀拼在一起。
8519
+ // 只认可当前强 ETag;旧标记/弱 ETag/日期统一退回完整响应。
8520
+ const ifRange = requestHeaderText(req, "if-range").trim();
8521
+ const range = parseByteRange(ifRange && ifRange !== etag ? "" : requestHeaderText(req, "range"), st.size);
8522
+ if (range && range.invalid) {
8523
+ res.writeHead(416, {
8024
8524
  "accept-ranges": "bytes",
8525
+ "content-range": `bytes */${st.size}`,
8526
+ "content-length": "0",
8025
8527
  etag,
8026
- "last-modified": lastModified,
8027
- // v3.1.5+39:取完即断(半关连接复用会让手机侧等满超时)
8528
+ "cache-control": "no-store",
8028
8529
  connection: "close",
8029
- ...(range ? { "content-range": `bytes ${start}-${end}/${st.size}` } : {}),
8030
- };
8031
- res.writeHead(range ? 206 : 200, headers);
8032
- if (method === "HEAD" || st.size === 0) {
8033
- res.end();
8034
- return;
8530
+ });
8531
+ res.end();
8532
+ return true;
8533
+ }
8534
+ const start = range ? range.start : 0;
8535
+ const end = range ? range.end : st.size - 1;
8536
+ const length = st.size === 0 ? 0 : end - start + 1;
8537
+ const headers = {
8538
+ "content-type": fileMimeOf(name),
8539
+ "content-length": String(length),
8540
+ "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
8541
+ "cache-control": "no-store",
8542
+ "accept-ranges": "bytes",
8543
+ etag,
8544
+ "last-modified": lastModified,
8545
+ // v3.1.5+39:取完即断(半关连接复用会让手机侧等满超时)
8546
+ connection: "close",
8547
+ ...(range ? { "content-range": `bytes ${start}-${end}/${st.size}` } : {}),
8548
+ };
8549
+ res.writeHead(range ? 206 : 200, headers);
8550
+ if (method === "HEAD" || st.size === 0) {
8551
+ res.end();
8552
+ return true;
8553
+ }
8554
+ const source = createReadStream(target, { start, end });
8555
+ // 客户端取消/断开时销毁文件流,避免 fd 泄漏。
8556
+ res.on("close", () => {
8557
+ try {
8558
+ source.destroy();
8559
+ } catch {
8560
+ // 已销毁
8561
+ }
8562
+ });
8563
+ source.on("error", () => {
8564
+ try {
8565
+ res.destroy();
8566
+ } catch {
8567
+ // 已销毁
8035
8568
  }
8036
- const source = createReadStream(target, { start, end });
8037
- // 客户端取消/断开时销毁文件流,避免 fd 泄漏。
8038
- res.on("close", () => {
8569
+ });
8570
+ source.pipe(res);
8571
+ return true;
8572
+ };
8573
+ /** 非负整数查询参数;缺失/非法都返回 null(调用方按 400 处理)。 */
8574
+ const nonNegativeIntParam = (raw) => {
8575
+ if (raw === null) return null;
8576
+ if (raw.trim() === "") return null;
8577
+ const value = Number(raw);
8578
+ if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) return null;
8579
+ return value;
8580
+ };
8581
+
8582
+ // ── v3.3(issue #53):轮末产出物(改动摘要 / 单文件对比 / 按坐标取文件) ──
8583
+ if (rest === "/changes/summary") {
8584
+ if (requireGet(method, res)) return;
8585
+ const sessionId = url.searchParams.get("sessionId");
8586
+ const turn = nonNegativeIntParam(url.searchParams.get("turn"));
8587
+ if (!sessionId) return error(res, 400, "bad-request", "missing sessionId or turn");
8588
+ if (turn === null) return error(res, 400, "bad-request", "turn must be a non-negative integer");
8589
+ const sessions = ctx.get("sessions");
8590
+ if (!sessions) return error(res, 503, "sessions-unavailable");
8591
+ // 服务不可用/会话休眠/摘要失效统一按 state 返回(不 5xx),App 统一降级不占位。
8592
+ const unavailable = { ok: true, state: "unavailable", turn, files: [], total: 0, added: 0, deleted: 0, truncated: false };
8593
+ const workspaceChanges = ctx.get("workspaceChanges");
8594
+ if (!workspaceChanges || typeof workspaceChanges.summary !== "function") return sendJson(res, 200, unavailable);
8595
+ const session = sessions.get(sessionId);
8596
+ if (!session) return sendJson(res, 200, unavailable);
8597
+ const source = latestWorkspaceChangesEvent(session, turn);
8598
+ if (!source) return sendJson(res, 200, { ...unavailable, state: "absent" });
8599
+ let summary;
8600
+ try {
8601
+ summary = workspaceChanges.summary(sessionId, source.seq);
8602
+ } catch (err) {
8603
+ ctx.logger.warn?.(`mobile-remote: changes.summary 读取失败(${sessionId}/${turn}):${failureDetail(err)}`);
8604
+ return sendJson(res, 200, unavailable);
8605
+ }
8606
+ if (!summary || !Array.isArray(summary.files)) return sendJson(res, 200, unavailable);
8607
+ const allFiles = summary.files;
8608
+ const files = allFiles.slice(0, TURN_TAIL_MAX_FILES).map((file, index) => {
8609
+ const recordedPath = typeof file?.path === "string" ? file.path : "";
8610
+ const display = typeof file?.display === "string" && file.display !== "" ? file.display : mobileDisplayPath(recordedPath, summary.cwd);
8611
+ return {
8612
+ seq: source.seq,
8613
+ index,
8614
+ display,
8615
+ name: posixBasenameOf(recordedPath || display),
8616
+ added: Number.isFinite(file?.added) ? Math.max(0, Math.trunc(file.added)) : 0,
8617
+ deleted: Number.isFinite(file?.deleted) ? Math.max(0, Math.trunc(file.deleted)) : 0,
8618
+ binary: file?.binary === true,
8619
+ oversized: file?.oversized === true,
8620
+ };
8621
+ });
8622
+ return sendJson(res, 200, {
8623
+ ok: true,
8624
+ state: "available",
8625
+ turn,
8626
+ files,
8627
+ total: Number.isFinite(summary.total) ? Math.max(0, Math.trunc(summary.total)) : allFiles.length,
8628
+ added: Number.isFinite(summary.added) ? Math.max(0, Math.trunc(summary.added)) : 0,
8629
+ deleted: Number.isFinite(summary.deleted) ? Math.max(0, Math.trunc(summary.deleted)) : 0,
8630
+ // 宿主 maxFiles 或移动端 200 上限任一截断都显式标记;total 仍是全量计数。
8631
+ truncated: allFiles.length > TURN_TAIL_MAX_FILES || (Number.isFinite(summary.total) && summary.total > allFiles.length),
8632
+ });
8633
+ }
8634
+ if (rest === "/changes/diff") {
8635
+ if (requireGet(method, res)) return;
8636
+ const sessionId = url.searchParams.get("sessionId");
8637
+ const turn = nonNegativeIntParam(url.searchParams.get("turn"));
8638
+ const index = nonNegativeIntParam(url.searchParams.get("index"));
8639
+ if (!sessionId) return error(res, 400, "bad-request", "missing sessionId, turn or index");
8640
+ if (turn === null || index === null) return error(res, 400, "bad-request", "turn/index must be non-negative integers");
8641
+ const sessions = ctx.get("sessions");
8642
+ if (!sessions) return error(res, 503, "changes-unavailable");
8643
+ const workspaceChanges = ctx.get("workspaceChanges");
8644
+ if (!workspaceChanges || typeof workspaceChanges.diff !== "function") return error(res, 503, "changes-unavailable");
8645
+ // 摘要只随 live 会话存在:休眠/重启后没有可对比内容(§6.22)。
8646
+ const session = sessions.get(sessionId);
8647
+ const source = session ? latestWorkspaceChangesEvent(session, turn) : null;
8648
+ if (!source) return error(res, 404, "diff-not-found");
8649
+ let diff;
8650
+ try {
8651
+ diff = await workspaceChanges.diff(sessionId, source.seq, index, requestAbort(res));
8652
+ } catch (err) {
8653
+ if (res.destroyed || res.writableEnded) return;
8654
+ ctx.logger.warn?.(`mobile-remote: changes.diff 读取失败(${sessionId}/${turn}/${index}):${failureDetail(err)}`);
8655
+ return error(res, 503, "changes-unavailable");
8656
+ }
8657
+ if (!diff) return error(res, 404, "diff-not-found");
8658
+ if (diff.kind === "binary" || diff.kind === "oversized") {
8659
+ return sendJson(res, 200, {
8660
+ ok: true,
8661
+ state: "available",
8662
+ diff: { kind: diff.kind, display: typeof diff.display === "string" ? diff.display : "" },
8663
+ });
8664
+ }
8665
+ const rendered = renderUnifiedDiffText(diff);
8666
+ return sendJson(res, 200, {
8667
+ ok: true,
8668
+ state: "available",
8669
+ diff: {
8670
+ kind: "text",
8671
+ display: typeof diff.display === "string" ? diff.display : "",
8672
+ before: diff.before !== false,
8673
+ after: diff.after !== false,
8674
+ coarse: diff.coarse === true,
8675
+ diff: rendered.text,
8676
+ truncated: rendered.truncated,
8677
+ },
8678
+ });
8679
+ }
8680
+ if (rest === "/turn-file" && (method === "GET" || method === "HEAD")) {
8681
+ const sessionId = url.searchParams.get("sessionId");
8682
+ const kind = url.searchParams.get("kind");
8683
+ const seq = nonNegativeIntParam(url.searchParams.get("seq"));
8684
+ const index = nonNegativeIntParam(url.searchParams.get("index"));
8685
+ if (!sessionId || (kind !== "presented" && kind !== "changed")) return error(res, 400, "bad-request", "missing sessionId or invalid kind");
8686
+ if (seq === null || index === null) return error(res, 400, "bad-request", "seq/index must be non-negative integers");
8687
+ const sessions = ctx.get("sessions");
8688
+ if (!sessions) return error(res, 503, "sessions-unavailable");
8689
+ let target = null;
8690
+ if (kind === "presented") {
8691
+ // 路径只从会话记录里解析:客户端只给坐标,不能指定路径(GitLab #16 收紧方向)。
8692
+ const query = ctx.get("sessionQuery");
8693
+ let event = null;
8694
+ let cwd;
8695
+ if (typeof query?.readEvent === "function") {
8039
8696
  try {
8040
- source.destroy();
8697
+ const read = await query.readEvent({ sessionId, seq });
8698
+ event = read?.target ?? read?.event ?? read?.value ?? null;
8699
+ cwd = read?.session?.cwd ?? read?.header?.cwd;
8041
8700
  } catch {
8042
- // 已销毁
8701
+ event = null;
8043
8702
  }
8044
- });
8045
- source.on("error", () => {
8703
+ }
8704
+ const liveSession = sessions.get(sessionId);
8705
+ if (!event && liveSession) {
8706
+ event = eventBySeq(liveSession, seq);
8707
+ cwd ??= sessionCwdOf(liveSession);
8708
+ }
8709
+ if (!event && typeof query?.readSession === "function") {
8046
8710
  try {
8047
- res.destroy();
8711
+ const snapshot = await query.readSession(sessionId);
8712
+ event = (snapshot?.events ?? []).find((candidate) => Number(candidate?.seq) === seq) ?? null;
8713
+ cwd ??= snapshot?.session?.cwd ?? snapshot?.header?.cwd;
8048
8714
  } catch {
8049
- // 已销毁
8715
+ event = null;
8050
8716
  }
8051
- });
8052
- source.pipe(res);
8717
+ }
8718
+ const file = presentedEventFilesOf(event, index);
8719
+ if (!file) return error(res, 404, "record-not-found");
8720
+ cwd ??= sessionCwdOf(liveSession);
8721
+ target = resolveRecordedPath(file.path, cwd);
8722
+ if (!target) return error(res, 404, "record-not-found");
8723
+ } else {
8724
+ const workspaceChanges = ctx.get("workspaceChanges");
8725
+ if (!workspaceChanges || typeof workspaceChanges.summary !== "function") return error(res, 503, "changes-unavailable");
8726
+ const session = sessions.get(sessionId);
8727
+ // 改动摘要只随 live 会话存在:休眠/重启后没有可解析的路径(§6.23)。
8728
+ if (!session) return error(res, 503, "changes-unavailable");
8729
+ let summary;
8730
+ try {
8731
+ summary = workspaceChanges.summary(sessionId, seq);
8732
+ } catch {
8733
+ summary = undefined;
8734
+ }
8735
+ if (!summary || !Array.isArray(summary.files)) return error(res, 503, "changes-unavailable");
8736
+ const file = summary.files[index];
8737
+ if (!file || typeof file?.path !== "string" || file.path === "") return error(res, 404, "record-not-found");
8738
+ target = resolveRecordedPath(file.path, summary.cwd);
8739
+ if (!target) return error(res, 404, "record-not-found");
8740
+ }
8741
+ try {
8742
+ serveFileBytes(req, res, target, { method });
8743
+ } catch {
8744
+ // 记录里的文件已被删除/不可读:不泄露主机路径。
8745
+ return error(res, 404, "file-not-found");
8746
+ }
8747
+ return;
8748
+ }
8749
+ if (rest === "/files" && (method === "GET" || method === "HEAD")) {
8750
+ const path = url.searchParams.get("path");
8751
+ if (!path || path === "") return error(res, 400, "bad-request", "missing path");
8752
+ const target = resolve(normalizeServerPath(path));
8753
+ try {
8754
+ serveFileBytes(req, res, target, { method });
8053
8755
  } catch (err) {
8756
+ if (err?.code === "not-a-file") return error(res, 400, "not-a-file", "path is not a file");
8054
8757
  return error(res, 404, "file-not-found", failureDetail(err)); // v3.1.5 S7:不再回主机绝对路径(含进程 cwd)
8055
8758
  }
8056
8759
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marktrue/dsh-mobile-remote",
3
- "version": "3.2.4-alpha.6",
3
+ "version": "3.2.4-alpha.7",
4
4
  "description": "DSH Mobile:把 DeepSeek Harness 变成随身控制台——手机远程发消息派活、看进度、收通知、审批决策、管理会话;配套 Flutter App(当前 Android 端,iOS 未开发)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -52,7 +52,7 @@
52
52
  "qrcode"
53
53
  ],
54
54
  "optionalDependencies": {
55
- "@marktrue/dsh-mobile-remote-app": "npm:@marktrue/dsh-mobile-remote@3.2.4-alpha.6-app"
55
+ "@marktrue/dsh-mobile-remote-app": "npm:@marktrue/dsh-mobile-remote@3.2.4-alpha.7-app"
56
56
  },
57
57
  "peerDependencies": {
58
58
  "@deepseek-ai/dsh-credentials": ">=0.1.0-rc.6 <=0.2.2 || >=0.2.0-0 <0.2.0 || >=0.2.1-0 <0.2.1 || >=0.2.2-0 <0.2.2",