dsh-mobile-plugin 0.5.34 → 0.5.35

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 (82) hide show
  1. package/lib/impl.js +0 -4
  2. package/lib/mobile/approval-facts.js +0 -13
  3. package/lib/mobile/permissions.js +5 -19
  4. package/lib/mobile/session-send.js +0 -1
  5. package/lib/routes/mobile-api.js +1 -39
  6. package/package.json +1 -2
  7. package/assets/pets/README.md +0 -9
  8. package/assets/pets/deepy-whale/attention.gif +0 -0
  9. package/assets/pets/deepy-whale/done.gif +0 -0
  10. package/assets/pets/deepy-whale/error.gif +0 -0
  11. package/assets/pets/deepy-whale/idle.gif +0 -0
  12. package/assets/pets/deepy-whale/pack.json +0 -54
  13. package/assets/pets/deepy-whale/sleeping.gif +0 -0
  14. package/assets/pets/deepy-whale/working-3.gif +0 -0
  15. package/assets/pets/deepy-whale/working.gif +0 -0
  16. package/knowledge/apps/alipay.md +0 -30
  17. package/knowledge/apps/android-settings.md +0 -30
  18. package/knowledge/apps/baijiahao.md +0 -30
  19. package/knowledge/apps/bilibili.md +0 -31
  20. package/knowledge/apps/boss-zhipin.md +0 -32
  21. package/knowledge/apps/dedao.md +0 -33
  22. package/knowledge/apps/douyin.md +0 -32
  23. package/knowledge/apps/feishu.md +0 -35
  24. package/knowledge/apps/gmail.md +0 -33
  25. package/knowledge/apps/jike.md +0 -31
  26. package/knowledge/apps/kuaishou.md +0 -34
  27. package/knowledge/apps/linkedin.md +0 -33
  28. package/knowledge/apps/qqmail.md +0 -30
  29. package/knowledge/apps/taobao.md +0 -33
  30. package/knowledge/apps/telegram.md +0 -27
  31. package/knowledge/apps/toutiao.md +0 -32
  32. package/knowledge/apps/uber-eats.md +0 -26
  33. package/knowledge/apps/uber.md +0 -27
  34. package/knowledge/apps/wechat.md +0 -33
  35. package/knowledge/apps/weibo.md +0 -31
  36. package/knowledge/apps/whatsapp.md +0 -27
  37. package/knowledge/apps/x.md +0 -32
  38. package/knowledge/apps/xiaohongshu.md +0 -30
  39. package/knowledge/apps/zhihu.md +0 -31
  40. package/knowledge/sites/bilibili.com/SITE.md +0 -50
  41. package/knowledge/sites/bilibili.com/references/view-fields.md +0 -17
  42. package/knowledge/sites/github.com/SITE.md +0 -51
  43. package/knowledge/sites/github.com/references/repo-fields.md +0 -13
  44. package/knowledge/sites/x.com/SITE.md +0 -47
  45. package/knowledge/sites/xiaohongshu.com/SITE.md +0 -48
  46. package/knowledge/sites/xiaohongshu.com/references/note-fields.md +0 -18
  47. package/knowledge/sites/youtube.com/SITE.md +0 -49
  48. package/knowledge/sites/youtube.com/references/innertube-fields.md +0 -14
  49. package/knowledge/sites/zhihu.com/SITE.md +0 -47
  50. package/knowledge/sites/zhihu.com/references/api-fields.md +0 -21
  51. package/lib/mobile/pet-tools.js +0 -261
  52. package/lib/mobile/pets.js +0 -755
  53. package/lib/mobile/phone/access.js +0 -140
  54. package/lib/mobile/phone/binding.js +0 -247
  55. package/lib/mobile/phone/confirm.js +0 -190
  56. package/lib/mobile/phone/evidence.js +0 -228
  57. package/lib/mobile/phone/gate.js +0 -290
  58. package/lib/mobile/phone/grounding.js +0 -314
  59. package/lib/mobile/phone/guard.js +0 -465
  60. package/lib/mobile/phone/guarded.js +0 -86
  61. package/lib/mobile/phone/index.js +0 -114
  62. package/lib/mobile/phone/irreversible.js +0 -226
  63. package/lib/mobile/phone/knowledge-tools.js +0 -665
  64. package/lib/mobile/phone/learn.js +0 -329
  65. package/lib/mobile/phone/pacing.js +0 -173
  66. package/lib/mobile/phone/redact.js +0 -237
  67. package/lib/mobile/phone/risk.js +0 -95
  68. package/lib/mobile/phone/route-extract.js +0 -460
  69. package/lib/mobile/phone/route-hint.js +0 -164
  70. package/lib/mobile/phone/routes-memory.js +0 -133
  71. package/lib/mobile/phone/routes.js +0 -287
  72. package/lib/mobile/phone/service.js +0 -520
  73. package/lib/mobile/phone/site-commands.js +0 -271
  74. package/lib/mobile/phone/skill-recall.js +0 -246
  75. package/lib/mobile/phone/skill-routes.js +0 -106
  76. package/lib/mobile/phone/step-summary.js +0 -201
  77. package/lib/mobile/phone/stop-summary.js +0 -235
  78. package/lib/mobile/phone/tool-groups.js +0 -125
  79. package/lib/mobile/phone/tools.js +0 -2590
  80. package/lib/mobile/phone/untrusted.js +0 -65
  81. package/lib/mobile/phone-knowledge.js +0 -317
  82. package/lib/mobile/route-store.js +0 -266
@@ -1,140 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * 逐 App 访问控制(三档):用户定 AI 能不能碰某个 App —— 放行(allow)/ 每次问(ask)/ 禁止(block)。
5
- *
6
- * 这里是**策略真值**(插件侧、落盘):`mode` 按包名记档,`shareAllowed` 是另一个轴(即便交互被禁,
7
- * 能不能把内容分享进去)。判定由宿主 `tools.js` 读这份真值来 gate 执行;原生只作 block 兜底。
8
- *
9
- * 落盘形状 v2:`{version:2, mode:{pkg:'allow'|'ask'|'block'}, shareAllowed:[...]}`。
10
- * 读到旧的 `{blocked[], shareAllowed[]}` 就地换算(blocked→block,shareAllowed→block 且保留进
11
- * shareAllowed),下次 `update()` 落盘成 v2;没有一次性迁移脚本。未列出的包默认 `ask`。
12
- *
13
- * 能力面:只是本地开关,不扩「能碰什么 App」之外的能力;不涉及 shell/任意文件写。
14
- */
15
-
16
- const fs = require('fs');
17
- const path = require('path');
18
- const os = require('os');
19
-
20
- const MODES = ['allow', 'ask', 'block'];
21
- const DEFAULT_MODE = 'ask';
22
-
23
- function storePath() {
24
- const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
25
- return path.join(home, 'storages', 'mobile-plugin', 'phone-app-access.json');
26
- }
27
-
28
- function emptyState() {
29
- return { version: 2, mode: {}, shareAllowed: [] };
30
- }
31
-
32
- /** 只留下认识的档名;坏值一律当没写。 */
33
- function cleanModes(input) {
34
- const mode = {};
35
- if (input && typeof input === 'object') {
36
- for (const [pkg, value] of Object.entries(input)) {
37
- if (typeof pkg === 'string' && pkg && MODES.includes(value)) mode[pkg] = value;
38
- }
39
- }
40
- return mode;
41
- }
42
-
43
- /** 去重、只留字符串。 */
44
- function cleanList(input) {
45
- if (!Array.isArray(input)) return [];
46
- const out = [];
47
- for (const item of input) {
48
- if (typeof item === 'string' && item && !out.includes(item)) out.push(item);
49
- }
50
- return out;
51
- }
52
-
53
- /** 旧两档存档 → 三档:blocked→block;shareAllowed→block 且保留在 shareAllowed。 */
54
- function migrateLegacy(parsed) {
55
- const mode = {};
56
- const shareAllowed = [];
57
- for (const pkg of cleanList(parsed && parsed.blocked)) mode[pkg] = 'block';
58
- for (const pkg of cleanList(parsed && parsed.shareAllowed)) {
59
- mode[pkg] = 'block';
60
- shareAllowed.push(pkg);
61
- }
62
- return { version: 2, mode, shareAllowed };
63
- }
64
-
65
- function readState() {
66
- let parsed;
67
- try {
68
- parsed = JSON.parse(fs.readFileSync(storePath(), 'utf8'));
69
- } catch {
70
- return emptyState();
71
- }
72
- if (!parsed || typeof parsed !== 'object') return emptyState();
73
- // v2 形状:有 mode 映射就按它读,没有就把旧的 blocked / shareAllowed 换算过来。
74
- if (parsed.mode && typeof parsed.mode === 'object') {
75
- return { version: 2, mode: cleanModes(parsed.mode), shareAllowed: cleanList(parsed.shareAllowed) };
76
- }
77
- return migrateLegacy(parsed);
78
- }
79
-
80
- function writeState(state) {
81
- const file = storePath();
82
- fs.mkdirSync(path.dirname(file), { recursive: true });
83
- const tmp = `${file}.tmp`;
84
- fs.writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
85
- fs.renameSync(tmp, file);
86
- }
87
-
88
- function normalizePackage(value) {
89
- if (typeof value !== 'string') return '';
90
- const pkg = value.trim();
91
- // 包名形状:只允许点分标识符。挡住把路径/命令塞进来的调用。
92
- if (!/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$/.test(pkg)) return '';
93
- return pkg;
94
- }
95
-
96
- /** 一个 App 当前是哪个档;没写过的包回默认档。判定点只读它,别处不再解释档名。 */
97
- function modeFor(state, pkg) {
98
- if (!state || !state.mode || typeof state.mode !== 'object') return DEFAULT_MODE;
99
- const value = state.mode[pkg];
100
- return MODES.includes(value) ? value : DEFAULT_MODE;
101
- }
102
-
103
- /**
104
- * 改一个 App 的档 / 分享例外。只传哪个字段就只改哪个。
105
- * @returns {{ok:boolean, error?:string, modes?:string[], state?:object}}
106
- */
107
- function update(packageName, patch) {
108
- const pkg = normalizePackage(packageName);
109
- if (!pkg) return { ok: false, error: 'bad-package' };
110
- const p = patch && typeof patch === 'object' ? patch : {};
111
- if (p.mode !== undefined && !MODES.includes(p.mode)) {
112
- return { ok: false, error: 'unknown-mode', modes: MODES.slice() };
113
- }
114
- const state = readState();
115
- if (typeof p.mode === 'string') state.mode[pkg] = p.mode;
116
- if (typeof p.shareAllowed === 'boolean') {
117
- const has = state.shareAllowed.includes(pkg);
118
- if (p.shareAllowed === true && !has) state.shareAllowed.push(pkg);
119
- if (p.shareAllowed === false && has) state.shareAllowed.splice(state.shareAllowed.indexOf(pkg), 1);
120
- }
121
- writeState(state);
122
- return { ok: true, state };
123
- }
124
-
125
- /** 行视图:被改过档或进过分享白名单的 App 各一行,带档与分享例外。 */
126
- function rows() {
127
- const state = readState();
128
- const seen = new Set();
129
- const out = [];
130
- const push = (pkg) => {
131
- if (!pkg || seen.has(pkg)) return;
132
- seen.add(pkg);
133
- out.push({ packageName: pkg, mode: modeFor(state, pkg), shareAllowed: state.shareAllowed.includes(pkg) });
134
- };
135
- for (const pkg of Object.keys(state.mode)) push(pkg);
136
- for (const pkg of state.shareAllowed) push(pkg);
137
- return out;
138
- }
139
-
140
- module.exports = { readState, writeState, update, rows, modeFor, normalizePackage, storePath, MODES, DEFAULT_MODE };
@@ -1,247 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * 「这条会话操作哪台手机」的绑定账。
5
- *
6
- * 规则只有一条:**会话第一次收到某台手机发来的消息时,把会话绑到那台手机上**,之后不管
7
- * 用户在 B 手机还是平板上继续聊,都还是操作 A。绑定要落盘 —— 宿主重启、插件热替换之后
8
- * 它还在,否则用户第二天回来会发现任务跑到另一台手机上去了。
9
- *
10
- * 另记一本「最近一次发消息的是谁」。它不进绑定,只用来在两件事上有话可说:
11
- *
12
- * 1. 工具执行时发现「这一轮来自 B、绑着 A」,就把这件事交给模型,让它问一句要不要改绑,
13
- * 而不是闷头操纵 A;
14
- * 2. 没有任何绑定的老会话(这个功能上线之前就存在的对话)第一次要操作手机时,按最近一次
15
- * 发消息的那台算,而不是干等。
16
- *
17
- * 显式改绑走 `setBinding`(模型调 `phone_target`),它只改绑定,不改最近发消息的人 ——
18
- * 后者是事实,改了就成了编。
19
- *
20
- * 两本账都按 sessionId 存,条目上限与已读回执同一量级:会话被删掉时这里不会跟着删
21
- * (宿主不知道),只按最近活动淘汰,留着一条指向已删会话的记录只是几百字节。
22
- */
23
-
24
- const fs = require('node:fs');
25
- const path = require('node:path');
26
- const paths = require('../../shared/paths');
27
-
28
- /** sessionId 与 deviceId 的长度上限(真实值都是 UUID 量级)。 */
29
- const MAX_ID = 200;
30
- /** 条目上限:按 lastAt 保留最新的。 */
31
- const MAX_ENTRIES = 2000;
32
-
33
- /** 文件:`$DSH_HOME/phone-bindings.json`。DSH_HOME 在调用时解析,测试可注入。 */
34
- function stateFile() {
35
- return path.join(paths.dshHome(), 'phone-bindings.json');
36
- }
37
-
38
- /** null = 还没写过;否则 `{ [sessionId]: { bound, boundAt, last, lastAt } }`。 */
39
- let table = null;
40
-
41
- function load() {
42
- if (table) return table;
43
- try {
44
- const raw = JSON.parse(fs.readFileSync(stateFile(), 'utf8'));
45
- table = raw && typeof raw === 'object' && raw.sessions && typeof raw.sessions === 'object'
46
- ? raw.sessions
47
- : {};
48
- } catch {
49
- table = {};
50
- }
51
- return table;
52
- }
53
-
54
- function text(value) {
55
- return typeof value === 'string' ? value.trim().slice(0, MAX_ID) : '';
56
- }
57
-
58
- /** 只留合法形状,并按 lastAt 截断 —— 盘上的文件可能是旧版本或被人手改过。 */
59
- function normalize(entry) {
60
- if (!entry || typeof entry !== 'object') return null;
61
- const bound = text(entry.bound);
62
- const last = text(entry.last);
63
- if (!bound && !last) return null;
64
- const boundAt = Number.isFinite(entry.boundAt) ? entry.boundAt : 0;
65
- const lastAt = Number.isFinite(entry.lastAt) ? entry.lastAt : 0;
66
- return { bound, boundAt, last, lastAt };
67
- }
68
-
69
- function persist() {
70
- const entries = Object.entries(load())
71
- .map(([id, entry]) => [id, normalize(entry)])
72
- .filter(([, entry]) => entry);
73
- if (entries.length > MAX_ENTRIES) {
74
- entries.sort((a, b) => (b[1].lastAt || b[1].boundAt) - (a[1].lastAt || a[1].boundAt));
75
- entries.length = MAX_ENTRIES;
76
- }
77
- const sessions = Object.fromEntries(entries);
78
- try {
79
- fs.mkdirSync(path.dirname(stateFile()), { recursive: true });
80
- const tmp = `${stateFile()}.tmp`;
81
- fs.writeFileSync(tmp, JSON.stringify({ version: 1, sessions }), 'utf8');
82
- fs.renameSync(tmp, stateFile());
83
- } catch {
84
- // 落盘失败不该让一次动作中断:内存里那份仍然是对的,下一次写再试。
85
- }
86
- }
87
-
88
- function entryOf(sessionId) {
89
- const id = text(sessionId);
90
- if (!id) return null;
91
- return normalize(load()[id]);
92
- }
93
-
94
- /** 这条会话绑在哪台手机上;没有绑定时为 null。 */
95
- function boundDeviceOf(sessionId) {
96
- const entry = entryOf(sessionId);
97
- return entry && entry.bound ? entry.bound : null;
98
- }
99
-
100
- /** 最近一次给这条会话发消息的是哪台手机;没有记录时为 null。 */
101
- function lastSenderOf(sessionId) {
102
- const entry = entryOf(sessionId);
103
- return entry && entry.last ? entry.last : null;
104
- }
105
-
106
- /**
107
- * 记一次「这台手机发来了消息」。**同时**在会话还没有绑定时把它绑上去。
108
- *
109
- * 只有 deviceId 非空才动账:没带设备头的调用(桌面端、测试、老客户端)不该把一条已经绑好
110
- * 的会话改成「未绑定」,也不该把新会话绑到一台认不出的设备上。
111
- *
112
- * @returns {{bound: string, changed: boolean}} changed 表示这一次真的建立了绑定
113
- */
114
- function noteSender(sessionId, deviceId, now = Date.now()) {
115
- const id = text(sessionId);
116
- const device = text(deviceId);
117
- const current = entryOf(id);
118
- if (!id || !device) return { bound: current ? current.bound : '', changed: false };
119
- const entry = current || { bound: '', boundAt: 0, last: '', lastAt: 0 };
120
- const changed = !entry.bound;
121
- if (changed) {
122
- entry.bound = device;
123
- entry.boundAt = now;
124
- }
125
- entry.last = device;
126
- entry.lastAt = now;
127
- load()[id] = entry;
128
- persist();
129
- return { bound: entry.bound, changed };
130
- }
131
-
132
- /**
133
- * 显式改绑(模型调 `phone_target`)。只改 bound,`last` 原样留着。
134
- *
135
- * @returns {boolean} 有没有真的写下去(空 deviceId 一律拒)
136
- */
137
- function setBinding(sessionId, deviceId, now = Date.now()) {
138
- const id = text(sessionId);
139
- const device = text(deviceId);
140
- if (!id || !device) return false;
141
- const entry = entryOf(id) || { bound: '', boundAt: 0, last: '', lastAt: 0 };
142
- entry.bound = device;
143
- entry.boundAt = now;
144
- if (!entry.lastAt) entry.lastAt = now;
145
- load()[id] = entry;
146
- persist();
147
- return true;
148
- }
149
-
150
- /**
151
- * 从一次请求里认出「发消息的是哪台手机」,记进账。
152
- *
153
- * 挂在**发送成功之后**:发失败的那一发什么都没发生,拿它当「用户在这台手机上说话」会让一条
154
- * 会话被一条没送达的消息绑到某台机器上。没带设备头的调用(桌面端、老客户端、测试)落在
155
- * `legacy`,那不是任何一台手机,一律不记 —— 记了就会把已经绑好的账改成别的。
156
- *
157
- * 失败绝不影响调用方:绑定只是「下次操作哪台手机」的默认值,记账出错不该让一条已经交出去的
158
- * 消息报失败。
159
- */
160
- function noteRequestSender(req, sessionId) {
161
- try {
162
- const raw = req && req.headers ? req.headers['x-dsh-device'] : undefined;
163
- const deviceId = text(Array.isArray(raw) ? raw[0] : raw);
164
- if (!deviceId) return;
165
- noteSender(sessionId, deviceId);
166
- } catch { /* 绑定账写不进去不影响这一发 */ }
167
- }
168
-
169
- /**
170
- * 某台手机不再被操作时(用户解除配对),把**指向它**的绑定一条条清掉。
171
- *
172
- * 只清 `bound` 指向它的那些;`last` 也指向它的不动 —— 那是「谁发过消息」的事实,不该因为
173
- * 解绑就变成另一台。清掉之后这条会话回到「没有绑定」,下一次发消息的设备会重新绑上。
174
- *
175
- * @returns {number} 清了几条
176
- */
177
- function clearBindingForDevice(deviceId, now = Date.now()) {
178
- const device = text(deviceId);
179
- if (!device) return 0;
180
- const state = load();
181
- let removed = 0;
182
- for (const [id, entry] of Object.entries(state)) {
183
- const normalized = normalize(entry);
184
- if (!normalized || normalized.bound !== device) continue;
185
- normalized.bound = '';
186
- normalized.boundAt = 0;
187
- if (!normalized.last) { delete state[id]; continue; }
188
- normalized.lastAt = normalized.lastAt || now;
189
- state[id] = normalized;
190
- removed += 1;
191
- }
192
- if (removed) persist();
193
- return removed;
194
- }
195
-
196
- /** 会话被删 / 用户主动解绑时清掉。 */
197
- function clearBinding(sessionId) {
198
- const id = text(sessionId);
199
- if (!id) return false;
200
- const state = load();
201
- if (!(id in state)) return false;
202
- delete state[id];
203
- persist();
204
- return true;
205
- }
206
-
207
- /**
208
- * 这一次要操作哪台手机。
209
- *
210
- * 顺序:显式 target(调用方本次传入)→ 绑定 → 最近一次发消息的那台。三者都没有就是
211
- * `null` —— 调用方必须把这当成「没有目标」报出来,**不许**拿「随便挑一台在线的」顶上:
212
- * 那会让一条对话在用户不知情时去操作另一台手机。
213
- *
214
- * @returns {{deviceId: string, from: 'explicit'|'bound'|'sender'|'', changed: boolean}}
215
- */
216
- function resolveTarget(sessionId, explicit) {
217
- const wanted = text(explicit);
218
- if (wanted) {
219
- const current = boundDeviceOf(sessionId);
220
- const changed = current !== wanted;
221
- if (changed) setBinding(sessionId, wanted);
222
- return { deviceId: wanted, from: 'explicit', changed };
223
- }
224
- const bound = boundDeviceOf(sessionId);
225
- if (bound) return { deviceId: bound, from: 'bound', changed: false };
226
- const sender = lastSenderOf(sessionId);
227
- if (sender) return { deviceId: sender, from: 'sender', changed: true };
228
- return { deviceId: '', from: '', changed: false };
229
- }
230
-
231
- /** 测试用:丢掉内存里那份(下一个用例重新从盘上读)。 */
232
- function resetForTest() {
233
- table = null;
234
- }
235
-
236
- module.exports = {
237
- stateFile,
238
- boundDeviceOf,
239
- lastSenderOf,
240
- noteSender,
241
- noteRequestSender,
242
- setBinding,
243
- clearBinding,
244
- clearBindingForDevice,
245
- resolveTarget,
246
- resetForTest,
247
- };
@@ -1,190 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * 付款确认:把「这一下点下去要花钱」送去宿主已有的审批通道,等人点了「同意」再放行。
5
- *
6
- * ## 为什么复用审批通道,而不是自己推一张卡
7
- *
8
- * 手机上那张确认卡、用户点按钮、结论交回来,这条链在 0.2.x 上已经由审批桥
9
- * (`mobile/approvals.js`)铺好了:它 `prepend` 了宿主的 `approval/request` 钩子,钩子一响
10
- * 就把卡推给正在看这条会话的手机,用户点了同意再 `settle` 回钩子的 promise。我们自己再造
11
- * 一条推卡的路,等于让手机上同时存在两套确认卡、两套回答接口,谁先答都说不清。
12
- *
13
- * 所以这里只做一件事:以 `ctx.get('approval')` 的身份发起一次真正的审批请求。宿主的
14
- * `ApprovalService.request()` 会把这次的 `approval/asked` / `approval/decided` 记进会话日志
15
- * (审计里就是这么写的),再走一遍 `approval/request` waterfall —— 审批桥在那一步把卡交给
16
- * 手机。拿回 `allowed-once` 才等于「用户就这一下点了同意」。
17
- *
18
- * ## 为什么绝对不会挂死
19
- *
20
- * 三处都可能「永远没人答」:手机没在看(卡没有去处)、用户在别处把这一轮取消了、钩子上
21
- * 下游是个不回答的转发器。前两处各自有出路(下面判 unavailable / 跟着 signal 取消),
22
- * 第三处靠一道自己的硬期限兜底:到点就回 `unavailable`,且先 `abort()` 让宿主那头把
23
- * 挂起的审批一起收掉。工具调用挂在这里,模型的整轮就会一直转下去 —— 那比「没确认」
24
- * 严重得多,所以宁可超时也不要等。
25
- *
26
- * ## 三个返回值
27
- *
28
- * `allowed-once`(就这一次可以) / `rejected`(问过了,答案是拒绝或取消) /
29
- * `unavailable`(压根没能问到人)。调用点只认 `allowed-once`,别的一律不执行。
30
- */
31
-
32
- /**
33
- * 一次确认最多等多久。
34
- *
35
- * 够用户拿起手机看一眼再点同意,又不至于让模型的这一发停在那里。之所以不设「等到有人答
36
- * 为止」:卡没推到人手上(手机没在看这条会话、用户把 App 切走了)时,等的是一个永远不来
37
- * 的答案;而一次工具调用挂着一分钟以上,在模型那边就是「卡住了」。
38
- */
39
- const APPROVAL_TIMEOUT_MS = 90_000;
40
-
41
- /**
42
- * 这一步要不要人确认。判定仍由 `irreversible.js` 给,这里只挑「收钱」与「毁数据」两类:
43
- * payment(付款 / 下单 / 购买 / 结算)和 delete(删除 / 清空 / 移除)强制走一次人工确认。
44
- * 发送、提交是这条任务本来就该做的事,每一步都拦会让「让它发条消息」变成一连串确认框,
45
- * 所以维持「不逐条拦」的既有取舍 —— 这是刻意的,别把 send / submit 也扩进来。
46
- */
47
- function needsConfirmation(judged) {
48
- return Boolean(judged && judged.irreversible === true && (judged.kind === 'payment' || judged.kind === 'delete'));
49
- }
50
-
51
- /**
52
- * 宿主的审批服务。`ctx.get()` 而不是写进 inject:这个服务的装配顺序跟手机那几条路由无关,
53
- * 注入一个当前宿主版本里没有的服务会把整个插件装载拖垮(与 `mobile/host-web.js` 同一口径)。
54
- */
55
- function approvalOf(ctx) {
56
- if (!ctx) return null;
57
- try {
58
- if (typeof ctx.get === 'function') {
59
- const service = ctx.get('approval');
60
- if (service && typeof service.request === 'function') return service;
61
- }
62
- } catch { /* 服务没装就往下试属性那一种写法 */ }
63
- const direct = ctx.approval;
64
- return direct && typeof direct.request === 'function' ? direct : null;
65
- }
66
-
67
- /**
68
- * 这条会话的 agent。审批请求要求请求方带着自己的会话(`ApprovalService.request()` 要往
69
- * 那条会话里记审计事件,还要看它的 `approval/policy`),拿不到就等于没人能答。
70
- *
71
- * 工具层手上一般已经握着这次调用的 agent,优先用它 —— 比按 id 去服务里捞更准,
72
- * 子代理那条路径上 `agents.get(childSessionId)` 本来就取不到。
73
- */
74
- function agentOf(ctx, sessionId, hint) {
75
- if (hint && hint.session) return hint;
76
- if (!ctx || typeof ctx.get !== 'function' || !sessionId) return null;
77
- try {
78
- const agents = ctx.get('agents');
79
- if (agents && typeof agents.get === 'function') return agents.get(sessionId) || null;
80
- } catch { /* 没这个服务就没有别的路可走 */ }
81
- return null;
82
- }
83
-
84
- /** 卡片上那句话:做了什么都写进去,用户看着手机就能判断这一下该不该点。 */
85
- function summaryText(summary, amountText) {
86
- const parts = [];
87
- const head = typeof summary === 'string' ? summary.trim().slice(0, 200) : '';
88
- const amount = typeof amountText === 'string' ? amountText.trim().slice(0, 60) : '';
89
- if (head) parts.push(head);
90
- if (amount) parts.push(`金额 ${amount}`);
91
- return parts.join(';') || '操作手机:这一步涉及付款 / 下单,需要你确认';
92
- }
93
-
94
- /** 宿主那套结论词表收成一个三选一。取消与拒绝对调用点是一回事:都别执行。 */
95
- function normalizeOutcome(outcome) {
96
- if (outcome === 'allowed-once') return 'allowed-once';
97
- if (outcome === 'rejected' || outcome === 'cancelled') return 'rejected';
98
- return 'unavailable';
99
- }
100
-
101
- /**
102
- * 发起一次确认并等结论。
103
- *
104
- * @param {object} ctx 插件上下文(要能 `get('approval')`)
105
- * @param {object} options
106
- * @param {string} options.sessionId 这条对话
107
- * @param {string} [options.summary] 卡片摘要:这一步在做什么
108
- * @param {string} [options.amountText] 金额一类的字样,有就一起上卡
109
- * @param {object} [options.agent] 工具层手上这次调用的 agent(有就用,没有按会话捞)
110
- * @param {string} [options.toolName] 卡片上那个「工具 X」的名字
111
- * @param {string} [options.callId] 与这一步的工具调用对上,便于手机与桌面对同一张卡
112
- * @param {AbortSignal} [options.signal] 这一轮工具的取消信号(用户取消整轮时跟着结束)
113
- * @param {boolean} [options.watching] 有没有手机在看着这条会话;明确为 false 就不必问了
114
- * @param {number} [options.timeoutMs] 覆盖默认期限:调用方自己的预算比三分钟还短时用它,
115
- * 确认不该比整条调用活得久
116
- * @returns {Promise<'allowed-once'|'rejected'|'unavailable'>}
117
- */
118
- async function requestConfirmation(ctx, options) {
119
- const opts = options && typeof options === 'object' ? options : {};
120
- const sessionId = typeof opts.sessionId === 'string' ? opts.sessionId.trim() : '';
121
- // 认不出是哪条对话:卡片没有归属,宿主也会因为「没有开着的轮次」拒绝记账。
122
- if (!sessionId) return 'unavailable';
123
- // 没有手机在看:卡推不出去,问也白问。如实说「没问到」,别把这一步挂在那儿。
124
- if (opts.watching === false) return 'unavailable';
125
-
126
- const approval = approvalOf(ctx);
127
- if (!approval) return 'unavailable';
128
- const agent = agentOf(ctx, sessionId, opts.agent);
129
- if (!agent || !agent.session) return 'unavailable';
130
-
131
- const reason = summaryText(opts.summary, opts.amountText);
132
- const controller = new AbortController();
133
- const parent = opts.signal;
134
- const onAbort = () => controller.abort();
135
- if (parent && typeof parent.addEventListener === 'function') {
136
- // 工具已经被取消了就别再发一张卡出来:那一轮已经没有人在等这个答案。
137
- if (parent.aborted) return 'unavailable';
138
- parent.addEventListener('abort', onAbort, { once: true });
139
- }
140
-
141
- const waitMs = Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0
142
- ? Math.min(APPROVAL_TIMEOUT_MS, Math.round(opts.timeoutMs))
143
- : APPROVAL_TIMEOUT_MS;
144
- let timer = null;
145
- // 硬期限与请求本身赛跑:即便宿主那头不理会 abort,这里也一定在期限内交出结论。
146
- const deadline = new Promise((resolve) => {
147
- timer = setTimeout(() => {
148
- controller.abort();
149
- resolve('unavailable');
150
- }, waitMs);
151
- if (typeof timer.unref === 'function') timer.unref();
152
- });
153
-
154
- try {
155
- const asked = Promise.resolve()
156
- .then(() => approval.request({
157
- agent,
158
- ...(typeof opts.toolName === 'string' && opts.toolName ? { toolName: opts.toolName } : {}),
159
- ...(typeof opts.callId === 'string' && opts.callId ? { callId: opts.callId } : {}),
160
- reason,
161
- // 桌面与手机上的卡片都优先用这句(审批桥的 `displayReasonOf` 认 zh)。
162
- displayReason: { zh: reason },
163
- signal: controller.signal,
164
- }))
165
- // 宿主在「没有开着的轮次」「策略是 never」这些情况下会抛,一律折算成没问到。
166
- .then((outcome) => normalizeOutcome(outcome), () => 'unavailable');
167
- return await Promise.race([asked, deadline]);
168
- } catch {
169
- return 'unavailable';
170
- } finally {
171
- if (timer) clearTimeout(timer);
172
- if (parent && typeof parent.removeEventListener === 'function') parent.removeEventListener('abort', onAbort);
173
- }
174
- }
175
-
176
- /** 确认没拿到时给模型的那句话。两种没拿到的原因要分开说,模型据此决定要不要请用户回来。 */
177
- function blockedMessage(outcome, what) {
178
- const step = typeof what === 'string' && what ? what : '这一步';
179
- if (outcome === 'rejected') {
180
- return `${step}是需要确认的不可逆动作(付款 / 下单 / 删除),需要用户确认;用户没有同意(或者这一轮被取消了),所以没有执行。把这件事如实告诉用户,别自己重试。`;
181
- }
182
- return `${step}是需要确认的不可逆动作(付款 / 下单 / 删除),需要用户确认,但刚才没能把确认卡送到用户手上(手机没有在看这条对话,或者确认通道不可用),所以没有执行。请用户回到这条对话、在手机上看着屏幕再试一次;也可以让用户自己点这一下。`;
183
- }
184
-
185
- module.exports = {
186
- needsConfirmation,
187
- requestConfirmation,
188
- blockedMessage,
189
- APPROVAL_TIMEOUT_MS,
190
- };