reasonally 0.6.0 → 0.8.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.
- package/README.md +20 -0
- package/dist/agent/session.js +1 -0
- package/dist/api.js +12 -3
- package/dist/cli.js +6 -1
- package/dist/login.js +20 -4
- package/dist/sync/client.js +789 -0
- package/dist/sync/command.js +105 -0
- package/dist/sync/entries.js +139 -0
- package/dist/sync/live.js +107 -0
- package/dist/sync/protocol.js +14 -0
- package/dist/sync/redact.js +35 -0
- package/dist/sync/store.js +214 -0
- package/dist/sync/tail.js +66 -0
- package/dist/tui/app.js +63 -5
- package/dist/tui/args.js +20 -1
- package/dist/tui/start.js +39 -2
- package/package.json +1 -1
|
@@ -0,0 +1,789 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shows this computer's conversations on the web: uploads what the agent already saved (summaries
|
|
3
|
+
* only, see `entries.ts`), what's happening live while someone watches, and that the computer is
|
|
4
|
+
* there. Used by the terminal agent and the desktop app alike.
|
|
5
|
+
*
|
|
6
|
+
* It never gets in the way of the work:
|
|
7
|
+
* - it only reads conversation files, after they're written, and never touches them;
|
|
8
|
+
* - nothing a turn does waits for it: calls are queued and sent in the background;
|
|
9
|
+
* - it only uploads conversations this program holds (the lock), plus, when idle, recent ones
|
|
10
|
+
* no running program holds;
|
|
11
|
+
* - anything going wrong (offline, the server switch off, a revoked key) makes it go quiet and
|
|
12
|
+
* try again later. Progress is saved per conversation, so nothing is lost or sent twice.
|
|
13
|
+
*/
|
|
14
|
+
import { readdir, stat } from "node:fs/promises";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
import { sessionHolder } from "../agent/session.js";
|
|
17
|
+
import { entryFor, noteRecord, sessionLocation, titleFrom } from "./entries.js";
|
|
18
|
+
import { MAX_BATCH_BYTES, MAX_ENTRIES_PER_BATCH, NO_MARKS, SYNC_PROTOCOL, clip, MAX_TITLE_CHARS, } from "./protocol.js";
|
|
19
|
+
import { readTail } from "./tail.js";
|
|
20
|
+
import { clearCursors, deviceId as localDeviceId, deviceName as defaultDeviceName, devicePlatform, folderIsOn, readCursor, readServerDeviceId, readSyncSettings, serverDir, updateSyncSettings, writeCursor, writeServerDeviceId, } from "./store.js";
|
|
21
|
+
/** How often the computer checks in while the program runs. */
|
|
22
|
+
export const HEARTBEAT_MS = 5_000;
|
|
23
|
+
/** Saves within this long of each other are uploaded together. */
|
|
24
|
+
export const UPLOAD_DELAY_MS = 300;
|
|
25
|
+
/** Live text is grouped this long before it's sent. */
|
|
26
|
+
export const LIVE_EVERY_MS = 300;
|
|
27
|
+
/** Conversations changed this recently are uploaded when the program starts. */
|
|
28
|
+
export const BACKFILL_DAYS = 30;
|
|
29
|
+
/** How long after starting the backfill begins (the program gets going first). */
|
|
30
|
+
export const BACKFILL_DELAY_MS = 5_000;
|
|
31
|
+
/** How often a server that said "not available yet" is asked again. */
|
|
32
|
+
export const RECHECK_MS = 60 * 60 * 1000;
|
|
33
|
+
const MAX_BACKOFF_MS = 60_000;
|
|
34
|
+
const REQUEST_TIMEOUT_MS = 15_000;
|
|
35
|
+
/** How long one inbox request waits for a command while someone watches or a turn runs. */
|
|
36
|
+
export const INBOX_WAIT_SECONDS = 20;
|
|
37
|
+
/**
|
|
38
|
+
* The least time between two inbox requests that found nothing: a server (or a proxy) that
|
|
39
|
+
* answers at once instead of waiting can't turn the loop into a flood.
|
|
40
|
+
*/
|
|
41
|
+
export const INBOX_MIN_INTERVAL_MS = 1_000;
|
|
42
|
+
const UNREACHABLE = { ok: false, status: 0, code: null, retryAfterMs: null };
|
|
43
|
+
export class SyncClient {
|
|
44
|
+
options;
|
|
45
|
+
state = "starting";
|
|
46
|
+
offline = false;
|
|
47
|
+
features = null;
|
|
48
|
+
deviceId = null;
|
|
49
|
+
credentialsUsed = null;
|
|
50
|
+
watchedUntil = 0;
|
|
51
|
+
stopped = false;
|
|
52
|
+
queue = new Map();
|
|
53
|
+
statuses = new Map();
|
|
54
|
+
working = null;
|
|
55
|
+
uploadTimer = null;
|
|
56
|
+
backoffMs = 0;
|
|
57
|
+
retryTimer = null;
|
|
58
|
+
heartbeatTimer = null;
|
|
59
|
+
recheckTimer = null;
|
|
60
|
+
registering = null;
|
|
61
|
+
/**
|
|
62
|
+
* Live state per conversation: what was last set, whether something was sent, the grouping
|
|
63
|
+
* timer, and the sending loop with what it sends next (see `sendLive`).
|
|
64
|
+
*/
|
|
65
|
+
live = new Map();
|
|
66
|
+
settingsCache = null;
|
|
67
|
+
allowRemote = null;
|
|
68
|
+
/** The last inbox version answered; a newer one in a heartbeat means commands wait. */
|
|
69
|
+
inboxSeen = -1;
|
|
70
|
+
inboxLoop = null;
|
|
71
|
+
/** Results that couldn't be sent yet (offline): they go with the next heartbeat. */
|
|
72
|
+
unsentResults = [];
|
|
73
|
+
constructor(options) {
|
|
74
|
+
this.options = options;
|
|
75
|
+
}
|
|
76
|
+
now() {
|
|
77
|
+
return this.options.now?.() ?? Date.now();
|
|
78
|
+
}
|
|
79
|
+
log(line) {
|
|
80
|
+
this.options.log?.(`[sync] ${line}`);
|
|
81
|
+
}
|
|
82
|
+
get status() {
|
|
83
|
+
return {
|
|
84
|
+
state: this.state,
|
|
85
|
+
offline: this.offline,
|
|
86
|
+
waiting: this.queue.size,
|
|
87
|
+
watched: this.watched,
|
|
88
|
+
features: this.features,
|
|
89
|
+
allowRemote: this.allowRemote,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
get watched() {
|
|
93
|
+
return this.now() < this.watchedUntil;
|
|
94
|
+
}
|
|
95
|
+
setState(state, offline = this.offline) {
|
|
96
|
+
if (state === this.state && offline === this.offline)
|
|
97
|
+
return;
|
|
98
|
+
this.state = state;
|
|
99
|
+
this.offline = offline;
|
|
100
|
+
this.options.onStatus?.(this.status);
|
|
101
|
+
}
|
|
102
|
+
root(credentials) {
|
|
103
|
+
return serverDir(this.options.configDir, credentials.appUrl);
|
|
104
|
+
}
|
|
105
|
+
async settings() {
|
|
106
|
+
if (this.settingsCache && this.now() - this.settingsCache.at < 2_000)
|
|
107
|
+
return this.settingsCache.value;
|
|
108
|
+
const value = await readSyncSettings(this.options.configDir);
|
|
109
|
+
this.settingsCache = { at: this.now(), value };
|
|
110
|
+
return value;
|
|
111
|
+
}
|
|
112
|
+
// ----------------------------------------------------------------------------------- lifecycle
|
|
113
|
+
/** Starts syncing (never throws): says hello to the server, then checks in every few seconds. */
|
|
114
|
+
async start() {
|
|
115
|
+
this.stopped = false;
|
|
116
|
+
await this.register();
|
|
117
|
+
this.heartbeatTimer ??= setInterval(() => void this.heartbeat(), HEARTBEAT_MS);
|
|
118
|
+
this.heartbeatTimer.unref?.();
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Stops syncing: live state is cleared on the web and what's queued gets `timeoutMs` to go.
|
|
122
|
+
* Whatever doesn't make it is picked up next time (progress is saved per conversation).
|
|
123
|
+
*/
|
|
124
|
+
async stop(timeoutMs = 2_000) {
|
|
125
|
+
this.stopped = true;
|
|
126
|
+
for (const timer of [
|
|
127
|
+
this.heartbeatTimer,
|
|
128
|
+
this.recheckTimer,
|
|
129
|
+
this.uploadTimer,
|
|
130
|
+
this.retryTimer,
|
|
131
|
+
]) {
|
|
132
|
+
if (timer)
|
|
133
|
+
clearTimeout(timer);
|
|
134
|
+
}
|
|
135
|
+
this.heartbeatTimer = this.recheckTimer = this.uploadTimer = this.retryTimer = null;
|
|
136
|
+
const clearing = [...this.live.entries()]
|
|
137
|
+
.filter(([, l]) => l.sent || l.sending)
|
|
138
|
+
.map(([path]) => this.sendLive(path, null));
|
|
139
|
+
const draining = (async () => {
|
|
140
|
+
await Promise.all(clearing);
|
|
141
|
+
await this.drain(true);
|
|
142
|
+
})();
|
|
143
|
+
await Promise.race([draining, new Promise((r) => setTimeout(r, timeoutMs).unref?.())]);
|
|
144
|
+
for (const l of this.live.values())
|
|
145
|
+
if (l.timer)
|
|
146
|
+
clearTimeout(l.timer);
|
|
147
|
+
this.live.clear();
|
|
148
|
+
}
|
|
149
|
+
/** Says hello: learns whether syncing is on for this person, and this computer's id. */
|
|
150
|
+
register() {
|
|
151
|
+
this.registering ??= this.doRegister().finally(() => {
|
|
152
|
+
this.registering = null;
|
|
153
|
+
});
|
|
154
|
+
return this.registering;
|
|
155
|
+
}
|
|
156
|
+
async doRegister() {
|
|
157
|
+
const settings = await readSyncSettings(this.options.configDir);
|
|
158
|
+
const credentials = this.options.credentials();
|
|
159
|
+
this.credentialsUsed = credentials;
|
|
160
|
+
if (!settings.enabled) {
|
|
161
|
+
// Turned off while offline: the threads still come off the web now.
|
|
162
|
+
if (credentials)
|
|
163
|
+
await this.sendPendingForgets(credentials);
|
|
164
|
+
return this.setState("off", false);
|
|
165
|
+
}
|
|
166
|
+
if (!credentials)
|
|
167
|
+
return this.setState("signed-out", false);
|
|
168
|
+
const reply = await this.post(credentials, "device", {
|
|
169
|
+
clientDeviceId: await localDeviceId(this.options.configDir),
|
|
170
|
+
name: await (this.options.deviceName ?? defaultDeviceName)(),
|
|
171
|
+
platform: devicePlatform(),
|
|
172
|
+
appVersion: this.options.appVersion,
|
|
173
|
+
client: this.options.client,
|
|
174
|
+
});
|
|
175
|
+
if (!reply.ok) {
|
|
176
|
+
if (this.handleRefusal(reply))
|
|
177
|
+
return;
|
|
178
|
+
this.setState(this.state === "starting" ? "on" : this.state, true);
|
|
179
|
+
this.scheduleRecheck(Math.min(MAX_BACKOFF_MS, 15_000));
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
this.features = reply.body.features;
|
|
183
|
+
if (!reply.body.enabled) {
|
|
184
|
+
this.deviceId = null;
|
|
185
|
+
this.setState("unavailable", false);
|
|
186
|
+
this.scheduleRecheck(RECHECK_MS);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
this.deviceId = reply.body.deviceId;
|
|
190
|
+
this.setAllowRemote(reply.body.allowRemote);
|
|
191
|
+
await writeServerDeviceId(this.root(credentials), reply.body.deviceId).catch(() => { });
|
|
192
|
+
this.setState("on", false);
|
|
193
|
+
if (!settings.noticeShown[this.options.surface]) {
|
|
194
|
+
await updateSyncSettings(this.options.configDir, (s) => {
|
|
195
|
+
s.noticeShown[this.options.surface] = new Date(this.now()).toISOString();
|
|
196
|
+
}).catch(() => { });
|
|
197
|
+
this.options.onFirstSync?.();
|
|
198
|
+
}
|
|
199
|
+
await this.sendPendingForgets(credentials);
|
|
200
|
+
this.kick(0);
|
|
201
|
+
}
|
|
202
|
+
scheduleRecheck(ms) {
|
|
203
|
+
if (this.stopped)
|
|
204
|
+
return;
|
|
205
|
+
if (this.recheckTimer)
|
|
206
|
+
clearTimeout(this.recheckTimer);
|
|
207
|
+
this.recheckTimer = setTimeout(() => {
|
|
208
|
+
this.recheckTimer = null;
|
|
209
|
+
void this.register();
|
|
210
|
+
}, ms);
|
|
211
|
+
this.recheckTimer.unref?.();
|
|
212
|
+
}
|
|
213
|
+
/** Whether a refusal stops syncing for now (and how it reads). False: try again later. */
|
|
214
|
+
handleRefusal(reply) {
|
|
215
|
+
if (reply.status === 401) {
|
|
216
|
+
this.deviceId = null;
|
|
217
|
+
this.setState("signed-out", false);
|
|
218
|
+
return true;
|
|
219
|
+
}
|
|
220
|
+
if (reply.status === 426) {
|
|
221
|
+
this.deviceId = null;
|
|
222
|
+
this.setState("update", false);
|
|
223
|
+
return true;
|
|
224
|
+
}
|
|
225
|
+
if (reply.status === 403) {
|
|
226
|
+
this.deviceId = null;
|
|
227
|
+
this.setState(reply.code === "sync_needs_person" ? "signed-out" : "unavailable", false);
|
|
228
|
+
this.scheduleRecheck(RECHECK_MS);
|
|
229
|
+
return true;
|
|
230
|
+
}
|
|
231
|
+
return false;
|
|
232
|
+
}
|
|
233
|
+
/** The key changed (signed in again): start over with it. */
|
|
234
|
+
credentialsChanged() {
|
|
235
|
+
const now = this.options.credentials();
|
|
236
|
+
const before = this.credentialsUsed;
|
|
237
|
+
return now?.apiKey !== before?.apiKey || now?.appUrl !== before?.appUrl;
|
|
238
|
+
}
|
|
239
|
+
async heartbeat() {
|
|
240
|
+
if (this.stopped)
|
|
241
|
+
return;
|
|
242
|
+
if (this.credentialsChanged())
|
|
243
|
+
return this.register();
|
|
244
|
+
const credentials = this.credentialsUsed;
|
|
245
|
+
if (this.state !== "on" || !credentials || !this.deviceId)
|
|
246
|
+
return;
|
|
247
|
+
const remote = this.options.remote;
|
|
248
|
+
const reply = await this.post(credentials, "heartbeat", {
|
|
249
|
+
deviceId: this.deviceId,
|
|
250
|
+
...(remote ? { accepting: true } : {}),
|
|
251
|
+
});
|
|
252
|
+
if (reply.ok) {
|
|
253
|
+
this.watchedUntil = reply.body.watched ? this.now() + HEARTBEAT_MS * 2 + 1_000 : 0;
|
|
254
|
+
if (this.offline) {
|
|
255
|
+
this.setState("on", false);
|
|
256
|
+
this.kick(0);
|
|
257
|
+
}
|
|
258
|
+
if (remote) {
|
|
259
|
+
if (this.unsentResults.length)
|
|
260
|
+
void this.reportCommands([]);
|
|
261
|
+
const waiting = reply.body.inbox !== undefined && reply.body.inbox > this.inboxSeen;
|
|
262
|
+
if (waiting)
|
|
263
|
+
void this.pollInbox(0);
|
|
264
|
+
this.engage();
|
|
265
|
+
}
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
if (reply.status === 404)
|
|
269
|
+
return this.register();
|
|
270
|
+
if (!this.handleRefusal(reply))
|
|
271
|
+
this.setState("on", true);
|
|
272
|
+
}
|
|
273
|
+
// ------------------------------------------------------------------------------------- uploads
|
|
274
|
+
/**
|
|
275
|
+
* A conversation this program holds was saved: upload what's new, shortly. `flush` waits for
|
|
276
|
+
* the writer; `status` is how the thread stands now (working, waiting for an answer, …).
|
|
277
|
+
*/
|
|
278
|
+
poke(path, options = {}) {
|
|
279
|
+
if (options.status)
|
|
280
|
+
this.statuses.set(path, options.status);
|
|
281
|
+
const queued = this.queue.get(path);
|
|
282
|
+
this.queue.set(path, { path, flush: options.flush ?? queued?.flush, held: true });
|
|
283
|
+
this.kick(UPLOAD_DELAY_MS);
|
|
284
|
+
}
|
|
285
|
+
/** The thread's status changed without anything being saved (a turn started or ended). */
|
|
286
|
+
setStatus(path, status) {
|
|
287
|
+
if (this.statuses.get(path) === status)
|
|
288
|
+
return;
|
|
289
|
+
this.poke(path, { status });
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Uploads recent conversations no running program holds (made while syncing was off, offline,
|
|
293
|
+
* or by an older version). In idle time, one at a time.
|
|
294
|
+
*/
|
|
295
|
+
backfill(sessionDirs) {
|
|
296
|
+
const timer = setTimeout(() => void this.queueBackfill(sessionDirs), BACKFILL_DELAY_MS);
|
|
297
|
+
timer.unref?.();
|
|
298
|
+
}
|
|
299
|
+
async queueBackfill(sessionDirs) {
|
|
300
|
+
if (this.stopped || this.state !== "on")
|
|
301
|
+
return;
|
|
302
|
+
const since = this.now() - BACKFILL_DAYS * 24 * 60 * 60 * 1000;
|
|
303
|
+
const found = [];
|
|
304
|
+
for (const dir of sessionDirs) {
|
|
305
|
+
let names = [];
|
|
306
|
+
try {
|
|
307
|
+
names = (await readdir(dir)).filter((n) => n.endsWith(".jsonl"));
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
for (const name of names) {
|
|
313
|
+
const s = await stat(join(dir, name)).catch(() => null);
|
|
314
|
+
if (s && s.mtimeMs >= since)
|
|
315
|
+
found.push({ path: join(dir, name), mtime: s.mtimeMs });
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
// Newest first: what the person is most likely to look for.
|
|
319
|
+
for (const { path } of found.sort((a, b) => b.mtime - a.mtime)) {
|
|
320
|
+
if (!this.queue.has(path))
|
|
321
|
+
this.queue.set(path, { path, held: false });
|
|
322
|
+
}
|
|
323
|
+
this.kick(0);
|
|
324
|
+
}
|
|
325
|
+
/** Every conversation folder in the config folder (the desktop app backfills them all). */
|
|
326
|
+
static async allSessionDirs(configDir) {
|
|
327
|
+
const root = join(configDir, "sessions");
|
|
328
|
+
try {
|
|
329
|
+
return (await readdir(root)).map((name) => join(root, name));
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
return [];
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
/** Uploads what's queued now, without the usual short wait (Settings' "Sync now", tests). */
|
|
336
|
+
async syncNow() {
|
|
337
|
+
if (this.uploadTimer)
|
|
338
|
+
clearTimeout(this.uploadTimer);
|
|
339
|
+
this.uploadTimer = null;
|
|
340
|
+
await this.working;
|
|
341
|
+
await this.drain(false);
|
|
342
|
+
}
|
|
343
|
+
/** Waits for anything queued for the backfill to be found (tests). */
|
|
344
|
+
async backfillNow(sessionDirs) {
|
|
345
|
+
await this.queueBackfill(sessionDirs);
|
|
346
|
+
await this.syncNow();
|
|
347
|
+
}
|
|
348
|
+
kick(delayMs) {
|
|
349
|
+
if (this.stopped || this.retryTimer)
|
|
350
|
+
return;
|
|
351
|
+
if (this.uploadTimer)
|
|
352
|
+
clearTimeout(this.uploadTimer);
|
|
353
|
+
this.uploadTimer = setTimeout(() => {
|
|
354
|
+
this.uploadTimer = null;
|
|
355
|
+
void this.drain(false);
|
|
356
|
+
}, delayMs);
|
|
357
|
+
this.uploadTimer.unref?.();
|
|
358
|
+
}
|
|
359
|
+
/** Uploads what's queued, held conversations first. `final`: once, without waiting to retry. */
|
|
360
|
+
drain(final) {
|
|
361
|
+
this.working ??= this.doDrain(final).finally(() => {
|
|
362
|
+
this.working = null;
|
|
363
|
+
});
|
|
364
|
+
return this.working;
|
|
365
|
+
}
|
|
366
|
+
async doDrain(final) {
|
|
367
|
+
const credentials = this.credentialsUsed;
|
|
368
|
+
if (this.state !== "on" || !credentials || !this.deviceId)
|
|
369
|
+
return;
|
|
370
|
+
while (this.queue.size > 0) {
|
|
371
|
+
if (this.stopped && !final)
|
|
372
|
+
return;
|
|
373
|
+
const jobs = [...this.queue.values()];
|
|
374
|
+
const job = jobs.find((j) => j.held) ?? jobs[0];
|
|
375
|
+
this.queue.delete(job.path);
|
|
376
|
+
const outcome = await this.upload(credentials, job).catch((error) => {
|
|
377
|
+
this.log(`couldn't upload ${job.path}: ${error.message}`);
|
|
378
|
+
return "done";
|
|
379
|
+
});
|
|
380
|
+
if (outcome === "retry") {
|
|
381
|
+
// Back in line (unless saved again meanwhile), and wait before trying again.
|
|
382
|
+
if (!this.queue.has(job.path))
|
|
383
|
+
this.queue.set(job.path, job);
|
|
384
|
+
if (final)
|
|
385
|
+
return;
|
|
386
|
+
this.backoffMs = Math.min(MAX_BACKOFF_MS, this.backoffMs ? this.backoffMs * 2 : 1_000);
|
|
387
|
+
this.setState("on", true);
|
|
388
|
+
this.retryTimer = setTimeout(() => {
|
|
389
|
+
this.retryTimer = null;
|
|
390
|
+
this.kick(0);
|
|
391
|
+
}, this.backoffMs);
|
|
392
|
+
this.retryTimer.unref?.();
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
if (outcome === "stop")
|
|
396
|
+
return;
|
|
397
|
+
this.backoffMs = 0;
|
|
398
|
+
if (this.offline)
|
|
399
|
+
this.setState("on", false);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Uploads one conversation from where it was left. "retry": the server couldn't be reached
|
|
404
|
+
* (it stays queued); "stop": syncing stopped (signed out, switched off); "done" otherwise.
|
|
405
|
+
*/
|
|
406
|
+
async upload(credentials, job) {
|
|
407
|
+
const where = sessionLocation(job.path);
|
|
408
|
+
if (!where)
|
|
409
|
+
return "done";
|
|
410
|
+
const settings = await this.settings();
|
|
411
|
+
if (!folderIsOn(settings, where.folderKey))
|
|
412
|
+
return "done";
|
|
413
|
+
if (!job.held && (await sessionHolder(job.path)))
|
|
414
|
+
return "done"; // its program uploads it
|
|
415
|
+
await job.flush?.().catch(() => { });
|
|
416
|
+
const root = this.root(credentials);
|
|
417
|
+
const saved = await readCursor(root, where.folderKey, where.sessionId);
|
|
418
|
+
if (saved.removed)
|
|
419
|
+
return "done";
|
|
420
|
+
const tail = await readTail(job.path, saved.offset, saved.line);
|
|
421
|
+
if (!tail)
|
|
422
|
+
return "done"; // gone (deleted, moved to the Trash)
|
|
423
|
+
// A file that got shorter is read again from the start (uploading the same entries is safe).
|
|
424
|
+
const cursor = tail.reset ? { ...saved, ...RESTART } : { ...saved };
|
|
425
|
+
let committed = saved;
|
|
426
|
+
let batch = [];
|
|
427
|
+
let batchBytes = 0;
|
|
428
|
+
/** Uploads `batch` with the details as of `upTo` (progress up to there), and saves progress. */
|
|
429
|
+
const send = async (upTo) => {
|
|
430
|
+
let next = { ...upTo };
|
|
431
|
+
// Nothing typed yet: not a conversation the web shows. Keep reading from here next time.
|
|
432
|
+
if (upTo.cwd === null || upTo.startedAt === null || upTo.firstMessage === null) {
|
|
433
|
+
if (batch.length > 0) {
|
|
434
|
+
// Leave them to be read again once there's a first message (rare: a file with no
|
|
435
|
+
// message from the person yet has almost nothing in it).
|
|
436
|
+
batch = [];
|
|
437
|
+
batchBytes = 0;
|
|
438
|
+
return "done";
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
else {
|
|
442
|
+
const upload = this.threadUpload(upTo, where.sessionId, job.path, tail.mtime, batch);
|
|
443
|
+
const details = detailsKey(upload);
|
|
444
|
+
if (batch.length > 0 || details !== upTo.uploaded) {
|
|
445
|
+
const result = await this.uploadThread(credentials, upload);
|
|
446
|
+
if (result === "retry" || result === "stop")
|
|
447
|
+
return result;
|
|
448
|
+
next = { ...upTo, uploaded: details, removed: result === "removed" };
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
batch = [];
|
|
452
|
+
batchBytes = 0;
|
|
453
|
+
if (JSON.stringify(next) !== JSON.stringify(committed)) {
|
|
454
|
+
committed = next;
|
|
455
|
+
await writeCursor(root, where.folderKey, where.sessionId, committed).catch(() => { });
|
|
456
|
+
}
|
|
457
|
+
return committed.removed ? "removed" : "done";
|
|
458
|
+
};
|
|
459
|
+
for (const line of tail.lines) {
|
|
460
|
+
const entry = line.record ? entryFor(line.record, line.line) : null;
|
|
461
|
+
const bytes = entry ? Buffer.byteLength(JSON.stringify(entry)) : 0;
|
|
462
|
+
if (entry &&
|
|
463
|
+
(batch.length >= MAX_ENTRIES_PER_BATCH || batchBytes + bytes > MAX_BATCH_BYTES)) {
|
|
464
|
+
// Full: upload what's gathered, with progress up to the line before this one.
|
|
465
|
+
const result = await send(cursor);
|
|
466
|
+
if (result === "retry" || result === "stop")
|
|
467
|
+
return result;
|
|
468
|
+
if (result === "removed")
|
|
469
|
+
return "done";
|
|
470
|
+
}
|
|
471
|
+
if (line.record)
|
|
472
|
+
noteRecord(cursor, line.record);
|
|
473
|
+
if (entry) {
|
|
474
|
+
batch.push(entry);
|
|
475
|
+
batchBytes += bytes;
|
|
476
|
+
}
|
|
477
|
+
cursor.offset = line.end;
|
|
478
|
+
cursor.line = line.line + 1;
|
|
479
|
+
}
|
|
480
|
+
const last = await send(cursor);
|
|
481
|
+
if (last === "retry" || last === "stop")
|
|
482
|
+
return last;
|
|
483
|
+
// A very long file is read in parts: carry on with the rest.
|
|
484
|
+
if (last === "done" && tail.lines.length > 0 && committed.offset < tail.size) {
|
|
485
|
+
this.queue.set(job.path, job);
|
|
486
|
+
}
|
|
487
|
+
return "done";
|
|
488
|
+
}
|
|
489
|
+
threadUpload(cursor, sessionId, path, mtime, entries) {
|
|
490
|
+
const given = this.options.titleOf?.(sessionId);
|
|
491
|
+
return {
|
|
492
|
+
deviceId: this.deviceId,
|
|
493
|
+
sessionId,
|
|
494
|
+
surface: cursor.surface ?? "terminal",
|
|
495
|
+
folderName: folderName(cursor.cwd),
|
|
496
|
+
folderKey: sessionLocation(path).folderKey,
|
|
497
|
+
title: clip(given?.trim() || titleFrom(cursor.firstMessage), MAX_TITLE_CHARS),
|
|
498
|
+
model: cursor.model,
|
|
499
|
+
status: this.statuses.get(path) ?? "idle",
|
|
500
|
+
costMicros: cursor.costMicros,
|
|
501
|
+
startedAt: cursor.startedAt,
|
|
502
|
+
updatedAt: mtime.toISOString(),
|
|
503
|
+
marks: this.options.marksOf?.(sessionId) ?? NO_MARKS,
|
|
504
|
+
entries,
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
async uploadThread(credentials, upload) {
|
|
508
|
+
let reply = await this.post(credentials, "threads", upload);
|
|
509
|
+
if (!reply.ok && reply.status === 404) {
|
|
510
|
+
// The server forgot this computer (or it was a different server): say hello again.
|
|
511
|
+
await this.register();
|
|
512
|
+
if (this.state !== "on" || !this.deviceId)
|
|
513
|
+
return "stop";
|
|
514
|
+
reply = await this.post(credentials, "threads", {
|
|
515
|
+
...upload,
|
|
516
|
+
deviceId: this.deviceId,
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
if (reply.ok)
|
|
520
|
+
return reply.body.removed ? "removed" : "done";
|
|
521
|
+
if (this.handleRefusal(reply))
|
|
522
|
+
return "stop";
|
|
523
|
+
if (reply.status === 400 || reply.status === 413) {
|
|
524
|
+
// Something here the server won't take: skip it rather than retry forever.
|
|
525
|
+
this.log(`the server refused an upload (${reply.status} ${reply.code ?? ""})`);
|
|
526
|
+
return "done";
|
|
527
|
+
}
|
|
528
|
+
return "retry";
|
|
529
|
+
}
|
|
530
|
+
// ---------------------------------------------------------------------------------------- live
|
|
531
|
+
/**
|
|
532
|
+
* What's happening in a conversation now. Sent at once when `urgent` (the status, a step, an
|
|
533
|
+
* approval); otherwise grouped and sent only while someone watches. Null clears it.
|
|
534
|
+
*/
|
|
535
|
+
setLive(path, state, urgent) {
|
|
536
|
+
if (this.state !== "on" || this.stopped)
|
|
537
|
+
return;
|
|
538
|
+
let live = this.live.get(path);
|
|
539
|
+
if (!live) {
|
|
540
|
+
live = { pending: null, sent: false, timer: null, next: null, sending: null };
|
|
541
|
+
this.live.set(path, live);
|
|
542
|
+
}
|
|
543
|
+
live.pending = state;
|
|
544
|
+
if (state === null) {
|
|
545
|
+
if (live.timer)
|
|
546
|
+
clearTimeout(live.timer);
|
|
547
|
+
live.timer = null;
|
|
548
|
+
// Also when one is still on its way: it must not be what stays.
|
|
549
|
+
if (live.sent || live.sending)
|
|
550
|
+
void this.sendLive(path, null);
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
if (urgent) {
|
|
554
|
+
if (live.timer)
|
|
555
|
+
clearTimeout(live.timer);
|
|
556
|
+
live.timer = null;
|
|
557
|
+
void this.sendLive(path, state);
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
if (!this.watched || live.timer)
|
|
561
|
+
return;
|
|
562
|
+
live.timer = setTimeout(() => {
|
|
563
|
+
const current = this.live.get(path);
|
|
564
|
+
if (!current)
|
|
565
|
+
return;
|
|
566
|
+
current.timer = null;
|
|
567
|
+
if (current.pending)
|
|
568
|
+
void this.sendLive(path, current.pending);
|
|
569
|
+
}, LIVE_EVERY_MS);
|
|
570
|
+
live.timer.unref?.();
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Sends a conversation's live state, one update at a time and in order: the server answers
|
|
574
|
+
* requests in parallel, so two on their way at once could be stored older-last (a step's update
|
|
575
|
+
* landing after its approval's, and the approval gone from the web). Updates set while one is on
|
|
576
|
+
* its way wait, and only the newest goes. Resolves once everything set so far has been sent.
|
|
577
|
+
*/
|
|
578
|
+
sendLive(path, state) {
|
|
579
|
+
const live = this.live.get(path);
|
|
580
|
+
if (!live)
|
|
581
|
+
return this.postLive(path, state);
|
|
582
|
+
live.next = { state };
|
|
583
|
+
live.sending ??= (async () => {
|
|
584
|
+
try {
|
|
585
|
+
while (live.next) {
|
|
586
|
+
const next = live.next.state;
|
|
587
|
+
live.next = null;
|
|
588
|
+
await this.postLive(path, next);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
finally {
|
|
592
|
+
live.sending = null;
|
|
593
|
+
}
|
|
594
|
+
})();
|
|
595
|
+
return live.sending;
|
|
596
|
+
}
|
|
597
|
+
async postLive(path, state) {
|
|
598
|
+
const credentials = this.credentialsUsed;
|
|
599
|
+
const where = sessionLocation(path);
|
|
600
|
+
if (!credentials || !this.deviceId || !where)
|
|
601
|
+
return;
|
|
602
|
+
// Nothing leaves this computer for a folder that's off, not even for a moment.
|
|
603
|
+
if (state !== null && !folderIsOn(await this.settings(), where.folderKey))
|
|
604
|
+
return;
|
|
605
|
+
const live = this.live.get(path);
|
|
606
|
+
if (live)
|
|
607
|
+
live.sent = state !== null;
|
|
608
|
+
const reply = await this.post(credentials, "live", {
|
|
609
|
+
deviceId: this.deviceId,
|
|
610
|
+
sessionId: where.sessionId,
|
|
611
|
+
state: state && { ...state, sentAt: this.now() },
|
|
612
|
+
});
|
|
613
|
+
if (!reply.ok && reply.status === 404)
|
|
614
|
+
void this.register();
|
|
615
|
+
}
|
|
616
|
+
// -------------------------------------------------------------------------------------- forget
|
|
617
|
+
/**
|
|
618
|
+
* Takes threads off the web: some conversations (deleted here), a folder, or everything (syncing
|
|
619
|
+
* turned off). Progress is forgotten too, so turning syncing back on uploads them again. If the
|
|
620
|
+
* server can't be reached, it's done the next time it can.
|
|
621
|
+
*/
|
|
622
|
+
async forget(scope) {
|
|
623
|
+
const credentials = this.options.credentials();
|
|
624
|
+
if (credentials)
|
|
625
|
+
await clearCursors(this.root(credentials), scope).catch(() => { });
|
|
626
|
+
const sent = credentials ? await this.sendForget(credentials, scope) : false;
|
|
627
|
+
if (!sent) {
|
|
628
|
+
await updateSyncSettings(this.options.configDir, (s) => {
|
|
629
|
+
s.pendingForget.push(scope);
|
|
630
|
+
}).catch(() => { });
|
|
631
|
+
}
|
|
632
|
+
return sent;
|
|
633
|
+
}
|
|
634
|
+
async sendForget(credentials, scope) {
|
|
635
|
+
const deviceId = this.deviceId ?? (await readServerDeviceId(this.root(credentials)));
|
|
636
|
+
if (!deviceId)
|
|
637
|
+
return true; // this server never had anything from this computer
|
|
638
|
+
const reply = await this.post(credentials, "forget", { deviceId, scope });
|
|
639
|
+
return reply.ok || reply.status === 404 || reply.status === 401;
|
|
640
|
+
}
|
|
641
|
+
async sendPendingForgets(credentials) {
|
|
642
|
+
const { pendingForget } = await readSyncSettings(this.options.configDir);
|
|
643
|
+
if (pendingForget.length === 0)
|
|
644
|
+
return;
|
|
645
|
+
const left = [];
|
|
646
|
+
for (const scope of pendingForget) {
|
|
647
|
+
if (!(await this.sendForget(credentials, scope)))
|
|
648
|
+
left.push(scope);
|
|
649
|
+
}
|
|
650
|
+
await updateSyncSettings(this.options.configDir, (s) => {
|
|
651
|
+
s.pendingForget = left;
|
|
652
|
+
}).catch(() => { });
|
|
653
|
+
}
|
|
654
|
+
// ------------------------------------------------------------------------------------- remote
|
|
655
|
+
setAllowRemote(allow) {
|
|
656
|
+
if (allow === this.allowRemote)
|
|
657
|
+
return;
|
|
658
|
+
this.allowRemote = allow;
|
|
659
|
+
this.options.remote?.onAllowRemote?.(allow);
|
|
660
|
+
this.options.onStatus?.(this.status);
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* While someone watches on the web or a turn runs here, an inbox request is always waiting, so
|
|
664
|
+
* a reply or an approval arrives within a second; otherwise the heartbeat says when to look.
|
|
665
|
+
*/
|
|
666
|
+
engage() {
|
|
667
|
+
const remote = this.options.remote;
|
|
668
|
+
if (!remote || this.inboxLoop || !this.canTakeCommands())
|
|
669
|
+
return;
|
|
670
|
+
if (!this.watched && !remote.engaged())
|
|
671
|
+
return;
|
|
672
|
+
this.inboxLoop = (async () => {
|
|
673
|
+
while (this.canTakeCommands() && (this.watched || remote.engaged())) {
|
|
674
|
+
const started = this.now();
|
|
675
|
+
const found = await this.pollInbox(INBOX_WAIT_SECONDS);
|
|
676
|
+
if (found === null)
|
|
677
|
+
break; // offline or refused: the heartbeat tries again
|
|
678
|
+
const left = INBOX_MIN_INTERVAL_MS - (this.now() - started);
|
|
679
|
+
if (!found && left > 0)
|
|
680
|
+
await new Promise((r) => setTimeout(r, left));
|
|
681
|
+
}
|
|
682
|
+
})().finally(() => {
|
|
683
|
+
this.inboxLoop = null;
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
canTakeCommands() {
|
|
687
|
+
return !this.stopped && this.state === "on" && !!this.deviceId && !!this.credentialsUsed;
|
|
688
|
+
}
|
|
689
|
+
/** Looks in the inbox (waiting up to `wait` seconds): whether it found any; null if it couldn't. */
|
|
690
|
+
async pollInbox(wait) {
|
|
691
|
+
const credentials = this.credentialsUsed;
|
|
692
|
+
if (!this.canTakeCommands() || !credentials)
|
|
693
|
+
return null;
|
|
694
|
+
const reply = await this.post(credentials, "inbox", { deviceId: this.deviceId, wait }, (wait + 15) * 1000);
|
|
695
|
+
if (!reply.ok) {
|
|
696
|
+
if (reply.status === 404)
|
|
697
|
+
void this.register();
|
|
698
|
+
return null;
|
|
699
|
+
}
|
|
700
|
+
this.inboxSeen = Math.max(this.inboxSeen, reply.body.version);
|
|
701
|
+
this.setAllowRemote(reply.body.allowRemote);
|
|
702
|
+
if (reply.body.commands.length)
|
|
703
|
+
this.options.remote?.onCommands(reply.body.commands);
|
|
704
|
+
return reply.body.commands.length > 0;
|
|
705
|
+
}
|
|
706
|
+
/** Says how commands went; kept and sent again if Reasonally can't be reached. */
|
|
707
|
+
async reportCommands(results) {
|
|
708
|
+
const credentials = this.credentialsUsed;
|
|
709
|
+
const all = [...this.unsentResults, ...results];
|
|
710
|
+
this.unsentResults = [];
|
|
711
|
+
if (all.length === 0)
|
|
712
|
+
return;
|
|
713
|
+
if (!credentials || !this.deviceId) {
|
|
714
|
+
this.unsentResults = all;
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
for (let i = 0; i < all.length; i += 100) {
|
|
718
|
+
const batch = all.slice(i, i + 100);
|
|
719
|
+
const reply = await this.post(credentials, "commands", {
|
|
720
|
+
deviceId: this.deviceId,
|
|
721
|
+
results: batch,
|
|
722
|
+
});
|
|
723
|
+
if (!reply.ok && reply.status === 0)
|
|
724
|
+
this.unsentResults.push(...batch);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
/** This computer's own yes (or no) to replies and approvals from the web. */
|
|
728
|
+
async setConsent(allow) {
|
|
729
|
+
const credentials = this.credentialsUsed;
|
|
730
|
+
if (!credentials || !this.deviceId)
|
|
731
|
+
return false;
|
|
732
|
+
const reply = await this.post(credentials, "consent", {
|
|
733
|
+
deviceId: this.deviceId,
|
|
734
|
+
allowRemote: allow,
|
|
735
|
+
});
|
|
736
|
+
if (!reply.ok)
|
|
737
|
+
return false;
|
|
738
|
+
this.setAllowRemote(reply.body.allowRemote);
|
|
739
|
+
return true;
|
|
740
|
+
}
|
|
741
|
+
// ---------------------------------------------------------------------------------------- http
|
|
742
|
+
async post(credentials, path, body, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
743
|
+
const fetcher = this.options.fetch ?? fetch;
|
|
744
|
+
let res;
|
|
745
|
+
try {
|
|
746
|
+
res = await fetcher(`${credentials.appUrl}/api/sync/${path}`, {
|
|
747
|
+
method: "POST",
|
|
748
|
+
headers: {
|
|
749
|
+
authorization: `Bearer ${credentials.apiKey}`,
|
|
750
|
+
"content-type": "application/json",
|
|
751
|
+
"x-reasonally-sync": String(SYNC_PROTOCOL),
|
|
752
|
+
"user-agent": `reasonally-${this.options.client}/${this.options.appVersion}`,
|
|
753
|
+
},
|
|
754
|
+
body: JSON.stringify(body),
|
|
755
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
catch {
|
|
759
|
+
return UNREACHABLE;
|
|
760
|
+
}
|
|
761
|
+
if (res.ok) {
|
|
762
|
+
const json = res.status === 204 ? null : await res.json().catch(() => null);
|
|
763
|
+
return { ok: true, body: json };
|
|
764
|
+
}
|
|
765
|
+
const error = (await res.json().catch(() => null));
|
|
766
|
+
const retryAfter = Number(res.headers.get("retry-after"));
|
|
767
|
+
return {
|
|
768
|
+
ok: false,
|
|
769
|
+
status: res.status,
|
|
770
|
+
code: error?.error?.code ?? null,
|
|
771
|
+
retryAfterMs: Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : null,
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
/** Progress reset for a file read again from the start. */
|
|
776
|
+
const RESTART = {
|
|
777
|
+
offset: 0,
|
|
778
|
+
line: 0,
|
|
779
|
+
model: "",
|
|
780
|
+
costMicros: "0",
|
|
781
|
+
firstMessage: null,
|
|
782
|
+
uploaded: null,
|
|
783
|
+
};
|
|
784
|
+
/** What decides whether a details-only upload is needed (everything but the entries and time). */
|
|
785
|
+
function detailsKey(upload) {
|
|
786
|
+
const { title, model, status, costMicros, marks } = upload;
|
|
787
|
+
return JSON.stringify({ title, model, status, costMicros, marks });
|
|
788
|
+
}
|
|
789
|
+
const folderName = (cwd) => cwd.split(/[\\/]/).filter(Boolean).at(-1) ?? cwd;
|