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,288 @@
1
+ import { spawn } from "node:child_process";
2
+ import { opendir, readFile, stat } from "node:fs/promises";
3
+ import { basename, join, relative, sep } from "node:path";
4
+ import { count } from "./files.js";
5
+ import { displayPath, resolvePath } from "./paths.js";
6
+ import { optionalBool, optionalInt, optionalString, stringArg, ToolInputError, truncateMiddle, } from "./types.js";
7
+ const MAX_MATCH_LINES = 250;
8
+ const MAX_FILES = 500;
9
+ const MAX_OUTPUT_CHARS = 30_000;
10
+ /** Folders the built-in search skips (ripgrep, when installed, follows .gitignore instead). */
11
+ const SKIP_DIRS = new Set([".git", "node_modules", ".next", ".turbo", ".venv", "__pycache__"]);
12
+ const MAX_SCANNED_FILES = 50_000;
13
+ const MAX_SEARCHED_BYTES = 1024 * 1024;
14
+ /** A glob as a RegExp: `*`, `**`, `?`, `{a,b}` and `[abc]`. */
15
+ export function globToRegExp(glob) {
16
+ let re = "";
17
+ let braces = 0;
18
+ for (let i = 0; i < glob.length; i++) {
19
+ const c = glob[i];
20
+ if (c === "*") {
21
+ if (glob[i + 1] === "*") {
22
+ i++;
23
+ if (glob[i + 1] === "/") {
24
+ i++;
25
+ re += "(?:.*/)?";
26
+ }
27
+ else
28
+ re += ".*";
29
+ }
30
+ else
31
+ re += "[^/]*";
32
+ }
33
+ else if (c === "?")
34
+ re += "[^/]";
35
+ else if (c === "{") {
36
+ braces++;
37
+ re += "(?:";
38
+ }
39
+ else if (c === "}" && braces > 0) {
40
+ braces--;
41
+ re += ")";
42
+ }
43
+ else if (c === "," && braces > 0)
44
+ re += "|";
45
+ else if (c === "[") {
46
+ const end = glob.indexOf("]", i + 1);
47
+ if (end === -1)
48
+ re += "\\[";
49
+ else {
50
+ const body = glob
51
+ .slice(i + 1, end)
52
+ .replace(/^!/, "^")
53
+ .replace(/\\/g, "\\\\");
54
+ re += `[${body}]`;
55
+ i = end;
56
+ }
57
+ }
58
+ else
59
+ re += c.replace(/[.+^$()|\\/]/g, "\\$&");
60
+ }
61
+ return new RegExp(`^${re}$`);
62
+ }
63
+ /** Whether `rel` (a project-relative path with "/") matches: globs without "/" match file names. */
64
+ export function matchesGlob(rel, glob, re = globToRegExp(glob)) {
65
+ return re.test(glob.includes("/") ? rel : basename(rel));
66
+ }
67
+ async function* walk(root) {
68
+ const stack = [root];
69
+ let seen = 0;
70
+ while (stack.length) {
71
+ const dir = stack.pop();
72
+ let handle;
73
+ try {
74
+ handle = await opendir(dir);
75
+ }
76
+ catch {
77
+ continue;
78
+ }
79
+ for await (const entry of handle) {
80
+ const path = join(dir, entry.name);
81
+ if (entry.isDirectory()) {
82
+ if (!SKIP_DIRS.has(entry.name))
83
+ stack.push(path);
84
+ }
85
+ else if (entry.isFile()) {
86
+ if (++seen > MAX_SCANNED_FILES)
87
+ return;
88
+ yield path;
89
+ }
90
+ }
91
+ }
92
+ }
93
+ let ripgrep;
94
+ /** Whether `rg` is on PATH (checked once). */
95
+ export function hasRipgrep() {
96
+ ripgrep ??= new Promise((resolve) => {
97
+ const child = spawn("rg", ["--version"], { stdio: "ignore" });
98
+ child.on("error", () => resolve(false));
99
+ child.on("exit", (code) => resolve(code === 0));
100
+ });
101
+ return ripgrep;
102
+ }
103
+ /** Tests: force the built-in search (false), ripgrep (true), or detect again (undefined). */
104
+ export function setRipgrepForTests(available) {
105
+ ripgrep = available === undefined ? undefined : Promise.resolve(available);
106
+ }
107
+ /** Runs a program (no shell), collecting at most ~1 MB of stdout. */
108
+ function runProgram(file, args, cwd, signal) {
109
+ return new Promise((resolve, reject) => {
110
+ const child = spawn(file, args, { cwd, stdio: ["ignore", "pipe", "pipe"], signal });
111
+ let stdout = "";
112
+ let stderr = "";
113
+ child.stdout.on("data", (c) => {
114
+ if (stdout.length < 1_000_000)
115
+ stdout += c.toString("utf8");
116
+ else
117
+ child.kill();
118
+ });
119
+ child.stderr.on("data", (c) => (stderr += c.toString("utf8")));
120
+ child.on("error", reject);
121
+ child.on("close", (code) => resolve({ code, stdout, stderr }));
122
+ });
123
+ }
124
+ const capLines = (lines, max, what) => lines.length > max
125
+ ? `${lines.slice(0, max).join("\n")}\n[… ${lines.length - max} more ${what} not shown. Narrow the search.]`
126
+ : lines.join("\n");
127
+ const toSlash = (p) => p.split(sep).join("/");
128
+ export const grepTool = {
129
+ name: "grep",
130
+ description: "Search file contents with a regular expression (ripgrep syntax). Returns `path:line:text` " +
131
+ "matches, or only file names with files_only. Respects .gitignore when ripgrep is installed.",
132
+ parameters: {
133
+ type: "object",
134
+ properties: {
135
+ pattern: { type: "string", description: "Regular expression to search for." },
136
+ path: { type: "string", description: "Folder or file to search (default: the project)." },
137
+ glob: { type: "string", description: 'Only search files matching this glob, e.g. "*.ts".' },
138
+ ignore_case: { type: "boolean", description: "Case-insensitive search." },
139
+ files_only: { type: "boolean", description: "List matching files instead of lines." },
140
+ context: { type: "integer", description: "Lines of context around each match (0-10)." },
141
+ },
142
+ required: ["pattern"],
143
+ additionalProperties: false,
144
+ },
145
+ async prepare(args, ctx) {
146
+ const pattern = stringArg(args, "pattern");
147
+ const target = await resolvePath(optionalString(args, "path") ?? ".", ctx.cwd, ctx.home);
148
+ const glob = optionalString(args, "glob");
149
+ const ignoreCase = optionalBool(args, "ignore_case");
150
+ const filesOnly = optionalBool(args, "files_only");
151
+ const context = optionalInt(args, "context", 0, 10) ?? 0;
152
+ const shown = displayPath(target, ctx.cwd, ctx.home);
153
+ const where = shown === "." ? "" : ` in ${shown}`;
154
+ return {
155
+ kind: "read",
156
+ paths: [target],
157
+ title: `Search "${pattern}"${where}`,
158
+ async run() {
159
+ let lines;
160
+ if (await hasRipgrep()) {
161
+ const rgArgs = ["--line-number", "--no-heading", "--color=never", "--no-require-git"];
162
+ rgArgs.push("--max-columns=400");
163
+ rgArgs.push("--max-columns-preview");
164
+ if (ignoreCase)
165
+ rgArgs.push("-i");
166
+ if (glob)
167
+ rgArgs.push("-g", glob);
168
+ if (filesOnly)
169
+ rgArgs.push("-l");
170
+ else if (context)
171
+ rgArgs.push("-C", String(context));
172
+ rgArgs.push("-e", pattern, "--", relative(ctx.cwd, target) || ".");
173
+ const result = await runProgram("rg", rgArgs, ctx.cwd, ctx.signal);
174
+ if (result.code === 2 && !result.stdout) {
175
+ return {
176
+ output: result.stderr.trim() || "The search failed.",
177
+ summary: `Search "${pattern}" failed`,
178
+ isError: true,
179
+ };
180
+ }
181
+ lines = result.stdout.split("\n").filter(Boolean);
182
+ }
183
+ else {
184
+ let re;
185
+ try {
186
+ re = new RegExp(pattern, ignoreCase ? "i" : "");
187
+ }
188
+ catch (error) {
189
+ throw new ToolInputError(`Invalid regular expression: ${error.message}`);
190
+ }
191
+ const globRe = glob ? globToRegExp(glob) : null;
192
+ lines = [];
193
+ const info = await stat(target).catch(() => null);
194
+ const files = info?.isFile() ? [target] : walk(target);
195
+ for await (const file of files) {
196
+ if (ctx.signal.aborted)
197
+ break;
198
+ const rel = toSlash(relative(ctx.cwd, file));
199
+ if (globRe && !matchesGlob(rel, glob, globRe))
200
+ continue;
201
+ const text = await readFile(file, "utf8").catch(() => null);
202
+ if (text === null || text.length > MAX_SEARCHED_BYTES || text.includes("\0"))
203
+ continue;
204
+ const fileLines = text.split(/\r?\n/);
205
+ let hit = false;
206
+ for (let i = 0; i < fileLines.length; i++) {
207
+ if (!re.test(fileLines[i]))
208
+ continue;
209
+ hit = true;
210
+ if (filesOnly)
211
+ break;
212
+ lines.push(`${rel}:${i + 1}:${fileLines[i].slice(0, 400)}`);
213
+ }
214
+ if (hit && filesOnly)
215
+ lines.push(rel);
216
+ if (lines.length > MAX_MATCH_LINES * 2)
217
+ break;
218
+ }
219
+ }
220
+ if (lines.length === 0) {
221
+ return { output: "No matches.", summary: `Searched "${pattern}"${where} · no matches` };
222
+ }
223
+ const files = filesOnly ? lines.length : new Set(lines.map((l) => l.split(":")[0])).size;
224
+ const found = filesOnly
225
+ ? count(files, "file")
226
+ : `${count(lines.length, "match", "matches")} in ${count(files, "file")}`;
227
+ return {
228
+ output: truncateMiddle(capLines(lines, MAX_MATCH_LINES, "lines"), MAX_OUTPUT_CHARS),
229
+ summary: `Searched "${pattern}"${where} · ${found}`,
230
+ };
231
+ },
232
+ };
233
+ },
234
+ };
235
+ export const findTool = {
236
+ name: "find",
237
+ description: 'Find files by name with a glob, e.g. "*.test.ts" (any folder) or "src/**/page.tsx". ' +
238
+ "Returns project-relative paths.",
239
+ parameters: {
240
+ type: "object",
241
+ properties: {
242
+ pattern: { type: "string", description: "Glob to match." },
243
+ path: { type: "string", description: "Folder to search (default: the project)." },
244
+ },
245
+ required: ["pattern"],
246
+ additionalProperties: false,
247
+ },
248
+ async prepare(args, ctx) {
249
+ const pattern = stringArg(args, "pattern");
250
+ const target = await resolvePath(optionalString(args, "path") ?? ".", ctx.cwd, ctx.home);
251
+ const shown = displayPath(target, ctx.cwd, ctx.home);
252
+ const where = shown === "." ? "" : ` in ${shown}`;
253
+ return {
254
+ kind: "read",
255
+ paths: [target],
256
+ title: `Find ${pattern}${where}`,
257
+ async run() {
258
+ let found;
259
+ if (await hasRipgrep()) {
260
+ const rel = relative(ctx.cwd, target) || ".";
261
+ const result = await runProgram("rg", ["--files", "--no-require-git", "--sort", "path", "-g", pattern, "--", rel], ctx.cwd, ctx.signal);
262
+ found = result.stdout.split("\n").filter(Boolean);
263
+ }
264
+ else {
265
+ const re = globToRegExp(pattern);
266
+ found = [];
267
+ for await (const file of walk(target)) {
268
+ if (ctx.signal.aborted)
269
+ break;
270
+ const rel = toSlash(relative(target, file));
271
+ if (matchesGlob(rel, pattern, re))
272
+ found.push(toSlash(relative(ctx.cwd, file)));
273
+ if (found.length > MAX_FILES * 2)
274
+ break;
275
+ }
276
+ found.sort();
277
+ }
278
+ if (found.length === 0) {
279
+ return { output: "No files found.", summary: `Found no ${pattern}${where}` };
280
+ }
281
+ return {
282
+ output: capLines(found, MAX_FILES, "files"),
283
+ summary: `Found ${found.length} ${found.length === 1 ? "file" : "files"} matching ${pattern}${where}`,
284
+ };
285
+ },
286
+ };
287
+ },
288
+ };
@@ -0,0 +1,42 @@
1
+ import { stringArg, ToolInputError } from "./types.js";
2
+ /** Helpers that may run at once, from one reply's `task` calls. */
3
+ export const MAX_PARALLEL_HELPERS = 4;
4
+ export const HELPER_NOTE = `# You are a helper
5
+ Another agent handed you the task below and will act on your report; the user sees only a one-line
6
+ status for you. Work on your own: you can't ask the user questions. You can read and search freely;
7
+ edits and commands need the user's approval, so only make changes the task asks for.
8
+ Finish with a concise report: what you found (with path:line references), anything you changed,
9
+ and anything you couldn't do. Don't paste whole files.`;
10
+ export const taskTool = {
11
+ name: "task",
12
+ description: "Hand a self-contained piece of work to a helper agent that starts with fresh context and " +
13
+ "reports back. Good for searching or investigating across many files, or for independent " +
14
+ "parts of a larger change, without filling this conversation. Several task calls in one " +
15
+ "reply run at the same time (up to 4). The helper can't see this conversation: put " +
16
+ "everything it needs in the prompt. It reads freely; its edits and commands ask the user.",
17
+ parameters: {
18
+ type: "object",
19
+ properties: {
20
+ description: {
21
+ type: "string",
22
+ description: "A short label for the user, 3-6 words (e.g. 'Find the auth middleware').",
23
+ },
24
+ prompt: { type: "string", description: "The complete task, with all context it needs." },
25
+ },
26
+ required: ["description", "prompt"],
27
+ additionalProperties: false,
28
+ },
29
+ async prepare(args, ctx) {
30
+ const description = stringArg(args, "description").replace(/\s+/g, " ").slice(0, 60);
31
+ const prompt = stringArg(args, "prompt");
32
+ const helpers = ctx.helpers;
33
+ if (!helpers)
34
+ throw new ToolInputError("Helpers can't start helpers of their own.");
35
+ return {
36
+ kind: "meta",
37
+ paths: [],
38
+ title: `Helper: ${description}`,
39
+ run: () => helpers.run({ description, prompt }, ctx.signal, ctx.progress ?? (() => { })),
40
+ };
41
+ },
42
+ };
@@ -0,0 +1,59 @@
1
+ import { ToolInputError } from "./types.js";
2
+ const STATUSES = new Set(["pending", "in_progress", "completed"]);
3
+ /** "[x] done", "[>] doing", "[ ] to do", one per line. */
4
+ export function formatTodos(todos) {
5
+ const mark = { completed: "[x]", in_progress: "[>]", pending: "[ ]" };
6
+ return todos.map((t) => `${mark[t.status]} ${t.content}`).join("\n");
7
+ }
8
+ export const todoTool = {
9
+ name: "todo",
10
+ description: "Keep a short checklist for multi-step work, shown to the user. Send the whole list each time " +
11
+ "(it replaces the previous one). Keep exactly one item in_progress while working, and mark " +
12
+ "items completed as soon as they're done. Skip it for simple one-step tasks.",
13
+ parameters: {
14
+ type: "object",
15
+ properties: {
16
+ todos: {
17
+ type: "array",
18
+ items: {
19
+ type: "object",
20
+ properties: {
21
+ content: { type: "string" },
22
+ status: { type: "string", enum: ["pending", "in_progress", "completed"] },
23
+ },
24
+ required: ["content", "status"],
25
+ additionalProperties: false,
26
+ },
27
+ },
28
+ },
29
+ required: ["todos"],
30
+ additionalProperties: false,
31
+ },
32
+ async prepare(args, ctx) {
33
+ if (!Array.isArray(args.todos))
34
+ throw new ToolInputError("`todos` must be a list.");
35
+ const todos = args.todos.map((raw, i) => {
36
+ const item = raw;
37
+ if (!item ||
38
+ typeof item.content !== "string" ||
39
+ !item.content.trim() ||
40
+ !STATUSES.has(item.status)) {
41
+ throw new ToolInputError(`Item ${i + 1} needs a non-empty content and a status of pending, in_progress or completed.`);
42
+ }
43
+ return { content: item.content.trim(), status: item.status };
44
+ });
45
+ return {
46
+ kind: "meta",
47
+ paths: [],
48
+ title: "Update todos",
49
+ async run() {
50
+ ctx.todos.splice(0, ctx.todos.length, ...todos);
51
+ const done = todos.filter((t) => t.status === "completed").length;
52
+ return {
53
+ output: todos.length ? `Todo list updated:\n${formatTodos(todos)}` : "Todo list cleared.",
54
+ summary: todos.length ? `Updated todos (${done}/${todos.length} done)` : "Cleared todos",
55
+ };
56
+ },
57
+ };
58
+ },
59
+ };
@@ -0,0 +1,57 @@
1
+ /** When each file was last read or written by the agent, to catch edits to stale content. */
2
+ export class FileTracker {
3
+ seen = new Map();
4
+ record(path, mtimeMs) {
5
+ this.seen.set(path, mtimeMs);
6
+ }
7
+ /** "unread": never read · "changed": modified since · "ok". */
8
+ check(path, mtimeMs) {
9
+ const known = this.seen.get(path);
10
+ if (known === undefined)
11
+ return "unread";
12
+ return known === mtimeMs ? "ok" : "changed";
13
+ }
14
+ }
15
+ /** Bad arguments or an impossible request: reported to the model, never shown as an approval. */
16
+ export class ToolInputError extends Error {
17
+ }
18
+ export function stringArg(args, name) {
19
+ const value = args[name];
20
+ if (typeof value !== "string" || value === "") {
21
+ throw new ToolInputError(`\`${name}\` is required and must be a non-empty string.`);
22
+ }
23
+ return value;
24
+ }
25
+ export function optionalString(args, name) {
26
+ const value = args[name];
27
+ if (value === undefined || value === null || value === "")
28
+ return undefined;
29
+ if (typeof value !== "string")
30
+ throw new ToolInputError(`\`${name}\` must be a string.`);
31
+ return value;
32
+ }
33
+ export function optionalInt(args, name, min, max) {
34
+ const value = args[name];
35
+ if (value === undefined || value === null)
36
+ return undefined;
37
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
38
+ throw new ToolInputError(`\`${name}\` must be a whole number from ${min} to ${max}.`);
39
+ }
40
+ return value;
41
+ }
42
+ export function optionalBool(args, name) {
43
+ const value = args[name];
44
+ if (value === undefined || value === null)
45
+ return false;
46
+ if (typeof value !== "boolean")
47
+ throw new ToolInputError(`\`${name}\` must be true or false.`);
48
+ return value;
49
+ }
50
+ /** Keeps the start and end of long output, which is where the useful parts usually are. */
51
+ export function truncateMiddle(text, max) {
52
+ if (text.length <= max)
53
+ return text;
54
+ const half = Math.floor((max - 60) / 2);
55
+ const cut = text.length - half * 2;
56
+ return `${text.slice(0, half)}\n\n[… ${cut.toLocaleString("en-US")} characters cut …]\n\n${text.slice(-half)}`;
57
+ }
@@ -0,0 +1,2 @@
1
+ /** Chat messages in the OpenAI format, as the agent keeps them. */
2
+ export {};
package/dist/api.js CHANGED
@@ -3,10 +3,14 @@ import { parseCatalog } from "./catalog.js";
3
3
  export class ApiError extends Error {
4
4
  status;
5
5
  code;
6
- constructor(message, status, code) {
6
+ retryAfterMs;
7
+ constructor(message, status, code,
8
+ /** From a `Retry-After` header, when the server sent one. */
9
+ retryAfterMs = null) {
7
10
  super(message);
8
11
  this.status = status;
9
12
  this.code = code;
13
+ this.retryAfterMs = retryAfterMs;
10
14
  }
11
15
  }
12
16
  async function call(url, init = {}) {
@@ -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
+ }