dsh-mobile-plugin 0.5.46 → 0.5.48

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.
@@ -16,8 +16,8 @@
16
16
  * - `read` / `read_image`:读过的本地文件,路径指出「这个结论是从哪份材料来的」;
17
17
  * - `web_search`:搜索本身也算材料来源,查询词是它唯一的指针。
18
18
  * `grep` / `glob` 不挑:它们是在仓库里找,挑出来只是一串正则,读者拿它回不到任何一份材料。
19
- * 工具名与摘要一律走 `step-index.js` 的 `toolStepSummary`,不在这里另拼一套(同一行摘要在
20
- * 过程清单里长什么样,来源卡里就长什么样)。
19
+ * 来源地址从工具原始参数里取,完整保留路径 / 网址 / 查询词;过程清单的 72 字摘要只用于
20
+ * 预览,不能拿来当来源地址,否则长路径会先被截短,连文件名与复制出的地址也一起丢失。
21
21
  *
22
22
  * 条数:这一轮读过的材料都给出来,手机上自己折叠成前几条、展开看全。插件侧只留一条极端兜底
23
23
  * (`MAX_SOURCES`),防的是一轮读几百份材料时把回包撑爆,正常研究场景到不了。
@@ -26,8 +26,10 @@
26
26
  const { sendJson } = require('../shared/http-util');
27
27
  const { callSessions } = require('./rpc.js');
28
28
  const { unwrap } = require('./envelope.js');
29
- const { toolStepSummary } = require('./step-index.js');
30
- const { liveStepsOf, liveStepsTurnOf } = require('./live-steps.js');
29
+ const { parseArgs } = require('./step-index.js');
30
+ const { liveStepOf, liveStepsOf, liveStepsTurnOf } = require('./live-steps.js');
31
+ const { readTurnEvents } = require('./session-changes.js');
32
+ const { resultCallId, successfulResult } = require('./turn-facts.js');
31
33
 
32
34
  /** 来源条数的极端兜底:一轮读到的材料照单全出,这里只防回包被几百份材料撑爆。 */
33
35
  const MAX_SOURCES = 60;
@@ -48,6 +50,21 @@ function kindOfTool(name) {
48
50
  return '';
49
51
  }
50
52
 
53
+ /** 来源指针取原始参数,不经过过程清单的摘要截断。 */
54
+ function placesOfTool(name, rawArgs) {
55
+ const args = parseArgs(rawArgs);
56
+ if (SEARCH_TOOLS.has(name) && Array.isArray(args.queries)) {
57
+ return args.queries.filter((value) => typeof value === 'string' && value.trim() !== '')
58
+ .map((value) => value.trim());
59
+ }
60
+ const keys = FILE_TOOLS.has(name) ? ['file_path', 'path']
61
+ : WEB_TOOLS.has(name) ? ['url'] : ['query', 'q'];
62
+ for (const key of keys) {
63
+ if (typeof args[key] === 'string' && args[key].trim() !== '') return [args[key].trim()];
64
+ }
65
+ return [];
66
+ }
67
+
51
68
  /** 网址里的主机名(取不到就回空串,调用方退回整条网址)。 */
52
69
  function hostOf(url) {
53
70
  const match = /^[a-z][a-z0-9+.-]*:\/\/([^/?#]+)/i.exec(String(url || ''));
@@ -64,9 +81,8 @@ function baseOf(path) {
64
81
  /**
65
82
  * 从一轮的步骤里挑出来源。
66
83
  *
67
- * @param {ReadonlyArray<{key?: string, step?: object}>} entries 过程清单(与 `liveStepsOf` /
68
- * `turnProcess.steps` 同一个形状:`{ key, step }`,`step` 带 `kind` / `name` / `summary` /
69
- * `state`)。
84
+ * @param {ReadonlyArray<{key?: string, step?: object, argsRaw?: string|object}>} entries
85
+ * 过程清单附宿主内的原始参数;只提取指针,不把参数放进返回值。
70
86
  * @returns {Array<{obsId:number, kind:string, place:string, title:string, step:number, mediaIds:number[], source:string}>}
71
87
  * 宿主侧的来源形状(App 的 `HostAnswerSource`),至多 `MAX_SOURCES` 条,按读到先后。
72
88
  */
@@ -83,13 +99,13 @@ function answerSourcesOf(entries) {
83
99
  const name = typeof step.name === 'string' ? step.name : '';
84
100
  const kind = kindOfTool(name);
85
101
  if (kind === '') continue;
86
- const place = typeof step.summary === 'string' ? step.summary.trim() : '';
87
- if (place === '') continue;
88
- const title = kind === 'web' ? (hostOf(place) || place) : kind === 'file' ? (baseOf(place) || place) : place;
89
- const hit = { kind, place, title, step: index + 1, source: name };
90
- const seen = hits.findIndex((item) => item.kind === kind && item.place === place);
91
- if (seen >= 0) hits.splice(seen, 1);
92
- hits.push(hit);
102
+ for (const place of placesOfTool(name, entry.argsRaw)) {
103
+ const title = kind === 'web' ? (hostOf(place) || place) : kind === 'file' ? (baseOf(place) || place) : place;
104
+ const hit = { kind, place, title, step: index + 1, source: name };
105
+ const seen = hits.findIndex((item) => item.kind === kind && item.place === place);
106
+ if (seen >= 0) hits.splice(seen, 1);
107
+ hits.push(hit);
108
+ }
93
109
  }
94
110
  // 冲到兜底上限时留最近读的那几条:越近越可能是这一轮结论的出处。
95
111
  return hits.slice(-MAX_SOURCES).map((hit, index) => ({
@@ -107,11 +123,20 @@ function answerSourcesOf(entries) {
107
123
  * 历史事件里的工具调用 → 每一轮的步骤数组。
108
124
  *
109
125
  * 只读 assistant 消息里的 tool-call 块(参数在这一层还在,与 `history-derive` 取「做过哪些
110
- * 写」同一个位置);摘要走 `toolStepSummary`。
126
+ * 写」同一个位置);保留原始参数供来源提取,不把截短的摘要当地址。
111
127
  */
112
128
  function stepsByTurnOf(events) {
113
129
  const turns = [];
114
130
  const byTurn = new Map();
131
+ const results = new Map();
132
+ for (const raw of events) {
133
+ const event = raw && raw.event ? raw.event : raw;
134
+ if (event?.type !== 'tool/result') continue;
135
+ const id = resultCallId(event);
136
+ if (!id) continue;
137
+ const interrupted = event.data?.error?.code === 'interrupted';
138
+ results.set(id, successfulResult(event) ? 'ok' : interrupted ? 'stopped' : 'error');
139
+ }
115
140
  const push = (turn, entry) => {
116
141
  if (!byTurn.has(turn)) {
117
142
  byTurn.set(turn, []);
@@ -124,6 +149,11 @@ function stepsByTurnOf(events) {
124
149
  if (!event || event.type !== 'assistant/message') continue;
125
150
  const data = event.data && typeof event.data === 'object' ? event.data : {};
126
151
  const turn = typeof data.turn === 'number' ? data.turn : null;
152
+ // 已知轮的纯文字答复也证明空来源;没在窗口里的旧轮仍返回 null。
153
+ if (turn !== null && !byTurn.has(turn)) {
154
+ byTurn.set(turn, []);
155
+ turns.push(turn);
156
+ }
127
157
  const message = data.message;
128
158
  const content = message && Array.isArray(message.content) ? message.content : [];
129
159
  for (const block of content) {
@@ -131,11 +161,11 @@ function stepsByTurnOf(events) {
131
161
  const callId = block.id != null ? String(block.id) : `${turn}:${byTurn.get(turn) ? byTurn.get(turn).length : 0}`;
132
162
  push(turn, {
133
163
  key: `tool:${callId}`,
164
+ argsRaw: block.arguments,
134
165
  step: {
135
166
  kind: 'tool',
136
167
  name: block.name,
137
- summary: toolStepSummary(block.name, block.arguments),
138
- state: 'ok',
168
+ state: results.get(callId) || 'ok',
139
169
  },
140
170
  });
141
171
  }
@@ -190,19 +220,25 @@ async function handleAnswerSources(ctx, req, res) {
190
220
  // 直播副本优先:跑着的那一轮(以及刚收口、还没重新拉历史的那一轮)只有这里有。
191
221
  const liveTurn = liveStepsTurnOf(ctx, sessionId);
192
222
  const liveSteps = liveStepsOf(ctx, sessionId);
193
- if (liveSteps.length > 0 && (wantedTurn === null || liveTurn === null || liveTurn === wantedTurn)) {
194
- return sendJson(res, 200, { ok: true, turn: liveTurn, sources: answerSourcesOf(liveSteps) });
223
+ if (!hasSubagentAddress && liveSteps.length > 0 && (wantedTurn === null || liveTurn === wantedTurn)) {
224
+ const entries = liveSteps.map((entry) => {
225
+ if (kindOfTool(entry.step.name) === '') return entry;
226
+ const detail = liveStepOf(ctx, sessionId, entry.step);
227
+ return { ...entry, argsRaw: detail && detail.argsRaw };
228
+ });
229
+ return sendJson(res, 200, { ok: true, turn: liveTurn, sources: answerSourcesOf(entries) });
195
230
  }
196
231
 
197
232
  const address = hasSubagentAddress ? { parentSessionId, mode } : {};
198
233
  try {
199
- const { value, error } = unwrap(await callSessions(ctx, 'history', {
200
- sessionId,
201
- maxMessages: HISTORY_MAX_MESSAGES,
202
- ...address,
234
+ // 点名旧轮时沿现有游标定向翻到轮首;只读尾窗会让屏幕上已经能看的旧回答永远没有来源。
235
+ const requested = wantedTurn !== null ? await readTurnEvents(ctx, sessionId, wantedTurn, address, new AbortController().signal) : null;
236
+ const history = requested ? null : unwrap(await callSessions(ctx, 'history', {
237
+ sessionId, maxMessages: HISTORY_MAX_MESSAGES, ...address,
203
238
  }));
204
- if (error) throw error;
205
- const events = value && Array.isArray(value.events) ? value.events : [];
239
+ if (history && history.error) throw history.error;
240
+ const events = requested ? requested.events : history?.value && Array.isArray(history.value.events) ? history.value.events : [];
241
+ if (requested?.truncated) return sendJson(res, 200, { ok: true, turn: null, sources: [] });
206
242
  const { turns, byTurn } = stepsByTurnOf(events);
207
243
  // 没有明确的轮号就取最近一轮(历史事件按 seq 递增,最后出现的轮号就是最近的)。
208
244
  const turn = wantedTurn !== null && byTurn.has(wantedTurn)
@@ -9,9 +9,15 @@
9
9
  * 一句话分工:headline 是 agent 自己说的(reason / displayReason),事实行是电脑从原始参数
10
10
  * 算出来的;删除 / 推送 / 装软件高亮。算不出来就**不出这一行**,绝不糊一句会让用户误判的话。
11
11
  *
12
- * 动作类别键 `classKey`(`<tool>:<class>`)既做「这一类以后都同意」的记账键,也做「同一轮
12
+ * 动作类别键 `classKey`(`<tool>:<class>[@档位]`)既做「这一类以后都同意」的记账键,也做「同一轮
13
13
  * 重复请求」的比较键,两处必须用同一份,所以只在这里算一遍。
14
14
  *
15
+ * 「以后都同意」的粒度是这里最要紧的一处判断,四条都只认参数本身(`rememberable`):
16
+ * - 删除 / 推送 / 装软件 / 跑第三方包(`isIrreversibleClass`);
17
+ * - 写到**会话工作区之外**(`isWithin`):记 `write:abs` 等于「以后任意路径都能静默改」;
18
+ * - **解析不出内容的壳**:内联执行的代码(`node -e` / `python3 -c`)、带命令替换的 shell;
19
+ * - 只起包装作用的程序先剥掉(`WRAPPERS`),否则记的是 `env` / `timeout` / `xargs` 这类壳。
20
+ *
15
21
  * 详见 docs/dev-map / decisions 里这条改动的原因。
16
22
  */
17
23
 
@@ -24,6 +30,23 @@ const MAX_CLAUSES = 3;
24
30
 
25
31
  /** 删除类程序:高亮。 */
26
32
  const DELETE_PROGS = new Set(['rm', 'rmdir', 'unlink', 'shred']);
33
+ /**
34
+ * 只是把后面那条命令包起来、自己不干活的程序:剥掉再判它包的是什么。
35
+ *
36
+ * 不剥的代价很实在:`env A=1 rm -rf x`、`timeout 60 rm -rf x`、`xargs rm -rf` 的类别键会落成
37
+ * `bash:env` / `bash:timeout` / `bash:xargs`,于是「以后都同意 env」等于「以后任意命令静默放行」。
38
+ */
39
+ const WRAPPERS = new Set(['sudo', 'env', 'nohup', 'nice', 'stdbuf', 'command', 'exec', 'xargs', 'watch', 'time', 'timeout']);
40
+ /** 拿走了第一个参数、其后才是真正命令的那几个(`timeout 60 rm`、`nice -n 10 rm`)。 */
41
+ const WRAPPER_WITH_ARG = new Set(['timeout', 'nice', 'time']);
42
+ /** 包装器的这些选项自带取值:`sudo -u root rm` 里 `root` 是用户名,不是命令。 */
43
+ const OPTS_WITH_VALUE = new Set(['-u', '-g', '-n', '-p', '-C', '-S', '-I', '-L', '-P', '--signal', '--kill-after', '--user', '--group', '-s']);
44
+ /** 跑第三方包的程序:等同于装软件,不给记忆(见 `isIrreversibleClass` 的理由)。 */
45
+ const RUNNER_PROGS = new Set(['npx', 'bunx', 'uvx']);
46
+ /** 内联执行代码的解释器:`node -e …` / `python3 -c …` 看不出来里面干了什么。 */
47
+ const INTERPRETERS = new Set(['node', 'deno', 'bun', 'python', 'python3', 'ruby', 'perl', 'php']);
48
+ /** 记账键里的档位尾巴:只有这两档是真档位,`unknown` 不加(见 `deriveApprovalFacts`)。 */
49
+ const KEY_TIERS = new Set(['workspace-write', 'danger-full-access']);
27
50
  /** 包管理器 → 装包动词集合。 */
28
51
  const PM_INSTALL = {
29
52
  npm: new Set(['install', 'i', 'add']),
@@ -52,12 +75,13 @@ function baseOf(p) {
52
75
  return idx >= 0 ? norm.slice(idx + 1) : norm;
53
76
  }
54
77
 
55
- /** 相对 cwd 的第一段目录;超出 cwd / 取不到就 `abs`。 */
78
+ /** 相对 cwd 的第一段目录;超出 cwd / 取不到就 `abs`。相对路径按 cwd 拼出来再判。 */
56
79
  function dirKeyOf(p, cwd) {
57
80
  if (typeof p !== 'string' || !p) return 'abs';
58
81
  if (typeof cwd !== 'string' || !cwd) return 'abs';
59
- const norm = p.replace(/\\/g, '/');
60
82
  const root = cwd.replace(/\\/g, '/').replace(/\/+$/, '');
83
+ let norm = p.replace(/\\/g, '/');
84
+ if (!/^[A-Za-z]:|^\//.test(norm) && !norm.startsWith('~')) norm = `${root}/${norm}`;
61
85
  if (!norm.startsWith(`${root}/`)) return 'abs';
62
86
  const rel = norm.slice(root.length + 1);
63
87
  const seg = rel.split('/')[0];
@@ -72,6 +96,23 @@ function pathOf(args) {
72
96
  return '';
73
97
  }
74
98
 
99
+ /**
100
+ * 这个落点是不是「会话工作区里面」。
101
+ *
102
+ * 判不准的一律算外面(不给记忆):`~` 开头的路径本函数不展开,相对路径在没有 cwd 时也说不清
103
+ * —— 把说不清的当里面,等于给了一条能静默改到 `~/.zshrc` 的规则。
104
+ */
105
+ function isWithin(p, cwd) {
106
+ if (typeof p !== 'string' || !p) return false;
107
+ if (typeof cwd !== 'string' || !cwd) return false;
108
+ if (p.startsWith('~')) return false;
109
+ const norm = p.replace(/\\/g, '/');
110
+ const root = cwd.replace(/\\/g, '/').replace(/\/+$/, '');
111
+ if (/^[A-Za-z]:|^\//.test(norm)) return norm === root || norm.startsWith(`${root}/`);
112
+ // 相对路径:没写 `..` 就算在工作区里(`../x` 或 `a/../../x` 一律当外面)。
113
+ return !/(^|\/)\.\.(\/|$)/.test(norm);
114
+ }
115
+
75
116
  /** 把一个目标清单收成「a、b 等 N 个」,最多 `MAX_TARGETS` 个。 */
76
117
  function listTargets(names) {
77
118
  const clean = names.map((n) => String(n || '').trim()).filter(Boolean);
@@ -80,7 +121,34 @@ function listTargets(names) {
80
121
  return `${clean.slice(0, MAX_TARGETS).join('、')} 等 ${clean.length} 个`;
81
122
  }
82
123
 
83
- /** 按 `&&` `||` `;` `|` 换行切段,剥 sudo 与 VAR=val 前缀,返回每段的 token 数组。 */
124
+ /**
125
+ * 剥掉只起包装作用的程序(`sudo` / `env` / `timeout 60` / `nohup` / `xargs` …),露出真正干活
126
+ * 的那一条。剥不干净的代价见 `WRAPPERS` 的注释:类别键会落在包装器上,「以后都同意 env」等于
127
+ * 「以后任意命令都静默放行」。认不出来的包装器一律不动,宁可少剥一层。
128
+ */
129
+ function stripWrappers(tokens) {
130
+ let out = tokens;
131
+ for (let guard = 0; guard < 8; guard += 1) {
132
+ if (out.length === 0) return out;
133
+ const prog = baseOf(out[0]);
134
+ if (!WRAPPERS.has(prog)) return out;
135
+ let rest = out.slice(1);
136
+ // 选项连同它的取值一起剥:`sudo -u root cmd`、`nice -n 10 cmd` 里那个词是参数不是命令。
137
+ while (rest.length && rest[0].startsWith('-')) {
138
+ const opt = rest[0];
139
+ rest = rest.slice(1);
140
+ if (OPTS_WITH_VALUE.has(opt) && rest.length) rest = rest.slice(1);
141
+ }
142
+ // `env A=1 cmd`:剥完 `env` 之后还压着一层赋值,继续剥掉。
143
+ while (rest.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(rest[0])) rest = rest.slice(1);
144
+ // `timeout 60 cmd` / `nice 10 cmd`:包装器自己吃掉一个参数,其后才是命令。
145
+ if (WRAPPER_WITH_ARG.has(prog) && rest.length > 1 && /^[\d.]+[smhd]?$/.test(rest[0])) rest = rest.slice(1);
146
+ out = rest;
147
+ }
148
+ return out;
149
+ }
150
+
151
+ /** 按 `&&` `||` `;` `|` 换行切段,剥包装器与 VAR=val 前缀,返回每段的 token 数组。 */
84
152
  function splitSegments(command) {
85
153
  if (typeof command !== 'string') return [];
86
154
  // 先把 sh -c "…" / bash -c "…" 剥一层(常见且便宜)。
@@ -94,12 +162,7 @@ function splitSegments(command) {
94
162
  if (!seg) continue;
95
163
  // 剥段首赋值 VAR=value
96
164
  seg = seg.replace(/^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/, '');
97
- let tokens = seg.split(/\s+/).filter(Boolean);
98
- // 剥 sudo(可能带选项)
99
- while (tokens[0] === 'sudo') {
100
- tokens = tokens.slice(1);
101
- while (tokens.length && tokens[0].startsWith('-')) tokens = tokens.slice(1);
102
- }
165
+ const tokens = stripWrappers(seg.split(/\s+/).filter(Boolean));
103
166
  if (tokens.length === 0) continue;
104
167
  out.push(tokens);
105
168
  }
@@ -178,10 +241,11 @@ function clauseOfSegment(tokens) {
178
241
  return { clause: host ? `连 ${host}` : `跑 ${prog}`, highlight: false, prog };
179
242
  }
180
243
 
181
- // 重定向写文件(段内出现 > 或 >>)
244
+ // 重定向写文件(段内出现 > 或 >>)。写到工作区外与 write 同一口径:句子照旧说,但不给记忆。
182
245
  const redirect = tokens.findIndex((t) => t === '>' || t === '>>');
183
246
  if (redirect >= 0 && tokens[redirect + 1]) {
184
- return { clause: `写 ${baseOf(tokens[redirect + 1])}`, highlight: false, prog };
247
+ const target = unquote(tokens[redirect + 1]);
248
+ return { clause: `写 ${baseOf(target)}`, highlight: false, nowhere: !isWithin(target, opts.cwd), prog };
185
249
  }
186
250
 
187
251
  // 其它程序
@@ -228,7 +292,15 @@ function isOpaque(toolName, args) {
228
292
  return false;
229
293
  }
230
294
 
231
- /** 单次调用 → `{ clause, highlight, classKey }`。 */
295
+ /** 判断一段命令是不是「内联执行代码」:`node -e …` / `python3 -c …` / `<prog> -m …` 之类。 */
296
+ function isInlineCode(tokens) {
297
+ if (!tokens || tokens.length === 0) return false;
298
+ const prog = baseOf(tokens[0] || '');
299
+ if (!INTERPRETERS.has(prog)) return false;
300
+ return tokens.slice(1).some((t) => t === '-e' || t === '--eval' || t === '-c' || t === '-m' || /^-[a-z]*[ecm]$/.test(t));
301
+ }
302
+
303
+ /** 单次调用 → `{ clause, highlight, nowhere, classKey }`。 */
232
304
  function callToPiece(toolName, args) {
233
305
  const name = typeof toolName === 'string' ? toolName : '';
234
306
  if (name === 'bash') {
@@ -238,23 +310,32 @@ function callToPiece(toolName, args) {
238
310
  if (isOpaque(name, args)) {
239
311
  const segs = splitSegments(args.command);
240
312
  const prog = segs.length ? baseOf(segs[0][0] || '') : 'bash';
241
- return { clause: `跑 ${prog}(内容无法静态解析)`, highlight: false, classKey: `bash:${prog}` };
313
+ // 解析不出来的壳不给记忆:`node -e` / `python3 -c` 里面能写任何东西,记成「以后同意 node」
314
+ // 就是「以后任意脚本静默放行」。
315
+ return { clause: `跑 ${prog}(内容无法静态解析)`, highlight: false, nowhere: true, classKey: `bash:${prog}` };
242
316
  }
243
317
  const segs = splitSegments(args.command);
244
318
  const clauses = [];
245
319
  let highlight = false;
320
+ let nowhere = false;
246
321
  for (const tokens of segs) {
322
+ // 段内联执行代码(`python3 -c "…"`):整张卡不给记忆,理由同上面的 `isOpaque`。
323
+ if (isInlineCode(tokens)) nowhere = true;
247
324
  const piece = clauseOfSegment(tokens);
248
325
  if (!piece) continue;
249
326
  if (piece.clause) clauses.push(piece.clause);
250
327
  if (piece.highlight) highlight = true;
328
+ if (piece.nowhere) nowhere = true;
251
329
  }
252
- return { clause: clauses.join(';'), highlight, classKey: bashClassKey(args.command) };
330
+ return { clause: clauses.join(';'), highlight, nowhere, classKey: bashClassKey(args.command) };
253
331
  }
254
332
 
255
333
  if (name === 'write' || name === 'edit') {
256
334
  const p = pathOf(args);
257
335
  if (!p) return { clause: '', highlight: false, classKey: `tool:${name}` };
336
+ // 工作区外一律不给记忆(`nowhere` 只管「能不能记」,不改这一行的颜色):写 `~/.zshrc`、
337
+ // `~/.ssh/authorized_keys`、开机启动项都是这一类,而用户点头时想的是「工作区里改文件」。
338
+ if (!isWithin(p, opts.cwd)) return { clause: `改 ${baseOf(p)}`, highlight: false, nowhere: true, classKey: `${name}:abs` };
258
339
  const d = dirKeyOf(p, opts.cwd);
259
340
  return { clause: `改 ${baseOf(p)}`, highlight: false, classKey: `${name}:${d}` };
260
341
  }
@@ -288,17 +369,18 @@ function callToPiece(toolName, args) {
288
369
 
289
370
  /** 危险度排序,用于多调用聚合时取「最危险那条」做 classKey。 */
290
371
  function dangerRank(classKey) {
291
- if (/^(bash:rm|bash:rmdir|bash:unlink|bash:shred)$/.test(classKey)) return 5;
292
- if (classKey === 'bash:git:push' || classKey === 'bash:git:reset' || classKey === 'bash:git:clean') return 5;
293
- if (INSTALL_MANAGERS.has((classKey.split(':')[1] || '').split(':')[0]) && /install|add|:i$/.test(classKey)) return 4;
294
- if (/^(write|edit):/.test(classKey)) return 3;
295
- if (/^read:/.test(classKey)) return 2;
372
+ const key = String(classKey || '').replace(/@(?:workspace-write|danger-full-access|unknown)$/, '');
373
+ if (/^(bash:rm|bash:rmdir|bash:unlink|bash:shred)$/.test(key)) return 5;
374
+ if (key === 'bash:git:push' || key === 'bash:git:reset' || key === 'bash:git:clean') return 5;
375
+ if (INSTALL_MANAGERS.has((key.split(':')[1] || '').split(':')[0]) && /install|add|:i$/.test(key)) return 4;
376
+ if (/^(write|edit):/.test(key)) return 3;
377
+ if (/^read:/.test(key)) return 2;
296
378
  return 1;
297
379
  }
298
380
 
299
- /** 把 classKey 翻成给人看的一句(撤销页 / 按钮用)。 */
381
+ /** 把 classKey 翻成给人看的一句(撤销页 / 按钮用)。档位尾巴只进键,不进这句人话。 */
300
382
  function labelOf(classKey) {
301
- const parts = String(classKey || '').split(':');
383
+ const parts = String(classKey || '').replace(/@(?:workspace-write|danger-full-access|unknown)$/, '').split(':');
302
384
  const tool = parts[0];
303
385
  if (tool === 'bash') {
304
386
  if (parts[1] === 'git' && parts[2]) {
@@ -338,6 +420,8 @@ function deriveApprovalFacts(calls, options) {
338
420
  const nonEmpty = pieces.filter((p) => p.clause);
339
421
  const joined = nonEmpty.map((p) => p.clause).slice(0, MAX_CLAUSES).join(';');
340
422
  const highlight = pieces.some((p) => p.highlight);
423
+ /** 有一处写到了工作区外 / 是解析不出内容的壳:整张卡不给「以后都同意」。 */
424
+ const nowhere = pieces.some((p) => p.nowhere);
341
425
  let fact = joined;
342
426
  if (fact.length > FACT_MAX) {
343
427
  // 先保数量与动词、再保目标名:若带「等 N 个」,保住这段后缀,只截前面的目标清单。
@@ -358,7 +442,12 @@ function deriveApprovalFacts(calls, options) {
358
442
  }
359
443
  // 高亮是同一份解析给出的第二个信号:删除 / 推送 / reset / clean / 装包只在这几处点亮
360
444
  // (见 `clauseOfSegment`)。组合命令的类别键容易把危险那一段藏进 `a+b`,两条一起看才不漏。
361
- const rememberable = isRememberable(classKey) && !highlight;
445
+ // `nowhere` 是第三个信号:写到了工作区外面(含重定向),那类不给记忆,理由见 `callToPiece`。
446
+ let rememberable = isRememberable(classKey) && !highlight && !nowhere;
447
+ // 档位尾巴:`workspace-write` 与 `danger-full-access` 下的同名动作不是同一条授权 —— 「以后
448
+ // 都同意在工作区里改文件」不该把「升到完全访问」也一起放行。记在键里,换档后重新弹卡;
449
+ // 档位认不出(`unknown`)就不加尾巴,那种键只和同样认不出档位的请求互相匹配。
450
+ if (rememberable && KEY_TIERS.has(opts.tier)) classKey = `${classKey}@${opts.tier}`;
362
451
  return {
363
452
  fact,
364
453
  highlight,
@@ -381,7 +470,8 @@ function deriveApprovalFacts(calls, options) {
381
470
  * 宁可多推一张卡。
382
471
  */
383
472
  function isIrreversibleClass(classKey) {
384
- const key = String(classKey || '');
473
+ // 记账键可能带档位尾巴(`bash:git:push@danger-full-access`),先剥掉再判。
474
+ const key = String(classKey || '').replace(/@(?:workspace-write|danger-full-access|unknown)$/, '');
385
475
  if (!key) return false;
386
476
  // `git rm` 也是删文件(只是经过了 git),`git push/reset/clean` 会动远端或不可恢复。
387
477
  if (key === 'bash:git:push' || key === 'bash:git:reset' || key === 'bash:git:clean' || key === 'bash:git:rm') return true;
@@ -392,6 +482,8 @@ function isIrreversibleClass(classKey) {
392
482
  if (!prog) continue;
393
483
  if (DELETE_PROGS.has(prog)) return true;
394
484
  if (INSTALL_MANAGERS.has(prog) && PM_INSTALL[prog].has(String(verb || '').toLowerCase())) return true;
485
+ // `npx 某个包`:跑的就是刚装下来的第三方包,与装软件同一条理由。
486
+ if (RUNNER_PROGS.has(prog)) return true;
395
487
  }
396
488
  return false;
397
489
  }
@@ -10,7 +10,8 @@
10
10
  * rpcId 找到挂起项把结论交回钩子。
11
11
  *
12
12
  * 钩子必须 prepend:宿主自己的转发器在桌面窗口开着时会一直等桌面回答、不调用 `next()`,
13
- * 老实排在注册顺序后面等于「桌面开着时手机永远收不到」。
13
+ * 老实排在注册顺序后面等于「桌面开着时手机永远收不到」。手机在看时独占审批,最后一条
14
+ * 会话连接离开后将未裁决的请求交给桌面;桌面不可用时仍保留手机作答入口。
14
15
  *
15
16
  * 钩子上没有宿主 id,且与 `approval/asked` 的到达顺序不定,所以两个来源共用一张挂起项表:
16
17
  * 先到的建项,后到的补字段。
@@ -274,8 +275,11 @@ function attachSession(sessionId, sink) {
274
275
  if (entry.bound) { try { sink(cardFrame(entry)); } catch { /* ignore */ } }
275
276
  }
276
277
  return () => {
277
- set.delete(sink);
278
- if (set.size === 0) watchers.delete(sessionId);
278
+ if (!set.delete(sink)) return;
279
+ if (set.size === 0) {
280
+ watchers.delete(sessionId);
281
+ for (const entry of openEntries(sessionId)) entry.forwardToDesktop?.();
282
+ }
279
283
  };
280
284
  }
281
285
 
@@ -721,36 +725,41 @@ function bindRequest(entry, request) {
721
725
  }
722
726
 
723
727
  /**
724
- * 挂起这条请求直到有人给结论。
725
- *
726
- * 传了 `next` 就与下游竞速:`next()` 一调,桌面窗口那张卡照旧出现,谁先给结论谁算数,
727
- * 输的那张卡由结算帧收掉;两边都没人答就一直挂着。
728
- *
729
- * 不传 `next`(手机正在看这个会话)就是手机独家作答:不往下游转发,桌面从源头就不弹卡。
730
- * 独家作答后结论照常走 `approval/decided`,桌面看得到裁决结果。
731
- *
732
- * 唯一兜不住的边角是「审批发出时手机没在看、卡已转发到桌面,之后手机才连上来」:那一发
733
- * 已经转发出去,手机后来答时靠 `cancelForwardedCards` 把它撤掉(见下)。
728
+ * 手机在看时先独占;最后一条连接离开后,将同一审批交给桌面竞速一次。
729
+ * 交接时桌面不可用只表示没人接手,仍等手机回来作答;不改变无人观看时的原有下游结论。
734
730
  */
735
731
  function holdForPhone(entry, next) {
736
- const downstream = next === undefined
737
- ? new Promise(() => {})
738
- : Promise.resolve().then(() => next()).then((outcome) => {
739
- const value = DECISIONS.has(outcome) ? outcome : 'unavailable';
740
- settle(entry, value);
741
- return value;
742
- });
743
- return Promise.race([entry.wait.then((result) => result.outcome), downstream]);
732
+ const handoff = isSessionWatched(entry.sessionId);
733
+ const downstream = new Promise((resolve, reject) => {
734
+ let forwarded = false;
735
+ entry.forwardToDesktop = () => {
736
+ if (forwarded || entry.settled) return;
737
+ forwarded = true;
738
+ Promise.resolve().then(() => {
739
+ if (!entry.settled) return next();
740
+ }).then((outcome) => {
741
+ if (entry.settled) return;
742
+ const value = DECISIONS.has(outcome) ? outcome : 'unavailable';
743
+ if (handoff && value === 'unavailable') return;
744
+ settle(entry, value);
745
+ resolve(value);
746
+ }, (error) => {
747
+ if (entry.settled || (handoff && error?.code === 'NO_PROVIDER')) return;
748
+ reject(error);
749
+ });
750
+ };
751
+ if (!handoff) entry.forwardToDesktop();
752
+ });
753
+ return Promise.race([entry.wait.then((result) => result.outcome), downstream])
754
+ .finally(() => { entry.forwardToDesktop = null; });
744
755
  }
745
756
 
746
757
  /**
747
758
  * 收掉桌面那张审批卡:把宿主已经发给桌面窗口、还挂着的那一发转发撤掉。
748
759
  *
749
- * 手机在看这条会话时审批桥本就不转发,桌面没有卡可收;会走到这里的是那条边角 —— 审批
750
- * 发出时手机没在看、卡已转发到桌面,之后手机才连上来答。那一发只有桌面自己答 / 本轮取消
751
- * / 宿主撤回三条路会消失,本桥替它补上最后一条(与提问桥 2026-10-31 同一手法:把钩子收到
752
- * 的请求对象交给传输层,按它认回网关 `pendingRemoteEvents` 里那一发并撤回)。认不到(老
753
- * 宿主没这道网关)就什么都不做 —— 「桌面没卡可收」本来就是对的。
760
+ * 手机在看时不转发;没有观众或最后一条连接离开后,桌面那一发会与手机作答竞速。手机先答
761
+ * 时按请求对象撤回桌面卡,与提问桥共用传输层的收尾口子。认不到(老宿主没这道网关)就
762
+ * 什么都不做 —— 「桌面没卡可收」本来就是对的。
754
763
  */
755
764
  function cancelForwardedCards(ctx, entry) {
756
765
  if (!entry.requestRef) return;
@@ -806,9 +815,8 @@ async function onApprovalRequest(ctx, request, next) {
806
815
  reason: typeof request.reason === 'string' ? request.reason : undefined,
807
816
  }, { unboundOnly: true });
808
817
  bindRequest(entry, request);
809
- // 手机正在看这个会话就不往下游转发(不传 next):桌面从源头不弹卡,由手机独家作答。
810
- // 没有观众时照旧竞速,纯桌面使用一字不改。
811
- return holdForPhone(entry, isSessionWatched(sessionId) ? undefined : next);
818
+ // 在场时手机先答;最后一条手机连接离开后由 attachSession 交接给桌面。
819
+ return holdForPhone(entry, next);
812
820
  }
813
821
 
814
822
  /**