@arhan-w/ibex 0.0.0-stage → 3.6.0
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 +21 -0
- package/README.md +295 -2
- package/npm-package/LICENSE +21 -0
- package/npm-package/README.md +176 -0
- package/npm-package/bin/goat.js +3 -0
- package/npm-package/bin/ibex.js +77 -0
- package/npm-package/package.json +58 -0
- package/npm-package/scripts/install-binary.js +168 -0
- package/package.json +69 -6
- package/src/agent.ts +695 -0
- package/src/agents/loader.ts +110 -0
- package/src/ambient.d.ts +2 -0
- package/src/code/extract.ts +292 -0
- package/src/code/find.ts +244 -0
- package/src/code/grammars.ts +88 -0
- package/src/code/indexer.ts +242 -0
- package/src/code/semantic.ts +253 -0
- package/src/code/slash.ts +88 -0
- package/src/code/tool.ts +40 -0
- package/src/collab/client.ts +141 -0
- package/src/collab/handlers.ts +141 -0
- package/src/collab/invite.ts +39 -0
- package/src/collab/relay.ts +106 -0
- package/src/collab/sync.ts +131 -0
- package/src/commands.tsx +943 -0
- package/src/computer.ts +629 -0
- package/src/config.ts +318 -0
- package/src/constants.ts +18 -0
- package/src/context.ts +73 -0
- package/src/data/providers.json +2342 -0
- package/src/diff.ts +50 -0
- package/src/doctor.ts +443 -0
- package/src/errors.ts +139 -0
- package/src/gflash.ts +170 -0
- package/src/hooks.ts +133 -0
- package/src/ide/assets.gen.ts +3 -0
- package/src/ide/index.html +844 -0
- package/src/ide/server.ts +506 -0
- package/src/ide/vendor/marked.umd.js +80 -0
- package/src/ide/vendor/vs/base/browser/ui/codicons/codicon/codicon.ttf +0 -0
- package/src/ide/vendor/vs/base/worker/workerMain.js +31 -0
- package/src/ide/vendor/vs/basic-languages/abap/abap.js +10 -0
- package/src/ide/vendor/vs/basic-languages/apex/apex.js +10 -0
- package/src/ide/vendor/vs/basic-languages/azcli/azcli.js +10 -0
- package/src/ide/vendor/vs/basic-languages/bat/bat.js +10 -0
- package/src/ide/vendor/vs/basic-languages/bicep/bicep.js +11 -0
- package/src/ide/vendor/vs/basic-languages/cameligo/cameligo.js +10 -0
- package/src/ide/vendor/vs/basic-languages/clojure/clojure.js +10 -0
- package/src/ide/vendor/vs/basic-languages/coffee/coffee.js +10 -0
- package/src/ide/vendor/vs/basic-languages/cpp/cpp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/csharp/csharp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/csp/csp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/css/css.js +12 -0
- package/src/ide/vendor/vs/basic-languages/cypher/cypher.js +10 -0
- package/src/ide/vendor/vs/basic-languages/dart/dart.js +10 -0
- package/src/ide/vendor/vs/basic-languages/dockerfile/dockerfile.js +10 -0
- package/src/ide/vendor/vs/basic-languages/ecl/ecl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/elixir/elixir.js +10 -0
- package/src/ide/vendor/vs/basic-languages/flow9/flow9.js +10 -0
- package/src/ide/vendor/vs/basic-languages/freemarker2/freemarker2.js +12 -0
- package/src/ide/vendor/vs/basic-languages/fsharp/fsharp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/go/go.js +10 -0
- package/src/ide/vendor/vs/basic-languages/graphql/graphql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/handlebars/handlebars.js +10 -0
- package/src/ide/vendor/vs/basic-languages/hcl/hcl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/html/html.js +10 -0
- package/src/ide/vendor/vs/basic-languages/ini/ini.js +10 -0
- package/src/ide/vendor/vs/basic-languages/java/java.js +10 -0
- package/src/ide/vendor/vs/basic-languages/javascript/javascript.js +10 -0
- package/src/ide/vendor/vs/basic-languages/julia/julia.js +10 -0
- package/src/ide/vendor/vs/basic-languages/kotlin/kotlin.js +10 -0
- package/src/ide/vendor/vs/basic-languages/less/less.js +11 -0
- package/src/ide/vendor/vs/basic-languages/lexon/lexon.js +10 -0
- package/src/ide/vendor/vs/basic-languages/liquid/liquid.js +10 -0
- package/src/ide/vendor/vs/basic-languages/lua/lua.js +10 -0
- package/src/ide/vendor/vs/basic-languages/m3/m3.js +10 -0
- package/src/ide/vendor/vs/basic-languages/markdown/markdown.js +10 -0
- package/src/ide/vendor/vs/basic-languages/mdx/mdx.js +10 -0
- package/src/ide/vendor/vs/basic-languages/mips/mips.js +10 -0
- package/src/ide/vendor/vs/basic-languages/msdax/msdax.js +10 -0
- package/src/ide/vendor/vs/basic-languages/mysql/mysql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/objective-c/objective-c.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pascal/pascal.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pascaligo/pascaligo.js +10 -0
- package/src/ide/vendor/vs/basic-languages/perl/perl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pgsql/pgsql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/php/php.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pla/pla.js +10 -0
- package/src/ide/vendor/vs/basic-languages/postiats/postiats.js +10 -0
- package/src/ide/vendor/vs/basic-languages/powerquery/powerquery.js +10 -0
- package/src/ide/vendor/vs/basic-languages/powershell/powershell.js +10 -0
- package/src/ide/vendor/vs/basic-languages/protobuf/protobuf.js +11 -0
- package/src/ide/vendor/vs/basic-languages/pug/pug.js +10 -0
- package/src/ide/vendor/vs/basic-languages/python/python.js +10 -0
- package/src/ide/vendor/vs/basic-languages/qsharp/qsharp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/r/r.js +10 -0
- package/src/ide/vendor/vs/basic-languages/razor/razor.js +10 -0
- package/src/ide/vendor/vs/basic-languages/redis/redis.js +10 -0
- package/src/ide/vendor/vs/basic-languages/redshift/redshift.js +10 -0
- package/src/ide/vendor/vs/basic-languages/restructuredtext/restructuredtext.js +10 -0
- package/src/ide/vendor/vs/basic-languages/ruby/ruby.js +10 -0
- package/src/ide/vendor/vs/basic-languages/rust/rust.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sb/sb.js +10 -0
- package/src/ide/vendor/vs/basic-languages/scala/scala.js +10 -0
- package/src/ide/vendor/vs/basic-languages/scheme/scheme.js +10 -0
- package/src/ide/vendor/vs/basic-languages/scss/scss.js +12 -0
- package/src/ide/vendor/vs/basic-languages/shell/shell.js +10 -0
- package/src/ide/vendor/vs/basic-languages/solidity/solidity.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sophia/sophia.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sparql/sparql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sql/sql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/st/st.js +10 -0
- package/src/ide/vendor/vs/basic-languages/swift/swift.js +13 -0
- package/src/ide/vendor/vs/basic-languages/systemverilog/systemverilog.js +10 -0
- package/src/ide/vendor/vs/basic-languages/tcl/tcl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/twig/twig.js +10 -0
- package/src/ide/vendor/vs/basic-languages/typescript/typescript.js +10 -0
- package/src/ide/vendor/vs/basic-languages/typespec/typespec.js +10 -0
- package/src/ide/vendor/vs/basic-languages/vb/vb.js +10 -0
- package/src/ide/vendor/vs/basic-languages/wgsl/wgsl.js +307 -0
- package/src/ide/vendor/vs/basic-languages/xml/xml.js +10 -0
- package/src/ide/vendor/vs/basic-languages/yaml/yaml.js +10 -0
- package/src/ide/vendor/vs/editor/editor.main.css +8 -0
- package/src/ide/vendor/vs/editor/editor.main.js +798 -0
- package/src/ide/vendor/vs/language/css/cssMode.js +13 -0
- package/src/ide/vendor/vs/language/css/cssWorker.js +77 -0
- package/src/ide/vendor/vs/language/html/htmlMode.js +13 -0
- package/src/ide/vendor/vs/language/html/htmlWorker.js +454 -0
- package/src/ide/vendor/vs/language/json/jsonMode.js +19 -0
- package/src/ide/vendor/vs/language/json/jsonWorker.js +42 -0
- package/src/ide/vendor/vs/language/typescript/tsMode.js +20 -0
- package/src/ide/vendor/vs/language/typescript/tsWorker.js +51328 -0
- package/src/ide/vendor/vs/loader.js +11 -0
- package/src/index-shared.ts +117 -0
- package/src/index.ts +586 -0
- package/src/llm.ts +721 -0
- package/src/logger.ts +39 -0
- package/src/mcp/client.ts +121 -0
- package/src/mcp/types.ts +27 -0
- package/src/oauth.ts +205 -0
- package/src/onboarding.ts +140 -0
- package/src/palette.tsx +199 -0
- package/src/permissions.ts +123 -0
- package/src/plugins/loader.ts +120 -0
- package/src/plugins/marketplace.ts +252 -0
- package/src/plugins/sandbox.ts +303 -0
- package/src/plugins/tar.ts +241 -0
- package/src/pricing.ts +78 -0
- package/src/protocol/client.ts +102 -0
- package/src/protocol/rpc.ts +43 -0
- package/src/protocol/serve.ts +136 -0
- package/src/providers.ts +402 -0
- package/src/rate-limiter.ts +101 -0
- package/src/refs.ts +97 -0
- package/src/runtime.ts +144 -0
- package/src/session.ts +401 -0
- package/src/skills/loader.ts +136 -0
- package/src/statusline.ts +70 -0
- package/src/system-prompt.ts +28 -0
- package/src/tools.ts +1280 -0
- package/src/tui.tsx +1355 -0
- package/src/update.ts +236 -0
- package/src/vendor/flashServer.ts +2 -0
- package/src/vendor/gemini-web2api/gemini_web2api.py +1136 -0
- package/src/virtual-list.tsx +125 -0
- package/src/window.ts +31 -0
- package/tsconfig.json +16 -0
package/src/computer.ts
ADDED
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Desktop control ("computer use") — GoatCode can see the screen and drive
|
|
3
|
+
* real apps: open things, click, type, read windows, use the clipboard.
|
|
4
|
+
*
|
|
5
|
+
* Two backends, auto-detected:
|
|
6
|
+
* 1. cua-driver (preferred) — the open-source accessibility driver daemon.
|
|
7
|
+
* Background input: clicks/types go to target windows WITHOUT stealing
|
|
8
|
+
* focus or moving the user's cursor.
|
|
9
|
+
* 2. Native fallbacks — PowerShell SendInput + GDI (Windows),
|
|
10
|
+
* osascript + screencapture (macOS), xdotool + ImageMagick (Linux).
|
|
11
|
+
* Foreground input; works on any stock OS with zero installs.
|
|
12
|
+
*
|
|
13
|
+
* Every mutating action flows through the ToolKit permission system and
|
|
14
|
+
* deny rules; a few hard-forbidden keys (lock, sign-out) are refused outright.
|
|
15
|
+
*/
|
|
16
|
+
import { execFile } from "node:child_process";
|
|
17
|
+
import { existsSync, readFileSync, statSync, unlinkSync } from "node:fs";
|
|
18
|
+
import { homedir, tmpdir } from "node:os";
|
|
19
|
+
import { join } from "node:path";
|
|
20
|
+
import { log } from "./logger.ts";
|
|
21
|
+
|
|
22
|
+
const DRIVER_TIMEOUT_MS = 30_000;
|
|
23
|
+
const OS_TIMEOUT_MS = 20_000;
|
|
24
|
+
|
|
25
|
+
/** Key combos that must never be sent, whatever the model asks for. */
|
|
26
|
+
const FORBIDDEN_KEYS = [
|
|
27
|
+
/^win\+l$/i, /^super\+l$/i, // lock workstation
|
|
28
|
+
/^ctrl\+alt\+delete$/i,
|
|
29
|
+
/^cmd\+option\+esc$/i, // force-quit panel
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
export interface Shot {
|
|
33
|
+
png: Buffer;
|
|
34
|
+
width: number;
|
|
35
|
+
height: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function run(cmd: string, args: string[], timeoutMs: number, stdinData?: string): Promise<{ code: number; stdout: string; stderr: string }> {
|
|
39
|
+
return new Promise((done) => {
|
|
40
|
+
const child = execFile(cmd, args, { timeout: timeoutMs, windowsHide: true, maxBuffer: 64 * 1024 * 1024 },
|
|
41
|
+
(err, stdout, stderr) => {
|
|
42
|
+
done({ code: err ? ((err as any).killed ? -1 : 1) : 0, stdout: stdout ?? "", stderr: stderr ?? "" });
|
|
43
|
+
});
|
|
44
|
+
if (stdinData !== undefined) child.stdin?.end(stdinData);
|
|
45
|
+
else child.stdin?.end();
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// ---------- backend: cua-driver ----------
|
|
50
|
+
|
|
51
|
+
/** Normalize a cua-driver window row (new `bounds` shape or legacy flat x/y/w/h). */
|
|
52
|
+
function normWin(v: any): { pid: number; title: string; x: number; y: number; width: number; height: number; onScreen: boolean; minimized: boolean; z: number } {
|
|
53
|
+
const b = v.bounds ?? v;
|
|
54
|
+
return {
|
|
55
|
+
pid: Number(v.pid ?? 0), title: String(v.title ?? ""),
|
|
56
|
+
x: Number(b.x ?? 0), y: Number(b.y ?? 0),
|
|
57
|
+
width: Number(b.width ?? 0), height: Number(b.height ?? 0),
|
|
58
|
+
onScreen: v.is_on_screen !== false, minimized: v.minimized === true,
|
|
59
|
+
z: Number(v.z_index ?? 0),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
class CuaDriver {
|
|
64
|
+
constructor(private exe: string) {}
|
|
65
|
+
|
|
66
|
+
async call(tool: string, args: Record<string, unknown> = {}): Promise<any> {
|
|
67
|
+
const r = await run(this.exe, ["call", tool, JSON.stringify(args)], DRIVER_TIMEOUT_MS);
|
|
68
|
+
if (r.code !== 0 || !r.stdout.trim())
|
|
69
|
+
throw new Error(`cua-driver ${tool}: ${(r.stderr || r.stdout).slice(0, 300) || "no output"}`);
|
|
70
|
+
try { return JSON.parse(r.stdout); } catch { return { text: r.stdout.slice(0, 4000) }; }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async available(): Promise<boolean> {
|
|
74
|
+
try {
|
|
75
|
+
const r = await this.call("get_screen_size");
|
|
76
|
+
return Number(r.width ?? r.screen_width) > 0;
|
|
77
|
+
} catch {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** On-screen, unminimized, non-driver windows, front-most first. */
|
|
83
|
+
private async realWindows(): Promise<ReturnType<typeof normWin>[]> {
|
|
84
|
+
const w = await this.call("list_windows");
|
|
85
|
+
const rows: any[] = w.windows ?? w._legacy_windows ?? [];
|
|
86
|
+
return rows.map(normWin)
|
|
87
|
+
.filter((v) => v.onScreen && !v.minimized && v.pid > 0 && !/cua\.agentcursor/i.test(v.title) && v.width < 10000)
|
|
88
|
+
.sort((a, b) => b.z - a.z);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async shot(): Promise<Shot> {
|
|
92
|
+
const d = await this.call("get_desktop_state");
|
|
93
|
+
if (!d.screenshot_png_b64) throw new Error("cua-driver returned no pixels");
|
|
94
|
+
return {
|
|
95
|
+
png: Buffer.from(d.screenshot_png_b64, "base64"),
|
|
96
|
+
width: Number(d.screen_width ?? d.screenshot_width ?? 0),
|
|
97
|
+
height: Number(d.screen_height ?? d.screenshot_height ?? 0),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async click(x: number, y: number, button: string, double: boolean, pid?: number): Promise<string> {
|
|
102
|
+
const extra: Record<string, unknown> = pid ? { pid } : { scope: "desktop" };
|
|
103
|
+
let kind: string;
|
|
104
|
+
if (button === "right") kind = "right_click";
|
|
105
|
+
else if (double) kind = "double_click";
|
|
106
|
+
else kind = "click";
|
|
107
|
+
if (kind === "click" && button !== "left") extra.button = button;
|
|
108
|
+
const r = await this.call(kind, { x, y, ...extra });
|
|
109
|
+
return `${kind} at (${x},${y}) → ${r.effect ?? "sent"}`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Resolve a target pid (and window_id when the title pins one window) from args. */
|
|
113
|
+
async targetPid(a: Record<string, any>): Promise<number> {
|
|
114
|
+
return (await this.target(a)).pid;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** pid + optional window_id chosen from `pid` and/or a window-title substring. */
|
|
118
|
+
async target(a: Record<string, any>): Promise<{ pid: number; window_id?: number }> {
|
|
119
|
+
const rows = await this.windowRows();
|
|
120
|
+
if (a.pid) {
|
|
121
|
+
const p = Number(a.pid);
|
|
122
|
+
// an app with several windows is ambiguous for the driver — pin the
|
|
123
|
+
// front-most visible one by window_id so input lands where it should
|
|
124
|
+
const mine = rows.filter((v) => v.pid === p && v.onScreen && !v.minimized && v.window_id);
|
|
125
|
+
if (mine.length === 1) return { pid: p, window_id: Number(mine[0].window_id) };
|
|
126
|
+
if (mine.length > 1) {
|
|
127
|
+
mine.sort((x, y) => y.z - x.z);
|
|
128
|
+
return { pid: p, window_id: Number(mine[0].window_id) };
|
|
129
|
+
}
|
|
130
|
+
return { pid: p }; // let the driver route/ask
|
|
131
|
+
}
|
|
132
|
+
const title = String(a.window_title ?? a.title ?? "");
|
|
133
|
+
if (title) {
|
|
134
|
+
const hits = rows.filter((v) => v.title.toLowerCase().includes(title.toLowerCase()));
|
|
135
|
+
if (hits.length === 1) return { pid: Number(hits[0].pid), window_id: Number(hits[0].window_id ?? undefined) };
|
|
136
|
+
if (hits.length > 1)
|
|
137
|
+
throw new Error(`${hits.length} visible windows match "${title}" — narrow the title or pass pid`);
|
|
138
|
+
throw new Error(`no visible window matching "${title}" — check the windows action`);
|
|
139
|
+
}
|
|
140
|
+
throw new Error("type/key need a target: pass pid or window_title (see the windows action)");
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
private async windowRows(): Promise<any[]> {
|
|
144
|
+
const w = await this.call("list_windows");
|
|
145
|
+
return (w.windows ?? w._legacy_windows ?? []).map((v: any) => ({ ...normWin(v), window_id: v.window_id }));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async typeText(text: string, target: { pid: number; window_id?: number }): Promise<string> {
|
|
149
|
+
const r = await this.call("type_text", { ...target, text });
|
|
150
|
+
return `pid ${target.pid}: typed ${text.length} chars → ${r.effect ?? "sent"}`;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async key(combo: string, target: { pid?: number; window_id?: number } | null): Promise<string> {
|
|
154
|
+
const parts = combo.toLowerCase().split(/[+\-]/).map((s) => s.trim()).filter(Boolean);
|
|
155
|
+
const key = parts[parts.length - 1];
|
|
156
|
+
const mods = new Set(parts.slice(0, -1).map((m) => (m === "cmd" || m === "super" || m === "win" ? "meta" : m)));
|
|
157
|
+
const arg: Record<string, unknown> = { key, ctrl: mods.has("ctrl"), alt: mods.has("alt"), shift: mods.has("shift"), meta: mods.has("meta") };
|
|
158
|
+
if (target?.pid) Object.assign(arg, target); else arg.scope = "desktop"; // desktop = current foreground app
|
|
159
|
+
const r = await this.call("press_key", arg);
|
|
160
|
+
return `${target?.pid ? `pid ${target.pid}: ` : ""}${combo} → ${r.effect ?? "sent"}`;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async scroll(x: number, y: number, dir: string, amount: number, target?: { pid?: number; window_id?: number } | null): Promise<string> {
|
|
164
|
+
await this.call("scroll", { ...(target ?? {}), direction: dir, amount });
|
|
165
|
+
return `scrolled ${dir} ${amount} at (${x},${y})`;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async launch(app: string): Promise<string> {
|
|
169
|
+
const looksPath = /[\\/]/.test(app) || /\.(exe|app|msi)$/i.test(app);
|
|
170
|
+
const r = await this.call("launch_app", looksPath ? { path: app } : { name: app });
|
|
171
|
+
return r.pid ? `launched ${app} (pid ${r.pid})` : `launched ${app}`;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async windows(): Promise<string> {
|
|
175
|
+
const w = await this.call("list_windows");
|
|
176
|
+
const rows: any[] = w.windows ?? w._legacy_windows ?? [];
|
|
177
|
+
return rows.map(normWin)
|
|
178
|
+
.filter((v) => v.onScreen && v.pid > 0)
|
|
179
|
+
.map((v) => `pid ${String(v.pid).padEnd(7)} ${String(v.x).padStart(5)},${String(v.y).padStart(5)} ${String(v.width).padStart(5)}x${String(v.height).padStart(5)}${v.minimized ? " [min]" : ""} ${v.title.slice(0, 70)}`)
|
|
180
|
+
.join("\n") || "(no visible windows)";
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async clipboard(write?: string): Promise<string> {
|
|
184
|
+
if (write === undefined) {
|
|
185
|
+
const r = await this.call("clipboard_read", { include_text: true });
|
|
186
|
+
return String(r.text ?? r.plain_text ?? "(empty)");
|
|
187
|
+
}
|
|
188
|
+
await this.call("clipboard_write", { text: write });
|
|
189
|
+
return `clipboard set (${write.length} chars)`;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// ---------- backend: native OS fallbacks ----------
|
|
194
|
+
|
|
195
|
+
/** PowerShell one-shot: SendInput mouse/keyboard + GDI screenshots. */
|
|
196
|
+
const PS_PRELUDE = `
|
|
197
|
+
$sig = @"
|
|
198
|
+
using System; using System.Runtime.InteropServices;
|
|
199
|
+
public static class Goat {
|
|
200
|
+
[DllImport("user32.dll")] public static extern uint SendInput(uint n, INPUT[] p, int cb);
|
|
201
|
+
[DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
|
|
202
|
+
[DllImport("user32.dll")] public static extern bool GetCursorPos(out P o);
|
|
203
|
+
[DllImport("user32.dll")] public static extern void mouse_event(uint f, uint x, uint y, uint d, int e);
|
|
204
|
+
[StructLayout(LayoutKind.Sequential)] public struct M { public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
|
|
205
|
+
[StructLayout(LayoutKind.Sequential)] public struct K { public ushort vk; public ushort scan; public uint flags; public uint time; public IntPtr info; }
|
|
206
|
+
[StructLayout(LayoutKind.Explicit)] public struct I { [FieldOffset(0)] public uint type; [FieldOffset(8)] public M mi; [FieldOffset(8)] public K ki; }
|
|
207
|
+
[StructLayout(LayoutKind.Sequential)] public struct P { public int X; public int Y; }
|
|
208
|
+
}
|
|
209
|
+
"@; Add-Type -AssemblyName System.Windows.Forms,System.Drawing -ErrorAction SilentlyContinue; Add-Type $sig
|
|
210
|
+
function SI($inputs) { [Goat]::SendInput($inputs.Length, $inputs, [System.Runtime.InteropServices.Marshal]::SizeOf([type][Goat+I])) | Out-Null }
|
|
211
|
+
function MI($f, $x=0, $y=0, $d=0) { $i=[Goat+I]::new(); $i.type=0; $i.mi.dx=$x; $i.mi.dy=$y; $i.mi.dwFlags=$f; $i.mi.mouseData=$d; ,$i }
|
|
212
|
+
function KI($vk, $up=$false) { $i=[Goat+I]::new(); $i.type=1; $i.ki.vk=$vk; if($up){$i.ki.flags=2}; $i }
|
|
213
|
+
function ClickAt($x,$y) { [Goat]::SetCursorPos($x,$y)|Out-Null; SI (MI 0x0002); SI (MI 0x0004) }
|
|
214
|
+
`;
|
|
215
|
+
|
|
216
|
+
function psVk(token: string): number | null {
|
|
217
|
+
const t = token.toLowerCase();
|
|
218
|
+
const named: Record<string, number> = {
|
|
219
|
+
enter: 0x0d, return: 0x0d, tab: 0x09, esc: 0x1b, escape: 0x1b, space: 0x20,
|
|
220
|
+
backspace: 0x08, delete: 0x2e, del: 0x2e, insert: 0x2d, home: 0x24, end: 0x23,
|
|
221
|
+
pageup: 0x21, prior: 0x21, pagedown: 0x22, next: 0x22, up: 0x26, down: 0x28, left: 0x25, right: 0x27,
|
|
222
|
+
f5: 0x74, f11: 0x7a, f12: 0x7b, win: 0x5b, super: 0x5b, cmd: 0x5b,
|
|
223
|
+
};
|
|
224
|
+
if (named[t] !== undefined) return named[t];
|
|
225
|
+
if (/^[a-z0-9]$/.test(t)) return t.toUpperCase().charCodeAt(0);
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
class PowerShellBackend {
|
|
230
|
+
private async ps(body: string): Promise<string> {
|
|
231
|
+
const script = `$ProgressPreference='SilentlyContinue'; ${PS_PRELUDE}\n${body}`;
|
|
232
|
+
const r = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], OS_TIMEOUT_MS);
|
|
233
|
+
if (r.code !== 0) throw new Error(`powershell: ${(r.stderr || r.stdout).slice(0, 300)}`);
|
|
234
|
+
return r.stdout.trim();
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async available(): Promise<boolean> {
|
|
238
|
+
try { await this.ps("Write-Output ok"); return true; } catch { return false; }
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async shot(): Promise<Shot> {
|
|
242
|
+
const tmp = join(tmpdir(), `goat-shot-${Date.now()}.png`);
|
|
243
|
+
await this.ps(`
|
|
244
|
+
$b = [System.Windows.Forms.SystemInformation]::VirtualScreen
|
|
245
|
+
$bmp = New-Object System.Drawing.Bitmap $b.Width, $b.Height
|
|
246
|
+
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
|
247
|
+
$g.CopyFromScreen($b.Location, [Drawing.Point]::Empty, $b.Size)
|
|
248
|
+
$bmp.Save('${tmp}', [System.Drawing.Imaging.ImageFormat]::Png)
|
|
249
|
+
Write-Output "$($b.Width)x$($b.Height)"`);
|
|
250
|
+
const png = readFileSync(tmp);
|
|
251
|
+
try { unlinkSync(tmp); } catch { /* */ }
|
|
252
|
+
const dims = await this.ps(`$b=[System.Windows.Forms.SystemInformation]::VirtualScreen; "$($b.Width)x$($b.Height)"`);
|
|
253
|
+
const [w, h] = dims.split("x").map(Number);
|
|
254
|
+
return { png, width: w || 0, height: h || 0 };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async click(x: number, y: number, button: string, double: boolean): Promise<string> {
|
|
258
|
+
if (button === "right")
|
|
259
|
+
await this.ps(`[Goat]::SetCursorPos(${x},${y})|Out-Null; SI (MI 0x0008); SI (MI 0x0010)`);
|
|
260
|
+
else {
|
|
261
|
+
await this.ps(`ClickAt ${x} ${y}; if (${double ? 2 : 1} -eq 2) { Start-Sleep -Milliseconds 80; ClickAt ${x} ${y} }`);
|
|
262
|
+
}
|
|
263
|
+
return `${double ? "double-" : ""}${button}-click at (${x},${y})`;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async typeText(text: string): Promise<string> {
|
|
267
|
+
// SendKeys meta-characters are hostile to raw text — clipboard+paste is the
|
|
268
|
+
// reliable path for arbitrary content.
|
|
269
|
+
return this.typeViaClipboard(text);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async key(combo: string): Promise<string> {
|
|
273
|
+
const parts = combo.toLowerCase().split(/[+\-]/).map((s) => s.trim()).filter(Boolean);
|
|
274
|
+
const main = psVk(parts[parts.length - 1]);
|
|
275
|
+
if (main === null) throw new Error(`unknown key in combo: ${combo}`);
|
|
276
|
+
const mods = new Set(parts.slice(0, -1));
|
|
277
|
+
const modDefs: [string, number][] = [["ctrl", 0x11], ["alt", 0x12], ["shift", 0x10], ["win", 0x5b], ["super", 0x5b], ["cmd", 0x5b]];
|
|
278
|
+
const held = modDefs.filter(([n]) => mods.has(n));
|
|
279
|
+
let script = "";
|
|
280
|
+
for (const [, vk] of held) script += `SI (KI ${vk}); `;
|
|
281
|
+
script += `SI (KI ${main}); SI (KI ${main} $true); `;
|
|
282
|
+
for (const [, vk] of held.slice().reverse()) script += `SI (KI ${vk} $true); `;
|
|
283
|
+
await this.ps(script);
|
|
284
|
+
return `sent ${combo}`;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
async scroll(_x: number, y: number, dir: string, amount: number): Promise<string> {
|
|
288
|
+
const d = dir === "down" || dir === "right" ? -1 : 1;
|
|
289
|
+
await this.ps(`[Goat]::SetCursorPos(${_x},${y})|Out-Null; for($i=0;$i -lt ${amount};$i++){ [Goat]::mouse_event(0x0800,0,0,${d * 120},0); Start-Sleep -Milliseconds 30 }`);
|
|
290
|
+
return `scrolled ${dir} ${amount}`;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
async launch(app: string): Promise<string> {
|
|
294
|
+
await this.ps(`Start-Process -FilePath '${app.replaceAll("'", "''")}'`);
|
|
295
|
+
return `launched ${app}`;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async windows(): Promise<string> {
|
|
299
|
+
const out = await this.ps(
|
|
300
|
+
`Get-Process | Where-Object { $_.MainWindowHandle -ne 0 } | ForEach-Object { "{0,-8} {1}" -f $_.Id, $_.MainWindowTitle }`);
|
|
301
|
+
return out || "(no visible windows)";
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async clipboard(write?: string): Promise<string> {
|
|
305
|
+
if (write === undefined) return this.ps("Get-Clipboard");
|
|
306
|
+
await this.ps(`Set-Clipboard -Value @'\n${write.replaceAll("'@@", "'@'@'@@")}\n'@`);
|
|
307
|
+
return `clipboard set (${write.length} chars)`;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** SendKeys meta-characters are brittle for raw text — clipboard+paste instead. */
|
|
311
|
+
async typeViaClipboard(text: string): Promise<string> {
|
|
312
|
+
await this.clipboard(text);
|
|
313
|
+
await this.key("ctrl+v");
|
|
314
|
+
return `pasted ${text.length} chars via clipboard`;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
class MacBackend {
|
|
319
|
+
private async osa(script: string): Promise<string> {
|
|
320
|
+
const r = await run("osascript", ["-e", script], OS_TIMEOUT_MS);
|
|
321
|
+
if (r.code !== 0) throw new Error(`osascript: ${(r.stderr || r.stdout).slice(0, 300)}`);
|
|
322
|
+
return r.stdout.trim();
|
|
323
|
+
}
|
|
324
|
+
async available(): Promise<boolean> { return process.platform === "darwin"; }
|
|
325
|
+
async shot(): Promise<Shot> {
|
|
326
|
+
const tmp = join(tmpdir(), `goat-shot-${Date.now()}.png`);
|
|
327
|
+
await run("screencapture", ["-x", tmp], OS_TIMEOUT_MS);
|
|
328
|
+
const png = readFileSync(tmp);
|
|
329
|
+
return { png, width: 0, height: 0 };
|
|
330
|
+
}
|
|
331
|
+
async click(x: number, y: number): Promise<string> {
|
|
332
|
+
const r = await run("cliclick", [`c:${x},${y}`], 5000);
|
|
333
|
+
if (r.code !== 0) throw new Error("mouse clicks need `brew install cliclick` (or cua-driver) on macOS");
|
|
334
|
+
return `click at (${x},${y})`;
|
|
335
|
+
}
|
|
336
|
+
async typeText(text: string): Promise<string> {
|
|
337
|
+
// clipboard+paste: AppleScript keystroke chokes on non-ASCII and quoting
|
|
338
|
+
const r = await run("pbcopy", [], 5000, text);
|
|
339
|
+
if (r.code !== 0) throw new Error("pbcopy failed");
|
|
340
|
+
await this.osa(`tell application "System Events" to keystroke "v" using command down`);
|
|
341
|
+
return `pasted ${text.length} chars via clipboard`;
|
|
342
|
+
}
|
|
343
|
+
async key(combo: string): Promise<string> {
|
|
344
|
+
const parts = combo.toLowerCase().split(/[+\-]/).map((s) => s.trim()).filter(Boolean);
|
|
345
|
+
const main = parts.pop()!;
|
|
346
|
+
const using = parts
|
|
347
|
+
.map((p) => ({ ctrl: "control down", alt: "option down", shift: "shift down", cmd: "command down", super: "command down", win: "command down", meta: "command down" }[p] ?? ""))
|
|
348
|
+
.filter(Boolean);
|
|
349
|
+
const keyCode: Record<string, string> = {
|
|
350
|
+
enter: "36", return: "36", tab: "48", esc: "53", escape: "53", space: "49",
|
|
351
|
+
up: "126", down: "125", left: "123", right: "124", delete: "117", backspace: "51",
|
|
352
|
+
};
|
|
353
|
+
let script: string;
|
|
354
|
+
if (keyCode[main])
|
|
355
|
+
script = `key code ${keyCode[main]}${using.length ? ` using {${using.join(", ")}}` : ""}`;
|
|
356
|
+
else if (main.length === 1)
|
|
357
|
+
script = `keystroke "${main === '"' ? '\\"' : main}"${using.length ? ` using {${using.join(", ")}}` : ""}`;
|
|
358
|
+
else throw new Error(`unknown key: ${main}`);
|
|
359
|
+
await this.osa(`tell application "System Events" to ${script}`);
|
|
360
|
+
return `sent ${combo}`;
|
|
361
|
+
}
|
|
362
|
+
async scroll(_x: number, _y: number, dir: string, amount: number): Promise<string> {
|
|
363
|
+
const dy = dir === "down" ? amount : dir === "up" ? -amount : 0;
|
|
364
|
+
const dx = dir === "right" ? amount : dir === "left" ? -amount : 0;
|
|
365
|
+
if (!dx && !dy) throw new Error(`bad scroll direction: ${dir}`);
|
|
366
|
+
throw new Error("macOS scrolling needs cliclick or cua-driver installed");
|
|
367
|
+
}
|
|
368
|
+
async launch(app: string): Promise<string> {
|
|
369
|
+
await run("open", ["-a", app], 10_000);
|
|
370
|
+
return `launched ${app}`;
|
|
371
|
+
}
|
|
372
|
+
async windows(): Promise<string> {
|
|
373
|
+
return this.osa(`tell application "System Events" to get name of (processes where background only is false)`);
|
|
374
|
+
}
|
|
375
|
+
async clipboard(write?: string): Promise<string> {
|
|
376
|
+
if (write === undefined) return (await run("pbpaste", [], 5000)).stdout;
|
|
377
|
+
const r = await run("pbcopy", [], 5000, write);
|
|
378
|
+
if (r.code !== 0) throw new Error("pbcopy failed");
|
|
379
|
+
return `clipboard set (${write.length} chars)`;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
class XdotoolBackend {
|
|
384
|
+
async available(): Promise<boolean> { return (await run("which", ["xdotool"], 5000)).code === 0; }
|
|
385
|
+
private async x(args: string[]): Promise<string> {
|
|
386
|
+
const r = await run("xdotool", args, OS_TIMEOUT_MS);
|
|
387
|
+
if (r.code !== 0) throw new Error(`xdotool: ${(r.stderr || r.stdout).slice(0, 300)}`);
|
|
388
|
+
return r.stdout.trim();
|
|
389
|
+
}
|
|
390
|
+
async shot(): Promise<Shot> {
|
|
391
|
+
const tmp = join(tmpdir(), `goat-shot-${Date.now()}.png`);
|
|
392
|
+
let r = await run("gnome-screenshot", ["-f", tmp], OS_TIMEOUT_MS);
|
|
393
|
+
if (r.code !== 0) r = await run("import", ["-window", "root", tmp], OS_TIMEOUT_MS);
|
|
394
|
+
if (r.code !== 0) r = await run("scrot", [tmp], OS_TIMEOUT_MS);
|
|
395
|
+
if (r.code !== 0) throw new Error("no screenshot tool found (gnome-screenshot/import/scrot)");
|
|
396
|
+
return { png: readFileSync(tmp), width: 0, height: 0 };
|
|
397
|
+
}
|
|
398
|
+
async click(x: number, y: number, button: string): Promise<string> {
|
|
399
|
+
const b = button === "right" ? "3" : button === "middle" ? "2" : "1";
|
|
400
|
+
await this.x(["mousemove", String(x), String(y), "click", b]);
|
|
401
|
+
return `${button}-click at (${x},${y})`;
|
|
402
|
+
}
|
|
403
|
+
async typeText(text: string): Promise<string> {
|
|
404
|
+
await this.x(["type", "--clearmodifiers", text]);
|
|
405
|
+
return `typed ${text.length} chars`;
|
|
406
|
+
}
|
|
407
|
+
async key(combo: string): Promise<string> {
|
|
408
|
+
await this.x(["key", combo.toLowerCase().replace(/[+\-]/g, "+")]);
|
|
409
|
+
return `sent ${combo}`;
|
|
410
|
+
}
|
|
411
|
+
async scroll(_x: number, y: number, dir: string, amount: number): Promise<string> {
|
|
412
|
+
const btn = { up: "4", down: "5", left: "6", right: "7" }[dir] ?? "4";
|
|
413
|
+
await this.x(["mousemove", String(_x), String(y), "click", "--repeat", String(amount), "--delay", "40", btn]);
|
|
414
|
+
return `scrolled ${dir} ${amount}`;
|
|
415
|
+
}
|
|
416
|
+
async launch(app: string): Promise<string> {
|
|
417
|
+
await run(app, [], 3000).catch(() => { /* detached-ish */ });
|
|
418
|
+
return `launched ${app}`;
|
|
419
|
+
}
|
|
420
|
+
async windows(): Promise<string> {
|
|
421
|
+
const ids = await this.x(["search", "--onlyvisible", "--name", ""]);
|
|
422
|
+
return ids || "(no visible windows)";
|
|
423
|
+
}
|
|
424
|
+
async clipboard(write?: string): Promise<string> {
|
|
425
|
+
if (write === undefined) return (await run("xclip", ["-selection", "clipboard", "-o"], 5000)).stdout;
|
|
426
|
+
const r = await run("xclip", ["-selection", "clipboard"], 5000, write);
|
|
427
|
+
if (r.code !== 0) throw new Error("xclip not available");
|
|
428
|
+
return `clipboard set (${write.length} chars)`;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// ---------- facade ----------
|
|
433
|
+
|
|
434
|
+
export type DesktopBackend = "cua-driver" | "powershell" | "osascript" | "xdotool" | "none";
|
|
435
|
+
|
|
436
|
+
export class Desktop {
|
|
437
|
+
private driver: CuaDriver | null = null;
|
|
438
|
+
private ps: PowerShellBackend | null = null;
|
|
439
|
+
private mac: MacBackend | null = null;
|
|
440
|
+
private x11: XdotoolBackend | null = null;
|
|
441
|
+
backend: DesktopBackend = "none";
|
|
442
|
+
private detecting: Promise<void> | null = null;
|
|
443
|
+
|
|
444
|
+
/** Lazy backend detection (runs once; cheap calls only). */
|
|
445
|
+
async detect(): Promise<DesktopBackend> {
|
|
446
|
+
if (this.backend === "none" && !this.detecting) this.detecting = this._detect();
|
|
447
|
+
await this.detecting;
|
|
448
|
+
return this.backend;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
private async _detect(): Promise<void> {
|
|
452
|
+
if (process.platform === "win32") {
|
|
453
|
+
const exe = findCuaDriver();
|
|
454
|
+
if (exe) {
|
|
455
|
+
const d = new CuaDriver(exe);
|
|
456
|
+
if (await d.available().catch(() => false)) { this.driver = d; this.backend = "cua-driver"; log("desktop", "backend: cua-driver"); return; }
|
|
457
|
+
}
|
|
458
|
+
this.ps = new PowerShellBackend();
|
|
459
|
+
this.backend = "powershell";
|
|
460
|
+
log("desktop", "backend: powershell (SendInput)");
|
|
461
|
+
} else if (process.platform === "darwin") {
|
|
462
|
+
const exe = findCuaDriver();
|
|
463
|
+
if (exe) {
|
|
464
|
+
const d = new CuaDriver(exe);
|
|
465
|
+
if (await d.available().catch(() => false)) { this.driver = d; this.backend = "cua-driver"; return; }
|
|
466
|
+
}
|
|
467
|
+
this.mac = new MacBackend();
|
|
468
|
+
this.backend = "osascript";
|
|
469
|
+
} else {
|
|
470
|
+
const exe = findCuaDriver();
|
|
471
|
+
if (exe) {
|
|
472
|
+
const d = new CuaDriver(exe);
|
|
473
|
+
if (await d.available().catch(() => false)) { this.driver = d; this.backend = "cua-driver"; return; }
|
|
474
|
+
}
|
|
475
|
+
this.x11 = new XdotoolBackend();
|
|
476
|
+
this.backend = (await this.x11.available().catch(() => false)) ? "xdotool" : "none";
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
async screenshot(outPath: string): Promise<Shot> {
|
|
481
|
+
const b = await this.detect();
|
|
482
|
+
const shot = b === "cua-driver" ? await this.driver!.shot()
|
|
483
|
+
: b === "powershell" ? await this.ps!.shot()
|
|
484
|
+
: b === "osascript" ? await this.mac!.shot()
|
|
485
|
+
: await this.x11!.shot();
|
|
486
|
+
const { writeFileSync } = await import("node:fs");
|
|
487
|
+
writeFileSync(outPath, shot.png);
|
|
488
|
+
return shot;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
async act(action: string, a: Record<string, any>): Promise<string> {
|
|
492
|
+
const b = await this.detect();
|
|
493
|
+
const d = this.driver, ps = this.ps, mac = this.mac, x11 = this.x11;
|
|
494
|
+
switch (action) {
|
|
495
|
+
case "click":
|
|
496
|
+
case "double_click":
|
|
497
|
+
case "right_click": {
|
|
498
|
+
const x = Number(a.x), y = Number(a.y);
|
|
499
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error(`${action} needs numeric x,y in screenshot pixels`);
|
|
500
|
+
if (b === "cua-driver") return d!.click(x, y, action === "right_click" ? "right" : "left", action === "double_click", a.pid ? Number(a.pid) : undefined);
|
|
501
|
+
if (b === "powershell") return ps!.click(x, y, action === "right_click" ? "right" : "left", action === "double_click");
|
|
502
|
+
if (b === "osascript") return mac!.click(x, y);
|
|
503
|
+
return x11!.click(x, y, action === "right_click" ? "right" : "left");
|
|
504
|
+
}
|
|
505
|
+
case "type": {
|
|
506
|
+
const text = String(a.text ?? "");
|
|
507
|
+
if (!text) throw new Error("type needs text");
|
|
508
|
+
if (b === "cua-driver") return d!.typeText(text, await d!.target(a));
|
|
509
|
+
if (b === "powershell") return ps!.typeText(text);
|
|
510
|
+
if (b === "osascript") return mac!.typeText(text);
|
|
511
|
+
return x11!.typeText(text);
|
|
512
|
+
}
|
|
513
|
+
case "key": {
|
|
514
|
+
const combo = String(a.combo ?? a.key ?? "");
|
|
515
|
+
if (FORBIDDEN_KEYS.some((re) => re.test(combo.replace(/\s/g, "+"))))
|
|
516
|
+
throw new Error(`refused: ${combo} is on the never-send list (system lock / sign-out)`);
|
|
517
|
+
if (b === "cua-driver") {
|
|
518
|
+
const t = a.pid || a.window_title ? await d!.target(a) : null;
|
|
519
|
+
return d!.key(combo, t);
|
|
520
|
+
}
|
|
521
|
+
if (b === "powershell") return ps!.key(combo);
|
|
522
|
+
if (b === "osascript") return mac!.key(combo);
|
|
523
|
+
return x11!.key(combo);
|
|
524
|
+
}
|
|
525
|
+
case "scroll": {
|
|
526
|
+
const x = Number(a.x ?? 0), y = Number(a.y ?? 0);
|
|
527
|
+
const dir = ["up", "down", "left", "right"].includes(a.direction) ? a.direction : "down";
|
|
528
|
+
const amount = Math.min(20, Math.max(1, Number(a.amount ?? 3)));
|
|
529
|
+
if (b === "cua-driver")
|
|
530
|
+
return d!.scroll(x, y, dir, amount, a.pid || a.window_title ? await d!.target(a) : null);
|
|
531
|
+
if (b === "powershell") return ps!.scroll(x, y, dir, amount);
|
|
532
|
+
if (b === "osascript") return mac!.scroll(x, y, dir, amount);
|
|
533
|
+
return x11!.scroll(x, y, dir, amount);
|
|
534
|
+
}
|
|
535
|
+
case "launch": {
|
|
536
|
+
const app = String(a.app ?? "");
|
|
537
|
+
if (!app) throw new Error("launch needs app name or path");
|
|
538
|
+
if (b === "cua-driver") return d!.launch(app);
|
|
539
|
+
if (b === "powershell") return ps!.launch(app);
|
|
540
|
+
if (b === "osascript") return mac!.launch(app);
|
|
541
|
+
return x11!.launch(app);
|
|
542
|
+
}
|
|
543
|
+
case "windows": {
|
|
544
|
+
if (b === "cua-driver") return d!.windows();
|
|
545
|
+
if (b === "powershell") return ps!.windows();
|
|
546
|
+
if (b === "osascript") return mac!.windows();
|
|
547
|
+
return x11!.windows();
|
|
548
|
+
}
|
|
549
|
+
case "clipboard": {
|
|
550
|
+
const write = a.text === undefined ? undefined : String(a.text);
|
|
551
|
+
if (b === "cua-driver") return d!.clipboard(write);
|
|
552
|
+
if (b === "powershell") return ps!.clipboard(write);
|
|
553
|
+
if (b === "osascript") return mac!.clipboard(write);
|
|
554
|
+
return x11!.clipboard(write);
|
|
555
|
+
}
|
|
556
|
+
default:
|
|
557
|
+
throw new Error(`unknown desktop action: ${action}`);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** Locate cua-driver.exe / cua-driver on PATH or the known install dir. */
|
|
563
|
+
export function findCuaDriver(): string | null {
|
|
564
|
+
const names = process.platform === "win32" ? ["cua-driver.exe", "cua-driver"] : ["cua-driver"];
|
|
565
|
+
const dirs = [
|
|
566
|
+
process.env.CUA_DRIVER_PATH,
|
|
567
|
+
join(homedir(), ".cua-driver", "bin"),
|
|
568
|
+
join(homedir(), ".local", "bin"),
|
|
569
|
+
process.platform === "win32"
|
|
570
|
+
? join(process.env.LOCALAPPDATA ?? "", "Programs", "Cua", "cua-driver", "bin")
|
|
571
|
+
: "/usr/local/bin",
|
|
572
|
+
].filter(Boolean) as string[];
|
|
573
|
+
for (const n of names)
|
|
574
|
+
for (const d of dirs) {
|
|
575
|
+
const p = join(d, n);
|
|
576
|
+
if (existsSync(p)) return p;
|
|
577
|
+
}
|
|
578
|
+
return null;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
export const desktop = new Desktop();
|
|
582
|
+
|
|
583
|
+
// ---------- clipboard image (Ctrl+V in the TUI) ----------
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Grab an image from the system clipboard, save as PNG, return the path.
|
|
587
|
+
* null when the clipboard holds no image. Per-OS native tools; no deps.
|
|
588
|
+
*/
|
|
589
|
+
export async function clipboardImage(): Promise<string | null> {
|
|
590
|
+
const tmp = join(tmpdir(), `goat-paste-${Date.now()}.png`);
|
|
591
|
+
if (process.platform === "win32") {
|
|
592
|
+
const script = `
|
|
593
|
+
Add-Type -AssemblyName System.Windows.Forms,System.Drawing -ErrorAction SilentlyContinue
|
|
594
|
+
$img = [System.Windows.Forms.Clipboard]::GetImage()
|
|
595
|
+
if ($img) { $img.Save('${tmp.replaceAll("'", "''")}', [System.Drawing.Imaging.ImageFormat]::Png); Write-Output ok }`;
|
|
596
|
+
const r = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], OS_TIMEOUT_MS);
|
|
597
|
+
if (r.code === 0 && r.stdout.trim() === "ok" && existsSync(tmp)) return tmp;
|
|
598
|
+
return null;
|
|
599
|
+
}
|
|
600
|
+
if (process.platform === "darwin") {
|
|
601
|
+
// try PNG directly, else TIFF -> sips convert
|
|
602
|
+
const png = await run("osascript", ["-e",
|
|
603
|
+
`set f to open for access POSIX file "${tmp}" with write permission
|
|
604
|
+
try
|
|
605
|
+
write (the clipboard as «class PNGf») to f
|
|
606
|
+
end try
|
|
607
|
+
close access f`], OS_TIMEOUT_MS);
|
|
608
|
+
if (png.code === 0 && existsSync(tmp)) return tmp;
|
|
609
|
+
const tiff = tmp.replace(/\.png$/, ".tiff");
|
|
610
|
+
const t = await run("osascript", ["-e",
|
|
611
|
+
`set f to open for access POSIX file "${tiff}" with write permission
|
|
612
|
+
try
|
|
613
|
+
write (the clipboard as «class TIFF») to f
|
|
614
|
+
end try
|
|
615
|
+
close access f`], OS_TIMEOUT_MS);
|
|
616
|
+
if (t.code === 0 && existsSync(tiff)) {
|
|
617
|
+
await run("sips", ["-s", "format", "png", tiff, "--out", tmp], OS_TIMEOUT_MS);
|
|
618
|
+
try { unlinkSync(tiff); } catch { /* */ }
|
|
619
|
+
if (existsSync(tmp)) return tmp;
|
|
620
|
+
}
|
|
621
|
+
return null;
|
|
622
|
+
}
|
|
623
|
+
// Linux: Wayland then X11 (shell redirect keeps the bytes binary-safe)
|
|
624
|
+
const sh = (cmd: string) => run("bash", ["-c", `${cmd} > ${tmp} 2>/dev/null`], 5000);
|
|
625
|
+
if ((await sh("wl-paste --type image/png")).code === 0 && existsSync(tmp) && statSync(tmp).size > 0) return tmp;
|
|
626
|
+
if ((await sh("xclip -t image/png -selection clipboard -o")).code === 0 && existsSync(tmp) && statSync(tmp).size > 0) return tmp;
|
|
627
|
+
try { if (existsSync(tmp)) unlinkSync(tmp); } catch { /* */ }
|
|
628
|
+
return null;
|
|
629
|
+
}
|