dsh-mobile-plugin 0.5.34 → 0.5.36
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/impl.js +0 -11
- package/lib/mobile/answer-sources.js +223 -0
- package/lib/mobile/approval-facts.js +0 -13
- package/lib/mobile/approval-memory.js +1 -1
- package/lib/mobile/events.js +0 -20
- package/lib/mobile/extension-data.js +105 -5
- package/lib/mobile/history-derive.js +54 -1
- package/lib/mobile/notification-prefs.js +2 -2
- package/lib/mobile/permissions.js +13 -24
- package/lib/mobile/plugin-market.js +103 -4
- package/lib/mobile/run-timeline.js +317 -0
- package/lib/mobile/session-send.js +0 -1
- package/lib/mobile/session-stop-summary.js +122 -0
- package/lib/mobile/stats-ledger.cjs +45 -0
- package/lib/mobile/stop-summary.js +146 -0
- package/lib/mobile/third-party-extensions.js +86 -0
- package/lib/mobile/tool-result-cache.js +30 -2
- package/lib/panel/index.html +15 -15
- package/lib/relay/lan-proxy.js +20 -11
- package/lib/relay/tunnel.js +28 -12
- package/lib/routes/mobile-api.js +26 -58
- package/lib/shared/derived-cache.js +121 -0
- package/lib/shared/http-util.js +55 -18
- package/package.json +1 -3
- package/assets/pets/README.md +0 -9
- package/assets/pets/deepy-whale/attention.gif +0 -0
- package/assets/pets/deepy-whale/done.gif +0 -0
- package/assets/pets/deepy-whale/error.gif +0 -0
- package/assets/pets/deepy-whale/idle.gif +0 -0
- package/assets/pets/deepy-whale/pack.json +0 -54
- package/assets/pets/deepy-whale/sleeping.gif +0 -0
- package/assets/pets/deepy-whale/working-3.gif +0 -0
- package/assets/pets/deepy-whale/working.gif +0 -0
- package/config/agent-presets/supervisor/agent.cordis.yml +0 -237
- package/config/agent-presets/supervisor/preset.yml +0 -3
- package/knowledge/apps/alipay.md +0 -30
- package/knowledge/apps/android-settings.md +0 -30
- package/knowledge/apps/baijiahao.md +0 -30
- package/knowledge/apps/bilibili.md +0 -31
- package/knowledge/apps/boss-zhipin.md +0 -32
- package/knowledge/apps/dedao.md +0 -33
- package/knowledge/apps/douyin.md +0 -32
- package/knowledge/apps/feishu.md +0 -35
- package/knowledge/apps/gmail.md +0 -33
- package/knowledge/apps/jike.md +0 -31
- package/knowledge/apps/kuaishou.md +0 -34
- package/knowledge/apps/linkedin.md +0 -33
- package/knowledge/apps/qqmail.md +0 -30
- package/knowledge/apps/taobao.md +0 -33
- package/knowledge/apps/telegram.md +0 -27
- package/knowledge/apps/toutiao.md +0 -32
- package/knowledge/apps/uber-eats.md +0 -26
- package/knowledge/apps/uber.md +0 -27
- package/knowledge/apps/wechat.md +0 -33
- package/knowledge/apps/weibo.md +0 -31
- package/knowledge/apps/whatsapp.md +0 -27
- package/knowledge/apps/x.md +0 -32
- package/knowledge/apps/xiaohongshu.md +0 -30
- package/knowledge/apps/zhihu.md +0 -31
- package/knowledge/sites/bilibili.com/SITE.md +0 -50
- package/knowledge/sites/bilibili.com/references/view-fields.md +0 -17
- package/knowledge/sites/github.com/SITE.md +0 -51
- package/knowledge/sites/github.com/references/repo-fields.md +0 -13
- package/knowledge/sites/x.com/SITE.md +0 -47
- package/knowledge/sites/xiaohongshu.com/SITE.md +0 -48
- package/knowledge/sites/xiaohongshu.com/references/note-fields.md +0 -18
- package/knowledge/sites/youtube.com/SITE.md +0 -49
- package/knowledge/sites/youtube.com/references/innertube-fields.md +0 -14
- package/knowledge/sites/zhihu.com/SITE.md +0 -47
- package/knowledge/sites/zhihu.com/references/api-fields.md +0 -21
- package/lib/mobile/auto-review-log.js +0 -160
- package/lib/mobile/knowledge-base.js +0 -481
- package/lib/mobile/mail.js +0 -621
- package/lib/mobile/pet-tools.js +0 -261
- package/lib/mobile/pets.js +0 -755
- package/lib/mobile/phone/access.js +0 -140
- package/lib/mobile/phone/binding.js +0 -247
- package/lib/mobile/phone/confirm.js +0 -190
- package/lib/mobile/phone/evidence.js +0 -228
- package/lib/mobile/phone/gate.js +0 -290
- package/lib/mobile/phone/grounding.js +0 -314
- package/lib/mobile/phone/guard.js +0 -465
- package/lib/mobile/phone/guarded.js +0 -86
- package/lib/mobile/phone/index.js +0 -114
- package/lib/mobile/phone/irreversible.js +0 -226
- package/lib/mobile/phone/knowledge-tools.js +0 -665
- package/lib/mobile/phone/learn.js +0 -329
- package/lib/mobile/phone/pacing.js +0 -173
- package/lib/mobile/phone/redact.js +0 -237
- package/lib/mobile/phone/risk.js +0 -95
- package/lib/mobile/phone/route-extract.js +0 -460
- package/lib/mobile/phone/route-hint.js +0 -164
- package/lib/mobile/phone/routes-memory.js +0 -133
- package/lib/mobile/phone/routes.js +0 -287
- package/lib/mobile/phone/service.js +0 -520
- package/lib/mobile/phone/site-commands.js +0 -271
- package/lib/mobile/phone/skill-recall.js +0 -246
- package/lib/mobile/phone/skill-routes.js +0 -106
- package/lib/mobile/phone/step-summary.js +0 -201
- package/lib/mobile/phone/stop-summary.js +0 -235
- package/lib/mobile/phone/tool-groups.js +0 -125
- package/lib/mobile/phone/tools.js +0 -2590
- package/lib/mobile/phone/untrusted.js +0 -65
- package/lib/mobile/phone-knowledge.js +0 -317
- package/lib/mobile/route-store.js +0 -266
- package/lib/mobile/supervisor-broadcast.js +0 -503
- package/lib/mobile/supervisor-memory/index.js +0 -305
- package/lib/mobile/supervisor-runtime/index.js +0 -54
- package/lib/mobile/supervisor-runtime/inject.js +0 -218
- package/lib/mobile/supervisor-runtime/judgment.js +0 -113
- package/lib/mobile/supervisor-tools.js +0 -419
- package/lib/mobile/task-ledger.js +0 -381
|
@@ -1,2590 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* 给模型的那组手机动作。
|
|
5
|
-
*
|
|
6
|
-
* ## 能力面的边界
|
|
7
|
-
*
|
|
8
|
-
* 这里面**没有**「执行命令」。模型能说的是「看这块屏」「点第 7 个元素」「输入这段字」
|
|
9
|
-
* 「往上滑一屏」「返回」「打开这个 App」,参数全是结构化字段、全部经过校验;没有任何一格
|
|
10
|
-
* 能拼出一段 shell。手机侧认的动作表与这里一一对应(见 `phone/service.js` 的 `ACTIONS`),
|
|
11
|
-
* 多一个动作就是两边同时扩一次能力面。
|
|
12
|
-
*
|
|
13
|
-
* ## 为什么每个工具都要先问一次「操作哪台手机」
|
|
14
|
-
*
|
|
15
|
-
* 一台电脑可以连好几台手机,而一条会话可能在任意一台手机上被打开。目标由 `phone/binding`
|
|
16
|
-
* 决定(会话第一次收到谁的消息就绑谁),模型的参数里**没有** deviceId —— 它不该、也没法
|
|
17
|
-
* 自己挑一台机器。要换,就走 `phone_target`:那是显式的、用户看得见的一次改绑。
|
|
18
|
-
*
|
|
19
|
-
* ## 报错口径
|
|
20
|
-
*
|
|
21
|
-
* 目标不存在、那台手机断开、动作超时,都抛成工具失败 —— 消息写得像人话,模型据此改主意
|
|
22
|
-
* 或者问用户,而不是重试同一发。**绝不**在目标不可用时偷偷换一台在线的顶上。
|
|
23
|
-
*/
|
|
24
|
-
|
|
25
|
-
const binding = require('./binding.js');
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* 本轮并行加的三个邻居:不可逆判定、节奏、App 知识库。
|
|
29
|
-
*
|
|
30
|
-
* 它们各自是别人的一次提交,可能还没合并进来。这里一律按「拿得到就用、拿不到就当没有」,
|
|
31
|
-
* 因为少一层提示 / 少一段停留都不该让工具的整条注册失败 —— 那会把八个旧工具也一起拖没。
|
|
32
|
-
*/
|
|
33
|
-
let irreversible = null;
|
|
34
|
-
try { irreversible = require('./irreversible.js'); } catch { irreversible = null; }
|
|
35
|
-
let pacing = null;
|
|
36
|
-
try { pacing = require('./pacing.js'); } catch { pacing = null; }
|
|
37
|
-
let phoneKnowledge = null;
|
|
38
|
-
try { phoneKnowledge = require('../phone-knowledge.js'); } catch { phoneKnowledge = null; }
|
|
39
|
-
// 付款确认:走宿主审批通道的那条路。它拿不到审批服务 / 会话时一律回 unavailable,
|
|
40
|
-
// 所以这里直接 require 也没关系 —— 确认要不到只会让「付款那一步不执行」,不会挂住工具。
|
|
41
|
-
const confirm = require('./confirm.js');
|
|
42
|
-
// 「教一次就学会」:批跑成之后把这一批抽成可重放路线,存进技能目录的待收下草稿。
|
|
43
|
-
// 抽不出来(含付款、有只靠坐标认的步、脱敏失败)就什么都不写 —— 学歪一条比不学更糟。
|
|
44
|
-
const routeExtract = require('./route-extract.js');
|
|
45
|
-
let routeStore = null;
|
|
46
|
-
try { routeStore = require('../route-store.js'); } catch { routeStore = null; }
|
|
47
|
-
// 逐 App 三档授权:真值落盘在插件侧,这里读它来决定某个动作能不能对当前 App 下手。
|
|
48
|
-
const access = require('./access.js');
|
|
49
|
-
|
|
50
|
-
/** 元素的短标签:模型看到的是「第几个」,不是像素坐标。 */
|
|
51
|
-
const MAX_TEXT = 120;
|
|
52
|
-
|
|
53
|
-
/* ── 守卫账 ─────────────────────────────────────────────────────────────── */
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* 每个插件上下文一份:一轮里 phone_* 的调用次数、同一个 ref 的连点、同一屏的连读、同一批的失败。
|
|
57
|
-
* 按 ctx 隔离,热替换之后旧账不会串到新实例上。
|
|
58
|
-
*/
|
|
59
|
-
const guardStates = new WeakMap();
|
|
60
|
-
|
|
61
|
-
function guardStateFor(ctx) {
|
|
62
|
-
let state = guardStates.get(ctx);
|
|
63
|
-
if (!state) {
|
|
64
|
-
state = {
|
|
65
|
-
budget: new Map(), taps: new Map(), screens: new Map(), batches: new Map(),
|
|
66
|
-
autoShot: new Map(), revisions: new Map(),
|
|
67
|
-
// 上一次读屏的元素表:stale-ref 重试要按「旧文字 + 旧位置」把同一个元素认回来,
|
|
68
|
-
// 没有这一份就只能靠序号猜。只留最近一屏,一条会话一份。
|
|
69
|
-
lastElements: new Map(),
|
|
70
|
-
// 每条会话最近一次动作 / 读屏回报的前台包名:按 App 授权要知道「现在动的是谁」。
|
|
71
|
-
lastPackage: new Map(),
|
|
72
|
-
// 本轮已授权的 App 集合:键是 `${turnKey}:${sessionId}`,轮次变即换新键(等于清空),
|
|
73
|
-
// 与 budgetEntry 的轮次口径一致。
|
|
74
|
-
appAllowed: new Map(),
|
|
75
|
-
};
|
|
76
|
-
guardStates.set(ctx, state);
|
|
77
|
-
}
|
|
78
|
-
return state;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/** 一轮里允许调用 phone_* 的次数:到了软上限就催收尾,越过硬上限直接拒。 */
|
|
82
|
-
const CALL_SOFT_LIMIT = 60;
|
|
83
|
-
const CALL_HARD_LIMIT = 90;
|
|
84
|
-
/**
|
|
85
|
-
* 一轮里工具结果累计的字节数:超过软线提醒收尾,越过硬线直接拒。
|
|
86
|
-
*
|
|
87
|
-
* 次数拦得住「调用很密」,拦不住「读得很肥」:一次 `phone_steps` 回来两百个元素、
|
|
88
|
-
* 再带一整段知识正文,几轮下来上下文就被界面文字占满了。体积按序列化后的 JSON 估,
|
|
89
|
-
* 不追求精确 —— 目的是拦住「反复读整屏」这种浪费,而不是量到字节。
|
|
90
|
-
*/
|
|
91
|
-
const BYTES_SOFT_LIMIT = 400 * 1024;
|
|
92
|
-
const BYTES_HARD_LIMIT = 800 * 1024;
|
|
93
|
-
/** 拿不到轮次号时,靠「多久没动过」兜底清账,免得同一会话把上限永远吃满。 */
|
|
94
|
-
const IDLE_RESET_MS = 10 * 60 * 1000;
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* 这一发属于会话的哪一轮。
|
|
98
|
-
*
|
|
99
|
-
* 复用直播过程那套轮次口径:`turn/start` 会把当前 turn 号写进 liveSteps 桶,工具执行时读得到。
|
|
100
|
-
* 读不到就退到一个固定键,再由「空闲超时」负责清账(宁可多给几次,也别把还在干活的一轮提前掐死)。
|
|
101
|
-
*/
|
|
102
|
-
function turnKeyOf(ctx, sessionId) {
|
|
103
|
-
try {
|
|
104
|
-
const { liveStepsTurnOf } = require('../live-steps.js');
|
|
105
|
-
const turn = liveStepsTurnOf(ctx, sessionId);
|
|
106
|
-
if (typeof turn === 'number') return `t${turn}`;
|
|
107
|
-
} catch { /* 没有直播模块就走兜底 */ }
|
|
108
|
-
return 'u';
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* 这一轮的那本账:次数与体积记在同一条目里。
|
|
113
|
-
*
|
|
114
|
-
* 两笔账共用一条记录、共用同一次重置(轮次变了就一起清零),因为「这一轮」是同一个概念 ——
|
|
115
|
-
* 分成两个 Map 就得写两遍重置条件,早晚有一边忘了清,于是体积账在新的一轮里还挂着旧数,
|
|
116
|
-
* 第一次读屏就被判超限。
|
|
117
|
-
*/
|
|
118
|
-
function budgetEntry(ctx, sessionId) {
|
|
119
|
-
const state = guardStateFor(ctx);
|
|
120
|
-
const now = Date.now();
|
|
121
|
-
const key = turnKeyOf(ctx, sessionId);
|
|
122
|
-
let entry = state.budget.get(sessionId);
|
|
123
|
-
if (!entry || entry.turnKey !== key || (key === 'u' && now - entry.at > IDLE_RESET_MS)) {
|
|
124
|
-
entry = { turnKey: key, count: 0, bytes: 0, at: now };
|
|
125
|
-
state.budget.set(sessionId, entry);
|
|
126
|
-
}
|
|
127
|
-
entry.at = now;
|
|
128
|
-
return entry;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/** 记一次调用并判断是否该拦。返回值里的 count 供软提醒用,bytes 是上一发为止的累计体积。 */
|
|
132
|
-
function checkBudget(ctx, sessionId) {
|
|
133
|
-
const entry = budgetEntry(ctx, sessionId);
|
|
134
|
-
const bytes = entry.bytes;
|
|
135
|
-
entry.count += 1;
|
|
136
|
-
return { blocked: entry.count > CALL_HARD_LIMIT, count: entry.count, bytes };
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
/**
|
|
140
|
-
* 记一发结果的体积,并判断越过了哪条线。
|
|
141
|
-
*
|
|
142
|
-
* 在结果**定稿之后**才记账:工具把自己的 note 补完、把知识附进去之后那份才是真交给模型的
|
|
143
|
-
* 那一段。硬线在下一发调用开头生效(`checkBudget` 带回来的是记账前的数),因为「这一发已经
|
|
144
|
-
* 做完了」再拦它没有意义,能省的是后面那一发。
|
|
145
|
-
*/
|
|
146
|
-
function noteBytes(ctx, sessionId, value) {
|
|
147
|
-
const entry = budgetEntry(ctx, sessionId);
|
|
148
|
-
const size = byteSizeOf(value);
|
|
149
|
-
entry.bytes += size;
|
|
150
|
-
if (entry.bytes > BYTES_HARD_LIMIT) return { over: 'hard', bytes: entry.bytes };
|
|
151
|
-
if (entry.bytes > BYTES_SOFT_LIMIT) return { over: 'soft', bytes: entry.bytes };
|
|
152
|
-
return { over: '', bytes: entry.bytes };
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/** 序列化后有多少字节。算不出来就按 0 记 —— 体积账坏了不该把工具弄挂。 */
|
|
156
|
-
function byteSizeOf(value) {
|
|
157
|
-
try {
|
|
158
|
-
const json = JSON.stringify(value);
|
|
159
|
-
return typeof json === 'string' ? Buffer.byteLength(json, 'utf8') : 0;
|
|
160
|
-
} catch {
|
|
161
|
-
return 0;
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
function sleep(ms) {
|
|
166
|
-
if (!Number.isFinite(ms) || ms <= 0) return Promise.resolve();
|
|
167
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
function betweenDelay() {
|
|
171
|
-
if (!pacing || typeof pacing.get !== 'function' || typeof pacing.paceFor !== 'function') return 0;
|
|
172
|
-
try {
|
|
173
|
-
const range = pacing.paceFor(pacing.get()).betweenActionsMs;
|
|
174
|
-
if (!Array.isArray(range)) return 0;
|
|
175
|
-
const lo = Number(range[0]) || 0;
|
|
176
|
-
const hi = Number(range[1]) || lo;
|
|
177
|
-
return lo + Math.round(Math.random() * Math.max(0, hi - lo));
|
|
178
|
-
} catch {
|
|
179
|
-
return 0;
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
/**
|
|
184
|
-
* 这一批交给手机侧的节奏参数 `{mode, place}`(见协议 §1.2/§3.3)。
|
|
185
|
-
*
|
|
186
|
-
* mode 来自插件设置的三档(pacing.js 的 get(),默认 standard);place 来自 App 知识里那个 App 的
|
|
187
|
-
* `pace`(careful 的 App 手机侧停更久、按字数读)。手机侧按它把「步间停留 / type 分片」放到批循环里跑,
|
|
188
|
-
* 电脑侧插不进 sleep(批是一次下发、手机侧 for 循环)。拿不到就给空,手机侧按 standard / normal 兜底。
|
|
189
|
-
*/
|
|
190
|
-
function pacingModeOf() {
|
|
191
|
-
if (pacing && typeof pacing.get === 'function') {
|
|
192
|
-
try {
|
|
193
|
-
const m = pacing.get();
|
|
194
|
-
if (typeof m === 'string' && m) return m;
|
|
195
|
-
} catch {
|
|
196
|
-
/* 读不到就走默认 */
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
return 'standard';
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
function batchPlaceOf(steps) {
|
|
203
|
-
if (!phoneKnowledge || typeof phoneKnowledge.matchApp !== 'function') return '';
|
|
204
|
-
let pkg = '';
|
|
205
|
-
for (const s of steps) {
|
|
206
|
-
if (s && s.action === 'app.open' && s.args && typeof s.args.packageName === 'string' && s.args.packageName) {
|
|
207
|
-
pkg = s.args.packageName;
|
|
208
|
-
break;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
if (!pkg) return '';
|
|
212
|
-
try {
|
|
213
|
-
const doc = phoneKnowledge.matchApp(pkg);
|
|
214
|
-
return doc && typeof doc.pace === 'string' ? doc.pace : '';
|
|
215
|
-
} catch {
|
|
216
|
-
return '';
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
/** 这台手机报没报某项能力;拿不到能力接口时按「支持」放过,别凭空白挡一条路径。 */
|
|
221
|
-
function supports(service, deviceId, cap) {
|
|
222
|
-
if (!service || typeof service.hasCapability !== 'function') return true;
|
|
223
|
-
try { return service.hasCapability(deviceId, cap) === true; } catch { return true; }
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
function unsupportedNote(feature) {
|
|
227
|
-
return `这台手机还不支持${feature},需要把手机上的 App 升级到最新。`;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
/**
|
|
231
|
-
* `phone_open_link` 的两张封闭白名单。uri 只放行常见入口,settings 只放行这些设置页。
|
|
232
|
-
* 白名单而不是「拼字符串」:拼的话就回到了任意外部输入直达系统的口子。
|
|
233
|
-
*/
|
|
234
|
-
const URI_SCHEMES = new Set([
|
|
235
|
-
'http', 'https', 'tel', 'mailto', 'sms', 'smsto', 'geo', 'market',
|
|
236
|
-
'package', 'weixin', 'alipays', 'taobao', 'bilibili', 'zhihu', 'sinaweibo', 'snssdk1128',
|
|
237
|
-
]);
|
|
238
|
-
|
|
239
|
-
const SETTINGS_ACTIONS = new Set([
|
|
240
|
-
'android.settings.SETTINGS',
|
|
241
|
-
'android.settings.WIFI_SETTINGS',
|
|
242
|
-
'android.settings.BLUETOOTH_SETTINGS',
|
|
243
|
-
'android.settings.DATA_ROAMING_SETTINGS',
|
|
244
|
-
'android.settings.NFC_SETTINGS',
|
|
245
|
-
'android.settings.AIRPLANE_MODE_SETTINGS',
|
|
246
|
-
'android.settings.DISPLAY_SETTINGS',
|
|
247
|
-
'android.settings.SOUND_SETTINGS',
|
|
248
|
-
'android.settings.BATTERY_SAVER_SETTINGS',
|
|
249
|
-
'android.settings.LOCATION_SOURCE_SETTINGS',
|
|
250
|
-
'android.settings.PRIVACY_SETTINGS',
|
|
251
|
-
'android.settings.SECURITY_SETTINGS',
|
|
252
|
-
'android.settings.ACCESSIBILITY_SETTINGS',
|
|
253
|
-
'android.settings.APPLICATION_SETTINGS',
|
|
254
|
-
'android.settings.MANAGE_APPLICATIONS_SETTINGS',
|
|
255
|
-
'android.settings.APPLICATION_DETAILS_SETTINGS',
|
|
256
|
-
'android.settings.NOTIFICATION_SETTINGS',
|
|
257
|
-
'android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS',
|
|
258
|
-
'android.settings.USAGE_ACCESS_SETTINGS',
|
|
259
|
-
]);
|
|
260
|
-
|
|
261
|
-
/** phone_steps 里每一步允许的动作:单动作,不能再嵌套 batch。 */
|
|
262
|
-
const STEP_ACTIONS = new Set(['tap', 'type', 'swipe', 'key', 'app.open', 'app.close', 'screen.read', 'wait', 'gesture']);
|
|
263
|
-
|
|
264
|
-
/** 等待条件的默认与上限,和协议 1.2 一致。 */
|
|
265
|
-
const WAIT_DEFAULT_MS = 8000;
|
|
266
|
-
const WAIT_MAX_MS = 20000;
|
|
267
|
-
|
|
268
|
-
function clampTimeoutMs(value) {
|
|
269
|
-
if (!Number.isFinite(value)) return WAIT_DEFAULT_MS;
|
|
270
|
-
return Math.max(0, Math.min(WAIT_MAX_MS, Math.round(value)));
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/** 判一下这一步是不是不可逆;判定模块没就绪就返回 null(安静跳过)。 */
|
|
274
|
-
function judgeIrreversible(action, args, screenText) {
|
|
275
|
-
if (!irreversible || typeof irreversible.judge !== 'function') return null;
|
|
276
|
-
try { return irreversible.judge({ action, args, screenText }); } catch { return null; }
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
/** 把一段提示补进结果已有的 note 里;没有 note 或没有提示就原样不动。 */
|
|
280
|
-
function appendNote(value, notes) {
|
|
281
|
-
if (!value || typeof value !== 'object') return value;
|
|
282
|
-
const extra = (Array.isArray(notes) ? notes : [notes]).filter((n) => typeof n === 'string' && n);
|
|
283
|
-
if (extra.length === 0) return value;
|
|
284
|
-
const existing = typeof value.note === 'string' ? value.note : '';
|
|
285
|
-
value.note = existing ? `${existing} ${extra.join(' ')}` : extra.join(' ');
|
|
286
|
-
return value;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
function elementText(el) {
|
|
290
|
-
if (!el || typeof el !== 'object') return '';
|
|
291
|
-
for (const key of ['text', 'name', 'label', 'description', 'contentDescription', 'hint']) {
|
|
292
|
-
const value = el[key];
|
|
293
|
-
if (typeof value === 'string' && value.trim()) return value;
|
|
294
|
-
}
|
|
295
|
-
return '';
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
/** 一屏的指纹:包名 + 前若干个元素的「ref:文字」。用来判断「这块屏一直没变」。 */
|
|
299
|
-
function screenSignature(value) {
|
|
300
|
-
if (!value || typeof value !== 'object') return '';
|
|
301
|
-
const pkg = typeof value.packageName === 'string' ? value.packageName : '';
|
|
302
|
-
const elements = Array.isArray(value.elements) ? value.elements : [];
|
|
303
|
-
const parts = elements.slice(0, 80).map((el) => {
|
|
304
|
-
const ref = el && el.ref ? String(el.ref) : '';
|
|
305
|
-
return `${ref}:${elementText(el).slice(0, 40)}`;
|
|
306
|
-
});
|
|
307
|
-
return `${pkg}|${parts.join('|')}`;
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
/** 元素在哪:手机给的是 `[left, top, right, bottom]` 百分比。读不出来就返回 null。 */
|
|
311
|
-
function centerOf(el) {
|
|
312
|
-
const bounds = el && Array.isArray(el.bounds) ? el.bounds : null;
|
|
313
|
-
if (!bounds || bounds.length < 4) return null;
|
|
314
|
-
const nums = bounds.slice(0, 4).map((n) => Number(n));
|
|
315
|
-
if (!nums.every((n) => Number.isFinite(n))) return null;
|
|
316
|
-
return { x: (nums[0] + nums[2]) / 2, y: (nums[1] + nums[3]) / 2 };
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
/**
|
|
320
|
-
* 在一屏元素里找回「刚才那个元素」:先按原文文字找,文字一样的有多个时按离原位置最近的算。
|
|
321
|
-
*
|
|
322
|
-
* 为什么按文字 + 相对位置,而不是只按位置:列表滚过一屏之后,同一个位置上是别的条目;
|
|
323
|
-
* 而只按文字又会撞上「发送」这种一屏里出现两次的按钮。两个条件一起用,才既能认出
|
|
324
|
-
* 「同一个控件挪了位置」,也能认出「同一个控件还在原地」。
|
|
325
|
-
*/
|
|
326
|
-
function relocateIn(elements, wanted) {
|
|
327
|
-
const list = Array.isArray(elements) ? elements : [];
|
|
328
|
-
const text = wanted && typeof wanted.text === 'string' ? wanted.text.trim() : '';
|
|
329
|
-
if (!text) return null;
|
|
330
|
-
const same = list.filter((el) => elementText(el).trim() === text);
|
|
331
|
-
if (same.length === 0) return null;
|
|
332
|
-
if (same.length === 1) return same[0];
|
|
333
|
-
const anchor = wanted.center;
|
|
334
|
-
if (!anchor) return same[0];
|
|
335
|
-
let best = null;
|
|
336
|
-
let bestDist = Infinity;
|
|
337
|
-
for (const el of same) {
|
|
338
|
-
const center = centerOf(el);
|
|
339
|
-
if (!center) continue;
|
|
340
|
-
const dist = (center.x - anchor.x) ** 2 + (center.y - anchor.y) ** 2;
|
|
341
|
-
if (dist < bestDist) { bestDist = dist; best = el; }
|
|
342
|
-
}
|
|
343
|
-
return best || same[0];
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
/**
|
|
347
|
-
* 认一下「这一屏里叫 ref 的那个元素」。读屏结果的元素表就是手机刚吐出来的那一屏,
|
|
348
|
-
* 按 ref 找即可;找不到说明它已经不在这一屏上了。
|
|
349
|
-
*/
|
|
350
|
-
function elementByRef(elements, ref) {
|
|
351
|
-
const wanted = typeof ref === 'string' ? ref.trim() : '';
|
|
352
|
-
if (!wanted) return null;
|
|
353
|
-
const list = Array.isArray(elements) ? elements : [];
|
|
354
|
-
return list.find((el) => el && String(el.ref) === wanted) || null;
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
/**
|
|
358
|
-
* 死循环守卫:同一 ref 连点、同一屏连读、同一批连败,都在结果里加一句该换思路的话。
|
|
359
|
-
* 只提醒、不拦截 —— 拦截会把「界面本来就慢」误判成模型在瞎试。
|
|
360
|
-
*/
|
|
361
|
-
function deadLoopNotes(ctx, sessionId, name, args, value) {
|
|
362
|
-
const state = guardStateFor(ctx);
|
|
363
|
-
const notes = [];
|
|
364
|
-
|
|
365
|
-
if (name === 'phone_tap') {
|
|
366
|
-
const ref = args && typeof args.ref === 'string' ? args.ref.trim() : '';
|
|
367
|
-
if (ref) {
|
|
368
|
-
let entry = state.taps.get(sessionId);
|
|
369
|
-
if (!entry || entry.ref !== ref) entry = { ref, count: 0 };
|
|
370
|
-
entry.count += 1;
|
|
371
|
-
state.taps.set(sessionId, entry);
|
|
372
|
-
if (entry.count >= 4) {
|
|
373
|
-
notes.push(`同一个元素(${ref})已经连点 ${entry.count} 次,几乎肯定点错了。别再点它:重新读屏,换一个元素或换一条路径。`);
|
|
374
|
-
} else if (entry.count === 3) {
|
|
375
|
-
notes.push(`同一个元素(${ref})已经点了 3 次,屏没变就别再点,先读屏看看实际停在哪。`);
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
if (name === 'phone_screen') {
|
|
381
|
-
const sig = screenSignature(value);
|
|
382
|
-
if (sig) {
|
|
383
|
-
let entry = state.screens.get(sessionId);
|
|
384
|
-
if (!entry || entry.sig !== sig) entry = { sig, count: 0 };
|
|
385
|
-
entry.count += 1;
|
|
386
|
-
state.screens.set(sessionId, entry);
|
|
387
|
-
if (entry.count >= 5) {
|
|
388
|
-
notes.push(`这块屏已经连续读了 ${entry.count} 次,内容一直没变。别再用 phone_screen 反复读,换个做法。`);
|
|
389
|
-
} else if (entry.count === 4) {
|
|
390
|
-
notes.push('这块屏连续读了 4 次没变化,再读一次也不会变,考虑换个做法。');
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
if (name === 'phone_steps') {
|
|
396
|
-
const failed = Boolean(value && (value.ok === false || value.stopReason === 'step-failed'));
|
|
397
|
-
const entry = state.batches.get(sessionId) || { count: 0 };
|
|
398
|
-
entry.count = failed ? entry.count + 1 : 0;
|
|
399
|
-
state.batches.set(sessionId, entry);
|
|
400
|
-
if (entry.count >= 3) {
|
|
401
|
-
notes.push(`这一批已经失败 ${entry.count} 次,原样重试大概率还是失败。换一种做法:拆成单步,先读屏确认。`);
|
|
402
|
-
} else if (entry.count === 2) {
|
|
403
|
-
notes.push('这一批已经失败 2 次,原样重试大概率还是失败,换个思路。');
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
return notes;
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
function textOf(value, max) {
|
|
411
|
-
if (typeof value !== 'string') return '';
|
|
412
|
-
const trimmed = value.trim();
|
|
413
|
-
return trimmed.length > max ? `${trimmed.slice(0, max - 1)}…` : trimmed;
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
/**
|
|
417
|
-
* 这些工具都要拿到「这条会话绑在哪台手机上」,拿不到就抛一句能照做的话。
|
|
418
|
-
*
|
|
419
|
-
* @returns {{deviceId: string, service: object}}
|
|
420
|
-
*/
|
|
421
|
-
function targetOf(ctx, deps, sessionId) {
|
|
422
|
-
const { deviceId, from } = binding.resolveTarget(sessionId);
|
|
423
|
-
if (!deviceId) {
|
|
424
|
-
throw new Error('这条对话还没有指定要操作哪台手机:让用户在这台手机上发一句话,或者用 phone_target 选定一台。');
|
|
425
|
-
}
|
|
426
|
-
const service = deps.getService();
|
|
427
|
-
if (!service) throw new Error('手机操作服务没在运行(插件刚启动或已停用),先让用户重新连一次。');
|
|
428
|
-
if (!service.isOnline(deviceId)) {
|
|
429
|
-
const label = deps.describeDevice ? deps.describeDevice(deviceId) : deviceId;
|
|
430
|
-
throw new Error(`要操作的那台手机(${label})现在没连上。让用户在手机上打开 App 让连接恢复,或者用 phone_target 换一台。`);
|
|
431
|
-
}
|
|
432
|
-
return { deviceId, from, service };
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
/**
|
|
436
|
-
* 某个动作要判「现在动的是哪个 App」时,取包名。
|
|
437
|
-
* app.open / app.link 直接看参数里的包名;别的动作看最近一次动作 / 读屏回报的前台包。
|
|
438
|
-
* lastData 是刚拿到的一次 call 结果(有 packageName 就优先用它)。都没有就返回空串。
|
|
439
|
-
*/
|
|
440
|
-
function packageOf(ctx, sessionId, action, args, lastData) {
|
|
441
|
-
if (lastData && typeof lastData.packageName === 'string' && lastData.packageName.trim()) {
|
|
442
|
-
return lastData.packageName.trim();
|
|
443
|
-
}
|
|
444
|
-
if (action === 'app.open' || action === 'app.link') {
|
|
445
|
-
const pkg = args && typeof args.packageName === 'string' ? args.packageName.trim() : '';
|
|
446
|
-
if (pkg) return pkg;
|
|
447
|
-
}
|
|
448
|
-
const last = guardStateFor(ctx).lastPackage.get(sessionId);
|
|
449
|
-
return typeof last === 'string' ? last : '';
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
/** 本轮这条会话已授权的 App 集合。轮次变了就落到新键(旧的顺手清掉,免得越攒越多)。 */
|
|
453
|
-
function appAllowedFor(ctx, sessionId) {
|
|
454
|
-
const state = guardStateFor(ctx);
|
|
455
|
-
const key = `${turnKeyOf(ctx, sessionId)}:${sessionId}`;
|
|
456
|
-
let set = state.appAllowed.get(key);
|
|
457
|
-
if (!set) {
|
|
458
|
-
const suffix = `:${sessionId}`;
|
|
459
|
-
for (const existing of state.appAllowed.keys()) {
|
|
460
|
-
if (existing !== key && existing.endsWith(suffix)) state.appAllowed.delete(existing);
|
|
461
|
-
}
|
|
462
|
-
set = new Set();
|
|
463
|
-
state.appAllowed.set(key, set);
|
|
464
|
-
}
|
|
465
|
-
return set;
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
/** 把服务层的失败翻译成一句能给模型看的话。 */
|
|
469
|
-
async function runCore(service, deviceId, sessionId, action, args, signal) {
|
|
470
|
-
try {
|
|
471
|
-
const { data } = await service.call(deviceId, sessionId, action, args, { signal });
|
|
472
|
-
return data === undefined ? null : data;
|
|
473
|
-
} catch (error) {
|
|
474
|
-
const code = error && error.code ? error.code : 'failed';
|
|
475
|
-
const message = error && error.message ? error.message : '手机那边没能完成这一步';
|
|
476
|
-
// 抛出去的时候把手机侧的 code 带在 error 上:`stale-ref` 要在这里被上层认出来做一次
|
|
477
|
-
// 自动重试,而「人话」那段文案里不带机器码。别的地方照旧只看 message。
|
|
478
|
-
const withCode = (text) => {
|
|
479
|
-
const wrapped = new Error(text);
|
|
480
|
-
wrapped.code = code;
|
|
481
|
-
return wrapped;
|
|
482
|
-
};
|
|
483
|
-
if (code === 'offline') throw withCode('那台手机在这期间断开了连接,这一步没有做。');
|
|
484
|
-
if (code === 'timeout') throw withCode(`那台手机 ${message}。可以再试一次,或者先 phone_screen 看看它现在停在哪。`);
|
|
485
|
-
if (code === 'unsupported') throw withCode(`那台手机上装的 App 版本还不支持 ${action},需要把手机上的 App 升级到最新。`);
|
|
486
|
-
if (code === 'not-supported') throw withCode('这台手机上没有一个 App 能接这个动作,退回操作界面去做吧。');
|
|
487
|
-
if (code === 'adb-unavailable') throw withCode('那台手机的无线调试没连上(可能被系统关了),让用户在手机上重新打开无线调试。');
|
|
488
|
-
if (code === 'warming') throw withCode('手机正在准备后台屏,大约还要几秒,稍等再试。');
|
|
489
|
-
if (code === 'aborted') throw withCode('这一步被取消了。');
|
|
490
|
-
// 用户接管了手机:AI 暂停。原生可能报 paused,也可能报同义的 taken-over 之类,一并翻成人话。
|
|
491
|
-
if (code === 'paused' || code === 'taken-over' || code === 'takenover' || code === 'taken_over') {
|
|
492
|
-
throw withCode('用户已接管手机操作,AI 已暂停;要恢复让用户在预览页点回来。');
|
|
493
|
-
}
|
|
494
|
-
if (code === 'stale-ref') throw withCode(`${message}(界面在点之前变了)。`);
|
|
495
|
-
throw withCode(message);
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
/** 一句话总结「现在屏上是什么」,给工具结果用。 */
|
|
500
|
-
function summarizeScreen(data) {
|
|
501
|
-
if (!data || typeof data !== 'object') return '没有读到屏幕内容。';
|
|
502
|
-
// 「读屏没开」必须说在前面:否则「0 个元素」会被读成「界面是空的」或「App 没起来」,
|
|
503
|
-
// 模型就会反复重读、换 App 打开,越试越乱(2026-11-04 用户现场)。
|
|
504
|
-
if (data.a11yDisabled) {
|
|
505
|
-
return '读屏没有打开:只看到 0 个元素,不是界面空的,是我们看不见。让用户在「设置 › 权限 › 操作手机」里点「去打开」(现在点一下就开,不用去系统设置翻),然后重新读。';
|
|
506
|
-
}
|
|
507
|
-
const parts = [];
|
|
508
|
-
if (data.packageName) parts.push(`当前 App:${data.packageName}`);
|
|
509
|
-
if (data.activity) parts.push(`页面:${data.activity}`);
|
|
510
|
-
const count = Array.isArray(data.elements) ? data.elements.length : 0;
|
|
511
|
-
parts.push(`可见元素 ${count} 个`);
|
|
512
|
-
if (data.treeUnreadable) parts.push('没读到应用窗口(可能是自绘界面),坐标只能看截图');
|
|
513
|
-
// 元素表要写进这段文本里:模型看到的是 render 出来的文字,不是工具结果里的 json 字段。
|
|
514
|
-
// 只给「可见元素 61 个」而不给这 61 个是什么,等于告诉模型「屏上有东西但我不告诉你」——
|
|
515
|
-
// 它就只能去截图猜、或者拿 ref 瞎试。
|
|
516
|
-
const lines = elementLines(data.elements);
|
|
517
|
-
if (lines.length > 0) parts.push('', ...lines);
|
|
518
|
-
return parts.join('\n');
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
/** 把元素表写成一行一个的短文本;每个都带 ref,模型据此点。 */
|
|
522
|
-
function elementLines(elements) {
|
|
523
|
-
const list = Array.isArray(elements) ? elements : [];
|
|
524
|
-
const out = [];
|
|
525
|
-
for (const el of list) {
|
|
526
|
-
if (!el || typeof el !== 'object') continue;
|
|
527
|
-
const ref = el.ref === undefined || el.ref === null ? '' : String(el.ref);
|
|
528
|
-
if (!ref) continue;
|
|
529
|
-
const bits = [];
|
|
530
|
-
if (el.role) bits.push(String(el.role));
|
|
531
|
-
const label = el.text || el.name || el.description || '';
|
|
532
|
-
if (label) bits.push(`"${String(label).replace(/\s+/g, ' ').slice(0, 80)}"`);
|
|
533
|
-
if (el.clickable) bits.push('可点');
|
|
534
|
-
if (el.editable) bits.push('可输入');
|
|
535
|
-
if (el.scrollable) bits.push('可滚动');
|
|
536
|
-
if (el.checked === true) bits.push('已勾选');
|
|
537
|
-
if (el.secret) bits.push('密码框');
|
|
538
|
-
if (el.enabled === false) bits.push('不可用');
|
|
539
|
-
const b = Array.isArray(el.bounds) ? el.bounds : null;
|
|
540
|
-
if (b && b.length === 4) bits.push(`[${b.join(',')}]`);
|
|
541
|
-
out.push(`${ref}: ${bits.join(' ')}`);
|
|
542
|
-
}
|
|
543
|
-
return out;
|
|
544
|
-
}
|
|
545
|
-
|
|
546
|
-
/**
|
|
547
|
-
* 注册这组工具。缺 `tools` 注入的 profile(比如纯手机端宿主)静默跳过 —— 与
|
|
548
|
-
* `installExtensions` 同一口径,别把整块装配掀掉。
|
|
549
|
-
*
|
|
550
|
-
* **必须走 `ctx.inject(['tools'], …)`,不能直接 `ctx.tools.register`**:宿主里 `tools` 是
|
|
551
|
-
* 子代理作用域提供的服务,插件这一层直接读 `ctx.tools` 拿到的是 undefined(或者一个没有
|
|
552
|
-
* `register` 的影子对象),`register` 一调就抛,被下面那句容错吞掉 —— 现象是八个工具**一条
|
|
553
|
-
* 都没交到模型手上**,而模型只知道能用 `bash` 去敲 adb,于是它去截了电脑上连着的另一台设备。
|
|
554
|
-
* 同树的 `dsh-free-search` 也是这么写的(`ctx.inject(['tools'], (sctx) => …)`)。
|
|
555
|
-
*/
|
|
556
|
-
function installPhoneTools(ctx, deps) {
|
|
557
|
-
let defineTool;
|
|
558
|
-
try {
|
|
559
|
-
({ defineTool } = require('@deepseek-ai/dsh-tools'));
|
|
560
|
-
} catch {
|
|
561
|
-
return;
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
const build = (scoped) => {
|
|
565
|
-
/**
|
|
566
|
-
* 下发给手机并顺手记「这次回来的是哪个前台 App」。
|
|
567
|
-
*
|
|
568
|
-
* 任何一次 run 成功、结果里有 `packageName`,就更新这条会话的 lastPackage —— 下一步按 App
|
|
569
|
-
* 授权要知道现在动的是谁。包着 `runCore`,调用点不用各自记得更新。
|
|
570
|
-
*/
|
|
571
|
-
const run = async (service, deviceId, sessionId, action, args, signal) => {
|
|
572
|
-
const data = await runCore(service, deviceId, sessionId, action, args, signal);
|
|
573
|
-
if (data && typeof data.packageName === 'string' && data.packageName.trim()) {
|
|
574
|
-
guardStateFor(ctx).lastPackage.set(sessionId, data.packageName.trim());
|
|
575
|
-
}
|
|
576
|
-
return data;
|
|
577
|
-
};
|
|
578
|
-
|
|
579
|
-
/**
|
|
580
|
-
* 统一注册口:每条工具都套上「步数预算」与「死循环」两道软守卫。
|
|
581
|
-
*
|
|
582
|
-
* 包在注册这一层而不是每条 execute 里各写一遍 —— 守卫要对**所有** phone_* 生效,
|
|
583
|
-
* 漏一条就等于漏一条腿。预算越界直接拒(返回前就抛),软提醒补进结果已有的 note。
|
|
584
|
-
*/
|
|
585
|
-
const register = (tool) => {
|
|
586
|
-
const inner = tool.execute;
|
|
587
|
-
scoped.tools.register(defineTool({
|
|
588
|
-
...tool,
|
|
589
|
-
execute: async (args, exec) => {
|
|
590
|
-
const sessionId = sessionOf(exec);
|
|
591
|
-
const gate = checkBudget(ctx, sessionId);
|
|
592
|
-
if (gate.blocked) {
|
|
593
|
-
throw new Error(`这一轮操作手机已经到上限(约 ${CALL_HARD_LIMIT} 次),不能继续试了。把现在的进度告诉用户,需要的话用 end_not_done 收尾。`);
|
|
594
|
-
}
|
|
595
|
-
// 体积硬线:上一发之后累计已经越过 800KB 就直接拒。这一发还没跑,拦下来才有意义;
|
|
596
|
-
// 预算按「这一轮」算,轮次变了由 `budgetEntry` 一起清掉(次数与体积同一次重置)。
|
|
597
|
-
if (gate.bytes > BYTES_HARD_LIMIT) {
|
|
598
|
-
throw new Error(`这一轮手机界面读回来的内容已经超过 ${Math.round(BYTES_HARD_LIMIT / 1024)}KB,上下文塞不下了,不能继续读。把现在的进度告诉用户,需要的话用 end_not_done 收尾。`);
|
|
599
|
-
}
|
|
600
|
-
const value = await inner(args, exec);
|
|
601
|
-
// 顺手记住这次结果里的元素表:stale-ref 重试靠它把「上一次那个元素」认回来。
|
|
602
|
-
// 只在真的读到元素时更新 —— 无障碍没开时是一张空表,拿它覆盖会把上一屏一起忘掉。
|
|
603
|
-
if (value && Array.isArray(value.elements) && value.elements.length > 0) {
|
|
604
|
-
guardStateFor(ctx).lastElements.set(sessionId, value.elements);
|
|
605
|
-
}
|
|
606
|
-
const notes = [];
|
|
607
|
-
if (gate.count > CALL_SOFT_LIMIT) {
|
|
608
|
-
notes.push(`这一轮操作手机的次数已经超过 ${CALL_SOFT_LIMIT} 次(现在 ${gate.count} 次),请尽快收尾或结束这一步,别再零碎地反复试。`);
|
|
609
|
-
}
|
|
610
|
-
notes.push(...deadLoopNotes(ctx, sessionId, tool.name, args, value));
|
|
611
|
-
const withNotes = appendNote(value, notes);
|
|
612
|
-
// 体积账在结果定稿之后才记:附进去的那些提示本身也是交给模型的字节。
|
|
613
|
-
const size = noteBytes(ctx, sessionId, withNotes);
|
|
614
|
-
if (size.over === 'soft') {
|
|
615
|
-
appendNote(withNotes, `这一轮读到的手机界面已经累计约 ${Math.round(size.bytes / 1024)}KB,读得太多了。该收尾了:把结论说给用户,别再整屏整屏地读。`);
|
|
616
|
-
}
|
|
617
|
-
return withNotes;
|
|
618
|
-
},
|
|
619
|
-
}));
|
|
620
|
-
};
|
|
621
|
-
|
|
622
|
-
/**
|
|
623
|
-
* 宿主的附件库:截图要交给它存,编号才是宿主认得的那种(见 `phone_screenshot` 的说明)。
|
|
624
|
-
*
|
|
625
|
-
* 取用放在执行时、不在注册时:`attachments` 是宿主后装的,注册这一趟它可能还不在。先问
|
|
626
|
-
* 注入作用域、再问外层 —— 与 `schedule.js` 同一个口径(那边也是执行时 `ctx.get`)。
|
|
627
|
-
*/
|
|
628
|
-
const attachmentsOf = () => {
|
|
629
|
-
for (const source of [scoped, ctx]) {
|
|
630
|
-
if (!source || typeof source.get !== 'function') continue;
|
|
631
|
-
let store = null;
|
|
632
|
-
try { store = source.get('attachments'); } catch { store = null; }
|
|
633
|
-
if (store && typeof store.saveImage === 'function') return store;
|
|
634
|
-
}
|
|
635
|
-
return null;
|
|
636
|
-
};
|
|
637
|
-
|
|
638
|
-
/**
|
|
639
|
-
* 截一张后台屏并存进宿主附件库,返回可直接塞进结果的那个图片块。
|
|
640
|
-
*
|
|
641
|
-
* 截图有两条用途:模型主动要看(`phone_screenshot`),以及读屏读不出应用窗口时自动补一张
|
|
642
|
-
* (`phone_screen`)。存图这件事只写一遍 —— 引用编号必须是宿主那种 `sha256:` 形状,写错地方
|
|
643
|
-
* 下一轮整条请求会挂(2026-11-04 真机)。
|
|
644
|
-
*/
|
|
645
|
-
const captureImage = async (service, deviceId, sessionId, target, signal) => {
|
|
646
|
-
const data = await run(service, deviceId, sessionId, 'screen.screenshot', {}, signal);
|
|
647
|
-
const blob = data && typeof data.blob === 'string' ? data.blob : '';
|
|
648
|
-
if (!blob) throw new Error('没截到画面:手机那边没有回图片。');
|
|
649
|
-
const store = attachmentsOf();
|
|
650
|
-
if (!store) throw new Error('宿主没有附件库,这张图存不进去。');
|
|
651
|
-
let ref;
|
|
652
|
-
try {
|
|
653
|
-
ref = await store.saveImage({
|
|
654
|
-
data: Buffer.from(blob, 'base64'),
|
|
655
|
-
mediaType: data && data.format === 'jpeg' ? 'image/jpeg' : 'image/png',
|
|
656
|
-
name: textOf(target, MAX_TEXT) || 'phone-screen',
|
|
657
|
-
});
|
|
658
|
-
} catch (error) {
|
|
659
|
-
throw new Error(`截到的画面存不下来:${String((error && error.message) || error).slice(0, 200)}`);
|
|
660
|
-
}
|
|
661
|
-
return {
|
|
662
|
-
width: Number(ref.width) || 0,
|
|
663
|
-
height: Number(ref.height) || 0,
|
|
664
|
-
image: {
|
|
665
|
-
type: 'image',
|
|
666
|
-
attachment: {
|
|
667
|
-
attachmentId: ref.attachmentId,
|
|
668
|
-
mediaType: ref.mediaType,
|
|
669
|
-
bytes: ref.bytes,
|
|
670
|
-
width: ref.width,
|
|
671
|
-
height: ref.height,
|
|
672
|
-
...(ref.name ? { name: ref.name } : {}),
|
|
673
|
-
},
|
|
674
|
-
},
|
|
675
|
-
};
|
|
676
|
-
};
|
|
677
|
-
|
|
678
|
-
/** 在一屏元素里对一下等待条件,成立就返回。 */
|
|
679
|
-
const matchCondition = (elements, pkg, until) => {
|
|
680
|
-
const hay = (Array.isArray(elements) ? elements : []).map(elementText).join('\n').toLowerCase();
|
|
681
|
-
const pkgLower = String(pkg || '').toLowerCase();
|
|
682
|
-
if (until.appears && hay.includes(String(until.appears).toLowerCase())) return { met: true, stopped: null };
|
|
683
|
-
if (until.gone && !hay.includes(String(until.gone).toLowerCase())) return { met: true, stopped: null };
|
|
684
|
-
if (until.app && pkgLower.includes(String(until.app).toLowerCase())) return { met: true, stopped: null };
|
|
685
|
-
return null;
|
|
686
|
-
};
|
|
687
|
-
|
|
688
|
-
/**
|
|
689
|
-
* 原生的 screen.wait 用不了时的兜底:自己按 500ms 读一屏比对。
|
|
690
|
-
* 慢,但比「假装等到了」或直接报不支持强 —— 能力差异不该让用户的任务断掉。
|
|
691
|
-
*/
|
|
692
|
-
const pollCondition = async (service, deviceId, sessionId, until, timeoutMs, signal) => {
|
|
693
|
-
const start = Date.now();
|
|
694
|
-
const deadline = start + timeoutMs;
|
|
695
|
-
let lastSig = '';
|
|
696
|
-
let unchanged = 0;
|
|
697
|
-
for (;;) {
|
|
698
|
-
const data = await run(service, deviceId, sessionId, 'screen.read', { includeText: true }, signal);
|
|
699
|
-
const elements = Array.isArray(data && data.elements) ? data.elements : [];
|
|
700
|
-
const hit = matchCondition(elements, data && data.packageName, until);
|
|
701
|
-
if (hit) return { met: true, stopped: null, waitedMs: Date.now() - start };
|
|
702
|
-
if (until.stable === true) {
|
|
703
|
-
const sig = screenSignature({ packageName: data && data.packageName, elements });
|
|
704
|
-
if (sig === lastSig) {
|
|
705
|
-
unchanged += 1;
|
|
706
|
-
if (unchanged >= 1) return { met: true, stopped: null, waitedMs: Date.now() - start };
|
|
707
|
-
} else {
|
|
708
|
-
unchanged = 0;
|
|
709
|
-
lastSig = sig;
|
|
710
|
-
}
|
|
711
|
-
}
|
|
712
|
-
if (Date.now() >= deadline) return { met: false, stopped: 'timeout', waitedMs: Date.now() - start };
|
|
713
|
-
await sleep(Math.max(50, Math.min(500, deadline - Date.now())));
|
|
714
|
-
}
|
|
715
|
-
};
|
|
716
|
-
|
|
717
|
-
/** 等一个条件:原生 screen.wait 可用就走它,否则退回轮询。 */
|
|
718
|
-
const waitCondition = async (service, deviceId, sessionId, until, signal, canNative) => {
|
|
719
|
-
const timeoutMs = clampTimeoutMs(until && until.timeoutMs);
|
|
720
|
-
const cond = { timeoutMs };
|
|
721
|
-
if (until && typeof until.appears === 'string' && until.appears.trim()) cond.appears = textOf(until.appears, 200);
|
|
722
|
-
if (until && typeof until.gone === 'string' && until.gone.trim()) cond.gone = textOf(until.gone, 200);
|
|
723
|
-
if (until && typeof until.app === 'string' && until.app.trim()) cond.app = textOf(until.app, 200);
|
|
724
|
-
if (until && until.stable === true) cond.stable = true;
|
|
725
|
-
const hasCondition = cond.appears !== undefined || cond.gone !== undefined || cond.app !== undefined || cond.stable === true;
|
|
726
|
-
if (!hasCondition) return { met: true, stopped: null, waitedMs: 0 };
|
|
727
|
-
if (canNative) {
|
|
728
|
-
try {
|
|
729
|
-
const data = await run(service, deviceId, sessionId, 'screen.wait', cond, signal);
|
|
730
|
-
return {
|
|
731
|
-
met: Boolean(data && data.met === true),
|
|
732
|
-
stopped: data && data.stopped != null ? data.stopped : null,
|
|
733
|
-
waitedMs: Number(data && data.waitedMs) || 0,
|
|
734
|
-
};
|
|
735
|
-
} catch { /* 原生等失败就退回轮询 */ }
|
|
736
|
-
}
|
|
737
|
-
return pollCondition(service, deviceId, sessionId, cond, timeoutMs, signal);
|
|
738
|
-
};
|
|
739
|
-
|
|
740
|
-
/**
|
|
741
|
-
* 所有工具都要的那一步:从执行上下文里认出这条会话。
|
|
742
|
-
*
|
|
743
|
-
* `exec.agent.id` 就是会话 id(本仓 `dsh-codex-subscription` 也这么取)。**别写成
|
|
744
|
-
* `exec.agent.session.id`**:那一格不存在,取出来恒为空串,于是每个工具都以为「这条对话
|
|
745
|
-
* 还没绑手机」,绑定账也永远写着另一个键 —— 症状是「明明绑过,它还是说没有目标」。
|
|
746
|
-
*/
|
|
747
|
-
const sessionOf = (exec) => {
|
|
748
|
-
const id = exec && exec.agent && exec.agent.id;
|
|
749
|
-
return typeof id === 'string' ? id : '';
|
|
750
|
-
};
|
|
751
|
-
|
|
752
|
-
/**
|
|
753
|
-
* 有没有手机正在**看这条会话**。
|
|
754
|
-
*
|
|
755
|
-
* 判据是「这台设备开着会话流」:`stream-registry` 按 deviceId 只记「有没有流开着」,
|
|
756
|
-
* 会话级的观众表在审批桥里且是模块私有的。所以这里退一步用「这台会话绑的手机上有没有
|
|
757
|
-
* 流开着」—— 手机开着会话页就一定有一条流,关掉就一条都不剩。
|
|
758
|
-
*
|
|
759
|
-
* 判错的代价不对称:判成「有」只是多发一张没人答的卡(有硬期限兜底,最坏三分钟后回
|
|
760
|
-
* unavailable),判成「没有」会把一次本该发生的确认降级成 unavailable 而根本不问。
|
|
761
|
-
* 所以宁可宽一点。
|
|
762
|
-
*/
|
|
763
|
-
const someoneWatching = (sessionId) => {
|
|
764
|
-
let deviceId = '';
|
|
765
|
-
try {
|
|
766
|
-
const { boundDeviceOf } = require('./binding.js');
|
|
767
|
-
deviceId = boundDeviceOf(sessionId) || '';
|
|
768
|
-
} catch {
|
|
769
|
-
return true;
|
|
770
|
-
}
|
|
771
|
-
// 不知道绑哪台(新会话还没绑定):当作「可能有人看」,让审批桥自己去推。
|
|
772
|
-
if (!deviceId) return true;
|
|
773
|
-
try {
|
|
774
|
-
const registry = require('../stream-registry.js');
|
|
775
|
-
if (typeof registry.has === 'function') return registry.has(deviceId);
|
|
776
|
-
// 登记表没给按设备查的口子时只能看总数:有流开着就试一次。
|
|
777
|
-
if (typeof registry.size === 'function') return registry.size() > 0;
|
|
778
|
-
} catch { /* 没有登记表就不凭空白挡 */ }
|
|
779
|
-
return true;
|
|
780
|
-
};
|
|
781
|
-
|
|
782
|
-
/**
|
|
783
|
-
* 付款 / 下单那一步的关卡:先问宿主审批通道,拿到 `allowed-once` 才放行。
|
|
784
|
-
*
|
|
785
|
-
* 返回 null 表示可以执行;返回一句话表示不执行,那句话直接进工具结果交给模型。
|
|
786
|
-
* 只有 `payment` 走这里(`confirm.needsConfirmation` 的判据),发送 / 提交 / 删除照旧只按
|
|
787
|
-
* 节奏拉间隔 —— 那几种是任务本身要做的动作,每一步都拦会让人没法用。
|
|
788
|
-
*/
|
|
789
|
-
const requirePaymentConfirmation = async (sessionId, exec, what) => {
|
|
790
|
-
const callId = exec && typeof exec.callId === 'string' ? exec.callId : '';
|
|
791
|
-
const outcome = await confirm.requestConfirmation(ctx, {
|
|
792
|
-
sessionId,
|
|
793
|
-
summary: what,
|
|
794
|
-
agent: exec && exec.agent,
|
|
795
|
-
// 卡片上那个「工具 X 请求越权执行」的 X。写真实的工具名,用户在手机上看得出来
|
|
796
|
-
// 这一下是哪条工具要动手。
|
|
797
|
-
toolName: 'phone_tap',
|
|
798
|
-
// 有值才塞:宿主与守卫都不认值为 undefined 的字段。
|
|
799
|
-
...(callId ? { callId } : {}),
|
|
800
|
-
signal: exec && exec.signal,
|
|
801
|
-
watching: someoneWatching(sessionId),
|
|
802
|
-
});
|
|
803
|
-
if (outcome === 'allowed-once') return null;
|
|
804
|
-
return confirm.blockedMessage(outcome, what);
|
|
805
|
-
};
|
|
806
|
-
|
|
807
|
-
/* ── 按 App 三档授权(allow / ask / block) ──────────────────────────────── */
|
|
808
|
-
|
|
809
|
-
// 纯读动作一律放行:读屏不该因为「这个 App 被禁」就看不见。只有会改世界 / 操作界面的动作
|
|
810
|
-
// 才过授权层(tap/type/swipe/key/gesture/app.open/app.link/share.text/wheel.set/batch)。
|
|
811
|
-
const READ_ONLY_ACTIONS = new Set([
|
|
812
|
-
'screen.read', 'screen.screenshot', 'screen.wait', 'wait',
|
|
813
|
-
'find', 'query', 'collect', 'extract', 'app.list',
|
|
814
|
-
]);
|
|
815
|
-
|
|
816
|
-
const APP_BLOCKED_NOTE = '这个 App 被用户在「按 App 授权」里设为禁止,AI 不碰它;不要重试,换路或如实告诉用户。';
|
|
817
|
-
const ASK_REJECTED_NOTE = '用户没有允许 AI 操作这个 App(或这一轮被取消了),所以没有执行。把这件事如实告诉用户,别自己重试。';
|
|
818
|
-
const ASK_UNAVAILABLE_NOTE = '没能把「是否允许 AI 操作这个 App」的确认送到用户手上(手机没有在看这条对话,或者确认通道不可用),所以没有执行。请用户回到这条对话、在手机上看着再试一次。';
|
|
819
|
-
|
|
820
|
-
/**
|
|
821
|
-
* 按 App 挡一道。返回 null = 放行;返回 `{ok:false, blocked, note}` = 不执行。
|
|
822
|
-
*
|
|
823
|
-
* - block:直接拒。
|
|
824
|
-
* - ask:本轮该 App 已授权就放行;否则问一次审批桥,allowed-once 才放行并把 App 记进本轮。
|
|
825
|
-
* - allow:放行。
|
|
826
|
-
* - 付款动作(judged 命中 needsConfirmation)跳过 App 问卡:让它落到付款确认那张卡上,
|
|
827
|
-
* 同时把该 App 记进本轮已授权,避免下一步再问一次。
|
|
828
|
-
*/
|
|
829
|
-
async function appGate(gateCtx, sessionId, opts) {
|
|
830
|
-
const o = opts || {};
|
|
831
|
-
const action = typeof o.action === 'string' ? o.action : '';
|
|
832
|
-
if (READ_ONLY_ACTIONS.has(action)) return null;
|
|
833
|
-
const pkg = typeof o.packageName === 'string' ? o.packageName.trim() : '';
|
|
834
|
-
const mode = access.modeFor(access.readState(), pkg);
|
|
835
|
-
if (mode === 'allow') return null;
|
|
836
|
-
if (mode === 'block') return { ok: false, blocked: 'app-blocked', note: APP_BLOCKED_NOTE };
|
|
837
|
-
|
|
838
|
-
const allowed = appAllowedFor(gateCtx, sessionId);
|
|
839
|
-
const judged = o.judged || null;
|
|
840
|
-
if (judged && confirm.needsConfirmation(judged)) {
|
|
841
|
-
if (pkg) allowed.add(pkg);
|
|
842
|
-
return null;
|
|
843
|
-
}
|
|
844
|
-
if (pkg && allowed.has(pkg)) return null;
|
|
845
|
-
|
|
846
|
-
const exec = o.exec || null;
|
|
847
|
-
// 有值才塞:宿主与守卫都不认值为 undefined 的字段。
|
|
848
|
-
const ask = {
|
|
849
|
-
sessionId,
|
|
850
|
-
summary: `允许 AI 操作「${pkg || '这个 App'}」吗?`,
|
|
851
|
-
agent: exec && exec.agent,
|
|
852
|
-
toolName: exec && typeof exec.toolName === 'string' ? exec.toolName : 'phone_tap',
|
|
853
|
-
signal: exec && exec.signal,
|
|
854
|
-
watching: someoneWatching(sessionId),
|
|
855
|
-
};
|
|
856
|
-
if (exec && typeof exec.callId === 'string' && exec.callId) ask.callId = exec.callId;
|
|
857
|
-
const outcome = await confirm.requestConfirmation(gateCtx, ask);
|
|
858
|
-
if (outcome === 'allowed-once') {
|
|
859
|
-
if (pkg) allowed.add(pkg);
|
|
860
|
-
return null;
|
|
861
|
-
}
|
|
862
|
-
return { ok: false, blocked: 'app-ask-denied', note: outcome === 'rejected' ? ASK_REJECTED_NOTE : ASK_UNAVAILABLE_NOTE };
|
|
863
|
-
}
|
|
864
|
-
|
|
865
|
-
/**
|
|
866
|
-
* 动作执行前的一道:先取包名,取不到就补读一屏学前台包,再交给 appGate。
|
|
867
|
-
* 补读也学不到就保守拒(`app-access-unverified`),让模型先 phone_screen。
|
|
868
|
-
*/
|
|
869
|
-
const gateBeforeAction = async (sessionId, exec, info) => {
|
|
870
|
-
const action = info.action;
|
|
871
|
-
const args = info.args || {};
|
|
872
|
-
const { deviceId, service } = info;
|
|
873
|
-
let pkg = packageOf(ctx, sessionId, action, args, info.lastData);
|
|
874
|
-
if (!pkg) {
|
|
875
|
-
try {
|
|
876
|
-
const data = await run(service, deviceId, sessionId, 'screen.read', { includeText: true }, exec && exec.signal);
|
|
877
|
-
pkg = data && typeof data.packageName === 'string' ? data.packageName.trim() : '';
|
|
878
|
-
} catch { /* 读不到就按未验证处理 */ }
|
|
879
|
-
if (!pkg) {
|
|
880
|
-
return {
|
|
881
|
-
ok: false,
|
|
882
|
-
blocked: 'app-access-unverified',
|
|
883
|
-
note: '没能确认现在前台是哪个 App,为安全起见这一步没有执行。先 phone_screen 看看当前停在哪,再继续。',
|
|
884
|
-
};
|
|
885
|
-
}
|
|
886
|
-
}
|
|
887
|
-
return appGate(ctx, sessionId, { packageName: pkg, action, judged: info.judged || null, exec });
|
|
888
|
-
};
|
|
889
|
-
|
|
890
|
-
/**
|
|
891
|
-
* 「教一次就学会」:把刚跑成的一批动作抽成一条可重放路线,存成待收下的技能草稿。
|
|
892
|
-
*
|
|
893
|
-
* 返回一句给模型看的话(学会时说学了什么,没学时一句话都不多说 —— 学不成是常态,
|
|
894
|
-
* 每次都念一遍会淹掉真正重要的结果)。
|
|
895
|
-
*
|
|
896
|
-
* 三条硬边界:
|
|
897
|
-
* - **只学真跑成的**:`stopped` 为真表示这批中途停了,不学。收款步被切开的也不学。
|
|
898
|
-
* - **学不成不报错**:抽不出来(含付款、认出不了目标、敏感信息)就安静返回空串,
|
|
899
|
-
* 绝不让「学习」这件事把一次本来成功的操作判成失败。
|
|
900
|
-
* - **只写待收下的草稿**:落盘要用户点头(`route-store.accept`),不自动启用。
|
|
901
|
-
*/
|
|
902
|
-
/** 这一批是冲着哪个 App 去的:优先批里 app.open 那个包,抽不到再看最终屏。 */
|
|
903
|
-
const packageOfBatch = (steps) => {
|
|
904
|
-
for (const s of Array.isArray(steps) ? steps : []) {
|
|
905
|
-
if (s && s.action === 'app.open' && s.args && typeof s.args.packageName === 'string' && s.args.packageName.trim()) {
|
|
906
|
-
return s.args.packageName.trim();
|
|
907
|
-
}
|
|
908
|
-
}
|
|
909
|
-
return '';
|
|
910
|
-
};
|
|
911
|
-
|
|
912
|
-
const learnFromBatch = ({ sessionId, steps, results, packageName, stopped, exec }) => {
|
|
913
|
-
if (stopped) return '';
|
|
914
|
-
if (!routeStore) return '';
|
|
915
|
-
if (!Array.isArray(steps) || steps.length === 0) return '';
|
|
916
|
-
if (!packageName) return '';
|
|
917
|
-
|
|
918
|
-
// 每步动手之前那一屏:手机侧批量默认只回最终屏,只有 `quiet:false` 才有每步元素。
|
|
919
|
-
// 拿不到就给 null,抽取那边会退回模型给的 `target` 文字当锚 —— 那条通常就够。
|
|
920
|
-
const screens = Array.isArray(results)
|
|
921
|
-
? results.map((row) => (row && Array.isArray(row.elements) ? row.elements : null))
|
|
922
|
-
: [];
|
|
923
|
-
|
|
924
|
-
let extracted;
|
|
925
|
-
try {
|
|
926
|
-
extracted = routeExtract.extractRoute({
|
|
927
|
-
packageName,
|
|
928
|
-
steps,
|
|
929
|
-
screens,
|
|
930
|
-
results,
|
|
931
|
-
intentText: lastUserTextOf(exec),
|
|
932
|
-
});
|
|
933
|
-
} catch {
|
|
934
|
-
return '';
|
|
935
|
-
}
|
|
936
|
-
if (!extracted.ok) return '';
|
|
937
|
-
|
|
938
|
-
try {
|
|
939
|
-
const learned = routeStore.learn(extracted.route);
|
|
940
|
-
if (!learned.ok) return '';
|
|
941
|
-
return `这一批做成了,已经按它学成一条可重放的技能草稿「${learned.name}」,等你在手机上收下之后下次就能直接用。`;
|
|
942
|
-
} catch {
|
|
943
|
-
return '';
|
|
944
|
-
}
|
|
945
|
-
};
|
|
946
|
-
|
|
947
|
-
/**
|
|
948
|
-
* 这一轮用户说的那句话:它才是「意图」的正身。
|
|
949
|
-
*
|
|
950
|
-
* 拿不到就返回空串 —— 抽取那边会把意图留空、只按 App 认,比编一句假的强。
|
|
951
|
-
* 只读会话历史里最后一条用户发言,不猜、不外推。
|
|
952
|
-
*/
|
|
953
|
-
function lastUserTextOf(exec) {
|
|
954
|
-
const agent = exec && exec.agent;
|
|
955
|
-
const session = agent && agent.session;
|
|
956
|
-
const messages = session && Array.isArray(session.messages) ? session.messages : null;
|
|
957
|
-
if (!messages) return '';
|
|
958
|
-
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
|
959
|
-
const item = messages[i];
|
|
960
|
-
const role = item && (item.role || (item.data && item.data.role));
|
|
961
|
-
if (role !== 'user') continue;
|
|
962
|
-
const text = item && (typeof item.content === 'string'
|
|
963
|
-
? item.content
|
|
964
|
-
: (item.data && typeof item.data.text === 'string' ? item.data.text : ''));
|
|
965
|
-
if (typeof text === 'string' && text.trim()) return text.trim().slice(0, 500);
|
|
966
|
-
return '';
|
|
967
|
-
}
|
|
968
|
-
return '';
|
|
969
|
-
}
|
|
970
|
-
|
|
971
|
-
/**
|
|
972
|
-
* 这一屏里还认不认得那个 ref;认不得就按「上一次那个 ref 的文字 + 相对位置」在**新读的一屏**
|
|
973
|
-
* 里把同一个元素找回来。
|
|
974
|
-
*
|
|
975
|
-
* 手机侧自己也做了一次同样的重定位(`PhoneExecutor.relocate`),但那条路只覆盖「手机那一侧
|
|
976
|
-
* 拿到的旧屏还在」。插件这一层再兜一次,是因为模型拿到的 ref 来自我们上一次读屏的结果 ——
|
|
977
|
-
* 那一屏可能比手机自己记的还旧。多花一次读屏换模型少一次来回,值得。
|
|
978
|
-
*
|
|
979
|
-
* 只做一次:再认不出就是界面真的换了,那时报错比循环更有用(与协议 7.4「只重试一次」一致)。
|
|
980
|
-
*
|
|
981
|
-
* @returns {Promise<{ref: string, note: string}|null>} 找到就返回新 ref 与一句说明
|
|
982
|
-
*/
|
|
983
|
-
const relocateStaleRef = async (service, deviceId, sessionId, ref, signal) => {
|
|
984
|
-
const wanted = String(ref || '').trim();
|
|
985
|
-
if (!wanted) return null;
|
|
986
|
-
const previous = guardStateFor(ctx).lastElements.get(sessionId);
|
|
987
|
-
const staleEl = elementByRef(previous, wanted);
|
|
988
|
-
let data;
|
|
989
|
-
try {
|
|
990
|
-
data = await run(service, deviceId, sessionId, 'screen.read', { includeText: true }, signal);
|
|
991
|
-
} catch {
|
|
992
|
-
return null;
|
|
993
|
-
}
|
|
994
|
-
const elements = Array.isArray(data && data.elements) ? data.elements : [];
|
|
995
|
-
if (data && Array.isArray(data.elements)) guardStateFor(ctx).lastElements.set(sessionId, elements);
|
|
996
|
-
// 先按「旧文字 + 旧位置」认:这是协议里定的口径,比按序号猜准得多。
|
|
997
|
-
const hit = staleEl
|
|
998
|
-
? relocateIn(elements, { text: elementText(staleEl), center: centerOf(staleEl) })
|
|
999
|
-
: null;
|
|
1000
|
-
if (hit && hit.ref) {
|
|
1001
|
-
return {
|
|
1002
|
-
ref: String(hit.ref),
|
|
1003
|
-
note: `元素编号 ${wanted} 已经不在界面上了,按「${elementText(staleEl).slice(0, 24)}」重新定位到 ${hit.ref},重试过一次。`,
|
|
1004
|
-
};
|
|
1005
|
-
}
|
|
1006
|
-
return null;
|
|
1007
|
-
};
|
|
1008
|
-
|
|
1009
|
-
/**
|
|
1010
|
-
* 带一次 stale-ref 重试的执行。
|
|
1011
|
-
*
|
|
1012
|
-
* `tap` 与 `type` 的 ref 都是「上一次读屏的编号」,界面一动就过期。手机侧会回 `stale-ref`,
|
|
1013
|
-
* 这里收到之后**自动重新读一屏、找回同一个元素、用新编号再试一次**,并且把重试这件事
|
|
1014
|
-
* 如实写进结果 —— 模型要知道「看到的编号不一定还作数」,但不必为一次正常的界面变化
|
|
1015
|
-
* 再跑一整轮读屏 + 决策。
|
|
1016
|
-
*/
|
|
1017
|
-
const runWithStaleRetry = async (service, deviceId, sessionId, action, args, signal) => {
|
|
1018
|
-
try {
|
|
1019
|
-
return { data: await run(service, deviceId, sessionId, action, args, signal), note: '' };
|
|
1020
|
-
} catch (error) {
|
|
1021
|
-
if (!error || error.code !== 'stale-ref') throw error;
|
|
1022
|
-
const ref = typeof args.ref === 'string' ? args.ref.trim() : '';
|
|
1023
|
-
const found = await relocateStaleRef(service, deviceId, sessionId, ref, signal);
|
|
1024
|
-
if (!found) throw error;
|
|
1025
|
-
const retryArgs = { ...args, ref: found.ref };
|
|
1026
|
-
return { data: await run(service, deviceId, sessionId, action, retryArgs, signal), note: found.note };
|
|
1027
|
-
}
|
|
1028
|
-
};
|
|
1029
|
-
|
|
1030
|
-
/**
|
|
1031
|
-
* 拼出一句「这一轮来自谁、绑着谁」的提醒。
|
|
1032
|
-
*
|
|
1033
|
-
* 只在两者不一致时才说 —— 每一轮都说一遍等于噪音,模型很快就会学会忽略它。
|
|
1034
|
-
*/
|
|
1035
|
-
const mentionMismatch = (sessionId, bound) => {
|
|
1036
|
-
const sender = binding.lastSenderOf(sessionId);
|
|
1037
|
-
if (!sender || !bound || sender === bound) return '';
|
|
1038
|
-
const boundLabel = deps.describeDevice ? deps.describeDevice(bound) : bound;
|
|
1039
|
-
const senderLabel = deps.describeDevice ? deps.describeDevice(sender) : sender;
|
|
1040
|
-
return `(提醒:这条对话绑的是 ${boundLabel},而这句话是 ${senderLabel} 发来的。没让你换的话就继续操作 ${boundLabel},别擅自改绑。)`;
|
|
1041
|
-
};
|
|
1042
|
-
|
|
1043
|
-
register({
|
|
1044
|
-
name: 'phone_screen',
|
|
1045
|
-
description: 'Read the phone screen the agent is working on: which app is in front, and the visible elements with a short ref each. This is the structured accessibility tree, not a picture; call it before tapping so refs are fresh.',
|
|
1046
|
-
parameters: {
|
|
1047
|
-
includeText: {
|
|
1048
|
-
type: 'boolean',
|
|
1049
|
-
description: 'Include the readable text of each element. Default true; turn off for very long lists.',
|
|
1050
|
-
},
|
|
1051
|
-
compact: {
|
|
1052
|
-
type: 'boolean',
|
|
1053
|
-
description: 'Only return elements that changed since the previous read, plus a count of unchanged ones. Default false; use it in a loop to keep results small. Ignored on phones that cannot report changes.',
|
|
1054
|
-
},
|
|
1055
|
-
},
|
|
1056
|
-
output: {
|
|
1057
|
-
schema: {
|
|
1058
|
-
type: 'object',
|
|
1059
|
-
additionalProperties: false,
|
|
1060
|
-
properties: {
|
|
1061
|
-
deviceId: { type: 'string' },
|
|
1062
|
-
packageName: { type: 'string' },
|
|
1063
|
-
activity: { type: 'string' },
|
|
1064
|
-
// 元素是**任意形状的界面节点**(不同 App 给的字段不一样),所以 items 必须显式允许
|
|
1065
|
-
// 附加字段 —— dsh-tools 的 schema 编译器不接受留空的 additionalProperties。
|
|
1066
|
-
elements: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
1067
|
-
// 无障碍没开时这一格为真:说清楚「是我们看不见」而不是「界面是空的」。
|
|
1068
|
-
a11yDisabled: { type: 'boolean' },
|
|
1069
|
-
treeUnreadable: { type: 'boolean' },
|
|
1070
|
-
// 读屏读不出应用窗口时,第一次读会自动补一张截图,和文字一起回来。
|
|
1071
|
-
image: { type: 'object', additionalProperties: true },
|
|
1072
|
-
note: { type: 'string' },
|
|
1073
|
-
},
|
|
1074
|
-
},
|
|
1075
|
-
render: (_args, value) => {
|
|
1076
|
-
const blocks = [{ type: 'text', text: summarizeScreen(value) }];
|
|
1077
|
-
if (value.image) blocks.push(value.image);
|
|
1078
|
-
return blocks;
|
|
1079
|
-
},
|
|
1080
|
-
},
|
|
1081
|
-
execute: async (args, exec) => {
|
|
1082
|
-
const sessionId = sessionOf(exec);
|
|
1083
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
1084
|
-
const wantCompact = args.compact === true;
|
|
1085
|
-
const canCompact = supports(service, deviceId, 'screen.compact');
|
|
1086
|
-
const readArgs = { includeText: args.includeText !== false };
|
|
1087
|
-
// 参数只有在手机确实报了这项能力时才透传;否则如实说一句,而不是假装成功。
|
|
1088
|
-
const gsRev = guardStateFor(ctx).revisions;
|
|
1089
|
-
if (wantCompact && canCompact) {
|
|
1090
|
-
readArgs.compact = true;
|
|
1091
|
-
// 带上上次的读屏编号,手机才知道「从哪一版开始算变化」;对不上它会自动回全量。
|
|
1092
|
-
if (gsRev.has(sessionId)) readArgs.since = gsRev.get(sessionId);
|
|
1093
|
-
}
|
|
1094
|
-
const data = await run(service, deviceId, sessionId, 'screen.read', readArgs, exec.signal);
|
|
1095
|
-
if (data && Number.isFinite(data.revision)) gsRev.set(sessionId, data.revision);
|
|
1096
|
-
|
|
1097
|
-
const notes = [mentionMismatch(sessionId, deviceId)];
|
|
1098
|
-
if (wantCompact && !canCompact) notes.push(unsupportedNote('紧凑读屏(compact)'));
|
|
1099
|
-
|
|
1100
|
-
// App 用法知识:同一个对话、同一个 App 只附一次。知识库没就绪就当作没有。
|
|
1101
|
-
if (phoneKnowledge && typeof phoneKnowledge.noteFor === 'function') {
|
|
1102
|
-
try {
|
|
1103
|
-
const knowledge = phoneKnowledge.noteFor(sessionId, data && data.packageName);
|
|
1104
|
-
if (knowledge) notes.push(knowledge);
|
|
1105
|
-
} catch { /* 知识是锦上添花,读坏了不影响读屏 */ }
|
|
1106
|
-
}
|
|
1107
|
-
|
|
1108
|
-
// 这两个开关**只在这两件事真的成立时才有键**:宿主不允许工具结果里出现值为 undefined
|
|
1109
|
-
// 的字段(整条结果会被判成不是合法 JSON,模型看到的是「读屏坏了」),所以按「有值才塞」
|
|
1110
|
-
// 的写法构造,而不是摆一个 undefined 占位。
|
|
1111
|
-
const value = {
|
|
1112
|
-
deviceId,
|
|
1113
|
-
packageName: textOf(data && data.packageName, MAX_TEXT),
|
|
1114
|
-
activity: textOf(data && data.activity, MAX_TEXT),
|
|
1115
|
-
elements: Array.isArray(data && data.elements) ? data.elements.slice(0, 200) : [],
|
|
1116
|
-
};
|
|
1117
|
-
if (data && data.a11yDisabled === true) value.a11yDisabled = true;
|
|
1118
|
-
if (data && data.treeUnreadable === true) value.treeUnreadable = true;
|
|
1119
|
-
|
|
1120
|
-
// 读屏读不出应用窗口(自绘界面)时,第一次自动补一张截图:同一个结果里文字和图像一起给,
|
|
1121
|
-
// 省掉模型先读一次、再决定要不要截的来回。屏恢复可读后清掉标记,下次再遇到还能自动补。
|
|
1122
|
-
const gs = guardStateFor(ctx);
|
|
1123
|
-
if (data && data.treeUnreadable === true) {
|
|
1124
|
-
if (supports(service, deviceId, 'screen.screenshot') && !gs.autoShot.has(sessionId)) {
|
|
1125
|
-
gs.autoShot.set(sessionId, true);
|
|
1126
|
-
try {
|
|
1127
|
-
const shot = await captureImage(service, deviceId, sessionId, 'phone-screen', exec.signal);
|
|
1128
|
-
value.image = shot.image;
|
|
1129
|
-
notes.push('读屏读不出应用窗口,已自动附一张截图。');
|
|
1130
|
-
} catch { /* 截图失败不影响已经拿到的文字 */ }
|
|
1131
|
-
}
|
|
1132
|
-
} else if (gs.autoShot.has(sessionId)) {
|
|
1133
|
-
gs.autoShot.delete(sessionId);
|
|
1134
|
-
}
|
|
1135
|
-
|
|
1136
|
-
const note = notes.filter((n) => typeof n === 'string' && n).join(' ');
|
|
1137
|
-
if (note) value.note = note;
|
|
1138
|
-
return value;
|
|
1139
|
-
},
|
|
1140
|
-
});
|
|
1141
|
-
|
|
1142
|
-
/**
|
|
1143
|
-
* 截一张后台屏的画面。
|
|
1144
|
-
*
|
|
1145
|
-
* **为什么要有它**:读屏拿到的是界面树(文字、控件、坐标),但视频、画布、游戏、部分网页
|
|
1146
|
-
* 根本没有可读的节点 —— 那时候模型只能瞎猜。实测(2026-11-04):让它去抖音里看内容,
|
|
1147
|
-
* 它连标题都读不到,因为整屏都是自绘的画面。截图这条能力一直在手机侧(读屏读不到时兜底
|
|
1148
|
-
* 用的就是它),只是没交到模型手上。
|
|
1149
|
-
*
|
|
1150
|
-
* 图必须存进**宿主**的附件库:工具结果里的图片引用会随会话历史再发给模型,而宿主只认自己
|
|
1151
|
-
* 发的那种带 `sha256:` 前缀的编号。2026-11-04 真机:图存进了插件自己那份库里、编号是裸的
|
|
1152
|
-
* 哈希,下一轮请求整条挂掉(「附件引用无效」)。插件那份库是给手机端发图用的,两边不是一回事。
|
|
1153
|
-
*/
|
|
1154
|
-
register({
|
|
1155
|
-
name: 'phone_screenshot',
|
|
1156
|
-
description: 'Take a picture of the background screen the agent is working on. Use it when the accessibility tree cannot describe what is on screen: videos, canvas, games, image galleries. Returns the picture as an image.',
|
|
1157
|
-
parameters: {
|
|
1158
|
-
target: { type: 'string', description: 'What you are looking at, in a few words.' },
|
|
1159
|
-
},
|
|
1160
|
-
output: {
|
|
1161
|
-
schema: {
|
|
1162
|
-
type: 'object',
|
|
1163
|
-
additionalProperties: false,
|
|
1164
|
-
properties: {
|
|
1165
|
-
deviceId: { type: 'string' },
|
|
1166
|
-
width: { type: 'number' },
|
|
1167
|
-
height: { type: 'number' },
|
|
1168
|
-
note: { type: 'string' },
|
|
1169
|
-
image: { type: 'object', additionalProperties: true },
|
|
1170
|
-
},
|
|
1171
|
-
},
|
|
1172
|
-
render: (_args, value) => {
|
|
1173
|
-
const blocks = [{ type: 'text', text: `后台屏截图(${value.width}×${value.height})` }];
|
|
1174
|
-
if (value.image) blocks.push(value.image);
|
|
1175
|
-
return blocks;
|
|
1176
|
-
},
|
|
1177
|
-
},
|
|
1178
|
-
execute: async (args, exec) => {
|
|
1179
|
-
const sessionId = sessionOf(exec);
|
|
1180
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
1181
|
-
const shot = await captureImage(service, deviceId, sessionId, args.target, exec.signal);
|
|
1182
|
-
// 有值才塞键:宿主不接受值为 undefined 的字段(见 A3-79 的坑)。
|
|
1183
|
-
return {
|
|
1184
|
-
deviceId,
|
|
1185
|
-
width: shot.width,
|
|
1186
|
-
height: shot.height,
|
|
1187
|
-
note: mentionMismatch(sessionId, deviceId),
|
|
1188
|
-
image: shot.image,
|
|
1189
|
-
};
|
|
1190
|
-
},
|
|
1191
|
-
});
|
|
1192
|
-
|
|
1193
|
-
register({
|
|
1194
|
-
name: 'phone_tap',
|
|
1195
|
-
description: 'Tap an element on the phone screen by its ref (from phone_screen), or by viewport-relative percentage coordinates when no ref fits. One call taps once.',
|
|
1196
|
-
parameters: {
|
|
1197
|
-
ref: { type: 'string', description: 'Element ref from the latest phone_screen, e.g. "e12".' },
|
|
1198
|
-
x: { type: 'number', description: 'Horizontal position in percent of the screen width (0-100). Use only without ref.' },
|
|
1199
|
-
y: { type: 'number', description: 'Vertical position in percent of the screen height (0-100). Use only without ref.' },
|
|
1200
|
-
target: { type: 'string', description: 'What you are tapping, in a few words. Required for coordinate taps so the step stays readable.' },
|
|
1201
|
-
},
|
|
1202
|
-
output: {
|
|
1203
|
-
schema: {
|
|
1204
|
-
type: 'object',
|
|
1205
|
-
additionalProperties: false,
|
|
1206
|
-
properties: {
|
|
1207
|
-
ok: { type: 'boolean' },
|
|
1208
|
-
packageName: { type: 'string' },
|
|
1209
|
-
// 元素是**任意形状的界面节点**(不同 App 给的字段不一样),所以 items 必须显式允许
|
|
1210
|
-
// 附加字段 —— dsh-tools 的 schema 编译器不接受留空的 additionalProperties。
|
|
1211
|
-
elements: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
1212
|
-
// 「没执行」的原因码:付款那一步没拿到用户确认时就只有它。
|
|
1213
|
-
blocked: { type: 'string' },
|
|
1214
|
-
note: { type: 'string' },
|
|
1215
|
-
},
|
|
1216
|
-
},
|
|
1217
|
-
render: (_args, value) => [{ type: 'text', text: value.ok === false ? `这一步没有执行:${value.note || '见说明'}。` : `已点击。\n${summarizeScreen(value)}` }],
|
|
1218
|
-
},
|
|
1219
|
-
execute: async (args, exec) => {
|
|
1220
|
-
const sessionId = sessionOf(exec);
|
|
1221
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
1222
|
-
const hasRef = typeof args.ref === 'string' && args.ref.trim();
|
|
1223
|
-
const hasPoint = Number.isFinite(args.x) && Number.isFinite(args.y);
|
|
1224
|
-
if (!hasRef && !hasPoint) throw new Error('要么给 ref(phone_screen 里的元素编号),要么给 x / y 百分比。');
|
|
1225
|
-
if (hasRef && hasPoint) throw new Error('ref 和坐标只能给一样:有 ref 就按元素点。');
|
|
1226
|
-
if (!hasRef && !textOf(args.target, MAX_TEXT)) throw new Error('按坐标点的时候要说明点的是什么(target)。');
|
|
1227
|
-
const target = textOf(args.target, MAX_TEXT);
|
|
1228
|
-
const ref = hasRef ? args.ref.trim() : '';
|
|
1229
|
-
const tapArgs = {
|
|
1230
|
-
ref,
|
|
1231
|
-
x: hasPoint ? args.x : null,
|
|
1232
|
-
y: hasPoint ? args.y : null,
|
|
1233
|
-
target,
|
|
1234
|
-
};
|
|
1235
|
-
const notes = [mentionMismatch(sessionId, deviceId)];
|
|
1236
|
-
|
|
1237
|
-
// 付款 / 下单:先拿到人点的「同意」才按下去。判定用模型给的 ref + target,
|
|
1238
|
-
// 而 target 是这一下点的是什么 —— 模型按 phone_screen 里的文字填,词表在
|
|
1239
|
-
// irreversible.js,这里只认 kind === 'payment' 那一类。
|
|
1240
|
-
const judged = judgeIrreversible('tap', { ref, x: args.x, y: args.y, target }, '');
|
|
1241
|
-
// 先过按 App 授权(block 到此为止、ask 问一次),再无条件走付款确认。
|
|
1242
|
-
const accessBlocked = await gateBeforeAction(sessionId, exec, { action: 'tap', args: tapArgs, judged, deviceId, service });
|
|
1243
|
-
if (accessBlocked && accessBlocked.blocked) return accessBlocked;
|
|
1244
|
-
if (judged && confirm.needsConfirmation(judged)) {
|
|
1245
|
-
const blocked = await requirePaymentConfirmation(sessionId, exec, `在手机上点「${target || ref}」`);
|
|
1246
|
-
if (blocked) {
|
|
1247
|
-
// 不执行、也不抛:抛会把「问过用户、用户没同意」做成一次工具失败,模型会当成
|
|
1248
|
-
// 手机坏了去重试。如实回一句「没做,为什么」才是它该看到的东西。
|
|
1249
|
-
return { ok: false, blocked: 'payment-confirmation', note: blocked };
|
|
1250
|
-
}
|
|
1251
|
-
notes.push('这一步是付款 / 下单,用户已经确认过一次,就这一下有效。');
|
|
1252
|
-
}
|
|
1253
|
-
|
|
1254
|
-
const { data, note: retried } = await runWithStaleRetry(service, deviceId, sessionId, 'tap', tapArgs, exec.signal);
|
|
1255
|
-
if (retried) notes.push(retried);
|
|
1256
|
-
// 单步本来就是做不可逆动作的正确姿势(批里会被熔断)。这里给一句确认,让模型知道
|
|
1257
|
-
// 这一下为什么该单独做、做之前最好再核一眼。
|
|
1258
|
-
if (judged && judged.irreversible && !confirm.needsConfirmation(judged)) {
|
|
1259
|
-
notes.push(`这一步看起来不可逆(${judged.reason}),已经作为单独一步执行;接着看结果再决定下一步。`);
|
|
1260
|
-
}
|
|
1261
|
-
const value = {
|
|
1262
|
-
ok: true,
|
|
1263
|
-
packageName: textOf(data && data.packageName, MAX_TEXT),
|
|
1264
|
-
elements: Array.isArray(data && data.elements) ? data.elements.slice(0, 120) : [],
|
|
1265
|
-
};
|
|
1266
|
-
const note = notes.filter(Boolean).join(' ');
|
|
1267
|
-
if (note) value.note = note;
|
|
1268
|
-
return value;
|
|
1269
|
-
},
|
|
1270
|
-
});
|
|
1271
|
-
|
|
1272
|
-
register({
|
|
1273
|
-
name: 'phone_type',
|
|
1274
|
-
description: 'Type text into an input on the phone screen. Give the input element ref from phone_screen; without it the text goes to whatever field already has focus.',
|
|
1275
|
-
parameters: {
|
|
1276
|
-
text: { type: 'string', required: true, description: 'Text to enter. Replaces the field content when ref is given.' },
|
|
1277
|
-
ref: { type: 'string', description: 'Input element ref from phone_screen. Omit to type into the focused field.' },
|
|
1278
|
-
submit: { type: 'boolean', description: 'Press Enter afterwards. Default false.' },
|
|
1279
|
-
},
|
|
1280
|
-
output: {
|
|
1281
|
-
schema: {
|
|
1282
|
-
type: 'object',
|
|
1283
|
-
additionalProperties: false,
|
|
1284
|
-
properties: {
|
|
1285
|
-
ok: { type: 'boolean' },
|
|
1286
|
-
packageName: { type: 'string' },
|
|
1287
|
-
// 元素是**任意形状的界面节点**(不同 App 给的字段不一样),所以 items 必须显式允许
|
|
1288
|
-
// 附加字段 —— dsh-tools 的 schema 编译器不接受留空的 additionalProperties。
|
|
1289
|
-
elements: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
1290
|
-
// 按 App 授权被拦(app-blocked / app-ask-denied / app-access-unverified)时的原因码。
|
|
1291
|
-
blocked: { type: 'string' },
|
|
1292
|
-
note: { type: 'string' },
|
|
1293
|
-
},
|
|
1294
|
-
},
|
|
1295
|
-
render: (_args, value) => [{ type: 'text', text: value.ok === false ? `这一步没有执行:${value.note || '见说明'}。` : `已输入。\n${summarizeScreen(value)}` }],
|
|
1296
|
-
},
|
|
1297
|
-
execute: async (args, exec) => {
|
|
1298
|
-
const sessionId = sessionOf(exec);
|
|
1299
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
1300
|
-
const value = typeof args.text === 'string' ? args.text : '';
|
|
1301
|
-
if (!value) throw new Error('要输入的文字是空的。');
|
|
1302
|
-
const typeArgs = {
|
|
1303
|
-
text: value,
|
|
1304
|
-
ref: typeof args.ref === 'string' ? args.ref.trim() : '',
|
|
1305
|
-
submit: args.submit === true,
|
|
1306
|
-
};
|
|
1307
|
-
const accessBlocked = await gateBeforeAction(sessionId, exec, { action: 'type', args: typeArgs, judged: null, deviceId, service });
|
|
1308
|
-
if (accessBlocked && accessBlocked.blocked) return accessBlocked;
|
|
1309
|
-
const { data, note: retried } = await runWithStaleRetry(service, deviceId, sessionId, 'type', typeArgs, exec.signal);
|
|
1310
|
-
const notes = [mentionMismatch(sessionId, deviceId)];
|
|
1311
|
-
if (retried) notes.push(retried);
|
|
1312
|
-
const result = {
|
|
1313
|
-
ok: true,
|
|
1314
|
-
packageName: textOf(data && data.packageName, MAX_TEXT),
|
|
1315
|
-
elements: Array.isArray(data && data.elements) ? data.elements.slice(0, 120) : [],
|
|
1316
|
-
};
|
|
1317
|
-
const note = notes.filter(Boolean).join(' ');
|
|
1318
|
-
if (note) result.note = note;
|
|
1319
|
-
return result;
|
|
1320
|
-
},
|
|
1321
|
-
});
|
|
1322
|
-
|
|
1323
|
-
register({
|
|
1324
|
-
name: 'phone_scroll',
|
|
1325
|
-
description: 'Scroll the phone screen: up (content moves up, i.e. see what is below), down, left or right. Distance is a fraction of the screen.',
|
|
1326
|
-
parameters: {
|
|
1327
|
-
direction: { type: 'string', required: true, enum: ['up', 'down', 'left', 'right'], description: 'Direction the content moves.' },
|
|
1328
|
-
amount: { type: 'number', description: 'How far, as a fraction of the screen (0.1-1). Default 0.7.' },
|
|
1329
|
-
},
|
|
1330
|
-
output: {
|
|
1331
|
-
schema: {
|
|
1332
|
-
type: 'object',
|
|
1333
|
-
additionalProperties: false,
|
|
1334
|
-
properties: {
|
|
1335
|
-
ok: { type: 'boolean' },
|
|
1336
|
-
packageName: { type: 'string' },
|
|
1337
|
-
// 元素是**任意形状的界面节点**(不同 App 给的字段不一样),所以 items 必须显式允许
|
|
1338
|
-
// 附加字段 —— dsh-tools 的 schema 编译器不接受留空的 additionalProperties。
|
|
1339
|
-
elements: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
1340
|
-
blocked: { type: 'string' },
|
|
1341
|
-
note: { type: 'string' },
|
|
1342
|
-
},
|
|
1343
|
-
},
|
|
1344
|
-
render: (_args, value) => [{ type: 'text', text: value.ok === false ? `这一步没有执行:${value.note || '见说明'}。` : `已滚动。\n${summarizeScreen(value)}` }],
|
|
1345
|
-
},
|
|
1346
|
-
execute: async (args, exec) => {
|
|
1347
|
-
const sessionId = sessionOf(exec);
|
|
1348
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
1349
|
-
const direction = ['up', 'down', 'left', 'right'].includes(args.direction) ? args.direction : '';
|
|
1350
|
-
if (!direction) throw new Error('direction 只能是 up / down / left / right。');
|
|
1351
|
-
const amount = Number.isFinite(args.amount) ? Math.min(1, Math.max(0.1, args.amount)) : 0.7;
|
|
1352
|
-
const swipeArgs = { direction, amount };
|
|
1353
|
-
const accessBlocked = await gateBeforeAction(sessionId, exec, { action: 'swipe', args: swipeArgs, judged: null, deviceId, service });
|
|
1354
|
-
if (accessBlocked && accessBlocked.blocked) return accessBlocked;
|
|
1355
|
-
const data = await run(service, deviceId, sessionId, 'swipe', swipeArgs, exec.signal);
|
|
1356
|
-
return {
|
|
1357
|
-
ok: true,
|
|
1358
|
-
packageName: textOf(data && data.packageName, MAX_TEXT),
|
|
1359
|
-
elements: Array.isArray(data && data.elements) ? data.elements.slice(0, 120) : [],
|
|
1360
|
-
note: mentionMismatch(sessionId, deviceId),
|
|
1361
|
-
};
|
|
1362
|
-
},
|
|
1363
|
-
});
|
|
1364
|
-
|
|
1365
|
-
register({
|
|
1366
|
-
name: 'phone_key',
|
|
1367
|
-
description: 'Press one system key on the phone: back, home, enter, recents, tab (next field), paste, selectall, or delete. Nothing else — the power and volume buttons are the user\'s own and are never pressed.',
|
|
1368
|
-
parameters: {
|
|
1369
|
-
key: { type: 'string', required: true, enum: ['back', 'home', 'enter', 'recents', 'tab', 'paste', 'selectall', 'delete'], description: 'Which key to press.' },
|
|
1370
|
-
},
|
|
1371
|
-
output: {
|
|
1372
|
-
schema: {
|
|
1373
|
-
type: 'object',
|
|
1374
|
-
additionalProperties: false,
|
|
1375
|
-
properties: {
|
|
1376
|
-
ok: { type: 'boolean' },
|
|
1377
|
-
packageName: { type: 'string' },
|
|
1378
|
-
// 元素是**任意形状的界面节点**(不同 App 给的字段不一样),所以 items 必须显式允许
|
|
1379
|
-
// 附加字段 —— dsh-tools 的 schema 编译器不接受留空的 additionalProperties。
|
|
1380
|
-
elements: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
1381
|
-
blocked: { type: 'string' },
|
|
1382
|
-
note: { type: 'string' },
|
|
1383
|
-
},
|
|
1384
|
-
},
|
|
1385
|
-
render: (_args, value) => [{ type: 'text', text: value.ok === false ? `这一步没有执行:${value.note || '见说明'}。` : `已按键。\n${summarizeScreen(value)}` }],
|
|
1386
|
-
},
|
|
1387
|
-
execute: async (args, exec) => {
|
|
1388
|
-
const sessionId = sessionOf(exec);
|
|
1389
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
1390
|
-
const KEYS = ['back', 'home', 'enter', 'recents', 'tab', 'paste', 'selectall', 'delete'];
|
|
1391
|
-
const key = KEYS.includes(args.key) ? args.key : '';
|
|
1392
|
-
if (!key) throw new Error(`key 只能是 ${KEYS.join(' / ')}。`);
|
|
1393
|
-
const accessBlocked = await gateBeforeAction(sessionId, exec, { action: 'key', args: { key }, judged: null, deviceId, service });
|
|
1394
|
-
if (accessBlocked && accessBlocked.blocked) return accessBlocked;
|
|
1395
|
-
const data = await run(service, deviceId, sessionId, 'key', { key }, exec.signal);
|
|
1396
|
-
return {
|
|
1397
|
-
ok: true,
|
|
1398
|
-
packageName: textOf(data && data.packageName, MAX_TEXT),
|
|
1399
|
-
elements: Array.isArray(data && data.elements) ? data.elements.slice(0, 120) : [],
|
|
1400
|
-
note: mentionMismatch(sessionId, deviceId),
|
|
1401
|
-
};
|
|
1402
|
-
},
|
|
1403
|
-
});
|
|
1404
|
-
|
|
1405
|
-
register({
|
|
1406
|
-
name: 'phone_apps',
|
|
1407
|
-
description: 'List the apps installed on the phone that can be opened (label + package), optionally filtered by a keyword. Use it to find the package before phone_open_app.',
|
|
1408
|
-
parameters: {
|
|
1409
|
-
query: { type: 'string', description: 'Case-insensitive keyword matched against label or package.' },
|
|
1410
|
-
limit: { type: 'integer', description: 'How many to return, 1-100. Default 40.' },
|
|
1411
|
-
},
|
|
1412
|
-
output: {
|
|
1413
|
-
schema: {
|
|
1414
|
-
type: 'object',
|
|
1415
|
-
additionalProperties: false,
|
|
1416
|
-
properties: {
|
|
1417
|
-
apps: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
1418
|
-
note: { type: 'string' },
|
|
1419
|
-
},
|
|
1420
|
-
},
|
|
1421
|
-
render: (_args, value) => [{ type: 'text', text: `找到 ${Array.isArray(value.apps) ? value.apps.length : 0} 个 App。` }],
|
|
1422
|
-
},
|
|
1423
|
-
execute: async (args, exec) => {
|
|
1424
|
-
const sessionId = sessionOf(exec);
|
|
1425
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
1426
|
-
const limit = Number.isInteger(args.limit) ? Math.min(100, Math.max(1, args.limit)) : 40;
|
|
1427
|
-
const data = await run(service, deviceId, sessionId, 'app.list', {
|
|
1428
|
-
query: textOf(args.query, 60),
|
|
1429
|
-
limit,
|
|
1430
|
-
}, exec.signal);
|
|
1431
|
-
return {
|
|
1432
|
-
apps: Array.isArray(data && data.apps) ? data.apps.slice(0, limit) : [],
|
|
1433
|
-
note: mentionMismatch(sessionId, deviceId),
|
|
1434
|
-
};
|
|
1435
|
-
},
|
|
1436
|
-
});
|
|
1437
|
-
|
|
1438
|
-
register({
|
|
1439
|
-
name: 'phone_open_app',
|
|
1440
|
-
description: 'Open an app on the phone screen the agent works on. Opening happens on a background display, so the user keeps their own screen.',
|
|
1441
|
-
parameters: {
|
|
1442
|
-
packageName: { type: 'string', required: true, description: 'Android package name, e.g. "com.tencent.mm". Find it with phone_apps.' },
|
|
1443
|
-
fresh: { type: 'boolean', description: 'Restart the app instead of reusing its existing state. Default false.' },
|
|
1444
|
-
},
|
|
1445
|
-
output: {
|
|
1446
|
-
schema: {
|
|
1447
|
-
type: 'object',
|
|
1448
|
-
additionalProperties: false,
|
|
1449
|
-
properties: {
|
|
1450
|
-
ok: { type: 'boolean' },
|
|
1451
|
-
packageName: { type: 'string' },
|
|
1452
|
-
// 元素是**任意形状的界面节点**(不同 App 给的字段不一样),所以 items 必须显式允许
|
|
1453
|
-
// 附加字段 —— dsh-tools 的 schema 编译器不接受留空的 additionalProperties。
|
|
1454
|
-
elements: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
1455
|
-
blocked: { type: 'string' },
|
|
1456
|
-
note: { type: 'string' },
|
|
1457
|
-
},
|
|
1458
|
-
},
|
|
1459
|
-
render: (_args, value) => [{ type: 'text', text: value.ok === false ? `这一步没有执行:${value.note || '见说明'}。` : `已打开 ${value.packageName || 'App'}。` }],
|
|
1460
|
-
},
|
|
1461
|
-
execute: async (args, exec) => {
|
|
1462
|
-
const sessionId = sessionOf(exec);
|
|
1463
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
1464
|
-
const pkg = textOf(args.packageName, 200);
|
|
1465
|
-
if (!/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$/.test(pkg)) throw new Error('packageName 看起来不像安卓包名。');
|
|
1466
|
-
const accessBlocked = await gateBeforeAction(sessionId, exec, { action: 'app.open', args: { packageName: pkg }, judged: null, deviceId, service });
|
|
1467
|
-
if (accessBlocked && accessBlocked.blocked) return accessBlocked;
|
|
1468
|
-
const data = await run(service, deviceId, sessionId, 'app.open', {
|
|
1469
|
-
packageName: pkg,
|
|
1470
|
-
fresh: args.fresh === true,
|
|
1471
|
-
}, exec.signal);
|
|
1472
|
-
return {
|
|
1473
|
-
ok: true,
|
|
1474
|
-
packageName: textOf(data && data.packageName, MAX_TEXT) || pkg,
|
|
1475
|
-
elements: Array.isArray(data && data.elements) ? data.elements.slice(0, 120) : [],
|
|
1476
|
-
note: mentionMismatch(sessionId, deviceId),
|
|
1477
|
-
};
|
|
1478
|
-
},
|
|
1479
|
-
});
|
|
1480
|
-
|
|
1481
|
-
register({
|
|
1482
|
-
name: 'phone_steps',
|
|
1483
|
-
description: 'Run several phone actions in one call, executed in order on the phone. Use it to save round-trips when you already know the next few steps (open an app, tap a search box, type, tap search). Give 1-20 steps; each step has action + args and an optional until to wait for the next screen. Do NOT put a payment step (pay, order, buy, checkout) in a batch — the batch will stop right before it and you must do that one step on its own with phone_tap, because it needs the user to confirm. Sending, submitting and deleting are fine to batch. If a step fails the batch stops and tells you where.',
|
|
1484
|
-
parameters: {
|
|
1485
|
-
steps: {
|
|
1486
|
-
type: 'array',
|
|
1487
|
-
description: '1-20 steps run in order on the phone.',
|
|
1488
|
-
items: {
|
|
1489
|
-
type: 'object',
|
|
1490
|
-
additionalProperties: true,
|
|
1491
|
-
properties: {
|
|
1492
|
-
action: { type: 'string', description: 'One single action: tap, type, swipe, key, app.open, app.close, screen.read, wait, or gesture. Never batch.' },
|
|
1493
|
-
args: { type: 'object', additionalProperties: true, description: 'Arguments for that action, same fields as the matching single tool.' },
|
|
1494
|
-
until: {
|
|
1495
|
-
type: 'object',
|
|
1496
|
-
additionalProperties: true,
|
|
1497
|
-
properties: {
|
|
1498
|
-
appears: { type: 'string', description: 'Wait until an element containing this text appears (case-insensitive).' },
|
|
1499
|
-
gone: { type: 'string', description: 'Wait until this text is no longer on screen.' },
|
|
1500
|
-
app: { type: 'string', description: 'Wait until this package is in front.' },
|
|
1501
|
-
stable: { type: 'boolean', description: 'Wait until the screen stops changing.' },
|
|
1502
|
-
timeoutMs: { type: 'number', description: 'Max wait for this step, default 8000, max 20000.' },
|
|
1503
|
-
},
|
|
1504
|
-
},
|
|
1505
|
-
},
|
|
1506
|
-
},
|
|
1507
|
-
},
|
|
1508
|
-
quiet: { type: 'boolean', description: 'Only return the final screen (default true). Set false to also get the screen after each step.' },
|
|
1509
|
-
},
|
|
1510
|
-
output: {
|
|
1511
|
-
schema: {
|
|
1512
|
-
type: 'object',
|
|
1513
|
-
additionalProperties: false,
|
|
1514
|
-
properties: {
|
|
1515
|
-
ok: { type: 'boolean' },
|
|
1516
|
-
steps: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
1517
|
-
stoppedAt: { type: 'number' },
|
|
1518
|
-
stopReason: { type: 'string' },
|
|
1519
|
-
packageName: { type: 'string' },
|
|
1520
|
-
elements: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
1521
|
-
revision: { type: 'number' },
|
|
1522
|
-
blocked: { type: 'string' },
|
|
1523
|
-
note: { type: 'string' },
|
|
1524
|
-
},
|
|
1525
|
-
},
|
|
1526
|
-
render: (_args, value) => {
|
|
1527
|
-
if (value.ok === false && value.blocked) return [{ type: 'text', text: `这一批没有执行:${value.note || '见说明'}。` }];
|
|
1528
|
-
const ran = Array.isArray(value.steps) ? value.steps.length : 0;
|
|
1529
|
-
const bad = value.stopReason ? `,在第 ${Number.isInteger(value.stoppedAt) ? value.stoppedAt + 1 : '?'} 步停下(${value.stopReason})` : '';
|
|
1530
|
-
return [{ type: 'text', text: `做了 ${ran} 步${bad}。` }];
|
|
1531
|
-
},
|
|
1532
|
-
},
|
|
1533
|
-
execute: async (args, exec) => {
|
|
1534
|
-
const sessionId = sessionOf(exec);
|
|
1535
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
1536
|
-
const raw = Array.isArray(args.steps) ? args.steps : [];
|
|
1537
|
-
if (raw.length < 1 || raw.length > 20) throw new Error('steps 要给 1 到 20 步。');
|
|
1538
|
-
|
|
1539
|
-
const steps = raw.map((step, i) => {
|
|
1540
|
-
if (!step || typeof step !== 'object') throw new Error(`第 ${i + 1} 步不是对象。`);
|
|
1541
|
-
const action = typeof step.action === 'string' ? step.action.trim() : '';
|
|
1542
|
-
if (!STEP_ACTIONS.has(action)) {
|
|
1543
|
-
throw new Error(`第 ${i + 1} 步的动作 ${action || '(空)'} 不能放进批量:只能是 ${[...STEP_ACTIONS].join(' / ')}。`);
|
|
1544
|
-
}
|
|
1545
|
-
const stepArgs = step.args && typeof step.args === 'object' ? step.args : {};
|
|
1546
|
-
const out = { action, args: stepArgs };
|
|
1547
|
-
if (step.until && typeof step.until === 'object') out.until = step.until;
|
|
1548
|
-
return out;
|
|
1549
|
-
});
|
|
1550
|
-
|
|
1551
|
-
// 按 App 授权:只判「批入口包」——扫 app.open 步的包,再看 args.packageName,最后看最近前台包。
|
|
1552
|
-
// 批中途从 A 导航进被禁的 B,宿主在批下发前看不见,只能靠原生 block 兜底(见交付说明的盲区)。
|
|
1553
|
-
let entryPkg = '';
|
|
1554
|
-
for (const s of steps) {
|
|
1555
|
-
if (s.action === 'app.open' && s.args && typeof s.args.packageName === 'string' && s.args.packageName.trim()) {
|
|
1556
|
-
entryPkg = s.args.packageName.trim();
|
|
1557
|
-
break;
|
|
1558
|
-
}
|
|
1559
|
-
}
|
|
1560
|
-
if (!entryPkg && typeof args.packageName === 'string' && args.packageName.trim()) entryPkg = args.packageName.trim();
|
|
1561
|
-
if (!entryPkg) entryPkg = guardStateFor(ctx).lastPackage.get(sessionId) || '';
|
|
1562
|
-
if (!entryPkg) {
|
|
1563
|
-
try {
|
|
1564
|
-
const data = await run(service, deviceId, sessionId, 'screen.read', { includeText: true }, exec.signal);
|
|
1565
|
-
entryPkg = data && typeof data.packageName === 'string' ? data.packageName.trim() : '';
|
|
1566
|
-
} catch { /* 读不到就按未验证处理 */ }
|
|
1567
|
-
}
|
|
1568
|
-
if (!entryPkg) {
|
|
1569
|
-
return {
|
|
1570
|
-
ok: false,
|
|
1571
|
-
blocked: 'app-access-unverified',
|
|
1572
|
-
note: '没能确认现在前台是哪个 App,为安全起见这一批没有执行。先 phone_screen 看看当前停在哪,再继续。',
|
|
1573
|
-
};
|
|
1574
|
-
}
|
|
1575
|
-
const appBlocked = await appGate(ctx, sessionId, { packageName: entryPkg, action: 'batch', judged: null, exec });
|
|
1576
|
-
if (appBlocked && appBlocked.blocked) return appBlocked;
|
|
1577
|
-
|
|
1578
|
-
// 批里熔断**收钱 / 毁数据**这两类不可逆动作(payment / delete):批内没有确认的位置,
|
|
1579
|
-
// 这一步要用户亲自点一次同意。发送 / 提交不熔断 —— 它们是任务本身要做的事,靠节奏拉间隔。
|
|
1580
|
-
// ref-only 的 tap 没有 target 文字,从最近一屏按 ref 找回元素文字再判 —— 否则付款按钮
|
|
1581
|
-
// 用 {action:'tap',args:{ref}} 写进批里就能绕过熔断。
|
|
1582
|
-
let blockedAt = -1;
|
|
1583
|
-
let blockedReason = '';
|
|
1584
|
-
for (let i = 0; i < steps.length; i += 1) {
|
|
1585
|
-
const s = steps[i];
|
|
1586
|
-
let text = typeof s.args.target === 'string' ? s.args.target : (typeof s.args.text === 'string' ? s.args.text : '');
|
|
1587
|
-
let scanArgs = s.args;
|
|
1588
|
-
if (s.action === 'tap' && !text) {
|
|
1589
|
-
const ref = typeof s.args.ref === 'string' ? s.args.ref.trim() : '';
|
|
1590
|
-
if (ref) {
|
|
1591
|
-
const el = elementByRef(guardStateFor(ctx).lastElements.get(sessionId), ref);
|
|
1592
|
-
const label = el ? elementText(el).trim() : '';
|
|
1593
|
-
if (label) { text = label; scanArgs = { ...s.args, target: label }; }
|
|
1594
|
-
}
|
|
1595
|
-
}
|
|
1596
|
-
const judged = judgeIrreversible(s.action, scanArgs, text);
|
|
1597
|
-
if (judged && confirm.needsConfirmation(judged)) { blockedAt = i; blockedReason = judged.reason || ''; break; }
|
|
1598
|
-
}
|
|
1599
|
-
const runnable = blockedAt >= 0 ? steps.slice(0, blockedAt) : steps;
|
|
1600
|
-
|
|
1601
|
-
const notes = [mentionMismatch(sessionId, deviceId)];
|
|
1602
|
-
if (blockedAt === 0) {
|
|
1603
|
-
// 第一步就要确认:这一批没有能跑的部分。不抛错 —— 抛错会被读成「批量坏了」,
|
|
1604
|
-
// 而事实是「这一步得单独做」,如实把这一批的结果写成「停在第一步」更贴切。
|
|
1605
|
-
const only = {
|
|
1606
|
-
ok: true,
|
|
1607
|
-
steps: [],
|
|
1608
|
-
stoppedAt: 0,
|
|
1609
|
-
stopReason: 'blocked-irreversible',
|
|
1610
|
-
note: `第 1 步是付款 / 下单(${blockedReason}),批里不执行它。请把这一步单独做(phone_tap),它会走一次用户确认;其余步骤再另起一批。`,
|
|
1611
|
-
};
|
|
1612
|
-
return only;
|
|
1613
|
-
}
|
|
1614
|
-
if (blockedAt > 0) {
|
|
1615
|
-
notes.push(`第 ${blockedAt + 1} 步是付款 / 下单(${blockedReason}),没有放进这一批:它要在这一批之后单独做,单独走一次确认。`);
|
|
1616
|
-
}
|
|
1617
|
-
|
|
1618
|
-
const canBatch = supports(service, deviceId, 'batch');
|
|
1619
|
-
const stepResults = [];
|
|
1620
|
-
let stoppedAt = null;
|
|
1621
|
-
let stopReason = '';
|
|
1622
|
-
let finalData = null;
|
|
1623
|
-
|
|
1624
|
-
if (canBatch) {
|
|
1625
|
-
// 只把**停点之前**那几步交给手机。也可以把付款那步连同标记一起发过去、让手机自己停
|
|
1626
|
-
// (它认 `irreversible`),但那条路要求手机版本跟得上;发不过去的旧版本会直接把这步
|
|
1627
|
-
// 执行掉 —— 一次没人确认的付款不能押在「对方版本够新」上。切片在插件这边做,任何
|
|
1628
|
-
// 版本的手机都只会收到它该做的那几步。
|
|
1629
|
-
const batchArgs = {
|
|
1630
|
-
steps: runnable.map((s) => ({ action: s.action, args: s.args, ...(s.until ? { until: s.until } : {}) })),
|
|
1631
|
-
quiet: args.quiet !== false,
|
|
1632
|
-
// 节奏跟着批一起下去:mode 来自设置三档,place 来自 App 知识;手机侧在批循环里消费(协议 §1.2 / §3.3)。
|
|
1633
|
-
pacing: { mode: pacingModeOf(), place: batchPlaceOf(runnable) },
|
|
1634
|
-
};
|
|
1635
|
-
const data = await run(service, deviceId, sessionId, 'batch', batchArgs, exec.signal);
|
|
1636
|
-
finalData = data;
|
|
1637
|
-
const list = Array.isArray(data && data.steps) ? data.steps : [];
|
|
1638
|
-
for (const st of list) {
|
|
1639
|
-
const row = { index: st && st.index, action: st && st.action, ok: Boolean(st && st.ok === true) };
|
|
1640
|
-
if (st && Number.isFinite(st.waitedMs)) row.waitedMs = st.waitedMs;
|
|
1641
|
-
if (st && st.wait && typeof st.wait === 'object') row.wait = { met: st.wait.met === true, stopped: st.wait.stopped == null ? null : st.wait.stopped };
|
|
1642
|
-
if (st && typeof st.effect === 'string') row.effect = st.effect;
|
|
1643
|
-
if (st && st.error && typeof st.error === 'object') {
|
|
1644
|
-
row.error = {
|
|
1645
|
-
code: typeof st.error.code === 'string' ? st.error.code : 'failed',
|
|
1646
|
-
message: typeof st.error.message === 'string' ? st.error.message : '',
|
|
1647
|
-
};
|
|
1648
|
-
}
|
|
1649
|
-
stepResults.push(row);
|
|
1650
|
-
}
|
|
1651
|
-
if (data && data.stoppedAt != null) stoppedAt = data.stoppedAt;
|
|
1652
|
-
if (data && typeof data.stopReason === 'string' && data.stopReason) stopReason = data.stopReason;
|
|
1653
|
-
// 手机那边跑完了前面那几步、没别的原因停下:停点就是付款那一步(编号按原始 steps 算,
|
|
1654
|
-
// 因为切片是前缀,两边编号一致)。
|
|
1655
|
-
if (blockedAt >= 0 && stopReason === '') {
|
|
1656
|
-
stoppedAt = blockedAt;
|
|
1657
|
-
stopReason = 'blocked-irreversible';
|
|
1658
|
-
}
|
|
1659
|
-
} else {
|
|
1660
|
-
// 手机没报 batch 能力:退回逐步执行。慢一点,但任务能完成;并如实说一句。
|
|
1661
|
-
notes.push(`${unsupportedNote('一次多步(批量)')} 已改为逐步执行,会慢一些。`);
|
|
1662
|
-
const canNativeWait = supports(service, deviceId, 'screen.wait');
|
|
1663
|
-
for (let i = 0; i < runnable.length; i += 1) {
|
|
1664
|
-
if (i > 0) await sleep(betweenDelay());
|
|
1665
|
-
const s = runnable[i];
|
|
1666
|
-
try {
|
|
1667
|
-
await run(service, deviceId, sessionId, s.action, s.args, exec.signal);
|
|
1668
|
-
} catch (error) {
|
|
1669
|
-
const message = String((error && error.message) || error);
|
|
1670
|
-
const code = /不支持/.test(message) ? 'unsupported' : (/断开/.test(message) ? 'offline' : 'step-failed');
|
|
1671
|
-
stepResults.push({ index: i, action: s.action, ok: false, error: { code, message } });
|
|
1672
|
-
stoppedAt = i;
|
|
1673
|
-
stopReason = 'step-failed';
|
|
1674
|
-
break;
|
|
1675
|
-
}
|
|
1676
|
-
const row = { index: i, action: s.action, ok: true };
|
|
1677
|
-
if (s.until) {
|
|
1678
|
-
const w = await waitCondition(service, deviceId, sessionId, s.until, exec.signal, canNativeWait);
|
|
1679
|
-
row.waitedMs = w.waitedMs;
|
|
1680
|
-
row.wait = { met: w.met, stopped: w.stopped == null ? null : w.stopped };
|
|
1681
|
-
}
|
|
1682
|
-
stepResults.push(row);
|
|
1683
|
-
}
|
|
1684
|
-
try {
|
|
1685
|
-
finalData = await run(service, deviceId, sessionId, 'screen.read', { includeText: true }, exec.signal);
|
|
1686
|
-
} catch { /* 拿不到最终屏就给空,别把整批判成失败 */ }
|
|
1687
|
-
// 逐步执行这条路上停点由插件自己定:跑完了能跑的那几步、停在付款那一步之前。
|
|
1688
|
-
if (blockedAt >= 0 && stopReason === '') {
|
|
1689
|
-
stoppedAt = runnable.length;
|
|
1690
|
-
stopReason = 'blocked-irreversible';
|
|
1691
|
-
}
|
|
1692
|
-
}
|
|
1693
|
-
|
|
1694
|
-
const value = { ok: stopReason !== 'step-failed', steps: stepResults };
|
|
1695
|
-
if (stoppedAt !== null) value.stoppedAt = stoppedAt;
|
|
1696
|
-
if (stopReason) value.stopReason = stopReason;
|
|
1697
|
-
if (finalData && typeof finalData.packageName === 'string') value.packageName = textOf(finalData.packageName, MAX_TEXT);
|
|
1698
|
-
if (finalData && Array.isArray(finalData.elements)) value.elements = finalData.elements.slice(0, 200);
|
|
1699
|
-
if (finalData && Number.isFinite(finalData.revision)) value.revision = finalData.revision;
|
|
1700
|
-
// 批量结果同样附一次 App 用法知识:`noteFor` 的去重账与 phone_screen 是同一份,
|
|
1701
|
-
// 同一对话同一 App 不管先从哪条路看到,都只附一遍(协议 7.5)。
|
|
1702
|
-
if (phoneKnowledge && typeof phoneKnowledge.noteFor === 'function') {
|
|
1703
|
-
try {
|
|
1704
|
-
const knowledge = phoneKnowledge.noteFor(sessionId, finalData && finalData.packageName);
|
|
1705
|
-
if (knowledge) notes.push(knowledge);
|
|
1706
|
-
} catch { /* 知识是锦上添花,读坏了不影响这一批的结果 */ }
|
|
1707
|
-
}
|
|
1708
|
-
// 「教一次就学会」:这一批整批做成了、又不是付款那类被切开的,就把这一批学成一条路线草稿。
|
|
1709
|
-
// 只学真跑过的那几部(`runnable`),学歪的不写 —— 判据全在 `route-extract.js` 里。
|
|
1710
|
-
const learned = learnFromBatch({
|
|
1711
|
-
sessionId,
|
|
1712
|
-
steps: runnable,
|
|
1713
|
-
results: stepResults,
|
|
1714
|
-
packageName: (finalData && finalData.packageName) || packageOfBatch(runnable),
|
|
1715
|
-
stopped: stopReason !== '' && stopReason !== undefined,
|
|
1716
|
-
exec,
|
|
1717
|
-
ctx,
|
|
1718
|
-
});
|
|
1719
|
-
if (learned) notes.push(learned);
|
|
1720
|
-
const note = notes.filter((n) => typeof n === 'string' && n).join(' ');
|
|
1721
|
-
if (note) value.note = note;
|
|
1722
|
-
return value;
|
|
1723
|
-
},
|
|
1724
|
-
});
|
|
1725
|
-
|
|
1726
|
-
register({
|
|
1727
|
-
name: 'phone_wait',
|
|
1728
|
-
description: 'Wait until the screen reaches a condition, using the phone\'s accessibility events instead of polling. Use it after an action that loads something (a search, a page open) instead of taking repeated screenshots. Give at least one of appears / gone / app / stable. Returns met=true or met=false on timeout.',
|
|
1729
|
-
parameters: {
|
|
1730
|
-
appears: { type: 'string', description: 'Wait until an element containing this text appears (case-insensitive).' },
|
|
1731
|
-
gone: { type: 'string', description: 'Wait until this text is no longer on screen.' },
|
|
1732
|
-
app: { type: 'string', description: 'Wait until this package is in front.' },
|
|
1733
|
-
stable: { type: 'boolean', description: 'Wait until the screen stops changing.' },
|
|
1734
|
-
timeoutMs: { type: 'number', description: 'Max wait in ms, default 8000, max 20000.' },
|
|
1735
|
-
},
|
|
1736
|
-
output: {
|
|
1737
|
-
schema: {
|
|
1738
|
-
type: 'object',
|
|
1739
|
-
additionalProperties: false,
|
|
1740
|
-
properties: {
|
|
1741
|
-
met: { type: 'boolean' },
|
|
1742
|
-
stopped: { type: 'string' },
|
|
1743
|
-
waitedMs: { type: 'number' },
|
|
1744
|
-
note: { type: 'string' },
|
|
1745
|
-
},
|
|
1746
|
-
},
|
|
1747
|
-
render: (_args, value) => [{ type: 'text', text: value.met ? `条件成立(等了 ${value.waitedMs || 0}ms)。` : '等超时了,条件没成立。' }],
|
|
1748
|
-
},
|
|
1749
|
-
execute: async (args, exec) => {
|
|
1750
|
-
const sessionId = sessionOf(exec);
|
|
1751
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
1752
|
-
const until = {};
|
|
1753
|
-
if (typeof args.appears === 'string' && args.appears.trim()) until.appears = args.appears;
|
|
1754
|
-
if (typeof args.gone === 'string' && args.gone.trim()) until.gone = args.gone;
|
|
1755
|
-
if (typeof args.app === 'string' && args.app.trim()) until.app = args.app;
|
|
1756
|
-
if (args.stable === true) until.stable = true;
|
|
1757
|
-
until.timeoutMs = clampTimeoutMs(args.timeoutMs);
|
|
1758
|
-
if (until.appears === undefined && until.gone === undefined && until.app === undefined && until.stable !== true) {
|
|
1759
|
-
throw new Error('要等什么?给 appears / gone / app / stable 其中至少一个。');
|
|
1760
|
-
}
|
|
1761
|
-
const canNative = supports(service, deviceId, 'screen.wait');
|
|
1762
|
-
const w = await waitCondition(service, deviceId, sessionId, until, exec.signal, canNative);
|
|
1763
|
-
const value = { met: w.met };
|
|
1764
|
-
if (w.stopped != null) value.stopped = w.stopped;
|
|
1765
|
-
if (Number.isFinite(w.waitedMs)) value.waitedMs = w.waitedMs;
|
|
1766
|
-
const notes = [mentionMismatch(sessionId, deviceId)];
|
|
1767
|
-
if (!canNative) notes.push(`${unsupportedNote('等条件(screen.wait)')} 这次是轮询读屏等到的,会慢一些。`);
|
|
1768
|
-
const note = notes.filter(Boolean).join(' ');
|
|
1769
|
-
if (note) value.note = note;
|
|
1770
|
-
return value;
|
|
1771
|
-
},
|
|
1772
|
-
});
|
|
1773
|
-
|
|
1774
|
-
register({
|
|
1775
|
-
name: 'phone_gesture',
|
|
1776
|
-
description: 'Send a finger gesture the simple tools cannot express: a long press, a drag along a path, or a two-finger pinch. Coordinates are viewport percentages (x 0-100 left-to-right, y 0-100 top-to-bottom). Give 1-2 strokes; each stroke is a list of points; a long press is one point with holdMs 500-800; two strokes at once is a pinch.',
|
|
1777
|
-
parameters: {
|
|
1778
|
-
strokes: {
|
|
1779
|
-
type: 'array',
|
|
1780
|
-
description: '1-2 finger strokes, done at the same time.',
|
|
1781
|
-
items: {
|
|
1782
|
-
type: 'object',
|
|
1783
|
-
additionalProperties: true,
|
|
1784
|
-
properties: {
|
|
1785
|
-
points: {
|
|
1786
|
-
type: 'array',
|
|
1787
|
-
description: '2-32 points the finger moves through, each { x, y } in 0-100 percent.',
|
|
1788
|
-
items: {
|
|
1789
|
-
type: 'object',
|
|
1790
|
-
additionalProperties: true,
|
|
1791
|
-
properties: {
|
|
1792
|
-
x: { type: 'number', description: 'Horizontal position, 0-100 percent of screen width.' },
|
|
1793
|
-
y: { type: 'number', description: 'Vertical position, 0-100 percent of screen height.' },
|
|
1794
|
-
},
|
|
1795
|
-
},
|
|
1796
|
-
},
|
|
1797
|
-
holdMs: { type: 'number', description: 'How long to hold at the first point before moving, in ms. Use 500-800 for a long press.' },
|
|
1798
|
-
startMs: { type: 'number', description: 'Delay before this stroke starts, in ms (to stagger strokes).' },
|
|
1799
|
-
},
|
|
1800
|
-
},
|
|
1801
|
-
},
|
|
1802
|
-
},
|
|
1803
|
-
output: {
|
|
1804
|
-
schema: {
|
|
1805
|
-
type: 'object',
|
|
1806
|
-
additionalProperties: false,
|
|
1807
|
-
properties: {
|
|
1808
|
-
ok: { type: 'boolean' },
|
|
1809
|
-
packageName: { type: 'string' },
|
|
1810
|
-
elements: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
1811
|
-
blocked: { type: 'string' },
|
|
1812
|
-
note: { type: 'string' },
|
|
1813
|
-
},
|
|
1814
|
-
},
|
|
1815
|
-
render: (_args, value) => [{ type: 'text', text: value.ok === false ? `这一步没有执行:${value.note || '见说明'}。` : '已做手势。' }],
|
|
1816
|
-
},
|
|
1817
|
-
execute: async (args, exec) => {
|
|
1818
|
-
const sessionId = sessionOf(exec);
|
|
1819
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
1820
|
-
const raw = Array.isArray(args.strokes) ? args.strokes : [];
|
|
1821
|
-
if (raw.length < 1 || raw.length > 2) throw new Error('strokes 要给 1 到 2 段。');
|
|
1822
|
-
const strokes = raw.map((stroke, i) => {
|
|
1823
|
-
if (!stroke || typeof stroke !== 'object') throw new Error(`第 ${i + 1} 段手势格式不对,要是 { points: [...] }。`);
|
|
1824
|
-
const pts = Array.isArray(stroke.points) ? stroke.points : [];
|
|
1825
|
-
if (pts.length < 2 || pts.length > 32) throw new Error(`第 ${i + 1} 段手势要有 2 到 32 个点。`);
|
|
1826
|
-
const points = pts.map((p, j) => {
|
|
1827
|
-
const x = Number(p && p.x);
|
|
1828
|
-
const y = Number(p && p.y);
|
|
1829
|
-
if (!Number.isFinite(x) || !Number.isFinite(y) || x < 0 || x > 100 || y < 0 || y > 100) {
|
|
1830
|
-
throw new Error(`第 ${i + 1} 段第 ${j + 1} 个点要是 0 到 100 的百分比坐标。`);
|
|
1831
|
-
}
|
|
1832
|
-
return { x, y };
|
|
1833
|
-
});
|
|
1834
|
-
const out = { points };
|
|
1835
|
-
if (Number.isFinite(stroke.holdMs)) out.holdMs = Math.max(0, Math.min(5000, Math.round(stroke.holdMs)));
|
|
1836
|
-
if (Number.isFinite(stroke.startMs)) out.startMs = Math.max(0, Math.min(3000, Math.round(stroke.startMs)));
|
|
1837
|
-
return out;
|
|
1838
|
-
});
|
|
1839
|
-
const accessBlocked = await gateBeforeAction(sessionId, exec, { action: 'gesture', args: { strokes }, judged: null, deviceId, service });
|
|
1840
|
-
if (accessBlocked && accessBlocked.blocked) return accessBlocked;
|
|
1841
|
-
const data = await run(service, deviceId, sessionId, 'gesture', { strokes }, exec.signal);
|
|
1842
|
-
const notes = [mentionMismatch(sessionId, deviceId)];
|
|
1843
|
-
if (!supports(service, deviceId, 'gesture.multi')) notes.push(`${unsupportedNote('多指手势')} 单段手势仍会尝试,失败就以提示为准。`);
|
|
1844
|
-
const value = {
|
|
1845
|
-
ok: true,
|
|
1846
|
-
packageName: textOf(data && data.packageName, MAX_TEXT),
|
|
1847
|
-
elements: Array.isArray(data && data.elements) ? data.elements.slice(0, 120) : [],
|
|
1848
|
-
};
|
|
1849
|
-
const note = notes.filter(Boolean).join(' ');
|
|
1850
|
-
if (note) value.note = note;
|
|
1851
|
-
return value;
|
|
1852
|
-
},
|
|
1853
|
-
});
|
|
1854
|
-
|
|
1855
|
-
register({
|
|
1856
|
-
name: 'phone_open_link',
|
|
1857
|
-
description: 'Open a link or a system page by kind. kind=uri opens a web or app link (only http/https and common app schemes); kind=settings opens one standard Android settings page from a fixed list; kind=package opens an app\'s details page in system settings. Use it for system settings and app-info pages instead of hunting through menus. It cannot open arbitrary intents.',
|
|
1858
|
-
parameters: {
|
|
1859
|
-
kind: { type: 'string', required: true, enum: ['uri', 'settings', 'package'], description: 'What to open.' },
|
|
1860
|
-
uri: { type: 'string', description: 'For kind=uri: the link, e.g. https://example.com or a common app scheme.' },
|
|
1861
|
-
action: { type: 'string', description: 'For kind=settings: the Android settings action name, e.g. android.settings.WIFI_SETTINGS.' },
|
|
1862
|
-
packageName: { type: 'string', description: 'For kind=package (and app-details settings): the Android package name.' },
|
|
1863
|
-
},
|
|
1864
|
-
output: {
|
|
1865
|
-
schema: {
|
|
1866
|
-
type: 'object',
|
|
1867
|
-
additionalProperties: false,
|
|
1868
|
-
properties: {
|
|
1869
|
-
ok: { type: 'boolean' },
|
|
1870
|
-
packageName: { type: 'string' },
|
|
1871
|
-
elements: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
1872
|
-
blocked: { type: 'string' },
|
|
1873
|
-
note: { type: 'string' },
|
|
1874
|
-
},
|
|
1875
|
-
},
|
|
1876
|
-
render: (_args, value) => [{ type: 'text', text: value.ok === false ? `这一步没有执行:${value.note || '见说明'}。` : '已打开链接/页面。' }],
|
|
1877
|
-
},
|
|
1878
|
-
execute: async (args, exec) => {
|
|
1879
|
-
const sessionId = sessionOf(exec);
|
|
1880
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
1881
|
-
const kind = ['uri', 'settings', 'package'].includes(args.kind) ? args.kind : '';
|
|
1882
|
-
if (!kind) throw new Error('kind 只能是 uri / settings / package。');
|
|
1883
|
-
const linkArgs = { kind };
|
|
1884
|
-
if (kind === 'uri') {
|
|
1885
|
-
const uri = textOf(args.uri, 2000);
|
|
1886
|
-
if (!uri) throw new Error('kind=uri 时要给 uri。');
|
|
1887
|
-
const scheme = uri.includes(':') ? uri.split(':')[0].toLowerCase() : '';
|
|
1888
|
-
if (!URI_SCHEMES.has(scheme)) {
|
|
1889
|
-
throw new Error(`不打开这个 scheme(${scheme || '无'})。只放行 http / https / tel / mailto / sms / geo / market 这类常见入口。`);
|
|
1890
|
-
}
|
|
1891
|
-
linkArgs.uri = uri;
|
|
1892
|
-
} else if (kind === 'settings') {
|
|
1893
|
-
const action = textOf(args.action, 200);
|
|
1894
|
-
if (!SETTINGS_ACTIONS.has(action)) throw new Error(`这个设置入口不在白名单里:${action || '(空)'}。`);
|
|
1895
|
-
linkArgs.action = action;
|
|
1896
|
-
if (action === 'android.settings.APPLICATION_DETAILS_SETTINGS') {
|
|
1897
|
-
const pkg = textOf(args.packageName, 200);
|
|
1898
|
-
if (!/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$/.test(pkg)) throw new Error('打开某个 App 的详情页时要带合法的 packageName。');
|
|
1899
|
-
linkArgs.packageName = pkg;
|
|
1900
|
-
}
|
|
1901
|
-
} else {
|
|
1902
|
-
const pkg = textOf(args.packageName, 200);
|
|
1903
|
-
if (!/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$/.test(pkg)) throw new Error('packageName 看起来不像安卓包名。');
|
|
1904
|
-
linkArgs.packageName = pkg;
|
|
1905
|
-
}
|
|
1906
|
-
const accessBlocked = await gateBeforeAction(sessionId, exec, { action: 'app.link', args: linkArgs, judged: null, deviceId, service });
|
|
1907
|
-
if (accessBlocked && accessBlocked.blocked) return accessBlocked;
|
|
1908
|
-
const data = await run(service, deviceId, sessionId, 'app.link', linkArgs, exec.signal);
|
|
1909
|
-
const notes = [mentionMismatch(sessionId, deviceId)];
|
|
1910
|
-
if (!supports(service, deviceId, 'app.link')) notes.push(unsupportedNote('按类别打开链接(app.link)'));
|
|
1911
|
-
const value = {
|
|
1912
|
-
ok: true,
|
|
1913
|
-
packageName: textOf(data && data.packageName, MAX_TEXT),
|
|
1914
|
-
elements: Array.isArray(data && data.elements) ? data.elements.slice(0, 120) : [],
|
|
1915
|
-
};
|
|
1916
|
-
const note = notes.filter(Boolean).join(' ');
|
|
1917
|
-
if (note) value.note = note;
|
|
1918
|
-
return value;
|
|
1919
|
-
},
|
|
1920
|
-
});
|
|
1921
|
-
|
|
1922
|
-
register({
|
|
1923
|
-
name: 'phone_scroll_to',
|
|
1924
|
-
description: 'Scroll the screen until an element containing the given text is visible, then return its ref so you can tap it. It reads and swipes at most 8 times. Use it for a long list or search results when the target is not on the current screen; do not use it to read a whole page (use phone_screen). If it returns found=false, the text was not reached — say so rather than guessing.',
|
|
1925
|
-
parameters: {
|
|
1926
|
-
text: { type: 'string', required: true, description: 'Text on the element to scroll to (case-insensitive substring).' },
|
|
1927
|
-
direction: { type: 'string', enum: ['up', 'down'], description: 'Where the target is: down means scroll down to see lower content (default down).' },
|
|
1928
|
-
maxScrolls: { type: 'integer', description: 'How many swipes to try at most, 1-8 (default 8).' },
|
|
1929
|
-
},
|
|
1930
|
-
output: {
|
|
1931
|
-
schema: {
|
|
1932
|
-
type: 'object',
|
|
1933
|
-
additionalProperties: false,
|
|
1934
|
-
properties: {
|
|
1935
|
-
found: { type: 'boolean' },
|
|
1936
|
-
ref: { type: 'string' },
|
|
1937
|
-
text: { type: 'string' },
|
|
1938
|
-
packageName: { type: 'string' },
|
|
1939
|
-
scrolls: { type: 'number' },
|
|
1940
|
-
elements: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
1941
|
-
note: { type: 'string' },
|
|
1942
|
-
},
|
|
1943
|
-
},
|
|
1944
|
-
render: (_args, value) => [{ type: 'text', text: value.found ? `找到了(${value.text || value.ref})。` : '滚到头也没找到。' }],
|
|
1945
|
-
},
|
|
1946
|
-
execute: async (args, exec) => {
|
|
1947
|
-
const sessionId = sessionOf(exec);
|
|
1948
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
1949
|
-
const query = textOf(args.text, 200);
|
|
1950
|
-
if (!query) throw new Error('要滚到哪个元素?给 text(元素上的文字)。');
|
|
1951
|
-
const direction = args.direction === 'up' ? 'up' : 'down';
|
|
1952
|
-
const maxScrolls = Number.isInteger(args.maxScrolls) ? Math.min(8, Math.max(1, args.maxScrolls)) : 8;
|
|
1953
|
-
const needle = query.toLowerCase();
|
|
1954
|
-
let found = null;
|
|
1955
|
-
let scrolls = 0;
|
|
1956
|
-
let packageName = '';
|
|
1957
|
-
let lastSig = '';
|
|
1958
|
-
let unchanged = 0;
|
|
1959
|
-
let elements = [];
|
|
1960
|
-
for (let i = 0; ; i += 1) {
|
|
1961
|
-
const data = await run(service, deviceId, sessionId, 'screen.read', { includeText: true }, exec.signal);
|
|
1962
|
-
packageName = textOf(data && data.packageName, MAX_TEXT) || packageName;
|
|
1963
|
-
elements = Array.isArray(data && data.elements) ? data.elements : [];
|
|
1964
|
-
found = elements.find((el) => elementText(el).toLowerCase().includes(needle)) || null;
|
|
1965
|
-
if (found) break;
|
|
1966
|
-
const sig = screenSignature({ packageName: data && data.packageName, elements });
|
|
1967
|
-
unchanged = sig === lastSig ? unchanged + 1 : 0;
|
|
1968
|
-
lastSig = sig;
|
|
1969
|
-
if (unchanged >= 2 || scrolls >= maxScrolls) break;
|
|
1970
|
-
await run(service, deviceId, sessionId, 'swipe', { direction, amount: 0.7 }, exec.signal);
|
|
1971
|
-
scrolls += 1;
|
|
1972
|
-
}
|
|
1973
|
-
const notes = [mentionMismatch(sessionId, deviceId)];
|
|
1974
|
-
if (!found) notes.push(`滚了 ${scrolls} 次也没找到「${query}」,如实说没找到,别猜它在哪。`);
|
|
1975
|
-
const value = { found: Boolean(found), scrolls, packageName, elements: elements.slice(0, 120) };
|
|
1976
|
-
if (found && found.ref) value.ref = String(found.ref);
|
|
1977
|
-
if (found) value.text = elementText(found).slice(0, MAX_TEXT);
|
|
1978
|
-
const note = notes.filter(Boolean).join(' ');
|
|
1979
|
-
if (note) value.note = note;
|
|
1980
|
-
return value;
|
|
1981
|
-
},
|
|
1982
|
-
});
|
|
1983
|
-
|
|
1984
|
-
// ── 结构化:提取 / 查询 / 查找 / 采集 / 滚轮 ──────────────────────────────
|
|
1985
|
-
|
|
1986
|
-
register({
|
|
1987
|
-
name: 'phone_extract',
|
|
1988
|
-
description: 'Extract structured data from the current screen in one read on the phone. mode=text pulls visible text; mode=list groups a scrollable list/recycler into rows with bounds and parents; mode=form returns only editable fields (secret fields show a boolean, never the value). It reads the accessibility tree on the phone, so list rows beyond the first 160 elements come back with bounds but no tappable ref (best-effort).',
|
|
1989
|
-
parameters: {
|
|
1990
|
-
mode: { type: 'string', enum: ['text', 'list', 'form'], description: 'What to extract: text, list rows, or form fields.' },
|
|
1991
|
-
maxItems: { type: 'integer', description: 'Maximum records, 1-200 (default 100).' },
|
|
1992
|
-
},
|
|
1993
|
-
output: {
|
|
1994
|
-
schema: {
|
|
1995
|
-
type: 'object',
|
|
1996
|
-
additionalProperties: false,
|
|
1997
|
-
properties: {
|
|
1998
|
-
ok: { type: 'boolean' },
|
|
1999
|
-
mode: { type: 'string' },
|
|
2000
|
-
items: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
2001
|
-
count: { type: 'number' },
|
|
2002
|
-
truncated: { type: 'boolean' },
|
|
2003
|
-
packageName: { type: 'string' },
|
|
2004
|
-
revision: { type: 'number' },
|
|
2005
|
-
note: { type: 'string' },
|
|
2006
|
-
},
|
|
2007
|
-
},
|
|
2008
|
-
render: (_args, value) => [{ type: 'text', text: `提取了 ${value.count || 0} 条(${value.mode || ''})${value.truncated ? ',已截断' : ''}。` }],
|
|
2009
|
-
},
|
|
2010
|
-
execute: async (args, exec) => {
|
|
2011
|
-
const sessionId = sessionOf(exec);
|
|
2012
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
2013
|
-
const mode = ['text', 'list', 'form'].includes(args.mode) ? args.mode : 'text';
|
|
2014
|
-
const maxItems = Number.isInteger(args.maxItems) ? Math.min(200, Math.max(1, args.maxItems)) : 100;
|
|
2015
|
-
const data = await run(service, deviceId, sessionId, 'extract', { mode, maxItems }, exec.signal);
|
|
2016
|
-
const notes = [mentionMismatch(sessionId, deviceId)];
|
|
2017
|
-
if (!supports(service, deviceId, 'extract')) notes.push(unsupportedNote('结构化提取(extract)'));
|
|
2018
|
-
const value = {
|
|
2019
|
-
ok: true,
|
|
2020
|
-
mode,
|
|
2021
|
-
items: Array.isArray(data && data.items) ? data.items : [],
|
|
2022
|
-
count: Number.isFinite(data && data.count) ? data.count : (Array.isArray(data && data.items) ? data.items.length : 0),
|
|
2023
|
-
truncated: Boolean(data && data.truncated),
|
|
2024
|
-
};
|
|
2025
|
-
if (data && typeof data.packageName === 'string' && data.packageName) value.packageName = textOf(data.packageName, MAX_TEXT);
|
|
2026
|
-
if (data && Number.isFinite(data.revision)) value.revision = data.revision;
|
|
2027
|
-
const note = notes.filter(Boolean).join(' ');
|
|
2028
|
-
if (note) value.note = note;
|
|
2029
|
-
return value;
|
|
2030
|
-
},
|
|
2031
|
-
});
|
|
2032
|
-
|
|
2033
|
-
register({
|
|
2034
|
-
name: 'phone_query',
|
|
2035
|
-
description: 'Find controls on the current screen by text, resource id, or role without scrolling, returning ref, bounds, parents and whether each is clickable/editable. Use it when the same text appears many places or a control has no visible label. limit up to 100 (default 30).',
|
|
2036
|
-
parameters: {
|
|
2037
|
-
text: { type: 'string', description: 'Case-insensitive text or accessibility description to find.' },
|
|
2038
|
-
resourceId: { type: 'string', description: 'Full or partial Android resource id to find.' },
|
|
2039
|
-
role: { type: 'string', description: 'Full or partial role/class to find.' },
|
|
2040
|
-
limit: { type: 'integer', description: 'Maximum results, 1-100 (default 30).' },
|
|
2041
|
-
},
|
|
2042
|
-
output: {
|
|
2043
|
-
schema: {
|
|
2044
|
-
type: 'object',
|
|
2045
|
-
additionalProperties: false,
|
|
2046
|
-
properties: {
|
|
2047
|
-
ok: { type: 'boolean' },
|
|
2048
|
-
total: { type: 'number' },
|
|
2049
|
-
truncated: { type: 'boolean' },
|
|
2050
|
-
matches: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
2051
|
-
packageName: { type: 'string' },
|
|
2052
|
-
revision: { type: 'number' },
|
|
2053
|
-
note: { type: 'string' },
|
|
2054
|
-
},
|
|
2055
|
-
},
|
|
2056
|
-
render: (_args, value) => [{ type: 'text', text: `找到 ${value.total || 0} 个匹配(返回 ${Array.isArray(value.matches) ? value.matches.length : 0} 条)。` }],
|
|
2057
|
-
},
|
|
2058
|
-
execute: async (args, exec) => {
|
|
2059
|
-
const sessionId = sessionOf(exec);
|
|
2060
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
2061
|
-
const queryArgs = {};
|
|
2062
|
-
if (typeof args.text === 'string' && args.text.trim()) queryArgs.text = textOf(args.text, 200);
|
|
2063
|
-
if (typeof args.resourceId === 'string' && args.resourceId.trim()) queryArgs.resourceId = textOf(args.resourceId, 200);
|
|
2064
|
-
if (typeof args.role === 'string' && args.role.trim()) queryArgs.role = textOf(args.role, 100);
|
|
2065
|
-
if (!queryArgs.text && !queryArgs.resourceId && !queryArgs.role) {
|
|
2066
|
-
throw new Error('要查什么?给 text / resourceId / role 其中至少一个。');
|
|
2067
|
-
}
|
|
2068
|
-
queryArgs.limit = Number.isInteger(args.limit) ? Math.min(100, Math.max(1, args.limit)) : 30;
|
|
2069
|
-
const data = await run(service, deviceId, sessionId, 'query', queryArgs, exec.signal);
|
|
2070
|
-
const notes = [mentionMismatch(sessionId, deviceId)];
|
|
2071
|
-
if (!supports(service, deviceId, 'query')) notes.push(unsupportedNote('按字段查询(query)'));
|
|
2072
|
-
const value = {
|
|
2073
|
-
ok: true,
|
|
2074
|
-
total: Number.isFinite(data && data.total) ? data.total : 0,
|
|
2075
|
-
truncated: Boolean(data && data.truncated),
|
|
2076
|
-
matches: Array.isArray(data && data.matches) ? data.matches : [],
|
|
2077
|
-
};
|
|
2078
|
-
if (data && typeof data.packageName === 'string' && data.packageName) value.packageName = textOf(data.packageName, MAX_TEXT);
|
|
2079
|
-
if (data && Number.isFinite(data.revision)) value.revision = data.revision;
|
|
2080
|
-
const note = notes.filter(Boolean).join(' ');
|
|
2081
|
-
if (note) value.note = note;
|
|
2082
|
-
return value;
|
|
2083
|
-
},
|
|
2084
|
-
});
|
|
2085
|
-
|
|
2086
|
-
register({
|
|
2087
|
-
name: 'phone_find',
|
|
2088
|
-
description: 'Scroll on the phone until an element matching text/resourceId/role is visible, then return its ref. It reads, matches, swipes and waits for the screen to settle in a loop on the phone. Stopped reason is one of found / screen_needs_review / app_switched / content_unchanged / scroll_limit / read_failed. maxScrolls 1-200 (default 30).',
|
|
2089
|
-
parameters: {
|
|
2090
|
-
text: { type: 'string', description: 'Text or accessibility description to find.' },
|
|
2091
|
-
resourceId: { type: 'string', description: 'Full or partial Android resource id.' },
|
|
2092
|
-
role: { type: 'string', description: 'Full or partial role/class.' },
|
|
2093
|
-
direction: { type: 'string', enum: ['up', 'down'], description: 'Where the target is: down means scroll down to see lower content (default down).' },
|
|
2094
|
-
maxScrolls: { type: 'integer', description: 'Maximum scrolls, 1-200 (default 30).' },
|
|
2095
|
-
},
|
|
2096
|
-
output: {
|
|
2097
|
-
schema: {
|
|
2098
|
-
type: 'object',
|
|
2099
|
-
additionalProperties: false,
|
|
2100
|
-
properties: {
|
|
2101
|
-
ok: { type: 'boolean' },
|
|
2102
|
-
found: { type: 'boolean' },
|
|
2103
|
-
stoppedBecause: { type: 'string' },
|
|
2104
|
-
scrolls: { type: 'number' },
|
|
2105
|
-
match: { type: 'object', additionalProperties: true },
|
|
2106
|
-
packageName: { type: 'string' },
|
|
2107
|
-
revision: { type: 'number' },
|
|
2108
|
-
note: { type: 'string' },
|
|
2109
|
-
},
|
|
2110
|
-
},
|
|
2111
|
-
render: (_args, value) => [{ type: 'text', text: value.found ? '找到了。' : `没找到(${value.stoppedBecause || '未知'},滚了 ${value.scrolls || 0} 次)。` }],
|
|
2112
|
-
},
|
|
2113
|
-
execute: async (args, exec) => {
|
|
2114
|
-
const sessionId = sessionOf(exec);
|
|
2115
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
2116
|
-
const findArgs = { direction: args.direction === 'up' ? 'up' : 'down' };
|
|
2117
|
-
if (typeof args.text === 'string' && args.text.trim()) findArgs.text = textOf(args.text, 200);
|
|
2118
|
-
if (typeof args.resourceId === 'string' && args.resourceId.trim()) findArgs.resourceId = textOf(args.resourceId, 200);
|
|
2119
|
-
if (typeof args.role === 'string' && args.role.trim()) findArgs.role = textOf(args.role, 100);
|
|
2120
|
-
if (!findArgs.text && !findArgs.resourceId && !findArgs.role) throw new Error('要找什么?给 text / resourceId / role 其中至少一个。');
|
|
2121
|
-
findArgs.maxScrolls = Number.isInteger(args.maxScrolls) ? Math.min(200, Math.max(1, args.maxScrolls)) : 30;
|
|
2122
|
-
const data = await run(service, deviceId, sessionId, 'find', findArgs, exec.signal);
|
|
2123
|
-
const notes = [mentionMismatch(sessionId, deviceId)];
|
|
2124
|
-
if (!supports(service, deviceId, 'find')) notes.push(unsupportedNote('滚动查找(find)'));
|
|
2125
|
-
const value = {
|
|
2126
|
-
ok: Boolean(data && data.found),
|
|
2127
|
-
found: Boolean(data && data.found),
|
|
2128
|
-
stoppedBecause: textOf(data && data.stoppedBecause, 40) || 'scroll_limit',
|
|
2129
|
-
scrolls: Number.isFinite(data && data.scrolls) ? data.scrolls : 0,
|
|
2130
|
-
};
|
|
2131
|
-
if (data && data.match && typeof data.match === 'object') value.match = data.match;
|
|
2132
|
-
if (data && typeof data.packageName === 'string' && data.packageName) value.packageName = textOf(data.packageName, MAX_TEXT);
|
|
2133
|
-
if (data && Number.isFinite(data.revision)) value.revision = data.revision;
|
|
2134
|
-
if (!value.found) notes.push(`滚了 ${value.scrolls} 次也没找到(${value.stoppedBecause}),如实说没找到,别猜它在哪。`);
|
|
2135
|
-
const note = notes.filter(Boolean).join(' ');
|
|
2136
|
-
if (note) value.note = note;
|
|
2137
|
-
return value;
|
|
2138
|
-
},
|
|
2139
|
-
});
|
|
2140
|
-
|
|
2141
|
-
register({
|
|
2142
|
-
name: 'phone_collect',
|
|
2143
|
-
description: 'Scroll 1-30 screens and merge the text across them with de-duplication on the phone, returning one merged list. Use it to read a long list or chat without one round-trip per screen. Has both a maxItems and a 50KB byte cap.',
|
|
2144
|
-
parameters: {
|
|
2145
|
-
direction: { type: 'string', enum: ['up', 'down'], description: 'Direction of newer content: up or down (default down).' },
|
|
2146
|
-
pages: { type: 'integer', description: 'Maximum screens to inspect, 1-30 (default 10).' },
|
|
2147
|
-
maxItems: { type: 'integer', description: 'Maximum lines to return, 1-1000 (default 300).' },
|
|
2148
|
-
fromY: { type: 'integer', description: 'Top of the content area, normalized 0-999 (default 50).' },
|
|
2149
|
-
toY: { type: 'integer', description: 'Bottom of the content area, normalized 0-999 (default 950).' },
|
|
2150
|
-
},
|
|
2151
|
-
output: {
|
|
2152
|
-
schema: {
|
|
2153
|
-
type: 'object',
|
|
2154
|
-
additionalProperties: false,
|
|
2155
|
-
properties: {
|
|
2156
|
-
ok: { type: 'boolean' },
|
|
2157
|
-
pagesInspected: { type: 'number' },
|
|
2158
|
-
scrolls: { type: 'number' },
|
|
2159
|
-
stoppedBecause: { type: 'string' },
|
|
2160
|
-
count: { type: 'number' },
|
|
2161
|
-
items: { type: 'array', items: { type: 'string' } },
|
|
2162
|
-
text: { type: 'string' },
|
|
2163
|
-
truncated: { type: 'boolean' },
|
|
2164
|
-
currentApp: { type: 'string' },
|
|
2165
|
-
note: { type: 'string' },
|
|
2166
|
-
},
|
|
2167
|
-
},
|
|
2168
|
-
render: (_args, value) => [{ type: 'text', text: `采集了 ${value.pagesInspected || 0} 屏,合并 ${value.count || 0} 行(${value.stoppedBecause || ''})${value.truncated ? ',已截断' : ''}。` }],
|
|
2169
|
-
},
|
|
2170
|
-
execute: async (args, exec) => {
|
|
2171
|
-
const sessionId = sessionOf(exec);
|
|
2172
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
2173
|
-
const collectArgs = {
|
|
2174
|
-
direction: args.direction === 'up' ? 'up' : 'down',
|
|
2175
|
-
pages: Number.isInteger(args.pages) ? Math.min(30, Math.max(1, args.pages)) : 10,
|
|
2176
|
-
maxItems: Number.isInteger(args.maxItems) ? Math.min(1000, Math.max(1, args.maxItems)) : 300,
|
|
2177
|
-
fromY: Number.isInteger(args.fromY) ? Math.min(999, Math.max(0, args.fromY)) : 50,
|
|
2178
|
-
toY: Number.isInteger(args.toY) ? Math.min(999, Math.max(0, args.toY)) : 950,
|
|
2179
|
-
};
|
|
2180
|
-
const data = await run(service, deviceId, sessionId, 'collect', collectArgs, exec.signal);
|
|
2181
|
-
const notes = [mentionMismatch(sessionId, deviceId)];
|
|
2182
|
-
if (!supports(service, deviceId, 'collect')) notes.push(unsupportedNote('多屏采集(collect)'));
|
|
2183
|
-
const items = Array.isArray(data && data.items) ? data.items.map((x) => String(x)) : [];
|
|
2184
|
-
const value = {
|
|
2185
|
-
ok: Boolean(data && data.ok !== false),
|
|
2186
|
-
pagesInspected: Number.isFinite(data && data.pagesInspected) ? data.pagesInspected : 0,
|
|
2187
|
-
scrolls: Number.isFinite(data && data.scrolls) ? data.scrolls : 0,
|
|
2188
|
-
stoppedBecause: textOf(data && data.stoppedBecause, 40) || 'page_limit',
|
|
2189
|
-
count: Number.isFinite(data && data.count) ? data.count : items.length,
|
|
2190
|
-
items,
|
|
2191
|
-
text: textOf(data && data.text, 50_000) || items.join('\n'),
|
|
2192
|
-
truncated: Boolean(data && data.truncated),
|
|
2193
|
-
};
|
|
2194
|
-
if (data && typeof data.currentApp === 'string' && data.currentApp) value.currentApp = textOf(data.currentApp, MAX_TEXT);
|
|
2195
|
-
const note = notes.filter(Boolean).join(' ');
|
|
2196
|
-
if (note) value.note = note;
|
|
2197
|
-
return value;
|
|
2198
|
-
},
|
|
2199
|
-
});
|
|
2200
|
-
|
|
2201
|
-
register({
|
|
2202
|
-
name: 'phone_wheel',
|
|
2203
|
-
description: 'Turn a wheel picker (time / date / region) straight to a value in one call. The phone reads the column, scrolls or drags, and reads back to verify. Give ref (from phone_screen) and value. Error codes: not_a_wheel, wheel_at_end, wheel_unreadable, wheel_not_moving.',
|
|
2204
|
-
parameters: {
|
|
2205
|
-
ref: { type: 'string', required: true, description: 'Element ref of the wheel column (from phone_screen).' },
|
|
2206
|
-
value: { type: 'string', required: true, description: 'The value to reach, e.g. "14", "30", "November".' },
|
|
2207
|
-
},
|
|
2208
|
-
output: {
|
|
2209
|
-
schema: {
|
|
2210
|
-
type: 'object',
|
|
2211
|
-
additionalProperties: false,
|
|
2212
|
-
properties: {
|
|
2213
|
-
ok: { type: 'boolean' },
|
|
2214
|
-
reached: { type: 'boolean' },
|
|
2215
|
-
target: { type: 'string' },
|
|
2216
|
-
value: { type: 'string' },
|
|
2217
|
-
from: { type: 'string' },
|
|
2218
|
-
attempts: { type: 'number' },
|
|
2219
|
-
method: { type: 'string' },
|
|
2220
|
-
error: { type: 'object', additionalProperties: true },
|
|
2221
|
-
effect: { type: 'string' },
|
|
2222
|
-
packageName: { type: 'string' },
|
|
2223
|
-
elements: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
2224
|
-
blocked: { type: 'string' },
|
|
2225
|
-
note: { type: 'string' },
|
|
2226
|
-
},
|
|
2227
|
-
},
|
|
2228
|
-
render: (_args, value) => [{ type: 'text', text: value.ok === false && value.blocked ? `这一步没有执行:${value.note || '见说明'}。` : (value.reached ? `已转到 ${value.value || value.target}。` : `没转到位:${value.error ? value.error.code : '未知'}。`) }],
|
|
2229
|
-
},
|
|
2230
|
-
execute: async (args, exec) => {
|
|
2231
|
-
const sessionId = sessionOf(exec);
|
|
2232
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
2233
|
-
const ref = textOf(args.ref, 40);
|
|
2234
|
-
const target = textOf(args.value, 100);
|
|
2235
|
-
if (!ref) throw new Error('给滚轮那一列的 ref(phone_screen 里的编号)。');
|
|
2236
|
-
if (!target) throw new Error('要转到哪个值?给 value。');
|
|
2237
|
-
const wheelArgs = { ref, value: target };
|
|
2238
|
-
const accessBlocked = await gateBeforeAction(sessionId, exec, { action: 'wheel.set', args: wheelArgs, judged: null, deviceId, service });
|
|
2239
|
-
if (accessBlocked && accessBlocked.blocked) return accessBlocked;
|
|
2240
|
-
const data = await run(service, deviceId, sessionId, 'wheel.set', wheelArgs, exec.signal);
|
|
2241
|
-
const notes = [mentionMismatch(sessionId, deviceId)];
|
|
2242
|
-
if (!supports(service, deviceId, 'wheel.set')) notes.push(unsupportedNote('滚轮选择器(wheel.set)'));
|
|
2243
|
-
const value = {
|
|
2244
|
-
ok: Boolean(data && data.reached),
|
|
2245
|
-
reached: Boolean(data && data.reached),
|
|
2246
|
-
target,
|
|
2247
|
-
attempts: Number.isFinite(data && data.attempts) ? data.attempts : 0,
|
|
2248
|
-
method: textOf(data && data.method, 20) || 'none',
|
|
2249
|
-
};
|
|
2250
|
-
if (data && typeof data.value === 'string') value.value = data.value;
|
|
2251
|
-
if (data && typeof data.from === 'string') value.from = data.from;
|
|
2252
|
-
if (data && data.error && typeof data.error === 'object') value.error = data.error;
|
|
2253
|
-
if (data && typeof data.effect === 'string') value.effect = data.effect;
|
|
2254
|
-
if (data && typeof data.packageName === 'string' && data.packageName) value.packageName = textOf(data.packageName, MAX_TEXT);
|
|
2255
|
-
if (data && Array.isArray(data.elements)) value.elements = data.elements.slice(0, 120);
|
|
2256
|
-
const note = notes.filter(Boolean).join(' ');
|
|
2257
|
-
if (note) value.note = note;
|
|
2258
|
-
return value;
|
|
2259
|
-
},
|
|
2260
|
-
});
|
|
2261
|
-
|
|
2262
|
-
// ── 分享文字 / 系统动作 / App 去留 ────────────────────────────────────────
|
|
2263
|
-
|
|
2264
|
-
register({
|
|
2265
|
-
name: 'phone_share_text',
|
|
2266
|
-
description: 'Share a piece of text to an app via ACTION_SEND (text/plain), landing on that app\'s share page. Parameters are only the package and the text.',
|
|
2267
|
-
parameters: {
|
|
2268
|
-
packageName: { type: 'string', required: true, description: 'Android package name of the app to share into.' },
|
|
2269
|
-
text: { type: 'string', required: true, description: 'The text to share.' },
|
|
2270
|
-
},
|
|
2271
|
-
output: {
|
|
2272
|
-
schema: {
|
|
2273
|
-
type: 'object',
|
|
2274
|
-
additionalProperties: false,
|
|
2275
|
-
properties: {
|
|
2276
|
-
ok: { type: 'boolean' },
|
|
2277
|
-
packageName: { type: 'string' },
|
|
2278
|
-
handledBy: { type: 'string' },
|
|
2279
|
-
effect: { type: 'string' },
|
|
2280
|
-
elements: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
2281
|
-
blocked: { type: 'string' },
|
|
2282
|
-
note: { type: 'string' },
|
|
2283
|
-
},
|
|
2284
|
-
},
|
|
2285
|
-
render: (_args, value) => [{ type: 'text', text: value.ok === false ? `这一步没有执行:${value.note || '见说明'}。` : `已把文字分享到 ${value.packageName || '那个 App'}。` }],
|
|
2286
|
-
},
|
|
2287
|
-
execute: async (args, exec) => {
|
|
2288
|
-
const sessionId = sessionOf(exec);
|
|
2289
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
2290
|
-
const pkg = textOf(args.packageName, 200);
|
|
2291
|
-
if (!/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$/.test(pkg)) throw new Error('packageName 看起来不像安卓包名。');
|
|
2292
|
-
const body = textOf(args.text, 20_000);
|
|
2293
|
-
if (!body) throw new Error('要分享的文字是空的。');
|
|
2294
|
-
const accessBlocked = await gateBeforeAction(sessionId, exec, { action: 'share.text', args: { packageName: pkg }, judged: null, deviceId, service });
|
|
2295
|
-
if (accessBlocked && accessBlocked.blocked) return accessBlocked;
|
|
2296
|
-
const data = await run(service, deviceId, sessionId, 'share.text', { packageName: pkg, text: body }, exec.signal);
|
|
2297
|
-
const notes = [mentionMismatch(sessionId, deviceId)];
|
|
2298
|
-
if (!supports(service, deviceId, 'share.text')) notes.push(unsupportedNote('分享文字(share.text)'));
|
|
2299
|
-
const value = {
|
|
2300
|
-
ok: true,
|
|
2301
|
-
packageName: pkg,
|
|
2302
|
-
handledBy: textOf(data && data.share && data.share.handledBy, 200) || pkg,
|
|
2303
|
-
};
|
|
2304
|
-
if (data && typeof data.effect === 'string') value.effect = data.effect;
|
|
2305
|
-
if (data && Array.isArray(data.elements)) value.elements = data.elements.slice(0, 120);
|
|
2306
|
-
const note = notes.filter(Boolean).join(' ');
|
|
2307
|
-
if (note) value.note = note;
|
|
2308
|
-
return value;
|
|
2309
|
-
},
|
|
2310
|
-
});
|
|
2311
|
-
|
|
2312
|
-
const weekdayNames = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
|
|
2313
|
-
const systemNotes = (sessionId, deviceId, cap) => {
|
|
2314
|
-
const notes = [mentionMismatch(sessionId, deviceId)];
|
|
2315
|
-
if (!supports(service, deviceId, cap)) notes.push(unsupportedNote('这类系统动作'));
|
|
2316
|
-
return notes;
|
|
2317
|
-
};
|
|
2318
|
-
|
|
2319
|
-
register({
|
|
2320
|
-
name: 'phone_set_alarm',
|
|
2321
|
-
description: 'Set an alarm through the standard Android clock interface without touching its UI. If no clock app handles it, returns not-supported and you should fall back to operating the UI.',
|
|
2322
|
-
parameters: {
|
|
2323
|
-
hour: { type: 'integer', required: true, description: 'Hour of day, 0-23.' },
|
|
2324
|
-
minute: { type: 'integer', required: true, description: 'Minute, 0-59.' },
|
|
2325
|
-
label: { type: 'string', description: 'Optional label shown with the alarm.' },
|
|
2326
|
-
days: { type: 'array', items: { type: 'string' }, description: 'Optional repeat days: MON..SUN. Omit for a one-time alarm.' },
|
|
2327
|
-
vibrate: { type: 'boolean', description: 'Optional: vibrate when it rings.' },
|
|
2328
|
-
},
|
|
2329
|
-
output: {
|
|
2330
|
-
schema: {
|
|
2331
|
-
type: 'object',
|
|
2332
|
-
additionalProperties: false,
|
|
2333
|
-
properties: {
|
|
2334
|
-
ok: { type: 'boolean' },
|
|
2335
|
-
requested: { type: 'object', additionalProperties: true },
|
|
2336
|
-
handledBy: { type: 'string' },
|
|
2337
|
-
note: { type: 'string' },
|
|
2338
|
-
},
|
|
2339
|
-
},
|
|
2340
|
-
render: (_args, value) => [{ type: 'text', text: `已把闹钟交给 ${value.handledBy || '时钟 App'}。` }],
|
|
2341
|
-
},
|
|
2342
|
-
execute: async (args, exec) => {
|
|
2343
|
-
const sessionId = sessionOf(exec);
|
|
2344
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
2345
|
-
if (!Number.isInteger(args.hour) || args.hour < 0 || args.hour > 23) throw new Error('hour 要是 0-23 的整数。');
|
|
2346
|
-
if (!Number.isInteger(args.minute) || args.minute < 0 || args.minute > 59) throw new Error('minute 要是 0-59 的整数。');
|
|
2347
|
-
const payload = { hour: args.hour, minute: args.minute };
|
|
2348
|
-
if (typeof args.label === 'string' && args.label.trim()) payload.label = textOf(args.label, 100);
|
|
2349
|
-
if (Array.isArray(args.days) && args.days.length > 0) {
|
|
2350
|
-
const days = args.days.map((d) => {
|
|
2351
|
-
const idx = weekdayNames.indexOf(String(d).trim().toUpperCase().slice(0, 3));
|
|
2352
|
-
if (idx < 0) throw new Error(`days 里只能是 ${weekdayNames.join(' / ')}。`);
|
|
2353
|
-
return idx + 1;
|
|
2354
|
-
});
|
|
2355
|
-
payload.days = [...new Set(days)].sort((a, b) => a - b);
|
|
2356
|
-
}
|
|
2357
|
-
if (args.vibrate === true) payload.vibrate = true;
|
|
2358
|
-
const data = await run(service, deviceId, sessionId, 'system.alarm', payload, exec.signal);
|
|
2359
|
-
const value = { ok: true, requested: { time: `${String(args.hour).padStart(2, '0')}:${String(args.minute).padStart(2, '0')}` } };
|
|
2360
|
-
if (payload.label) value.requested.label = payload.label;
|
|
2361
|
-
const handledBy = textOf(data && data.system && data.system.handledBy, 200);
|
|
2362
|
-
if (handledBy) value.handledBy = handledBy;
|
|
2363
|
-
const note = systemNotes(sessionId, deviceId, 'system.alarm').filter(Boolean).join(' ');
|
|
2364
|
-
if (note) value.note = note;
|
|
2365
|
-
return value;
|
|
2366
|
-
},
|
|
2367
|
-
});
|
|
2368
|
-
|
|
2369
|
-
register({
|
|
2370
|
-
name: 'phone_set_timer',
|
|
2371
|
-
description: 'Start a timer through the standard Android clock interface without touching its UI. If no clock app handles it, returns not-supported and you should fall back to operating the UI.',
|
|
2372
|
-
parameters: {
|
|
2373
|
-
seconds: { type: 'integer', required: true, description: 'Length of the timer in seconds, 1-86400.' },
|
|
2374
|
-
label: { type: 'string', description: 'Optional label shown with the timer.' },
|
|
2375
|
-
},
|
|
2376
|
-
output: {
|
|
2377
|
-
schema: {
|
|
2378
|
-
type: 'object',
|
|
2379
|
-
additionalProperties: false,
|
|
2380
|
-
properties: {
|
|
2381
|
-
ok: { type: 'boolean' },
|
|
2382
|
-
requested: { type: 'object', additionalProperties: true },
|
|
2383
|
-
handledBy: { type: 'string' },
|
|
2384
|
-
note: { type: 'string' },
|
|
2385
|
-
},
|
|
2386
|
-
},
|
|
2387
|
-
render: (_args, value) => [{ type: 'text', text: `已把计时器交给 ${value.handledBy || '时钟 App'}。` }],
|
|
2388
|
-
},
|
|
2389
|
-
execute: async (args, exec) => {
|
|
2390
|
-
const sessionId = sessionOf(exec);
|
|
2391
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
2392
|
-
if (!Number.isInteger(args.seconds) || args.seconds < 1 || args.seconds > 86400) throw new Error('seconds 要是 1-86400 的整数。');
|
|
2393
|
-
const payload = { seconds: args.seconds };
|
|
2394
|
-
if (typeof args.label === 'string' && args.label.trim()) payload.label = textOf(args.label, 100);
|
|
2395
|
-
const data = await run(service, deviceId, sessionId, 'system.timer', payload, exec.signal);
|
|
2396
|
-
const value = { ok: true, requested: { seconds: args.seconds } };
|
|
2397
|
-
if (payload.label) value.requested.label = payload.label;
|
|
2398
|
-
const handledBy = textOf(data && data.system && data.system.handledBy, 200);
|
|
2399
|
-
if (handledBy) value.handledBy = handledBy;
|
|
2400
|
-
const note = systemNotes(sessionId, deviceId, 'system.timer').filter(Boolean).join(' ');
|
|
2401
|
-
if (note) value.note = note;
|
|
2402
|
-
return value;
|
|
2403
|
-
},
|
|
2404
|
-
});
|
|
2405
|
-
|
|
2406
|
-
register({
|
|
2407
|
-
name: 'phone_show_alarms',
|
|
2408
|
-
description: 'Open the clock app\'s alarm list on the phone so alarms can be inspected or edited there. If no clock app handles it, returns not-supported.',
|
|
2409
|
-
parameters: {},
|
|
2410
|
-
output: {
|
|
2411
|
-
schema: {
|
|
2412
|
-
type: 'object',
|
|
2413
|
-
additionalProperties: false,
|
|
2414
|
-
properties: {
|
|
2415
|
-
ok: { type: 'boolean' },
|
|
2416
|
-
handledBy: { type: 'string' },
|
|
2417
|
-
effect: { type: 'string' },
|
|
2418
|
-
elements: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
2419
|
-
note: { type: 'string' },
|
|
2420
|
-
},
|
|
2421
|
-
},
|
|
2422
|
-
render: (_args, value) => [{ type: 'text', text: `已打开闹钟列表(${value.handledBy || '时钟 App'})。` }],
|
|
2423
|
-
},
|
|
2424
|
-
execute: async (args, exec) => {
|
|
2425
|
-
const sessionId = sessionOf(exec);
|
|
2426
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
2427
|
-
const data = await run(service, deviceId, sessionId, 'system.show_alarms', {}, exec.signal);
|
|
2428
|
-
const value = { ok: true };
|
|
2429
|
-
const handledBy = textOf(data && data.system && data.system.handledBy, 200);
|
|
2430
|
-
if (handledBy) value.handledBy = handledBy;
|
|
2431
|
-
if (data && typeof data.effect === 'string') value.effect = data.effect;
|
|
2432
|
-
if (data && Array.isArray(data.elements)) value.elements = data.elements.slice(0, 120);
|
|
2433
|
-
const note = systemNotes(sessionId, deviceId, 'system.show_alarms').filter(Boolean).join(' ');
|
|
2434
|
-
if (note) value.note = note;
|
|
2435
|
-
return value;
|
|
2436
|
-
},
|
|
2437
|
-
});
|
|
2438
|
-
|
|
2439
|
-
register({
|
|
2440
|
-
name: 'phone_add_calendar_event',
|
|
2441
|
-
description: 'Open a pre-filled new-event page in the calendar app (nothing is saved until you tap save there). Standard Android Intent, no calendar permission needed. If no calendar app handles it, returns not-supported.',
|
|
2442
|
-
parameters: {
|
|
2443
|
-
title: { type: 'string', required: true, description: 'Event title.' },
|
|
2444
|
-
start: { type: 'string', required: true, description: 'Start as local date-time yyyy-MM-ddTHH:mm, or a date yyyy-MM-dd with allDay=true.' },
|
|
2445
|
-
end: { type: 'string', description: 'Optional end, same format as start. Defaults to one hour after start (one day for all-day).' },
|
|
2446
|
-
allDay: { type: 'boolean', description: 'All-day event (default false).' },
|
|
2447
|
-
location: { type: 'string', description: 'Optional location.' },
|
|
2448
|
-
description: { type: 'string', description: 'Optional notes.' },
|
|
2449
|
-
},
|
|
2450
|
-
output: {
|
|
2451
|
-
schema: {
|
|
2452
|
-
type: 'object',
|
|
2453
|
-
additionalProperties: false,
|
|
2454
|
-
properties: {
|
|
2455
|
-
ok: { type: 'boolean' },
|
|
2456
|
-
requested: { type: 'object', additionalProperties: true },
|
|
2457
|
-
handledBy: { type: 'string' },
|
|
2458
|
-
effect: { type: 'string' },
|
|
2459
|
-
elements: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
2460
|
-
note: { type: 'string' },
|
|
2461
|
-
},
|
|
2462
|
-
},
|
|
2463
|
-
render: (_args, value) => [{ type: 'text', text: `已打开新日程页(${value.handledBy || '日历 App'}),还没保存。` }],
|
|
2464
|
-
},
|
|
2465
|
-
execute: async (args, exec) => {
|
|
2466
|
-
const sessionId = sessionOf(exec);
|
|
2467
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
2468
|
-
const title = textOf(args.title, 200);
|
|
2469
|
-
if (!title) throw new Error('日程要有 title。');
|
|
2470
|
-
const allDay = args.allDay === true;
|
|
2471
|
-
const parseLocal = (raw) => {
|
|
2472
|
-
let s = String(raw || '').trim();
|
|
2473
|
-
if (!s) return null;
|
|
2474
|
-
if (/^\d{4}-\d{2}-\d{2}$/.test(s)) s += allDay ? 'T00:00' : 'T09:00';
|
|
2475
|
-
const ms = Date.parse(s);
|
|
2476
|
-
return Number.isFinite(ms) ? ms : null;
|
|
2477
|
-
};
|
|
2478
|
-
const beginMs = parseLocal(args.start);
|
|
2479
|
-
if (beginMs === null) throw new Error('start 要是 yyyy-MM-ddTHH:mm 或 yyyy-MM-dd。');
|
|
2480
|
-
let endMs = parseLocal(args.end);
|
|
2481
|
-
if (endMs === null || endMs <= beginMs) endMs = beginMs + (allDay ? 24 * 3_600_000 : 3_600_000);
|
|
2482
|
-
const payload = { title, beginMs, endMs, allDay };
|
|
2483
|
-
if (typeof args.location === 'string' && args.location.trim()) payload.location = textOf(args.location, 200);
|
|
2484
|
-
if (typeof args.description === 'string' && args.description.trim()) payload.description = textOf(args.description, 2000);
|
|
2485
|
-
const data = await run(service, deviceId, sessionId, 'system.calendar_insert', payload, exec.signal);
|
|
2486
|
-
const value = { ok: true, requested: { title, start: new Date(beginMs).toISOString().slice(0, 16).replace('T', ' ') } };
|
|
2487
|
-
if (allDay) value.requested.allDay = true;
|
|
2488
|
-
const handledBy = textOf(data && data.system && data.system.handledBy, 200);
|
|
2489
|
-
if (handledBy) value.handledBy = handledBy;
|
|
2490
|
-
if (data && typeof data.effect === 'string') value.effect = data.effect;
|
|
2491
|
-
if (data && Array.isArray(data.elements)) value.elements = data.elements.slice(0, 120);
|
|
2492
|
-
const note = systemNotes(sessionId, deviceId, 'system.calendar_insert').filter(Boolean).join(' ');
|
|
2493
|
-
if (note) value.note = note;
|
|
2494
|
-
return value;
|
|
2495
|
-
},
|
|
2496
|
-
});
|
|
2497
|
-
|
|
2498
|
-
register({
|
|
2499
|
-
name: 'phone_app_after_task',
|
|
2500
|
-
description: 'Decide whether an app should be left running or closed when the task ends, with a reason. It only records the mark; nothing is touched now. Default (when unmarked) is to keep a quiet app in the background and close one that is playing sound.',
|
|
2501
|
-
parameters: {
|
|
2502
|
-
packageName: { type: 'string', required: true, description: 'Exact package name of the app.' },
|
|
2503
|
-
action: { type: 'string', required: true, enum: ['keep', 'close'], description: 'keep: leave it running after the task (even if playing sound). close: close it when the task ends.' },
|
|
2504
|
-
reason: { type: 'string', required: true, description: 'Why, in a few words.' },
|
|
2505
|
-
user: { type: 'integer', description: 'Only for another copy of the app (clone / work profile): that copy\'s user value. Leave out for the main app.' },
|
|
2506
|
-
},
|
|
2507
|
-
output: {
|
|
2508
|
-
schema: {
|
|
2509
|
-
type: 'object',
|
|
2510
|
-
additionalProperties: false,
|
|
2511
|
-
properties: {
|
|
2512
|
-
ok: { type: 'boolean' },
|
|
2513
|
-
packageName: { type: 'string' },
|
|
2514
|
-
action: { type: 'string' },
|
|
2515
|
-
replaces: { type: 'string' },
|
|
2516
|
-
note: { type: 'string' },
|
|
2517
|
-
},
|
|
2518
|
-
},
|
|
2519
|
-
render: (_args, value) => [{ type: 'text', text: `${value.packageName || '这个 App'} 任务后${value.action === 'close' ? '关掉' : '留着'}。` }],
|
|
2520
|
-
},
|
|
2521
|
-
execute: async (args, exec) => {
|
|
2522
|
-
const sessionId = sessionOf(exec);
|
|
2523
|
-
const { deviceId, service } = targetOf(ctx, deps, sessionId);
|
|
2524
|
-
const pkg = textOf(args.packageName, 200);
|
|
2525
|
-
if (!/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$/.test(pkg)) throw new Error('packageName 看起来不像安卓包名。');
|
|
2526
|
-
if (args.action !== 'keep' && args.action !== 'close') throw new Error('action 只能是 keep / close。');
|
|
2527
|
-
const reason = textOf(args.reason, 200);
|
|
2528
|
-
if (!reason) throw new Error('给一句原因(reason)。');
|
|
2529
|
-
const payload = { packageName: pkg, action: args.action, reason };
|
|
2530
|
-
if (Number.isInteger(args.user)) payload.user = args.user;
|
|
2531
|
-
const data = await run(service, deviceId, sessionId, 'app.after_task', payload, exec.signal);
|
|
2532
|
-
const value = { ok: true, packageName: pkg, action: args.action };
|
|
2533
|
-
if (data && typeof data.replaces === 'string') value.replaces = data.replaces;
|
|
2534
|
-
const note = [mentionMismatch(sessionId, deviceId), '只记下了,任务结束时才按它处置,不会当场关掉。'].filter(Boolean).join(' ');
|
|
2535
|
-
if (note) value.note = note;
|
|
2536
|
-
return value;
|
|
2537
|
-
},
|
|
2538
|
-
});
|
|
2539
|
-
|
|
2540
|
-
register({
|
|
2541
|
-
name: 'phone_target',
|
|
2542
|
-
description: 'Show or change which phone this conversation operates. Without arguments it reports the binding and the phones currently connected. With a deviceId it rebinds — only do that when the user asked to switch phones.',
|
|
2543
|
-
parameters: {
|
|
2544
|
-
deviceId: { type: 'string', description: 'Rebind this conversation to that phone. Omit to just look.' },
|
|
2545
|
-
},
|
|
2546
|
-
output: {
|
|
2547
|
-
schema: {
|
|
2548
|
-
type: 'object',
|
|
2549
|
-
additionalProperties: false,
|
|
2550
|
-
properties: {
|
|
2551
|
-
deviceId: { type: 'string' },
|
|
2552
|
-
from: { type: 'string' },
|
|
2553
|
-
changed: { type: 'boolean' },
|
|
2554
|
-
devices: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
2555
|
-
note: { type: 'string' },
|
|
2556
|
-
},
|
|
2557
|
-
},
|
|
2558
|
-
render: (_args, value) => [{ type: 'text', text: value.deviceId ? `这条对话操作的是 ${value.deviceId}。` : '这条对话还没有指定手机。' }],
|
|
2559
|
-
},
|
|
2560
|
-
execute: async (args, exec) => {
|
|
2561
|
-
const sessionId = sessionOf(exec);
|
|
2562
|
-
const wanted = textOf(args.deviceId, 200);
|
|
2563
|
-
if (wanted) {
|
|
2564
|
-
const service = deps.getService();
|
|
2565
|
-
if (!service || !service.isOnline(wanted)) {
|
|
2566
|
-
throw new Error('那台手机现在没连上,先让用户在手机上打开 App 让连接恢复,再改绑。');
|
|
2567
|
-
}
|
|
2568
|
-
}
|
|
2569
|
-
const resolved = binding.resolveTarget(sessionId, wanted);
|
|
2570
|
-
return {
|
|
2571
|
-
deviceId: resolved.deviceId,
|
|
2572
|
-
from: resolved.from,
|
|
2573
|
-
changed: resolved.changed,
|
|
2574
|
-
devices: deps.listDevices ? deps.listDevices() : [],
|
|
2575
|
-
note: mentionMismatch(sessionId, resolved.deviceId),
|
|
2576
|
-
};
|
|
2577
|
-
},
|
|
2578
|
-
});
|
|
2579
|
-
};
|
|
2580
|
-
|
|
2581
|
-
// 老宿主 / 无工具注入的 profile(纯手机端宿主):`ctx.inject` 不存在时什么也不做,
|
|
2582
|
-
// 别把整块装配掀掉。注册本身抛错照旧往上抛 —— 那是真的坏了,不该被当成「没有这个 profile」。
|
|
2583
|
-
if (typeof ctx.inject !== 'function') return;
|
|
2584
|
-
ctx.inject(['tools'], (scoped) => {
|
|
2585
|
-
if (!scoped || !scoped.tools || typeof scoped.tools.register !== 'function') return;
|
|
2586
|
-
build(scoped);
|
|
2587
|
-
});
|
|
2588
|
-
}
|
|
2589
|
-
|
|
2590
|
-
module.exports = { installPhoneTools, summarizeScreen };
|