reasonally 0.5.0 → 0.7.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.
@@ -6,8 +6,10 @@ import { createHash, randomBytes } from "node:crypto";
6
6
  import { access, appendFile, chmod, mkdir, readdir, readFile, rename, rm, stat, utimes, writeFile, } from "node:fs/promises";
7
7
  import { hostname } from "node:os";
8
8
  import { basename, join } from "node:path";
9
+ import { contentText } from "./compact.js";
9
10
  import { CONTINUE_PROMPT, HELPER_PLAN_ON_NOTE, INTERRUPTED_NOTE, PLAN_OFF_NOTE, PLAN_ON_NOTE, } from "./loop-constants.js";
10
11
  import { PLAN_TOOL } from "./tools/plan.js";
12
+ import { commandLabel } from "./command-template.js";
11
13
  /** A new session's id, which is also its file name: when it started, plus a few random characters. */
12
14
  export function newSessionId(now = new Date()) {
13
15
  const stamp = now.toISOString().replace(/[:.]/g, "-");
@@ -270,11 +272,69 @@ function planArgument(args) {
270
272
  }
271
273
  /** Notes the agent adds in front of a message, never shown as what the user wrote. */
272
274
  const LEADING_NOTES = [INTERRUPTED_NOTE, PLAN_ON_NOTE, HELPER_PLAN_ON_NOTE, PLAN_OFF_NOTE];
275
+ /**
276
+ * A message as it's saved: images become a placeholder, so session files stay small and their
277
+ * content stays text. The conversation in memory keeps them. Other messages are returned as is.
278
+ */
279
+ export function savedMessage(message) {
280
+ if (message.role !== "user" || typeof message.content === "string")
281
+ return message;
282
+ return { ...message, content: contentText(message.content) };
283
+ }
284
+ /**
285
+ * The record a host saves for a change to the conversation. Every kind of change has its own
286
+ * record (a change saved as the wrong kind would rewrite the conversation on the next load).
287
+ * Images become `[image]` (see `savedMessage`): files stay small and hold no screenshots, while the
288
+ * conversation in memory keeps them. A slash command goes beside its message, never in it: older
289
+ * versions read only `message`, so they never send it on.
290
+ */
291
+ export function changeRecord(change) {
292
+ switch (change.type) {
293
+ case "usage":
294
+ return {
295
+ type: "usage",
296
+ promptTokens: change.usage.promptTokens,
297
+ completionTokens: change.usage.completionTokens,
298
+ costMicros: change.costMicros.toString(),
299
+ };
300
+ case "append": {
301
+ const message = savedMessage(change.message);
302
+ if (message.role !== "user" || !message.command)
303
+ return { type: "append", message };
304
+ const { command, ...rest } = message;
305
+ return { type: "append", message: rest, command };
306
+ }
307
+ case "replace":
308
+ return {
309
+ type: "replace",
310
+ reason: change.reason,
311
+ messages: change.messages.map((m) => savedMessage(withoutCommand(m))),
312
+ };
313
+ default: {
314
+ const unknown = change;
315
+ throw new Error(`No session record for ${JSON.stringify(unknown)}`);
316
+ }
317
+ }
318
+ }
319
+ function withoutCommand(message) {
320
+ if (message.role !== "user" || !message.command)
321
+ return message;
322
+ const copy = { ...message };
323
+ delete copy.command;
324
+ return copy;
325
+ }
326
+ /** A saved `command`, if it has the right shape (a file edited by hand may not). */
327
+ function commandOf(value) {
328
+ const c = value;
329
+ return c && typeof c.name === "string" && c.name && typeof c.args === "string"
330
+ ? { name: c.name, args: c.args }
331
+ : null;
332
+ }
273
333
  /** Strips our own markers from a user message, for showing it. */
274
334
  export function userText(content) {
275
335
  if (content === CONTINUE_PROMPT)
276
336
  return null;
277
- let text = content;
337
+ let text = typeof content === "string" ? content : contentText(content);
278
338
  for (let found = true; found;) {
279
339
  const note = LEADING_NOTES.find((n) => text.startsWith(n));
280
340
  found = Boolean(note);
@@ -331,12 +391,14 @@ export async function loadSession(path) {
331
391
  display.push({ kind: "compacted" });
332
392
  break;
333
393
  case "append": {
334
- const m = r.message;
394
+ const command = r.message.role === "user" ? commandOf(r.command) : null;
395
+ const m = command && r.message.role === "user" ? { ...r.message, command } : r.message;
335
396
  messages.push(m);
336
397
  if (m.role === "user") {
337
- const shown = userText(m.content);
398
+ // A tool call's images, added by the agent: not something the user wrote.
399
+ const shown = m.synthetic ? null : userText(m.content);
338
400
  if (shown)
339
- display.push({ kind: "user", text: shown });
401
+ display.push({ kind: "user", text: shown, ...(command ? { command } : {}) });
340
402
  }
341
403
  else if (m.role === "assistant") {
342
404
  if (m.content)
@@ -396,13 +458,19 @@ export async function listSessions(dir) {
396
458
  id: s.meta.id,
397
459
  path: s.path,
398
460
  surface: s.meta.surface ?? "terminal",
399
- firstMessage: s.display.find((d) => d.kind === "user").text,
461
+ firstMessage: shownText(s.display.find((d) => d.kind === "user")),
400
462
  model: s.model,
401
463
  costMicros: s.costMicros,
402
464
  updatedAt: s.updatedAt,
403
465
  }))
404
466
  .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime() || b.id.localeCompare(a.id));
405
467
  }
468
+ /** How a user message reads in a list: what was typed (`/review auth` for a command). */
469
+ function shownText(entry) {
470
+ if (entry.kind !== "user")
471
+ return "";
472
+ return entry.command ? commandLabel(entry.command) : entry.text;
473
+ }
406
474
  /** "just now", "5m ago", "3h ago", "2d ago", or the date. */
407
475
  export function timeAgo(date, now = new Date()) {
408
476
  const s = Math.max(0, (now.getTime() - date.getTime()) / 1000);
package/dist/api.js CHANGED
@@ -31,15 +31,24 @@ async function call(url, init = {}) {
31
31
  return body;
32
32
  }
33
33
  const bearer = (apiKey) => ({ authorization: `Bearer ${apiKey}` });
34
- export function exchangeCode(appUrl,
35
- /** `client` names the kind of key ("desktop"); the CLI leaves it out. */
36
- body) {
34
+ export function exchangeCode(appUrl, body) {
37
35
  return call(`${appUrl}/api/cli/token`, {
38
36
  method: "POST",
39
37
  headers: { "content-type": "application/json" },
40
38
  body: JSON.stringify(body),
41
39
  });
42
40
  }
41
+ /**
42
+ * Exchanges a "Show your web chats" approval (`purpose: "web"`) for the chat window's sign-in.
43
+ * It makes no key: the app proves the approval is for it by presenting its own.
44
+ */
45
+ export function exchangeWebApproval(appUrl, apiKey, body) {
46
+ return call(`${appUrl}/api/cli/token`, {
47
+ method: "POST",
48
+ headers: { "content-type": "application/json", ...bearer(apiKey) },
49
+ body: JSON.stringify({ ...body, client: "desktop", purpose: "web" }),
50
+ });
51
+ }
43
52
  export function fetchAccount(appUrl, apiKey) {
44
53
  return call(`${appUrl}/api/cli/me`, {
45
54
  headers: bearer(apiKey),
@@ -55,6 +55,21 @@ export function isLocalHostname(hostname) {
55
55
  // A single label ("router", "nas") only resolves through local search domains.
56
56
  !host.includes("."));
57
57
  }
58
+ /**
59
+ * This computer itself, by its exact names: `localhost`, `*.localhost`, `127.0.0.1` and `[::1]`.
60
+ * Narrower than `isLocalHostname`, which also counts private networks, `.local` names and single
61
+ * labels (a router, a NAS): those aren't the app being built here.
62
+ */
63
+ export function isLoopbackHostname(hostname) {
64
+ const host = hostname.toLowerCase().replace(/\.$/, "");
65
+ if (!isLocalHostname(host))
66
+ return false;
67
+ return (host === "localhost" ||
68
+ host.endsWith(".localhost") ||
69
+ host === "127.0.0.1" ||
70
+ host === "[::1]" ||
71
+ host === "::1");
72
+ }
58
73
  const SCHEME = /^[a-z][a-z0-9+.-]*:/i;
59
74
  const HOST_PORT = /^[^/?#:@]+:\d{1,5}(?:[/?#]|$)/; // "example.com:8080/x" is a host, not a scheme
60
75
  /**
@@ -0,0 +1,61 @@
1
+ /** An error whose message is already written for the chat. */
2
+ export class UserError extends Error {
3
+ }
4
+ /** Customer-facing wording for whatever Playwright or the network threw. Never a stack trace. */
5
+ export function friendlyError(error, action) {
6
+ if (error instanceof UserError)
7
+ return error.message;
8
+ const message = String(error?.message ?? error);
9
+ const has = (pattern) => pattern.test(message);
10
+ if (has(/has been closed|Target closed|Browser closed|browser has disconnected/i)) {
11
+ return "The window was closed during the action. Try again to open a new one.";
12
+ }
13
+ if (has(/ERR_NAME_NOT_RESOLVED/))
14
+ return "Couldn't find that site. Check the address.";
15
+ if (has(/ERR_INTERNET_DISCONNECTED/))
16
+ return "This computer seems to be offline.";
17
+ if (has(/ERR_CERT_|ERR_SSL_/)) {
18
+ return "The site's security certificate isn't valid, so the page wasn't opened.";
19
+ }
20
+ if (has(/ERR_TOO_MANY_REDIRECTS/))
21
+ return "The site redirected too many times.";
22
+ if (has(/ERR_CONNECTION_|ERR_TIMED_OUT|ERR_ADDRESS_UNREACHABLE|ERR_EMPTY_RESPONSE/)) {
23
+ return "Couldn't connect to that site.";
24
+ }
25
+ if (has(/ERR_ABORTED/)) {
26
+ return "The page stopped loading (it may have started a download, which isn't supported).";
27
+ }
28
+ if (has(/Unknown key/i)) {
29
+ return "Unknown key. Use names like Enter, Tab, Escape, ArrowDown or Control+A.";
30
+ }
31
+ if (has(/not a <select> element|Element is not a <select>/i))
32
+ return "That element isn't a dropdown.";
33
+ if (has(/did not find some options/i))
34
+ return "That option isn't in the list.";
35
+ if (has(/not an <input>|not an? (input|textarea)|cannot type|Element is not editable/i)) {
36
+ return "That element can't be typed into.";
37
+ }
38
+ if (has(/Timeout \d+ms exceeded|TimeoutError/)) {
39
+ if (action === "navigate" || action === "back")
40
+ return "The page took too long to load.";
41
+ if (action === "click" || action === "type" || action === "select") {
42
+ return "That element didn't respond (it may be hidden, disabled or covered). Take a new snapshot and try again.";
43
+ }
44
+ return "The page took too long to respond.";
45
+ }
46
+ return UNKNOWN_FAILURE;
47
+ }
48
+ export const UNKNOWN_FAILURE = "The browser couldn't do that. Take a new snapshot and try again.";
49
+ /** Quoted for a message, cut to 60 characters. */
50
+ export const quote = (text) => `"${text.length > 60 ? `${text.slice(0, 57)}…` : text}"`;
51
+ const DIALOGS = {
52
+ alert: "an alert",
53
+ confirm: "a confirmation",
54
+ prompt: "a prompt",
55
+ beforeunload: "a leave-page warning",
56
+ };
57
+ export function dialogNote(type, message) {
58
+ const what = DIALOGS[type] ?? "a dialog";
59
+ const text = message.trim() ? `: ${quote(message.trim())}` : "";
60
+ return `The page showed ${what}${text} (${type === "beforeunload" ? "left the page" : "dismissed it"}).`;
61
+ }
@@ -8,7 +8,9 @@
8
8
  import { lookup } from "node:dns/promises";
9
9
  import { isIP } from "node:net";
10
10
  import { checkPressTarget, checkTypeTarget, checkUrl, isAllowedPageUrl, isNonPublicAddress, LOCAL_BLOCKED, } from "./guards.js";
11
+ import { dialogNote, friendlyError, quote, UNKNOWN_FAILURE, UserError } from "./messages.js";
11
12
  import { capSnapshot, nameForRef, STALE_REF, } from "./protocol.js";
13
+ export { dialogNote, friendlyError, UserError };
12
14
  const ACTION_TIMEOUT_MS = 10_000;
13
15
  const NAVIGATION_TIMEOUT_MS = 30_000;
14
16
  /** Lets a click start its navigation (or open its tab) before we wait for the page. */
@@ -21,9 +23,6 @@ const NO_BROWSER = "Couldn't open a browser on this computer. Ask the person to
21
23
  "(or run `npx playwright install chromium`), then try again.";
22
24
  const LOCAL_PAGE = "This window is showing an address on this computer or the local network, which the browser " +
23
25
  "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
26
  /** The page as the model sees it: Playwright's AI-mode aria snapshot, with `[ref=e12]` handles. */
28
27
  export function snapshotForAI(page) {
29
28
  return page.ariaSnapshot({ mode: "ai", timeout: ACTION_TIMEOUT_MS });
@@ -32,63 +31,6 @@ export function snapshotForAI(page) {
32
31
  export function refLocator(page, ref) {
33
32
  return page.getByRef(ref);
34
33
  }
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
34
  /**
93
35
  * The focused field of every frame (cross-origin frames included). Without window focus no frame
94
36
  * "has" focus, so each frame's active element counts.
package/dist/cli.js CHANGED
@@ -20,6 +20,7 @@ Usage:
20
20
  reasonally logout Log out and revoke this computer's key
21
21
  reasonally browser Let your Reasonally chats use a browser window on this computer
22
22
  (--port N, default 47614; --allow-local: allow local addresses)
23
+ reasonally sync [on|off] Whether your conversations show on the web (--here: this folder)
23
24
 
24
25
  Agents:
25
26
  ${HARNESSES.map((h) => ` ${h.id.padEnd(10)} ${h.name}`).join("\n")}
@@ -226,6 +227,10 @@ export async function main(argv) {
226
227
  const { browserCommand } = await import("./browser/command.js");
227
228
  return await browserCommand(args, log);
228
229
  }
230
+ case "sync": {
231
+ const { syncCommand } = await import("./sync/command.js");
232
+ return await syncCommand(args, log);
233
+ }
229
234
  }
230
235
  // Options without a command are the agent's: `reasonally --model x`, `reasonally --yes`.
231
236
  if (command.startsWith("-"))
package/dist/login.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { createServer } from "node:http";
3
3
  import { hostname } from "node:os";
4
- import { exchangeCode } from "./api.js";
4
+ import { exchangeCode, exchangeWebApproval } from "./api.js";
5
5
  import { createPkce } from "./pkce.js";
6
6
  /** How long to wait for the user to approve in the browser. */
7
7
  const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
@@ -15,6 +15,8 @@ export function authorizeUrl(appUrl, params) {
15
15
  });
16
16
  if (params.client)
17
17
  query.set("client", params.client);
18
+ if (params.client && params.purpose)
19
+ query.set("purpose", params.purpose);
18
20
  return `${appUrl}/cli/authorize?${query}`;
19
21
  }
20
22
  /** Interprets a request to the loopback server. Only `/callback` with our `state` counts. */
@@ -99,7 +101,20 @@ function waitForCallback(server, state, { signal, returnTo = "your terminal" } =
99
101
  });
100
102
  });
101
103
  }
102
- export async function browserLogin(appUrl, log, options = {}) {
104
+ export function browserLogin(appUrl, log, options = {}) {
105
+ return approveInBrowser(appUrl, log, options, (exchange) => exchangeCode(appUrl, exchange));
106
+ }
107
+ /**
108
+ * "Show your web chats": the desktop app, already signed in, asks the browser to approve showing
109
+ * the person's web chats, and gets back the one-time code that signs its chat window in (null when
110
+ * the platform doesn't show web chats in the app). No new key is made.
111
+ */
112
+ export async function browserWebHandoff(appUrl, apiKey, log, options = {}) {
113
+ const result = await approveInBrowser(appUrl, log, { ...options, client: "desktop", purpose: "web" }, (exchange) => exchangeWebApproval(appUrl, apiKey, exchange));
114
+ return result.web_handoff ?? null;
115
+ }
116
+ /** Opens the approval page, waits for the code on a one-shot loopback server, and exchanges it. */
117
+ async function approveInBrowser(appUrl, log, options, exchange) {
103
118
  const { open = true } = options;
104
119
  const pkce = createPkce();
105
120
  const server = createServer();
@@ -116,6 +131,7 @@ export async function browserLogin(appUrl, log, options = {}) {
116
131
  state: pkce.state,
117
132
  device: options.device ?? hostname().replace(/\.local$/, ""),
118
133
  client: options.client,
134
+ purpose: options.purpose,
119
135
  });
120
136
  options.onUrl?.(url);
121
137
  if (open) {
@@ -127,11 +143,11 @@ export async function browserLogin(appUrl, log, options = {}) {
127
143
  log(`Open this link in the browser where you're signed in, on this computer:\n\n ${url}\n`);
128
144
  }
129
145
  const code = await waitForCallback(server, pkce.state, options);
130
- return await exchangeCode(appUrl, {
146
+ return await exchange({
131
147
  code,
132
148
  code_verifier: pkce.verifier,
133
149
  redirect_uri: redirectUri,
134
- client: options.client,
150
+ ...(options.client ? { client: options.client } : {}),
135
151
  });
136
152
  }
137
153
  finally {