pi-pocket 0.29.0 → 0.30.0-beta.2

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/README.md +58 -1
  2. package/SECURITY.md +1 -0
  3. package/docs/architecture.md +9 -4
  4. package/docs/desktop-app.md +54 -0
  5. package/docs/examples/approval-monitor.ts +82 -0
  6. package/docs/extensions/people-values.md +8 -0
  7. package/docs/extensions/policies/api-stability.md +1 -0
  8. package/docs/extensions/reference/api-versions.md +3 -0
  9. package/docs/extensions/reference/host.md +92 -1
  10. package/docs/extensions/tools.md +1 -0
  11. package/docs/features.md +4 -4
  12. package/docs/index.md +3 -0
  13. package/docs/macos.md +90 -0
  14. package/docs/map.md +9 -5
  15. package/docs/windows.md +73 -0
  16. package/npm-shrinkwrap.json +71 -67
  17. package/package.json +9 -9
  18. package/src/launcher/desktop.ts +45 -0
  19. package/src/launcher/main.ts +81 -17
  20. package/src/launcher/options.ts +59 -2
  21. package/src/server/alerts.ts +2 -2
  22. package/src/server/app.ts +2 -0
  23. package/src/server/auth.ts +40 -0
  24. package/src/server/background.ts +109 -241
  25. package/src/server/commands.ts +28 -17
  26. package/src/server/design/scan-fig-container.ts +3 -2
  27. package/src/server/design/scan-files.ts +3 -11
  28. package/src/server/design/system.ts +3 -4
  29. package/src/server/design/tokens-io.ts +2 -3
  30. package/src/server/docs.ts +9 -0
  31. package/src/server/errors.ts +12 -0
  32. package/src/server/extension-document-compat.ts +4 -0
  33. package/src/server/extensions/artifacts.ts +2 -6
  34. package/src/server/extensions/codemode.ts +27 -1
  35. package/src/server/extensions/guard.ts +9 -1
  36. package/src/server/extensions/pocket-relay/files.ts +10 -3
  37. package/src/server/extensions/pocket-relay/runtime.ts +6 -0
  38. package/src/server/extensions/pocket-relay.ts +31 -3
  39. package/src/server/extensions/schedules.ts +9 -2
  40. package/src/server/host.ts +25 -0
  41. package/src/server/http/api.ts +21 -4
  42. package/src/server/http/browser-routes.ts +5 -2
  43. package/src/server/http/conversation-routes.ts +4 -3
  44. package/src/server/http/events.ts +9 -4
  45. package/src/server/http/io.ts +5 -2
  46. package/src/server/http/sign-in.ts +9 -3
  47. package/src/server/limit-gate.ts +257 -65
  48. package/src/server/limits.ts +80 -4
  49. package/src/server/main.ts +71 -16
  50. package/src/server/no-follow.ts +67 -0
  51. package/src/server/pending-approvals.ts +174 -0
  52. package/src/server/processes.ts +1480 -0
  53. package/src/server/projection.ts +7 -6
  54. package/src/server/room.ts +2 -0
  55. package/src/server/schedules.ts +226 -4
  56. package/src/server/secrets.ts +6 -4
  57. package/src/server/socket-path.ts +167 -0
  58. package/src/server/themes.ts +2 -4
  59. package/src/server/worktrees.ts +16 -17
  60. package/types/pocket.d.ts +74 -0
  61. package/web/agent-now.js +2 -2
  62. package/web/notify.js +1 -5
  63. package/web/peeks.js +1 -1
  64. package/web/sessions.js +2 -3
  65. package/web/sheets/schedules.js +18 -0
  66. package/web/store.js +126 -13
  67. package/web/transcript.js +4 -30
@@ -0,0 +1,45 @@
1
+ /**
2
+ * What the desktop apps (packaging/windows, packaging/macos) read from a launcher: `launcher-running.json` in the data folder
3
+ * says which launcher runs and where its server answers on this machine. The launcher writes it each time its server
4
+ * is ready and removes it when it quits. It holds no secret: the apps sign in with a one-time link
5
+ * (docs/desktop-app.md). Installed apps read it across versions, so its fields only ever grow.
6
+ */
7
+ import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+
10
+ export const RUNNING_FILE = "launcher-running.json";
11
+
12
+ export interface Running {
13
+ version: 1;
14
+ /** The launcher's process. */
15
+ pid: number;
16
+ /** The server's address for a browser on this machine, such as `http://127.0.0.1:8787`; null on a Unix socket. */
17
+ url: string | null;
18
+ /** Started by a desktop app (`--desktop`), which stops it when it quits. */
19
+ desktop: boolean;
20
+ }
21
+
22
+ export function writeRunning(data: string, running: Running): void {
23
+ const file = join(data, RUNNING_FILE);
24
+ const temp = `${file}.${process.pid}.tmp`;
25
+
26
+ writeFileSync(temp, `${JSON.stringify(running)}\n`, { mode: 0o600 });
27
+ renameSync(temp, file);
28
+ }
29
+
30
+ export function readRunning(data: string): Running | undefined {
31
+ try {
32
+ const running = JSON.parse(readFileSync(join(data, RUNNING_FILE), "utf8")) as Running;
33
+
34
+ return Number.isInteger(running?.pid) ? running : undefined;
35
+ } catch {
36
+ return undefined;
37
+ }
38
+ }
39
+
40
+ /** Remove the file if launcher `pid` wrote it: a launcher that failed to start must not remove the running one's. */
41
+ export function removeRunning(data: string, pid: number): void {
42
+ if (readRunning(data)?.pid === pid) {
43
+ rmSync(join(data, RUNNING_FILE), { force: true });
44
+ }
45
+ }
@@ -5,6 +5,7 @@
5
5
  *
6
6
  * pi-pocket [--access local|lan|cloudflare|tailscale|tailscale-serve] [-y] [--port 8787] [--cwd DIR] [--data DIR]
7
7
  * [--rotate-token]
8
+ * pi-pocket --socket PATH [--cwd DIR] [--data DIR] [--rotate-token] (behind a reverse proxy, no access mode)
8
9
  */
9
10
  import { type ChildProcess, spawn } from "node:child_process";
10
11
  import { once } from "node:events";
@@ -30,6 +31,7 @@ import {
30
31
  TAILSCALE_MISSING_MESSAGE,
31
32
  tailscaleAddress,
32
33
  } from "./access.ts";
34
+ import { RUNNING_FILE, removeRunning, writeRunning } from "./desktop.ts";
33
35
  import { fail, parseArgs } from "./options.ts";
34
36
  import { removeStaleServe, TailscaleServe } from "./serve.ts";
35
37
  // The two server modules the launcher runs itself: both import only Node's own, so an update cannot break the launcher.
@@ -132,6 +134,11 @@ function loadSettings(): { access?: AccessMode } {
132
134
  }
133
135
 
134
136
  function saveSettings(access: AccessMode): void {
137
+ // The desktop app's own choice (this device only, unless it says otherwise) is not the console's last choice.
138
+ if (options.desktop) {
139
+ return;
140
+ }
141
+
135
142
  try {
136
143
  writeFileSync(settingsFile, `${JSON.stringify({ access }, null, "\t")}\n`, { mode: 0o600 });
137
144
  } catch (error) {
@@ -375,7 +382,7 @@ async function ensureCloudflared(): Promise<string | undefined> {
375
382
 
376
383
  // ─── State ──────────────────────────────────────────────────────────────
377
384
 
378
- type Mode = AccessMode | "custom";
385
+ type Mode = AccessMode | "custom" | "socket";
379
386
 
380
387
  const state = {
381
388
  mode: "local" as Mode,
@@ -434,6 +441,10 @@ function localUrl(): string {
434
441
  }
435
442
 
436
443
  function modeLabel(): string {
444
+ if (state.mode === "socket") {
445
+ return "Reverse proxy (Unix socket)";
446
+ }
447
+
437
448
  if (state.mode === "custom") {
438
449
  return `Listening on ${state.host}`;
439
450
  }
@@ -456,6 +467,8 @@ function modeNote(): string {
456
467
  return "devices on your tailnet";
457
468
  case "tailscale-serve":
458
469
  return state.accessUrl === undefined ? "serve not up yet" : "https on your tailnet";
470
+ case "socket":
471
+ return options.socket!;
459
472
  default:
460
473
  return "";
461
474
  }
@@ -492,7 +505,10 @@ function sendAccess(): void {
492
505
 
493
506
  // ─── The panel ──────────────────────────────────────────────────────────
494
507
 
495
- const KEYS_HINT = "q quit · r restart server · a access · o open here · s sign-in QR";
508
+ const KEYS_HINT =
509
+ options.socket === undefined
510
+ ? "q quit · r restart server · a access · o open here · s sign-in QR"
511
+ : "q quit · r restart server · s sign-in path";
496
512
 
497
513
  async function showPanel(withQr: boolean): Promise<void> {
498
514
  const width = columns();
@@ -500,7 +516,9 @@ async function showPanel(withQr: boolean): Promise<void> {
500
516
  const lines = ["", ` ${accent("π")} ${bold("Pi Pocket")} ${green("● running")}`, ""];
501
517
 
502
518
  lines.push(row("Access", `${modeLabel()}${modeNote() ? dim(` · ${modeNote()}`) : ""}`));
503
- lines.push(row("Open", cyan(appUrl())));
519
+ lines.push(
520
+ row("Open", state.mode === "socket" ? dim("your reverse proxy's address") : cyan(appUrl())),
521
+ );
504
522
 
505
523
  if (state.mode === "lan") {
506
524
  for (const address of lanAddresses().slice(1)) {
@@ -516,7 +534,11 @@ async function showPanel(withQr: boolean): Promise<void> {
516
534
  const base = (reachable() ? appUrl() : localUrl()).replace(/\/+$/, "");
517
535
  const login = state.loginPath === undefined ? undefined : `${base}${state.loginPath}`;
518
536
 
519
- if (login !== undefined) {
537
+ // No http link reaches a Unix socket, so no QR code.
538
+ if (state.mode === "socket" && state.loginPath !== undefined) {
539
+ lines.push(row("Sign in", `${state.loginPath} ${dim("at your reverse proxy's address")}`));
540
+ lines.push("");
541
+ } else if (login !== undefined) {
520
542
  if (withQr && reachable()) {
521
543
  lines.push(
522
544
  ` ${bold("Scan to sign in on your phone.")} ${dim("It is your owner link: keep it private.")}`,
@@ -560,6 +582,14 @@ function maybeShowPanel(): void {
560
582
  }
561
583
 
562
584
  state.panelPending = false;
585
+
586
+ // No sign-in link and no QR code: what the desktop app prints goes to a log file. Its window signs in by itself.
587
+ if (options.desktop) {
588
+ log(green(` ✓ Pi Pocket is ready at ${localUrl()}.`));
589
+
590
+ return;
591
+ }
592
+
563
593
  void showPanel(true);
564
594
  }
565
595
 
@@ -575,10 +605,9 @@ function startServer(first: boolean): void {
575
605
 
576
606
  const args = [
577
607
  SERVER,
578
- "--host",
579
- state.host,
580
- "--port",
581
- String(options.port),
608
+ ...(state.mode === "socket"
609
+ ? ["--socket", options.socket!]
610
+ : ["--host", state.host, "--port", String(options.port)]),
582
611
  "--cwd",
583
612
  options.cwd,
584
613
  "--data",
@@ -636,6 +665,7 @@ function startServer(first: boolean): void {
636
665
 
637
666
  state.everReady = true;
638
667
  sendAccess();
668
+ noteRunning();
639
669
 
640
670
  if (state.panelPending) {
641
671
  maybeShowPanel();
@@ -731,6 +761,20 @@ function startServer(first: boolean): void {
731
761
  });
732
762
  }
733
763
 
764
+ /** Say in the data folder where this launcher's server answers, for the desktop app (`desktop.ts`). */
765
+ function noteRunning(): void {
766
+ try {
767
+ writeRunning(options.data, {
768
+ version: 1,
769
+ pid: process.pid,
770
+ url: state.mode === "socket" ? null : localUrl(),
771
+ desktop: options.desktop,
772
+ });
773
+ } catch (error) {
774
+ log(yellow(` Could not write ${RUNNING_FILE}: ${(error as Error).message}`));
775
+ }
776
+ }
777
+
734
778
  function restartServer(): void {
735
779
  if (child === undefined) {
736
780
  return;
@@ -1000,7 +1044,7 @@ async function changeAccess(): Promise<void> {
1000
1044
  log("");
1001
1045
 
1002
1046
  try {
1003
- const current = state.mode === "custom" ? undefined : state.mode;
1047
+ const current = state.mode === "custom" || state.mode === "socket" ? undefined : state.mode;
1004
1048
  const next = await pickAccess(current);
1005
1049
 
1006
1050
  if (next === undefined || next === state.mode) {
@@ -1051,11 +1095,11 @@ function onRunKey(key: string): void {
1051
1095
  void quit(0);
1052
1096
  } else if (key === "r") {
1053
1097
  restartServer();
1054
- } else if (key === "o" && state.loginPath !== undefined) {
1098
+ } else if (key === "o" && state.loginPath !== undefined && state.mode !== "socket") {
1055
1099
  openInBrowser(`${localUrl()}${state.loginPath}`);
1056
1100
  } else if (key === "s") {
1057
1101
  void showPanel(true);
1058
- } else if (key === "a") {
1102
+ } else if (key === "a" && state.mode !== "socket") {
1059
1103
  busyWithKey = true;
1060
1104
  void changeAccess().finally(() => {
1061
1105
  busyWithKey = false;
@@ -1100,9 +1144,24 @@ if (process.platform !== "win32") {
1100
1144
 
1101
1145
  process.on("exit", () => {
1102
1146
  restoreTerminal();
1147
+
1148
+ try {
1149
+ removeRunning(options.data, process.pid);
1150
+ } catch {
1151
+ // The desktop app checks that the launcher it names still runs.
1152
+ }
1153
+
1103
1154
  releaseLauncherLock();
1104
1155
  });
1105
1156
 
1157
+ // The desktop app holds the other end of standard input: when it quits, or crashes, the launcher stops with it.
1158
+ if (options.desktop) {
1159
+ process.stdin.on("error", () => {});
1160
+ process.stdin.on("end", () => void quit(0));
1161
+ process.stdin.on("close", () => void quit(0));
1162
+ process.stdin.resume();
1163
+ }
1164
+
1106
1165
  // ─── Start ──────────────────────────────────────────────────────────────
1107
1166
 
1108
1167
  async function main(): Promise<void> {
@@ -1124,6 +1183,7 @@ async function main(): Promise<void> {
1124
1183
  // are problems to report when serve is prepared, not reasons to refuse to launch. `--host` alone never uses serve,
1125
1184
  // so a saved choice is not a reason to refuse to start there either.
1126
1185
  if (
1186
+ options.socket === undefined &&
1127
1187
  serveBailOut({
1128
1188
  access: options.access,
1129
1189
  saved: settings.access,
@@ -1135,7 +1195,7 @@ async function main(): Promise<void> {
1135
1195
  fail(TAILSCALE_MISSING_MESSAGE);
1136
1196
  }
1137
1197
 
1138
- let mode: Mode | undefined = options.access;
1198
+ let mode: Mode | undefined = options.socket === undefined ? options.access : "socket";
1139
1199
 
1140
1200
  if (mode === undefined && options.host !== undefined) {
1141
1201
  mode = loopback(options.host) ? "local" : wildcard(options.host) ? "lan" : "custom";
@@ -1152,7 +1212,7 @@ async function main(): Promise<void> {
1152
1212
  try {
1153
1213
  let binary: string | undefined;
1154
1214
 
1155
- if (mode !== "custom") {
1215
+ if (mode !== "custom" && mode !== "socket") {
1156
1216
  const chosen = await chooseAccess({
1157
1217
  given: mode,
1158
1218
  saved: settings.access,
@@ -1179,9 +1239,9 @@ async function main(): Promise<void> {
1179
1239
  }
1180
1240
 
1181
1241
  state.mode = mode;
1182
- state.host = listenHost(mode, options.host);
1242
+ state.host = mode === "socket" ? "127.0.0.1" : listenHost(mode, options.host);
1183
1243
 
1184
- if (mode !== "custom") {
1244
+ if (mode !== "custom" && mode !== "socket") {
1185
1245
  saveSettings(mode);
1186
1246
  }
1187
1247
 
@@ -1189,7 +1249,9 @@ async function main(): Promise<void> {
1189
1249
  // answering 502. Clear it before this run needs the port, whichever mode it starts in. Only a mount with a
1190
1250
  // receipt is ours: a port alone proves nothing, since 0.27's docs had owners point `tailscale serve` at
1191
1251
  // `--access local` themselves. Never for `tailscale-serve` itself, whose mount prepareServe() made or adopted.
1192
- const stalePorts = staleServePorts(mode, savedServeMountPort());
1252
+ // On a socket no `tailscale serve` runs, not even to clear a stale mount: the node's Serve route may now be the
1253
+ // one that reaches this socket. The receipt stays for a later start on a port.
1254
+ const stalePorts = mode === "socket" ? [] : staleServePorts(mode, savedServeMountPort());
1193
1255
 
1194
1256
  if (stalePorts.length > 0) {
1195
1257
  const tailscale = findTailscale();
@@ -1226,7 +1288,9 @@ async function main(): Promise<void> {
1226
1288
  startTunnel(binary);
1227
1289
  }
1228
1290
 
1229
- onKeys(onRunKey);
1291
+ if (!options.desktop) {
1292
+ onKeys(onRunKey);
1293
+ }
1230
1294
  } catch (error) {
1231
1295
  stopServe();
1232
1296
 
@@ -1,6 +1,7 @@
1
1
  /** The launcher's command line: its options, from arguments and the environment, and its help. */
2
2
  import { homedir } from "node:os";
3
3
  import { join, resolve } from "node:path";
4
+ import { parseSocketPath, socketArgument } from "../server/socket-path.ts";
4
5
  import { ACCESS_MODES, type AccessMode, isAccessMode } from "./access.ts";
5
6
  import { restoreTerminal } from "./term.ts";
6
7
 
@@ -22,19 +23,28 @@ Usage: pi-pocket [options]
22
23
  --host HOST Listen on this address instead of choosing an access mode; it overrides the
23
24
  address a named mode would pick, except with --access tailscale-serve, which
24
25
  always listens on 127.0.0.1
26
+ --socket PATH Listen on this Unix socket, for a reverse proxy on this machine, instead of an
27
+ address and an access mode. Its folder must be owned by you or root and writable
28
+ by no one else (see Remote access in the README)
25
29
  --rotate-token Replace the owner sign-in link, signing out the devices that used it
30
+ --desktop For the desktop app: this device only (unless --access says otherwise), no menu,
31
+ no keys, no sign-in link or QR code, and it stops when its input closes. The
32
+ access choice is not saved
26
33
  -h, --help Show this help
27
34
 
28
- Environment: PI_POCKET_ACCESS, PI_POCKET_PORT, PI_POCKET_DIR, PI_POCKET_HOST, PI_POCKET_GUARD=off`;
35
+ Environment: PI_POCKET_ACCESS, PI_POCKET_PORT, PI_POCKET_DIR, PI_POCKET_HOST, PI_POCKET_SOCKET,
36
+ PI_POCKET_GUARD=off`;
29
37
 
30
38
  export interface Options {
31
39
  access: AccessMode | undefined;
32
40
  yes: boolean;
33
41
  host: string | undefined;
34
42
  port: number;
43
+ socket: string | undefined;
35
44
  cwd: string;
36
45
  data: string;
37
46
  rotateToken: boolean;
47
+ desktop: boolean;
38
48
  }
39
49
 
40
50
  export function parseArgs(argv: string[]): Options {
@@ -44,10 +54,16 @@ export function parseArgs(argv: string[]): Options {
44
54
  yes: false,
45
55
  host: process.env.PI_POCKET_HOST || undefined,
46
56
  port: Number(process.env.PI_POCKET_PORT ?? 8787),
57
+ socket: process.env.PI_POCKET_SOCKET,
47
58
  cwd: process.cwd(),
48
59
  data: resolve(process.env.PI_POCKET_DIR ?? join(homedir(), ".pi-pocket")),
49
60
  rotateToken: false,
61
+ desktop: false,
50
62
  };
63
+ let accessGiven = false;
64
+ let hostGiven = false;
65
+ let socketGiven = false;
66
+ const tcpFlags: string[] = [];
51
67
 
52
68
  for (let index = 0; index < argv.length; index++) {
53
69
  const arg = argv[index]!;
@@ -70,18 +86,33 @@ export function parseArgs(argv: string[]): Options {
70
86
  }
71
87
 
72
88
  options.access = mode as AccessMode;
89
+ accessGiven = true;
90
+ tcpFlags.push(arg);
73
91
  } else if (arg === "--yes" || arg === "-y") {
74
92
  options.yes = true;
75
93
  } else if (arg === "--host") {
76
94
  options.host = value();
95
+ hostGiven = true;
96
+ tcpFlags.push(arg);
77
97
  } else if (arg === "--port" || arg === "-p") {
78
98
  options.port = Number(value());
99
+ tcpFlags.push(arg);
100
+ } else if (arg === "--socket") {
101
+ socketGiven = true;
102
+
103
+ try {
104
+ options.socket = socketArgument(value());
105
+ } catch (error) {
106
+ fail((error as Error).message);
107
+ }
79
108
  } else if (arg === "--cwd") {
80
109
  options.cwd = resolve(value());
81
110
  } else if (arg === "--data") {
82
111
  options.data = resolve(value());
83
112
  } else if (arg === "--rotate-token") {
84
113
  options.rotateToken = true;
114
+ } else if (arg === "--desktop") {
115
+ options.desktop = true;
85
116
  } else if (arg === "--help" || arg === "-h") {
86
117
  console.log(HELP);
87
118
  process.exit(0);
@@ -90,7 +121,33 @@ export function parseArgs(argv: string[]): Options {
90
121
  }
91
122
  }
92
123
 
93
- if (!Number.isInteger(options.port) || options.port <= 0 || options.port > 65535) {
124
+ if (options.desktop) {
125
+ if (socketGiven) {
126
+ fail("--desktop cannot be combined with --socket: the app window needs an address");
127
+ }
128
+
129
+ // The app window is on this machine: it shares nothing with other devices unless its own arguments say so. The
130
+ // environment of a login shell (PI_POCKET_ACCESS, PI_POCKET_HOST, PI_POCKET_SOCKET) does not count.
131
+ options.yes = true;
132
+ options.access = accessGiven ? options.access : "local";
133
+ options.host = hostGiven ? options.host : undefined;
134
+ options.socket = undefined;
135
+ }
136
+
137
+ try {
138
+ options.socket = parseSocketPath(options.socket);
139
+ } catch (error) {
140
+ fail((error as Error).message);
141
+ }
142
+
143
+ if (options.socket !== undefined && tcpFlags.length > 0) {
144
+ fail(`--socket cannot be combined with ${tcpFlags[0]}`);
145
+ }
146
+
147
+ if (
148
+ options.socket === undefined &&
149
+ (!Number.isInteger(options.port) || options.port <= 0 || options.port > 65535)
150
+ ) {
94
151
  fail("--port must be a port number");
95
152
  }
96
153
 
@@ -170,7 +170,7 @@ export class Alerts {
170
170
  }
171
171
 
172
172
  /**
173
- * A run began to wait a long while for its provider's limit to clear: one push to the people in its session, who may
173
+ * A run began a long wait before a retry: one push to the people in its session, who may
174
174
  * want to come back at the time, or stop it. When the run ends, "Pi finished" goes as always.
175
175
  */
176
176
  limitWait(conversationId: number, view: WaitView): void {
@@ -186,7 +186,7 @@ export class Alerts {
186
186
  const title = await app.conversationTitle(root);
187
187
  const who = app.sessionMeta(root)?.pip === undefined ? "" : "PiP: ";
188
188
  const message: PushMessage = {
189
- title: `Waiting for a usage limit · ${who}${title}`,
189
+ title: `Waiting to retry · ${who}${title}`,
190
190
  body: snippet(
191
191
  `${view.reason}. Pi tries again in ${span(view.until - Date.now())} and goes on by itself. Open the session to try now or stop.`,
192
192
  400,
package/src/server/app.ts CHANGED
@@ -97,6 +97,7 @@ import {
97
97
  } from "./host.ts";
98
98
  import { type GuardStatus, LancetGuard } from "./lancet.ts";
99
99
  import { takeLock } from "./lock.ts";
100
+ import { pendingApprovalsFor } from "./pending-approvals.ts";
100
101
  import { Memory } from "./memory.ts";
101
102
  import { isThinkingLevel, modelInfo, modelList, resolveModel, THINKING_LEVELS } from "./models.ts";
102
103
  import { Updates } from "./updates.ts";
@@ -886,6 +887,7 @@ export class PocketApp {
886
887
  const host: PocketHost = {
887
888
  guard: this.guard,
888
889
  approvals: this.approvals,
890
+ pendingApprovals: pendingApprovalsFor(this),
889
891
  agentDir: getAgentDir(),
890
892
  dataDir: this.dataDir,
891
893
  pocketVersion: pocketVersion(),
@@ -8,6 +8,11 @@ export const COOKIE = "pocket_auth";
8
8
  export const INVITE_MINUTES = [15, 60, 24 * 60, 7 * 24 * 60] as const;
9
9
  export type InviteMinutes = (typeof INVITE_MINUTES)[number];
10
10
 
11
+ /** How long a one-time sign-in link lasts: the desktop app opens its window with it at once. */
12
+ export const SIGN_IN_LINK_MS = 60_000;
13
+ /** One-time sign-in links that may wait at once; a new one ends the oldest. */
14
+ const SIGN_IN_LINKS = 8;
15
+
11
16
  export function parseCookies(header: string | undefined): Record<string, string> {
12
17
  const out: Record<string, string> = {};
13
18
 
@@ -86,6 +91,8 @@ export type InviteGrant =
86
91
  /** Invites live in `config.json` (by their codes' hashes), so one that lasts a day or a week outlives a restart. */
87
92
  export class Auth {
88
93
  readonly #config: ConfigStore;
94
+ /** One-time sign-in links for the owner: the code, and when it ends. Only in memory, so a restart ends them. */
95
+ readonly #links = new Map<string, number>();
89
96
 
90
97
  constructor(config: ConfigStore) {
91
98
  this.#config = config;
@@ -190,4 +197,37 @@ export class Auth {
190
197
  invite.session === undefined ? undefined : [invite.session],
191
198
  );
192
199
  }
200
+
201
+ /**
202
+ * A one-time sign-in link for the owner, for a window of the desktop app on this machine (docs/desktop-app.md): it
203
+ * signs a browser in once, within `SIGN_IN_LINK_MS`, so the owner's token never goes on a command line.
204
+ */
205
+ createSignInLink(): string {
206
+ const now = Date.now();
207
+
208
+ for (const [code, expiresAt] of this.#links) {
209
+ if (expiresAt <= now || this.#links.size >= SIGN_IN_LINKS) {
210
+ this.#links.delete(code);
211
+ }
212
+ }
213
+
214
+ const code = randomBytes(32).toString("base64url");
215
+
216
+ this.#links.set(code, now + SIGN_IN_LINK_MS);
217
+
218
+ return code;
219
+ }
220
+
221
+ /** The owner's token for a one-time sign-in link that is still live. The link is gone after this, used or not. */
222
+ redeemSignInLink(code: string): string | undefined {
223
+ const expiresAt = this.#links.get(code);
224
+
225
+ if (expiresAt === undefined) {
226
+ return undefined;
227
+ }
228
+
229
+ this.#links.delete(code);
230
+
231
+ return expiresAt > Date.now() ? this.#config.ownerToken : undefined;
232
+ }
193
233
  }