litepaseo 0.1.0 → 0.3.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 (128) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +98 -40
  3. package/dist/server/cli.mjs +1338 -201
  4. package/dist/web/assets/CodeBlockNode-D-c_NpDN.js +3 -0
  5. package/dist/web/assets/CodeBlockNode-D-c_NpDN.js.br +0 -0
  6. package/dist/web/assets/CodeBlockNode-D-c_NpDN.js.gz +0 -0
  7. package/dist/web/assets/FileViewer-C6rgOMRo.js +2 -0
  8. package/dist/web/assets/FileViewer-C6rgOMRo.js.br +0 -0
  9. package/dist/web/assets/FileViewer-C6rgOMRo.js.gz +0 -0
  10. package/dist/web/assets/FileViewer-CljYTF8J.css +1 -0
  11. package/dist/web/assets/FileViewer-CljYTF8J.css.br +0 -0
  12. package/dist/web/assets/FileViewer-CljYTF8J.css.gz +0 -0
  13. package/dist/web/assets/FilesPanel-CNkBvKGD.js +1 -0
  14. package/dist/web/assets/FilesPanel-CNkBvKGD.js.br +0 -0
  15. package/dist/web/assets/FilesPanel-CNkBvKGD.js.gz +0 -0
  16. package/dist/web/assets/FilesPanel-CY9yMixJ.css +1 -0
  17. package/dist/web/assets/FilesPanel-CY9yMixJ.css.br +0 -0
  18. package/dist/web/assets/FilesPanel-CY9yMixJ.css.gz +0 -0
  19. package/dist/web/assets/MarkdownMessage-DjRNZCD0.js +199 -0
  20. package/dist/web/assets/MarkdownMessage-DjRNZCD0.js.br +0 -0
  21. package/dist/web/assets/MarkdownMessage-DjRNZCD0.js.gz +0 -0
  22. package/dist/web/assets/{PreCodeBlock-B2Mi6ata.js → PreCodeBlock-BitPoeXT.js} +1 -1
  23. package/dist/web/assets/{PreCodeBlock.vue_vue_type_style_index_0_lang-Twzt_rFe.js → PreCodeBlock.vue_vue_type_style_index_0_lang-DVJqSz-5.js} +1 -1
  24. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DVJqSz-5.js.br +0 -0
  25. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DVJqSz-5.js.gz +0 -0
  26. package/dist/web/assets/TerminalPanel-CpGnkfa7.js +3 -0
  27. package/dist/web/assets/TerminalPanel-CpGnkfa7.js.br +0 -0
  28. package/dist/web/assets/TerminalPanel-CpGnkfa7.js.gz +0 -0
  29. package/dist/web/assets/TerminalPanel-DvfBWyiQ.css +1 -0
  30. package/dist/web/assets/TerminalPanel-DvfBWyiQ.css.br +0 -0
  31. package/dist/web/assets/TerminalPanel-DvfBWyiQ.css.gz +0 -0
  32. package/dist/web/assets/Tooltip-C9GHriiI.js +1 -0
  33. package/dist/web/assets/Tooltip-C9GHriiI.js.br +0 -0
  34. package/dist/web/assets/Tooltip-C9GHriiI.js.gz +0 -0
  35. package/dist/web/assets/addon-fit-DIOBYJe3.js +1 -0
  36. package/dist/web/assets/addon-fit-DIOBYJe3.js.br +0 -0
  37. package/dist/web/assets/addon-fit-DIOBYJe3.js.gz +0 -0
  38. package/dist/web/assets/index-D4mQel3H.js +30 -0
  39. package/dist/web/assets/index-D4mQel3H.js.br +0 -0
  40. package/dist/web/assets/index-D4mQel3H.js.gz +0 -0
  41. package/dist/web/assets/index-Wf4Xa0ob.css +1 -0
  42. package/dist/web/assets/index-Wf4Xa0ob.css.br +0 -0
  43. package/dist/web/assets/index-Wf4Xa0ob.css.gz +0 -0
  44. package/dist/web/assets/index10-QexvIpKb.js +6 -0
  45. package/dist/web/assets/index10-QexvIpKb.js.br +0 -0
  46. package/dist/web/assets/index10-QexvIpKb.js.gz +0 -0
  47. package/dist/web/assets/index3-B9LRPNVQ.js +1 -0
  48. package/dist/web/assets/index4-CTBFr99S.js +1 -0
  49. package/dist/web/assets/index5-DaBM1kaC.js +1 -0
  50. package/dist/web/assets/index5-DaBM1kaC.js.br +0 -0
  51. package/dist/web/assets/index5-DaBM1kaC.js.gz +0 -0
  52. package/dist/web/assets/{index6-DczfWbCr.js → index6-1dcCVob7.js} +1 -1
  53. package/dist/web/assets/index6-1dcCVob7.js.br +0 -0
  54. package/dist/web/assets/index6-1dcCVob7.js.gz +0 -0
  55. package/dist/web/assets/index7-DGSFcnYT.js +2 -0
  56. package/dist/web/assets/index7-DGSFcnYT.js.br +0 -0
  57. package/dist/web/assets/index7-DGSFcnYT.js.gz +0 -0
  58. package/dist/web/assets/index8-BjPxjipz.js +2 -0
  59. package/dist/web/assets/index8-BjPxjipz.js.br +0 -0
  60. package/dist/web/assets/index8-BjPxjipz.js.gz +0 -0
  61. package/dist/web/assets/index9-VNQsX15e.js +1 -0
  62. package/dist/web/assets/index9-VNQsX15e.js.br +0 -0
  63. package/dist/web/assets/index9-VNQsX15e.js.gz +0 -0
  64. package/dist/web/assets/{vue.runtime.esm-bundler-HH4C0BYQ.js → vue.runtime.esm-bundler-D6xZ1zFq.js} +1 -1
  65. package/dist/web/assets/vue.runtime.esm-bundler-D6xZ1zFq.js.br +0 -0
  66. package/dist/web/assets/{vue.runtime.esm-bundler-HH4C0BYQ.js.gz → vue.runtime.esm-bundler-D6xZ1zFq.js.gz} +0 -0
  67. package/dist/web/assets/xterm-BMsy1fDS.js +16 -0
  68. package/dist/web/assets/xterm-BMsy1fDS.js.br +0 -0
  69. package/dist/web/assets/xterm-BMsy1fDS.js.gz +0 -0
  70. package/dist/web/icons/apple-touch-icon.png +0 -0
  71. package/dist/web/icons/badge-96.png +0 -0
  72. package/dist/web/icons/badge.svg +1 -0
  73. package/dist/web/icons/badge.svg.br +0 -0
  74. package/dist/web/icons/badge.svg.gz +0 -0
  75. package/dist/web/icons/favicon-64.png +0 -0
  76. package/dist/web/icons/favicon-attention-64.png +0 -0
  77. package/dist/web/icons/favicon-running-64.png +0 -0
  78. package/dist/web/icons/favicon-unread-64.png +0 -0
  79. package/dist/web/icons/icon-192.png +0 -0
  80. package/dist/web/icons/icon-512.png +0 -0
  81. package/dist/web/icons/mark.svg +9 -0
  82. package/dist/web/icons/mark.svg.br +0 -0
  83. package/dist/web/icons/mark.svg.gz +0 -0
  84. package/dist/web/icons/maskable-512.png +0 -0
  85. package/dist/web/index.html +5 -4
  86. package/dist/web/index.html.br +0 -0
  87. package/dist/web/index.html.gz +0 -0
  88. package/dist/web/manifest.webmanifest +2 -2
  89. package/docs/performance-plan.md +119 -241
  90. package/package.json +4 -2
  91. package/dist/web/assets/CodeBlockNode-CHQVlCcV.js +0 -3
  92. package/dist/web/assets/CodeBlockNode-CHQVlCcV.js.br +0 -0
  93. package/dist/web/assets/CodeBlockNode-CHQVlCcV.js.gz +0 -0
  94. package/dist/web/assets/MarkdownMessage-IYvqW4k2.js +0 -199
  95. package/dist/web/assets/MarkdownMessage-IYvqW4k2.js.br +0 -0
  96. package/dist/web/assets/MarkdownMessage-IYvqW4k2.js.gz +0 -0
  97. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Twzt_rFe.js.br +0 -0
  98. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Twzt_rFe.js.gz +0 -0
  99. package/dist/web/assets/Tooltip-CKXNC_qW.js +0 -1
  100. package/dist/web/assets/Tooltip-CKXNC_qW.js.br +0 -0
  101. package/dist/web/assets/Tooltip-CKXNC_qW.js.gz +0 -0
  102. package/dist/web/assets/index-DKzFEex_.js +0 -11
  103. package/dist/web/assets/index-DKzFEex_.js.br +0 -0
  104. package/dist/web/assets/index-DKzFEex_.js.gz +0 -0
  105. package/dist/web/assets/index-D_IXICNJ.css +0 -1
  106. package/dist/web/assets/index-D_IXICNJ.css.br +0 -0
  107. package/dist/web/assets/index-D_IXICNJ.css.gz +0 -0
  108. package/dist/web/assets/index10-tc5-49RH.js +0 -6
  109. package/dist/web/assets/index10-tc5-49RH.js.br +0 -0
  110. package/dist/web/assets/index10-tc5-49RH.js.gz +0 -0
  111. package/dist/web/assets/index3-C0ZPykQc.js +0 -1
  112. package/dist/web/assets/index4-D1FQ6lkb.js +0 -1
  113. package/dist/web/assets/index5-SOHOEHRz.js +0 -1
  114. package/dist/web/assets/index5-SOHOEHRz.js.br +0 -0
  115. package/dist/web/assets/index5-SOHOEHRz.js.gz +0 -0
  116. package/dist/web/assets/index6-DczfWbCr.js.br +0 -0
  117. package/dist/web/assets/index6-DczfWbCr.js.gz +0 -0
  118. package/dist/web/assets/index7-CzZrkyqI.js +0 -2
  119. package/dist/web/assets/index7-CzZrkyqI.js.br +0 -0
  120. package/dist/web/assets/index7-CzZrkyqI.js.gz +0 -0
  121. package/dist/web/assets/index8-g00UcLGR.js +0 -2
  122. package/dist/web/assets/index8-g00UcLGR.js.br +0 -0
  123. package/dist/web/assets/index8-g00UcLGR.js.gz +0 -0
  124. package/dist/web/assets/index9-EOMgiANd.js +0 -1
  125. package/dist/web/assets/index9-EOMgiANd.js.br +0 -0
  126. package/dist/web/assets/index9-EOMgiANd.js.gz +0 -0
  127. package/dist/web/assets/vue.runtime.esm-bundler-HH4C0BYQ.js.br +0 -0
  128. package/docs/operations.md +0 -143
@@ -2,7 +2,7 @@
2
2
  import { appendFileSync, chmodSync, closeSync, constants, copyFileSync, cpSync, existsSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
3
3
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
4
4
  import { execFileSync, fork, spawn } from "node:child_process";
5
- import { dirname, join, resolve } from "node:path";
5
+ import { basename, dirname, isAbsolute, join, normalize, resolve } from "node:path";
6
6
  import { connect, createServer } from "node:net";
7
7
  import { DatabaseSync } from "node:sqlite";
8
8
  import { serve } from "@hono/node-server";
@@ -10,18 +10,19 @@ import { createHostClient, parseHostTarget } from "@getpaseo/client/node";
10
10
  import { createPaseoApi } from "@getpaseo/client";
11
11
  import { deriveAgentStateBucket } from "@getpaseo/protocol/agent-state-bucket";
12
12
  import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity";
13
+ import { z } from "zod";
14
+ import { lstat, readFile, realpath } from "node:fs/promises";
15
+ import { homedir, tmpdir } from "node:os";
13
16
  import { Hono } from "hono";
14
17
  import { bodyLimit } from "hono/body-limit";
15
18
  import { serveStatic } from "@hono/node-server/serve-static";
16
19
  import { deleteCookie, getCookie, setCookie } from "hono/cookie";
17
20
  import QRCode from "qrcode";
18
- import { z } from "zod";
19
21
  import { AgentPermissionResponseSchema } from "@getpaseo/protocol/messages";
20
22
  import webpush from "web-push";
21
- import { homedir } from "node:os";
22
23
  import { fileURLToPath } from "node:url";
23
24
  // src/server/version.ts
24
- const VERSION = "0.1.0";
25
+ const VERSION = "0.3.0";
25
26
  // src/server/rotating-log.ts
26
27
  /** One writer (the supervisor); bounded active file plus numbered archives. */
27
28
  var RotatingLog = class {
@@ -307,6 +308,7 @@ async function supervise(directory, cliPath, options = {}) {
307
308
  await recoverSocket(path);
308
309
  let child = null, stopping = false, ready = false, url = "", restarts = 0;
309
310
  let failure = null, lastError = "";
311
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
310
312
  let retry;
311
313
  let killTimer;
312
314
  let finish;
@@ -396,6 +398,8 @@ async function supervise(directory, cliPath, options = {}) {
396
398
  if (input === "status") socket.end(JSON.stringify({
397
399
  ready,
398
400
  url,
401
+ version: VERSION,
402
+ startedAt,
399
403
  pid: process.pid,
400
404
  workerPid: child?.pid ?? null,
401
405
  restarts,
@@ -730,7 +734,7 @@ var VersionedCollection = class {
730
734
  // src/server/host-directory.ts
731
735
  const PAGE = 200;
732
736
  const RETRY_MS$1 = 2e3;
733
- const basename = (path) => path.replace(/\/+$/, "").split("/").pop() || path;
737
+ const basename$1 = (path) => path.replace(/\/+$/, "").split("/").pop() || path;
734
738
  const time = (value) => value ? Date.parse(value) || 0 : 0;
735
739
  /**
736
740
  * Mirrors one daemon directory into a shared collection. After the first snapshot it consumes
@@ -955,6 +959,7 @@ function summarize(hostId, agent, project, activity = time(agent.updatedAt)) {
955
959
  attentionReason: agent.attentionReason
956
960
  });
957
961
  const state = agent.status === "initializing" && bucket === "done" ? "running" : bucket === "attention" ? "unread" : bucket;
962
+ const turnActive = isRunning(agent) || agent.status === "initializing";
958
963
  return {
959
964
  key: `${hostId}:${agent.id}`,
960
965
  hostId,
@@ -962,17 +967,23 @@ function summarize(hostId, agent, project, activity = time(agent.updatedAt)) {
962
967
  workspaceId: agent.workspaceId ?? null,
963
968
  title: agent.title ?? null,
964
969
  status: agent.status,
965
- turnActive: isRunning(agent) || agent.status === "initializing",
970
+ turnActive,
966
971
  provider: agent.provider,
967
972
  cwd: agent.cwd,
968
- project: project?.projectName || basename(agent.cwd) || "Other",
973
+ project: project?.projectName || basename$1(agent.cwd) || "Other",
969
974
  projectKey: project?.projectKey ?? null,
970
975
  activityAt: activity,
976
+ turnStartedAt: turnActive ? time(agent.activeTurn?.startedAt) || time(agent.lastUserMessageAt) || null : null,
971
977
  attention: state === "needs_input",
972
978
  state,
973
979
  unread: agent.requiresAttention === true && state !== "needs_input",
974
980
  lastError: agent.lastError ? agent.lastError.slice(0, 300) : null,
975
- pendingPermissions: permissions
981
+ pendingPermissions: permissions,
982
+ model: agent.model ?? agent.runtimeInfo?.model ?? null,
983
+ thinking: agent.effectiveThinkingOptionId ?? agent.thinkingOptionId ?? agent.runtimeInfo?.thinkingOptionId ?? null,
984
+ modeId: agent.currentModeId ?? null,
985
+ contextUsed: agent.lastUsage?.contextWindowUsedTokens ?? null,
986
+ contextMax: agent.lastUsage?.contextWindowMaxTokens ?? null
976
987
  };
977
988
  }
978
989
  const agentAdapter = {
@@ -1019,7 +1030,9 @@ const agentAdapter = {
1019
1030
  },
1020
1031
  retain: (agent) => ({
1021
1032
  provider: agent.provider,
1022
- capabilities: agent.capabilities
1033
+ capabilities: agent.capabilities,
1034
+ availableModes: agent.availableModes ?? [],
1035
+ features: agent.features ?? []
1023
1036
  })
1024
1037
  };
1025
1038
  /** One daemon's active agents. */
@@ -1044,7 +1057,7 @@ function summarizeWorkspace(hostId, ws, activity) {
1044
1057
  id: ws.id,
1045
1058
  name: ws.name,
1046
1059
  title: ws.title ?? null,
1047
- project: ws.project?.projectName || ws.projectDisplayName || basename(ws.projectRootPath) || "Other",
1060
+ project: ws.project?.projectName || ws.projectDisplayName || basename$1(ws.projectRootPath) || "Other",
1048
1061
  projectKey: ws.project?.projectKey ?? ws.projectId,
1049
1062
  rootPath: ws.projectRootPath,
1050
1063
  directory: ws.workspaceDirectory ?? ws.projectRootPath,
@@ -1702,6 +1715,407 @@ var Hosts = class {
1702
1715
  for (const listener of listeners) listener();
1703
1716
  }
1704
1717
  };
1718
+ // src/server/sse.ts
1719
+ const HEARTBEAT_MS = 2e4;
1720
+ /** Server-sent events over a plain fetch response, so the bearer header still authenticates. */
1721
+ function eventStream(signal, open, valid = () => true) {
1722
+ const encoder = new TextEncoder();
1723
+ let cleanup;
1724
+ const stop = () => {
1725
+ cleanup?.();
1726
+ cleanup = void 0;
1727
+ };
1728
+ const body = new ReadableStream({
1729
+ start(controller) {
1730
+ const write = (text) => {
1731
+ try {
1732
+ controller.enqueue(encoder.encode(text));
1733
+ } catch {
1734
+ stop();
1735
+ }
1736
+ };
1737
+ const heartbeat = setInterval(() => {
1738
+ if (valid()) return write(": ping\n\n");
1739
+ stop();
1740
+ try {
1741
+ controller.close();
1742
+ } catch {}
1743
+ }, HEARTBEAT_MS);
1744
+ const close = open((data) => write(`data: ${JSON.stringify(data)}\n\n`));
1745
+ cleanup = () => {
1746
+ clearInterval(heartbeat);
1747
+ close();
1748
+ };
1749
+ signal.addEventListener("abort", () => {
1750
+ stop();
1751
+ try {
1752
+ controller.close();
1753
+ } catch {}
1754
+ });
1755
+ },
1756
+ cancel: stop
1757
+ });
1758
+ return new Response(body, { headers: {
1759
+ "Content-Type": "text/event-stream",
1760
+ "Cache-Control": "no-cache, no-transform",
1761
+ "X-Accel-Buffering": "no"
1762
+ } });
1763
+ }
1764
+ // src/server/media.ts
1765
+ /** Raster images only: an SVG opened directly could run script on this origin. */
1766
+ const IMAGE_MIME = {
1767
+ png: "image/png",
1768
+ jpg: "image/jpeg",
1769
+ jpeg: "image/jpeg",
1770
+ webp: "image/webp",
1771
+ gif: "image/gif",
1772
+ bmp: "image/bmp",
1773
+ avif: "image/avif"
1774
+ };
1775
+ const MAX_IMAGE_BYTES = 16777216;
1776
+ const extension = (path) => /\.([a-z0-9]+)$/i.exec(path)?.[1]?.toLowerCase() ?? "";
1777
+ const imageMime = (path) => IMAGE_MIME[extension(path)] ?? null;
1778
+ /** True when the daemon runs on this machine (loopback TCP/WebSocket or a local socket). */
1779
+ function isLocalConnection(connection) {
1780
+ try {
1781
+ const target = parseHostTarget(connection);
1782
+ if (target.kind !== "socket") return false;
1783
+ if (target.socketPath) return true;
1784
+ const host = new URL(target.url ?? "").hostname.replace(/^\[|\]$/g, "");
1785
+ return host === "localhost" || host === "::1" || /^127\./.test(host);
1786
+ } catch {
1787
+ return false;
1788
+ }
1789
+ }
1790
+ /**
1791
+ * Images a provider returned inline (screenshots, `read` of a PNG) are written by the daemon to
1792
+ * `<tmp>/paseo-attachments-XXXXXX/<sha256>.<ext>` and referenced from the message as file:// URLs.
1793
+ * The daemon's file API is confined to the workspace, so these are read from disk, and only when
1794
+ * the daemon shares this machine. The name pattern admits nothing but those materialized files.
1795
+ */
1796
+ function isMaterializedImagePath(path) {
1797
+ if (!isAbsolute(path) || normalize(path) !== path || !imageMime(path)) return false;
1798
+ const directory = dirname(path);
1799
+ return /^[a-f0-9]{64}\.[a-z0-9]+$/.test(basename(path)) && /^paseo-attachments-[A-Za-z0-9_-]{1,32}$/.test(basename(directory)) && [tmpdir(), "/tmp"].includes(dirname(directory));
1800
+ }
1801
+ async function readMaterializedImage(path) {
1802
+ if (!isMaterializedImagePath(path)) return null;
1803
+ try {
1804
+ const stats = await lstat(path);
1805
+ if (!stats.isFile() || stats.size > 16777216) return null;
1806
+ if (!isMaterializedImagePath(await realpath(path))) return null;
1807
+ return await readFile(path);
1808
+ } catch {
1809
+ return null;
1810
+ }
1811
+ }
1812
+ /** Small LRU for project icons: a sidebar asks for each project once per page load. */
1813
+ var IconCache = class {
1814
+ entries = /* @__PURE__ */ new Map();
1815
+ limit;
1816
+ ttlMs;
1817
+ constructor(limit = 256, ttlMs = 6e5) {
1818
+ this.limit = limit;
1819
+ this.ttlMs = ttlMs;
1820
+ }
1821
+ get(key) {
1822
+ const entry = this.entries.get(key);
1823
+ if (!entry) return void 0;
1824
+ if (Date.now() - entry.at > this.ttlMs) {
1825
+ this.entries.delete(key);
1826
+ return;
1827
+ }
1828
+ this.entries.delete(key);
1829
+ this.entries.set(key, entry);
1830
+ return entry.icon;
1831
+ }
1832
+ set(key, icon) {
1833
+ this.entries.delete(key);
1834
+ this.entries.set(key, {
1835
+ at: Date.now(),
1836
+ icon
1837
+ });
1838
+ if (this.entries.size > this.limit) this.entries.delete(this.entries.keys().next().value);
1839
+ }
1840
+ };
1841
+ // src/server/workspace-routes.ts
1842
+ /** Text files larger than this open truncated: the viewer is for reading, not for dumps. */
1843
+ const MAX_TEXT_BYTES = 1048576;
1844
+ const MAX_ENTRIES = 2e3;
1845
+ /** Terminal output is coalesced into one event per frame-ish interval. */
1846
+ const TERMINAL_FLUSH_MS = 16;
1847
+ const path = z.string().min(1).max(4096).refine((p) => !p.includes("\0"));
1848
+ /**
1849
+ * The workspace side panel (files, terminals) and schedules. Every call goes to the host's
1850
+ * daemon, which confines file access to the workspace and owns the terminals; nothing here
1851
+ * keeps state beyond an open terminal stream.
1852
+ */
1853
+ function registerWorkspaceRoutes(app, hosts, store, valid) {
1854
+ app.get("/api/hosts/:host/fs/list", async (c) => {
1855
+ const cwd = path.parse(c.req.query("cwd"));
1856
+ const dir = c.req.query("path") || ".";
1857
+ const { driver } = hosts.get(c.req.param("host"));
1858
+ try {
1859
+ const result = await driver.listDirectory(cwd, dir);
1860
+ const entries = (result.entries ?? []).map((e) => ({
1861
+ name: e.name,
1862
+ path: e.path,
1863
+ kind: e.kind,
1864
+ size: e.size
1865
+ })).sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name, void 0, { numeric: true }) : a.kind === "directory" ? -1 : 1);
1866
+ return c.json({
1867
+ path: result.path,
1868
+ entries: entries.slice(0, MAX_ENTRIES),
1869
+ truncated: entries.length > MAX_ENTRIES
1870
+ });
1871
+ } catch (error) {
1872
+ return c.json({ error: error.message || "Directory unavailable" }, 404);
1873
+ }
1874
+ });
1875
+ app.get("/api/hosts/:host/fs/read", async (c) => {
1876
+ const cwd = path.parse(c.req.query("cwd"));
1877
+ const file = path.parse(c.req.query("path"));
1878
+ const { driver } = hosts.get(c.req.param("host"));
1879
+ try {
1880
+ const result = await driver.readFile(cwd, file, void 0, 1048577);
1881
+ const text = result.kind === "text" ? new TextDecoder().decode(result.bytes.subarray(0, MAX_TEXT_BYTES)) : void 0;
1882
+ return c.json({
1883
+ path: result.path,
1884
+ kind: result.kind,
1885
+ mime: result.mime,
1886
+ size: result.size,
1887
+ modifiedAt: result.modifiedAt,
1888
+ ...text !== void 0 ? {
1889
+ text,
1890
+ truncated: result.size > MAX_TEXT_BYTES
1891
+ } : {}
1892
+ });
1893
+ } catch (error) {
1894
+ return c.json({ error: error.message || "File unavailable" }, 404);
1895
+ }
1896
+ });
1897
+ app.get("/api/hosts/:host/fs/raw", async (c) => {
1898
+ const cwd = path.parse(c.req.query("cwd"));
1899
+ const file = path.parse(c.req.query("path"));
1900
+ const mime = imageMime(file);
1901
+ if (!mime) return c.json({ error: "Only images can be opened raw" }, 415);
1902
+ const { driver } = hosts.get(c.req.param("host"));
1903
+ try {
1904
+ const result = await driver.readFile(cwd, file, void 0, MAX_IMAGE_BYTES);
1905
+ return c.body(result.bytes, 200, {
1906
+ "Content-Type": mime,
1907
+ "Cache-Control": "private, max-age=60"
1908
+ });
1909
+ } catch {
1910
+ return c.json({ error: "Image unavailable" }, 404);
1911
+ }
1912
+ });
1913
+ app.get("/api/hosts/:host/terminals", async (c) => {
1914
+ const cwd = path.parse(c.req.query("cwd"));
1915
+ const result = await hosts.get(c.req.param("host")).driver.listTerminals(cwd);
1916
+ return c.json((result.terminals ?? []).map((t) => ({
1917
+ id: t.id,
1918
+ name: t.name,
1919
+ title: t.title ?? null,
1920
+ cwd: t.cwd
1921
+ })));
1922
+ });
1923
+ app.post("/api/hosts/:host/terminals", async (c) => {
1924
+ const input = z.object({
1925
+ cwd: path,
1926
+ rows: z.number().int().min(4).max(500),
1927
+ cols: z.number().int().min(10).max(1e3),
1928
+ name: z.string().max(80).optional()
1929
+ }).parse(await c.req.json());
1930
+ const result = await hosts.get(c.req.param("host")).driver.createTerminal(input.cwd, input.name, void 0, { size: {
1931
+ rows: input.rows,
1932
+ cols: input.cols
1933
+ } });
1934
+ if (!result.terminal) return c.json({ error: result.error ?? "Could not open a terminal" }, 502);
1935
+ return c.json({
1936
+ id: result.terminal.id,
1937
+ name: result.terminal.name,
1938
+ title: result.terminal.title ?? null,
1939
+ cwd: result.terminal.cwd
1940
+ }, 201);
1941
+ });
1942
+ app.delete("/api/hosts/:host/terminals/:id", async (c) => {
1943
+ await hosts.get(c.req.param("host")).driver.killTerminal(c.req.param("id"));
1944
+ return c.json({ ok: true });
1945
+ });
1946
+ app.post("/api/hosts/:host/terminals/:id/input", async (c) => {
1947
+ const input = z.union([z.object({ data: z.string().min(1).max(65536) }), z.object({
1948
+ rows: z.number().int().min(4).max(500),
1949
+ cols: z.number().int().min(10).max(1e3)
1950
+ })]).parse(await c.req.json());
1951
+ const { driver } = hosts.get(c.req.param("host"));
1952
+ driver.sendTerminalInput(c.req.param("id"), "data" in input ? {
1953
+ type: "input",
1954
+ data: input.data
1955
+ } : {
1956
+ type: "resize",
1957
+ rows: input.rows,
1958
+ cols: input.cols
1959
+ });
1960
+ return c.json({ ok: true });
1961
+ });
1962
+ /** Live output as SSE: a full replay first (scrollback), then coalesced output chunks. */
1963
+ app.get("/api/hosts/:host/terminals/:id/stream", (c) => {
1964
+ const { driver } = hosts.get(c.req.param("host"));
1965
+ const id = c.req.param("id");
1966
+ const rows = Number(c.req.query("rows")) || 24, cols = Number(c.req.query("cols")) || 80;
1967
+ return eventStream(c.req.raw.signal, (send) => {
1968
+ let pending = [];
1969
+ let timer;
1970
+ const flush = () => {
1971
+ timer = void 0;
1972
+ if (!pending.length) return;
1973
+ send({
1974
+ t: "o",
1975
+ d: Buffer.concat(pending).toString("base64")
1976
+ });
1977
+ pending = [];
1978
+ };
1979
+ const push = (bytes) => {
1980
+ pending.push(bytes);
1981
+ timer ??= setTimeout(flush, TERMINAL_FLUSH_MS);
1982
+ };
1983
+ const subscription = driver.observeTerminal(id, (event) => {
1984
+ if (event.type === "output") push(event.data);
1985
+ else if (event.replay.type === "begin") {
1986
+ pending = [];
1987
+ send({ t: "reset" });
1988
+ } else if (event.replay.type === "data") push(event.replay.data);
1989
+ }, { restore: {
1990
+ mode: "full-snapshot",
1991
+ scrollbackLines: 2e3,
1992
+ size: {
1993
+ rows,
1994
+ cols
1995
+ }
1996
+ } });
1997
+ const stop = subscription.subscribe({
1998
+ snapshot: () => {},
1999
+ update: (message) => {
2000
+ if (message.type === "terminal_stream_exit") send({ t: "exit" });
2001
+ },
2002
+ error: () => send({ t: "exit" })
2003
+ });
2004
+ subscription.ready.catch(() => send({ t: "exit" }));
2005
+ return () => {
2006
+ clearTimeout(timer);
2007
+ stop();
2008
+ subscription.release().catch(() => {});
2009
+ };
2010
+ }, valid(c));
2011
+ });
2012
+ /** Every connected host's schedules; a host that fails reports its error instead. */
2013
+ app.get("/api/schedules", async (c) => {
2014
+ const results = await Promise.all(store.hosts().map(async (h) => {
2015
+ try {
2016
+ if (hosts.state(h.id) !== "connected") return {
2017
+ hostId: h.id,
2018
+ schedules: [],
2019
+ error: "Host is offline"
2020
+ };
2021
+ const list = await hosts.get(h.id).driver.scheduleList();
2022
+ return {
2023
+ hostId: h.id,
2024
+ schedules: list.schedules ?? [],
2025
+ error: list.error ?? null
2026
+ };
2027
+ } catch (error) {
2028
+ return {
2029
+ hostId: h.id,
2030
+ schedules: [],
2031
+ error: error.message || "Schedules unavailable"
2032
+ };
2033
+ }
2034
+ }));
2035
+ return c.json(results);
2036
+ });
2037
+ app.post("/api/hosts/:host/schedules", async (c) => {
2038
+ const input = z.object({
2039
+ name: z.string().trim().max(120).optional(),
2040
+ prompt: z.string().trim().min(1).max(2e4),
2041
+ cron: z.string().trim().min(9).max(120),
2042
+ timezone: z.string().max(80).optional(),
2043
+ cwd: path,
2044
+ provider: z.string().min(1).max(200),
2045
+ model: z.string().min(1).max(300).optional(),
2046
+ thinkingOptionId: z.string().min(1).max(200).optional(),
2047
+ archiveOnFinish: z.boolean().default(true),
2048
+ runOnCreate: z.boolean().default(false)
2049
+ }).parse(await c.req.json());
2050
+ const result = await hosts.get(c.req.param("host")).driver.scheduleCreate({
2051
+ prompt: input.prompt,
2052
+ name: input.name || null,
2053
+ cadence: {
2054
+ type: "cron",
2055
+ expression: input.cron,
2056
+ ...input.timezone ? { timezone: input.timezone } : {}
2057
+ },
2058
+ target: {
2059
+ type: "new-agent",
2060
+ config: {
2061
+ provider: input.provider,
2062
+ cwd: input.cwd,
2063
+ ...input.model ? { model: input.model } : {},
2064
+ ...input.thinkingOptionId ? { thinkingOptionId: input.thinkingOptionId } : {},
2065
+ archiveOnFinish: input.archiveOnFinish,
2066
+ isolation: "local",
2067
+ title: input.name || null
2068
+ }
2069
+ },
2070
+ runOnCreate: input.runOnCreate
2071
+ });
2072
+ if (result.error) return c.json({ error: result.error }, 400);
2073
+ return c.json(result.schedule, 201);
2074
+ });
2075
+ app.patch("/api/hosts/:host/schedules/:id", async (c) => {
2076
+ const input = z.object({
2077
+ name: z.string().trim().max(120).nullable().optional(),
2078
+ prompt: z.string().trim().min(1).max(2e4).optional(),
2079
+ cron: z.string().trim().min(9).max(120).optional(),
2080
+ timezone: z.string().max(80).optional(),
2081
+ cwd: path.optional(),
2082
+ provider: z.string().min(1).max(200).optional(),
2083
+ model: z.string().min(1).max(300).nullable().optional(),
2084
+ archiveOnFinish: z.boolean().optional()
2085
+ }).parse(await c.req.json());
2086
+ const agentConfig = {
2087
+ ...input.provider ? { provider: input.provider } : {},
2088
+ ...input.model !== void 0 ? { model: input.model } : {},
2089
+ ...input.cwd ? { cwd: input.cwd } : {},
2090
+ ...input.archiveOnFinish !== void 0 ? { archiveOnFinish: input.archiveOnFinish } : {}
2091
+ };
2092
+ const result = await hosts.get(c.req.param("host")).driver.scheduleUpdate({
2093
+ id: c.req.param("id"),
2094
+ ...input.name !== void 0 ? { name: input.name || null } : {},
2095
+ ...input.prompt ? { prompt: input.prompt } : {},
2096
+ ...input.cron ? { cadence: {
2097
+ type: "cron",
2098
+ expression: input.cron,
2099
+ ...input.timezone ? { timezone: input.timezone } : {}
2100
+ } } : {},
2101
+ ...Object.keys(agentConfig).length ? { newAgentConfig: agentConfig } : {}
2102
+ });
2103
+ if (result?.error) return c.json({ error: result.error }, 400);
2104
+ return c.json(result?.schedule ?? { ok: true });
2105
+ });
2106
+ const action = (name) => async (c) => {
2107
+ const { driver } = hosts.get(c.req.param("host"));
2108
+ const options = { id: c.req.param("id") };
2109
+ const result = name === "pause" ? await driver.schedulePause(options) : name === "resume" ? await driver.scheduleResume(options) : name === "run" ? await driver.scheduleRunOnce(options) : name === "delete" ? await driver.scheduleDelete(options) : await driver.scheduleLogs(options);
2110
+ if (result?.error) return c.json({ error: result.error }, 400);
2111
+ return c.json(name === "logs" ? { runs: (result.runs ?? []).slice(-50).reverse() } : { ok: true });
2112
+ };
2113
+ app.post("/api/hosts/:host/schedules/:id/pause", action("pause"));
2114
+ app.post("/api/hosts/:host/schedules/:id/resume", action("resume"));
2115
+ app.post("/api/hosts/:host/schedules/:id/run", action("run"));
2116
+ app.delete("/api/hosts/:host/schedules/:id", action("delete"));
2117
+ app.get("/api/hosts/:host/schedules/:id/logs", action("logs"));
2118
+ }
1705
2119
  // src/server/attachments.ts
1706
2120
  const MAX_FILE_BYTES = 8388608;
1707
2121
  const MAX_TOTAL = 67108864;
@@ -1900,12 +2314,9 @@ const SESSION_TTL_MS = 2592e6;
1900
2314
  const TOUCH_INTERVAL_MS = 36e5;
1901
2315
  const TOTP_PERIOD_S = 30;
1902
2316
  const TOTP_DIGITS = 6;
1903
- /**
1904
- * Code guessing is the only feasible attack (a 6-digit code, ±1 step, is ~1 in 333k), so code
1905
- * attempts get a server-wide budget whose lockout doubles each time it is exhausted (15 min up
1906
- * to 24 h, reset by a successful sign-in): roughly 20 guesses a day, decades to brute force.
1907
- * The 256-bit access token cannot be guessed, so it is exempt from that global lock: someone
1908
- * spamming bad codes can never lock the owner out of the token path.
2317
+ /** Only clients that know the access token can reach TOTP verification.
2318
+ * Code attempts have a persistent server-wide budget across IPs and restarts.
2319
+ * Exhausting it doubles the lockout from 15 minutes to at most 24 hours.
1909
2320
  */
1910
2321
  const WINDOW_MS = 9e5;
1911
2322
  const MAX_CODE_FAILURES_PER_CLIENT = 5;
@@ -1971,7 +2382,7 @@ const equalSecret = (a, b) => {
1971
2382
  return x.length === y.length && timingSafeEqual(x, y);
1972
2383
  };
1973
2384
  /**
1974
- * Login and sessions. A browser signs in once, with the access token or an authenticator code,
2385
+ * Login and sessions. A browser signs in once, with the access token and, when enabled, an authenticator code,
1975
2386
  * and receives an opaque session secret (stored only as a hash). Sessions are listed and
1976
2387
  * revocable; revoking one also drops the push subscriptions it registered.
1977
2388
  */
@@ -1989,6 +2400,19 @@ var Auth = class {
1989
2400
  constructor(store, token) {
1990
2401
  this.store = store;
1991
2402
  this.token = token;
2403
+ const saved = store.setting("totp_login_limit");
2404
+ if (saved) this.global = JSON.parse(saved);
2405
+ if (store.setting("auth_policy") !== "token-plus-totp-v1") {
2406
+ store.db.exec("BEGIN IMMEDIATE");
2407
+ try {
2408
+ if (this.totpEnabled()) store.revokeSessions();
2409
+ store.setSetting("auth_policy", "token-plus-totp-v1");
2410
+ store.db.exec("COMMIT");
2411
+ } catch (error) {
2412
+ store.db.exec("ROLLBACK");
2413
+ throw error;
2414
+ }
2415
+ }
1992
2416
  }
1993
2417
  totpEnabled() {
1994
2418
  return this.store.setting("totp_secret") !== null;
@@ -1998,33 +2422,39 @@ var Auth = class {
1998
2422
  return equalSecret(token, this.token);
1999
2423
  }
2000
2424
  login(input, client, label, now = Date.now()) {
2001
- const usesCode = !input.token;
2002
- const limited = this.limited(client, usesCode, now);
2003
- if (limited) return {
2425
+ const tokenLimit = this.limited(client, false, now);
2426
+ if (tokenLimit) return {
2004
2427
  ok: false,
2005
2428
  status: 429,
2006
- retryAfter: limited
2429
+ retryAfter: tokenLimit
2007
2430
  };
2008
- let ok = false;
2009
- if (input.token) ok = this.checkToken(input.token);
2010
- else if (input.code) {
2011
- const secret = this.store.setting("totp_secret");
2012
- const step = secret ? matchTotp(base32Decode(secret), input.code, now) : null;
2013
- ok = step !== null && this.store.advanceSetting("totp_last_step", step);
2014
- }
2015
- if (!ok) {
2016
- this.fail(client, usesCode, now);
2431
+ if (!input.token || !this.checkToken(input.token)) {
2432
+ this.fail(client, false, now);
2017
2433
  return {
2018
2434
  ok: false,
2019
2435
  status: 401
2020
2436
  };
2021
2437
  }
2022
- (usesCode ? this.codeFailures : this.tokenFailures).delete(client);
2023
- if (usesCode) this.global = {
2024
- count: 0,
2025
- reset: 0,
2026
- lockMs: WINDOW_MS
2027
- };
2438
+ const totpSecret = this.store.setting("totp_secret");
2439
+ if (totpSecret) {
2440
+ const codeLimit = this.limited(client, true, now);
2441
+ if (codeLimit) return {
2442
+ ok: false,
2443
+ status: 429,
2444
+ retryAfter: codeLimit
2445
+ };
2446
+ const step = matchTotp(base32Decode(totpSecret), input.code ?? "", now);
2447
+ if (step === null || !this.store.advanceSetting("totp_last_step", step)) {
2448
+ this.fail(client, true, now);
2449
+ return {
2450
+ ok: false,
2451
+ status: 401
2452
+ };
2453
+ }
2454
+ this.codeFailures.delete(client);
2455
+ this.resetCodeLimit();
2456
+ }
2457
+ this.tokenFailures.delete(client);
2028
2458
  const secret = randomBytes(32).toString("base64url");
2029
2459
  const session = {
2030
2460
  id: randomUUID(),
@@ -2070,6 +2500,7 @@ var Auth = class {
2070
2500
  this.store.revokeSessions(sessionId);
2071
2501
  }
2072
2502
  beginTotp(sessionId, now = Date.now()) {
2503
+ if (this.totpEnabled()) throw new Error("Disable the current authenticator before replacing it");
2073
2504
  const secret = base32Encode(randomBytes(20));
2074
2505
  this.pendingTotp = {
2075
2506
  secret,
@@ -2083,25 +2514,51 @@ var Auth = class {
2083
2514
  }
2084
2515
  /** Enables the pending secret once the user proves their app produces matching codes. */
2085
2516
  confirmTotp(sessionId, code, now = Date.now()) {
2517
+ if (this.totpEnabled()) return false;
2086
2518
  const pending = this.pendingTotp;
2087
2519
  if (!pending || pending.sessionId !== sessionId || pending.expires < now) return false;
2088
2520
  const step = matchTotp(base32Decode(pending.secret), code, now);
2089
2521
  if (step === null) return false;
2090
- this.store.setSetting("totp_secret", pending.secret);
2091
- this.store.setSetting("totp_last_step", String(step));
2522
+ this.store.db.exec("BEGIN IMMEDIATE");
2523
+ try {
2524
+ this.store.setSetting("totp_secret", pending.secret);
2525
+ this.store.setSetting("totp_last_step", String(step));
2526
+ this.store.db.prepare("DELETE FROM push_subscriptions WHERE session_id<>?").run(sessionId);
2527
+ this.store.db.prepare("DELETE FROM sessions WHERE id<>?").run(sessionId);
2528
+ this.resetCodeLimit();
2529
+ this.store.db.exec("COMMIT");
2530
+ } catch (error) {
2531
+ this.store.db.exec("ROLLBACK");
2532
+ throw error;
2533
+ }
2092
2534
  this.pendingTotp = null;
2093
2535
  return true;
2094
2536
  }
2095
2537
  disableTotp(code, now = Date.now()) {
2538
+ if (this.limited("settings", true, now)) return false;
2096
2539
  const secret = this.store.setting("totp_secret");
2097
2540
  const step = secret ? matchTotp(base32Decode(secret), code, now) : null;
2098
- if (step === null || !this.store.advanceSetting("totp_last_step", step)) return false;
2541
+ if (step === null || !this.store.advanceSetting("totp_last_step", step)) {
2542
+ this.fail("settings", true, now);
2543
+ return false;
2544
+ }
2099
2545
  this.store.setSetting("totp_secret", null);
2546
+ this.resetCodeLimit();
2100
2547
  return true;
2101
2548
  }
2549
+ resetCodeLimit() {
2550
+ this.global = {
2551
+ count: 0,
2552
+ reset: 0,
2553
+ lockMs: WINDOW_MS
2554
+ };
2555
+ this.store.setSetting("totp_login_limit", JSON.stringify(this.global));
2556
+ }
2102
2557
  limited(client, usesCode, now) {
2103
2558
  if (usesCode && this.global.reset > now && this.global.count >= MAX_CODE_FAILURES_GLOBAL) return Math.ceil((this.global.reset - now) / 1e3);
2104
- const entry = (usesCode ? this.codeFailures : this.tokenFailures).get(client);
2559
+ const map = usesCode ? this.codeFailures : this.tokenFailures;
2560
+ if (!map.has(client) && map.size >= 1e4) client = "overflow";
2561
+ const entry = map.get(client);
2105
2562
  const max = usesCode ? MAX_CODE_FAILURES_PER_CLIENT : MAX_TOKEN_FAILURES_PER_CLIENT;
2106
2563
  if (entry && entry.reset > now && entry.count >= max) return Math.ceil((entry.reset - now) / 1e3);
2107
2564
  return 0;
@@ -2114,15 +2571,16 @@ var Auth = class {
2114
2571
  this.global.reset = now + this.global.lockMs;
2115
2572
  this.global.lockMs = Math.min(this.global.lockMs * 2, MAX_LOCK_MS);
2116
2573
  } else if (this.global.reset <= now) this.global.reset = now + WINDOW_MS;
2574
+ this.store.setSetting("totp_login_limit", JSON.stringify(this.global));
2117
2575
  }
2118
2576
  const map = usesCode ? this.codeFailures : this.tokenFailures;
2577
+ if (!map.has(client) && map.size >= 1e4) client = "overflow";
2119
2578
  let entry = map.get(client);
2120
2579
  if (!entry || entry.reset <= now) map.set(client, entry = {
2121
2580
  count: 0,
2122
2581
  reset: now + WINDOW_MS
2123
2582
  });
2124
2583
  entry.count++;
2125
- if (map.size > 1e4) map.clear();
2126
2584
  }
2127
2585
  };
2128
2586
  // src/shared/wire.ts
@@ -2347,10 +2805,184 @@ var UsageService = class {
2347
2805
  return request;
2348
2806
  }
2349
2807
  };
2808
+ // src/server/dictation.ts
2809
+ /**
2810
+ * Voice input configured once in LitePaseo instead of on every Paseo host. The browser records
2811
+ * 16 kHz mono PCM and posts it once; the server wraps it as WAV and sends it to an
2812
+ * OpenAI-compatible `/audio/transcriptions` endpoint. No host is involved.
2813
+ *
2814
+ * Request shape differs by model generation (OpenAI speech-to-text guide, 2026):
2815
+ * - `gpt-transcribe` takes `languages[]` (several expected languages, for code-switching) and
2816
+ * `keywords[]`; it "replaces the singular `language` field. Don't send both fields."
2817
+ * - `whisper-1`, `gpt-4o(-mini)-transcribe` and most compatible providers (Groq, local Whisper
2818
+ * servers) take a single `language` and a free-text `prompt`.
2819
+ * Paseo always sends `language` (default "en"), which is what breaks `gpt-transcribe` there.
2820
+ * Here the shape follows the model name, and a 400 about the language field retries once with
2821
+ * the other shape, so unknown models on compatible providers still work.
2822
+ */
2823
+ const DEFAULT_BASE_URL = "https://api.openai.com/v1";
2824
+ /** Five minutes of 16 kHz, 16-bit mono speech (9.6 MB as WAV, under the 25 MB upload limit). */
2825
+ const MAX_DICTATION_BYTES = 96e5;
2826
+ const SETTING = "dictation";
2827
+ const UPSTREAM_TIMEOUT_MS = 11e4;
2828
+ /** Whisper reads at most 224 prompt tokens; keep the folded vocabulary well under that. */
2829
+ const LEGACY_PROMPT_CHARS = 600;
2830
+ const baseUrl = z.string().trim().max(500).transform((v) => (v || "https://api.openai.com/v1").replace(/\/+$/, "")).refine((v) => {
2831
+ try {
2832
+ return ["http:", "https:"].includes(new URL(v).protocol);
2833
+ } catch {
2834
+ return false;
2835
+ }
2836
+ }, "Base URL must be an http(s) address");
2837
+ const languageCode = z.string().trim().transform((v) => v.toLowerCase().replace("_", "-")).refine((v) => /^[a-z]{2,3}(-[a-z]{2})?$/.test(v), "Languages must be codes such as en, zh or zh-tw");
2838
+ /** The API rejects the whole request for a keyword with <, > or a line break. */
2839
+ const keyword = z.string().trim().min(1).max(100, "Each vocabulary term must be under 100 characters").refine((v) => !/[<>\r\n]/.test(v), "Vocabulary terms cannot contain < or >");
2840
+ const unique = (values) => [...new Set(values)];
2841
+ const DictationUpdate = z.object({
2842
+ baseUrl: baseUrl.optional().default(DEFAULT_BASE_URL),
2843
+ /** Omitted or empty keeps the saved key. */
2844
+ apiKey: z.string().trim().max(1e3).optional(),
2845
+ model: z.string().trim().max(200).optional().transform((v) => v || "gpt-transcribe"),
2846
+ languages: z.array(languageCode).max(10, "At most 10 languages").optional().default([]).transform(unique),
2847
+ keywords: z.array(keyword).max(100, "At most 100 vocabulary terms").optional().default([]).transform(unique)
2848
+ });
2849
+ function dictationConfig(store) {
2850
+ const raw = store.setting(SETTING);
2851
+ if (!raw) return null;
2852
+ try {
2853
+ const value = JSON.parse(raw);
2854
+ if (!value.apiKey || !value.baseUrl || !value.model) return null;
2855
+ return {
2856
+ baseUrl: value.baseUrl,
2857
+ apiKey: value.apiKey,
2858
+ model: value.model,
2859
+ languages: value.languages ?? [],
2860
+ keywords: value.keywords ?? []
2861
+ };
2862
+ } catch {
2863
+ return null;
2864
+ }
2865
+ }
2866
+ function dictationSettings(store) {
2867
+ const config = dictationConfig(store);
2868
+ return {
2869
+ configured: !!config,
2870
+ baseUrl: config?.baseUrl ?? "https://api.openai.com/v1",
2871
+ model: config?.model ?? "gpt-transcribe",
2872
+ languages: config?.languages ?? [],
2873
+ keywords: config?.keywords ?? [],
2874
+ keyHint: config ? "…" + config.apiKey.slice(-4) : ""
2875
+ };
2876
+ }
2877
+ function saveDictation(store, input) {
2878
+ const update = DictationUpdate.parse(input);
2879
+ const apiKey = update.apiKey || dictationConfig(store)?.apiKey;
2880
+ if (!apiKey) throw new Error("An API key is required");
2881
+ const config = {
2882
+ baseUrl: update.baseUrl,
2883
+ apiKey,
2884
+ model: update.model,
2885
+ languages: update.languages,
2886
+ keywords: update.keywords
2887
+ };
2888
+ store.setSetting(SETTING, JSON.stringify(config));
2889
+ return dictationSettings(store);
2890
+ }
2891
+ function clearDictation(store) {
2892
+ store.setSetting(SETTING, null);
2893
+ }
2894
+ /** A 44-byte RIFF header makes raw PCM16 a file every transcription API accepts. */
2895
+ function wav(pcm, rate) {
2896
+ const out = Buffer.alloc(44 + pcm.length);
2897
+ out.write("RIFF", 0);
2898
+ out.writeUInt32LE(36 + pcm.length, 4);
2899
+ out.write("WAVE", 8);
2900
+ out.write("fmt ", 12);
2901
+ out.writeUInt32LE(16, 16);
2902
+ out.writeUInt16LE(1, 20);
2903
+ out.writeUInt16LE(1, 22);
2904
+ out.writeUInt32LE(rate, 24);
2905
+ out.writeUInt32LE(rate * 2, 28);
2906
+ out.writeUInt16LE(2, 32);
2907
+ out.writeUInt16LE(16, 34);
2908
+ out.write("data", 36);
2909
+ out.writeUInt32LE(pcm.length, 40);
2910
+ out.set(pcm, 44);
2911
+ return out;
2912
+ }
2913
+ const shapeFor = (model) => /(^|\/)gpt-transcribe\b/i.test(model) ? "hints" : "single";
2914
+ /** The multipart fields besides the file, for one request shape. */
2915
+ function transcriptionFields(config, shape) {
2916
+ const fields = [["model", config.model], ["response_format", "json"]];
2917
+ if (shape === "hints") {
2918
+ for (const code of config.languages) fields.push(["languages[]", code]);
2919
+ for (const term of config.keywords) fields.push(["keywords[]", term]);
2920
+ return fields;
2921
+ }
2922
+ if (config.languages.length === 1) fields.push(["language", config.languages[0].split("-")[0]]);
2923
+ if (config.keywords.length) {
2924
+ let prompt = "";
2925
+ for (const term of config.keywords) {
2926
+ const next = prompt ? `${prompt}, ${term}` : term;
2927
+ if (next.length > LEGACY_PROMPT_CHARS) break;
2928
+ prompt = next;
2929
+ }
2930
+ fields.push(["prompt", prompt]);
2931
+ }
2932
+ return fields;
2933
+ }
2934
+ var DictationError = class extends Error {
2935
+ status;
2936
+ constructor(message, status) {
2937
+ super(message);
2938
+ this.status = status;
2939
+ }
2940
+ };
2941
+ async function send(config, file, shape, fetchImpl) {
2942
+ const form = new FormData();
2943
+ form.append("file", file, "dictation.wav");
2944
+ for (const [name, value] of transcriptionFields(config, shape)) form.append(name, value);
2945
+ let response;
2946
+ try {
2947
+ response = await fetchImpl(config.baseUrl + "/audio/transcriptions", {
2948
+ method: "POST",
2949
+ headers: { authorization: `Bearer ${config.apiKey}` },
2950
+ body: form,
2951
+ signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
2952
+ });
2953
+ } catch (error) {
2954
+ const timeout = error.name === "TimeoutError";
2955
+ throw new DictationError(timeout ? "The transcription service did not answer in time" : `Could not reach the transcription service: ${error.message}`.slice(0, 300), timeout ? 504 : 502);
2956
+ }
2957
+ const body = await response.text();
2958
+ let data = {};
2959
+ try {
2960
+ data = JSON.parse(body);
2961
+ } catch {}
2962
+ const detail = typeof data.error === "string" ? data.error : typeof data.error?.message === "string" ? data.error.message : response.ok ? "" : body;
2963
+ return {
2964
+ ok: response.ok,
2965
+ status: response.status,
2966
+ text: typeof data.text === "string" ? data.text : void 0,
2967
+ detail: String(detail)
2968
+ };
2969
+ }
2970
+ async function transcribe(config, pcm, rate, fetchImpl = fetch) {
2971
+ const file = new Blob([wav(pcm, rate)], { type: "audio/wav" });
2972
+ const shape = shapeFor(config.model);
2973
+ let result = await send(config, file, shape, fetchImpl);
2974
+ const hinted = config.languages.length > 0 || config.keywords.length > 0;
2975
+ if (!result.ok && result.status === 400 && hinted && /language|keyword|prompt/i.test(result.detail)) result = await send(config, file, shape === "hints" ? "single" : "hints", fetchImpl).then((retry) => retry.ok ? retry : result);
2976
+ if (!result.ok) {
2977
+ const scrubbed = result.detail.split(config.apiKey).join("…").replace(/\s+/g, " ").trim().slice(0, 200);
2978
+ throw new DictationError(`Transcription failed (${result.status})${scrubbed ? ": " + scrubbed : ""}`, 502);
2979
+ }
2980
+ if (result.text === void 0) throw new DictationError("The transcription service returned no text", 502);
2981
+ return result.text.trim();
2982
+ }
2350
2983
  // src/server/app.ts
2351
2984
  const AGENT_FLUSH_MS = 100;
2352
2985
  const HOST_FLUSH_MS = 100;
2353
- const HEARTBEAT_MS = 2e4;
2354
2986
  function parseJson(text) {
2355
2987
  try {
2356
2988
  return JSON.parse(text ?? "null");
@@ -2358,50 +2990,6 @@ function parseJson(text) {
2358
2990
  return null;
2359
2991
  }
2360
2992
  }
2361
- /** Server-sent events over a plain fetch response, so the bearer header still authenticates. */
2362
- function eventStream(signal, open, valid = () => true) {
2363
- const encoder = new TextEncoder();
2364
- let cleanup;
2365
- const stop = () => {
2366
- cleanup?.();
2367
- cleanup = void 0;
2368
- };
2369
- const body = new ReadableStream({
2370
- start(controller) {
2371
- const write = (text) => {
2372
- try {
2373
- controller.enqueue(encoder.encode(text));
2374
- } catch {
2375
- stop();
2376
- }
2377
- };
2378
- const heartbeat = setInterval(() => {
2379
- if (valid()) return write(": ping\n\n");
2380
- stop();
2381
- try {
2382
- controller.close();
2383
- } catch {}
2384
- }, HEARTBEAT_MS);
2385
- const close = open((data) => write(`data: ${JSON.stringify(data)}\n\n`));
2386
- cleanup = () => {
2387
- clearInterval(heartbeat);
2388
- close();
2389
- };
2390
- signal.addEventListener("abort", () => {
2391
- stop();
2392
- try {
2393
- controller.close();
2394
- } catch {}
2395
- });
2396
- },
2397
- cancel: stop
2398
- });
2399
- return new Response(body, { headers: {
2400
- "Content-Type": "text/event-stream",
2401
- "Cache-Control": "no-cache, no-transform",
2402
- "X-Accel-Buffering": "no"
2403
- } });
2404
- }
2405
2993
  const card = z.object({
2406
2994
  id: z.string().uuid(),
2407
2995
  title: z.string().min(1).max(300),
@@ -2421,6 +3009,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
2421
3009
  const app = new Hono();
2422
3010
  const auth = new Auth(store, token);
2423
3011
  const attachments = new Attachments();
3012
+ const projectIcons = new IconCache();
2424
3013
  const viewers = /* @__PURE__ */ new Map();
2425
3014
  const notifier = new Notifier({
2426
3015
  store,
@@ -2439,11 +3028,11 @@ function createApp(store, hosts, token, webRoot, options = {}) {
2439
3028
  c.header("Referrer-Policy", "no-referrer");
2440
3029
  c.header("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self'; manifest-src 'self'; frame-ancestors 'none'");
2441
3030
  });
2442
- app.use("/api/*", (c, next) => bodyLimit({ maxSize: c.req.method === "POST" && c.req.path.endsWith("/attachments") ? MAX_FILE_BYTES : 1048576 })(c, next));
3031
+ app.use("/api/*", (c, next) => bodyLimit({ maxSize: c.req.method !== "POST" ? 1048576 : c.req.path.endsWith("/attachments") ? MAX_FILE_BYTES : c.req.path === "/api/dictation/transcribe" ? MAX_DICTATION_BYTES : 1048576 })(c, next));
2443
3032
  app.use("/api/*", async (c, next) => {
2444
3033
  c.header("Cache-Control", "no-store");
2445
3034
  const bearer = c.req.header("authorization")?.replace(/^Bearer /, "");
2446
- if (bearer && !PUBLIC_API.has(c.req.path) && auth.checkToken(bearer)) {
3035
+ if (bearer && !PUBLIC_API.has(c.req.path) && !auth.totpEnabled() && auth.checkToken(bearer)) {
2447
3036
  c.set("session", null);
2448
3037
  return next();
2449
3038
  }
@@ -2474,7 +3063,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
2474
3063
  const input = z.object({
2475
3064
  token: z.string().min(1).max(200).optional(),
2476
3065
  code: z.string().regex(/^\d{6}$/).optional()
2477
- }).refine((x) => !!x.token !== !!x.code).parse(await c.req.json());
3066
+ }).refine((x) => !!x.token || !!x.code).parse(await c.req.json());
2478
3067
  const userAgent = c.req.header("user-agent") ?? "";
2479
3068
  const label = (/iPhone|iPad/.test(userAgent) ? "iOS" : /Android/.test(userAgent) ? "Android" : /Mac OS/.test(userAgent) ? "macOS" : /Windows/.test(userAgent) ? "Windows" : /Linux/.test(userAgent) ? "Linux" : "Browser") + (/Edg\//.test(userAgent) ? " · Edge" : /Chrome\//.test(userAgent) ? " · Chrome" : /Firefox\//.test(userAgent) ? " · Firefox" : /Safari\//.test(userAgent) ? " · Safari" : "");
2480
3069
  const result = auth.login(input, clientId(c), label);
@@ -2528,6 +3117,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
2528
3117
  };
2529
3118
  app.post("/api/totp/setup", async (c) => {
2530
3119
  const session = requireSession(c.get("session"));
3120
+ if (auth.totpEnabled()) return c.json({ error: "Disable the current authenticator before replacing it." }, 409);
2531
3121
  const { secret, uri } = auth.beginTotp(session.id);
2532
3122
  const qr = await QRCode.toString(uri, {
2533
3123
  type: "svg",
@@ -2636,6 +3226,8 @@ function createApp(store, hosts, token, webRoot, options = {}) {
2636
3226
  const directoryStreams = /* @__PURE__ */ new Set();
2637
3227
  let agentFlush;
2638
3228
  let hostFlush;
3229
+ /** Set on shutdown: closing the hosts still reports changes, but the store is about to close. */
3230
+ let disposed = false;
2639
3231
  const deliverAgents = (stream) => {
2640
3232
  deliverWorkspaces(stream);
2641
3233
  const { agents } = hosts;
@@ -2672,14 +3264,14 @@ function createApp(store, hosts, token, webRoot, options = {}) {
2672
3264
  stream.lastWorkspaces = workspaces.seq;
2673
3265
  };
2674
3266
  hosts.onAgentsChanged(() => {
2675
- if (agentFlush || !directoryStreams.size) return;
3267
+ if (disposed || agentFlush || !directoryStreams.size) return;
2676
3268
  agentFlush = setTimeout(() => {
2677
3269
  agentFlush = void 0;
2678
3270
  for (const stream of directoryStreams) deliverAgents(stream);
2679
3271
  }, AGENT_FLUSH_MS);
2680
3272
  });
2681
3273
  hosts.onHostsChanged(() => {
2682
- if (hostFlush || !directoryStreams.size) return;
3274
+ if (disposed || hostFlush || !directoryStreams.size) return;
2683
3275
  hostFlush = setTimeout(() => {
2684
3276
  hostFlush = void 0;
2685
3277
  const message = {
@@ -2689,7 +3281,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
2689
3281
  for (const stream of directoryStreams) stream.send(message);
2690
3282
  }, HOST_FLUSH_MS);
2691
3283
  });
2692
- const streamValidity = (session) => session ? () => auth.stillValid(session.id) : () => true;
3284
+ const streamValidity = (session) => session ? () => auth.stillValid(session.id) : () => !auth.totpEnabled();
2693
3285
  app.get("/api/stream", (c) => {
2694
3286
  const since = Number(c.req.query("since"));
2695
3287
  const resumable = c.req.query("generation") === hosts.agents.generation && Number.isInteger(since);
@@ -2869,6 +3461,155 @@ function createApp(store, hosts, token, webRoot, options = {}) {
2869
3461
  }))
2870
3462
  });
2871
3463
  });
3464
+ /**
3465
+ * An image an agent referenced in a message (`![](file:///…)`, an absolute or workspace path).
3466
+ * Workspace files go through the daemon's file API; images the daemon materialized from
3467
+ * provider output live outside the workspace and are read from disk when the daemon is local.
3468
+ */
3469
+ app.get("/api/hosts/:host/agents/:agent/image", async (c) => {
3470
+ const hostId = c.req.param("host");
3471
+ const path = z.string().min(1).max(4096).refine((p) => !p.includes("\0")).parse(c.req.query("path"));
3472
+ const mime = imageMime(path);
3473
+ if (!mime) return c.json({ error: "Not an image" }, 415);
3474
+ const { driver } = hosts.get(hostId);
3475
+ const cwd = hosts.agents.get(`${hostId}:${c.req.param("agent")}`)?.cwd;
3476
+ let bytes = null;
3477
+ if (isMaterializedImagePath(path)) {
3478
+ const host = store.hosts().find((h) => h.id === hostId);
3479
+ if (host && isLocalConnection(host.connection)) bytes = await readMaterializedImage(path);
3480
+ } else if (cwd) try {
3481
+ const file = await driver.readFile(cwd, path, void 0, MAX_IMAGE_BYTES);
3482
+ if (file.size <= 16777216) bytes = file.bytes;
3483
+ } catch {
3484
+ bytes = null;
3485
+ }
3486
+ if (!bytes) return c.json({ error: "Image unavailable from this host" }, 404);
3487
+ return c.body(bytes, 200, {
3488
+ "Content-Type": mime,
3489
+ "Cache-Control": "private, max-age=86400",
3490
+ "Content-Disposition": "inline"
3491
+ });
3492
+ });
3493
+ /** A project's icon (favicon/logo the daemon found in its root), cached briefly per host. */
3494
+ app.get("/api/hosts/:host/project-icon", async (c) => {
3495
+ const hostId = c.req.param("host");
3496
+ const cwd = z.string().min(1).max(4096).parse(c.req.query("cwd"));
3497
+ const key = `${hostId}\n${cwd}`;
3498
+ let icon = projectIcons.get(key);
3499
+ if (icon === void 0) {
3500
+ try {
3501
+ const result = await hosts.get(hostId).driver.requestProjectIcon(cwd);
3502
+ icon = result.icon && /^image\/(png|jpeg|webp|gif|x-icon|vnd\.microsoft\.icon)$/.test(result.icon.mimeType) ? {
3503
+ data: Buffer.from(result.icon.data, "base64"),
3504
+ mimeType: result.icon.mimeType
3505
+ } : null;
3506
+ } catch (error) {
3507
+ if (error instanceof UnknownHostError) throw error;
3508
+ return c.json({ error: "Icon unavailable" }, 502);
3509
+ }
3510
+ projectIcons.set(key, icon);
3511
+ }
3512
+ if (!icon) return c.body(null, 204, { "Cache-Control": "private, max-age=600" });
3513
+ return c.body(icon.data, 200, {
3514
+ "Content-Type": icon.mimeType,
3515
+ "Cache-Control": "private, max-age=600"
3516
+ });
3517
+ });
3518
+ /** What the open agent can switch to. Modes/features come from the live directory (no round trip). */
3519
+ app.get("/api/hosts/:host/agents/:agent/config", async (c) => {
3520
+ const hostId = c.req.param("host");
3521
+ const client = hosts.get(hostId);
3522
+ const facts = client.directory.facts(c.req.param("agent"));
3523
+ if (!facts) return c.json({ error: "Unknown agent" }, 404);
3524
+ const options = {
3525
+ models: ((await client.api.providers.snapshot()).entries.find((p) => p.provider === facts.provider)?.models ?? []).filter((m) => m.isSelectable !== false).map((m) => ({
3526
+ id: m.id,
3527
+ label: m.label,
3528
+ thinking: (m.thinkingOptions ?? []).map((t) => ({
3529
+ id: t.id,
3530
+ label: t.label
3531
+ })),
3532
+ defaultThinkingId: m.defaultThinkingOptionId ?? null
3533
+ })),
3534
+ modes: facts.availableModes.map((m) => ({
3535
+ id: m.id,
3536
+ label: m.label,
3537
+ ...m.description ? { description: m.description } : {}
3538
+ })),
3539
+ features: facts.features.map((f) => f.type === "toggle" ? {
3540
+ type: "toggle",
3541
+ id: f.id,
3542
+ label: f.label,
3543
+ ...f.tooltip ? { tooltip: f.tooltip } : {},
3544
+ value: f.value
3545
+ } : {
3546
+ type: "select",
3547
+ id: f.id,
3548
+ label: f.label,
3549
+ ...f.tooltip ? { tooltip: f.tooltip } : {},
3550
+ value: f.value,
3551
+ options: f.options.map((o) => ({
3552
+ id: o.id,
3553
+ label: o.label
3554
+ }))
3555
+ })
3556
+ };
3557
+ return c.json(options);
3558
+ });
3559
+ app.post("/api/hosts/:host/agents/:agent/config", async (c) => {
3560
+ const change = z.object({
3561
+ model: z.string().min(1).max(300).optional(),
3562
+ thinkingOptionId: z.string().min(1).max(200).optional(),
3563
+ modeId: z.string().min(1).max(200).optional(),
3564
+ feature: z.object({
3565
+ id: z.string().min(1).max(200),
3566
+ value: z.union([z.string().max(200), z.boolean()])
3567
+ }).optional()
3568
+ }).refine((v) => Object.values(v).filter((x) => x !== void 0).length === 1).parse(await c.req.json());
3569
+ const { driver } = hosts.get(c.req.param("host"));
3570
+ const agent = c.req.param("agent");
3571
+ let notice = null;
3572
+ if (change.model) await driver.setAgentModel(agent, change.model);
3573
+ else if (change.thinkingOptionId) notice = await driver.setAgentThinkingOption(agent, change.thinkingOptionId);
3574
+ else if (change.modeId) notice = await driver.setAgentMode(agent, change.modeId);
3575
+ else if (change.feature) await driver.setAgentFeature(agent, change.feature.id, change.feature.value);
3576
+ return c.json({
3577
+ ok: true,
3578
+ notice
3579
+ });
3580
+ });
3581
+ /**
3582
+ * Speech to text through the transcription service configured here, once for every host. The
3583
+ * browser records 16 kHz mono PCM and posts it once when the user stops: one request, no
3584
+ * socket kept open while idle. The API key never leaves the server.
3585
+ */
3586
+ app.get("/api/dictation", (c) => c.json(dictationSettings(store)));
3587
+ app.put("/api/dictation", async (c) => {
3588
+ try {
3589
+ return c.json(saveDictation(store, await c.req.json()));
3590
+ } catch (error) {
3591
+ const message = error instanceof z.ZodError ? error.issues[0]?.message ?? "Invalid settings" : error.message;
3592
+ return c.json({ error: message }, 400);
3593
+ }
3594
+ });
3595
+ app.delete("/api/dictation", (c) => {
3596
+ clearDictation(store);
3597
+ return c.json(dictationSettings(store));
3598
+ });
3599
+ app.post("/api/dictation/transcribe", async (c) => {
3600
+ const config = dictationConfig(store);
3601
+ if (!config) return c.json({ error: "Voice input is not set up. Add a transcription service in Settings." }, 409);
3602
+ const format = /^audio\/pcm;rate=(\d{4,6});bits=16$/.exec(c.req.header("x-audio-format") ?? "");
3603
+ if (!format) return c.json({ error: "Unsupported audio format" }, 415);
3604
+ const audio = new Uint8Array(await c.req.arrayBuffer());
3605
+ if (audio.length < 3200 || audio.length % 2) return c.json({ error: "Recording too short" }, 400);
3606
+ try {
3607
+ return c.json({ text: await transcribe(config, audio, Number(format[1]), options.fetch) });
3608
+ } catch (error) {
3609
+ if (error instanceof DictationError) return c.json({ error: error.message }, error.status);
3610
+ throw error;
3611
+ }
3612
+ });
2872
3613
  const attachmentOwner = (c) => c.get("session")?.id ?? "bearer";
2873
3614
  app.get("/api/hosts/:host/agents/:agent/attachments/capabilities", async (c) => c.json(await attachments.capabilities(hosts, c.req.param("host"), c.req.param("agent"))));
2874
3615
  app.post("/api/hosts/:host/agents/:agent/attachments", async (c) => {
@@ -3008,6 +3749,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3008
3749
  });
3009
3750
  }
3010
3751
  });
3752
+ registerWorkspaceRoutes(app, hosts, store, (c) => streamValidity(c.get("session")));
3011
3753
  app.get("/api/usage", async (c) => c.json(await usage.report(c.req.query("refresh") === "1")));
3012
3754
  app.get("/api/board", (c) => c.json(store.board()));
3013
3755
  app.put("/api/board", async (c) => {
@@ -3045,7 +3787,13 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3045
3787
  return Object.assign(app, {
3046
3788
  /** Open directory streams; lets tests prove that disconnects release them. */
3047
3789
  openStreams: () => directoryStreams.size,
3048
- dispose: () => attachments.close()
3790
+ dispose: () => {
3791
+ disposed = true;
3792
+ clearTimeout(agentFlush);
3793
+ clearTimeout(hostFlush);
3794
+ agentFlush = hostFlush = void 0;
3795
+ attachments.close();
3796
+ }
3049
3797
  });
3050
3798
  }
3051
3799
  // src/server/worker.ts
@@ -3253,35 +4001,332 @@ async function resolveDataDirectory(env, home, platform, isLive = socketIsLive)
3253
4001
  notice: `Moved LitePaseo data from ${legacy} to ${target}.`
3254
4002
  };
3255
4003
  }
4004
+ // src/server/cli-format.ts
4005
+ const json = {
4006
+ name: "json",
4007
+ summary: "Print machine-readable JSON"
4008
+ };
4009
+ const SERVICE_ACTIONS = [
4010
+ "print",
4011
+ "install",
4012
+ "uninstall",
4013
+ "status",
4014
+ "start",
4015
+ "stop",
4016
+ "restart"
4017
+ ];
4018
+ const COMMANDS = [
4019
+ {
4020
+ name: "start",
4021
+ group: "Service",
4022
+ summary: "Start in the background",
4023
+ details: ["Waits up to 10 s until the web console answers, then prints its address.", "Does nothing if LitePaseo is already running."],
4024
+ flags: [json]
4025
+ },
4026
+ {
4027
+ name: "stop",
4028
+ group: "Service",
4029
+ summary: "Stop the background instance",
4030
+ details: ["Waits until the instance has exited."]
4031
+ },
4032
+ {
4033
+ name: "restart",
4034
+ group: "Service",
4035
+ summary: "Stop, then start again",
4036
+ details: ["Use after upgrading so the new version serves."],
4037
+ flags: [json]
4038
+ },
4039
+ {
4040
+ name: "status",
4041
+ group: "Service",
4042
+ summary: "Show state, address and processes",
4043
+ details: ["Exit status: 0 running, 3 not running."],
4044
+ flags: [json]
4045
+ },
4046
+ {
4047
+ name: "logs",
4048
+ group: "Service",
4049
+ summary: "Show recent logs",
4050
+ flags: [{
4051
+ name: "lines",
4052
+ short: "n",
4053
+ value: "<count>",
4054
+ summary: "Number of lines to show (default 100)"
4055
+ }, {
4056
+ name: "follow",
4057
+ short: "f",
4058
+ summary: "Keep printing new lines until Ctrl-C"
4059
+ }],
4060
+ examples: ["litepaseo logs -n 500", "litepaseo logs -f"]
4061
+ },
4062
+ {
4063
+ name: "serve",
4064
+ group: "Service",
4065
+ summary: "Run in the foreground (for service managers)"
4066
+ },
4067
+ {
4068
+ name: "token",
4069
+ group: "Sign-in",
4070
+ summary: "Print the access token",
4071
+ details: ["The token is required to sign in from a browser."]
4072
+ },
4073
+ {
4074
+ name: "totp-reset",
4075
+ group: "Sign-in",
4076
+ summary: "Turn off authenticator sign-in (lost phone)"
4077
+ },
4078
+ {
4079
+ name: "signout-all",
4080
+ group: "Sign-in",
4081
+ summary: "Sign out every browser and stop its notifications"
4082
+ },
4083
+ {
4084
+ name: "backup",
4085
+ group: "Data",
4086
+ args: "<directory>",
4087
+ positional: 1,
4088
+ summary: "Back up all data into a new directory",
4089
+ details: ["The backup contains credentials: keep it private."],
4090
+ examples: ["litepaseo backup ~/litepaseo-backup"]
4091
+ },
4092
+ {
4093
+ name: "restore",
4094
+ group: "Data",
4095
+ args: "<directory>",
4096
+ positional: 1,
4097
+ summary: "Restore a backup into an empty home",
4098
+ examples: ["LITEPASEO_HOME=~/.litepaseo-restored litepaseo restore ~/litepaseo-backup"]
4099
+ },
4100
+ {
4101
+ name: "service",
4102
+ group: "Autostart",
4103
+ args: "<action>",
4104
+ summary: "Manage the systemd / launchd user service",
4105
+ details: [
4106
+ "Actions:",
4107
+ " print show the service definition without installing it",
4108
+ " install install and start it at login",
4109
+ " uninstall stop and remove it",
4110
+ " status show the service manager's status",
4111
+ " start | stop | restart"
4112
+ ],
4113
+ examples: ["litepaseo service install"]
4114
+ },
4115
+ {
4116
+ name: "version",
4117
+ group: "Other",
4118
+ summary: "Show version details",
4119
+ flags: [json]
4120
+ },
4121
+ {
4122
+ name: "help",
4123
+ group: "Other",
4124
+ args: "[command]",
4125
+ summary: "Show help for a command"
4126
+ }
4127
+ ];
4128
+ function findCommand(name) {
4129
+ return COMMANDS.find((c) => c.name === name);
4130
+ }
4131
+ /** Edit distance counting a swap of neighbouring letters as one edit, the commonest typo. */
4132
+ function distance(a, b) {
4133
+ const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => i ? j ? 0 : i : j));
4134
+ for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) {
4135
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
4136
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
4137
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
4138
+ }
4139
+ return d[a.length][b.length];
4140
+ }
4141
+ /** The closest known name, if it is plausibly a typo. */
4142
+ function suggest(input, names) {
4143
+ let best, score = Infinity;
4144
+ for (const name of names) {
4145
+ const d = name.startsWith(input) && input.length >= 2 ? 0 : distance(input, name);
4146
+ if (d < score) [best, score] = [name, d];
4147
+ }
4148
+ return score <= Math.max(1, Math.floor((best?.length ?? 0) / 3)) ? best : void 0;
4149
+ }
4150
+ var UsageError = class extends Error {};
4151
+ /** Parses the arguments after the command name against its declared flags. */
4152
+ function parseArgs(command, argv) {
4153
+ const result = {
4154
+ positional: [],
4155
+ flags: {},
4156
+ help: false
4157
+ };
4158
+ const flags = command.flags ?? [];
4159
+ for (let i = 0; i < argv.length; i++) {
4160
+ const arg = argv[i];
4161
+ if (arg === "-h" || arg === "--help") {
4162
+ result.help = true;
4163
+ continue;
4164
+ }
4165
+ if (arg === "--") {
4166
+ result.positional.push(...argv.slice(i + 1));
4167
+ break;
4168
+ }
4169
+ if (!arg.startsWith("-") || arg === "-") {
4170
+ result.positional.push(arg);
4171
+ continue;
4172
+ }
4173
+ const [raw, inline] = arg.startsWith("--") ? [arg.slice(2).split("=")[0], arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : void 0] : [arg.slice(1), void 0];
4174
+ const flag = arg.startsWith("--") ? flags.find((f) => f.name === raw) : flags.find((f) => f.short === raw);
4175
+ if (!flag) throw new UsageError(`Unknown option ${arg} for '${command.name}'.`);
4176
+ if (!flag.value) {
4177
+ if (inline !== void 0) throw new UsageError(`Option --${flag.name} takes no value.`);
4178
+ result.flags[flag.name] = true;
4179
+ continue;
4180
+ }
4181
+ const value = inline ?? argv[++i];
4182
+ if (value === void 0) throw new UsageError(`Option ${arg} needs a value ${flag.value}.`);
4183
+ result.flags[flag.name] = value;
4184
+ }
4185
+ if (result.help) return result;
4186
+ const required = command.positional ?? 0;
4187
+ if (result.positional.length < required) throw new UsageError(`Missing ${command.args} for '${command.name}'.`);
4188
+ const allowed = command.args ? command.args.split(" ").length : 0;
4189
+ if (result.positional.length > allowed) throw new UsageError(`Unexpected argument '${result.positional[allowed]}' for '${command.name}'.`);
4190
+ return result;
4191
+ }
4192
+ function makeStyle(enabled) {
4193
+ const wrap = (open, close) => (s) => enabled ? `\x1b[${open}m${s}\x1b[${close}m` : s;
4194
+ return {
4195
+ bold: wrap(1, 22),
4196
+ dim: wrap(2, 22),
4197
+ green: wrap(32, 39),
4198
+ red: wrap(31, 39),
4199
+ yellow: wrap(33, 39),
4200
+ cyan: wrap(36, 39)
4201
+ };
4202
+ }
4203
+ /** Colour only for a terminal, and never against NO_COLOR; FORCE_COLOR overrides both. */
4204
+ function colorEnabled(env, isTTY) {
4205
+ if (env.FORCE_COLOR !== void 0) return env.FORCE_COLOR !== "0";
4206
+ if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "") return false;
4207
+ return Boolean(isTTY) && env.TERM !== "dumb";
4208
+ }
4209
+ const usageOf = (c) => `litepaseo ${c.name}${c.args ? " " + c.args : ""}${c.flags?.length ? " [options]" : ""}`;
4210
+ function mainHelp(version, directory, s) {
4211
+ const lines = [
4212
+ `${s.bold("LitePaseo")} ${version}: a resource-conscious web console for your Paseo agents`,
4213
+ "",
4214
+ `${s.bold("Usage:")} litepaseo <command> [options]`
4215
+ ];
4216
+ const groups = [...new Set(COMMANDS.map((c) => c.group))];
4217
+ for (const group of groups) {
4218
+ lines.push("", s.bold(group));
4219
+ for (const c of COMMANDS.filter((x) => x.group === group)) lines.push(` ${s.cyan((c.name + (c.args ? " " + c.args : "")).padEnd(22))}${c.summary}`);
4220
+ }
4221
+ lines.push("", s.bold("Options"), ` ${s.cyan("-h, --help".padEnd(22))}Show help (also after a command)`, ` ${s.cyan("-v, --version".padEnd(22))}Print the version`, "", s.bold("Environment"), ` ${s.cyan("LITEPASEO_HOME".padEnd(24))}Data directory ${s.dim(`(now ${directory})`)}`, ` ${s.cyan("LITEPASEO_PORT".padEnd(24))}Port ${s.dim("(8787)")}`, ` ${s.cyan("LITEPASEO_BIND".padEnd(24))}Listen address ${s.dim("(127.0.0.1)")}`, ` ${s.cyan("LITEPASEO_PUSH_SUBJECT".padEnd(24))}mailto: or https: contact for push services`, "", `Run ${s.bold("litepaseo help <command>")} for details on a command.`);
4222
+ return lines.join("\n");
4223
+ }
4224
+ function commandHelp(c, s) {
4225
+ const lines = [
4226
+ `${s.bold("Usage:")} ${usageOf(c)}`,
4227
+ "",
4228
+ c.summary + "."
4229
+ ];
4230
+ if (c.details?.length) lines.push("", ...c.details);
4231
+ if (c.flags?.length) {
4232
+ lines.push("", s.bold("Options"));
4233
+ for (const f of c.flags) {
4234
+ const label = `${f.short ? `-${f.short}, ` : " "}--${f.name}${f.value ? " " + f.value : ""}`;
4235
+ lines.push(` ${s.cyan(label.padEnd(24))}${f.summary}`);
4236
+ }
4237
+ }
4238
+ if (c.examples?.length) lines.push("", s.bold("Examples"), ...c.examples.map((e) => " " + e));
4239
+ return lines.join("\n");
4240
+ }
4241
+ function formatDuration(ms) {
4242
+ const seconds = Math.max(0, Math.floor(ms / 1e3));
4243
+ const d = Math.floor(seconds / 86400), h = Math.floor(seconds % 86400 / 3600), m = Math.floor(seconds % 3600 / 60);
4244
+ if (d) return `${d}d ${h}h`;
4245
+ if (h) return `${h}h ${m}m`;
4246
+ if (m) return `${m}m ${seconds % 60}s`;
4247
+ return `${seconds}s`;
4248
+ }
4249
+ /** A note when the running instance is not the installed version (an upgrade needs a restart). */
4250
+ function versionNote(status, installed, s) {
4251
+ if (status.version === installed) return null;
4252
+ const running = status.version ? `version ${status.version}` : "an earlier version";
4253
+ return s.yellow(`! The running instance is ${running}; ${installed} is installed. Run 'litepaseo restart' to switch.`);
4254
+ }
4255
+ function formatStatus(status, installed, directory, s, now = Date.now()) {
4256
+ const state = status.ready ? s.green("● running") : status.restarts ? s.yellow("● restarting the worker") : s.yellow("● starting");
4257
+ const row = (label, value) => ` ${s.dim(label.padEnd(11))}${value}`;
4258
+ const lines = [`${s.bold("LitePaseo")} ${status.version ?? ""} ${state}`.replace(" ", " ")];
4259
+ if (status.url) lines.push(row("Address", s.cyan(status.url)));
4260
+ if (status.startedAt) {
4261
+ const started = new Date(status.startedAt);
4262
+ if (!Number.isNaN(started.getTime())) lines.push(row("Uptime", `${formatDuration(now - started.getTime())} ${s.dim(`(since ${started.toLocaleString()})`)}`));
4263
+ }
4264
+ lines.push(row("Processes", `supervisor ${status.pid}${status.workerPid ? `, worker ${status.workerPid}` : ", no worker"}`));
4265
+ if (status.restarts) lines.push(row("Restarts", String(status.restarts)));
4266
+ if (status.lastError) lines.push(row("Last error", s.red(status.lastError)));
4267
+ lines.push(row("Data", directory));
4268
+ const note = versionNote(status, installed, s);
4269
+ if (note) lines.push("", note);
4270
+ return lines.join("\n");
4271
+ }
4272
+ /** The last `count` lines of a text, keeping a trailing newline out of the count. */
4273
+ function lastLines(text, count) {
4274
+ if (count <= 0) return "";
4275
+ const body = text.endsWith("\n") ? text.slice(0, -1) : text;
4276
+ let index = body.length;
4277
+ for (let i = 0; i < count; i++) {
4278
+ index = body.lastIndexOf("\n", index - 1);
4279
+ if (index < 0) return text;
4280
+ }
4281
+ return text.slice(index + 1);
4282
+ }
3256
4283
  // src/server/cli.ts
3257
- const command = process.argv[2] ?? "help";
3258
- if (command === "--version" || command === "-v") {
3259
- console.log(VERSION);
3260
- process.exit(0);
3261
- }
3262
- const { directory, notice } = await resolveDataDirectory(process.env, homedir(), process.platform);
3263
- if (notice) console.error(notice);
3264
- mkdirSync(directory, {
3265
- recursive: true,
3266
- mode: 448
3267
- });
3268
- process.umask(63);
3269
- const socket = join(directory, "control.sock");
3270
- const tokenPath = join(directory, "token");
3271
- const log = join(directory, "service.log");
3272
- async function control(action) {
3273
- return new Promise((resolve, reject) => {
4284
+ /** `status` exit code when nothing is running, as for `systemctl status`. */
4285
+ const NOT_RUNNING = 3;
4286
+ const out = makeStyle(colorEnabled(process.env, process.stdout.isTTY));
4287
+ const err = makeStyle(colorEnabled(process.env, process.stderr.isTTY));
4288
+ const argv = process.argv.slice(2);
4289
+ const name = argv[0] ?? "help";
4290
+ /** Where data lives, for help text only: resolving it for real may migrate a legacy directory. */
4291
+ const displayDirectory = () => resolve(process.env.LITEPASEO_HOME || process.env.LITEPASEO_DATA_DIR || join(homedir(), ".litepaseo"));
4292
+ async function dataDirectory() {
4293
+ const { directory, notice } = await resolveDataDirectory(process.env, homedir(), process.platform);
4294
+ if (notice) console.error(notice);
4295
+ mkdirSync(directory, {
4296
+ recursive: true,
4297
+ mode: 448
4298
+ });
4299
+ process.umask(63);
4300
+ return {
4301
+ directory,
4302
+ socket: join(directory, "control.sock"),
4303
+ token: join(directory, "token"),
4304
+ log: join(directory, "service.log")
4305
+ };
4306
+ }
4307
+ function control(socket, action) {
4308
+ return new Promise((done, reject) => {
3274
4309
  const s = connect(socket);
3275
- let out = "";
4310
+ let text = "";
3276
4311
  s.setTimeout(2e3, () => s.destroy(/* @__PURE__ */ new Error("Control request timed out")));
3277
4312
  s.on("error", reject);
3278
4313
  s.on("connect", () => s.end(action));
3279
- s.on("data", (chunk) => out += chunk);
3280
- s.on("end", () => resolve(out));
4314
+ s.on("data", (chunk) => text += chunk);
4315
+ s.on("end", () => done(text));
3281
4316
  });
3282
4317
  }
4318
+ async function status(paths) {
4319
+ const text = await control(paths.socket, "status").catch(() => null);
4320
+ if (!text) return null;
4321
+ try {
4322
+ return JSON.parse(text);
4323
+ } catch {
4324
+ return null;
4325
+ }
4326
+ }
4327
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
3283
4328
  /** The reason recorded by the supervisor that just stopped, if any. */
3284
- function lastFailure(since) {
4329
+ function lastFailure(log, since) {
3285
4330
  if (!existsSync(log)) return null;
3286
4331
  const bytes = readFileSync(log);
3287
4332
  const lines = bytes.subarray(bytes.length >= since ? since : 0).toString("utf8").trim().split("\n").reverse();
@@ -3291,107 +4336,199 @@ function lastFailure(since) {
3291
4336
  } catch {}
3292
4337
  return null;
3293
4338
  }
3294
- async function main() {
3295
- if (command === "help" || command === "--help") {
3296
- console.log([
3297
- "LitePaseo: start | serve | status | stop | restart | logs | token | totp-reset | signout-all | backup <directory> | restore <directory> | service print|install|uninstall|status|start|stop|restart",
3298
- " token print the access token (sign-in fallback)",
3299
- " totp-reset turn off authenticator sign-in (lost phone)",
3300
- " signout-all revoke every signed-in browser and its notifications",
3301
- `Data: ${directory}`,
3302
- "Environment: LITEPASEO_HOME (default ~/.litepaseo), LITEPASEO_PORT (8787), LITEPASEO_BIND (127.0.0.1),",
3303
- " LITEPASEO_PUSH_SUBJECT (mailto: or https: contact for push services)"
3304
- ].join("\n"));
3305
- return;
3306
- }
3307
- if (command === "service") {
3308
- console.log(manageService(process.argv[3] ?? "print", {
3309
- platform: process.platform,
3310
- home: homedir(),
3311
- directory,
3312
- node: process.execPath,
3313
- cli: fileURLToPath(import.meta.url),
3314
- env: process.env,
3315
- uid: process.getuid?.() ?? 0
3316
- }));
3317
- return;
3318
- }
3319
- if (command === "backup" || command === "restore") {
3320
- const path = process.argv[3];
3321
- if (!path) throw new Error(`Usage: litepaseo ${command} <backup-directory>`);
3322
- if (command === "backup") backup(directory, path);
3323
- else await restore(path, directory);
3324
- console.log(command === "backup" ? "Backup complete. Keep this directory private: it contains credentials." : "Restore complete. Start LitePaseo with this LITEPASEO_HOME.");
3325
- return;
3326
- }
3327
- if (command === "token") {
3328
- console.log(readFileSync(tokenPath, "utf8"));
4339
+ function printStarted(state, already) {
4340
+ console.log(`${out.green("●")} LitePaseo ${state.version ?? ""} ${already ? "is already running" : "is running"} at ${out.cyan(state.url)}`.replace(" ", " "));
4341
+ const note = versionNote(state, VERSION, out);
4342
+ if (note) console.log(note);
4343
+ else if (!already) console.log(out.dim(" Sign in with the access token from: litepaseo token"));
4344
+ }
4345
+ async function start(paths, args) {
4346
+ const running = await status(paths);
4347
+ if (running) {
4348
+ if (args.flags.json) console.log(JSON.stringify(running));
4349
+ else printStarted(running, true);
3329
4350
  return;
3330
4351
  }
3331
- if (command === "totp-reset" || command === "signout-all") {
3332
- const store = new Store(directory);
3333
- if (command === "totp-reset") {
3334
- store.setSetting("totp_secret", null);
3335
- console.log("Authenticator sign-in is off. Sign in with: litepaseo token");
3336
- } else {
3337
- store.revokeSessions();
3338
- console.log("Every browser is signed out; their notifications stop.");
4352
+ const logStart = existsSync(paths.log) ? statSync(paths.log).size : 0;
4353
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "serve"], {
4354
+ detached: true,
4355
+ stdio: "ignore",
4356
+ env: process.env
4357
+ });
4358
+ let exited = false;
4359
+ child.on("error", () => {});
4360
+ child.once("exit", () => {
4361
+ exited = true;
4362
+ });
4363
+ child.unref();
4364
+ for (let i = 0; i < 100; i++) {
4365
+ await sleep(100);
4366
+ if (exited) throw new Error(lastFailure(paths.log, logStart) ?? "Startup failed. Run 'litepaseo logs' for details.");
4367
+ const ready = await status(paths);
4368
+ if (ready?.ready) {
4369
+ if (args.flags.json) console.log(JSON.stringify(ready));
4370
+ else printStarted(ready, false);
4371
+ return;
3339
4372
  }
3340
- store.close();
3341
- return;
3342
4373
  }
3343
- if (command === "logs") {
3344
- console.log(existsSync(log) ? readFileSync(log, "utf8").slice(-64e3) : "No logs");
4374
+ throw new Error("Startup not ready after 10 s. Run 'litepaseo status' or 'litepaseo logs'.");
4375
+ }
4376
+ async function stop(paths, quiet = false) {
4377
+ if (!await control(paths.socket, "stop").catch(() => null)) {
4378
+ if (!quiet) console.log("LitePaseo is not running.");
3345
4379
  return;
3346
4380
  }
3347
- if (command === "status") {
3348
- console.log(await control("status").catch(() => "Not running or control endpoint unavailable"));
3349
- return;
4381
+ for (let i = 0; i < 150 && existsSync(paths.socket); i++) await sleep(100);
4382
+ if (existsSync(paths.socket)) throw new Error("LitePaseo has not stopped after 15 s. Run 'litepaseo status'.");
4383
+ if (!quiet) console.log("LitePaseo stopped.");
4384
+ }
4385
+ async function showStatus(paths, args) {
4386
+ const state = await status(paths);
4387
+ if (args.flags.json) console.log(JSON.stringify(state ?? { running: false }));
4388
+ else if (state) console.log(formatStatus(state, VERSION, paths.directory, out));
4389
+ else console.log(`${out.dim("○")} LitePaseo is not running\n ${out.dim("Start it with: litepaseo start")}`);
4390
+ if (!state) process.exitCode = NOT_RUNNING;
4391
+ }
4392
+ async function logs(paths, args) {
4393
+ const count = args.flags.lines === void 0 ? 100 : Number(args.flags.lines);
4394
+ if (!Number.isInteger(count) || count < 0) throw new UsageError("--lines needs a whole number.");
4395
+ let text = existsSync(paths.log) ? readFileSync(paths.log, "utf8") : "";
4396
+ if (text.split("\n").length <= count && existsSync(paths.log + ".1")) text = readFileSync(paths.log + ".1", "utf8") + text;
4397
+ const tail = lastLines(text, count);
4398
+ if (tail) process.stdout.write(tail.endsWith("\n") ? tail : tail + "\n");
4399
+ else if (!args.flags.follow) console.log(out.dim(`No logs yet in ${paths.log}`));
4400
+ if (!args.flags.follow) return;
4401
+ let position = existsSync(paths.log) ? statSync(paths.log).size : 0;
4402
+ let inode = existsSync(paths.log) ? statSync(paths.log).ino : 0;
4403
+ for (;;) {
4404
+ await sleep(500);
4405
+ if (!existsSync(paths.log)) continue;
4406
+ const info = statSync(paths.log);
4407
+ if (info.ino !== inode || info.size < position) [position, inode] = [0, info.ino];
4408
+ if (info.size === position) continue;
4409
+ const fd = openSync(paths.log, "r");
4410
+ try {
4411
+ const chunk = Buffer.alloc(info.size - position);
4412
+ const read = readSync(fd, chunk, 0, chunk.length, position);
4413
+ process.stdout.write(chunk.subarray(0, read));
4414
+ position += read;
4415
+ } finally {
4416
+ closeSync(fd);
4417
+ }
3350
4418
  }
3351
- if (command === "stop" || command === "restart") {
3352
- console.log(await control("stop").catch(() => "Not running"));
3353
- if (command === "stop") return;
3354
- for (let i = 0; i < 150 && existsSync(socket); i++) await new Promise((r) => setTimeout(r, 100));
3355
- if (existsSync(socket)) throw new Error("Previous instance has not stopped");
4419
+ }
4420
+ async function version(args) {
4421
+ const paths = await dataDirectory();
4422
+ const state = await status(paths);
4423
+ const details = {
4424
+ version: VERSION,
4425
+ node: process.versions.node,
4426
+ platform: `${process.platform}-${process.arch}`,
4427
+ home: paths.directory,
4428
+ running: state ? state.version ?? "unknown" : null
4429
+ };
4430
+ if (args.flags.json) return console.log(JSON.stringify(details));
4431
+ const row = (label, value) => ` ${out.dim(label.padEnd(10))}${value}`;
4432
+ console.log([
4433
+ `${out.bold("LitePaseo")} ${VERSION}`,
4434
+ row("Node.js", details.node),
4435
+ row("Platform", details.platform),
4436
+ row("Data", details.home),
4437
+ row("Running", state ? `${details.running} at ${out.cyan(state.url)}` : out.dim("not running"))
4438
+ ].join("\n"));
4439
+ if (state) {
4440
+ const note = versionNote(state, VERSION, out);
4441
+ if (note) console.log("\n" + note);
3356
4442
  }
3357
- if (command === "start" || command === "restart") {
3358
- const running = await control("status").catch(() => null);
3359
- if (running) {
3360
- console.log(running);
4443
+ }
4444
+ async function run() {
4445
+ if (name === "--version" || name === "-v" || name === "-V") return console.log(VERSION);
4446
+ if (name === "--help" || name === "-h") return console.log(mainHelp(VERSION, displayDirectory(), out));
4447
+ if (name === "worker") return runWorker((await dataDirectory()).directory, fileURLToPath(new URL("../web/", import.meta.url)));
4448
+ const command = findCommand(name);
4449
+ if (!command) {
4450
+ const guess = suggest(name, COMMANDS.map((c) => c.name));
4451
+ throw new UsageError(`Unknown command '${name}'.${guess ? ` Did you mean '${guess}'?` : ""}`);
4452
+ }
4453
+ const args = parseArgs(command, argv.slice(1));
4454
+ if (args.help) return console.log(commandHelp(command, out));
4455
+ switch (command.name) {
4456
+ case "help": {
4457
+ const topic = args.positional[0];
4458
+ if (!topic) return console.log(mainHelp(VERSION, displayDirectory(), out));
4459
+ const target = findCommand(topic);
4460
+ if (!target) {
4461
+ const guess = suggest(topic, COMMANDS.map((c) => c.name));
4462
+ throw new UsageError(`No help for '${topic}'.${guess ? ` Did you mean '${guess}'?` : ""}`);
4463
+ }
4464
+ return console.log(commandHelp(target, out));
4465
+ }
4466
+ case "version": return version(args);
4467
+ }
4468
+ const paths = await dataDirectory();
4469
+ switch (command.name) {
4470
+ case "start": return start(paths, args);
4471
+ case "stop": return stop(paths);
4472
+ case "restart":
4473
+ await stop(paths, true);
4474
+ return start(paths, args);
4475
+ case "status": return showStatus(paths, args);
4476
+ case "logs": return logs(paths, args);
4477
+ case "serve": return supervise(paths.directory, fileURLToPath(import.meta.url));
4478
+ case "token":
4479
+ if (!existsSync(paths.token)) throw new Error("No access token yet: it is created on first start. Run 'litepaseo start'.");
4480
+ return console.log(readFileSync(paths.token, "utf8").trim());
4481
+ case "totp-reset":
4482
+ case "signout-all": {
4483
+ const store = new Store(paths.directory);
4484
+ try {
4485
+ if (command.name === "totp-reset") {
4486
+ store.setSetting("totp_secret", null);
4487
+ console.log("Authenticator sign-in is off. Sign in with the token from: litepaseo token");
4488
+ } else {
4489
+ store.revokeSessions();
4490
+ console.log("Every browser is signed out; their notifications stop.");
4491
+ }
4492
+ } finally {
4493
+ store.close();
4494
+ }
3361
4495
  return;
3362
4496
  }
3363
- const logStart = existsSync(log) ? statSync(log).size : 0;
3364
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "serve"], {
3365
- detached: true,
3366
- stdio: "ignore",
3367
- env: process.env
3368
- });
3369
- let exited = false;
3370
- child.on("error", () => {});
3371
- child.once("exit", () => {
3372
- exited = true;
3373
- });
3374
- child.unref();
3375
- for (let i = 0; i < 100; i++) {
3376
- await new Promise((r) => setTimeout(r, 100));
3377
- if (exited) throw new Error(lastFailure(logStart) ?? "Startup failed. Run litepaseo logs for details.");
3378
- const ready = await control("status").catch(() => null);
3379
- if (ready && JSON.parse(ready).ready) {
3380
- console.log(ready);
3381
- console.log("Retrieve your browser access token with: litepaseo token");
3382
- return;
4497
+ case "backup":
4498
+ backup(paths.directory, args.positional[0]);
4499
+ return console.log("Backup complete. Keep this directory private: it contains credentials.");
4500
+ case "restore":
4501
+ await restore(args.positional[0], paths.directory);
4502
+ return console.log(`Restore complete into ${paths.directory}. Start it with: litepaseo start`);
4503
+ case "service": {
4504
+ const action = args.positional[0] ?? "print";
4505
+ if (!SERVICE_ACTIONS.includes(action)) {
4506
+ const guess = suggest(action, SERVICE_ACTIONS);
4507
+ throw new UsageError(`Unknown service action '${action}'.${guess ? ` Did you mean '${guess}'?` : ""} Actions: ${SERVICE_ACTIONS.join(", ")}.`);
3383
4508
  }
4509
+ return console.log(manageService(action, {
4510
+ platform: process.platform,
4511
+ home: homedir(),
4512
+ directory: paths.directory,
4513
+ node: process.execPath,
4514
+ cli: fileURLToPath(import.meta.url),
4515
+ env: process.env,
4516
+ uid: process.getuid?.() ?? 0
4517
+ }));
3384
4518
  }
3385
- throw new Error("Startup not ready after 10 s. Run litepaseo status or litepaseo logs.");
3386
4519
  }
3387
- if (command === "worker") return runWorker(directory, fileURLToPath(new URL("../web/", import.meta.url)));
3388
- if (command === "serve") return supervise(directory, fileURLToPath(import.meta.url));
3389
- throw new Error("Unknown command. Run litepaseo --help");
3390
4520
  }
3391
- main().catch((error) => {
3392
- console.error(error.message);
3393
- if (command === "serve" && !(error instanceof StartupFailure)) try {
3394
- new RotatingLog(log).write(JSON.stringify({
4521
+ run().catch(async (error) => {
4522
+ if (error instanceof UsageError) {
4523
+ console.error(`${err.red("error:")} ${error.message}`);
4524
+ const command = findCommand(name);
4525
+ console.error(err.dim(command && name !== "help" ? `Run 'litepaseo ${name} --help' for usage.` : "Run 'litepaseo --help' for the list of commands."));
4526
+ process.exitCode = 2;
4527
+ return;
4528
+ }
4529
+ console.error(`${err.red("error:")} ${error.message}`);
4530
+ if (name === "serve" && !(error instanceof StartupFailure)) try {
4531
+ new RotatingLog((await dataDirectory()).log).write(JSON.stringify({
3395
4532
  event: "supervisor_start_failed",
3396
4533
  error: error.message
3397
4534
  }) + "\n");