pi-durable-bot 0.7.1 → 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.
Files changed (67) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +19 -11
  3. package/dist/agent/agent.js +160 -33
  4. package/dist/agent/agent.js.map +1 -1
  5. package/dist/agent/children.js +159 -26
  6. package/dist/agent/children.js.map +1 -1
  7. package/dist/agent/memory.js +12 -6
  8. package/dist/agent/memory.js.map +1 -1
  9. package/dist/agent/scopes.js +267 -0
  10. package/dist/agent/scopes.js.map +1 -0
  11. package/dist/agent/screen.js +37 -2
  12. package/dist/agent/screen.js.map +1 -1
  13. package/dist/bot/bot.js +65 -21
  14. package/dist/bot/bot.js.map +1 -1
  15. package/dist/bot/definition.js +25 -11
  16. package/dist/bot/definition.js.map +1 -1
  17. package/dist/bot/prompt.js +33 -13
  18. package/dist/bot/prompt.js.map +1 -1
  19. package/dist/cli/agent.js +1 -1
  20. package/dist/cli/agent.js.map +1 -1
  21. package/dist/cli/ai.js +92 -37
  22. package/dist/cli/ai.js.map +1 -1
  23. package/dist/cli/bots.js +69 -5
  24. package/dist/cli/bots.js.map +1 -1
  25. package/dist/cli/chat.js +59 -4
  26. package/dist/cli/chat.js.map +1 -1
  27. package/dist/cli/commands.js +23 -2
  28. package/dist/cli/commands.js.map +1 -1
  29. package/dist/cli/init.js +4 -18
  30. package/dist/cli/init.js.map +1 -1
  31. package/dist/cli/login.js +20 -26
  32. package/dist/cli/login.js.map +1 -1
  33. package/dist/cli/pages.js +25 -6
  34. package/dist/cli/pages.js.map +1 -1
  35. package/dist/cli/service.js +30 -1
  36. package/dist/cli/service.js.map +1 -1
  37. package/dist/main.js +10 -0
  38. package/dist/main.js.map +1 -1
  39. package/dist/pages/desktop-page.js +293 -0
  40. package/dist/pages/desktop-page.js.map +1 -0
  41. package/dist/pages/desktop.js +672 -0
  42. package/dist/pages/desktop.js.map +1 -0
  43. package/dist/pages/host.js +55 -2
  44. package/dist/pages/host.js.map +1 -1
  45. package/dist/pages/rfb.js +389 -0
  46. package/dist/pages/rfb.js.map +1 -0
  47. package/dist/pages/server.js +172 -1
  48. package/dist/pages/server.js.map +1 -1
  49. package/dist/pages/store.js +26 -4
  50. package/dist/pages/store.js.map +1 -1
  51. package/docs/for-agents.md +27 -7
  52. package/kit/desktop/desktop.css +1010 -0
  53. package/kit/desktop/desktop.js +1421 -0
  54. package/kit/desktop/novnc/AUTHORS +13 -0
  55. package/kit/desktop/novnc/LICENSE.BSD-2-Clause +22 -0
  56. package/kit/desktop/novnc/LICENSE.BSD-3-Clause +24 -0
  57. package/kit/desktop/novnc/LICENSE.MPL-2.0 +373 -0
  58. package/kit/desktop/novnc/LICENSE.OFL-1.1 +91 -0
  59. package/kit/desktop/novnc/LICENSE.pako +21 -0
  60. package/kit/desktop/novnc/LICENSE.txt +62 -0
  61. package/kit/desktop/novnc.js +14404 -0
  62. package/package.json +5 -5
  63. package/skills/desktop-page/SKILL.md +153 -0
  64. package/skills/discord-channel/SKILL.md +4 -4
  65. package/skills/pages/SKILL.md +9 -4
  66. package/skills/slack-channel/SKILL.md +6 -5
  67. package/skills/telegram-channel/SKILL.md +4 -4
@@ -0,0 +1,672 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { desktopHolder, ScreenLeases } from "../agent/screen.js";
4
+ import { expandHome } from "../core/env-file.js";
5
+ import { formatTime } from "../core/time.js";
6
+ import { connectVnc, Reader, readDesktopLayout, readServerInit, readVncPassword, restoreDesktopLayout, sizeText, VncError } from "./rfb.js";
7
+ // Desktop pages: one-time links with which a person sees and controls the bot's screen in their browser, through the
8
+ // VNC server that shows it on this computer. Pots signs in to that server itself and carries the browser's WebSocket to
9
+ // it, so the VNC password never leaves this process. Nothing streams before the person presses Start; the first browser
10
+ // that presses Start keeps the link (a cookie), and may open it again until it ends. While it is started, the person has
11
+ // the bot's screen lease, so no agent drives the screen under their hands. The link ends when they hand the desktop
12
+ // back (done, or "I can't do it"), when it expires, or when the bot takes it back; then Pots sets the desktop's size back
13
+ // to what it was at Start, gives the screen back, and wakes the bot, once.
14
+ /** A desktop link that nobody started stops working after this long. */
15
+ export const DESKTOP_UNOPENED_MS = 3_600_000;
16
+ /** How long a desktop link works after Start, unless the bot gives another number. */
17
+ export const DESKTOP_MINUTES = 15;
18
+ export const DESKTOP_MAX_MINUTES = 60;
19
+ /** What a step can ask the person to type, so their page offers the right field. */
20
+ export const INPUT_KINDS = ["password", "code", "text"];
21
+ /**
22
+ * After the last connection of a started link closed, the desktop's size is set back after restoreAfterMs, unless the
23
+ * browser came back. The server pings each connection every pingMs, so proxies keep it, and ends one that stops
24
+ * answering. For tests: change them.
25
+ */
26
+ export const desktopTimes = { restoreAfterMs: 20_000, pingMs: 25_000, wakeRetryMs: 10_000 };
27
+ /** The name of the cookie that binds a link to the browser that pressed Start. */
28
+ export const DESKTOP_COOKIE = "pots_desktop";
29
+ const DAY_MS = 86_400_000;
30
+ /** Desktop links are listed and kept this long after they were made. */
31
+ const KEEP_MS = 7 * DAY_MS;
32
+ const MAX_TEXT = 2_000;
33
+ const MAX_NOTE = 1_000;
34
+ /** How long Pots waits for the VNC server: to sign in and read the desktop, or to set its size back. */
35
+ const VNC_TIMEOUT_MS = 10_000;
36
+ /** Bytes waiting for the browser above which Pots stops reading the VNC server until they are sent. */
37
+ const HIGH_WATER = 8 * 1024 * 1024;
38
+ const SCHEMA = `
39
+ CREATE TABLE IF NOT EXISTS bot_desktop_links (
40
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
41
+ token TEXT NOT NULL UNIQUE,
42
+ text TEXT NOT NULL,
43
+ input TEXT,
44
+ area TEXT,
45
+ minutes INTEGER NOT NULL,
46
+ made_for TEXT,
47
+ created_at INTEGER NOT NULL,
48
+ expires_at INTEGER NOT NULL,
49
+ state TEXT NOT NULL,
50
+ started_at INTEGER,
51
+ browser TEXT,
52
+ layout TEXT,
53
+ ended_at INTEGER,
54
+ note TEXT,
55
+ restored_at INTEGER,
56
+ woken_at INTEGER
57
+ );
58
+ `;
59
+ /**
60
+ * The Starts of this process, one after another: between the check that nobody uses the screen and the binding, a
61
+ * Start waits for the VNC server, and two links must not both pass the check meanwhile.
62
+ */
63
+ let starting = Promise.resolve();
64
+ const linkId = (row) => `D${row.id}`;
65
+ const hash = (secret) => createHash("sha256").update(secret).digest("hex");
66
+ const madeFor = (person) => person ?? "anyone";
67
+ /** The desktop links of one bot, in its bot.sqlite, and their connections. */
68
+ export class BotDesktop {
69
+ #options;
70
+ #sql;
71
+ #clock;
72
+ #live = new Map();
73
+ #stopped = false;
74
+ #wakeRetry;
75
+ constructor(options) {
76
+ this.#options = options;
77
+ this.#sql = options.sql;
78
+ this.#clock = options.clock ?? Date.now;
79
+ }
80
+ static async open(options) {
81
+ await options.sql.exec(SCHEMA);
82
+ return new BotDesktop(options);
83
+ }
84
+ #leases() {
85
+ return this.#options.leases?.() ?? ScreenLeases.shared();
86
+ }
87
+ /** The VNC server of bot.json, with its password read now. */
88
+ #target() {
89
+ const vnc = this.#options.vnc();
90
+ if (!vnc) {
91
+ throw new VncError('bot.json has no "vnc": a desktop page needs a VNC server that shows your screen on this computer, set as "vnc": {"port": 5900, "passwordFile": "vnc.env"}; the desktop-page skill says how to set one up');
92
+ }
93
+ if (!vnc.passwordFile)
94
+ return { port: vnc.port, password: undefined };
95
+ const file = isAbsolute(expandHome(vnc.passwordFile)) ? expandHome(vnc.passwordFile) : join(this.#options.secretsDir, vnc.passwordFile);
96
+ return { port: vnc.port, password: readVncPassword(file), passwordFile: file };
97
+ }
98
+ // ---- Links ----
99
+ /** pots page desktop: check that the VNC server answers, then make a link, written before it is given out. */
100
+ async create(input) {
101
+ const text = input.text.trim();
102
+ if (!text)
103
+ throw new Error("--text is required: what the person should do on your screen, and when to press Done");
104
+ if (text.length > MAX_TEXT)
105
+ throw new Error(`--text is longer than ${MAX_TEXT} characters`);
106
+ if (input.input !== undefined && !INPUT_KINDS.includes(input.input))
107
+ throw new Error(`bad --input ${JSON.stringify(input.input)}: password, code or text`);
108
+ const area = input.area === undefined ? null : parseArea(input.area);
109
+ const minutes = input.minutes ?? DESKTOP_MINUTES;
110
+ if (!Number.isInteger(minutes) || minutes < 1 || minutes > DESKTOP_MAX_MINUTES)
111
+ throw new Error(`bad --minutes: a whole number from 1 to ${DESKTOP_MAX_MINUTES}`);
112
+ const person = input.person?.trim() || null;
113
+ if (person && (person.length > 200 || /[\u0000-\u001f\u007f]/.test(person)))
114
+ throw new Error("bad --for: a person's address, on one line");
115
+ // A link to a desktop that Pots cannot reach would only fail in the person's hands.
116
+ const layout = await readDesktopLayout(this.#target(), VNC_TIMEOUT_MS);
117
+ const token = randomBytes(18).toString("base64url");
118
+ const now = this.#clock();
119
+ const expiresAt = now + DESKTOP_UNOPENED_MS;
120
+ const id = await this.#sql.transaction(async (tx) => {
121
+ await tx.run("INSERT INTO bot_desktop_links (token, text, input, area, minutes, made_for, created_at, expires_at, state, layout) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'open', ?)", token, text, input.input ?? null, area ? JSON.stringify(area) : null, minutes, person, now, expiresAt, JSON.stringify(layout));
122
+ return (await tx.get("SELECT last_insert_rowid() AS id")).id;
123
+ });
124
+ this.#arm(id, expiresAt);
125
+ this.#options.print("desktop link made", { link: `D${id}`, desktop: sizeText(layout), resizable: layout.screens !== undefined });
126
+ return { id: `D${id}`, token, expiresAt };
127
+ }
128
+ async #row(token) {
129
+ return this.#sql.get("SELECT * FROM bot_desktop_links WHERE token = ?", token);
130
+ }
131
+ /** A row's state now: a live link past its time counts as expired, before its timer has run. */
132
+ #state(row) {
133
+ return (row.state === "open" || row.state === "started") && row.expires_at <= this.#clock() ? "expired" : row.state;
134
+ }
135
+ #mine(row, secret) {
136
+ if (!row.browser || !secret)
137
+ return false;
138
+ const given = Buffer.from(hash(secret), "hex");
139
+ const kept = Buffer.from(row.browser, "hex");
140
+ return given.length === kept.length && timingSafeEqual(given, kept);
141
+ }
142
+ #view(row, secret) {
143
+ const layout = row.layout ? JSON.parse(row.layout) : null;
144
+ return {
145
+ id: linkId(row),
146
+ state: this.#state(row),
147
+ text: row.text,
148
+ input: row.input,
149
+ area: row.area ? JSON.parse(row.area) : null,
150
+ minutes: row.minutes,
151
+ expiresAt: row.expires_at,
152
+ startedAt: row.started_at,
153
+ resizable: layout?.screens !== undefined,
154
+ size: layout ? { width: layout.width, height: layout.height } : null,
155
+ mine: this.#mine(row, secret),
156
+ madeFor: row.made_for,
157
+ };
158
+ }
159
+ /** The link with this token, for its page; undefined when there is none. Looking never starts or uses it. */
160
+ async view(token, secret) {
161
+ const row = await this.#row(token);
162
+ if (!row)
163
+ return undefined;
164
+ if (this.#state(row) !== row.state)
165
+ await this.checkExpiry();
166
+ return this.#view(row, secret);
167
+ }
168
+ /**
169
+ * The person pressed Start. The first browser to do so keeps the link: it gets a new secret for its cookie. The same
170
+ * browser may press it again (the page reloaded, or it was opened again), and keeps its secret. Before the link is
171
+ * bound, Pots checks that it reaches the desktop, and reads the desktop's layout to set back at the end.
172
+ */
173
+ async start(token, secret) {
174
+ const row = await this.#row(token);
175
+ if (!row)
176
+ return { ok: false, status: 404, code: "missing", error: "This link does not work." };
177
+ const state = this.#state(row);
178
+ if (state === "started") {
179
+ if (!this.#mine(row, secret))
180
+ return { ok: false, status: 409, code: "elsewhere", error: "This link is open on another device." };
181
+ this.#hold(row.id);
182
+ return { ok: true, secret: secret, view: this.#view(row, secret) };
183
+ }
184
+ if (state !== "open")
185
+ return { ok: false, status: 410, code: state, error: "This link has ended." };
186
+ const turn = starting.then(() => this.#bind(row, secret));
187
+ starting = turn.catch(() => { });
188
+ return turn;
189
+ }
190
+ /** The rest of a Start, alone among the Starts of this process. */
191
+ async #bind(row, secret) {
192
+ const busy = await this.#busy(row.id);
193
+ if (busy)
194
+ return { ok: false, status: 409, code: "busy", error: `Someone is using this desktop through another link (${busy}).` };
195
+ let layout;
196
+ try {
197
+ layout = await readDesktopLayout(this.#target(), VNC_TIMEOUT_MS);
198
+ }
199
+ catch (error) {
200
+ const reason = error instanceof Error ? error.message : String(error);
201
+ this.#options.print("desktop page could not reach the desktop", { link: linkId(row), error: reason });
202
+ await this.#options
203
+ .wake(`desktop page: someone pressed Start on link ${linkId(row)} (made for ${madeFor(row.made_for)}), but Pots could not reach your desktop: ${reason}. Their page says so; the link still works, and Start tries again.`, `desktop:${linkId(row)}:unreachable`)
204
+ .catch((wakeError) => this.#options.print("desktop page wake failed", { link: linkId(row), error: String(wakeError) }));
205
+ return { ok: false, status: 503, code: "unreachable", error: reason };
206
+ }
207
+ const fresh = randomBytes(32).toString("base64url");
208
+ const now = this.#clock();
209
+ const bound = await this.#sql.transaction(async (tx) => {
210
+ const current = await tx.get("SELECT * FROM bot_desktop_links WHERE id = ?", row.id);
211
+ if (!current || this.#state(current) !== "open")
212
+ return current;
213
+ // The same browser pressed Start twice at once: the first one bound it.
214
+ if (current.state === "started")
215
+ return current;
216
+ await tx.run("UPDATE bot_desktop_links SET state = 'started', started_at = ?, browser = ?, layout = ?, expires_at = ? WHERE id = ?", now, hash(fresh), JSON.stringify(layout), now + current.minutes * 60_000, row.id);
217
+ return await tx.get("SELECT * FROM bot_desktop_links WHERE id = ?", row.id);
218
+ });
219
+ if (!bound || bound.browser !== hash(fresh)) {
220
+ // Another browser was a moment faster, or the link ended meanwhile.
221
+ if (bound && this.#state(bound) === "started") {
222
+ if (this.#mine(bound, secret))
223
+ return { ok: true, secret: secret, view: this.#view(bound, secret) };
224
+ return { ok: false, status: 409, code: "elsewhere", error: "This link is open on another device." };
225
+ }
226
+ return { ok: false, status: 410, code: bound ? this.#state(bound) : "missing", error: "This link has ended." };
227
+ }
228
+ this.#arm(row.id, bound.expires_at);
229
+ this.#hold(row.id);
230
+ this.#options.print("desktop page started", { link: linkId(row), desktop: sizeText(layout) });
231
+ return { ok: true, secret: fresh, view: this.#view(bound, fresh) };
232
+ }
233
+ /** Another link that a person uses on this screen now, of this bot or another one; undefined when there is none. */
234
+ async #busy(id) {
235
+ const other = await this.#sql.get("SELECT id FROM bot_desktop_links WHERE state = 'started' AND expires_at > ? AND id != ?", this.#clock(), id);
236
+ if (other)
237
+ return linkId(other);
238
+ const key = this.#options.screen()?.key;
239
+ if (key === undefined)
240
+ return undefined;
241
+ try {
242
+ const lease = this.#leases().holder(key);
243
+ const link = lease ? /^desktop:(D\d+)$/.exec(lease.conversation)?.[1] : undefined;
244
+ if (link && !(lease.bot === this.#options.dir && link === `D${id}`))
245
+ return lease.bot === this.#options.dir ? link : `${link} of ${lease.name}`;
246
+ }
247
+ catch (error) {
248
+ this.#options.print("could not read the screen lease", { error: String(error) });
249
+ }
250
+ return undefined;
251
+ }
252
+ /** The person handed the desktop back: done, or they could not do the step. */
253
+ async end(token, secret, how, note) {
254
+ const row = await this.#row(token);
255
+ if (!row)
256
+ return { ok: false, status: 404, error: "This link does not work." };
257
+ if (!this.#mine(row, secret))
258
+ return { ok: false, status: 403, error: "Only the device that pressed Start can hand the desktop back." };
259
+ if (this.#state(row) !== "started")
260
+ return { ok: false, status: 410, error: "This link has ended." };
261
+ const text = note.replace(/\r\n?/g, "\n").replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g, " ").trim().slice(0, MAX_NOTE);
262
+ const restored = await this.#finish(row.id, how, text || null);
263
+ return { ok: true, restored: restored === "set" };
264
+ }
265
+ /** pots page unlink: by link ID (D3) or token. The link ID, or undefined when it is not a desktop link of this bot. */
266
+ async revoke(link) {
267
+ const number = /^D(\d+)$/.exec(link);
268
+ const row = number
269
+ ? await this.#sql.get("SELECT * FROM bot_desktop_links WHERE id = ?", Number(number[1]))
270
+ : /^[A-Za-z0-9_-]{16,128}$/.test(link)
271
+ ? await this.#row(link)
272
+ : undefined;
273
+ if (!row || row.state === "revoked")
274
+ return undefined;
275
+ await this.#finish(row.id, "revoked", null);
276
+ return linkId(row);
277
+ }
278
+ /** For pots page list: the links of the last 7 days. */
279
+ async list() {
280
+ const rows = await this.#sql.all("SELECT * FROM bot_desktop_links WHERE state != 'revoked' ORDER BY id");
281
+ return rows.map((row) => ({
282
+ link: linkId(row),
283
+ token: row.token,
284
+ for: row.made_for,
285
+ text: row.text,
286
+ created: row.created_at,
287
+ expires: row.expires_at,
288
+ state: this.#state(row),
289
+ started: row.started_at,
290
+ ended: row.ended_at,
291
+ connected: (this.#live.get(row.id)?.streams.size ?? 0) > 0,
292
+ }));
293
+ }
294
+ // ---- Ends ----
295
+ #liveOf(id) {
296
+ let live = this.#live.get(id);
297
+ if (!live) {
298
+ live = { streams: new Set(), queue: Promise.resolve() };
299
+ this.#live.set(id, live);
300
+ }
301
+ return live;
302
+ }
303
+ /** Run checkExpiry when the link's time comes. */
304
+ #arm(id, expiresAt) {
305
+ if (this.#stopped)
306
+ return;
307
+ const live = this.#liveOf(id);
308
+ clearTimeout(live.timer);
309
+ live.timer = setTimeout(() => void this.checkExpiry(), Math.max(0, expiresAt - this.#clock()) + 50).unref();
310
+ }
311
+ /** End the live links whose time has come. The timers call it; tests that move the clock call it too. */
312
+ async checkExpiry() {
313
+ const due = await this.#sql.all("SELECT * FROM bot_desktop_links WHERE state IN ('open', 'started') AND expires_at <= ?", this.#clock());
314
+ for (const row of due)
315
+ await this.#finish(row.id, "expired", null);
316
+ }
317
+ /**
318
+ * End a link: its new state goes into the table first, so a crash after it finishes the rest at the next start. Then
319
+ * its connections close, the desktop's size is set back to the one at Start, the screen lease goes, and the bot is
320
+ * woken, but not for a link it took back itself. The result of setting the size back, when the link was started.
321
+ */
322
+ async #finish(id, state, note) {
323
+ const now = this.#clock();
324
+ const ended = await this.#sql.transaction(async (tx) => {
325
+ const row = await tx.get("SELECT * FROM bot_desktop_links WHERE id = ?", id);
326
+ if (!row || (row.state !== "open" && row.state !== "started"))
327
+ return undefined;
328
+ await tx.run("UPDATE bot_desktop_links SET state = ?, ended_at = ?, note = ? WHERE id = ?", state, now, note, id);
329
+ return { ...row, state, ended_at: now, note };
330
+ });
331
+ if (!ended)
332
+ return undefined;
333
+ const live = this.#live.get(id);
334
+ this.#live.delete(id);
335
+ if (live) {
336
+ clearTimeout(live.timer);
337
+ clearTimeout(live.restoreTimer);
338
+ for (const stream of live.streams)
339
+ stream.close(4000, `link ${state}`);
340
+ }
341
+ this.#options.print("desktop page ended", { link: linkId(ended), state });
342
+ return this.#settle(ended, live);
343
+ }
344
+ /** The steps after a link ended: set the size back, give the screen back, wake the bot. Each step is recorded. */
345
+ async #settle(row, live) {
346
+ let restored;
347
+ if (row.started_at !== null && row.restored_at === null) {
348
+ if (live)
349
+ await live.queue.catch(() => { });
350
+ restored = await this.#restore(row);
351
+ await this.#sql.run("UPDATE bot_desktop_links SET restored_at = ? WHERE id = ?", this.#clock(), row.id);
352
+ }
353
+ this.#letGo(row.id, live);
354
+ if (row.state !== "revoked" && row.woken_at === null) {
355
+ try {
356
+ await this.#options.wake(this.#endNote(row, restored), `desktop:${linkId(row)}`);
357
+ await this.#sql.run("UPDATE bot_desktop_links SET woken_at = ? WHERE id = ?", this.#clock(), row.id);
358
+ }
359
+ catch (error) {
360
+ this.#options.print("desktop page wake failed", { link: linkId(row), error: String(error) });
361
+ this.#retryWakes();
362
+ }
363
+ }
364
+ return restored;
365
+ }
366
+ /** Set the wakes that failed after a while, and again while one fails; the next start does too. */
367
+ #retryWakes() {
368
+ if (this.#wakeRetry || this.#stopped)
369
+ return;
370
+ this.#wakeRetry = setTimeout(() => {
371
+ this.#wakeRetry = undefined;
372
+ void this.#sql
373
+ .all("SELECT * FROM bot_desktop_links WHERE state IN ('done', 'cannot', 'expired') AND woken_at IS NULL")
374
+ .then(async (rows) => {
375
+ for (const row of rows)
376
+ await this.#settle(row, undefined);
377
+ })
378
+ .catch((error) => {
379
+ this.#options.print("desktop page wake failed", { error: String(error) });
380
+ this.#retryWakes();
381
+ });
382
+ }, desktopTimes.wakeRetryMs).unref();
383
+ }
384
+ #endNote(row, restored) {
385
+ const link = `link ${linkId(row)} (made for ${madeFor(row.made_for)})`;
386
+ const note = row.note ? ` Their note: ${JSON.stringify(row.note)}.` : " They left no note.";
387
+ const layout = row.layout ? JSON.parse(row.layout) : undefined;
388
+ const size = restored === undefined || !layout
389
+ ? ""
390
+ : restored === "set"
391
+ ? ` Its size is back to ${sizeText(layout)}, as at Start.`
392
+ : restored === "same" || restored === "unsupported"
393
+ ? ""
394
+ : ` Pots could not set its size back to ${sizeText(layout)}, as at Start: ${restored}.`;
395
+ const yours = ` The screen is yours again.${size}`;
396
+ if (row.state === "done")
397
+ return `desktop page: someone handed your desktop back on ${link} and pressed Done: the step is done, they say.${note}${yours}`;
398
+ if (row.state === "cannot")
399
+ return `desktop page: someone handed your desktop back on ${link} without doing the step: they pressed "I can't do it".${note}${yours}`;
400
+ if (row.started_at === null)
401
+ return `desktop page: ${link} expired at ${formatTime(row.expires_at)}: nobody pressed Start within an hour.`;
402
+ return `desktop page: ${link} ended at ${formatTime(row.expires_at)}, ${row.minutes} minutes after Start, and nobody pressed Done.${yours}`;
403
+ }
404
+ /** Set the desktop back to its layout at Start. What happened, in words, or undefined when there was nothing to do. */
405
+ async #restore(row) {
406
+ const layout = row.layout ? JSON.parse(row.layout) : undefined;
407
+ if (!layout?.screens)
408
+ return undefined;
409
+ try {
410
+ const result = await restoreDesktopLayout(this.#target(), layout, VNC_TIMEOUT_MS);
411
+ if (result !== "same")
412
+ this.#options.print("desktop size set back", { link: linkId(row), size: sizeText(layout), result });
413
+ return result;
414
+ }
415
+ catch (error) {
416
+ const reason = error instanceof Error ? error.message : String(error);
417
+ this.#options.print("desktop size not set back", { link: linkId(row), error: reason });
418
+ return reason;
419
+ }
420
+ }
421
+ // ---- The screen ----
422
+ /** The person takes the bot's screen lease, also from an agent that holds it. */
423
+ #hold(id) {
424
+ const live = this.#liveOf(id);
425
+ if (live.lease)
426
+ return;
427
+ const key = this.#options.screen()?.key;
428
+ if (key === undefined)
429
+ return;
430
+ try {
431
+ live.lease = this.#leases().seize(key, {
432
+ bot: this.#options.dir,
433
+ name: this.#options.name(),
434
+ agent: `a person, through desktop page link D${id}`,
435
+ conversation: desktopHolder(`D${id}`),
436
+ });
437
+ }
438
+ catch (error) {
439
+ this.#options.print("could not take the screen for a desktop page", { link: `D${id}`, error: String(error) });
440
+ }
441
+ }
442
+ #letGo(id, live) {
443
+ const held = live?.lease !== undefined;
444
+ live?.lease?.done();
445
+ if (live)
446
+ live.lease = undefined;
447
+ // A bot with no screen never opened the lease file; it need not open it now.
448
+ if (!held && this.#options.screen()?.key === undefined)
449
+ return;
450
+ try {
451
+ this.#leases().release(this.#options.dir, desktopHolder(`D${id}`));
452
+ }
453
+ catch (error) {
454
+ this.#options.print("could not give the screen back after a desktop page", { link: `D${id}`, error: String(error) });
455
+ }
456
+ }
457
+ // ---- Connections ----
458
+ /**
459
+ * Carry a browser's WebSocket to the VNC server, for a started link of this browser. A new connection takes the place
460
+ * of the one before (another tab, or the page loaded again). False when the link does not take it.
461
+ */
462
+ async attach(token, secret, ws) {
463
+ const row = await this.#row(token);
464
+ if (!row || this.#state(row) !== "started" || !this.#mine(row, secret) || this.#stopped) {
465
+ ws.close(4000, "link not started");
466
+ return false;
467
+ }
468
+ const live = this.#liveOf(row.id);
469
+ clearTimeout(live.restoreTimer);
470
+ for (const stream of live.streams)
471
+ stream.close(4001, "opened again");
472
+ const link = linkId(row);
473
+ let closed = false;
474
+ let socketClose;
475
+ const stream = {
476
+ close: (code, reason) => {
477
+ if (closed)
478
+ return;
479
+ closed = true;
480
+ socketClose?.();
481
+ try {
482
+ ws.close(code, reason);
483
+ }
484
+ catch {
485
+ ws.terminate();
486
+ }
487
+ setTimeout(() => ws.terminate(), 2_000).unref();
488
+ },
489
+ };
490
+ live.streams.add(stream);
491
+ const forget = () => {
492
+ if (!live.streams.delete(stream))
493
+ return;
494
+ // The browser may come back; if it does not, the desktop gets its size back after a while.
495
+ if (live.streams.size === 0 && this.#live.get(row.id) === live && !this.#stopped) {
496
+ clearTimeout(live.restoreTimer);
497
+ live.restoreTimer = setTimeout(() => {
498
+ live.queue = live.queue.then(async () => {
499
+ if (live.streams.size > 0 || this.#live.get(row.id) !== live)
500
+ return;
501
+ const current = await this.#sql.get("SELECT * FROM bot_desktop_links WHERE id = ?", row.id);
502
+ if (current && this.#state(current) === "started")
503
+ await this.#restore(current);
504
+ });
505
+ }, desktopTimes.restoreAfterMs).unref();
506
+ }
507
+ };
508
+ ws.once("close", () => {
509
+ closed = true;
510
+ socketClose?.();
511
+ forget();
512
+ });
513
+ // What the browser sends before the bridge is ready waits in a reader.
514
+ const fromBrowser = new Reader();
515
+ const early = (data) => fromBrowser.push(bytesOf(data));
516
+ ws.on("message", early);
517
+ ws.once("close", () => fromBrowser.fail(new Error("the browser closed the connection")));
518
+ ws.on("error", (error) => this.#options.print("desktop page connection error", { link, error: error.message }));
519
+ await live.queue.catch(() => { });
520
+ if (closed)
521
+ return true;
522
+ let vnc;
523
+ try {
524
+ vnc = await connectVnc(this.#target(), VNC_TIMEOUT_MS);
525
+ }
526
+ catch (error) {
527
+ const reason = error instanceof Error ? error.message : String(error);
528
+ this.#options.print("desktop page lost the desktop", { link, error: reason });
529
+ // The person waits on a page that tries again by itself; the bot may be able to bring the server back.
530
+ await this.#options
531
+ .wake(`desktop page: the person on link ${link} (made for ${madeFor(row.made_for)}) lost your desktop: Pots could not reach it: ${reason}. Their page tries again by itself until the link ends.`, `desktop:${link}:lost`)
532
+ .catch((wakeError) => this.#options.print("desktop page wake failed", { link, error: String(wakeError) }));
533
+ stream.close(4002, "Pots could not reach the desktop");
534
+ return true;
535
+ }
536
+ try {
537
+ socketClose = () => vnc.socket.destroy();
538
+ if (closed) {
539
+ vnc.socket.destroy();
540
+ return true;
541
+ }
542
+ vnc.socket.once("close", () => stream.close(4002, "the VNC server closed the connection"));
543
+ // The browser signs in with no password: Pots has signed in already.
544
+ const browser = { read: (n) => fromBrowser.read(n), write: (data) => ws.send(data) };
545
+ browser.write(Buffer.from("RFB 003.008\n", "latin1"));
546
+ const version = (await browser.read(12)).toString("latin1");
547
+ if (version !== "RFB 003.008\n")
548
+ throw new Error(`the browser speaks ${JSON.stringify(version)}`);
549
+ browser.write(Buffer.from([1, 1]));
550
+ if ((await browser.read(1))[0] !== 1)
551
+ throw new Error("the browser chose a sign-in Pots did not offer");
552
+ browser.write(Buffer.alloc(4));
553
+ // ClientInit: whatever the browser asks, the desktop stays shared with its other viewers.
554
+ await browser.read(1);
555
+ vnc.write(Buffer.from([1]));
556
+ const init = await readServerInit(vnc);
557
+ browser.write(init.bytes);
558
+ // From here on, bytes go both ways as they come.
559
+ ws.off("message", early);
560
+ const rest = fromBrowser.take();
561
+ if (rest.length > 0)
562
+ vnc.write(rest);
563
+ ws.on("message", (data) => {
564
+ if (!vnc.socket.write(bytesOf(data))) {
565
+ ws.pause();
566
+ vnc.socket.once("drain", () => ws.resume());
567
+ }
568
+ });
569
+ let waiting;
570
+ vnc.handOver((chunk) => {
571
+ if (closed)
572
+ return;
573
+ ws.send(chunk);
574
+ if (ws.bufferedAmount > HIGH_WATER && !waiting) {
575
+ vnc.socket.pause();
576
+ waiting = setInterval(() => {
577
+ if (!closed && ws.bufferedAmount > HIGH_WATER / 8)
578
+ return;
579
+ clearInterval(waiting);
580
+ waiting = undefined;
581
+ vnc.socket.resume();
582
+ }, 50);
583
+ }
584
+ });
585
+ // Pings keep proxies from closing a quiet connection, and find one whose browser has gone.
586
+ let answered = true;
587
+ ws.on("pong", () => (answered = true));
588
+ const ping = setInterval(() => {
589
+ if (!answered)
590
+ return stream.close(4003, "the browser stopped answering");
591
+ answered = false;
592
+ ws.ping();
593
+ }, desktopTimes.pingMs);
594
+ ws.once("close", () => {
595
+ clearInterval(ping);
596
+ clearInterval(waiting);
597
+ vnc.socket.destroy();
598
+ });
599
+ this.#options.print("desktop page connected", { link, desktop: `${init.width}×${init.height}` });
600
+ }
601
+ catch (error) {
602
+ const reason = error instanceof Error ? error.message : String(error);
603
+ if (!closed)
604
+ this.#options.print("desktop page connection failed", { link, error: reason });
605
+ stream.close(4002, reason.slice(0, 120));
606
+ }
607
+ return true;
608
+ }
609
+ // ---- Start and stop ----
610
+ /**
611
+ * At a start, before the agents run: a person who had a started link keeps the screen, as before the stop. The
612
+ * page connects again by itself.
613
+ */
614
+ async holdScreens() {
615
+ const rows = await this.#sql.all("SELECT * FROM bot_desktop_links WHERE state = 'started' AND expires_at > ?", this.#clock());
616
+ for (const row of rows)
617
+ this.#hold(row.id);
618
+ }
619
+ /**
620
+ * After a start: end the links whose time came while Pots was stopped, finish ends a stop or a crash cut off (the
621
+ * size, the screen, the wake), and set the timers of the others.
622
+ */
623
+ async resume() {
624
+ for (const row of await this.#sql.all("SELECT * FROM bot_desktop_links WHERE state IN ('open', 'started')"))
625
+ this.#arm(row.id, row.expires_at);
626
+ await this.checkExpiry();
627
+ const unfinished = await this.#sql.all("SELECT * FROM bot_desktop_links WHERE state IN ('done', 'cannot', 'expired', 'revoked') AND ((started_at IS NOT NULL AND restored_at IS NULL) OR (state != 'revoked' AND woken_at IS NULL))");
628
+ for (const row of unfinished)
629
+ await this.#settle(row, undefined);
630
+ }
631
+ /** The gateway stops: close the connections, and set the desktop's size back. The links stay; after the start they go on. */
632
+ async stop() {
633
+ this.#stopped = true;
634
+ clearTimeout(this.#wakeRetry);
635
+ const lives = [...this.#live.entries()];
636
+ for (const [, live] of lives) {
637
+ clearTimeout(live.timer);
638
+ clearTimeout(live.restoreTimer);
639
+ for (const stream of live.streams)
640
+ stream.close(1012, "Pots is restarting");
641
+ }
642
+ await Promise.all(lives.map(async ([id, live]) => {
643
+ await live.queue.catch(() => { });
644
+ const row = await this.#sql.get("SELECT * FROM bot_desktop_links WHERE id = ?", id).catch(() => undefined);
645
+ if (row && row.state === "started")
646
+ await this.#restore(row);
647
+ this.#letGo(id, live);
648
+ }));
649
+ this.#live.clear();
650
+ }
651
+ /** Forget desktop links 7 days after they were made, once they ended. */
652
+ async cleanup() {
653
+ await this.#sql.run("DELETE FROM bot_desktop_links WHERE created_at < ? AND state NOT IN ('open', 'started') AND (started_at IS NULL OR restored_at IS NOT NULL) AND (state = 'revoked' OR woken_at IS NOT NULL)", this.#clock() - KEEP_MS);
654
+ }
655
+ }
656
+ function bytesOf(data) {
657
+ if (Buffer.isBuffer(data))
658
+ return data;
659
+ if (Array.isArray(data))
660
+ return Buffer.concat(data);
661
+ return Buffer.from(data);
662
+ }
663
+ /** --area x,y,width,height: whole numbers, in the desktop's pixels. */
664
+ function parseArea(text) {
665
+ const parts = text.split(",").map((part) => part.trim());
666
+ const numbers = parts.map(Number);
667
+ if (parts.length !== 4 || numbers.some((value) => !Number.isInteger(value) || value < 0 || value > 65_535) || numbers[2] === 0 || numbers[3] === 0) {
668
+ throw new Error(`bad --area ${JSON.stringify(text)}: x,y,width,height in your screen's pixels, such as 440,300,400,260`);
669
+ }
670
+ return numbers;
671
+ }
672
+ //# sourceMappingURL=desktop.js.map