@celljs/ta-reflex 0.0.0-stage → 4.36.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/README.en.md +28 -0
- package/README.md +27 -2
- package/extension/index.mjs +975 -0
- package/host/index.mjs +1942 -0
- package/package.json +72 -4
- package/web/index.js +2232 -0
package/host/index.mjs
ADDED
|
@@ -0,0 +1,1942 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __returnValue = (v) => v;
|
|
3
|
+
function __exportSetter(name, newValue) {
|
|
4
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
5
|
+
}
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, {
|
|
9
|
+
get: all[name],
|
|
10
|
+
enumerable: true,
|
|
11
|
+
configurable: true,
|
|
12
|
+
set: __exportSetter.bind(all, name)
|
|
13
|
+
});
|
|
14
|
+
};
|
|
15
|
+
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
|
|
16
|
+
|
|
17
|
+
// ../ta-computer-use/esm/cua-driver.js
|
|
18
|
+
var exports_cua_driver = {};
|
|
19
|
+
__export(exports_cua_driver, {
|
|
20
|
+
CuaDriver: () => CuaDriver
|
|
21
|
+
});
|
|
22
|
+
import { statSync } from "node:fs";
|
|
23
|
+
import { homedir } from "node:os";
|
|
24
|
+
import { join } from "node:path";
|
|
25
|
+
var CuaDriver;
|
|
26
|
+
var init_cua_driver = __esm(() => {
|
|
27
|
+
(function(CuaDriver2) {
|
|
28
|
+
CuaDriver2.SERVER = "cua-driver";
|
|
29
|
+
CuaDriver2.NAMESPACE = "mcp__cua_driver";
|
|
30
|
+
CuaDriver2.SECTION = "computer_use";
|
|
31
|
+
CuaDriver2.BUNDLED_ENV = "TA_CUA_DRIVER";
|
|
32
|
+
function prompt2(platform) {
|
|
33
|
+
return [
|
|
34
|
+
"Cua Driver lets you use the desktop apps of this computer in the background, without taking the user's pointer or keyboard: list apps and windows, read a window's accessibility tree, click, type, scroll and take screenshots.",
|
|
35
|
+
`Its tools are \`tools.${CuaDriver2.NAMESPACE}__*\` in codemode scripts. It starts the first time a script names \`${CuaDriver2.NAMESPACE}\`: begin with \`describeNamespace("${CuaDriver2.NAMESPACE}")\` for its tools and how to use them.`,
|
|
36
|
+
"Use it only when a task needs a desktop app, not for files or commands.",
|
|
37
|
+
...PLATFORM_NOTES[platform] ? [PLATFORM_NOTES[platform]] : []
|
|
38
|
+
].join(`
|
|
39
|
+
`);
|
|
40
|
+
}
|
|
41
|
+
CuaDriver2.prompt = prompt2;
|
|
42
|
+
const PLATFORM_NOTES = {
|
|
43
|
+
darwin: "If a call waits for the permissions of macOS, Ta has asked the user for them; do not ask again.",
|
|
44
|
+
win32: "Windows does not let it control the windows of apps run as administrator unless Ta runs as administrator too.",
|
|
45
|
+
linux: "It needs the desktop session of the user (X11, or Wayland with XWayland) and its accessibility bus (AT-SPI)."
|
|
46
|
+
};
|
|
47
|
+
CuaDriver2.BUNDLED_ENV_VARS = { CUA_DRIVER_RS_TELEMETRY_ENABLED: "0", CUA_DRIVER_RS_UPDATE_CHECK: "0" };
|
|
48
|
+
CuaDriver2.DESCRIPTION = "Use the desktop apps of this computer in the background (Cua Driver)";
|
|
49
|
+
CuaDriver2.INSTALL = {
|
|
50
|
+
posix: '/bin/bash -c "$(curl -fsSL https://cua.ai/driver/install.sh)"',
|
|
51
|
+
win32: "irm https://cua.ai/driver/install.ps1 | iex"
|
|
52
|
+
};
|
|
53
|
+
function locate(host = currentHost()) {
|
|
54
|
+
var _a;
|
|
55
|
+
if (host.bundled && host.isFile(host.bundled)) {
|
|
56
|
+
return { path: host.bundled, bundled: true };
|
|
57
|
+
}
|
|
58
|
+
const windows = host.platform === "win32";
|
|
59
|
+
const name = windows ? "cua-driver.exe" : "cua-driver";
|
|
60
|
+
const dirs = ((_a = host.path) !== null && _a !== undefined ? _a : "").split(windows ? ";" : ":").filter(Boolean);
|
|
61
|
+
const candidates = [...dirs.map((dir) => join(dir, name)), join(host.home, ".local", "bin", name)];
|
|
62
|
+
if (host.platform === "darwin") {
|
|
63
|
+
const app = "CuaDriver.app/Contents/MacOS/cua-driver";
|
|
64
|
+
candidates.push(join("/Applications", app), join(host.home, "Applications", app));
|
|
65
|
+
}
|
|
66
|
+
const own = candidates.find((candidate) => host.isFile(candidate));
|
|
67
|
+
return own ? { path: own, bundled: false } : undefined;
|
|
68
|
+
}
|
|
69
|
+
CuaDriver2.locate = locate;
|
|
70
|
+
function appOf(program) {
|
|
71
|
+
const inside = "/Contents/MacOS/cua-driver";
|
|
72
|
+
const app = program.slice(0, -inside.length);
|
|
73
|
+
return program.endsWith(inside) && app.endsWith(".app") ? app : undefined;
|
|
74
|
+
}
|
|
75
|
+
CuaDriver2.appOf = appOf;
|
|
76
|
+
function reaches(reach, input) {
|
|
77
|
+
if (reach === undefined) {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
if (reach === "all") {
|
|
81
|
+
return JSON.stringify(input !== null && input !== undefined ? input : null).includes(CuaDriver2.NAMESPACE);
|
|
82
|
+
}
|
|
83
|
+
return reach.some((word) => word.includes(CuaDriver2.NAMESPACE));
|
|
84
|
+
}
|
|
85
|
+
CuaDriver2.reaches = reaches;
|
|
86
|
+
function status(program, platform) {
|
|
87
|
+
if (program) {
|
|
88
|
+
const which = program.bundled ? `the one that comes with Ta Desktop (${program.path})` : program.path;
|
|
89
|
+
return `Cua Driver: ${which}. Ta starts it the first time it uses a desktop app, and checks what the system needs then.`;
|
|
90
|
+
}
|
|
91
|
+
const install = platform === "win32" ? CuaDriver2.INSTALL.win32 : CuaDriver2.INSTALL.posix;
|
|
92
|
+
return `Ta uses desktop apps through Cua Driver, which is not installed. Install it with \`${install}\`, or use Ta Desktop, which comes with it; Ta finds it on the next message, with no restart.`;
|
|
93
|
+
}
|
|
94
|
+
CuaDriver2.status = status;
|
|
95
|
+
function currentHost() {
|
|
96
|
+
return { platform: process.platform, path: process.env.PATH, home: homedir(), bundled: process.env[CuaDriver2.BUNDLED_ENV], isFile };
|
|
97
|
+
}
|
|
98
|
+
function isFile(path) {
|
|
99
|
+
try {
|
|
100
|
+
return statSync(path).isFile();
|
|
101
|
+
} catch (_a) {
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
})(CuaDriver || (CuaDriver = {}));
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
// ../ta-computer-use/esm/cua-driver-access.js
|
|
109
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
110
|
+
function ofLanguage(tag) {
|
|
111
|
+
if (/^zh/i.test(tag)) {
|
|
112
|
+
return /(?:tw|hk|mo|hant)/i.test(tag) ? "zh-TW" : "zh-CN";
|
|
113
|
+
}
|
|
114
|
+
if (/^ja/i.test(tag)) {
|
|
115
|
+
return "ja-JP";
|
|
116
|
+
}
|
|
117
|
+
return "en-US";
|
|
118
|
+
}
|
|
119
|
+
function askMac(env = process.env) {
|
|
120
|
+
const language = ofLanguage(env.TA_LANGUAGE || env.LC_ALL || env.LANG || "");
|
|
121
|
+
return language === "zh-CN" ? "Ta 正在请 macOS 允许 Cua Driver 使用这台 Mac:请在 Cua Driver 打开的窗口或“系统设置”里,打开“辅助功能”(用于点击和输入)和“屏幕录制”(用于查看窗口)中的 Cua Driver。开好后 Ta 会自动继续;点“停止”可放弃。" : language === "zh-TW" ? "Ta 正在請 macOS 允許 Cua Driver 使用這台 Mac:請在 Cua Driver 開啟的視窗或「系統設定」裡,開啟「輔助功能」(用於點選和輸入)和「螢幕錄製」(用於檢視視窗)中的 Cua Driver。開好後 Ta 會自動繼續;點「停止」可放棄。" : language === "ja-JP" ? "Ta は macOS に Cua Driver がこの Mac を使用することを許可するよう要求しています。Cua Driver が開いたウィンドウまたは「システム設定」で、「アクセシビリティ」(クリックと入力用)と「画面録画」(ウィンドウ表示用)の Cua Driver をオンにしてください。有効にした後、Ta は自動的に続行します。「停止」をクリックすると中止できます。" : "Ta is asking macOS to let Cua Driver use this Mac: turn Cua Driver on under Accessibility (to click and type) and Screen Recording (to see windows), in the window Cua Driver opened or in System Settings. Ta goes on by itself once you have; Stop gives up.";
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
class CuaDriverAccess {
|
|
125
|
+
constructor(program, options) {
|
|
126
|
+
var _a;
|
|
127
|
+
this.program = program;
|
|
128
|
+
this.options = options;
|
|
129
|
+
this.run = (_a = options.run) !== null && _a !== undefined ? _a : runProgram;
|
|
130
|
+
}
|
|
131
|
+
check(notify, signal) {
|
|
132
|
+
return this.options.platform === "darwin" ? this.checkMac(notify, signal) : this.checkDesktop();
|
|
133
|
+
}
|
|
134
|
+
async permissions() {
|
|
135
|
+
const socket = this.options.socket ? ["--socket", this.options.socket] : [];
|
|
136
|
+
const result = await this.run(this.program, ["call", "check_permissions", '{"prompt":false}', ...socket], CHECK_TIMEOUT_MS, this.options.env);
|
|
137
|
+
return CuaDriverAccess.parsePermissions(result);
|
|
138
|
+
}
|
|
139
|
+
async checkMac(notify, signal) {
|
|
140
|
+
var _a, _b, _c, _d;
|
|
141
|
+
var _e, _f, _g, _h;
|
|
142
|
+
let state = await this.permissions();
|
|
143
|
+
const grace = Date.now() + ((_e = this.options.graceMs) !== null && _e !== undefined ? _e : GRACE_MS);
|
|
144
|
+
while ((state === null || state === undefined ? undefined : state.pending) && Date.now() < grace && !(signal === null || signal === undefined ? undefined : signal.aborted)) {
|
|
145
|
+
await sleep(GRACE_POLL_MS, signal);
|
|
146
|
+
state = await this.permissions();
|
|
147
|
+
}
|
|
148
|
+
if (!state || state.accessibility && state.screenRecording) {
|
|
149
|
+
return { ready: true, notes: [], known: state !== undefined };
|
|
150
|
+
}
|
|
151
|
+
notify(askMac());
|
|
152
|
+
if (!state.pending) {
|
|
153
|
+
(_b = (_a = this.options).openSettings) === null || _b === undefined || _b.call(_a, state.accessibility ? "Privacy_ScreenCapture" : "Privacy_Accessibility");
|
|
154
|
+
}
|
|
155
|
+
const deadline = Date.now() + ((_f = this.options.waitMs) !== null && _f !== undefined ? _f : WAIT_MS);
|
|
156
|
+
while (!(signal === null || signal === undefined ? undefined : signal.aborted) && Date.now() < deadline && !((state === null || state === undefined ? undefined : state.accessibility) && (state.screenRecording || !state.pending))) {
|
|
157
|
+
await sleep((_g = this.options.pollMs) !== null && _g !== undefined ? _g : POLL_MS, signal);
|
|
158
|
+
await ((_d = (_c = this.options).beforeLook) === null || _d === undefined ? undefined : _d.call(_c));
|
|
159
|
+
state = (_h = await this.permissions()) !== null && _h !== undefined ? _h : state;
|
|
160
|
+
}
|
|
161
|
+
if (state === null || state === undefined ? undefined : state.accessibility) {
|
|
162
|
+
return { ready: true, notes: state.screenRecording ? [] : [NO_SCREEN_RECORDING], known: true };
|
|
163
|
+
}
|
|
164
|
+
return { ready: false, reason: (signal === null || signal === undefined ? undefined : signal.aborted) ? "Stopped while waiting for the permissions of macOS." : NO_ACCESSIBILITY };
|
|
165
|
+
}
|
|
166
|
+
async checkDesktop() {
|
|
167
|
+
const result = await this.run(this.program, ["doctor", "--json"], DOCTOR_TIMEOUT_MS, this.options.env);
|
|
168
|
+
return CuaDriverAccess.parseDoctor(result, this.options.platform);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function runProgram(program, args, timeoutMs, env) {
|
|
172
|
+
return new Promise((resolve) => {
|
|
173
|
+
execFile2(program, args, { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024, env: { ...process.env, ...env } }, (error, stdout, stderr) => {
|
|
174
|
+
const code = error ? typeof error.code === "number" ? error.code : -1 : 0;
|
|
175
|
+
resolve({ code, stdout: String(stdout), stderr: String(stderr) });
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
function sleep(ms, signal) {
|
|
180
|
+
return new Promise((resolve) => {
|
|
181
|
+
const timer = setTimeout(done, ms);
|
|
182
|
+
signal === null || signal === undefined || signal.addEventListener("abort", done, { once: true });
|
|
183
|
+
function done() {
|
|
184
|
+
clearTimeout(timer);
|
|
185
|
+
signal === null || signal === undefined || signal.removeEventListener("abort", done);
|
|
186
|
+
resolve();
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
var CHECK_TIMEOUT_MS = 5000, DOCTOR_TIMEOUT_MS = 15000, POLL_MS = 1000, GRACE_MS = 3000, GRACE_POLL_MS = 100, WAIT_MS, DESKTOP_PROBES, MISSING_LIBRARY, NO_ACCESSIBILITY = "Cua Driver has no Accessibility permission of macOS, which it needs to read and use apps: ask the user to turn Cua Driver on in System Settings → Privacy & Security → Accessibility (`/computer-use` in Ta opens it), then try again.", NO_SCREEN_RECORDING = "Cua Driver has no Screen Recording permission of macOS: it reads and uses apps, but takes no screenshots. Turn it on in System Settings → Privacy & Security → Screen & System Audio Recording.";
|
|
191
|
+
var init_cua_driver_access = __esm(() => {
|
|
192
|
+
WAIT_MS = 3 * 60 * 1000;
|
|
193
|
+
DESKTOP_PROBES = /display|x11|wayland|at-spi|accessib|session|desktop|automation|uia/i;
|
|
194
|
+
MISSING_LIBRARY = /error while loading shared libraries: (\S+?):/;
|
|
195
|
+
(function(CuaDriverAccess2) {
|
|
196
|
+
function parsePermissions(result) {
|
|
197
|
+
if (`${result.stdout}${result.stderr}`.includes("permissions_pending")) {
|
|
198
|
+
return { accessibility: false, screenRecording: false, pending: true };
|
|
199
|
+
}
|
|
200
|
+
try {
|
|
201
|
+
const answer = JSON.parse(result.stdout);
|
|
202
|
+
if (typeof answer.accessibility !== "boolean") {
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
return { accessibility: answer.accessibility, screenRecording: answer.screen_recording === true, pending: false };
|
|
206
|
+
} catch (_a) {
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
CuaDriverAccess2.parsePermissions = parsePermissions;
|
|
211
|
+
function parseDoctor(result, platform) {
|
|
212
|
+
var _a;
|
|
213
|
+
var _b;
|
|
214
|
+
const library = (_a = MISSING_LIBRARY.exec(result.stderr)) === null || _a === undefined ? undefined : _a[1];
|
|
215
|
+
if (library) {
|
|
216
|
+
const install = platform === "linux" ? " On Debian or Ubuntu: `sudo apt install libx11-6 libxi6 libxkbcommon0 at-spi2-core`." : "";
|
|
217
|
+
return { ready: false, reason: `Cua Driver cannot start: the system has no ${library}.${install}` };
|
|
218
|
+
}
|
|
219
|
+
let probes;
|
|
220
|
+
try {
|
|
221
|
+
probes = (_b = JSON.parse(result.stdout).probes) !== null && _b !== undefined ? _b : [];
|
|
222
|
+
} catch (_c) {
|
|
223
|
+
return { ready: true, notes: [], known: true };
|
|
224
|
+
}
|
|
225
|
+
const text2 = (probe) => [`${probe.label}: ${probe.message}`, probe.detail].filter(Boolean).join(" — ");
|
|
226
|
+
const failed = probes.filter((probe) => {
|
|
227
|
+
var _a2;
|
|
228
|
+
return probe.status === "error" || probe.status === "warn" && /display server/i.test((_a2 = probe.label) !== null && _a2 !== undefined ? _a2 : "");
|
|
229
|
+
});
|
|
230
|
+
if (failed.length > 0) {
|
|
231
|
+
return { ready: false, reason: `Cua Driver cannot use the desktop: ${failed.map(text2).join("; ")}` };
|
|
232
|
+
}
|
|
233
|
+
const warned = probes.filter((probe) => {
|
|
234
|
+
var _a2;
|
|
235
|
+
return probe.status === "warn" && DESKTOP_PROBES.test((_a2 = probe.label) !== null && _a2 !== undefined ? _a2 : "");
|
|
236
|
+
});
|
|
237
|
+
return { ready: true, notes: warned.map((probe) => `Cua Driver: ${text2(probe)}`), known: true };
|
|
238
|
+
}
|
|
239
|
+
CuaDriverAccess2.parseDoctor = parseDoctor;
|
|
240
|
+
})(CuaDriverAccess || (CuaDriverAccess = {}));
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
// ../ta-computer-use/esm/cua-driver-daemon.js
|
|
244
|
+
import { execFile as execFile3 } from "node:child_process";
|
|
245
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";
|
|
246
|
+
import { connect } from "node:net";
|
|
247
|
+
import { homedir as homedir2 } from "node:os";
|
|
248
|
+
import { dirname, join as join2 } from "node:path";
|
|
249
|
+
|
|
250
|
+
class CuaDriverDaemon {
|
|
251
|
+
constructor(source, options = {}) {
|
|
252
|
+
var _a, _b;
|
|
253
|
+
this.source = source;
|
|
254
|
+
this.options = options;
|
|
255
|
+
this.launched = false;
|
|
256
|
+
this.verified = false;
|
|
257
|
+
this.dir = (_a = options.dir) !== null && _a !== undefined ? _a : join2(homedir2(), "Library", "Caches", "ta");
|
|
258
|
+
this.app = CuaDriverDaemon.nested(source) ? join2(this.stageDir, CuaDriverDaemon.version(source), "CuaDriver.app") : source;
|
|
259
|
+
this.socket = join2(this.dir, "cua-driver.sock");
|
|
260
|
+
this.pidFile = join2(this.dir, "cua-driver.pid");
|
|
261
|
+
this.launch = (_b = options.launch) !== null && _b !== undefined ? _b : openApp;
|
|
262
|
+
}
|
|
263
|
+
async ensure() {
|
|
264
|
+
var _a;
|
|
265
|
+
if (await this.alive() && (this.verified || await this.adopt())) {
|
|
266
|
+
this.touch();
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
clearTimeout(this.idle);
|
|
270
|
+
(_a = this.starting) !== null && _a !== undefined || (this.starting = this.start().finally(() => {
|
|
271
|
+
this.starting = undefined;
|
|
272
|
+
}));
|
|
273
|
+
await this.starting;
|
|
274
|
+
this.touch();
|
|
275
|
+
}
|
|
276
|
+
alive() {
|
|
277
|
+
if (!existsSync(this.socket)) {
|
|
278
|
+
return Promise.resolve(false);
|
|
279
|
+
}
|
|
280
|
+
return new Promise((resolve) => {
|
|
281
|
+
const socket = connect(this.socket);
|
|
282
|
+
socket.once("connect", () => {
|
|
283
|
+
socket.destroy();
|
|
284
|
+
resolve(true);
|
|
285
|
+
});
|
|
286
|
+
socket.on("error", () => resolve(false));
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
stop() {
|
|
290
|
+
clearTimeout(this.idle);
|
|
291
|
+
if (!this.launched) {
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
this.launched = false;
|
|
295
|
+
const pid = this.pid();
|
|
296
|
+
if (pid) {
|
|
297
|
+
try {
|
|
298
|
+
process.kill(pid, "SIGTERM");
|
|
299
|
+
} catch (_a) {}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
async reap() {
|
|
303
|
+
var _a;
|
|
304
|
+
const program = this.program;
|
|
305
|
+
const own = this.pid();
|
|
306
|
+
const list = await new Promise((resolve) => execFile3("ps", ["-axo", "pid=,command="], (_error, stdout) => resolve(String(stdout !== null && stdout !== undefined ? stdout : ""))));
|
|
307
|
+
for (const line of list.split(`
|
|
308
|
+
`)) {
|
|
309
|
+
const [, pid, command] = (_a = /^\s*(\d+)\s+(.*)$/.exec(line)) !== null && _a !== undefined ? _a : [];
|
|
310
|
+
if (pid && Number(pid) !== own && command.startsWith(`${program} serve`) && !command.includes(this.socket)) {
|
|
311
|
+
try {
|
|
312
|
+
process.kill(Number(pid), "SIGTERM");
|
|
313
|
+
} catch (_b) {}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
async adopt() {
|
|
318
|
+
const running = await this.identify();
|
|
319
|
+
if (!running || running.executable === this.program) {
|
|
320
|
+
this.verified = true;
|
|
321
|
+
return true;
|
|
322
|
+
}
|
|
323
|
+
try {
|
|
324
|
+
process.kill(running.pid, "SIGTERM");
|
|
325
|
+
} catch (_a) {}
|
|
326
|
+
return false;
|
|
327
|
+
}
|
|
328
|
+
identify() {
|
|
329
|
+
return new Promise((resolve) => execFile3(this.program, ["call", "check_permissions", '{"prompt":false}', "--socket", this.socket], { timeout: 5000, env: { ...process.env, ...this.options.env } }, (_error, stdout) => {
|
|
330
|
+
try {
|
|
331
|
+
const { source } = JSON.parse(String(stdout));
|
|
332
|
+
resolve((source === null || source === undefined ? undefined : source.executable) && source.pid ? { executable: source.executable, pid: source.pid } : undefined);
|
|
333
|
+
} catch (_a) {
|
|
334
|
+
resolve(undefined);
|
|
335
|
+
}
|
|
336
|
+
}));
|
|
337
|
+
}
|
|
338
|
+
get program() {
|
|
339
|
+
return join2(this.app, "Contents", "MacOS", "cua-driver");
|
|
340
|
+
}
|
|
341
|
+
async verify() {
|
|
342
|
+
const pid = this.pid();
|
|
343
|
+
const command = pid ? await this.commandOf(pid) : undefined;
|
|
344
|
+
const program = this.program;
|
|
345
|
+
if (command === undefined || command.includes(`${program} serve`)) {
|
|
346
|
+
this.verified = true;
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
this.stop();
|
|
350
|
+
throw new Error(`macOS started another copy of CuaDriver.app (${command.split(" serve")[0]}). Run \`${program} doctor --fix\`, which makes macOS forget the other copies, then try again.`);
|
|
351
|
+
}
|
|
352
|
+
commandOf(pid) {
|
|
353
|
+
return new Promise((resolve) => execFile3("ps", ["-o", "command=", "-p", String(pid)], (error, stdout) => resolve(error ? undefined : String(stdout).trim())));
|
|
354
|
+
}
|
|
355
|
+
touch() {
|
|
356
|
+
var _a, _b;
|
|
357
|
+
var _c;
|
|
358
|
+
clearTimeout(this.idle);
|
|
359
|
+
this.idle = setTimeout(() => this.stop(), (_c = this.options.idleMs) !== null && _c !== undefined ? _c : IDLE_MS);
|
|
360
|
+
(_b = (_a = this.idle).unref) === null || _b === undefined || _b.call(_a);
|
|
361
|
+
}
|
|
362
|
+
pid() {
|
|
363
|
+
try {
|
|
364
|
+
return Number(readFileSync(this.pidFile, "utf8").trim()) || undefined;
|
|
365
|
+
} catch (_a) {
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
get stageDir() {
|
|
370
|
+
var _a;
|
|
371
|
+
return (_a = this.options.stageDir) !== null && _a !== undefined ? _a : join2(homedir2(), "Library", "Application Support", "Ta", "cua-driver");
|
|
372
|
+
}
|
|
373
|
+
async stage() {
|
|
374
|
+
if (this.app === this.source || existsSync(this.app)) {
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
const versions = dirname(dirname(this.app));
|
|
378
|
+
const temp = `${dirname(this.app)}.part`;
|
|
379
|
+
rmSync(temp, { recursive: true, force: true });
|
|
380
|
+
mkdirSync(temp, { recursive: true });
|
|
381
|
+
await run("cp", ["-cR", this.source, temp]).catch(() => run("cp", ["-R", this.source, temp]));
|
|
382
|
+
rmSync(dirname(this.app), { recursive: true, force: true });
|
|
383
|
+
renameSync(temp, dirname(this.app));
|
|
384
|
+
for (const name of readdirSync(versions)) {
|
|
385
|
+
if (join2(versions, name) !== dirname(this.app)) {
|
|
386
|
+
rmSync(join2(versions, name), { recursive: true, force: true });
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
async start() {
|
|
391
|
+
var _a;
|
|
392
|
+
await this.stage();
|
|
393
|
+
mkdirSync(this.dir, { recursive: true });
|
|
394
|
+
rmSync(this.socket, { force: true });
|
|
395
|
+
this.verified = false;
|
|
396
|
+
await this.launch(this.app, ["serve", "--socket", this.socket, "--pid-file", this.pidFile], (_a = this.options.env) !== null && _a !== undefined ? _a : {});
|
|
397
|
+
if (!this.launched) {
|
|
398
|
+
this.launched = true;
|
|
399
|
+
process.once("exit", () => this.stop());
|
|
400
|
+
}
|
|
401
|
+
const deadline = Date.now() + START_TIMEOUT_MS;
|
|
402
|
+
while (Date.now() < deadline) {
|
|
403
|
+
if (await this.alive()) {
|
|
404
|
+
return this.verify();
|
|
405
|
+
}
|
|
406
|
+
await new Promise((resolve) => setTimeout(resolve, POLL_MS2));
|
|
407
|
+
}
|
|
408
|
+
throw new Error(`Cua Driver did not start in ${START_TIMEOUT_MS / 1000} s: run \`${join2(this.app, "Contents/MacOS/cua-driver")} doctor\`.`);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
async function openApp(app, args, env) {
|
|
412
|
+
await run(LSREGISTER, ["-f", app]).catch(() => {
|
|
413
|
+
return;
|
|
414
|
+
});
|
|
415
|
+
const vars = Object.entries(env).flatMap(([name, value]) => ["--env", `${name}=${value}`]);
|
|
416
|
+
await run("open", ["-g", "-n", "-a", app, ...vars, "--args", ...args]);
|
|
417
|
+
}
|
|
418
|
+
function run(program, args) {
|
|
419
|
+
return new Promise((resolve, reject) => execFile3(program, args, (error, stdout) => error ? reject(error) : resolve(String(stdout))));
|
|
420
|
+
}
|
|
421
|
+
var START_TIMEOUT_MS = 1e4, POLL_MS2 = 20, IDLE_MS, LSREGISTER = "/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister";
|
|
422
|
+
var init_cua_driver_daemon = __esm(() => {
|
|
423
|
+
IDLE_MS = 10 * 60 * 1000;
|
|
424
|
+
(function(CuaDriverDaemon2) {
|
|
425
|
+
function nested(app) {
|
|
426
|
+
return /\.app\//.test(dirname(app));
|
|
427
|
+
}
|
|
428
|
+
CuaDriverDaemon2.nested = nested;
|
|
429
|
+
function version(app) {
|
|
430
|
+
var _a;
|
|
431
|
+
var _b;
|
|
432
|
+
try {
|
|
433
|
+
return (_b = (_a = /<key>CFBundleVersion<\/key>\s*<string>([^<]+)<\/string>/.exec(readFileSync(join2(app, "Contents", "Info.plist"), "utf8"))) === null || _a === undefined ? undefined : _a[1]) !== null && _b !== undefined ? _b : "current";
|
|
434
|
+
} catch (_c) {
|
|
435
|
+
return "current";
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
CuaDriverDaemon2.version = version;
|
|
439
|
+
})(CuaDriverDaemon || (CuaDriverDaemon = {}));
|
|
440
|
+
});
|
|
441
|
+
|
|
442
|
+
// ../ta-computer-use/esm/extension.js
|
|
443
|
+
var exports_extension = {};
|
|
444
|
+
__export(exports_extension, {
|
|
445
|
+
setupOf: () => setupOf,
|
|
446
|
+
default: () => computerUse,
|
|
447
|
+
activate: () => activate
|
|
448
|
+
});
|
|
449
|
+
import { execFile as execFile4 } from "node:child_process";
|
|
450
|
+
import { realpathSync } from "node:fs";
|
|
451
|
+
import { join as join3 } from "node:path";
|
|
452
|
+
function setupOf(found, platform) {
|
|
453
|
+
const program = { ...found, path: realPath(found.path) };
|
|
454
|
+
let setup = setups.get(program.path);
|
|
455
|
+
if (!setup) {
|
|
456
|
+
const env = program.bundled ? { ...CuaDriver.BUNDLED_ENV_VARS } : undefined;
|
|
457
|
+
const app = program.bundled && platform === "darwin" ? CuaDriver.appOf(program.path) : undefined;
|
|
458
|
+
const daemon = app ? new CuaDriverDaemon(app, { env }) : undefined;
|
|
459
|
+
const access = new CuaDriverAccess(daemon ? join3(daemon.app, "Contents", "MacOS", "cua-driver") : program.path, {
|
|
460
|
+
platform,
|
|
461
|
+
socket: daemon === null || daemon === undefined ? undefined : daemon.socket,
|
|
462
|
+
env,
|
|
463
|
+
beforeLook: daemon ? () => daemon.ensure() : undefined,
|
|
464
|
+
openSettings: (pane) => execFile4("open", [`x-apple.systempreferences:com.apple.preference.security?${pane}`], () => {
|
|
465
|
+
return;
|
|
466
|
+
})
|
|
467
|
+
});
|
|
468
|
+
const args = daemon ? ["mcp", "--embedded", "--socket", daemon.socket] : ["mcp"];
|
|
469
|
+
setup = { program, daemon, access, args, env, ready: false };
|
|
470
|
+
setups.set(program.path, setup);
|
|
471
|
+
}
|
|
472
|
+
return setup;
|
|
473
|
+
}
|
|
474
|
+
function realPath(path) {
|
|
475
|
+
try {
|
|
476
|
+
return realpathSync(path);
|
|
477
|
+
} catch (_a) {
|
|
478
|
+
return path;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
function activate(pi, options = DEFAULTS) {
|
|
482
|
+
let setup;
|
|
483
|
+
let connected = false;
|
|
484
|
+
let connecting;
|
|
485
|
+
const prefix = `${CuaDriver.NAMESPACE}__`;
|
|
486
|
+
const ready = () => pi.getAllTools().some((tool) => tool.name.startsWith(prefix));
|
|
487
|
+
const found = () => {
|
|
488
|
+
if (!setup) {
|
|
489
|
+
const program = options.locate();
|
|
490
|
+
setup = program ? options.setup(program, options.platform) : undefined;
|
|
491
|
+
}
|
|
492
|
+
return setup;
|
|
493
|
+
};
|
|
494
|
+
const connect2 = async (driver, signal) => {
|
|
495
|
+
if (!pi.getMcpServers().some((server) => server.name === CuaDriver.SERVER)) {
|
|
496
|
+
pi.registerMcpServer(CuaDriver.SERVER, { command: driver.program.path, args: driver.args, env: driver.env, description: CuaDriver.DESCRIPTION });
|
|
497
|
+
}
|
|
498
|
+
const deadline = Date.now() + CONNECT_WAIT_MS;
|
|
499
|
+
while (!ready() && Date.now() < deadline && !(signal === null || signal === undefined ? undefined : signal.aborted)) {
|
|
500
|
+
await new Promise((resolve) => setTimeout(resolve, POLL_MS3));
|
|
501
|
+
}
|
|
502
|
+
connected = !(signal === null || signal === undefined ? undefined : signal.aborted);
|
|
503
|
+
};
|
|
504
|
+
const check = async (driver, notify, signal) => {
|
|
505
|
+
var _a;
|
|
506
|
+
var _b;
|
|
507
|
+
(_b = driver.checking) !== null && _b !== undefined || (driver.checking = driver.access.check(notify, signal).finally(() => {
|
|
508
|
+
driver.checking = undefined;
|
|
509
|
+
}));
|
|
510
|
+
const result = await driver.checking;
|
|
511
|
+
if (!result.ready) {
|
|
512
|
+
return result.reason;
|
|
513
|
+
}
|
|
514
|
+
if (result.known && !driver.ready) {
|
|
515
|
+
driver.ready = true;
|
|
516
|
+
for (const note of result.notes) {
|
|
517
|
+
notify(note);
|
|
518
|
+
}
|
|
519
|
+
(_a = driver.daemon) === null || _a === undefined || _a.reap();
|
|
520
|
+
}
|
|
521
|
+
return;
|
|
522
|
+
};
|
|
523
|
+
pi.on("before_agent_start", (event) => {
|
|
524
|
+
const { sections } = event.systemPromptOptions;
|
|
525
|
+
if (found()) {
|
|
526
|
+
sections[CuaDriver.SECTION] = CuaDriver.prompt(options.platform);
|
|
527
|
+
} else {
|
|
528
|
+
delete sections[CuaDriver.SECTION];
|
|
529
|
+
}
|
|
530
|
+
});
|
|
531
|
+
pi.on("tool_call", async (event, ctx) => {
|
|
532
|
+
var _a, _b;
|
|
533
|
+
const driver = setup;
|
|
534
|
+
if (!driver) {
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
if (driver.ready && connected && !driver.daemon) {
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
const tool = pi.getAllTools().find((candidate) => candidate.name === event.toolName);
|
|
541
|
+
if (!CuaDriver.reaches((_a = tool === null || tool === undefined ? undefined : tool.reachesTools) === null || _a === undefined ? undefined : _a.call(tool, event.input), event.input)) {
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
const notify = (message) => ctx.ui.notify(message, "warning");
|
|
545
|
+
try {
|
|
546
|
+
await ((_b = driver.daemon) === null || _b === undefined ? undefined : _b.ensure());
|
|
547
|
+
const reason = driver.daemon && !driver.ready ? await check(driver, notify, ctx.signal) : undefined;
|
|
548
|
+
if (reason) {
|
|
549
|
+
return { block: true, reason };
|
|
550
|
+
}
|
|
551
|
+
if (!connected) {
|
|
552
|
+
connecting !== null && connecting !== undefined || (connecting = connect2(driver, ctx.signal).finally(() => {
|
|
553
|
+
connecting = undefined;
|
|
554
|
+
}));
|
|
555
|
+
await connecting;
|
|
556
|
+
}
|
|
557
|
+
const after = !driver.daemon && !driver.ready ? await check(driver, notify, ctx.signal) : undefined;
|
|
558
|
+
return after ? { block: true, reason: after } : undefined;
|
|
559
|
+
} catch (error) {
|
|
560
|
+
return { block: true, reason: error.message };
|
|
561
|
+
}
|
|
562
|
+
});
|
|
563
|
+
pi.registerCommand("computer-use", {
|
|
564
|
+
description: "Whether Ta can use the desktop apps of this computer (Cua Driver), and what the system still needs",
|
|
565
|
+
handler: async (_args, ctx) => {
|
|
566
|
+
var _a;
|
|
567
|
+
const program = options.locate();
|
|
568
|
+
ctx.ui.notify(CuaDriver.status(program, options.platform), program ? "info" : "warning");
|
|
569
|
+
if (!program) {
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
const driver = options.setup(program, options.platform);
|
|
573
|
+
await ((_a = driver.daemon) === null || _a === undefined ? undefined : _a.ensure());
|
|
574
|
+
const result = await driver.access.check((message) => ctx.ui.notify(message, "warning"), ctx.signal);
|
|
575
|
+
if (!result.ready) {
|
|
576
|
+
ctx.ui.notify(result.reason, "warning");
|
|
577
|
+
} else if (result.known) {
|
|
578
|
+
driver.ready = true;
|
|
579
|
+
ctx.ui.notify(["Cua Driver has what it needs.", ...result.notes].join(`
|
|
580
|
+
`), result.notes.length > 0 ? "warning" : "info");
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
function computerUse(pi) {
|
|
586
|
+
activate(pi);
|
|
587
|
+
}
|
|
588
|
+
var CONNECT_WAIT_MS = 5000, POLL_MS3 = 15, setups, DEFAULTS;
|
|
589
|
+
var init_extension = __esm(() => {
|
|
590
|
+
init_cua_driver();
|
|
591
|
+
init_cua_driver_access();
|
|
592
|
+
init_cua_driver_daemon();
|
|
593
|
+
setups = new Map;
|
|
594
|
+
DEFAULTS = { locate: () => CuaDriver.locate(), platform: process.platform, setup: setupOf };
|
|
595
|
+
});
|
|
596
|
+
|
|
597
|
+
// ../ta-protocol/esm/common/local-models-protocol.js
|
|
598
|
+
var TA_LOCAL_MODELS = "@celljs/ta-local-models";
|
|
599
|
+
|
|
600
|
+
// web-src/desktop-apps.ts
|
|
601
|
+
import { execFile } from "node:child_process";
|
|
602
|
+
|
|
603
|
+
// web-src/desktop-target.ts
|
|
604
|
+
var ROLES = {
|
|
605
|
+
AXButton: "button",
|
|
606
|
+
AXLink: "link",
|
|
607
|
+
AXTextField: "textfield",
|
|
608
|
+
AXTextArea: "textarea",
|
|
609
|
+
AXSearchField: "searchbox",
|
|
610
|
+
AXComboBox: "combobox",
|
|
611
|
+
AXCheckBox: "checkbox",
|
|
612
|
+
AXRadioButton: "radio",
|
|
613
|
+
AXSwitch: "switch",
|
|
614
|
+
AXTab: "tab",
|
|
615
|
+
AXTabGroup: "tablist",
|
|
616
|
+
AXSheet: "dialog",
|
|
617
|
+
AXMenuItem: "menuitem",
|
|
618
|
+
AXMenuBarItem: "menuitem",
|
|
619
|
+
AXPopUpButton: "combobox",
|
|
620
|
+
AXMenuButton: "button",
|
|
621
|
+
AXCell: "cell",
|
|
622
|
+
AXRow: "row",
|
|
623
|
+
AXOutlineRow: "treeitem",
|
|
624
|
+
AXSlider: "slider",
|
|
625
|
+
AXIncrementor: "spinbutton",
|
|
626
|
+
AXStaticText: "text",
|
|
627
|
+
AXImage: "image",
|
|
628
|
+
AXHeading: "heading",
|
|
629
|
+
AXDisclosureTriangle: "button"
|
|
630
|
+
};
|
|
631
|
+
var LEFT_OUT = new Set([
|
|
632
|
+
"AXMenu",
|
|
633
|
+
"AXMenuBar",
|
|
634
|
+
"AXApplication",
|
|
635
|
+
"AXWindow",
|
|
636
|
+
"AXGroup",
|
|
637
|
+
"AXSplitGroup",
|
|
638
|
+
"AXScrollArea",
|
|
639
|
+
"AXLayoutArea",
|
|
640
|
+
"AXUnknown",
|
|
641
|
+
"AXToolbar"
|
|
642
|
+
]);
|
|
643
|
+
var ELEMENTS_MAX = 300;
|
|
644
|
+
var DesktopTarget;
|
|
645
|
+
((DesktopTarget) => {
|
|
646
|
+
DesktopTarget.PREFIX = "app:";
|
|
647
|
+
DesktopTarget.HZ = 3;
|
|
648
|
+
function id(window) {
|
|
649
|
+
return `${DesktopTarget.PREFIX}${window.pid}:${window.window_id}`;
|
|
650
|
+
}
|
|
651
|
+
DesktopTarget.id = id;
|
|
652
|
+
function parse(id2) {
|
|
653
|
+
const match = /^app:(\d+):(\d+)$/.exec(id2);
|
|
654
|
+
return match ? { pid: Number(match[1]), window: Number(match[2]) } : undefined;
|
|
655
|
+
}
|
|
656
|
+
DesktopTarget.parse = parse;
|
|
657
|
+
function title(window) {
|
|
658
|
+
return window.title && window.title !== window.app_name ? `${window.app_name} · ${window.title}` : window.app_name;
|
|
659
|
+
}
|
|
660
|
+
DesktopTarget.title = title;
|
|
661
|
+
const NOT_APPS = new Set(["Cua Driver"]);
|
|
662
|
+
function windows(listed, own = []) {
|
|
663
|
+
const kept = listed.filter((window) => window.is_on_screen !== false && !NOT_APPS.has(window.app_name) && (window.layer ?? 0) === 0 && !own.includes(window.pid) && (window.bounds?.width ?? 100) >= 80 && (window.bounds?.height ?? 100) >= 60);
|
|
664
|
+
const titled = new Set(kept.filter((window) => window.title).map((window) => window.pid));
|
|
665
|
+
return kept.filter((window) => window.title || !titled.has(window.pid));
|
|
666
|
+
}
|
|
667
|
+
DesktopTarget.windows = windows;
|
|
668
|
+
const SHOWN_ROW = /^\s*- (AX\w+)(?: = "((?:[^"\\]|\\.)*)")?(?: \(([^)]*)\))?/;
|
|
669
|
+
const MARKS = /[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
|
|
670
|
+
function shown(markdown) {
|
|
671
|
+
const out = [];
|
|
672
|
+
for (const line of (markdown ?? "").split(`
|
|
673
|
+
`)) {
|
|
674
|
+
if (/^\s*- \[\d+\]/.test(line)) {
|
|
675
|
+
continue;
|
|
676
|
+
}
|
|
677
|
+
const match = SHOWN_ROW.exec(line);
|
|
678
|
+
const role = match?.[1];
|
|
679
|
+
const text = (match?.[2] || match?.[3] || "").replace(MARKS, "").trim();
|
|
680
|
+
if (role && text && !LEFT_OUT.has(role)) {
|
|
681
|
+
out.push({ type: ROLES[role] ?? role.replace(/^AX/, "").toLowerCase(), text });
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
return out;
|
|
685
|
+
}
|
|
686
|
+
DesktopTarget.shown = shown;
|
|
687
|
+
function observation(elements, window, markdown) {
|
|
688
|
+
const entities = shown(markdown).map((one, i) => ({ id: `shown:${i + 1}`, type: one.type, text: one.text }));
|
|
689
|
+
const tokens = new Map;
|
|
690
|
+
const seen = new Map;
|
|
691
|
+
for (const element of elements) {
|
|
692
|
+
if (LEFT_OUT.has(element.role) || entities.length >= ELEMENTS_MAX) {
|
|
693
|
+
continue;
|
|
694
|
+
}
|
|
695
|
+
const type = ROLES[element.role] ?? element.role.replace(/^AX/, "").toLowerCase();
|
|
696
|
+
const label = (element.label ?? "").trim();
|
|
697
|
+
const value = element.value === undefined || element.value === null ? "" : String(element.value).trim();
|
|
698
|
+
if (!label && !value && type === "text") {
|
|
699
|
+
continue;
|
|
700
|
+
}
|
|
701
|
+
const base = `${type}:${label || value}`;
|
|
702
|
+
const nth = seen.get(base) ?? 0;
|
|
703
|
+
seen.set(base, nth + 1);
|
|
704
|
+
const id2 = nth ? `${base}#${nth + 1}` : base;
|
|
705
|
+
if (element.element_token) {
|
|
706
|
+
tokens.set(id2, element.element_token);
|
|
707
|
+
}
|
|
708
|
+
const box = element.frame && window && window.width > 0 && window.height > 0 ? {
|
|
709
|
+
x: (element.frame.x - window.x) / window.width,
|
|
710
|
+
y: (element.frame.y - window.y) / window.height,
|
|
711
|
+
w: element.frame.w / window.width,
|
|
712
|
+
h: element.frame.h / window.height
|
|
713
|
+
} : undefined;
|
|
714
|
+
entities.push({ id: id2, type, ...label ? { text: label } : {}, ...value && value !== label ? { value } : {}, ...box ? { box } : {} });
|
|
715
|
+
}
|
|
716
|
+
return { observation: { entities }, tokens };
|
|
717
|
+
}
|
|
718
|
+
DesktopTarget.observation = observation;
|
|
719
|
+
function call(action, at, tokens) {
|
|
720
|
+
const token = (ref) => {
|
|
721
|
+
if (ref === undefined) {
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
const found = tokens.get(ref);
|
|
725
|
+
if (found === undefined) {
|
|
726
|
+
throw new Error(`No element ${JSON.stringify(ref)} in the window now: read it again.`);
|
|
727
|
+
}
|
|
728
|
+
return found;
|
|
729
|
+
};
|
|
730
|
+
const on = { pid: at.pid, window_id: at.window };
|
|
731
|
+
switch (action.kind) {
|
|
732
|
+
case "pointer": {
|
|
733
|
+
const element = token(action.ref);
|
|
734
|
+
if (element === undefined) {
|
|
735
|
+
throw new Error('A desktop app takes a click on an entity: {kind: "pointer", ref}.');
|
|
736
|
+
}
|
|
737
|
+
return { tool: "click", args: { element_token: element } };
|
|
738
|
+
}
|
|
739
|
+
case "text": {
|
|
740
|
+
const element = token(action.ref);
|
|
741
|
+
return { tool: "type_text", args: element !== undefined ? { element_token: element, text: action.text } : { ...on, text: action.text } };
|
|
742
|
+
}
|
|
743
|
+
case "key": {
|
|
744
|
+
const parts = action.key.split("+");
|
|
745
|
+
const key = parts.pop().toLowerCase();
|
|
746
|
+
const named = key === "enter" ? "return" : key;
|
|
747
|
+
return parts.length ? { tool: "hotkey", args: { ...on, keys: [...parts.map((part) => part.toLowerCase() === "meta" ? "cmd" : part.toLowerCase()), named] } } : { tool: "press_key", args: { ...on, key: named } };
|
|
748
|
+
}
|
|
749
|
+
case "scroll": {
|
|
750
|
+
const element = token(action.ref);
|
|
751
|
+
const dy = action.dy ?? 0;
|
|
752
|
+
return {
|
|
753
|
+
tool: "scroll",
|
|
754
|
+
args: {
|
|
755
|
+
...element !== undefined ? { element_token: element } : on,
|
|
756
|
+
direction: dy < 0 ? "up" : "down",
|
|
757
|
+
amount: Math.max(1, Math.round(Math.abs(dy) / 100) || 3)
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
case "verb":
|
|
762
|
+
throw new Error("A desktop app has no verbs: use pointer, text, key and scroll.");
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
DesktopTarget.call = call;
|
|
766
|
+
})(DesktopTarget ||= {});
|
|
767
|
+
|
|
768
|
+
// web-src/desktop-apps.ts
|
|
769
|
+
var CALL_MS = 8000;
|
|
770
|
+
var LIST_MS = 2000;
|
|
771
|
+
var WALK_MAX = 600;
|
|
772
|
+
var DRIVER_SESSION = "ta-reflex";
|
|
773
|
+
var PENDING_MS = 1e4;
|
|
774
|
+
var PENDING_EVERY_MS = 500;
|
|
775
|
+
var runDriver = (driver, call, timeoutMs) => new Promise((resolve, reject) => {
|
|
776
|
+
const args = ["call", call.tool, JSON.stringify(call.args), ...driver.socket ? ["--socket", driver.socket] : []];
|
|
777
|
+
execFile(driver.program, args, { timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, ...driver.env } }, (error, stdout, stderr) => {
|
|
778
|
+
if (error) {
|
|
779
|
+
reject(new Error((stderr || stdout || error.message).trim().slice(0, 400)));
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
try {
|
|
783
|
+
resolve(JSON.parse(stdout));
|
|
784
|
+
} catch {
|
|
785
|
+
resolve(stdout);
|
|
786
|
+
}
|
|
787
|
+
});
|
|
788
|
+
});
|
|
789
|
+
|
|
790
|
+
class DesktopApps {
|
|
791
|
+
driver;
|
|
792
|
+
own;
|
|
793
|
+
now;
|
|
794
|
+
sleep;
|
|
795
|
+
windows = new Map;
|
|
796
|
+
listed;
|
|
797
|
+
run;
|
|
798
|
+
constructor(driver, run = runDriver, own = [process.pid, process.ppid], now = () => Date.now(), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) {
|
|
799
|
+
this.driver = driver;
|
|
800
|
+
this.own = own;
|
|
801
|
+
this.now = now;
|
|
802
|
+
this.sleep = sleep;
|
|
803
|
+
this.run = async (driver2, call, timeoutMs) => {
|
|
804
|
+
const until = this.now() + PENDING_MS;
|
|
805
|
+
for (;; ) {
|
|
806
|
+
try {
|
|
807
|
+
return await run(driver2, call, timeoutMs);
|
|
808
|
+
} catch (failure) {
|
|
809
|
+
if (!/permissions_pending/.test(String(failure?.message)) || this.now() >= until) {
|
|
810
|
+
throw failure;
|
|
811
|
+
}
|
|
812
|
+
await this.sleep(PENDING_EVERY_MS);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
async list() {
|
|
818
|
+
const driver = await this.driver();
|
|
819
|
+
if (!driver) {
|
|
820
|
+
return [];
|
|
821
|
+
}
|
|
822
|
+
if (!this.listed || this.now() - this.listed.at > LIST_MS) {
|
|
823
|
+
await driver.ensure?.();
|
|
824
|
+
const listed = await this.run(driver, { tool: "list_windows", args: {} }, CALL_MS);
|
|
825
|
+
this.listed = { at: this.now(), windows: DesktopTarget.windows(listed.windows ?? [], this.own) };
|
|
826
|
+
}
|
|
827
|
+
return this.listed.windows.map((window) => DesktopApps.info(window));
|
|
828
|
+
}
|
|
829
|
+
async observe(id) {
|
|
830
|
+
const at = DesktopTarget.parse(id);
|
|
831
|
+
const driver = await this.driver();
|
|
832
|
+
if (!at || !driver) {
|
|
833
|
+
return;
|
|
834
|
+
}
|
|
835
|
+
await driver.ensure?.();
|
|
836
|
+
const window = this.windows.get(id)?.window ?? await this.find(id);
|
|
837
|
+
if (!window) {
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
const state = await this.run(driver, {
|
|
841
|
+
tool: "get_window_state",
|
|
842
|
+
args: {
|
|
843
|
+
pid: at.pid,
|
|
844
|
+
window_id: at.window,
|
|
845
|
+
include_screenshot: false,
|
|
846
|
+
max_elements: WALK_MAX,
|
|
847
|
+
tree_format: "both",
|
|
848
|
+
session: DRIVER_SESSION
|
|
849
|
+
}
|
|
850
|
+
}, CALL_MS);
|
|
851
|
+
if (state.degraded && !state.elements?.length) {
|
|
852
|
+
throw new Error(`The window cannot be read now: ${(state.degraded_reason ?? "the driver says it is degraded").split(".")[0]}.`);
|
|
853
|
+
}
|
|
854
|
+
const { observation, tokens } = DesktopTarget.observation(state.elements ?? [], window.bounds, state.tree_markdown);
|
|
855
|
+
this.windows.set(id, { window, tokens });
|
|
856
|
+
return { ...observation, data: { app: window.app_name, ...state.window_title ? { title: state.window_title } : {} } };
|
|
857
|
+
}
|
|
858
|
+
async act(id, actions) {
|
|
859
|
+
const at = DesktopTarget.parse(id);
|
|
860
|
+
const driver = await this.driver();
|
|
861
|
+
const known = this.windows.get(id);
|
|
862
|
+
if (!at || !driver) {
|
|
863
|
+
throw new Error("No such window of a desktop app here.");
|
|
864
|
+
}
|
|
865
|
+
for (const action of actions) {
|
|
866
|
+
const call = DesktopTarget.call(action, at, known?.tokens ?? new Map);
|
|
867
|
+
await this.run(driver, { tool: call.tool, args: { ...call.args, session: DRIVER_SESSION } }, CALL_MS);
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
async find(id) {
|
|
871
|
+
this.listed = undefined;
|
|
872
|
+
await this.list();
|
|
873
|
+
const listed = this.listed;
|
|
874
|
+
return listed?.windows.find((window) => DesktopTarget.id(window) === id);
|
|
875
|
+
}
|
|
876
|
+
static info(window) {
|
|
877
|
+
return {
|
|
878
|
+
id: DesktopTarget.id(window),
|
|
879
|
+
kind: "app",
|
|
880
|
+
title: DesktopTarget.title(window),
|
|
881
|
+
tier: "tree",
|
|
882
|
+
actions: ["pointer", "text", "key", "scroll"],
|
|
883
|
+
hz: DesktopTarget.HZ,
|
|
884
|
+
describe: "entities: the controls of the window, each {id, type (button, textfield, checkbox, menuitem, text, … as a page has them), text (its label), value?, box of the window}; act on one by its id (ref)"
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
// web-src/deciders.ts
|
|
890
|
+
var DecideQuestions;
|
|
891
|
+
((DecideQuestions) => {
|
|
892
|
+
DecideQuestions.YES = "yes";
|
|
893
|
+
DecideQuestions.NO = "no";
|
|
894
|
+
function options(question) {
|
|
895
|
+
if ("choice" in question) {
|
|
896
|
+
return question.options;
|
|
897
|
+
}
|
|
898
|
+
if ("noul" in question) {
|
|
899
|
+
return [DecideQuestions.YES, DecideQuestions.NO];
|
|
900
|
+
}
|
|
901
|
+
return levels(question.scale).map(String);
|
|
902
|
+
}
|
|
903
|
+
DecideQuestions.options = options;
|
|
904
|
+
function text(question) {
|
|
905
|
+
return "choice" in question ? question.choice : ("noul" in question) ? question.noul : question.score;
|
|
906
|
+
}
|
|
907
|
+
DecideQuestions.text = text;
|
|
908
|
+
function levels([from, to]) {
|
|
909
|
+
const span = to - from;
|
|
910
|
+
const count = Math.min(10, Math.max(2, Number.isInteger(span) ? span + 1 : 10));
|
|
911
|
+
return Array.from({ length: count }, (_, i) => Math.round((from + span * i / (count - 1)) * 100) / 100);
|
|
912
|
+
}
|
|
913
|
+
DecideQuestions.levels = levels;
|
|
914
|
+
function answer(question, probs) {
|
|
915
|
+
const options2 = DecideQuestions.options(question);
|
|
916
|
+
const sum = probs.reduce((a, b) => a + b, 0) || 1;
|
|
917
|
+
const share = probs.map((p) => p / sum);
|
|
918
|
+
const best = share.indexOf(Math.max(...share));
|
|
919
|
+
const named = Object.fromEntries(options2.map((option, i) => [option, Math.round(share[i] * 1000) / 1000]));
|
|
920
|
+
const value = "noul" in question ? best === 0 : ("score" in question) ? Number(options2[best]) : options2[best];
|
|
921
|
+
return { ...question.id ? { id: question.id } : {}, answer: value, probs: named, confidence: share[best] };
|
|
922
|
+
}
|
|
923
|
+
DecideQuestions.answer = answer;
|
|
924
|
+
})(DecideQuestions ||= {});
|
|
925
|
+
var CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
926
|
+
var OPTIONS_MAX = CODES.length;
|
|
927
|
+
var SYSTEM = "You choose for an agent that works an app for the user. Answer with the letter of one option only.";
|
|
928
|
+
function base(url) {
|
|
929
|
+
return url.replace(/\/+$/, "").replace(/\/v1$/, "");
|
|
930
|
+
}
|
|
931
|
+
function prompt(state, question) {
|
|
932
|
+
const options = "choice" in question && question.means ? question.options.map((option, at) => question.means?.[at] ?? option) : DecideQuestions.options(question);
|
|
933
|
+
if (options.length > OPTIONS_MAX) {
|
|
934
|
+
throw new Error(`A question asked of a chat model has at most ${OPTIONS_MAX} options.`);
|
|
935
|
+
}
|
|
936
|
+
return `Screen: ${state}
|
|
937
|
+
${DecideQuestions.text(question)}
|
|
938
|
+
${options.map((option, i) => `${CODES[i]}: ${option}`).join(`
|
|
939
|
+
`)}
|
|
940
|
+
Answer:`;
|
|
941
|
+
}
|
|
942
|
+
function envKeys(env = {}) {
|
|
943
|
+
return async (config) => config.keyEnv ? env[config.keyEnv] : undefined;
|
|
944
|
+
}
|
|
945
|
+
var DECIDE_TIMEOUT_MS = { local: 5000, remote: 2500 };
|
|
946
|
+
function isLocal(url) {
|
|
947
|
+
return /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:|\/|$)/.test(url);
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
class HttpDecider {
|
|
951
|
+
config;
|
|
952
|
+
fetch;
|
|
953
|
+
name;
|
|
954
|
+
online;
|
|
955
|
+
keys;
|
|
956
|
+
constructor(config, fetch2, keys = {}) {
|
|
957
|
+
this.config = config;
|
|
958
|
+
this.fetch = fetch2;
|
|
959
|
+
this.name = config.name ?? (config.model ? `${config.model} @ ${base(config.baseUrl)}` : base(config.baseUrl));
|
|
960
|
+
this.online = !isLocal(config.baseUrl);
|
|
961
|
+
this.keys = typeof keys === "function" ? keys : envKeys(keys);
|
|
962
|
+
}
|
|
963
|
+
async post(path, body, signal) {
|
|
964
|
+
const key = await this.keys(this.config);
|
|
965
|
+
const timeout = AbortSignal.timeout(this.config.timeoutMs ?? (this.online ? DECIDE_TIMEOUT_MS.remote : DECIDE_TIMEOUT_MS.local));
|
|
966
|
+
const response = await this.fetch(`${base(this.config.baseUrl)}${path}`, {
|
|
967
|
+
method: "POST",
|
|
968
|
+
headers: { "content-type": "application/json", ...key ? { authorization: `Bearer ${key}` } : {} },
|
|
969
|
+
body: JSON.stringify(body),
|
|
970
|
+
signal: signal ? AbortSignal.any([signal, timeout]) : timeout
|
|
971
|
+
});
|
|
972
|
+
if (!response.ok) {
|
|
973
|
+
throw new Error(`${this.name} answered ${response.status}: ${(await response.text()).slice(0, 200)}`);
|
|
974
|
+
}
|
|
975
|
+
return await response.json();
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
class DecisionsDecider extends HttpDecider {
|
|
980
|
+
api = "decisions";
|
|
981
|
+
async decide(ask, signal) {
|
|
982
|
+
const questions = Object.fromEntries(ask.questions.map((question, i) => [
|
|
983
|
+
`q${i}`,
|
|
984
|
+
"choice" in question ? {
|
|
985
|
+
type: "choice",
|
|
986
|
+
instructions: question.choice,
|
|
987
|
+
criteria: Object.fromEntries(question.options.map((option, at) => [option, question.means?.[at] ?? ""]))
|
|
988
|
+
} : ("noul" in question) ? { type: "noul", instructions: question.noul } : { type: "score", instructions: question.score, criteria: DecideQuestions.levels(question.scale).map(String) }
|
|
989
|
+
]));
|
|
990
|
+
const json = await this.post("/v1/systemone", { model: this.config.model ?? "jev-latest", state: ask.state, questions }, signal);
|
|
991
|
+
const answers = json.answers ?? {};
|
|
992
|
+
return ask.questions.map((question, i) => {
|
|
993
|
+
const got = answers[`q${i}`];
|
|
994
|
+
if (!got) {
|
|
995
|
+
throw new Error(`${this.name} gave no answer to a question.`);
|
|
996
|
+
}
|
|
997
|
+
const options = DecideQuestions.options(question);
|
|
998
|
+
if ("noul" in question) {
|
|
999
|
+
const p = Number(got.noul);
|
|
1000
|
+
return DecideQuestions.answer(question, [p, 1 - p]);
|
|
1001
|
+
}
|
|
1002
|
+
const probabilities = got.probabilities ?? {};
|
|
1003
|
+
const probs = options.map((option, at) => Number(probabilities[option] ?? probabilities[String(at)] ?? 0));
|
|
1004
|
+
if (probs.every((p) => !p)) {
|
|
1005
|
+
const picked = "choice" in question ? options.indexOf(String(got.choice)) : options.indexOf(String(got.score));
|
|
1006
|
+
return DecideQuestions.answer(question, options.map((_, at) => at === picked ? Number(got.confidence ?? 1) : 0));
|
|
1007
|
+
}
|
|
1008
|
+
return DecideQuestions.answer(question, probs);
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
class LogprobsDecider extends HttpDecider {
|
|
1014
|
+
api = "logprobs";
|
|
1015
|
+
decide(ask, signal) {
|
|
1016
|
+
return Promise.all(ask.questions.map((question) => this.one(ask.state, question, signal)));
|
|
1017
|
+
}
|
|
1018
|
+
async one(state, question, signal) {
|
|
1019
|
+
const json = await this.post("/v1/chat/completions", {
|
|
1020
|
+
model: this.config.model ?? "default",
|
|
1021
|
+
messages: [
|
|
1022
|
+
{ role: "system", content: SYSTEM },
|
|
1023
|
+
{ role: "user", content: prompt(state, question) }
|
|
1024
|
+
],
|
|
1025
|
+
temperature: 0,
|
|
1026
|
+
max_tokens: 1,
|
|
1027
|
+
logprobs: true,
|
|
1028
|
+
top_logprobs: 20
|
|
1029
|
+
}, signal);
|
|
1030
|
+
const choice = json.choices?.[0];
|
|
1031
|
+
const top = choice?.logprobs?.content?.[0]?.top_logprobs;
|
|
1032
|
+
if (!top?.length) {
|
|
1033
|
+
throw new Error(`${this.name} gives no logprobs: ask it by json-schema instead.`);
|
|
1034
|
+
}
|
|
1035
|
+
const options = DecideQuestions.options(question);
|
|
1036
|
+
return DecideQuestions.answer(question, options.map((_, i) => Math.exp(top.find((each) => each.token.trim() === CODES[i])?.logprob ?? Number.NEGATIVE_INFINITY)));
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
class SchemaDecider extends HttpDecider {
|
|
1041
|
+
api = "json-schema";
|
|
1042
|
+
decide(ask, signal) {
|
|
1043
|
+
return Promise.all(ask.questions.map((question) => this.one(ask.state, question, signal)));
|
|
1044
|
+
}
|
|
1045
|
+
async one(state, question, signal) {
|
|
1046
|
+
const options = DecideQuestions.options(question);
|
|
1047
|
+
const letters = options.map((_, i) => CODES[i]);
|
|
1048
|
+
const json = await this.post("/v1/chat/completions", {
|
|
1049
|
+
model: this.config.model ?? "default",
|
|
1050
|
+
messages: [
|
|
1051
|
+
{ role: "system", content: `${SYSTEM} Say how sure you are, from 0 to 1.` },
|
|
1052
|
+
{ role: "user", content: prompt(state, question) }
|
|
1053
|
+
],
|
|
1054
|
+
temperature: 0,
|
|
1055
|
+
max_tokens: 120,
|
|
1056
|
+
response_format: {
|
|
1057
|
+
type: "json_schema",
|
|
1058
|
+
json_schema: {
|
|
1059
|
+
name: "decision",
|
|
1060
|
+
strict: true,
|
|
1061
|
+
schema: {
|
|
1062
|
+
type: "object",
|
|
1063
|
+
properties: { answer: { type: "string", enum: letters }, confidence: { type: "number" } },
|
|
1064
|
+
required: ["answer", "confidence"]
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
}, signal);
|
|
1069
|
+
const content = json.choices?.[0]?.message?.content ?? "";
|
|
1070
|
+
const parsed = JSON.parse(content);
|
|
1071
|
+
const picked = letters.indexOf(String(parsed.answer));
|
|
1072
|
+
if (picked < 0) {
|
|
1073
|
+
throw new Error(`${this.name} answered none of the options.`);
|
|
1074
|
+
}
|
|
1075
|
+
const said = Number(parsed.confidence);
|
|
1076
|
+
const sure = Math.min(1, Math.max(0, said > 1 ? said / 100 : Number.isFinite(said) ? said : 0.5));
|
|
1077
|
+
const rest = options.length > 1 ? (1 - sure) / (options.length - 1) : 0;
|
|
1078
|
+
return DecideQuestions.answer(question, options.map((_, i) => i === picked ? sure : rest));
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
var Deciders;
|
|
1082
|
+
((Deciders) => {
|
|
1083
|
+
function of(config, fetch2, env = {}) {
|
|
1084
|
+
switch (config.api) {
|
|
1085
|
+
case "decisions":
|
|
1086
|
+
return new DecisionsDecider(config, fetch2, env);
|
|
1087
|
+
case "logprobs":
|
|
1088
|
+
return new LogprobsDecider(config, fetch2, env);
|
|
1089
|
+
case "json-schema":
|
|
1090
|
+
return new SchemaDecider(config, fetch2, env);
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
Deciders.of = of;
|
|
1094
|
+
})(Deciders ||= {});
|
|
1095
|
+
|
|
1096
|
+
// web-src/reflex-deciders.ts
|
|
1097
|
+
var LOCAL_SERVERS = ["http://127.0.0.1:8080", "http://127.0.0.1:11434", "http://127.0.0.1:1234", "http://127.0.0.1:8000"];
|
|
1098
|
+
var MIN_START = 0.8;
|
|
1099
|
+
var MIN_FLOOR = 0.6;
|
|
1100
|
+
var MIN_CEIL = 0.98;
|
|
1101
|
+
var MISS_TARGET = 0.05;
|
|
1102
|
+
var DOWN_MS = 30000;
|
|
1103
|
+
var FOUND_MS = 60000;
|
|
1104
|
+
var CACHE_MS = 1e4;
|
|
1105
|
+
var CACHE_MAX = 64;
|
|
1106
|
+
var PROBE_MS = 400;
|
|
1107
|
+
var UNASKED_DAYS = 7;
|
|
1108
|
+
|
|
1109
|
+
class ManagedDecider {
|
|
1110
|
+
name;
|
|
1111
|
+
managed;
|
|
1112
|
+
fetch;
|
|
1113
|
+
api = "decisions";
|
|
1114
|
+
online = false;
|
|
1115
|
+
by;
|
|
1116
|
+
constructor(name, managed, fetch2) {
|
|
1117
|
+
this.name = name;
|
|
1118
|
+
this.managed = managed;
|
|
1119
|
+
this.fetch = fetch2;
|
|
1120
|
+
}
|
|
1121
|
+
async decide(ask, signal) {
|
|
1122
|
+
const url = await this.managed.url();
|
|
1123
|
+
if (this.by?.url !== url) {
|
|
1124
|
+
this.by = { url, decider: Deciders.of({ api: "decisions", baseUrl: url, name: this.name, model: "local" }, this.fetch) };
|
|
1125
|
+
}
|
|
1126
|
+
return this.by.decider.decide(ask, signal);
|
|
1127
|
+
}
|
|
1128
|
+
warm() {
|
|
1129
|
+
this.managed.url().catch(() => {
|
|
1130
|
+
return;
|
|
1131
|
+
});
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
class ReflexDeciders {
|
|
1136
|
+
settings;
|
|
1137
|
+
fetch;
|
|
1138
|
+
env;
|
|
1139
|
+
now;
|
|
1140
|
+
extra;
|
|
1141
|
+
kept = new Map;
|
|
1142
|
+
found;
|
|
1143
|
+
cache = new Map;
|
|
1144
|
+
constructor(settings, fetch2, env = {}, now = () => Date.now(), extra = {}) {
|
|
1145
|
+
this.settings = settings;
|
|
1146
|
+
this.fetch = fetch2;
|
|
1147
|
+
this.env = env;
|
|
1148
|
+
this.now = now;
|
|
1149
|
+
this.extra = extra;
|
|
1150
|
+
}
|
|
1151
|
+
async info() {
|
|
1152
|
+
const settings = await this.settings();
|
|
1153
|
+
if (settings.off) {
|
|
1154
|
+
return { min: MIN_START, why: "The user turned decision models off: the commander decides." };
|
|
1155
|
+
}
|
|
1156
|
+
const [first] = await this.usable(settings);
|
|
1157
|
+
if (!first) {
|
|
1158
|
+
return {
|
|
1159
|
+
min: MIN_START,
|
|
1160
|
+
why: (settings.online ? "No decision model answers: none is set and none was found on this computer." : "No decision model on this computer answers, and online ones are off.") + await this.offer()
|
|
1161
|
+
};
|
|
1162
|
+
}
|
|
1163
|
+
return {
|
|
1164
|
+
by: first.decider.name,
|
|
1165
|
+
api: first.decider.api,
|
|
1166
|
+
online: first.decider.online,
|
|
1167
|
+
...first.ms !== undefined ? { ms: Math.round(first.ms) } : {},
|
|
1168
|
+
min: settings.min ?? first.min
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
async decide(ask, signal) {
|
|
1172
|
+
const key = JSON.stringify(ask);
|
|
1173
|
+
const cached = this.cache.get(key);
|
|
1174
|
+
if (cached && this.now() - cached.at < CACHE_MS) {
|
|
1175
|
+
return cached.result;
|
|
1176
|
+
}
|
|
1177
|
+
const settings = await this.settings();
|
|
1178
|
+
if (settings.off) {
|
|
1179
|
+
throw new Error("The user turned decision models off.");
|
|
1180
|
+
}
|
|
1181
|
+
const failures = [];
|
|
1182
|
+
for (const kept of await this.usable(settings)) {
|
|
1183
|
+
const started = this.now();
|
|
1184
|
+
try {
|
|
1185
|
+
const answers = await kept.decider.decide(ask, signal);
|
|
1186
|
+
const ms = this.now() - started;
|
|
1187
|
+
kept.ms = kept.ms === undefined ? ms : kept.ms * 0.7 + ms * 0.3;
|
|
1188
|
+
const result = { answers, by: kept.decider.name, api: kept.decider.api, ms };
|
|
1189
|
+
this.remember(key, result);
|
|
1190
|
+
return result;
|
|
1191
|
+
} catch (failure) {
|
|
1192
|
+
if (signal?.aborted) {
|
|
1193
|
+
throw failure;
|
|
1194
|
+
}
|
|
1195
|
+
kept.downUntil = this.now() + DOWN_MS;
|
|
1196
|
+
failures.push(failure instanceof Error ? failure.message : String(failure));
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
throw new Error(failures.length ? `No decision model answered: ${failures.join("; ")}` : "No decision model is set or found.");
|
|
1200
|
+
}
|
|
1201
|
+
min(by, settings) {
|
|
1202
|
+
return settings?.min ?? (by ? this.kept.get(by)?.min : undefined) ?? MIN_START;
|
|
1203
|
+
}
|
|
1204
|
+
report(by, missed) {
|
|
1205
|
+
const kept = [...this.kept.values()].find((each) => each.decider.name === by);
|
|
1206
|
+
if (!kept) {
|
|
1207
|
+
return;
|
|
1208
|
+
}
|
|
1209
|
+
kept.acted++;
|
|
1210
|
+
kept.missed += missed ? 1 : 0;
|
|
1211
|
+
if (missed) {
|
|
1212
|
+
kept.min = Math.min(MIN_CEIL, kept.min + 0.05);
|
|
1213
|
+
} else if (kept.acted >= 20 && kept.missed / kept.acted < MISS_TARGET) {
|
|
1214
|
+
kept.min = Math.max(MIN_FLOOR, kept.min - 0.01);
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
async warm() {
|
|
1218
|
+
const settings = await this.settings();
|
|
1219
|
+
const [first] = settings.off ? [] : await this.usable(settings);
|
|
1220
|
+
if (first?.decider instanceof ManagedDecider) {
|
|
1221
|
+
first.decider.warm();
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
async told(told) {
|
|
1225
|
+
for (const event of told.events) {
|
|
1226
|
+
if (event.type === "unsure" && event.data?.decider === "none") {
|
|
1227
|
+
await this.unasked();
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
async unasked() {
|
|
1232
|
+
const store = this.extra.unasked;
|
|
1233
|
+
if (!store) {
|
|
1234
|
+
return;
|
|
1235
|
+
}
|
|
1236
|
+
const today = new Date(this.now()).toISOString().slice(0, 10);
|
|
1237
|
+
const days = { ...await store.load().catch(() => {
|
|
1238
|
+
return;
|
|
1239
|
+
}) ?? {} };
|
|
1240
|
+
days[today] = (days[today] ?? 0) + 1;
|
|
1241
|
+
const kept = Object.keys(days).sort().slice(-UNASKED_DAYS);
|
|
1242
|
+
await store.save(Object.fromEntries(kept.map((day) => [day, days[day]])));
|
|
1243
|
+
}
|
|
1244
|
+
async offer() {
|
|
1245
|
+
const offer = await this.extra.managed?.offer().catch(() => {
|
|
1246
|
+
return;
|
|
1247
|
+
});
|
|
1248
|
+
if (!offer) {
|
|
1249
|
+
return "";
|
|
1250
|
+
}
|
|
1251
|
+
const days = await this.extra.unasked?.load().catch(() => {
|
|
1252
|
+
return;
|
|
1253
|
+
}) ?? {};
|
|
1254
|
+
const count = Object.values(days).reduce((sum, n) => sum + n, 0);
|
|
1255
|
+
const gb = (offer.bytes / 1e9).toFixed(1);
|
|
1256
|
+
return ` The user can turn on a decision model of this computer in Settings → Local models (${offer.label}, ${gb} GB to download, only then)` + (count ? `: ${count} questions of programs came to you in the last ${UNASKED_DAYS} days that it could have answered in a fraction of a second.` : ".") + " Propose it once if they do such work often; never turn it on yourself.";
|
|
1257
|
+
}
|
|
1258
|
+
remember(key, result) {
|
|
1259
|
+
this.cache.set(key, { at: this.now(), result });
|
|
1260
|
+
if (this.cache.size > CACHE_MAX) {
|
|
1261
|
+
this.cache.delete(this.cache.keys().next().value);
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
async usable(settings) {
|
|
1265
|
+
const set = settings.deciders ?? [];
|
|
1266
|
+
const kept = [
|
|
1267
|
+
...set.filter((config) => isLocal(config.baseUrl)).map((config) => this.keep(config)),
|
|
1268
|
+
...(await this.local()).map((config) => this.keep(config)),
|
|
1269
|
+
...await this.managed(),
|
|
1270
|
+
...set.filter((config) => !isLocal(config.baseUrl)).map((config) => this.keep(config))
|
|
1271
|
+
];
|
|
1272
|
+
const now = this.now();
|
|
1273
|
+
return kept.filter((each) => (settings.online || !each.decider.online) && (each.downUntil === undefined || each.downUntil <= now));
|
|
1274
|
+
}
|
|
1275
|
+
async managed() {
|
|
1276
|
+
const ready = await this.extra.managed?.ready().catch(() => {
|
|
1277
|
+
return;
|
|
1278
|
+
});
|
|
1279
|
+
if (!ready || !this.extra.managed) {
|
|
1280
|
+
return [];
|
|
1281
|
+
}
|
|
1282
|
+
const id = `managed:${ready.name}`;
|
|
1283
|
+
let kept = this.kept.get(id);
|
|
1284
|
+
if (!kept) {
|
|
1285
|
+
kept = { decider: new ManagedDecider(ready.name, this.extra.managed, this.fetch), acted: 0, missed: 0, min: MIN_START };
|
|
1286
|
+
this.kept.set(id, kept);
|
|
1287
|
+
}
|
|
1288
|
+
return [kept];
|
|
1289
|
+
}
|
|
1290
|
+
keep(config) {
|
|
1291
|
+
const id = JSON.stringify(config);
|
|
1292
|
+
let kept = this.kept.get(id);
|
|
1293
|
+
if (!kept) {
|
|
1294
|
+
kept = { decider: Deciders.of(config, this.fetch, this.env), acted: 0, missed: 0, min: MIN_START };
|
|
1295
|
+
this.kept.set(id, kept);
|
|
1296
|
+
}
|
|
1297
|
+
return kept;
|
|
1298
|
+
}
|
|
1299
|
+
async local() {
|
|
1300
|
+
if (this.found && this.now() - this.found.at < FOUND_MS) {
|
|
1301
|
+
return this.found.configs;
|
|
1302
|
+
}
|
|
1303
|
+
const configs = (await Promise.all(LOCAL_SERVERS.map((url) => this.probe(url)))).flat();
|
|
1304
|
+
this.found = { at: this.now(), configs };
|
|
1305
|
+
return configs;
|
|
1306
|
+
}
|
|
1307
|
+
async probe(baseUrl) {
|
|
1308
|
+
const signal = AbortSignal.timeout(PROBE_MS);
|
|
1309
|
+
const tried = (api) => Deciders.of({ api, baseUrl }, this.fetch, this.env).decide({ state: "A page with one button, OK.", questions: [{ noul: "Is there a button?" }] }, signal).then(() => true, () => false);
|
|
1310
|
+
if (await tried("decisions")) {
|
|
1311
|
+
return [{ api: "decisions", baseUrl, name: `decision model @ ${baseUrl}` }];
|
|
1312
|
+
}
|
|
1313
|
+
if (await tried("logprobs")) {
|
|
1314
|
+
return [{ api: "logprobs", baseUrl, name: `chat model @ ${baseUrl}` }];
|
|
1315
|
+
}
|
|
1316
|
+
return [];
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
// web-src/reflex-protocol.ts
|
|
1321
|
+
var NAME = "@celljs/ta-reflex";
|
|
1322
|
+
var ASK_KIND = "reflex";
|
|
1323
|
+
var PATHS_KEY = "paths";
|
|
1324
|
+
|
|
1325
|
+
// web-src/reflex-host.ts
|
|
1326
|
+
var ASK_MS = 40000;
|
|
1327
|
+
|
|
1328
|
+
class ReflexHost {
|
|
1329
|
+
host;
|
|
1330
|
+
now;
|
|
1331
|
+
deciders;
|
|
1332
|
+
paths;
|
|
1333
|
+
runs = new Map;
|
|
1334
|
+
listeners = new Map;
|
|
1335
|
+
waiters = new Map;
|
|
1336
|
+
count = 0;
|
|
1337
|
+
constructor(host, now = () => Date.now(), deciders, paths) {
|
|
1338
|
+
this.host = host;
|
|
1339
|
+
this.now = now;
|
|
1340
|
+
this.deciders = deciders;
|
|
1341
|
+
this.paths = paths;
|
|
1342
|
+
}
|
|
1343
|
+
async learned(titles) {
|
|
1344
|
+
const paths = this.paths;
|
|
1345
|
+
if (!paths) {
|
|
1346
|
+
return {};
|
|
1347
|
+
}
|
|
1348
|
+
const found = await Promise.all(titles.map((title) => paths.of(title).catch(() => [])));
|
|
1349
|
+
return Object.fromEntries(titles.map((title, i) => [title, found[i]]).filter(([, one]) => one.length));
|
|
1350
|
+
}
|
|
1351
|
+
async wayFor(title, goal) {
|
|
1352
|
+
return this.paths?.best(title, goal).catch(() => {
|
|
1353
|
+
return;
|
|
1354
|
+
});
|
|
1355
|
+
}
|
|
1356
|
+
decide() {
|
|
1357
|
+
return this.deciders?.info().catch(() => {
|
|
1358
|
+
return;
|
|
1359
|
+
}) ?? Promise.resolve(undefined);
|
|
1360
|
+
}
|
|
1361
|
+
attach(sessionFile, listener) {
|
|
1362
|
+
const set = this.listeners.get(sessionFile) ?? new Set;
|
|
1363
|
+
set.add(listener);
|
|
1364
|
+
this.listeners.set(sessionFile, set);
|
|
1365
|
+
return () => {
|
|
1366
|
+
set.delete(listener);
|
|
1367
|
+
if (!set.size) {
|
|
1368
|
+
this.listeners.delete(sessionFile);
|
|
1369
|
+
}
|
|
1370
|
+
};
|
|
1371
|
+
}
|
|
1372
|
+
targets(sessionFile) {
|
|
1373
|
+
return this.ask({ kind: "targets" }, sessionFile);
|
|
1374
|
+
}
|
|
1375
|
+
async start(sessionFile, target, program, intent) {
|
|
1376
|
+
if (!sessionFile) {
|
|
1377
|
+
throw new Error("A run belongs to a conversation: this one has no session file.");
|
|
1378
|
+
}
|
|
1379
|
+
const run = `r${this.now().toString(36)}${(this.count++).toString(36)}`;
|
|
1380
|
+
const session = (await this.host.listSessions()).find((one) => one.sessionFile === sessionFile);
|
|
1381
|
+
const who = session?.sessionName || session?.firstMessage?.slice(0, 40) || undefined;
|
|
1382
|
+
this.runs.set(run, { sessionFile, target });
|
|
1383
|
+
const answer = await this.ask({ kind: "start", run, target, ...program ? { program } : {}, ...intent ? { intent } : {}, ...who ? { who } : {} }, sessionFile).catch((failure) => {
|
|
1384
|
+
this.runs.delete(run);
|
|
1385
|
+
throw failure;
|
|
1386
|
+
});
|
|
1387
|
+
if (answer?.kind !== "run") {
|
|
1388
|
+
this.runs.delete(run);
|
|
1389
|
+
}
|
|
1390
|
+
return { run, answer };
|
|
1391
|
+
}
|
|
1392
|
+
intent(sessionFile, run, intent) {
|
|
1393
|
+
return this.ask({ kind: "intent", run: this.own(sessionFile, run), ...intent ? { intent } : {} }, sessionFile);
|
|
1394
|
+
}
|
|
1395
|
+
program(sessionFile, run, program) {
|
|
1396
|
+
return this.ask({ kind: "program", run: this.own(sessionFile, run), program }, sessionFile);
|
|
1397
|
+
}
|
|
1398
|
+
async stop(sessionFile, run) {
|
|
1399
|
+
const answer = await this.ask({ kind: "stop", run: this.own(sessionFile, run) }, sessionFile);
|
|
1400
|
+
this.runs.delete(run);
|
|
1401
|
+
await this.paths?.ended(run).catch(() => {
|
|
1402
|
+
return;
|
|
1403
|
+
});
|
|
1404
|
+
return answer;
|
|
1405
|
+
}
|
|
1406
|
+
batch(sessionFile, target, steps) {
|
|
1407
|
+
return this.ask({ kind: "batch", target, steps }, sessionFile);
|
|
1408
|
+
}
|
|
1409
|
+
next(sessionFile, run, ms, signal) {
|
|
1410
|
+
const id = this.own(sessionFile, run);
|
|
1411
|
+
return new Promise((resolve) => {
|
|
1412
|
+
const set = this.waiters.get(id) ?? new Set;
|
|
1413
|
+
this.waiters.set(id, set);
|
|
1414
|
+
const done = (told) => {
|
|
1415
|
+
clearTimeout(timer);
|
|
1416
|
+
signal?.removeEventListener("abort", aborted);
|
|
1417
|
+
set.delete(done);
|
|
1418
|
+
if (!set.size) {
|
|
1419
|
+
this.waiters.delete(id);
|
|
1420
|
+
}
|
|
1421
|
+
resolve(told);
|
|
1422
|
+
};
|
|
1423
|
+
const aborted = () => done(undefined);
|
|
1424
|
+
const timer = setTimeout(aborted, ms);
|
|
1425
|
+
signal?.addEventListener("abort", aborted, { once: true });
|
|
1426
|
+
set.add(done);
|
|
1427
|
+
});
|
|
1428
|
+
}
|
|
1429
|
+
runsOf(sessionFile) {
|
|
1430
|
+
return [...this.runs].filter(([, run]) => run.sessionFile === sessionFile).map(([id]) => id);
|
|
1431
|
+
}
|
|
1432
|
+
told(told) {
|
|
1433
|
+
const run = told && typeof told.run === "string" ? this.runs.get(told.run) : undefined;
|
|
1434
|
+
if (!run || !Array.isArray(told.events)) {
|
|
1435
|
+
return;
|
|
1436
|
+
}
|
|
1437
|
+
if (told.summary?.state === "stopped") {
|
|
1438
|
+
this.runs.delete(told.run);
|
|
1439
|
+
}
|
|
1440
|
+
this.paths?.told(told).catch(() => {
|
|
1441
|
+
return;
|
|
1442
|
+
});
|
|
1443
|
+
if (!told.events.length) {
|
|
1444
|
+
return;
|
|
1445
|
+
}
|
|
1446
|
+
const waiting = this.waiters.get(told.run);
|
|
1447
|
+
if (waiting?.size) {
|
|
1448
|
+
for (const done of [...waiting]) {
|
|
1449
|
+
done(told);
|
|
1450
|
+
}
|
|
1451
|
+
return;
|
|
1452
|
+
}
|
|
1453
|
+
for (const listener of this.listeners.get(run.sessionFile) ?? []) {
|
|
1454
|
+
listener(told);
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
own(sessionFile, run) {
|
|
1458
|
+
if (this.runs.get(run)?.sessionFile !== sessionFile || !sessionFile) {
|
|
1459
|
+
const mine = this.runsOf(sessionFile);
|
|
1460
|
+
throw new Error(`No run ${run} of this conversation${mine.length ? `: its runs are ${mine.join(", ")}` : ""}.`);
|
|
1461
|
+
}
|
|
1462
|
+
return run;
|
|
1463
|
+
}
|
|
1464
|
+
async ask(ask, sessionFile) {
|
|
1465
|
+
const options = { ...sessionFile ? { sessionFile } : {}, timeoutMs: ASK_MS };
|
|
1466
|
+
if (!this.host.pages.has(ASK_KIND, options)) {
|
|
1467
|
+
return;
|
|
1468
|
+
}
|
|
1469
|
+
return await this.host.pages.ask(ASK_KIND, ask, options);
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
// web-src/reflex-local-model.ts
|
|
1474
|
+
var urls = (repo, file) => [
|
|
1475
|
+
`https://huggingface.co/${repo}/resolve/main/${file}`,
|
|
1476
|
+
`https://hf-mirror.com/${repo}/resolve/main/${file}`,
|
|
1477
|
+
`https://www.modelscope.cn/models/${repo}/resolve/master/${file}`
|
|
1478
|
+
];
|
|
1479
|
+
var KEV_4B = {
|
|
1480
|
+
id: "kev-4b",
|
|
1481
|
+
label: "Kev-4B",
|
|
1482
|
+
runtime: "llama.cpp",
|
|
1483
|
+
file: "Kev-4B-Q4_K_M.gguf",
|
|
1484
|
+
sha256: "33ae6b18926502b2209a1bf7d3b61a350d65938441515c686bb87d226a19eff9",
|
|
1485
|
+
bytes: 3033489824,
|
|
1486
|
+
urls: urls("ggml-org/Kev-4B-GGUF", "Kev-4B-Q4_K_M.gguf"),
|
|
1487
|
+
forMemoryGB: 16,
|
|
1488
|
+
runMB: 3800
|
|
1489
|
+
};
|
|
1490
|
+
var KEV_08B = {
|
|
1491
|
+
id: "kev-0.8b",
|
|
1492
|
+
label: "Kev-0.8B",
|
|
1493
|
+
runtime: "llama.cpp",
|
|
1494
|
+
file: "Kev-0.8B-Q8_0.gguf",
|
|
1495
|
+
sha256: "27278f34eb3273bceea4c053dc50dd61a5161da21a718c4aacdf8fd5830771d0",
|
|
1496
|
+
bytes: 812406304,
|
|
1497
|
+
urls: urls("ggml-org/Kev-0.8B-GGUF", "Kev-0.8B-Q8_0.gguf"),
|
|
1498
|
+
runMB: 1100
|
|
1499
|
+
};
|
|
1500
|
+
var DECIDE_NEED = {
|
|
1501
|
+
id: "@celljs/ta-reflex/decide",
|
|
1502
|
+
title: { "zh-CN": "实时操作的决策模型", "zh-TW": "即時操作的決策模型", "en-US": "Decision model of live hands", "ja-JP": "リアルタイム操作の判断モデル" },
|
|
1503
|
+
hint: {
|
|
1504
|
+
"zh-CN": "点哪个按钮、弹窗选哪个、做完没有这类小判断在本机几百毫秒内答完,不用每次问 Ta;没把握时仍会问 Ta。",
|
|
1505
|
+
"zh-TW": "點哪個按鈕、彈窗選哪個、做完沒有這類小判斷在本機幾百毫秒內答完,不用每次問 Ta;沒把握時仍會問 Ta。",
|
|
1506
|
+
"en-US": "Small decisions (which button, which choice of a dialog, is it done) answered here in a few hundred milliseconds rather than asking Ta each time; Ta is still asked when it is unsure.",
|
|
1507
|
+
"ja-JP": "どのボタンを押すか、ダイアログで何を選ぶか、終わったか、といった小さな判断をこのコンピューターで数百ミリ秒で答え、毎回 Ta に聞かずに済みます。自信がないときは Ta に聞きます。"
|
|
1508
|
+
},
|
|
1509
|
+
models: [KEV_4B, KEV_08B]
|
|
1510
|
+
};
|
|
1511
|
+
var STATUS_MS = 5000;
|
|
1512
|
+
|
|
1513
|
+
class ReflexLocalModel {
|
|
1514
|
+
call;
|
|
1515
|
+
on;
|
|
1516
|
+
now;
|
|
1517
|
+
status;
|
|
1518
|
+
constructor(call, on, now = () => Date.now()) {
|
|
1519
|
+
this.call = call;
|
|
1520
|
+
this.on = on;
|
|
1521
|
+
this.now = now;
|
|
1522
|
+
}
|
|
1523
|
+
async register() {
|
|
1524
|
+
if (this.on()) {
|
|
1525
|
+
this.status = {
|
|
1526
|
+
at: this.now(),
|
|
1527
|
+
value: await this.call(TA_LOCAL_MODELS, "need", [DECIDE_NEED]).catch(() => {
|
|
1528
|
+
return;
|
|
1529
|
+
})
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
async ready() {
|
|
1534
|
+
const status = await this.read();
|
|
1535
|
+
const model = status?.state === "ready" ? DECIDE_NEED.models.find((one) => one.id === status.model) : undefined;
|
|
1536
|
+
return model ? { name: `${model.label} (this computer)` } : undefined;
|
|
1537
|
+
}
|
|
1538
|
+
async url() {
|
|
1539
|
+
return String(await this.call(TA_LOCAL_MODELS, "url", [DECIDE_NEED.id]));
|
|
1540
|
+
}
|
|
1541
|
+
async offer() {
|
|
1542
|
+
const status = await this.read();
|
|
1543
|
+
if (!status?.supported || status.on) {
|
|
1544
|
+
return;
|
|
1545
|
+
}
|
|
1546
|
+
const model = DECIDE_NEED.models.find((one) => one.id === status.recommended) ?? DECIDE_NEED.models[0];
|
|
1547
|
+
return { label: model.label, bytes: model.bytes };
|
|
1548
|
+
}
|
|
1549
|
+
async read() {
|
|
1550
|
+
if (!this.on()) {
|
|
1551
|
+
return;
|
|
1552
|
+
}
|
|
1553
|
+
if (!this.status || this.now() - this.status.at > STATUS_MS) {
|
|
1554
|
+
const value = await this.call(TA_LOCAL_MODELS, "needStatus", [DECIDE_NEED.id]).catch(async () => {
|
|
1555
|
+
await this.register();
|
|
1556
|
+
return this.status?.value;
|
|
1557
|
+
});
|
|
1558
|
+
this.status = { at: this.now(), value };
|
|
1559
|
+
}
|
|
1560
|
+
return this.status.value;
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
// web-src/reflex-paths.ts
|
|
1565
|
+
var PATHS_PER_TARGET = 5;
|
|
1566
|
+
var PATH_TARGETS = 30;
|
|
1567
|
+
var PATH_MAX = 40;
|
|
1568
|
+
function said(goal) {
|
|
1569
|
+
return goal.toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, "");
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
class ReflexPaths {
|
|
1573
|
+
store;
|
|
1574
|
+
now;
|
|
1575
|
+
loaded;
|
|
1576
|
+
pending = new Map;
|
|
1577
|
+
constructor(store, now = () => Date.now()) {
|
|
1578
|
+
this.store = store;
|
|
1579
|
+
this.now = now;
|
|
1580
|
+
}
|
|
1581
|
+
async told(told) {
|
|
1582
|
+
for (const event of told.events) {
|
|
1583
|
+
const path = event.data?.path;
|
|
1584
|
+
const goal = event.data?.goal;
|
|
1585
|
+
if (event.type === "done" && Array.isArray(path) && path.length && typeof goal === "string" && goal.trim()) {
|
|
1586
|
+
this.pending.set(told.run, { title: told.title ?? told.target, goal: goal.trim(), path: path.map(String).slice(0, PATH_MAX) });
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
if (told.summary?.state === "stopped") {
|
|
1590
|
+
await this.ended(told.run);
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
async ended(run) {
|
|
1594
|
+
const done = this.pending.get(run);
|
|
1595
|
+
this.pending.delete(run);
|
|
1596
|
+
if (done) {
|
|
1597
|
+
await this.learn(done.title, done.goal, done.path);
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
async of(title) {
|
|
1601
|
+
return (await this.all())[title] ?? [];
|
|
1602
|
+
}
|
|
1603
|
+
async best(title, goal) {
|
|
1604
|
+
return ReflexPaths.closest(await this.of(title), goal);
|
|
1605
|
+
}
|
|
1606
|
+
static closest(paths, goal) {
|
|
1607
|
+
const want = said(goal);
|
|
1608
|
+
return want ? paths.find((path) => said(path.goal) === want) : undefined;
|
|
1609
|
+
}
|
|
1610
|
+
async learn(title, goal, path) {
|
|
1611
|
+
const all = { ...await this.all() };
|
|
1612
|
+
const kept = (all[title] ?? []).filter((one) => one.goal !== goal);
|
|
1613
|
+
delete all[title];
|
|
1614
|
+
all[title] = [{ goal, path, at: this.now() }, ...kept].slice(0, PATHS_PER_TARGET);
|
|
1615
|
+
const titles = Object.keys(all);
|
|
1616
|
+
for (const old of titles.slice(0, Math.max(0, titles.length - PATH_TARGETS))) {
|
|
1617
|
+
delete all[old];
|
|
1618
|
+
}
|
|
1619
|
+
this.loaded = Promise.resolve(all);
|
|
1620
|
+
await this.store.save(all);
|
|
1621
|
+
}
|
|
1622
|
+
all() {
|
|
1623
|
+
if (!this.loaded) {
|
|
1624
|
+
this.loaded = this.store.load().then((paths) => paths && typeof paths === "object" ? paths : {}, () => ({}));
|
|
1625
|
+
}
|
|
1626
|
+
return this.loaded;
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
// web-src/decide-protocol.ts
|
|
1631
|
+
var DECIDE_APIS = ["decisions", "logprobs", "json-schema"];
|
|
1632
|
+
|
|
1633
|
+
// web-src/reflex-remotes.ts
|
|
1634
|
+
var PROBE_MS2 = 8000;
|
|
1635
|
+
function onPrivateNetwork(url) {
|
|
1636
|
+
const host = url.hostname;
|
|
1637
|
+
if (host === "localhost" || host === "[::1]" || /^[\w-]+\.local$/.test(host)) {
|
|
1638
|
+
return true;
|
|
1639
|
+
}
|
|
1640
|
+
const ip = /^(\d+)\.(\d+)\.\d+\.\d+$/.exec(host);
|
|
1641
|
+
if (!ip) {
|
|
1642
|
+
return false;
|
|
1643
|
+
}
|
|
1644
|
+
const [a, b] = [Number(ip[1]), Number(ip[2])];
|
|
1645
|
+
return a === 127 || a === 10 || a === 192 && b === 168 || a === 172 && b >= 16 && b <= 31;
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
class ReflexRemotes {
|
|
1649
|
+
store;
|
|
1650
|
+
credentials;
|
|
1651
|
+
fetch;
|
|
1652
|
+
env;
|
|
1653
|
+
id;
|
|
1654
|
+
constructor(store, credentials, fetch2, env = {}, id = () => Math.random().toString(36).slice(2, 10)) {
|
|
1655
|
+
this.store = store;
|
|
1656
|
+
this.credentials = credentials;
|
|
1657
|
+
this.fetch = fetch2;
|
|
1658
|
+
this.env = env;
|
|
1659
|
+
this.id = id;
|
|
1660
|
+
}
|
|
1661
|
+
static credentialId(id) {
|
|
1662
|
+
return `reflex-decider:${id}`;
|
|
1663
|
+
}
|
|
1664
|
+
keys = async (config) => config.key && config.id ? (await this.credentials.get(ReflexRemotes.credentialId(config.id)).catch(() => {
|
|
1665
|
+
return;
|
|
1666
|
+
}))?.password : envKeys(this.env)(config);
|
|
1667
|
+
async list() {
|
|
1668
|
+
return (await this.store.load() ?? []).map((config) => ({
|
|
1669
|
+
id: config.id ?? config.baseUrl,
|
|
1670
|
+
name: config.name ?? new URL(config.baseUrl).host,
|
|
1671
|
+
baseUrl: config.baseUrl,
|
|
1672
|
+
api: config.api,
|
|
1673
|
+
...config.model ? { model: config.model } : {},
|
|
1674
|
+
key: config.key === true || config.keyEnv !== undefined,
|
|
1675
|
+
online: !isLocal(config.baseUrl)
|
|
1676
|
+
}));
|
|
1677
|
+
}
|
|
1678
|
+
async add(input) {
|
|
1679
|
+
const baseUrl = String(input.baseUrl ?? "").trim().replace(/\/+$/, "");
|
|
1680
|
+
let url;
|
|
1681
|
+
try {
|
|
1682
|
+
url = new URL(baseUrl);
|
|
1683
|
+
} catch {
|
|
1684
|
+
throw new Error("The address of a decision model is a URL: https://api.example.com/v1.");
|
|
1685
|
+
}
|
|
1686
|
+
const key = input.key?.trim() || undefined;
|
|
1687
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && onPrivateNetwork(url))) {
|
|
1688
|
+
throw new Error("A decision model on the internet is reached over HTTPS: what the page shows goes to it.");
|
|
1689
|
+
}
|
|
1690
|
+
if (key && !this.credentials.available()) {
|
|
1691
|
+
throw new Error("Its key is kept in the vault: turn Secrets on first.");
|
|
1692
|
+
}
|
|
1693
|
+
const model = input.model?.trim() || undefined;
|
|
1694
|
+
const api = await this.probe(baseUrl, model, key);
|
|
1695
|
+
const id = this.id();
|
|
1696
|
+
if (key) {
|
|
1697
|
+
await this.credentials.set(ReflexRemotes.credentialId(id), { password: key }, { feature: "model", name: url.host });
|
|
1698
|
+
}
|
|
1699
|
+
const config = {
|
|
1700
|
+
id,
|
|
1701
|
+
name: input.name?.trim() || (model ? `${model} @ ${url.host}` : url.host),
|
|
1702
|
+
api,
|
|
1703
|
+
baseUrl,
|
|
1704
|
+
...model ? { model } : {},
|
|
1705
|
+
...key ? { key: true } : {}
|
|
1706
|
+
};
|
|
1707
|
+
await this.store.save([...await this.store.load() ?? [], config]);
|
|
1708
|
+
return this.list();
|
|
1709
|
+
}
|
|
1710
|
+
async remove(id) {
|
|
1711
|
+
const all = await this.store.load() ?? [];
|
|
1712
|
+
const gone = all.find((config) => (config.id ?? config.baseUrl) === id);
|
|
1713
|
+
await this.store.save(all.filter((config) => config !== gone));
|
|
1714
|
+
if (gone?.key && gone.id) {
|
|
1715
|
+
await this.credentials.remove(ReflexRemotes.credentialId(gone.id)).catch(() => {
|
|
1716
|
+
return;
|
|
1717
|
+
});
|
|
1718
|
+
}
|
|
1719
|
+
return this.list();
|
|
1720
|
+
}
|
|
1721
|
+
async probe(baseUrl, model, key) {
|
|
1722
|
+
const failures = [];
|
|
1723
|
+
for (const api of DECIDE_APIS) {
|
|
1724
|
+
const config = { api, baseUrl, ...model ? { model } : {}, timeoutMs: PROBE_MS2 };
|
|
1725
|
+
try {
|
|
1726
|
+
await Deciders.of(config, this.fetch, async () => key).decide({
|
|
1727
|
+
state: "A page with one button, OK.",
|
|
1728
|
+
questions: [{ noul: "Is there a button?" }]
|
|
1729
|
+
});
|
|
1730
|
+
return api;
|
|
1731
|
+
} catch (failure) {
|
|
1732
|
+
failures.push(`${api}: ${failure instanceof Error ? failure.message : String(failure)}`.slice(0, 160));
|
|
1733
|
+
}
|
|
1734
|
+
}
|
|
1735
|
+
throw new Error(`It answered none of the Decisions API, logprobs or JSON Schema: ${failures.join("; ")}`);
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1739
|
+
// web-src/reflex-util.ts
|
|
1740
|
+
var ACTIONS_MAX = 32;
|
|
1741
|
+
var PRESSES = { pointer: ["click", "move", "down", "up"], key: ["tap", "down", "up"] };
|
|
1742
|
+
function finite(value, name, min = Number.NEGATIVE_INFINITY, max = Number.POSITIVE_INFINITY) {
|
|
1743
|
+
if (value === undefined) {
|
|
1744
|
+
return;
|
|
1745
|
+
}
|
|
1746
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {
|
|
1747
|
+
throw new Error(`${name} is a number${min > Number.NEGATIVE_INFINITY ? ` from ${min} to ${max}` : ""}, not ${JSON.stringify(value)}.`);
|
|
1748
|
+
}
|
|
1749
|
+
return value;
|
|
1750
|
+
}
|
|
1751
|
+
function text(value, name) {
|
|
1752
|
+
if (typeof value !== "string" || !value) {
|
|
1753
|
+
throw new Error(`${name} is a string, not ${JSON.stringify(value)}.`);
|
|
1754
|
+
}
|
|
1755
|
+
return value;
|
|
1756
|
+
}
|
|
1757
|
+
var ReflexUtil;
|
|
1758
|
+
((ReflexUtil) => {
|
|
1759
|
+
function actions(value) {
|
|
1760
|
+
if (value === undefined || value === null) {
|
|
1761
|
+
return [];
|
|
1762
|
+
}
|
|
1763
|
+
const list = Array.isArray(value) ? value : [value];
|
|
1764
|
+
if (list.length > ACTIONS_MAX) {
|
|
1765
|
+
throw new Error(`A step gives at most ${ACTIONS_MAX} actions, not ${list.length}.`);
|
|
1766
|
+
}
|
|
1767
|
+
return list.map((one, at) => action(one, `actions[${at}]`));
|
|
1768
|
+
}
|
|
1769
|
+
ReflexUtil.actions = actions;
|
|
1770
|
+
function action(value, name = "action") {
|
|
1771
|
+
const one = value ?? {};
|
|
1772
|
+
switch (one.kind) {
|
|
1773
|
+
case "pointer": {
|
|
1774
|
+
const press = one.press ?? "click";
|
|
1775
|
+
if (!PRESSES.pointer.includes(press)) {
|
|
1776
|
+
throw new Error(`${name}.press is one of ${PRESSES.pointer.join(", ")}.`);
|
|
1777
|
+
}
|
|
1778
|
+
const x = finite(one.x, `${name}.x`, 0, 1);
|
|
1779
|
+
const y = finite(one.y, `${name}.y`, 0, 1);
|
|
1780
|
+
const dx = finite(one.dx, `${name}.dx`, -1e4, 1e4);
|
|
1781
|
+
const dy = finite(one.dy, `${name}.dy`, -1e4, 1e4);
|
|
1782
|
+
return {
|
|
1783
|
+
kind: "pointer",
|
|
1784
|
+
...x !== undefined ? { x } : {},
|
|
1785
|
+
...y !== undefined ? { y } : {},
|
|
1786
|
+
...typeof one.ref === "string" ? { ref: one.ref } : {},
|
|
1787
|
+
...dx !== undefined ? { dx } : {},
|
|
1788
|
+
...dy !== undefined ? { dy } : {},
|
|
1789
|
+
...one.press !== undefined ? { press } : {}
|
|
1790
|
+
};
|
|
1791
|
+
}
|
|
1792
|
+
case "key": {
|
|
1793
|
+
const press = one.press ?? "tap";
|
|
1794
|
+
if (!PRESSES.key.includes(press)) {
|
|
1795
|
+
throw new Error(`${name}.press is one of ${PRESSES.key.join(", ")}.`);
|
|
1796
|
+
}
|
|
1797
|
+
const ms = finite(one.ms, `${name}.ms`, 10, 5000);
|
|
1798
|
+
return {
|
|
1799
|
+
kind: "key",
|
|
1800
|
+
key: text(one.key, `${name}.key`),
|
|
1801
|
+
...one.press !== undefined ? { press } : {},
|
|
1802
|
+
...ms !== undefined ? { ms } : {}
|
|
1803
|
+
};
|
|
1804
|
+
}
|
|
1805
|
+
case "text":
|
|
1806
|
+
return { kind: "text", text: String(one.text ?? ""), ...typeof one.ref === "string" ? { ref: one.ref } : {} };
|
|
1807
|
+
case "scroll": {
|
|
1808
|
+
const dx = finite(one.dx, `${name}.dx`);
|
|
1809
|
+
const dy = finite(one.dy, `${name}.dy`);
|
|
1810
|
+
return {
|
|
1811
|
+
kind: "scroll",
|
|
1812
|
+
...dx !== undefined ? { dx } : {},
|
|
1813
|
+
...dy !== undefined ? { dy } : {},
|
|
1814
|
+
...typeof one.ref === "string" ? { ref: one.ref } : {}
|
|
1815
|
+
};
|
|
1816
|
+
}
|
|
1817
|
+
case "verb":
|
|
1818
|
+
return {
|
|
1819
|
+
kind: "verb",
|
|
1820
|
+
name: text(one.name, `${name}.name`),
|
|
1821
|
+
...one.input && typeof one.input === "object" ? { input: one.input } : {}
|
|
1822
|
+
};
|
|
1823
|
+
default:
|
|
1824
|
+
throw new Error(`${name}.kind is pointer, key, text, scroll or verb, not ${JSON.stringify(one.kind)}.`);
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
ReflexUtil.action = action;
|
|
1828
|
+
function intent(value) {
|
|
1829
|
+
const one = value && typeof value === "object" ? value : {};
|
|
1830
|
+
const ttl = finite(one.ttl, "intent.ttl", 0.1, 86400);
|
|
1831
|
+
return {
|
|
1832
|
+
...typeof one.goal === "string" ? { goal: one.goal } : {},
|
|
1833
|
+
...one.params && typeof one.params === "object" && !Array.isArray(one.params) ? { params: one.params } : {},
|
|
1834
|
+
...ttl !== undefined ? { ttl } : {},
|
|
1835
|
+
...Array.isArray(one.reportOn) ? { reportOn: one.reportOn.filter((type) => typeof type === "string") } : {}
|
|
1836
|
+
};
|
|
1837
|
+
}
|
|
1838
|
+
ReflexUtil.intent = intent;
|
|
1839
|
+
function percentile(values, p) {
|
|
1840
|
+
if (!values.length) {
|
|
1841
|
+
return 0;
|
|
1842
|
+
}
|
|
1843
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
1844
|
+
return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * p))];
|
|
1845
|
+
}
|
|
1846
|
+
ReflexUtil.percentile = percentile;
|
|
1847
|
+
})(ReflexUtil ||= {});
|
|
1848
|
+
|
|
1849
|
+
// web-src/host.ts
|
|
1850
|
+
function decideSettings(host) {
|
|
1851
|
+
return async () => {
|
|
1852
|
+
const [decide, online, deciders, min] = await Promise.all(["decide", "decideOnline", "deciders", "decideMin"].map((key) => host.getExtensionData(NAME, key).catch(() => {
|
|
1853
|
+
return;
|
|
1854
|
+
})));
|
|
1855
|
+
return {
|
|
1856
|
+
...decide === false ? { off: true } : {},
|
|
1857
|
+
...online === true ? { online: true } : {},
|
|
1858
|
+
...Array.isArray(deciders) ? { deciders } : {},
|
|
1859
|
+
...typeof min === "number" ? { min } : {}
|
|
1860
|
+
};
|
|
1861
|
+
};
|
|
1862
|
+
}
|
|
1863
|
+
var COMPUTER_USE = "@celljs/ta-computer-use";
|
|
1864
|
+
var ALLOWED_MS = 30000;
|
|
1865
|
+
function desktopDriver(host) {
|
|
1866
|
+
let allowed;
|
|
1867
|
+
return async () => {
|
|
1868
|
+
if (!allowed || Date.now() - allowed.at > ALLOWED_MS) {
|
|
1869
|
+
const packages = await host.listPackages().catch(() => []);
|
|
1870
|
+
allowed = { at: Date.now(), on: packages.some((pkg) => pkg.name === COMPUTER_USE && pkg.enabled !== false) };
|
|
1871
|
+
}
|
|
1872
|
+
if (!allowed.on) {
|
|
1873
|
+
return;
|
|
1874
|
+
}
|
|
1875
|
+
const { CuaDriver: CuaDriver2 } = await Promise.resolve().then(() => (init_cua_driver(), exports_cua_driver));
|
|
1876
|
+
const { setupOf: setupOf2 } = await Promise.resolve().then(() => (init_extension(), exports_extension));
|
|
1877
|
+
const program = CuaDriver2.locate();
|
|
1878
|
+
if (!program) {
|
|
1879
|
+
return;
|
|
1880
|
+
}
|
|
1881
|
+
const setup = setupOf2(program, process.platform);
|
|
1882
|
+
const daemon = setup.daemon;
|
|
1883
|
+
return {
|
|
1884
|
+
program: daemon ? `${daemon.app}/Contents/MacOS/cua-driver` : setup.program.path,
|
|
1885
|
+
...daemon ? { socket: daemon.socket, ensure: () => daemon.ensure() } : {},
|
|
1886
|
+
...setup.env ? { env: setup.env } : {}
|
|
1887
|
+
};
|
|
1888
|
+
};
|
|
1889
|
+
}
|
|
1890
|
+
function activate2(host) {
|
|
1891
|
+
const remotes = new ReflexRemotes({
|
|
1892
|
+
load: async () => {
|
|
1893
|
+
const configs = await host.getExtensionData(NAME, "deciders").catch(() => {
|
|
1894
|
+
return;
|
|
1895
|
+
});
|
|
1896
|
+
return Array.isArray(configs) ? configs : undefined;
|
|
1897
|
+
},
|
|
1898
|
+
save: (configs) => host.setExtensionData(NAME, "deciders", configs)
|
|
1899
|
+
}, host.credentials, fetch, process.env);
|
|
1900
|
+
const local = new ReflexLocalModel((name, method, params) => host.callPackageHost(name, method, params), () => host.packageHosts?.on(TA_LOCAL_MODELS) ?? false);
|
|
1901
|
+
local.register();
|
|
1902
|
+
const stopWatching = host.packageHosts?.onChange(() => void local.register());
|
|
1903
|
+
const deciders = new ReflexDeciders(decideSettings(host), fetch, remotes.keys, undefined, {
|
|
1904
|
+
managed: local,
|
|
1905
|
+
unasked: {
|
|
1906
|
+
load: async () => await host.getExtensionData(NAME, "unasked").catch(() => {
|
|
1907
|
+
return;
|
|
1908
|
+
}),
|
|
1909
|
+
save: (days) => host.setExtensionData(NAME, "unasked", days)
|
|
1910
|
+
}
|
|
1911
|
+
});
|
|
1912
|
+
const paths = new ReflexPaths({
|
|
1913
|
+
load: async () => await host.getExtensionData(NAME, PATHS_KEY),
|
|
1914
|
+
save: (paths2) => host.setExtensionData(NAME, PATHS_KEY, paths2)
|
|
1915
|
+
});
|
|
1916
|
+
const reflex = new ReflexHost(host, undefined, deciders, paths);
|
|
1917
|
+
const apps = new DesktopApps(desktopDriver(host));
|
|
1918
|
+
return {
|
|
1919
|
+
apps: () => apps.list().catch(() => []),
|
|
1920
|
+
appObserve: (id) => apps.observe(String(id)),
|
|
1921
|
+
appAct: (id, actions) => apps.act(String(id), ReflexUtil.actions(actions)),
|
|
1922
|
+
told: async (told) => {
|
|
1923
|
+
await reflex.told(told);
|
|
1924
|
+
await deciders.told(told);
|
|
1925
|
+
},
|
|
1926
|
+
deciders: () => deciders.info(),
|
|
1927
|
+
decide: async (ask) => {
|
|
1928
|
+
const result = await deciders.decide(ask);
|
|
1929
|
+
return { answers: result.answers, by: result.by, ms: result.ms };
|
|
1930
|
+
},
|
|
1931
|
+
decided: (by, missed) => deciders.report(String(by), missed === true),
|
|
1932
|
+
warm: () => deciders.warm(),
|
|
1933
|
+
remotes: () => remotes.list(),
|
|
1934
|
+
addRemote: (input) => remotes.add(input),
|
|
1935
|
+
removeRemote: (id) => remotes.remove(String(id)),
|
|
1936
|
+
dispose: () => stopWatching?.(),
|
|
1937
|
+
service: reflex
|
|
1938
|
+
};
|
|
1939
|
+
}
|
|
1940
|
+
export {
|
|
1941
|
+
activate2 as default
|
|
1942
|
+
};
|