reasonally 0.1.0 → 0.3.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.
Files changed (42) hide show
  1. package/README.md +143 -5
  2. package/dist/agent/accumulate.js +146 -0
  3. package/dist/agent/client.js +174 -0
  4. package/dist/agent/compact.js +79 -0
  5. package/dist/agent/cost.js +22 -0
  6. package/dist/agent/loop-constants.js +3 -0
  7. package/dist/agent/loop.js +559 -0
  8. package/dist/agent/mcp-config.js +72 -0
  9. package/dist/agent/mcp.js +194 -0
  10. package/dist/agent/permissions.js +116 -0
  11. package/dist/agent/prompt.js +98 -0
  12. package/dist/agent/session.js +196 -0
  13. package/dist/agent/sse.js +46 -0
  14. package/dist/agent/tools/bash.js +176 -0
  15. package/dist/agent/tools/diff.js +33 -0
  16. package/dist/agent/tools/files.js +270 -0
  17. package/dist/agent/tools/index.js +21 -0
  18. package/dist/agent/tools/paths.js +43 -0
  19. package/dist/agent/tools/search.js +288 -0
  20. package/dist/agent/tools/task.js +42 -0
  21. package/dist/agent/tools/todo.js +59 -0
  22. package/dist/agent/tools/types.js +57 -0
  23. package/dist/agent/types.js +2 -0
  24. package/dist/api.js +5 -1
  25. package/dist/browser/command.js +93 -0
  26. package/dist/browser/guards.js +138 -0
  27. package/dist/browser/pairing.js +123 -0
  28. package/dist/browser/protocol.js +172 -0
  29. package/dist/browser/server.js +157 -0
  30. package/dist/browser/sessions.js +478 -0
  31. package/dist/catalog.js +12 -0
  32. package/dist/cli.js +43 -3
  33. package/dist/config.js +17 -4
  34. package/dist/tui/app.js +869 -0
  35. package/dist/tui/args.js +32 -0
  36. package/dist/tui/commands.js +38 -0
  37. package/dist/tui/components.js +375 -0
  38. package/dist/tui/format.js +116 -0
  39. package/dist/tui/node-version.js +7 -0
  40. package/dist/tui/start.js +135 -0
  41. package/dist/tui/theme.js +36 -0
  42. package/package.json +11 -3
@@ -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
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * The companion's HTTP server (protocol v1). Only the Reasonally app's origin, on 127.0.0.1, with a
3
+ * paired token may drive a browser; see `protocol.ts` for the shapes.
4
+ */
5
+ import { createServer } from "node:http";
6
+ import { bearerToken } from "./pairing.js";
7
+ import { BodyError, isChatId, parseAction, PROTOCOL_VERSION, readJsonBody, } from "./protocol.js";
8
+ const ALLOWED_METHODS = "GET, POST, DELETE, OPTIONS";
9
+ /** Runs tasks for the same key one after another; different keys run in parallel. */
10
+ export function createQueue() {
11
+ const tails = new Map();
12
+ return function enqueue(key, task) {
13
+ const previous = tails.get(key) ?? Promise.resolve();
14
+ const run = previous.then(task, task);
15
+ const tail = run.catch(() => { });
16
+ tails.set(key, tail);
17
+ void tail.then(() => {
18
+ if (tails.get(key) === tail)
19
+ tails.delete(key);
20
+ });
21
+ return run;
22
+ };
23
+ }
24
+ /** `Host` must name this server on loopback: anything else is DNS rebinding or a stray request. */
25
+ export function isAllowedHost(host, port) {
26
+ const value = host?.toLowerCase();
27
+ return value === `127.0.0.1:${port}` || value === `localhost:${port}`;
28
+ }
29
+ export function createCompanionServer(options) {
30
+ const { origin, version, pairing, sessions, log = () => { } } = options;
31
+ const enqueue = createQueue();
32
+ const server = createServer((req, res) => {
33
+ handle(req, res).catch((error) => {
34
+ log(`Unexpected error: ${error?.stack ?? error}`);
35
+ if (!res.headersSent)
36
+ send(res, 500, { ok: false, error: "The browser companion hit an error." });
37
+ else
38
+ res.end();
39
+ });
40
+ });
41
+ function send(res, status, body, headers = {}) {
42
+ res.writeHead(status, {
43
+ "content-type": "application/json; charset=utf-8",
44
+ "cache-control": "no-store",
45
+ ...headers,
46
+ });
47
+ res.end(JSON.stringify(body));
48
+ }
49
+ const fail = (res, status, error, headers) => send(res, status, { ok: false, error }, headers);
50
+ async function handle(req, res) {
51
+ const { port } = server.address();
52
+ if (!isAllowedHost(req.headers.host, port))
53
+ return fail(res, 403, "Forbidden host.");
54
+ if (req.headers.origin !== origin)
55
+ return fail(res, 403, "Forbidden origin.");
56
+ const cors = { "access-control-allow-origin": origin, vary: "Origin" };
57
+ if (req.method === "OPTIONS") {
58
+ res.writeHead(204, {
59
+ ...cors,
60
+ "access-control-allow-methods": ALLOWED_METHODS,
61
+ "access-control-allow-headers": "authorization, content-type",
62
+ "access-control-allow-private-network": "true",
63
+ "access-control-max-age": "600",
64
+ vary: "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
65
+ });
66
+ return res.end();
67
+ }
68
+ const reply = (status, body) => send(res, status, body, cors);
69
+ const replyError = (status, error) => fail(res, status, error, cors);
70
+ const methodNotAllowed = (allow) => fail(res, 405, "Method not allowed.", { ...cors, allow });
71
+ const path = new URL(req.url ?? "/", "http://127.0.0.1").pathname;
72
+ const token = bearerToken(req.headers.authorization);
73
+ if (path === "/v1/status") {
74
+ if (req.method !== "GET")
75
+ return methodNotAllowed("GET");
76
+ const paired = await pairing.verify(token, origin);
77
+ const status = {
78
+ app: "reasonally-browser",
79
+ protocol: PROTOCOL_VERSION,
80
+ version,
81
+ paired,
82
+ sessions: paired ? sessions.list() : [],
83
+ };
84
+ return reply(200, status);
85
+ }
86
+ if (path === "/v1/pair") {
87
+ if (req.method !== "POST")
88
+ return methodNotAllowed("POST");
89
+ const gone = new AbortController();
90
+ res.on("close", () => {
91
+ if (!res.writableFinished)
92
+ gone.abort();
93
+ });
94
+ const outcome = await pairing.request(origin, gone.signal);
95
+ switch (outcome.kind) {
96
+ case "approved":
97
+ log(`Paired with ${origin}.`);
98
+ return reply(200, { token: outcome.token });
99
+ case "busy":
100
+ return replyError(409, "Another pairing request is waiting for an answer in the terminal.");
101
+ case "timeout":
102
+ return replyError(403, "Nobody answered in the terminal within 60 seconds.");
103
+ default:
104
+ return replyError(403, "The request was declined in the terminal.");
105
+ }
106
+ }
107
+ const match = path.match(/^\/v1\/sessions\/([^/]+)(\/actions)?$/);
108
+ if (!match)
109
+ return replyError(404, "Not found.");
110
+ const chatId = safeDecode(match[1]);
111
+ if (!chatId || !isChatId(chatId))
112
+ return replyError(400, "Invalid chat id.");
113
+ if (!(await pairing.verify(token, origin))) {
114
+ return replyError(401, "This chat isn't paired with the browser companion. Pair again.");
115
+ }
116
+ if (match[2]) {
117
+ if (req.method !== "POST")
118
+ return methodNotAllowed("POST");
119
+ let body;
120
+ try {
121
+ body = await readJsonBody(req);
122
+ }
123
+ catch (error) {
124
+ if (error instanceof BodyError) {
125
+ return fail(res, error.status, error.message, { ...cors, connection: "close" });
126
+ }
127
+ throw error;
128
+ }
129
+ const parsed = parseAction(body);
130
+ if (!parsed.ok) {
131
+ // A stale ref is an ordinary action failure the model should see and recover from.
132
+ return parsed.staleRef
133
+ ? reply(200, { ok: false, error: parsed.error })
134
+ : replyError(400, parsed.error);
135
+ }
136
+ const result = await enqueue(chatId, () => sessions.run(chatId, parsed.action));
137
+ log(`[${chatId.slice(0, 8)}] ${result.ok ? result.summary : `${parsed.action.action}: ${result.error}`}`);
138
+ return reply(200, result);
139
+ }
140
+ if (req.method === "GET")
141
+ return reply(200, await sessions.info(chatId));
142
+ if (req.method === "DELETE") {
143
+ await sessions.close(chatId);
144
+ return reply(200, { ok: true });
145
+ }
146
+ return methodNotAllowed("GET, DELETE");
147
+ }
148
+ return server;
149
+ }
150
+ function safeDecode(segment) {
151
+ try {
152
+ return decodeURIComponent(segment);
153
+ }
154
+ catch {
155
+ return null;
156
+ }
157
+ }