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.
@@ -0,0 +1,105 @@
1
+ /**
2
+ * `reasonally sync`: whether this computer's conversations show on the web, and turning that on
3
+ * or off, for everything or for this folder. Turning it off also takes them off the web (they stay
4
+ * on this computer); if the server can't be reached, that happens the next time it can.
5
+ */
6
+ import { realpath } from "node:fs/promises";
7
+ import { createRequire } from "node:module";
8
+ import { basename } from "node:path";
9
+ import { fetchAccount } from "../api.js";
10
+ import { configDir, readCredentials, resolveSession } from "../config.js";
11
+ import { sessionsDir, timeAgo } from "../agent/session.js";
12
+ import { SyncClient } from "./client.js";
13
+ import { folderIsOn, lastUpload, readSyncSettings, serverDir, updateSyncSettings, } from "./store.js";
14
+ const USAGE = `Usage:
15
+ reasonally sync Show whether this computer's conversations show on the web
16
+ reasonally sync on Show them on the web (summaries: messages, replies, one-line steps)
17
+ reasonally sync off Stop, and take this computer's conversations off the web
18
+ reasonally sync on|off --here Only for this folder`;
19
+ /** This folder's key: the path hash its conversations are saved under. */
20
+ export const folderKeyOf = (config, cwd) => basename(sessionsDir(config, cwd)).slice(-10);
21
+ export async function syncCommand(args, log) {
22
+ const [action = "status", ...flags] = args;
23
+ const here = flags.includes("--here");
24
+ const unknown = flags.filter((f) => f !== "--here");
25
+ if (unknown.length ||
26
+ !["status", "on", "off"].includes(action) ||
27
+ (here && action === "status")) {
28
+ log(USAGE);
29
+ return 1;
30
+ }
31
+ const config = configDir();
32
+ const cwd = await realpath(process.cwd());
33
+ const folderKey = folderKeyOf(config, cwd);
34
+ const session = resolveSession(process.env, await readCredentials());
35
+ const credentials = session && !session.fromEnv ? { appUrl: session.appUrl, apiKey: session.apiKey } : null;
36
+ if (action === "status")
37
+ return status(config, folderKey, session, credentials);
38
+ const on = action === "on";
39
+ const settings = await updateSyncSettings(config, (s) => {
40
+ if (here) {
41
+ s.offFolders = s.offFolders.filter((f) => f !== folderKey);
42
+ if (!on)
43
+ s.offFolders.push(folderKey);
44
+ }
45
+ else {
46
+ s.enabled = on;
47
+ }
48
+ });
49
+ if (on) {
50
+ if (here && !settings.enabled) {
51
+ log("This folder is back on, but syncing is off on this computer. Turn it on with `reasonally sync on`.");
52
+ }
53
+ else {
54
+ log(here
55
+ ? "This folder's conversations show on the web again."
56
+ : "Syncing is on. Your conversations show on the web as summaries: messages, replies and one-line steps.");
57
+ }
58
+ return 0;
59
+ }
60
+ const scope = here ? { kind: "folder", folderKey } : { kind: "device" };
61
+ const client = new SyncClient({
62
+ configDir: config,
63
+ credentials: () => credentials,
64
+ client: "cli",
65
+ surface: "terminal",
66
+ appVersion: createRequire(import.meta.url)("../../package.json").version,
67
+ });
68
+ const taken = await client.forget(scope);
69
+ const what = here ? "This folder's conversations" : "This computer's conversations";
70
+ const off = `Syncing is off${here ? " for this folder" : ""}.`;
71
+ log(!credentials
72
+ ? `${off} Anything it uploaded comes off the web the next time you're logged in.`
73
+ : taken
74
+ ? `${off} ${what} are off the web; they stay here.`
75
+ : `${off} ${what} will be taken off the web the next time Reasonally can reach it; they stay here.`);
76
+ return 0;
77
+ }
78
+ async function status(config, folderKey, session, credentials) {
79
+ const settings = await readSyncSettings(config);
80
+ console.log(`Syncing: ${settings.enabled ? "on" : "off"} · this folder: ${folderIsOn(settings, folderKey) ? "on" : "off"}`);
81
+ if (!session) {
82
+ console.log("Not logged in: run `reasonally login` to sync.");
83
+ return 0;
84
+ }
85
+ if (!credentials) {
86
+ console.log("Using the key in REASONALLY_API_KEY: only `reasonally login` syncs.");
87
+ return 0;
88
+ }
89
+ let features = null;
90
+ try {
91
+ const account = (await fetchAccount(session.appUrl, session.apiKey));
92
+ features = account.features ?? null;
93
+ }
94
+ catch {
95
+ console.log("Couldn't reach Reasonally to check the server.");
96
+ }
97
+ if (features) {
98
+ console.log(features.computerSync
99
+ ? "Your account: on (conversations show on the web)"
100
+ : "Your account: not available yet");
101
+ }
102
+ const last = await lastUpload(serverDir(config, credentials.appUrl));
103
+ console.log(`Last upload: ${last ? timeAgo(last) : "never"}`);
104
+ return 0;
105
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Turns a conversation file's lines into what the web shows: the same entries the transcript
3
+ * shows when a conversation is reloaded (see `loadSession`), but only the summaries. Each entry
4
+ * takes its line's position in the file, so it stays the same whatever a later version maps.
5
+ *
6
+ * What becomes an entry:
7
+ * - a message the person sent: its text as shown (our own notes stripped, a slash command as
8
+ * typed), images only as a count;
9
+ * - the agent's reply text;
10
+ * - a step's one-line title and summary (cleaned of secrets), or a plan and its outcome;
11
+ * - a compaction, as a marker.
12
+ * What never does: tool results, tool call arguments, reasoning, the system prompt.
13
+ *
14
+ * Pure, so it's unit-tested.
15
+ */
16
+ import { basename, dirname } from "node:path";
17
+ import { commandLabel } from "../agent/command-template.js";
18
+ import { PLAN_TOOL } from "../agent/tools/plan.js";
19
+ import { userText } from "../agent/session.js";
20
+ import { clip, MAX_ENTRY_CHARS, MAX_POSITIONS } from "./protocol.js";
21
+ import { cleanStepText } from "./redact.js";
22
+ /** Where a conversation file sits: its folder's key (the path hash) and its id. */
23
+ export function sessionLocation(sessionPath) {
24
+ const folder = basename(dirname(sessionPath));
25
+ const match = /-([0-9a-f]{10})$/.exec(folder);
26
+ const sessionId = basename(sessionPath, ".jsonl");
27
+ if (!match || !/^[A-Za-z0-9._-]{1,120}$/.test(sessionId))
28
+ return null;
29
+ return { folderKey: match[1], sessionId };
30
+ }
31
+ const IMAGE_LINE = "[image]";
32
+ /** A message the person sent, as the web shows it; null for one they didn't write. */
33
+ function userEntry(record, seq) {
34
+ const message = record.message;
35
+ if (message.role !== "user" || message.synthetic)
36
+ return null;
37
+ const command = commandOf(record.command);
38
+ const shown = userText(message.content);
39
+ if (shown === null)
40
+ return null;
41
+ // Saved images are `[image]` lines (see `savedMessage`): keep only how many there were.
42
+ const lines = shown.split("\n");
43
+ const images = lines.filter((l) => l.trim() === IMAGE_LINE).length;
44
+ const text = command
45
+ ? commandLabel(command)
46
+ : lines
47
+ .filter((l) => l.trim() !== IMAGE_LINE)
48
+ .join("\n")
49
+ .trim();
50
+ if (!text && !images)
51
+ return null;
52
+ return {
53
+ seq,
54
+ kind: "user",
55
+ text: clip(text, MAX_ENTRY_CHARS),
56
+ ...(images ? { images } : {}),
57
+ };
58
+ }
59
+ function commandOf(value) {
60
+ const c = value;
61
+ return c && typeof c.name === "string" && c.name && typeof c.args === "string"
62
+ ? { name: c.name, args: c.args }
63
+ : null;
64
+ }
65
+ /** The entry for one saved record at position `seq`, or null when the web shows nothing for it. */
66
+ export function entryFor(record, seq) {
67
+ if (seq >= MAX_POSITIONS)
68
+ return null;
69
+ switch (record.type) {
70
+ case "append": {
71
+ if (record.message.role === "user")
72
+ return userEntry(record, seq);
73
+ if (record.message.role === "assistant" && record.message.content?.trim()) {
74
+ return { seq, kind: "text", text: clip(record.message.content, MAX_ENTRY_CHARS) };
75
+ }
76
+ return null;
77
+ }
78
+ case "step": {
79
+ if (record.plan) {
80
+ return {
81
+ seq,
82
+ kind: "plan",
83
+ text: clip(record.plan.text, MAX_ENTRY_CHARS),
84
+ edited: record.plan.edited,
85
+ outcome: record.plan.outcome,
86
+ feedback: record.plan.feedback ? clip(record.plan.feedback, 4_000) : null,
87
+ };
88
+ }
89
+ return {
90
+ seq,
91
+ kind: "step",
92
+ title: cleanStepText(record.title),
93
+ summary: cleanStepText(record.summary),
94
+ isError: record.isError,
95
+ };
96
+ }
97
+ case "replace":
98
+ // A merge (two queued messages made one) changes nothing that was shown.
99
+ return record.reason === "compact" ? { seq, kind: "compacted" } : null;
100
+ default:
101
+ return null;
102
+ }
103
+ }
104
+ /** Notes what a record says about the conversation as a whole (where, which model, the cost). */
105
+ export function noteRecord(cursor, record) {
106
+ switch (record.type) {
107
+ case "meta":
108
+ cursor.cwd = record.cwd;
109
+ cursor.startedAt = record.createdAt;
110
+ cursor.surface = record.surface ?? "terminal";
111
+ if (!cursor.model)
112
+ cursor.model = record.model;
113
+ break;
114
+ case "model":
115
+ cursor.model = record.id;
116
+ break;
117
+ case "usage":
118
+ try {
119
+ cursor.costMicros = (BigInt(cursor.costMicros) + BigInt(record.costMicros)).toString();
120
+ }
121
+ catch {
122
+ // a hand-edited file: leave the cost as it was
123
+ }
124
+ break;
125
+ case "append":
126
+ if (cursor.firstMessage === null && record.message.role === "user") {
127
+ const entry = userEntry(record, 0);
128
+ if (entry?.kind === "user" && entry.text)
129
+ cursor.firstMessage = entry.text;
130
+ }
131
+ break;
132
+ default:
133
+ break;
134
+ }
135
+ }
136
+ /** The title a conversation shows until it's given one: its first message, on one line. */
137
+ export const titleFrom = (firstMessage) => clip(firstMessage.replace(/\s+/g, " ").trim(), 80);
138
+ /** A plan presented with `present_plan` is a step like any other until it's answered. */
139
+ export const isPlanTool = (name) => name === PLAN_TOOL;
@@ -0,0 +1,107 @@
1
+ import { PLAN_TOOL } from "../agent/tools/plan.js";
2
+ import { clip, MAX_ENTRY_CHARS, } from "./protocol.js";
3
+ import { cleanStepText } from "./redact.js";
4
+ export class LiveTracker {
5
+ now;
6
+ status = "idle";
7
+ text = "";
8
+ step = null;
9
+ plan = null;
10
+ approval = null;
11
+ queued = 0;
12
+ /** Steps running at once (helpers), newest last. */
13
+ running = new Map();
14
+ constructor(now = Date.now) {
15
+ this.now = now;
16
+ }
17
+ get active() {
18
+ return this.status === "running" || this.status === "waiting";
19
+ }
20
+ turnStarted() {
21
+ this.status = "running";
22
+ this.text = "";
23
+ this.step = null;
24
+ this.plan = null;
25
+ this.approval = null;
26
+ this.running.clear();
27
+ return "now";
28
+ }
29
+ /** A new model call: its reply starts afresh, as in the transcript. */
30
+ modelStarted() {
31
+ this.text = "";
32
+ return "soon";
33
+ }
34
+ textDelta(delta) {
35
+ this.text = clip(this.text + delta, MAX_ENTRY_CHARS);
36
+ return "soon";
37
+ }
38
+ stepStarted(id, title) {
39
+ this.running.set(id, cleanStepText(title));
40
+ this.step = [...this.running.values()].at(-1) ?? null;
41
+ return "now";
42
+ }
43
+ stepDone(id) {
44
+ this.running.delete(id);
45
+ this.step = [...this.running.values()].at(-1) ?? null;
46
+ return "now";
47
+ }
48
+ planDraft(text) {
49
+ this.plan = clip(text, MAX_ENTRY_CHARS);
50
+ return "soon";
51
+ }
52
+ planDropped() {
53
+ this.plan = null;
54
+ return "now";
55
+ }
56
+ approvalAsked(id, request) {
57
+ const plan = request.tool === PLAN_TOOL;
58
+ this.status = "waiting";
59
+ this.approval = {
60
+ id,
61
+ kind: plan ? "plan" : request.kind,
62
+ title: cleanStepText(request.title),
63
+ preview: request.preview ? clip(request.preview, 20_000) : null,
64
+ host: request.host ?? null,
65
+ act: request.act ?? null,
66
+ };
67
+ return "now";
68
+ }
69
+ approvalAnswered() {
70
+ this.approval = null;
71
+ if (this.status === "waiting")
72
+ this.status = "running";
73
+ return "now";
74
+ }
75
+ setQueued(count) {
76
+ this.queued = Math.max(0, Math.min(100, count));
77
+ return "now";
78
+ }
79
+ /** The turn ended: nothing is happening any more. `failed` keeps the problem on the thread. */
80
+ turnEnded(failed) {
81
+ this.status = failed ? "failed" : "idle";
82
+ this.text = "";
83
+ this.step = null;
84
+ this.plan = null;
85
+ this.approval = null;
86
+ this.running.clear();
87
+ return "now";
88
+ }
89
+ /** The status the thread has now, for its details. */
90
+ get threadStatus() {
91
+ return this.status;
92
+ }
93
+ /** The state to send; null once nothing is happening. */
94
+ snapshot() {
95
+ if (!this.active)
96
+ return null;
97
+ return {
98
+ sentAt: this.now(),
99
+ status: this.status,
100
+ text: this.text || null,
101
+ step: this.step,
102
+ plan: this.plan,
103
+ approval: this.approval,
104
+ queued: this.queued,
105
+ };
106
+ }
107
+ }
@@ -0,0 +1,14 @@
1
+ export const SYNC_PROTOCOL = 1;
2
+ /** Longest message, reply or plan uploaded (characters); the server keeps the same. */
3
+ export const MAX_ENTRY_CHARS = 32_000;
4
+ /** Longest step line uploaded (characters). */
5
+ export const MAX_STEP_CHARS = 200;
6
+ export const MAX_TITLE_CHARS = 200;
7
+ /** Most entries in one upload. */
8
+ export const MAX_ENTRIES_PER_BATCH = 200;
9
+ /** Largest upload body we build (bytes); the server refuses over 1 MB. */
10
+ export const MAX_BATCH_BYTES = 800_000;
11
+ /** Positions (file lines) the server keeps per thread. */
12
+ export const MAX_POSITIONS = 20_000;
13
+ export const NO_MARKS = { pinned: false, archived: false, unread: false };
14
+ export const clip = (text, max) => text.length > max ? `${text.slice(0, max - 1)}…` : text;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Cleans a step's one-line summary before it leaves the computer: a command run with a token in
3
+ * it, or a page address with a key in its query. The server cleans steps the same way again
4
+ * (`cleanStepText` in the app's `src/lib/computer-threads.ts`); a contract test keeps the two in
5
+ * step.
6
+ */
7
+ import { clip, MAX_STEP_CHARS } from "./protocol.js";
8
+ const MASK = "••••";
9
+ const SECRET_PATTERNS = [
10
+ [/\bsk-[A-Za-z0-9_-]{16,}/g, MASK],
11
+ [/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g, MASK],
12
+ [/\bgithub_pat_[A-Za-z0-9_]{20,}/g, MASK],
13
+ [/\bAKIA[0-9A-Z]{16}\b/g, MASK],
14
+ [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, MASK],
15
+ [/\bAIza[0-9A-Za-z_-]{35}\b/g, MASK],
16
+ [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, MASK],
17
+ [/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, `$1 ${MASK}`],
18
+ [
19
+ /(--?(?:password|passwd|token|secret|api[_-]?key|access[_-]?key)(?:=|\s+))("[^"]*"|'[^']*'|[^\s"']+)/gi,
20
+ `$1${MASK}`,
21
+ ],
22
+ [
23
+ /\b(password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|auth)(\s*[=:]\s*)("[^"]*"|'[^']*'|[^\s&"']+)/gi,
24
+ `$1$2${MASK}`,
25
+ ],
26
+ ];
27
+ export function redactSecrets(text) {
28
+ let out = text;
29
+ for (const [pattern, replacement] of SECRET_PATTERNS)
30
+ out = out.replace(pattern, replacement);
31
+ return out;
32
+ }
33
+ export const cutUrls = (text) => text.replace(/\b(https?:\/\/[^\s?#"'<>]+)[?#][^\s"'<>]*/gi, "$1");
34
+ /** A step as it's uploaded: secrets masked, addresses cut, one line, at most 200 characters. */
35
+ export const cleanStepText = (text) => clip(cutUrls(redactSecrets(text)).replace(/\s+/g, " ").trim(), MAX_STEP_CHARS);
@@ -0,0 +1,214 @@
1
+ /**
2
+ * What sync keeps on this computer, in the Reasonally config folder the terminal agent and the
3
+ * desktop app share:
4
+ * - `device.json`: this computer's own id, picked once, so both programs report as one computer;
5
+ * - `sync/settings.json`: syncing on or off, for everything or for one folder;
6
+ * - `sync/servers/<host>/`: per server (production, or a local one being tried), the id the server
7
+ * gave this computer and, in `cursors/<folder>/<conversation>.json`, how far each conversation
8
+ * has been uploaded there. One small file each, so two programs never overwrite each other.
9
+ *
10
+ * Everything is owner-only, like the rest of the config folder. Nothing here is ever required:
11
+ * a file that's missing or unreadable means "start over", which uploads the same entries again,
12
+ * and the server keeps them by position, so nothing is duplicated.
13
+ */
14
+ import { execFile } from "node:child_process";
15
+ import { randomUUID } from "node:crypto";
16
+ import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
17
+ import { hostname } from "node:os";
18
+ import { join } from "node:path";
19
+ import { writePrivateFile } from "../config.js";
20
+ // ------------------------------------------------------------------------------------- device
21
+ const devicePath = (configDir) => join(configDir, "device.json");
22
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
23
+ async function readDeviceId(configDir) {
24
+ try {
25
+ const parsed = JSON.parse(await readFile(devicePath(configDir), "utf8"));
26
+ return typeof parsed.id === "string" && UUID.test(parsed.id) ? parsed.id : null;
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ /**
33
+ * This computer's id. The first program to need it writes it; the file is created exclusively,
34
+ * so when the terminal and the app start at once, both end up with the one that was written.
35
+ */
36
+ export async function deviceId(configDir) {
37
+ const existing = await readDeviceId(configDir);
38
+ if (existing)
39
+ return existing;
40
+ await mkdir(configDir, { recursive: true, mode: 0o700 });
41
+ const id = randomUUID();
42
+ try {
43
+ await writeFile(devicePath(configDir), `${JSON.stringify({ version: 1, id, createdAt: new Date().toISOString() })}\n`, { flag: "wx", mode: 0o600 });
44
+ return id;
45
+ }
46
+ catch (error) {
47
+ if (error.code !== "EEXIST")
48
+ throw error;
49
+ // Another program wrote it a moment ago; it may still be writing.
50
+ for (let attempt = 0; attempt < 5; attempt++) {
51
+ const written = await readDeviceId(configDir);
52
+ if (written)
53
+ return written;
54
+ await new Promise((r) => setTimeout(r, 40));
55
+ }
56
+ // A file that never became readable (corrupt): replace it.
57
+ await writePrivateFile(devicePath(configDir), `${JSON.stringify({ version: 1, id, createdAt: new Date().toISOString() })}\n`);
58
+ return id;
59
+ }
60
+ }
61
+ const fromHostname = () => hostname().replace(/\.(local|lan|home)$/i, "") || "this computer";
62
+ /** What this computer is called, as people know it: "Aldo's MacBook Pro" rather than a hostname. */
63
+ export function deviceName(platform = process.platform) {
64
+ if (platform !== "darwin")
65
+ return Promise.resolve(fromHostname());
66
+ return new Promise((resolve) => {
67
+ execFile("scutil", ["--get", "ComputerName"], { timeout: 2000 }, (error, out) => {
68
+ const name = out?.toString().trim();
69
+ resolve(!error && name ? name : fromHostname());
70
+ });
71
+ });
72
+ }
73
+ export const devicePlatform = (platform = process.platform) => platform === "darwin" || platform === "win32" || platform === "linux" ? platform : "other";
74
+ const DEFAULT_SETTINGS = {
75
+ version: 1,
76
+ enabled: true,
77
+ offFolders: [],
78
+ noticeShown: {},
79
+ pendingForget: [],
80
+ };
81
+ const settingsPath = (configDir) => join(configDir, "sync", "settings.json");
82
+ export async function readSyncSettings(configDir) {
83
+ try {
84
+ const parsed = JSON.parse(await readFile(settingsPath(configDir), "utf8"));
85
+ return {
86
+ ...DEFAULT_SETTINGS,
87
+ ...parsed,
88
+ version: 1,
89
+ enabled: parsed.enabled !== false,
90
+ offFolders: Array.isArray(parsed.offFolders)
91
+ ? parsed.offFolders.filter((f) => typeof f === "string")
92
+ : [],
93
+ noticeShown: parsed.noticeShown && typeof parsed.noticeShown === "object" ? parsed.noticeShown : {},
94
+ pendingForget: Array.isArray(parsed.pendingForget) ? parsed.pendingForget : [],
95
+ };
96
+ }
97
+ catch {
98
+ return { ...DEFAULT_SETTINGS, offFolders: [], noticeShown: {}, pendingForget: [] };
99
+ }
100
+ }
101
+ /** Reads, changes and writes the settings (fields a newer version added are kept). */
102
+ export async function updateSyncSettings(configDir, change) {
103
+ let raw = {};
104
+ try {
105
+ raw = JSON.parse(await readFile(settingsPath(configDir), "utf8"));
106
+ }
107
+ catch {
108
+ // first write
109
+ }
110
+ const settings = await readSyncSettings(configDir);
111
+ change(settings);
112
+ await writePrivateFile(settingsPath(configDir), `${JSON.stringify({ ...raw, ...settings }, null, 2)}\n`);
113
+ return settings;
114
+ }
115
+ export const folderIsOn = (settings, folderKey) => settings.enabled && !settings.offFolders.includes(folderKey);
116
+ export const freshCursor = () => ({
117
+ version: 1,
118
+ offset: 0,
119
+ line: 0,
120
+ cwd: null,
121
+ startedAt: null,
122
+ surface: null,
123
+ model: "",
124
+ costMicros: "0",
125
+ firstMessage: null,
126
+ uploaded: null,
127
+ removed: false,
128
+ });
129
+ /** Where sync keeps what it knows about one server (`app.reasonally.ai`, `localhost-3001`). */
130
+ export function serverDir(configDir, appUrl) {
131
+ let key = "server";
132
+ try {
133
+ const url = new URL(appUrl);
134
+ key = `${url.hostname}${url.port ? `-${url.port}` : ""}`.replace(/[^A-Za-z0-9.-]/g, "-");
135
+ }
136
+ catch {
137
+ // keep the fallback
138
+ }
139
+ return join(configDir, "sync", "servers", key);
140
+ }
141
+ const cursorsDir = (root) => join(root, "cursors");
142
+ const cursorPath = (root, folderKey, sessionId) => join(cursorsDir(root), folderKey, `${sessionId}.json`);
143
+ export async function readCursor(root, folderKey, sessionId) {
144
+ try {
145
+ const parsed = JSON.parse(await readFile(cursorPath(root, folderKey, sessionId), "utf8"));
146
+ if (typeof parsed.offset !== "number" || typeof parsed.line !== "number")
147
+ return freshCursor();
148
+ return { ...freshCursor(), ...parsed, version: 1 };
149
+ }
150
+ catch {
151
+ return freshCursor();
152
+ }
153
+ }
154
+ export function writeCursor(root, folderKey, sessionId, cursor) {
155
+ return writePrivateFile(cursorPath(root, folderKey, sessionId), `${JSON.stringify(cursor)}\n`);
156
+ }
157
+ /** Forgets upload progress: for some conversations, a folder, or everything. */
158
+ export async function clearCursors(root, scope) {
159
+ if (scope.kind === "sessions") {
160
+ // Their folder isn't known here: look in each.
161
+ let folders = [];
162
+ try {
163
+ folders = await readdir(cursorsDir(root));
164
+ }
165
+ catch {
166
+ return;
167
+ }
168
+ await Promise.all(folders.flatMap((folder) => scope.sessionIds.map((id) => rm(cursorPath(root, folder, id), { force: true }))));
169
+ return;
170
+ }
171
+ await rm(scope.kind === "folder" ? join(cursorsDir(root), scope.folderKey) : cursorsDir(root), {
172
+ recursive: true,
173
+ force: true,
174
+ });
175
+ }
176
+ /** The id this server gave the computer, remembered so it can still clean up while offline later. */
177
+ export async function readServerDeviceId(root) {
178
+ try {
179
+ const parsed = JSON.parse(await readFile(join(root, "device.json"), "utf8"));
180
+ return typeof parsed.deviceId === "string" ? parsed.deviceId : null;
181
+ }
182
+ catch {
183
+ return null;
184
+ }
185
+ }
186
+ export function writeServerDeviceId(root, deviceId) {
187
+ return writePrivateFile(join(root, "device.json"), `${JSON.stringify({ deviceId })}\n`);
188
+ }
189
+ /** When anything was last uploaded to this server (the newest cursor), for `reasonally sync status`. */
190
+ export async function lastUpload(root) {
191
+ let newest = 0;
192
+ let folders;
193
+ try {
194
+ folders = await readdir(cursorsDir(root));
195
+ }
196
+ catch {
197
+ return null;
198
+ }
199
+ for (const folder of folders) {
200
+ let names = [];
201
+ try {
202
+ names = await readdir(join(cursorsDir(root), folder));
203
+ }
204
+ catch {
205
+ continue;
206
+ }
207
+ for (const name of names) {
208
+ const s = await stat(join(cursorsDir(root), folder, name)).catch(() => null);
209
+ if (s && s.mtimeMs > newest)
210
+ newest = s.mtimeMs;
211
+ }
212
+ }
213
+ return newest ? new Date(newest) : null;
214
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Reads what was added to a conversation file since the last upload: whole lines only, each with
3
+ * where it ends, so progress is saved exactly at the last line uploaded. A half-written last line
4
+ * waits for the next read. A file that got shorter (replaced by hand) is read again from the start.
5
+ */
6
+ import { open, stat } from "node:fs/promises";
7
+ /** Reads at most this much at once; the rest comes on the next read. */
8
+ const MAX_READ = 4 * 1024 * 1024;
9
+ /** Longest line it will widen its window for. */
10
+ const MAX_LINE = 64 * 1024 * 1024;
11
+ export async function readTail(path, offset, line, maxRead = MAX_READ) {
12
+ let size;
13
+ let mtime;
14
+ try {
15
+ const s = await stat(path);
16
+ size = s.size;
17
+ mtime = s.mtime;
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ const reset = size < offset;
23
+ const from = reset ? 0 : offset;
24
+ let next = reset ? 0 : line;
25
+ if (size === from)
26
+ return { lines: [], reset, size, mtime };
27
+ // A window that holds at least one whole line: widened for a very long one (a compaction
28
+ // record re-states the conversation), up to a limit no real line reaches.
29
+ let span = maxRead;
30
+ let buffer;
31
+ let length;
32
+ for (;;) {
33
+ length = Math.min(size - from, span);
34
+ buffer = Buffer.alloc(length);
35
+ const file = await open(path, "r");
36
+ try {
37
+ await file.read(buffer, 0, length, from);
38
+ }
39
+ finally {
40
+ await file.close();
41
+ }
42
+ if (buffer.includes(0x0a) || length === size - from || span >= MAX_LINE)
43
+ break;
44
+ span *= 4;
45
+ }
46
+ const lines = [];
47
+ let start = 0;
48
+ for (let i = 0; i < length; i++) {
49
+ if (buffer[i] !== 0x0a)
50
+ continue;
51
+ const text = buffer.subarray(start, i).toString("utf8");
52
+ let record = null;
53
+ if (text.trim()) {
54
+ try {
55
+ record = JSON.parse(text);
56
+ }
57
+ catch {
58
+ record = null; // a corrupt line: skipped, as loadSession skips it
59
+ }
60
+ lines.push({ line: next, end: from + i + 1, record });
61
+ next++;
62
+ }
63
+ start = i + 1;
64
+ }
65
+ return { lines, reset, size, mtime };
66
+ }