litepaseo 0.3.0 → 0.4.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 (109) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +68 -18
  3. package/dist/server/cli.mjs +837 -37
  4. package/dist/web/assets/{CodeBlockNode-D-c_NpDN.js → CodeBlockNode-BOQ7WC72.js} +1 -1
  5. package/dist/web/assets/CodeBlockNode-BOQ7WC72.js.br +0 -0
  6. package/dist/web/assets/CodeBlockNode-BOQ7WC72.js.gz +0 -0
  7. package/dist/web/assets/FileViewer-16UXxzOe.js +2 -0
  8. package/dist/web/assets/FileViewer-16UXxzOe.js.br +0 -0
  9. package/dist/web/assets/FileViewer-16UXxzOe.js.gz +0 -0
  10. package/dist/web/assets/FileViewer-T756VVq4.css +1 -0
  11. package/dist/web/assets/FileViewer-T756VVq4.css.br +0 -0
  12. package/dist/web/assets/FileViewer-T756VVq4.css.gz +0 -0
  13. package/dist/web/assets/{FilesPanel-CNkBvKGD.js → FilesPanel-CdDybrQn.js} +1 -1
  14. package/dist/web/assets/FilesPanel-CdDybrQn.js.br +0 -0
  15. package/dist/web/assets/FilesPanel-CdDybrQn.js.gz +0 -0
  16. package/dist/web/assets/MarkdownMessage-Bm42-B56.js +199 -0
  17. package/dist/web/assets/MarkdownMessage-Bm42-B56.js.br +0 -0
  18. package/dist/web/assets/MarkdownMessage-Bm42-B56.js.gz +0 -0
  19. package/dist/web/assets/{PreCodeBlock-BitPoeXT.js → PreCodeBlock-BiQ6xAvM.js} +1 -1
  20. package/dist/web/assets/{PreCodeBlock.vue_vue_type_style_index_0_lang-DVJqSz-5.js → PreCodeBlock.vue_vue_type_style_index_0_lang-DUZXIc-h.js} +1 -1
  21. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DUZXIc-h.js.br +0 -0
  22. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DUZXIc-h.js.gz +0 -0
  23. package/dist/web/assets/{TerminalPanel-CpGnkfa7.js → TerminalPanel-B5K5NCf0.js} +1 -1
  24. package/dist/web/assets/TerminalPanel-B5K5NCf0.js.br +0 -0
  25. package/dist/web/assets/TerminalPanel-B5K5NCf0.js.gz +0 -0
  26. package/dist/web/assets/{Tooltip-C9GHriiI.js → Tooltip-ClqPy17d.js} +1 -1
  27. package/dist/web/assets/Tooltip-ClqPy17d.js.br +0 -0
  28. package/dist/web/assets/Tooltip-ClqPy17d.js.gz +0 -0
  29. package/dist/web/assets/highlight-BnTrj1LT.js +5 -0
  30. package/dist/web/assets/highlight-BnTrj1LT.js.br +0 -0
  31. package/dist/web/assets/highlight-BnTrj1LT.js.gz +0 -0
  32. package/dist/web/assets/index-By8I8BM7.js +32 -0
  33. package/dist/web/assets/index-By8I8BM7.js.br +0 -0
  34. package/dist/web/assets/index-By8I8BM7.js.gz +0 -0
  35. package/dist/web/assets/index-CITaZKmy.css +1 -0
  36. package/dist/web/assets/index-CITaZKmy.css.br +0 -0
  37. package/dist/web/assets/index-CITaZKmy.css.gz +0 -0
  38. package/dist/web/assets/{index10-QexvIpKb.js → index10-BG65E54y.js} +1 -1
  39. package/dist/web/assets/index10-BG65E54y.js.br +0 -0
  40. package/dist/web/assets/index10-BG65E54y.js.gz +0 -0
  41. package/dist/web/assets/index3-6tLrzhUa.js +1 -0
  42. package/dist/web/assets/index4-CZn-viSK.js +1 -0
  43. package/dist/web/assets/{index5-DaBM1kaC.js → index5-CzcXp9wR.js} +1 -1
  44. package/dist/web/assets/index5-CzcXp9wR.js.br +0 -0
  45. package/dist/web/assets/index5-CzcXp9wR.js.gz +0 -0
  46. package/dist/web/assets/{index6-1dcCVob7.js → index6-DPLyU-vO.js} +1 -1
  47. package/dist/web/assets/index6-DPLyU-vO.js.br +0 -0
  48. package/dist/web/assets/index6-DPLyU-vO.js.gz +0 -0
  49. package/dist/web/assets/{index7-DGSFcnYT.js → index7-6uQOIsxo.js} +1 -1
  50. package/dist/web/assets/index7-6uQOIsxo.js.br +0 -0
  51. package/dist/web/assets/index7-6uQOIsxo.js.gz +0 -0
  52. package/dist/web/assets/{index8-BjPxjipz.js → index8-DUBqmq2E.js} +1 -1
  53. package/dist/web/assets/index8-DUBqmq2E.js.br +0 -0
  54. package/dist/web/assets/index8-DUBqmq2E.js.gz +0 -0
  55. package/dist/web/assets/{index9-VNQsX15e.js → index9-Czv_zULn.js} +1 -1
  56. package/dist/web/assets/index9-Czv_zULn.js.br +0 -0
  57. package/dist/web/assets/index9-Czv_zULn.js.gz +0 -0
  58. package/dist/web/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  59. package/dist/web/assets/vue.runtime.esm-bundler-DwGo9CTz.js +4 -0
  60. package/dist/web/assets/vue.runtime.esm-bundler-DwGo9CTz.js.br +0 -0
  61. package/dist/web/assets/vue.runtime.esm-bundler-DwGo9CTz.js.gz +0 -0
  62. package/dist/web/index.html +4 -3
  63. package/dist/web/index.html.br +0 -0
  64. package/dist/web/index.html.gz +0 -0
  65. package/docs/cloudflare-access.md +111 -0
  66. package/docs/markstream-integration-validation.md +3 -2
  67. package/package.json +6 -2
  68. package/dist/web/assets/CodeBlockNode-D-c_NpDN.js.br +0 -0
  69. package/dist/web/assets/CodeBlockNode-D-c_NpDN.js.gz +0 -0
  70. package/dist/web/assets/FileViewer-C6rgOMRo.js +0 -2
  71. package/dist/web/assets/FileViewer-C6rgOMRo.js.br +0 -0
  72. package/dist/web/assets/FileViewer-C6rgOMRo.js.gz +0 -0
  73. package/dist/web/assets/FileViewer-CljYTF8J.css +0 -1
  74. package/dist/web/assets/FileViewer-CljYTF8J.css.br +0 -0
  75. package/dist/web/assets/FileViewer-CljYTF8J.css.gz +0 -0
  76. package/dist/web/assets/FilesPanel-CNkBvKGD.js.br +0 -0
  77. package/dist/web/assets/FilesPanel-CNkBvKGD.js.gz +0 -0
  78. package/dist/web/assets/MarkdownMessage-DjRNZCD0.js +0 -199
  79. package/dist/web/assets/MarkdownMessage-DjRNZCD0.js.br +0 -0
  80. package/dist/web/assets/MarkdownMessage-DjRNZCD0.js.gz +0 -0
  81. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DVJqSz-5.js.br +0 -0
  82. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DVJqSz-5.js.gz +0 -0
  83. package/dist/web/assets/TerminalPanel-CpGnkfa7.js.br +0 -0
  84. package/dist/web/assets/TerminalPanel-CpGnkfa7.js.gz +0 -0
  85. package/dist/web/assets/Tooltip-C9GHriiI.js.br +0 -0
  86. package/dist/web/assets/Tooltip-C9GHriiI.js.gz +0 -0
  87. package/dist/web/assets/index-D4mQel3H.js +0 -30
  88. package/dist/web/assets/index-D4mQel3H.js.br +0 -0
  89. package/dist/web/assets/index-D4mQel3H.js.gz +0 -0
  90. package/dist/web/assets/index-Wf4Xa0ob.css +0 -1
  91. package/dist/web/assets/index-Wf4Xa0ob.css.br +0 -0
  92. package/dist/web/assets/index-Wf4Xa0ob.css.gz +0 -0
  93. package/dist/web/assets/index10-QexvIpKb.js.br +0 -0
  94. package/dist/web/assets/index10-QexvIpKb.js.gz +0 -0
  95. package/dist/web/assets/index3-B9LRPNVQ.js +0 -1
  96. package/dist/web/assets/index4-CTBFr99S.js +0 -1
  97. package/dist/web/assets/index5-DaBM1kaC.js.br +0 -0
  98. package/dist/web/assets/index5-DaBM1kaC.js.gz +0 -0
  99. package/dist/web/assets/index6-1dcCVob7.js.br +0 -0
  100. package/dist/web/assets/index6-1dcCVob7.js.gz +0 -0
  101. package/dist/web/assets/index7-DGSFcnYT.js.br +0 -0
  102. package/dist/web/assets/index7-DGSFcnYT.js.gz +0 -0
  103. package/dist/web/assets/index8-BjPxjipz.js.br +0 -0
  104. package/dist/web/assets/index8-BjPxjipz.js.gz +0 -0
  105. package/dist/web/assets/index9-VNQsX15e.js.br +0 -0
  106. package/dist/web/assets/index9-VNQsX15e.js.gz +0 -0
  107. package/dist/web/assets/vue.runtime.esm-bundler-D6xZ1zFq.js +0 -4
  108. package/dist/web/assets/vue.runtime.esm-bundler-D6xZ1zFq.js.br +0 -0
  109. package/dist/web/assets/vue.runtime.esm-bundler-D6xZ1zFq.js.gz +0 -0
@@ -20,9 +20,10 @@ import { deleteCookie, getCookie, setCookie } from "hono/cookie";
20
20
  import QRCode from "qrcode";
21
21
  import { AgentPermissionResponseSchema } from "@getpaseo/protocol/messages";
22
22
  import webpush from "web-push";
23
+ import WebSocket, { WebSocketServer } from "ws";
23
24
  import { fileURLToPath } from "node:url";
24
25
  // src/server/version.ts
25
- const VERSION = "0.3.0";
26
+ const VERSION = "0.4.0";
26
27
  // src/server/rotating-log.ts
27
28
  /** One writer (the supervisor); bounded active file plus numbered archives. */
28
29
  var RotatingLog = class {
@@ -983,9 +984,19 @@ function summarize(hostId, agent, project, activity = time(agent.updatedAt)) {
983
984
  thinking: agent.effectiveThinkingOptionId ?? agent.thinkingOptionId ?? agent.runtimeInfo?.thinkingOptionId ?? null,
984
985
  modeId: agent.currentModeId ?? null,
985
986
  contextUsed: agent.lastUsage?.contextWindowUsedTokens ?? null,
986
- contextMax: agent.lastUsage?.contextWindowMaxTokens ?? null
987
+ contextMax: agent.lastUsage?.contextWindowMaxTokens ?? null,
988
+ rewind: rewindModes(agent.capabilities)
987
989
  };
988
990
  }
991
+ /** The rewind modes a provider supports, in Paseo's menu order. */
992
+ function rewindModes(capabilities) {
993
+ const c = capabilities ?? {};
994
+ const modes = [];
995
+ if (c.supportsRewindConversation === true) modes.push("conversation");
996
+ if (c.supportsRewindFiles === true) modes.push("files");
997
+ if (c.supportsRewindBoth === true) modes.push("both");
998
+ return modes;
999
+ }
989
1000
  const agentAdapter = {
990
1001
  updateType: "agent_update",
991
1002
  base: { scope: "active" },
@@ -2377,10 +2388,47 @@ function matchTotp(secret, code, now = Date.now()) {
2377
2388
  return null;
2378
2389
  }
2379
2390
  const sha256 = (text) => createHash("sha256").update(text).digest("hex");
2380
- const equalSecret = (a, b) => {
2381
- const x = Buffer.from(a), y = Buffer.from(b);
2382
- return x.length === y.length && timingSafeEqual(x, y);
2383
- };
2391
+ /** Compares digests, so neither the content nor the length of the secret leaks through timing. */
2392
+ const equalSecret = (a, b) => timingSafeEqual(createHash("sha256").update(a).digest(), createHash("sha256").update(b).digest());
2393
+ const MIN_DISTINCT_CHARACTERS = 8;
2394
+ const generateToken = () => randomBytes(32).toString("hex");
2395
+ /** Why a chosen access token is refused, or null when it is acceptable. */
2396
+ function tokenProblem(token) {
2397
+ if (token.length < 16) return `The token needs at least 16 characters.`;
2398
+ if (token.length > 200) return `The token can have at most 200 characters.`;
2399
+ if (!/^[\x21-\x7e]+$/.test(token)) return "Use letters, digits and punctuation only (no spaces or other characters).";
2400
+ if (new Set(token).size < MIN_DISTINCT_CHARACTERS) return `Use at least ${MIN_DISTINCT_CHARACTERS} different characters.`;
2401
+ return null;
2402
+ }
2403
+ /** Replaces the token file in one step, readable only by its owner. */
2404
+ function writeTokenFile(path, token) {
2405
+ const temporary = `${path}.${process.pid}.tmp`;
2406
+ writeFileSync(temporary, token + "\n", { mode: 384 });
2407
+ renameSync(temporary, path);
2408
+ }
2409
+ /**
2410
+ * The current token from its file. Re-read when the file changes, so `litepaseo token set` and
2411
+ * `token rotate` take effect in a running server. A missing or unreadable file admits nobody.
2412
+ */
2413
+ function tokenFile(path) {
2414
+ let cached = {
2415
+ key: "",
2416
+ token: ""
2417
+ };
2418
+ return () => {
2419
+ try {
2420
+ const info = statSync(path);
2421
+ const key = `${info.ino}:${info.mtimeMs}:${info.size}`;
2422
+ if (key !== cached.key) cached = {
2423
+ key,
2424
+ token: readFileSync(path, "utf8").trim()
2425
+ };
2426
+ return cached.token;
2427
+ } catch {
2428
+ return "";
2429
+ }
2430
+ };
2431
+ }
2384
2432
  /**
2385
2433
  * Login and sessions. A browser signs in once, with the access token and, when enabled, an authenticator code,
2386
2434
  * and receives an opaque session secret (stored only as a hash). Sessions are listed and
@@ -2399,7 +2447,7 @@ var Auth = class {
2399
2447
  pendingTotp = null;
2400
2448
  constructor(store, token) {
2401
2449
  this.store = store;
2402
- this.token = token;
2450
+ this.token = typeof token === "string" ? () => token : token;
2403
2451
  const saved = store.setting("totp_login_limit");
2404
2452
  if (saved) this.global = JSON.parse(saved);
2405
2453
  if (store.setting("auth_policy") !== "token-plus-totp-v1") {
@@ -2417,9 +2465,30 @@ var Auth = class {
2417
2465
  totpEnabled() {
2418
2466
  return this.store.setting("totp_secret") !== null;
2419
2467
  }
2420
- /** Validates a bearer token (CLI, tests) without creating a session. */
2468
+ /** Whether `token` is the current access token. */
2421
2469
  checkToken(token) {
2422
- return equalSecret(token, this.token);
2470
+ const expected = this.token();
2471
+ return !!expected && equalSecret(token, expected);
2472
+ }
2473
+ /**
2474
+ * A bearer token (scripts on this machine) authenticates without creating a session. It
2475
+ * draws on the same failure budget as sign-in, so it cannot be used to guess the token.
2476
+ */
2477
+ bearer(token, client, now = Date.now()) {
2478
+ const limit = this.limited(client, false, now);
2479
+ if (limit) return {
2480
+ ok: false,
2481
+ status: 429,
2482
+ retryAfter: limit
2483
+ };
2484
+ if (!this.checkToken(token)) {
2485
+ this.fail(client, false, now);
2486
+ return {
2487
+ ok: false,
2488
+ status: 401
2489
+ };
2490
+ }
2491
+ return { ok: true };
2423
2492
  }
2424
2493
  login(input, client, label, now = Date.now()) {
2425
2494
  const tokenLimit = this.limited(client, false, now);
@@ -2807,9 +2876,9 @@ var UsageService = class {
2807
2876
  };
2808
2877
  // src/server/dictation.ts
2809
2878
  /**
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.
2879
+ * File transcription for phrases from dictation-stream and complete clips from older clients.
2880
+ * Wraps mono PCM as WAV for an OpenAI-compatible `/audio/transcriptions` endpoint.
2881
+ * Voice input is configured in LitePaseo; no Paseo host is involved.
2813
2882
  *
2814
2883
  * Request shape differs by model generation (OpenAI speech-to-text guide, 2026):
2815
2884
  * - `gpt-transcribe` takes `languages[]` (several expected languages, for code-switching) and
@@ -2938,7 +3007,7 @@ var DictationError = class extends Error {
2938
3007
  this.status = status;
2939
3008
  }
2940
3009
  };
2941
- async function send(config, file, shape, fetchImpl) {
3010
+ async function send(config, file, shape, fetchImpl, signal) {
2942
3011
  const form = new FormData();
2943
3012
  form.append("file", file, "dictation.wav");
2944
3013
  for (const [name, value] of transcriptionFields(config, shape)) form.append(name, value);
@@ -2948,7 +3017,7 @@ async function send(config, file, shape, fetchImpl) {
2948
3017
  method: "POST",
2949
3018
  headers: { authorization: `Bearer ${config.apiKey}` },
2950
3019
  body: form,
2951
- signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
3020
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)]) : AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
2952
3021
  });
2953
3022
  } catch (error) {
2954
3023
  const timeout = error.name === "TimeoutError";
@@ -2967,12 +3036,12 @@ async function send(config, file, shape, fetchImpl) {
2967
3036
  detail: String(detail)
2968
3037
  };
2969
3038
  }
2970
- async function transcribe(config, pcm, rate, fetchImpl = fetch) {
3039
+ async function transcribe(config, pcm, rate, fetchImpl = fetch, signal) {
2971
3040
  const file = new Blob([wav(pcm, rate)], { type: "audio/wav" });
2972
3041
  const shape = shapeFor(config.model);
2973
- let result = await send(config, file, shape, fetchImpl);
3042
+ let result = await send(config, file, shape, fetchImpl, signal);
2974
3043
  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);
3044
+ if (!result.ok && result.status === 400 && hinted && /language|keyword|prompt/i.test(result.detail)) result = await send(config, file, shape === "hints" ? "single" : "hints", fetchImpl, signal).then((retry) => retry.ok ? retry : result);
2976
3045
  if (!result.ok) {
2977
3046
  const scrubbed = result.detail.split(config.apiKey).join("…").replace(/\s+/g, " ").trim().slice(0, 200);
2978
3047
  throw new DictationError(`Transcription failed (${result.status})${scrubbed ? ": " + scrubbed : ""}`, 502);
@@ -2980,6 +3049,445 @@ async function transcribe(config, pcm, rate, fetchImpl = fetch) {
2980
3049
  if (result.text === void 0) throw new DictationError("The transcription service returned no text", 502);
2981
3050
  return result.text.trim();
2982
3051
  }
3052
+ // src/server/dictation-stream.ts
3053
+ const DICTATION_RATE = 24e3;
3054
+ const BYTES_PER_SECOND = DICTATION_RATE * 2;
3055
+ const MAX_BYTES = BYTES_PER_SECOND * 300;
3056
+ const MAX_BUFFERED = BYTES_PER_SECOND * 10;
3057
+ /** One-use, short-lived tickets keep credentials out of WebSocket URLs. */
3058
+ var DictationStreams = class {
3059
+ tickets = /* @__PURE__ */ new Map();
3060
+ sessions = /* @__PURE__ */ new Set();
3061
+ unsupported = /* @__PURE__ */ new Map();
3062
+ wss = new WebSocketServer({
3063
+ noServer: true,
3064
+ maxPayload: BYTES_PER_SECOND,
3065
+ perMessageDeflate: false
3066
+ });
3067
+ fetchImpl;
3068
+ log;
3069
+ constructor(fetchImpl = fetch, log = () => {}) {
3070
+ this.fetchImpl = fetchImpl;
3071
+ this.log = log;
3072
+ }
3073
+ issue(config, valid) {
3074
+ for (const [key, ticket] of this.tickets) if (ticket.expires < Date.now()) this.tickets.delete(key);
3075
+ if (this.tickets.size + this.sessions.size >= 16) throw new Error("Too many voice sessions. Try again shortly.");
3076
+ const ticket = randomUUID();
3077
+ this.tickets.set(ticket, {
3078
+ config,
3079
+ valid,
3080
+ expires: Date.now() + 3e4
3081
+ });
3082
+ return {
3083
+ ticket,
3084
+ rate: DICTATION_RATE
3085
+ };
3086
+ }
3087
+ attach(server) {
3088
+ server.on("upgrade", (request, socket, head) => {
3089
+ const url = new URL(request.url ?? "/", "http://localhost");
3090
+ if (url.pathname !== "/api/dictation/stream") {
3091
+ socket.destroy();
3092
+ return;
3093
+ }
3094
+ const key = url.searchParams.get("ticket") ?? "";
3095
+ const ticket = this.tickets.get(key);
3096
+ this.tickets.delete(key);
3097
+ if (!ticket || ticket.expires < Date.now() || !ticket.valid()) {
3098
+ socket.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
3099
+ return;
3100
+ }
3101
+ this.wss.handleUpgrade(request, socket, head, (client) => {
3102
+ const cacheKey = ticket.config.baseUrl + ":" + ticket.config.model;
3103
+ const stream = new DictationStream(client, ticket.config, ticket.valid, {
3104
+ fetch: this.fetchImpl,
3105
+ skipRealtime: (this.unsupported.get(cacheKey) ?? 0) > Date.now(),
3106
+ unsupported: () => {
3107
+ for (const [key, until] of this.unsupported) if (until < Date.now()) this.unsupported.delete(key);
3108
+ this.unsupported.set(cacheKey, Date.now() + 3e5);
3109
+ },
3110
+ closed: () => this.sessions.delete(stream),
3111
+ log: this.log
3112
+ });
3113
+ this.sessions.add(stream);
3114
+ stream.start();
3115
+ });
3116
+ });
3117
+ }
3118
+ close() {
3119
+ for (const stream of this.sessions) stream.close();
3120
+ this.tickets.clear();
3121
+ this.unsupported.clear();
3122
+ this.wss.close();
3123
+ }
3124
+ };
3125
+ /** Audio flows while recording. Realtime is preferred; file-only services transcribe phrases. */
3126
+ var DictationStream = class {
3127
+ upstream;
3128
+ mode = "connecting";
3129
+ closed = false;
3130
+ finishing = false;
3131
+ totalBytes = 0;
3132
+ segmentBytes = 0;
3133
+ silenceBytes = 0;
3134
+ speech = false;
3135
+ chunks = [];
3136
+ segments = [];
3137
+ commits = [];
3138
+ items = /* @__PURE__ */ new Map();
3139
+ jobs = [];
3140
+ activeJobs = 0;
3141
+ abort = new AbortController();
3142
+ started = Date.now();
3143
+ stopped = 0;
3144
+ firstText = null;
3145
+ deadline;
3146
+ heartbeat;
3147
+ client;
3148
+ config;
3149
+ valid;
3150
+ options;
3151
+ constructor(client, config, valid, options) {
3152
+ this.client = client;
3153
+ this.config = config;
3154
+ this.valid = valid;
3155
+ this.options = options;
3156
+ this.heartbeat = setInterval(() => {
3157
+ if (!valid()) this.fail("Your session ended. Sign in again.");
3158
+ else if (Date.now() - this.started > 43e4) this.fail("Voice session timed out.");
3159
+ else if (client.readyState === WebSocket.OPEN) client.ping();
3160
+ }, 1e4);
3161
+ this.heartbeat.unref();
3162
+ client.on("message", (data, binary) => {
3163
+ if (this.closed) return;
3164
+ if (!valid()) {
3165
+ this.fail("Your session ended. Sign in again.");
3166
+ return;
3167
+ }
3168
+ try {
3169
+ if (binary) this.append(Buffer.from(data));
3170
+ else {
3171
+ const event = JSON.parse(data.toString());
3172
+ if (event.type === "stop") this.finish();
3173
+ else if (event.type === "cancel") this.close();
3174
+ else this.fail("Unknown voice command.");
3175
+ }
3176
+ } catch {
3177
+ this.fail("Invalid voice data.");
3178
+ }
3179
+ });
3180
+ client.on("error", () => this.close());
3181
+ client.on("close", () => this.close());
3182
+ }
3183
+ async start() {
3184
+ const realtimeModel = /^(gpt-transcribe|gpt-live-transcribe|gpt-4o(-mini)?-transcribe|whisper-1)$/.test(this.config.model);
3185
+ if (this.options.skipRealtime || !realtimeModel) {
3186
+ this.ready("segmented");
3187
+ return;
3188
+ }
3189
+ try {
3190
+ await this.connectRealtime();
3191
+ if (!this.closed) this.ready("realtime");
3192
+ } catch (error) {
3193
+ if (this.closed) return;
3194
+ if (error instanceof Unavailable) {
3195
+ this.options.unsupported();
3196
+ this.ready("segmented");
3197
+ } else this.fail(error.message);
3198
+ }
3199
+ }
3200
+ connectRealtime() {
3201
+ return new Promise((resolve, reject) => {
3202
+ const url = new URL(this.config.baseUrl + "/realtime");
3203
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
3204
+ url.searchParams.set("intent", "transcription");
3205
+ const ws = this.upstream = new WebSocket(url, {
3206
+ headers: { Authorization: `Bearer ${this.config.apiKey}` },
3207
+ handshakeTimeout: 4e3,
3208
+ maxPayload: 1048576
3209
+ });
3210
+ let settled = false;
3211
+ const finish = (error) => {
3212
+ if (settled) return;
3213
+ settled = true;
3214
+ clearTimeout(timeout);
3215
+ if (error) {
3216
+ this.upstream = void 0;
3217
+ ws.terminate();
3218
+ reject(error);
3219
+ } else resolve();
3220
+ };
3221
+ const timeout = setTimeout(() => finish(new Unavailable("Realtime connection timed out")), 5e3);
3222
+ ws.on("open", () => {
3223
+ const hints = /^(gpt-transcribe|gpt-live-transcribe)$/.test(this.config.model);
3224
+ const transcription = {
3225
+ model: this.config.model,
3226
+ ...hints ? {
3227
+ ...this.config.languages.length ? { languages: this.config.languages } : {},
3228
+ ...this.config.keywords.length ? { keywords: this.config.keywords } : {}
3229
+ } : {
3230
+ ...this.config.languages.length === 1 ? { language: this.config.languages[0].split("-")[0] } : {},
3231
+ ...this.config.keywords.length ? { prompt: this.config.keywords.join(", ").slice(0, 600) } : {}
3232
+ }
3233
+ };
3234
+ ws.send(JSON.stringify({
3235
+ type: "session.update",
3236
+ session: {
3237
+ type: "transcription",
3238
+ audio: { input: {
3239
+ format: {
3240
+ type: "audio/pcm",
3241
+ rate: DICTATION_RATE
3242
+ },
3243
+ transcription,
3244
+ turn_detection: null
3245
+ } }
3246
+ }
3247
+ }));
3248
+ });
3249
+ ws.on("unexpected-response", (_, response) => {
3250
+ const status = response.statusCode;
3251
+ response.destroy();
3252
+ finish([
3253
+ 400,
3254
+ 404,
3255
+ 405,
3256
+ 501
3257
+ ].includes(status ?? 0) ? new Unavailable("Realtime is not supported") : /* @__PURE__ */ new Error(`Voice connection failed (${status}). Check the transcription service settings.`));
3258
+ });
3259
+ ws.on("message", (data) => {
3260
+ let event;
3261
+ try {
3262
+ event = JSON.parse(data.toString());
3263
+ } catch {
3264
+ finish(/* @__PURE__ */ new Error("Invalid transcription service response."));
3265
+ return;
3266
+ }
3267
+ if (!settled) {
3268
+ if (event.type === "session.updated") finish();
3269
+ else if (event.type === "error") finish(new Unavailable("Realtime configuration is not supported"));
3270
+ } else if (this.mode === "realtime" && !this.closed) this.upstreamEvent(event);
3271
+ });
3272
+ ws.on("error", () => {
3273
+ if (!settled) finish(new Unavailable("Realtime is unavailable"));
3274
+ else if (this.mode === "realtime") this.fail("Voice connection interrupted. Please try again.");
3275
+ });
3276
+ ws.on("close", () => {
3277
+ if (!settled) finish(new Unavailable("Realtime is unavailable"));
3278
+ else if (this.mode === "realtime" && !this.closed) this.fail("Voice connection interrupted. Please try again.");
3279
+ });
3280
+ });
3281
+ }
3282
+ ready(mode) {
3283
+ if (this.closed) return;
3284
+ if (mode === "segmented" && this.config.model === "gpt-live-transcribe") {
3285
+ this.fail("This service does not support realtime transcription. Choose gpt-transcribe or a realtime-compatible service.");
3286
+ return;
3287
+ }
3288
+ this.mode = mode;
3289
+ this.send({
3290
+ type: "ready",
3291
+ mode,
3292
+ rate: DICTATION_RATE
3293
+ });
3294
+ }
3295
+ append(audio) {
3296
+ if (this.finishing || this.mode === "connecting") {
3297
+ this.fail("Voice session is not recording.");
3298
+ return;
3299
+ }
3300
+ if (!audio.length || audio.length % 2 || audio.length > BYTES_PER_SECOND) {
3301
+ this.fail("Invalid audio chunk.");
3302
+ return;
3303
+ }
3304
+ this.totalBytes += audio.length;
3305
+ if (this.totalBytes > MAX_BYTES) {
3306
+ this.fail("Recording exceeds five minutes.");
3307
+ return;
3308
+ }
3309
+ this.chunks.push(audio);
3310
+ this.segmentBytes += audio.length;
3311
+ let energy = 0;
3312
+ for (let i = 0; i < audio.length; i += 2) {
3313
+ const sample = audio.readInt16LE(i) / 32768;
3314
+ energy += sample * sample;
3315
+ }
3316
+ if (Math.sqrt(energy / (audio.length / 2)) >= .006) {
3317
+ this.speech = true;
3318
+ this.silenceBytes = 0;
3319
+ } else this.silenceBytes += audio.length;
3320
+ if (this.mode === "realtime") {
3321
+ if (!this.upstream || this.upstream.bufferedAmount > MAX_BUFFERED) {
3322
+ this.fail("Voice upload cannot keep up with recording.");
3323
+ return;
3324
+ }
3325
+ this.upstream.send(JSON.stringify({
3326
+ type: "input_audio_buffer.append",
3327
+ audio: audio.toString("base64")
3328
+ }));
3329
+ }
3330
+ if (this.speech && (this.segmentBytes >= BYTES_PER_SECOND && this.silenceBytes >= BYTES_PER_SECOND * .7 || this.segmentBytes >= BYTES_PER_SECOND * 30)) this.commit();
3331
+ else if (!this.speech && this.segmentBytes >= BYTES_PER_SECOND * 2) this.clearAudio();
3332
+ }
3333
+ clearAudio() {
3334
+ this.chunks = [];
3335
+ this.segmentBytes = this.silenceBytes = 0;
3336
+ this.speech = false;
3337
+ if (this.mode === "realtime") this.upstream?.send(JSON.stringify({ type: "input_audio_buffer.clear" }));
3338
+ }
3339
+ commit() {
3340
+ if (!this.segmentBytes) return;
3341
+ const segment = {
3342
+ text: "",
3343
+ done: false
3344
+ };
3345
+ this.segments.push(segment);
3346
+ if (this.mode === "realtime") {
3347
+ if (this.segmentBytes < BYTES_PER_SECOND / 10) this.upstream?.send(JSON.stringify({
3348
+ type: "input_audio_buffer.append",
3349
+ audio: Buffer.alloc(BYTES_PER_SECOND / 10 - this.segmentBytes).toString("base64")
3350
+ }));
3351
+ this.commits.push(segment);
3352
+ this.upstream?.send(JSON.stringify({ type: "input_audio_buffer.commit" }));
3353
+ } else {
3354
+ this.jobs.push({
3355
+ audio: Buffer.concat(this.chunks),
3356
+ segment
3357
+ });
3358
+ this.pump();
3359
+ }
3360
+ this.chunks = [];
3361
+ this.segmentBytes = this.silenceBytes = 0;
3362
+ this.speech = false;
3363
+ }
3364
+ pump() {
3365
+ while (!this.closed && this.activeJobs < 2 && this.jobs.length) {
3366
+ const job = this.jobs.shift();
3367
+ this.activeJobs++;
3368
+ transcribe(this.config, job.audio, DICTATION_RATE, this.options.fetch, this.abort.signal).then((text) => {
3369
+ if (this.closed) return;
3370
+ job.segment.text = text;
3371
+ job.segment.done = true;
3372
+ this.publish();
3373
+ }).catch(() => {
3374
+ if (!this.closed) this.fail("Transcription failed. Please try again or check the service settings.");
3375
+ }).finally(() => {
3376
+ this.activeJobs--;
3377
+ this.pump();
3378
+ });
3379
+ }
3380
+ }
3381
+ upstreamEvent(event) {
3382
+ const id = typeof event.item_id === "string" ? event.item_id : "";
3383
+ if (event.type === "input_audio_buffer.committed") {
3384
+ const segment = this.commits.shift();
3385
+ if (!segment || !id) {
3386
+ this.fail("Unexpected transcription sequence.");
3387
+ return;
3388
+ }
3389
+ const draft = this.items.get(id);
3390
+ if (draft) {
3391
+ segment.text = draft.text;
3392
+ segment.done = draft.done;
3393
+ }
3394
+ segment.id = id;
3395
+ this.items.set(id, segment);
3396
+ this.publish();
3397
+ } else if (event.type === "conversation.item.input_audio_transcription.delta" || event.type === "conversation.item.input_audio_transcription.completed") {
3398
+ let segment = this.items.get(id);
3399
+ if (!segment) {
3400
+ segment = {
3401
+ text: "",
3402
+ done: false,
3403
+ id
3404
+ };
3405
+ this.items.set(id, segment);
3406
+ }
3407
+ if (event.type.endsWith(".completed")) {
3408
+ segment.text = String(event.transcript ?? "");
3409
+ segment.done = true;
3410
+ } else if (!segment.done) segment.text += String(event.delta ?? "");
3411
+ this.publish();
3412
+ } else if (event.type === "error" || event.type === "conversation.item.input_audio_transcription.failed") this.fail("The transcription service could not process this recording.");
3413
+ }
3414
+ text() {
3415
+ const parts = [];
3416
+ for (const segment of this.segments) {
3417
+ if (segment.text.trim()) parts.push(segment.text.trim());
3418
+ if (!segment.done) break;
3419
+ }
3420
+ if (this.mode === "realtime" && this.config.model === "gpt-live-transcribe") {
3421
+ for (const segment of this.items.values()) if (!this.segments.includes(segment) && segment.text.trim()) parts.push(segment.text.trim());
3422
+ }
3423
+ return parts.join(" ");
3424
+ }
3425
+ publish() {
3426
+ if (this.closed) return;
3427
+ const text = this.text();
3428
+ if (text && this.firstText === null) this.firstText = Date.now() - this.started;
3429
+ if (this.finishing && this.segments.every((s) => s.done)) {
3430
+ this.options.log({
3431
+ mode: this.mode,
3432
+ audioMs: this.totalBytes / BYTES_PER_SECOND * 1e3,
3433
+ firstTextMs: this.firstText,
3434
+ finishMs: Date.now() - this.stopped
3435
+ });
3436
+ this.send({
3437
+ type: "done",
3438
+ text
3439
+ });
3440
+ this.close();
3441
+ } else this.send({
3442
+ type: "partial",
3443
+ text
3444
+ });
3445
+ }
3446
+ finish() {
3447
+ if (this.finishing || this.closed) return;
3448
+ if (this.mode === "connecting") {
3449
+ this.fail("Voice session is still connecting.");
3450
+ return;
3451
+ }
3452
+ this.finishing = true;
3453
+ this.stopped = Date.now();
3454
+ if (this.speech) this.commit();
3455
+ else this.clearAudio();
3456
+ this.deadline = setTimeout(() => this.fail("Timed out waiting for transcription."), 12e4);
3457
+ this.publish();
3458
+ }
3459
+ send(event) {
3460
+ if (this.client.readyState === WebSocket.OPEN) {
3461
+ if (this.client.bufferedAmount > 1048576) {
3462
+ this.close();
3463
+ return;
3464
+ }
3465
+ this.client.send(JSON.stringify(event));
3466
+ }
3467
+ }
3468
+ fail(message) {
3469
+ if (this.closed) return;
3470
+ this.send({
3471
+ type: "error",
3472
+ message,
3473
+ text: this.text()
3474
+ });
3475
+ this.close();
3476
+ }
3477
+ close() {
3478
+ if (this.closed) return;
3479
+ this.closed = true;
3480
+ clearInterval(this.heartbeat);
3481
+ clearTimeout(this.deadline);
3482
+ this.abort.abort();
3483
+ this.upstream?.terminate();
3484
+ this.chunks = [];
3485
+ this.jobs = [];
3486
+ this.client.close();
3487
+ this.options.closed();
3488
+ }
3489
+ };
3490
+ var Unavailable = class extends Error {};
2983
3491
  // src/server/app.ts
2984
3492
  const AGENT_FLUSH_MS = 100;
2985
3493
  const HOST_FLUSH_MS = 100;
@@ -3005,9 +3513,25 @@ const SESSION_COOKIE = "lp_session";
3005
3513
  /** Cookie-authenticated writes must carry this header; a cross-site form or image cannot. */
3006
3514
  const CSRF_HEADER = "x-litepaseo";
3007
3515
  const PUBLIC_API = /* @__PURE__ */ new Set(["/api/auth", "/api/login"]);
3516
+ /**
3517
+ * Requests that arrived through a tunnel or reverse proxy. A bearer token is never accepted from
3518
+ * them: over the network, only the browser sign-in (with its rate limits and optional
3519
+ * authenticator code) admits anyone.
3520
+ */
3521
+ const proxied = (c) => [
3522
+ "cf-connecting-ip",
3523
+ "x-forwarded-for",
3524
+ "x-real-ip",
3525
+ "forwarded"
3526
+ ].some((name) => c.req.header(name) !== void 0);
3527
+ /** `token` is the access token, or a function returning the current one (it can be rotated). */
3008
3528
  function createApp(store, hosts, token, webRoot, options = {}) {
3009
3529
  const app = new Hono();
3010
3530
  const auth = new Auth(store, token);
3531
+ const dictationStreams = new DictationStreams(options.fetch, (metrics) => console.info(JSON.stringify({
3532
+ event: "dictation_complete",
3533
+ ...metrics
3534
+ })));
3011
3535
  const attachments = new Attachments();
3012
3536
  const projectIcons = new IconCache();
3013
3537
  const viewers = /* @__PURE__ */ new Map();
@@ -3031,9 +3555,16 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3031
3555
  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));
3032
3556
  app.use("/api/*", async (c, next) => {
3033
3557
  c.header("Cache-Control", "no-store");
3034
- const bearer = c.req.header("authorization")?.replace(/^Bearer /, "");
3035
- if (bearer && !PUBLIC_API.has(c.req.path) && !auth.totpEnabled() && auth.checkToken(bearer)) {
3558
+ c.set("bearer", null);
3559
+ const bearer = /^Bearer (.+)$/.exec(c.req.header("authorization") ?? "")?.[1];
3560
+ if (bearer && !PUBLIC_API.has(c.req.path) && !auth.totpEnabled() && !proxied(c)) {
3561
+ const result = auth.bearer(bearer, clientId(c));
3562
+ if (!result.ok) {
3563
+ if (result.retryAfter) c.header("Retry-After", String(result.retryAfter));
3564
+ return c.json({ error: result.status === 429 ? "Too many attempts. Try again later." : "Sign in required" }, result.status);
3565
+ }
3036
3566
  c.set("session", null);
3567
+ c.set("bearer", bearer);
3037
3568
  return next();
3038
3569
  }
3039
3570
  const secret = getCookie(c, SESSION_COOKIE);
@@ -3281,7 +3812,12 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3281
3812
  for (const stream of directoryStreams) stream.send(message);
3282
3813
  }, HOST_FLUSH_MS);
3283
3814
  });
3284
- const streamValidity = (session) => session ? () => auth.stillValid(session.id) : () => !auth.totpEnabled();
3815
+ /** Re-checked on heartbeat: a revoked session, or a rotated token, loses its open streams. */
3816
+ const streamValidity = (c) => {
3817
+ const session = c.get("session"), bearer = c.get("bearer");
3818
+ if (session) return () => auth.stillValid(session.id);
3819
+ return () => !!bearer && !auth.totpEnabled() && auth.checkToken(bearer);
3820
+ };
3285
3821
  app.get("/api/stream", (c) => {
3286
3822
  const since = Number(c.req.query("since"));
3287
3823
  const resumable = c.req.query("generation") === hosts.agents.generation && Number.isInteger(since);
@@ -3300,7 +3836,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3300
3836
  deliverAgents(stream);
3301
3837
  directoryStreams.add(stream);
3302
3838
  return () => directoryStreams.delete(stream);
3303
- }, streamValidity(c.get("session")));
3839
+ }, streamValidity(c));
3304
3840
  });
3305
3841
  app.post("/api/hosts", async (c) => {
3306
3842
  const input = z.object({
@@ -3432,7 +3968,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3432
3968
  if (!devices.size) viewers.delete(key);
3433
3969
  }
3434
3970
  };
3435
- }, streamValidity(c.get("session")));
3971
+ }, streamValidity(c));
3436
3972
  });
3437
3973
  /** Bounded history pages; the browser bookmarks boundaries for forward navigation. */
3438
3974
  app.get("/api/hosts/:host/agents/:agent/timeline", async (c) => {
@@ -3461,6 +3997,46 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3461
3997
  }))
3462
3998
  });
3463
3999
  });
4000
+ /** The conversation's user prompts (seq + short preview), for the outline rail. */
4001
+ app.get("/api/hosts/:host/agents/:agent/timeline/prompts", async (c) => {
4002
+ const client = hosts.get(c.req.param("host"));
4003
+ try {
4004
+ const page = await client.driver.listAgentTimelinePrompts(c.req.param("agent"), { timeout: 15e3 });
4005
+ return c.json({
4006
+ epoch: page.epoch,
4007
+ prompts: page.prompts.map((p) => ({
4008
+ seq: p.seq,
4009
+ preview: p.preview.replace(/\s+/g, " ").trim().slice(0, 240)
4010
+ }))
4011
+ });
4012
+ } catch (error) {
4013
+ return c.json({ error: error.message || "Prompt index unavailable" }, 501);
4014
+ }
4015
+ });
4016
+ /**
4017
+ * Rewinds to just before a user message: the conversation, the tracked files, or both, as
4018
+ * the provider supports. Cannot be undone; the timeline is replaced (new epoch) on success.
4019
+ */
4020
+ app.post("/api/hosts/:host/agents/:agent/rewind", async (c) => {
4021
+ const { messageId, mode } = z.object({
4022
+ messageId: z.string().min(1).max(500),
4023
+ mode: z.enum([
4024
+ "conversation",
4025
+ "files",
4026
+ "both"
4027
+ ])
4028
+ }).parse(await c.req.json());
4029
+ const client = hosts.get(c.req.param("host"));
4030
+ const facts = client.directory.facts(c.req.param("agent"));
4031
+ if (!facts) return c.json({ error: "Unknown agent" }, 404);
4032
+ if (!rewindModes(facts.capabilities).includes(mode)) return c.json({ error: "This agent cannot rewind that way." }, 400);
4033
+ try {
4034
+ await client.driver.rewindAgent(c.req.param("agent"), messageId, mode);
4035
+ return c.json({ ok: true });
4036
+ } catch (error) {
4037
+ return c.json({ error: error.message || "Rewind failed" }, 502);
4038
+ }
4039
+ });
3464
4040
  /**
3465
4041
  * An image an agent referenced in a message (`![](file:///…)`, an absolute or workspace path).
3466
4042
  * Workspace files go through the daemon's file API; images the daemon materialized from
@@ -3580,10 +4156,19 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3580
4156
  });
3581
4157
  /**
3582
4158
  * 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.
4159
+ * browser streams PCM over a short-lived socket. The file endpoint remains for older
4160
+ * clients. The API key never leaves the server.
3585
4161
  */
3586
4162
  app.get("/api/dictation", (c) => c.json(dictationSettings(store)));
4163
+ app.post("/api/dictation/session", (c) => {
4164
+ const config = dictationConfig(store);
4165
+ if (!config) return c.json({ error: "Voice input is not set up. Add a transcription service in Settings." }, 409);
4166
+ try {
4167
+ return c.json(dictationStreams.issue(config, streamValidity(c)));
4168
+ } catch (error) {
4169
+ return c.json({ error: error.message }, 429);
4170
+ }
4171
+ });
3587
4172
  app.put("/api/dictation", async (c) => {
3588
4173
  try {
3589
4174
  return c.json(saveDictation(store, await c.req.json()));
@@ -3749,7 +4334,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3749
4334
  });
3750
4335
  }
3751
4336
  });
3752
- registerWorkspaceRoutes(app, hosts, store, (c) => streamValidity(c.get("session")));
4337
+ registerWorkspaceRoutes(app, hosts, store, (c) => streamValidity(c));
3753
4338
  app.get("/api/usage", async (c) => c.json(await usage.report(c.req.query("refresh") === "1")));
3754
4339
  app.get("/api/board", (c) => c.json(store.board()));
3755
4340
  app.put("/api/board", async (c) => {
@@ -3785,6 +4370,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3785
4370
  precompressed: true
3786
4371
  }));
3787
4372
  return Object.assign(app, {
4373
+ dictationStreams,
3788
4374
  /** Open directory streams; lets tests prove that disconnects release them. */
3789
4375
  openStreams: () => directoryStreams.size,
3790
4376
  dispose: () => {
@@ -3793,14 +4379,84 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3793
4379
  clearTimeout(hostFlush);
3794
4380
  agentFlush = hostFlush = void 0;
3795
4381
  attachments.close();
4382
+ dictationStreams.close();
3796
4383
  }
3797
4384
  });
3798
4385
  }
4386
+ // src/server/config.ts
4387
+ /**
4388
+ * Settings that used to need an environment variable on every start. `litepaseo config set`
4389
+ * saves them with the rest of LitePaseo's data (so backups carry them); an environment
4390
+ * variable, when present, still wins for that run.
4391
+ */
4392
+ const CONFIG_KEYS = {
4393
+ port: {
4394
+ env: "LITEPASEO_PORT",
4395
+ fallback: "8787",
4396
+ summary: "Port the web console listens on",
4397
+ check: (value) => /^\d+$/.test(value) && Number(value) >= 1 && Number(value) <= 65535 ? null : "Use a port number from 1 to 65535."
4398
+ },
4399
+ bind: {
4400
+ env: "LITEPASEO_BIND",
4401
+ fallback: "127.0.0.1",
4402
+ summary: "Address to listen on (keep 127.0.0.1 behind a tunnel)",
4403
+ check: (value) => /^[^\s/]{1,255}$/.test(value) ? null : "Use an IP address or host name, such as 127.0.0.1."
4404
+ },
4405
+ "push-subject": {
4406
+ env: "LITEPASEO_PUSH_SUBJECT",
4407
+ fallback: "mailto:litepaseo@example.com",
4408
+ summary: "Contact sent to push services (mailto: or https: URL)",
4409
+ check: (value) => {
4410
+ if (/^mailto:[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return null;
4411
+ try {
4412
+ if (new URL(value).protocol === "https:") return null;
4413
+ } catch {}
4414
+ return "Use mailto:you@example.com or an https:// address you control.";
4415
+ }
4416
+ }
4417
+ };
4418
+ const configKeys = Object.keys(CONFIG_KEYS);
4419
+ const isConfigKey = (key) => Object.hasOwn(CONFIG_KEYS, key);
4420
+ const settingName = (key) => `config.${key}`;
4421
+ function setConfig(store, key, value) {
4422
+ if (value !== null) {
4423
+ const problem = CONFIG_KEYS[key].check(value);
4424
+ if (problem) throw new Error(problem);
4425
+ }
4426
+ store.setSetting(settingName(key), value);
4427
+ }
4428
+ /** The value in effect for each key: environment, then saved configuration, then the default. */
4429
+ function effectiveConfig(store, env) {
4430
+ const entries = configKeys.map((key) => {
4431
+ const { env: name, fallback } = CONFIG_KEYS[key];
4432
+ const saved = store.setting(settingName(key));
4433
+ const fromEnv = env[name];
4434
+ if (fromEnv !== void 0 && fromEnv !== "") return {
4435
+ key,
4436
+ value: fromEnv,
4437
+ source: "environment",
4438
+ saved
4439
+ };
4440
+ if (saved !== null) return {
4441
+ key,
4442
+ value: saved,
4443
+ source: "saved",
4444
+ saved
4445
+ };
4446
+ return {
4447
+ key,
4448
+ value: fallback,
4449
+ source: "default",
4450
+ saved
4451
+ };
4452
+ });
4453
+ return Object.fromEntries(entries.map((entry) => [entry.key, entry]));
4454
+ }
3799
4455
  // src/server/worker.ts
3800
4456
  async function runWorker(directory, webRoot) {
3801
4457
  if (!process.send) throw new Error("worker is an internal supervised command");
3802
4458
  const tokenPath = join(directory, "token");
3803
- if (!existsSync(tokenPath)) writeFileSync(tokenPath, randomBytes(32).toString("hex"), {
4459
+ if (!existsSync(tokenPath)) writeFileSync(tokenPath, generateToken(), {
3804
4460
  mode: 384,
3805
4461
  flag: "wx"
3806
4462
  });
@@ -3810,13 +4466,15 @@ async function runWorker(directory, webRoot) {
3810
4466
  } catch {
3811
4467
  console.error("Could not initialize host", host.id);
3812
4468
  }
3813
- const port = Number(process.env.LITEPASEO_PORT ?? 8787), hostname = process.env.LITEPASEO_BIND ?? "127.0.0.1";
3814
- const app = createApp(store, hosts, readFileSync(tokenPath, "utf8").trim(), webRoot, { pushSubject: process.env.LITEPASEO_PUSH_SUBJECT });
4469
+ const config = effectiveConfig(store, process.env);
4470
+ const port = Number(config.port.value), hostname = config.bind.value;
4471
+ const app = createApp(store, hosts, tokenFile(tokenPath), webRoot, { pushSubject: config["push-subject"].value });
3815
4472
  const server = serve({
3816
4473
  fetch: app.fetch,
3817
4474
  port,
3818
4475
  hostname
3819
4476
  });
4477
+ app.dictationStreams.attach(server);
3820
4478
  let stopping = false;
3821
4479
  const shutdown = async () => {
3822
4480
  if (stopping) return;
@@ -3833,7 +4491,7 @@ async function runWorker(directory, webRoot) {
3833
4491
  process.once("SIGTERM", () => void shutdown());
3834
4492
  process.once("disconnect", () => void shutdown());
3835
4493
  server.once("error", (error) => {
3836
- const message = error.code === "EADDRINUSE" ? `Port ${port} on ${hostname} is already in use (set LITEPASEO_PORT to use another)` : error.code === "EACCES" ? `Not permitted to listen on ${hostname}:${port}` : error.message;
4494
+ const message = error.code === "EADDRINUSE" ? `Port ${port} on ${hostname} is already in use (choose another with: litepaseo config set port <number>)` : error.code === "EACCES" ? `Not permitted to listen on ${hostname}:${port}` : error.message;
3837
4495
  console.error(message);
3838
4496
  process.send?.({
3839
4497
  type: "fatal",
@@ -3929,7 +4587,7 @@ async function restore(source, directory) {
3929
4587
  } finally {
3930
4588
  db.close();
3931
4589
  }
3932
- if (!/^[a-f0-9]{64}\s*$/.test(readFileSync(join(stage, "token"), "utf8"))) throw new Error("Invalid backup access token.");
4590
+ if (!/^[\x21-\x7e]{1,200}$/.test(readFileSync(join(stage, "token"), "utf8").trim())) throw new Error("Invalid backup access token.");
3933
4591
  writeFileSync(join(directory, ".restore-incomplete"), "Restore interrupted: restore the backup to a fresh home.\n", {
3934
4592
  mode: 384,
3935
4593
  flag: "wx"
@@ -4006,6 +4664,8 @@ const json = {
4006
4664
  name: "json",
4007
4665
  summary: "Print machine-readable JSON"
4008
4666
  };
4667
+ const TOKEN_ACTIONS = ["set", "rotate"];
4668
+ const CONFIG_ACTIONS = ["set", "unset"];
4009
4669
  const SERVICE_ACTIONS = [
4010
4670
  "print",
4011
4671
  "install",
@@ -4067,8 +4727,47 @@ const COMMANDS = [
4067
4727
  {
4068
4728
  name: "token",
4069
4729
  group: "Sign-in",
4070
- summary: "Print the access token",
4071
- details: ["The token is required to sign in from a browser."]
4730
+ args: "[set|rotate]",
4731
+ summary: "Print, choose or replace the access token",
4732
+ details: [
4733
+ "The token is required to sign in from a browser.",
4734
+ "",
4735
+ "Actions:",
4736
+ " (none) print the current token",
4737
+ " set choose your own token: typed twice without echo, or read from standard input",
4738
+ " rotate replace it with a new random token and print it",
4739
+ "",
4740
+ `A chosen token needs at least 16 characters (letters, digits, punctuation; no spaces).`,
4741
+ "Both actions take effect immediately and sign out every browser."
4742
+ ],
4743
+ examples: [
4744
+ "litepaseo token",
4745
+ "litepaseo token set",
4746
+ "litepaseo token rotate"
4747
+ ]
4748
+ },
4749
+ {
4750
+ name: "config",
4751
+ group: "Configuration",
4752
+ args: "[set|unset] [key] [value]",
4753
+ summary: "Show or change saved settings",
4754
+ details: [
4755
+ "Saved settings apply on every start, so environment variables are no longer needed.",
4756
+ "An environment variable still overrides its setting for that run.",
4757
+ "",
4758
+ "Keys:",
4759
+ " port port the web console listens on (8787)",
4760
+ " bind address to listen on (127.0.0.1; keep it behind a tunnel)",
4761
+ " push-subject contact for push services: mailto:you@example.com or an https:// URL",
4762
+ "",
4763
+ "Changes apply after 'litepaseo restart' (or 'litepaseo service restart')."
4764
+ ],
4765
+ flags: [json],
4766
+ examples: [
4767
+ "litepaseo config",
4768
+ "litepaseo config set push-subject mailto:you@example.com",
4769
+ "litepaseo config unset port"
4770
+ ]
4072
4771
  },
4073
4772
  {
4074
4773
  name: "totp-reset",
@@ -4214,11 +4913,13 @@ function mainHelp(version, directory, s) {
4214
4913
  `${s.bold("Usage:")} litepaseo <command> [options]`
4215
4914
  ];
4216
4915
  const groups = [...new Set(COMMANDS.map((c) => c.group))];
4916
+ const label = (c) => c.name + (c.args ? " " + c.args : "");
4917
+ const width = Math.max(22, ...COMMANDS.map((c) => label(c).length + 2));
4217
4918
  for (const group of groups) {
4218
4919
  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}`);
4920
+ for (const c of COMMANDS.filter((x) => x.group === group)) lines.push(` ${s.cyan(label(c).padEnd(width))}${c.summary}`);
4220
4921
  }
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.`);
4922
+ 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.dim("(overrides 'litepaseo config' for one run)")}`, ` ${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
4923
  return lines.join("\n");
4223
4924
  }
4224
4925
  function commandHelp(c, s) {
@@ -4417,6 +5118,106 @@ async function logs(paths, args) {
4417
5118
  }
4418
5119
  }
4419
5120
  }
5121
+ /** Reads a line from the terminal without echoing it. */
5122
+ function promptHidden(question) {
5123
+ return new Promise((done, reject) => {
5124
+ const input = process.stdin;
5125
+ process.stderr.write(question);
5126
+ input.setRawMode(true);
5127
+ input.setEncoding("utf8");
5128
+ input.resume();
5129
+ let value = "";
5130
+ const finish = (error) => {
5131
+ input.setRawMode(false);
5132
+ input.pause();
5133
+ input.removeListener("data", onData);
5134
+ process.stderr.write("\n");
5135
+ if (error) reject(error);
5136
+ else done(value);
5137
+ };
5138
+ const onData = (chunk) => {
5139
+ for (const char of chunk) {
5140
+ if (char === "\r" || char === "\n") return finish();
5141
+ if (char === "" || char === "") return finish(/* @__PURE__ */ new Error("Cancelled; the token is unchanged."));
5142
+ if (char === "" || char === "\b") value = value.slice(0, -1);
5143
+ else value += char;
5144
+ }
5145
+ };
5146
+ input.on("data", onData);
5147
+ });
5148
+ }
5149
+ /** The new token from the terminal (typed twice) or from standard input, never from argv. */
5150
+ async function chosenToken() {
5151
+ if (process.stdin.isTTY) {
5152
+ const first = (await promptHidden("New access token: ")).trim();
5153
+ const problem = tokenProblem(first);
5154
+ if (problem) throw new Error(problem);
5155
+ if ((await promptHidden("Repeat it: ")).trim() !== first) throw new Error("The tokens differ; the token is unchanged.");
5156
+ return first;
5157
+ }
5158
+ const value = readFileSync(0, "utf8").trim();
5159
+ const problem = tokenProblem(value);
5160
+ if (problem) throw new Error(problem);
5161
+ return value;
5162
+ }
5163
+ async function token(paths, action) {
5164
+ if (action === void 0) {
5165
+ if (!existsSync(paths.token)) throw new Error("No access token yet: it is created on first start. Run 'litepaseo start'.");
5166
+ return console.log(readFileSync(paths.token, "utf8").trim());
5167
+ }
5168
+ if (!TOKEN_ACTIONS.includes(action)) {
5169
+ const guess = suggest(action, TOKEN_ACTIONS);
5170
+ throw new UsageError(`Unknown token action '${action}'.${guess ? ` Did you mean '${guess}'?` : ""} Actions: ${TOKEN_ACTIONS.join(", ")}.`);
5171
+ }
5172
+ const value = action === "set" ? await chosenToken() : generateToken();
5173
+ writeTokenFile(paths.token, value);
5174
+ const store = new Store(paths.directory);
5175
+ try {
5176
+ store.revokeSessions();
5177
+ } finally {
5178
+ store.close();
5179
+ }
5180
+ if (action === "rotate") console.log(value);
5181
+ console.error(`${action === "set" ? "Access token saved" : "New access token above"}. Every browser is signed out; sign in again with the new token.`);
5182
+ const running = await status(paths);
5183
+ const note = running && versionNote(running, VERSION, err);
5184
+ if (note) console.error(note);
5185
+ }
5186
+ async function config(paths, args) {
5187
+ const [action, key, value] = args.positional;
5188
+ const store = new Store(paths.directory);
5189
+ try {
5190
+ if (action === void 0) {
5191
+ const entries = Object.values(effectiveConfig(store, process.env));
5192
+ if (args.flags.json) return console.log(JSON.stringify(Object.fromEntries(entries.map((e) => [e.key, {
5193
+ value: e.value,
5194
+ source: e.source
5195
+ }]))));
5196
+ for (const entry of entries) {
5197
+ const note = entry.source === "environment" ? `from ${CONFIG_KEYS[entry.key].env}${entry.saved !== null ? `, overriding saved ${entry.saved}` : ""}` : entry.source;
5198
+ console.log(`${out.cyan(entry.key.padEnd(14))}${entry.value} ${out.dim(`(${note})`)}`);
5199
+ }
5200
+ return;
5201
+ }
5202
+ if (!CONFIG_ACTIONS.includes(action)) {
5203
+ const guess = suggest(action, CONFIG_ACTIONS);
5204
+ throw new UsageError(`Unknown config action '${action}'.${guess ? ` Did you mean '${guess}'?` : ""} Actions: ${CONFIG_ACTIONS.join(", ")}.`);
5205
+ }
5206
+ if (!key || !isConfigKey(key)) {
5207
+ const guess = key ? suggest(key, configKeys) : void 0;
5208
+ throw new UsageError(`${key ? `Unknown key '${key}'.` : "Missing key."}${guess ? ` Did you mean '${guess}'?` : ""} Keys: ${configKeys.join(", ")}.`);
5209
+ }
5210
+ if (action === "set" && value === void 0) throw new UsageError(`Missing value for '${key}'.`);
5211
+ if (action === "unset" && value !== void 0) throw new UsageError(`'unset' takes no value.`);
5212
+ setConfig(store, key, action === "set" ? value : null);
5213
+ const entry = effectiveConfig(store, process.env)[key];
5214
+ console.log(action === "set" ? `${key} saved: ${value}` : `${key} reset to the default: ${CONFIG_KEYS[key].fallback}`);
5215
+ if (entry.source === "environment") console.log(out.yellow(`! ${CONFIG_KEYS[key].env} is set in this shell and overrides it.`));
5216
+ } finally {
5217
+ store.close();
5218
+ }
5219
+ if (await status(paths)) console.log(out.dim(" Restart to apply: litepaseo restart (or litepaseo service restart)"));
5220
+ }
4420
5221
  async function version(args) {
4421
5222
  const paths = await dataDirectory();
4422
5223
  const state = await status(paths);
@@ -4475,9 +5276,8 @@ async function run() {
4475
5276
  case "status": return showStatus(paths, args);
4476
5277
  case "logs": return logs(paths, args);
4477
5278
  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());
5279
+ case "token": return token(paths, args.positional[0]);
5280
+ case "config": return config(paths, args);
4481
5281
  case "totp-reset":
4482
5282
  case "signout-all": {
4483
5283
  const store = new Store(paths.directory);