@marktrue/dsh-mobile-remote 3.3.1-alpha.3 → 3.3.1-alpha.4

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
@@ -4793,6 +4793,249 @@ export function apply(ctx, config, runtime = {}) {
4793
4793
  // 不加私网黑名单;风险见 docs/04-security.md。
4794
4794
  const REGISTRY_MAX_LENGTH = 2048;
4795
4795
 
4796
+ // ── #175 P2:任意 spec(包名 / git / 宿主绝对路径 / tarball)安装 ──────
4797
+ //
4798
+ // 边界(详见 docs/04-security.md):
4799
+ // - **不在插件侧解析 spec**:形态判定、路径合法性、git 地址、tarball 全部交宿主
4800
+ // `parseInstallSpec()` 与 `pluginManager.inspect()`;这里只做「长度有界 + 拒绝
4801
+ // 控制字符」这类与语义无关的线性输入防御,避免把超长/带控制字符的串送进宿主。
4802
+ // - **不回显原始 spec**:spec 可能含 token、内网主机或家目录路径。错误响应只给
4803
+ // 稳定码与类别,宿主 `inspect()` 的 `reason` 也可能夹带路径原文,这里统一过滤。
4804
+ // - **不做 build scripts 授权**:手机端没有 `approvedBuilds` 通道;遇到
4805
+ // build-blocked 只回报 `build-blocked` 让 App 指引用户去电脑端处理。
4806
+ const INSTALL_SPEC_MAX_LENGTH = 2048;
4807
+ /** 稳定拒绝原因码 → 人可读类别(不含原文)。 */
4808
+ const INSTALL_SPEC_INVALID = "invalid-spec";
4809
+
4810
+ /**
4811
+ * 校验 App 传来的安装 spec 的**输入形态**(不判语义,语义交宿主)。
4812
+ *
4813
+ * 返回 `{ok:true, spec}` 或 `{ok:false, detail}`;`detail` 只给类别,不含 spec 片段。
4814
+ * 不在此处 trim 后匹配包名/git/路径——那是宿主的职责,重复实现必然漂移。
4815
+ */
4816
+ function validateInstallSpecInput(value) {
4817
+ if (typeof value !== "string") return { ok: false, detail: "not-string" };
4818
+ if (value.trim() === "") return { ok: false, detail: "empty" };
4819
+ if (value.length > INSTALL_SPEC_MAX_LENGTH) return { ok: false, detail: "too-long" };
4820
+ // 控制字符(含 NUL、CR、LF)一律拒绝:它们会被下游裁剪或截断日志,等于接受了
4821
+ // 一个「不同的」spec;换行还能伪造日志行。
4822
+ if (/[\u0000-\u001f\u007f]/.test(value)) return { ok: false, detail: "control-char" };
4823
+ return { ok: true, spec: value.trim() };
4824
+ }
4825
+
4826
+ // ── #175 P3:插件市场索引(可写电脑端配置)与搜索(SSRF 边界) ──────
4827
+ //
4828
+ // 边界(详见 docs/04-security.md):
4829
+ // - **索引是电脑端配置**:`setIndexes()` 内部走 `settings.update(entryId, {indexes})`。
4830
+ // `plugin-market` 的 Config 里 `indexes` 带 `.volatile()`,所以这条路**成立**
4831
+ // (与 pluginManager.registry 零 volatile 不同,不需 configEditor seam)。
4832
+ // - **SSRF(P0)**:`search(url)` 会真的去抓那个 URL。因此 `url` **必须**在宿主
4833
+ // 当前已配置索引列表里;不在列表 → 明确拒绝,绝不把用户输入直接交给 fetch。
4834
+ // 宿主 `document()` 自身也做同样检查(`unknown-index`),这里做**显式前置**校验:
4835
+ // 错误码稳定、且不依赖宿主版本行为。
4836
+ // - **索引 URL 不复用 registry 的语义**:索引通常带路径,`normalizeRegistry` 的
4837
+ // 「末尾补 `/`」会改变语义,这里只做 href 规范化(与宿主 `normalizeIndexUrl` 一致)。
4838
+ const MARKET_INDEX_MAX_COUNT = 8;
4839
+ const MARKET_INDEX_MAX_LENGTH = 2048;
4840
+ const MARKET_SEARCH_MAX_LIMIT = 100;
4841
+ const MARKET_SEARCH_DEFAULT_LIMIT = 20;
4842
+
4843
+ /**
4844
+ * 校验单条索引 URL(形态层)。
4845
+ *
4846
+ * 与宿主 `normalizeIndexUrl` **同判据**:绝对 http(s)、无凭据、无 fragment。
4847
+ * **不补尾斜杠**——索引 URL 的路径有意义(`/index.json` 与 `/index.json/` 不同)。
4848
+ * 额外收紧:拒绝 query(索引 URL 带 query 多为签名/一次性令牌,且会进错误回显)、
4849
+ * 拒绝控制字符与空白、长度上限。
4850
+ *
4851
+ * 返回 `{ok:true, url}` 或 `{ok:false, detail}`;`detail` 只给类别,**不回显原文**。
4852
+ */
4853
+ function validateMarketIndexUrl(value) {
4854
+ if (typeof value !== "string") return { ok: false, detail: "not-string" };
4855
+ const text = value.trim();
4856
+ if (text === "") return { ok: false, detail: "empty" };
4857
+ if (text.length > MARKET_INDEX_MAX_LENGTH) return { ok: false, detail: "too-long" };
4858
+ if (/[\u0000-\u001f\u007f]/.test(text)) return { ok: false, detail: "control-char" };
4859
+ if (/\s/.test(text)) return { ok: false, detail: "whitespace" };
4860
+ let parsed;
4861
+ try {
4862
+ parsed = new URL(text);
4863
+ } catch {
4864
+ return { ok: false, detail: "unparsable" };
4865
+ }
4866
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return { ok: false, detail: "unsupported-protocol" };
4867
+ if (parsed.hostname === "") return { ok: false, detail: "missing-host" };
4868
+ if (parsed.username !== "" || parsed.password !== "") return { ok: false, detail: "has-credentials" };
4869
+ if (parsed.hash !== "") return { ok: false, detail: "has-fragment" };
4870
+ if (parsed.search !== "") return { ok: false, detail: "has-query" };
4871
+ // 与宿主 normalizeIndexUrl 等价:输出 href(保留路径,不补斜杠)。
4872
+ return { ok: true, url: parsed.href };
4873
+ }
4874
+
4875
+ /**
4876
+ * 校验一组索引 URL:逐条形态校验 + 数量上限 + 去重保序。
4877
+ *
4878
+ * 返回 `{ok:true, urls}` 或 `{ok:false, detail, index}`(`index` 是第一条出错的序号,
4879
+ * 便于 App 定位到具体那一行;不含 URL 原文)。
4880
+ */
4881
+ function validateMarketIndexList(values) {
4882
+ if (!Array.isArray(values)) return { ok: false, detail: "not-array" };
4883
+ if (values.length > MARKET_INDEX_MAX_COUNT) return { ok: false, detail: "too-many" };
4884
+ const urls = [];
4885
+ const seen = new Set();
4886
+ for (let index = 0; index < values.length; index += 1) {
4887
+ const checked = validateMarketIndexUrl(values[index]);
4888
+ if (!checked.ok) return { ok: false, detail: checked.detail, index };
4889
+ // 去重按规范化后的 href:`https://a/x` 与 `https://a/x` + 大小写 host 归一后相同。
4890
+ if (seen.has(checked.url)) continue;
4891
+ seen.add(checked.url);
4892
+ urls.push(checked.url);
4893
+ }
4894
+ return { ok: true, urls };
4895
+ }
4896
+
4897
+ /** 市场服务(旧宿主没有该服务 → null,端点降级 supported:false)。 */
4898
+ function pluginMarketService() {
4899
+ let market = null;
4900
+ try { market = ctx.get?.("pluginMarket") ?? null; } catch { market = null; }
4901
+ return market && typeof market === "object" ? market : null;
4902
+ }
4903
+
4904
+ /**
4905
+ * 该宿主是否**可写**索引:有 `setIndexes` 且 `plugin-market` 的 profile entry 可解析
4906
+ * (宿主 `setIndexes` 在缺 settings/entryId 时抛 `settings-unavailable`)。
4907
+ *
4908
+ * 只做能力探测,不尝试写。
4909
+ */
4910
+ function marketIndexesWritable(market) {
4911
+ if (!market || typeof market.setIndexes !== "function") return false;
4912
+ try {
4913
+ const settings = ctx.get?.("settings");
4914
+ if (settings === void 0 || settings === null || typeof settings.update !== "function") return false;
4915
+ } catch {
4916
+ return false;
4917
+ }
4918
+ return true;
4919
+ }
4920
+
4921
+ /** 宿主 `plugin-market/*` 的 RemoteError code → 稳定 HTTP + 码。 */
4922
+ function marketErrorResponse(error) {
4923
+ const code = typeof error?.code === "string" ? error.code : "";
4924
+ switch (code) {
4925
+ case "plugin-market/invalid-index-url":
4926
+ return { status: 400, error: "index-invalid" };
4927
+ case "plugin-market/invalid-query":
4928
+ return { status: 400, error: "invalid-query" };
4929
+ case "plugin-market/unknown-index":
4930
+ // 与 SSRF 前置校验同码:无论宿主还是本地拦截,对外都只能说「不是已配置的索引」。
4931
+ return { status: 400, error: "unknown-index" };
4932
+ case "plugin-market/unknown-plugin":
4933
+ return { status: 404, error: "unknown-plugin" };
4934
+ case "plugin-market/settings-unavailable":
4935
+ return { status: 409, error: "settings-write-unavailable" };
4936
+ case "plugin-market/fetch-failed":
4937
+ return { status: 502, error: "index-fetch-failed" };
4938
+ case "plugin-market/invalid-index":
4939
+ return { status: 502, error: "index-invalid-document" };
4940
+ default:
4941
+ return { status: 503, error: "plugin-market-unavailable" };
4942
+ }
4943
+ }
4944
+
4945
+ /**
4946
+ * 把宿主 `listIndexes()` 的行投影成稳定形状。
4947
+ *
4948
+ * `url` **要**回显:它本来就是电脑端已配置的配置项,用户在索引管理页必须看到自己
4949
+ * 配了什么才能删改;这与「不回显用户刚输入的待校验 spec」不同。
4950
+ * `error` 只透出宿主给的类别串,不额外拼接。
4951
+ */
4952
+ function publicMarketIndex(row) {
4953
+ return {
4954
+ url: typeof row?.url === "string" ? row.url : "",
4955
+ title: typeof row?.title === "string" ? row.title : "",
4956
+ description: typeof row?.description === "string" ? row.description : "",
4957
+ error: typeof row?.error === "string" ? row.error.slice(0, 300) : "",
4958
+ };
4959
+ }
4960
+
4961
+ /**
4962
+ * 市场条目投影:**移除任何本地路径线索**。
4963
+ *
4964
+ * 宿主 `listingOf()` 的条目带 `install {spec, registry?}` 与 `versions[]`。
4965
+ * `install.spec` 对 git 源是 `git+https://...`(安全),对 npm 是 `name@version`
4966
+ * (安全)。但仍逐字段白名单构造,避免宿主未来新增字段把本地路径/凭据带出来。
4967
+ */
4968
+ function publicMarketEntry(entry) {
4969
+ const versions = Array.isArray(entry?.versions) ? entry.versions : [];
4970
+ return {
4971
+ name: typeof entry?.name === "string" ? entry.name : "",
4972
+ title: typeof entry?.title === "string" ? entry.title : "",
4973
+ description: typeof entry?.description === "string" ? entry.description : "",
4974
+ category: typeof entry?.category === "string" ? entry.category : "",
4975
+ labels: (Array.isArray(entry?.labels) ? entry.labels : [])
4976
+ .map((value) => (typeof value === "string" ? value : ""))
4977
+ .filter((value) => value !== "")
4978
+ .slice(0, 24),
4979
+ defaultVersion: typeof entry?.defaultVersion === "string" ? entry.defaultVersion : "",
4980
+ installation: {
4981
+ status: typeof entry?.installation?.status === "string" ? entry.installation.status : "not-installed",
4982
+ installedVersion: typeof entry?.installation?.installedVersion === "string" ? entry.installation.installedVersion : "",
4983
+ },
4984
+ versions: versions.slice(0, 24).map((version) => ({
4985
+ version: typeof version?.version === "string" ? version.version : "",
4986
+ prerelease: version?.prerelease === true,
4987
+ deprecated: typeof version?.deprecated === "string" ? version.deprecated : "",
4988
+ // 安装目标由宿主算好;App 只透传,**不自己拼 spec**(与 P2 的契约一致)。
4989
+ install: version?.install === undefined ? null : {
4990
+ spec: typeof version.install?.spec === "string" ? version.install.spec : "",
4991
+ registry: typeof version.install?.registry === "string" && safeRegistryValue(version.install.registry) !== null
4992
+ ? safeRegistryValue(version.install.registry)
4993
+ : null,
4994
+ },
4995
+ compatible: version?.compatibility?.compatible === true,
4996
+ incompatibleRequirements: version?.compatibility?.compatible === true
4997
+ ? []
4998
+ : Object.entries(version?.compatibility?.requirements ?? {})
4999
+ .map(([key, value]) => `${key}: ${String(value)}`)
5000
+ .slice(0, 4),
5001
+ update: version?.update === true,
5002
+ })),
5003
+ };
5004
+ }
5005
+
5006
+ /**
5007
+ * 把宿主 `inspect()` 的 `reason` 收敛成**不回显原文**的稳定类别。
5008
+ *
5009
+ * 宿主对 `path` 的拒绝会把路径/文件系统错误写进 `reason`(例如
5010
+ * `no readable package.json at the path: <EACCES ... /home/x>`),对 registry 则会
5011
+ * 回传 registry 的原始错误。这些都不能直接进响应或日志。
5012
+ *
5013
+ * 只保留**已知且安全**的短句;其余一律给类别码,App 按 `problem` 出人话文案。
5014
+ */
5015
+ function safeInspectReason(problem, reason) {
5016
+ const text = typeof reason === "string" ? reason.trim() : "";
5017
+ // 宿主对这几类给的是固定短句(不含路径/凭据),可以原样保留以改善可读性。
5018
+ if (problem === "not-a-bundle" && /^[\w@/.-]+ declares no dsh\.bundle$/.test(text)) return text;
5019
+ if (problem === "already-installed" && /^[\w@/.-]+ is already installed$/.test(text)) return text;
5020
+ // `invalid-spec` 的 reason 全部来自 `parseInstallSpec` 的固定短句(不含用户输入):
5021
+ // "a local path must be absolute" / "not a package name the registry accepts" /
5022
+ // "a URL must point at a git repository or a tarball"。
5023
+ // 但仍用白名单匹配,避免宿主将来改成拼接原文时这里跟着泄露。
5024
+ if (problem === "invalid-spec") {
5025
+ if (text === "a local path must be absolute") return text;
5026
+ if (text === "not a package name the registry accepts") return text;
5027
+ if (text === "a URL must point at a git repository or a tarball") return text;
5028
+ return "";
5029
+ }
5030
+ if (problem === "not-a-package") {
5031
+ if (text === "the tarball does not exist") return text;
5032
+ if (text === "the path does not exist") return text;
5033
+ if (text === "the package.json names no package") return text;
5034
+ return "";
5035
+ }
5036
+ return "";
5037
+ }
5038
+
4796
5039
  /**
4797
5040
  * 校验并规范化 App 传来的 registry URL。
4798
5041
  *
@@ -5027,6 +5270,10 @@ export function apply(ctx, config, runtime = {}) {
5027
5270
  registries: [...op.registries],
5028
5271
  attempt: op.attempt === null ? null : { index: op.attempt.index, total: op.attempt.total },
5029
5272
  answeredRegistry: op.answeredRegistry,
5273
+ // #175 P2:`source:"name"` 沿用 #153 的配置渠道安装;`source:"spec"` 是手动 spec。
5274
+ source: op.source,
5275
+ // #175 P2:非空表示 pnpm 拦下了安装脚本,需要在**电脑端**授权后重装。
5276
+ pendingBuilds: [...op.pendingBuilds],
5030
5277
  startedAt: op.startedAt,
5031
5278
  finishedAt: op.finishedAt,
5032
5279
  };
@@ -5068,6 +5315,12 @@ export function apply(ctx, config, runtime = {}) {
5068
5315
  registries: [],
5069
5316
  attempt: null,
5070
5317
  answeredRegistry: null,
5318
+ // #175 P2:按 name 装(宿主 installable 清单)还是按任意 spec 装。
5319
+ // App 据此区分「配置渠道安装」与「手动指定 spec」;不影响 #153 的 name 路径。
5320
+ source: "name",
5321
+ // #175 P2:build scripts 待授权清单(只有 build-blocked 失败时非空)。
5322
+ // 手机端**不提供**批准入口,只用来出「请去电脑端授权」的指引。
5323
+ pendingBuilds: [],
5071
5324
  startedAt: Date.now(),
5072
5325
  finishedAt: null,
5073
5326
  };
@@ -5131,6 +5384,47 @@ export function apply(ctx, config, runtime = {}) {
5131
5384
  if (succeeded && op.registries.length > 0) op.answeredRegistry = op.registries[op.registries.length - 1];
5132
5385
  }
5133
5386
 
5387
+ /**
5388
+ * #175 P2:从宿主事务结果里取 pnpm 的失败类别(`packageResult.kind`)。
5389
+ *
5390
+ * **为什么不能只看 `error.code`**:宿主 `installBundle()` 在 pnpm 失败时执行
5391
+ * `throw new Error(run.output)`——这是普通 `Error`,`managementError()` 会把它归成
5392
+ * `code:"operation-error"`,**真正的 `build-blocked` 只留在
5393
+ * `result.packageResult.kind` 里**(由 `classifyInstallFailure()` 判出)。
5394
+ * 实测 `classifyInstallFailure({log:"Ignored build scripts: x"})` → `"build-blocked"`。
5395
+ *
5396
+ * 返回稳定类别串;无法判定时返回空串(宁可不说,也不编造原因)。
5397
+ */
5398
+ function pluginInstallFailureKind(change) {
5399
+ const kind = change?.packageResult?.kind;
5400
+ return typeof kind === "string" ? kind : "";
5401
+ }
5402
+
5403
+ /**
5404
+ * #175 P2:build scripts 待授权清单——**只透出包名**,不含任何路径/命令原文。
5405
+ *
5406
+ * 宿主只在 pnpm 失败后才填 `pendingBuilds`;此时若类别是 `build-blocked`,说明
5407
+ * 有安装脚本被拦下,需要用户在**电脑端**显式授权。手机端不提供批准入口。
5408
+ *
5409
+ * 宿主 `blockedBuildNames()` 已过滤通配符与凭据,但这里再做一次**包名形状**校验:
5410
+ * 这个字段会显示在手机上,绝不能把绝对路径/命令行片段透出去。
5411
+ */
5412
+ function pluginPendingBuilds(change) {
5413
+ const list = Array.isArray(change?.pendingBuilds) ? change.pendingBuilds : [];
5414
+ const safe = [];
5415
+ for (const value of list) {
5416
+ if (typeof value !== "string") continue;
5417
+ const name = value.trim();
5418
+ if (name === "" || name.length > 200) continue;
5419
+ // npm 包名形状:可带 @scope/,只允许字母数字与 . _ - ;排除 `/` 开头的路径、
5420
+ // 盘符、反斜杠与空白/控制字符。
5421
+ if (!/^(?:@[A-Za-z0-9._-]+\/)?[A-Za-z0-9._-]+$/.test(name)) continue;
5422
+ if (name === "." || name === "..") continue;
5423
+ if (!safe.includes(name)) safe.push(name);
5424
+ }
5425
+ return safe;
5426
+ }
5427
+
5134
5428
  function finishPluginOperation(op, action, result, error) {
5135
5429
  if (!op || op.status !== "running") return;
5136
5430
  op.finishedAt = Date.now();
@@ -5147,6 +5441,9 @@ export function apply(ctx, config, runtime = {}) {
5147
5441
  const change = action === "update" ? result?.result : result;
5148
5442
  const application = change?.application;
5149
5443
  const errorCode = change?.error?.code;
5444
+ // #175 P2:宿主把 pnpm 失败折成 `operation-error`,真实类别在 packageResult.kind。
5445
+ // 只有 install 会撞上 pnpm 的 build scripts 拦截,因此只在这里改写。
5446
+ const failureKind = pluginInstallFailureKind(change);
5150
5447
  if (action === "uninstall" || action === "toggle") {
5151
5448
  op.version = typeof change?.version === "string" ? change.version : "";
5152
5449
  if (application === "failed" || !application) {
@@ -5168,7 +5465,15 @@ export function apply(ctx, config, runtime = {}) {
5168
5465
  op.version = typeof change?.version === "string" ? change.version : "";
5169
5466
  if (application === "failed" || !application) {
5170
5467
  op.status = "failed";
5171
- op.errorCode = errorCode || "operation-failed";
5468
+ // #175 P2:pnpm 拦下安装脚本时,宿主的 error.code 是 `operation-error`,
5469
+ // 真实原因在 packageResult.kind。对手机端有意义的是「去电脑端授权」,
5470
+ // 所以把 build-blocked 提成显式错误码,并附待授权包名(只有名字)。
5471
+ if (failureKind === "build-blocked") {
5472
+ op.errorCode = "build-blocked";
5473
+ op.pendingBuilds = pluginPendingBuilds(change);
5474
+ } else {
5475
+ op.errorCode = errorCode || "operation-failed";
5476
+ }
5172
5477
  op.rolledBack = Boolean(application === "failed"); // installBundle 文档:失败恢复 profile
5173
5478
  } else if (application === "cancelled") {
5174
5479
  op.status = "cancelled";
@@ -5202,6 +5507,55 @@ export function apply(ctx, config, runtime = {}) {
5202
5507
  notePluginRegistryFacts(op, change, op.status === "succeeded");
5203
5508
  }
5204
5509
 
5510
+ /**
5511
+ * #175 P2:按**任意 spec** 安装(包名 / git / 宿主绝对路径 / tarball)。
5512
+ *
5513
+ * 与 `startPluginInstall(name)` 的区别:
5514
+ * - 不查宿主 `installable` 清单,因此能装清单之外的包;
5515
+ * - spec 的形态、路径合法性、git 地址、tarball 判定**全部交宿主**
5516
+ * (`installBundle` 内部走 `parseInstallSpec`),这里不做任何拼接或解析;
5517
+ * - 手机的定位只是「把用户输入原样转交给电脑端」,与在电脑端跑
5518
+ * `dsh plugin install <spec>` 等价。
5519
+ *
5520
+ * 失败形态:宿主 `installBundle` 在 pnpm 失败时抛普通 Error,被 `change()` 折成
5521
+ * `application:"failed"`;`finishPluginOperation` 再从 `packageResult.kind` 还原
5522
+ * `build-blocked`。这里不 catch,交给统一的 finish 逻辑。
5523
+ */
5524
+ async function startPluginInstallBySpec(spec, registry, inspect) {
5525
+ const manager = pluginManagerService();
5526
+ if (!manager || typeof manager.installBundle !== "function") {
5527
+ throw Object.assign(new Error("plugin-manager-unavailable"), { httpStatus: 409, code: "plugin-manager-unavailable" });
5528
+ }
5529
+ // 并行安装互斥:同一时刻只允许一个按 spec 的安装。宿主的 profile 锁会串行化,
5530
+ // 但排队只会让手机端长时间看不到反馈;这里显式拒绝(name 路径不受影响)。
5531
+ for (const existing of pluginOperations.values()) {
5532
+ if (existing.status === "running" && existing.action === "install" && existing.source === "spec") {
5533
+ throw Object.assign(new Error("operation-in-progress"), { httpStatus: 409, code: "plugin-install-in-progress" });
5534
+ }
5535
+ }
5536
+ // op 的 name:预校验给了名字就用它(预校验通过时一定有),否则先用 spec 的稳定
5537
+ // 占位(**不能**把原始 spec 放进 name——它会被回显给 App 且在日志里出现)。
5538
+ const opName = inspect?.status === "accepted" && typeof inspect.name === "string" && inspect.name !== ""
5539
+ ? inspect.name
5540
+ : "install-spec";
5541
+ const op = beginPluginOperation("install", opName, inspect?.status === "accepted" && typeof inspect.version === "string" ? inspect.version : "");
5542
+ op.source = "spec";
5543
+ (async () => {
5544
+ markPluginOperationStep(op, "prepare");
5545
+ try {
5546
+ const result = await manager.installBundle(spec, {
5547
+ requestId: op.opId,
5548
+ saveExact: true,
5549
+ ...(registry === undefined ? {} : { registry }),
5550
+ });
5551
+ finishPluginOperation(op, "install", result, null);
5552
+ } catch (error) {
5553
+ finishPluginOperation(op, "install", null, error);
5554
+ }
5555
+ })();
5556
+ return op;
5557
+ }
5558
+
5205
5559
  function pluginManagerService() {
5206
5560
  let manager = null;
5207
5561
  try { manager = ctx.get?.("pluginManager") ?? null; } catch { manager = null; }
@@ -8029,10 +8383,68 @@ export function apply(ctx, config, runtime = {}) {
8029
8383
  mobileRejected: sseRejected,
8030
8384
  };
8031
8385
  };
8386
+ // issue #177:**只观测,不改行为**。四类审批/问询帧在广播时记连接数与写失败数——
8387
+ // 「手机没连着 → 帧静默丢弃」是定位「提问卡不提示」时最大的盲区:日志里原本
8388
+ // 完全看不出「根本没人在听」和「发了但 App 没渲染」的区别。
8389
+ //
8390
+ // 性能:`broadcast` 是热路径,所以这四类之外的帧走原路径(一次 Set 查表即返回),
8391
+ // 不做任何字符串拼接。
8392
+ const OBSERVED_FRAME_TYPES = new Set([
8393
+ "question/requested",
8394
+ "question/resolved",
8395
+ "approval/requested",
8396
+ "approval/resolved",
8397
+ ]);
8398
+ /**
8399
+ * 给要广播的帧解析一个「业务标识」行(只含 id 与 type,**绝不含题干/选项/正文**)。
8400
+ *
8401
+ * @returns 观测标签;非四类帧返回 `null`(调用方据此完全跳过额外计算)。
8402
+ */
8403
+ const observedFrameLabel = (frame) => {
8404
+ if (!frame || typeof frame !== "object") return null;
8405
+ // 审批/问询帧有两种投递形态:直接 `{type:"question/requested",...}`,
8406
+ // 或包在 `{type:"mobile/frame", frame:{...}}` 里(本插件走后者)。
8407
+ const inner = frame.type === "mobile/frame" && frame.frame && typeof frame.frame === "object"
8408
+ ? frame.frame
8409
+ : frame;
8410
+ const type = typeof inner?.type === "string" ? inner.type : "";
8411
+ if (!OBSERVED_FRAME_TYPES.has(type)) return null;
8412
+ // 只取标识字段;不存在就留空(不拼接未知字段,避免把正文带出来)。
8413
+ // `question/resolved` 的关联 id 叫 `questionRpcId`(不是 `rpcId`),两种都要认,
8414
+ // 否则 resolved 行的 rpcId 会恒空、看不出结算的是哪一条。
8415
+ const rpcId = typeof inner.rpcId === "string"
8416
+ ? inner.rpcId
8417
+ : typeof inner.questionRpcId === "string" ? inner.questionRpcId : "";
8418
+ const questionId = typeof inner.questionId === "string" ? inner.questionId : "";
8419
+ const sessionId = typeof inner.sessionId === "string" ? inner.sessionId : "";
8420
+ return { type, rpcId, questionId, sessionId };
8421
+ };
8032
8422
  const broadcast = (frame) => {
8033
8423
  const line = `data: ${JSON.stringify(frame)}\n\n`;
8034
- // 复制迭代:safeWrite 可能在背压/写失败时移除连接。
8035
- for (const res of [...connections]) safeWrite(res, line);
8424
+ const observed = observedFrameLabel(frame);
8425
+ // 非四类帧:与原实现完全等价(不做任何额外计数/拼接),热路径不退化。
8426
+ if (observed === null) {
8427
+ // 复制迭代:safeWrite 可能在背压/写失败时移除连接。
8428
+ for (const res of [...connections]) safeWrite(res, line);
8429
+ return;
8430
+ }
8431
+ // 连接数必须在**发送前**取:safeWrite 失败会 dropConn,循环后 size 已经变小,
8432
+ // 用循环后的值会把「3 个连接全写失败」误报成「0 个连接」。
8433
+ const connCount = connections.size;
8434
+ let written = 0;
8435
+ let failed = 0;
8436
+ for (const res of [...connections]) {
8437
+ if (safeWrite(res, line)) written += 1;
8438
+ else failed += 1;
8439
+ }
8440
+ // issue #177:info 级(用户无需开 debug 就能看到)。`connCount === 0` 时
8441
+ // 醒目标注「帧仅入回放」——那正是"App 没弹卡"最可能的断点之一。
8442
+ ctx.logger.info?.(
8443
+ `mobile-remote: broadcast ${observed.type} rpcId=${observed.rpcId} ` +
8444
+ `questionId=${observed.questionId} session=${observed.sessionId} ` +
8445
+ `connections=${connCount} written=${written} failed=${failed}` +
8446
+ `${connCount === 0 ? " ⚠ 无手机连接,帧仅入回放" : ""}`,
8447
+ );
8036
8448
  };
8037
8449
  // ── v2.7 任务(jobs)视图:与 PC 端 GUI 同源(apiproxy 模式)──
8038
8450
  // 内核任务注册表(ctx.jobs)按会话(agent)隔离;任务视图随 session/jobs 帧下发。
@@ -8079,9 +8491,12 @@ export function apply(ctx, config, runtime = {}) {
8079
8491
  };
8080
8492
  // ── 问询/审批桥(移动端弹窗):rpcId → frame 待答清单,App 重连时补发 ──
8081
8493
  const pendingFrames = new Map(); // `q:${rpcId}` / `a:${approvalId}` -> { rpcId, at, ...frame }
8082
- // v2.7.2 review(M3):上限 + TTL,防"永不回答的审批/提问帧"永久残留并在每次重连全量回放
8494
+ // v2.7.2 review(M3):上限防"永不回答的审批/提问帧"永久残留并在每次重连全量回放。
8495
+ // issue #177 方案 A:**TTL 已移除**——回放层若按时间清帧,会重现「离开久了回来没卡」
8496
+ // 正是本次要修的问题(原本 24h TTL 还与回收层 70min 自相矛盾)。改由:
8497
+ // - `PENDING_FRAMES_MAX` 容量上限(与 `PENDING_ENTRIES_MAX` 对齐,成对清理);
8498
+ // - 条目结算 / 另一端先答 / 插件卸载时的成对清理。
8083
8499
  const PENDING_FRAMES_MAX = 200;
8084
- const PENDING_FRAMES_TTL = 24 * 3600 * 1000;
8085
8500
  const pendingFrameSet = (key, frame) => {
8086
8501
  // review:先删再设,刷新插入序(超限逐出时不会误逐刚更新的帧)
8087
8502
  pendingFrames.delete(key);
@@ -8156,17 +8571,25 @@ export function apply(ctx, config, runtime = {}) {
8156
8571
  ctx.logger.debug?.(`mobile-remote: SSE open pendingQuestions=${pendingQuestions.size} pendingFrames=${pendingFrames.size} host=${hostIdentity}`);
8157
8572
  // 补发断线期间挂起的问询/审批(与 PC 端 GUI 连接时的 pending 回放一致;超 TTL 的僵尸帧先清掉)
8158
8573
  const replayed = [];
8159
- for (const [key, f] of pendingFrames) {
8160
- if (now - (f.at ?? 0) > PENDING_FRAMES_TTL) {
8161
- pendingFrames.delete(key);
8162
- continue;
8163
- }
8574
+ // issue #177 方案 A:不再按时间丢弃过期帧(回放层无 TTL)。
8575
+ // 残留由 `PENDING_FRAMES_MAX` 容量上限与成对清理兜底。
8576
+ for (const [, f] of pendingFrames) {
8164
8577
  if (!safeWrite(res, `data: ${JSON.stringify({ type: "mobile/frame", frame: f })}\n\n`)) return;
8165
8578
  replayed.push(f);
8166
8579
  }
8167
8580
  ctx.logger.debug?.(`mobile-remote: SSE replay id=${meta.id} frames=${replayed.length} ` +
8168
8581
  `pendingQuestions=${pendingQuestions.size} pendingFrames=${pendingFrames.size} ` +
8169
8582
  `questions=${replayed.filter((f) => f.type === "question/requested").map((f) => `${f.rpcId}/${f.questionId ?? ""}/${f.sessionId ?? ""}`).join(",")}`);
8583
+ // issue #177:回放是「手机重连后能否看到卡」的关键一环,而上面那条是 debug 级
8584
+ // (用户默认看不到)。这里只在**确实有**待答帧被补发时补一条 info,信息与 debug
8585
+ // 版同源但不含题干;没有可回放帧时不打,避免每次重连刷屏。
8586
+ const replayedAsks = replayed.filter((f) => OBSERVED_FRAME_TYPES.has(f?.type));
8587
+ if (replayedAsks.length > 0) {
8588
+ ctx.logger.info?.(
8589
+ `mobile-remote: SSE replay asked id=${meta.id} frames=${replayedAsks.length} ` +
8590
+ `items=${replayedAsks.map((f) => `${f.type}:${f.rpcId ?? ""}/${f.sessionId ?? ""}`).join(",")}`,
8591
+ );
8592
+ }
8170
8593
  // v3.3(吸收上游 #64):同一有序流上,回放后追加完整待办快照边界。
8171
8594
  // 客户端只据此撤销本宿主已不在 pending 中的业务通知(其它宿主/常驻通知不受影响)。
8172
8595
  if (!safeWrite(res, `data: ${JSON.stringify({ type: "attention/snapshot", version: 1,
@@ -9357,11 +9780,263 @@ export function apply(ctx, config, runtime = {}) {
9357
9780
  return sendJson(res, 200, { ok: true, supported: false, complete: false, reason: "host-registry-unavailable", writable: false, registries: [] });
9358
9781
  }
9359
9782
  }
9783
+ // ── #175 P3:插件市场索引(读/写)+ 搜索(SSRF 边界) ────────────────
9784
+ //
9785
+ // 索引是**电脑端配置**;写操作与新端点都需移动端口令(同所有 /plugin-inventory/*)。
9786
+ // `search` 的 url 必须是**已配置**索引之一,否则等于开了任意 URL 抓取。
9787
+ // 显式三方法分派(GET/HEAD 读、POST 写);端点登记门禁从分派头部抽方法。
9788
+ if (rest === "/plugin-inventory/market/indexes") {
9789
+ if (method !== "GET" && method !== "HEAD" && method !== "POST") return error(res, 405, "method-not-allowed");
9790
+ const market = pluginMarketService();
9791
+ const supported = Boolean(market && typeof market.listIndexes === "function");
9792
+ const writable = supported && marketIndexesWritable(market);
9793
+ if (method === "GET" || method === "HEAD") {
9794
+ if (!supported) {
9795
+ // 旧宿主:200 + supported:false(不 404/500,App 据此整块降级)。
9796
+ if (method === "HEAD") { res.writeHead(200, { "cache-control": "no-store" }); res.end(); return; }
9797
+ return sendJson(res, 200, { ok: true, supported: false, writable: false, reason: "plugin-market-unavailable", indexes: [], defaults: { count: 0 } });
9798
+ }
9799
+ let rows;
9800
+ try {
9801
+ rows = await market.listIndexes();
9802
+ } catch {
9803
+ if (method === "HEAD") { res.writeHead(200, { "cache-control": "no-store" }); res.end(); return; }
9804
+ return sendJson(res, 200, { ok: true, supported: false, writable: false, reason: "plugin-market-unavailable", indexes: [], defaults: { count: 0 } });
9805
+ }
9806
+ const indexes = (Array.isArray(rows) ? rows : []).map(publicMarketIndex);
9807
+ if (method === "HEAD") { res.writeHead(200, { "cache-control": "no-store" }); res.end(); return; }
9808
+ // `defaults.count` = 宿主配置里**可用**(无 error)的索引数,供 App 说明基线。
9809
+ return sendJson(res, 200, {
9810
+ ok: true,
9811
+ supported: true,
9812
+ writable,
9813
+ reason: writable ? "" : "settings-write-unavailable",
9814
+ indexes,
9815
+ defaults: { count: indexes.filter((row) => row.error === "").length },
9816
+ });
9817
+ }
9818
+ if (!supported) return error(res, 409, "plugin-market-unavailable");
9819
+ if (!writable) return error(res, 409, "settings-write-unavailable");
9820
+ let body;
9821
+ try { const text = await readBody(req, 16 * 1024); body = text ? JSON.parse(text) : {}; }
9822
+ catch { return error(res, 400, "bad-request", "body must be JSON"); }
9823
+ // 只接受 `{urls: string[]}`;其他形状一律拒绝(不做宽容解析,避免写入意外内容)。
9824
+ if (body === null || typeof body !== "object" || !Array.isArray(body.urls)) {
9825
+ return error(res, 400, "bad-request", "body must carry urls");
9826
+ }
9827
+ const checked = validateMarketIndexList(body.urls);
9828
+ if (!checked.ok) {
9829
+ return sendJson(res, 400, {
9830
+ error: "index-invalid",
9831
+ detail: checked.detail,
9832
+ ...(checked.index === undefined ? {} : { index: checked.index }),
9833
+ });
9834
+ }
9835
+ try {
9836
+ await market.setIndexes(checked.urls);
9837
+ } catch (e) {
9838
+ const mapped = marketErrorResponse(e);
9839
+ return error(res, mapped.status, mapped.error);
9840
+ }
9841
+ // 写成功后回读一次,让 App 拿到**宿主实际接受**的列表(不乐观回显入参)。
9842
+ let after = [];
9843
+ try {
9844
+ const rows = await market.listIndexes();
9845
+ after = (Array.isArray(rows) ? rows : []).map(publicMarketIndex);
9846
+ } catch {
9847
+ // 回读失败不影响写入结果;给空列表让 App 自行重试。
9848
+ after = [];
9849
+ }
9850
+ return sendJson(res, 200, {
9851
+ ok: true,
9852
+ supported: true,
9853
+ writable: true,
9854
+ indexes: after,
9855
+ defaults: { count: after.filter((row) => row.error === "").length },
9856
+ });
9857
+ }
9858
+ // SSRF 边界:search 的 `url` 必须是**已配置索引**之一。
9859
+ if (rest === "/plugin-inventory/market/search") {
9860
+ if (requireGet(method, res)) return;
9861
+ const market = pluginMarketService();
9862
+ if (!market || typeof market.search !== "function" || typeof market.listIndexes !== "function") {
9863
+ return sendJson(res, 200, { ok: true, supported: false, reason: "plugin-market-unavailable" });
9864
+ }
9865
+ const rawUrl = url.searchParams.get("url") ?? "";
9866
+ if (rawUrl === "") return error(res, 400, "bad-request", "url is required");
9867
+ const indexed = validateMarketIndexUrl(rawUrl);
9868
+ if (!indexed.ok) return error(res, 400, "index-invalid", indexed.detail);
9869
+ // 取宿主已配置列表;**只有**命中其中一项才允许抓取。
9870
+ let configured;
9871
+ try {
9872
+ const rows = await market.listIndexes();
9873
+ configured = (Array.isArray(rows) ? rows : []).map(publicMarketIndex);
9874
+ } catch {
9875
+ return error(res, 503, "plugin-market-unavailable");
9876
+ }
9877
+ const target = configured.find((row) => row.url === indexed.url);
9878
+ if (target === undefined) {
9879
+ // 不告诉调用方「这个 URL 存在但不是索引」——只说不是已配置索引,避免探测。
9880
+ return error(res, 400, "unknown-index");
9881
+ }
9882
+ // 宿主已标记该索引不可用(配置写坏/上次读取失败):不发起抓取。
9883
+ if (target.error !== "") return sendJson(res, 409, { ok: false, error: "index-unusable" });
9884
+ // 分页/过滤参数:宿主自己也会校验,这里先归一成稳定错误码。
9885
+ const rawOffset = url.searchParams.get("offset");
9886
+ const rawLimit = url.searchParams.get("limit");
9887
+ let offset = 0;
9888
+ if (rawOffset !== null && rawOffset !== "") {
9889
+ if (!/^\d+$/.test(rawOffset)) return error(res, 400, "invalid-query", "offset");
9890
+ offset = Number(rawOffset);
9891
+ if (!Number.isSafeInteger(offset)) return error(res, 400, "invalid-query", "offset");
9892
+ }
9893
+ let limit = MARKET_SEARCH_DEFAULT_LIMIT;
9894
+ if (rawLimit !== null && rawLimit !== "") {
9895
+ if (!/^\d+$/.test(rawLimit)) return error(res, 400, "invalid-query", "limit");
9896
+ limit = Number(rawLimit);
9897
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > MARKET_SEARCH_MAX_LIMIT) {
9898
+ return error(res, 400, "invalid-query", "limit");
9899
+ }
9900
+ }
9901
+ const query = { offset, limit };
9902
+ const text = url.searchParams.get("text");
9903
+ if (text !== null && text.trim() !== "") query.text = text.trim().slice(0, 200);
9904
+ const category = url.searchParams.get("category");
9905
+ if (category !== null && category.trim() !== "") query.category = category.trim().slice(0, 100);
9906
+ const rawRefresh = url.searchParams.get("refresh");
9907
+ if (rawRefresh === "1" || rawRefresh === "true") query.refresh = true;
9908
+ let result;
9909
+ try {
9910
+ result = await market.search(indexed.url, query);
9911
+ } catch (e) {
9912
+ const mapped = marketErrorResponse(e);
9913
+ return error(res, mapped.status, mapped.error);
9914
+ }
9915
+ const entries = (Array.isArray(result?.entries) ? result.entries : []).map(publicMarketEntry);
9916
+ return sendJson(res, 200, {
9917
+ ok: true,
9918
+ supported: true,
9919
+ url: indexed.url,
9920
+ title: typeof result?.title === "string" ? result.title : "",
9921
+ description: typeof result?.description === "string" ? result.description : "",
9922
+ fetchedAt: Number.isFinite(result?.fetchedAt) ? result.fetchedAt : 0,
9923
+ total: Number.isFinite(result?.total) ? result.total : entries.length,
9924
+ nextOffset: Number.isFinite(result?.nextOffset) ? result.nextOffset : null,
9925
+ entries,
9926
+ });
9927
+ }
9928
+ // ── #175 P2:任意 spec 的安装前预校验(只读,不写 profile) ──────────
9929
+ //
9930
+ // 语义全部交宿主 `pluginManager.inspect()`:这里只做输入形态校验(长度/控制字符)
9931
+ // 与**回显收敛**。spec 原文不出现在响应、detail 或日志里。
9932
+ if (rest === "/plugin-inventory/inspect") {
9933
+ if (method !== "POST") return error(res, 405, "method-not-allowed");
9934
+ let body;
9935
+ try { const text = await readBody(req, 16 * 1024); body = text ? JSON.parse(text) : {}; }
9936
+ catch { return error(res, 400, "bad-request", "body must be JSON"); }
9937
+ const checked = validateInstallSpecInput(body?.spec);
9938
+ if (!checked.ok) return error(res, 400, INSTALL_SPEC_INVALID, checked.detail);
9939
+ let registry;
9940
+ if (body?.registry !== undefined && body?.registry !== null) {
9941
+ const parsedRegistry = validateRegistryUrl(body.registry);
9942
+ if (!parsedRegistry.ok) return error(res, 400, "registry-invalid", parsedRegistry.detail);
9943
+ registry = parsedRegistry.registry;
9944
+ }
9945
+ const manager = pluginManagerService();
9946
+ // 旧宿主没有 inspect():200 + supported:false(不 404/500,App 据此降级)。
9947
+ if (!manager || typeof manager.inspect !== "function") {
9948
+ return sendJson(res, 200, { ok: true, supported: false, reason: "inspect-unavailable", status: "refused", problem: "unknown" });
9949
+ }
9950
+ let inspection;
9951
+ try {
9952
+ inspection = await manager.inspect(checked.spec, registry === undefined ? undefined : { registry });
9953
+ } catch {
9954
+ // 宿主抛错不外泄原文:只给稳定码。
9955
+ return sendJson(res, 200, { ok: true, supported: true, status: "refused", kind: "", problem: "unknown", reason: "", registry: null, host: "" });
9956
+ }
9957
+ const accepted = inspection?.status === "accepted";
9958
+ const safeRegistry = safeRegistryValue(inspection?.registry);
9959
+ const host = typeof inspection?.host === "string" && inspection.host !== "" ? inspection.host.slice(0, 255) : "";
9960
+ const kind = typeof inspection?.kind === "string" ? inspection.kind : "";
9961
+ if (accepted) {
9962
+ return sendJson(res, 200, {
9963
+ ok: true,
9964
+ supported: true,
9965
+ status: "accepted",
9966
+ kind,
9967
+ name: typeof inspection.name === "string" ? inspection.name : "",
9968
+ version: typeof inspection.version === "string" ? inspection.version : "",
9969
+ description: typeof inspection.description === "string" ? inspection.description.slice(0, 500) : "",
9970
+ // bundle 为 null 表示该形态(git/tarball)在预校验阶段还读不到是否声明 dsh.bundle。
9971
+ bundle: inspection.bundle === true ? true : inspection.bundle === false ? false : null,
9972
+ registry: safeRegistry,
9973
+ host,
9974
+ problem: "",
9975
+ reason: "",
9976
+ });
9977
+ }
9978
+ const problem = typeof inspection?.problem === "string" ? inspection.problem : "unknown";
9979
+ return sendJson(res, 200, {
9980
+ ok: true,
9981
+ supported: true,
9982
+ status: "refused",
9983
+ kind,
9984
+ name: "",
9985
+ version: "",
9986
+ description: "",
9987
+ bundle: null,
9988
+ registry: safeRegistry,
9989
+ host,
9990
+ problem,
9991
+ // 宿主 reason 可能夹带路径/registry 原文 → 只保留白名单里的固定短句。
9992
+ reason: safeInspectReason(problem, inspection?.reason),
9993
+ });
9994
+ }
9360
9995
  if (rest === "/plugin-inventory/install") {
9361
9996
  if (method !== "POST") return error(res, 405, "method-not-allowed");
9362
9997
  let body;
9363
9998
  try { const text = await readBody(req, 16 * 1024); body = text ? JSON.parse(text) : {}; }
9364
9999
  catch { return error(res, 400, "bad-request", "body must be JSON"); }
10000
+ // #175 P2:`name` 与 `spec` 互斥——同传无法判定用户意图,明确拒绝而不是二选一。
10001
+ const hasName = body?.name !== undefined && body?.name !== null;
10002
+ const hasSpec = body?.spec !== undefined && body?.spec !== null;
10003
+ if (hasName && hasSpec) return error(res, 400, "bad-request", "name and spec are mutually exclusive");
10004
+ if (hasSpec) {
10005
+ const checked = validateInstallSpecInput(body.spec);
10006
+ if (!checked.ok) return error(res, 400, INSTALL_SPEC_INVALID, checked.detail);
10007
+ let registry;
10008
+ if (body?.registry !== undefined && body?.registry !== null) {
10009
+ const parsedRegistry = validateRegistryUrl(body.registry);
10010
+ if (!parsedRegistry.ok) return error(res, 400, "registry-invalid", parsedRegistry.detail);
10011
+ registry = parsedRegistry.registry;
10012
+ }
10013
+ const manager = pluginManagerService();
10014
+ // 预校验只用于拿到 op 的展示名/版本,并让明显该拒的 spec 在开装前就拒。
10015
+ // 预校验不可用(旧宿主)不阻断:installBundle 自己会做完整校验。
10016
+ let inspection = null;
10017
+ if (manager && typeof manager.inspect === "function") {
10018
+ try {
10019
+ inspection = await manager.inspect(checked.spec, registry === undefined ? undefined : { registry });
10020
+ } catch {
10021
+ inspection = null;
10022
+ }
10023
+ if (inspection?.status === "refused") {
10024
+ const problem = typeof inspection.problem === "string" ? inspection.problem : "unknown";
10025
+ return sendJson(res, 400, {
10026
+ ok: false,
10027
+ error: "spec-refused",
10028
+ problem,
10029
+ reason: safeInspectReason(problem, inspection.reason),
10030
+ });
10031
+ }
10032
+ }
10033
+ try {
10034
+ const op = await startPluginInstallBySpec(checked.spec, registry, inspection);
10035
+ return sendJson(res, 200, { ok: true, operation: publicPluginOperation(op) });
10036
+ } catch (e) {
10037
+ return error(res, Number(e?.httpStatus) || 503, e?.code || "plugin-install-failed");
10038
+ }
10039
+ }
9365
10040
  const name = typeof body?.name === "string" ? body.name.trim() : "";
9366
10041
  if (name === "" || name.length > 200) return error(res, 400, "invalid-plugin-name");
9367
10042
  let registry;
@@ -13689,11 +14364,23 @@ export function apply(ctx, config, runtime = {}) {
13689
14364
  const pendingApprovals = new Map(); // phoneApprovalId -> { phoneId, sessionId, rpcId, timer, settle(outcome) }
13690
14365
  const pendingQuestions = new Map(); // phoneQuestionId -> { phoneId, sessionId, rpcId, timer, settle(value) }
13691
14366
  /**
13692
- * 手机离线时的待答条目寿命(v3.1.4,issue #14)。
13693
- * 无手机在线时,条目 + 回放帧只是"等手机回来再答"的记录:到期**成对清理**且**不结算**,
13694
- * 既不给桌面端流程添乱,也不会留下"点了没反应"的死卡(条目没了帧还在)。
14367
+ * 待答条目的**容量**兜底(issue #177 方案 A)。
14368
+ *
14369
+ * 历史:v3.1.4(issue #14)曾用「离线 70 分钟 TTL」在手机离线时到期
14370
+ * **成对删除条目 + 回放帧**(不结算、不通知)。该设计比 DSH 本体激进得多,且
14371
+ * 与本文件回放层当时的 24 小时 TTL 自相矛盾——用户实测「离线 2 小时后
14372
+ * 重连无卡」正是被它清掉的。
14373
+ *
14374
+ * 现语义(跟随本体):
14375
+ * - 网关 `pendingRemoteEvents` **无 TTL**(只在 settle/cancel/Context 释放时删);
14376
+ * - 内核 `ask_user_question` 超时只是"先返回 pending 结果给模型",**提问仍有效**;
14377
+ * - 故本插件也不再设离线 TTL:条目一直保留,直到结算 / 另一端先答 /
14378
+ * Context 释放 / 插件卸载 / 容量逐出。
14379
+ *
14380
+ * 代价是内存可能长期增长,因此用**容量上限**兜底:超限按插入序逐出最旧,
14381
+ * 且**成对清理条目与回放帧**(issue #14 的教训:只删一个会留下幽灵卡)。
13695
14382
  */
13696
- const OFFLINE_PENDING_TTL_MS = 70 * 60_000; // 必须 > 在线保持时长(1h),否则回放帧先于结算消失
14383
+ const PENDING_ENTRIES_MAX = 200;
13697
14384
  /**
13698
14385
  * 待答帧的回放存储读写(v3.1.4,issue #14 Bug2)。
13699
14386
  * 键以 phoneId 为主(与 /respond 结算同源),并兼容 rpcId 形态的旧键;
@@ -13704,11 +14391,47 @@ export function apply(ctx, config, runtime = {}) {
13704
14391
  const putAskReplay = (prefix, entry, frame) => {
13705
14392
  pendingFrameSet(`${prefix}:${entry.phoneId}`, frame);
13706
14393
  ctx.logger.debug?.(`mobile-remote: ask replay stored kind=${prefix} rpcId=${entry.rpcId} ` +
13707
- `questionId=${frame.questionId ?? ""} sessionId=${entry.sessionId} pendingFrames=${pendingFrames.size}`);
14394
+ `questionId=${frame.questionId ?? ""} sessionId=${entry.sessionId} ` +
14395
+ // issue #177:补 `connections` ——「存回放那一刻有没有手机连着」是区分
14396
+ // 「本就没人在听(等回放)」与「有人在听却没渲染」的关键。
14397
+ `connections=${connections.size} pendingFrames=${pendingFrames.size}`);
13708
14398
  };
13709
14399
  const dropAskReplay = (prefix, entry) => {
13710
14400
  for (const key of askReplayKeys(prefix, entry)) pendingFrames.delete(key);
13711
14401
  };
14402
+ /**
14403
+ * issue #177 方案 A:待答条目的**容量**兜底(替代已移除的离线 TTL)。
14404
+ *
14405
+ * 条目不再按时间过期(跟随 DSH 本体:网关 pendingRemoteEvents 无 TTL、
14406
+ * 内核超时后提问仍有效),因此必须有容量上限防止内存无限增长。
14407
+ *
14408
+ * 逐出规则:`Map` 按插入序迭代,超限即删**最旧**的一条;并且
14409
+ * **成对清理条目 + 回放帧**——issue #14 的教训是"只删一个 → 幽灵卡"
14410
+ * (条目没了、帧还在 → 手机每次重连都被回放一张点不动的卡)。
14411
+ *
14412
+ * **所有插入点都要调用**(在线与离线、瀑布与 `$events` 四条路径):否则在线
14413
+ * 路径在高频审批时仍会无限增长。
14414
+ *
14415
+ * @param kind `"approval"` / `"question"`,决定清哪张 Map 与回放前缀
14416
+ */
14417
+ const evictOldestIfOverCapacity = (kind) => {
14418
+ const map = kind === "approval" ? pendingApprovals : pendingQuestions;
14419
+ const prefix = kind === "approval" ? "a" : "q";
14420
+ while (map.size > PENDING_ENTRIES_MAX) {
14421
+ const oldestKey = map.keys().next().value;
14422
+ const entry = map.get(oldestKey);
14423
+ map.delete(oldestKey);
14424
+ if (entry !== undefined) {
14425
+ // 成对清理:条目与回放帧必须同时消失。
14426
+ dropAskReplay(prefix, entry);
14427
+ if (entry.timer) { clearTimeout(entry.timer); entry.timer = null; }
14428
+ }
14429
+ ctx.logger.warn?.(
14430
+ `mobile-remote: 待答条目超容量逐出(kind=${kind} key=${oldestKey} ` +
14431
+ `max=${PENDING_ENTRIES_MAX} 条目与回放帧已成对清理)`,
14432
+ );
14433
+ }
14434
+ };
13712
14435
  /** $events 进程内客户端就绪态(both 双端呈现的传输前提;事件按发生时刻实时判定)。 */
13713
14436
  const eventsState = { ready: false, clientId: "", peer: null };
13714
14437
  let eventsAbort = null; // AbortController:插件卸载时断开 $events 流
@@ -13819,22 +14542,9 @@ export function apply(ctx, config, runtime = {}) {
13819
14542
  timer.unref?.();
13820
14543
  entry.timer = timer;
13821
14544
  };
13822
- /**
13823
- * 无手机在线时的**只清理**定时器(v3.1.4,issue #14)。
13824
- * 与 armTimeout 的关键区别:不结算、不 fail-close——手机不在场时是桌面端在处理审批,
13825
- * 不能被手机侧的 120s 超时误杀(报告人明确提醒的成对修复点)。
13826
- */
13827
- const armOfflineReap = (entry, prefix) => {
13828
- const timer = setTimeout(() => {
13829
- if (!pendingApprovals.has(entry.phoneId) && !pendingQuestions.has(entry.phoneId)) return;
13830
- pendingApprovals.delete(entry.phoneId);
13831
- pendingQuestions.delete(entry.phoneId);
13832
- dropAskReplay(prefix, entry);
13833
- ctx.logger.info?.(`mobile-remote: 离线待答条目到期清理(${entry.phoneId},不结算)`);
13834
- }, OFFLINE_PENDING_TTL_MS);
13835
- timer.unref?.();
13836
- entry.timer = timer;
13837
- };
14545
+ // issue #177 方案 A:**已移除** `armOfflineReap`(原 70 分钟离线回收定时器)。
14546
+ // 见 `PENDING_ENTRIES_MAX` 处的说明:离线条目改为跟随 DSH 本体语义长期保留,
14547
+ // 由容量上限兜底;在线分支仍用 `armTimeout`(不结算的"只清理"语义已不再需要)。
13838
14548
  const notifyAsk = (sessionId, req) =>
13839
14549
  notifyNeedsAnswer(sessionId, `审批请求:${typeof req?.toolName === "string" && req.toolName ? req.toolName : "工具"} 需要授权`);
13840
14550
  const notifyQuestion = (sessionId) => notifyNeedsAnswer(sessionId, "agent 正在等待你的回答");
@@ -13860,8 +14570,16 @@ export function apply(ctx, config, runtime = {}) {
13860
14570
  // v3.3.0:改为先建 Promise 再建条目,便于双端竞速时由调用方拿到 entry 收卡
13861
14571
  let resolveHeld;
13862
14572
  const held = new Promise((resolve) => { resolveHeld = resolve; });
13863
- const entry = { phoneId: phoneKey, sessionId, rpcId: phoneKey, timer: null, holdMs, settle: resolveHeld };
14573
+ const entry = {
14574
+ phoneId: phoneKey, sessionId, rpcId: phoneKey, timer: null, holdMs, settle: resolveHeld,
14575
+ // #177:跨路径去重的内容判据(见 `findTwinApproval`)。
14576
+ // `reason` 参与比对是刻意的:R16 里同一 callId 的第二次 sandbox escalation
14577
+ // 只因 `reason` 不同就必须算作**两次不同审批**,不能被去重吞掉。
14578
+ toolName: req?.toolName, callId: req?.callId, reason: req?.reason,
14579
+ };
13864
14580
  pendingApprovals.set(phoneKey, entry);
14581
+ // #177 方案 A:所有插入点都做容量兜底(不只在离线分支)。
14582
+ evictOldestIfOverCapacity("approval");
13865
14583
  armTimeout(entry, () => {
13866
14584
  // 手机超时未应答:按「超时自动拒绝」结算(rejected),而非 unavailable——前者用户看得到「被拒绝」,后者只显示「没有答复」
13867
14585
  ctx.logger.warn?.(`mobile-remote: approval/request 手机超时未应答 → rejected(超时自动拒绝)(${phoneKey})`);
@@ -13899,6 +14617,8 @@ export function apply(ctx, config, runtime = {}) {
13899
14617
  reject: (reason) => { rejectHeld(reason); return true; },
13900
14618
  };
13901
14619
  pendingQuestions.set(phoneKey, entry);
14620
+ // #177 方案 A:所有插入点都做容量兜底(不只在离线分支)。
14621
+ evictOldestIfOverCapacity("question");
13902
14622
  armTimeout(entry, () => {
13903
14623
  ctx.logger.warn?.(`mobile-remote: user-questions/request 手机超时未应答 → 取消(${phoneKey})`);
13904
14624
  finishQuestion(entry, questionCancelledError("ask_user_question timed out before the user answered"), { reject: true });
@@ -13916,6 +14636,66 @@ export function apply(ctx, config, runtime = {}) {
13916
14636
  return { held, entry };
13917
14637
  };
13918
14638
 
14639
+ // ── #177:两条建卡路径的**跨路径去重** ──────────────────────────────
14640
+ //
14641
+ // 本插件接管一次提问有两条路径,且它们的条目身份**形态不同**:
14642
+ // ① 瀑布路径 `holdQuestion`:`${sessionId}:${Date.now().toString(36)}`(每次接管新键)
14643
+ // ② `$events` 路径 `onEventsWaterfall`:`${sessionId}:${eventId}`(eventId 稳定)
14644
+ //
14645
+ // 两条路径**互不去重**,而同一次逻辑提问可能被两条路径各命中一次。可达路径
14646
+ // (不是假想,见 `dsh-api-gateway/lib/index.js`):
14647
+ // - 提问发生在 `$events` 尚未就绪时 → ① 接管并(both 下)`next()` 放行
14648
+ // → 网关 `startRemoteEvent()` 把该请求挂进 `pendingRemoteEvents`;
14649
+ // - 稍后插件的 `$events` 客户端注册成功 → 网关在**新客户端注册时重推所有 pending**
14650
+ // (同文件 `:1045`)→ ② 又建一个条目。
14651
+ // - 结果:手机收到两张卡、宿主有两个条目;`/respond` 只结算其中一个 → 另一张成幽灵卡。
14652
+ //
14653
+ // 修法:**只针对“同一次逻辑请求”做跨路径去重**,不是“同 session 只留一个”。
14654
+ //
14655
+ // 关键约束(评审 R16,`test/host-compat-021.test.mjs` / `offline-approval-dual.test.mjs`
14656
+ // 明确钉住):同一个 `callId` 上的**两次不同审批**(如 pre-execute 与工具体内
14657
+ // sandbox escalation)必须各自建条目、各自有独立身份;同一 `eventId` 的重放才去重。
14658
+ // 因此**不能**用“同 session 已有待答就跳过”去做仲裁——那会把 R16 的真实第二条审批吞掉。
14659
+ //
14660
+ // 这里用的判据是**内容同一性**:
14661
+ // - 问询:同 session 且 `questions` 结构相同(JSON 相等)的未结算条目 = 同一次逻辑提问;
14662
+ // - 审批:同 session 且 `toolName` + `callId` + `reason` 都相同的未结算条目。
14663
+ // 注意 R16 的第二条审批 `reason` 不同("sandbox escalation"),所以不会被误并。
14664
+ // 只有“两条路径都看到同一次请求”才会命中;两次真实的新请求仍各建一张卡。
14665
+ //
14666
+ // 该判据保守、可解释,且不依赖 `Date.now()` 那种不可复现的身份。
14667
+ // 命中时按 `跨路径去重(#177)` 记 info 日志,便于现场取证。
14668
+ const sameJson = (a, b) => {
14669
+ try { return JSON.stringify(a ?? null) === JSON.stringify(b ?? null); } catch { return false; }
14670
+ };
14671
+
14672
+ /**
14673
+ * 找“同一次逻辑问询”的跨路径孪生条目。
14674
+ *
14675
+ * `$events` 路径已在上面按 `sessionId:eventId` 精确去重;这里额外处理
14676
+ * **瀑布路径先建、`$events` 后到**(以及反向)时两条路径身份形态不同导致的重复。
14677
+ */
14678
+ const findTwinQuestion = (sessionId, questions) => {
14679
+ for (const entry of pendingQuestions.values()) {
14680
+ if (entry.sessionId !== sessionId) continue;
14681
+ if (!sameJson(entry.questions, questions)) continue;
14682
+ return entry;
14683
+ }
14684
+ return null;
14685
+ };
14686
+
14687
+ /** 找“同一次逻辑审批”的跨路径孪生条目(`reason` 不同即视为不同审批,见 R16)。 */
14688
+ const findTwinApproval = (sessionId, request) => {
14689
+ for (const entry of pendingApprovals.values()) {
14690
+ if (entry.sessionId !== sessionId) continue;
14691
+ if (entry.toolName !== request?.toolName) continue;
14692
+ if (entry.callId !== request?.callId) continue;
14693
+ if (entry.reason !== request?.reason) continue;
14694
+ return entry;
14695
+ }
14696
+ return null;
14697
+ };
14698
+
13919
14699
  // $events 事件处理:瀑布经内核转发到达网关后才投给本客户端。
13920
14700
  // v3.1.4(issue #14 Bug1+Bug2):**不再因手机离线而早退**——旧行为
13921
14701
  // `if (connections.size === 0) return;` 同时造成两件事:
@@ -13923,7 +14703,8 @@ export function apply(ctx, config, runtime = {}) {
13923
14703
  // (报告人 12 小时 ntfy 历史 0 条即此,而不是他推测的"推送挂在 apiProxy 上");
13924
14704
  // ② 待答条目与回放帧都不建 → 手机事后打开既没有卡可显示、/respond 也无条目可结算。
13925
14705
  // 现在:无论手机是否在线都建条目 + 写回放存储;**只在手机在线时** arm fail-close 超时
13926
- // (离线时由桌面端独自处理,不能被手机侧 120s 超时误杀),离线条目走 armOfflineReap。
14706
+ // (离线时由桌面端独自处理,不能被手机侧 120s 超时误杀)。离线条目**不设 TTL**
14707
+ // (#177 方案 A:跟随本体语义,等手机回来补答),仅受 `PENDING_ENTRIES_MAX` 容量兜底。
13927
14708
  const onEventsWaterfall = (frame) => {
13928
14709
  const phoneOnline = connections.size > 0;
13929
14710
  // issue #120(防御性修复):$events 帧只带 agentId 字符串,而 agentId 与 sessionId
@@ -13943,12 +14724,24 @@ export function apply(ctx, config, runtime = {}) {
13943
14724
  // 新审批被第一次的 resolved 身份拦截,又保留重放去重(下面的 has())。
13944
14725
  const phoneKey = `${sessionId}:${eventId}`;
13945
14726
  if (pendingApprovals.has(phoneKey)) return;
14727
+ // #177:跨路径去重。**只**合并“同一次逻辑审批”(toolName+callId+reason 全同),
14728
+ // 不能按 session 一刀切——R16 要求同一 callId 的第二次 escalation 单独建卡。
14729
+ const twinApproval = findTwinApproval(sessionId, request);
14730
+ if (twinApproval !== null) {
14731
+ ctx.logger.info?.(`mobile-remote: approval/request 跨路径去重(#177):session=${sessionId} ` +
14732
+ `eventId=${eventId} 与已有待答 ${twinApproval.phoneId} 是同一次审批 → 不重复建卡`);
14733
+ return;
14734
+ }
13946
14735
  ctx.logger.info?.(`mobile-remote: approval/request 双端呈现(${sessionId} tool=${request?.toolName}${phoneOnline ? "" : ",手机离线→记账待回放"})`);
13947
14736
  const entry = {
13948
14737
  phoneId: phoneKey, sessionId, rpcId: eventId, timer: null,
13949
14738
  settle: (outcome) => void postEventsValue(eventId, outcome),
14739
+ // #177:与瀑布路径条目同形的内容判据,供反向去重(`findTwinApproval`)比对。
14740
+ toolName: request?.toolName, callId: request?.callId, reason: request?.reason,
13950
14741
  };
13951
14742
  pendingApprovals.set(phoneKey, entry);
14743
+ // #177 方案 A:所有插入点都做容量兜底。
14744
+ evictOldestIfOverCapacity("approval");
13952
14745
  const requested = {
13953
14746
  type: "approval/requested", rpcId: eventId, sessionId, approvalId: phoneKey,
13954
14747
  toolName: request?.toolName, callId: request?.callId, reason: request?.reason,
@@ -13961,9 +14754,9 @@ export function apply(ctx, config, runtime = {}) {
13961
14754
  ctx.logger.warn?.(`mobile-remote: approval/request 双端待办超时 → rejected(超时自动拒绝)(${phoneKey})`);
13962
14755
  finishApproval(entry, "rejected");
13963
14756
  });
13964
- } else {
13965
- armOfflineReap(entry, "a");
13966
14757
  }
14758
+ // #177 方案 A:离线不再 arm 回收定时器(条目长期保留,等手机回来补答)。
14759
+ // 容量兜底已在插入点统一处理,这里无需额外动作。
13967
14760
  broadcast({ type: "mobile/frame", frame: requested });
13968
14761
  // 推送与手机是否在线无关:App 关闭时这是**唯一**的提醒通道(issue #14 Bug1)。
13969
14762
  // 宽限期:桌面先答/自动批准时不该再响一次。
@@ -13977,6 +14770,16 @@ export function apply(ctx, config, runtime = {}) {
13977
14770
  // 而永不触发。稳定身份同时保证定时器与回放帧被复用,而不是各来一份。
13978
14771
  const phoneKey = `${sessionId}:${eventId}`;
13979
14772
  if (pendingQuestions.has(phoneKey)) return;
14773
+ // #177:跨路径去重。**只**合并 `questions` 结构相同的条目(= 同一次提问)。
14774
+ // 典型来源:本插件瀑布路径刚接管过同一次提问,随后网关在新客户端注册时把该
14775
+ // pending 重推过来。这里保留**已有**条目:它 bound 到内核瀑布 promise、
14776
+ // 有自己的超时与回放帧,替换会让那条 promise 失去结算通路。
14777
+ const twin = findTwinQuestion(sessionId, request?.questions);
14778
+ if (twin !== null) {
14779
+ ctx.logger.info?.(`mobile-remote: user-questions/request 跨路径去重(#177):session=${sessionId} ` +
14780
+ `eventId=${eventId} 与已有待答 ${twin.phoneId} 是同一次提问 → 不重复建卡`);
14781
+ return;
14782
+ }
13980
14783
  ctx.logger.info?.(`mobile-remote: user-questions/request 双端呈现(${sessionId}${phoneOnline ? "" : ",手机离线→记账待回放"})`);
13981
14784
  ctx.logger.debug?.(`mobile-remote: question requested source=events sessionId=${sessionId} eventId=${eventId} ` +
13982
14785
  `phoneOnline=${phoneOnline} pendingQuestions=${pendingQuestions.size} pendingFrames=${pendingFrames.size}`);
@@ -13989,6 +14792,8 @@ export function apply(ctx, config, runtime = {}) {
13989
14792
  reject: (reason) => void postEventsRejection(eventId, reason),
13990
14793
  };
13991
14794
  pendingQuestions.set(phoneKey, entry);
14795
+ // #177 方案 A:所有插入点都做容量兜底。
14796
+ evictOldestIfOverCapacity("question");
13992
14797
  const requested = {
13993
14798
  type: "question/requested", rpcId: eventId, sessionId, questionId: phoneKey,
13994
14799
  // 网关投影后的 request 为顶层 questions(projectRemoteEventRequest 只剥
@@ -14001,9 +14806,8 @@ export function apply(ctx, config, runtime = {}) {
14001
14806
  ctx.logger.warn?.(`mobile-remote: user-questions/request 双端待办超时 → 取消(${phoneKey})`);
14002
14807
  finishQuestion(entry, questionCancelledError("ask_user_question timed out before the user answered"), { reject: true });
14003
14808
  });
14004
- } else {
14005
- armOfflineReap(entry, "q");
14006
14809
  }
14810
+ // #177 方案 A:同上,离线不设 TTL(跟随本体语义),容量兜底在插入点统一处理。
14007
14811
  broadcast({ type: "mobile/frame", frame: requested });
14008
14812
  notifyAskDeferred(sessionId, () => pendingQuestions.has(phoneKey), () => notifyQuestion(sessionId));
14009
14813
  return;
@@ -14175,6 +14979,13 @@ export function apply(ctx, config, runtime = {}) {
14175
14979
  ctx.logger.info?.("mobile-remote: approval/request 放行内核转发(桌面 GUI 弹卡)");
14176
14980
  return next();
14177
14981
  }
14982
+ // #177:跨路径去重的另一半。`$events` 路径已先为**同一次审批**建卡时不再建第二个。
14983
+ const twinApprovalHold = findTwinApproval(sessionId, req);
14984
+ if (twinApprovalHold !== null) {
14985
+ ctx.logger.info?.(`mobile-remote: approval/request 跨路径去重(#177):session=${sessionId} ` +
14986
+ `与已有待答 ${twinApprovalHold.phoneId} 是同一次审批 → 不重复建卡(放行内核)`);
14987
+ return next();
14988
+ }
14178
14989
  const { held, entry } = holdApproval(req, sessionId);
14179
14990
  // both 的语义就是「两端同显、先答生效」。$events 不可用时用 hold + next 竞速在本地复现;
14180
14991
  // mobile 保持手机独占;离线场景由 offlineAlsoDesktop 决定是否带上桌面。
@@ -14191,6 +15002,16 @@ export function apply(ctx, config, runtime = {}) {
14191
15002
  ctx.logger.info?.("mobile-remote: user-questions/request 放行内核转发(桌面 GUI 弹卡)");
14192
15003
  return next();
14193
15004
  }
15005
+ // #177:跨路径去重的另一半。同 session 已有未结算问询(典型:`$events` 路径先建了
15006
+ // 卡片,随后断流 → ready 翻 false → 同一提问再次走到瀑布路径)→ 不再建第二个条目。
15007
+ // 直接返回已有条目对应的 hold promise 不可能(它属于另一条路径的闭包),
15008
+ // 因此这里**只放行内核**:桌面照常弹卡,手机侧沿用既有条目,不会多出一张。
15009
+ const twin = findTwinQuestion(sessionId, req?.questions);
15010
+ if (twin !== null) {
15011
+ ctx.logger.info?.(`mobile-remote: user-questions/request 跨路径去重(#177):session=${sessionId} ` +
15012
+ `与已有待答 ${twin.phoneId} 是同一次提问 → 不重复建卡(放行内核)`);
15013
+ return next();
15014
+ }
14194
15015
  const { held, entry } = holdQuestion(req, sessionId);
14195
15016
  const wantDual = approvalMode === "both" || (!phoneOnline && offlineAlsoDesktop);
14196
15017
  if (!wantDual) return held;