@marktrue/dsh-mobile-remote 3.2.4-alpha.2 → 3.2.4-alpha.20

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, lstatSync, readlinkSync, 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,
@@ -69,11 +80,11 @@ import {
69
80
  acquireLock,
70
81
  convergeStaleTransaction,
71
82
  dependencyKeysFor,
72
- defaultIsPidAlive,
83
+ finishOwnedTerminal,
84
+ lockHolderAlive,
73
85
  findProfileDir,
74
86
  newOperationId,
75
87
  profileSpecifierOf,
76
- readLock,
77
88
  readTransaction,
78
89
  releaseLock,
79
90
  transactionFile,
@@ -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`;
@@ -1073,6 +1276,21 @@ export const isVisibleConversationMessage = (event) => {
1073
1276
  return kind === undefined || kind === null || kind === "user";
1074
1277
  };
1075
1278
 
1279
+ /** issue #109:事件列表里是否至少有一条**可见对话消息**(判空唯一口径,不看 time)。 */
1280
+ export const hasVisibleConversationMessage = (events) =>
1281
+ Array.isArray(events) && events.some((event) => isVisibleConversationMessage(event));
1282
+
1283
+ /**
1284
+ * issue #109:会话是否为“空对话”(零可见消息且无工具调用/结果)。
1285
+ * tool/call、tool/result 是有价值的会话活动,不能被当成空会话删除;
1286
+ * 空 assistant、系统注入、纯配置/生命周期事件不算活动。
1287
+ */
1288
+ export const isEmptyConversationSessionEvents = (events) => {
1289
+ if (!Array.isArray(events) || events.length === 0) return true;
1290
+ if (hasVisibleConversationMessage(events)) return false;
1291
+ return !events.some((event) => event?.type === "tool/call" || event?.type === "tool/result");
1292
+ };
1293
+
1076
1294
  /**
1077
1295
  * 会话列表排序键(ADR 0013):`lastMessageAt` → `lastActivity` → `createdAt`。
1078
1296
  * 后两级只为旧内核/旧插件降级保留,新版正常路径恒有 `lastMessageAt`。
@@ -1100,6 +1318,20 @@ export const latestMessageTimeOf = (events) => {
1100
1318
  return latest;
1101
1319
  };
1102
1320
 
1321
+ /**
1322
+ * issue #109:默认列表要排除「零可见消息」会话,但 `lastMessageAt` 对休眠会话是
1323
+ * 异步回填的。过滤前对未知会话做一次**有界**消息时间解析(与后台回填共用读取/缓存),
1324
+ * 超预算的未知项保留(宁可多显示,不能误删有消息的会话)。
1325
+ */
1326
+ const EMPTY_FILTER_BACKFILL_BUDGET_MS = 2_500;
1327
+ // issue #109 实机(alpha.18)空会话日志实测为 4–7 个配置事件(session/permission/
1328
+ // sandbox/approval/model/end-seed);正常对话会话至少还会多出 turn/step/消息事件。
1329
+ // 阈值留一档余量到 8,并辅以 sizeBytes 仅作 eventCount 缺失时的保守回退。
1330
+ const EMPTY_SESSION_MAX_EVENTS = 8;
1331
+ const EMPTY_SESSION_MAX_SAFE_BYTES = 1_024;
1332
+ const EMPTY_SESSION_GREY_MAX_BYTES = 2_048;
1333
+ const PERSISTENCE_SNAPSHOT_BUDGET_MS = 1_500;
1334
+
1103
1335
  /** 完整语料观测的新鲜度上限:超过它说明最近没人拉过列表,语料可能落后于新建会话。 */
1104
1336
  export const CORPUS_FRESH_MS = 30 * 60 * 1000;
1105
1337
 
@@ -1164,8 +1396,208 @@ const FILE_MIME = {
1164
1396
  ".js": "text/javascript; charset=utf-8", ".ts": "text/plain; charset=utf-8", ".py": "text/plain; charset=utf-8",
1165
1397
  ".html": "text/html; charset=utf-8", ".mp4": "video/mp4", ".apk": "application/vnd.android.package-archive",
1166
1398
  };
1399
+
1400
+ /** issue #94:图片字节端点的白名单/嗅探(不依赖扩展名信任)。 */
1401
+ const IMAGE_EXTENSIONS = new Map([
1402
+ [".png", "image/png"],
1403
+ [".jpg", "image/jpeg"],
1404
+ [".jpeg", "image/jpeg"],
1405
+ [".gif", "image/gif"],
1406
+ [".webp", "image/webp"],
1407
+ ]);
1408
+ const IMAGE_MAX_BYTES = 8 * 1024 * 1024;
1409
+ const IMAGE_MAX_DIMENSION = 8192;
1410
+ const IMAGE_MAX_PIXELS = 40_000_000;
1411
+
1412
+ /** 按 magic bytes 嗅探图片类型;未知返回 null。 */
1413
+ function sniffImageBufferType(buf) {
1414
+ if (!Buffer.isBuffer(buf) || buf.length < 12) return null;
1415
+ if (buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return "image/png";
1416
+ if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return "image/jpeg";
1417
+ const ascii = buf.subarray(0, 6).toString("ascii");
1418
+ if (ascii === "GIF87a" || ascii === "GIF89a") return "image/gif";
1419
+ if (buf.subarray(0, 4).toString("ascii") === "RIFF" && buf.subarray(8, 12).toString("ascii") === "WEBP") return "image/webp";
1420
+ return null;
1421
+ }
1422
+
1423
+ /** 从图片头解析像素尺寸(支持 PNG/GIF/WebP/JPEG);解析不到返回 null。 */
1424
+ function imageDimensions(buf) {
1425
+ try {
1426
+ if (sniffImageBufferType(buf) === "image/png") {
1427
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
1428
+ }
1429
+ if (sniffImageBufferType(buf) === "image/gif") {
1430
+ return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
1431
+ }
1432
+ if (sniffImageBufferType(buf) === "image/webp") {
1433
+ const chunk = buf.subarray(12, 16).toString("ascii");
1434
+ if (chunk === "VP8X") {
1435
+ return { width: 1 + buf.readUIntLE(24, 3), height: 1 + buf.readUIntLE(27, 3) };
1436
+ }
1437
+ if (chunk === "VP8 " && buf.length >= 30) {
1438
+ return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff };
1439
+ }
1440
+ if (chunk === "VP8L" && buf.length >= 25) {
1441
+ const b = buf.readUInt32LE(21);
1442
+ return { width: (b & 0x3fff) + 1, height: ((b >> 14) & 0x3fff) + 1 };
1443
+ }
1444
+ return null;
1445
+ }
1446
+ if (sniffImageBufferType(buf) === "image/jpeg") {
1447
+ let i = 2;
1448
+ while (i + 9 < buf.length) {
1449
+ if (buf[i] !== 0xff) return null;
1450
+ const marker = buf[i + 1];
1451
+ const length = buf.readUInt16BE(i + 2);
1452
+ if (length < 2) return null;
1453
+ // SOF0-SOF15(排除 DHT/JPG/DAC)带尺寸。
1454
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
1455
+ return { width: buf.readUInt16BE(i + 7), height: buf.readUInt16BE(i + 5) };
1456
+ }
1457
+ i += 2 + length;
1458
+ }
1459
+ }
1460
+ } catch {
1461
+ return null;
1462
+ }
1463
+ return null;
1464
+ }
1465
+ /**
1466
+ * issue #95(#94 TOCTOU):打开并验证工作区图片 fd,避免 realpath→stat→read(path)
1467
+ * 的二次路径读取竞态。必须在 open 后经 `/proc/self/fd/<fd>` 校验实际路径仍落在
1468
+ * cwd + 已登记工作区内;无 O_NOFOLLOW / 无 procfs / 非 Linux 一律 501 fail-closed。
1469
+ *
1470
+ * 供 HTTP 端点与确定性竞态测试共用;fs 可注入(测试换链/无 proc/非 Linux)。
1471
+ */
1472
+ export function openVerifiedWorkspaceImage({
1473
+ candidateLex,
1474
+ cwdReal,
1475
+ workspaceRoots,
1476
+ expectedType,
1477
+ consent = null,
1478
+ platform = process.platform,
1479
+ fs = { existsSync, openSync, fstatSync, readlinkSync, closeSync, readSync, constants },
1480
+ maxBytes = IMAGE_MAX_BYTES,
1481
+ }) {
1482
+ const inside = (parent, child) => {
1483
+ const rel = relative(parent, child);
1484
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
1485
+ };
1486
+ const noProc = !fs.existsSync?.("/proc/self/fd");
1487
+ const noFollow = fs.constants?.O_NOFOLLOW;
1488
+ if (platform !== "linux" || noFollow === undefined || noProc) {
1489
+ return { ok: false, status: 501, code: "image-verification-unavailable" };
1490
+ }
1491
+ let fd = null;
1492
+ try {
1493
+ try {
1494
+ fd = fs.openSync(
1495
+ candidateLex,
1496
+ fs.constants.O_RDONLY | noFollow | (fs.constants.O_NONBLOCK ?? 0),
1497
+ );
1498
+ } catch (err) {
1499
+ if (err?.code === "ELOOP") return { ok: false, status: 403, code: "path-outside-workspace" };
1500
+ if (err?.code === "EACCES" || err?.code === "EPERM") return { ok: false, status: 403, code: "path-outside-workspace" };
1501
+ return { ok: false, status: 404, code: "image-not-found" };
1502
+ }
1503
+ let st;
1504
+ try { st = fs.fstatSync(fd); } catch { return { ok: false, status: 404, code: "image-not-found" }; }
1505
+ if (!st.isFile()) return { ok: false, status: 404, code: "image-not-found" };
1506
+ if (st.size <= 0) return { ok: false, status: 404, code: "image-not-found" };
1507
+ if (st.size > maxBytes) return { ok: false, status: 413, code: "image-too-large" };
1508
+ let actual;
1509
+ try { actual = fs.readlinkSync(`/proc/self/fd/${fd}`); }
1510
+ catch { return { ok: false, status: 501, code: "image-verification-unavailable" }; }
1511
+ actual = String(actual ?? "").replace(/ \(deleted\)$/, "");
1512
+ if (!isAbsolute(actual)) return { ok: false, status: 501, code: "image-verification-unavailable" };
1513
+ // 实际文件名也必须仍是期望图片扩展名(防止中间目录换链后指向别的文件)。
1514
+ if (IMAGE_EXTENSIONS.get(extname(actual).toLowerCase()) !== expectedType) {
1515
+ return { ok: false, status: 403, code: "path-outside-workspace" };
1516
+ }
1517
+ if (consent) {
1518
+ // issue #98:工作区外读取必须由 fd 实际路径匹配授权(once=精确文件;
1519
+ // session-directory=图片所在目录,不递归)。授权不绕过 fd 校验。
1520
+ if (consent.scope === "once") {
1521
+ if (actual !== consent.realPath) return { ok: false, status: 403, code: "consent-invalid" };
1522
+ } else if (consent.scope === "session-directory") {
1523
+ if (dirname(actual) !== consent.realDir) return { ok: false, status: 403, code: "consent-invalid" };
1524
+ } else {
1525
+ return { ok: false, status: 403, code: "consent-invalid" };
1526
+ }
1527
+ } else {
1528
+ // open 后(含中间目录换链)实际文件必须仍在 cwd real 与某个登记工作区内。
1529
+ if (!inside(cwdReal, actual)) return { ok: false, status: 403, code: "path-outside-workspace" };
1530
+ let inWorkspace = false;
1531
+ for (const root of workspaceRoots) {
1532
+ if (inside(root, actual)) { inWorkspace = true; break; }
1533
+ }
1534
+ if (!inWorkspace) return { ok: false, status: 403, code: "workspace-not-authorized" };
1535
+ }
1536
+ const buffer = Buffer.alloc(st.size);
1537
+ let offset = 0;
1538
+ while (offset < st.size) {
1539
+ let read = 0;
1540
+ try { read = fs.readSync(fd, buffer, offset, st.size - offset, offset); }
1541
+ catch { return { ok: false, status: 404, code: "image-not-found" }; }
1542
+ if (!Number.isInteger(read) || read <= 0) break;
1543
+ offset += read;
1544
+ }
1545
+ if (offset === 0) return { ok: false, status: 404, code: "image-not-found" };
1546
+ return { ok: true, bytes: buffer.subarray(0, offset), actualPath: actual };
1547
+ } finally {
1548
+ if (fd !== null) {
1549
+ try { fs.closeSync(fd); } catch {}
1550
+ }
1551
+ }
1552
+ }
1553
+
1554
+ /** issue #98:工作区外图片的会话授权(仅内存、12h TTL、不可伪造、绑定 session)。 */
1555
+ export function createWorkspaceImageConsentStore({ ttlMs = 12 * 60 * 60 * 1000, maxEntries = 512 } = {}) {
1556
+ const entries = new Map();
1557
+ const cleanup = (now = Date.now()) => {
1558
+ for (const [id, entry] of entries) {
1559
+ if (entry.expiresAtMs <= now) entries.delete(id);
1560
+ }
1561
+ };
1562
+ return {
1563
+ issue({ sessionId, scope, realPath, realDir, ttl = ttlMs }) {
1564
+ if (typeof sessionId !== "string" || sessionId === "") throw new Error("session-required");
1565
+ if (scope !== "once" && scope !== "session-directory") throw new Error("invalid-scope");
1566
+ cleanup();
1567
+ while (entries.size >= maxEntries) entries.delete(entries.keys().next().value);
1568
+ const consentId = randomBytes(24).toString("base64url");
1569
+ const expiresAtMs = Date.now() + ttl;
1570
+ entries.set(consentId, { sessionId, scope, realPath, realDir, expiresAtMs });
1571
+ return { consentId, scope, expiresAt: new Date(expiresAtMs).toISOString() };
1572
+ },
1573
+ lookup(consentId, sessionId) {
1574
+ if (typeof consentId !== "string" || consentId === "") return null;
1575
+ cleanup();
1576
+ const entry = entries.get(consentId);
1577
+ if (!entry || entry.sessionId !== sessionId) return null;
1578
+ if (entry.expiresAtMs <= Date.now()) {
1579
+ entries.delete(consentId);
1580
+ return null;
1581
+ }
1582
+ return entry;
1583
+ },
1584
+ clear() { entries.clear(); },
1585
+ size: () => entries.size,
1586
+ };
1587
+ }
1588
+
1167
1589
  const fileMimeOf = (name) => FILE_MIME[extname(name).toLowerCase()] ?? "application/octet-stream";
1168
1590
 
1591
+ /**
1592
+ * `GET /m/api/directories` 条目可见性(issue #45)。
1593
+ *
1594
+ * 默认隐藏所有点开头条目;`includeHidden=1` 时保留点开头文件/目录。
1595
+ * 名称恰为 `.git` 的条目(文件或目录)**永远排除**:既避免把对象库/可能含
1596
+ * 凭据的 `.git/config` 暴露给文件浏览,也不提供进入其内部的入口。
1597
+ * dirs / files / fileEntries 三条列表共用这一条规则,避免实现分叉。
1598
+ */
1599
+ const directoryEntryVisible = (name, includeHidden) => name !== ".git" && (includeHidden || !String(name).startsWith("."));
1600
+
1169
1601
  /** 旧宿主逐个标题兜底的读取宽度:与宿主 `persistedReadConcurrency` 默认值一致(≤4)。 */
1170
1602
  const TITLE_FALLBACK_READ_WIDTH = DEFAULT_TITLE_REFRESH_CONCURRENCY;
1171
1603
  /**
@@ -1556,6 +1988,94 @@ function readUpdateManifest(dir, basePath = "/m", origin = "") {
1556
1988
  return { ok: true, manifest, pluginServed, dir };
1557
1989
  }
1558
1990
 
1991
+ /** DSH `session.attachment` 请求 schema 允许的媒体类型(strict enum,issue #78)。 */
1992
+ const ATTACHMENT_MEDIA_TYPES = Object.freeze(["image/png", "image/jpeg", "image/webp", "image/gif"]);
1993
+
1994
+ /** attachmentId 基本形状校验:不透明存储 id(允许 `sha256:` 等),拒绝空白/控制字符。 */
1995
+ export function attachmentIdValid(value) {
1996
+ return typeof value === "string"
1997
+ && value.length > 0
1998
+ && value.length <= 512
1999
+ && !/[\s\u0000-\u001f\u007f]/.test(value);
2000
+ }
2001
+
2002
+ /**
2003
+ * 从原始 attachment ref 提取 `session.attachment` strict schema 允许的完整引用
2004
+ * (issue #78):新 DSH schema 只接受 `{attachmentId,mediaType,bytes,width,height,name?,
2005
+ * originalDimensions?}`,且 mediaType 是 png/jpeg/webp/gif 枚举。字段缺失/非法一律
2006
+ * fail-closed 返回 null(绝不把客户端字段或半截引用发给网关)。
2007
+ * @param {unknown} value 原始 attachment 对象。
2008
+ * @returns {{attachmentId:string,mediaType:string,bytes:number,width:number,height:number,name?:string,originalDimensions?:{width:number,height:number}}|null}
2009
+ */
2010
+ export function attachmentRefFrom(value) {
2011
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
2012
+ const attachmentId = typeof value.attachmentId === "string" ? value.attachmentId : "";
2013
+ if (!attachmentIdValid(attachmentId)) return null;
2014
+ const mediaType = typeof value.mediaType === "string" ? value.mediaType : "";
2015
+ if (!ATTACHMENT_MEDIA_TYPES.includes(mediaType)) return null;
2016
+ const bytes = value.bytes;
2017
+ const width = value.width;
2018
+ const height = value.height;
2019
+ if (!Number.isFinite(bytes) || bytes <= 0) return null;
2020
+ if (!Number.isFinite(width) || width <= 0) return null;
2021
+ if (!Number.isFinite(height) || height <= 0) return null;
2022
+ const ref = { attachmentId, mediaType, bytes, width, height };
2023
+ if (typeof value.name === "string" && value.name !== "") {
2024
+ // name 可选;保持为纯展示字段(不拼接本地路径),并去掉控制字符。
2025
+ const name = value.name.replace(/[\u0000-\u001f\u007f]/g, "").trim();
2026
+ if (name !== "") ref.name = name.slice(0, 512);
2027
+ }
2028
+ const dimensions = value.originalDimensions;
2029
+ if (dimensions && typeof dimensions === "object"
2030
+ && Number.isFinite(dimensions.width) && dimensions.width > 0
2031
+ && Number.isFinite(dimensions.height) && dimensions.height > 0) {
2032
+ ref.originalDimensions = { width: dimensions.width, height: dimensions.height };
2033
+ }
2034
+ return ref;
2035
+ }
2036
+
2037
+ /**
2038
+ * 按 attachmentId 从会话原始事件里找到完整 image attachment ref(issue #78)。
2039
+ * 服务端投影的 `images[]` 只有元数据、没有 bytes;`session.attachment` 新 schema
2040
+ * 需要完整 ref,因此必须回到**原始事件**(user/message、assistant/message、
2041
+ * tool/result 的 content blocks)里按 id 查找。找不到/字段不完整返回 null(不猜)。
2042
+ * @param {any[]} events 会话原始事件。
2043
+ * @param {string} attachmentId 目标 id。
2044
+ * @returns {object|null} 经 attachmentRefFrom 校验后的完整 ref。
2045
+ */
2046
+ export function extractAttachmentRef(events, attachmentId) {
2047
+ if (!Array.isArray(events) || !attachmentIdValid(attachmentId)) return null;
2048
+ let found = null;
2049
+ const seen = new Set();
2050
+ const consider = (value) => {
2051
+ if (found || !value || typeof value !== "object") return;
2052
+ const ref = attachmentRefFrom(value);
2053
+ if (ref && ref.attachmentId === attachmentId) found = ref;
2054
+ };
2055
+ const visit = (value, depth) => {
2056
+ if (found || depth > 12 || value === null || value === undefined) return;
2057
+ if (Array.isArray(value)) {
2058
+ for (const entry of value) visit(entry, depth + 1);
2059
+ return;
2060
+ }
2061
+ if (typeof value !== "object") return;
2062
+ if (seen.has(value)) return;
2063
+ seen.add(value);
2064
+ // image block:attachment 在嵌套对象里;images[]/message.content 里的 flat ref 也接受。
2065
+ if (value.type === "image" && value.attachment) consider(value.attachment);
2066
+ consider(value);
2067
+ for (const key of Object.keys(value)) {
2068
+ const child = value[key];
2069
+ if (child !== null && typeof child === "object") visit(child, depth + 1);
2070
+ }
2071
+ };
2072
+ for (const event of events) {
2073
+ if (event !== null && typeof event === "object") visit(event.data ?? event, 0);
2074
+ if (found) break;
2075
+ }
2076
+ return found;
2077
+ }
2078
+
1559
2079
  /** image attachment 引用 → 移动端图片元数据(仅引用不含字节;渲染时 App 按 attachmentId 走 /attachment 端点拉取)。 */
1560
2080
  function imageMetaOf(ref) {
1561
2081
  if (!ref || typeof ref !== "object" || !ref.attachmentId) return null;
@@ -1668,11 +2188,1046 @@ function sniffImageType(data) {
1668
2188
  return null;
1669
2189
  }
1670
2190
 
2191
+ /** 把路径统一成 POSIX 斜杠文本(`display` 契约始终用 `/` 分隔,§6.21)。 */
2192
+ const posixPathText = (value) => String(value ?? "").replaceAll("\\", "/");
2193
+ /** 是否绝对路径(POSIX 根 / Windows 盘符);`display` 派生只看文本,不依赖宿主平台。 */
2194
+ const isAbsolutePathText = (value) => value.startsWith("/") || /^[A-Za-z]:\//.test(value);
2195
+ /**
2196
+ * issue #60 round7(F2):把「记录路径 + 会话 cwd」归一到同一规范绝对路径。
2197
+ * 宿主两条投影的路径形状可能不同:presented 常是 realpath 绝对路径(或相对),
2198
+ * changed 常是相对路径;两处 cwd 文本也可能不同(header.cwd 含 symlink 别名、
2199
+ * summary.cwd 是 realpath 或子目录)。只靠文本 resolve 会发散,故哈希/派生前统一:
2200
+ * 1) 仅对会话 cwd 做 realpath,合并同一工作目录的符号链接别名;
2201
+ * 2) 记录路径按 cwd 词法展开,保留各路径段(包括符号链接条目)作为文件身份。
2202
+ * 任何失败都 try/catch 兜底退回纯文本 resolve,**绝不因 realpath 抛错**、
2203
+ * 也绝不改变 id 的格式(仍是 sha256 前 16 hex、不可逆、不含可拼路径)。
2204
+ * 注意:本函数只在服务端内部用于派生 id / display,规范绝对路径绝不下发到任何响应。
2205
+ * @returns {string} 规范绝对路径文本;path 非法时返回空串。
2206
+ */
2207
+ const canonicalWorkspacePath = (path, cwd) => {
2208
+ const text = normalizeServerPath(path);
2209
+ if (typeof text !== "string" || text === "") return "";
2210
+ if (typeof cwd !== "string" || cwd === "") return isAbsolute(text) ? resolve(text) : text;
2211
+ const lexicalCwd = resolve(normalizeServerPath(cwd));
2212
+ let canonicalCwd = lexicalCwd;
2213
+ try { canonicalCwd = realpathSync(lexicalCwd); } catch { /* unavailable cwd */ }
2214
+ const absolute = isAbsolute(text) ? resolve(text) : resolve(lexicalCwd, text);
2215
+ const within = (root, target) => {
2216
+ const rel = relative(root, target);
2217
+ return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
2218
+ };
2219
+ // 只解析 cwd 本身的别名;保留记录相对路径每一段,包括末级/中间符号链接。
2220
+ // Git 工作区中符号链接条目和目标是不同记录,不能对文件全路径调用 realpath。
2221
+ if (within(lexicalCwd, absolute)) return resolve(canonicalCwd, relative(lexicalCwd, absolute));
2222
+ if (within(canonicalCwd, absolute)) return absolute;
2223
+ // 绝对路径可能通过 cwd 的另一别名进入工作区(如 /var/run 与 /run)。
2224
+ // 只寻找真实指向 cwd 的祖先;保留其后的每一段,即使中间条目是符号链接或不存在。
2225
+ let head = dirname(absolute);
2226
+ const suffix = [basename(absolute)];
2227
+ let entryPath = null;
2228
+ while (true) {
2229
+ // 取最外层 cwd 别名。内层 symlink 也可能恰好指回 cwd,不能把它当别名吞掉。
2230
+ try { if (realpathSync(head) === canonicalCwd) entryPath = resolve(canonicalCwd, ...suffix); }
2231
+ catch { /* 尚不存在或不可读:继续寻找更高祖先 */ }
2232
+ const parent = dirname(head);
2233
+ if (parent === head) break;
2234
+ suffix.unshift(basename(head));
2235
+ head = parent;
2236
+ }
2237
+ return entryPath ?? absolute;
2238
+ };
2239
+ /**
2240
+ * 记录内文件的**不泄路径稳定身份**(issue #60 round4-2 / R08):
2241
+ * 路径 SHA-256 前 16 位十六进制。presented 与 changed 两条投影必须使用同一 helper,
2242
+ * App 才能把同一逻辑文件在两种来源下合并(不可逆、不含主机前缀)。
2243
+ * @param {unknown} path 记录内的路径(绝对或相对)。
2244
+ * @param {unknown} cwd 会话工作目录(两处调用须同源,见 /changes/summary 的 idBase)。
2245
+ * @returns {string} 16 位 hex;path 非法时返回空串。
2246
+ */
2247
+ export function recordFileId(path, cwd) {
2248
+ if (typeof path !== "string" || path === "") return "";
2249
+ const canonical = canonicalWorkspacePath(path, cwd);
2250
+ if (canonical === "") return "";
2251
+ return createHash("sha256").update(canonical).digest("hex").slice(0, 16);
2252
+ }
2253
+
2254
+ /** 不依赖宿主平台的 basename(`basename()` 在 Windows 路径上会保留反斜杠段)。 */
2255
+ const posixBasenameOf = (value) => {
2256
+ const text = posixPathText(value).replace(/\/+$/, "");
2257
+ const index = text.lastIndexOf("/");
2258
+ const base = index >= 0 ? text.slice(index + 1) : text;
2259
+ return base === "" ? "file" : base;
2260
+ };
2261
+
2262
+ /**
2263
+ * `deliverables/presented` 的 `display` 派生(issue #53 / §6.20):
2264
+ * 工作目录内给相对路径,家目录下给 `~/…`,其余**只给 basename**——绝不把主机绝对
2265
+ * 路径交给客户端。`cwd` 未知(休眠会话/旧宿主)时退化为 basename。
2266
+ * @param {unknown} path 记录里的原始路径。
2267
+ * @param {unknown} cwd 会话工作目录(宿主侧事实,只用于派生,不下发)。
2268
+ * @returns {string} 可展示路径(永不包含可拼接的绝对路径)。
2269
+ */
2270
+ export function mobileDisplayPath(path, cwd) {
2271
+ const text = posixPathText(path).trim();
2272
+ if (text === "") return "";
2273
+ if (!isAbsolutePathText(text)) return text.replace(/^\.\//, "");
2274
+ // issue #60(F2):规范 cwd 及其别名、保留工作区内的词法条目后再比较,避免
2275
+ // presented 绝对路径落在 symlink 别名 cwd 的「文本之外」而退化成 basename,
2276
+ // changed 却是 `src/a.ts`(display 不一致 → App 精确链接丢失)。
2277
+ // canonicalWorkspacePath 只在服务端内部使用;返回的相对/`~/`/basename 满足 R05,
2278
+ // 绝不把规范绝对路径写进响应。
2279
+ const canonicalPath = posixPathText(canonicalWorkspacePath(text, cwd));
2280
+ let cwdText = typeof cwd === "string" && cwd !== "" ? posixPathText(cwd).replace(/\/+$/, "") : "";
2281
+ if (cwdText !== "") {
2282
+ try { cwdText = realpathSync(cwdText); } catch { /* cwd 不存在:退回原文本 */ }
2283
+ cwdText = posixPathText(cwdText).replace(/\/+$/, "");
2284
+ }
2285
+ if (cwdText !== "" && (canonicalPath === cwdText || canonicalPath.startsWith(`${cwdText}/`))) {
2286
+ const rel = canonicalPath.slice(cwdText.length).replace(/^\/+/, "");
2287
+ return rel === "" ? posixBasenameOf(canonicalPath) : rel;
2288
+ }
2289
+ const homeText = posixPathText(homedir()).replace(/\/+$/, "");
2290
+ if (homeText !== "" && canonicalPath.startsWith(`${homeText}/`)) return `~/${canonicalPath.slice(homeText.length + 1)}`;
2291
+ return posixBasenameOf(canonicalPath);
2292
+ }
2293
+
2294
+ /** 词法包含判定(与 `canonicalWorkspacePath` 内的 `within` 同式;issue #67 独立实现,不重构既有函数)。 */
2295
+ const isWithinDir = (root, target) => {
2296
+ const rel = relative(root, target);
2297
+ return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
2298
+ };
2299
+
2300
+ /**
2301
+ * issue #67(M3 Batch 2-B):工具卡路径的**可预览目标**(§6.24)。
2302
+ *
2303
+ * 输入是工具原始参数里的 `file_path`/`filePath` 与**会话 cwd**,输出仅
2304
+ * `{ relative, previewable: true }` 或 `null`(两字段一起缺省)。语义是 fail-closed:
2305
+ * - **本函数的判定**全部词法校验先做、零 fs 调用;cwd 之外的绝对路径**绝不**触发
2306
+ * realpath/stat(否则判定会变成对任意敏感目录的存在性探测器);
2307
+ * - 只有词法已在 cwd 内的候选才做 realpath containment(拒绝符号链接逃逸)
2308
+ * 与 isFile / R_OK 验证;
2309
+ * - 输出恒为 cwd 相对 POSIX 路径(无前导 `/`、无盘符、无 `.`/`..`/空段,
2310
+ * ≤300 字且**绝不截断**——截断会指向另一个文件)。
2311
+ * 边界(reviewer P1):同一条 `tool/call` 摘要里的 `display`(`filePath` 等)由
2312
+ * `mobileDisplayPath` → `canonicalWorkspacePath`(issue #60 F2)派生,它会为合并
2313
+ * cwd 符号链接别名而对**已给出的绝对路径祖先**做 realpath;那是 #54/#60 既有行为,
2314
+ * 不属于 #67 新增的探测面,且本 issue 不修改它。即:**preview 判定零探测,整条摘要
2315
+ * 链路不承诺零探测**(绝对路径祖先的 realpath 由 display 派生承担)。
2316
+ * 只供摘要投影使用;不改变 `mobileDisplayPath`/`display` 语义,也不下发任何绝对路径。
2317
+ * @param {unknown} rawPath 工具原始参数里的路径。
2318
+ * @param {unknown} cwd 会话工作目录(宿主侧事实,不下发)。
2319
+ * @returns {{relative: string, previewable: true} | null}
2320
+ */
2321
+ export function previewTargetOf(rawPath, cwd) {
2322
+ // A. 词法(零 fs 调用)
2323
+ if (typeof rawPath !== "string" || rawPath === "") return null;
2324
+ if (rawPath.length > 4096) return null;
2325
+ if (rawPath.includes("\0")) return null;
2326
+ // display 会 trim;保留首尾空白会让「显示的目标」与「跳转的目标」不一致,直接拒绝。
2327
+ if (rawPath !== rawPath.trim()) return null;
2328
+ // reviewer P2:POSIX 上 `\` 是合法文件名字符,不是分隔符。若把它归一成 `/`,
2329
+ // 字面文件 `dir\a` 与 `dir/a` 同时存在时摘要会指向**另一份文件**(点击打开错文件)。
2330
+ // 因此只有 cwd 呈 Windows 形态(那里 `\` 是分隔符、不存在字面反斜杠文件名)才保留
2331
+ // `\`→`/` 归一;检测必须用**原始 cwd 字符串**,不能用 posixPathText 归一后的值。
2332
+ const windowsCwd =
2333
+ typeof cwd === "string" &&
2334
+ (/^[A-Za-z]:[\\/]/.test(cwd) || (cwd.includes("\\") && !cwd.startsWith("/")));
2335
+ if (!windowsCwd && rawPath.includes("\\")) return null;
2336
+ const text = posixPathText(rawPath).replace(/^\.\//, "");
2337
+ if (text === "") return null;
2338
+ const absolute = isAbsolutePathText(text);
2339
+ let segments;
2340
+ if (absolute) {
2341
+ // 剥盘符前缀与一个前导 `/`;剥掉的前缀不参与输出(Windows 盘符绝对路径在 cwd 内时仍可换算)。
2342
+ let rest = text.replace(/^[A-Za-z]:/, "");
2343
+ if (rest.startsWith("/")) rest = rest.slice(1);
2344
+ segments = rest === "" ? [] : rest.split("/");
2345
+ } else {
2346
+ segments = text.split("/");
2347
+ }
2348
+ // 空段 / `.` / `..` / 含 `:` 段一律拒绝;只剥一次前导 `./`(与 display 同式)。
2349
+ if (segments.length === 0) return null;
2350
+ for (const segment of segments) {
2351
+ if (segment === "" || segment === "." || segment === ".." || segment.includes(":")) return null;
2352
+ }
2353
+ // B. cwd(fs 只碰 cwd 自身)
2354
+ if (typeof cwd !== "string" || cwd === "") return null;
2355
+ if (!isAbsolutePathText(posixPathText(cwd))) return null;
2356
+ const rootLex = resolve(normalizeServerPath(cwd));
2357
+ let rootReal;
2358
+ try { rootReal = realpathSync(rootLex); } catch { return null; }
2359
+ let rootStat;
2360
+ try { rootStat = statSync(rootReal); } catch { return null; }
2361
+ if (!rootStat.isDirectory()) return null;
2362
+ // C. 词法夹取(fs 之前完成)
2363
+ let targetAbs;
2364
+ if (absolute) {
2365
+ targetAbs = resolve(normalizeServerPath(text));
2366
+ // cwd 外的绝对路径在这里就返回:绝不 realpath/stat 候选。
2367
+ if (!isWithinDir(rootLex, targetAbs) && !isWithinDir(rootReal, targetAbs)) return null;
2368
+ } else {
2369
+ targetAbs = resolve(rootLex, ...segments);
2370
+ }
2371
+ // D. 相对文本(取用户路径的词法形状,realpath 只当闸门)
2372
+ const base = isWithinDir(rootLex, targetAbs) ? rootLex : rootReal;
2373
+ const rel = posixPathText(relative(base, targetAbs));
2374
+ if (rel === "" || isAbsolutePathText(rel)) return null;
2375
+ for (const segment of rel.split("/")) {
2376
+ if (segment === "" || segment === "." || segment === ".." || segment.includes(":")) return null;
2377
+ }
2378
+ if (rel.length > TOOL_CARD_PREVIEW_PATH_MAX) return null;
2379
+ // E. 目标验证(fs 只碰候选)
2380
+ let realTarget;
2381
+ try { realTarget = realpathSync(targetAbs); } catch { return null; }
2382
+ if (!isWithinDir(rootReal, realTarget)) return null; // 符号链接逃逸
2383
+ let targetStat;
2384
+ try { targetStat = statSync(realTarget); } catch { return null; }
2385
+ if (!targetStat.isFile()) return null; // 目录 / FIFO / socket / 设备
2386
+ try { accessSync(realTarget, constants.R_OK); } catch { return null; }
2387
+ return { relative: rel, previewable: true };
2388
+ }
2389
+
2390
+ /**
2391
+ * 从会话事件折叠 `callId → tool/call.name`(issue #60 R14):结果事件通常不带工具名,
2392
+ * 调用方用它在投影前解析"这次调用是什么工具",避免无名字时从内容猜终止状态。
2393
+ * @param {any[]} events 会话原始事件。
2394
+ * @returns {Map<string, string>}
2395
+ */
2396
+ export function toolNamesOf(events) {
2397
+ const names = new Map();
2398
+ for (const event of events ?? []) {
2399
+ if (event?.type !== "tool/call") continue;
2400
+ const callId = event?.data?.callId;
2401
+ const name = event?.data?.name;
2402
+ if (typeof callId === "string" && callId !== "" && typeof name === "string" && name !== "") {
2403
+ names.set(callId, name);
2404
+ }
2405
+ }
2406
+ return names;
2407
+ }
2408
+
2409
+ /**
2410
+ * `tool/result` 的真实调用坐标(issue #60 recheck-4 / R14):
2411
+ * 当前内核把 callId 放在 `message.source.callId`、`message.toolCallId` 或
2412
+ * `message.content[].toolCallId`,**不在** `event.data.callId`。统一从这些位置提取,
2413
+ * 供摘要 callId、toolNamesOf 关联(history/SSE)与 App 生命周期合并共用。
2414
+ * @param {any} event tool/result 事件。
2415
+ * @returns {string} callId;无法确定时为空串。
2416
+ */
2417
+ export function toolResultCallIdOf(event) {
2418
+ const data = event?.data ?? {};
2419
+ const message = data.message;
2420
+ const content = Array.isArray(message?.content) ? message.content : [];
2421
+ const candidates = [
2422
+ data.callId,
2423
+ data.toolCallId,
2424
+ message?.toolCallId,
2425
+ message?.source?.callId,
2426
+ ];
2427
+ for (const block of content) {
2428
+ if (!block || typeof block !== "object") continue;
2429
+ candidates.push(block.toolCallId);
2430
+ if (Array.isArray(block.content)) {
2431
+ for (const inner of block.content) candidates.push(inner?.toolCallId);
2432
+ }
2433
+ }
2434
+ return candidates.find((value) => typeof value === "string" && value !== "") ?? "";
2435
+ }
2436
+
2437
+ /** 工具参数解析(issue #54):只接受 JSON 对象;非法/非对象一律 fail-open 返回 null。 */
2438
+ function parseToolArguments(raw) {
2439
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) return raw;
2440
+ if (typeof raw !== "string" || raw.trim() === "") return null;
2441
+ try {
2442
+ const parsed = JSON.parse(raw);
2443
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
2444
+ } catch {
2445
+ return null;
2446
+ }
2447
+ }
2448
+
2449
+ /** 折叠行/字段单行化(换行压成空格,避免破坏卡片布局)。 */
2450
+ const singleLineText = (value) => String(value ?? "").replace(/\s+/g, " ").trim();
2451
+
2452
+ /** 正整数参数(offset/limit):非正/非整数忽略(fail-open)。 */
2453
+ const positiveIntArg = (value) =>
2454
+ typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
2455
+
2456
+ /** 按行切分,同时忽略末尾换行产生的空哨兵(与桌面 diff 行数口径一致)。 */
2457
+ function diffLinesOf(text) {
2458
+ if (typeof text !== "string" || text === "") return [];
2459
+ const lines = text.split("\n");
2460
+ if (text.endsWith("\n")) lines.pop();
2461
+ return lines;
2462
+ }
2463
+
2464
+ /**
2465
+ * 统一 diff 体积上限保护(issue #54 note 1761):≤8 KiB 原样返回,超出**整段缺省**并
2466
+ * 标记 diffTruncated(不截半段,避免 App 的 diff 解析错位)。
2467
+ * @returns {{diff?: string, diffTruncated?: true}}
2468
+ */
2469
+ function boundedDiff(headerLines, bodyLines) {
2470
+ const text = `${[...headerLines, ...bodyLines].join("\n")}\n`;
2471
+ if (Buffer.byteLength(text, "utf8") > TOOL_CARD_DIFF_MAX_BYTES) return { diffTruncated: true };
2472
+ return { diff: text };
2473
+ }
2474
+
2475
+ /** write 的「全新增」统一 diff(display 已派生,不含主机路径)。 */
2476
+ function addedFileDiff(display, content) {
2477
+ const lines = diffLinesOf(content);
2478
+ if (lines.length === 0) return {};
2479
+ return boundedDiff(
2480
+ ["--- /dev/null", `+++ b/${display}`, `@@ -0,0 +1,${lines.length} @@`],
2481
+ lines.map((line) => `+${line}`),
2482
+ );
2483
+ }
2484
+
2485
+ /**
2486
+ * edit 的近似统一 diff(issue #54 note 1761 允许近似):
2487
+ * 不做上下文/位置搜索,直接把 old_string 全部列为删除行、new_string 全部列为新增行;
2488
+ * `added`/`deleted` 也按行数近似(含省略末尾空行),仅用于折叠行统计。
2489
+ */
2490
+ function editedFileDiff(display, oldText, newText) {
2491
+ const oldLines = diffLinesOf(oldText);
2492
+ const newLines = diffLinesOf(newText);
2493
+ const header = [
2494
+ oldLines.length === 0 ? "--- /dev/null" : `--- a/${display}`,
2495
+ newLines.length === 0 ? "+++ /dev/null" : `+++ b/${display}`,
2496
+ `@@ -1,${oldLines.length} +1,${newLines.length} @@`,
2497
+ ];
2498
+ const body = [
2499
+ ...oldLines.map((line) => `-${line}`),
2500
+ ...newLines.map((line) => `+${line}`),
2501
+ ];
2502
+ const bounded = boundedDiff(header, body);
2503
+ return {
2504
+ ...bounded,
2505
+ added: newLines.length,
2506
+ deleted: oldLines.length,
2507
+ };
2508
+ }
2509
+
2510
+ /**
2511
+ * `tool/call` 的结构化摘要(issue #54 §2):从**原始** `data.arguments` 解析,先解析后
2512
+ * clamp;路径一律经 `mobileDisplayPath` 派生,**绝不下发绝对路径**。未知工具/非法参数
2513
+ * 返回 undefined 或只带 kind/tool 的最小摘要,绝不抛错(fail-open 到通用卡)。
2514
+ * @param {unknown} toolName 工具名。
2515
+ * @param {unknown} rawArguments 原始 arguments(JSON 字符串或对象)。
2516
+ * @param {unknown} cwd 会话工作目录(仅用于 display 派生,不下发)。
2517
+ * @returns {object|undefined}
2518
+ */
2519
+ export function toolCallSummaryOf(toolName, rawArguments, cwd) {
2520
+ const tool = typeof toolName === "string" ? toolName : "";
2521
+ const kind = TOOL_CARD_KIND[tool];
2522
+ if (kind === undefined) return undefined;
2523
+ const summary = { kind, tool };
2524
+ const args = parseToolArguments(rawArguments);
2525
+ if (args === null) return summary;
2526
+ // 注意(reviewer P1):`displayOf` 沿用既有 `mobileDisplayPath` → `canonicalWorkspacePath`
2527
+ // 派生,可能为对齐 cwd 符号链接别名而对**已给出的绝对路径祖先**做 realpath;那是
2528
+ // #54/#60 的 display 语义、语义未改,也不是 #67 新增的探测面。issue #67 的
2529
+ // `previewTargetOf` 判定本身对 cwd 外绝对路径零 fs 探测(见其头注释)。
2530
+ const displayOf = (value) => {
2531
+ if (typeof value !== "string" || value.trim() === "") return undefined;
2532
+ return clampText(mobileDisplayPath(value, cwd), 300);
2533
+ };
2534
+ const toolFilePath = displayOf(args.file_path ?? args.filePath);
2535
+ // issue #67:仅 read/write/edit/read_image 的原始路径参与可预览判定;两字段严格同现/同缺。
2536
+ // 其它工具即便参数里带了 file_path 也不做任何 fs 探测(grep/glob 的 path 不扩到本能力)。
2537
+ const preview = tool === "read" || tool === "write" || tool === "edit" || tool === "read_image"
2538
+ ? previewTargetOf(args.file_path ?? args.filePath, cwd)
2539
+ : null;
2540
+ switch (tool) {
2541
+ case "bash":
2542
+ case "pwsh": {
2543
+ if (typeof args.command === "string" && args.command.trim() !== "") {
2544
+ summary.command = clampText(singleLineText(args.command), 200);
2545
+ }
2546
+ const workdir = displayOf(args.workdir);
2547
+ if (workdir !== undefined) summary.workdir = workdir;
2548
+ if (args.run_in_background === true) summary.background = true;
2549
+ if (typeof args.description === "string" && args.description.trim() !== "") {
2550
+ summary.description = clampText(singleLineText(args.description), 120);
2551
+ }
2552
+ break;
2553
+ }
2554
+ case "read": {
2555
+ if (toolFilePath !== undefined) summary.filePath = toolFilePath;
2556
+ if (preview !== null) Object.assign(summary, preview);
2557
+ const offset = positiveIntArg(args.offset);
2558
+ if (offset !== undefined) summary.offset = offset;
2559
+ const limit = positiveIntArg(args.limit);
2560
+ if (limit !== undefined) summary.limit = limit;
2561
+ break;
2562
+ }
2563
+ case "write": {
2564
+ if (toolFilePath !== undefined) summary.filePath = toolFilePath;
2565
+ if (preview !== null) Object.assign(summary, preview);
2566
+ if (typeof args.content === "string") {
2567
+ // 与桌面 `NKB` 同口径:UTF-16 code unit 长度 / 1024 向上取整。
2568
+ summary.sizeKb = Math.ceil(args.content.length / 1024);
2569
+ if (toolFilePath !== undefined) {
2570
+ Object.assign(summary, addedFileDiff(toolFilePath, args.content));
2571
+ }
2572
+ }
2573
+ break;
2574
+ }
2575
+ case "edit": {
2576
+ if (toolFilePath !== undefined) summary.filePath = toolFilePath;
2577
+ if (preview !== null) Object.assign(summary, preview);
2578
+ const oldText = typeof args.old_string === "string" ? args.old_string : typeof args.oldString === "string" ? args.oldString : "";
2579
+ const newText = typeof args.new_string === "string" ? args.new_string : typeof args.newString === "string" ? args.newString : "";
2580
+ summary.sizeKb = Math.ceil((oldText.length + newText.length) / 1024);
2581
+ if (toolFilePath !== undefined) {
2582
+ Object.assign(summary, editedFileDiff(toolFilePath, oldText, newText));
2583
+ } else {
2584
+ summary.added = diffLinesOf(newText).length;
2585
+ summary.deleted = diffLinesOf(oldText).length;
2586
+ }
2587
+ break;
2588
+ }
2589
+ case "grep":
2590
+ case "glob": {
2591
+ if (typeof args.pattern === "string" && args.pattern.trim() !== "") {
2592
+ summary.pattern = clampText(singleLineText(args.pattern), 200);
2593
+ }
2594
+ const searchPath = displayOf(args.path);
2595
+ if (searchPath !== undefined) summary.path = searchPath;
2596
+ if (tool === "grep" && typeof args.include === "string" && args.include.trim() !== "") {
2597
+ summary.include = clampText(singleLineText(args.include), 200);
2598
+ }
2599
+ break;
2600
+ }
2601
+ case "web_fetch": {
2602
+ if (typeof args.url === "string" && args.url.trim() !== "") summary.url = clampText(args.url.trim(), 500);
2603
+ break;
2604
+ }
2605
+ case "web_search": {
2606
+ const first = Array.isArray(args.queries) ? args.queries.find((value) => typeof value === "string" && value.trim() !== "") : undefined;
2607
+ if (typeof first === "string") summary.query = clampText(singleLineText(first), 200);
2608
+ break;
2609
+ }
2610
+ case "read_image": {
2611
+ if (toolFilePath !== undefined) summary.filePath = toolFilePath;
2612
+ if (preview !== null) Object.assign(summary, preview);
2613
+ break;
2614
+ }
2615
+ case "todo_write": {
2616
+ // issue #66(契约 §1.2):`todos` 必须是数组;非数组不猜,只回 kind/tool(App 回退通用卡)。
2617
+ // 空数组是合法快照(可渲染 0 项);status 不在宿主枚举内一律归 pending,
2618
+ // counts 恒带三键且由**归一后**的 items 统计(三项和 = items.length)。
2619
+ // R2(评审):与 App 逐项降级口径一致——非对象 / content 非 string 的元素直接跳过
2620
+ // (App 会丢弃它们),counts 只统计保留下来的 items,避免折叠行「N 项任务」与展开
2621
+ // 清单的项数/完成数对不上(此前 map 会把 42/"x" 变成空 content 的伪 item)。
2622
+ if (!Array.isArray(args.todos)) break;
2623
+ const items = [];
2624
+ for (const todo of args.todos) {
2625
+ if (items.length >= TOOL_CARD_MAX_TODO_ITEMS) break;
2626
+ if (!todo || typeof todo !== "object" || typeof todo.content !== "string") continue;
2627
+ items.push({
2628
+ content: clampText(singleLineText(todo.content), TOOL_CARD_MAX_TODO_CONTENT),
2629
+ status: TOOL_CARD_TODO_STATUSES.includes(todo.status) ? todo.status : "pending",
2630
+ });
2631
+ }
2632
+ const counts = { pending: 0, inProgress: 0, completed: 0 };
2633
+ for (const item of items) {
2634
+ if (item.status === "in_progress") counts.inProgress++;
2635
+ else if (item.status === "completed") counts.completed++;
2636
+ else counts.pending++;
2637
+ }
2638
+ summary.items = items;
2639
+ summary.counts = counts;
2640
+ break;
2641
+ }
2642
+ case "ask_user_question": {
2643
+ // issue #66(契约 §1.2):questions 非数组/无有效题 → 只回 kind/tool(不可渲染)。
2644
+ // `question` 是渲染必需字段,缺失/空白的题整题丢弃;`id` 是 App 关联"待答"的
2645
+ // 唯一依据,必须保留(只 clamp,不做单行化,保证与 tool/result 回放的 echo 一致)。
2646
+ if (!Array.isArray(args.questions)) break;
2647
+ const questions = [];
2648
+ for (const raw of args.questions) {
2649
+ if (questions.length >= TOOL_CARD_MAX_QUESTIONS) break;
2650
+ if (!raw || typeof raw !== "object") continue;
2651
+ // 契约要求 question 必须是字符串;非字符串/空白一律整题丢弃。
2652
+ const questionText = typeof raw.question === "string" ? singleLineText(raw.question) : "";
2653
+ if (questionText === "") continue;
2654
+ const entry = { question: clampText(questionText, TOOL_CARD_MAX_QUESTION_TEXT) };
2655
+ if (typeof raw.id === "string" && raw.id.trim() !== "") entry.id = clampText(raw.id, TOOL_CARD_MAX_QUESTION_ID);
2656
+ const header = typeof raw.header === "string" ? singleLineText(raw.header) : "";
2657
+ if (header !== "") entry.header = clampText(header, TOOL_CARD_MAX_QUESTION_HEADER);
2658
+ if (Array.isArray(raw.options)) {
2659
+ const options = [];
2660
+ for (const rawOption of raw.options) {
2661
+ if (options.length >= TOOL_CARD_MAX_QUESTION_OPTIONS) break;
2662
+ if (!rawOption || typeof rawOption !== "object") continue;
2663
+ const label = typeof rawOption.label === "string" ? singleLineText(rawOption.label) : "";
2664
+ if (label === "") continue; // 无 label 的 option 逐项丢弃
2665
+ const option = { label: clampText(label, TOOL_CARD_MAX_OPTION_LABEL) };
2666
+ const description = typeof rawOption.description === "string" ? singleLineText(rawOption.description) : "";
2667
+ if (description !== "") option.description = clampText(description, TOOL_CARD_MAX_OPTION_DESCRIPTION);
2668
+ options.push(option);
2669
+ }
2670
+ // 处理后为空 → 不下发该字段(契约 §1.2)。
2671
+ if (options.length > 0) entry.options = options;
2672
+ }
2673
+ // 宿主参数是 snake_case 的 multi_select;同时接受 camelCase(两种形状都只认 true)。
2674
+ if (raw.multi_select === true || raw.multiSelect === true) entry.multiSelect = true;
2675
+ questions.push(entry);
2676
+ }
2677
+ if (questions.length > 0) summary.questions = questions;
2678
+ break;
2679
+ }
2680
+ case "skill": {
2681
+ // issue #66(契约 §1.2):只下发 skill 名;resourceBase/provider/content 等一律不带。
2682
+ if (typeof args.name === "string" && args.name.trim() !== "") {
2683
+ summary.name = clampText(args.name, TOOL_CARD_MAX_SKILL_NAME);
2684
+ }
2685
+ break;
2686
+ }
2687
+ }
2688
+ return summary;
2689
+ }
2690
+
2691
+ /**
2692
+ * PTC 子调用事件类型(issue #68):`run_code` 内被调度工具的执行前/落定事件。
2693
+ * 两个类型共用同一投影分支,App 以 `callId` 合并 start→result。
2694
+ */
2695
+ const PTC_DISPATCH_EVENT_TYPES = Object.freeze(["tool/ptc-dispatch-start", "tool/ptc-dispatch"]);
2696
+ /** 是否为 PTC 子调用事件(投影/接线共用判据,避免两处分叉)。 */
2697
+ function isPtcDispatchEvent(event) {
2698
+ return event !== null && typeof event === "object" && PTC_DISPATCH_EVENT_TYPES.includes(event.type);
2699
+ }
2700
+
2701
+ /** PTC 事件 id 防御:非空字符串且 ≤300 才接受;非法 → undefined(整条投影降级为无 data)。 */
2702
+ function ptcIdOf(value) {
2703
+ return typeof value === "string" && value.length > 0 && value.length <= PTC_MAX_ID_LENGTH ? value : undefined;
2704
+ }
2705
+
2706
+ /**
2707
+ * L2-2:PTC `text`/`error` 只接受安全码语法(`FS_NOT_FOUND`/`EACCES`/`FsError`/
2708
+ * `ToolArgsError` 等);任意自由文本(路径/栈/注入字符)一律拒绝。
2709
+ */
2710
+ // 注意:不用 `$`(JS 的 `$` 会放过末尾换行),用否定任意字符收尾;且**不 trim**——含
2711
+ // 空格/换行/制表符的原串一律不是安全码(L2-8 严格验证)。
2712
+ const PTC_SAFE_CODE_PATTERN = /^[A-Za-z][A-Za-z0-9_.-]{0,63}(?![\s\S])/;
2713
+ function ptcSafeCodeOf(value) {
2714
+ return typeof value === "string" && PTC_SAFE_CODE_PATTERN.test(value)
2715
+ ? value
2716
+ : undefined;
2717
+ }
2718
+
2719
+ /** http(s) URL 在路径脱敏时先整体占位保护(URL 不是主机路径,不得被改写)。 */
2720
+ const PTC_SCRUB_URL_PATTERN = /\bhttps?:\/\/[^\s"'`)\]]+/gi;
2721
+
2722
+ /**
2723
+ * 路径 token 的 basename:去掉尾部 `/`/`\`,取最后一个非空段(Windows/POSIX/file URL 通用)。
2724
+ */
2725
+ function ptcBasenameOfPathToken(token) {
2726
+ const clean = String(token).replace(/[\\/]+$/, "");
2727
+ const segments = clean.split(/[\\/]+/).filter((segment) => segment !== "" && segment !== "file:");
2728
+ return segments[segments.length - 1];
2729
+ }
2730
+
2731
+ /**
2732
+ * L2-1/L2-7:PTC summary 自由文本(command/description)的主机路径脱敏。
2733
+ * - 先保护 `http(s)://` URL(URL 不是主机路径,原样保留);
2734
+ * - 已知根前缀(cwd / cwd realpath / homedir,先长后短)→ `.` / `~`;
2735
+ * - 引用段 `"..."`/`'...'`:内容为绝对路径(POSIX/Windows/file://)→ 整体 `…/<basename>`,
2736
+ * 保留引号;引用段内是 URL 或非路径内容则原样;
2737
+ * - 剩余绝对路径 token(含反斜杠转义空格,如 `/home/a\ b/c`)→ `…/<basename>`;
2738
+ * - 结构字段 filePath/workdir/path 已由 mobileDisplayPath 派生,不经此函数。
2739
+ */
2740
+ function ptcScrubPathsOf(value, cwd) {
2741
+ if (typeof value !== "string" || value === "") return value;
2742
+ const urls = [];
2743
+ let text = value.replace(PTC_SCRUB_URL_PATTERN, (match) => {
2744
+ const token = `\u0000PTcurl${urls.length}\u0000`;
2745
+ urls.push(match);
2746
+ return token;
2747
+ });
2748
+ const home = homedir();
2749
+ const prefixes = [];
2750
+ for (const prefix of [cwd, ...(typeof cwd === "string" && cwd !== "" ? [(() => {
2751
+ try {
2752
+ return realpathSync(cwd);
2753
+ } catch {
2754
+ return undefined;
2755
+ }
2756
+ })()] : []), home]) {
2757
+ if (typeof prefix === "string" && prefix.length > 1 && prefix !== "/") prefixes.push(prefix);
2758
+ }
2759
+ prefixes.sort((a, b) => b.length - a.length);
2760
+ const seen = new Set();
2761
+ for (const prefix of prefixes) {
2762
+ if (seen.has(prefix)) continue;
2763
+ seen.add(prefix);
2764
+ const replacement = prefix === home ? "~" : ".";
2765
+ const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2766
+ // 仅替换作为路径起始出现的前缀(前一个字符不是路径字符),避免误伤子串。
2767
+ text = text.replace(
2768
+ new RegExp(`(^|[\\s"'\`(=,;:])${escaped}(?=$|[\\\\/\\s"'\`)\\]}])`, "g"),
2769
+ (_match, lead) => `${lead}${replacement}`,
2770
+ );
2771
+ }
2772
+ // L2-7:引用段整体处理(含空格的绝对路径不再被空格截断而残留层级)。
2773
+ text = text.replace(/(["'])((?:(?!\1)[\s\S])*)\1/g, (match, quote, inner) => {
2774
+ const trimmed = inner.trim();
2775
+ if (trimmed === "" || /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(trimmed)) return match; // URL/占位符/空串不动
2776
+ const absolute = /^(?:file:\/\/\/|[A-Za-z]:[\\/]|[\\/])/.test(trimmed);
2777
+ if (!absolute) return match;
2778
+ const base = ptcBasenameOfPathToken(trimmed);
2779
+ return base === undefined || base === "" ? match : `${quote}…/${base}${quote}`;
2780
+ });
2781
+ // 剩余绝对路径 token:允许反斜杠转义空格(`\ `),按整体取 basename,不保留主机层级。
2782
+ text = text.replace(
2783
+ /(?:file:\/\/\/(?:[^\s"'`)\],;\\]|\\.)+)|(?<![A-Za-z0-9_…])[A-Za-z]:[\\/](?:[^\s"'`)\],;\\]|\\.)+|(?<![\w.~…])[/](?:[^\s"'`)\],;\\]|\\.)+/g,
2784
+ (match) => {
2785
+ const base = ptcBasenameOfPathToken(match);
2786
+ return base === undefined || base === "" ? match : `…/${base}`;
2787
+ },
2788
+ );
2789
+ return text.replace(/\u0000PTcurl(\d+)\u0000/g, (_match, index) => urls[Number(index)]);
2790
+ }
2791
+
2792
+ /**
2793
+ * 50 子调用预算(issue #68 契约 §1.6):`/history` 每响应一个、SSE 每会话一个。
2794
+ * `roots` 按 rootCallId 分组(缺省根用空串),组内 `seen` 按 callId 去重计数。
2795
+ * 同一 callId 的 start/result 共享 1 个名额;预算不持久化,也不是新事实源。
2796
+ * @returns {{roots: Map<string, {seen: Set<string>, noticeSent: boolean}>}}
2797
+ */
2798
+ export function createPtcBudget() {
2799
+ return { roots: new Map() };
2800
+ }
2801
+
2802
+ /**
2803
+ * 50 上限 gate(issue #68 契约 §1.6):`"full"` 正常投影;`"notice"` 超限时每个
2804
+ * 计数作用域只发一条最小截断信号;`"drop"` 其余超限事件只留 `{seq,type}`。
2805
+ * 无 budget(纯函数测试模式)永不截断。
2806
+ * @param {{roots: Map}|undefined} budget
2807
+ * @param {unknown} data 原始 PTC 事件 data。
2808
+ * @returns {"full" | "notice" | "drop"}
2809
+ */
2810
+ export function ptcGateOf(budget, data) {
2811
+ if (!budget || !(budget.roots instanceof Map)) return "full";
2812
+ const callId = data?.subCallId;
2813
+ // 非法 id 在 ptcProjectionOf 已整条降级;这里不计数,避免坏数据污染预算。
2814
+ if (typeof callId !== "string" || callId === "") return "full";
2815
+ const rootKey = ptcIdOf(data?.rootCallId) ?? "";
2816
+ let state = budget.roots.get(rootKey);
2817
+ if (state === undefined) {
2818
+ state = { seen: new Set(), noticeSent: false };
2819
+ budget.roots.set(rootKey, state);
2820
+ // L2-5:有界 FIFO——按插入序逐出最旧 root,不做触碰刷新,仅作内存上界。
2821
+ if (budget.roots.size > 1000) budget.roots.delete(budget.roots.keys().next().value);
2822
+ }
2823
+ if (state.seen.has(callId)) return "full";
2824
+ if (state.seen.size < PTC_MAX_SUBCALLS) {
2825
+ state.seen.add(callId);
2826
+ return "full";
2827
+ }
2828
+ if (!state.noticeSent) {
2829
+ state.noticeSent = true;
2830
+ return "notice";
2831
+ }
2832
+ return "drop";
2833
+ }
2834
+
2835
+ /**
2836
+ * PTC 子调用的折叠行摘要(issue #68 契约 §1.4):复用 `toolCallSummaryOf` 的安全
2837
+ * display 摘要(路径已由 `mobileDisplayPath` 派生,绝不下发绝对路径),按 App
2838
+ * 折叠行白名单裁剪后限制 2KiB;超预算整份降级为 `{kind, tool}`,绝不抛错。
2839
+ * 明确丢弃仅为二级详情设计的 `diff`/`diffTruncated`/`relative`/`previewable`。
2840
+ */
2841
+ function ptcSummaryOf(name, rawArguments, cwd) {
2842
+ const full = toolCallSummaryOf(name, rawArguments, cwd);
2843
+ if (full === undefined) return undefined;
2844
+ const compact = { kind: full.kind, tool: full.tool };
2845
+ const whitelist = {
2846
+ command: ["command", "workdir", "background", "description"],
2847
+ file: ["filePath", "offset", "limit", "sizeKb", "added", "deleted"],
2848
+ search: ["pattern", "path", "include"],
2849
+ web: ["url", "query"],
2850
+ image: ["filePath"],
2851
+ todo: ["items", "counts"],
2852
+ question: ["questions"],
2853
+ skill: ["name"],
2854
+ }[full.kind];
2855
+ for (const key of whitelist ?? []) {
2856
+ if (full[key] !== undefined) compact[key] = full[key];
2857
+ }
2858
+ // L2-1:command/description 是自由文本(可能夹带主机绝对路径),PTC 专属脱敏;
2859
+ // 结构字段 filePath/workdir/path 已由 mobileDisplayPath 派生,不在此重复处理。
2860
+ for (const key of ["command", "description"]) {
2861
+ if (typeof compact[key] === "string") compact[key] = ptcScrubPathsOf(compact[key], cwd);
2862
+ }
2863
+ let bytes;
2864
+ try {
2865
+ bytes = Buffer.byteLength(JSON.stringify(compact), "utf8");
2866
+ } catch {
2867
+ bytes = Number.POSITIVE_INFINITY;
2868
+ }
2869
+ return bytes <= PTC_MAX_SUMMARY_BYTES ? compact : { kind: full.kind, tool: full.tool };
2870
+ }
2871
+
2872
+ /**
2873
+ * 失败子调用的安全 `text`(issue #68 契约 §1.5,lead 裁定 L1):
2874
+ * **只**取安全错误码 —— `error.code` 优先、缺失时 `error.name`,各自 clamp ≤120;
2875
+ * **绝不**使用 `content`/`arguments`/`meta`/`error.reason`(真实夹具的失败 content
2876
+ * 含绝对工作目录路径)。两人都缺 → 省略 text。
2877
+ */
2878
+ function ptcFailureTextOf(data) {
2879
+ const error = data?.error;
2880
+ const err = error !== null && typeof error === "object" && !Array.isArray(error) ? error : undefined;
2881
+ const raw = ptcSafeCodeOf(err?.code) ?? ptcSafeCodeOf(err?.name);
2882
+ return raw === undefined ? undefined : clampText(raw, 500);
2883
+ }
2884
+
2885
+ /** PTC 失败事件的 error 白名单(issue #68 契约 §1.3/D5):只下发 name+code,无 reason。 */
2886
+ function ptcErrorOf(data) {
2887
+ const error = data?.error;
2888
+ const err = error !== null && typeof error === "object" && !Array.isArray(error) ? error : undefined;
2889
+ const name = ptcSafeCodeOf(err?.name);
2890
+ const code = ptcSafeCodeOf(err?.code);
2891
+ // L2-2:name 与 code 都必须合法才整对象下发;任一不合法(路径/注入字符)→ 省略。
2892
+ return name === undefined || code === undefined
2893
+ ? undefined
2894
+ : { name: clampText(name, 120), code: clampText(code, 120) };
2895
+ }
2896
+
2897
+ /**
2898
+ * PTC 事件的 turn/step 派生(issue #68 契约 §1.7):内核 PTC data 不带位置,
2899
+ * 由原始会话事件(含被 timeline 过滤的 `step/start`)扫描到目标 seq 为止。
2900
+ * 派生不到就省略,**禁止用 0 伪造**;App 不依赖该字段排序。
2901
+ * @param {unknown} events 原始会话事件数组。
2902
+ * @param {unknown} seq 目标事件 seq。
2903
+ * @returns {{turn?: number, step?: number}}
2904
+ */
2905
+ function ptcLocationOf(events, seq) {
2906
+ if (!Array.isArray(events) || !Number.isSafeInteger(seq)) return {};
2907
+ let turn;
2908
+ let step;
2909
+ for (const event of events) {
2910
+ if (Number.isSafeInteger(event?.seq) && event.seq > seq) break;
2911
+ if (event?.type === "turn/start" && Number.isSafeInteger(event?.data?.turn)) {
2912
+ turn = event.data.turn;
2913
+ step = undefined;
2914
+ } else if (event?.type === "step/start" && Number.isSafeInteger(event?.data?.step)) {
2915
+ step = event.data.step;
2916
+ }
2917
+ }
2918
+ return {
2919
+ ...(turn === undefined || turn < 1 ? {} : { turn }),
2920
+ ...(step === undefined || step < 0 ? {} : { step }),
2921
+ };
2922
+ }
2923
+
2924
+ /**
2925
+ * PTC 子调用事件投影(issue #68 契约 §1.3):start → `status:"running"`,
2926
+ * result → `status:"success"|"failed"` + `isError`;同一 `callId` 原地更新由 App 负责。
2927
+ * - `summary` 来自本事件自己的 `arguments`(安全 display,≤2KiB);
2928
+ * - `text` **仅失败结果**、只含安全错误码(L1);
2929
+ * - 永不下发 `arguments` 原文 / `meta` / `content` / `images` / `error.reason`;
2930
+ * - id 缺失/非法 → `{seq,type}`(事件仍在,无 data);50 超限见 ptcGateOf。
2931
+ * @param {{seq:unknown, type:string, data:unknown}} event
2932
+ * @param {{cwd?:unknown, turn?:unknown, step?:unknown, ptcBudget?:unknown}} options
2933
+ * @returns {{seq: unknown, type: string, data?: object}}
2934
+ */
2935
+ function ptcProjectionOf(event, options = {}) {
2936
+ const { seq, type } = event;
2937
+ const data = event.data;
2938
+ if (data === null || typeof data !== "object" || Array.isArray(data)) return { seq, type };
2939
+ const callId = ptcIdOf(data.subCallId);
2940
+ const parentCallId = ptcIdOf(data.parentCallId);
2941
+ if (callId === undefined || parentCallId === undefined) return { seq, type };
2942
+ const isStart = type === "tool/ptc-dispatch-start";
2943
+ const isError = isStart ? false : data.isError === true;
2944
+ const status = isStart ? "running" : isError ? "failed" : "success";
2945
+ const gate = ptcGateOf(options.ptcBudget, data);
2946
+ if (gate === "drop") return { seq, type };
2947
+ const rootCallId = ptcIdOf(data.rootCallId);
2948
+ const name = typeof data.name === "string" && data.name.trim() !== "" ? clampText(data.name, 120) : undefined;
2949
+ const turn = Number.isSafeInteger(options.turn) && options.turn >= 1 ? options.turn : undefined;
2950
+ const step = Number.isSafeInteger(options.step) && options.step >= 0 ? options.step : undefined;
2951
+ const base = {
2952
+ ...(turn === undefined ? {} : { turn }),
2953
+ ...(step === undefined ? {} : { step }),
2954
+ ...(rootCallId === undefined ? {} : { rootCallId }),
2955
+ parentCallId,
2956
+ callId,
2957
+ ...(name === undefined ? {} : { name }),
2958
+ status,
2959
+ };
2960
+ // L2-3:截断通知单独构造,**不展开**含 turn/step 的 base;
2961
+ // 只保留 rootCallId?/parentCallId/callId/name?/status + truncated。
2962
+ if (gate === "notice") {
2963
+ return {
2964
+ seq,
2965
+ type,
2966
+ data: {
2967
+ ...(rootCallId === undefined ? {} : { rootCallId }),
2968
+ parentCallId,
2969
+ callId,
2970
+ ...(name === undefined ? {} : { name }),
2971
+ status,
2972
+ truncated: true,
2973
+ },
2974
+ };
2975
+ }
2976
+ const summary = ptcSummaryOf(data.name, data.arguments, options.cwd);
2977
+ if (isStart) {
2978
+ return { seq, type, data: { ...base, ...(summary === undefined ? {} : { summary }) } };
2979
+ }
2980
+ const text = isError ? ptcFailureTextOf(data) : undefined;
2981
+ const error = isError ? ptcErrorOf(data) : undefined;
2982
+ return {
2983
+ seq,
2984
+ type,
2985
+ data: {
2986
+ ...base,
2987
+ ...(summary === undefined ? {} : { summary }),
2988
+ ...(text === undefined || text === "" ? {} : { text }),
2989
+ isError,
2990
+ ...(error === undefined ? {} : { error }),
2991
+ },
2992
+ };
2993
+ }
2994
+
2995
+ /**
2996
+ * 宿主的命令终止 trailer:`[exit code: N]` / `[killed by signal: X]` / `[stopped: …]`。
2997
+ *
2998
+ * issue #60 R13:这些标记由 bash/pwsh 在结果**末尾**追加;stdout 正文可能碰巧包含同样的
2999
+ * 字符串。因此只接受**最后一条**且其后仅剩空白(换行)的标记;signal/stopped/exit 三者
3000
+ * 互斥,按宿主追加顺序取最后一条(signal 优先于 stopped,二者都优先于 exit)。
3001
+ * @param {string} text 未 clamp 的结果文本。
3002
+ * @returns {{kind: "exit", exitCode: number} | {kind: "signal", signal: string} | {kind: "stopped", stopped: string} | null}
3003
+ */
3004
+ function terminalTrailerOf(text) {
3005
+ if (typeof text !== "string" || text === "") return null;
3006
+ const pattern = /\[(exit code: (-?\d+)|killed by signal: ([^\]\n]+)|stopped: ([^\]\n]+))\]/g;
3007
+ let last = null;
3008
+ let match;
3009
+ while ((match = pattern.exec(text)) !== null) last = match;
3010
+ if (last === null) return null;
3011
+ // marker 必须位于结果末尾(允许尾随空白/换行);正文中间的类似文本一律不算。
3012
+ if (text.slice(last.index + last[0].length).trim() !== "") return null;
3013
+ if (matchPrefixSignal(last[3])) return { kind: "signal", signal: clampText(last[3].trim(), 40) };
3014
+ if (matchPrefixStopped(last[4])) return { kind: "stopped", stopped: clampText(last[4].trim(), 120) };
3015
+ return { kind: "exit", exitCode: Number(last[2]) };
3016
+ }
3017
+
3018
+ const matchPrefixSignal = (value) => typeof value === "string" && value !== "";
3019
+ const matchPrefixStopped = (value) => typeof value === "string" && value !== "";
3020
+
3021
+ /**
3022
+ * `tool/result` 的结构化摘要(issue #54 §3):只从结果**文本标记**与宿主 `meta` 解析,
3023
+ * 解析不到就缺省(不猜)。exit/signal 标记只由 bash/pwsh 输出;grep/glob 的匹配总数优先
3024
+ * 取 `meta.total`(宿主 presentationMeta),缺失时按结果文本的稳定句式解析。
3025
+ * @param {unknown} toolName 工具名(可为空:结果事件常不带名字)。
3026
+ * @param {unknown} rawResultText 未 clamp 的结果文本。
3027
+ * @param {unknown} meta 宿主 tool/result 的 presentationMeta(不透传给 App)。
3028
+ * @returns {object|undefined}
3029
+ */
3030
+ export function toolResultSummaryOf(toolName, rawResultText, meta) {
3031
+ const summary = {};
3032
+ const text = typeof rawResultText === "string" ? rawResultText : "";
3033
+ const tool = typeof toolName === "string" ? toolName : "";
3034
+ // issue #60 R14:终止状态只对**已确定是 bash/pwsh** 的结果下发;无工具名时不得从内容猜
3035
+ // (调用方应按 callId→tool/call.name 关联后再传 resolvedToolName)。
3036
+ if (tool === "bash" || tool === "pwsh") {
3037
+ // issue #60 R13:只认宿主在**结果末尾**追加的终止 trailer,且取最后一条;
3038
+ // stdout 里碰巧出现的 `[exit code: N]` 不得覆盖真实终止状态。
3039
+ const trailer = terminalTrailerOf(text);
3040
+ if (trailer?.kind === "exit") summary.exitCode = trailer.exitCode;
3041
+ else if (trailer?.kind === "signal") summary.signal = trailer.signal;
3042
+ else if (trailer?.kind === "stopped") summary.stopped = trailer.stopped;
3043
+ }
3044
+ // issue #66(契约 §1.3):只有确定是 ask_user_question 才回放 answers;结果文本缺失/
3045
+ // 非 JSON/pending 形状一律缺省,绝不从文本猜(名字由调用方按 callId→name 解析后传入)。
3046
+ if (tool === "ask_user_question") {
3047
+ const answers = answerSummaryOf(text);
3048
+ if (answers !== undefined) summary.answers = answers;
3049
+ }
3050
+ const metaShape = meta && typeof meta === "object" ? meta.shape : undefined;
3051
+ const searchShaped = metaShape === "matches" || metaShape === "paths";
3052
+ const searchTool = tool === "grep" || tool === "glob";
3053
+ if (searchShaped || searchTool || tool === "") {
3054
+ const metaTotal = meta && typeof meta === "object" && Number.isSafeInteger(meta.total) ? meta.total : undefined;
3055
+ if (metaTotal !== undefined && metaTotal >= 0) {
3056
+ summary.resultCount = metaTotal;
3057
+ } else if (searchTool || searchShaped || tool === "") {
3058
+ const count = parseSearchResultCount(text, tool);
3059
+ if (count !== undefined) summary.resultCount = count;
3060
+ }
3061
+ }
3062
+ return Object.keys(summary).length > 0 ? summary : undefined;
3063
+ }
3064
+
3065
+ /**
3066
+ * `ask_user_question` 结果文本 → `answers` 只读回放(issue #66 契约 §1.3)。
3067
+ *
3068
+ * 宿主 `render` 把结果 value 原样 `JSON.stringify`:成功批次是
3069
+ * `{answers:[{id,selected,custom?}]}`,超时 pending 是 `{pending:true,callId,message}`。
3070
+ * 只认 JSON 对象里的 `answers` 数组;无效 answer 项(缺/空 id)逐项丢弃,
3071
+ * 最终没有有效项或形状不符时返回 undefined(调用方缺省,不猜)。
3072
+ * @param {string} text 未 clamp 的结果文本。
3073
+ * @returns {{questionId: string, values: string[]}[]|undefined}
3074
+ */
3075
+ function answerSummaryOf(text) {
3076
+ let parsed;
3077
+ try {
3078
+ parsed = JSON.parse(text);
3079
+ } catch {
3080
+ return undefined;
3081
+ }
3082
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Array.isArray(parsed.answers)) return undefined;
3083
+ const answers = [];
3084
+ for (const raw of parsed.answers) {
3085
+ if (answers.length >= TOOL_CARD_MAX_ANSWER_ITEMS) break;
3086
+ if (!raw || typeof raw !== "object") continue;
3087
+ // questionId 是 App 关联「这道题答了什么」的唯一键;缺失/空白的项无法回放,丢弃。
3088
+ if (typeof raw.id !== "string" || raw.id.trim() === "") continue;
3089
+ const values = [];
3090
+ if (Array.isArray(raw.selected)) {
3091
+ for (const selected of raw.selected) {
3092
+ if (values.length >= TOOL_CARD_MAX_ANSWER_VALUES) break;
3093
+ if (typeof selected !== "string") continue;
3094
+ values.push(clampText(selected, TOOL_CARD_MAX_ANSWER_TEXT));
3095
+ }
3096
+ }
3097
+ // 自定义答案与选项 label 同列回放:追加在 values 末尾(自定义答案在语义上是最后一项)。
3098
+ if (values.length < TOOL_CARD_MAX_ANSWER_VALUES && typeof raw.custom === "string" && raw.custom.trim() !== "") {
3099
+ values.push(clampText(raw.custom, TOOL_CARD_MAX_ANSWER_TEXT));
3100
+ }
3101
+ answers.push({ questionId: clampText(raw.id, TOOL_CARD_MAX_QUESTION_ID), values });
3102
+ }
3103
+ return answers.length > 0 ? answers : undefined;
3104
+ }
3105
+
3106
+ /** 从 grep/glob 的结果文本解析匹配总数;解析不到返回 undefined(不猜)。 */
3107
+ function parseSearchResultCount(text, tool) {
3108
+ if (text === "") return undefined;
3109
+ const found = /(?:^|\n)Found (\d+)(?: of (\d+))? match(?:es)?(?:\n|$)/.exec(text);
3110
+ if (found) return Number(found[2] ?? found[1]);
3111
+ if (/^No matches found\b/.test(text)) return 0;
3112
+ const showing = /\(Showing \d+ of (\d+) paths/.exec(text);
3113
+ if (showing) return Number(showing[1]);
3114
+ if (/^No files found\b/.test(text)) return 0;
3115
+ // glob 在 cap 内直接输出路径列表(每行一条);仅当工具名已知且没有分页/落盘提示时计数。
3116
+ if (tool === "glob" && !text.includes("(Showing") && !text.includes("Full sorted result")) {
3117
+ const count = text.split("\n").filter((line) => line.trim() !== "").length;
3118
+ return count > 0 ? count : undefined;
3119
+ }
3120
+ return undefined;
3121
+ }
3122
+
3123
+ /**
3124
+ * 单轮轮末信号(`turn/end` 的 `tail`);无任何产出物时返回 null(字段不出现)。
3125
+ * @param {any[]} events 会话原始事件(含被移动时间线过滤的 `workspace/changes`)。
3126
+ * @param {unknown} turn 轮号。
3127
+ * @returns {{changes: boolean, presented: boolean} | null}
3128
+ */
3129
+ export function turnTailOf(events, turn) {
3130
+ if (!Number.isSafeInteger(turn) || turn < 1) return null;
3131
+ let changes = false;
3132
+ let presented = false;
3133
+ for (const event of events ?? []) {
3134
+ const eventTurn = event?.data?.turn;
3135
+ if (Number(eventTurn) !== turn) continue;
3136
+ if (event?.type === "workspace/changes") changes = true;
3137
+ else if (event?.type === "deliverables/presented" && Array.isArray(event?.data?.files) && event.data.files.length > 0) presented = true;
3138
+ }
3139
+ if (!changes && !presented) return null;
3140
+ return { changes, presented };
3141
+ }
3142
+
3143
+ /**
3144
+ * `/history` 响应增量 `turnTails`(§6.20):**单次遍历**已加载事件得出,不调用宿主服务;
3145
+ * 只包含有产出物的轮次。key 为轮号字符串。
3146
+ * @param {any[]} events 会话原始事件。
3147
+ * @returns {Record<string, {changes: boolean, presented: boolean}>}
3148
+ */
3149
+ export function turnTailsOf(events) {
3150
+ const flags = new Map();
3151
+ for (const event of events ?? []) {
3152
+ const turn = event?.data?.turn;
3153
+ if (!Number.isSafeInteger(turn) || turn < 1) continue;
3154
+ if (event?.type === "workspace/changes") {
3155
+ const tail = flags.get(turn) ?? { changes: false, presented: false };
3156
+ tail.changes = true;
3157
+ flags.set(turn, tail);
3158
+ } else if (event?.type === "deliverables/presented" && Array.isArray(event?.data?.files) && event.data.files.length > 0) {
3159
+ const tail = flags.get(turn) ?? { changes: false, presented: false };
3160
+ tail.presented = true;
3161
+ flags.set(turn, tail);
3162
+ }
3163
+ }
3164
+ const out = {};
3165
+ for (const turn of [...flags.keys()].sort((a, b) => a - b)) out[String(turn)] = flags.get(turn);
3166
+ return out;
3167
+ }
3168
+
3169
+ /**
3170
+ * 把宿主 `workspaceChanges.diff()` 的 hunks 渲染成统一 diff 文本(§6.22),供 App 的
3171
+ * `GitFileViewer` 差异模式直接消费。按**行边界**截断到体积上限,避免切断一行导致解析错位。
3172
+ * @param {any} diff 宿主返回的对比结果(text 形态)。
3173
+ * @returns {{text: string, truncated: boolean}}
3174
+ */
3175
+ export function renderUnifiedDiffText(diff, displayOverride) {
3176
+ // issue #60 R05:展示值必须由调用方用 mobileDisplayPath 重派生后传入;未传时退回
3177
+ // 宿主 display/路径的 basename,绝不把可拼接的绝对路径写进 diff 标头。
3178
+ const display = typeof displayOverride === "string" && displayOverride !== ""
3179
+ ? displayOverride
3180
+ : posixBasenameOf(diff?.path ?? diff?.display);
3181
+ const lines = [
3182
+ diff?.before === false ? "--- /dev/null" : `--- a/${display}`,
3183
+ diff?.after === false ? "+++ /dev/null" : `+++ b/${display}`,
3184
+ ];
3185
+ for (const hunk of Array.isArray(diff?.hunks) ? diff.hunks : []) {
3186
+ if (!hunk) continue;
3187
+ const oldStart = Number.isSafeInteger(hunk.oldStart) ? hunk.oldStart : 0;
3188
+ const oldLines = Number.isSafeInteger(hunk.oldLines) ? hunk.oldLines : 0;
3189
+ const newStart = Number.isSafeInteger(hunk.newStart) ? hunk.newStart : 0;
3190
+ const newLines = Number.isSafeInteger(hunk.newLines) ? hunk.newLines : 0;
3191
+ lines.push(`@@ -${oldStart},${oldLines} +${newStart},${newLines} @@`);
3192
+ for (const line of Array.isArray(hunk.lines) ? hunk.lines : []) lines.push(String(line));
3193
+ }
3194
+ let text = `${lines.join("\n")}\n`;
3195
+ if (Buffer.byteLength(text, "utf8") <= TURN_TAIL_DIFF_MAX_BYTES) return { text, truncated: false };
3196
+ const kept = [];
3197
+ let used = 0;
3198
+ for (const line of lines) {
3199
+ const cost = Buffer.byteLength(line, "utf8") + 1;
3200
+ if (used + cost > TURN_TAIL_DIFF_MAX_BYTES) break;
3201
+ kept.push(line);
3202
+ used += cost;
3203
+ }
3204
+ return { text: kept.length ? `${kept.join("\n")}\n` : "", truncated: true };
3205
+ }
3206
+
3207
+ /**
3208
+ * 事件时间戳(issue #52,docs/03-api.md §6.20):只接受 SessionEvent.time 里
3209
+ * **有限非负数字**的 Unix 毫秒值,其余(缺失/字符串/NaN/负数)一律不下发——
3210
+ * App 不得用本地接收时间推算耗时,因此宁缺毋滥。
3211
+ */
3212
+ function eventTimeOf(event) {
3213
+ const time = event?.time;
3214
+ return typeof time === "number" && Number.isSafeInteger(time) && time >= 0 ? time : undefined;
3215
+ }
3216
+
1671
3217
  /**
1672
3218
  * 把 SessionEvent 转成移动端摘要(docs/03-api.md §3.6)。
1673
- * 返回 { seq, type, data?, detail? };未识别类型保留 type/seq,详情按需读取。
3219
+ * 返回 { seq, type, time?, data?, detail? };未识别类型保留 type/seq,详情按需读取。
3220
+ * v3.3(issue #52):顶层 `time` 为所有时间线事件摘要的增量字段(只增不改),
3221
+ * 供 App 计算轮次/过程组用时;旧字段形状不变。
1674
3222
  */
1675
- function summarizeEventCore(event) {
3223
+ function summarizeEventCore(event, options = {}) {
3224
+ const summary = summarizeEventCoreBody(event, options);
3225
+ const time = eventTimeOf(event);
3226
+ return time === undefined ? summary : { ...summary, time };
3227
+ }
3228
+
3229
+ /** summarizeEventCore 的原有逐类型摘要实现(issue #52 起由上面的包装补顶层 time)。 */
3230
+ function summarizeEventCoreBody(event, options = {}) {
1676
3231
  const { seq, type, data } = event;
1677
3232
  // review:内核实参可能缺 data(防御,避免 TypeError 打崩事件发射器)
1678
3233
  if (data === undefined) return { seq, type };
@@ -1751,7 +3306,21 @@ function summarizeEventCore(event) {
1751
3306
  if (typeof argumentsText !== "string") {
1752
3307
  try { argumentsText = JSON.stringify(argumentsText ?? {}); } catch { argumentsText = String(argumentsText ?? ""); }
1753
3308
  }
1754
- return { seq, type, data: { turn: data.turn, step: data.step, callId: data.callId, name: data.name, arguments: clampText(argumentsText, 2000) } };
3309
+ // issue #54:summary 从**原始** arguments 解析(先解析后 clamp);解析失败只降级,
3310
+ // 绝不让摘要/历史/SSE 抛错。
3311
+ const summary = toolCallSummaryOf(data.name, data.arguments, options.cwd);
3312
+ return {
3313
+ seq,
3314
+ type,
3315
+ data: {
3316
+ turn: data.turn,
3317
+ step: data.step,
3318
+ callId: data.callId,
3319
+ name: data.name,
3320
+ arguments: clampText(argumentsText, 2000),
3321
+ ...(summary === undefined ? {} : { summary }),
3322
+ },
3323
+ };
1755
3324
  }
1756
3325
  case "tool/result": {
1757
3326
  // v3.0.0(版本二):对齐 PC contentParts 语义——content 为 tool-result 块数组,
@@ -1759,7 +3328,9 @@ function summarizeEventCore(event) {
1759
3328
  const message = data.message;
1760
3329
  const blocks = Array.isArray(message?.content) ? message.content : [];
1761
3330
  // 兼容旧宿主/测试夹具直接提供的 { callId, name, text, isError } wire 形态。
1762
- let callId = typeof data.callId === "string" ? data.callId : typeof data.toolCallId === "string" ? data.toolCallId : "";
3331
+ // issue #60 recheck-4:真实结果形状的 callId 在 message.source.callId /
3332
+ // message.toolCallId / content[].toolCallId,不在 event.data.callId。
3333
+ let callId = toolResultCallIdOf(event);
1763
3334
  let isError = data.error !== undefined || data.isError === true;
1764
3335
  let text = typeof data.text === "string" ? data.text : "";
1765
3336
  const images = Array.isArray(data.images)
@@ -1781,6 +3352,12 @@ function summarizeEventCore(event) {
1781
3352
  // 学到的真名,于是已结束的工具卡标题变成裸 `call_00_...`(进行中的那张正常)。
1782
3353
  // 名字未知就不下发该字段,由消费端自行兜底显示「工具」。
1783
3354
  const resultName = directName || errName;
3355
+ // issue #54:结果摘要从**未 clamp 的原始文本**与宿主 meta 解析(exit/signal 标记
3356
+ // 通常在输出末尾,clamp 后可能被截掉;meta 只用来取匹配总数,不透传)。
3357
+ // issue #60 R14:结果事件常不带工具名;调用方通过 callId→tool/call.name 解析出
3358
+ // resolvedToolName 后再传进来,只有确定是 bash/pwsh 时才下发命令终止状态。
3359
+ const resolvedToolName = typeof options.resolvedToolName === "string" ? options.resolvedToolName : resultName;
3360
+ const resultSummary = toolResultSummaryOf(resolvedToolName, text, data.meta);
1784
3361
  return {
1785
3362
  seq,
1786
3363
  type,
@@ -1791,10 +3368,18 @@ function summarizeEventCore(event) {
1791
3368
  ...(resultName ? { name: resultName } : {}),
1792
3369
  isError,
1793
3370
  text: clampText(text, 2000),
3371
+ ...(resultSummary === undefined ? {} : { summary: resultSummary }),
1794
3372
  ...(images.length ? { images: images.slice(0, 20) } : {}),
1795
3373
  },
1796
3374
  };
1797
3375
  }
3376
+ case "tool/ptc-dispatch-start":
3377
+ case "tool/ptc-dispatch": {
3378
+ // issue #68(M3 Batch 2-C):PTC 子调用结构化投影。start → running,
3379
+ // result → success/failed;`callId` 来自内核 `subCallId`,`arguments`
3380
+ // 原文/`meta`/`content`/`error.reason` 永不下发(安全见投影 helper)。
3381
+ return ptcProjectionOf(event, options);
3382
+ }
1798
3383
  case "todo/write": {
1799
3384
  // v3.1.4(issue #12 姊妹需求):内核 dsh-tool-todo 每次调用写入**整份清单快照**
1800
3385
  // ({ todos: [{ content, status }] },status ∈ pending / in_progress / completed)。
@@ -1815,6 +3400,39 @@ function summarizeEventCore(event) {
1815
3400
  return { seq, type, data: { turn: data.turn } };
1816
3401
  case "turn/end":
1817
3402
  return { seq, type, data: { turn: data.turn, reason: data.reason } };
3403
+ case "deliverables/presented": {
3404
+ // issue #53(§6.20):交付文件声明只下发 name/display/description,**不下发主机
3405
+ // 绝对路径**;display 由本插件按会话工作目录派生(cwd 是宿主事实,随摘要上下文传入)。
3406
+ const files = Array.isArray(data.files) ? data.files : [];
3407
+ const cwd = options.cwd;
3408
+ const mapped = [];
3409
+ for (const file of files.slice(0, TURN_TAIL_MAX_FILES)) {
3410
+ const path = typeof file?.path === "string" ? file.path : "";
3411
+ if (path === "") continue;
3412
+ // issue #60 R08:服务端 display 是**脱敏后的展示值**,不同目录的同名文件会
3413
+ // 得到相同 display;再下发一个不泄路径的稳定身份(路径摘要)供 App 去重。
3414
+ // 该 id 不含可逆路径/主机前缀,只用于同一轮内跨 present 事件的同一文件合并。
3415
+ const identity = recordFileId(path, cwd);
3416
+ const entry = {
3417
+ id: identity,
3418
+ name: posixBasenameOf(path),
3419
+ display: mobileDisplayPath(path, cwd),
3420
+ };
3421
+ if (typeof file.description === "string" && file.description.trim() !== "") entry.description = clampText(file.description, 200);
3422
+ mapped.push(entry);
3423
+ }
3424
+ const turn = Number.isSafeInteger(data.turn) && data.turn >= 1 ? data.turn : undefined;
3425
+ const callId = typeof data.callId === "string" && data.callId !== "" ? data.callId : undefined;
3426
+ return {
3427
+ seq,
3428
+ type,
3429
+ data: {
3430
+ ...(turn === undefined ? {} : { turn }),
3431
+ ...(callId === undefined ? {} : { callId }),
3432
+ files: mapped,
3433
+ },
3434
+ };
3435
+ }
1818
3436
  default:
1819
3437
  return { seq, type };
1820
3438
  }
@@ -1852,11 +3470,84 @@ export function detailEventFor(event) {
1852
3470
  }
1853
3471
 
1854
3472
  /**
1855
- * 移动端事件摘要:保留轻量 data,同时声明可通过 seq 读取无损详情。
1856
- * 老客户端只会忽略新增的 detail 字段,保持向后兼容。
3473
+ * issue #99:把 surface 投影 envelope 的只读字段透传给移动端。
3474
+ *
3475
+ * DSH 的真实 surface 形状是 union(以 session 22226918 实测与内核落盘为准):
3476
+ * - `surfaceOp: "append"`(字符串,真实事件常见;可带 sourceEventSeqs);
3477
+ * - `surfaceOp: { op: "replace"|"append", startSeq, endSeq }`(对象;replace 必带
3478
+ * start/end,append 可省略 start/end)。
3479
+ * App 侧只有 **对象 replace** 触发 shadow;字符串/对象 append 只是投影元数据,
3480
+ * 不遮蔽 source 事件,且 sourceEventSeqs 不得丢弃。
3481
+ *
3482
+ * 输出形状(向后兼容、文档化):
3483
+ * - 输入字符串 append → 输出保持字符串 `"append"`;
3484
+ * - 输入对象 → 输出规范化对象 `{op:"replace"|"append", (startSeq,endSeq)?}`;
3485
+ * - 非法/未知字符串或对象字段 → **整组 envelope 字段丢弃**,绝不猜测。
3486
+ *
3487
+ * 严格校验(复审 P2):start/end 仅接受非负 safe integer(不做 Number() 强转);
3488
+ * replace 要求 startSeq<=endSeq;sourceEventSeqs 每一项严格小于当前事件 seq、
3489
+ * 去重后正序、最多 64 项。任一非法 → 整个 envelope 无输出。
1857
3490
  */
1858
- export function summarizeEvent(event) {
1859
- const summary = summarizeEventCore(event);
3491
+ const isSafeSeq = (value) =>
3492
+ typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
3493
+
3494
+ /** 规范化 surfaceOp;返回 undefined=非法/缺失(调用方整组丢弃)。 */
3495
+ function normalizeSurfaceOp(raw) {
3496
+ if (typeof raw === "string") {
3497
+ return raw === "append" ? "append" : undefined;
3498
+ }
3499
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
3500
+ if (raw.op !== "replace" && raw.op !== "append") return undefined;
3501
+ if (raw.op === "replace") {
3502
+ if (!isSafeSeq(raw.startSeq) || !isSafeSeq(raw.endSeq)) return undefined;
3503
+ if (raw.startSeq > raw.endSeq) return undefined;
3504
+ return { op: "replace", startSeq: raw.startSeq, endSeq: raw.endSeq };
3505
+ }
3506
+ // append:start/end 可整体省略;若出现则必须同时存在且合法有序。
3507
+ const hasStart = raw.startSeq !== undefined;
3508
+ const hasEnd = raw.endSeq !== undefined;
3509
+ if (!hasStart && !hasEnd) return { op: "append" };
3510
+ if (!hasStart || !hasEnd || !isSafeSeq(raw.startSeq) || !isSafeSeq(raw.endSeq)) {
3511
+ return undefined;
3512
+ }
3513
+ if (raw.startSeq > raw.endSeq) return undefined;
3514
+ return { op: "append", startSeq: raw.startSeq, endSeq: raw.endSeq };
3515
+ }
3516
+
3517
+ export function surfaceWireFields(event) {
3518
+ const hasSurfaceOp = event?.surfaceOp !== undefined;
3519
+ const hasSources = event?.sourceEventSeqs !== undefined;
3520
+ if (!hasSurfaceOp && !hasSources) return {};
3521
+ const fields = {};
3522
+ if (hasSurfaceOp) {
3523
+ const surfaceOp = normalizeSurfaceOp(event.surfaceOp);
3524
+ if (surfaceOp === undefined) return {};
3525
+ fields.surfaceOp = surfaceOp;
3526
+ }
3527
+ if (hasSources) {
3528
+ const source = event.sourceEventSeqs;
3529
+ const currentSeq = event.seq;
3530
+ if (!Array.isArray(source) || source.length === 0 || source.length > 64) return {};
3531
+ if (!isSafeSeq(currentSeq)) return {};
3532
+ const unique = [];
3533
+ const seen = new Set();
3534
+ for (const value of source) {
3535
+ if (!isSafeSeq(value) || value >= currentSeq) return {};
3536
+ if (seen.has(value)) continue;
3537
+ seen.add(value);
3538
+ unique.push(value);
3539
+ }
3540
+ if (unique.length === 0 || unique.length > 64) return {};
3541
+ unique.sort((a, b) => a - b);
3542
+ fields.sourceEventSeqs = unique;
3543
+ }
3544
+ return fields;
3545
+ }
3546
+
3547
+ export function summarizeEvent(event, options = {}) {
3548
+ const base = summarizeEventCore(event, options);
3549
+ const wire = surfaceWireFields(event);
3550
+ const summary = Object.keys(wire).length > 0 ? { ...base, ...wire } : base;
1860
3551
  if (event?.seq === undefined || event?.seq === null) return summary;
1861
3552
  // 只对详情端点真的能取回的事件声明指针:token delta / 内部记录会被 /event-detail
1862
3553
  // 拒绝(isTimelineRecord),未列入 allow-list 的类型同样会被拒(fail-closed)。
@@ -2237,6 +3928,36 @@ export const requestAbort = (res) => {
2237
3928
  return ac.signal;
2238
3929
  };
2239
3930
 
3931
+ /**
3932
+ * 首个 root agent(无 root 时退回任意 agent)。
3933
+ *
3934
+ * issue #112:DSH 0.2.2-rc.2 的 AgentRegistry 移除了 roots。旧实现直接
3935
+ * 调用 roots 属性会在 rc.2 下抛 TypeError,导致 /catalog 500、diagnostics
3936
+ * modelsRpc=false。这里按能力探测:roots 是函数才调用;空/抛错/缺失都退回 list;
3937
+ * 两者都不可用返回 undefined,绝不向上抛。
3938
+ */
3939
+ export function firstAgent(agents) {
3940
+ if (!agents || (typeof agents !== "object" && typeof agents !== "function")) return undefined;
3941
+ const rootsOf = agents["roots"];
3942
+ if (typeof rootsOf === "function") {
3943
+ try {
3944
+ const roots = rootsOf.call(agents);
3945
+ if (Array.isArray(roots) && roots.length > 0) return roots[0];
3946
+ } catch {
3947
+ // rc.2 / 旧宿主异常:继续走 list fallback
3948
+ }
3949
+ }
3950
+ if (typeof agents.list === "function") {
3951
+ try {
3952
+ const list = agents.list();
3953
+ if (Array.isArray(list) && list.length > 0) return list[0];
3954
+ } catch {
3955
+ // 无可用 agent
3956
+ }
3957
+ }
3958
+ return undefined;
3959
+ }
3960
+
2240
3961
  /** 插件主体。 */
2241
3962
  export function apply(ctx, config, runtime = {}) {
2242
3963
  const basePath = config.path;
@@ -2250,6 +3971,8 @@ export function apply(ctx, config, runtime = {}) {
2250
3971
  ? { token: String(runtime.authToken.token ?? ""), source: String(runtime.authToken.source ?? "runtime") }
2251
3972
  : resolvePluginAuthToken({ home: homedir(), configured: config.authToken });
2252
3973
  const authToken = authTokenState.token;
3974
+ // 不能把临时 UUID 宣告为稳定身份:身份不可用时阻止插件启动,保留现场供人工恢复。
3975
+ const hostIdentity = resolveHostIdentity();
2253
3976
  const authEnabled = authToken !== "";
2254
3977
  const authGenerated = authTokenState.source === "generated";
2255
3978
  // ── LAN 桥三态(#36 S1)配置归一(bootstrap/qr-config/diagnostics 在请求期读这些)──
@@ -2321,30 +4044,71 @@ export function apply(ctx, config, runtime = {}) {
2321
4044
  const pluginUpdateStatus = { state: "unknown", reason: "not-checked" };
2322
4045
  // 是否由 systemd 托管:决定"终止宿主后有没有人把它拉起来"。INVOCATION_ID 只有服务单元里才有。
2323
4046
  const systemdManaged = () => existsSync("/run/systemd/system") && Boolean(process.env.INVOCATION_ID);
2324
- const restartFormOf = runtime.pluginUpdates?.restartForm ?? (() => detectRestartForm({ hasSystemdUnit: systemdManaged }));
4047
+ // 前台 web 形态的重启必须复用**本进程原命令行**:容器/自定义启动常见 `dsh web --port 3082`,
4048
+ // 拼一个默认的 `dsh web --profile web` 会丢掉端口等参数(重启后监听面就变了)。
4049
+ const respawnCommand = respawnCommandOf(process.argv);
4050
+ const restartFormOf = runtime.pluginUpdates?.restartForm
4051
+ ?? (() => detectRestartForm({ hasSystemdUnit: systemdManaged, commandLine: process.argv }));
2325
4052
  const restartContext = () => ({
2326
4053
  plan: restartPlan({
2327
4054
  form: restartFormOf(),
2328
4055
  pid: process.pid,
2329
4056
  profile: process.env.DSH_PROFILE || "web",
4057
+ respawnCommand,
2330
4058
  }),
2331
4059
  pid: process.pid,
2332
4060
  });
2333
4061
  // 监督器是否还在照看(用锁的持有者进程是否存活判断)
2334
- const supervisorAlive = () => {
2335
- const holder = readLock(pluginUpdateLockFile);
2336
- return Boolean(holder && holder.pid && defaultIsPidAlive(holder.pid));
2337
- };
4062
+ const supervisorAlive = () => lockHolderAlive(pluginUpdateLockFile);
2338
4063
  {
2339
4064
  // 事务报告(**只读**):回滚由外部监督器负责,不再依赖新版插件能否加载(评审 R1)。
2340
4065
  // 这里只处理"监督器已消失且明显超时"的收敛,避免手机永久等待。
4066
+ const holderAlive = supervisorAlive();
2341
4067
  const reported = reportPendingUpdate({
2342
4068
  stateFile: pluginUpdateStateFile,
2343
4069
  lockPath: pluginUpdateLockFile,
2344
4070
  localContentSha256: selfContentSha256,
2345
- supervisorAlive: supervisorAlive(),
4071
+ holderAlive,
4072
+ supervisorAlive: holderAlive,
2346
4073
  });
2347
- if (reported.action === "matched") {
4074
+ if (reported.action === "adoptable") {
4075
+ // issue #110 P1-B:当前运行内容已经是 target,且 holder 已死(按 /proc starttime)。
4076
+ // 新宿主认领并结算 restart-pending,释放 holder;保留事务里的 artifact/snapshot 元数据。
4077
+ let adopted = false;
4078
+ let lastError = null;
4079
+ for (let attempt = 0; attempt < 3 && !adopted; attempt += 1) {
4080
+ try {
4081
+ finishOwnedTerminal(pluginUpdateStateFile, {
4082
+ phase: "settled",
4083
+ result: { ok: true, matched: "loaded-target-content-adopted" },
4084
+ expectedPhases: ["restart-pending"],
4085
+ }, {
4086
+ lockPath: pluginUpdateLockFile,
4087
+ lease: reported.transaction?.lease,
4088
+ currentFile: pluginUpdateStateFile,
4089
+ });
4090
+ adopted = true;
4091
+ } catch (error) {
4092
+ lastError = error;
4093
+ }
4094
+ }
4095
+ if (adopted) {
4096
+ ctx.logger.info?.("mobile-remote: 插件自更新已由启动认领结算(loaded target content)");
4097
+ } else {
4098
+ // holder 已缺失/lease 失效时不能永久 pending:退回有界收敛(P1-C)。
4099
+ try {
4100
+ const converged = convergeStaleTransaction({
4101
+ stateFile: pluginUpdateStateFile,
4102
+ lockPath: pluginUpdateLockFile,
4103
+ localContentSha256: selfContentSha256,
4104
+ staleMs: 0,
4105
+ });
4106
+ ctx.logger.warn?.(`mobile-remote: 启动认领失败已转收敛:${converged.action}${converged.error ? `(${converged.error})` : ""}`);
4107
+ } catch (convergeError) {
4108
+ ctx.logger.warn?.(`mobile-remote: 启动认领/收敛均失败(不影响运行):${lastError?.message ?? lastError} / ${convergeError?.message ?? convergeError}`);
4109
+ }
4110
+ }
4111
+ } else if (reported.action === "matched") {
2348
4112
  ctx.logger.info?.("mobile-remote: 插件自更新已生效");
2349
4113
  } else if (reported.action === "expired") {
2350
4114
  ctx.logger.warn("mobile-remote: 插件自更新未确认生效且监督器已退出;请在电脑上确认插件状态");
@@ -2357,25 +4121,110 @@ export function apply(ctx, config, runtime = {}) {
2357
4121
  if (pluginUpdateChecked) return;
2358
4122
  pluginUpdateChecked = true;
2359
4123
  if (resolvePluginUpdateSource(config.pluginUpdateManifest).kind === UPDATE_SOURCE_KIND.OFF) return;
2360
- updates.check()
4124
+ // issue #96 review P2:bootstrap 也走共享 checkService(deadline/缓存/in-flight 去重),
4125
+ // 不再裸调 checkForUpdate;错误只落稳定 code,不把内部 message 写入公开状态。
4126
+ updates.checkSync()
2361
4127
  .then((r) => Object.assign(pluginUpdateStatus, r))
2362
- .catch((e) => Object.assign(pluginUpdateStatus, { state: "unavailable", reason: String(e?.message ?? e) }));
4128
+ .catch(() => Object.assign(pluginUpdateStatus, {
4129
+ state: "unavailable", reason: "update-check-failed", source: "npm", checkedAt: new Date().toISOString(),
4130
+ }));
2363
4131
  };
2364
4132
  // 自更新能力与降级指引:内容状态驱动"能不能一键",版本号只管文案(评审 R11)。
4133
+ //
4134
+ // 通道选择(v3.5 / DSH 0.2.2+):宿主若提供 `pluginManager.updateBundle()`,就优先
4135
+ // 委托它在**进程内**更新——不重启宿主,也不依赖我们能否重启。传统「改依赖 →
4136
+ // pnpm install → 重启 → 健康确认」通道保留给旧宿主(<0.2.2)以及宿主管理器不可用的
4137
+ // 形态。两条通道都不可用时才退回人工指引。
4138
+ const hostUpdateState = {
4139
+ // 探测结果缓存:`listBundles()` 会读 profile 清单,不必每次请求都跑一遍。
4140
+ at: 0,
4141
+ result: null,
4142
+ // 探测失败/不可用时也为 true,避免每个请求都重试。
4143
+ settled: false,
4144
+ };
4145
+ const hostUpdateCacheMs = Number.isFinite(runtime.pluginUpdates?.hostCapabilityTtlMs)
4146
+ ? runtime.pluginUpdates.hostCapabilityTtlMs
4147
+ : 30_000;
4148
+ /**
4149
+ * 探测宿主原生更新能力(同步读缓存,异步刷新)。
4150
+ *
4151
+ * 首次调用返回「尚未探测」的中性结论,同时排一次探测;下一次请求就能拿到结论。
4152
+ * 这样 bootstrap 路径不会被 `listBundles()`(可能读盘、可能等锁)拖慢。
4153
+ */
4154
+ function hostUpdateCapabilities() {
4155
+ // 测试/定制注入优先:给了结论就不再去探测(生产不传)。
4156
+ if (runtime.pluginUpdates?.hostCapabilities !== undefined) {
4157
+ return runtime.pluginUpdates.hostCapabilities;
4158
+ }
4159
+ const cached = hostUpdateState.result;
4160
+ const fresh = cached && Date.now() - hostUpdateState.at < hostUpdateCacheMs;
4161
+ if (!fresh) {
4162
+ detectHostUpdateCapabilities({
4163
+ ctx,
4164
+ packageName: pluginPackageName,
4165
+ // 探测失败一律收敛成 unavailable,绝不向上抛;结论只影响通道选择。
4166
+ }).then((r) => {
4167
+ hostUpdateState.result = r;
4168
+ hostUpdateState.at = Date.now();
4169
+ hostUpdateState.settled = true;
4170
+ return r;
4171
+ }).catch(() => {
4172
+ hostUpdateState.result = {
4173
+ packageName: pluginPackageName, managerAvailable: false, managerReason: HOST_MANAGER_REASON.PROBE_FAILED,
4174
+ hmrAvailable: false, hmrReason: "", updatable: false,
4175
+ state: HOST_MANAGER_STATE.UNSUPPORTED, channel: UPDATE_CHANNEL.GUIDANCE, installedVersion: "",
4176
+ };
4177
+ hostUpdateState.at = Date.now();
4178
+ hostUpdateState.settled = true;
4179
+ return hostUpdateState.result;
4180
+ });
4181
+ }
4182
+ return hostUpdateState.result;
4183
+ }
4184
+ /** 宿主管理器当前是否可用于本插件(探测结论 + 目标可被它更新)。 */
4185
+ function hostManagerUsable() {
4186
+ const caps = hostUpdateCapabilities();
4187
+ return Boolean(caps && caps.managerAvailable && caps.updatable);
4188
+ }
2365
4189
  function pluginUpdateCapabilities() {
2366
4190
  const form = restartFormOf();
2367
4191
  const specifier = profileSpecifierOf(pluginProfileDir, { keys: pluginDependencyKeys });
2368
4192
  const specPath = specifier.startsWith("file:") ? specifier.slice("file:".length) : "";
2369
4193
  const isGitRepo = specPath !== "" && existsSync(join(specPath, ".git"));
2370
4194
  const installShape = detectInstallShape({ specifier, dirPath: specPath, isGitRepo: () => isGitRepo });
2371
- const canSelfUpdate = Boolean(pluginProfileDir) && form !== "unsupported";
4195
+ // 「能自动完成」由**通道**决定,不再只由重启形态决定:宿主管理器可用时,
4196
+ // 即使我们判断不出重启方式(容器、无 systemd、进程无 DSH_PROFILE)也能自动更新。
4197
+ const canRestart = Boolean(pluginProfileDir) && form !== "unsupported";
4198
+ const hostCaps = hostUpdateCapabilities();
4199
+ const channel = chooseUpdateChannel({
4200
+ hostManagerAvailable: hostManagerUsable(),
4201
+ canRestart,
4202
+ });
4203
+ const canSelfUpdate = channel.channel !== UPDATE_CHANNEL.GUIDANCE;
2372
4204
  const plan = planForShape(installShape, {
2373
4205
  specifier,
2374
4206
  dirPath: specPath,
2375
4207
  canSelfUpdate,
2376
4208
  reason: canSelfUpdate ? "" : pluginProfileDir ? `restart-form-${form}` : "profile-not-found",
4209
+ channel: channel.channel,
2377
4210
  });
2378
- return { installShape, canSelfUpdate, restartForm: form, guidance: plan };
4211
+ return {
4212
+ installShape,
4213
+ canSelfUpdate,
4214
+ restartForm: form,
4215
+ guidance: plan,
4216
+ // 通道与宿主动更能力(手机/桌面据此显示「不重启更新」还是「会重启」)。
4217
+ updateChannel: channel.channel,
4218
+ updateChannelDescription: describeUpdateChannel(channel.channel),
4219
+ hostManager: hostCaps ? {
4220
+ available: Boolean(hostCaps.managerAvailable && hostCaps.updatable),
4221
+ state: hostCaps.state,
4222
+ reason: hostCaps.managerReason || "",
4223
+ hmrAvailable: Boolean(hostCaps.hmrAvailable),
4224
+ } : null,
4225
+ // 兼容旧字段语义:`canSelfUpdate` 曾经等价于「能重启」,现在由通道决定。
4226
+ canRestartHost: canRestart,
4227
+ };
2379
4228
  }
2380
4229
  /** 客户端视图参数:公开基址只取 actual endpoint 视图(W1;Host/trustedHosts 不能证明监听)。 */
2381
4230
  function clientViewFor(_req) {
@@ -2400,6 +4249,19 @@ export function apply(ctx, config, runtime = {}) {
2400
4249
  transaction: transactionSummary(view),
2401
4250
  };
2402
4251
  }
4252
+ /** issue #96:检查结果按请求方投影(不带既有事务摘要)。 */
4253
+ function publicCheckResult(req, result) {
4254
+ const view = clientViewFor(req);
4255
+ return {
4256
+ ...(result ?? {}),
4257
+ ...pluginUpdateCapabilities(),
4258
+ release: result?.release ? clientReleaseView(result.release, view) : null,
4259
+ };
4260
+ }
4261
+ const consentTtlOverride = Number(ctx.get?.("workspaceImageConsentTtlMs"));
4262
+ const imageConsentStore = createWorkspaceImageConsentStore(
4263
+ Number.isFinite(consentTtlOverride) && consentTtlOverride > 0 ? { ttlMs: consentTtlOverride } : {},
4264
+ );
2403
4265
  const updates = createPluginUpdateController({
2404
4266
  home: homedir(), configValue: config.pluginUpdateManifest, profileDir: pluginProfileDir, packageName: pluginPackageName,
2405
4267
  capabilities: pluginUpdateCapabilities, localVersion: () => pluginVersion(), localContentSha256: selfContentSha256,
@@ -2409,8 +4271,21 @@ export function apply(ctx, config, runtime = {}) {
2409
4271
  // 内部 worker 永远用**受信回环定位 + 有效口令**(自动生成的口令同样要带上,否则 401)
2410
4272
  auth: { token: authToken, trustedOrigin: `http://127.0.0.1:${ctx.webServer.port}`, basePath },
2411
4273
  workerOptions: { installedRoot: pluginRootDir, pluginRoot: pluginRootDir, needsEscape: systemdManaged(),
4274
+ // issue #110 P2:事务记录宿主原始 argv,supervisor 重启时使用(其自身 argv 不含宿主参数)。
4275
+ respawnCommand,
2412
4276
  restartForm: restartFormOf(), hostPid: process.pid, port: ctx.webServer.port, basePath,
2413
4277
  token: authToken, profile: process.env.DSH_PROFILE || "web", dshCommand: process.env.DSH_BIN || "dsh" },
4278
+ // DSH 0.2.2+:宿主原生插件管理器可用时,更新走「进程内卸载→安装」,不重启宿主。
4279
+ // 不提供该执行器的宿主(<0.2.2 或服务未挂载)自动回落到下面的重启通道。
4280
+ runHostUpdate: ({ targetVersion, installedVersion, onStep, log }) => runHostManagerUpdate({
4281
+ service: probeHostPluginManager(ctx).service,
4282
+ packageName: pluginPackageName,
4283
+ targetVersion,
4284
+ installedVersion,
4285
+ requestId: `mobile-remote-${targetVersion}`,
4286
+ onProgress: (progress) => onStep?.(progress.step === 'installing' ? 'installing' : 'staging'),
4287
+ log: { stage: (stage, message) => { onStep?.(stage); log?.(message); } },
4288
+ }),
2414
4289
  ...runtime.pluginUpdates,
2415
4290
  });
2416
4291
  // 实际监听成功才算可用(绑定失败时 QR/地址回退回环,不指向死端口)
@@ -3274,9 +5149,134 @@ export function apply(ctx, config, runtime = {}) {
3274
5149
  backfillQueued.add(id);
3275
5150
  added = true;
3276
5151
  }
3277
- if (!added) return;
3278
- pumpBackfillQueue(); // 有额度才真正开工;否则等既有任务腾出额度时自动续跑
5152
+ if (!added) return;
5153
+ pumpBackfillQueue(); // 有额度才真正开工;否则等既有任务腾出额度时自动续跑
5154
+ };
5155
+ /**
5156
+ * issue #109:默认列表过滤前的**可见性**解析(不是时间解析)。
5157
+ *
5158
+ * - 判空用 `hasVisibleConversationMessage(events)`;time 只用于排序,缺失时间不影响可见;
5159
+ * - 只把**本次请求成功读到的空会话**放进 `resolvedNowEmpty`;超预算/失败/在途一律不删;
5160
+ * - 每次 readSession 都 race 一个 deadline(signal 不可中断时也不会无限挂住),
5161
+ * 总预算 2.5s、并发 ≤4;避免与后台同会话读取重复(见 backfillInFlight)。
5162
+ */
5163
+ const resolveVisibilityForFilter = async (sessionIds, signal) => {
5164
+ const resolvedNowEmpty = new Set();
5165
+ const query = ctx.get("sessionQuery");
5166
+ if (!query || typeof query.readSession !== "function") return resolvedNowEmpty;
5167
+ const pending = [...new Set(sessionIds)].filter((id) => typeof id === "string" && id !== "" && !messageTimeMap.has(id));
5168
+ if (pending.length === 0) return resolvedNowEmpty;
5169
+ const deadline = performance.now() + EMPTY_FILTER_BACKFILL_BUDGET_MS;
5170
+ let cursor = 0;
5171
+ const readWithinDeadline = async (id) => {
5172
+ const remaining = deadline - performance.now();
5173
+ if (remaining <= 0) return null;
5174
+ let timer;
5175
+ const timeout = new Promise((resolve) => {
5176
+ timer = setTimeout(() => resolve(null), remaining);
5177
+ });
5178
+ const aborted = new Promise((resolve) => {
5179
+ if (signal?.aborted) {
5180
+ resolve(null);
5181
+ return;
5182
+ }
5183
+ signal?.addEventListener("abort", () => resolve(null), { once: true });
5184
+ });
5185
+ try {
5186
+ return await Promise.race([
5187
+ Promise.resolve().then(() => query.readSession(id)),
5188
+ timeout,
5189
+ aborted,
5190
+ ]);
5191
+ } catch {
5192
+ return null;
5193
+ } finally {
5194
+ clearTimeout(timer);
5195
+ }
5196
+ };
5197
+ const worker = async () => {
5198
+ while (cursor < pending.length) {
5199
+ if (signal?.aborted || performance.now() >= deadline) return;
5200
+ const id = pending[cursor];
5201
+ cursor += 1;
5202
+ if (messageTimeMap.has(id)) continue;
5203
+ // 已由后台回填在读:不在本请求重复读;本次不确认,保留可见。
5204
+ if (backfillInFlight.has(id)) continue;
5205
+ const snapshot = await readWithinDeadline(id);
5206
+ if (signal?.aborted) return;
5207
+ if (!snapshot || !Array.isArray(snapshot.events)) continue; // 超时/失败/坏形状 → 未确认
5208
+ if (isEmptyConversationSessionEvents(snapshot.events)) {
5209
+ resolvedNowEmpty.add(id);
5210
+ // 只缓存“成功读到且为空”,供后台/后续读取复用;但过滤绝不依赖旧缓存。
5211
+ messageTimeBackfill.set(id, { at: Date.now(), ok: true });
5212
+ continue;
5213
+ }
5214
+ const latest = latestMessageTimeOf(snapshot.events);
5215
+ if (latest !== null) touchMessageTime(id, latest);
5216
+ // 可见但 time 缺失:保留可见,不写 messageTimeMap(排序回退 lastActivity/createdAt)。
5217
+ }
5218
+ };
5219
+ await Promise.all(Array.from({ length: Math.min(4, pending.length) }, () => worker()));
5220
+ return resolvedNowEmpty;
5221
+ };
5222
+
5223
+ /**
5224
+ * issue #109 实机修复:用 `sessionPersistence.list()` 的廉价 metadata 判定空会话。
5225
+ * 返回 Map<id, snapshot>;服务缺失/失败返回 null(调用方退回有界 readSession 兜底)。
5226
+ */
5227
+ const loadPersistenceSnapshots = async (signal) => {
5228
+ try {
5229
+ const persistence = ctx.get("sessionPersistence");
5230
+ if (!persistence || typeof persistence.list !== "function") return null;
5231
+ let timer;
5232
+ const timeout = new Promise((resolve) => {
5233
+ timer = setTimeout(() => resolve(null), PERSISTENCE_SNAPSHOT_BUDGET_MS);
5234
+ });
5235
+ try {
5236
+ const snapshots = await Promise.race([
5237
+ Promise.resolve().then(() => persistence.list({ signal })),
5238
+ timeout,
5239
+ ]);
5240
+ if (!Array.isArray(snapshots)) return null;
5241
+ const map = new Map();
5242
+ for (const snapshot of snapshots) {
5243
+ const id = snapshot?.header?.id;
5244
+ if (typeof id === "string" && id !== "") map.set(id, snapshot);
5245
+ }
5246
+ return map;
5247
+ } finally {
5248
+ clearTimeout(timer);
5249
+ }
5250
+ } catch {
5251
+ return null;
5252
+ }
5253
+ };
5254
+ /**
5255
+ * metadata 判空三态:`empty` / `nonEmpty` / `unknown`(unknown 走有界 readSession)。
5256
+ *
5257
+ * 生产 JSONL backend 当前**没有 eventCount**,只有 sizeBytes;因此:
5258
+ * - size≤1024 才直接判空(实测空 329–704B、最小非空 40KB);
5259
+ * - 1024<size≤2048 是灰区 → unknown(可能含小 tool-only/only-user,读日志确认);
5260
+ * - size>2048 → nonEmpty;
5261
+ * - size 缺失 → unknown;eventCount 只在同时可用且≤8 时作辅助,不能单独判空。
5262
+ */
5263
+ const metadataEmptyVerdict = (snapshot) => {
5264
+ if (!snapshot) return "unknown";
5265
+ const size = typeof snapshot.sizeBytes === "number" && Number.isFinite(snapshot.sizeBytes)
5266
+ ? snapshot.sizeBytes
5267
+ : null;
5268
+ const eventCount = typeof snapshot.eventCount === "number" && Number.isFinite(snapshot.eventCount)
5269
+ ? snapshot.eventCount
5270
+ : null;
5271
+ if (size === null) return "unknown";
5272
+ if (size <= EMPTY_SESSION_MAX_SAFE_BYTES) {
5273
+ if (eventCount !== null && eventCount > EMPTY_SESSION_MAX_EVENTS) return "nonEmpty";
5274
+ return "empty";
5275
+ }
5276
+ if (size <= EMPTY_SESSION_GREY_MAX_BYTES) return "unknown";
5277
+ return "nonEmpty";
3279
5278
  };
5279
+
3280
5280
  // v3.1.2:0.1.2 的 Session 类改为 snapshotEvents()/eventAt()/seq(无 .events 数组)——
3281
5281
  // 统一取事件数组;休眠快照(readSession 返回值 {events})与旧版会话保持兼容。
3282
5282
  const eventsOf = (session) => {
@@ -3290,6 +5290,36 @@ export function apply(ctx, config, runtime = {}) {
3290
5290
  if (!Number.isSafeInteger(n) || n < 0) return null;
3291
5291
  return eventsOf(session).find((event) => Number(event?.seq) === n) ?? null;
3292
5292
  };
5293
+ /** 会话工作目录(宿主事实):live 会话在 header,休眠快照在 snapshot.session。 */
5294
+ const sessionCwdOf = (session) => {
5295
+ const cwd = session?.header?.cwd;
5296
+ return typeof cwd === "string" && cwd !== "" ? cwd : undefined;
5297
+ };
5298
+ /** 该轮**最新**一条 `workspace/changes` 事件(摘要与预览的 seq 坐标来源)。 */
5299
+ const latestWorkspaceChangesEvent = (session, turn) => {
5300
+ const events = eventsOf(session);
5301
+ for (let index = events.length - 1; index >= 0; index -= 1) {
5302
+ const event = events[index];
5303
+ if (event?.type === "workspace/changes" && Number(event?.data?.turn) === turn) return event;
5304
+ }
5305
+ return null;
5306
+ };
5307
+ /** 单个事件是否属于该会话的指定轮/类型(presented 坐标校验)。 */
5308
+ const presentedEventFilesOf = (event, index) => {
5309
+ if (!event || event.type !== "deliverables/presented") return null;
5310
+ const files = event?.data?.files;
5311
+ if (!Array.isArray(files) || index < 0 || index >= files.length) return null;
5312
+ const file = files[index];
5313
+ return typeof file?.path === "string" && file.path !== "" ? file : null;
5314
+ };
5315
+ /** 从记录里的路径解析出**只读目标**:相对路径按记录所属会话的工作目录展开。 */
5316
+ const resolveRecordedPath = (recordedPath, cwd) => {
5317
+ const text = normalizeServerPath(recordedPath);
5318
+ if (text === "") return null;
5319
+ if (isAbsolute(text)) return resolve(text);
5320
+ if (typeof cwd !== "string" || cwd === "") return null;
5321
+ return resolve(normalizeServerPath(cwd), text);
5322
+ };
3293
5323
  /** v3.1.2:从事件数组折叠会话配置(休眠会话读取用——0.1.2 模型选择事件为 model/selection)。 */
3294
5324
  const foldFromEvents = (events) => {
3295
5325
  const out = { model: undefined, provider: undefined, reasoningEffort: undefined, permissionPreset: undefined, agentPreset: undefined };
@@ -4809,6 +6839,19 @@ export function apply(ctx, config, runtime = {}) {
4809
6839
  pendingFrames.delete(oldest);
4810
6840
  }
4811
6841
  };
6842
+ // issue #68:PTC 50 子调用预算在 SSE 侧按会话维护(契约 §1.6/D8);会话数上限 200,
6843
+ // L2-5:超限按插入序 FIFO 逐出最旧(不做触碰刷新)。/history 每个响应各建一个,
6844
+ // 两处共用同一投影分支与 gate。
6845
+ const ptcBudgets = new Map(); // sessionId -> createPtcBudget()
6846
+ const ptcBudgetFor = (sessionId) => {
6847
+ let budget = ptcBudgets.get(sessionId);
6848
+ if (budget === undefined) {
6849
+ budget = createPtcBudget();
6850
+ ptcBudgets.set(sessionId, budget);
6851
+ if (ptcBudgets.size > 200) ptcBudgets.delete(ptcBudgets.keys().next().value);
6852
+ }
6853
+ return budget;
6854
+ };
4812
6855
  const connect = (res) => {
4813
6856
  if (connections.size >= config.maxConnections) {
4814
6857
  res.writeHead(503, { "content-type": "application/json; charset=utf-8" });
@@ -4826,7 +6869,7 @@ export function apply(ctx, config, runtime = {}) {
4826
6869
  "connection": "keep-alive",
4827
6870
  });
4828
6871
  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`);
6872
+ 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
6873
  connections.add(res);
4831
6874
  // 补发断线期间挂起的问询/审批(与 PC 端 GUI 连接时的 pending 回放一致;超 TTL 的僵尸帧先清掉)
4832
6875
  for (const [key, f] of pendingFrames) {
@@ -4836,6 +6879,14 @@ export function apply(ctx, config, runtime = {}) {
4836
6879
  }
4837
6880
  res.write(`data: ${JSON.stringify({ type: "mobile/frame", frame: f })}\n\n`);
4838
6881
  }
6882
+ // v3.3(吸收上游 #64):同一有序流上,回放后追加完整待办快照边界。
6883
+ // 客户端只据此撤销本宿主已不在 pending 中的业务通知(其它宿主/常驻通知不受影响)。
6884
+ res.write(`data: ${JSON.stringify({ type: "attention/snapshot", version: 1,
6885
+ pending: [...pendingFrames.values()].flatMap((f) => {
6886
+ const kind = f.type === "approval/requested" ? "approval" : f.type === "question/requested" ? "question" : null;
6887
+ const identity = kind === "approval" ? f.approvalId || f.rpcId : f.rpcId;
6888
+ return kind && identity && f.sessionId ? [{ kind, identity, sessionId: f.sessionId }] : [];
6889
+ }) })}\n\n`);
4839
6890
  // v2.7:连接回放各会话任务视图(与 PC 端 GUI 同源)
4840
6891
  for (const f of sessionJobsFrames()) {
4841
6892
  res.write(`data: ${JSON.stringify(f)}\n\n`);
@@ -4843,7 +6894,26 @@ export function apply(ctx, config, runtime = {}) {
4843
6894
  };
4844
6895
  const onSessionEvent = (session, event) => {
4845
6896
  if (isLiveTimelineRecord(event)) {
4846
- broadcast({ type: "session/event", sessionId: session.id, event: summarizeEvent(event) });
6897
+ // issue #53:交付文件声明的 display 需要会话工作目录才能派生;turn/end 额外带
6898
+ // 轮末信号 `tail`(§6.20),供 App 决定是否渲染改动卡/交付卡。
6899
+ // issue #60 R14:实时 tool/result 同样按 callId→name 解析命令工具身份。
6900
+ const resolvedToolName = event.type === "tool/result"
6901
+ ? toolNamesOf(eventsOf(session)).get(toolResultCallIdOf(event))
6902
+ : undefined;
6903
+ const summary = summarizeEvent(event, {
6904
+ cwd: sessionCwdOf(session),
6905
+ resolvedToolName,
6906
+ // issue #68:PTC 事件的 turn/step 由原始会话事件派生(派生不到省略),
6907
+ // 50 预算按会话复用;两处 options 与 /history 同构。
6908
+ ...(isPtcDispatchEvent(event)
6909
+ ? { ...ptcLocationOf(eventsOf(session), event.seq), ptcBudget: ptcBudgetFor(session.id) }
6910
+ : {}),
6911
+ });
6912
+ if (event.type === "turn/end") {
6913
+ const tail = turnTailOf(eventsOf(session), event.data?.turn);
6914
+ if (tail) summary.data = { ...(summary.data ?? {}), tail };
6915
+ }
6916
+ broadcast({ type: "session/event", sessionId: session.id, event: summary });
4847
6917
  }
4848
6918
  // 会话有动静 = 标题可能变化:使该会话的标题缓存失效(活跃会话本就实时取标题,
4849
6919
  // 休眠会话不受影响——它没有实时事件流)
@@ -5023,6 +7093,32 @@ export function apply(ctx, config, runtime = {}) {
5023
7093
  };
5024
7094
  // 流式端点:只取首帧(如 session/control 基线流),unary invoke 会被网关拒绝
5025
7095
  const RPC_STREAM_METHODS = new Set(["session.control"]);
7096
+ /**
7097
+ * issue #87:subagents 服务代际探测(ADR 0017:能力优先,不用版本号)。
7098
+ * rc.2 提供 listDescendants/interruptByUser;rc.1 提供 listChildren/interruptByParent。
7099
+ */
7100
+ const subagentsService = () => {
7101
+ try {
7102
+ return ctx.get("subagents");
7103
+ } catch {
7104
+ return undefined;
7105
+ }
7106
+ };
7107
+ const subagentsGeneration = () => {
7108
+ const service = subagentsService();
7109
+ return {
7110
+ catalog: typeof service?.listDescendants === "function"
7111
+ ? "descendants"
7112
+ : typeof service?.listChildren === "function"
7113
+ ? "children"
7114
+ : "none",
7115
+ interrupt: typeof service?.interruptByUser === "function"
7116
+ ? "user"
7117
+ : typeof service?.interruptByParent === "function"
7118
+ ? "parent"
7119
+ : "none",
7120
+ };
7121
+ };
5026
7122
  /** v3.1.2:session/control(baseline)中取某会话的投影值(modelSelection/imageLimits 等)。 */
5027
7123
  const projectionOf = (control, sessionId) =>
5028
7124
  control?.type === "baseline" ? control.value?.projections?.[sessionId]?.values : undefined;
@@ -5085,8 +7181,13 @@ export function apply(ctx, config, runtime = {}) {
5085
7181
  // 0.2.x 位置参数形态形参 ≥3;0.1.x 是 (endpoint, options) 两参
5086
7182
  const modernGateway = gateway.invokeRpc.length >= 3;
5087
7183
  const peer = modernGateway ? gatewayPeer() : void 0;
5088
- const endpoint = RPC_ENDPOINT_RENAMES[method] ?? method.replace(".", "/");
5089
- const adapted = RPC_PAYLOAD_ADAPTER[method]?.(payload) ?? { request: payload };
7184
+ let endpoint = RPC_ENDPOINT_RENAMES[method] ?? method.replace(".", "/");
7185
+ let adapted = RPC_PAYLOAD_ADAPTER[method]?.(payload) ?? { request: payload };
7186
+ // issue #87:rc.2 中断端点改名且参数收窄到仅 childSessionId;rc.1 保持旧 3 字段。
7187
+ if (method === "subagent.interrupt" && typeof subagentsService()?.interruptByUser === "function") {
7188
+ endpoint = "subagents/interruptByUser";
7189
+ adapted = { childSessionId: payload.childSessionId };
7190
+ }
5090
7191
  if (RPC_STREAM_METHODS.has(method)) {
5091
7192
  // 基线流(session/control 等):首帧即基线快照,取完即断
5092
7193
  const [namespace, name] = endpoint.split("/");
@@ -5186,8 +7287,6 @@ export function apply(ctx, config, runtime = {}) {
5186
7287
  const forwarded = value.slice(sep + 1).trim();
5187
7288
  return forwarded === "" ? remote : forwarded;
5188
7289
  };
5189
- /** 首个 root agent(无 root 时退回任意 agent)。 */
5190
- const firstAgent = (agents) => agents?.roots()[0] ?? agents?.list()[0];
5191
7290
  /** 会话短码(统一格式:前 8 + … + 后 4;短 id 原样)。 */
5192
7291
  const shortSessionId = (id) => (id.length > 12 ? `${id.slice(0, 8)}…${id.slice(-4)}` : id);
5193
7292
  /** 通知标题:会话标题兜底短码。 */
@@ -5466,6 +7565,48 @@ export function apply(ctx, config, runtime = {}) {
5466
7565
  // 队列有界 + 截止时间从请求到达时算起(issue #25 评审 P1):见 createTurnOutlineQueue。
5467
7566
  const turnOutlineQueue = createTurnOutlineQueue();
5468
7567
 
7568
+ // issue #78:/attachment 每次请求都要从会话原始事件里按 id 找完整 ref;同一张图常被
7569
+ // 缩略图/查看器/重试重复拉取,用进程内小 LRU 缓存已校验的 ref(只缓存完整合法 ref,
7570
+ // 解析失败不缓存,避免污染)。
7571
+ const attachmentRefCache = new Map();
7572
+ const ATTACHMENT_REF_CACHE_LIMIT = 64;
7573
+ const rememberAttachmentRef = (key, ref) => {
7574
+ attachmentRefCache.delete(key);
7575
+ attachmentRefCache.set(key, ref);
7576
+ while (attachmentRefCache.size > ATTACHMENT_REF_CACHE_LIMIT) {
7577
+ const oldest = attachmentRefCache.keys().next().value;
7578
+ attachmentRefCache.delete(oldest);
7579
+ }
7580
+ };
7581
+ /** 取会话原始事件:live 会话走 snapshotEvents;休眠会话走 readSession(含 seeded 降级)。 */
7582
+ const attachmentEventsOf = async (sessionId) => {
7583
+ const sessions = ctx.get("sessions");
7584
+ let live;
7585
+ try { live = sessions?.get?.(sessionId); } catch { live = undefined; }
7586
+ if (live) {
7587
+ const events = eventsOf(live);
7588
+ if (events.length > 0) return events;
7589
+ }
7590
+ const query = ctx.get("sessionQuery");
7591
+ if (!query || typeof query.readSession !== "function") return null;
7592
+ const loaded = await loadDormantSession(query, sessionId);
7593
+ return loaded?.ok ? eventsOf(loaded.snapshot) : null;
7594
+ };
7595
+ /**
7596
+ * 解析 attachmentId → 严格 schema 的完整 ref;缓存命中直接返回,未命中扫事件。
7597
+ * 解析失败返回 null(调用方 404,不按路径读文件、不猜)。
7598
+ */
7599
+ const resolveAttachmentRef = async (sessionId, attachmentId) => {
7600
+ const key = `${sessionId}\u0000${attachmentId}`;
7601
+ const cached = attachmentRefCache.get(key);
7602
+ if (cached) return { ref: cached, cached: true, key };
7603
+ let events = null;
7604
+ try { events = await attachmentEventsOf(sessionId); } catch { events = null; }
7605
+ const ref = extractAttachmentRef(events ?? [], attachmentId);
7606
+ if (!ref) return null;
7607
+ rememberAttachmentRef(key, ref);
7608
+ return { ref, cached: false, key };
7609
+ };
5469
7610
  const handleApi = async (req, res, url, rest) => {
5470
7611
  if (!hostAllowed(req)) {
5471
7612
  error(res, 403, "host-not-allowed");
@@ -5560,12 +7701,17 @@ export function apply(ctx, config, runtime = {}) {
5560
7701
  // contentSha256 = **当前正在运行的代码**的内容标识:监督器与手机据此确认
5561
7702
  // "新实例已健康生效",而不是只看磁盘字节或版本号(评审 R1/R7)
5562
7703
  // instanceId = 本服务实例身份:换实例后旧健康结论不能冒充新的(§5.3)。
5563
- plugin: { name: "dsh-mobile-remote", version: pluginVersion(), contentSha256: selfContentSha256, pid: process.pid, instanceId: pluginInstanceId },
7704
+ plugin: { name: "dsh-mobile-remote", version: pluginVersion(), contentSha256: selfContentSha256, pid: process.pid, instanceId: pluginInstanceId, hostId: hostIdentity },
5564
7705
  capabilities: {
5565
7706
  eventTimeline: EVENT_TIMELINE_CAPABILITIES,
5566
7707
  // 宿主是否**真的**挂了 `turnOutline` 投影单元、且观察接口可用,决定声明是
5567
7708
  // "支持"还是"能力缺失"——App 先读声明再决定是否渲染未加载刻度(不按宿主版本推断)。
5568
7709
  turnOutline: turnOutlineCapabilityOf(ctx),
7710
+ // v3.3(issue #53):轮末产出物能力位;`changed/changesDiff` 只按宿主是否真的
7711
+ // 注册 `workspaceChanges` 判定(ADR 0017),SSE hello 同判据同形状。
7712
+ turnTail: turnTailCapabilityOf(ctx),
7713
+ // v3.4(issue #54):工具卡结构化投影能力位(按本插件实际投影的工具集合声明)。
7714
+ toolCards: toolCardsCapabilityOf(),
5569
7715
  // v3.2.3:普通文件下载支持 Range/HEAD/ETag(大文件续传 + 前缀预览)。
5570
7716
  fileRange: FILE_RANGE_CAPABILITIES,
5571
7717
  // v3.2.4(issue #55):手机端待办等待上限(仅供显示剩余时间,结算仍以服务端为准)。
@@ -5662,15 +7808,47 @@ export function apply(ctx, config, runtime = {}) {
5662
7808
  }
5663
7809
 
5664
7810
 
5665
- // 只读 NPM 检查:桌面设置页/手机端可按需刷新;不下载产物、不改 profile、不重启。
7811
+ // 只读 NPM 检查:旧 App GET 缓存命中立即返回;新 App POST 异步检查 + checkId 轮询。
7812
+ // 不下载产物、不改 profile、不重启,也不返回半结果。
5666
7813
  if (rest === "/plugin-update/check") {
5667
- if (method !== "GET") return error(res, 405, "method-not-allowed");
7814
+ // registry 提取器按头部识别方法:用集合校验,避免被块内 GET 分支误判成 GET。
7815
+ if (!["GET", "POST"].includes(method)) return error(res, 405, "method-not-allowed");
7816
+ if (method === "GET") {
7817
+ const checkId = url.searchParams.get("checkId") ?? "";
7818
+ if (checkId !== "") {
7819
+ const status = updates.getAsyncCheck(checkId);
7820
+ if (status.status === 404) return error(res, 404, "check-not-found");
7821
+ if (status.status === 410) return error(res, 410, "check-expired");
7822
+ const body = status.body;
7823
+ if (body.state === "done") {
7824
+ return sendJson(res, 200, {
7825
+ ok: true,
7826
+ state: "done",
7827
+ checkId,
7828
+ pluginUpdate: publicCheckResult(req, body.result),
7829
+ });
7830
+ }
7831
+ return sendJson(res, 200, { ok: true, ...body });
7832
+ }
7833
+ try {
7834
+ Object.assign(pluginUpdateStatus, await updates.checkSync());
7835
+ } catch {
7836
+ Object.assign(pluginUpdateStatus, { state: "unavailable", reason: "update-check-failed", source: "npm", checkedAt: new Date().toISOString() });
7837
+ }
7838
+ return sendJson(res, 200, { ok: true, pluginUpdate: publicUpdateStatus(req) });
7839
+ }
7840
+ // POST:{force?:boolean} → 200 {ok:true,state:"checking",checkId}。绝不用 202,
7841
+ // 现有 App 的 postJson 只接受 200。
7842
+ let body;
5668
7843
  try {
5669
- Object.assign(pluginUpdateStatus, await updates.check());
7844
+ const text = await readBody(req, 16 * 1024);
7845
+ body = text ? JSON.parse(text) : {};
5670
7846
  } catch {
5671
- Object.assign(pluginUpdateStatus, { state: "unavailable", reason: "update-check-failed", source: "npm", checkedAt: new Date().toISOString() });
7847
+ return error(res, 400, "bad-request", "body must be JSON");
5672
7848
  }
5673
- return sendJson(res, 200, { ok: true, pluginUpdate: publicUpdateStatus(req) });
7849
+ if (!body || typeof body !== "object" || Array.isArray(body)) return error(res, 400, "bad-request");
7850
+ const started = updates.startAsyncCheck({ force: body.force === true });
7851
+ return sendJson(res, 200, { ok: true, state: "checking", checkId: started.checkId });
5674
7852
  }
5675
7853
 
5676
7854
  // 旧 carrier 缺少 App build metadata 时,用户明确触发的预检只下载/校验 NPM 产物,不改 profile。
@@ -5718,8 +7896,101 @@ export function apply(ctx, config, runtime = {}) {
5718
7896
  return sendJson(res, result.status, result.body);
5719
7897
  }
5720
7898
 
5721
- if (new Set(["/git/capabilities", "/git/repository", "/git/branches", "/git/graph", "/git/commit", "/git/worktree", "/git/preview", "/git/files", "/git/file-history"]).has(rest)) {
5722
- if (requireGet(method, res)) return;
7899
+ // task-28 / re-review P1-1:/git/graph 独立分派,允许 GET/HEAD/POST;其余 Git 只读
7900
+ // 端点单独分支保持 GET/HEAD(POST 405)。endpoint-registry 按真实方法登记。
7901
+ if (rest === "/git/graph") {
7902
+ if (method !== "GET" && method !== "HEAD" && method !== "POST") return error(res, 405, "method-not-allowed");
7903
+ // HEAD = 能力探测:200 无 body,且不创建 snapshot。
7904
+ if (method === "HEAD") {
7905
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
7906
+ res.end();
7907
+ return;
7908
+ }
7909
+ const GRAPH_POST_BODY_LIMIT = 256 * 1024;
7910
+ const GRAPH_TIP_NAME_LIMIT = 1024;
7911
+ // focus 只接受分支 ref 或完整 commit oid;字符串长度有界,避免日志/扫描放大。
7912
+ const sourceFocusInvalid = (value) => value !== undefined
7913
+ && (typeof value !== "string" || value.length === 0 || Buffer.byteLength(value, "utf8") > GRAPH_TIP_NAME_LIMIT);
7914
+ let postBody = null;
7915
+ if (method === "POST") {
7916
+ const declared = Number(req.headers?.["content-length"]);
7917
+ if (Number.isFinite(declared) && declared > GRAPH_POST_BODY_LIMIT) return error(res, 413, "payload-too-large");
7918
+ let text;
7919
+ try { text = await readBody(req, GRAPH_POST_BODY_LIMIT); }
7920
+ catch (err) { return bodyError(err, res); }
7921
+ try { postBody = text ? JSON.parse(text) : {}; }
7922
+ catch { return error(res, 400, "bad-request", "body must be JSON"); }
7923
+ if (!postBody || typeof postBody !== "object" || Array.isArray(postBody)) return error(res, 400, "bad-request");
7924
+ const tips = postBody.tips;
7925
+ if (tips !== undefined) {
7926
+ if (!Array.isArray(tips)) return error(res, 400, "bad-request", "tips must be an array");
7927
+ for (const tip of tips) {
7928
+ const name = tip?.name;
7929
+ if (typeof name !== "string" || Buffer.byteLength(name, "utf8") > GRAPH_TIP_NAME_LIMIT) {
7930
+ return error(res, 413, "payload-too-large");
7931
+ }
7932
+ }
7933
+ }
7934
+ const allMode = postBody.all === true;
7935
+ if (allMode) {
7936
+ // issue #93:all 模式忽略/不接受 tips 选择集;focus 可选(分支 ref)。
7937
+ if (tips !== undefined && (!Array.isArray(tips) || tips.length > 0)) {
7938
+ return error(res, 400, "bad-request", "tips must be omitted in all mode");
7939
+ }
7940
+ if (sourceFocusInvalid(postBody.focus)) return error(res, 400, "bad-request", "focus must be a ref or oid");
7941
+ } else if (postBody.snapshotId === undefined && postBody.cursor === undefined && !Array.isArray(tips)) {
7942
+ return error(res, 400, "bad-request", "tips is required");
7943
+ }
7944
+ }
7945
+ const source = postBody ?? {};
7946
+ const allMode = method === "POST" && source.all === true;
7947
+ if (method === "GET" && (url.searchParams.get("all") === "true" || url.searchParams.get("all") === "1")) {
7948
+ return error(res, 400, "bad-request", "all mode requires POST");
7949
+ }
7950
+ const sessionId = (method === "POST" ? source.sessionId : null) ?? url.searchParams.get("sessionId") ?? "";
7951
+ if (!sessionId) return error(res, 400, "bad-request", "sessionId is required");
7952
+ const repositoryId = (method === "POST" ? source.repositoryId : null) ?? url.searchParams.get("repositoryId") ?? "";
7953
+ if (!repositoryId) return error(res, 400, "bad-request", "repositoryId is required");
7954
+ try {
7955
+ let value;
7956
+ if (method === "POST") {
7957
+ value = await gitRead.graph(sessionId, repositoryId, {
7958
+ tips: source.tips,
7959
+ snapshotId: source.snapshotId,
7960
+ cursor: source.cursor,
7961
+ limit: source.limit,
7962
+ maxTips: 128,
7963
+ all: allMode,
7964
+ focus: allMode ? (typeof source.focus === "string" ? source.focus : undefined) : undefined,
7965
+ });
7966
+ } else {
7967
+ let tips;
7968
+ const rawTips = url.searchParams.get("tips");
7969
+ if (rawTips !== null) {
7970
+ try { tips = JSON.parse(rawTips); } catch { return error(res, 400, "bad-request", "tips must be JSON"); }
7971
+ }
7972
+ value = await gitRead.graph(sessionId, repositoryId, {
7973
+ tips,
7974
+ snapshotId: url.searchParams.get("snapshotId") ?? undefined,
7975
+ cursor: url.searchParams.get("cursor") ?? undefined,
7976
+ limit: url.searchParams.get("limit") ?? undefined,
7977
+ maxTips: 32,
7978
+ });
7979
+ }
7980
+ sendJson(res, 200, { ok: true, ...value });
7981
+ } catch (err) {
7982
+ const known = new Set(["session-not-found", "workspace-not-allowed", "not-git-repository", "git-provider-unavailable", "repository-not-authorized", "graph-stale", "graph-tip-invalid", "graph-too-many-tips", "graph-too-many-refs", "graph-focus-invalid", "graph-focus-not-found", "graph-timeout", "invalid-oid", "git-command-failed", "git-output-too-large", "provider-incompatible"]);
7983
+ const code = known.has(err?.code) ? err.code : "git-provider-unavailable";
7984
+ const status = Number(err?.status);
7985
+ ctx.logger.warn?.(`mobile-remote: Git graph failed (${code}): ${err?.message ?? err}`);
7986
+ return error(res, Number.isInteger(status) && status >= 400 && status <= 599 ? status : 503, code);
7987
+ }
7988
+ return;
7989
+ }
7990
+
7991
+ if (new Set(["/git/capabilities", "/git/repository", "/git/branches", "/git/commit", "/git/worktree", "/git/preview", "/git/files", "/git/file-history"]).has(rest)) {
7992
+ // 只读 Git 端点:GET/HEAD;POST 等一律 405(与登记表 GET/HEAD 一致)。
7993
+ if (method !== "GET" && method !== "HEAD") return error(res, 405, "method-not-allowed");
5723
7994
  const sessionId = url.searchParams.get("sessionId") ?? "";
5724
7995
  if (!sessionId) return error(res, 400, "bad-request", "sessionId is required");
5725
7996
  try {
@@ -5737,21 +8008,12 @@ export function apply(ctx, config, runtime = {}) {
5737
8008
  const path = url.searchParams.get("path");
5738
8009
  if (path === null || path === "") return error(res, 400, "bad-request", "path is required");
5739
8010
  value = await gitRead.fileHistory(sessionId, repositoryId, { path, cursor: url.searchParams.get("cursor") ?? undefined, limit: url.searchParams.get("limit") ?? undefined });
5740
- } else if (rest === "/git/graph") {
5741
- let tips;
5742
- const rawTips = url.searchParams.get("tips");
5743
- if (rawTips !== null) {
5744
- try { tips = JSON.parse(rawTips); } catch { return error(res, 400, "bad-request", "tips must be JSON"); }
5745
- }
5746
- value = await gitRead.graph(sessionId, repositoryId, { tips, snapshotId: url.searchParams.get("snapshotId") ?? undefined, cursor: url.searchParams.get("cursor") ?? undefined, limit: url.searchParams.get("limit") ?? undefined });
5747
8011
  } else if (rest === "/git/commit") value = await gitRead.commit(sessionId, repositoryId, url.searchParams.get("oid") ?? "", { filesCursor: url.searchParams.get("filesCursor") ?? undefined, filesLimit: url.searchParams.get("filesLimit") ?? undefined });
5748
8012
  else return error(res, 404, "not-found");
5749
8013
  }
5750
8014
  sendJson(res, 200, { ok: true, ...value });
5751
8015
  } catch (err) {
5752
- // External providers may include host paths or credentials in messages:
5753
- // only expose stable mobile error codes, never raw provider details.
5754
- const known = new Set(["session-not-found", "workspace-not-allowed", "not-git-repository", "git-provider-unavailable", "repository-not-authorized", "graph-stale", "graph-tip-invalid", "graph-too-many-tips", "invalid-oid", "invalid-files-cursor", "invalid-history-cursor", "path-invalid", "git-command-failed", "git-output-too-large", "provider-incompatible", "preview-invalid", "preview-file-not-found"]);
8016
+ const known = new Set(["session-not-found", "workspace-not-allowed", "not-git-repository", "git-provider-unavailable", "repository-not-authorized", "invalid-oid", "invalid-files-cursor", "invalid-history-cursor", "path-invalid", "git-command-failed", "git-output-too-large", "provider-incompatible", "preview-invalid", "preview-file-not-found"]);
5755
8017
  const code = known.has(err?.code) ? err.code : "git-provider-unavailable";
5756
8018
  const status = Number(err?.status);
5757
8019
  ctx.logger.warn?.(`mobile-remote: Git read failed (${code}): ${err?.message ?? err}`);
@@ -5863,7 +8125,7 @@ export function apply(ctx, config, runtime = {}) {
5863
8125
  const agents = ctx.get("agents");
5864
8126
  if (!agents) return error(res, 503, "agents-unavailable");
5865
8127
  const sessionId = typeof body?.sessionId === "string" && body.sessionId ? body.sessionId : undefined;
5866
- let target = sessionId ? agents.get(sessionId) : agents.roots()[0];
8128
+ let target = sessionId ? agents.get(sessionId) : firstAgent(agents);
5867
8129
  // v3.1.5:休眠配置折叠回退默认时置位,finalize 在所有响应上附带 configDegraded
5868
8130
  let configDegraded = false;
5869
8131
  if (!target && sessionId) {
@@ -5989,7 +8251,7 @@ export function apply(ctx, config, runtime = {}) {
5989
8251
  const sessionId = url.searchParams.get("sessionId") ?? undefined;
5990
8252
  const requestId = url.searchParams.get("requestId");
5991
8253
  if (!requestId || !/^[A-Za-z0-9-]{8,64}$/.test(requestId)) return error(res, 400, "bad-request", "invalid requestId");
5992
- const rootId = ctx.get("agents")?.roots()[0]?.id;
8254
+ const rootId = firstAgent(ctx.get("agents"))?.id;
5993
8255
  const key = receiptKeyOf(sessionId, rootId, requestId);
5994
8256
  // v3.0.0(热修 08):读取路径全量清理——未访问的旧回执同样清除并持久化(TTL 语义一致化)
5995
8257
  if (pruneReceipts()) persistReceipts();
@@ -6011,14 +8273,32 @@ export function apply(ctx, config, runtime = {}) {
6011
8273
  const sessionId = url.searchParams.get("sessionId");
6012
8274
  const attachmentId = url.searchParams.get("attachmentId");
6013
8275
  if (!sessionId || !attachmentId) return error(res, 400, "bad-request", "sessionId/attachmentId required");
8276
+ // 非法 id 直接 404:不扫事件、不把客户端字段当 ref(issue #78)。
8277
+ if (!attachmentIdValid(attachmentId)) return error(res, 404, "attachment-not-found");
8278
+ let resolved = await resolveAttachmentRef(sessionId, attachmentId);
8279
+ if (!resolved) return error(res, 404, "attachment-not-found");
6014
8280
  try {
6015
- const value = await apiRpc("session.attachment", { sessionId, attachmentId }, 30_000);
6016
- const ref = value?.attachment;
6017
- if (!ref || typeof value?.data !== "string" || value.data === "") return error(res, 404, "attachment-not-found");
8281
+ let value;
8282
+ try {
8283
+ // 新 DSH schema:{sessionId, attachment:{attachmentId,mediaType,bytes,width,height,name?}}
8284
+ value = await apiRpc("session.attachment", { sessionId, attachment: resolved.ref }, 30_000);
8285
+ } catch (err) {
8286
+ // 缓存可能过期/宿主侧引用已变化:清掉缓存重扫一次,仍失败才按原错误返回。
8287
+ if (!resolved.cached) throw err;
8288
+ attachmentRefCache.delete(resolved.key);
8289
+ resolved = await resolveAttachmentRef(sessionId, attachmentId);
8290
+ if (!resolved) return error(res, 404, "attachment-not-found");
8291
+ value = await apiRpc("session.attachment", { sessionId, attachment: resolved.ref }, 30_000);
8292
+ }
8293
+ // 响应仍带 attachment 与 base64 data;优先信宿主回显的 ref,缺失时用请求 ref。
8294
+ const ref = value?.attachment && typeof value.attachment === "object" ? value.attachment : resolved.ref;
8295
+ if (typeof value?.data !== "string" || value.data === "") return error(res, 404, "attachment-not-found");
6018
8296
  const buf = Buffer.from(value.data, "base64");
8297
+ if (buf.length === 0) return error(res, 404, "attachment-not-found");
8298
+ const contentType = ATTACHMENT_MEDIA_TYPES.includes(ref.mediaType) ? ref.mediaType : resolved.ref.mediaType;
6019
8299
  guardRes(res);
6020
8300
  res.writeHead(200, {
6021
- "content-type": typeof ref.mediaType === "string" ? ref.mediaType : "image/jpeg",
8301
+ "content-type": contentType,
6022
8302
  "content-length": buf.length,
6023
8303
  "cache-control": "private, max-age=3600",
6024
8304
  // v3.0.0(热修 04):与 sendJson 同策略——图片取完即断,不留下可被复用的半关连接
@@ -6032,6 +8312,9 @@ export function apply(ctx, config, runtime = {}) {
6032
8312
  });
6033
8313
  res.end(buf);
6034
8314
  } catch (err) {
8315
+ // 调用前 ref 已经过严格校验;宿主仍报 attachment-invalid 基本是对象已不存在,
8316
+ // 对客户端按 404 attachment-not-found 处理(不暴露存储路径/内部错误)。
8317
+ if (err?.code === "session/attachment-invalid") return error(res, 404, "attachment-not-found");
6035
8318
  return error(res, ...rpcError(err, "attachment-failed"));
6036
8319
  }
6037
8320
  return;
@@ -6281,6 +8564,8 @@ export function apply(ctx, config, runtime = {}) {
6281
8564
 
6282
8565
  if (rest === "/sessions") {
6283
8566
  if (requireGet(method, res)) return;
8567
+ // issue #109:只有显式 includeEmpty=1 才返回零可见消息会话;非法值按 false。
8568
+ const includeEmpty = url.searchParams.get("includeEmpty") === "1";
6284
8569
  const sessions = ctx.get("sessions");
6285
8570
  if (!sessions) return error(res, 503, "sessions-unavailable");
6286
8571
  // v3.1.6(issue #20):客户端断开即停止**本请求**的扫描(宿主支持取消,此前一处没传)。
@@ -6301,7 +8586,7 @@ export function apply(ctx, config, runtime = {}) {
6301
8586
  if (enumeration.timedOut) return error(res, 504, "sessions-timeout");
6302
8587
  } else records = enumeration.records;
6303
8588
  }
6304
- const list = [];
8589
+ let list = [];
6305
8590
  const archived = coreArchivedIds();
6306
8591
  if (records) {
6307
8592
  // v3.1.6(issue #14 复核):这是**完整语料**观测——记下来供剪枝按会话存在性
@@ -6362,6 +8647,64 @@ export function apply(ctx, config, runtime = {}) {
6362
8647
  });
6363
8648
  }
6364
8649
  }
8650
+ // issue #109:默认过滤要在 title/message 回填后做;判空用**事件可见性**,
8651
+ // 不用 latestMessageTimeOf/time(可见消息可能没有 time,不能因此误删)。
8652
+ if (!includeEmpty) {
8653
+ // 1) 活跃会话的 snapshotEvents 是同步权威来源。
8654
+ const liveKnownEmpty = new Set();
8655
+ for (const row of list) {
8656
+ const live = sessions.get(row.id);
8657
+ if (!live) continue;
8658
+ try {
8659
+ const events = eventsOf(live);
8660
+ if (isEmptyConversationSessionEvents(events)) {
8661
+ if (row.lastMessageAt === null) liveKnownEmpty.add(row.id);
8662
+ continue;
8663
+ }
8664
+ if (row.lastMessageAt === null) {
8665
+ const latest = latestMessageTimeOf(events);
8666
+ if (latest !== null) {
8667
+ touchMessageTime(row.id, latest);
8668
+ row.lastMessageAt = latest;
8669
+ }
8670
+ // 可见但没有 time:保留可见,排序回退 lastActivity/createdAt。
8671
+ }
8672
+ } catch {
8673
+ // 读取失败视为未知,保留可见
8674
+ }
8675
+ }
8676
+ // 2) 休眠/归档:先用 sessionPersistence.list() 的 eventCount/sizeBytes 廉价判定;
8677
+ // 只有 metadata 不足以判定(服务缺失/条目缺失)时才退回有界 readSession。
8678
+ // 324 个休眠空会话在实机上逐个 readSession 不可行(2.5s 只能读极少)。
8679
+ const metadataSnapshots = await loadPersistenceSnapshots(signal);
8680
+ if (signal.aborted) return;
8681
+ const metadataKnownEmpty = new Set();
8682
+ const needReadFallback = [];
8683
+ for (const row of list) {
8684
+ if (row.lastMessageAt !== null || liveKnownEmpty.has(row.id)) continue;
8685
+ const snapshot = metadataSnapshots?.get(row.id);
8686
+ if (snapshot) {
8687
+ const verdict = metadataEmptyVerdict(snapshot);
8688
+ if (verdict === "empty") metadataKnownEmpty.add(row.id);
8689
+ else if (verdict === "unknown") needReadFallback.push(row.id);
8690
+ continue;
8691
+ }
8692
+ needReadFallback.push(row.id);
8693
+ }
8694
+ const resolvedNowEmpty = needReadFallback.length > 0
8695
+ ? await resolveVisibilityForFilter(needReadFallback, signal)
8696
+ : new Set();
8697
+ if (signal.aborted) return;
8698
+ for (const row of list) {
8699
+ if (row.lastMessageAt === null) row.lastMessageAt = messageTimeMap.get(row.id) ?? null;
8700
+ }
8701
+ list = list.filter((row) => {
8702
+ if (liveKnownEmpty.has(row.id)) return false;
8703
+ if (metadataKnownEmpty.has(row.id)) return false;
8704
+ if (resolvedNowEmpty.has(row.id)) return false;
8705
+ return true;
8706
+ });
8707
+ }
6365
8708
  // v3.1.6(issue #14 / ADR 0013):按最新消息时间倒序(缺失回退 lastActivity,
6366
8709
  // 再回退 createdAt),等值以 id 为次级键。旧版 App 仍读 lastActivity,语义未变。
6367
8710
  list.sort(compareSessionsForList);
@@ -6633,7 +8976,9 @@ export function apply(ctx, config, runtime = {}) {
6633
8976
  return error(res, 500, "session-read-failed", "会话存在但历史读取失败");
6634
8977
  }
6635
8978
  if (loaded.ok) {
6636
- session = { events: loaded.snapshot.events };
8979
+ // issue #53:保留会话头(工作目录)——交付文件 display 派生与
8980
+ // turn-file 的相对路径解析都需要它;事件本身仍走同一过滤。
8981
+ session = { events: loaded.snapshot.events, header: loaded.snapshot.session ?? loaded.snapshot.header };
6637
8982
  degraded = loaded.degraded === true;
6638
8983
  }
6639
8984
  }
@@ -6669,7 +9014,14 @@ export function apply(ctx, config, runtime = {}) {
6669
9014
  // seq 不连续(非完整日志),before/after 分页只在 surface 范围内有效——
6670
9015
  // 上翻到被 surface 替换的 log-only 历史区域时可能返回空页,属预期;
6671
9016
  // 客户端应结合 historyMode="current-surface" 提示"部分历史不可上翻"。
6672
- const surface = eventsOf(session).filter(isTimelineRecord);
9017
+ const rawEvents = eventsOf(session);
9018
+ const surface = rawEvents.filter(isTimelineRecord);
9019
+ // issue #53(§6.20):轮末信号 `turnTails` 由**一次遍历原始事件**得出(会话日志
9020
+ // 仍含被过滤的 `workspace/changes`),不额外调用宿主服务;只含有产出物的轮次。
9021
+ const turnTails = turnTailsOf(eventsOf(session));
9022
+ const cwd = sessionCwdOf(session);
9023
+ // issue #60 R14:结果事件通常无工具名,用 callId→name 关联后再解析终止状态。
9024
+ const toolNames = toolNamesOf(eventsOf(session));
6673
9025
  let events;
6674
9026
  let hasMore = false;
6675
9027
  if (afterParam !== null) {
@@ -6689,6 +9041,15 @@ export function apply(ctx, config, runtime = {}) {
6689
9041
  hasMore = surface.length > limit;
6690
9042
  events = surface.slice(-limit);
6691
9043
  }
9044
+ // issue #68(M3 Batch 2-C):PTC 子调用投影与 SSE 共用同一 summarizeEvent
9045
+ // 分支;50 预算按**本响应**新建(契约 §1.6/D8),turn/step 从原始事件
9046
+ // (不是过滤后的 surface,否则拿不到 step/start)派生,派生不到就省略。
9047
+ const ptcBudget = createPtcBudget();
9048
+ const summarizeForMobile = (event) => summarizeEvent(event, {
9049
+ cwd,
9050
+ resolvedToolName: event?.type === "tool/result" ? toolNames.get(toolResultCallIdOf(event)) : undefined,
9051
+ ...(isPtcDispatchEvent(event) ? { ...ptcLocationOf(rawEvents, event.seq), ptcBudget } : {}),
9052
+ });
6692
9053
  sendJson(res, 200, {
6693
9054
  ok: true,
6694
9055
  sessionId,
@@ -6697,7 +9058,8 @@ export function apply(ctx, config, runtime = {}) {
6697
9058
  ...(degraded ? { degraded: true, historyMode: "current-surface" } : {}),
6698
9059
  after: events.length ? events[events.length - 1].seq : 0,
6699
9060
  hasMore,
6700
- events: events.map(summarizeEvent),
9061
+ turnTails,
9062
+ events: events.map(summarizeForMobile),
6701
9063
  });
6702
9064
  return;
6703
9065
  }
@@ -7595,6 +9957,9 @@ export function apply(ctx, config, runtime = {}) {
7595
9957
  credentials: probe("credentials"),
7596
9958
  messageFeedback: probe("messageFeedback"),
7597
9959
  userQuestions: probe("userQuestions"),
9960
+ // DSH 0.2.2+:宿主原生插件管理能力(决定更新是否免重启)。能力看声明,不看版本号。
9961
+ pluginManager: probe("pluginManager"),
9962
+ hmr: probe("hmr"),
7598
9963
  };
7599
9964
  const checks = { modelsRpc: false, sessionsList: false, directories: false, workspaces: false, notifications: false, actions: false };
7600
9965
  try {
@@ -7648,6 +10013,7 @@ export function apply(ctx, config, runtime = {}) {
7648
10013
  const gatewaySvc = ctx.get("typertGateway");
7649
10014
  const presetsSvc = ctx.get("permissionPresets");
7650
10015
  const workspaceSvc = ctx.get("workspaceRegistry");
10016
+ const subagentsSvc = subagentsService();
7651
10017
  // issue #34:0.2.1 的进程内 peer 来源(`connection.createPeer`);旧代靠网关 operator 兜底
7652
10018
  let connectionSvc;
7653
10019
  try {
@@ -7712,6 +10078,12 @@ export function apply(ctx, config, runtime = {}) {
7712
10078
  // (网关不再兜底)——只探存在性会把「开流必失败」报成绿灯,正是 ADR 0017 要防的
7713
10079
  // "服务在、成员在、语义已变"。旧代 3 参开流不需要 peer,按 ok 处理。
7714
10080
  "gateway.eventsPeer": eventsPeerProbe.state,
10081
+ // issue #87:rc.2 两处宿主契约漂移(中断端点改名/参数收窄、目录方法改名)。
10082
+ // 两种代际各自的成员都算 ok;都缺失才 drift/missing。
10083
+ "subagents.catalog": capabilityState(subagentsSvc, (s) =>
10084
+ typeof s.listDescendants === "function" || typeof s.listChildren === "function"),
10085
+ "subagents.interrupt": capabilityState(subagentsSvc, (s) =>
10086
+ typeof s.interruptByUser === "function" || typeof s.interruptByParent === "function"),
7715
10087
  };
7716
10088
  checks.hostCapabilities = hostCapabilities;
7717
10089
  // 已探测到的代际选择:便于人工核对插件实际走了哪条路径(排查"为什么这个功能表现不同")
@@ -7727,6 +10099,8 @@ export function apply(ctx, config, runtime = {}) {
7727
10099
  : eventsPeerProbe.state === "ok"
7728
10100
  ? peerSource
7729
10101
  : "none",
10102
+ // issue #87:实际走的 subagents 代际(descendants/children、user/parent)。
10103
+ subagents: subagentsGeneration(),
7730
10104
  };
7731
10105
  // 任一项非 ok 都必须给出可执行的原因,而不只是状态值
7732
10106
  const degradedCaps = Object.entries(hostCapabilities).filter(([, state]) => state !== "ok");
@@ -7767,7 +10141,7 @@ export function apply(ctx, config, runtime = {}) {
7767
10141
  checks.updateDir = `${updateDirState.source}${updateDirState.ready ? "" : `(${updateDirState.reason || "not-ready"})`}`;
7768
10142
  sendJson(res, 200, {
7769
10143
  ok: true,
7770
- plugin: { name: "dsh-mobile-remote", version: pluginVersion(), contentSha256: selfContentSha256, instanceId: pluginInstanceId },
10144
+ plugin: { name: "dsh-mobile-remote", version: pluginVersion(), contentSha256: selfContentSha256, instanceId: pluginInstanceId, hostId: hostIdentity },
7771
10145
  runtime: {
7772
10146
  // #36 follow-up(note 1509 §3/§4):form 取**桥启动决策时的同一份形态快照**,
7773
10147
  // 不再按请求重新探测(避免"诊断 desktop、启动 form-unknown"不一致);
@@ -7868,20 +10242,23 @@ export function apply(ctx, config, runtime = {}) {
7868
10242
  }
7869
10243
  // v3.1.1(issue #5):兜底兼容旧版 App 的 `\` 拼接(WSL 上 `/\home` 归一为 `/home`)
7870
10244
  const base = normalizeServerPath(path);
10245
+ // issue #45:`includeHidden=1` 时显示点开头条目;默认(含旧客户端不传参)
10246
+ // 保持旧行为,全部隐藏。无论开关如何,名称恰为 `.git` 的条目永不出现。
10247
+ const includeHidden = url.searchParams.get("includeHidden") === "1";
7871
10248
  try {
7872
10249
  const entries = await readdir(base, { withFileTypes: true });
7873
10250
  const dirs = entries
7874
- .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
10251
+ .filter((entry) => entry.isDirectory() && directoryEntryVisible(entry.name, includeHidden))
7875
10252
  .map((entry) => entry.name)
7876
10253
  .sort((a, b) => a.localeCompare(b, "zh-CN"));
7877
10254
  // v3.1.2:文件列表(文件选择器用;纯增量字段,旧版 App 忽略)
7878
10255
  const files = entries
7879
- .filter((entry) => entry.isFile() && !entry.name.startsWith("."))
10256
+ .filter((entry) => entry.isFile() && directoryEntryVisible(entry.name, includeHidden))
7880
10257
  .map((entry) => entry.name)
7881
10258
  .sort((a, b) => a.localeCompare(b, "zh-CN"));
7882
10259
  // v3.2.3:文件元数据(大小/修改时间/MIME);files 保持纯字符串以兼容旧 App。
7883
10260
  const fileEntries = entries
7884
- .filter((entry) => entry.isFile() && !entry.name.startsWith("."))
10261
+ .filter((entry) => entry.isFile() && directoryEntryVisible(entry.name, includeHidden))
7885
10262
  .map((entry) => {
7886
10263
  let size = null;
7887
10264
  let mtimeMs = null;
@@ -7940,74 +10317,475 @@ export function apply(ctx, config, runtime = {}) {
7940
10317
  .some((part) => part === "*" || part === etag);
7941
10318
  };
7942
10319
 
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",
10320
+ /**
10321
+ * 文件字节响应(v3.2.3 语义):Range/HEAD/ETag/If-None-Match/304/416 +
10322
+ * `connection: close`。`/files` 与 `/turn-file` 共用同一实现,避免头部语义漂移。
10323
+ * 文件不可读时抛错,由调用方映射成各自的稳定错误码。
10324
+ * @returns {true} 已写出响应(调用方仍应 return)。
10325
+ */
10326
+ const serveFileBytes = (req, res, target, { method }) => {
10327
+ const st = statSync(target);
10328
+ if (!st.isFile()) throw Object.assign(new Error("not-a-file"), { code: "not-a-file" });
10329
+ const name = basename(target);
10330
+ // 保留时间精度并纳入 ctime,避免同大小改写且恢复 mtime 后沿用旧断点。
10331
+ const etag = `"${st.size.toString(16)}-${st.mtimeMs.toString(16)}-${st.ctimeMs.toString(16)}"`;
10332
+ const lastModified = new Date(st.mtimeMs).toUTCString();
10333
+ guardRes(res);
10334
+ if (ifNoneMatch(req, etag)) {
10335
+ res.writeHead(304, { etag, "cache-control": "no-store", connection: "close" });
10336
+ res.end();
10337
+ return true;
10338
+ }
10339
+ // 断点属于旧文件时从头返回,不能把旧前缀和新后缀拼在一起。
10340
+ // 只认可当前强 ETag;旧标记/弱 ETag/日期统一退回完整响应。
10341
+ const ifRange = requestHeaderText(req, "if-range").trim();
10342
+ const range = parseByteRange(ifRange && ifRange !== etag ? "" : requestHeaderText(req, "range"), st.size);
10343
+ if (range && range.invalid) {
10344
+ res.writeHead(416, {
7981
10345
  "accept-ranges": "bytes",
10346
+ "content-range": `bytes */${st.size}`,
10347
+ "content-length": "0",
7982
10348
  etag,
7983
- "last-modified": lastModified,
7984
- // v3.1.5+39:取完即断(半关连接复用会让手机侧等满超时)
10349
+ "cache-control": "no-store",
7985
10350
  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;
10351
+ });
10352
+ res.end();
10353
+ return true;
10354
+ }
10355
+ const start = range ? range.start : 0;
10356
+ const end = range ? range.end : st.size - 1;
10357
+ const length = st.size === 0 ? 0 : end - start + 1;
10358
+ const headers = {
10359
+ "content-type": fileMimeOf(name),
10360
+ "content-length": String(length),
10361
+ "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
10362
+ "cache-control": "no-store",
10363
+ "accept-ranges": "bytes",
10364
+ etag,
10365
+ "last-modified": lastModified,
10366
+ // v3.1.5+39:取完即断(半关连接复用会让手机侧等满超时)
10367
+ connection: "close",
10368
+ ...(range ? { "content-range": `bytes ${start}-${end}/${st.size}` } : {}),
10369
+ };
10370
+ res.writeHead(range ? 206 : 200, headers);
10371
+ if (method === "HEAD" || st.size === 0) {
10372
+ res.end();
10373
+ return true;
10374
+ }
10375
+ const source = createReadStream(target, { start, end });
10376
+ // 客户端取消/断开时销毁文件流,避免 fd 泄漏。
10377
+ res.on("close", () => {
10378
+ try {
10379
+ source.destroy();
10380
+ } catch {
10381
+ // 已销毁
10382
+ }
10383
+ });
10384
+ source.on("error", () => {
10385
+ try {
10386
+ res.destroy();
10387
+ } catch {
10388
+ // 已销毁
7992
10389
  }
7993
- const source = createReadStream(target, { start, end });
7994
- // 客户端取消/断开时销毁文件流,避免 fd 泄漏。
7995
- res.on("close", () => {
10390
+ });
10391
+ source.pipe(res);
10392
+ return true;
10393
+ };
10394
+ /** 非负整数查询参数;缺失/非法都返回 null(调用方按 400 处理)。 */
10395
+ const nonNegativeIntParam = (raw) => {
10396
+ if (raw === null) return null;
10397
+ if (raw.trim() === "") return null;
10398
+ const value = Number(raw);
10399
+ if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) return null;
10400
+ return value;
10401
+ };
10402
+
10403
+ // ── v3.3(issue #53):轮末产出物(改动摘要 / 单文件对比 / 按坐标取文件) ──
10404
+ if (rest === "/changes/summary") {
10405
+ if (requireGet(method, res)) return;
10406
+ const sessionId = url.searchParams.get("sessionId");
10407
+ const turn = nonNegativeIntParam(url.searchParams.get("turn"));
10408
+ if (!sessionId) return error(res, 400, "bad-request", "missing sessionId or turn");
10409
+ if (turn === null) return error(res, 400, "bad-request", "turn must be a non-negative integer");
10410
+ const sessions = ctx.get("sessions");
10411
+ if (!sessions) return error(res, 503, "sessions-unavailable");
10412
+ // 服务不可用/会话休眠/摘要失效统一按 state 返回(不 5xx),App 统一降级不占位。
10413
+ const unavailable = { ok: true, state: "unavailable", turn, files: [], total: 0, added: 0, deleted: 0, truncated: false };
10414
+ const workspaceChanges = ctx.get("workspaceChanges");
10415
+ if (!workspaceChanges || typeof workspaceChanges.summary !== "function") return sendJson(res, 200, unavailable);
10416
+ const session = sessions.get(sessionId);
10417
+ if (!session) return sendJson(res, 200, unavailable);
10418
+ const source = latestWorkspaceChangesEvent(session, turn);
10419
+ if (!source) return sendJson(res, 200, { ...unavailable, state: "absent" });
10420
+ let summary;
10421
+ try {
10422
+ summary = workspaceChanges.summary(sessionId, source.seq);
10423
+ } catch (err) {
10424
+ ctx.logger.warn?.(`mobile-remote: changes.summary 读取失败(${sessionId}/${turn}):${failureDetail(err)}`);
10425
+ return sendJson(res, 200, unavailable);
10426
+ }
10427
+ if (!summary || !Array.isArray(summary.files)) return sendJson(res, 200, unavailable);
10428
+ const allFiles = summary.files;
10429
+ // issue #60 round7(F2):presented 的 cwd 来自 sessionCwdOf(session)(header.cwd),
10430
+ // changed 的 cwd 来自宿主 workspaceChanges.summary().cwd,**两者文本/基准不保证相同**
10431
+ // (同一 display 下会算出两个逻辑 id → App 行内/basename 链接丢失)。两条投影统一用
10432
+ // 「会话 base」:会话 cwd 优先、宿主摘要 cwd 兜底,再交给 canonicalWorkspacePath
10433
+ // 按 realpath 归一(消掉 symlink 别名 / 绝对路径形状差异)。绝不把 cwd 写进响应。
10434
+ // 真宿主 dsh-workspace-changes 的 recorderFor(session, cwd) 冻结 cwd=session.header.cwd
10435
+ // 并作为 summary.cwd 返回,故生产里两者本就相同;这里用会话 base 兜底裁剪/旧宿主。
10436
+ // 已知 P3 接受:① 裁剪宿主把 header.cwd 与 summary.cwd 指向不同子目录、且两处
10437
+ // 记录各自相对该 cwd 的文本时,单一 base 无法同时对齐(非真宿主形状);
10438
+ // ② 两处 cwd 都缺失且绝对/相对混排时无基准可归一(live 会话 header.cwd 必存在)。
10439
+ const idBase = sessionCwdOf(session) ?? summary.cwd;
10440
+ const files = allFiles.slice(0, TURN_TAIL_MAX_FILES).map((file, index) => {
10441
+ const recordedPath = typeof file?.path === "string" ? file.path : "";
10442
+ // issue #60 R05:宿主 display 可能是 cwd/home 外的**绝对路径**(合法宿主形状);
10443
+ // 一律从记录路径 + 会话 cwd 重新派生安全 display,绝不直通宿主 display。
10444
+ const displaySource = recordedPath !== "" ? recordedPath : (typeof file?.display === "string" ? file.display : "");
10445
+ const display = mobileDisplayPath(displaySource, idBase) || posixBasenameOf(displaySource);
10446
+ return {
10447
+ seq: source.seq,
10448
+ index,
10449
+ // round4-2:与 presented 共用同一路径摘要,供 App 按逻辑身份合并
10450
+ // delivered/changed;不含可拼路径。
10451
+ id: recordFileId(recordedPath, idBase),
10452
+ display,
10453
+ name: posixBasenameOf(recordedPath || display),
10454
+ added: Number.isFinite(file?.added) ? Math.max(0, Math.trunc(file.added)) : 0,
10455
+ deleted: Number.isFinite(file?.deleted) ? Math.max(0, Math.trunc(file.deleted)) : 0,
10456
+ binary: file?.binary === true,
10457
+ oversized: file?.oversized === true,
10458
+ };
10459
+ });
10460
+ return sendJson(res, 200, {
10461
+ ok: true,
10462
+ state: "available",
10463
+ turn,
10464
+ files,
10465
+ total: Number.isFinite(summary.total) ? Math.max(0, Math.trunc(summary.total)) : allFiles.length,
10466
+ added: Number.isFinite(summary.added) ? Math.max(0, Math.trunc(summary.added)) : 0,
10467
+ deleted: Number.isFinite(summary.deleted) ? Math.max(0, Math.trunc(summary.deleted)) : 0,
10468
+ // 宿主 maxFiles 或移动端 200 上限任一截断都显式标记;total 仍是全量计数。
10469
+ truncated: allFiles.length > TURN_TAIL_MAX_FILES || (Number.isFinite(summary.total) && summary.total > allFiles.length),
10470
+ });
10471
+ }
10472
+ if (rest === "/changes/diff") {
10473
+ if (requireGet(method, res)) return;
10474
+ const sessionId = url.searchParams.get("sessionId");
10475
+ const turn = nonNegativeIntParam(url.searchParams.get("turn"));
10476
+ const index = nonNegativeIntParam(url.searchParams.get("index"));
10477
+ if (!sessionId) return error(res, 400, "bad-request", "missing sessionId, turn or index");
10478
+ if (turn === null || index === null) return error(res, 400, "bad-request", "turn/index must be non-negative integers");
10479
+ const sessions = ctx.get("sessions");
10480
+ if (!sessions) return error(res, 503, "changes-unavailable");
10481
+ const workspaceChanges = ctx.get("workspaceChanges");
10482
+ if (!workspaceChanges || typeof workspaceChanges.diff !== "function") return error(res, 503, "changes-unavailable");
10483
+ // 摘要只随 live 会话存在:休眠/重启后没有可对比内容(§6.22)。
10484
+ const session = sessions.get(sessionId);
10485
+ const source = session ? latestWorkspaceChangesEvent(session, turn) : null;
10486
+ if (!source) return error(res, 404, "diff-not-found");
10487
+ let diff;
10488
+ try {
10489
+ diff = await workspaceChanges.diff(sessionId, source.seq, index, requestAbort(res));
10490
+ } catch (err) {
10491
+ if (res.destroyed || res.writableEnded) return;
10492
+ ctx.logger.warn?.(`mobile-remote: changes.diff 读取失败(${sessionId}/${turn}/${index}):${failureDetail(err)}`);
10493
+ return error(res, 503, "changes-unavailable");
10494
+ }
10495
+ if (!diff) return error(res, 404, "diff-not-found");
10496
+ // issue #60 R05:diff 的 display 同样不得直通宿主(可能是绝对路径);从 diff.path
10497
+ // 与会话 cwd 重新派生,并让统一 diff 的 ---/+++ 标头使用同一安全值。
10498
+ const diffPathSource = typeof diff.path === "string" && diff.path !== "" ? diff.path : (typeof diff.display === "string" ? diff.display : "");
10499
+ const safeDisplay = mobileDisplayPath(diffPathSource, sessionCwdOf(session)) || posixBasenameOf(diffPathSource);
10500
+ if (diff.kind === "binary" || diff.kind === "oversized") {
10501
+ return sendJson(res, 200, {
10502
+ ok: true,
10503
+ state: "available",
10504
+ diff: { kind: diff.kind, display: safeDisplay },
10505
+ });
10506
+ }
10507
+ const rendered = renderUnifiedDiffText(diff, safeDisplay);
10508
+ return sendJson(res, 200, {
10509
+ ok: true,
10510
+ state: "available",
10511
+ diff: {
10512
+ kind: "text",
10513
+ display: safeDisplay,
10514
+ before: diff.before !== false,
10515
+ after: diff.after !== false,
10516
+ coarse: diff.coarse === true,
10517
+ diff: rendered.text,
10518
+ truncated: rendered.truncated,
10519
+ },
10520
+ });
10521
+ }
10522
+ if (rest === "/turn-file" && (method === "GET" || method === "HEAD")) {
10523
+ const sessionId = url.searchParams.get("sessionId");
10524
+ const kind = url.searchParams.get("kind");
10525
+ const seq = nonNegativeIntParam(url.searchParams.get("seq"));
10526
+ const index = nonNegativeIntParam(url.searchParams.get("index"));
10527
+ if (!sessionId || (kind !== "presented" && kind !== "changed")) return error(res, 400, "bad-request", "missing sessionId or invalid kind");
10528
+ if (seq === null || index === null) return error(res, 400, "bad-request", "seq/index must be non-negative integers");
10529
+ const sessions = ctx.get("sessions");
10530
+ if (!sessions) return error(res, 503, "sessions-unavailable");
10531
+ let target = null;
10532
+ if (kind === "presented") {
10533
+ // 路径只从会话记录里解析:客户端只给坐标,不能指定路径(GitLab #16 收紧方向)。
10534
+ const query = ctx.get("sessionQuery");
10535
+ let event = null;
10536
+ let cwd;
10537
+ if (typeof query?.readEvent === "function") {
7996
10538
  try {
7997
- source.destroy();
10539
+ const read = await query.readEvent({ sessionId, seq });
10540
+ event = read?.target ?? read?.event ?? read?.value ?? null;
10541
+ cwd = read?.session?.cwd ?? read?.header?.cwd;
7998
10542
  } catch {
7999
- // 已销毁
10543
+ event = null;
8000
10544
  }
8001
- });
8002
- source.on("error", () => {
10545
+ }
10546
+ const liveSession = sessions.get(sessionId);
10547
+ if (!event && liveSession) {
10548
+ event = eventBySeq(liveSession, seq);
10549
+ cwd ??= sessionCwdOf(liveSession);
10550
+ }
10551
+ if (!event && typeof query?.readSession === "function") {
8003
10552
  try {
8004
- res.destroy();
10553
+ const snapshot = await query.readSession(sessionId);
10554
+ event = (snapshot?.events ?? []).find((candidate) => Number(candidate?.seq) === seq) ?? null;
10555
+ cwd ??= snapshot?.session?.cwd ?? snapshot?.header?.cwd;
8005
10556
  } catch {
8006
- // 已销毁
10557
+ event = null;
8007
10558
  }
8008
- });
8009
- source.pipe(res);
10559
+ }
10560
+ const file = presentedEventFilesOf(event, index);
10561
+ if (!file) return error(res, 404, "record-not-found");
10562
+ cwd ??= sessionCwdOf(liveSession);
10563
+ target = resolveRecordedPath(file.path, cwd);
10564
+ if (!target) return error(res, 404, "record-not-found");
10565
+ } else {
10566
+ const workspaceChanges = ctx.get("workspaceChanges");
10567
+ if (!workspaceChanges || typeof workspaceChanges.summary !== "function") return error(res, 503, "changes-unavailable");
10568
+ const session = sessions.get(sessionId);
10569
+ // 改动摘要只随 live 会话存在:休眠/重启后没有可解析的路径(§6.23)。
10570
+ if (!session) return error(res, 503, "changes-unavailable");
10571
+ let summary;
10572
+ try {
10573
+ summary = workspaceChanges.summary(sessionId, seq);
10574
+ } catch {
10575
+ summary = undefined;
10576
+ }
10577
+ if (!summary || !Array.isArray(summary.files)) return error(res, 503, "changes-unavailable");
10578
+ const file = summary.files[index];
10579
+ if (!file || typeof file?.path !== "string" || file.path === "") return error(res, 404, "record-not-found");
10580
+ target = resolveRecordedPath(file.path, summary.cwd);
10581
+ if (!target) return error(res, 404, "record-not-found");
10582
+ }
10583
+ try {
10584
+ serveFileBytes(req, res, target, { method });
10585
+ } catch {
10586
+ // 记录里的文件已被删除/不可读:不泄露主机路径。
10587
+ return error(res, 404, "file-not-found");
10588
+ }
10589
+ return;
10590
+ }
10591
+ // issue #98:工作区外图片的会话授权(once / session-directory)。
10592
+ if (rest === "/workspace-image/consent") {
10593
+ if (method !== "POST") return error(res, 405, "method-not-allowed");
10594
+ let body;
10595
+ try {
10596
+ const text = await readBody(req, 16 * 1024);
10597
+ body = text ? JSON.parse(text) : {};
10598
+ } catch {
10599
+ return error(res, 400, "bad-request", "body must be JSON");
10600
+ }
10601
+ const sessionId = typeof body?.sessionId === "string" ? body.sessionId : "";
10602
+ const rawPath = typeof body?.path === "string" ? body.path : "";
10603
+ const scope = body?.scope === "session-directory" ? "session-directory" : body?.scope === "once" ? "once" : "";
10604
+ if (sessionId === "" || rawPath === "" || rawPath.includes("\0") || scope === "") {
10605
+ return error(res, 400, "bad-request", "sessionId/path/scope required");
10606
+ }
10607
+ const agents = ctx.get("agents");
10608
+ const sessions = ctx.get("sessions");
10609
+ const liveSession = agents?.get?.(sessionId)?.session;
10610
+ const session = liveSession ?? sessions?.get?.(sessionId);
10611
+ if (!session) return error(res, 404, "session-not-found");
10612
+ const cwd = sessionCwdOf(session);
10613
+ if (typeof cwd !== "string" || cwd === "") return error(res, 404, "workspace-not-found");
10614
+ const cwdLex = resolve(normalizeServerPath(cwd));
10615
+ let candidateLex;
10616
+ try {
10617
+ const normalized = normalizeServerPath(rawPath);
10618
+ candidateLex = isAbsolute(normalized) ? resolve(normalized) : resolve(cwdLex, normalized);
10619
+ } catch {
10620
+ return error(res, 400, "bad-request", "invalid path");
10621
+ }
10622
+ const regexExtension = extname(candidateLex).toLowerCase();
10623
+ const expectedType = IMAGE_EXTENSIONS.get(regexExtension);
10624
+ if (!expectedType) return error(res, 415, "unsupported-image-type");
10625
+ // 前置:会话 cwd 必须属于登记工作区(授权不改变工作区前置)。
10626
+ const registry = ctx.get("workspaceRegistry");
10627
+ const listed = registry?.list?.();
10628
+ const workspaces = Array.isArray(listed) ? listed : [];
10629
+ let realCwd;
10630
+ let cwdInWorkspace = false;
10631
+ let workspaceRoots = [];
10632
+ try { realCwd = realpathSync(cwdLex); } catch { return error(res, 404, "workspace-not-found"); }
10633
+ for (const entry of workspaces) {
10634
+ const root = entry?.path;
10635
+ if (typeof root !== "string" || root === "") continue;
10636
+ try {
10637
+ const realRoot = realpathSync(root);
10638
+ workspaceRoots.push(realRoot);
10639
+ if (relative(realRoot, realCwd) === "" || (!relative(realRoot, realCwd).startsWith("..") && !isAbsolute(relative(realRoot, realCwd)))) {
10640
+ cwdInWorkspace = true;
10641
+ }
10642
+ } catch {}
10643
+ }
10644
+ if (!cwdInWorkspace) return error(res, 403, "workspace-not-authorized");
10645
+ // issue #98 P3:GET 用 O_NOFOLLOW,末级 symlink 永远无法通过 fd 校验;
10646
+ // consent 端点提前拒绝,避免“授权后仍 403”的死循环。
10647
+ try {
10648
+ if (lstatSync(candidateLex).isSymbolicLink()) {
10649
+ return error(res, 415, "unsupported-image-symlink");
10650
+ }
10651
+ } catch {
10652
+ return error(res, 404, "image-not-found");
10653
+ }
10654
+ let realTarget;
10655
+ try { realTarget = realpathSync(candidateLex); } catch { return error(res, 404, "image-not-found"); }
10656
+ let targetStat;
10657
+ try { targetStat = statSync(realTarget); } catch { return error(res, 404, "image-not-found"); }
10658
+ if (!targetStat.isFile() || targetStat.size <= 0) return error(res, 404, "image-not-found");
10659
+ if (targetStat.size > IMAGE_MAX_BYTES) return error(res, 413, "image-too-large");
10660
+ let head;
10661
+ try { head = readFileSync(realTarget); } catch { return error(res, 404, "image-not-found"); }
10662
+ if (head.length > IMAGE_MAX_BYTES) return error(res, 413, "image-too-large");
10663
+ const sniffed = sniffImageBufferType(head);
10664
+ if (!sniffed || sniffed !== expectedType) return error(res, 415, "unsupported-image-type");
10665
+ const dims = imageDimensions(head);
10666
+ if (!dims) return error(res, 415, "unsupported-image-type");
10667
+ if (dims.width <= 0 || dims.height <= 0 ||
10668
+ dims.width > IMAGE_MAX_DIMENSION || dims.height > IMAGE_MAX_DIMENSION ||
10669
+ dims.width * dims.height > IMAGE_MAX_PIXELS) return error(res, 413, "image-too-large");
10670
+ let record = { sessionId, scope, realPath: realTarget, realDir: null };
10671
+ if (scope === "session-directory") {
10672
+ const realDir = dirname(realTarget);
10673
+ if (realDir === "/" || realDir === realpathSync(homedir()) ||
10674
+ workspaceRoots.some((root) => realDir === root)) {
10675
+ return error(res, 403, "consent-root-not-allowed");
10676
+ }
10677
+ record = { ...record, realDir };
10678
+ }
10679
+ let issued;
10680
+ try { issued = imageConsentStore.issue(record); }
10681
+ catch { return error(res, 400, "bad-request", "invalid consent scope"); }
10682
+ return sendJson(res, 200, { ok: true, ...issued });
10683
+ }
10684
+ if (rest === "/workspace-image") {
10685
+ if (method !== "GET" && method !== "HEAD") return error(res, 405, "method-not-allowed");
10686
+ // issue #94/#98:工作区内图片无需授权;工作区外必须携带有效 consentId。
10687
+ // fd/O_NOFOLLOW/proc containment、图片类型/大小/像素限制始终执行。
10688
+ const sessionId = url.searchParams.get("sessionId") ?? "";
10689
+ if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
10690
+ const rawPath = url.searchParams.get("path");
10691
+ if (!rawPath || rawPath.includes("\0")) return error(res, 400, "bad-request", "missing path");
10692
+ const agents = ctx.get("agents");
10693
+ const sessions = ctx.get("sessions");
10694
+ const liveSession = agents?.get?.(sessionId)?.session;
10695
+ const session = liveSession ?? sessions?.get?.(sessionId);
10696
+ if (!session) return error(res, 404, "session-not-found");
10697
+ const cwd = sessionCwdOf(session);
10698
+ if (typeof cwd !== "string" || cwd === "") return error(res, 404, "workspace-not-found");
10699
+ const cwdLex = resolve(normalizeServerPath(cwd));
10700
+ let candidateLex;
10701
+ try {
10702
+ const normalized = normalizeServerPath(rawPath);
10703
+ candidateLex = isAbsolute(normalized) ? resolve(normalized) : resolve(cwdLex, normalized);
10704
+ } catch {
10705
+ return error(res, 400, "bad-request", "invalid path");
10706
+ }
10707
+ const inside = (parent, child) => {
10708
+ const rel = relative(parent, child);
10709
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
10710
+ };
10711
+ const insideCwd = inside(cwdLex, candidateLex);
10712
+ const extension = extname(candidateLex).toLowerCase();
10713
+ const expectedType = IMAGE_EXTENSIONS.get(extension);
10714
+ if (!expectedType) return error(res, 415, "unsupported-image-type");
10715
+ let realCwd;
10716
+ try { realCwd = realpathSync(cwdLex); } catch { return error(res, 404, "workspace-not-found"); }
10717
+ const registry = ctx.get("workspaceRegistry");
10718
+ const listed = registry?.list?.();
10719
+ const workspaces = Array.isArray(listed) ? listed : [];
10720
+ const workspaceRoots = [];
10721
+ let cwdInWorkspace = false;
10722
+ for (const entry of workspaces) {
10723
+ const root = entry?.path;
10724
+ if (typeof root !== "string" || root === "") continue;
10725
+ try {
10726
+ const realRoot = realpathSync(root);
10727
+ workspaceRoots.push(realRoot);
10728
+ if (inside(realRoot, realCwd)) cwdInWorkspace = true;
10729
+ } catch {}
10730
+ }
10731
+ if (!cwdInWorkspace) return error(res, 403, "workspace-not-authorized");
10732
+ const consentId = url.searchParams.get("consentId") ?? "";
10733
+ let consent = null;
10734
+ if (!insideCwd) {
10735
+ if (consentId === "") return error(res, 403, "consent-required");
10736
+ consent = imageConsentStore.lookup(consentId, sessionId);
10737
+ if (!consent) return error(res, 403, "consent-invalid");
10738
+ }
10739
+ const opened = openVerifiedWorkspaceImage({
10740
+ candidateLex,
10741
+ cwdReal: realCwd,
10742
+ workspaceRoots,
10743
+ expectedType,
10744
+ consent,
10745
+ });
10746
+ if (!opened.ok) return error(res, opened.status, opened.code);
10747
+ const bytes = opened.bytes;
10748
+ if (bytes.length === 0) return error(res, 404, "image-not-found");
10749
+ if (bytes.length > IMAGE_MAX_BYTES) return error(res, 413, "image-too-large");
10750
+ const sniffed = sniffImageBufferType(bytes);
10751
+ if (!sniffed || sniffed !== expectedType) return error(res, 415, "unsupported-image-type");
10752
+ const dims = imageDimensions(bytes);
10753
+ if (!dims) return error(res, 415, "unsupported-image-type");
10754
+ if (dims.width <= 0 || dims.height <= 0 ||
10755
+ dims.width > IMAGE_MAX_DIMENSION || dims.height > IMAGE_MAX_DIMENSION ||
10756
+ dims.width * dims.height > IMAGE_MAX_PIXELS) {
10757
+ return error(res, 413, "image-too-large");
10758
+ }
10759
+ const etag = `"${createHash("sha256").update(bytes).digest("hex").slice(0, 32)}"`;
10760
+ const headers = {
10761
+ "content-type": sniffed,
10762
+ "content-length": String(bytes.length),
10763
+ "cache-control": "private, max-age=86400",
10764
+ etag,
10765
+ "x-content-type-options": "nosniff",
10766
+ connection: "close",
10767
+ };
10768
+ if (String(req.headers?.["if-none-match"] ?? "") === etag) {
10769
+ res.writeHead(304, { etag, "cache-control": headers["cache-control"], connection: "close" });
10770
+ res.end();
10771
+ return;
10772
+ }
10773
+ res.writeHead(200, headers);
10774
+ if (method === "HEAD") {
10775
+ res.end();
10776
+ return;
10777
+ }
10778
+ res.end(bytes);
10779
+ return;
10780
+ }
10781
+ if (rest === "/files" && (method === "GET" || method === "HEAD")) {
10782
+ const path = url.searchParams.get("path");
10783
+ if (!path || path === "") return error(res, 400, "bad-request", "missing path");
10784
+ const target = resolve(normalizeServerPath(path));
10785
+ try {
10786
+ serveFileBytes(req, res, target, { method });
8010
10787
  } catch (err) {
10788
+ if (err?.code === "not-a-file") return error(res, 400, "not-a-file", "path is not a file");
8011
10789
  return error(res, 404, "file-not-found", failureDetail(err)); // v3.1.5 S7:不再回主机绝对路径(含进程 cwd)
8012
10790
  }
8013
10791
  return;
@@ -8125,7 +10903,9 @@ export function apply(ctx, config, runtime = {}) {
8125
10903
  // issue #20:与 /sessions 同一条全量枚举路径,宿主目录与持久化回退都接入请求取消。
8126
10904
  const signal = requestAbort(res);
8127
10905
  const parent = sessions?.get?.(parentSessionId);
8128
- const hasCatalog = typeof subagentsSvc?.listChildren === "function";
10906
+ // issue #87:rc.2 用 listDescendants(递归,需 depth===1 收窄);rc.1 回退 listChildren。
10907
+ const hasDescendants = typeof subagentsSvc?.listDescendants === "function";
10908
+ const hasChildren = typeof subagentsSvc?.listChildren === "function";
8129
10909
  // 目录来源按优先级取——**两边能力都要保留**(issue #14/#17/#21):
8130
10910
  // ① 宿主持久目录 `subagents.listChildren`:包含已释放子代理和 mode/label 元数据,
8131
10911
  // 不要求父会话有活跃 Agent;
@@ -8134,11 +10914,35 @@ export function apply(ctx, config, runtime = {}) {
8134
10914
  // 状态另取自活 agent(AgentStatus = idle | running);目录条目本身不带状态。
8135
10915
  let catalogRows = null;
8136
10916
  let catalogDegraded = false;
8137
- if (hasCatalog) {
10917
+ // 决策 1(A):listDescendants 返回整棵树,只取直接子级 depth===1。
10918
+ if (hasDescendants) {
10919
+ try {
10920
+ const rows = await subagentsSvc.listDescendants(parentSessionId, signal);
10921
+ if (signal.aborted) return;
10922
+ if (Array.isArray(rows)) {
10923
+ catalogRows = rows
10924
+ .filter((row) => row?.depth === 1)
10925
+ .map((row) => ({
10926
+ ...row,
10927
+ // rc.2 diagnostic 行没有 mode,只有 kind + reason;不要用 mode 判分支。
10928
+ diagnosticReason: row?.kind === "diagnostic" ? row.reason : undefined,
10929
+ }));
10930
+ }
10931
+ } catch {
10932
+ if (signal.aborted) return;
10933
+ catalogRows = null; // 目录读取失败 → 回退 listChildren / 持久化枚举
10934
+ }
10935
+ }
10936
+ if (catalogRows === null && hasChildren) {
8138
10937
  try {
8139
10938
  const rows = await subagentsSvc.listChildren(parentSessionId, signal);
8140
10939
  if (signal.aborted) return;
8141
- if (Array.isArray(rows)) catalogRows = rows;
10940
+ if (Array.isArray(rows)) {
10941
+ catalogRows = rows.map((row) => ({
10942
+ ...row,
10943
+ diagnosticReason: row?.mode === "unknown" ? "unsupported" : undefined,
10944
+ }));
10945
+ }
8142
10946
  } catch {
8143
10947
  if (signal.aborted) return; // 客户端已离开,不再触发回退或写响应
8144
10948
  catalogRows = null; // 目录读取失败 → 落到持久化枚举
@@ -8191,7 +10995,17 @@ export function apply(ctx, config, runtime = {}) {
8191
10995
  const label = typeof row?.label === "string" && row.label !== "" ? row.label : undefined;
8192
10996
  const rowTitle = typeof row?.title === "string" && row.title !== "" ? row.title : undefined;
8193
10997
  const liveTitle = sessionTitleOf(session);
8194
- return { id, live, createdAt, label, rowTitle, liveTitle, mode: row?.mode };
10998
+ const diagnosticReason = ["unsupported", "corrupt", "unavailable"].includes(row?.diagnosticReason)
10999
+ ? row.diagnosticReason
11000
+ : undefined;
11001
+ const isDiagnostic = row?.kind === "diagnostic" ||
11002
+ row?.diagnosticReason !== undefined ||
11003
+ row?.mode === "unknown";
11004
+ return {
11005
+ id, live, createdAt, label, rowTitle, liveTitle,
11006
+ rowName: typeof row?.name === "string" && row.name !== "" ? row.name : undefined,
11007
+ isDiagnostic, diagnosticReason,
11008
+ };
8195
11009
  }).filter((row) => row.id !== "");
8196
11010
  // issue #30 评审 WARNING 1:目录条目的 `label` 可省略,而**已释放**的子代理不在 live
8197
11011
  // 注册表里(拿不到会话快照标题)。三个来源都拿不到时必须按需**补读持久标题**,
@@ -8206,18 +11020,16 @@ export function apply(ctx, config, runtime = {}) {
8206
11020
  const entries = rows
8207
11021
  .map((row) => ({
8208
11022
  id: row.id,
8209
- // issue #30 评审 WARNING 2:目录 `mode: "unknown"` 是宿主明确判定的**不受支持
8210
- // 条目**(宿主 `listDescendants` 映射为 diagnostic/unsupported),不能伪装成
8211
- // 普通闲置子代理——否则消费者无法区分"不受支持"与"正常闲置",等于删掉 RPC 时
8212
- // 顺带静默删掉既有诊断语义(docs/03-api 承诺 `status` 可为 diagnostic reason)。
8213
- kind: row.mode === "unknown" ? "diagnostic" : "child",
11023
+ // issue #87:rc.2 diagnostic 用 kind==='diagnostic' 判定(无 mode 字段);
11024
+ // reason 映射为三枚举 status:unsupported / corrupt / unavailable(决策 3 C)。
11025
+ kind: row.isDiagnostic ? "diagnostic" : "child",
8214
11026
  // 状态取自活 agent;已结束/已释放的子代理回落 inactive(与既有语义一致)
8215
- status: row.mode === "unknown"
8216
- ? "unsupported"
11027
+ status: row.isDiagnostic
11028
+ ? (row.diagnosticReason ?? "unsupported")
8217
11029
  : (typeof row.live?.status === "string" && row.live.status !== ""
8218
11030
  ? (row.live.status === "running" ? "running" : "inactive") // AgentStatus = 'idle' | 'running'
8219
11031
  : "inactive"),
8220
- title: row.label ?? row.rowTitle ?? row.liveTitle ?? persistedTitleMap.get(row.id) ?? shortSessionId(row.id),
11032
+ title: row.label ?? row.rowName ?? row.rowTitle ?? row.liveTitle ?? persistedTitleMap.get(row.id) ?? shortSessionId(row.id),
8221
11033
  ...(row.createdAt === undefined ? {} : { createdAt: row.createdAt }),
8222
11034
  }))
8223
11035
  .sort((a, b) => {
@@ -8245,13 +11057,73 @@ export function apply(ctx, config, runtime = {}) {
8245
11057
  const childSessionId = typeof body.childSessionId === "string" ? body.childSessionId : "";
8246
11058
  if (!parentSessionId || !childSessionId) return error(res, 400, "parentSessionId-and-childSessionId-required");
8247
11059
  try {
8248
- await apiRpc("subagent.interrupt", { parentSessionId, childSessionId, mode: "continuable" });
8249
- sendJson(res, 200, { ok: true });
11060
+ const receipt = await apiRpc("subagent.interrupt", { parentSessionId, childSessionId, mode: "continuable" });
11061
+ // issue #87:rc.2 返回 SubagentInterruptReceipt({accepted}),语义是「中断信号已受理」,
11062
+ // 不等于目标已经静默;旧宿主无 receipt 时保持 {ok:true}。
11063
+ sendJson(res, 200, {
11064
+ ok: true,
11065
+ ...(receipt && typeof receipt.accepted === "boolean" ? { accepted: receipt.accepted } : {}),
11066
+ });
8250
11067
  } catch (err) {
8251
11068
  return error(res, ...rpcError(err, "subagent-interrupt-failed"));
8252
11069
  }
8253
11070
  return;
8254
11071
  }
11072
+ if (rest === "/skills") {
11073
+ if (method !== "GET" && method !== "HEAD") return error(res, 405, "method-not-allowed");
11074
+ // issue #90:只读技能目录(DSH ctx.skills.list 的透传)。
11075
+ // 仅下发 name/description/whenToUse/modelInvocable;不暴露 path/正文/资源。
11076
+ // 旧宿主/服务缺失/目录失败一律 200 + unavailable(不 5xx、不阻塞命令)。
11077
+ const sessionId = url.searchParams.get("sessionId") ?? "";
11078
+ if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
11079
+ const agents = ctx.get("agents");
11080
+ const presets = ctx.get("agentPresets");
11081
+ const sessions = ctx.get("sessions");
11082
+ const skillRegistryOf = (agent) => {
11083
+ try {
11084
+ const scoped = presets?.serviceFor?.(agent, "skills");
11085
+ if (scoped) return scoped;
11086
+ } catch {}
11087
+ return ctx.get("skills");
11088
+ };
11089
+ const listSkills = async (agent) => {
11090
+ const registry = skillRegistryOf(agent);
11091
+ if (!registry || typeof registry.list !== "function") return null;
11092
+ const cwd = agent?.session?.header?.cwd
11093
+ ?? sessions?.get?.(sessionId)?.header?.cwd
11094
+ ?? process.cwd();
11095
+ const skills = await registry.list({ cwd, scope: agent });
11096
+ return (Array.isArray(skills) ? skills : [])
11097
+ .filter((skill) => skill?.invocation?.userInvocable === true)
11098
+ .map((skill) => ({
11099
+ name: String(skill.name),
11100
+ description: String(skill.description ?? ""),
11101
+ ...(skill.whenToUse ? { whenToUse: String(skill.whenToUse) } : {}),
11102
+ modelInvocable: skill.invocation?.modelInvocable === true,
11103
+ }));
11104
+ };
11105
+ try {
11106
+ let agent = agents?.get?.(sessionId);
11107
+ if (!agent) {
11108
+ try { agent = (await resumeDormantAgent(sessionId))?.agent; } catch {}
11109
+ }
11110
+ if (!agent) {
11111
+ // 会话确实不存在:明确 404(与 /commands 一致),但技能目录缺失本身不会走到这里。
11112
+ return error(res, 404, "session-not-found", `session not found: ${sessionId}`);
11113
+ }
11114
+ const skills = await listSkills(agent);
11115
+ if (skills === null) {
11116
+ sendJson(res, 200, { ok: true, skills: [], unavailable: true });
11117
+ return;
11118
+ }
11119
+ sendJson(res, 200, { ok: true, skills });
11120
+ } catch (err) {
11121
+ // 技能目录不可用必须静默降级:命令菜单仍可用。
11122
+ ctx.logger.warn?.(`mobile-remote: skills list unavailable (${sessionId}): ${err?.message ?? err}`);
11123
+ sendJson(res, 200, { ok: true, skills: [], unavailable: true });
11124
+ }
11125
+ return;
11126
+ }
8255
11127
  if (rest === "/commands") {
8256
11128
  // v2.8.0:斜杠命令目录(对齐 PC 端 ctx.commands)——GET 列出、POST 执行
8257
11129
  // v2.8.2 适配:commands 服务可能未注册(desktop profile / 旧 DSH 无 dsh-commands host 服务)——
@@ -8404,7 +11276,7 @@ export function apply(ctx, config, runtime = {}) {
8404
11276
  const agents = ctx.get("agents");
8405
11277
  if (!agents) return error(res, 503, "agents-unavailable");
8406
11278
  const sessionId = typeof body?.sessionId === "string" && body.sessionId !== "" ? body.sessionId : undefined;
8407
- const agent = (sessionId ? agents.get(sessionId) : undefined) ?? agents.roots()[0];
11279
+ const agent = (sessionId ? agents.get(sessionId) : undefined) ?? firstAgent(agents);
8408
11280
  if (!agent) return error(res, 404, "no-live-agent");
8409
11281
  const synthetic = {
8410
11282
  agent,
@@ -8611,9 +11483,14 @@ export function apply(ctx, config, runtime = {}) {
8611
11483
  // 旧值空串让服务端只能靠 `find(e => e.rpcId === "")` 命中"第一个"条目——
8612
11484
  // 多会话并发接管时会张冠李戴。
8613
11485
  const holdApproval = (req, sessionId) => {
8614
- const phoneKey = `${sessionId}:${typeof req?.callId === "string" && req.callId !== ""
11486
+ // issue #60 R16:审批身份必须标识**这一次审批请求**,callId 只作关联。同一工具在
11487
+ // pre-execute 与工具体内 sandbox escalation 会复用 callId;若用 sessionId:callId
11488
+ // 作身份,App 会把第二次新审批误当成已解决请求重放而永久静默。
11489
+ // 因此每次实际请求生成唯一 approvalId;断线重连回放同一 entry 时 id 不变。
11490
+ const callRef = typeof req?.callId === "string" && req.callId !== ""
8615
11491
  ? req.callId
8616
- : Date.now().toString(36)}`;
11492
+ : Date.now().toString(36);
11493
+ const phoneKey = `${sessionId}:${callRef}:${randomUUID()}`;
8617
11494
  const phoneOnline = connections.size > 0;
8618
11495
  const holdMs = phoneOnline ? PENDING_TIMEOUT_MS : OFFLINE_HOLD_MS;
8619
11496
  ctx.logger.info?.(`mobile-remote: approval/request 手机接管(${sessionId} tool=${req?.toolName}${phoneOnline ? "" : `,手机离线,最多等待 ${Math.round(holdMs / 1000)}s`})`);
@@ -8689,14 +11566,11 @@ export function apply(ctx, config, runtime = {}) {
8689
11566
  if (!sessionId || !eventId) return;
8690
11567
  const request = frame.request ?? {};
8691
11568
  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}`;
11569
+ // issue #60 R16:$events 路径的身份必须标识**这一次实际审批请求**,callId 只作
11570
+ // 关联(同一工具 pre-execute 与 sandbox escalation 会复用同一个 callId)。
11571
+ // eventId 每次实际请求唯一,且宿主断线重放同一事件时保持不变——既不会让第二次
11572
+ // 新审批被第一次的 resolved 身份拦截,又保留重放去重(下面的 has())。
11573
+ const phoneKey = `${sessionId}:${eventId}`;
8700
11574
  if (pendingApprovals.has(phoneKey)) return;
8701
11575
  ctx.logger.info?.(`mobile-remote: approval/request 双端呈现(${sessionId} tool=${request?.toolName}${phoneOnline ? "" : ",手机离线→记账待回放"})`);
8702
11576
  const entry = {