dsh-mobile-plugin 0.5.88 → 0.5.90

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.
Files changed (41) hide show
  1. package/config/agent-presets/standard/agent.cordis.yml +5 -0
  2. package/config/agent-presets/standard/skills/dsh-mobile-kb/SKILL.md +43 -0
  3. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/network.md +27 -0
  4. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/offline.md +30 -0
  5. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/pairing.md +27 -0
  6. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/relay.md +23 -0
  7. package/docs/extension-authoring.md +24 -8
  8. package/extension-registry/index.json +15 -1
  9. package/lib/client.js +131 -28
  10. package/lib/impl.js +9 -13
  11. package/lib/mobile/ai-recipient.cjs +61 -0
  12. package/lib/mobile/approval-facts.js +26 -3
  13. package/lib/mobile/approvals.js +42 -11
  14. package/lib/mobile/extension-catalog.js +29 -3
  15. package/lib/mobile/extension-dev.js +7 -0
  16. package/lib/mobile/extension-metadata.cjs +40 -0
  17. package/lib/mobile/feedback-read.cjs +59 -0
  18. package/lib/mobile/feedback.js +24 -16
  19. package/lib/mobile/mux.js +30 -3
  20. package/lib/mobile/permissions.js +30 -0
  21. package/lib/mobile/plugin-catalog.js +5 -0
  22. package/lib/mobile/questions.js +21 -2
  23. package/lib/mobile/relay-control.js +4 -3
  24. package/lib/mobile/session-models.js +2 -1
  25. package/lib/mobile/session-send.js +16 -2
  26. package/lib/mobile/stream-registry.js +29 -4
  27. package/lib/mobile/subagents.js +6 -1
  28. package/lib/mobile/third-party-extensions.js +6 -1
  29. package/lib/panel/index.html +17 -15
  30. package/lib/relay/identity-rotate.cjs +4 -1
  31. package/lib/relay/preview.js +10 -1
  32. package/lib/relay/protocol.js +2 -2
  33. package/lib/relay/tunnel.js +7 -2
  34. package/lib/remote/controller.cjs +4 -1
  35. package/lib/remote/tunnel-helper.cjs +2 -2
  36. package/lib/routes/control-plane.js +21 -11
  37. package/lib/routes/feedback.cjs +20 -0
  38. package/lib/shared/route-order.cjs +6 -0
  39. package/lib/sidecar-facade-worker.cjs +8 -2
  40. package/lib/sidecar-lifecycle.cjs +94 -14
  41. package/package.json +2 -1
@@ -0,0 +1,61 @@
1
+ /** 已知自建端点在接入 prompt 前核对当前模型与配置;不读取凭据,不承诺队列未来每步的路由。 */
2
+ 'use strict';
3
+ const { unwrap } = require('./envelope.js');
4
+
5
+ function publicEndpoint(value) {
6
+ try {
7
+ const url = new URL(typeof value === 'string' ? value : '');
8
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') return '';
9
+ return `${url.protocol}//${url.host}${url.pathname.replace(/\/+$/, '')}`;
10
+ } catch { return ''; }
11
+ }
12
+ function refusal(code) {
13
+ return { code, message: code === 'ai-recipient-changed'
14
+ ? '模型接收方已改变,请回到手机重新确认后发送。'
15
+ : '这台电脑无法核实已确认的模型接收方,请更新插件或重新确认当前路由。' };
16
+ }
17
+
18
+ /** 缺省字段保留逐消息授权电脑当前路由的旧路径;显式字段不允许悄悄降级。 */
19
+ async function expectedAiRecipientError(ctx, { sessionId, expected, selection, child = false }) {
20
+ if (expected === undefined) return null;
21
+ if (!expected || typeof expected !== 'object' || typeof expected.provider !== 'string'
22
+ || !expected.provider.trim() || !publicEndpoint(expected.endpoint)) {
23
+ return { code: 'bad-request', message: 'expectedAiRecipient 需要 { provider, endpoint }。' };
24
+ }
25
+ const provider = expected.provider.trim();
26
+ const endpoint = publicEndpoint(expected.endpoint);
27
+ if (selection && selection.provider !== provider) return refusal('ai-recipient-changed');
28
+ try {
29
+ const llm = ctx.get && ctx.get('llm');
30
+ if (!llm || typeof llm.resolveCallConfig !== 'function') return refusal('ai-recipient-unverifiable');
31
+ const agents = ctx.get && ctx.get('agents');
32
+ let agent = agents && typeof agents.get === 'function' ? agents.get(sessionId) : null;
33
+ if (!agent && !child) {
34
+ const controller = ctx.get && ctx.get('sessionController');
35
+ if (controller && typeof controller.resolveAgent === 'function') {
36
+ const resolved = await controller.resolveAgent(sessionId);
37
+ if (resolved && !resolved.error) agent = resolved.agent;
38
+ }
39
+ }
40
+ const actual = agent && agent.model && typeof agent.model.current === 'function' ? agent.model.current() : null;
41
+ if (!actual || !actual.provider || !actual.model) return refusal('ai-recipient-unverifiable');
42
+ if (actual.provider !== provider) return refusal('ai-recipient-changed');
43
+ // 这是宿主当前模型配置校验,不把客户端声称的 route 当成实际 route。
44
+ const resolved = await llm.resolveCallConfig(actual);
45
+ if (!resolved || resolved.provider !== actual.provider || resolved.model !== actual.model) return refusal('ai-recipient-unverifiable');
46
+ const settings = unwrap(await ctx.apiProxy.settings.describe({ rpcId: 'mobile', method: 'settings.describe', payload: {} }));
47
+ if (settings.error) return refusal('ai-recipient-unverifiable');
48
+ const rows = Array.isArray(settings.value) ? settings.value : settings.value && settings.value.namespaces;
49
+ const namespace = Array.isArray(rows) ? rows.find((row) => row && row.ns === 'llm-pi-ai') : null;
50
+ const profiles = namespace && namespace.value && namespace.value.providers;
51
+ const profile = profiles && Object.hasOwn(profiles, provider) ? profiles[provider] : null;
52
+ // llm-pi-ai 的显式 baseURL 覆盖全部模型端点;无显式值时内置模型可能各用自己的端点。
53
+ const actualEndpoint = publicEndpoint(profile && profile.baseURL);
54
+ if (!actualEndpoint) return refusal('ai-recipient-unverifiable');
55
+ if (actualEndpoint !== endpoint) return refusal('ai-recipient-changed');
56
+ return null;
57
+ } catch {
58
+ return refusal('ai-recipient-unverifiable');
59
+ }
60
+ }
61
+ module.exports = { publicEndpoint, expectedAiRecipientError };
@@ -15,7 +15,8 @@
15
15
  * 「以后都同意」的粒度是这里最要紧的一处判断,四条都只认参数本身(`rememberable`):
16
16
  * - 删除 / 推送 / 装软件 / 跑第三方包(`isIrreversibleClass`);
17
17
  * - 写到**会话工作区之外**(`isWithin`):记 `write:abs` 等于「以后任意路径都能静默改」;
18
- * - **解析不出内容的壳**:内联执行的代码(`node -e` / `python3 -c`)、带命令替换的 shell;
18
+ * - **解析不出内容的壳**:内联执行的代码(`node -e` / `python3 -c`)、带命令替换的 shell、
19
+ * 解释器跑外部脚本文件(`bash install.sh`)、管道把内容喂进 shell(`curl … | sh`);
19
20
  * - 只起包装作用的程序先剥掉(`WRAPPERS`),否则记的是 `env` / `timeout` / `xargs` 这类壳。
20
21
  *
21
22
  * 详见 docs/dev-map / decisions 里这条改动的原因。
@@ -45,6 +46,8 @@ const OPTS_WITH_VALUE = new Set(['-u', '-g', '-n', '-p', '-C', '-S', '-I', '-L',
45
46
  const RUNNER_PROGS = new Set(['npx', 'bunx', 'uvx']);
46
47
  /** 内联执行代码的解释器:`node -e …` / `python3 -c …` 看不出来里面干了什么。 */
47
48
  const INTERPRETERS = new Set(['node', 'deno', 'bun', 'python', 'python3', 'ruby', 'perl', 'php']);
49
+ /** 壳解释器:`bash install.sh`、`curl … | sh` 这两种跑的内容同样读不到静态参数里。 */
50
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'fish']);
48
51
  /** 记账键里的档位尾巴:只有这两档是真档位,`unknown` 不加(见 `deriveApprovalFacts`)。 */
49
52
  const KEY_TIERS = new Set(['workspace-write', 'danger-full-access']);
50
53
  /** 包管理器 → 装包动词集合。 */
@@ -300,6 +303,25 @@ function isInlineCode(tokens) {
300
303
  return tokens.slice(1).some((t) => t === '-e' || t === '--eval' || t === '-c' || t === '-m' || /^-[a-z]*[ecm]$/.test(t));
301
304
  }
302
305
 
306
+ /**
307
+ * 这一段是不是「内容读不到」的执行:解释器/壳跑外部脚本文件,或管道把内容喂进壳。
308
+ *
309
+ * 与 `isOpaque` 同一个口径:命中的整张卡标 `nowhere`(不可「以后都同意」)。理由很直接:
310
+ * `bash install.sh` 里那支脚本、`curl … | sh` 那条管道喂进来的脚本,实际内容都不在这条
311
+ * 命令的静态参数里;按程序名记成 `bash:bash` / `bash:curl+sh` 就等于「以后任意脚本静默执行」。
312
+ * `-e/-c` 那种内联执行由上面的 `isInlineCode` 处理,这里不重复。
313
+ */
314
+ function isUnparseableExec(tokens) {
315
+ if (!tokens || tokens.length === 0) return false;
316
+ const prog = baseOf(tokens[0] || '');
317
+ // 壳解释器:`bash install.sh` / 管道末端的 `sh`(`curl … | sh`)——交给它的脚本看不到。
318
+ if (SHELLS.has(prog)) return true;
319
+ // 其它解释器带一个位置参数(脚本文件):`python a.py`、`node server.js` —— 文件内容看不到。
320
+ // 只有选项(`node --version`)没有脚本可跑,不算。
321
+ if (INTERPRETERS.has(prog)) return tokens.slice(1).some((t) => !t.startsWith('-'));
322
+ return false;
323
+ }
324
+
303
325
  /** 单次调用 → `{ clause, highlight, nowhere, classKey }`。 */
304
326
  function callToPiece(toolName, args) {
305
327
  const name = typeof toolName === 'string' ? toolName : '';
@@ -319,8 +341,9 @@ function callToPiece(toolName, args) {
319
341
  let highlight = false;
320
342
  let nowhere = false;
321
343
  for (const tokens of segs) {
322
- // 段内联执行代码(`python3 -c "…"`):整张卡不给记忆,理由同上面的 `isOpaque`。
323
- if (isInlineCode(tokens)) nowhere = true;
344
+ // 段内联执行代码(`python3 -c "…"`)或解释器/壳跑外部脚本:整张卡不给记忆,
345
+ // 理由同上面的 `isOpaque`。
346
+ if (isInlineCode(tokens) || isUnparseableExec(tokens)) nowhere = true;
324
347
  const piece = clauseOfSegment(tokens);
325
348
  if (!piece) continue;
326
349
  if (piece.clause) clauses.push(piece.clause);
@@ -29,6 +29,10 @@
29
29
  *
30
30
  * `classLabel`(类别人话)在推卡时随卡下发,供第三颗按钮旁那行说明;撤销接口在写盘失败时
31
31
  * 回非 ok,手机据此保留那一行并提示重试,不把没删成的规则当成已撤销。
32
+ *
33
+ * 「以后都同意」的 remembered 由 `approval-memory.addRule` 的返回值决定(写盘失败回 false),
34
+ * 与撤销同一口径。审批的 approvalId 一经下发不再变:钩子先到时的占位 id 保持不变,宿主真 id
35
+ * 另存 `realApprovalId`,只用于认领 `approval/decided` —— App 的审批队列按 approvalId 去重。
32
36
  */
33
37
 
34
38
  const { randomUUID } = require('node:crypto');
@@ -37,6 +41,20 @@ const { cancelForwardedRequests } = require('./host-bridge/transport.js');
37
41
  const { sessionIdOf } = require('./session-id.js');
38
42
  const facts = require('./approval-facts.js');
39
43
  const approvalMemory = require('./approval-memory.js');
44
+ const { anyApprover } = require('./permissions.js');
45
+ const { credentialsEntry } = require('../shared/credentials-entry.js');
46
+
47
+ /**
48
+ * 这台电脑上还有没有能答审批的设备。只读档设备收到的卡点了必然 403,所以一台能答的都没有时
49
+ * 桥不建卡也不推送。凭据包读不到时按「有」处理(任何异常都回 true,见 permissions.anyApprover)。
50
+ */
51
+ function canShowCards() {
52
+ try {
53
+ return anyApprover(credentialsEntry());
54
+ } catch {
55
+ return true;
56
+ }
57
+ }
40
58
 
41
59
  /**
42
60
  * `/approval/respond` 认三种结论(与 App 的按钮一一对应):
@@ -149,6 +167,9 @@ function broadcast(sessionId, frame) {
149
167
 
150
168
  function pushCard(entry) {
151
169
  if (entry.settled) return;
170
+ // 一台能答审批的设备都没有时(例如只配了只读档手机):不建卡也不推送。点下去必然 403 的卡
171
+ // 送上去只是打扰,见 `canShowCards`。
172
+ if (!canShowCards()) return;
152
173
  if (watcherCount(entry.sessionId) > 0) broadcast(entry.sessionId, cardFrame(entry));
153
174
  // 有人看就走 SSE,没人看也别什么都不做:手机在后台 / 被杀时那张卡到不了,
154
175
  // 只有这条推送能把它带到系统通知上。只有「已绑上钩子 = 答得动」的卡才推,
@@ -206,9 +227,11 @@ function entryFor(sessionId, ask, { unboundOnly = false } = {}) {
206
227
  // rpcId 是本桥自己铸的:0.2.x 的宿主不再提供任何可作答的帧级 id,而 App 只认带 rpcId 的帧。
207
228
  rpcId: `m-${randomUUID()}`,
208
229
  sessionId,
209
- // 钩子先到时还不知道宿主的 approvalId,先铸一个占位(只用于挂起项身份,回答不看它);
210
- // `approval/asked` 一到就换成真 id,好让 App 能把 approval/decided 对上。
230
+ // 钩子先到时还不知道宿主的 approvalId,先铸一个占位(只用于挂起项身份,回答不看它)。
231
+ // 真 id 到了**不改这一格**,另存 `realApprovalId`:App 的审批队列按 approvalId 去重/更新,
232
+ // approvalId 一变就会排成两张卡(见 noteAsk)。真 id 只用来把会话里的 approval/decided 对上。
211
233
  approvalId: ask.approvalId || `m-${randomUUID()}`,
234
+ realApprovalId: ask.approvalId || null,
212
235
  toolName: ask.toolName,
213
236
  callId: ask.callId,
214
237
  reason: ask.reason,
@@ -254,9 +277,11 @@ function attachSession(sessionId, sink) {
254
277
  if (!set) { set = new Set(); watchers.set(sessionId, set); }
255
278
  set.add(sink);
256
279
  // 补发:审批可能在手机还没看这个会话时就挂起了(用户在列表页点了进来),
257
- // 而钩子上的请求还在等 —— 那时候这张卡仍然答得动。
258
- for (const entry of openEntries(sessionId)) {
259
- if (entry.bound) { try { sink(cardFrame(entry)); } catch { /* ignore */ } }
280
+ // 而钩子上的请求还在等 —— 那时候这张卡仍然答得动。没有能答审批的设备时补发也没意义。
281
+ if (canShowCards()) {
282
+ for (const entry of openEntries(sessionId)) {
283
+ if (entry.bound) { try { sink(cardFrame(entry)); } catch { /* ignore */ } }
284
+ }
260
285
  }
261
286
  return () => {
262
287
  if (!set.delete(sink)) return;
@@ -286,6 +311,7 @@ function hasPending(sessionId) {
286
311
  * 一致:没绑上钩子的卡答不动,送上去只会让人点出一个 409。
287
312
  */
288
313
  function pendingCardOf(sessionId) {
314
+ if (!canShowCards()) return undefined;
289
315
  for (const entry of openEntries(sessionId)) {
290
316
  if (entry.bound) return cardFrame(entry);
291
317
  }
@@ -606,11 +632,13 @@ function noteAsk(session, sessionId, data) {
606
632
  callId: typeof data.callId === 'string' ? data.callId : undefined,
607
633
  reason: typeof data.reason === 'string' ? data.reason : undefined,
608
634
  };
609
- // 1) 已经挂着的那条(钩子先到):回填真 id、补事实、重推一次卡。这一步**不受**「已同意 /
635
+ // 1) 已经挂着的那条(钩子先到):补真 id、补事实、重推一次卡。这一步**不受**「已同意 /
610
636
  // 重复」影响 —— 钩子此刻正等着这个 id,丢了它 `approval/decided` 就永远对不上。
611
637
  const existing = findOpenEntry(sessionId, ask);
612
638
  if (existing) {
613
- existing.approvalId = approvalId;
639
+ // **不改 approvalId**:占位 id 已经随第一张卡发给了 App,这一改就会在 App 上排成第二张卡
640
+ // (其中一张回答必然 409)。真 id 另存,只给 `approval/decided` 认领用。
641
+ existing.realApprovalId = approvalId;
614
642
  if (ask.reason) {
615
643
  existing.reasonRaw = existing.reasonRaw || ask.reason;
616
644
  existing.reason = existing.reason || ask.reason;
@@ -632,7 +660,8 @@ function noteAsk(session, sessionId, data) {
632
660
  function noteDecided(sessionId, data) {
633
661
  const approvalId = typeof data.id === 'string' && data.id ? data.id : null;
634
662
  if (!approvalId) return;
635
- const entry = openEntries(sessionId).find((candidate) => candidate.approvalId === approvalId);
663
+ const entry = openEntries(sessionId).find((candidate) => candidate.approvalId === approvalId
664
+ || candidate.realApprovalId === approvalId);
636
665
  if (!entry) return;
637
666
  settle(entry, DECISIONS.has(data.outcome) ? data.outcome : 'unavailable');
638
667
  }
@@ -785,15 +814,17 @@ async function handleApprovalRespond(ctx, req, res) {
785
814
  const reason = typeof body.reason === 'string' ? body.reason.trim().slice(0, REASON_MAX) : '';
786
815
  const entry = entries.get(body.rpcId);
787
816
  if (entry && !entry.settled && entry.bound
788
- && entry.sessionId === body.sessionId && entry.approvalId === body.approvalId) {
817
+ && entry.sessionId === body.sessionId
818
+ && (entry.approvalId === body.approvalId || entry.realApprovalId === body.approvalId)) {
789
819
  // 「这一类以后都同意」:宿主只有 allowed-once 能放行,当前这条折成 allowed-once 交回;
790
820
  // 同时把动作类别记进本机规则账(能区分的键才记),之后同类不再弹卡。
791
821
  if (body.outcome === 'allowed-class') {
792
822
  let remembered = false;
793
823
  if (entry.rememberable && entry.classKey) {
794
824
  try {
795
- approvalMemory.addRule({ classKey: entry.classKey, label: facts.labelOf(entry.classKey) });
796
- remembered = true;
825
+ // 用 addRule 的返回值决定 remembered:写盘失败时它回 false(与 removeRule 的撤销口径
826
+ // 对齐),不能把没落成盘的规则回报成「已记住」,否则重启后规则又没了。
827
+ remembered = approvalMemory.addRule({ classKey: entry.classKey, label: facts.labelOf(entry.classKey) }) === true;
797
828
  } catch { /* 落盘失败不影响这一发放行 */ }
798
829
  }
799
830
  settle(entry, 'allowed-once');
@@ -1,3 +1,4 @@
1
+ // 目录返回真实来源与声明元数据;未知年龄与未公开链接保持空值。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -24,6 +25,18 @@ const path = require('node:path');
24
25
 
25
26
  const { sendJson } = require('../shared/http-util');
26
27
  const thirdParty = require('./third-party-extensions');
28
+ const { metadataOf } = require('./extension-metadata.cjs');
29
+ const registry = require('../../extension-registry/index.json');
30
+
31
+ /** 只有登记了实际扩展 slug 的条目才有官网详情;私装包不凭空获得公开记录。 */
32
+ function registryMetadata(slug, packageName) {
33
+ for (const plugin of registry.plugins || []) {
34
+ if (plugin.npm !== packageName) continue;
35
+ const extension = (plugin.extensions || []).find((entry) => entry.slug === slug);
36
+ if (extension) return metadataOf(extension);
37
+ }
38
+ return {};
39
+ }
27
40
 
28
41
  /** 审核清单文件名。只有列进来的 slug 才下发。 */
29
42
  const CATALOG_FILE = 'catalog.json';
@@ -109,8 +122,7 @@ function devServerOf(value) {
109
122
 
110
123
  /**
111
124
  * 读审核清单。文件不在、读坏、形状不对都当空清单 —— 空的插件包本来就没有第三方扩展。
112
- * 只收 slug / description / author / releaseNotes 四样,其余字段(包括任何 size / sha256)
113
- * 一概不认:清单只负责「谁审过了」,文件事实由扫目录算。
125
+ * 文案、来源、年龄与公开详情由清单声明;文件大小与 sha256 仍由扫目录算。
114
126
  */
115
127
  function readCatalog(root) {
116
128
  let text;
@@ -130,6 +142,7 @@ function readCatalog(root) {
130
142
  description: textOrNull(raw.description),
131
143
  author: textOrNull(raw.author),
132
144
  releaseNotes: textOrNull(raw.releaseNotes),
145
+ ...metadataOf(raw),
133
146
  });
134
147
  }
135
148
  return rows;
@@ -186,7 +199,14 @@ function readPackage(directory, slug, meta = {}) {
186
199
  const acc = { root: directory, files: [], bytes: 0 };
187
200
  if (!collectFiles(directory, acc) || acc.files.length === 0) return null;
188
201
  if (!acc.files.some((file) => file.path === 'index.html')) return null;
202
+ const declared = metadataOf(manifest);
203
+ const catalog = metadataOf(meta);
189
204
  return {
205
+ purpose: textOrNull(meta.purpose) ?? declared.purpose ?? textOrNull(meta.description),
206
+ sourceUrl: catalog.sourceUrl ?? declared.sourceUrl,
207
+ publicUrl: catalog.publicUrl ?? declared.publicUrl,
208
+ ageRating: catalog.ageRating ?? declared.ageRating,
209
+ sourcePackage: textOrNull(meta.sourcePackage),
190
210
  slug,
191
211
  name: textField(manifest.name, slug),
192
212
  description: meta.description ?? null,
@@ -247,7 +267,13 @@ function listThirdParty(pluginsRoot) {
247
267
  const description = manifest && typeof manifest.description === 'string' && manifest.description.trim()
248
268
  ? manifest.description
249
269
  : null;
250
- const pkg = readPackage(found.directory, found.slug, { description, author });
270
+ const registered = registryMetadata(found.slug, found.packageName);
271
+ const pkg = readPackage(found.directory, found.slug, {
272
+ description, author,
273
+ ...registered,
274
+ sourceUrl: found.sourceUrl ?? registered.sourceUrl,
275
+ sourcePackage: found.packageName,
276
+ });
251
277
  if (pkg) packages.push(pkg);
252
278
  }
253
279
  return packages;
@@ -1,3 +1,4 @@
1
+ // 开发包也返回实际声明的用途、来源、年龄与能力,供手动安装前确认。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -21,6 +22,7 @@ const path = require('node:path');
21
22
 
22
23
  const { sendJson } = require('../shared/http-util');
23
24
  const { dshHome } = require('../shared/paths');
25
+ const { metadataOf } = require('./extension-metadata.cjs');
24
26
 
25
27
  /** 开发包根目录名。目录不存在时按需建出来 —— 作者要往里放东西。 */
26
28
  const DEV_ROOT_NAME = 'extension-dev';
@@ -140,6 +142,11 @@ function listPackages(root) {
140
142
  const acc = { root: directory, files: [], bytes: 0 };
141
143
  if (!collectFiles(directory, acc)) continue;
142
144
  packages.push({
145
+ ...metadataOf(manifest),
146
+ sourcePackage: null,
147
+ capabilities: Array.isArray(manifest.capabilities)
148
+ ? [...new Set(manifest.capabilities.filter((value) => typeof value === 'string' && value.trim()))]
149
+ : [],
143
150
  slug: entry.name,
144
151
  name: textField(manifest.name, entry.name),
145
152
  versionName: textField(manifest.versionName, textField(manifest.version, '0.0.0')),
@@ -0,0 +1,40 @@
1
+ // 扩展目录声明:来源、用途和年龄只透传作者提供的事实,不推断评级。
2
+ 'use strict';
3
+
4
+ function textOrNull(value) {
5
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
6
+ }
7
+
8
+ function httpsOrNull(value) {
9
+ const text = textOrNull(value);
10
+ if (!text) return null;
11
+ try { return new URL(text).protocol === 'https:' ? text : null; } catch { return null; }
12
+ }
13
+
14
+ function ageRatingOf(value) {
15
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
16
+ const system = textOrNull(value.system);
17
+ const rating = textOrNull(value.value);
18
+ const minAge = Number.isInteger(value.minAge) && value.minAge >= 0 && value.minAge <= 21 ? value.minAge : null;
19
+ return system && rating ? { system, value: rating, minAge, url: httpsOrNull(value.url) } : null;
20
+ }
21
+
22
+ function metadataOf(value) {
23
+ const row = value && typeof value === 'object' ? value : {};
24
+ return {
25
+ purpose: textOrNull(row.purpose) || textOrNull(row.description),
26
+ sourceUrl: httpsOrNull(row.sourceUrl),
27
+ publicUrl: httpsOrNull(row.publicUrl),
28
+ ageRating: ageRatingOf(row.ageRating),
29
+ };
30
+ }
31
+
32
+ /** package.json 的仓库写法有字符串与对象两种;它是来源地址,不是公共详情页。 */
33
+ function packageSourceUrl(manifest) {
34
+ const repository = manifest && manifest.repository;
35
+ const raw = typeof repository === 'string' ? repository : repository && repository.url;
36
+ return httpsOrNull(typeof raw === 'string' ? raw.replace(/^git\+/, '').replace(/\.git$/, '') : null)
37
+ || httpsOrNull(manifest && manifest.homepage);
38
+ }
39
+
40
+ module.exports = { metadataOf, ageRatingOf, httpsOrNull, packageSourceUrl };
@@ -0,0 +1,59 @@
1
+ // 用途:按线程 key 读取固定分发平台的反馈,工具与本机控制面共用同一份线程契约。
2
+ 'use strict';
3
+
4
+ const PLATFORM_ORIGIN = 'https://app.wnluo.com';
5
+ const FEEDBACK_PATH = '/api/sdk/feedback';
6
+ const READ_TIMEOUT_MS = 10_000;
7
+
8
+ function feedbackError(message, status) {
9
+ return Object.assign(new Error(message), { status });
10
+ }
11
+
12
+ /** 与 App 的反馈线程视图保持同形状,不回传平台侧的设备与诊断元数据。 */
13
+ function threadView(raw) {
14
+ if (!raw || typeof raw.thread_key !== 'string' || !raw.thread_key.trim()) {
15
+ throw feedbackError('反馈接口没有返回线程信息', 502);
16
+ }
17
+ return {
18
+ id: typeof raw.id === 'number' ? raw.id : 0,
19
+ thread_key: raw.thread_key,
20
+ status: raw.status === 'closed' ? 'closed' : 'open',
21
+ messages: Array.isArray(raw.messages) ? raw.messages.filter(message => message && typeof message.id === 'number').map(message => ({
22
+ id: message.id,
23
+ author: message.author === 'staff' ? 'staff' : 'user',
24
+ content: typeof message.content === 'string' ? message.content : '',
25
+ created_at: typeof message.created_at === 'string' ? message.created_at : '',
26
+ attachments: Array.isArray(message.attachments)
27
+ ? message.attachments.filter(file => file && typeof file.url === 'string' && typeof file.file_name === 'string')
28
+ : [],
29
+ })) : [],
30
+ created_at: typeof raw.created_at === 'string' ? raw.created_at : undefined,
31
+ last_user_at: typeof raw.last_user_at === 'string' ? raw.last_user_at : null,
32
+ last_staff_at: typeof raw.last_staff_at === 'string' ? raw.last_staff_at : null,
33
+ };
34
+ }
35
+
36
+ async function readFeedback(threadKey) {
37
+ const key = typeof threadKey === 'string' ? threadKey.trim() : '';
38
+ if (!key) throw feedbackError('read 需要 threadKey', 400);
39
+ const controller = new AbortController();
40
+ const timer = setTimeout(() => controller.abort(), READ_TIMEOUT_MS);
41
+ try {
42
+ const response = await fetch(`${PLATFORM_ORIGIN}${FEEDBACK_PATH}?thread_key=${encodeURIComponent(key)}`, {
43
+ method: 'GET',
44
+ signal: controller.signal,
45
+ });
46
+ let body = null;
47
+ try { body = await response.json(); } catch { body = null; }
48
+ if (response.status >= 200 && response.status < 300) return threadView(body?.data);
49
+ const message = typeof body?.error === 'string' ? body.error.trim() : '';
50
+ throw feedbackError(message || `反馈读取失败(HTTP ${response.status})`, response.status);
51
+ } catch (error) {
52
+ if (error?.name === 'AbortError') throw feedbackError('反馈读取超时,网络可能不通', 504);
53
+ throw error;
54
+ } finally {
55
+ clearTimeout(timer);
56
+ }
57
+ }
58
+
59
+ module.exports = { readFeedback };
@@ -1,4 +1,4 @@
1
- // 用途:插件反馈的统一提交口——AI 工具与就地入口共用字段、身份与诊断附件,无手机也能提交。
1
+ // 用途:插件反馈统一提交与读取口;工具和本机面板按线程查看官方回复、继续跟进。
2
2
  'use strict';
3
3
 
4
4
  /**
@@ -9,8 +9,8 @@
9
9
  *
10
10
  * - **分发平台**:公开反馈接口(`/api/sdk/feedback`)。明确指定设备号时带上那台手机的
11
11
  * 身份;没指定时用这台电脑上的插件安装身份;没配手机时依然能交,受影响手机那几格留空。
12
- * 诊断文本作为 text/plain 附件一起发。官方回复在维护者反馈队列里跟进(`npm run feedback`),
13
- * 这条先留在本机,不会写进 App 的反馈列表,线程 key 当场回显给用户复制。
12
+ * 诊断文本作为 text/plain 附件一起发。线程 key 当场回显,可在本机面板或工具里读取
13
+ * 官方回复,再带同一个 key 继续补充;线程历史由提交端保留,不写进 App 的反馈列表。
14
14
  * - **GitHub**:插件代码本身的 bug 可以直接提 PR。这条路依赖用户自己登录 GitHub,
15
15
  * 插件无法代提,所以只把仓库与前提写进说明,由 AI 自己判断走不走。
16
16
  *
@@ -23,6 +23,7 @@
23
23
 
24
24
  const { randomUUID } = require('node:crypto');
25
25
  const { version: COMPONENT_VERSION } = require('../../package.json');
26
+ const { readFeedback } = require('./feedback-read.cjs');
26
27
 
27
28
  const PLATFORM_ORIGIN = 'https://app.wnluo.com';
28
29
  const FEEDBACK_PATH = '/api/sdk/feedback';
@@ -65,7 +66,7 @@ function feedbackChannels() {
65
66
  {
66
67
  kind: 'distribution',
67
68
  name: 'APP 分发系统反馈',
68
- description: '提交到分发平台的公开反馈接口(与 App 里的反馈页同一个)。没配手机也能提交:指定设备号才带那台手机的身份,否则用这台电脑的插件安装身份;诊断文本作 text/plain 附件。官方回复在维护者反馈队列里跟进(npm run feedback 查看),这条先留在本机,不会写进 App 的反馈列表,提交后当场给出可复制的线程 key。',
69
+ description: '提交到分发平台的公开反馈接口(与 App 里的反馈页同一个)。没配手机也能提交:指定设备号才带那台手机的身份,否则用这台电脑的插件安装身份;诊断文本作 text/plain 附件。提交后给出可复制的线程 key,可在本机面板或工具 read 动作查看官方回复,再用 submit 带 threadKey 继续补充;不会写进 App 的反馈列表。',
69
70
  endpoint: `${PLATFORM_ORIGIN}${FEEDBACK_PATH}`,
70
71
  requiresLogin: false,
71
72
  },
@@ -178,9 +179,8 @@ async function postMultipart(form) {
178
179
  const text = body && typeof body === 'object' && typeof body.error === 'string'
179
180
  ? body.error.trim()
180
181
  : '';
181
- if (text) throw new Error(text);
182
- if (response.status === 429) throw new Error('反馈提交太频繁,稍后再试');
183
- throw new Error(`反馈提交失败(HTTP ${response.status})`);
182
+ const message = text || (response.status === 429 ? '反馈提交太频繁,稍后再试' : `反馈提交失败(HTTP ${response.status})`);
183
+ throw Object.assign(new Error(message), { status: response.status });
184
184
  } catch (error) {
185
185
  if (error && error.name === 'AbortError') throw new Error('反馈提交超时,网络可能不通');
186
186
  throw error;
@@ -196,6 +196,9 @@ async function postMultipart(form) {
196
196
  * `componentVersion`(就地入口从宿主读到的版本)。
197
197
  */
198
198
  async function submitFeedback(deps, content, threadKey, deviceId, options = {}) {
199
+ content = typeof content === 'string' ? content.trim() : '';
200
+ if (!content) throw Object.assign(new Error('submit 需要 content'), { status: 400 });
201
+ if (content.length > CONTENT_MAX) throw Object.assign(new Error(`content 超长(上限 ${CONTENT_MAX} 字)`), { status: 400 });
199
202
  const id = typeof deps && typeof deps.instanceId === 'function' ? deps.instanceId() : '';
200
203
  const devices = deps && deps.credentials && typeof deps.credentials.listDevices === 'function'
201
204
  ? deps.credentials.listDevices(id)
@@ -222,7 +225,7 @@ async function submitFeedback(deps, content, threadKey, deviceId, options = {})
222
225
  threadKey: key,
223
226
  submissionId,
224
227
  message: key
225
- ? `已提交到分发平台,反馈编号 ${key}。请复制编号留档;这条先留在本机,不会写进 App 的反馈列表。`
228
+ ? `已提交到分发平台,反馈编号 ${key}。请复制编号留档,可在本机面板查看回复,或用 read 读取、submit 带 threadKey 继续补充;不会写进 App 的反馈列表。`
226
229
  : '已提交到分发平台。',
227
230
  };
228
231
  }
@@ -237,15 +240,15 @@ function registerFeedbackTool(ctx, deps) {
237
240
  ctx.tools.register(defineTool({
238
241
  name: 'dsh_feedback',
239
242
  description: 'Report a real problem with this mobile plugin or the AI-HUB app. '
240
- + 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it. You do NOT need to find the root cause: describe what you observed, what you already checked, and what is still uncertain. No paired phone is required either; without an explicitly chosen device the plugin submits under its local installation identity, with a text/plain diagnostics attachment and a thread key you can show to the user. Official replies are followed up in the maintainer feedback queue (run `npm run feedback`); the feedback stays local first and is not written into the in-app feedback list. '
243
+ + 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it. You do NOT need to find the root cause: describe what you observed, what you already checked, and what is still uncertain. No paired phone is required either; without an explicitly chosen device the plugin submits under its local installation identity, with a text/plain diagnostics attachment and a thread key you can show to the user. Use `read` with the thread key to view the conversation and official replies, then `submit` with the same threadKey to follow up. The local feedback dialog can show these threads; they are not written into the in-app feedback list. '
241
244
  + '(2) GitHub — code-level bugs can go to https://github.com/WNLUO/dsh-mobile-plugin as a pull request or issue, but that needs the user to be logged into GitHub and is not submitted by this tool. '
242
245
  + 'Use `channels` to list both routes.',
243
246
  parameters: {
244
247
  action: {
245
248
  type: 'string',
246
249
  required: true,
247
- enum: ['channels', 'submit'],
248
- description: 'channels: list the feedback routes. submit: send the content to the distribution platform.',
250
+ enum: ['channels', 'read', 'submit'],
251
+ description: 'channels: list the feedback routes. read: view a thread and replies. submit: open a feedback thread or follow up using threadKey.',
249
252
  },
250
253
  content: {
251
254
  type: 'string',
@@ -253,7 +256,7 @@ function registerFeedbackTool(ctx, deps) {
253
256
  },
254
257
  threadKey: {
255
258
  type: 'string',
256
- description: 'Optional for submit: append to an existing feedback thread instead of opening a new one.',
259
+ description: 'Required for read. Optional for submit: append to this existing feedback thread instead of opening a new one.',
257
260
  },
258
261
  deviceId: {
259
262
  type: 'string',
@@ -282,6 +285,7 @@ function registerFeedbackTool(ctx, deps) {
282
285
  },
283
286
  },
284
287
  submitted: { type: 'boolean' },
288
+ thread: { type: 'object', additionalProperties: true },
285
289
  threadKey: { type: 'string' },
286
290
  message: { type: 'string' },
287
291
  },
@@ -292,11 +296,12 @@ function registerFeedbackTool(ctx, deps) {
292
296
  switch (args.action) {
293
297
  case 'channels':
294
298
  return { action: 'channels', channels };
299
+ case 'read': {
300
+ const thread = await readFeedback(args.threadKey);
301
+ return { action: 'read', threadKey: thread.thread_key, thread };
302
+ }
295
303
  case 'submit': {
296
- const content = typeof args.content === 'string' ? args.content.trim() : '';
297
- if (!content) throw new Error('submit 需要 content');
298
- if (content.length > CONTENT_MAX) throw new Error(`content 超长(上限 ${CONTENT_MAX} 字)`);
299
- const submitted = await submitFeedback(deps, content, args.threadKey, args.deviceId);
304
+ const submitted = await submitFeedback(deps, args.content, args.threadKey, args.deviceId);
300
305
  return { action: 'submit', submitted: true, threadKey: submitted.threadKey, message: submitted.message };
301
306
  }
302
307
  default:
@@ -312,6 +317,8 @@ function renderSummary(value) {
312
317
  const names = (value.channels || []).map((channel) => channel.name).join('、');
313
318
  return `两条反馈途径:${names || '(空)'}`;
314
319
  }
320
+ case 'read':
321
+ return `反馈 ${value.threadKey}(${value.thread.status})\n${value.thread.messages.map(message => `[${message.author === 'staff' ? '官方' : '用户'} ${message.created_at}] ${message.content}`).join('\n')}`;
315
322
  case 'submit':
316
323
  return value.message || '已提交反馈。';
317
324
  default:
@@ -345,6 +352,7 @@ module.exports = {
345
352
  installFeedback,
346
353
  localDeviceId,
347
354
  pickDevice,
355
+ readFeedback,
348
356
  registerFeedbackTool,
349
357
  submissionIdFor,
350
358
  submitFeedback,
package/lib/mobile/mux.js CHANGED
@@ -1,4 +1,4 @@
1
- // 将已鉴权设备的多路请求限制在移动 API,并管理心跳、响应头期限与上游生命周期。
1
+ // mux 握手遵守查看权限,连接归属随身份迁移并保留有界吊销回执。
2
2
  'use strict';
3
3
 
4
4
  /**
@@ -25,6 +25,7 @@ const { performance } = require('node:perf_hooks');
25
25
  const { StringDecoder } = require('node:string_decoder');
26
26
  const { WebSocketServer } = require('ws');
27
27
  const { withViaHeader } = require('../shared/via-header');
28
+ const { resolvePermission, hasPermission } = require('./permissions');
28
29
 
29
30
  const MOBILE_PATH = /^\/api\/mobile\/v1\/[a-zA-Z0-9/_-]+(?:\?[^\r\n#]*)?$/;
30
31
  const CONNECTION_HEADERS = new Set([
@@ -62,6 +63,19 @@ function safeJson(text) {
62
63
  try { return JSON.parse(text); } catch { return null; }
63
64
  }
64
65
 
66
+ /** 当前实现的鉴权提供给稳定外壳,旧 mux 也使用本代的查看权限判定。 */
67
+ function createMuxAuthorizer(authOutcome) {
68
+ return (req) => {
69
+ try {
70
+ const outcome = authOutcome(req);
71
+ if (!outcome.ok || !outcome.record) return false;
72
+ if (!hasPermission(outcome.record, resolvePermission('/api/mobile/v1/mux', 'GET'))) return false;
73
+ req.__dshRecord = outcome.record;
74
+ return true;
75
+ } catch { return false; }
76
+ };
77
+ }
78
+
65
79
  /**
66
80
  * 建一个 mux 服务。
67
81
  *
@@ -94,6 +108,12 @@ function createMuxService(opts = {}) {
94
108
  try { socket.destroy(); } catch { /* ignore */ }
95
109
  return;
96
110
  }
111
+ const need = resolvePermission('/api/mobile/v1/mux', 'GET');
112
+ if (need === 'unknown' || (need && !hasPermission(req.__dshRecord, need))) {
113
+ try { socket.write('HTTP/1.1 403 Forbidden\r\nconnection: close\r\ncontent-length: 0\r\n\r\n'); } catch { /* 已断 */ }
114
+ try { socket.destroy(); } catch { /* 已关闭 */ }
115
+ return;
116
+ }
97
117
  if (connectionCount >= MAX_CONNECTIONS) {
98
118
  try { socket.write('HTTP/1.1 503 Service Unavailable\r\nconnection: close\r\ncontent-length: 0\r\n\r\n'); } catch { /* ignore */ }
99
119
  try { socket.destroy(); } catch { /* ignore */ }
@@ -350,9 +370,16 @@ function createMuxService(opts = {}) {
350
370
  }
351
371
  return count;
352
372
  };
373
+ const reassignInstance = (fromInstanceId, toInstanceId) => {
374
+ const from = String(fromInstanceId || '');
375
+ const to = String(toInstanceId || '');
376
+ for (const identity of deviceConnections.values()) {
377
+ if (identity.instanceId === from) identity.instanceId = to;
378
+ }
379
+ };
353
380
  const dropDevice = (deviceId, instanceId, response) => dropConnections(deviceId, instanceId, response);
354
381
  const dropAll = (instanceId, response) => dropConnections(undefined, instanceId, response);
355
- return { handleUpgrade, dropDevice, dropAll, MAX_MESSAGE_BYTES };
382
+ return { handleUpgrade, dropDevice, dropAll, reassignInstance, MAX_MESSAGE_BYTES };
356
383
  }
357
384
 
358
- module.exports = { createMuxService, MAX_MESSAGE_BYTES, MAX_STREAMS_PER_CONNECTION, MAX_CONNECTIONS, REVOKE_DRAIN_TIMEOUT_MS };
385
+ module.exports = { createMuxService, createMuxAuthorizer, MAX_MESSAGE_BYTES, MAX_STREAMS_PER_CONNECTION, MAX_CONNECTIONS, REVOKE_DRAIN_TIMEOUT_MS };