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

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
@@ -11,7 +11,7 @@ import { networkInterfaces, homedir } from "node:os";
11
11
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
12
12
  import {
13
13
  accessSync, closeSync, constants, createReadStream, existsSync, fstatSync, linkSync, mkdirSync, openSync,
14
- readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, unlinkSync,
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";
@@ -80,11 +80,11 @@ import {
80
80
  acquireLock,
81
81
  convergeStaleTransaction,
82
82
  dependencyKeysFor,
83
- defaultIsPidAlive,
83
+ finishOwnedTerminal,
84
+ lockHolderAlive,
84
85
  findProfileDir,
85
86
  newOperationId,
86
87
  profileSpecifierOf,
87
- readLock,
88
88
  readTransaction,
89
89
  releaseLock,
90
90
  transactionFile,
@@ -806,10 +806,11 @@ export const TURN_TAIL_MAX_FILES = 200;
806
806
  export const TURN_TAIL_DIFF_MAX_BYTES = 512 * 1024;
807
807
 
808
808
  /**
809
- * M3(issue #54 Batch 1):本插件实际投影的工具集合与能力位。
809
+ * M3(issue #54 Batch 1 / issue #66 Batch 2-A):本插件实际投影的工具集合与能力位。
810
810
  *
811
811
  * App 以 `capabilities.toolCards.tools` 决定哪些工具用专用卡;未列入的工具(未知/自定义)
812
812
  * 一律回退现有通用卡。声明按**本插件实现**给出,不按宿主版本推断(ADR 0017)。
813
+ * issue #66:追加 todo_write / ask_user_question / skill 三个非文件工具(只增集合、version 不变)。
813
814
  */
814
815
  export const TOOL_CARD_TOOLS = Object.freeze([
815
816
  "bash",
@@ -822,11 +823,27 @@ export const TOOL_CARD_TOOLS = Object.freeze([
822
823
  "web_fetch",
823
824
  "web_search",
824
825
  "read_image",
826
+ "todo_write",
827
+ "ask_user_question",
828
+ "skill",
825
829
  ]);
826
830
  /** 工具卡结构化投影版本(只增不改)。 */
827
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;
828
840
  /** write/edit 摘要内联 diff 的体积上限(§issue #54 note 1761):超出缺省并标 diffTruncated。 */
829
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;
830
847
  /** 工具名 → 卡片 kind(未列入即通用卡)。 */
831
848
  const TOOL_CARD_KIND = Object.freeze({
832
849
  bash: "command",
@@ -839,8 +856,31 @@ const TOOL_CARD_KIND = Object.freeze({
839
856
  web_fetch: "web",
840
857
  web_search: "web",
841
858
  read_image: "image",
859
+ todo_write: "todo",
860
+ ask_user_question: "question",
861
+ skill: "skill",
842
862
  });
843
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
+
844
884
  /**
845
885
  * 冷折叠有界等待上限(issue #25 性能前置实测,2026-10-09):单会话最坏实测 1.8 s
846
886
  * (证据见 reports/25-cold-fold-20261009.md),并发时单会话仍 ≤1.8 s;5 s ≈3× 余量。
@@ -1038,10 +1078,16 @@ export function turnTailCapabilityOf(ctx) {
1038
1078
  /**
1039
1079
  * 工具卡能力位(issue #54):始终声明本插件实际投影的工具集合。
1040
1080
  * bootstrap 与 SSE hello 同判据、同形状;旧插件不下发 → App 全部回退通用卡。
1041
- * @returns {{version: number, tools: string[]}}
1081
+ * issue #68:追加 `ptc: { version: 1 }`(子调用树);键序保持 version→tools→ptc,
1082
+ * 既有 `"toolCards":{"version":1,"tools":` 文本断言不受影响。
1083
+ * @returns {{version: number, tools: string[], ptc: {version: number}}}
1042
1084
  */
1043
1085
  export function toolCardsCapabilityOf() {
1044
- return { version: TOOL_CARDS_CAPABILITY_VERSION, tools: [...TOOL_CARD_TOOLS] };
1086
+ return {
1087
+ version: TOOL_CARDS_CAPABILITY_VERSION,
1088
+ tools: [...TOOL_CARD_TOOLS],
1089
+ ptc: { version: TOOL_CARDS_PTC_VERSION },
1090
+ };
1045
1091
  }
1046
1092
 
1047
1093
  /**
@@ -1230,6 +1276,21 @@ export const isVisibleConversationMessage = (event) => {
1230
1276
  return kind === undefined || kind === null || kind === "user";
1231
1277
  };
1232
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
+
1233
1294
  /**
1234
1295
  * 会话列表排序键(ADR 0013):`lastMessageAt` → `lastActivity` → `createdAt`。
1235
1296
  * 后两级只为旧内核/旧插件降级保留,新版正常路径恒有 `lastMessageAt`。
@@ -1257,6 +1318,20 @@ export const latestMessageTimeOf = (events) => {
1257
1318
  return latest;
1258
1319
  };
1259
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
+
1260
1335
  /** 完整语料观测的新鲜度上限:超过它说明最近没人拉过列表,语料可能落后于新建会话。 */
1261
1336
  export const CORPUS_FRESH_MS = 30 * 60 * 1000;
1262
1337
 
@@ -1321,6 +1396,196 @@ const FILE_MIME = {
1321
1396
  ".js": "text/javascript; charset=utf-8", ".ts": "text/plain; charset=utf-8", ".py": "text/plain; charset=utf-8",
1322
1397
  ".html": "text/html; charset=utf-8", ".mp4": "video/mp4", ".apk": "application/vnd.android.package-archive",
1323
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
+
1324
1589
  const fileMimeOf = (name) => FILE_MIME[extname(name).toLowerCase()] ?? "application/octet-stream";
1325
1590
 
1326
1591
  /**
@@ -1723,6 +1988,94 @@ function readUpdateManifest(dir, basePath = "/m", origin = "") {
1723
1988
  return { ok: true, manifest, pluginServed, dir };
1724
1989
  }
1725
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
+
1726
2079
  /** image attachment 引用 → 移动端图片元数据(仅引用不含字节;渲染时 App 按 attachmentId 走 /attachment 端点拉取)。 */
1727
2080
  function imageMetaOf(ref) {
1728
2081
  if (!ref || typeof ref !== "object" || !ref.attachmentId) return null;
@@ -1938,6 +2291,102 @@ export function mobileDisplayPath(path, cwd) {
1938
2291
  return posixBasenameOf(canonicalPath);
1939
2292
  }
1940
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
+
1941
2390
  /**
1942
2391
  * 从会话事件折叠 `callId → tool/call.name`(issue #60 R14):结果事件通常不带工具名,
1943
2392
  * 调用方用它在投影前解析"这次调用是什么工具",避免无名字时从内容猜终止状态。
@@ -2074,11 +2523,20 @@ export function toolCallSummaryOf(toolName, rawArguments, cwd) {
2074
2523
  const summary = { kind, tool };
2075
2524
  const args = parseToolArguments(rawArguments);
2076
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 探测(见其头注释)。
2077
2530
  const displayOf = (value) => {
2078
2531
  if (typeof value !== "string" || value.trim() === "") return undefined;
2079
2532
  return clampText(mobileDisplayPath(value, cwd), 300);
2080
2533
  };
2081
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;
2082
2540
  switch (tool) {
2083
2541
  case "bash":
2084
2542
  case "pwsh": {
@@ -2095,6 +2553,7 @@ export function toolCallSummaryOf(toolName, rawArguments, cwd) {
2095
2553
  }
2096
2554
  case "read": {
2097
2555
  if (toolFilePath !== undefined) summary.filePath = toolFilePath;
2556
+ if (preview !== null) Object.assign(summary, preview);
2098
2557
  const offset = positiveIntArg(args.offset);
2099
2558
  if (offset !== undefined) summary.offset = offset;
2100
2559
  const limit = positiveIntArg(args.limit);
@@ -2103,6 +2562,7 @@ export function toolCallSummaryOf(toolName, rawArguments, cwd) {
2103
2562
  }
2104
2563
  case "write": {
2105
2564
  if (toolFilePath !== undefined) summary.filePath = toolFilePath;
2565
+ if (preview !== null) Object.assign(summary, preview);
2106
2566
  if (typeof args.content === "string") {
2107
2567
  // 与桌面 `NKB` 同口径:UTF-16 code unit 长度 / 1024 向上取整。
2108
2568
  summary.sizeKb = Math.ceil(args.content.length / 1024);
@@ -2114,6 +2574,7 @@ export function toolCallSummaryOf(toolName, rawArguments, cwd) {
2114
2574
  }
2115
2575
  case "edit": {
2116
2576
  if (toolFilePath !== undefined) summary.filePath = toolFilePath;
2577
+ if (preview !== null) Object.assign(summary, preview);
2117
2578
  const oldText = typeof args.old_string === "string" ? args.old_string : typeof args.oldString === "string" ? args.oldString : "";
2118
2579
  const newText = typeof args.new_string === "string" ? args.new_string : typeof args.newString === "string" ? args.newString : "";
2119
2580
  summary.sizeKb = Math.ceil((oldText.length + newText.length) / 1024);
@@ -2148,12 +2609,389 @@ export function toolCallSummaryOf(toolName, rawArguments, cwd) {
2148
2609
  }
2149
2610
  case "read_image": {
2150
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
+ }
2151
2685
  break;
2152
2686
  }
2153
2687
  }
2154
2688
  return summary;
2155
2689
  }
2156
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
+
2157
2995
  /**
2158
2996
  * 宿主的命令终止 trailer:`[exit code: N]` / `[killed by signal: X]` / `[stopped: …]`。
2159
2997
  *
@@ -2203,6 +3041,12 @@ export function toolResultSummaryOf(toolName, rawResultText, meta) {
2203
3041
  else if (trailer?.kind === "signal") summary.signal = trailer.signal;
2204
3042
  else if (trailer?.kind === "stopped") summary.stopped = trailer.stopped;
2205
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
+ }
2206
3050
  const metaShape = meta && typeof meta === "object" ? meta.shape : undefined;
2207
3051
  const searchShaped = metaShape === "matches" || metaShape === "paths";
2208
3052
  const searchTool = tool === "grep" || tool === "glob";
@@ -2218,6 +3062,47 @@ export function toolResultSummaryOf(toolName, rawResultText, meta) {
2218
3062
  return Object.keys(summary).length > 0 ? summary : undefined;
2219
3063
  }
2220
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
+
2221
3106
  /** 从 grep/glob 的结果文本解析匹配总数;解析不到返回 undefined(不猜)。 */
2222
3107
  function parseSearchResultCount(text, tool) {
2223
3108
  if (text === "") return undefined;
@@ -2488,6 +3373,13 @@ function summarizeEventCoreBody(event, options = {}) {
2488
3373
  },
2489
3374
  };
2490
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
+ }
2491
3383
  case "todo/write": {
2492
3384
  // v3.1.4(issue #12 姊妹需求):内核 dsh-tool-todo 每次调用写入**整份清单快照**
2493
3385
  // ({ todos: [{ content, status }] },status ∈ pending / in_progress / completed)。
@@ -2578,11 +3470,84 @@ export function detailEventFor(event) {
2578
3470
  }
2579
3471
 
2580
3472
  /**
2581
- * 移动端事件摘要:保留轻量 data,同时声明可通过 seq 读取无损详情。
2582
- * 老客户端只会忽略新增的 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 无输出。
2583
3490
  */
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
+
2584
3547
  export function summarizeEvent(event, options = {}) {
2585
- const summary = summarizeEventCore(event, options);
3548
+ const base = summarizeEventCore(event, options);
3549
+ const wire = surfaceWireFields(event);
3550
+ const summary = Object.keys(wire).length > 0 ? { ...base, ...wire } : base;
2586
3551
  if (event?.seq === undefined || event?.seq === null) return summary;
2587
3552
  // 只对详情端点真的能取回的事件声明指针:token delta / 内部记录会被 /event-detail
2588
3553
  // 拒绝(isTimelineRecord),未列入 allow-list 的类型同样会被拒(fail-closed)。
@@ -2963,6 +3928,36 @@ export const requestAbort = (res) => {
2963
3928
  return ac.signal;
2964
3929
  };
2965
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
+
2966
3961
  /** 插件主体。 */
2967
3962
  export function apply(ctx, config, runtime = {}) {
2968
3963
  const basePath = config.path;
@@ -3064,20 +4059,56 @@ export function apply(ctx, config, runtime = {}) {
3064
4059
  pid: process.pid,
3065
4060
  });
3066
4061
  // 监督器是否还在照看(用锁的持有者进程是否存活判断)
3067
- const supervisorAlive = () => {
3068
- const holder = readLock(pluginUpdateLockFile);
3069
- return Boolean(holder && holder.pid && defaultIsPidAlive(holder.pid));
3070
- };
4062
+ const supervisorAlive = () => lockHolderAlive(pluginUpdateLockFile);
3071
4063
  {
3072
4064
  // 事务报告(**只读**):回滚由外部监督器负责,不再依赖新版插件能否加载(评审 R1)。
3073
4065
  // 这里只处理"监督器已消失且明显超时"的收敛,避免手机永久等待。
4066
+ const holderAlive = supervisorAlive();
3074
4067
  const reported = reportPendingUpdate({
3075
4068
  stateFile: pluginUpdateStateFile,
3076
4069
  lockPath: pluginUpdateLockFile,
3077
4070
  localContentSha256: selfContentSha256,
3078
- supervisorAlive: supervisorAlive(),
4071
+ holderAlive,
4072
+ supervisorAlive: holderAlive,
3079
4073
  });
3080
- 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") {
3081
4112
  ctx.logger.info?.("mobile-remote: 插件自更新已生效");
3082
4113
  } else if (reported.action === "expired") {
3083
4114
  ctx.logger.warn("mobile-remote: 插件自更新未确认生效且监督器已退出;请在电脑上确认插件状态");
@@ -3090,9 +4121,13 @@ export function apply(ctx, config, runtime = {}) {
3090
4121
  if (pluginUpdateChecked) return;
3091
4122
  pluginUpdateChecked = true;
3092
4123
  if (resolvePluginUpdateSource(config.pluginUpdateManifest).kind === UPDATE_SOURCE_KIND.OFF) return;
3093
- updates.check()
4124
+ // issue #96 review P2:bootstrap 也走共享 checkService(deadline/缓存/in-flight 去重),
4125
+ // 不再裸调 checkForUpdate;错误只落稳定 code,不把内部 message 写入公开状态。
4126
+ updates.checkSync()
3094
4127
  .then((r) => Object.assign(pluginUpdateStatus, r))
3095
- .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
+ }));
3096
4131
  };
3097
4132
  // 自更新能力与降级指引:内容状态驱动"能不能一键",版本号只管文案(评审 R11)。
3098
4133
  //
@@ -3214,6 +4249,19 @@ export function apply(ctx, config, runtime = {}) {
3214
4249
  transaction: transactionSummary(view),
3215
4250
  };
3216
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
+ );
3217
4265
  const updates = createPluginUpdateController({
3218
4266
  home: homedir(), configValue: config.pluginUpdateManifest, profileDir: pluginProfileDir, packageName: pluginPackageName,
3219
4267
  capabilities: pluginUpdateCapabilities, localVersion: () => pluginVersion(), localContentSha256: selfContentSha256,
@@ -3223,6 +4271,8 @@ export function apply(ctx, config, runtime = {}) {
3223
4271
  // 内部 worker 永远用**受信回环定位 + 有效口令**(自动生成的口令同样要带上,否则 401)
3224
4272
  auth: { token: authToken, trustedOrigin: `http://127.0.0.1:${ctx.webServer.port}`, basePath },
3225
4273
  workerOptions: { installedRoot: pluginRootDir, pluginRoot: pluginRootDir, needsEscape: systemdManaged(),
4274
+ // issue #110 P2:事务记录宿主原始 argv,supervisor 重启时使用(其自身 argv 不含宿主参数)。
4275
+ respawnCommand,
3226
4276
  restartForm: restartFormOf(), hostPid: process.pid, port: ctx.webServer.port, basePath,
3227
4277
  token: authToken, profile: process.env.DSH_PROFILE || "web", dshCommand: process.env.DSH_BIN || "dsh" },
3228
4278
  // DSH 0.2.2+:宿主原生插件管理器可用时,更新走「进程内卸载→安装」,不重启宿主。
@@ -4102,6 +5152,131 @@ export function apply(ctx, config, runtime = {}) {
4102
5152
  if (!added) return;
4103
5153
  pumpBackfillQueue(); // 有额度才真正开工;否则等既有任务腾出额度时自动续跑
4104
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";
5278
+ };
5279
+
4105
5280
  // v3.1.2:0.1.2 的 Session 类改为 snapshotEvents()/eventAt()/seq(无 .events 数组)——
4106
5281
  // 统一取事件数组;休眠快照(readSession 返回值 {events})与旧版会话保持兼容。
4107
5282
  const eventsOf = (session) => {
@@ -5664,6 +6839,19 @@ export function apply(ctx, config, runtime = {}) {
5664
6839
  pendingFrames.delete(oldest);
5665
6840
  }
5666
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
+ };
5667
6855
  const connect = (res) => {
5668
6856
  if (connections.size >= config.maxConnections) {
5669
6857
  res.writeHead(503, { "content-type": "application/json; charset=utf-8" });
@@ -5712,7 +6900,15 @@ export function apply(ctx, config, runtime = {}) {
5712
6900
  const resolvedToolName = event.type === "tool/result"
5713
6901
  ? toolNamesOf(eventsOf(session)).get(toolResultCallIdOf(event))
5714
6902
  : undefined;
5715
- const summary = summarizeEvent(event, { cwd: sessionCwdOf(session), resolvedToolName });
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
+ });
5716
6912
  if (event.type === "turn/end") {
5717
6913
  const tail = turnTailOf(eventsOf(session), event.data?.turn);
5718
6914
  if (tail) summary.data = { ...(summary.data ?? {}), tail };
@@ -5897,6 +7093,32 @@ export function apply(ctx, config, runtime = {}) {
5897
7093
  };
5898
7094
  // 流式端点:只取首帧(如 session/control 基线流),unary invoke 会被网关拒绝
5899
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
+ };
5900
7122
  /** v3.1.2:session/control(baseline)中取某会话的投影值(modelSelection/imageLimits 等)。 */
5901
7123
  const projectionOf = (control, sessionId) =>
5902
7124
  control?.type === "baseline" ? control.value?.projections?.[sessionId]?.values : undefined;
@@ -5959,8 +7181,13 @@ export function apply(ctx, config, runtime = {}) {
5959
7181
  // 0.2.x 位置参数形态形参 ≥3;0.1.x 是 (endpoint, options) 两参
5960
7182
  const modernGateway = gateway.invokeRpc.length >= 3;
5961
7183
  const peer = modernGateway ? gatewayPeer() : void 0;
5962
- const endpoint = RPC_ENDPOINT_RENAMES[method] ?? method.replace(".", "/");
5963
- 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
+ }
5964
7191
  if (RPC_STREAM_METHODS.has(method)) {
5965
7192
  // 基线流(session/control 等):首帧即基线快照,取完即断
5966
7193
  const [namespace, name] = endpoint.split("/");
@@ -6060,8 +7287,6 @@ export function apply(ctx, config, runtime = {}) {
6060
7287
  const forwarded = value.slice(sep + 1).trim();
6061
7288
  return forwarded === "" ? remote : forwarded;
6062
7289
  };
6063
- /** 首个 root agent(无 root 时退回任意 agent)。 */
6064
- const firstAgent = (agents) => agents?.roots()[0] ?? agents?.list()[0];
6065
7290
  /** 会话短码(统一格式:前 8 + … + 后 4;短 id 原样)。 */
6066
7291
  const shortSessionId = (id) => (id.length > 12 ? `${id.slice(0, 8)}…${id.slice(-4)}` : id);
6067
7292
  /** 通知标题:会话标题兜底短码。 */
@@ -6340,6 +7565,48 @@ export function apply(ctx, config, runtime = {}) {
6340
7565
  // 队列有界 + 截止时间从请求到达时算起(issue #25 评审 P1):见 createTurnOutlineQueue。
6341
7566
  const turnOutlineQueue = createTurnOutlineQueue();
6342
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
+ };
6343
7610
  const handleApi = async (req, res, url, rest) => {
6344
7611
  if (!hostAllowed(req)) {
6345
7612
  error(res, 403, "host-not-allowed");
@@ -6541,15 +7808,47 @@ export function apply(ctx, config, runtime = {}) {
6541
7808
  }
6542
7809
 
6543
7810
 
6544
- // 只读 NPM 检查:桌面设置页/手机端可按需刷新;不下载产物、不改 profile、不重启。
7811
+ // 只读 NPM 检查:旧 App GET 缓存命中立即返回;新 App POST 异步检查 + checkId 轮询。
7812
+ // 不下载产物、不改 profile、不重启,也不返回半结果。
6545
7813
  if (rest === "/plugin-update/check") {
6546
- 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;
6547
7843
  try {
6548
- Object.assign(pluginUpdateStatus, await updates.check());
7844
+ const text = await readBody(req, 16 * 1024);
7845
+ body = text ? JSON.parse(text) : {};
6549
7846
  } catch {
6550
- 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");
6551
7848
  }
6552
- 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 });
6553
7852
  }
6554
7853
 
6555
7854
  // 旧 carrier 缺少 App build metadata 时,用户明确触发的预检只下载/校验 NPM 产物,不改 profile。
@@ -6597,8 +7896,101 @@ export function apply(ctx, config, runtime = {}) {
6597
7896
  return sendJson(res, result.status, result.body);
6598
7897
  }
6599
7898
 
6600
- if (new Set(["/git/capabilities", "/git/repository", "/git/branches", "/git/graph", "/git/commit", "/git/worktree", "/git/preview", "/git/files", "/git/file-history"]).has(rest)) {
6601
- 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");
6602
7994
  const sessionId = url.searchParams.get("sessionId") ?? "";
6603
7995
  if (!sessionId) return error(res, 400, "bad-request", "sessionId is required");
6604
7996
  try {
@@ -6616,21 +8008,12 @@ export function apply(ctx, config, runtime = {}) {
6616
8008
  const path = url.searchParams.get("path");
6617
8009
  if (path === null || path === "") return error(res, 400, "bad-request", "path is required");
6618
8010
  value = await gitRead.fileHistory(sessionId, repositoryId, { path, cursor: url.searchParams.get("cursor") ?? undefined, limit: url.searchParams.get("limit") ?? undefined });
6619
- } else if (rest === "/git/graph") {
6620
- let tips;
6621
- const rawTips = url.searchParams.get("tips");
6622
- if (rawTips !== null) {
6623
- try { tips = JSON.parse(rawTips); } catch { return error(res, 400, "bad-request", "tips must be JSON"); }
6624
- }
6625
- 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 });
6626
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 });
6627
8012
  else return error(res, 404, "not-found");
6628
8013
  }
6629
8014
  sendJson(res, 200, { ok: true, ...value });
6630
8015
  } catch (err) {
6631
- // External providers may include host paths or credentials in messages:
6632
- // only expose stable mobile error codes, never raw provider details.
6633
- 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"]);
6634
8017
  const code = known.has(err?.code) ? err.code : "git-provider-unavailable";
6635
8018
  const status = Number(err?.status);
6636
8019
  ctx.logger.warn?.(`mobile-remote: Git read failed (${code}): ${err?.message ?? err}`);
@@ -6742,7 +8125,7 @@ export function apply(ctx, config, runtime = {}) {
6742
8125
  const agents = ctx.get("agents");
6743
8126
  if (!agents) return error(res, 503, "agents-unavailable");
6744
8127
  const sessionId = typeof body?.sessionId === "string" && body.sessionId ? body.sessionId : undefined;
6745
- let target = sessionId ? agents.get(sessionId) : agents.roots()[0];
8128
+ let target = sessionId ? agents.get(sessionId) : firstAgent(agents);
6746
8129
  // v3.1.5:休眠配置折叠回退默认时置位,finalize 在所有响应上附带 configDegraded
6747
8130
  let configDegraded = false;
6748
8131
  if (!target && sessionId) {
@@ -6868,7 +8251,7 @@ export function apply(ctx, config, runtime = {}) {
6868
8251
  const sessionId = url.searchParams.get("sessionId") ?? undefined;
6869
8252
  const requestId = url.searchParams.get("requestId");
6870
8253
  if (!requestId || !/^[A-Za-z0-9-]{8,64}$/.test(requestId)) return error(res, 400, "bad-request", "invalid requestId");
6871
- const rootId = ctx.get("agents")?.roots()[0]?.id;
8254
+ const rootId = firstAgent(ctx.get("agents"))?.id;
6872
8255
  const key = receiptKeyOf(sessionId, rootId, requestId);
6873
8256
  // v3.0.0(热修 08):读取路径全量清理——未访问的旧回执同样清除并持久化(TTL 语义一致化)
6874
8257
  if (pruneReceipts()) persistReceipts();
@@ -6890,14 +8273,32 @@ export function apply(ctx, config, runtime = {}) {
6890
8273
  const sessionId = url.searchParams.get("sessionId");
6891
8274
  const attachmentId = url.searchParams.get("attachmentId");
6892
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");
6893
8280
  try {
6894
- const value = await apiRpc("session.attachment", { sessionId, attachmentId }, 30_000);
6895
- const ref = value?.attachment;
6896
- 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");
6897
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;
6898
8299
  guardRes(res);
6899
8300
  res.writeHead(200, {
6900
- "content-type": typeof ref.mediaType === "string" ? ref.mediaType : "image/jpeg",
8301
+ "content-type": contentType,
6901
8302
  "content-length": buf.length,
6902
8303
  "cache-control": "private, max-age=3600",
6903
8304
  // v3.0.0(热修 04):与 sendJson 同策略——图片取完即断,不留下可被复用的半关连接
@@ -6911,6 +8312,9 @@ export function apply(ctx, config, runtime = {}) {
6911
8312
  });
6912
8313
  res.end(buf);
6913
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");
6914
8318
  return error(res, ...rpcError(err, "attachment-failed"));
6915
8319
  }
6916
8320
  return;
@@ -7160,6 +8564,8 @@ export function apply(ctx, config, runtime = {}) {
7160
8564
 
7161
8565
  if (rest === "/sessions") {
7162
8566
  if (requireGet(method, res)) return;
8567
+ // issue #109:只有显式 includeEmpty=1 才返回零可见消息会话;非法值按 false。
8568
+ const includeEmpty = url.searchParams.get("includeEmpty") === "1";
7163
8569
  const sessions = ctx.get("sessions");
7164
8570
  if (!sessions) return error(res, 503, "sessions-unavailable");
7165
8571
  // v3.1.6(issue #20):客户端断开即停止**本请求**的扫描(宿主支持取消,此前一处没传)。
@@ -7180,7 +8586,7 @@ export function apply(ctx, config, runtime = {}) {
7180
8586
  if (enumeration.timedOut) return error(res, 504, "sessions-timeout");
7181
8587
  } else records = enumeration.records;
7182
8588
  }
7183
- const list = [];
8589
+ let list = [];
7184
8590
  const archived = coreArchivedIds();
7185
8591
  if (records) {
7186
8592
  // v3.1.6(issue #14 复核):这是**完整语料**观测——记下来供剪枝按会话存在性
@@ -7241,6 +8647,64 @@ export function apply(ctx, config, runtime = {}) {
7241
8647
  });
7242
8648
  }
7243
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
+ }
7244
8708
  // v3.1.6(issue #14 / ADR 0013):按最新消息时间倒序(缺失回退 lastActivity,
7245
8709
  // 再回退 createdAt),等值以 id 为次级键。旧版 App 仍读 lastActivity,语义未变。
7246
8710
  list.sort(compareSessionsForList);
@@ -7550,7 +9014,8 @@ export function apply(ctx, config, runtime = {}) {
7550
9014
  // seq 不连续(非完整日志),before/after 分页只在 surface 范围内有效——
7551
9015
  // 上翻到被 surface 替换的 log-only 历史区域时可能返回空页,属预期;
7552
9016
  // 客户端应结合 historyMode="current-surface" 提示"部分历史不可上翻"。
7553
- const surface = eventsOf(session).filter(isTimelineRecord);
9017
+ const rawEvents = eventsOf(session);
9018
+ const surface = rawEvents.filter(isTimelineRecord);
7554
9019
  // issue #53(§6.20):轮末信号 `turnTails` 由**一次遍历原始事件**得出(会话日志
7555
9020
  // 仍含被过滤的 `workspace/changes`),不额外调用宿主服务;只含有产出物的轮次。
7556
9021
  const turnTails = turnTailsOf(eventsOf(session));
@@ -7576,6 +9041,15 @@ export function apply(ctx, config, runtime = {}) {
7576
9041
  hasMore = surface.length > limit;
7577
9042
  events = surface.slice(-limit);
7578
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
+ });
7579
9053
  sendJson(res, 200, {
7580
9054
  ok: true,
7581
9055
  sessionId,
@@ -7585,10 +9059,7 @@ export function apply(ctx, config, runtime = {}) {
7585
9059
  after: events.length ? events[events.length - 1].seq : 0,
7586
9060
  hasMore,
7587
9061
  turnTails,
7588
- events: events.map((event) => summarizeEvent(event, {
7589
- cwd,
7590
- resolvedToolName: event?.type === "tool/result" ? toolNames.get(toolResultCallIdOf(event)) : undefined,
7591
- })),
9062
+ events: events.map(summarizeForMobile),
7592
9063
  });
7593
9064
  return;
7594
9065
  }
@@ -8542,6 +10013,7 @@ export function apply(ctx, config, runtime = {}) {
8542
10013
  const gatewaySvc = ctx.get("typertGateway");
8543
10014
  const presetsSvc = ctx.get("permissionPresets");
8544
10015
  const workspaceSvc = ctx.get("workspaceRegistry");
10016
+ const subagentsSvc = subagentsService();
8545
10017
  // issue #34:0.2.1 的进程内 peer 来源(`connection.createPeer`);旧代靠网关 operator 兜底
8546
10018
  let connectionSvc;
8547
10019
  try {
@@ -8606,6 +10078,12 @@ export function apply(ctx, config, runtime = {}) {
8606
10078
  // (网关不再兜底)——只探存在性会把「开流必失败」报成绿灯,正是 ADR 0017 要防的
8607
10079
  // "服务在、成员在、语义已变"。旧代 3 参开流不需要 peer,按 ok 处理。
8608
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"),
8609
10087
  };
8610
10088
  checks.hostCapabilities = hostCapabilities;
8611
10089
  // 已探测到的代际选择:便于人工核对插件实际走了哪条路径(排查"为什么这个功能表现不同")
@@ -8621,6 +10099,8 @@ export function apply(ctx, config, runtime = {}) {
8621
10099
  : eventsPeerProbe.state === "ok"
8622
10100
  ? peerSource
8623
10101
  : "none",
10102
+ // issue #87:实际走的 subagents 代际(descendants/children、user/parent)。
10103
+ subagents: subagentsGeneration(),
8624
10104
  };
8625
10105
  // 任一项非 ok 都必须给出可执行的原因,而不只是状态值
8626
10106
  const degradedCaps = Object.entries(hostCapabilities).filter(([, state]) => state !== "ok");
@@ -9108,6 +10588,196 @@ export function apply(ctx, config, runtime = {}) {
9108
10588
  }
9109
10589
  return;
9110
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
+ }
9111
10781
  if (rest === "/files" && (method === "GET" || method === "HEAD")) {
9112
10782
  const path = url.searchParams.get("path");
9113
10783
  if (!path || path === "") return error(res, 400, "bad-request", "missing path");
@@ -9233,7 +10903,9 @@ export function apply(ctx, config, runtime = {}) {
9233
10903
  // issue #20:与 /sessions 同一条全量枚举路径,宿主目录与持久化回退都接入请求取消。
9234
10904
  const signal = requestAbort(res);
9235
10905
  const parent = sessions?.get?.(parentSessionId);
9236
- 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";
9237
10909
  // 目录来源按优先级取——**两边能力都要保留**(issue #14/#17/#21):
9238
10910
  // ① 宿主持久目录 `subagents.listChildren`:包含已释放子代理和 mode/label 元数据,
9239
10911
  // 不要求父会话有活跃 Agent;
@@ -9242,11 +10914,35 @@ export function apply(ctx, config, runtime = {}) {
9242
10914
  // 状态另取自活 agent(AgentStatus = idle | running);目录条目本身不带状态。
9243
10915
  let catalogRows = null;
9244
10916
  let catalogDegraded = false;
9245
- 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) {
9246
10937
  try {
9247
10938
  const rows = await subagentsSvc.listChildren(parentSessionId, signal);
9248
10939
  if (signal.aborted) return;
9249
- 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
+ }
9250
10946
  } catch {
9251
10947
  if (signal.aborted) return; // 客户端已离开,不再触发回退或写响应
9252
10948
  catalogRows = null; // 目录读取失败 → 落到持久化枚举
@@ -9299,7 +10995,17 @@ export function apply(ctx, config, runtime = {}) {
9299
10995
  const label = typeof row?.label === "string" && row.label !== "" ? row.label : undefined;
9300
10996
  const rowTitle = typeof row?.title === "string" && row.title !== "" ? row.title : undefined;
9301
10997
  const liveTitle = sessionTitleOf(session);
9302
- 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
+ };
9303
11009
  }).filter((row) => row.id !== "");
9304
11010
  // issue #30 评审 WARNING 1:目录条目的 `label` 可省略,而**已释放**的子代理不在 live
9305
11011
  // 注册表里(拿不到会话快照标题)。三个来源都拿不到时必须按需**补读持久标题**,
@@ -9314,18 +11020,16 @@ export function apply(ctx, config, runtime = {}) {
9314
11020
  const entries = rows
9315
11021
  .map((row) => ({
9316
11022
  id: row.id,
9317
- // issue #30 评审 WARNING 2:目录 `mode: "unknown"` 是宿主明确判定的**不受支持
9318
- // 条目**(宿主 `listDescendants` 映射为 diagnostic/unsupported),不能伪装成
9319
- // 普通闲置子代理——否则消费者无法区分"不受支持"与"正常闲置",等于删掉 RPC 时
9320
- // 顺带静默删掉既有诊断语义(docs/03-api 承诺 `status` 可为 diagnostic reason)。
9321
- 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",
9322
11026
  // 状态取自活 agent;已结束/已释放的子代理回落 inactive(与既有语义一致)
9323
- status: row.mode === "unknown"
9324
- ? "unsupported"
11027
+ status: row.isDiagnostic
11028
+ ? (row.diagnosticReason ?? "unsupported")
9325
11029
  : (typeof row.live?.status === "string" && row.live.status !== ""
9326
11030
  ? (row.live.status === "running" ? "running" : "inactive") // AgentStatus = 'idle' | 'running'
9327
11031
  : "inactive"),
9328
- 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),
9329
11033
  ...(row.createdAt === undefined ? {} : { createdAt: row.createdAt }),
9330
11034
  }))
9331
11035
  .sort((a, b) => {
@@ -9353,13 +11057,73 @@ export function apply(ctx, config, runtime = {}) {
9353
11057
  const childSessionId = typeof body.childSessionId === "string" ? body.childSessionId : "";
9354
11058
  if (!parentSessionId || !childSessionId) return error(res, 400, "parentSessionId-and-childSessionId-required");
9355
11059
  try {
9356
- await apiRpc("subagent.interrupt", { parentSessionId, childSessionId, mode: "continuable" });
9357
- 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
+ });
9358
11067
  } catch (err) {
9359
11068
  return error(res, ...rpcError(err, "subagent-interrupt-failed"));
9360
11069
  }
9361
11070
  return;
9362
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
+ }
9363
11127
  if (rest === "/commands") {
9364
11128
  // v2.8.0:斜杠命令目录(对齐 PC 端 ctx.commands)——GET 列出、POST 执行
9365
11129
  // v2.8.2 适配:commands 服务可能未注册(desktop profile / 旧 DSH 无 dsh-commands host 服务)——
@@ -9512,7 +11276,7 @@ export function apply(ctx, config, runtime = {}) {
9512
11276
  const agents = ctx.get("agents");
9513
11277
  if (!agents) return error(res, 503, "agents-unavailable");
9514
11278
  const sessionId = typeof body?.sessionId === "string" && body.sessionId !== "" ? body.sessionId : undefined;
9515
- const agent = (sessionId ? agents.get(sessionId) : undefined) ?? agents.roots()[0];
11279
+ const agent = (sessionId ? agents.get(sessionId) : undefined) ?? firstAgent(agents);
9516
11280
  if (!agent) return error(res, 404, "no-live-agent");
9517
11281
  const synthetic = {
9518
11282
  agent,