reasonally 0.0.0-stage → 0.2.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.md +70 -2
- package/dist/api.js +50 -0
- package/dist/browser/command.js +93 -0
- package/dist/browser/guards.js +138 -0
- package/dist/browser/pairing.js +123 -0
- package/dist/browser/protocol.js +172 -0
- package/dist/browser/server.js +157 -0
- package/dist/browser/sessions.js +478 -0
- package/dist/catalog.js +55 -0
- package/dist/cli.js +220 -0
- package/dist/config.js +86 -0
- package/dist/harnesses/cline.js +26 -0
- package/dist/harnesses/crush.js +47 -0
- package/dist/harnesses/hermes.js +33 -0
- package/dist/harnesses/index.js +7 -0
- package/dist/harnesses/opencode.js +44 -0
- package/dist/harnesses/pi.js +46 -0
- package/dist/harnesses/types.js +18 -0
- package/dist/index.js +3 -0
- package/dist/launch.js +59 -0
- package/dist/login.js +113 -0
- package/dist/pkce.js +10 -0
- package/package.json +31 -4
package/README.md
CHANGED
|
@@ -1,3 +1,71 @@
|
|
|
1
|
-
#
|
|
1
|
+
# reasonally
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Run the coding agents you already use on Reasonally models, billed to your Reasonally workspace.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install -g reasonally
|
|
7
|
+
reasonally login # approve this computer in your browser
|
|
8
|
+
reasonally opencode --model anthropic/claude-sonnet-4.5
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Needs Node.js 20 or later.
|
|
12
|
+
|
|
13
|
+
## Agents
|
|
14
|
+
|
|
15
|
+
| Command | Agent |
|
|
16
|
+
| --------------------- | ----------------------------------------------------- |
|
|
17
|
+
| `reasonally opencode` | [OpenCode](https://opencode.ai) |
|
|
18
|
+
| `reasonally crush` | [Crush](https://github.com/charmbracelet/crush) |
|
|
19
|
+
| `reasonally cline` | [Cline](https://cline.bot) CLI |
|
|
20
|
+
| `reasonally pi` | [Pi](https://pi.dev) |
|
|
21
|
+
| `reasonally hermes` | [Hermes Agent](https://hermes-agent.nousresearch.com) |
|
|
22
|
+
|
|
23
|
+
Each agent keeps its own interface. Anything after the agent's name, except `--model`, is passed
|
|
24
|
+
to it unchanged. Without `--model`, pick a Reasonally model in the agent's own model picker
|
|
25
|
+
(Cline and Hermes need one to start; the last one you used is remembered).
|
|
26
|
+
|
|
27
|
+
The CLI points each agent at Reasonally for that launch without editing the agent's own config:
|
|
28
|
+
|
|
29
|
+
- **OpenCode**: inline config through `OPENCODE_CONFIG_CONTENT`.
|
|
30
|
+
- **Crush**: a generated `crushrc` (via `CRUSH_GLOBAL_CONFIG`) that loads your own crushrc first.
|
|
31
|
+
- **Cline**: a separate data directory (`CLINE_DATA_DIR`) configured with `cline auth`.
|
|
32
|
+
- **Pi**: a generated provider extension loaded with `-e`.
|
|
33
|
+
- **Hermes**: `hermes chat --provider custom` for that launch; `~/.hermes` is untouched.
|
|
34
|
+
|
|
35
|
+
Generated files live in `~/.config/reasonally/harness/`.
|
|
36
|
+
|
|
37
|
+
## Other commands
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
reasonally models [search] # models you can use, with context and price
|
|
41
|
+
reasonally whoami # account and balance
|
|
42
|
+
reasonally logout # log out and revoke this computer's key
|
|
43
|
+
reasonally login --no-browser # print the approval link instead of opening it
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Browser use
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
reasonally browser # keep it running while a chat uses the browser
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Lets a chat in your Reasonally dashboard control a visible browser window on this computer, using
|
|
53
|
+
Google Chrome (or Edge, or a Chromium from `npx playwright install chromium`). No login needed.
|
|
54
|
+
|
|
55
|
+
- The first time a chat asks, the terminal asks you to allow it (`y`). That browser stays paired for
|
|
56
|
+
30 days. Only the dashboard's own site can talk to the companion, and only on `127.0.0.1`.
|
|
57
|
+
- Each chat gets its own window with a fresh profile. Logins last until that window closes. Windows
|
|
58
|
+
close after 30 minutes without activity, and all of them close when you stop the companion
|
|
59
|
+
(Ctrl+C).
|
|
60
|
+
- Password, payment-card and one-time-code fields are left for you to fill in.
|
|
61
|
+
- Addresses on this computer or your local network (localhost, 192.168.x.x, `.local`, …) are off.
|
|
62
|
+
Pass `--allow-local` to allow them, e.g. for a dev server.
|
|
63
|
+
- `--port N` changes the port (default 47614).
|
|
64
|
+
|
|
65
|
+
## Environment
|
|
66
|
+
|
|
67
|
+
| Variable | Use |
|
|
68
|
+
| -------------------- | ------------------------------------------------------------ |
|
|
69
|
+
| `REASONALLY_API_KEY` | Use an existing API key instead of logging in (CI, servers). |
|
|
70
|
+
| `REASONALLY_URL` | Dashboard URL (default `https://app.reasonally.ai`). |
|
|
71
|
+
| `REASONALLY_API_URL` | API base URL (default `https://api.reasonally.ai/v1`). |
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { parseCatalog } from "./catalog.js";
|
|
2
|
+
/** A failed call to Reasonally, carrying the server's OpenAI-shaped error message. */
|
|
3
|
+
export class ApiError extends Error {
|
|
4
|
+
status;
|
|
5
|
+
code;
|
|
6
|
+
constructor(message, status, code) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.code = code;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
async function call(url, init = {}) {
|
|
13
|
+
let res;
|
|
14
|
+
try {
|
|
15
|
+
res = await fetch(url, { ...init, signal: AbortSignal.timeout(30_000) });
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
throw new ApiError(`Couldn't reach ${new URL(url).host}: ${error.message}`, 0, null);
|
|
19
|
+
}
|
|
20
|
+
const body = (await res.json().catch(() => null));
|
|
21
|
+
if (!res.ok) {
|
|
22
|
+
const message = body?.error?.message ?? `Request failed with HTTP ${res.status}.`;
|
|
23
|
+
throw new ApiError(message, res.status, body?.error?.code ?? null);
|
|
24
|
+
}
|
|
25
|
+
if (body === null)
|
|
26
|
+
throw new ApiError("The server sent an unreadable response.", res.status, null);
|
|
27
|
+
return body;
|
|
28
|
+
}
|
|
29
|
+
const bearer = (apiKey) => ({ authorization: `Bearer ${apiKey}` });
|
|
30
|
+
export function exchangeCode(appUrl, body) {
|
|
31
|
+
return call(`${appUrl}/api/cli/token`, {
|
|
32
|
+
method: "POST",
|
|
33
|
+
headers: { "content-type": "application/json" },
|
|
34
|
+
body: JSON.stringify(body),
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
export function fetchAccount(appUrl, apiKey) {
|
|
38
|
+
return call(`${appUrl}/api/cli/me`, {
|
|
39
|
+
headers: bearer(apiKey),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
export function revokeKey(appUrl, apiKey) {
|
|
43
|
+
return call(`${appUrl}/api/cli/logout`, {
|
|
44
|
+
method: "POST",
|
|
45
|
+
headers: bearer(apiKey),
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
export async function fetchModels(apiBaseUrl, apiKey) {
|
|
49
|
+
return parseCatalog(await call(`${apiBaseUrl}/models`, { headers: bearer(apiKey) }));
|
|
50
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/** `reasonally browser`: lets a Reasonally chat drive a visible browser window on this computer. */
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { appUrlFrom, readCredentials } from "../config.js";
|
|
4
|
+
import { createPairing, fileTokenStore, terminalPrompt } from "./pairing.js";
|
|
5
|
+
import { DEFAULT_PORT } from "./protocol.js";
|
|
6
|
+
import { createCompanionServer } from "./server.js";
|
|
7
|
+
import { createPlaywrightSessions } from "./sessions.js";
|
|
8
|
+
export function parseBrowserArgs(args) {
|
|
9
|
+
let port = DEFAULT_PORT;
|
|
10
|
+
let allowLocal = false;
|
|
11
|
+
for (let i = 0; i < args.length; i++) {
|
|
12
|
+
const arg = args[i];
|
|
13
|
+
if (arg === "--allow-local") {
|
|
14
|
+
allowLocal = true;
|
|
15
|
+
}
|
|
16
|
+
else if (arg === "--port" || arg.startsWith("--port=")) {
|
|
17
|
+
const value = arg === "--port" ? args[++i] : arg.slice("--port=".length);
|
|
18
|
+
const n = Number(value);
|
|
19
|
+
if (!value || !Number.isInteger(n) || n < 1 || n > 65535) {
|
|
20
|
+
return { error: "--port needs a number between 1 and 65535." };
|
|
21
|
+
}
|
|
22
|
+
port = n;
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
return {
|
|
26
|
+
error: `Unknown option "${arg}". Usage: reasonally browser [--port N] [--allow-local]`,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return { port, allowLocal };
|
|
31
|
+
}
|
|
32
|
+
export async function browserCommand(args, log) {
|
|
33
|
+
const parsed = parseBrowserArgs(args);
|
|
34
|
+
if ("error" in parsed) {
|
|
35
|
+
log(parsed.error);
|
|
36
|
+
return 1;
|
|
37
|
+
}
|
|
38
|
+
const appUrl = appUrlFrom(process.env, await readCredentials());
|
|
39
|
+
let origin;
|
|
40
|
+
try {
|
|
41
|
+
origin = new URL(appUrl).origin;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
log(`REASONALLY_URL isn't a valid URL: ${appUrl}`);
|
|
45
|
+
return 1;
|
|
46
|
+
}
|
|
47
|
+
// Playwright itself loads on the first action (`import()` in sessions.ts).
|
|
48
|
+
const sessions = createPlaywrightSessions({ allowLocal: parsed.allowLocal, log });
|
|
49
|
+
const server = createCompanionServer({
|
|
50
|
+
origin,
|
|
51
|
+
version: createRequire(import.meta.url)("../../package.json").version,
|
|
52
|
+
pairing: createPairing({ store: fileTokenStore(), prompt: terminalPrompt }),
|
|
53
|
+
sessions,
|
|
54
|
+
log,
|
|
55
|
+
});
|
|
56
|
+
try {
|
|
57
|
+
await new Promise((resolve, reject) => {
|
|
58
|
+
server.once("error", reject);
|
|
59
|
+
server.listen(parsed.port, "127.0.0.1", () => {
|
|
60
|
+
server.off("error", reject);
|
|
61
|
+
resolve();
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (error.code === "EADDRINUSE") {
|
|
67
|
+
log(`Port ${parsed.port} is already in use. Is another \`reasonally browser\` running? ` +
|
|
68
|
+
"Stop it, or pick another port with --port.");
|
|
69
|
+
return 1;
|
|
70
|
+
}
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
log(`Browser companion running on http://127.0.0.1:${parsed.port}`);
|
|
74
|
+
log(`Chats at ${origin} can ask to control a browser window on this computer.`);
|
|
75
|
+
if (parsed.allowLocal)
|
|
76
|
+
log("Local and private-network addresses are allowed (--allow-local).");
|
|
77
|
+
log("Keep this terminal open. Press Ctrl+C to stop.");
|
|
78
|
+
return new Promise((resolve) => {
|
|
79
|
+
let stopping = false;
|
|
80
|
+
const stop = () => {
|
|
81
|
+
if (stopping)
|
|
82
|
+
process.exit(130); // a second Ctrl+C doesn't wait for windows to close
|
|
83
|
+
stopping = true;
|
|
84
|
+
log("Closing browser windows…");
|
|
85
|
+
server.closeAllConnections();
|
|
86
|
+
server.close();
|
|
87
|
+
void sessions.closeAll().finally(() => resolve(0));
|
|
88
|
+
};
|
|
89
|
+
process.on("SIGINT", stop);
|
|
90
|
+
process.on("SIGTERM", stop);
|
|
91
|
+
process.on("SIGHUP", stop); // the terminal was closed
|
|
92
|
+
});
|
|
93
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the model may browse and type. Pure functions, so the rules are unit-tested without a
|
|
3
|
+
* browser. `sessions.ts` applies them before and after every action.
|
|
4
|
+
*/
|
|
5
|
+
import { BlockList, isIP } from "node:net";
|
|
6
|
+
import { HAND_OFF } from "./protocol.js";
|
|
7
|
+
export const LOCAL_BLOCKED = "That address is on this computer or your local network, which the browser companion doesn't open. " +
|
|
8
|
+
"To allow it, restart the companion with `reasonally browser --allow-local`.";
|
|
9
|
+
/** Loopback, private (RFC 1918 / ULA), link-local, CGNAT and other non-public ranges. */
|
|
10
|
+
const NON_PUBLIC = new BlockList();
|
|
11
|
+
for (const [net, prefix] of [
|
|
12
|
+
["0.0.0.0", 8], // "this network"; 0.0.0.0 reaches localhost on macOS and Linux
|
|
13
|
+
["10.0.0.0", 8],
|
|
14
|
+
["100.64.0.0", 10], // CGNAT
|
|
15
|
+
["127.0.0.0", 8],
|
|
16
|
+
["169.254.0.0", 16], // link-local
|
|
17
|
+
["172.16.0.0", 12],
|
|
18
|
+
["192.0.0.0", 24],
|
|
19
|
+
["192.168.0.0", 16],
|
|
20
|
+
["198.18.0.0", 15], // benchmarking
|
|
21
|
+
["224.0.0.0", 4], // multicast
|
|
22
|
+
["240.0.0.0", 4], // reserved + broadcast
|
|
23
|
+
]) {
|
|
24
|
+
NON_PUBLIC.addSubnet(net, prefix, "ipv4");
|
|
25
|
+
}
|
|
26
|
+
for (const [net, prefix] of [
|
|
27
|
+
["::", 128], // unspecified
|
|
28
|
+
["::1", 128], // loopback
|
|
29
|
+
["fc00::", 7], // unique local
|
|
30
|
+
["fe80::", 10], // link-local
|
|
31
|
+
["ff00::", 8], // multicast
|
|
32
|
+
]) {
|
|
33
|
+
NON_PUBLIC.addSubnet(net, prefix, "ipv6");
|
|
34
|
+
}
|
|
35
|
+
/** Whether an IP address (v4, v6 or IPv4-mapped v6) is outside the public internet. */
|
|
36
|
+
export function isNonPublicAddress(address) {
|
|
37
|
+
const ip = address.replace(/^\[|\]$/g, "");
|
|
38
|
+
const family = isIP(ip);
|
|
39
|
+
if (family === 4)
|
|
40
|
+
return NON_PUBLIC.check(ip, "ipv4");
|
|
41
|
+
if (family === 6)
|
|
42
|
+
return NON_PUBLIC.check(ip, "ipv6"); // also checks ::ffff:a.b.c.d against v4
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
/** Hostnames that resolve on this computer or the local network by convention. */
|
|
46
|
+
export function isLocalHostname(hostname) {
|
|
47
|
+
const host = hostname.toLowerCase().replace(/\.$/, "");
|
|
48
|
+
if (isNonPublicAddress(host))
|
|
49
|
+
return true;
|
|
50
|
+
if (isIP(host.replace(/^\[|\]$/g, "")))
|
|
51
|
+
return false;
|
|
52
|
+
return (host === "localhost" ||
|
|
53
|
+
host.endsWith(".localhost") ||
|
|
54
|
+
host.endsWith(".local") ||
|
|
55
|
+
// A single label ("router", "nas") only resolves through local search domains.
|
|
56
|
+
!host.includes("."));
|
|
57
|
+
}
|
|
58
|
+
const SCHEME = /^[a-z][a-z0-9+.-]*:/i;
|
|
59
|
+
const HOST_PORT = /^[^/?#:@]+:\d{1,5}(?:[/?#]|$)/; // "example.com:8080/x" is a host, not a scheme
|
|
60
|
+
/**
|
|
61
|
+
* Checks an address the model asked to open. Only http(s); a bare `example.com` gets `https://`.
|
|
62
|
+
* Local and private-network hosts are refused unless the companion runs with `--allow-local`.
|
|
63
|
+
*/
|
|
64
|
+
export function checkUrl(raw, { allowLocal = false } = {}) {
|
|
65
|
+
const input = raw.trim();
|
|
66
|
+
const hasScheme = SCHEME.test(input) && !HOST_PORT.test(input);
|
|
67
|
+
let url;
|
|
68
|
+
try {
|
|
69
|
+
url = new URL(hasScheme ? input : `https://${input}`);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return { ok: false, error: `"${input.slice(0, 200)}" isn't a valid web address.` };
|
|
73
|
+
}
|
|
74
|
+
// Local dev servers rarely speak https: `localhost:3000` means http://localhost:3000.
|
|
75
|
+
if (!hasScheme && isLocalHostname(url.hostname))
|
|
76
|
+
url.protocol = "http:";
|
|
77
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
78
|
+
return { ok: false, error: "Only http and https addresses can be opened." };
|
|
79
|
+
}
|
|
80
|
+
if (!url.hostname)
|
|
81
|
+
return { ok: false, error: "That address has no host." };
|
|
82
|
+
if (url.username || url.password) {
|
|
83
|
+
return { ok: false, error: "Addresses with a username or password in them can't be opened." };
|
|
84
|
+
}
|
|
85
|
+
if (!allowLocal && isLocalHostname(url.hostname))
|
|
86
|
+
return { ok: false, error: LOCAL_BLOCKED };
|
|
87
|
+
return { ok: true, url: url.href };
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Whether the browser may stay on a page it ended up on (after a click, redirect or script).
|
|
91
|
+
* Browser-internal pages (about:blank, error pages) are fine; local hosts need `--allow-local`.
|
|
92
|
+
*/
|
|
93
|
+
export function isAllowedPageUrl(href, { allowLocal = false } = {}) {
|
|
94
|
+
let url;
|
|
95
|
+
try {
|
|
96
|
+
url = new URL(href);
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
if (url.protocol !== "http:" && url.protocol !== "https:")
|
|
102
|
+
return true;
|
|
103
|
+
return allowLocal || !isLocalHostname(url.hostname);
|
|
104
|
+
}
|
|
105
|
+
const SENSITIVE_AUTOCOMPLETE = ["cc-", "current-password", "new-password", "one-time-code"];
|
|
106
|
+
/** Password, payment-card and one-time-code fields are for the person, never the model. */
|
|
107
|
+
export function isSensitiveField(field) {
|
|
108
|
+
if (field.tagName.toLowerCase() === "input" && field.type?.toLowerCase() === "password") {
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
const autocomplete = field.autocomplete?.toLowerCase() ?? "";
|
|
112
|
+
return SENSITIVE_AUTOCOMPLETE.some((token) => autocomplete.includes(token));
|
|
113
|
+
}
|
|
114
|
+
/** `null` when the model may type into the field, else the error to return. */
|
|
115
|
+
export function checkTypeTarget(field) {
|
|
116
|
+
return isSensitiveField(field) ? HAND_OFF : null;
|
|
117
|
+
}
|
|
118
|
+
/** Keys that move around or submit without entering text, so they're fine on a sensitive field. */
|
|
119
|
+
const NON_TEXT_KEYS = new Set([
|
|
120
|
+
"Tab",
|
|
121
|
+
"Shift+Tab",
|
|
122
|
+
"Enter",
|
|
123
|
+
"Escape",
|
|
124
|
+
"ArrowUp",
|
|
125
|
+
"ArrowDown",
|
|
126
|
+
"ArrowLeft",
|
|
127
|
+
"ArrowRight",
|
|
128
|
+
"Home",
|
|
129
|
+
"End",
|
|
130
|
+
"PageUp",
|
|
131
|
+
"PageDown",
|
|
132
|
+
]);
|
|
133
|
+
/** `press` on a focused sensitive field may only navigate; typed characters or pastes are refused. */
|
|
134
|
+
export function checkPressTarget(key, focused) {
|
|
135
|
+
if (!focused || !isSensitiveField(focused))
|
|
136
|
+
return null;
|
|
137
|
+
return NON_TEXT_KEYS.has(key) ? null : HAND_OFF;
|
|
138
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pairing: the person approves a chat origin once in the terminal; the chat gets a random token and
|
|
3
|
+
* we keep only its SHA-256 hash (in the CLI config dir, owner-only), valid for 30 days.
|
|
4
|
+
*/
|
|
5
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
6
|
+
import { readFile } from "node:fs/promises";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { createInterface } from "node:readline";
|
|
9
|
+
import { configDir, writePrivateFile } from "../config.js";
|
|
10
|
+
export const TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
11
|
+
export const PAIR_PROMPT_TIMEOUT_MS = 60 * 1000;
|
|
12
|
+
/** Each paired browser profile keeps a token; old ones beyond this are dropped. */
|
|
13
|
+
const MAX_TOKENS = 20;
|
|
14
|
+
export const hashToken = (token) => createHash("sha256").update(token).digest("hex");
|
|
15
|
+
export const newToken = () => randomBytes(32).toString("base64url");
|
|
16
|
+
/** The `Authorization: Bearer <token>` value, if any. */
|
|
17
|
+
export function bearerToken(header) {
|
|
18
|
+
const match = header?.match(/^Bearer\s+([A-Za-z0-9_-]{20,200})\s*$/i);
|
|
19
|
+
return match ? match[1] : null;
|
|
20
|
+
}
|
|
21
|
+
export function fileTokenStore({ path = join(configDir(), "browser-pairings.json"), now = () => Date.now(), } = {}) {
|
|
22
|
+
async function load() {
|
|
23
|
+
try {
|
|
24
|
+
const parsed = JSON.parse(await readFile(path, "utf8"));
|
|
25
|
+
if (!Array.isArray(parsed.tokens))
|
|
26
|
+
return [];
|
|
27
|
+
return parsed.tokens.filter((t) => typeof t?.hash === "string" &&
|
|
28
|
+
typeof t?.origin === "string" &&
|
|
29
|
+
typeof t?.expiresAt === "string");
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return [];
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const live = (t) => Date.parse(t.expiresAt) > now();
|
|
36
|
+
return {
|
|
37
|
+
async issue(origin) {
|
|
38
|
+
const token = newToken();
|
|
39
|
+
const created = now();
|
|
40
|
+
const entry = {
|
|
41
|
+
hash: hashToken(token),
|
|
42
|
+
origin,
|
|
43
|
+
createdAt: new Date(created).toISOString(),
|
|
44
|
+
expiresAt: new Date(created + TOKEN_TTL_MS).toISOString(),
|
|
45
|
+
};
|
|
46
|
+
const tokens = [...(await load()).filter(live), entry].slice(-MAX_TOKENS);
|
|
47
|
+
await writePrivateFile(path, `${JSON.stringify({ tokens }, null, 2)}\n`);
|
|
48
|
+
return token;
|
|
49
|
+
},
|
|
50
|
+
async verify(token, origin) {
|
|
51
|
+
if (!token)
|
|
52
|
+
return false;
|
|
53
|
+
const hash = Buffer.from(hashToken(token), "hex");
|
|
54
|
+
return (await load()).some((t) => t.origin === origin &&
|
|
55
|
+
live(t) &&
|
|
56
|
+
/^[0-9a-f]{64}$/.test(t.hash) &&
|
|
57
|
+
timingSafeEqual(Buffer.from(t.hash, "hex"), hash));
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** The real prompt: one line on stderr, the answer on stdin, default No. */
|
|
62
|
+
export const terminalPrompt = (question, signal) => new Promise((resolve) => {
|
|
63
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
64
|
+
let settled = false;
|
|
65
|
+
const finish = (answer, line) => {
|
|
66
|
+
if (settled)
|
|
67
|
+
return;
|
|
68
|
+
settled = true;
|
|
69
|
+
signal.removeEventListener("abort", onAbort);
|
|
70
|
+
if (line)
|
|
71
|
+
process.stderr.write(`${line}\n`);
|
|
72
|
+
rl.close();
|
|
73
|
+
resolve(answer);
|
|
74
|
+
};
|
|
75
|
+
const onAbort = () => finish(false, "\nNo answer in time; the request was declined.");
|
|
76
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
77
|
+
// Ctrl+C while the question is open: decline, then stop the companion as usual.
|
|
78
|
+
rl.on("SIGINT", () => {
|
|
79
|
+
finish(false, "\nDeclined.");
|
|
80
|
+
process.emit("SIGINT");
|
|
81
|
+
});
|
|
82
|
+
rl.on("close", () => finish(false));
|
|
83
|
+
rl.question(`${question} `, (answer) => {
|
|
84
|
+
const yes = /^\s*y(es)?\s*$/i.test(answer);
|
|
85
|
+
finish(yes, yes ? "Allowed." : "Declined.");
|
|
86
|
+
});
|
|
87
|
+
if (signal.aborted)
|
|
88
|
+
onAbort();
|
|
89
|
+
});
|
|
90
|
+
/** One pairing prompt at a time, each timing out after `timeoutMs`. */
|
|
91
|
+
export function createPairing({ store, prompt, timeoutMs = PAIR_PROMPT_TIMEOUT_MS, }) {
|
|
92
|
+
let pending = false;
|
|
93
|
+
return {
|
|
94
|
+
verify: (token, origin) => store.verify(token, origin),
|
|
95
|
+
/** `cancel` aborts the question, e.g. when the requesting tab goes away. */
|
|
96
|
+
async request(origin, cancel) {
|
|
97
|
+
if (pending)
|
|
98
|
+
return { kind: "busy" };
|
|
99
|
+
pending = true;
|
|
100
|
+
const controller = new AbortController();
|
|
101
|
+
let timedOut = false;
|
|
102
|
+
const timer = setTimeout(() => {
|
|
103
|
+
timedOut = true;
|
|
104
|
+
controller.abort();
|
|
105
|
+
}, timeoutMs);
|
|
106
|
+
const onCancel = () => controller.abort();
|
|
107
|
+
cancel?.addEventListener("abort", onCancel, { once: true });
|
|
108
|
+
try {
|
|
109
|
+
const question = `Allow the chat at ${origin} to control a browser on this computer? (y/N)`;
|
|
110
|
+
const approved = await prompt(question, controller.signal);
|
|
111
|
+
if (approved && !controller.signal.aborted) {
|
|
112
|
+
return { kind: "approved", token: await store.issue(origin) };
|
|
113
|
+
}
|
|
114
|
+
return { kind: timedOut ? "timeout" : "declined" };
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
clearTimeout(timer);
|
|
118
|
+
cancel?.removeEventListener("abort", onCancel);
|
|
119
|
+
pending = false;
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
export const PROTOCOL_VERSION = 1;
|
|
2
|
+
export const DEFAULT_PORT = 47614;
|
|
3
|
+
export const MAX_BODY_BYTES = 64 * 1024;
|
|
4
|
+
export const SNAPSHOT_CAP = 40_000;
|
|
5
|
+
export const TRUNCATED_NOTE = "[truncated]";
|
|
6
|
+
export const MAX_WAIT_SECONDS = 10;
|
|
7
|
+
export const STALE_REF = "That element changed; take a new snapshot.";
|
|
8
|
+
export const HAND_OFF = "Ask the person to enter this themselves (browser_hand_off).";
|
|
9
|
+
/** Refs come from the AI-mode aria snapshot: `e12`, or `f1e3` for an element inside an iframe. */
|
|
10
|
+
const REF = /^(?:f\d{1,6})?e\d{1,9}$/;
|
|
11
|
+
export const isRef = (value) => typeof value === "string" && REF.test(value);
|
|
12
|
+
const CHAT_ID = /^[A-Za-z0-9_-]{1,100}$/;
|
|
13
|
+
export const isChatId = (value) => CHAT_ID.test(value);
|
|
14
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
15
|
+
/**
|
|
16
|
+
* Validates `{ action, args }`. A malformed ref is reported as stale: to the model it is the same
|
|
17
|
+
* mistake (a ref it shouldn't use), with the same fix.
|
|
18
|
+
*/
|
|
19
|
+
export function parseAction(body) {
|
|
20
|
+
if (!isObject(body) || typeof body.action !== "string") {
|
|
21
|
+
return { ok: false, error: "Expected a JSON body like { action, args }." };
|
|
22
|
+
}
|
|
23
|
+
const args = body.args === undefined || body.args === null ? {} : body.args;
|
|
24
|
+
if (!isObject(args))
|
|
25
|
+
return { ok: false, error: "`args` must be an object." };
|
|
26
|
+
const bad = (error) => ({ ok: false, error });
|
|
27
|
+
const ref = () => (isRef(args.ref) ? args.ref : null);
|
|
28
|
+
const staleRef = { ok: false, error: STALE_REF, staleRef: true };
|
|
29
|
+
switch (body.action) {
|
|
30
|
+
case "navigate": {
|
|
31
|
+
const url = typeof args.url === "string" ? args.url.trim() : "";
|
|
32
|
+
if (!url)
|
|
33
|
+
return bad("navigate needs a `url`.");
|
|
34
|
+
if (url.length > 8192)
|
|
35
|
+
return bad("That address is too long.");
|
|
36
|
+
return { ok: true, action: { action: "navigate", args: { url } } };
|
|
37
|
+
}
|
|
38
|
+
case "snapshot":
|
|
39
|
+
case "back":
|
|
40
|
+
case "focus":
|
|
41
|
+
return { ok: true, action: { action: body.action, args: {} } };
|
|
42
|
+
case "click": {
|
|
43
|
+
const r = ref();
|
|
44
|
+
return r ? { ok: true, action: { action: "click", args: { ref: r } } } : staleRef;
|
|
45
|
+
}
|
|
46
|
+
case "type": {
|
|
47
|
+
if (typeof args.text !== "string")
|
|
48
|
+
return bad("type needs `text`.");
|
|
49
|
+
if (args.submit !== undefined && typeof args.submit !== "boolean") {
|
|
50
|
+
return bad("`submit` must be true or false.");
|
|
51
|
+
}
|
|
52
|
+
const r = ref();
|
|
53
|
+
if (!r)
|
|
54
|
+
return staleRef;
|
|
55
|
+
return {
|
|
56
|
+
ok: true,
|
|
57
|
+
action: { action: "type", args: { ref: r, text: args.text, submit: args.submit === true } },
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
case "select": {
|
|
61
|
+
const values = args.values;
|
|
62
|
+
if (!Array.isArray(values) ||
|
|
63
|
+
values.length === 0 ||
|
|
64
|
+
!values.every((v) => typeof v === "string")) {
|
|
65
|
+
return bad("select needs `values`: a list of option values or labels.");
|
|
66
|
+
}
|
|
67
|
+
const r = ref();
|
|
68
|
+
if (!r)
|
|
69
|
+
return staleRef;
|
|
70
|
+
return { ok: true, action: { action: "select", args: { ref: r, values } } };
|
|
71
|
+
}
|
|
72
|
+
case "press": {
|
|
73
|
+
const key = typeof args.key === "string" ? args.key : "";
|
|
74
|
+
// Playwright key names: "Enter", "ArrowDown", "Control+A", "a", "Shift+Tab"…
|
|
75
|
+
if (!key || key.length > 40 || /[\r\n]/.test(key)) {
|
|
76
|
+
return bad("press needs a `key`, like Enter, Tab, Escape or ArrowDown.");
|
|
77
|
+
}
|
|
78
|
+
return { ok: true, action: { action: "press", args: { key } } };
|
|
79
|
+
}
|
|
80
|
+
case "scroll":
|
|
81
|
+
if (args.direction !== "up" && args.direction !== "down") {
|
|
82
|
+
return bad('scroll needs `direction`: "up" or "down".');
|
|
83
|
+
}
|
|
84
|
+
return { ok: true, action: { action: "scroll", args: { direction: args.direction } } };
|
|
85
|
+
case "wait": {
|
|
86
|
+
const text = typeof args.text === "string" && args.text.trim() ? args.text : undefined;
|
|
87
|
+
if (args.seconds !== undefined) {
|
|
88
|
+
const s = args.seconds;
|
|
89
|
+
if (typeof s !== "number" || !Number.isFinite(s) || s <= 0 || s > MAX_WAIT_SECONDS) {
|
|
90
|
+
return bad(`wait \`seconds\` must be more than 0 and at most ${MAX_WAIT_SECONDS}.`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const seconds = args.seconds;
|
|
94
|
+
if (text === undefined && seconds === undefined) {
|
|
95
|
+
return bad("wait needs `text` to wait for, or `seconds` (at most 10).");
|
|
96
|
+
}
|
|
97
|
+
return { ok: true, action: { action: "wait", args: { text, seconds } } };
|
|
98
|
+
}
|
|
99
|
+
default:
|
|
100
|
+
return bad(`Unknown action "${body.action.slice(0, 40)}".`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Keeps a snapshot within `cap` characters, cutting at a line break and ending with a
|
|
105
|
+
* `[truncated]` line so the model knows the page goes on.
|
|
106
|
+
*/
|
|
107
|
+
export function capSnapshot(snapshot, cap = SNAPSHOT_CAP) {
|
|
108
|
+
if (snapshot.length <= cap)
|
|
109
|
+
return snapshot;
|
|
110
|
+
const room = cap - TRUNCATED_NOTE.length - 1;
|
|
111
|
+
const cut = snapshot.lastIndexOf("\n", room);
|
|
112
|
+
return `${snapshot.slice(0, cut > 0 ? cut : room)}\n${TRUNCATED_NOTE}`;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* What a ref points at, read from the snapshot it came from: `- button "Sign in" [ref=e12]`
|
|
116
|
+
* gives `{ role: "button", name: "Sign in" }`, and `- generic [ref=e3]: Hello` gives the text.
|
|
117
|
+
*/
|
|
118
|
+
export function describeRef(snapshot, ref) {
|
|
119
|
+
const marker = `[ref=${ref}]`;
|
|
120
|
+
const line = snapshot.split("\n").find((l) => l.includes(marker));
|
|
121
|
+
if (!line)
|
|
122
|
+
return null;
|
|
123
|
+
const match = line.match(/^\s*-\s+([a-z]+)(?:\s+"((?:[^"\\]|\\.)*)")?/i);
|
|
124
|
+
if (!match)
|
|
125
|
+
return null;
|
|
126
|
+
const inline = line
|
|
127
|
+
.slice(line.indexOf(marker) + marker.length)
|
|
128
|
+
.match(/^(?:\s*\[[^\]]*\])*:\s+(.+)$/);
|
|
129
|
+
const name = match[2]?.replace(/\\(.)/g, "$1") ?? inline?.[1]?.trim() ?? "";
|
|
130
|
+
return { role: match[1], name };
|
|
131
|
+
}
|
|
132
|
+
/** `"Sign in"` when the element has a name, else `the button`. */
|
|
133
|
+
export function nameForRef(snapshot, ref) {
|
|
134
|
+
const element = describeRef(snapshot, ref);
|
|
135
|
+
if (!element)
|
|
136
|
+
return "the element";
|
|
137
|
+
const name = element.name.length > 60 ? `${element.name.slice(0, 57)}…` : element.name;
|
|
138
|
+
if (name)
|
|
139
|
+
return `"${name}"`;
|
|
140
|
+
return element.role === "generic" ? "the element" : `the ${element.role}`;
|
|
141
|
+
}
|
|
142
|
+
export class BodyError extends Error {
|
|
143
|
+
status;
|
|
144
|
+
constructor(status, message) {
|
|
145
|
+
super(message);
|
|
146
|
+
this.status = status;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/** Reads a JSON request body of at most `limit` bytes (an empty body reads as `{}`). */
|
|
150
|
+
export async function readJsonBody(req, limit = MAX_BODY_BYTES) {
|
|
151
|
+
const tooLarge = () => new BodyError(413, `The request body is over ${limit / 1024} KB.`);
|
|
152
|
+
const declared = Number(req.headers["content-length"]);
|
|
153
|
+
if (Number.isFinite(declared) && declared > limit)
|
|
154
|
+
throw tooLarge();
|
|
155
|
+
const chunks = [];
|
|
156
|
+
let size = 0;
|
|
157
|
+
for await (const chunk of req) {
|
|
158
|
+
size += chunk.length;
|
|
159
|
+
if (size > limit)
|
|
160
|
+
throw tooLarge();
|
|
161
|
+
chunks.push(chunk);
|
|
162
|
+
}
|
|
163
|
+
const text = Buffer.concat(chunks).toString("utf8").trim();
|
|
164
|
+
if (!text)
|
|
165
|
+
return {};
|
|
166
|
+
try {
|
|
167
|
+
return JSON.parse(text);
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
throw new BodyError(400, "The request body isn't valid JSON.");
|
|
171
|
+
}
|
|
172
|
+
}
|