litepaseo 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +96 -39
  3. package/dist/server/cli.mjs +712 -134
  4. package/dist/web/assets/{CodeBlockNode-CehKIzSk.js → CodeBlockNode-D-c_NpDN.js} +1 -1
  5. package/dist/web/assets/CodeBlockNode-D-c_NpDN.js.br +0 -0
  6. package/dist/web/assets/CodeBlockNode-D-c_NpDN.js.gz +0 -0
  7. package/dist/web/assets/{FileViewer-01t53KTX.js → FileViewer-C6rgOMRo.js} +1 -1
  8. package/dist/web/assets/FileViewer-C6rgOMRo.js.br +0 -0
  9. package/dist/web/assets/FileViewer-C6rgOMRo.js.gz +0 -0
  10. package/dist/web/assets/{FilesPanel-B7NknFvl.js → FilesPanel-CNkBvKGD.js} +1 -1
  11. package/dist/web/assets/FilesPanel-CNkBvKGD.js.br +0 -0
  12. package/dist/web/assets/FilesPanel-CNkBvKGD.js.gz +0 -0
  13. package/dist/web/assets/{MarkdownMessage-UlvozPc5.js → MarkdownMessage-DjRNZCD0.js} +5 -5
  14. package/dist/web/assets/MarkdownMessage-DjRNZCD0.js.br +0 -0
  15. package/dist/web/assets/MarkdownMessage-DjRNZCD0.js.gz +0 -0
  16. package/dist/web/assets/{PreCodeBlock-DPQTlYty.js → PreCodeBlock-BitPoeXT.js} +1 -1
  17. package/dist/web/assets/{PreCodeBlock.vue_vue_type_style_index_0_lang-Cdy-YZRP.js → PreCodeBlock.vue_vue_type_style_index_0_lang-DVJqSz-5.js} +1 -1
  18. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DVJqSz-5.js.br +0 -0
  19. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DVJqSz-5.js.gz +0 -0
  20. package/dist/web/assets/{TerminalPanel-BdmAonFr.js → TerminalPanel-CpGnkfa7.js} +1 -1
  21. package/dist/web/assets/TerminalPanel-CpGnkfa7.js.br +0 -0
  22. package/dist/web/assets/TerminalPanel-CpGnkfa7.js.gz +0 -0
  23. package/dist/web/assets/{Tooltip-BJ2o2M_0.js → Tooltip-C9GHriiI.js} +1 -1
  24. package/dist/web/assets/Tooltip-C9GHriiI.js.br +0 -0
  25. package/dist/web/assets/Tooltip-C9GHriiI.js.gz +0 -0
  26. package/dist/web/assets/index-D4mQel3H.js +30 -0
  27. package/dist/web/assets/index-D4mQel3H.js.br +0 -0
  28. package/dist/web/assets/index-D4mQel3H.js.gz +0 -0
  29. package/dist/web/assets/index-Wf4Xa0ob.css +1 -0
  30. package/dist/web/assets/index-Wf4Xa0ob.css.br +0 -0
  31. package/dist/web/assets/index-Wf4Xa0ob.css.gz +0 -0
  32. package/dist/web/assets/{index10-WpTfisco.js → index10-QexvIpKb.js} +1 -1
  33. package/dist/web/assets/index10-QexvIpKb.js.br +0 -0
  34. package/dist/web/assets/index10-QexvIpKb.js.gz +0 -0
  35. package/dist/web/assets/index3-B9LRPNVQ.js +1 -0
  36. package/dist/web/assets/index4-CTBFr99S.js +1 -0
  37. package/dist/web/assets/{index5-BCbIyN1t.js → index5-DaBM1kaC.js} +1 -1
  38. package/dist/web/assets/index5-DaBM1kaC.js.br +0 -0
  39. package/dist/web/assets/index5-DaBM1kaC.js.gz +0 -0
  40. package/dist/web/assets/{index6-CbdnTDhy.js → index6-1dcCVob7.js} +1 -1
  41. package/dist/web/assets/index6-1dcCVob7.js.br +0 -0
  42. package/dist/web/assets/index6-1dcCVob7.js.gz +0 -0
  43. package/dist/web/assets/{index7-BzNzdNxO.js → index7-DGSFcnYT.js} +1 -1
  44. package/dist/web/assets/index7-DGSFcnYT.js.br +0 -0
  45. package/dist/web/assets/index7-DGSFcnYT.js.gz +0 -0
  46. package/dist/web/assets/{index8-CD8jmACo.js → index8-BjPxjipz.js} +1 -1
  47. package/dist/web/assets/index8-BjPxjipz.js.br +0 -0
  48. package/dist/web/assets/index8-BjPxjipz.js.gz +0 -0
  49. package/dist/web/assets/{index9-9FYLmtt9.js → index9-VNQsX15e.js} +1 -1
  50. package/dist/web/assets/index9-VNQsX15e.js.br +0 -0
  51. package/dist/web/assets/index9-VNQsX15e.js.gz +0 -0
  52. package/dist/web/index.html +2 -2
  53. package/dist/web/index.html.br +0 -0
  54. package/dist/web/index.html.gz +0 -0
  55. package/docs/performance-plan.md +119 -241
  56. package/package.json +2 -2
  57. package/dist/web/assets/CodeBlockNode-CehKIzSk.js.br +0 -0
  58. package/dist/web/assets/CodeBlockNode-CehKIzSk.js.gz +0 -0
  59. package/dist/web/assets/FileViewer-01t53KTX.js.br +0 -0
  60. package/dist/web/assets/FileViewer-01t53KTX.js.gz +0 -0
  61. package/dist/web/assets/FilesPanel-B7NknFvl.js.br +0 -0
  62. package/dist/web/assets/FilesPanel-B7NknFvl.js.gz +0 -0
  63. package/dist/web/assets/MarkdownMessage-UlvozPc5.js.br +0 -0
  64. package/dist/web/assets/MarkdownMessage-UlvozPc5.js.gz +0 -0
  65. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Cdy-YZRP.js.br +0 -0
  66. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Cdy-YZRP.js.gz +0 -0
  67. package/dist/web/assets/TerminalPanel-BdmAonFr.js.br +0 -0
  68. package/dist/web/assets/TerminalPanel-BdmAonFr.js.gz +0 -0
  69. package/dist/web/assets/Tooltip-BJ2o2M_0.js.br +0 -0
  70. package/dist/web/assets/Tooltip-BJ2o2M_0.js.gz +0 -0
  71. package/dist/web/assets/index-D_YTh7Zw.css +0 -1
  72. package/dist/web/assets/index-D_YTh7Zw.css.br +0 -0
  73. package/dist/web/assets/index-D_YTh7Zw.css.gz +0 -0
  74. package/dist/web/assets/index-civcSERr.js +0 -27
  75. package/dist/web/assets/index-civcSERr.js.br +0 -0
  76. package/dist/web/assets/index-civcSERr.js.gz +0 -0
  77. package/dist/web/assets/index10-WpTfisco.js.br +0 -0
  78. package/dist/web/assets/index10-WpTfisco.js.gz +0 -0
  79. package/dist/web/assets/index3-C4yf5W5o.js +0 -1
  80. package/dist/web/assets/index4-Cwl0ij4U.js +0 -1
  81. package/dist/web/assets/index5-BCbIyN1t.js.br +0 -0
  82. package/dist/web/assets/index5-BCbIyN1t.js.gz +0 -0
  83. package/dist/web/assets/index6-CbdnTDhy.js.br +0 -0
  84. package/dist/web/assets/index6-CbdnTDhy.js.gz +0 -0
  85. package/dist/web/assets/index7-BzNzdNxO.js.br +0 -0
  86. package/dist/web/assets/index7-BzNzdNxO.js.gz +0 -0
  87. package/dist/web/assets/index8-CD8jmACo.js.br +0 -0
  88. package/dist/web/assets/index8-CD8jmACo.js.gz +0 -0
  89. package/dist/web/assets/index9-9FYLmtt9.js.br +0 -0
  90. package/dist/web/assets/index9-9FYLmtt9.js.gz +0 -0
  91. package/docs/operations.md +0 -143
@@ -22,7 +22,7 @@ import { AgentPermissionResponseSchema } from "@getpaseo/protocol/messages";
22
22
  import webpush from "web-push";
23
23
  import { fileURLToPath } from "node:url";
24
24
  // src/server/version.ts
25
- const VERSION = "0.2.0";
25
+ const VERSION = "0.3.0";
26
26
  // src/server/rotating-log.ts
27
27
  /** One writer (the supervisor); bounded active file plus numbered archives. */
28
28
  var RotatingLog = class {
@@ -308,6 +308,7 @@ async function supervise(directory, cliPath, options = {}) {
308
308
  await recoverSocket(path);
309
309
  let child = null, stopping = false, ready = false, url = "", restarts = 0;
310
310
  let failure = null, lastError = "";
311
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
311
312
  let retry;
312
313
  let killTimer;
313
314
  let finish;
@@ -397,6 +398,8 @@ async function supervise(directory, cliPath, options = {}) {
397
398
  if (input === "status") socket.end(JSON.stringify({
398
399
  ready,
399
400
  url,
401
+ version: VERSION,
402
+ startedAt,
400
403
  pid: process.pid,
401
404
  workerPid: child?.pid ?? null,
402
405
  restarts,
@@ -2802,10 +2805,183 @@ var UsageService = class {
2802
2805
  return request;
2803
2806
  }
2804
2807
  };
2808
+ // src/server/dictation.ts
2809
+ /**
2810
+ * Voice input configured once in LitePaseo instead of on every Paseo host. The browser records
2811
+ * 16 kHz mono PCM and posts it once; the server wraps it as WAV and sends it to an
2812
+ * OpenAI-compatible `/audio/transcriptions` endpoint. No host is involved.
2813
+ *
2814
+ * Request shape differs by model generation (OpenAI speech-to-text guide, 2026):
2815
+ * - `gpt-transcribe` takes `languages[]` (several expected languages, for code-switching) and
2816
+ * `keywords[]`; it "replaces the singular `language` field. Don't send both fields."
2817
+ * - `whisper-1`, `gpt-4o(-mini)-transcribe` and most compatible providers (Groq, local Whisper
2818
+ * servers) take a single `language` and a free-text `prompt`.
2819
+ * Paseo always sends `language` (default "en"), which is what breaks `gpt-transcribe` there.
2820
+ * Here the shape follows the model name, and a 400 about the language field retries once with
2821
+ * the other shape, so unknown models on compatible providers still work.
2822
+ */
2823
+ const DEFAULT_BASE_URL = "https://api.openai.com/v1";
2824
+ /** Five minutes of 16 kHz, 16-bit mono speech (9.6 MB as WAV, under the 25 MB upload limit). */
2825
+ const MAX_DICTATION_BYTES = 96e5;
2826
+ const SETTING = "dictation";
2827
+ const UPSTREAM_TIMEOUT_MS = 11e4;
2828
+ /** Whisper reads at most 224 prompt tokens; keep the folded vocabulary well under that. */
2829
+ const LEGACY_PROMPT_CHARS = 600;
2830
+ const baseUrl = z.string().trim().max(500).transform((v) => (v || "https://api.openai.com/v1").replace(/\/+$/, "")).refine((v) => {
2831
+ try {
2832
+ return ["http:", "https:"].includes(new URL(v).protocol);
2833
+ } catch {
2834
+ return false;
2835
+ }
2836
+ }, "Base URL must be an http(s) address");
2837
+ const languageCode = z.string().trim().transform((v) => v.toLowerCase().replace("_", "-")).refine((v) => /^[a-z]{2,3}(-[a-z]{2})?$/.test(v), "Languages must be codes such as en, zh or zh-tw");
2838
+ /** The API rejects the whole request for a keyword with <, > or a line break. */
2839
+ const keyword = z.string().trim().min(1).max(100, "Each vocabulary term must be under 100 characters").refine((v) => !/[<>\r\n]/.test(v), "Vocabulary terms cannot contain < or >");
2840
+ const unique = (values) => [...new Set(values)];
2841
+ const DictationUpdate = z.object({
2842
+ baseUrl: baseUrl.optional().default(DEFAULT_BASE_URL),
2843
+ /** Omitted or empty keeps the saved key. */
2844
+ apiKey: z.string().trim().max(1e3).optional(),
2845
+ model: z.string().trim().max(200).optional().transform((v) => v || "gpt-transcribe"),
2846
+ languages: z.array(languageCode).max(10, "At most 10 languages").optional().default([]).transform(unique),
2847
+ keywords: z.array(keyword).max(100, "At most 100 vocabulary terms").optional().default([]).transform(unique)
2848
+ });
2849
+ function dictationConfig(store) {
2850
+ const raw = store.setting(SETTING);
2851
+ if (!raw) return null;
2852
+ try {
2853
+ const value = JSON.parse(raw);
2854
+ if (!value.apiKey || !value.baseUrl || !value.model) return null;
2855
+ return {
2856
+ baseUrl: value.baseUrl,
2857
+ apiKey: value.apiKey,
2858
+ model: value.model,
2859
+ languages: value.languages ?? [],
2860
+ keywords: value.keywords ?? []
2861
+ };
2862
+ } catch {
2863
+ return null;
2864
+ }
2865
+ }
2866
+ function dictationSettings(store) {
2867
+ const config = dictationConfig(store);
2868
+ return {
2869
+ configured: !!config,
2870
+ baseUrl: config?.baseUrl ?? "https://api.openai.com/v1",
2871
+ model: config?.model ?? "gpt-transcribe",
2872
+ languages: config?.languages ?? [],
2873
+ keywords: config?.keywords ?? [],
2874
+ keyHint: config ? "…" + config.apiKey.slice(-4) : ""
2875
+ };
2876
+ }
2877
+ function saveDictation(store, input) {
2878
+ const update = DictationUpdate.parse(input);
2879
+ const apiKey = update.apiKey || dictationConfig(store)?.apiKey;
2880
+ if (!apiKey) throw new Error("An API key is required");
2881
+ const config = {
2882
+ baseUrl: update.baseUrl,
2883
+ apiKey,
2884
+ model: update.model,
2885
+ languages: update.languages,
2886
+ keywords: update.keywords
2887
+ };
2888
+ store.setSetting(SETTING, JSON.stringify(config));
2889
+ return dictationSettings(store);
2890
+ }
2891
+ function clearDictation(store) {
2892
+ store.setSetting(SETTING, null);
2893
+ }
2894
+ /** A 44-byte RIFF header makes raw PCM16 a file every transcription API accepts. */
2895
+ function wav(pcm, rate) {
2896
+ const out = Buffer.alloc(44 + pcm.length);
2897
+ out.write("RIFF", 0);
2898
+ out.writeUInt32LE(36 + pcm.length, 4);
2899
+ out.write("WAVE", 8);
2900
+ out.write("fmt ", 12);
2901
+ out.writeUInt32LE(16, 16);
2902
+ out.writeUInt16LE(1, 20);
2903
+ out.writeUInt16LE(1, 22);
2904
+ out.writeUInt32LE(rate, 24);
2905
+ out.writeUInt32LE(rate * 2, 28);
2906
+ out.writeUInt16LE(2, 32);
2907
+ out.writeUInt16LE(16, 34);
2908
+ out.write("data", 36);
2909
+ out.writeUInt32LE(pcm.length, 40);
2910
+ out.set(pcm, 44);
2911
+ return out;
2912
+ }
2913
+ const shapeFor = (model) => /(^|\/)gpt-transcribe\b/i.test(model) ? "hints" : "single";
2914
+ /** The multipart fields besides the file, for one request shape. */
2915
+ function transcriptionFields(config, shape) {
2916
+ const fields = [["model", config.model], ["response_format", "json"]];
2917
+ if (shape === "hints") {
2918
+ for (const code of config.languages) fields.push(["languages[]", code]);
2919
+ for (const term of config.keywords) fields.push(["keywords[]", term]);
2920
+ return fields;
2921
+ }
2922
+ if (config.languages.length === 1) fields.push(["language", config.languages[0].split("-")[0]]);
2923
+ if (config.keywords.length) {
2924
+ let prompt = "";
2925
+ for (const term of config.keywords) {
2926
+ const next = prompt ? `${prompt}, ${term}` : term;
2927
+ if (next.length > LEGACY_PROMPT_CHARS) break;
2928
+ prompt = next;
2929
+ }
2930
+ fields.push(["prompt", prompt]);
2931
+ }
2932
+ return fields;
2933
+ }
2934
+ var DictationError = class extends Error {
2935
+ status;
2936
+ constructor(message, status) {
2937
+ super(message);
2938
+ this.status = status;
2939
+ }
2940
+ };
2941
+ async function send(config, file, shape, fetchImpl) {
2942
+ const form = new FormData();
2943
+ form.append("file", file, "dictation.wav");
2944
+ for (const [name, value] of transcriptionFields(config, shape)) form.append(name, value);
2945
+ let response;
2946
+ try {
2947
+ response = await fetchImpl(config.baseUrl + "/audio/transcriptions", {
2948
+ method: "POST",
2949
+ headers: { authorization: `Bearer ${config.apiKey}` },
2950
+ body: form,
2951
+ signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
2952
+ });
2953
+ } catch (error) {
2954
+ const timeout = error.name === "TimeoutError";
2955
+ throw new DictationError(timeout ? "The transcription service did not answer in time" : `Could not reach the transcription service: ${error.message}`.slice(0, 300), timeout ? 504 : 502);
2956
+ }
2957
+ const body = await response.text();
2958
+ let data = {};
2959
+ try {
2960
+ data = JSON.parse(body);
2961
+ } catch {}
2962
+ const detail = typeof data.error === "string" ? data.error : typeof data.error?.message === "string" ? data.error.message : response.ok ? "" : body;
2963
+ return {
2964
+ ok: response.ok,
2965
+ status: response.status,
2966
+ text: typeof data.text === "string" ? data.text : void 0,
2967
+ detail: String(detail)
2968
+ };
2969
+ }
2970
+ async function transcribe(config, pcm, rate, fetchImpl = fetch) {
2971
+ const file = new Blob([wav(pcm, rate)], { type: "audio/wav" });
2972
+ const shape = shapeFor(config.model);
2973
+ let result = await send(config, file, shape, fetchImpl);
2974
+ const hinted = config.languages.length > 0 || config.keywords.length > 0;
2975
+ if (!result.ok && result.status === 400 && hinted && /language|keyword|prompt/i.test(result.detail)) result = await send(config, file, shape === "hints" ? "single" : "hints", fetchImpl).then((retry) => retry.ok ? retry : result);
2976
+ if (!result.ok) {
2977
+ const scrubbed = result.detail.split(config.apiKey).join("…").replace(/\s+/g, " ").trim().slice(0, 200);
2978
+ throw new DictationError(`Transcription failed (${result.status})${scrubbed ? ": " + scrubbed : ""}`, 502);
2979
+ }
2980
+ if (result.text === void 0) throw new DictationError("The transcription service returned no text", 502);
2981
+ return result.text.trim();
2982
+ }
2805
2983
  // src/server/app.ts
2806
2984
  const AGENT_FLUSH_MS = 100;
2807
- /** Five minutes of 16 kHz, 16-bit mono speech. */
2808
- const MAX_DICTATION_BYTES = 96e5;
2809
2985
  const HOST_FLUSH_MS = 100;
2810
2986
  function parseJson(text) {
2811
2987
  try {
@@ -2852,7 +3028,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
2852
3028
  c.header("Referrer-Policy", "no-referrer");
2853
3029
  c.header("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self'; manifest-src 'self'; frame-ancestors 'none'");
2854
3030
  });
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));
3031
+ app.use("/api/*", (c, next) => bodyLimit({ maxSize: c.req.method !== "POST" ? 1048576 : c.req.path.endsWith("/attachments") ? MAX_FILE_BYTES : c.req.path === "/api/dictation/transcribe" ? MAX_DICTATION_BYTES : 1048576 })(c, next));
2856
3032
  app.use("/api/*", async (c, next) => {
2857
3033
  c.header("Cache-Control", "no-store");
2858
3034
  const bearer = c.req.header("authorization")?.replace(/^Bearer /, "");
@@ -3050,6 +3226,8 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3050
3226
  const directoryStreams = /* @__PURE__ */ new Set();
3051
3227
  let agentFlush;
3052
3228
  let hostFlush;
3229
+ /** Set on shutdown: closing the hosts still reports changes, but the store is about to close. */
3230
+ let disposed = false;
3053
3231
  const deliverAgents = (stream) => {
3054
3232
  deliverWorkspaces(stream);
3055
3233
  const { agents } = hosts;
@@ -3086,14 +3264,14 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3086
3264
  stream.lastWorkspaces = workspaces.seq;
3087
3265
  };
3088
3266
  hosts.onAgentsChanged(() => {
3089
- if (agentFlush || !directoryStreams.size) return;
3267
+ if (disposed || agentFlush || !directoryStreams.size) return;
3090
3268
  agentFlush = setTimeout(() => {
3091
3269
  agentFlush = void 0;
3092
3270
  for (const stream of directoryStreams) deliverAgents(stream);
3093
3271
  }, AGENT_FLUSH_MS);
3094
3272
  });
3095
3273
  hosts.onHostsChanged(() => {
3096
- if (hostFlush || !directoryStreams.size) return;
3274
+ if (disposed || hostFlush || !directoryStreams.size) return;
3097
3275
  hostFlush = setTimeout(() => {
3098
3276
  hostFlush = void 0;
3099
3277
  const message = {
@@ -3401,30 +3579,35 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3401
3579
  });
3402
3580
  });
3403
3581
  /**
3404
- * Speech to text through the host's own dictation service (its configured STT provider). The
3582
+ * Speech to text through the transcription service configured here, once for every host. The
3405
3583
  * browser records 16 kHz mono PCM and posts it once when the user stops: one request, no
3406
- * socket kept open while idle.
3584
+ * socket kept open while idle. The API key never leaves the server.
3407
3585
  */
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());
3586
+ app.get("/api/dictation", (c) => c.json(dictationSettings(store)));
3587
+ app.put("/api/dictation", async (c) => {
3588
+ try {
3589
+ return c.json(saveDictation(store, await c.req.json()));
3590
+ } catch (error) {
3591
+ const message = error instanceof z.ZodError ? error.issues[0]?.message ?? "Invalid settings" : error.message;
3592
+ return c.json({ error: message }, 400);
3593
+ }
3594
+ });
3595
+ app.delete("/api/dictation", (c) => {
3596
+ clearDictation(store);
3597
+ return c.json(dictationSettings(store));
3598
+ });
3599
+ app.post("/api/dictation/transcribe", async (c) => {
3600
+ const config = dictationConfig(store);
3601
+ if (!config) return c.json({ error: "Voice input is not set up. Add a transcription service in Settings." }, 409);
3602
+ const format = /^audio\/pcm;rate=(\d{4,6});bits=16$/.exec(c.req.header("x-audio-format") ?? "");
3603
+ if (!format) return c.json({ error: "Unsupported audio format" }, 415);
3604
+ const audio = new Uint8Array(await c.req.arrayBuffer());
3412
3605
  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
3606
  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 });
3607
+ return c.json({ text: await transcribe(config, audio, Number(format[1]), options.fetch) });
3422
3608
  } 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);
3609
+ if (error instanceof DictationError) return c.json({ error: error.message }, error.status);
3610
+ throw error;
3428
3611
  }
3429
3612
  });
3430
3613
  const attachmentOwner = (c) => c.get("session")?.id ?? "bearer";
@@ -3604,7 +3787,13 @@ function createApp(store, hosts, token, webRoot, options = {}) {
3604
3787
  return Object.assign(app, {
3605
3788
  /** Open directory streams; lets tests prove that disconnects release them. */
3606
3789
  openStreams: () => directoryStreams.size,
3607
- dispose: () => attachments.close()
3790
+ dispose: () => {
3791
+ disposed = true;
3792
+ clearTimeout(agentFlush);
3793
+ clearTimeout(hostFlush);
3794
+ agentFlush = hostFlush = void 0;
3795
+ attachments.close();
3796
+ }
3608
3797
  });
3609
3798
  }
3610
3799
  // src/server/worker.ts
@@ -3812,35 +4001,332 @@ async function resolveDataDirectory(env, home, platform, isLive = socketIsLive)
3812
4001
  notice: `Moved LitePaseo data from ${legacy} to ${target}.`
3813
4002
  };
3814
4003
  }
4004
+ // src/server/cli-format.ts
4005
+ const json = {
4006
+ name: "json",
4007
+ summary: "Print machine-readable JSON"
4008
+ };
4009
+ const SERVICE_ACTIONS = [
4010
+ "print",
4011
+ "install",
4012
+ "uninstall",
4013
+ "status",
4014
+ "start",
4015
+ "stop",
4016
+ "restart"
4017
+ ];
4018
+ const COMMANDS = [
4019
+ {
4020
+ name: "start",
4021
+ group: "Service",
4022
+ summary: "Start in the background",
4023
+ details: ["Waits up to 10 s until the web console answers, then prints its address.", "Does nothing if LitePaseo is already running."],
4024
+ flags: [json]
4025
+ },
4026
+ {
4027
+ name: "stop",
4028
+ group: "Service",
4029
+ summary: "Stop the background instance",
4030
+ details: ["Waits until the instance has exited."]
4031
+ },
4032
+ {
4033
+ name: "restart",
4034
+ group: "Service",
4035
+ summary: "Stop, then start again",
4036
+ details: ["Use after upgrading so the new version serves."],
4037
+ flags: [json]
4038
+ },
4039
+ {
4040
+ name: "status",
4041
+ group: "Service",
4042
+ summary: "Show state, address and processes",
4043
+ details: ["Exit status: 0 running, 3 not running."],
4044
+ flags: [json]
4045
+ },
4046
+ {
4047
+ name: "logs",
4048
+ group: "Service",
4049
+ summary: "Show recent logs",
4050
+ flags: [{
4051
+ name: "lines",
4052
+ short: "n",
4053
+ value: "<count>",
4054
+ summary: "Number of lines to show (default 100)"
4055
+ }, {
4056
+ name: "follow",
4057
+ short: "f",
4058
+ summary: "Keep printing new lines until Ctrl-C"
4059
+ }],
4060
+ examples: ["litepaseo logs -n 500", "litepaseo logs -f"]
4061
+ },
4062
+ {
4063
+ name: "serve",
4064
+ group: "Service",
4065
+ summary: "Run in the foreground (for service managers)"
4066
+ },
4067
+ {
4068
+ name: "token",
4069
+ group: "Sign-in",
4070
+ summary: "Print the access token",
4071
+ details: ["The token is required to sign in from a browser."]
4072
+ },
4073
+ {
4074
+ name: "totp-reset",
4075
+ group: "Sign-in",
4076
+ summary: "Turn off authenticator sign-in (lost phone)"
4077
+ },
4078
+ {
4079
+ name: "signout-all",
4080
+ group: "Sign-in",
4081
+ summary: "Sign out every browser and stop its notifications"
4082
+ },
4083
+ {
4084
+ name: "backup",
4085
+ group: "Data",
4086
+ args: "<directory>",
4087
+ positional: 1,
4088
+ summary: "Back up all data into a new directory",
4089
+ details: ["The backup contains credentials: keep it private."],
4090
+ examples: ["litepaseo backup ~/litepaseo-backup"]
4091
+ },
4092
+ {
4093
+ name: "restore",
4094
+ group: "Data",
4095
+ args: "<directory>",
4096
+ positional: 1,
4097
+ summary: "Restore a backup into an empty home",
4098
+ examples: ["LITEPASEO_HOME=~/.litepaseo-restored litepaseo restore ~/litepaseo-backup"]
4099
+ },
4100
+ {
4101
+ name: "service",
4102
+ group: "Autostart",
4103
+ args: "<action>",
4104
+ summary: "Manage the systemd / launchd user service",
4105
+ details: [
4106
+ "Actions:",
4107
+ " print show the service definition without installing it",
4108
+ " install install and start it at login",
4109
+ " uninstall stop and remove it",
4110
+ " status show the service manager's status",
4111
+ " start | stop | restart"
4112
+ ],
4113
+ examples: ["litepaseo service install"]
4114
+ },
4115
+ {
4116
+ name: "version",
4117
+ group: "Other",
4118
+ summary: "Show version details",
4119
+ flags: [json]
4120
+ },
4121
+ {
4122
+ name: "help",
4123
+ group: "Other",
4124
+ args: "[command]",
4125
+ summary: "Show help for a command"
4126
+ }
4127
+ ];
4128
+ function findCommand(name) {
4129
+ return COMMANDS.find((c) => c.name === name);
4130
+ }
4131
+ /** Edit distance counting a swap of neighbouring letters as one edit, the commonest typo. */
4132
+ function distance(a, b) {
4133
+ const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => i ? j ? 0 : i : j));
4134
+ for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) {
4135
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
4136
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
4137
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
4138
+ }
4139
+ return d[a.length][b.length];
4140
+ }
4141
+ /** The closest known name, if it is plausibly a typo. */
4142
+ function suggest(input, names) {
4143
+ let best, score = Infinity;
4144
+ for (const name of names) {
4145
+ const d = name.startsWith(input) && input.length >= 2 ? 0 : distance(input, name);
4146
+ if (d < score) [best, score] = [name, d];
4147
+ }
4148
+ return score <= Math.max(1, Math.floor((best?.length ?? 0) / 3)) ? best : void 0;
4149
+ }
4150
+ var UsageError = class extends Error {};
4151
+ /** Parses the arguments after the command name against its declared flags. */
4152
+ function parseArgs(command, argv) {
4153
+ const result = {
4154
+ positional: [],
4155
+ flags: {},
4156
+ help: false
4157
+ };
4158
+ const flags = command.flags ?? [];
4159
+ for (let i = 0; i < argv.length; i++) {
4160
+ const arg = argv[i];
4161
+ if (arg === "-h" || arg === "--help") {
4162
+ result.help = true;
4163
+ continue;
4164
+ }
4165
+ if (arg === "--") {
4166
+ result.positional.push(...argv.slice(i + 1));
4167
+ break;
4168
+ }
4169
+ if (!arg.startsWith("-") || arg === "-") {
4170
+ result.positional.push(arg);
4171
+ continue;
4172
+ }
4173
+ const [raw, inline] = arg.startsWith("--") ? [arg.slice(2).split("=")[0], arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : void 0] : [arg.slice(1), void 0];
4174
+ const flag = arg.startsWith("--") ? flags.find((f) => f.name === raw) : flags.find((f) => f.short === raw);
4175
+ if (!flag) throw new UsageError(`Unknown option ${arg} for '${command.name}'.`);
4176
+ if (!flag.value) {
4177
+ if (inline !== void 0) throw new UsageError(`Option --${flag.name} takes no value.`);
4178
+ result.flags[flag.name] = true;
4179
+ continue;
4180
+ }
4181
+ const value = inline ?? argv[++i];
4182
+ if (value === void 0) throw new UsageError(`Option ${arg} needs a value ${flag.value}.`);
4183
+ result.flags[flag.name] = value;
4184
+ }
4185
+ if (result.help) return result;
4186
+ const required = command.positional ?? 0;
4187
+ if (result.positional.length < required) throw new UsageError(`Missing ${command.args} for '${command.name}'.`);
4188
+ const allowed = command.args ? command.args.split(" ").length : 0;
4189
+ if (result.positional.length > allowed) throw new UsageError(`Unexpected argument '${result.positional[allowed]}' for '${command.name}'.`);
4190
+ return result;
4191
+ }
4192
+ function makeStyle(enabled) {
4193
+ const wrap = (open, close) => (s) => enabled ? `\x1b[${open}m${s}\x1b[${close}m` : s;
4194
+ return {
4195
+ bold: wrap(1, 22),
4196
+ dim: wrap(2, 22),
4197
+ green: wrap(32, 39),
4198
+ red: wrap(31, 39),
4199
+ yellow: wrap(33, 39),
4200
+ cyan: wrap(36, 39)
4201
+ };
4202
+ }
4203
+ /** Colour only for a terminal, and never against NO_COLOR; FORCE_COLOR overrides both. */
4204
+ function colorEnabled(env, isTTY) {
4205
+ if (env.FORCE_COLOR !== void 0) return env.FORCE_COLOR !== "0";
4206
+ if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "") return false;
4207
+ return Boolean(isTTY) && env.TERM !== "dumb";
4208
+ }
4209
+ const usageOf = (c) => `litepaseo ${c.name}${c.args ? " " + c.args : ""}${c.flags?.length ? " [options]" : ""}`;
4210
+ function mainHelp(version, directory, s) {
4211
+ const lines = [
4212
+ `${s.bold("LitePaseo")} ${version}: a resource-conscious web console for your Paseo agents`,
4213
+ "",
4214
+ `${s.bold("Usage:")} litepaseo <command> [options]`
4215
+ ];
4216
+ const groups = [...new Set(COMMANDS.map((c) => c.group))];
4217
+ for (const group of groups) {
4218
+ lines.push("", s.bold(group));
4219
+ for (const c of COMMANDS.filter((x) => x.group === group)) lines.push(` ${s.cyan((c.name + (c.args ? " " + c.args : "")).padEnd(22))}${c.summary}`);
4220
+ }
4221
+ lines.push("", s.bold("Options"), ` ${s.cyan("-h, --help".padEnd(22))}Show help (also after a command)`, ` ${s.cyan("-v, --version".padEnd(22))}Print the version`, "", s.bold("Environment"), ` ${s.cyan("LITEPASEO_HOME".padEnd(24))}Data directory ${s.dim(`(now ${directory})`)}`, ` ${s.cyan("LITEPASEO_PORT".padEnd(24))}Port ${s.dim("(8787)")}`, ` ${s.cyan("LITEPASEO_BIND".padEnd(24))}Listen address ${s.dim("(127.0.0.1)")}`, ` ${s.cyan("LITEPASEO_PUSH_SUBJECT".padEnd(24))}mailto: or https: contact for push services`, "", `Run ${s.bold("litepaseo help <command>")} for details on a command.`);
4222
+ return lines.join("\n");
4223
+ }
4224
+ function commandHelp(c, s) {
4225
+ const lines = [
4226
+ `${s.bold("Usage:")} ${usageOf(c)}`,
4227
+ "",
4228
+ c.summary + "."
4229
+ ];
4230
+ if (c.details?.length) lines.push("", ...c.details);
4231
+ if (c.flags?.length) {
4232
+ lines.push("", s.bold("Options"));
4233
+ for (const f of c.flags) {
4234
+ const label = `${f.short ? `-${f.short}, ` : " "}--${f.name}${f.value ? " " + f.value : ""}`;
4235
+ lines.push(` ${s.cyan(label.padEnd(24))}${f.summary}`);
4236
+ }
4237
+ }
4238
+ if (c.examples?.length) lines.push("", s.bold("Examples"), ...c.examples.map((e) => " " + e));
4239
+ return lines.join("\n");
4240
+ }
4241
+ function formatDuration(ms) {
4242
+ const seconds = Math.max(0, Math.floor(ms / 1e3));
4243
+ const d = Math.floor(seconds / 86400), h = Math.floor(seconds % 86400 / 3600), m = Math.floor(seconds % 3600 / 60);
4244
+ if (d) return `${d}d ${h}h`;
4245
+ if (h) return `${h}h ${m}m`;
4246
+ if (m) return `${m}m ${seconds % 60}s`;
4247
+ return `${seconds}s`;
4248
+ }
4249
+ /** A note when the running instance is not the installed version (an upgrade needs a restart). */
4250
+ function versionNote(status, installed, s) {
4251
+ if (status.version === installed) return null;
4252
+ const running = status.version ? `version ${status.version}` : "an earlier version";
4253
+ return s.yellow(`! The running instance is ${running}; ${installed} is installed. Run 'litepaseo restart' to switch.`);
4254
+ }
4255
+ function formatStatus(status, installed, directory, s, now = Date.now()) {
4256
+ const state = status.ready ? s.green("● running") : status.restarts ? s.yellow("● restarting the worker") : s.yellow("● starting");
4257
+ const row = (label, value) => ` ${s.dim(label.padEnd(11))}${value}`;
4258
+ const lines = [`${s.bold("LitePaseo")} ${status.version ?? ""} ${state}`.replace(" ", " ")];
4259
+ if (status.url) lines.push(row("Address", s.cyan(status.url)));
4260
+ if (status.startedAt) {
4261
+ const started = new Date(status.startedAt);
4262
+ if (!Number.isNaN(started.getTime())) lines.push(row("Uptime", `${formatDuration(now - started.getTime())} ${s.dim(`(since ${started.toLocaleString()})`)}`));
4263
+ }
4264
+ lines.push(row("Processes", `supervisor ${status.pid}${status.workerPid ? `, worker ${status.workerPid}` : ", no worker"}`));
4265
+ if (status.restarts) lines.push(row("Restarts", String(status.restarts)));
4266
+ if (status.lastError) lines.push(row("Last error", s.red(status.lastError)));
4267
+ lines.push(row("Data", directory));
4268
+ const note = versionNote(status, installed, s);
4269
+ if (note) lines.push("", note);
4270
+ return lines.join("\n");
4271
+ }
4272
+ /** The last `count` lines of a text, keeping a trailing newline out of the count. */
4273
+ function lastLines(text, count) {
4274
+ if (count <= 0) return "";
4275
+ const body = text.endsWith("\n") ? text.slice(0, -1) : text;
4276
+ let index = body.length;
4277
+ for (let i = 0; i < count; i++) {
4278
+ index = body.lastIndexOf("\n", index - 1);
4279
+ if (index < 0) return text;
4280
+ }
4281
+ return text.slice(index + 1);
4282
+ }
3815
4283
  // src/server/cli.ts
3816
- const command = process.argv[2] ?? "help";
3817
- if (command === "--version" || command === "-v") {
3818
- console.log(VERSION);
3819
- process.exit(0);
3820
- }
3821
- const { directory, notice } = await resolveDataDirectory(process.env, homedir(), process.platform);
3822
- if (notice) console.error(notice);
3823
- mkdirSync(directory, {
3824
- recursive: true,
3825
- mode: 448
3826
- });
3827
- process.umask(63);
3828
- const socket = join(directory, "control.sock");
3829
- const tokenPath = join(directory, "token");
3830
- const log = join(directory, "service.log");
3831
- async function control(action) {
3832
- return new Promise((resolve, reject) => {
4284
+ /** `status` exit code when nothing is running, as for `systemctl status`. */
4285
+ const NOT_RUNNING = 3;
4286
+ const out = makeStyle(colorEnabled(process.env, process.stdout.isTTY));
4287
+ const err = makeStyle(colorEnabled(process.env, process.stderr.isTTY));
4288
+ const argv = process.argv.slice(2);
4289
+ const name = argv[0] ?? "help";
4290
+ /** Where data lives, for help text only: resolving it for real may migrate a legacy directory. */
4291
+ const displayDirectory = () => resolve(process.env.LITEPASEO_HOME || process.env.LITEPASEO_DATA_DIR || join(homedir(), ".litepaseo"));
4292
+ async function dataDirectory() {
4293
+ const { directory, notice } = await resolveDataDirectory(process.env, homedir(), process.platform);
4294
+ if (notice) console.error(notice);
4295
+ mkdirSync(directory, {
4296
+ recursive: true,
4297
+ mode: 448
4298
+ });
4299
+ process.umask(63);
4300
+ return {
4301
+ directory,
4302
+ socket: join(directory, "control.sock"),
4303
+ token: join(directory, "token"),
4304
+ log: join(directory, "service.log")
4305
+ };
4306
+ }
4307
+ function control(socket, action) {
4308
+ return new Promise((done, reject) => {
3833
4309
  const s = connect(socket);
3834
- let out = "";
4310
+ let text = "";
3835
4311
  s.setTimeout(2e3, () => s.destroy(/* @__PURE__ */ new Error("Control request timed out")));
3836
4312
  s.on("error", reject);
3837
4313
  s.on("connect", () => s.end(action));
3838
- s.on("data", (chunk) => out += chunk);
3839
- s.on("end", () => resolve(out));
4314
+ s.on("data", (chunk) => text += chunk);
4315
+ s.on("end", () => done(text));
3840
4316
  });
3841
4317
  }
4318
+ async function status(paths) {
4319
+ const text = await control(paths.socket, "status").catch(() => null);
4320
+ if (!text) return null;
4321
+ try {
4322
+ return JSON.parse(text);
4323
+ } catch {
4324
+ return null;
4325
+ }
4326
+ }
4327
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
3842
4328
  /** The reason recorded by the supervisor that just stopped, if any. */
3843
- function lastFailure(since) {
4329
+ function lastFailure(log, since) {
3844
4330
  if (!existsSync(log)) return null;
3845
4331
  const bytes = readFileSync(log);
3846
4332
  const lines = bytes.subarray(bytes.length >= since ? since : 0).toString("utf8").trim().split("\n").reverse();
@@ -3850,107 +4336,199 @@ function lastFailure(since) {
3850
4336
  } catch {}
3851
4337
  return null;
3852
4338
  }
3853
- async function main() {
3854
- if (command === "help" || command === "--help") {
3855
- console.log([
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",
3857
- " token print the access token (required for sign-in)",
3858
- " totp-reset turn off authenticator sign-in (lost phone)",
3859
- " signout-all revoke every signed-in browser and its notifications",
3860
- `Data: ${directory}`,
3861
- "Environment: LITEPASEO_HOME (default ~/.litepaseo), LITEPASEO_PORT (8787), LITEPASEO_BIND (127.0.0.1),",
3862
- " LITEPASEO_PUSH_SUBJECT (mailto: or https: contact for push services)"
3863
- ].join("\n"));
3864
- return;
3865
- }
3866
- if (command === "service") {
3867
- console.log(manageService(process.argv[3] ?? "print", {
3868
- platform: process.platform,
3869
- home: homedir(),
3870
- directory,
3871
- node: process.execPath,
3872
- cli: fileURLToPath(import.meta.url),
3873
- env: process.env,
3874
- uid: process.getuid?.() ?? 0
3875
- }));
3876
- return;
3877
- }
3878
- if (command === "backup" || command === "restore") {
3879
- const path = process.argv[3];
3880
- if (!path) throw new Error(`Usage: litepaseo ${command} <backup-directory>`);
3881
- if (command === "backup") backup(directory, path);
3882
- else await restore(path, directory);
3883
- console.log(command === "backup" ? "Backup complete. Keep this directory private: it contains credentials." : "Restore complete. Start LitePaseo with this LITEPASEO_HOME.");
3884
- return;
3885
- }
3886
- if (command === "token") {
3887
- console.log(readFileSync(tokenPath, "utf8"));
4339
+ function printStarted(state, already) {
4340
+ console.log(`${out.green("●")} LitePaseo ${state.version ?? ""} ${already ? "is already running" : "is running"} at ${out.cyan(state.url)}`.replace(" ", " "));
4341
+ const note = versionNote(state, VERSION, out);
4342
+ if (note) console.log(note);
4343
+ else if (!already) console.log(out.dim(" Sign in with the access token from: litepaseo token"));
4344
+ }
4345
+ async function start(paths, args) {
4346
+ const running = await status(paths);
4347
+ if (running) {
4348
+ if (args.flags.json) console.log(JSON.stringify(running));
4349
+ else printStarted(running, true);
3888
4350
  return;
3889
4351
  }
3890
- if (command === "totp-reset" || command === "signout-all") {
3891
- const store = new Store(directory);
3892
- if (command === "totp-reset") {
3893
- store.setSetting("totp_secret", null);
3894
- console.log("Authenticator sign-in is off. Sign in with: litepaseo token");
3895
- } else {
3896
- store.revokeSessions();
3897
- console.log("Every browser is signed out; their notifications stop.");
4352
+ const logStart = existsSync(paths.log) ? statSync(paths.log).size : 0;
4353
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "serve"], {
4354
+ detached: true,
4355
+ stdio: "ignore",
4356
+ env: process.env
4357
+ });
4358
+ let exited = false;
4359
+ child.on("error", () => {});
4360
+ child.once("exit", () => {
4361
+ exited = true;
4362
+ });
4363
+ child.unref();
4364
+ for (let i = 0; i < 100; i++) {
4365
+ await sleep(100);
4366
+ if (exited) throw new Error(lastFailure(paths.log, logStart) ?? "Startup failed. Run 'litepaseo logs' for details.");
4367
+ const ready = await status(paths);
4368
+ if (ready?.ready) {
4369
+ if (args.flags.json) console.log(JSON.stringify(ready));
4370
+ else printStarted(ready, false);
4371
+ return;
3898
4372
  }
3899
- store.close();
3900
- return;
3901
4373
  }
3902
- if (command === "logs") {
3903
- console.log(existsSync(log) ? readFileSync(log, "utf8").slice(-64e3) : "No logs");
4374
+ throw new Error("Startup not ready after 10 s. Run 'litepaseo status' or 'litepaseo logs'.");
4375
+ }
4376
+ async function stop(paths, quiet = false) {
4377
+ if (!await control(paths.socket, "stop").catch(() => null)) {
4378
+ if (!quiet) console.log("LitePaseo is not running.");
3904
4379
  return;
3905
4380
  }
3906
- if (command === "status") {
3907
- console.log(await control("status").catch(() => "Not running or control endpoint unavailable"));
3908
- return;
4381
+ for (let i = 0; i < 150 && existsSync(paths.socket); i++) await sleep(100);
4382
+ if (existsSync(paths.socket)) throw new Error("LitePaseo has not stopped after 15 s. Run 'litepaseo status'.");
4383
+ if (!quiet) console.log("LitePaseo stopped.");
4384
+ }
4385
+ async function showStatus(paths, args) {
4386
+ const state = await status(paths);
4387
+ if (args.flags.json) console.log(JSON.stringify(state ?? { running: false }));
4388
+ else if (state) console.log(formatStatus(state, VERSION, paths.directory, out));
4389
+ else console.log(`${out.dim("○")} LitePaseo is not running\n ${out.dim("Start it with: litepaseo start")}`);
4390
+ if (!state) process.exitCode = NOT_RUNNING;
4391
+ }
4392
+ async function logs(paths, args) {
4393
+ const count = args.flags.lines === void 0 ? 100 : Number(args.flags.lines);
4394
+ if (!Number.isInteger(count) || count < 0) throw new UsageError("--lines needs a whole number.");
4395
+ let text = existsSync(paths.log) ? readFileSync(paths.log, "utf8") : "";
4396
+ if (text.split("\n").length <= count && existsSync(paths.log + ".1")) text = readFileSync(paths.log + ".1", "utf8") + text;
4397
+ const tail = lastLines(text, count);
4398
+ if (tail) process.stdout.write(tail.endsWith("\n") ? tail : tail + "\n");
4399
+ else if (!args.flags.follow) console.log(out.dim(`No logs yet in ${paths.log}`));
4400
+ if (!args.flags.follow) return;
4401
+ let position = existsSync(paths.log) ? statSync(paths.log).size : 0;
4402
+ let inode = existsSync(paths.log) ? statSync(paths.log).ino : 0;
4403
+ for (;;) {
4404
+ await sleep(500);
4405
+ if (!existsSync(paths.log)) continue;
4406
+ const info = statSync(paths.log);
4407
+ if (info.ino !== inode || info.size < position) [position, inode] = [0, info.ino];
4408
+ if (info.size === position) continue;
4409
+ const fd = openSync(paths.log, "r");
4410
+ try {
4411
+ const chunk = Buffer.alloc(info.size - position);
4412
+ const read = readSync(fd, chunk, 0, chunk.length, position);
4413
+ process.stdout.write(chunk.subarray(0, read));
4414
+ position += read;
4415
+ } finally {
4416
+ closeSync(fd);
4417
+ }
3909
4418
  }
3910
- if (command === "stop" || command === "restart") {
3911
- console.log(await control("stop").catch(() => "Not running"));
3912
- if (command === "stop") return;
3913
- for (let i = 0; i < 150 && existsSync(socket); i++) await new Promise((r) => setTimeout(r, 100));
3914
- if (existsSync(socket)) throw new Error("Previous instance has not stopped");
4419
+ }
4420
+ async function version(args) {
4421
+ const paths = await dataDirectory();
4422
+ const state = await status(paths);
4423
+ const details = {
4424
+ version: VERSION,
4425
+ node: process.versions.node,
4426
+ platform: `${process.platform}-${process.arch}`,
4427
+ home: paths.directory,
4428
+ running: state ? state.version ?? "unknown" : null
4429
+ };
4430
+ if (args.flags.json) return console.log(JSON.stringify(details));
4431
+ const row = (label, value) => ` ${out.dim(label.padEnd(10))}${value}`;
4432
+ console.log([
4433
+ `${out.bold("LitePaseo")} ${VERSION}`,
4434
+ row("Node.js", details.node),
4435
+ row("Platform", details.platform),
4436
+ row("Data", details.home),
4437
+ row("Running", state ? `${details.running} at ${out.cyan(state.url)}` : out.dim("not running"))
4438
+ ].join("\n"));
4439
+ if (state) {
4440
+ const note = versionNote(state, VERSION, out);
4441
+ if (note) console.log("\n" + note);
3915
4442
  }
3916
- if (command === "start" || command === "restart") {
3917
- const running = await control("status").catch(() => null);
3918
- if (running) {
3919
- console.log(running);
4443
+ }
4444
+ async function run() {
4445
+ if (name === "--version" || name === "-v" || name === "-V") return console.log(VERSION);
4446
+ if (name === "--help" || name === "-h") return console.log(mainHelp(VERSION, displayDirectory(), out));
4447
+ if (name === "worker") return runWorker((await dataDirectory()).directory, fileURLToPath(new URL("../web/", import.meta.url)));
4448
+ const command = findCommand(name);
4449
+ if (!command) {
4450
+ const guess = suggest(name, COMMANDS.map((c) => c.name));
4451
+ throw new UsageError(`Unknown command '${name}'.${guess ? ` Did you mean '${guess}'?` : ""}`);
4452
+ }
4453
+ const args = parseArgs(command, argv.slice(1));
4454
+ if (args.help) return console.log(commandHelp(command, out));
4455
+ switch (command.name) {
4456
+ case "help": {
4457
+ const topic = args.positional[0];
4458
+ if (!topic) return console.log(mainHelp(VERSION, displayDirectory(), out));
4459
+ const target = findCommand(topic);
4460
+ if (!target) {
4461
+ const guess = suggest(topic, COMMANDS.map((c) => c.name));
4462
+ throw new UsageError(`No help for '${topic}'.${guess ? ` Did you mean '${guess}'?` : ""}`);
4463
+ }
4464
+ return console.log(commandHelp(target, out));
4465
+ }
4466
+ case "version": return version(args);
4467
+ }
4468
+ const paths = await dataDirectory();
4469
+ switch (command.name) {
4470
+ case "start": return start(paths, args);
4471
+ case "stop": return stop(paths);
4472
+ case "restart":
4473
+ await stop(paths, true);
4474
+ return start(paths, args);
4475
+ case "status": return showStatus(paths, args);
4476
+ case "logs": return logs(paths, args);
4477
+ case "serve": return supervise(paths.directory, fileURLToPath(import.meta.url));
4478
+ case "token":
4479
+ if (!existsSync(paths.token)) throw new Error("No access token yet: it is created on first start. Run 'litepaseo start'.");
4480
+ return console.log(readFileSync(paths.token, "utf8").trim());
4481
+ case "totp-reset":
4482
+ case "signout-all": {
4483
+ const store = new Store(paths.directory);
4484
+ try {
4485
+ if (command.name === "totp-reset") {
4486
+ store.setSetting("totp_secret", null);
4487
+ console.log("Authenticator sign-in is off. Sign in with the token from: litepaseo token");
4488
+ } else {
4489
+ store.revokeSessions();
4490
+ console.log("Every browser is signed out; their notifications stop.");
4491
+ }
4492
+ } finally {
4493
+ store.close();
4494
+ }
3920
4495
  return;
3921
4496
  }
3922
- const logStart = existsSync(log) ? statSync(log).size : 0;
3923
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "serve"], {
3924
- detached: true,
3925
- stdio: "ignore",
3926
- env: process.env
3927
- });
3928
- let exited = false;
3929
- child.on("error", () => {});
3930
- child.once("exit", () => {
3931
- exited = true;
3932
- });
3933
- child.unref();
3934
- for (let i = 0; i < 100; i++) {
3935
- await new Promise((r) => setTimeout(r, 100));
3936
- if (exited) throw new Error(lastFailure(logStart) ?? "Startup failed. Run litepaseo logs for details.");
3937
- const ready = await control("status").catch(() => null);
3938
- if (ready && JSON.parse(ready).ready) {
3939
- console.log(ready);
3940
- console.log("Retrieve your browser access token with: litepaseo token");
3941
- return;
4497
+ case "backup":
4498
+ backup(paths.directory, args.positional[0]);
4499
+ return console.log("Backup complete. Keep this directory private: it contains credentials.");
4500
+ case "restore":
4501
+ await restore(args.positional[0], paths.directory);
4502
+ return console.log(`Restore complete into ${paths.directory}. Start it with: litepaseo start`);
4503
+ case "service": {
4504
+ const action = args.positional[0] ?? "print";
4505
+ if (!SERVICE_ACTIONS.includes(action)) {
4506
+ const guess = suggest(action, SERVICE_ACTIONS);
4507
+ throw new UsageError(`Unknown service action '${action}'.${guess ? ` Did you mean '${guess}'?` : ""} Actions: ${SERVICE_ACTIONS.join(", ")}.`);
3942
4508
  }
4509
+ return console.log(manageService(action, {
4510
+ platform: process.platform,
4511
+ home: homedir(),
4512
+ directory: paths.directory,
4513
+ node: process.execPath,
4514
+ cli: fileURLToPath(import.meta.url),
4515
+ env: process.env,
4516
+ uid: process.getuid?.() ?? 0
4517
+ }));
3943
4518
  }
3944
- throw new Error("Startup not ready after 10 s. Run litepaseo status or litepaseo logs.");
3945
4519
  }
3946
- if (command === "worker") return runWorker(directory, fileURLToPath(new URL("../web/", import.meta.url)));
3947
- if (command === "serve") return supervise(directory, fileURLToPath(import.meta.url));
3948
- throw new Error("Unknown command. Run litepaseo --help");
3949
4520
  }
3950
- main().catch((error) => {
3951
- console.error(error.message);
3952
- if (command === "serve" && !(error instanceof StartupFailure)) try {
3953
- new RotatingLog(log).write(JSON.stringify({
4521
+ run().catch(async (error) => {
4522
+ if (error instanceof UsageError) {
4523
+ console.error(`${err.red("error:")} ${error.message}`);
4524
+ const command = findCommand(name);
4525
+ console.error(err.dim(command && name !== "help" ? `Run 'litepaseo ${name} --help' for usage.` : "Run 'litepaseo --help' for the list of commands."));
4526
+ process.exitCode = 2;
4527
+ return;
4528
+ }
4529
+ console.error(`${err.red("error:")} ${error.message}`);
4530
+ if (name === "serve" && !(error instanceof StartupFailure)) try {
4531
+ new RotatingLog((await dataDirectory()).log).write(JSON.stringify({
3954
4532
  event: "supervisor_start_failed",
3955
4533
  error: error.message
3956
4534
  }) + "\n");