litepaseo 0.1.0 → 0.2.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 (126) hide show
  1. package/README.md +3 -2
  2. package/dist/server/cli.mjs +650 -91
  3. package/dist/web/assets/CodeBlockNode-CehKIzSk.js +3 -0
  4. package/dist/web/assets/CodeBlockNode-CehKIzSk.js.br +0 -0
  5. package/dist/web/assets/CodeBlockNode-CehKIzSk.js.gz +0 -0
  6. package/dist/web/assets/FileViewer-01t53KTX.js +2 -0
  7. package/dist/web/assets/FileViewer-01t53KTX.js.br +0 -0
  8. package/dist/web/assets/FileViewer-01t53KTX.js.gz +0 -0
  9. package/dist/web/assets/FileViewer-CljYTF8J.css +1 -0
  10. package/dist/web/assets/FileViewer-CljYTF8J.css.br +0 -0
  11. package/dist/web/assets/FileViewer-CljYTF8J.css.gz +0 -0
  12. package/dist/web/assets/FilesPanel-B7NknFvl.js +1 -0
  13. package/dist/web/assets/FilesPanel-B7NknFvl.js.br +0 -0
  14. package/dist/web/assets/FilesPanel-B7NknFvl.js.gz +0 -0
  15. package/dist/web/assets/FilesPanel-CY9yMixJ.css +1 -0
  16. package/dist/web/assets/FilesPanel-CY9yMixJ.css.br +0 -0
  17. package/dist/web/assets/FilesPanel-CY9yMixJ.css.gz +0 -0
  18. package/dist/web/assets/MarkdownMessage-UlvozPc5.js +199 -0
  19. package/dist/web/assets/MarkdownMessage-UlvozPc5.js.br +0 -0
  20. package/dist/web/assets/MarkdownMessage-UlvozPc5.js.gz +0 -0
  21. package/dist/web/assets/{PreCodeBlock-B2Mi6ata.js → PreCodeBlock-DPQTlYty.js} +1 -1
  22. package/dist/web/assets/{PreCodeBlock.vue_vue_type_style_index_0_lang-Twzt_rFe.js → PreCodeBlock.vue_vue_type_style_index_0_lang-Cdy-YZRP.js} +1 -1
  23. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Cdy-YZRP.js.br +0 -0
  24. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Cdy-YZRP.js.gz +0 -0
  25. package/dist/web/assets/TerminalPanel-BdmAonFr.js +3 -0
  26. package/dist/web/assets/TerminalPanel-BdmAonFr.js.br +0 -0
  27. package/dist/web/assets/TerminalPanel-BdmAonFr.js.gz +0 -0
  28. package/dist/web/assets/TerminalPanel-DvfBWyiQ.css +1 -0
  29. package/dist/web/assets/TerminalPanel-DvfBWyiQ.css.br +0 -0
  30. package/dist/web/assets/TerminalPanel-DvfBWyiQ.css.gz +0 -0
  31. package/dist/web/assets/Tooltip-BJ2o2M_0.js +1 -0
  32. package/dist/web/assets/Tooltip-BJ2o2M_0.js.br +0 -0
  33. package/dist/web/assets/Tooltip-BJ2o2M_0.js.gz +0 -0
  34. package/dist/web/assets/addon-fit-DIOBYJe3.js +1 -0
  35. package/dist/web/assets/addon-fit-DIOBYJe3.js.br +0 -0
  36. package/dist/web/assets/addon-fit-DIOBYJe3.js.gz +0 -0
  37. package/dist/web/assets/index-D_YTh7Zw.css +1 -0
  38. package/dist/web/assets/index-D_YTh7Zw.css.br +0 -0
  39. package/dist/web/assets/index-D_YTh7Zw.css.gz +0 -0
  40. package/dist/web/assets/index-civcSERr.js +27 -0
  41. package/dist/web/assets/index-civcSERr.js.br +0 -0
  42. package/dist/web/assets/index-civcSERr.js.gz +0 -0
  43. package/dist/web/assets/index10-WpTfisco.js +6 -0
  44. package/dist/web/assets/index10-WpTfisco.js.br +0 -0
  45. package/dist/web/assets/index10-WpTfisco.js.gz +0 -0
  46. package/dist/web/assets/index3-C4yf5W5o.js +1 -0
  47. package/dist/web/assets/index4-Cwl0ij4U.js +1 -0
  48. package/dist/web/assets/index5-BCbIyN1t.js +1 -0
  49. package/dist/web/assets/index5-BCbIyN1t.js.br +0 -0
  50. package/dist/web/assets/index5-BCbIyN1t.js.gz +0 -0
  51. package/dist/web/assets/{index6-DczfWbCr.js → index6-CbdnTDhy.js} +1 -1
  52. package/dist/web/assets/index6-CbdnTDhy.js.br +0 -0
  53. package/dist/web/assets/index6-CbdnTDhy.js.gz +0 -0
  54. package/dist/web/assets/index7-BzNzdNxO.js +2 -0
  55. package/dist/web/assets/index7-BzNzdNxO.js.br +0 -0
  56. package/dist/web/assets/index7-BzNzdNxO.js.gz +0 -0
  57. package/dist/web/assets/index8-CD8jmACo.js +2 -0
  58. package/dist/web/assets/index8-CD8jmACo.js.br +0 -0
  59. package/dist/web/assets/index8-CD8jmACo.js.gz +0 -0
  60. package/dist/web/assets/index9-9FYLmtt9.js +1 -0
  61. package/dist/web/assets/index9-9FYLmtt9.js.br +0 -0
  62. package/dist/web/assets/index9-9FYLmtt9.js.gz +0 -0
  63. package/dist/web/assets/{vue.runtime.esm-bundler-HH4C0BYQ.js → vue.runtime.esm-bundler-D6xZ1zFq.js} +1 -1
  64. package/dist/web/assets/vue.runtime.esm-bundler-D6xZ1zFq.js.br +0 -0
  65. package/dist/web/assets/{vue.runtime.esm-bundler-HH4C0BYQ.js.gz → vue.runtime.esm-bundler-D6xZ1zFq.js.gz} +0 -0
  66. package/dist/web/assets/xterm-BMsy1fDS.js +16 -0
  67. package/dist/web/assets/xterm-BMsy1fDS.js.br +0 -0
  68. package/dist/web/assets/xterm-BMsy1fDS.js.gz +0 -0
  69. package/dist/web/icons/apple-touch-icon.png +0 -0
  70. package/dist/web/icons/badge-96.png +0 -0
  71. package/dist/web/icons/badge.svg +1 -0
  72. package/dist/web/icons/badge.svg.br +0 -0
  73. package/dist/web/icons/badge.svg.gz +0 -0
  74. package/dist/web/icons/favicon-64.png +0 -0
  75. package/dist/web/icons/favicon-attention-64.png +0 -0
  76. package/dist/web/icons/favicon-running-64.png +0 -0
  77. package/dist/web/icons/favicon-unread-64.png +0 -0
  78. package/dist/web/icons/icon-192.png +0 -0
  79. package/dist/web/icons/icon-512.png +0 -0
  80. package/dist/web/icons/mark.svg +9 -0
  81. package/dist/web/icons/mark.svg.br +0 -0
  82. package/dist/web/icons/mark.svg.gz +0 -0
  83. package/dist/web/icons/maskable-512.png +0 -0
  84. package/dist/web/index.html +5 -4
  85. package/dist/web/index.html.br +0 -0
  86. package/dist/web/index.html.gz +0 -0
  87. package/dist/web/manifest.webmanifest +2 -2
  88. package/docs/operations.md +2 -2
  89. package/package.json +3 -1
  90. package/dist/web/assets/CodeBlockNode-CHQVlCcV.js +0 -3
  91. package/dist/web/assets/CodeBlockNode-CHQVlCcV.js.br +0 -0
  92. package/dist/web/assets/CodeBlockNode-CHQVlCcV.js.gz +0 -0
  93. package/dist/web/assets/MarkdownMessage-IYvqW4k2.js +0 -199
  94. package/dist/web/assets/MarkdownMessage-IYvqW4k2.js.br +0 -0
  95. package/dist/web/assets/MarkdownMessage-IYvqW4k2.js.gz +0 -0
  96. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Twzt_rFe.js.br +0 -0
  97. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Twzt_rFe.js.gz +0 -0
  98. package/dist/web/assets/Tooltip-CKXNC_qW.js +0 -1
  99. package/dist/web/assets/Tooltip-CKXNC_qW.js.br +0 -0
  100. package/dist/web/assets/Tooltip-CKXNC_qW.js.gz +0 -0
  101. package/dist/web/assets/index-DKzFEex_.js +0 -11
  102. package/dist/web/assets/index-DKzFEex_.js.br +0 -0
  103. package/dist/web/assets/index-DKzFEex_.js.gz +0 -0
  104. package/dist/web/assets/index-D_IXICNJ.css +0 -1
  105. package/dist/web/assets/index-D_IXICNJ.css.br +0 -0
  106. package/dist/web/assets/index-D_IXICNJ.css.gz +0 -0
  107. package/dist/web/assets/index10-tc5-49RH.js +0 -6
  108. package/dist/web/assets/index10-tc5-49RH.js.br +0 -0
  109. package/dist/web/assets/index10-tc5-49RH.js.gz +0 -0
  110. package/dist/web/assets/index3-C0ZPykQc.js +0 -1
  111. package/dist/web/assets/index4-D1FQ6lkb.js +0 -1
  112. package/dist/web/assets/index5-SOHOEHRz.js +0 -1
  113. package/dist/web/assets/index5-SOHOEHRz.js.br +0 -0
  114. package/dist/web/assets/index5-SOHOEHRz.js.gz +0 -0
  115. package/dist/web/assets/index6-DczfWbCr.js.br +0 -0
  116. package/dist/web/assets/index6-DczfWbCr.js.gz +0 -0
  117. package/dist/web/assets/index7-CzZrkyqI.js +0 -2
  118. package/dist/web/assets/index7-CzZrkyqI.js.br +0 -0
  119. package/dist/web/assets/index7-CzZrkyqI.js.gz +0 -0
  120. package/dist/web/assets/index8-g00UcLGR.js +0 -2
  121. package/dist/web/assets/index8-g00UcLGR.js.br +0 -0
  122. package/dist/web/assets/index8-g00UcLGR.js.gz +0 -0
  123. package/dist/web/assets/index9-EOMgiANd.js +0 -1
  124. package/dist/web/assets/index9-EOMgiANd.js.br +0 -0
  125. package/dist/web/assets/index9-EOMgiANd.js.gz +0 -0
  126. package/dist/web/assets/vue.runtime.esm-bundler-HH4C0BYQ.js.br +0 -0
@@ -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.2.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 {
@@ -730,7 +731,7 @@ var VersionedCollection = class {
730
731
  // src/server/host-directory.ts
731
732
  const PAGE = 200;
732
733
  const RETRY_MS$1 = 2e3;
733
- const basename = (path) => path.replace(/\/+$/, "").split("/").pop() || path;
734
+ const basename$1 = (path) => path.replace(/\/+$/, "").split("/").pop() || path;
734
735
  const time = (value) => value ? Date.parse(value) || 0 : 0;
735
736
  /**
736
737
  * Mirrors one daemon directory into a shared collection. After the first snapshot it consumes
@@ -955,6 +956,7 @@ function summarize(hostId, agent, project, activity = time(agent.updatedAt)) {
955
956
  attentionReason: agent.attentionReason
956
957
  });
957
958
  const state = agent.status === "initializing" && bucket === "done" ? "running" : bucket === "attention" ? "unread" : bucket;
959
+ const turnActive = isRunning(agent) || agent.status === "initializing";
958
960
  return {
959
961
  key: `${hostId}:${agent.id}`,
960
962
  hostId,
@@ -962,17 +964,23 @@ function summarize(hostId, agent, project, activity = time(agent.updatedAt)) {
962
964
  workspaceId: agent.workspaceId ?? null,
963
965
  title: agent.title ?? null,
964
966
  status: agent.status,
965
- turnActive: isRunning(agent) || agent.status === "initializing",
967
+ turnActive,
966
968
  provider: agent.provider,
967
969
  cwd: agent.cwd,
968
- project: project?.projectName || basename(agent.cwd) || "Other",
970
+ project: project?.projectName || basename$1(agent.cwd) || "Other",
969
971
  projectKey: project?.projectKey ?? null,
970
972
  activityAt: activity,
973
+ turnStartedAt: turnActive ? time(agent.activeTurn?.startedAt) || time(agent.lastUserMessageAt) || null : null,
971
974
  attention: state === "needs_input",
972
975
  state,
973
976
  unread: agent.requiresAttention === true && state !== "needs_input",
974
977
  lastError: agent.lastError ? agent.lastError.slice(0, 300) : null,
975
- pendingPermissions: permissions
978
+ pendingPermissions: permissions,
979
+ model: agent.model ?? agent.runtimeInfo?.model ?? null,
980
+ thinking: agent.effectiveThinkingOptionId ?? agent.thinkingOptionId ?? agent.runtimeInfo?.thinkingOptionId ?? null,
981
+ modeId: agent.currentModeId ?? null,
982
+ contextUsed: agent.lastUsage?.contextWindowUsedTokens ?? null,
983
+ contextMax: agent.lastUsage?.contextWindowMaxTokens ?? null
976
984
  };
977
985
  }
978
986
  const agentAdapter = {
@@ -1019,7 +1027,9 @@ const agentAdapter = {
1019
1027
  },
1020
1028
  retain: (agent) => ({
1021
1029
  provider: agent.provider,
1022
- capabilities: agent.capabilities
1030
+ capabilities: agent.capabilities,
1031
+ availableModes: agent.availableModes ?? [],
1032
+ features: agent.features ?? []
1023
1033
  })
1024
1034
  };
1025
1035
  /** One daemon's active agents. */
@@ -1044,7 +1054,7 @@ function summarizeWorkspace(hostId, ws, activity) {
1044
1054
  id: ws.id,
1045
1055
  name: ws.name,
1046
1056
  title: ws.title ?? null,
1047
- project: ws.project?.projectName || ws.projectDisplayName || basename(ws.projectRootPath) || "Other",
1057
+ project: ws.project?.projectName || ws.projectDisplayName || basename$1(ws.projectRootPath) || "Other",
1048
1058
  projectKey: ws.project?.projectKey ?? ws.projectId,
1049
1059
  rootPath: ws.projectRootPath,
1050
1060
  directory: ws.workspaceDirectory ?? ws.projectRootPath,
@@ -1702,6 +1712,407 @@ var Hosts = class {
1702
1712
  for (const listener of listeners) listener();
1703
1713
  }
1704
1714
  };
1715
+ // src/server/sse.ts
1716
+ const HEARTBEAT_MS = 2e4;
1717
+ /** Server-sent events over a plain fetch response, so the bearer header still authenticates. */
1718
+ function eventStream(signal, open, valid = () => true) {
1719
+ const encoder = new TextEncoder();
1720
+ let cleanup;
1721
+ const stop = () => {
1722
+ cleanup?.();
1723
+ cleanup = void 0;
1724
+ };
1725
+ const body = new ReadableStream({
1726
+ start(controller) {
1727
+ const write = (text) => {
1728
+ try {
1729
+ controller.enqueue(encoder.encode(text));
1730
+ } catch {
1731
+ stop();
1732
+ }
1733
+ };
1734
+ const heartbeat = setInterval(() => {
1735
+ if (valid()) return write(": ping\n\n");
1736
+ stop();
1737
+ try {
1738
+ controller.close();
1739
+ } catch {}
1740
+ }, HEARTBEAT_MS);
1741
+ const close = open((data) => write(`data: ${JSON.stringify(data)}\n\n`));
1742
+ cleanup = () => {
1743
+ clearInterval(heartbeat);
1744
+ close();
1745
+ };
1746
+ signal.addEventListener("abort", () => {
1747
+ stop();
1748
+ try {
1749
+ controller.close();
1750
+ } catch {}
1751
+ });
1752
+ },
1753
+ cancel: stop
1754
+ });
1755
+ return new Response(body, { headers: {
1756
+ "Content-Type": "text/event-stream",
1757
+ "Cache-Control": "no-cache, no-transform",
1758
+ "X-Accel-Buffering": "no"
1759
+ } });
1760
+ }
1761
+ // src/server/media.ts
1762
+ /** Raster images only: an SVG opened directly could run script on this origin. */
1763
+ const IMAGE_MIME = {
1764
+ png: "image/png",
1765
+ jpg: "image/jpeg",
1766
+ jpeg: "image/jpeg",
1767
+ webp: "image/webp",
1768
+ gif: "image/gif",
1769
+ bmp: "image/bmp",
1770
+ avif: "image/avif"
1771
+ };
1772
+ const MAX_IMAGE_BYTES = 16777216;
1773
+ const extension = (path) => /\.([a-z0-9]+)$/i.exec(path)?.[1]?.toLowerCase() ?? "";
1774
+ const imageMime = (path) => IMAGE_MIME[extension(path)] ?? null;
1775
+ /** True when the daemon runs on this machine (loopback TCP/WebSocket or a local socket). */
1776
+ function isLocalConnection(connection) {
1777
+ try {
1778
+ const target = parseHostTarget(connection);
1779
+ if (target.kind !== "socket") return false;
1780
+ if (target.socketPath) return true;
1781
+ const host = new URL(target.url ?? "").hostname.replace(/^\[|\]$/g, "");
1782
+ return host === "localhost" || host === "::1" || /^127\./.test(host);
1783
+ } catch {
1784
+ return false;
1785
+ }
1786
+ }
1787
+ /**
1788
+ * Images a provider returned inline (screenshots, `read` of a PNG) are written by the daemon to
1789
+ * `<tmp>/paseo-attachments-XXXXXX/<sha256>.<ext>` and referenced from the message as file:// URLs.
1790
+ * The daemon's file API is confined to the workspace, so these are read from disk, and only when
1791
+ * the daemon shares this machine. The name pattern admits nothing but those materialized files.
1792
+ */
1793
+ function isMaterializedImagePath(path) {
1794
+ if (!isAbsolute(path) || normalize(path) !== path || !imageMime(path)) return false;
1795
+ const directory = dirname(path);
1796
+ 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));
1797
+ }
1798
+ async function readMaterializedImage(path) {
1799
+ if (!isMaterializedImagePath(path)) return null;
1800
+ try {
1801
+ const stats = await lstat(path);
1802
+ if (!stats.isFile() || stats.size > 16777216) return null;
1803
+ if (!isMaterializedImagePath(await realpath(path))) return null;
1804
+ return await readFile(path);
1805
+ } catch {
1806
+ return null;
1807
+ }
1808
+ }
1809
+ /** Small LRU for project icons: a sidebar asks for each project once per page load. */
1810
+ var IconCache = class {
1811
+ entries = /* @__PURE__ */ new Map();
1812
+ limit;
1813
+ ttlMs;
1814
+ constructor(limit = 256, ttlMs = 6e5) {
1815
+ this.limit = limit;
1816
+ this.ttlMs = ttlMs;
1817
+ }
1818
+ get(key) {
1819
+ const entry = this.entries.get(key);
1820
+ if (!entry) return void 0;
1821
+ if (Date.now() - entry.at > this.ttlMs) {
1822
+ this.entries.delete(key);
1823
+ return;
1824
+ }
1825
+ this.entries.delete(key);
1826
+ this.entries.set(key, entry);
1827
+ return entry.icon;
1828
+ }
1829
+ set(key, icon) {
1830
+ this.entries.delete(key);
1831
+ this.entries.set(key, {
1832
+ at: Date.now(),
1833
+ icon
1834
+ });
1835
+ if (this.entries.size > this.limit) this.entries.delete(this.entries.keys().next().value);
1836
+ }
1837
+ };
1838
+ // src/server/workspace-routes.ts
1839
+ /** Text files larger than this open truncated: the viewer is for reading, not for dumps. */
1840
+ const MAX_TEXT_BYTES = 1048576;
1841
+ const MAX_ENTRIES = 2e3;
1842
+ /** Terminal output is coalesced into one event per frame-ish interval. */
1843
+ const TERMINAL_FLUSH_MS = 16;
1844
+ const path = z.string().min(1).max(4096).refine((p) => !p.includes("\0"));
1845
+ /**
1846
+ * The workspace side panel (files, terminals) and schedules. Every call goes to the host's
1847
+ * daemon, which confines file access to the workspace and owns the terminals; nothing here
1848
+ * keeps state beyond an open terminal stream.
1849
+ */
1850
+ function registerWorkspaceRoutes(app, hosts, store, valid) {
1851
+ app.get("/api/hosts/:host/fs/list", async (c) => {
1852
+ const cwd = path.parse(c.req.query("cwd"));
1853
+ const dir = c.req.query("path") || ".";
1854
+ const { driver } = hosts.get(c.req.param("host"));
1855
+ try {
1856
+ const result = await driver.listDirectory(cwd, dir);
1857
+ const entries = (result.entries ?? []).map((e) => ({
1858
+ name: e.name,
1859
+ path: e.path,
1860
+ kind: e.kind,
1861
+ size: e.size
1862
+ })).sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name, void 0, { numeric: true }) : a.kind === "directory" ? -1 : 1);
1863
+ return c.json({
1864
+ path: result.path,
1865
+ entries: entries.slice(0, MAX_ENTRIES),
1866
+ truncated: entries.length > MAX_ENTRIES
1867
+ });
1868
+ } catch (error) {
1869
+ return c.json({ error: error.message || "Directory unavailable" }, 404);
1870
+ }
1871
+ });
1872
+ app.get("/api/hosts/:host/fs/read", async (c) => {
1873
+ const cwd = path.parse(c.req.query("cwd"));
1874
+ const file = path.parse(c.req.query("path"));
1875
+ const { driver } = hosts.get(c.req.param("host"));
1876
+ try {
1877
+ const result = await driver.readFile(cwd, file, void 0, 1048577);
1878
+ const text = result.kind === "text" ? new TextDecoder().decode(result.bytes.subarray(0, MAX_TEXT_BYTES)) : void 0;
1879
+ return c.json({
1880
+ path: result.path,
1881
+ kind: result.kind,
1882
+ mime: result.mime,
1883
+ size: result.size,
1884
+ modifiedAt: result.modifiedAt,
1885
+ ...text !== void 0 ? {
1886
+ text,
1887
+ truncated: result.size > MAX_TEXT_BYTES
1888
+ } : {}
1889
+ });
1890
+ } catch (error) {
1891
+ return c.json({ error: error.message || "File unavailable" }, 404);
1892
+ }
1893
+ });
1894
+ app.get("/api/hosts/:host/fs/raw", async (c) => {
1895
+ const cwd = path.parse(c.req.query("cwd"));
1896
+ const file = path.parse(c.req.query("path"));
1897
+ const mime = imageMime(file);
1898
+ if (!mime) return c.json({ error: "Only images can be opened raw" }, 415);
1899
+ const { driver } = hosts.get(c.req.param("host"));
1900
+ try {
1901
+ const result = await driver.readFile(cwd, file, void 0, MAX_IMAGE_BYTES);
1902
+ return c.body(result.bytes, 200, {
1903
+ "Content-Type": mime,
1904
+ "Cache-Control": "private, max-age=60"
1905
+ });
1906
+ } catch {
1907
+ return c.json({ error: "Image unavailable" }, 404);
1908
+ }
1909
+ });
1910
+ app.get("/api/hosts/:host/terminals", async (c) => {
1911
+ const cwd = path.parse(c.req.query("cwd"));
1912
+ const result = await hosts.get(c.req.param("host")).driver.listTerminals(cwd);
1913
+ return c.json((result.terminals ?? []).map((t) => ({
1914
+ id: t.id,
1915
+ name: t.name,
1916
+ title: t.title ?? null,
1917
+ cwd: t.cwd
1918
+ })));
1919
+ });
1920
+ app.post("/api/hosts/:host/terminals", async (c) => {
1921
+ const input = z.object({
1922
+ cwd: path,
1923
+ rows: z.number().int().min(4).max(500),
1924
+ cols: z.number().int().min(10).max(1e3),
1925
+ name: z.string().max(80).optional()
1926
+ }).parse(await c.req.json());
1927
+ const result = await hosts.get(c.req.param("host")).driver.createTerminal(input.cwd, input.name, void 0, { size: {
1928
+ rows: input.rows,
1929
+ cols: input.cols
1930
+ } });
1931
+ if (!result.terminal) return c.json({ error: result.error ?? "Could not open a terminal" }, 502);
1932
+ return c.json({
1933
+ id: result.terminal.id,
1934
+ name: result.terminal.name,
1935
+ title: result.terminal.title ?? null,
1936
+ cwd: result.terminal.cwd
1937
+ }, 201);
1938
+ });
1939
+ app.delete("/api/hosts/:host/terminals/:id", async (c) => {
1940
+ await hosts.get(c.req.param("host")).driver.killTerminal(c.req.param("id"));
1941
+ return c.json({ ok: true });
1942
+ });
1943
+ app.post("/api/hosts/:host/terminals/:id/input", async (c) => {
1944
+ const input = z.union([z.object({ data: z.string().min(1).max(65536) }), z.object({
1945
+ rows: z.number().int().min(4).max(500),
1946
+ cols: z.number().int().min(10).max(1e3)
1947
+ })]).parse(await c.req.json());
1948
+ const { driver } = hosts.get(c.req.param("host"));
1949
+ driver.sendTerminalInput(c.req.param("id"), "data" in input ? {
1950
+ type: "input",
1951
+ data: input.data
1952
+ } : {
1953
+ type: "resize",
1954
+ rows: input.rows,
1955
+ cols: input.cols
1956
+ });
1957
+ return c.json({ ok: true });
1958
+ });
1959
+ /** Live output as SSE: a full replay first (scrollback), then coalesced output chunks. */
1960
+ app.get("/api/hosts/:host/terminals/:id/stream", (c) => {
1961
+ const { driver } = hosts.get(c.req.param("host"));
1962
+ const id = c.req.param("id");
1963
+ const rows = Number(c.req.query("rows")) || 24, cols = Number(c.req.query("cols")) || 80;
1964
+ return eventStream(c.req.raw.signal, (send) => {
1965
+ let pending = [];
1966
+ let timer;
1967
+ const flush = () => {
1968
+ timer = void 0;
1969
+ if (!pending.length) return;
1970
+ send({
1971
+ t: "o",
1972
+ d: Buffer.concat(pending).toString("base64")
1973
+ });
1974
+ pending = [];
1975
+ };
1976
+ const push = (bytes) => {
1977
+ pending.push(bytes);
1978
+ timer ??= setTimeout(flush, TERMINAL_FLUSH_MS);
1979
+ };
1980
+ const subscription = driver.observeTerminal(id, (event) => {
1981
+ if (event.type === "output") push(event.data);
1982
+ else if (event.replay.type === "begin") {
1983
+ pending = [];
1984
+ send({ t: "reset" });
1985
+ } else if (event.replay.type === "data") push(event.replay.data);
1986
+ }, { restore: {
1987
+ mode: "full-snapshot",
1988
+ scrollbackLines: 2e3,
1989
+ size: {
1990
+ rows,
1991
+ cols
1992
+ }
1993
+ } });
1994
+ const stop = subscription.subscribe({
1995
+ snapshot: () => {},
1996
+ update: (message) => {
1997
+ if (message.type === "terminal_stream_exit") send({ t: "exit" });
1998
+ },
1999
+ error: () => send({ t: "exit" })
2000
+ });
2001
+ subscription.ready.catch(() => send({ t: "exit" }));
2002
+ return () => {
2003
+ clearTimeout(timer);
2004
+ stop();
2005
+ subscription.release().catch(() => {});
2006
+ };
2007
+ }, valid(c));
2008
+ });
2009
+ /** Every connected host's schedules; a host that fails reports its error instead. */
2010
+ app.get("/api/schedules", async (c) => {
2011
+ const results = await Promise.all(store.hosts().map(async (h) => {
2012
+ try {
2013
+ if (hosts.state(h.id) !== "connected") return {
2014
+ hostId: h.id,
2015
+ schedules: [],
2016
+ error: "Host is offline"
2017
+ };
2018
+ const list = await hosts.get(h.id).driver.scheduleList();
2019
+ return {
2020
+ hostId: h.id,
2021
+ schedules: list.schedules ?? [],
2022
+ error: list.error ?? null
2023
+ };
2024
+ } catch (error) {
2025
+ return {
2026
+ hostId: h.id,
2027
+ schedules: [],
2028
+ error: error.message || "Schedules unavailable"
2029
+ };
2030
+ }
2031
+ }));
2032
+ return c.json(results);
2033
+ });
2034
+ app.post("/api/hosts/:host/schedules", async (c) => {
2035
+ const input = z.object({
2036
+ name: z.string().trim().max(120).optional(),
2037
+ prompt: z.string().trim().min(1).max(2e4),
2038
+ cron: z.string().trim().min(9).max(120),
2039
+ timezone: z.string().max(80).optional(),
2040
+ cwd: path,
2041
+ provider: z.string().min(1).max(200),
2042
+ model: z.string().min(1).max(300).optional(),
2043
+ thinkingOptionId: z.string().min(1).max(200).optional(),
2044
+ archiveOnFinish: z.boolean().default(true),
2045
+ runOnCreate: z.boolean().default(false)
2046
+ }).parse(await c.req.json());
2047
+ const result = await hosts.get(c.req.param("host")).driver.scheduleCreate({
2048
+ prompt: input.prompt,
2049
+ name: input.name || null,
2050
+ cadence: {
2051
+ type: "cron",
2052
+ expression: input.cron,
2053
+ ...input.timezone ? { timezone: input.timezone } : {}
2054
+ },
2055
+ target: {
2056
+ type: "new-agent",
2057
+ config: {
2058
+ provider: input.provider,
2059
+ cwd: input.cwd,
2060
+ ...input.model ? { model: input.model } : {},
2061
+ ...input.thinkingOptionId ? { thinkingOptionId: input.thinkingOptionId } : {},
2062
+ archiveOnFinish: input.archiveOnFinish,
2063
+ isolation: "local",
2064
+ title: input.name || null
2065
+ }
2066
+ },
2067
+ runOnCreate: input.runOnCreate
2068
+ });
2069
+ if (result.error) return c.json({ error: result.error }, 400);
2070
+ return c.json(result.schedule, 201);
2071
+ });
2072
+ app.patch("/api/hosts/:host/schedules/:id", async (c) => {
2073
+ const input = z.object({
2074
+ name: z.string().trim().max(120).nullable().optional(),
2075
+ prompt: z.string().trim().min(1).max(2e4).optional(),
2076
+ cron: z.string().trim().min(9).max(120).optional(),
2077
+ timezone: z.string().max(80).optional(),
2078
+ cwd: path.optional(),
2079
+ provider: z.string().min(1).max(200).optional(),
2080
+ model: z.string().min(1).max(300).nullable().optional(),
2081
+ archiveOnFinish: z.boolean().optional()
2082
+ }).parse(await c.req.json());
2083
+ const agentConfig = {
2084
+ ...input.provider ? { provider: input.provider } : {},
2085
+ ...input.model !== void 0 ? { model: input.model } : {},
2086
+ ...input.cwd ? { cwd: input.cwd } : {},
2087
+ ...input.archiveOnFinish !== void 0 ? { archiveOnFinish: input.archiveOnFinish } : {}
2088
+ };
2089
+ const result = await hosts.get(c.req.param("host")).driver.scheduleUpdate({
2090
+ id: c.req.param("id"),
2091
+ ...input.name !== void 0 ? { name: input.name || null } : {},
2092
+ ...input.prompt ? { prompt: input.prompt } : {},
2093
+ ...input.cron ? { cadence: {
2094
+ type: "cron",
2095
+ expression: input.cron,
2096
+ ...input.timezone ? { timezone: input.timezone } : {}
2097
+ } } : {},
2098
+ ...Object.keys(agentConfig).length ? { newAgentConfig: agentConfig } : {}
2099
+ });
2100
+ if (result?.error) return c.json({ error: result.error }, 400);
2101
+ return c.json(result?.schedule ?? { ok: true });
2102
+ });
2103
+ const action = (name) => async (c) => {
2104
+ const { driver } = hosts.get(c.req.param("host"));
2105
+ const options = { id: c.req.param("id") };
2106
+ 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);
2107
+ if (result?.error) return c.json({ error: result.error }, 400);
2108
+ return c.json(name === "logs" ? { runs: (result.runs ?? []).slice(-50).reverse() } : { ok: true });
2109
+ };
2110
+ app.post("/api/hosts/:host/schedules/:id/pause", action("pause"));
2111
+ app.post("/api/hosts/:host/schedules/:id/resume", action("resume"));
2112
+ app.post("/api/hosts/:host/schedules/:id/run", action("run"));
2113
+ app.delete("/api/hosts/:host/schedules/:id", action("delete"));
2114
+ app.get("/api/hosts/:host/schedules/:id/logs", action("logs"));
2115
+ }
1705
2116
  // src/server/attachments.ts
1706
2117
  const MAX_FILE_BYTES = 8388608;
1707
2118
  const MAX_TOTAL = 67108864;
@@ -1900,12 +2311,9 @@ const SESSION_TTL_MS = 2592e6;
1900
2311
  const TOUCH_INTERVAL_MS = 36e5;
1901
2312
  const TOTP_PERIOD_S = 30;
1902
2313
  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.
2314
+ /** Only clients that know the access token can reach TOTP verification.
2315
+ * Code attempts have a persistent server-wide budget across IPs and restarts.
2316
+ * Exhausting it doubles the lockout from 15 minutes to at most 24 hours.
1909
2317
  */
1910
2318
  const WINDOW_MS = 9e5;
1911
2319
  const MAX_CODE_FAILURES_PER_CLIENT = 5;
@@ -1971,7 +2379,7 @@ const equalSecret = (a, b) => {
1971
2379
  return x.length === y.length && timingSafeEqual(x, y);
1972
2380
  };
1973
2381
  /**
1974
- * Login and sessions. A browser signs in once, with the access token or an authenticator code,
2382
+ * Login and sessions. A browser signs in once, with the access token and, when enabled, an authenticator code,
1975
2383
  * and receives an opaque session secret (stored only as a hash). Sessions are listed and
1976
2384
  * revocable; revoking one also drops the push subscriptions it registered.
1977
2385
  */
@@ -1989,6 +2397,19 @@ var Auth = class {
1989
2397
  constructor(store, token) {
1990
2398
  this.store = store;
1991
2399
  this.token = token;
2400
+ const saved = store.setting("totp_login_limit");
2401
+ if (saved) this.global = JSON.parse(saved);
2402
+ if (store.setting("auth_policy") !== "token-plus-totp-v1") {
2403
+ store.db.exec("BEGIN IMMEDIATE");
2404
+ try {
2405
+ if (this.totpEnabled()) store.revokeSessions();
2406
+ store.setSetting("auth_policy", "token-plus-totp-v1");
2407
+ store.db.exec("COMMIT");
2408
+ } catch (error) {
2409
+ store.db.exec("ROLLBACK");
2410
+ throw error;
2411
+ }
2412
+ }
1992
2413
  }
1993
2414
  totpEnabled() {
1994
2415
  return this.store.setting("totp_secret") !== null;
@@ -1998,33 +2419,39 @@ var Auth = class {
1998
2419
  return equalSecret(token, this.token);
1999
2420
  }
2000
2421
  login(input, client, label, now = Date.now()) {
2001
- const usesCode = !input.token;
2002
- const limited = this.limited(client, usesCode, now);
2003
- if (limited) return {
2422
+ const tokenLimit = this.limited(client, false, now);
2423
+ if (tokenLimit) return {
2004
2424
  ok: false,
2005
2425
  status: 429,
2006
- retryAfter: limited
2426
+ retryAfter: tokenLimit
2007
2427
  };
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);
2428
+ if (!input.token || !this.checkToken(input.token)) {
2429
+ this.fail(client, false, now);
2017
2430
  return {
2018
2431
  ok: false,
2019
2432
  status: 401
2020
2433
  };
2021
2434
  }
2022
- (usesCode ? this.codeFailures : this.tokenFailures).delete(client);
2023
- if (usesCode) this.global = {
2024
- count: 0,
2025
- reset: 0,
2026
- lockMs: WINDOW_MS
2027
- };
2435
+ const totpSecret = this.store.setting("totp_secret");
2436
+ if (totpSecret) {
2437
+ const codeLimit = this.limited(client, true, now);
2438
+ if (codeLimit) return {
2439
+ ok: false,
2440
+ status: 429,
2441
+ retryAfter: codeLimit
2442
+ };
2443
+ const step = matchTotp(base32Decode(totpSecret), input.code ?? "", now);
2444
+ if (step === null || !this.store.advanceSetting("totp_last_step", step)) {
2445
+ this.fail(client, true, now);
2446
+ return {
2447
+ ok: false,
2448
+ status: 401
2449
+ };
2450
+ }
2451
+ this.codeFailures.delete(client);
2452
+ this.resetCodeLimit();
2453
+ }
2454
+ this.tokenFailures.delete(client);
2028
2455
  const secret = randomBytes(32).toString("base64url");
2029
2456
  const session = {
2030
2457
  id: randomUUID(),
@@ -2070,6 +2497,7 @@ var Auth = class {
2070
2497
  this.store.revokeSessions(sessionId);
2071
2498
  }
2072
2499
  beginTotp(sessionId, now = Date.now()) {
2500
+ if (this.totpEnabled()) throw new Error("Disable the current authenticator before replacing it");
2073
2501
  const secret = base32Encode(randomBytes(20));
2074
2502
  this.pendingTotp = {
2075
2503
  secret,
@@ -2083,25 +2511,51 @@ var Auth = class {
2083
2511
  }
2084
2512
  /** Enables the pending secret once the user proves their app produces matching codes. */
2085
2513
  confirmTotp(sessionId, code, now = Date.now()) {
2514
+ if (this.totpEnabled()) return false;
2086
2515
  const pending = this.pendingTotp;
2087
2516
  if (!pending || pending.sessionId !== sessionId || pending.expires < now) return false;
2088
2517
  const step = matchTotp(base32Decode(pending.secret), code, now);
2089
2518
  if (step === null) return false;
2090
- this.store.setSetting("totp_secret", pending.secret);
2091
- this.store.setSetting("totp_last_step", String(step));
2519
+ this.store.db.exec("BEGIN IMMEDIATE");
2520
+ try {
2521
+ this.store.setSetting("totp_secret", pending.secret);
2522
+ this.store.setSetting("totp_last_step", String(step));
2523
+ this.store.db.prepare("DELETE FROM push_subscriptions WHERE session_id<>?").run(sessionId);
2524
+ this.store.db.prepare("DELETE FROM sessions WHERE id<>?").run(sessionId);
2525
+ this.resetCodeLimit();
2526
+ this.store.db.exec("COMMIT");
2527
+ } catch (error) {
2528
+ this.store.db.exec("ROLLBACK");
2529
+ throw error;
2530
+ }
2092
2531
  this.pendingTotp = null;
2093
2532
  return true;
2094
2533
  }
2095
2534
  disableTotp(code, now = Date.now()) {
2535
+ if (this.limited("settings", true, now)) return false;
2096
2536
  const secret = this.store.setting("totp_secret");
2097
2537
  const step = secret ? matchTotp(base32Decode(secret), code, now) : null;
2098
- if (step === null || !this.store.advanceSetting("totp_last_step", step)) return false;
2538
+ if (step === null || !this.store.advanceSetting("totp_last_step", step)) {
2539
+ this.fail("settings", true, now);
2540
+ return false;
2541
+ }
2099
2542
  this.store.setSetting("totp_secret", null);
2543
+ this.resetCodeLimit();
2100
2544
  return true;
2101
2545
  }
2546
+ resetCodeLimit() {
2547
+ this.global = {
2548
+ count: 0,
2549
+ reset: 0,
2550
+ lockMs: WINDOW_MS
2551
+ };
2552
+ this.store.setSetting("totp_login_limit", JSON.stringify(this.global));
2553
+ }
2102
2554
  limited(client, usesCode, now) {
2103
2555
  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);
2556
+ const map = usesCode ? this.codeFailures : this.tokenFailures;
2557
+ if (!map.has(client) && map.size >= 1e4) client = "overflow";
2558
+ const entry = map.get(client);
2105
2559
  const max = usesCode ? MAX_CODE_FAILURES_PER_CLIENT : MAX_TOKEN_FAILURES_PER_CLIENT;
2106
2560
  if (entry && entry.reset > now && entry.count >= max) return Math.ceil((entry.reset - now) / 1e3);
2107
2561
  return 0;
@@ -2114,15 +2568,16 @@ var Auth = class {
2114
2568
  this.global.reset = now + this.global.lockMs;
2115
2569
  this.global.lockMs = Math.min(this.global.lockMs * 2, MAX_LOCK_MS);
2116
2570
  } else if (this.global.reset <= now) this.global.reset = now + WINDOW_MS;
2571
+ this.store.setSetting("totp_login_limit", JSON.stringify(this.global));
2117
2572
  }
2118
2573
  const map = usesCode ? this.codeFailures : this.tokenFailures;
2574
+ if (!map.has(client) && map.size >= 1e4) client = "overflow";
2119
2575
  let entry = map.get(client);
2120
2576
  if (!entry || entry.reset <= now) map.set(client, entry = {
2121
2577
  count: 0,
2122
2578
  reset: now + WINDOW_MS
2123
2579
  });
2124
2580
  entry.count++;
2125
- if (map.size > 1e4) map.clear();
2126
2581
  }
2127
2582
  };
2128
2583
  // src/shared/wire.ts
@@ -2349,8 +2804,9 @@ var UsageService = class {
2349
2804
  };
2350
2805
  // src/server/app.ts
2351
2806
  const AGENT_FLUSH_MS = 100;
2807
+ /** Five minutes of 16 kHz, 16-bit mono speech. */
2808
+ const MAX_DICTATION_BYTES = 96e5;
2352
2809
  const HOST_FLUSH_MS = 100;
2353
- const HEARTBEAT_MS = 2e4;
2354
2810
  function parseJson(text) {
2355
2811
  try {
2356
2812
  return JSON.parse(text ?? "null");
@@ -2358,50 +2814,6 @@ function parseJson(text) {
2358
2814
  return null;
2359
2815
  }
2360
2816
  }
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
2817
  const card = z.object({
2406
2818
  id: z.string().uuid(),
2407
2819
  title: z.string().min(1).max(300),
@@ -2421,6 +2833,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
2421
2833
  const app = new Hono();
2422
2834
  const auth = new Auth(store, token);
2423
2835
  const attachments = new Attachments();
2836
+ const projectIcons = new IconCache();
2424
2837
  const viewers = /* @__PURE__ */ new Map();
2425
2838
  const notifier = new Notifier({
2426
2839
  store,
@@ -2439,11 +2852,11 @@ function createApp(store, hosts, token, webRoot, options = {}) {
2439
2852
  c.header("Referrer-Policy", "no-referrer");
2440
2853
  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
2854
  });
2442
- app.use("/api/*", (c, next) => bodyLimit({ maxSize: c.req.method === "POST" && c.req.path.endsWith("/attachments") ? MAX_FILE_BYTES : 1048576 })(c, next));
2855
+ app.use("/api/*", (c, next) => bodyLimit({ maxSize: c.req.method !== "POST" ? 1048576 : c.req.path.endsWith("/attachments") ? MAX_FILE_BYTES : c.req.path.endsWith("/dictation") ? MAX_DICTATION_BYTES : 1048576 })(c, next));
2443
2856
  app.use("/api/*", async (c, next) => {
2444
2857
  c.header("Cache-Control", "no-store");
2445
2858
  const bearer = c.req.header("authorization")?.replace(/^Bearer /, "");
2446
- if (bearer && !PUBLIC_API.has(c.req.path) && auth.checkToken(bearer)) {
2859
+ if (bearer && !PUBLIC_API.has(c.req.path) && !auth.totpEnabled() && auth.checkToken(bearer)) {
2447
2860
  c.set("session", null);
2448
2861
  return next();
2449
2862
  }
@@ -2474,7 +2887,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
2474
2887
  const input = z.object({
2475
2888
  token: z.string().min(1).max(200).optional(),
2476
2889
  code: z.string().regex(/^\d{6}$/).optional()
2477
- }).refine((x) => !!x.token !== !!x.code).parse(await c.req.json());
2890
+ }).refine((x) => !!x.token || !!x.code).parse(await c.req.json());
2478
2891
  const userAgent = c.req.header("user-agent") ?? "";
2479
2892
  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
2893
  const result = auth.login(input, clientId(c), label);
@@ -2528,6 +2941,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
2528
2941
  };
2529
2942
  app.post("/api/totp/setup", async (c) => {
2530
2943
  const session = requireSession(c.get("session"));
2944
+ if (auth.totpEnabled()) return c.json({ error: "Disable the current authenticator before replacing it." }, 409);
2531
2945
  const { secret, uri } = auth.beginTotp(session.id);
2532
2946
  const qr = await QRCode.toString(uri, {
2533
2947
  type: "svg",
@@ -2689,7 +3103,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
2689
3103
  for (const stream of directoryStreams) stream.send(message);
2690
3104
  }, HOST_FLUSH_MS);
2691
3105
  });
2692
- const streamValidity = (session) => session ? () => auth.stillValid(session.id) : () => true;
3106
+ const streamValidity = (session) => session ? () => auth.stillValid(session.id) : () => !auth.totpEnabled();
2693
3107
  app.get("/api/stream", (c) => {
2694
3108
  const since = Number(c.req.query("since"));
2695
3109
  const resumable = c.req.query("generation") === hosts.agents.generation && Number.isInteger(since);
@@ -2869,6 +3283,150 @@ function createApp(store, hosts, token, webRoot, options = {}) {
2869
3283
  }))
2870
3284
  });
2871
3285
  });
3286
+ /**
3287
+ * An image an agent referenced in a message (`![](file:///…)`, an absolute or workspace path).
3288
+ * Workspace files go through the daemon's file API; images the daemon materialized from
3289
+ * provider output live outside the workspace and are read from disk when the daemon is local.
3290
+ */
3291
+ app.get("/api/hosts/:host/agents/:agent/image", async (c) => {
3292
+ const hostId = c.req.param("host");
3293
+ const path = z.string().min(1).max(4096).refine((p) => !p.includes("\0")).parse(c.req.query("path"));
3294
+ const mime = imageMime(path);
3295
+ if (!mime) return c.json({ error: "Not an image" }, 415);
3296
+ const { driver } = hosts.get(hostId);
3297
+ const cwd = hosts.agents.get(`${hostId}:${c.req.param("agent")}`)?.cwd;
3298
+ let bytes = null;
3299
+ if (isMaterializedImagePath(path)) {
3300
+ const host = store.hosts().find((h) => h.id === hostId);
3301
+ if (host && isLocalConnection(host.connection)) bytes = await readMaterializedImage(path);
3302
+ } else if (cwd) try {
3303
+ const file = await driver.readFile(cwd, path, void 0, MAX_IMAGE_BYTES);
3304
+ if (file.size <= 16777216) bytes = file.bytes;
3305
+ } catch {
3306
+ bytes = null;
3307
+ }
3308
+ if (!bytes) return c.json({ error: "Image unavailable from this host" }, 404);
3309
+ return c.body(bytes, 200, {
3310
+ "Content-Type": mime,
3311
+ "Cache-Control": "private, max-age=86400",
3312
+ "Content-Disposition": "inline"
3313
+ });
3314
+ });
3315
+ /** A project's icon (favicon/logo the daemon found in its root), cached briefly per host. */
3316
+ app.get("/api/hosts/:host/project-icon", async (c) => {
3317
+ const hostId = c.req.param("host");
3318
+ const cwd = z.string().min(1).max(4096).parse(c.req.query("cwd"));
3319
+ const key = `${hostId}\n${cwd}`;
3320
+ let icon = projectIcons.get(key);
3321
+ if (icon === void 0) {
3322
+ try {
3323
+ const result = await hosts.get(hostId).driver.requestProjectIcon(cwd);
3324
+ icon = result.icon && /^image\/(png|jpeg|webp|gif|x-icon|vnd\.microsoft\.icon)$/.test(result.icon.mimeType) ? {
3325
+ data: Buffer.from(result.icon.data, "base64"),
3326
+ mimeType: result.icon.mimeType
3327
+ } : null;
3328
+ } catch (error) {
3329
+ if (error instanceof UnknownHostError) throw error;
3330
+ return c.json({ error: "Icon unavailable" }, 502);
3331
+ }
3332
+ projectIcons.set(key, icon);
3333
+ }
3334
+ if (!icon) return c.body(null, 204, { "Cache-Control": "private, max-age=600" });
3335
+ return c.body(icon.data, 200, {
3336
+ "Content-Type": icon.mimeType,
3337
+ "Cache-Control": "private, max-age=600"
3338
+ });
3339
+ });
3340
+ /** What the open agent can switch to. Modes/features come from the live directory (no round trip). */
3341
+ app.get("/api/hosts/:host/agents/:agent/config", async (c) => {
3342
+ const hostId = c.req.param("host");
3343
+ const client = hosts.get(hostId);
3344
+ const facts = client.directory.facts(c.req.param("agent"));
3345
+ if (!facts) return c.json({ error: "Unknown agent" }, 404);
3346
+ const options = {
3347
+ models: ((await client.api.providers.snapshot()).entries.find((p) => p.provider === facts.provider)?.models ?? []).filter((m) => m.isSelectable !== false).map((m) => ({
3348
+ id: m.id,
3349
+ label: m.label,
3350
+ thinking: (m.thinkingOptions ?? []).map((t) => ({
3351
+ id: t.id,
3352
+ label: t.label
3353
+ })),
3354
+ defaultThinkingId: m.defaultThinkingOptionId ?? null
3355
+ })),
3356
+ modes: facts.availableModes.map((m) => ({
3357
+ id: m.id,
3358
+ label: m.label,
3359
+ ...m.description ? { description: m.description } : {}
3360
+ })),
3361
+ features: facts.features.map((f) => f.type === "toggle" ? {
3362
+ type: "toggle",
3363
+ id: f.id,
3364
+ label: f.label,
3365
+ ...f.tooltip ? { tooltip: f.tooltip } : {},
3366
+ value: f.value
3367
+ } : {
3368
+ type: "select",
3369
+ id: f.id,
3370
+ label: f.label,
3371
+ ...f.tooltip ? { tooltip: f.tooltip } : {},
3372
+ value: f.value,
3373
+ options: f.options.map((o) => ({
3374
+ id: o.id,
3375
+ label: o.label
3376
+ }))
3377
+ })
3378
+ };
3379
+ return c.json(options);
3380
+ });
3381
+ app.post("/api/hosts/:host/agents/:agent/config", async (c) => {
3382
+ const change = z.object({
3383
+ model: z.string().min(1).max(300).optional(),
3384
+ thinkingOptionId: z.string().min(1).max(200).optional(),
3385
+ modeId: z.string().min(1).max(200).optional(),
3386
+ feature: z.object({
3387
+ id: z.string().min(1).max(200),
3388
+ value: z.union([z.string().max(200), z.boolean()])
3389
+ }).optional()
3390
+ }).refine((v) => Object.values(v).filter((x) => x !== void 0).length === 1).parse(await c.req.json());
3391
+ const { driver } = hosts.get(c.req.param("host"));
3392
+ const agent = c.req.param("agent");
3393
+ let notice = null;
3394
+ if (change.model) await driver.setAgentModel(agent, change.model);
3395
+ else if (change.thinkingOptionId) notice = await driver.setAgentThinkingOption(agent, change.thinkingOptionId);
3396
+ else if (change.modeId) notice = await driver.setAgentMode(agent, change.modeId);
3397
+ else if (change.feature) await driver.setAgentFeature(agent, change.feature.id, change.feature.value);
3398
+ return c.json({
3399
+ ok: true,
3400
+ notice
3401
+ });
3402
+ });
3403
+ /**
3404
+ * Speech to text through the host's own dictation service (its configured STT provider). The
3405
+ * browser records 16 kHz mono PCM and posts it once when the user stops: one request, no
3406
+ * socket kept open while idle.
3407
+ */
3408
+ app.post("/api/hosts/:host/dictation", async (c) => {
3409
+ const format = c.req.header("x-audio-format") ?? "";
3410
+ if (!/^audio\/pcm;rate=\d{4,6};bits=16$/.test(format)) return c.json({ error: "Unsupported audio format" }, 415);
3411
+ const audio = Buffer.from(await c.req.arrayBuffer());
3412
+ if (audio.length < 3200 || audio.length % 2) return c.json({ error: "Recording too short" }, 400);
3413
+ const { driver } = hosts.get(c.req.param("host"));
3414
+ const id = randomUUID();
3415
+ try {
3416
+ await driver.startDictationStream(id, format);
3417
+ const CHUNK = 32e3;
3418
+ let seq = 0;
3419
+ for (let offset = 0; offset < audio.length; offset += CHUNK, seq++) driver.sendDictationStreamChunk(id, seq, audio.subarray(offset, offset + CHUNK).toString("base64"), format);
3420
+ const result = await driver.finishDictationStream(id, seq - 1);
3421
+ return c.json({ text: result.text });
3422
+ } catch (error) {
3423
+ try {
3424
+ driver.cancelDictationStream(id);
3425
+ } catch {}
3426
+ const message = error instanceof Error ? error.message : "";
3427
+ return c.json({ error: /disabled|not enabled|unavailable|not configured/i.test(message) ? "Dictation is not enabled on this host. Turn it on in the host's Paseo settings." : "Transcription failed" + (message ? `: ${message.slice(0, 200)}` : "") }, 502);
3428
+ }
3429
+ });
2872
3430
  const attachmentOwner = (c) => c.get("session")?.id ?? "bearer";
2873
3431
  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
3432
  app.post("/api/hosts/:host/agents/:agent/attachments", async (c) => {
@@ -3008,6 +3566,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3008
3566
  });
3009
3567
  }
3010
3568
  });
3569
+ registerWorkspaceRoutes(app, hosts, store, (c) => streamValidity(c.get("session")));
3011
3570
  app.get("/api/usage", async (c) => c.json(await usage.report(c.req.query("refresh") === "1")));
3012
3571
  app.get("/api/board", (c) => c.json(store.board()));
3013
3572
  app.put("/api/board", async (c) => {
@@ -3295,7 +3854,7 @@ async function main() {
3295
3854
  if (command === "help" || command === "--help") {
3296
3855
  console.log([
3297
3856
  "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)",
3857
+ " token print the access token (required for sign-in)",
3299
3858
  " totp-reset turn off authenticator sign-in (lost phone)",
3300
3859
  " signout-all revoke every signed-in browser and its notifications",
3301
3860
  `Data: ${directory}`,