@aivin-labs/cli 1.0.60 → 1.0.62
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/bin/lib/remote/codingAgents.mjs +46 -4
- package/bin/lib/remote/desktop/castTouchViewers.mjs +3 -5
- package/bin/lib/remote/desktop/desktopCast.mjs +2 -2
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +2 -2
- package/bin/lib/remote/desktop/desktopCastSource.mjs +0 -10
- package/bin/lib/remote/gui/index.mjs +832 -839
- package/bin/lib/remote/gui/skillSeeds.mjs +13 -0
- package/bin/lib/remote/gui/skills.mjs +273 -0
- package/bin/lib/remote/gui/windowsHostSource.mjs +2469 -2418
- package/bin/lib/remote/mascot/ask.mjs +1013 -1003
- package/bin/lib/remote/mascot/askHostSource.mjs +706 -667
- package/bin/lib/remote/mascot/hostSource.mjs +18 -0
- package/bin/lib/remote/mascot/strings.mjs +483 -474
- package/bin/lib/remote/toolHandlers.mjs +2 -1
- package/package.json +1 -1
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Kỹ năng giao diện hạt giống (14/11/2026), nhúng vào mã như các tài nguyên khác của CLI (mã host C#, ảnh linh vật): bản chạy đóng gói
|
|
3
|
+
* (bun compile) không có thư mục để đọc tệp .md. Nguồn đọc được cho người là chính chuỗi Markdown dưới đây (cùng định dạng ~/.aivin/skills/*.md).
|
|
4
|
+
* Thêm / sửa hạt giống: sửa chuỗi tương ứng (giữ frontmatter + khối yaml), chạy test/guiSkills.test.mjs.
|
|
5
|
+
*/
|
|
6
|
+
export const SEED_SKILLS = Object.freeze({
|
|
7
|
+
"antigravity.read_account.md": "---\nkey: antigravity.read_account\napp: Antigravity\nui_lang: en\nparams: []\nrisk: none\neffect: read\nsummary: Read the Google account Antigravity (agent manager) is signed in with; leaves Settings → Account open.\nverified: 2026-11-13 Antigravity agent manager (Windows), Settings → account button → Account page\n---\n\n# Antigravity — đọc tài khoản đang đăng nhập\n\nMở Settings, bấm nút tài khoản (nút có địa chỉ email), đọc trường `Email`. Không thay đổi gì.\nCây trợ năng của Antigravity (Electron) chỉ có sau ~5 s kể từ khi mở → chờ một mốc của khu Settings trước (Settings / Models / Sign Out:\nkỹ năng chạy được từ bất kỳ trạng thái nào — đang ở màn chính, đã mở Settings, hay đang ở trang Account).\n\n```yaml\n- window: { process: Antigravity, open: Antigravity, settle_ms: 2000 }\n- wait: { role: button, name_regex: \"^(Settings|Models|Sign Out)$\" }\n timeout_ms: 15000\n- click: { role: button, name: Settings }\n unless: { role: button, name_contains: \"@\" }\n settle_ms: 800\n- click: { role: button, name_contains: \"@\" }\n unless: { role: button, name: Sign Out }\n settle_ms: 800\n- read: { after_label: Email }\n save: signed_in_email\n```\n",
|
|
8
|
+
"antigravity.read_quota.md": "---\nkey: antigravity.read_quota\napp: Antigravity\nui_lang: en\nparams: []\nrisk: none\neffect: read\nsummary: \"Read Antigravity model quota (Settings → Models): plan, per model group weekly / five-hour limit remaining and refresh time.\"\nverified: '2026-11-13 Antigravity agent manager (Windows), Settings → Models → \"Models & Usage\"'\n---\n\n# Antigravity — đọc hạn mức model\n\nMở Settings → Models, gom chữ theo thứ tự từ tiêu đề \"Models & Usage\" tới nút làm mới hạn mức (nhóm model, \"Weekly Limit Remaining\", phần\ntrăm, câu \"refreshes in …\"). `quota_lines` là danh sách chữ đúng thứ tự trên trang — tín hiệu \"hết hạn mức\" để gợi ý chuyển tài khoản.\n\n```yaml\n- window: { process: Antigravity, open: Antigravity, settle_ms: 2000 }\n- wait: { role: button, name_regex: \"^(Settings|Models|Sign Out)$\" }\n timeout_ms: 15000\n- click: { role: button, name: Settings }\n unless: { role: button, name: Models }\n settle_ms: 800\n- click: { role: button, name: Models }\n settle_ms: 1200\n- wait: { name_regex: \"^Models & Usage\" }\n timeout_ms: 8000\n- collect: { from: { name_regex: \"^Models & Usage\" }, to: { role: button, name: Refresh quota and credits data }, role: text }\n save: quota_lines\n```\n",
|
|
9
|
+
"antigravity.sign_in_google.md": "---\nkey: antigravity.sign_in_google\napp: Antigravity\nui_lang: en\nparams: [email]\nrisk: sign_in\neffect: change\nsummary: From the Antigravity sign-in screen, continue with Google and pick the given account in the browser (no password typed).\nverified: 2026-11-13 Antigravity agent manager (Windows) + Microsoft Edge account chooser\n---\n\n# Antigravity — đăng nhập bằng Google\n\nBấm `Continue with Google`, chọn tài khoản trong trình duyệt (kỹ năng dùng chung `google.pick_account`), chờ Antigravity rời màn hình đăng nhập.\n\n```yaml\n- window: { process: Antigravity }\n- click: { role: button, name: Continue with Google }\n- call: { skill: google.pick_account, params: { email: \"{{email}}\", app_name: Antigravity } }\n- window: { process: Antigravity }\n- wait_gone: { role: button, name: Continue with Google }\n timeout_ms: 30000\n```\n",
|
|
10
|
+
"antigravity.sign_out.md": "---\nkey: antigravity.sign_out\napp: Antigravity\nui_lang: en\nparams: []\nrisk: sign_out\neffect: change\nsummary: Sign out of Antigravity (agent manager). Running agents may stop. Ends on the \"Welcome to Antigravity!\" sign-in screen.\nverified: 2026-11-13 Antigravity agent manager (Windows), Account → Sign Out → Welcome screen\n---\n\n# Antigravity — đăng xuất\n\nĐi tới trang Account (qua kỹ năng đọc tài khoản), bấm `Sign Out`, chờ màn hình đăng nhập.\n\n```yaml\n- call: { skill: antigravity.read_account }\n- window: { process: Antigravity }\n- click: { role: button, name: Sign Out }\n- wait: { role: button, name: Continue with Google }\n timeout_ms: 12000\n```\n",
|
|
11
|
+
"antigravity.switch_account.md": "---\nkey: antigravity.switch_account\napp: Antigravity\nui_lang: en\nparams: [email]\nrisk: sign_out\neffect: change\nsummary: Switch Antigravity (agent manager) to the given Google account with the app's own Sign Out / Continue with Google. Already on it → nothing changes. Verifies the Account page shows the email.\nverified: 2026-11-13 Antigravity agent manager (Windows), full sign-out → Google chooser → verify, 12.7 s, no LLM\n---\n\n# Antigravity — chuyển tài khoản\n\nGhép các kỹ năng nhỏ: đọc tài khoản → đã đúng thì thôi → đăng xuất → đăng nhập bằng Google (chọn tài khoản) → đọc lại và **kiểm email = email đích**.\nLưu ý: dùng nhiều tài khoản để cộng dồn hạn mức có thể trái điều khoản của nhà cung cấp.\n\n```yaml\n- call: { skill: antigravity.read_account }\n- return_if: { equals: [\"{{signed_in_email}}\", \"{{email}}\"] }\n- call: { skill: antigravity.sign_out }\n- call: { skill: antigravity.sign_in_google, params: { email: \"{{email}}\" } }\n- call: { skill: antigravity.read_account }\n- check_equals: [\"{{signed_in_email}}\", \"{{email}}\"]\n```\n",
|
|
12
|
+
"google.pick_account.md": "---\nkey: google.pick_account\napp: Google sign-in (browser)\nui_lang: vi, en\nparams: [email, app_name]\nrisk: sign_in\neffect: change\nsummary: On Google's \"choose an account\" page in the browser, pick the account by email and confirm for the named app. Never types a password — a password prompt stops with needs_human.\nverified: 2026-11-13 Microsoft Edge, Google account chooser (Vietnamese UI) → Antigravity consent page\n---\n\n# Google — chọn tài khoản (dùng chung cho mọi ứng dụng đăng nhập bằng Google)\n\nTài khoản đích phải đã đăng nhập sẵn trong trình duyệt (chỉ cần chọn). Gặp ô mật khẩu → dừng `needs_human`. Trang xác nhận chỉ hiện ở lần cấp quyền\nđầu (bước `optional`), và chỉ bấm khi trang có nhắc tới đúng ứng dụng. Nhãn nút xác nhận là chữ của ngôn ngữ tài khoản Google — liệt kê theo\n`ui_lang` của kỹ năng (vi, en); ngôn ngữ khác thì bước này bỏ qua và Planner bấm.\n\n```yaml\n- browser: { title_regex: \"Google Accounts|Tài khoản Google\" }\n timeout_ms: 15000\n- stop_if: { password: true }\n code: needs_human\n message: Google asks for the password — the person must sign in to this account in the browser once\n- click: { role: listitem, name_contains: \"{{email}}\", first: true }\n settle_ms: 1500\n- stop_if: { password: true }\n code: needs_human\n message: Google asks for the password — the person must sign in to this account in the browser once\n- expect: { any: [{ name_contains: \"{{app_name}}\" }] }\n optional: true\n- click: { role: button, name_regex: \"^(Continue|Allow|Sign in|Tiếp tục|Cho phép|Đăng nhập)$\" }\n optional: true\n settle_ms: 1500\n```\n",
|
|
13
|
+
});
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import YAML from 'yaml';
|
|
4
|
+
import { DeviceErrorCode, REMOTE_CONFIG_DIR, ToolGroup } from '../constants.mjs';
|
|
5
|
+
import { DeviceToolError } from '../sandbox.mjs';
|
|
6
|
+
import { SEED_SKILLS } from './skillSeeds.mjs';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Kỹ năng giao diện chạy TẤT ĐỊNH (14/11/2026) — luồng đã làm đúng một lần (thường do Planner dò ra) lưu thành các bước có MỐC nhận diện và ĐIỀU
|
|
10
|
+
* KIỆN kết quả, chạy lại không cần LLM. Mỗi bước kiểm mốc trước khi bấm; lệch → dừng, trả lý do có cấu trúc (`failed_step`, `code`) để Planner /
|
|
11
|
+
* BE sửa đúng bước đó rồi lưu bản mới — không bấm mù như ghi-rồi-phát-lại.
|
|
12
|
+
*
|
|
13
|
+
* Định dạng (Markdown, người và AI cùng đọc): frontmatter chỉ trường ngắn (`key`, `app`, `ui_lang`, `params`, `risk`, `effect`, `summary`), các bước
|
|
14
|
+
* trong một khối ```yaml``` (mỗi bước một mục). Mốc dùng vai trò + tên + AutomationId; chữ hiển thị đổi theo ngôn ngữ giao diện nên mỗi kỹ năng ghi
|
|
15
|
+
* `ui_lang` (cùng cách bản đồ site của AI Browser lưu theo host + ngôn ngữ). Kỹ năng ghép được (`call`), nên một kỹ năng của nhà cung cấp đăng nhập
|
|
16
|
+
* (google.pick_account) dùng chung cho mọi ứng dụng.
|
|
17
|
+
*
|
|
18
|
+
* Nguồn: hạt giống nhúng trong mã (`skillSeeds.mjs` — bản chạy đóng gói không có thư mục) + kỹ năng trên máy (`~/.aivin/skills/*.md`, trùng key thì
|
|
19
|
+
* bản trên máy thắng).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const LOCAL_DIR = path.join(REMOTE_CONFIG_DIR, 'skills');
|
|
23
|
+
const BROWSERS = ['msedge', 'chrome', 'firefox', 'brave', 'opera', 'vivaldi'];
|
|
24
|
+
const DEFAULT_WAIT_MS = 8000;
|
|
25
|
+
const MAX_CALL_DEPTH = 4;
|
|
26
|
+
|
|
27
|
+
/** Mã kết quả của một lần chạy kỹ năng. */
|
|
28
|
+
export const SkillCode = Object.freeze({
|
|
29
|
+
OK: 'ok',
|
|
30
|
+
ANCHOR_MISSING: 'anchor_missing',
|
|
31
|
+
AMBIGUOUS: 'ambiguous',
|
|
32
|
+
TIMEOUT: 'timeout',
|
|
33
|
+
NEEDS_HUMAN: 'needs_human',
|
|
34
|
+
EXPECT_FAILED: 'expect_failed',
|
|
35
|
+
ERROR: 'error',
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
/** Đọc một tệp kỹ năng: frontmatter + khối yaml đầu tiên chứa danh sách bước. */
|
|
39
|
+
export function parseSkill(text, source = '') {
|
|
40
|
+
const m = String(text || '').match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);
|
|
41
|
+
if (!m) throw new Error(`Skill ${source}: thiếu frontmatter`);
|
|
42
|
+
const meta = YAML.parse(m[1]) || {};
|
|
43
|
+
const block = m[2].match(/```ya?ml\r?\n([\s\S]*?)\r?\n```/);
|
|
44
|
+
const steps = block ? YAML.parse(block[1]) : null;
|
|
45
|
+
if (!meta.key || !Array.isArray(steps) || !steps.length) throw new Error(`Skill ${source}: cần key + khối yaml các bước`);
|
|
46
|
+
return { ...meta, params: meta.params || [], steps, source };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Tệp kỹ năng hỏng không bị nuốt im lặng: ghi vào `errors` để gui.skills báo ra (bản đầu bỏ qua → kỹ năng "biến mất" không ai biết). */
|
|
50
|
+
function readDir(dir, errors) {
|
|
51
|
+
if (!fs.existsSync(dir)) return [];
|
|
52
|
+
return fs.readdirSync(dir).filter((f) => f.endsWith('.md')).map((f) => {
|
|
53
|
+
const file = path.join(dir, f);
|
|
54
|
+
try { return parseSkill(fs.readFileSync(file, 'utf8'), file); } catch (e) { errors.push({ file: f, error: String(e.message || e).slice(0, 200) }); return null; }
|
|
55
|
+
}).filter(Boolean);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Mọi kỹ năng: hạt giống + trên máy (bản trên máy thắng khi trùng key). `map.errors` = tệp không đọc được. `seedDir` (test) thay hạt giống nhúng. */
|
|
59
|
+
export function loadSkills({ seedDir, localDir = LOCAL_DIR, seeds = SEED_SKILLS } = {}) {
|
|
60
|
+
const map = new Map();
|
|
61
|
+
const errors = [];
|
|
62
|
+
if (seedDir) for (const s of readDir(seedDir, errors)) map.set(s.key, s);
|
|
63
|
+
else for (const [file, text] of Object.entries(seeds)) {
|
|
64
|
+
try { const s = parseSkill(text, file); map.set(s.key, s); } catch (e) { errors.push({ file, error: String(e.message || e).slice(0, 200) }); }
|
|
65
|
+
}
|
|
66
|
+
for (const s of readDir(localDir, errors)) map.set(s.key, s);
|
|
67
|
+
map.errors = errors;
|
|
68
|
+
return map;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const fill = (v, vars) => (typeof v === 'string' ? v.replace(/\{\{(\w+)\}\}/g, (_, k) => (vars[k] ?? '')) : v);
|
|
72
|
+
const lc = (s) => String(s || '').toLowerCase();
|
|
73
|
+
|
|
74
|
+
/** Phần tử khớp mốc `{ role, name, name_contains, name_regex, aid, password }` (chữ đã điền tham số). */
|
|
75
|
+
export function nodeMatches(node, spec, vars = {}) {
|
|
76
|
+
if (!node || !spec) return false;
|
|
77
|
+
if (spec.role && lc(node.role) !== lc(spec.role)) return false;
|
|
78
|
+
if (spec.name !== undefined && String(node.name || '').trim() !== fill(spec.name, vars)) return false;
|
|
79
|
+
if (spec.name_contains !== undefined && !lc(node.name).includes(lc(fill(spec.name_contains, vars)))) return false;
|
|
80
|
+
if (spec.name_regex !== undefined && !new RegExp(fill(spec.name_regex, vars), 'i').test(String(node.name || ''))) return false;
|
|
81
|
+
if (spec.aid !== undefined && String(node.automation_id || '') !== fill(spec.aid, vars)) return false;
|
|
82
|
+
if (spec.password !== undefined && !!node.password !== !!spec.password) return false;
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Phần tử đứng ngay sau một nhãn chữ trùng `label` (đọc giá trị của trường "Email: …"). */
|
|
87
|
+
function afterLabel(nodes, label, vars) {
|
|
88
|
+
const want = fill(label, vars);
|
|
89
|
+
const i = nodes.findIndex((n) => String(n.name || '').trim() === want);
|
|
90
|
+
return i >= 0 ? nodes.slice(i + 1).find((n) => n.name && String(n.name).trim() !== want) : undefined;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Chạy một kỹ năng. `gui` = bộ điều khiển (createGuiController). `params` = tham số kỹ năng. Trả { ok, code, vars, trace, failed_step?, error? } —
|
|
97
|
+
* không ném lỗi khi bước lệch mốc (đó là kết quả cần báo Planner), chỉ ném khi kỹ năng không tồn tại / tham số thiếu.
|
|
98
|
+
*/
|
|
99
|
+
export async function runSkill({ gui, skills, key, params = {}, ctx = {}, env = {}, depth = 0 }) {
|
|
100
|
+
const skill = skills.get(key);
|
|
101
|
+
if (!skill) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No skill "${key}"`);
|
|
102
|
+
for (const p of skill.params) if (params[p] === undefined || params[p] === '') throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Skill ${key} needs param "${p}"`);
|
|
103
|
+
const vars = { ...params };
|
|
104
|
+
const trace = [];
|
|
105
|
+
let win = vars.window || null;
|
|
106
|
+
|
|
107
|
+
const observe = async () => {
|
|
108
|
+
if (!win) throw Object.assign(new Error('no window yet'), { code: SkillCode.ANCHOR_MISSING });
|
|
109
|
+
return gui.observe({ window: win, max_nodes: 1200 }, ctx);
|
|
110
|
+
};
|
|
111
|
+
const findOne = async (spec, stepNo) => {
|
|
112
|
+
const obs = await observe();
|
|
113
|
+
const hits = obs.nodes.filter((n) => nodeMatches(n, spec, vars) && !n.disabled);
|
|
114
|
+
const visible = hits.filter((n) => !n.offscreen);
|
|
115
|
+
const pool = visible.length ? visible : hits;
|
|
116
|
+
if (!pool.length) throw Object.assign(new Error(`step ${stepNo}: no element matches ${JSON.stringify(spec)}`), { code: SkillCode.ANCHOR_MISSING });
|
|
117
|
+
if (pool.length > 1 && !spec.first) throw Object.assign(new Error(`step ${stepNo}: ${pool.length} elements match ${JSON.stringify(spec)}`), { code: SkillCode.AMBIGUOUS, choices: pool.slice(0, 5).map((n) => `${n.role} "${n.name}"`) });
|
|
118
|
+
return { node: pool[0], obs };
|
|
119
|
+
};
|
|
120
|
+
const waitFor = async (spec, timeoutMs, gone = false) => {
|
|
121
|
+
const deadline = Date.now() + (timeoutMs || DEFAULT_WAIT_MS);
|
|
122
|
+
for (;;) {
|
|
123
|
+
const obs = await observe().catch(() => ({ nodes: [] }));
|
|
124
|
+
const present = obs.nodes.some((n) => nodeMatches(n, spec, vars));
|
|
125
|
+
if (present !== gone) return true;
|
|
126
|
+
if (Date.now() > deadline) return false;
|
|
127
|
+
await sleep(400);
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
const findWindow = async (step) => {
|
|
131
|
+
const procs = (step.process_any || (step.process ? [step.process] : [])).map(lc);
|
|
132
|
+
const deadline = Date.now() + (step.timeout_ms || DEFAULT_WAIT_MS);
|
|
133
|
+
for (;;) {
|
|
134
|
+
const list = (await gui.windows({}, ctx)).windows;
|
|
135
|
+
const w = list.find((x) => (!procs.length || procs.includes(lc(x.process)))
|
|
136
|
+
&& (!step.title_regex || new RegExp(fill(step.title_regex, vars), 'i').test(String(x.title || ''))) && !x.blocked);
|
|
137
|
+
if (w) return w;
|
|
138
|
+
if (Date.now() > deadline) return null;
|
|
139
|
+
await sleep(500);
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
for (let i = 0; i < skill.steps.length; i++) {
|
|
144
|
+
const step = skill.steps[i];
|
|
145
|
+
const kind = Object.keys(step).find((k) => ['window', 'browser', 'click', 'wait', 'wait_gone', 'read', 'collect', 'expect', 'stop_if', 'call', 'return_if', 'check_equals', 'pause'].includes(k));
|
|
146
|
+
const started = Date.now();
|
|
147
|
+
const rec = { step: i + 1, kind, note: step.note };
|
|
148
|
+
try {
|
|
149
|
+
// `unless`: trang đã ở trạng thái bước này nhắm tới (vd đã mở trang Account) → bỏ qua bước.
|
|
150
|
+
if (step.unless && win) {
|
|
151
|
+
const obs = await observe().catch(() => ({ nodes: [] }));
|
|
152
|
+
if (obs.nodes.some((n) => nodeMatches(n, step.unless, vars))) { trace.push({ ...rec, skipped: 'unless', ms: Date.now() - started }); continue; }
|
|
153
|
+
}
|
|
154
|
+
if (kind === 'window' || kind === 'browser') {
|
|
155
|
+
const spec = { ...(kind === 'browser' ? { process_any: BROWSERS, ...step.browser } : step.window), ...(step.timeout_ms ? { timeout_ms: step.timeout_ms } : {}) };
|
|
156
|
+
let w = await findWindow({ ...spec, timeout_ms: spec.open ? 1500 : spec.timeout_ms });
|
|
157
|
+
if (!w && spec.open) {
|
|
158
|
+
const opened = await gui.openApp({ name: spec.open }, ctx, env);
|
|
159
|
+
w = opened?.window || await findWindow(spec);
|
|
160
|
+
if (spec.settle_ms) await sleep(spec.settle_ms);
|
|
161
|
+
}
|
|
162
|
+
if (!w) throw Object.assign(new Error(`step ${i + 1}: no window for ${JSON.stringify(spec)}`), { code: SkillCode.ANCHOR_MISSING });
|
|
163
|
+
win = w.window;
|
|
164
|
+
vars.window = win;
|
|
165
|
+
rec.window = `${w.process} "${String(w.title || '').slice(0, 60)}"`;
|
|
166
|
+
} else if (kind === 'click') {
|
|
167
|
+
const { node } = await findOne(step.click, i + 1);
|
|
168
|
+
await gui.act({ action: 'click', node_id: node.id }, ctx);
|
|
169
|
+
rec.target = `${node.role} "${String(node.name || '').slice(0, 60)}"`;
|
|
170
|
+
if (step.settle_ms) await sleep(step.settle_ms);
|
|
171
|
+
} else if (kind === 'wait' || kind === 'wait_gone') {
|
|
172
|
+
const ok = await waitFor(step[kind], step.timeout_ms, kind === 'wait_gone');
|
|
173
|
+
if (!ok) throw Object.assign(new Error(`step ${i + 1}: ${kind} timed out for ${JSON.stringify(step[kind])}`), { code: SkillCode.TIMEOUT });
|
|
174
|
+
} else if (kind === 'read') {
|
|
175
|
+
const obs = await observe();
|
|
176
|
+
const node = step.read.after_label ? afterLabel(obs.nodes, step.read.after_label, vars) : obs.nodes.find((n) => nodeMatches(n, step.read, vars));
|
|
177
|
+
if (!node) throw Object.assign(new Error(`step ${i + 1}: nothing to read for ${JSON.stringify(step.read)}`), { code: SkillCode.ANCHOR_MISSING });
|
|
178
|
+
vars[step.save] = String(node.name || node.value || '').trim();
|
|
179
|
+
rec.saved = step.save;
|
|
180
|
+
} else if (kind === 'collect') {
|
|
181
|
+
// Chữ theo thứ tự giữa hai mốc (vd trang hạn mức: từ tiêu đề trang tới nút làm mới) — Planner / bộ hiểu hạn mức đọc tiếp.
|
|
182
|
+
const obs = await observe();
|
|
183
|
+
const from = step.collect.from ? obs.nodes.findIndex((n) => nodeMatches(n, step.collect.from, vars)) : 0;
|
|
184
|
+
const to = step.collect.to ? obs.nodes.findIndex((n, k) => k > from && nodeMatches(n, step.collect.to, vars)) : obs.nodes.length;
|
|
185
|
+
if (from < 0) throw Object.assign(new Error(`step ${i + 1}: collect start anchor missing`), { code: SkillCode.ANCHOR_MISSING });
|
|
186
|
+
vars[step.save] = obs.nodes.slice(from, to < 0 ? obs.nodes.length : to).filter((n) => n.name && (!step.collect.role || lc(n.role) === lc(step.collect.role))).map((n) => String(n.name).trim());
|
|
187
|
+
rec.saved = step.save;
|
|
188
|
+
} else if (kind === 'expect') {
|
|
189
|
+
const obs = await observe();
|
|
190
|
+
const all = step.expect.all || [];
|
|
191
|
+
const any = step.expect.any || [];
|
|
192
|
+
const ok = all.every((s) => obs.nodes.some((n) => nodeMatches(n, s, vars))) && (!any.length || any.some((s) => obs.nodes.some((n) => nodeMatches(n, s, vars))));
|
|
193
|
+
if (!ok) throw Object.assign(new Error(`step ${i + 1}: expectation not met ${JSON.stringify(step.expect)}`), { code: SkillCode.EXPECT_FAILED });
|
|
194
|
+
} else if (kind === 'stop_if') {
|
|
195
|
+
const obs = await observe().catch(() => ({ nodes: [] }));
|
|
196
|
+
if (obs.nodes.some((n) => nodeMatches(n, step.stop_if, vars))) {
|
|
197
|
+
const code = step.code || SkillCode.NEEDS_HUMAN;
|
|
198
|
+
rec.ms = Date.now() - started;
|
|
199
|
+
trace.push(rec);
|
|
200
|
+
return { ok: false, code, vars, trace, failed_step: i + 1, error: step.message || `stopped at step ${i + 1}` };
|
|
201
|
+
}
|
|
202
|
+
} else if (kind === 'return_if') {
|
|
203
|
+
// Đã đạt sẵn (vd đang ở đúng tài khoản) → xong, không làm các bước đổi trạng thái phía sau.
|
|
204
|
+
if (lc(fill(step.return_if.equals?.[0], vars)) === lc(fill(step.return_if.equals?.[1], vars))) {
|
|
205
|
+
rec.ms = Date.now() - started;
|
|
206
|
+
trace.push({ ...rec, returned: true });
|
|
207
|
+
return { ok: true, code: SkillCode.OK, vars, trace, early: true };
|
|
208
|
+
}
|
|
209
|
+
} else if (kind === 'check_equals') {
|
|
210
|
+
// Điều kiện kết quả: hai giá trị phải trùng (không phân biệt hoa thường) — vd email sau khi chuyển = email đích.
|
|
211
|
+
const [a, b] = (step.check_equals || []).map((v) => lc(String(fill(v, vars)).trim()));
|
|
212
|
+
if (!a || a !== b) throw Object.assign(new Error(`step ${i + 1}: check failed (${a || '-'} ≠ ${b || '-'})`), { code: SkillCode.EXPECT_FAILED });
|
|
213
|
+
} else if (kind === 'call') {
|
|
214
|
+
if (depth >= MAX_CALL_DEPTH) throw Object.assign(new Error('skill call depth exceeded'), { code: SkillCode.ERROR });
|
|
215
|
+
const args = Object.fromEntries(Object.entries(step.call.params || {}).map(([k, v]) => [k, fill(v, vars)]));
|
|
216
|
+
const sub = await runSkill({ gui, skills, key: step.call.skill, params: { ...args, window: undefined }, ctx, env, depth: depth + 1 });
|
|
217
|
+
rec.call = step.call.skill;
|
|
218
|
+
rec.sub = sub.trace;
|
|
219
|
+
if (!sub.ok) {
|
|
220
|
+
rec.ms = Date.now() - started;
|
|
221
|
+
trace.push(rec);
|
|
222
|
+
return { ok: false, code: sub.code, vars, trace, failed_step: i + 1, error: `${step.call.skill}: ${sub.error}` };
|
|
223
|
+
}
|
|
224
|
+
for (const [k, v] of Object.entries(sub.vars || {})) if (k !== 'window') vars[k] = v;
|
|
225
|
+
} else if (kind === 'pause') {
|
|
226
|
+
await sleep(Number(step.pause) || 0);
|
|
227
|
+
} else {
|
|
228
|
+
throw Object.assign(new Error(`step ${i + 1}: unknown step`), { code: SkillCode.ERROR });
|
|
229
|
+
}
|
|
230
|
+
rec.ms = Date.now() - started;
|
|
231
|
+
trace.push(rec);
|
|
232
|
+
} catch (e) {
|
|
233
|
+
rec.ms = Date.now() - started;
|
|
234
|
+
// `optional`: bước có thể không có (trang xác nhận chỉ hiện lần đầu cấp quyền) → bỏ qua khi thiếu mốc / hết giờ chờ.
|
|
235
|
+
if (step.optional && [SkillCode.ANCHOR_MISSING, SkillCode.EXPECT_FAILED, SkillCode.TIMEOUT].includes(e.code)) { trace.push({ ...rec, skipped: 'optional' }); continue; }
|
|
236
|
+
trace.push(rec);
|
|
237
|
+
return { ok: false, code: e.code && Object.values(SkillCode).includes(e.code) ? e.code : SkillCode.ERROR, vars, trace, failed_step: i + 1, error: String(e.message || e).slice(0, 300), choices: e.choices };
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return { ok: true, code: SkillCode.OK, vars, trace };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Công cụ cho Planner: liệt kê + chạy kỹ năng. Chạy kỹ năng có rủi ro (đăng xuất…) đi qua cổng duyệt như mọi công cụ có thay đổi. */
|
|
244
|
+
export function buildSkillTools(gui, { skillsLoader = loadSkills } = {}) {
|
|
245
|
+
return [
|
|
246
|
+
{
|
|
247
|
+
name: 'gui.skills', group: ToolGroup.GUI, read_only: true,
|
|
248
|
+
handler: async () => {
|
|
249
|
+
const all = skillsLoader();
|
|
250
|
+
return {
|
|
251
|
+
skills: [...all.values()].map((s) => ({ key: s.key, app: s.app, ui_lang: s.ui_lang, params: s.params, risk: s.risk || 'none', summary: s.summary })),
|
|
252
|
+
...(all.errors?.length ? { unreadable: all.errors } : {}),
|
|
253
|
+
};
|
|
254
|
+
},
|
|
255
|
+
description: 'List saved deterministic GUI skills (verified flows such as reading the signed-in account or switching account of an app). Prefer running a matching skill over planning the clicks yourself.',
|
|
256
|
+
input_schema: { type: 'object', properties: {} },
|
|
257
|
+
},
|
|
258
|
+
{
|
|
259
|
+
name: 'gui.run_skill', group: ToolGroup.GUI,
|
|
260
|
+
handler: async (a, ctx, env) => {
|
|
261
|
+
const res = await runSkill({ gui, skills: skillsLoader(), key: String(a.skill || ''), params: a.params || {}, ctx, env });
|
|
262
|
+
const { window: _w, ...vars } = res.vars || {};
|
|
263
|
+
return { ...res, vars };
|
|
264
|
+
},
|
|
265
|
+
description: 'Run a saved GUI skill by key with its params, without planning each click. Every step checks its anchor first; on a mismatch it stops and returns code (anchor_missing / ambiguous / timeout / expect_failed / needs_human), failed_step and the trace, so you can do or fix that step yourself. needs_human = the person must act (e.g. a password prompt).',
|
|
266
|
+
input_schema: {
|
|
267
|
+
type: 'object',
|
|
268
|
+
properties: { skill: { type: 'string', description: 'skill key from gui.skills' }, params: { type: 'object', description: 'skill params, e.g. {"email": "…"}' } },
|
|
269
|
+
required: ['skill'],
|
|
270
|
+
},
|
|
271
|
+
},
|
|
272
|
+
];
|
|
273
|
+
}
|