slipwing 0.0.0-stage → 0.1.1
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/LICENSE +202 -0
- package/NOTICE +12 -0
- package/README.md +145 -3
- package/bin/agent-desktop-win32-x64.exe +0 -0
- package/bin/workflow.js +512 -0
- package/browser/LICENSE +201 -0
- package/browser/LICENSE-axe-core-THIRD-PARTY.txt +66 -0
- package/browser/LICENSE-axe-core.txt +362 -0
- package/browser/bin/agent-browser-win32-x64.exe +0 -0
- package/browser/skill-data/agentcore/SKILL.md +115 -0
- package/browser/skill-data/core/SKILL.md +279 -0
- package/browser/skill-data/core/references/authentication.md +413 -0
- package/browser/skill-data/core/references/commands.md +727 -0
- package/browser/skill-data/core/references/profiling.md +120 -0
- package/browser/skill-data/core/references/proxy-support.md +221 -0
- package/browser/skill-data/core/references/session-management.md +215 -0
- package/browser/skill-data/core/references/snapshot-refs.md +244 -0
- package/browser/skill-data/core/references/streaming.md +107 -0
- package/browser/skill-data/core/references/trust-boundaries.md +69 -0
- package/browser/skill-data/core/references/video-recording.md +254 -0
- package/browser/skill-data/core/references/webgpu.md +118 -0
- package/browser/skill-data/core/templates/authenticated-session.sh +109 -0
- package/browser/skill-data/core/templates/capture-workflow.sh +69 -0
- package/browser/skill-data/core/templates/form-automation.sh +63 -0
- package/browser/skill-data/derive-client/SKILL.md +88 -0
- package/browser/skill-data/dogfood/SKILL.md +224 -0
- package/browser/skill-data/dogfood/references/issue-taxonomy.md +109 -0
- package/browser/skill-data/dogfood/templates/dogfood-report-template.md +53 -0
- package/browser/skill-data/electron/SKILL.md +236 -0
- package/browser/skill-data/modern-web-guidance/SKILL.md +165 -0
- package/browser/skill-data/slack/SKILL.md +288 -0
- package/browser/skill-data/slack/references/slack-tasks.md +349 -0
- package/browser/skill-data/slack/templates/slack-report-template.md +163 -0
- package/browser/skill-data/vercel/SKILL.md +160 -0
- package/browser/skill-data/vercel-sandbox/SKILL.md +237 -0
- package/browser/skill-data/webmcp-gen/SKILL.md +52 -0
- package/browser/skills/agent-browser/SKILL.md +51 -0
- package/bundle.json +19 -0
- package/lib/browser-move.js +185 -0
- package/lib/bundle-version.js +32 -0
- package/lib/choose.js +382 -0
- package/lib/cli-options.js +47 -0
- package/lib/control-changes.js +47 -0
- package/lib/current-page.js +165 -0
- package/lib/error-code.js +19 -0
- package/lib/final-picture.js +31 -0
- package/lib/final-words.json +7 -0
- package/lib/flow-record.js +32 -0
- package/lib/host-client.js +65 -0
- package/lib/host-command.js +175 -0
- package/lib/host-paths.js +22 -0
- package/lib/host-server.js +383 -0
- package/lib/host-waits.js +12 -0
- package/lib/host-watch.js +340 -0
- package/lib/mcp-guide.js +45 -0
- package/lib/mcp-server.js +264 -0
- package/lib/notify.js +31 -0
- package/lib/page-choice.js +273 -0
- package/lib/page-input.js +141 -0
- package/lib/page-lease.js +87 -0
- package/lib/page-line.js +83 -0
- package/lib/page-pointer.js +191 -0
- package/lib/page-read.js +44 -0
- package/lib/png-mark.js +83 -0
- package/lib/prefs.js +228 -0
- package/lib/routine-approvals.js +67 -0
- package/lib/routine-command.js +150 -0
- package/lib/routine-effects.js +119 -0
- package/lib/routine-store.js +143 -0
- package/lib/script-args.js +48 -0
- package/lib/script-call.js +63 -0
- package/lib/script-desktop.js +731 -0
- package/lib/script-final.js +93 -0
- package/lib/script-fix.js +121 -0
- package/lib/script-input.js +25 -0
- package/lib/script-match.js +90 -0
- package/lib/script-picture.js +104 -0
- package/lib/script-repeat.js +43 -0
- package/lib/script-run.js +367 -0
- package/lib/script-screen.js +53 -0
- package/lib/script-visible.js +228 -0
- package/lib/script-wait.js +15 -0
- package/lib/script-web.js +338 -0
- package/lib/skill-command.js +81 -0
- package/lib/space.js +56 -0
- package/lib/text-match.js +18 -0
- package/lib/watch-helper.ps1 +200 -0
- package/lib/web-page.js +214 -0
- package/lib/window-move.js +213 -0
- package/package.json +32 -5
- package/scripts/initialize-state.ps1 +13 -0
- package/skills/slipwing/SKILL.md +189 -0
- package/skills/slipwing/chrome.md +62 -0
- package/skills/slipwing/desktop.md +82 -0
- package/skills/slipwing/human.md +63 -0
- package/skills/slipwing/jobs.md +82 -0
- package/skills/slipwing/routines.md +73 -0
- package/skills/slipwing/watches.md +37 -0
package/bin/workflow.js
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const { execFileSync, spawnSync } = require('node:child_process');
|
|
5
|
+
const { existsSync, readFileSync, statSync } = require('node:fs');
|
|
6
|
+
const { basename, delimiter, isAbsolute, join } = require('node:path');
|
|
7
|
+
const { parseArgs } = require('node:util');
|
|
8
|
+
const { setTimeout: delay } = require('node:timers/promises');
|
|
9
|
+
const { randomUUID } = require('node:crypto');
|
|
10
|
+
const { prepareChoice, finishChoice, revealText } = require('../lib/choose');
|
|
11
|
+
const { view, move, edit, tap } = require('../lib/window-move');
|
|
12
|
+
const { browserMove, dropFile } = require('../lib/browser-move');
|
|
13
|
+
const { current, follow, editPage } = require('../lib/current-page');
|
|
14
|
+
const { choosePage } = require('../lib/page-choice');
|
|
15
|
+
const { typePage } = require('../lib/page-input');
|
|
16
|
+
const { wheelPage, pointerPage, physicalPointer } = require('../lib/page-pointer');
|
|
17
|
+
const { recordStep, readSteps } = require('../lib/flow-record');
|
|
18
|
+
const { connect, disconnect, webPerform, withRoute, chromeFlags } = require('../lib/web-page');
|
|
19
|
+
const { runScript, api } = require('../lib/script-run');
|
|
20
|
+
const { foregroundInterruption } = require('../lib/script-call');
|
|
21
|
+
const { space, spaceFlags } = require('../lib/space');
|
|
22
|
+
const { readPage } = require('../lib/page-read');
|
|
23
|
+
const { pageLease } = require('../lib/page-lease');
|
|
24
|
+
const { markRepeat, clearRepeat } = require('../lib/script-repeat');
|
|
25
|
+
const routines = require('../lib/routine-command');
|
|
26
|
+
const { initializeStateDir } = require('../lib/routine-store');
|
|
27
|
+
const host = require('../lib/host-command');
|
|
28
|
+
const prefs = require('../lib/prefs');
|
|
29
|
+
const { COMMAND_OPTIONS, POSITIONAL_COMMANDS, parseOptions } = require('../lib/cli-options');
|
|
30
|
+
const mcp = require('../lib/mcp-server');
|
|
31
|
+
const skill = require('../lib/skill-command');
|
|
32
|
+
const { versionReport } = require('../lib/bundle-version');
|
|
33
|
+
const { errorCode } = require('../lib/error-code');
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The background browser's own session. No guide tells anyone to attach this name to the user's Chrome, and an
|
|
37
|
+
* inherited AGENT_BROWSER_SESSION never replaces it, so background web steps cannot land in a browser the user signed
|
|
38
|
+
* into: an agent-browser session keeps whatever browser it was first connected to.
|
|
39
|
+
*/
|
|
40
|
+
const BACKGROUND_SESSION = 'agent-desktop-background';
|
|
41
|
+
|
|
42
|
+
const usage = [
|
|
43
|
+
'slipwing --version (the version of this bundle, and for each program the installed version and the official release it is built on)',
|
|
44
|
+
'slipwing desktop ARGS... | slipwing browser ARGS... (run the bundled agent-desktop or agent-browser command, including --help)',
|
|
45
|
+
'slipwing connect [--cdp URL] (once: lets page commands use your running Chrome without taking the foreground)',
|
|
46
|
+
'slipwing disconnect',
|
|
47
|
+
'slipwing current [--window ID | --page PAGE] [--visible] (--visible binds the tab for the real mouse and keyboard only and skips the background connection)',
|
|
48
|
+
'slipwing follow --page PAGE (--link NAME [--expect-url URL] | --button NAME --expect-url URL) [--visible]',
|
|
49
|
+
'slipwing type --page PAGE --field NAME (--value TEXT | --stdin) [--interval-ms MS | --human natural|careful [--seed N]] [--multiline] [--replace | --at start|end] [--after IMAGE.png] (text goes in at the caret; a field that was never clicked has its caret at the start, so say --at end to append)',
|
|
50
|
+
'slipwing wheel --page PAGE [--over VISIBLE_TEXT] [--lines N] [--until TEXT] [--human natural|careful] [--seed N] (positive is down; without --over the page itself scrolls)',
|
|
51
|
+
'slipwing point --page PAGE --on NAME [--role ROLE] [--nth N] [--expect-text TEXT] [--human natural|careful] [--seed N]',
|
|
52
|
+
'slipwing click --page PAGE --on NAME [--role ROLE] [--nth N] [--expect-text TEXT] [--human natural|careful] [--seed N]',
|
|
53
|
+
'slipwing edit --page PAGE --field NAME (--value TEXT | --stdin)',
|
|
54
|
+
'slipwing choose --page PAGE --field LABEL --value OPTION [--within SECTION] [--open BUTTON] [--popup PANEL] [--advance BUTTON] [--search FIELD] [--confirm BUTTON] [--expect-value TEXT]',
|
|
55
|
+
'slipwing choose --session NAME [--tab TAB] (--field LABEL | --input CSS) --value VALUE [--position N] [--format DATE_FORMAT]',
|
|
56
|
+
'slipwing choose-file --session NAME [--tab TAB] --input CSS --file ABSOLUTE_PATH',
|
|
57
|
+
'slipwing reveal --session NAME [--tab TAB] --within CSS --text EXACT_TEXT',
|
|
58
|
+
'slipwing view (--window ID | --app NAME) [--output NEW_IMAGE.png] [--region X,Y,W,H] [--popups] (without --output the image gets a new name; the reply has its path)',
|
|
59
|
+
'slipwing edit (--window ID | --app NAME) --document TAB_NAME [--field LABEL] (--value TEXT | --stdin)',
|
|
60
|
+
'slipwing move --frame IMAGE.png --from X,Y --to X,Y [--to-frame DEST.png] [--after IMAGE.png] [--human natural|careful] [--seed N]',
|
|
61
|
+
'slipwing tap --frame IMAGE.png (--at X,Y | --text VISIBLE_TEXT [--nth N]) [--button left|right|middle] [--count N] [--human natural|careful] [--seed N]',
|
|
62
|
+
'slipwing browser-move --session NAME [--tab TAB] --surface CSS --from X,Y --to X,Y [--object CSS] [--after IMAGE.png]',
|
|
63
|
+
'slipwing drop-file --session NAME [--tab TAB] --input DROP_ZONE_CSS --file ABSOLUTE_PATH',
|
|
64
|
+
'slipwing replay --file FLOW.jsonl [--window ID] [--speed N] (record a flow by setting AGENT_DESKTOP_RECORD=FLOW.jsonl)',
|
|
65
|
+
'slipwing run [--file SCRIPT.js] [--mode background|watch|record|direct] [--session NAME | --space | --chrome] [--allow-input] [--allow-final] [--timeout-ms MS] [--args JSON | --args-file FILE.json] [--save NAME --about TEXT [--param name="what it is"]... [--replace]] (many page and desktop steps in one call; the script comes from stdin without --file; run --api lists the helpers. Without --allow-input a step that needs the real mouse and keyboard is refused before anything is sent; without --allow-final a send, submit, pay or delete step is refused the same way. --save keeps a script that succeeded as a routine; argument values are not stored)',
|
|
66
|
+
'slipwing routine run NAME [--mode WAY] [--args JSON | --args-file FILE.json] [--allow-input] [--allow-final] [--session NAME | --space | --chrome] (runs a saved routine and stops at the first step whose effect differs from the saved runs: EFFECT_MISMATCH)',
|
|
67
|
+
'slipwing routine list [--for TEXT (a word of the name, description, app, site or address)] | routine show NAME | routine remove NAME | routine allow NAME | routine permissions | routine revoke NAME (allow: the user said in the chat that this routine may always do its final steps; permissions lists those routines and the apps and sites protected.json under the state folder protects)',
|
|
68
|
+
'slipwing run ... --detach | routine run NAME ... --detach (hands the work to the resident host and answers at once with a job id)',
|
|
69
|
+
'slipwing job list | job show ID | job wait ID [--timeout-ms MS] | job stop ID | job report ID',
|
|
70
|
+
'slipwing job retry ID [--target NAME] [--options JSON] | job do ID --file PATCH.js | job skip ID [--value JSON] (a job whose step failed waits up to 10 minutes for one of these)',
|
|
71
|
+
'slipwing host start | host stop | host status',
|
|
72
|
+
'slipwing watch add (--window TITLE [--gone] | --text TEXT --in WINDOW [--gone] | --notification TEXT | --file PATH) [--then ROUTINE [--args JSON] [--allow-final]] | watch list | watch show ID | watch wait ID | watch remove ID (the host watches; --then starts a saved routine as a job, which stops before a final step unless the user agreed to it when the watch was set: --allow-final)',
|
|
73
|
+
'slipwing job approve ID (a job stopped before a final step, reason "approval": ask the user in the chat first; job approve lets that one step go, job skip passes it, job stop ends the job)',
|
|
74
|
+
'slipwing job grant (ID | --all) --for SECONDS (a job waits with reason "hands" before a step that needs the real mouse and keyboard: let it, or every job, use them that long; a person touching them makes the job wait until they stop for 3 seconds; nothing goes on while the screen is locked)',
|
|
75
|
+
'slipwing prefs [--dir FOLDER] | prefs set KEY=VALUE... (--project | --dir FOLDER | --always | --routine NAME) | prefs unset KEY... SCOPE (how scripts work here: mode is background, watch, record or direct; pointer is amber, red, green, off or a PNG; browser is clean, chrome or space. The most specific wins: --mode for this run, the routine, the project folder, everywhere. Set them only when the user asks for it)',
|
|
76
|
+
'slipwing skill [NAME] | skill --list | skill --install [--dir FOLDER] [--force] (the working guide for agents; --install puts a short entry that points here into the Claude Code and Codex skill folders)',
|
|
77
|
+
'slipwing mcp (serves run, routines, preferences, jobs and watches as MCP tools over stdio, for any MCP client)',
|
|
78
|
+
'slipwing read --url URL (the text of a web page: a plain request and a background browser run together and the first full answer is returned)',
|
|
79
|
+
'slipwing space [--login URL | --close] (the agent\'s own browser profile: --login shows its window so the user signs in once; later runs with --space keep that sign-in in the background)',
|
|
80
|
+
].join('\n');
|
|
81
|
+
|
|
82
|
+
/** A command called the wrong way: the reply says how, with code INVALID_ARGS. */
|
|
83
|
+
function invalid(message) {
|
|
84
|
+
return Object.assign(new Error(message), { code: 'INVALID_ARGS' });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The text of a file the command was given, or FILE_NOT_FOUND naming the option and the folder a relative path counts from. */
|
|
88
|
+
function readText(path, option) {
|
|
89
|
+
try { return readFileSync(path, 'utf8'); } catch (err) {
|
|
90
|
+
if (!['ENOENT', 'EISDIR'].includes(err.code)) throw err;
|
|
91
|
+
throw Object.assign(new Error('No file at ' + path + (option ? ' (' + option + ')' : '') + '. A relative path counts from ' + process.cwd() + '.'), { code: 'FILE_NOT_FOUND' });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function one(items, description) {
|
|
96
|
+
if (items.length !== 1) throw new Error('Expected one ' + description + ', found ' + items.length);
|
|
97
|
+
return items[0];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function run(binary, args, input, check, inspect) {
|
|
101
|
+
check?.(args);
|
|
102
|
+
let out;
|
|
103
|
+
try {
|
|
104
|
+
const timeout = args[0] === 'type' && args.includes('--interval-ms') ? 0 : 15000;
|
|
105
|
+
out = execFileSync(binary, args, { encoding: 'utf8', windowsHide: true, timeout, maxBuffer: args[0] === 'screenshot' ? 96 * 1024 * 1024 : 8 * 1024 * 1024, input, stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'] });
|
|
106
|
+
} catch (err) {
|
|
107
|
+
if (!err.stdout) throw new Error('Cannot execute ' + basename(binary) + ' (' + (err.code ?? 'command failed') + ')');
|
|
108
|
+
out = err.stdout;
|
|
109
|
+
}
|
|
110
|
+
const reply = JSON.parse(out);
|
|
111
|
+
const interrupted = inspect?.(reply.data ?? reply.error);
|
|
112
|
+
if (interrupted) throw interrupted;
|
|
113
|
+
if (!(reply.ok ?? reply.success)) {
|
|
114
|
+
const message = reply.error?.message ?? reply.error ?? 'Command refused';
|
|
115
|
+
const error = new Error(String(message).replace(/^Evaluation error: Error: ([^\n]*)\n\s+at [\s\S]*$/, '$1'));
|
|
116
|
+
if (reply.error?.code) Object.assign(error, {code:reply.error.code, details:reply.error.details, disposition:reply.error.disposition, suggestion:reply.error.suggestion});
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
return reply.data;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function boundTab(session, tab) {
|
|
123
|
+
const binary = browserBinary();
|
|
124
|
+
const args = ['--session', session, '--pin-tab', '--json'];
|
|
125
|
+
const ab = (...command) => run(binary, [...args, ...command]);
|
|
126
|
+
const tabs = () => ab('tab', 'list').tabs;
|
|
127
|
+
const original = one(tabs().filter(t => tab ? [t.targetId, t.tabId, t.label].includes(tab) : t.active), 'matching tab');
|
|
128
|
+
if (!original.targetId) throw new Error('Cannot bind the requested tab.');
|
|
129
|
+
if (tab) ab('tab', original.targetId);
|
|
130
|
+
const check = () => {
|
|
131
|
+
if (one(tabs().filter(t => t.active), 'active session tab').targetId !== original.targetId) throw new Error('The session changed tabs.');
|
|
132
|
+
};
|
|
133
|
+
const evaluate = (fn, ...params) => run(binary, [...args, 'eval', '--stdin'],
|
|
134
|
+
'(' + fn.toString() + ')(...' + JSON.stringify(params) + ')').result;
|
|
135
|
+
return { ab, original, check, evaluate };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function choose({ session, tab, field, input, value, position, format }) {
|
|
139
|
+
if (!session || Boolean(field) === Boolean(input) || !value ||
|
|
140
|
+
(position !== undefined && (!/^[1-9]\d*$/.test(position) || !Number.isSafeInteger(Number(position))))) throw invalid(usage);
|
|
141
|
+
const { ab, original, check, evaluate } = boundTab(session, tab);
|
|
142
|
+
const key = 'data-ad-' + randomUUID();
|
|
143
|
+
try {
|
|
144
|
+
check();
|
|
145
|
+
const spec = { field, input, value, position: Number(position) || null, format, key, url: original.url };
|
|
146
|
+
let choice = evaluate(prepareChoice, spec);
|
|
147
|
+
check();
|
|
148
|
+
if (choice.action === 'open') {
|
|
149
|
+
ab('click', choice.selector);
|
|
150
|
+
check();
|
|
151
|
+
choice = evaluate(prepareChoice, spec, true);
|
|
152
|
+
check();
|
|
153
|
+
}
|
|
154
|
+
if (choice.action === 'date') evaluate(finishChoice, key, 'date');
|
|
155
|
+
if (choice.action === 'fill' || choice.action === 'select') ab(choice.action, choice.selector, choice.argument);
|
|
156
|
+
if (choice.action === 'click') ab('click', choice.selector);
|
|
157
|
+
const selected = evaluate(finishChoice, key);
|
|
158
|
+
check();
|
|
159
|
+
return { tab: original.tabId, targetId: original.targetId, ...selected };
|
|
160
|
+
} finally {
|
|
161
|
+
// Only the original document holds this per-call marker.
|
|
162
|
+
try { evaluate(finishChoice, key, 'clean'); } catch { /* The document may have closed. */ }
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function browserBinary() {
|
|
167
|
+
if (process.env.AGENT_BROWSER_BIN) return process.env.AGENT_BROWSER_BIN;
|
|
168
|
+
if (require('../package.json').name === 'slipwing') {
|
|
169
|
+
return join(__dirname, '..', 'browser', 'bin', 'agent-browser-win32-' + process.arch + '.exe');
|
|
170
|
+
}
|
|
171
|
+
for (const dir of (process.env.PATH ?? '').split(delimiter).filter(Boolean)) {
|
|
172
|
+
const candidate = join(dir, 'node_modules', 'agent-browser', 'bin', 'agent-browser-win32-' + process.arch + '.exe');
|
|
173
|
+
if (existsSync(candidate)) return candidate;
|
|
174
|
+
}
|
|
175
|
+
throw new Error('Set AGENT_BROWSER_BIN to the installed agent-browser executable.');
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function optionalBrowserBinary() {
|
|
179
|
+
try { return browserBinary(); } catch { return undefined; }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function browserPid(url) {
|
|
183
|
+
const endpoint = new URL(url);
|
|
184
|
+
if (endpoint.protocol !== 'ws:' || !['localhost', '127.0.0.1', '[::1]'].includes(endpoint.hostname)) throw new Error('A local headed Chromium session is required.');
|
|
185
|
+
const socket = new WebSocket(url);
|
|
186
|
+
try {
|
|
187
|
+
const processes = await new Promise((resolve, reject) => {
|
|
188
|
+
const timer = setTimeout(() => reject(new Error('Browser process lookup timed out')), 4000);
|
|
189
|
+
const fail = () => { clearTimeout(timer); reject(new Error('Cannot identify the browser process')); };
|
|
190
|
+
socket.onerror = fail;
|
|
191
|
+
socket.onclose = fail;
|
|
192
|
+
socket.onopen = () => socket.send(JSON.stringify({ id: 1, method: 'SystemInfo.getProcessInfo' }));
|
|
193
|
+
socket.onmessage = ({ data }) => {
|
|
194
|
+
try {
|
|
195
|
+
const msg = JSON.parse(data);
|
|
196
|
+
if (msg.id !== 1) return;
|
|
197
|
+
clearTimeout(timer);
|
|
198
|
+
if (msg.error || !msg.result?.processInfo) return fail();
|
|
199
|
+
resolve(msg.result.processInfo);
|
|
200
|
+
} catch { fail(); }
|
|
201
|
+
};
|
|
202
|
+
});
|
|
203
|
+
return one(processes.filter(p => p.type === 'browser'), 'browser process').id;
|
|
204
|
+
} finally { socket.close(); }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function descendants(root) {
|
|
208
|
+
return [root, ...(root.children ?? []).flatMap(descendants)];
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function pickerIn(snapshot) {
|
|
212
|
+
const children = (snapshot.tree.children ?? []).filter(n => n.role === 'window' || n.role === 'dialog');
|
|
213
|
+
if (!children.length) {
|
|
214
|
+
if (!snapshot.complete || snapshot.tree.subtree_truncated) throw new Error('Cannot determine whether a dialog is open.');
|
|
215
|
+
return null;
|
|
216
|
+
}
|
|
217
|
+
const nodes = descendants(one(children, 'owned dialog'));
|
|
218
|
+
const control = (id, roles) => one(nodes.filter(n => n.native_id?.kind === 'automation_id' && n.native_id.value === id && roles.includes(n.role) && n.ref_id), 'standard file dialog control ' + id);
|
|
219
|
+
return { field: control('1148', ['textfield']), open: control('1', ['button', 'menubutton']) };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function readFileInput(selector) {
|
|
223
|
+
const nodes = document.querySelectorAll(selector);
|
|
224
|
+
const field = nodes[0];
|
|
225
|
+
if (nodes.length !== 1 || !(field instanceof HTMLInputElement) || field.type !== 'file' || field.disabled) {
|
|
226
|
+
throw new Error('Expected a unique enabled file input');
|
|
227
|
+
}
|
|
228
|
+
const files = Array.from(field.files, ({ name, size, lastModified }) => ({ name, size, lastModified }));
|
|
229
|
+
return { url: location.href, epoch: performance.timeOrigin, files };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async function chooseFile({ session, tab, input, file }) {
|
|
233
|
+
if (process.platform !== 'win32' || typeof WebSocket === 'undefined') throw new Error('Requires Windows and Node.js 22 or newer.');
|
|
234
|
+
if (![session, input, file].every(Boolean) || !isAbsolute(file)) throw invalid(usage);
|
|
235
|
+
const stat = statSync(file);
|
|
236
|
+
if (!stat.isFile()) throw new Error('Expected a regular file.');
|
|
237
|
+
const { ab, original, check } = boundTab(session, tab);
|
|
238
|
+
const db = process.env.AGENT_DESKTOP_BIN ?? join(__dirname, 'agent-desktop-win32-' + process.arch + '.exe');
|
|
239
|
+
const ad = (...args) => run(db, args, undefined, undefined, foregroundInterruption);
|
|
240
|
+
|
|
241
|
+
const page = () => {
|
|
242
|
+
check();
|
|
243
|
+
return ab('eval', '(' + readFileInput.toString() + ')(' + JSON.stringify(input) + ')').result;
|
|
244
|
+
};
|
|
245
|
+
const initial = page();
|
|
246
|
+
const verifyPage = () => {
|
|
247
|
+
const current = page();
|
|
248
|
+
if (current.url !== initial.url || current.epoch !== initial.epoch) throw new Error('The original tab navigated.');
|
|
249
|
+
return current;
|
|
250
|
+
};
|
|
251
|
+
const pid = await browserPid(ab('get', 'cdp-url').cdpUrl);
|
|
252
|
+
const window = one(ad('list-windows').filter(w => w.pid === pid && w.visible && !w.minimized), 'visible window owned by this browser');
|
|
253
|
+
const dialog = () => {
|
|
254
|
+
if (!window.process_instance || !ad('list-windows').some(w => w.id === window.id && w.pid === pid && w.process_instance === window.process_instance)) {
|
|
255
|
+
throw new Error('The original native window is gone.');
|
|
256
|
+
}
|
|
257
|
+
return pickerIn(ad('snapshot', '--window-id', window.id, '--compact', '-i', '--max-depth', '20'));
|
|
258
|
+
};
|
|
259
|
+
if (dialog()) throw new Error('Close the existing browser dialog first.');
|
|
260
|
+
verifyPage();
|
|
261
|
+
ab('click', input);
|
|
262
|
+
const until = Date.now() + 5000;
|
|
263
|
+
let picker;
|
|
264
|
+
while (!(picker = dialog())) {
|
|
265
|
+
if (Date.now() >= until) throw new Error('The browser file dialog did not open or was cancelled.');
|
|
266
|
+
await delay(80);
|
|
267
|
+
}
|
|
268
|
+
verifyPage();
|
|
269
|
+
ad('set-value', picker.field.ref_id, file);
|
|
270
|
+
picker = dialog();
|
|
271
|
+
if (picker?.field.value !== file) throw new Error('The file dialog closed or its filename changed.');
|
|
272
|
+
verifyPage();
|
|
273
|
+
ad('click', picker.open.ref_id);
|
|
274
|
+
const end = Date.now() + 4000;
|
|
275
|
+
do {
|
|
276
|
+
const files = verifyPage().files;
|
|
277
|
+
if (files.length === 1 && files[0].name === basename(file) && files[0].size === stat.size && files[0].lastModified === Math.trunc(stat.mtimeMs) && !dialog()) {
|
|
278
|
+
return { tab: original.tabId, targetId: original.targetId, file: files[0] };
|
|
279
|
+
}
|
|
280
|
+
await delay(80);
|
|
281
|
+
} while (Date.now() < end);
|
|
282
|
+
throw new Error('File selection was not confirmed on the original input.');
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** A shell that splits `812,604` into separate words still means one coordinate. */
|
|
286
|
+
function joinCoordinates(args) {
|
|
287
|
+
const joined = [];
|
|
288
|
+
for (let i = 0; i < args.length; i++) {
|
|
289
|
+
joined.push(args[i]);
|
|
290
|
+
if (!['--at', '--from', '--to', '--region'].includes(args[i])) continue;
|
|
291
|
+
const parts = [];
|
|
292
|
+
while (/^-?\d+(\.\d+)?$/.test(args[i + 1] ?? '')) parts.push(args[++i]);
|
|
293
|
+
if (parts.length) joined.push(parts.join(','));
|
|
294
|
+
}
|
|
295
|
+
return joined;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async function main() {
|
|
299
|
+
const args = process.argv.slice(2);
|
|
300
|
+
if (args[0] === 'desktop' || args[0] === 'browser') {
|
|
301
|
+
if (args[0] === 'desktop' && !args.includes('--help') && !args.includes('--version')) initializeStateDir();
|
|
302
|
+
const binary = args.shift() === 'desktop' ? nativeBinary() : browserBinary();
|
|
303
|
+
const child = spawnSync(binary, args, { stdio: 'inherit', windowsHide: true });
|
|
304
|
+
if (child.error) throw child.error;
|
|
305
|
+
process.exitCode = child.status ?? 1;
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
if (args.includes('--help')) { console.log(usage); return; }
|
|
309
|
+
if (args[0] === '--version') { console.log(JSON.stringify({ ok: true, data: versionReport({ nativeBinary: nativeBinary(), browserBinary: optionalBrowserBinary() }) })); return; }
|
|
310
|
+
if (Number(process.versions.node.split('.')[0]) < 22) throw new Error('The workflow commands require Node.js 22 or later.');
|
|
311
|
+
const command = args.shift();
|
|
312
|
+
if (!Object.hasOwn(COMMAND_OPTIONS, command)) throw invalid(usage);
|
|
313
|
+
if (command === 'mcp') { await mcp.serve({ workflowPath: __filename }); return; }
|
|
314
|
+
const names = COMMAND_OPTIONS[command];
|
|
315
|
+
const { values, positionals } = parseArgs({ args: joinCoordinates(args), options: parseOptions(command), allowPositionals: POSITIONAL_COMMANDS.includes(command) });
|
|
316
|
+
if (names.includes('session') && !['run', 'routine'].includes(command) && !values.page && !values.session) values.session = process.env.AGENT_BROWSER_SESSION;
|
|
317
|
+
if (command === 'run' && values.api) { console.log(api); return; }
|
|
318
|
+
if (command === 'skill' && !values.list && !values.install) { console.log(skill.read(positionals[0])); return; }
|
|
319
|
+
initializeStateDir();
|
|
320
|
+
const own = {
|
|
321
|
+
replay: () => replay(values),
|
|
322
|
+
run: () => script(values),
|
|
323
|
+
routine: () => routine(positionals, values),
|
|
324
|
+
job: () => host.job(positionals, values, path => readText(path, '--file')),
|
|
325
|
+
host: () => host.hostCommand(positionals, { workflowPath: __filename, nativeBinary: nativeBinary() }),
|
|
326
|
+
'job-run': () => jobRun(positionals[0]),
|
|
327
|
+
watch: () => host.watch(positionals, values, { workflowPath: __filename, readText: path => readText(path, '--args-file'), routineExists: routines.requireRoutine,
|
|
328
|
+
settle: routine => runnerValues(prefs.runnerOptions(prefs.resolveSettings({ routine }), {})) }),
|
|
329
|
+
prefs: () => prefs.prefsCommand(positionals, values),
|
|
330
|
+
skill: () => (values.list ? { parts: skill.parts() } : skill.install({ dir: values.dir, force: Boolean(values.force) })),
|
|
331
|
+
space: () => space(browserBinary(), values),
|
|
332
|
+
read: () => readPage(browserBinary(), values.url ?? ''),
|
|
333
|
+
};
|
|
334
|
+
const data = await (own[command] ?? (() => perform(command, values)))();
|
|
335
|
+
if (process.env.AGENT_DESKTOP_RECORD) recordStep(process.env.AGENT_DESKTOP_RECORD, command, values);
|
|
336
|
+
console.log(JSON.stringify({ ok: true, data }));
|
|
337
|
+
if (command === 'run' || command === 'routine' || command === 'job') leave(0);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function nativeBinary() {
|
|
341
|
+
return process.env.AGENT_DESKTOP_BIN ?? join(__dirname, 'agent-desktop-win32-' + process.arch + '.exe');
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
async function replay({ file, window, speed = '1' }) {
|
|
345
|
+
const ad = (...args) => run(nativeBinary(), args, undefined, undefined, foregroundInterruption);
|
|
346
|
+
const factor = Number(speed);
|
|
347
|
+
if (!file || !(factor > 0)) throw invalid('Use --file FLOW.jsonl and a positive --speed.');
|
|
348
|
+
const steps = readSteps(file);
|
|
349
|
+
const report = [];
|
|
350
|
+
for (const [index, step] of steps.entries()) {
|
|
351
|
+
if (step.wait_ms) await delay(step.wait_ms / factor);
|
|
352
|
+
const options = { ...step.options };
|
|
353
|
+
if (step.needs_page) options.page = (await current(ad, { window })).page;
|
|
354
|
+
try {
|
|
355
|
+
const data = await perform(step.command, options);
|
|
356
|
+
report.push({ step: index + 1, command: step.command, delivery: data?.delivery, verified: data?.verified });
|
|
357
|
+
} catch (error) {
|
|
358
|
+
error.message = 'Replay stopped at step ' + (index + 1) + ' (' + step.command + '): ' + error.message;
|
|
359
|
+
throw error;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return { steps: report.length, report };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** The runner options a detached job carries to its own process. */
|
|
366
|
+
function runnerValues(values) {
|
|
367
|
+
return Object.fromEntries(['session', 'chrome', 'space', 'timeout-ms', 'allow-input', 'allow-final', 'pace', 'pointer', 'screen'].filter(k => values[k] !== undefined).map(k => [k, values[k]]));
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** A job may wait hours for a fix, the hands or the user's word before a final step, so its own clock is long. */
|
|
371
|
+
const JOB_TIMEOUT_MS = 6 * 60 * 60 * 1000;
|
|
372
|
+
|
|
373
|
+
/** One detached job: runs its script with the same runner, and a failed step waits for a fix sent through the host. */
|
|
374
|
+
async function jobRun(dir) {
|
|
375
|
+
const start = JSON.parse(readFileSync(join(dir, 'start.json'), 'utf8'));
|
|
376
|
+
return host.runJob(start, { runner: scriptRunner({ 'timeout-ms': String(JOB_TIMEOUT_MS), ...start.values }), routines, nativeBinary: nativeBinary() });
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** The runner both `run` and `routine run` use: same helpers, same refusals, same reply. */
|
|
380
|
+
function scriptRunner({ session, chrome, space: own, 'timeout-ms': wait = '120000', 'allow-input': allowInput = false, 'allow-final': allowFinal = false, pace, pointer, screen = false }) {
|
|
381
|
+
const timeout = Number(wait);
|
|
382
|
+
if (!(timeout > 0)) throw invalid('--timeout-ms takes a positive number.');
|
|
383
|
+
if ([session, chrome, own].filter(Boolean).length > 1) throw invalid('Choose one of --session NAME, --space and --chrome.');
|
|
384
|
+
process.env.AGENT_DESKTOP_POINTER_HOLDER ??= String(process.pid);
|
|
385
|
+
if (pointer) process.env.AGENT_DESKTOP_POINTER ??= pointer;
|
|
386
|
+
const flags = own ? spaceFlags() : chrome ? chromeFlags() : ['--session', session ?? BACKGROUND_SESSION];
|
|
387
|
+
return (source, extra) => runScript(source, {
|
|
388
|
+
browser: optionalBrowserBinary(), native: nativeBinary(), timeout, flow: perform, allowInput, allowFinal, startPace: pace, screen,
|
|
389
|
+
flags, lease: pageLease(flags, { own: !own && !chrome && !session }),
|
|
390
|
+
env: chrome ? { ...process.env, AGENT_BROWSER_IDLE_TIMEOUT_MS: '0' } : process.env, ...extra,
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** The first script that runs on a computer carries a short note on the ways of working, for the agent to pass on once. */
|
|
395
|
+
function welcomed(reply) {
|
|
396
|
+
return prefs.firstUse() ? { ...reply, welcome: prefs.WELCOME } : reply;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
async function script(values) {
|
|
400
|
+
const { file, save, about, param, replace = false, detach } = values;
|
|
401
|
+
if (!file && process.stdin.isTTY) throw invalid('Pipe a script to run, or pass --file SCRIPT.js.');
|
|
402
|
+
if ((about !== undefined || param || replace) && !save) throw invalid('--about, --param and --replace go with --save NAME.');
|
|
403
|
+
if (detach && save) throw invalid('--save runs in the foreground; leave out --detach.');
|
|
404
|
+
const args = routines.readArgs(values, path => readText(path, '--args-file'));
|
|
405
|
+
const source = (file ? readText(file, '--file') : readFileSync(0, 'utf8')).replace(/^\uFEFF/, '');
|
|
406
|
+
const settings = prefs.resolveSettings({ request: { mode: values.mode } });
|
|
407
|
+
const options = prefs.runnerOptions(settings, values);
|
|
408
|
+
if (detach) return welcomed({ ...await host.detach({ source, args, values: runnerValues(options) }, { workflowPath: __filename }), ...prefs.settingsNote(settings) });
|
|
409
|
+
const run = scriptRunner(options);
|
|
410
|
+
try {
|
|
411
|
+
const done = await run(source, { args, watch: Boolean(save) });
|
|
412
|
+
clearRepeat();
|
|
413
|
+
const reply = { ...done, ...prefs.settingsNote(settings) };
|
|
414
|
+
if (save) {
|
|
415
|
+
const saved = routines.save({ name: save, about, params: param, replace, source, args, done });
|
|
416
|
+
if (values.mode) prefs.rememberRoutineMode(save, values.mode);
|
|
417
|
+
return welcomed({ ...reply, saved });
|
|
418
|
+
}
|
|
419
|
+
const known = routines.knownRoutines(done.trail);
|
|
420
|
+
return welcomed(known.length ? { ...reply, known_routines: known, known_note: 'Saved routines already work on this app or site. Before writing steps here again, check them with routine show NAME and use routine run NAME.' } : reply);
|
|
421
|
+
} catch (err) {
|
|
422
|
+
throw markRepeat(err);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async function routine([action, name, ...rest], values) {
|
|
427
|
+
if (rest.length) throw invalid(usage);
|
|
428
|
+
if (action === 'list') return routines.list(values.for);
|
|
429
|
+
if (action === 'permissions') return routines.permissions();
|
|
430
|
+
if (action === 'allow' && name) return routines.allow(name);
|
|
431
|
+
if (action === 'revoke' && name) return routines.revoke(name);
|
|
432
|
+
if (!name) throw invalid('Name the routine: routine ' + (action ?? 'run') + ' NAME.');
|
|
433
|
+
if (action === 'show') return routines.show(name);
|
|
434
|
+
if (action === 'remove') return routines.remove(name);
|
|
435
|
+
if (action !== 'run') throw invalid(usage);
|
|
436
|
+
routines.requireRoutine(name);
|
|
437
|
+
const args = routines.readArgs(values, path => readText(path, '--args-file'));
|
|
438
|
+
const settings = prefs.resolveSettings({ routine: name, request: { mode: values.mode } });
|
|
439
|
+
const options = prefs.runnerOptions(settings, values);
|
|
440
|
+
if (values.detach) return welcomed({ ...await host.detach({ routine: name, args, values: runnerValues(options) }, { workflowPath: __filename }), ...prefs.settingsNote(settings) });
|
|
441
|
+
try {
|
|
442
|
+
const done = await routines.runRoutine(name, args, scriptRunner(options));
|
|
443
|
+
clearRepeat();
|
|
444
|
+
return welcomed({ ...done, ...prefs.settingsNote(settings) });
|
|
445
|
+
} catch (err) {
|
|
446
|
+
throw markRepeat(err);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
async function perform(command, values, check) {
|
|
451
|
+
const db = nativeBinary();
|
|
452
|
+
const nativeCall = (args, input) => run(db, args, input, check, foregroundInterruption);
|
|
453
|
+
const ad = (...args) => nativeCall(args);
|
|
454
|
+
const web = await webPerform(optionalBrowserBinary(), command, values);
|
|
455
|
+
if (web) return web;
|
|
456
|
+
let data;
|
|
457
|
+
switch (command) {
|
|
458
|
+
case 'connect': data = connect(browserBinary(), values); break;
|
|
459
|
+
case 'disconnect': data = disconnect(); break;
|
|
460
|
+
case 'current': {
|
|
461
|
+
const page = await current(ad, values);
|
|
462
|
+
data = values.visible ? { ...page, route: 'desktop' } : withRoute(optionalBrowserBinary(), page);
|
|
463
|
+
break;
|
|
464
|
+
}
|
|
465
|
+
case 'follow': data = await follow(ad, values, physicalPointer); break;
|
|
466
|
+
case 'choose-file': data = await chooseFile(values); break;
|
|
467
|
+
case 'choose':
|
|
468
|
+
if (!values.page && (values.within || values.open || values.popup || values.advance || values.search || values.confirm || values['expect-value'])) throw invalid('Native choice options require --page.');
|
|
469
|
+
data = values.page !== undefined ? await choosePage(ad, values) : choose(values);
|
|
470
|
+
break;
|
|
471
|
+
case 'reveal': {
|
|
472
|
+
if (!values.session || !values.within || !values.text?.trim()) throw invalid(usage);
|
|
473
|
+
const {original,check,evaluate}=boundTab(values.session,values.tab);
|
|
474
|
+
check();
|
|
475
|
+
data = {tab:original.tabId,...evaluate(revealText,values.within,values.text,original.url)};
|
|
476
|
+
check();
|
|
477
|
+
break;
|
|
478
|
+
}
|
|
479
|
+
case 'view': data = view(ad, values); break;
|
|
480
|
+
case 'type': data = await typePage(ad, nativeCall, values); break;
|
|
481
|
+
case 'wheel': data = await wheelPage(ad,values); break;
|
|
482
|
+
case 'point': case 'click': data = await pointerPage(ad,command,values); break;
|
|
483
|
+
case 'edit': {
|
|
484
|
+
data = values.page ? await editPage(ad, nativeCall, values) : edit(ad, nativeCall, values);
|
|
485
|
+
break;
|
|
486
|
+
}
|
|
487
|
+
case 'move': data = move(ad, values); break;
|
|
488
|
+
case 'tap': data = tap(ad, values); break;
|
|
489
|
+
case 'browser-move': data = await browserMove(boundTab, values); break;
|
|
490
|
+
case 'drop-file': data = await dropFile(boundTab, values); break;
|
|
491
|
+
}
|
|
492
|
+
return data;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
main().catch(err => {
|
|
496
|
+
const partial=err.details?.typed_keystrokes;
|
|
497
|
+
console.error(JSON.stringify({ok:false,error:err.message,code:errorCode(err),...(err.disposition ? {disposition:err.disposition} : {}),
|
|
498
|
+
...(err.suggestion ? {suggestion:err.suggestion} : {}),
|
|
499
|
+
...(Number.isInteger(partial) ? {typed_keystrokes:partial,keystrokes:err.details.keystrokes} : {}),
|
|
500
|
+
...(err.report ?? {}),
|
|
501
|
+
...(err.details && ['MISSING_ARGS','EFFECT_MISMATCH','FINAL_NOT_ALLOWED','AMBIGUOUS_TARGET','FOREGROUND_TAKEN'].includes(err.code) ? {details:err.details} : {})}));
|
|
502
|
+
process.exitCode=1;
|
|
503
|
+
if (err.report) leave(1);
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* A script that timed out or failed can still have timers of its own pending. The reply is already out, so the
|
|
508
|
+
* process ends now: the commands it started stop holding the agent pointer, and the caller gets its exit code.
|
|
509
|
+
*/
|
|
510
|
+
function leave(code) {
|
|
511
|
+
process.stdout.write('', () => process.stderr.write('', () => process.exit(code)));
|
|
512
|
+
}
|