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,478 @@
1
+ /**
2
+ * One visible browser window per chat, driven with Playwright. Each chat gets a fresh,
3
+ * non-persistent context, so logins last until its window closes.
4
+ *
5
+ * `playwright-core` is only `import type`d here and loaded with `import()` on first use, so the
6
+ * rest of the CLI never pays for it.
7
+ */
8
+ import { lookup } from "node:dns/promises";
9
+ import { isIP } from "node:net";
10
+ import { checkPressTarget, checkTypeTarget, checkUrl, isAllowedPageUrl, isNonPublicAddress, LOCAL_BLOCKED, } from "./guards.js";
11
+ import { capSnapshot, nameForRef, STALE_REF, } from "./protocol.js";
12
+ const ACTION_TIMEOUT_MS = 10_000;
13
+ const NAVIGATION_TIMEOUT_MS = 30_000;
14
+ /** Lets a click start its navigation (or open its tab) before we wait for the page. */
15
+ const SETTLE_MS = 500;
16
+ export const IDLE_CLOSE_MS = 30 * 60 * 1000;
17
+ export const WINDOW_REOPENED = "The window was closed; opened a new one — you may need to log in again";
18
+ const IDLE_REOPENED = "The window was closed after 30 minutes without activity; opened a new one — you may need to log in again";
19
+ export const NO_BROWSER_LINE = "Couldn't start a browser: install Google Chrome, or run `npx playwright install chromium`.";
20
+ const NO_BROWSER = "Couldn't open a browser on this computer. Ask the person to install Google Chrome " +
21
+ "(or run `npx playwright install chromium`), then try again.";
22
+ const LOCAL_PAGE = "This window is showing an address on this computer or the local network, which the browser " +
23
+ "companion doesn't read or control. Navigate somewhere else or go back.";
24
+ /** An error whose message is already written for the chat. */
25
+ export class UserError extends Error {
26
+ }
27
+ /** The page as the model sees it: Playwright's AI-mode aria snapshot, with `[ref=e12]` handles. */
28
+ export function snapshotForAI(page) {
29
+ return page.ariaSnapshot({ mode: "ai", timeout: ACTION_TIMEOUT_MS });
30
+ }
31
+ /** The element behind a ref from the latest snapshot of its frame (`aria-ref=e12`). */
32
+ export function refLocator(page, ref) {
33
+ return page.getByRef(ref);
34
+ }
35
+ /** Customer-facing wording for whatever Playwright or the network threw. Never a stack trace. */
36
+ export function friendlyError(error, action) {
37
+ if (error instanceof UserError)
38
+ return error.message;
39
+ const message = String(error?.message ?? error);
40
+ const has = (pattern) => pattern.test(message);
41
+ if (has(/has been closed|Target closed|Browser closed|browser has disconnected/i)) {
42
+ return "The window was closed during the action. Try again to open a new one.";
43
+ }
44
+ if (has(/ERR_NAME_NOT_RESOLVED/))
45
+ return "Couldn't find that site. Check the address.";
46
+ if (has(/ERR_INTERNET_DISCONNECTED/))
47
+ return "This computer seems to be offline.";
48
+ if (has(/ERR_CERT_|ERR_SSL_/)) {
49
+ return "The site's security certificate isn't valid, so the page wasn't opened.";
50
+ }
51
+ if (has(/ERR_TOO_MANY_REDIRECTS/))
52
+ return "The site redirected too many times.";
53
+ if (has(/ERR_CONNECTION_|ERR_TIMED_OUT|ERR_ADDRESS_UNREACHABLE|ERR_EMPTY_RESPONSE/)) {
54
+ return "Couldn't connect to that site.";
55
+ }
56
+ if (has(/ERR_ABORTED/)) {
57
+ return "The page stopped loading (it may have started a download, which isn't supported).";
58
+ }
59
+ if (has(/Unknown key/i)) {
60
+ return "Unknown key. Use names like Enter, Tab, Escape, ArrowDown or Control+A.";
61
+ }
62
+ if (has(/not a <select> element|Element is not a <select>/i))
63
+ return "That element isn't a dropdown.";
64
+ if (has(/did not find some options/i))
65
+ return "That option isn't in the list.";
66
+ if (has(/not an <input>|not an? (input|textarea)|cannot type|Element is not editable/i)) {
67
+ return "That element can't be typed into.";
68
+ }
69
+ if (has(/Timeout \d+ms exceeded|TimeoutError/)) {
70
+ if (action === "navigate" || action === "back")
71
+ return "The page took too long to load.";
72
+ if (action === "click" || action === "type" || action === "select") {
73
+ return "That element didn't respond (it may be hidden, disabled or covered). Take a new snapshot and try again.";
74
+ }
75
+ return "The page took too long to respond.";
76
+ }
77
+ return UNKNOWN_FAILURE;
78
+ }
79
+ const UNKNOWN_FAILURE = "The browser couldn't do that. Take a new snapshot and try again.";
80
+ const quote = (text) => `"${text.length > 60 ? `${text.slice(0, 57)}…` : text}"`;
81
+ const DIALOGS = {
82
+ alert: "an alert",
83
+ confirm: "a confirmation",
84
+ prompt: "a prompt",
85
+ beforeunload: "a leave-page warning",
86
+ };
87
+ export function dialogNote(type, message) {
88
+ const what = DIALOGS[type] ?? "a dialog";
89
+ const text = message.trim() ? `: ${quote(message.trim())}` : "";
90
+ return `The page showed ${what}${text} (${type === "beforeunload" ? "left the page" : "dismissed it"}).`;
91
+ }
92
+ /**
93
+ * The focused field of every frame (cross-origin frames included). Without window focus no frame
94
+ * "has" focus, so each frame's active element counts.
95
+ */
96
+ async function focusedFields(page) {
97
+ const fields = await Promise.all(page.frames().map((frame) => frame
98
+ .evaluate(() => {
99
+ const doc = globalThis
100
+ .document;
101
+ const el = doc.activeElement;
102
+ if (!el || ["BODY", "HTML", "IFRAME", "FRAME"].includes(el.tagName))
103
+ return null;
104
+ return {
105
+ tagName: el.tagName,
106
+ type: el.getAttribute("type"),
107
+ autocomplete: el.getAttribute("autocomplete"),
108
+ };
109
+ })
110
+ .catch(() => null)));
111
+ return fields.filter((f) => f !== null);
112
+ }
113
+ /** Whether a public-looking hostname resolves to this computer or the local network. */
114
+ async function resolvesLocally(hostname) {
115
+ if (isIP(hostname.replace(/^\[|\]$/g, "")))
116
+ return false; // checked by checkUrl already
117
+ const timeout = new Promise((resolve) => setTimeout(resolve, 3000, null).unref());
118
+ const addresses = await Promise.race([
119
+ lookup(hostname, { all: true }).catch(() => null),
120
+ timeout,
121
+ ]);
122
+ return addresses?.some((a) => isNonPublicAddress(a.address)) ?? false;
123
+ }
124
+ async function launchBrowser(log) {
125
+ const { chromium } = await import("playwright-core");
126
+ // The person's Chrome, then Edge, then a Chromium from `npx playwright install chromium`.
127
+ for (const channel of ["chrome", "msedge", undefined]) {
128
+ try {
129
+ return await chromium.launch({
130
+ channel,
131
+ headless: false,
132
+ // We close windows ourselves on Ctrl+C; Playwright's handlers would exit mid-way.
133
+ handleSIGINT: false,
134
+ handleSIGTERM: false,
135
+ handleSIGHUP: false,
136
+ });
137
+ }
138
+ catch {
139
+ // try the next one
140
+ }
141
+ }
142
+ log(NO_BROWSER_LINE);
143
+ throw new UserError(NO_BROWSER);
144
+ }
145
+ export function createPlaywrightSessions({ allowLocal, log, }) {
146
+ const sessions = new Map();
147
+ /** Why a chat's last window went away, told to the chat when its next one opens. */
148
+ const reopenNotes = new Map();
149
+ let browser = null;
150
+ let opening = 0;
151
+ function getBrowser() {
152
+ if (browser)
153
+ return browser;
154
+ const launching = launchBrowser(log);
155
+ browser = launching;
156
+ launching.then((b) => b.on("disconnected", () => {
157
+ if (browser === launching)
158
+ browser = null;
159
+ // Only this browser's windows: a newer one may already be running other chats.
160
+ for (const [chatId, session] of [...sessions]) {
161
+ if (session.context.browser() === b)
162
+ void forget(chatId, WINDOW_REOPENED);
163
+ }
164
+ }), () => {
165
+ if (browser === launching)
166
+ browser = null;
167
+ });
168
+ return launching;
169
+ }
170
+ /** Drops a chat's window and context (cookies, logins) and quits the browser once none are left. */
171
+ function forget(chatId, note) {
172
+ const session = sessions.get(chatId);
173
+ if (!session)
174
+ return;
175
+ session.closing = true;
176
+ clearTimeout(session.idleTimer);
177
+ sessions.delete(chatId);
178
+ if (note)
179
+ reopenNotes.set(chatId, note);
180
+ const closed = session.context.close().catch(() => { });
181
+ if (sessions.size === 0 && opening === 0 && browser) {
182
+ const current = browser;
183
+ browser = null;
184
+ void closed.then(() => current.then((b) => b.close()).catch(() => { }));
185
+ }
186
+ return closed;
187
+ }
188
+ function touch(chatId, session) {
189
+ clearTimeout(session.idleTimer);
190
+ session.idleTimer = setTimeout(() => {
191
+ log(`[${chatId.slice(0, 8)}] Closed the window after 30 minutes without activity.`);
192
+ void forget(chatId, IDLE_REOPENED);
193
+ }, IDLE_CLOSE_MS);
194
+ }
195
+ function watchPage(chatId, session, page) {
196
+ page.on("dialog", (dialog) => {
197
+ session.notes.push(dialogNote(dialog.type(), dialog.message()));
198
+ const answer = dialog.type() === "beforeunload" ? dialog.accept() : dialog.dismiss();
199
+ answer.catch(() => { });
200
+ });
201
+ page.on("close", () => {
202
+ if (session.closing)
203
+ return;
204
+ const open = session.context.pages().filter((p) => !p.isClosed());
205
+ if (open.length > 0) {
206
+ if (session.page === page)
207
+ session.page = open[open.length - 1];
208
+ return;
209
+ }
210
+ // The person closed the chat's window: its logins go with it.
211
+ void forget(chatId, WINDOW_REOPENED);
212
+ });
213
+ }
214
+ async function open(chatId) {
215
+ const existing = sessions.get(chatId);
216
+ if (existing)
217
+ return existing;
218
+ opening++;
219
+ try {
220
+ const context = await (await getBrowser()).newContext({ viewport: null });
221
+ const session = {
222
+ context,
223
+ page: undefined,
224
+ snapshot: "",
225
+ notes: [],
226
+ closing: false,
227
+ };
228
+ const note = reopenNotes.get(chatId);
229
+ if (note) {
230
+ session.notes.push(note);
231
+ reopenNotes.delete(chatId);
232
+ }
233
+ const watched = new WeakSet();
234
+ context.on("page", (page) => {
235
+ if (watched.has(page))
236
+ return;
237
+ watched.add(page);
238
+ watchPage(chatId, session, page);
239
+ // A tab the page opened (or the person opened) becomes the one we work in.
240
+ if (session.page)
241
+ session.notes.push("That opened a new tab; continuing there.");
242
+ session.page = page;
243
+ });
244
+ context.on("close", () => {
245
+ if (!session.closing && sessions.get(chatId) === session)
246
+ void forget(chatId, WINDOW_REOPENED);
247
+ });
248
+ const page = await context.newPage();
249
+ if (!watched.has(page)) {
250
+ watched.add(page);
251
+ watchPage(chatId, session, page);
252
+ }
253
+ session.page = page;
254
+ sessions.set(chatId, session);
255
+ return session;
256
+ }
257
+ finally {
258
+ opening--;
259
+ }
260
+ }
261
+ async function target(page, ref) {
262
+ const locator = refLocator(page, ref);
263
+ if ((await locator.count().catch(() => 0)) === 0)
264
+ throw new UserError(STALE_REF);
265
+ return locator;
266
+ }
267
+ /** Runs one action and returns its one-line summary. */
268
+ async function perform(session, action) {
269
+ const page = session.page;
270
+ const name = (ref) => nameForRef(session.snapshot, ref);
271
+ switch (action.action) {
272
+ case "navigate": {
273
+ const check = checkUrl(action.args.url, { allowLocal });
274
+ if (!check.ok)
275
+ throw new UserError(check.error);
276
+ if (!allowLocal && (await resolvesLocally(new URL(check.url).hostname))) {
277
+ throw new UserError(LOCAL_BLOCKED);
278
+ }
279
+ const response = await page.goto(check.url, {
280
+ waitUntil: "domcontentloaded",
281
+ timeout: NAVIGATION_TIMEOUT_MS,
282
+ });
283
+ if (response && response.status() >= 400) {
284
+ session.notes.push(`The site answered with HTTP ${response.status()}.`);
285
+ }
286
+ return `Opened ${check.url}`;
287
+ }
288
+ case "snapshot":
289
+ return "Read the page";
290
+ case "click": {
291
+ await (await target(page, action.args.ref)).click({ timeout: ACTION_TIMEOUT_MS });
292
+ return `Clicked ${name(action.args.ref)}`;
293
+ }
294
+ case "type": {
295
+ const field = await target(page, action.args.ref);
296
+ // Runs in the page: the attributes the typing guard needs, following a <label> to its control.
297
+ const info = await field.evaluate((node) => {
298
+ const element = node;
299
+ const el = element.tagName === "LABEL" && element.control ? element.control : element;
300
+ return {
301
+ tagName: el.tagName,
302
+ type: el.getAttribute("type"),
303
+ autocomplete: el.getAttribute("autocomplete"),
304
+ };
305
+ });
306
+ const refusal = checkTypeTarget(info);
307
+ if (refusal)
308
+ throw new UserError(refusal);
309
+ await field.fill(action.args.text, { timeout: ACTION_TIMEOUT_MS });
310
+ if (action.args.submit)
311
+ await field.press("Enter", { timeout: ACTION_TIMEOUT_MS });
312
+ return `Typed into ${name(action.args.ref)}${action.args.submit ? " and pressed Enter" : ""}`;
313
+ }
314
+ case "select": {
315
+ const field = await target(page, action.args.ref);
316
+ // Name a missing option right away (with the real ones) instead of timing out on it.
317
+ const options = await field.evaluate((node) => {
318
+ const el = node;
319
+ return el.tagName === "SELECT" && el.options
320
+ ? Array.from(el.options, (o) => ({ value: o.value, label: o.label.trim() }))
321
+ : null;
322
+ });
323
+ const missing = options
324
+ ? action.args.values.filter((v) => !options.some((o) => o.value === v || o.label === v.trim()))
325
+ : [];
326
+ if (options && missing.length) {
327
+ const list = options.slice(0, 30).map((o) => quote(o.label || o.value));
328
+ throw new UserError(`${missing.map(quote).join(", ")} isn't in the list. The options are: ${list.join(", ")}` +
329
+ (options.length > 30 ? ", …" : "."));
330
+ }
331
+ await field.selectOption(action.args.values, { timeout: ACTION_TIMEOUT_MS });
332
+ return `Selected ${action.args.values.map(quote).join(", ")} in ${name(action.args.ref)}`;
333
+ }
334
+ case "press": {
335
+ for (const field of await focusedFields(page)) {
336
+ const refusal = checkPressTarget(action.args.key, field);
337
+ if (refusal)
338
+ throw new UserError(refusal);
339
+ }
340
+ await page.keyboard.press(action.args.key);
341
+ return `Pressed ${action.args.key}`;
342
+ }
343
+ case "scroll": {
344
+ const { width, height } = await page.evaluate(() => ({
345
+ width: globalThis.innerWidth,
346
+ height: globalThis.innerHeight,
347
+ }));
348
+ // Wheel over the middle of the window, so pages that scroll an inner panel scroll too.
349
+ await page.mouse.move(width / 2, height / 2);
350
+ const distance = Math.round(height * 0.8);
351
+ await page.mouse.wheel(0, action.args.direction === "down" ? distance : -distance);
352
+ return `Scrolled ${action.args.direction}`;
353
+ }
354
+ case "back": {
355
+ const before = page.url();
356
+ const response = await page.goBack({
357
+ waitUntil: "domcontentloaded",
358
+ timeout: NAVIGATION_TIMEOUT_MS,
359
+ });
360
+ if (!response && page.url() === before) {
361
+ throw new UserError("There's no previous page in this window.");
362
+ }
363
+ return "Went back";
364
+ }
365
+ case "wait": {
366
+ const { text, seconds } = action.args;
367
+ if (text !== undefined) {
368
+ const limit = seconds ?? 10;
369
+ try {
370
+ await page
371
+ .getByText(text)
372
+ .first()
373
+ .waitFor({ state: "visible", timeout: limit * 1000 });
374
+ }
375
+ catch (error) {
376
+ if (/Timeout \d+ms exceeded/.test(String(error?.message))) {
377
+ throw new UserError(`${quote(text)} didn't appear within ${limit} seconds.`);
378
+ }
379
+ throw error;
380
+ }
381
+ return `Waited for ${quote(text)}`;
382
+ }
383
+ await page.waitForTimeout((seconds ?? 1) * 1000);
384
+ return `Waited ${seconds} second${seconds === 1 ? "" : "s"}`;
385
+ }
386
+ case "focus":
387
+ await page.bringToFront();
388
+ return "Brought the window to the front";
389
+ }
390
+ }
391
+ async function snapshotOf(page) {
392
+ try {
393
+ return await snapshotForAI(page);
394
+ }
395
+ catch (error) {
396
+ if (page.isClosed())
397
+ throw error;
398
+ // Usually the page navigated mid-snapshot; take it again once it has loaded.
399
+ await page
400
+ .waitForLoadState("domcontentloaded", { timeout: ACTION_TIMEOUT_MS })
401
+ .catch(() => { });
402
+ return await snapshotForAI(page);
403
+ }
404
+ }
405
+ const isLocalPage = (page) => !isAllowedPageUrl(page.url(), { allowLocal });
406
+ return {
407
+ async run(chatId, action) {
408
+ let session;
409
+ try {
410
+ session = await open(chatId);
411
+ }
412
+ catch (error) {
413
+ if (!(error instanceof UserError))
414
+ log(`Couldn't open a window: ${error?.message}`);
415
+ return { ok: false, error: friendlyError(error, action.action) };
416
+ }
417
+ touch(chatId, session);
418
+ try {
419
+ const leavesPage = action.action === "navigate" || action.action === "back" || action.action === "focus";
420
+ if (!leavesPage && isLocalPage(session.page))
421
+ throw new UserError(LOCAL_PAGE);
422
+ const summary = await perform(session, action);
423
+ if (action.action !== "snapshot" && action.action !== "focus" && action.action !== "wait") {
424
+ await new Promise((resolve) => setTimeout(resolve, SETTLE_MS));
425
+ await session.page
426
+ .waitForLoadState("domcontentloaded", { timeout: ACTION_TIMEOUT_MS })
427
+ .catch(() => { });
428
+ }
429
+ const page = session.page;
430
+ if (isLocalPage(page)) {
431
+ throw new UserError("That led to an address on this computer or the local network, which the browser " +
432
+ "companion doesn't read or control. Navigate somewhere else or go back.");
433
+ }
434
+ const snapshot = capSnapshot(await snapshotOf(page));
435
+ session.snapshot = snapshot;
436
+ const title = await page.title().catch(() => "");
437
+ const notes = session.notes.splice(0);
438
+ const result = { ok: true, url: page.url(), title, summary, snapshot };
439
+ if (notes.length)
440
+ result.notes = notes;
441
+ return result;
442
+ }
443
+ catch (error) {
444
+ const worded = friendlyError(error, action.action);
445
+ // The server logs the worded error; the raw one only helps when we had no wording for it.
446
+ if (worded === UNKNOWN_FAILURE) {
447
+ log(`[${chatId.slice(0, 8)}] ${error?.message?.split("\n")[0]}`);
448
+ }
449
+ return { ok: false, error: worded };
450
+ }
451
+ finally {
452
+ if (sessions.get(chatId) === session)
453
+ touch(chatId, session);
454
+ }
455
+ },
456
+ async info(chatId) {
457
+ const session = sessions.get(chatId);
458
+ if (!session || session.page.isClosed())
459
+ return { open: false };
460
+ const title = await Promise.race([
461
+ session.page.title().catch(() => undefined),
462
+ new Promise((resolve) => setTimeout(resolve, 2000, undefined).unref()),
463
+ ]);
464
+ return { open: true, url: session.page.url(), ...(title !== undefined ? { title } : {}) };
465
+ },
466
+ async close(chatId) {
467
+ reopenNotes.delete(chatId);
468
+ await forget(chatId);
469
+ },
470
+ list: () => [...sessions.keys()],
471
+ async closeAll() {
472
+ const current = browser;
473
+ browser = null;
474
+ await Promise.all([...sessions.keys()].map((chatId) => forget(chatId)));
475
+ await current?.then((b) => b.close()).catch(() => { });
476
+ },
477
+ };
478
+ }
package/dist/catalog.js CHANGED
@@ -1,3 +1,12 @@
1
+ /** "3.9" → 3_900_000n. Prices have at most six decimals; anything else counts as free (0). */
2
+ export function decimalToMicros(value) {
3
+ if (typeof value !== "string")
4
+ return 0n;
5
+ const match = /^(\d+)(?:\.(\d{1,6}))?$/.exec(value.trim());
6
+ if (!match)
7
+ return 0n;
8
+ return BigInt(match[1]) * 1000000n + BigInt((match[2] ?? "").padEnd(6, "0"));
9
+ }
1
10
  /** Used when the catalog doesn't publish a limit. */
2
11
  export const FALLBACK_CONTEXT = 128_000;
3
12
  const FALLBACK_OUTPUT = 16_384;
@@ -29,6 +38,9 @@ export function parseCatalog(payload) {
29
38
  tools: params.length === 0 || params.includes("tools"),
30
39
  inputPerM: price(pricing.input_per_million),
31
40
  outputPerM: price(pricing.output_per_million),
41
+ inputMicrosPerM: decimalToMicros(pricing.input_per_million),
42
+ outputMicrosPerM: decimalToMicros(pricing.output_per_million),
43
+ categories: strings(m.categories),
32
44
  });
33
45
  }
34
46
  return models;
package/dist/cli.js CHANGED
@@ -5,15 +5,21 @@ import { appUrlFrom, deleteCredentials, harnessDir, readCredentials, readLastMod
5
5
  import { findHarness, HARNESSES } from "./harnesses/index.js";
6
6
  import { launch } from "./launch.js";
7
7
  import { browserLogin } from "./login.js";
8
+ import { isInteractive, parseAgentArgs } from "./tui/args.js";
9
+ import { NODE_TOO_OLD, nodeSupported } from "./tui/node-version.js";
8
10
  const log = (line) => console.error(line);
9
11
  const HELP = `Run the coding agents you already use on Reasonally models.
10
12
 
11
13
  Usage:
14
+ reasonally Start Reasonally's coding agent in this folder
15
+ (--model <id>, --yes, --continue, --resume)
12
16
  reasonally login Log in through your browser (--no-browser: print the link)
13
17
  reasonally <agent> [--model <id>] [agent args…]
14
18
  reasonally models [search] List models you can use
15
19
  reasonally whoami Show the account and balance
16
20
  reasonally logout Log out and revoke this computer's key
21
+ reasonally browser Let your Reasonally chats use a browser window on this computer
22
+ (--port N, default 47614; --allow-local: allow local addresses)
17
23
 
18
24
  Agents:
19
25
  ${HARNESSES.map((h) => ` ${h.id.padEnd(10)} ${h.name}`).join("\n")}
@@ -50,10 +56,11 @@ async function requireSession() {
50
56
  }
51
57
  class UsageError extends Error {
52
58
  }
53
- async function login(args) {
59
+ /** Logs in through the browser and saves the new key, retiring the previous login's key. */
60
+ export async function loginAndSave(report, { open = true } = {}) {
54
61
  const previous = await readCredentials();
55
62
  const appUrl = appUrlFrom(process.env, previous);
56
- const token = await browserLogin(appUrl, log, { open: !args.includes("--no-browser") });
63
+ const token = await browserLogin(appUrl, report, { open });
57
64
  await writeCredentials({
58
65
  appUrl,
59
66
  apiBaseUrl: token.api_base_url,
@@ -65,13 +72,35 @@ async function login(args) {
65
72
  if (previous && previous.apiKey !== token.api_key) {
66
73
  await revokeKey(previous.appUrl, previous.apiKey).catch(() => { });
67
74
  }
75
+ return token;
76
+ }
77
+ async function login(args) {
78
+ const token = await loginAndSave(log, { open: !args.includes("--no-browser") });
68
79
  log(`Logged in as ${token.email}.`);
69
80
  if (process.env.REASONALLY_API_KEY) {
70
81
  log("Note: REASONALLY_API_KEY is set in your environment and takes precedence over this login.");
71
82
  }
72
- log(`Start an agent, e.g. \`reasonally ${HARNESSES[0].id}\`.`);
83
+ log(`Run \`reasonally\` to start coding, or launch an agent, e.g. \`reasonally ${HARNESSES[0].id}\`.`);
73
84
  return 0;
74
85
  }
86
+ /** Bare `reasonally` (and `reasonally --model …`): the agent, in an interactive terminal only. */
87
+ async function startAgent(argv) {
88
+ if (!isInteractive(process.stdin, process.stdout)) {
89
+ log("The agent needs an interactive terminal. See `reasonally --help` for other commands.");
90
+ return 1;
91
+ }
92
+ const parsed = parseAgentArgs(argv);
93
+ if (!parsed.ok) {
94
+ log(parsed.error);
95
+ return 1;
96
+ }
97
+ if (!nodeSupported(process.version)) {
98
+ log(NODE_TOO_OLD(process.version));
99
+ return 1;
100
+ }
101
+ const { startTui } = await import("./tui/start.js");
102
+ return await startTui(parsed.args, log);
103
+ }
75
104
  async function logout() {
76
105
  const creds = await readCredentials();
77
106
  if (!creds) {
@@ -172,6 +201,10 @@ export async function main(argv) {
172
201
  try {
173
202
  switch (command) {
174
203
  case undefined:
204
+ if (isInteractive(process.stdin, process.stdout))
205
+ return await startAgent([]);
206
+ console.log(HELP);
207
+ return 0;
175
208
  case "help":
176
209
  case "--help":
177
210
  case "-h":
@@ -189,7 +222,14 @@ export async function main(argv) {
189
222
  return await whoami();
190
223
  case "models":
191
224
  return await models(args);
225
+ case "browser": {
226
+ const { browserCommand } = await import("./browser/command.js");
227
+ return await browserCommand(args, log);
228
+ }
192
229
  }
230
+ // Options without a command are the agent's: `reasonally --model x`, `reasonally --yes`.
231
+ if (command.startsWith("-"))
232
+ return await startAgent(argv);
193
233
  const harness = findHarness(command);
194
234
  if (!harness) {
195
235
  log(`Unknown command "${command}".\n\n${HELP}`);
package/dist/config.js CHANGED
@@ -1,4 +1,5 @@
1
- import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
1
+ import { randomBytes } from "node:crypto";
2
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
3
  import { homedir } from "node:os";
3
4
  import { dirname, join } from "node:path";
4
5
  export const DEFAULT_APP_URL = "https://app.reasonally.ai";
@@ -25,11 +26,23 @@ export async function readCredentials(env = process.env) {
25
26
  return null;
26
27
  }
27
28
  }
28
- /** Writes a file only its owner can read: it holds an API key (or a config naming one). */
29
+ /**
30
+ * Writes a file only its owner can read: it holds an API key (or a config naming one). Written to
31
+ * a temporary file and renamed into place, so a reader (the agent and a launched agent can run at
32
+ * once) never sees half a file.
33
+ */
29
34
  export async function writePrivateFile(path, content) {
30
35
  await mkdir(dirname(path), { recursive: true, mode: 0o700 });
31
- await writeFile(path, content, { mode: 0o600 });
32
- await chmod(path, 0o600); // `mode` only applies when the file is created
36
+ const temp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
37
+ try {
38
+ await writeFile(temp, content, { mode: 0o600 });
39
+ await chmod(temp, 0o600); // `mode` is filtered by the umask
40
+ await rename(temp, path);
41
+ }
42
+ catch (error) {
43
+ await rm(temp, { force: true });
44
+ throw error;
45
+ }
33
46
  }
34
47
  export async function writeCredentials(creds, env = process.env) {
35
48
  await writePrivateFile(credentialsPath(env), `${JSON.stringify(creds, null, 2)}\n`);