litepaseo 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +2 -1
  3. package/dist/server/cli.mjs +259 -3787
  4. package/dist/server/worker-BxtQnBVZ.mjs +3619 -0
  5. package/dist/web/assets/{CodeBlockNode-BOQ7WC72.js → CodeBlockNode-Dg9n5ezc.js} +1 -1
  6. package/dist/web/assets/CodeBlockNode-Dg9n5ezc.js.br +0 -0
  7. package/dist/web/assets/CodeBlockNode-Dg9n5ezc.js.gz +0 -0
  8. package/dist/web/assets/{FileViewer-16UXxzOe.js → FileViewer-BqAUo_AP.js} +1 -1
  9. package/dist/web/assets/FileViewer-BqAUo_AP.js.br +0 -0
  10. package/dist/web/assets/FileViewer-BqAUo_AP.js.gz +0 -0
  11. package/dist/web/assets/{FilesPanel-CdDybrQn.js → FilesPanel-Bl65Hz3k.js} +1 -1
  12. package/dist/web/assets/FilesPanel-Bl65Hz3k.js.br +0 -0
  13. package/dist/web/assets/FilesPanel-Bl65Hz3k.js.gz +0 -0
  14. package/dist/web/assets/{MarkdownMessage-Bm42-B56.js → MarkdownMessage-j-M1z3-u.js} +5 -5
  15. package/dist/web/assets/MarkdownMessage-j-M1z3-u.js.br +0 -0
  16. package/dist/web/assets/MarkdownMessage-j-M1z3-u.js.gz +0 -0
  17. package/dist/web/assets/{PreCodeBlock-BiQ6xAvM.js → PreCodeBlock-B8fBuBdP.js} +1 -1
  18. package/dist/web/assets/{PreCodeBlock.vue_vue_type_style_index_0_lang-DUZXIc-h.js → PreCodeBlock.vue_vue_type_style_index_0_lang-Cj9vGyzE.js} +1 -1
  19. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Cj9vGyzE.js.br +0 -0
  20. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Cj9vGyzE.js.gz +0 -0
  21. package/dist/web/assets/TerminalPanel-ZkVJFLM1.js +3 -0
  22. package/dist/web/assets/TerminalPanel-ZkVJFLM1.js.br +0 -0
  23. package/dist/web/assets/TerminalPanel-ZkVJFLM1.js.gz +0 -0
  24. package/dist/web/assets/{TerminalPanel-DvfBWyiQ.css → TerminalPanel-mJ-uVP4H.css} +1 -1
  25. package/dist/web/assets/TerminalPanel-mJ-uVP4H.css.br +0 -0
  26. package/dist/web/assets/TerminalPanel-mJ-uVP4H.css.gz +0 -0
  27. package/dist/web/assets/{Tooltip-ClqPy17d.js → Tooltip-Jdp8zjwT.js} +1 -1
  28. package/dist/web/assets/Tooltip-Jdp8zjwT.js.br +0 -0
  29. package/dist/web/assets/Tooltip-Jdp8zjwT.js.gz +0 -0
  30. package/dist/web/assets/addon-unicode11-C82cyeHQ.js +7 -0
  31. package/dist/web/assets/addon-unicode11-C82cyeHQ.js.br +0 -0
  32. package/dist/web/assets/addon-unicode11-C82cyeHQ.js.gz +0 -0
  33. package/dist/web/assets/addon-webgl-C3a5wC6k.js +64 -0
  34. package/dist/web/assets/addon-webgl-C3a5wC6k.js.br +0 -0
  35. package/dist/web/assets/addon-webgl-C3a5wC6k.js.gz +0 -0
  36. package/dist/web/assets/index-Cf1QB007.js +32 -0
  37. package/dist/web/assets/index-Cf1QB007.js.br +0 -0
  38. package/dist/web/assets/index-Cf1QB007.js.gz +0 -0
  39. package/dist/web/assets/{index-CITaZKmy.css → index-Dzid_5f9.css} +1 -1
  40. package/dist/web/assets/index-Dzid_5f9.css.br +0 -0
  41. package/dist/web/assets/index-Dzid_5f9.css.gz +0 -0
  42. package/dist/web/assets/{index10-BG65E54y.js → index10-EuskhiaE.js} +1 -1
  43. package/dist/web/assets/index10-EuskhiaE.js.br +0 -0
  44. package/dist/web/assets/index10-EuskhiaE.js.gz +0 -0
  45. package/dist/web/assets/index3-bqHD_tAN.js +1 -0
  46. package/dist/web/assets/index4-CnpLIN0Y.js +1 -0
  47. package/dist/web/assets/{index5-CzcXp9wR.js → index5-CIMd5e5U.js} +1 -1
  48. package/dist/web/assets/index5-CIMd5e5U.js.br +0 -0
  49. package/dist/web/assets/index5-CIMd5e5U.js.gz +0 -0
  50. package/dist/web/assets/{index6-DPLyU-vO.js → index6-DrnWk0rr.js} +1 -1
  51. package/dist/web/assets/index6-DrnWk0rr.js.br +0 -0
  52. package/dist/web/assets/index6-DrnWk0rr.js.gz +0 -0
  53. package/dist/web/assets/{index7-6uQOIsxo.js → index7-BCl4u4Ci.js} +1 -1
  54. package/dist/web/assets/index7-BCl4u4Ci.js.br +0 -0
  55. package/dist/web/assets/index7-BCl4u4Ci.js.gz +0 -0
  56. package/dist/web/assets/{index8-DUBqmq2E.js → index8-tfhmdpKZ.js} +1 -1
  57. package/dist/web/assets/index8-tfhmdpKZ.js.br +0 -0
  58. package/dist/web/assets/index8-tfhmdpKZ.js.gz +0 -0
  59. package/dist/web/assets/{index9-Czv_zULn.js → index9-Co0BXJFT.js} +1 -1
  60. package/dist/web/assets/index9-Co0BXJFT.js.br +0 -0
  61. package/dist/web/assets/index9-Co0BXJFT.js.gz +0 -0
  62. package/dist/web/index.html +2 -2
  63. package/dist/web/index.html.br +0 -0
  64. package/dist/web/index.html.gz +0 -0
  65. package/package.json +5 -3
  66. package/dist/web/assets/CodeBlockNode-BOQ7WC72.js.br +0 -0
  67. package/dist/web/assets/CodeBlockNode-BOQ7WC72.js.gz +0 -0
  68. package/dist/web/assets/FileViewer-16UXxzOe.js.br +0 -0
  69. package/dist/web/assets/FileViewer-16UXxzOe.js.gz +0 -0
  70. package/dist/web/assets/FilesPanel-CdDybrQn.js.br +0 -0
  71. package/dist/web/assets/FilesPanel-CdDybrQn.js.gz +0 -0
  72. package/dist/web/assets/MarkdownMessage-Bm42-B56.js.br +0 -0
  73. package/dist/web/assets/MarkdownMessage-Bm42-B56.js.gz +0 -0
  74. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DUZXIc-h.js.br +0 -0
  75. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DUZXIc-h.js.gz +0 -0
  76. package/dist/web/assets/TerminalPanel-B5K5NCf0.js +0 -3
  77. package/dist/web/assets/TerminalPanel-B5K5NCf0.js.br +0 -0
  78. package/dist/web/assets/TerminalPanel-B5K5NCf0.js.gz +0 -0
  79. package/dist/web/assets/TerminalPanel-DvfBWyiQ.css.br +0 -0
  80. package/dist/web/assets/TerminalPanel-DvfBWyiQ.css.gz +0 -0
  81. package/dist/web/assets/Tooltip-ClqPy17d.js.br +0 -0
  82. package/dist/web/assets/Tooltip-ClqPy17d.js.gz +0 -0
  83. package/dist/web/assets/index-By8I8BM7.js +0 -32
  84. package/dist/web/assets/index-By8I8BM7.js.br +0 -0
  85. package/dist/web/assets/index-By8I8BM7.js.gz +0 -0
  86. package/dist/web/assets/index-CITaZKmy.css.br +0 -0
  87. package/dist/web/assets/index-CITaZKmy.css.gz +0 -0
  88. package/dist/web/assets/index10-BG65E54y.js.br +0 -0
  89. package/dist/web/assets/index10-BG65E54y.js.gz +0 -0
  90. package/dist/web/assets/index3-6tLrzhUa.js +0 -1
  91. package/dist/web/assets/index4-CZn-viSK.js +0 -1
  92. package/dist/web/assets/index5-CzcXp9wR.js.br +0 -0
  93. package/dist/web/assets/index5-CzcXp9wR.js.gz +0 -0
  94. package/dist/web/assets/index6-DPLyU-vO.js.br +0 -0
  95. package/dist/web/assets/index6-DPLyU-vO.js.gz +0 -0
  96. package/dist/web/assets/index7-6uQOIsxo.js.br +0 -0
  97. package/dist/web/assets/index7-6uQOIsxo.js.gz +0 -0
  98. package/dist/web/assets/index8-DUBqmq2E.js.br +0 -0
  99. package/dist/web/assets/index8-DUBqmq2E.js.gz +0 -0
  100. package/dist/web/assets/index9-Czv_zULn.js.br +0 -0
  101. package/dist/web/assets/index9-Czv_zULn.js.gz +0 -0
@@ -2,28 +2,13 @@
2
2
  import { appendFileSync, chmodSync, closeSync, constants, copyFileSync, cpSync, existsSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
3
3
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
4
4
  import { execFileSync, fork, spawn } from "node:child_process";
5
- import { basename, dirname, isAbsolute, join, normalize, resolve } from "node:path";
5
+ import { dirname, join, resolve } from "node:path";
6
6
  import { connect, createServer } from "node:net";
7
7
  import { DatabaseSync } from "node:sqlite";
8
- import { serve } from "@hono/node-server";
9
- import { createHostClient, parseHostTarget } from "@getpaseo/client/node";
10
- import { createPaseoApi } from "@getpaseo/client";
11
- import { deriveAgentStateBucket } from "@getpaseo/protocol/agent-state-bucket";
12
- import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity";
13
- import { z } from "zod";
14
- import { lstat, readFile, realpath } from "node:fs/promises";
15
- import { homedir, tmpdir } from "node:os";
16
- import { Hono } from "hono";
17
- import { bodyLimit } from "hono/body-limit";
18
- import { serveStatic } from "@hono/node-server/serve-static";
19
- import { deleteCookie, getCookie, setCookie } from "hono/cookie";
20
- import QRCode from "qrcode";
21
- import { AgentPermissionResponseSchema } from "@getpaseo/protocol/messages";
22
- import webpush from "web-push";
23
- import WebSocket, { WebSocketServer } from "ws";
8
+ import { homedir } from "node:os";
24
9
  import { fileURLToPath } from "node:url";
25
10
  // src/server/version.ts
26
- const VERSION = "0.4.0";
11
+ const VERSION = "0.4.2";
27
12
  // src/server/rotating-log.ts
28
13
  /** One writer (the supervisor); bounded active file plus numbered archives. */
29
14
  var RotatingLog = class {
@@ -572,6 +557,19 @@ var Store = class {
572
557
  cards: JSON.parse(String(row.cards))
573
558
  };
574
559
  }
560
+ /**
561
+ * Read-modify-write of one card, at the current revision (synchronous, so nothing interleaves).
562
+ * `change` returns the new card, or null to leave the board untouched. False: no such card.
563
+ */
564
+ updateCard(id, change) {
565
+ const { revision, cards } = this.board();
566
+ const index = cards.findIndex((c) => c.id === id);
567
+ if (index < 0) return false;
568
+ const next = change(cards[index]);
569
+ if (!next) return true;
570
+ cards[index] = next;
571
+ return this.saveBoard(revision, cards);
572
+ }
575
573
  saveBoard(revision, cards) {
576
574
  return this.db.prepare("UPDATE board SET revision=revision+1,cards=? WHERE id=1 AND revision=?").run(JSON.stringify(cards), revision).changes === 1;
577
575
  }
@@ -579,1770 +577,178 @@ var Store = class {
579
577
  this.db.close();
580
578
  }
581
579
  };
582
- // src/server/diagnostics.ts
583
- /** Classify untrusted SDK failures without copying URLs, credentials or remote text into logs/UI. */
584
- function connectionProblem(value) {
585
- const e = value;
586
- const text = [
587
- e?.reason,
588
- e?.failureCode,
589
- e?.message,
590
- e?.code
591
- ].filter((v) => typeof v === "string").join(" ").toLowerCase();
592
- if (/password.required|password required/.test(text)) return {
593
- code: "password_required",
594
- message: "Authentication required. Add this host using a password-bearing connection URL or a pairing offer."
595
- };
596
- if (/incorrect.password|unauthorized|authentication|auth.failed|forbidden/.test(text)) return {
597
- code: "authentication_failed",
598
- message: "Authentication failed. Check the host credentials or create a new pairing offer."
599
- };
600
- if (/version|protocol|incompatible/.test(text)) return {
601
- code: "incompatible",
602
- message: "Protocol negotiation failed. Check the daemon and client versions."
603
- };
604
- if (/enotfound|eai_again|dns/.test(text)) return {
605
- code: "dns",
606
- message: "Host name could not be resolved. Check the address and DNS."
607
- };
608
- if (/econnrefused|connection refused/.test(text)) return {
609
- code: "refused",
610
- message: "Connection refused. Check that the daemon is running and the port is reachable."
611
- };
612
- if (/timed?.?out|timeout/.test(text)) return {
613
- code: "timeout",
614
- message: "Connection timed out. Check the network, tunnel and firewall."
615
- };
616
- if (/cert|tls|ssl/.test(text)) return {
617
- code: "tls",
618
- message: "Secure connection failed. Check the server certificate and TLS configuration."
619
- };
620
- return {
621
- code: "disconnected",
622
- message: "Connection lost. Check the daemon, network and connection settings."
623
- };
624
- }
625
- // src/server/versioned-collection.ts
626
- /**
627
- * Keyed values ordered by their last change. Every write moves the entry to the tail, so
628
- * `changesSince(seq)` walks back only over entries changed after `seq`: O(changes), never
629
- * O(collection). Deletions stay as tombstones until the bounded tombstone budget evicts them;
630
- * readers older than the evicted horizon (`floor`) must take a snapshot instead.
631
- */
632
- var VersionedCollection = class {
633
- generation = randomUUID();
634
- nodes = /* @__PURE__ */ new Map();
635
- head = null;
636
- tail = null;
637
- current = 0;
638
- floor = 0;
639
- live = 0;
640
- tombstones = [];
641
- tombstoneHead = 0;
642
- maxTombstones;
643
- constructor(maxTombstones = 4096) {
644
- this.maxTombstones = maxTombstones;
645
- }
646
- get seq() {
647
- return this.current;
648
- }
649
- get size() {
650
- return this.live;
651
- }
652
- get(key) {
653
- const node = this.nodes.get(key);
654
- return node && node.value !== null ? node.value : void 0;
655
- }
656
- set(key, value) {
657
- let node = this.nodes.get(key);
658
- if (node) {
659
- if (node.value === null) this.live++;
660
- this.unlink(node);
661
- } else {
662
- node = {
663
- key,
664
- value,
665
- seq: 0,
666
- prev: null,
667
- next: null
668
- };
669
- this.nodes.set(key, node);
670
- this.live++;
671
- }
672
- node.value = value;
673
- node.seq = ++this.current;
674
- this.append(node);
675
- }
676
- delete(key) {
677
- const node = this.nodes.get(key);
678
- if (!node || node.value === null) return false;
679
- this.live--;
680
- node.value = null;
681
- node.seq = ++this.current;
682
- this.unlink(node);
683
- this.append(node);
684
- this.tombstones.push({
685
- node,
686
- seq: node.seq
580
+ // src/server/backup.ts
581
+ const FILES = ["litepaseo.sqlite", "token"];
582
+ const digest = (path) => createHash("sha256").update(readFileSync(path)).digest("hex");
583
+ /** A consistent SQLite snapshot includes committed WAL data; never copy a live database file. */
584
+ function backup(directory, destination) {
585
+ destination = resolve(destination);
586
+ if (!existsSync(join(directory, FILES[0])) || !existsSync(join(directory, "token"))) throw new Error("No initialized LitePaseo data to back up.");
587
+ mkdirSync(destination, { mode: 448 });
588
+ let store;
589
+ try {
590
+ store = new Store(directory);
591
+ store.db.prepare("VACUUM INTO ?").run(join(destination, FILES[0]));
592
+ copyFileSync(join(directory, "token"), join(destination, "token"), constants.COPYFILE_EXCL);
593
+ for (const file of FILES) chmodSync(join(destination, file), 384);
594
+ writeFileSync(join(destination, "manifest.json"), JSON.stringify({
595
+ format: 1,
596
+ schema: 1,
597
+ created: (/* @__PURE__ */ new Date()).toISOString(),
598
+ files: Object.fromEntries(FILES.map((file) => [file, digest(join(destination, file))]))
599
+ }, null, 2) + "\n", {
600
+ mode: 384,
601
+ flag: "wx"
687
602
  });
688
- this.evictTombstones();
689
- return true;
690
- }
691
- /** Latest value of each entry changed after `after`, oldest first; null when a snapshot is required. */
692
- changesSince(after) {
693
- if (after < this.floor || after > this.current) return null;
694
- const out = [];
695
- for (let node = this.tail; node && node.seq > after; node = node.prev) out.push({
696
- key: node.key,
697
- value: node.value
603
+ } catch (error) {
604
+ rmSync(destination, {
605
+ recursive: true,
606
+ force: true
698
607
  });
699
- return out.reverse();
700
- }
701
- /** Full contents. O(n); only for first loads and readers past the tombstone horizon. */
702
- snapshot() {
703
- const out = [];
704
- for (let node = this.head; node; node = node.next) if (node.value !== null) out.push(node.value);
705
- return out;
608
+ throw error;
609
+ } finally {
610
+ store?.close();
706
611
  }
707
- evictTombstones() {
708
- while (this.tombstones.length - this.tombstoneHead > this.maxTombstones) {
709
- const { node, seq } = this.tombstones[this.tombstoneHead++];
710
- if (node.value !== null || node.seq !== seq || this.nodes.get(node.key) !== node) continue;
711
- this.unlink(node);
712
- this.nodes.delete(node.key);
713
- this.floor = Math.max(this.floor, seq);
714
- }
715
- if (this.tombstoneHead > 1024 && this.tombstoneHead * 2 > this.tombstones.length) {
716
- this.tombstones = this.tombstones.slice(this.tombstoneHead);
717
- this.tombstoneHead = 0;
612
+ }
613
+ /** Restore only into an empty home; the same exclusive socket binding prevents concurrent startup. */
614
+ async function restore(source, directory) {
615
+ source = resolve(source);
616
+ mkdirSync(directory, {
617
+ recursive: true,
618
+ mode: 448
619
+ });
620
+ chmodSync(directory, 448);
621
+ const releaseRuntime = acquireRuntimeLock(directory);
622
+ const lock = createServer((socket) => socket.destroy());
623
+ await new Promise((resolve, reject) => {
624
+ lock.once("error", reject);
625
+ lock.listen(join(directory, "control.sock"), resolve);
626
+ }).catch((error) => {
627
+ releaseRuntime();
628
+ throw error;
629
+ });
630
+ const stage = join(directory, ".restore-staging");
631
+ let ownsStage = false;
632
+ try {
633
+ if (readdirSync(directory).some((file) => file !== "control.sock" && file !== "service-lock.sqlite" && file !== "service-lock.sqlite-journal")) throw new Error("Restore requires an empty LITEPASEO_HOME. Restore to a new directory, then start it.");
634
+ mkdirSync(stage, { mode: 448 });
635
+ ownsStage = true;
636
+ const manifest = JSON.parse(readFileSync(join(source, "manifest.json"), "utf8"));
637
+ if (manifest.format !== 1 || manifest.schema !== 1) throw new Error("Unsupported backup format or schema version.");
638
+ for (const file of FILES) {
639
+ copyFileSync(join(source, file), join(stage, file), constants.COPYFILE_EXCL);
640
+ chmodSync(join(stage, file), 384);
641
+ if (manifest.files?.[file] !== digest(join(stage, file))) throw new Error(`Backup checksum failed: ${file}`);
718
642
  }
719
- }
720
- unlink(node) {
721
- if (node.prev) node.prev.next = node.next;
722
- else this.head = node.next;
723
- if (node.next) node.next.prev = node.prev;
724
- else this.tail = node.prev;
725
- node.prev = node.next = null;
726
- }
727
- append(node) {
728
- node.prev = this.tail;
729
- node.next = null;
730
- if (this.tail) this.tail.next = node;
731
- else this.head = node;
732
- this.tail = node;
733
- }
734
- };
735
- // src/server/host-directory.ts
736
- const PAGE = 200;
737
- const RETRY_MS$1 = 2e3;
738
- const basename$1 = (path) => path.replace(/\/+$/, "").split("/").pop() || path;
739
- const time = (value) => value ? Date.parse(value) || 0 : 0;
740
- /**
741
- * Mirrors one daemon directory into a shared collection. After the first snapshot it consumes
742
- * only update deltas; reconnects resume from the daemon's directory-sync cursor, so
743
- * steady-state cost is proportional to changes. Summaries that did not change are dropped.
744
- */
745
- var HostMirror = class {
746
- cursor;
747
- members = /* @__PURE__ */ new Map();
748
- subscription = null;
749
- token = 0;
750
- stopStatus = null;
751
- retry;
752
- /** Items touched by live updates while a paged (non-sync) snapshot is being read. */
753
- liveTouched = null;
754
- adapter;
755
- hostId;
756
- driver;
757
- collection;
758
- changed;
759
- transition;
760
- constructor(adapter, hostId, driver, collection, changed, transition = () => {}) {
761
- this.adapter = adapter;
762
- this.hostId = hostId;
763
- this.driver = driver;
764
- this.collection = collection;
765
- this.changed = changed;
766
- this.transition = transition;
767
- }
768
- /** What the adapter retained for a member, from the latest update; O(1). */
769
- retained(id) {
770
- return this.members.get(id)?.retained;
771
- }
772
- start() {
773
- this.stopStatus = this.driver.subscribeConnectionStatus((state) => this.onStatus(state.status));
774
- this.onStatus(this.driver.getConnectionState().status);
775
- }
776
- dispose() {
777
- const released = this.close();
778
- this.stopStatus?.();
779
- for (const [id, member] of this.members) {
780
- this.collection.delete(this.key(id));
781
- this.transition(member.summary, null);
643
+ const db = new DatabaseSync(join(stage, FILES[0]), { readOnly: true });
644
+ try {
645
+ if (schemaVersion(db) !== 1 || db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("Backup database failed validation.");
646
+ for (const table of [
647
+ "hosts",
648
+ "board",
649
+ "settings",
650
+ "sessions",
651
+ "push_subscriptions"
652
+ ]) db.prepare(`SELECT * FROM ${table} LIMIT 0`).all();
653
+ } finally {
654
+ db.close();
782
655
  }
783
- if (this.members.size) this.changed();
784
- this.members.clear();
785
- return released;
786
- }
787
- key(id) {
788
- return `${this.hostId}:${id}`;
789
- }
790
- onStatus(status) {
791
- if (status === "connected") {
792
- if (!this.subscription) this.open();
793
- } else this.close();
794
- }
795
- open() {
796
- clearTimeout(this.retry);
797
- const token = ++this.token;
798
- const sync = this.driver.getLastServerInfoMessage()?.features?.directorySync === true;
799
- const { base } = this.adapter;
800
- const subscription = this.adapter.observe(this.driver, sync ? {
801
- ...base,
802
- sync: this.cursor ?? {}
803
- } : {
804
- ...base,
805
- page: { limit: PAGE }
656
+ if (!/^[\x21-\x7e]{1,200}$/.test(readFileSync(join(stage, "token"), "utf8").trim())) throw new Error("Invalid backup access token.");
657
+ writeFileSync(join(directory, ".restore-incomplete"), "Restore interrupted: restore the backup to a fresh home.\n", {
658
+ mode: 384,
659
+ flag: "wx"
806
660
  });
807
- this.subscription = subscription;
808
- subscription.subscribe({
809
- snapshot: (payload) => {
810
- if (token === this.token) this.onSnapshot(payload, token, sync).catch(() => this.fail(token));
811
- },
812
- update: (message) => {
813
- if (token === this.token && message.type === this.adapter.updateType) this.onUpdate(this.adapter.update(message.payload));
814
- },
815
- error: () => this.fail(token)
661
+ renameSync(join(stage, "token"), join(directory, "token"));
662
+ renameSync(join(stage, FILES[0]), join(directory, FILES[0]));
663
+ rmSync(join(directory, ".restore-incomplete"));
664
+ } finally {
665
+ if (ownsStage) rmSync(stage, {
666
+ recursive: true,
667
+ force: true
816
668
  });
669
+ await new Promise((resolve) => lock.close(() => resolve()));
670
+ releaseRuntime();
817
671
  }
818
- close() {
819
- this.token++;
820
- clearTimeout(this.retry);
821
- this.liveTouched = null;
822
- const subscription = this.subscription;
823
- this.subscription = null;
824
- return subscription?.release().catch(() => {}) ?? Promise.resolve();
825
- }
826
- fail(token) {
827
- if (token !== this.token) return;
828
- this.close();
829
- this.cursor = void 0;
830
- this.retry = setTimeout(() => {
831
- if (!this.subscription && this.driver.getConnectionState().status === "connected") this.open();
832
- }, RETRY_MS$1);
833
- this.retry.unref?.();
834
- }
835
- async onSnapshot(payload, token, sync) {
836
- if (payload.sync?.mode === "changes") {
837
- if (this.cursor?.generation !== payload.sync.generation) {
838
- this.cursor = void 0;
839
- this.close();
840
- this.open();
841
- return;
842
- }
843
- for (const e of payload.entries) {
844
- const { raw, seq, extra } = this.adapter.entry(e);
845
- this.upsert(raw, seq, false, extra);
846
- }
847
- for (const removal of payload.sync.removals) this.remove(removal.id, removal.seq);
848
- this.cursor = {
849
- generation: payload.sync.generation,
850
- afterSeq: payload.sync.headSeq
851
- };
852
- return;
853
- }
854
- let entries = payload.entries;
855
- if (!sync && payload.pageInfo.hasMore) {
856
- this.liveTouched = /* @__PURE__ */ new Set();
857
- entries = [...entries];
858
- let next = payload.pageInfo.nextCursor;
859
- while (next) {
860
- const page = await this.adapter.fetch(this.driver, {
861
- ...this.adapter.base,
862
- page: {
863
- limit: PAGE,
864
- cursor: next
865
- }
866
- });
867
- if (token !== this.token) return;
868
- entries.push(...page.entries);
869
- next = page.pageInfo.hasMore ? page.pageInfo.nextCursor : null;
870
- }
871
- }
872
- const seen = /* @__PURE__ */ new Set();
873
- for (const e of entries) {
874
- const { raw, seq, extra } = this.adapter.entry(e);
875
- seen.add(this.adapter.id(raw));
876
- this.upsert(raw, sync ? seq : void 0, sync, extra);
877
- }
878
- for (const id of [...this.members.keys()]) if (!seen.has(id) && !this.liveTouched?.has(id)) this.remove(id);
879
- this.liveTouched = null;
880
- this.cursor = payload.sync ? {
881
- generation: payload.sync.generation,
882
- afterSeq: payload.sync.headSeq
883
- } : void 0;
884
- }
885
- onUpdate(update) {
886
- if (update.generation && this.cursor && update.generation !== this.cursor.generation) {
887
- this.cursor = void 0;
888
- this.close();
889
- this.open();
890
- return;
891
- }
892
- const id = update.kind === "upsert" ? this.adapter.id(update.raw) : update.id;
893
- this.liveTouched?.add(id);
894
- if (update.kind === "upsert") this.upsert(update.raw, update.seq, false, update.extra);
895
- else this.remove(update.id, update.seq);
896
- if (update.seq !== void 0 && this.cursor) this.cursor.afterSeq = Math.max(this.cursor.afterSeq, update.seq);
897
- }
898
- upsert(raw, version, force = false, extra) {
899
- const id = this.adapter.id(raw);
900
- if (this.adapter.excluded(raw)) return this.remove(id, version, force);
901
- const member = this.members.get(id);
902
- if (!force && member?.version !== void 0 && version !== void 0 && version < member.version) return;
903
- const kept = extra === void 0 ? member?.extra : extra;
904
- const { summary, memo } = this.adapter.summarize(this.hostId, raw, kept, member?.memo);
905
- const fingerprint = JSON.stringify(summary);
906
- const next = {
907
- fingerprint,
908
- version,
909
- extra: kept,
910
- memo,
911
- summary,
912
- retained: this.adapter.retain?.(raw)
913
- };
914
- this.members.set(id, next);
915
- if (member?.fingerprint === fingerprint) {
916
- next.summary = member.summary;
917
- return;
918
- }
919
- this.collection.set(summary.key, summary);
920
- this.changed();
921
- this.transition(member?.summary ?? null, summary);
922
- }
923
- remove(id, version, force = false) {
924
- const member = this.members.get(id);
925
- if (!member) return;
926
- if (!force && member.version !== void 0 && version !== void 0 && version < member.version) return;
927
- this.members.delete(id);
928
- this.collection.delete(this.key(id));
929
- this.changed();
930
- this.transition(member.summary, null);
931
- }
932
- };
933
- const isRunning = (agent) => agent.status === "running" || !!agent.activeTurn;
934
- /**
935
- * When the session was last *used*: the moment its most recent turn ended. It holds still while
936
- * a turn runs and ignores idle metadata changes, so the sidebar does not reshuffle mid-turn.
937
- * The daemon has no turn-end timestamp, so it is derived from observed transitions:
938
- * - first sight, idle: the last change (normally the turn end);
939
- * - first sight, running: the turn start, else the last user message;
940
- * - running → idle: the change time at that moment;
941
- * - idle, but a new user message appeared (a turn we missed while disconnected): the change time.
942
- */
943
- function deriveActivity(current, previous) {
944
- const memo = (activityAt) => ({
945
- activityAt,
946
- running: current.running,
947
- lastUserMessageAt: current.lastUserMessageAt
948
- });
949
- if (!previous) return memo(current.running ? current.startedAt || current.lastUserMessageAt || current.changedAt : current.changedAt);
950
- if (current.running) return memo(previous.activityAt);
951
- if (previous.running || current.lastUserMessageAt > previous.lastUserMessageAt) return memo(Math.max(current.changedAt, previous.activityAt));
952
- return memo(previous.activityAt);
953
- }
954
- function summarize(hostId, agent, project, activity = time(agent.updatedAt)) {
955
- const permissions = agent.pendingPermissions ?? [];
956
- const bucket = deriveAgentStateBucket({
957
- status: agent.status,
958
- pendingPermissionCount: permissions.length,
959
- requiresAttention: agent.requiresAttention,
960
- attentionReason: agent.attentionReason
961
- });
962
- const state = agent.status === "initializing" && bucket === "done" ? "running" : bucket === "attention" ? "unread" : bucket;
963
- const turnActive = isRunning(agent) || agent.status === "initializing";
964
- return {
965
- key: `${hostId}:${agent.id}`,
966
- hostId,
967
- id: agent.id,
968
- workspaceId: agent.workspaceId ?? null,
969
- title: agent.title ?? null,
970
- status: agent.status,
971
- turnActive,
972
- provider: agent.provider,
973
- cwd: agent.cwd,
974
- project: project?.projectName || basename$1(agent.cwd) || "Other",
975
- projectKey: project?.projectKey ?? null,
976
- activityAt: activity,
977
- turnStartedAt: turnActive ? time(agent.activeTurn?.startedAt) || time(agent.lastUserMessageAt) || null : null,
978
- attention: state === "needs_input",
979
- state,
980
- unread: agent.requiresAttention === true && state !== "needs_input",
981
- lastError: agent.lastError ? agent.lastError.slice(0, 300) : null,
982
- pendingPermissions: permissions,
983
- model: agent.model ?? agent.runtimeInfo?.model ?? null,
984
- thinking: agent.effectiveThinkingOptionId ?? agent.thinkingOptionId ?? agent.runtimeInfo?.thinkingOptionId ?? null,
985
- modeId: agent.currentModeId ?? null,
986
- contextUsed: agent.lastUsage?.contextWindowUsedTokens ?? null,
987
- contextMax: agent.lastUsage?.contextWindowMaxTokens ?? null,
988
- rewind: rewindModes(agent.capabilities)
989
- };
990
672
  }
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;
673
+ // src/server/data-dir.ts
674
+ /** Locations before ~/.litepaseo: the platform data directories. */
675
+ function legacyDirectory(env, home, platform) {
676
+ return platform === "darwin" ? join(home, "Library/Application Support/LitePaseo") : join(env.XDG_DATA_HOME ?? join(home, ".local/share"), "litepaseo");
999
677
  }
1000
- const agentAdapter = {
1001
- updateType: "agent_update",
1002
- base: { scope: "active" },
1003
- observe: (driver, options) => driver.observeAgents(options),
1004
- fetch: (driver, options) => driver.fetchAgents(options),
1005
- entry: (e) => {
1006
- const entry = e;
1007
- return {
1008
- raw: entry.agent,
1009
- seq: entry.syncSeq,
1010
- extra: entry.project
1011
- };
1012
- },
1013
- update: (p) => {
1014
- const u = p;
1015
- return u.kind === "upsert" ? {
1016
- kind: "upsert",
1017
- raw: u.agent,
1018
- extra: u.project,
1019
- generation: u.generation,
1020
- seq: u.seq
1021
- } : {
1022
- kind: "remove",
1023
- id: u.agentId,
1024
- generation: u.generation,
1025
- seq: u.seq
1026
- };
1027
- },
1028
- id: (agent) => agent.id,
1029
- excluded: (agent) => !!agent.archivedAt || !!agent.internal,
1030
- summarize: (hostId, agent, project, previous) => {
1031
- const memo = deriveActivity({
1032
- running: isRunning(agent),
1033
- changedAt: time(agent.updatedAt),
1034
- startedAt: time(agent.activeTurn?.startedAt),
1035
- lastUserMessageAt: time(agent.lastUserMessageAt)
1036
- }, previous);
1037
- return {
1038
- summary: summarize(hostId, agent, project, memo.activityAt),
1039
- memo
678
+ /** Whether a LitePaseo process answers on this control socket. */
679
+ function socketIsLive(path, timeoutMs = 500) {
680
+ return new Promise((done) => {
681
+ if (!existsSync(path)) return done(false);
682
+ const s = connect(path);
683
+ const finish = (live) => {
684
+ s.destroy();
685
+ done(live);
1040
686
  };
1041
- },
1042
- retain: (agent) => ({
1043
- provider: agent.provider,
1044
- capabilities: agent.capabilities,
1045
- availableModes: agent.availableModes ?? [],
1046
- features: agent.features ?? []
1047
- })
1048
- };
1049
- /** One daemon's active agents. */
1050
- var HostDirectory = class extends HostMirror {
1051
- constructor(hostId, driver, collection, changed, transition) {
1052
- super(agentAdapter, hostId, driver, collection, changed, transition);
1053
- }
1054
- /** Provider and capabilities from the live directory; undefined if the agent is not listed. */
1055
- facts(agentId) {
1056
- return this.retained(agentId);
1057
- }
1058
- };
687
+ s.setTimeout(timeoutMs, () => finish(false));
688
+ s.once("connect", () => finish(true));
689
+ s.once("error", () => finish(false));
690
+ });
691
+ }
1059
692
  /**
1060
- * A workspace (a "thread" in Paseo's sidebar). Its state is the daemon's own aggregate over the
1061
- * workspace's agents; recency follows the same turn-end rule as agents.
693
+ * LitePaseo keeps everything in one directory, like Paseo's ~/.paseo: ~/.litepaseo, or
694
+ * LITEPASEO_HOME (LITEPASEO_DATA_DIR still works). Data from the old platform location moves
695
+ * over once, but never out from under a running instance: that one keeps its directory until
696
+ * it is stopped.
1062
697
  */
1063
- function summarizeWorkspace(hostId, ws, activity) {
1064
- const state = ws.status === "attention" ? "unread" : ws.status;
1065
- return {
1066
- key: `${hostId}:${ws.id}`,
1067
- hostId,
1068
- id: ws.id,
1069
- name: ws.name,
1070
- title: ws.title ?? null,
1071
- project: ws.project?.projectName || ws.projectDisplayName || basename$1(ws.projectRootPath) || "Other",
1072
- projectKey: ws.project?.projectKey ?? ws.projectId,
1073
- rootPath: ws.projectRootPath,
1074
- directory: ws.workspaceDirectory ?? ws.projectRootPath,
1075
- kind: ws.workspaceKind,
1076
- branch: ws.gitRuntime?.currentBranch ?? null,
1077
- pinnedAt: time(ws.pinnedAt),
1078
- activityAt: activity,
1079
- state,
1080
- attention: state === "needs_input",
1081
- unread: state === "unread" || state === "failed"
698
+ async function resolveDataDirectory(env, home, platform, isLive = socketIsLive) {
699
+ const configured = env.LITEPASEO_HOME || env.LITEPASEO_DATA_DIR;
700
+ if (configured) return { directory: resolve(configured) };
701
+ const target = join(home, ".litepaseo");
702
+ const legacy = legacyDirectory(env, home, platform);
703
+ if (!existsSync(legacy) || existsSync(target)) return { directory: target };
704
+ if (await isLive(join(legacy, "control.sock"))) return {
705
+ directory: legacy,
706
+ notice: `LitePaseo is running from ${legacy}. Run "litepaseo stop", then start it again to move its data to ${target}.`
1082
707
  };
1083
- }
1084
- const workspaceAdapter = {
1085
- updateType: "workspace_update",
1086
- base: {},
1087
- observe: (driver, options) => {
1088
- if (!driver.observeWorkspaces) throw new Error("Workspaces unsupported");
1089
- return driver.observeWorkspaces(options);
1090
- },
1091
- fetch: (driver, options) => {
1092
- if (!driver.fetchWorkspaces) throw new Error("Workspaces unsupported");
1093
- return driver.fetchWorkspaces(options);
1094
- },
1095
- entry: (e) => {
1096
- const ws = e;
1097
- return {
1098
- raw: ws,
1099
- seq: ws.syncSeq
1100
- };
1101
- },
1102
- update: (p) => {
1103
- const u = p;
1104
- return u.kind === "upsert" ? {
1105
- kind: "upsert",
1106
- raw: u.workspace,
1107
- generation: u.generation,
1108
- seq: u.seq
1109
- } : {
1110
- kind: "remove",
1111
- id: u.id,
1112
- generation: u.generation,
1113
- seq: u.seq
1114
- };
1115
- },
1116
- id: (ws) => ws.id,
1117
- excluded: (ws) => !!ws.archivingAt || !!ws.internal || !!ws.background,
1118
- summarize: (hostId, ws, _extra, previous) => {
1119
- const memo = deriveActivity({
1120
- running: ws.status === "running",
1121
- changedAt: time(ws.statusEnteredAt) || time(ws.activityAt),
1122
- startedAt: ws.status === "running" ? time(ws.statusEnteredAt) : 0,
1123
- lastUserMessageAt: time(ws.lastUserMessageAt)
1124
- }, previous);
1125
- const activity = previous || ws.status === "running" ? memo.activityAt : time(ws.activityAt) || memo.activityAt || time(ws.createdAt);
1126
- return {
1127
- summary: summarizeWorkspace(hostId, ws, activity),
1128
- memo: {
1129
- ...memo,
1130
- activityAt: activity
1131
- }
1132
- };
1133
- }
1134
- };
1135
- /** One daemon's workspaces (Paseo's threads). */
1136
- var HostWorkspaces = class extends HostMirror {
1137
- constructor(hostId, driver, collection, changed) {
1138
- super(workspaceAdapter, hostId, driver, collection, changed);
708
+ try {
709
+ renameSync(legacy, target);
710
+ } catch (error) {
711
+ if (error.code !== "EXDEV") throw error;
712
+ cpSync(legacy, target, {
713
+ recursive: true,
714
+ preserveTimestamps: true
715
+ });
716
+ rmSync(legacy, {
717
+ recursive: true,
718
+ force: true
719
+ });
1139
720
  }
1140
- };
1141
- // src/server/timeline-view.ts
1142
- const TAIL_LIMIT = 60;
1143
- const CATCH_UP_PAGE = 200;
1144
- /** Rows kept per view; older rows are dropped and stay reachable through history pages. */
1145
- const MAX_ROWS = 600;
1146
- const KEEP_ROWS = 500;
1147
- /** Rows sent to a client that (re)joins; older ones load on demand. */
1148
- const RESET_ROWS = 200;
1149
- const MAX_BUFFER = 5e3;
1150
- const FLUSH_MS = 500;
1151
- const RETRY_MS = 2e3;
1152
- /** Same fold the daemon's TimelineProjection applies when a tool call reports again. */
1153
- function mergeToolCallItems(existing, incoming) {
1154
- const a = existing.detail, b = incoming.detail;
1155
- const detail = a?.type === "unknown" && b?.type !== "unknown" ? b : b?.type === "unknown" && a?.type !== "unknown" ? a : b;
1156
- const metadata = existing.metadata || incoming.metadata ? {
1157
- ...existing.metadata,
1158
- ...incoming.metadata
1159
- } : void 0;
1160
- const merged = {
1161
- ...existing,
1162
- ...incoming,
1163
- detail,
1164
- metadata
721
+ const socket = join(target, "control.sock");
722
+ if (existsSync(socket)) unlinkSync(socket);
723
+ return {
724
+ directory: target,
725
+ notice: `Moved LitePaseo data from ${legacy} to ${target}.`
1165
726
  };
1166
- if (incoming.status === "failed") merged.error = incoming.error;
1167
- else if (incoming.status === "completed" || incoming.status === "canceled") merged.error = null;
1168
- else if (incoming.error !== void 0) merged.error = incoming.error;
1169
- return merged;
1170
727
  }
1171
- function textMergeable(previous, entry) {
1172
- const a = previous.item, b = entry.item;
1173
- if (a.type !== b.type || previous.seqEnd + 1 !== entry.seqStart || previous.turnId !== entry.turnId) return false;
1174
- if (a.type === "reasoning") return true;
1175
- return a.type === "assistant_message" && (b.messageId === void 0 || a.messageId === b.messageId);
1176
- }
1177
- /**
1178
- * Live projection of one agent's timeline, shared by every browser viewing it. Daemon stream
1179
- * events are folded with the daemon's own projection rules, so each event costs O(1) work and
1180
- * reaches browsers as a small upsert/append op. Gaps, unknown identities and reconnects fall
1181
- * back to an incremental `after` fetch, which returns only rows touched since the cursor.
728
+ // src/server/auth.ts
729
+ /** Sliding session lifetime: a device that keeps using the console stays signed in. */
730
+ const SESSION_TTL_MS = 2592e6;
731
+ const TOUCH_INTERVAL_MS = 36e5;
732
+ const TOTP_PERIOD_S = 30;
733
+ const TOTP_DIGITS = 6;
734
+ /** Only clients that know the access token can reach TOTP verification.
735
+ * Code attempts have a persistent server-wide budget across IPs and restarts.
736
+ * Exhausting it doubles the lockout from 15 minutes to at most 24 hours.
1182
737
  */
1183
- var TimelineView = class {
1184
- rows = [];
1185
- bySeqStart = /* @__PURE__ */ new Map();
1186
- identities = /* @__PURE__ */ new Map();
1187
- epoch = "";
1188
- lastSeq = -1;
1189
- hasOlder = false;
1190
- startCursor = null;
1191
- /** True while rows reach back to the first projected row, so unseen identities are new. */
1192
- complete = false;
1193
- state = "loading";
1194
- buffer = [];
1195
- overflowed = false;
1196
- watchers = /* @__PURE__ */ new Set();
1197
- /** seqStart → pending change since the last flush; full means send the whole row. */
1198
- pending = /* @__PURE__ */ new Map();
1199
- pendingReset = false;
1200
- flushTimer;
1201
- retryTimer;
1202
- subscription = null;
1203
- token = 0;
1204
- loads = 0;
1205
- driver;
1206
- agentId;
1207
- constructor(driver, agentId) {
1208
- this.driver = driver;
1209
- this.agentId = agentId;
1210
- }
1211
- get watcherCount() {
1212
- return this.watchers.size;
1213
- }
1214
- start() {
1215
- const token = ++this.token;
1216
- this.state = "loading";
1217
- const subscription = this.driver.subscribeAgentTimeline(this.agentId, (message) => {
1218
- if (token === this.token) this.onMessage(message);
1219
- });
1220
- this.subscription = subscription;
1221
- subscription.ready.then(() => token === this.token ? this.reload() : void 0, () => this.fail(token));
1222
- }
1223
- dispose() {
1224
- this.token++;
1225
- this.state = "disposed";
1226
- clearTimeout(this.flushTimer);
1227
- clearTimeout(this.retryTimer);
1228
- this.watchers.clear();
1229
- const released = this.subscription?.release().catch(() => {}) ?? Promise.resolve();
1230
- this.subscription = null;
1231
- return released;
1232
- }
1233
- watch(watcher) {
1234
- if (this.state === "live" || this.state === "catching-up") {
1235
- this.flush();
1236
- watcher([this.resetOp()]);
1237
- }
1238
- this.watchers.add(watcher);
1239
- return () => this.watchers.delete(watcher);
1240
- }
1241
- onMessage(message) {
1242
- switch (message.type) {
1243
- case "agent_stream": {
1244
- const payload = message.payload;
1245
- if (payload.event.type !== "timeline" || payload.seq === void 0) return;
1246
- if (this.state !== "live") return this.bufferEvent(payload);
1247
- return this.process(payload);
1248
- }
1249
- case "agent.timeline.replacement":
1250
- this.reload();
1251
- return;
1252
- case "agent.timeline.subscription_restored":
1253
- this.state === "live" && this.catchUp();
1254
- return;
1255
- case "agent.timeline.error": return this.fail(this.token);
1256
- }
1257
- }
1258
- bufferEvent(payload) {
1259
- if (this.overflowed) return;
1260
- if (this.buffer.length >= MAX_BUFFER) {
1261
- this.buffer = [];
1262
- this.overflowed = true;
1263
- return;
1264
- }
1265
- this.buffer.push(payload);
1266
- }
1267
- process(payload) {
1268
- const seq = payload.seq;
1269
- if (payload.epoch !== void 0 && payload.epoch !== this.epoch) return void this.reload();
1270
- if (seq <= this.lastSeq) return;
1271
- if (seq > this.lastSeq + 1) {
1272
- this.bufferEvent(payload);
1273
- this.catchUp();
1274
- return;
1275
- }
1276
- if (!this.applyLive(payload)) return void this.catchUp();
1277
- this.lastSeq = seq;
1278
- }
1279
- /** Folds one source event; false when the view cannot decide locally. */
1280
- applyLive(payload) {
1281
- const entry = {
1282
- seqStart: payload.seq,
1283
- seqEnd: payload.seq,
1284
- timestamp: payload.timestamp,
1285
- provider: payload.event.provider ?? "",
1286
- ...payload.event.turnId ? { turnId: payload.event.turnId } : {},
1287
- item: payload.event.item
1288
- };
1289
- const identity = timelineItemIdentity(entry.item);
1290
- if (identity !== null) {
1291
- const existing = this.identities.get(identity);
1292
- if (existing) {
1293
- if (entry.item.type === "tool_call") {
1294
- if (existing.item.type === "tool_call" && existing.turnId === entry.turnId) {
1295
- existing.item = mergeToolCallItems(existing.item, entry.item);
1296
- existing.timestamp = entry.timestamp;
1297
- existing.seqEnd = Math.max(existing.seqEnd, entry.seqEnd);
1298
- this.mark(existing.seqStart, true);
1299
- return true;
1300
- }
1301
- } else if (entry.item.type === "plugin" && existing.item.type === "plugin") {
1302
- Object.assign(existing, {
1303
- ...entry,
1304
- seqStart: existing.seqStart
1305
- });
1306
- this.mark(existing.seqStart, true);
1307
- return true;
1308
- }
1309
- } else if (!this.complete) return false;
1310
- }
1311
- const previous = this.rows.at(-1);
1312
- if (previous && textMergeable(previous, entry)) {
1313
- const text = entry.item.text ?? "";
1314
- previous.item = {
1315
- type: previous.item.type,
1316
- text: (previous.item.text ?? "") + text,
1317
- ...previous.item.type === "assistant_message" && previous.item.messageId ? { messageId: previous.item.messageId } : {}
1318
- };
1319
- previous.timestamp = entry.timestamp;
1320
- previous.seqEnd = entry.seqEnd;
1321
- this.mark(previous.seqStart, false, text);
1322
- return true;
1323
- }
1324
- this.insert(entry);
1325
- return true;
1326
- }
1327
- async reload() {
1328
- const token = this.token;
1329
- const load = ++this.loads;
1330
- this.state = "loading";
1331
- try {
1332
- const page = await this.driver.fetchAgentTimeline(this.agentId, {
1333
- direction: "tail",
1334
- limit: TAIL_LIMIT,
1335
- projection: "projected",
1336
- wholeTurns: true
1337
- });
1338
- if (token !== this.token || load !== this.loads) return;
1339
- this.replaceWith(page);
1340
- this.settle();
1341
- } catch {
1342
- this.fail(token);
1343
- }
1344
- }
1345
- async catchUp() {
1346
- if (this.state === "catching-up" || this.state === "loading") return;
1347
- const token = this.token;
1348
- this.state = "catching-up";
1349
- try {
1350
- for (;;) {
1351
- const page = await this.driver.fetchAgentTimeline(this.agentId, {
1352
- direction: "after",
1353
- cursor: {
1354
- epoch: this.epoch,
1355
- seq: Math.max(0, this.lastSeq)
1356
- },
1357
- limit: CATCH_UP_PAGE,
1358
- projection: "projected"
1359
- });
1360
- if (token !== this.token) return;
1361
- if (page.reset || page.epoch !== this.epoch) {
1362
- this.replaceWith(page);
1363
- break;
1364
- }
1365
- for (const entry of page.entries) this.upsertFetched(entry);
1366
- const end = page.endCursor?.seq ?? (page.hasNewer ? null : page.window.maxSeq);
1367
- if (end === null) break;
1368
- this.lastSeq = Math.max(this.lastSeq, end);
1369
- if (!page.hasNewer) break;
1370
- }
1371
- this.settle();
1372
- } catch {
1373
- this.fail(token);
1374
- }
1375
- }
1376
- /** Back to live: replay what arrived meanwhile, or reload if the buffer overflowed. */
1377
- settle() {
1378
- if (this.overflowed) {
1379
- this.overflowed = false;
1380
- this.buffer = [];
1381
- this.reload();
1382
- return;
1383
- }
1384
- this.state = "live";
1385
- const events = this.buffer;
1386
- this.buffer = [];
1387
- for (let i = 0; i < events.length; i++) {
1388
- if (this.state !== "live") {
1389
- this.buffer = events.slice(i).concat(this.buffer);
1390
- return;
1391
- }
1392
- this.process(events[i]);
1393
- }
1394
- }
1395
- fail(token) {
1396
- if (token !== this.token || this.state === "disposed") return;
1397
- this.state = "failed";
1398
- this.broadcast([{
1399
- type: "error",
1400
- message: "Timeline sync interrupted; retrying"
1401
- }]);
1402
- clearTimeout(this.retryTimer);
1403
- this.retryTimer = setTimeout(() => {
1404
- if (this.state !== "failed" || token !== this.token) return;
1405
- this.subscription?.release().catch(() => {});
1406
- this.start();
1407
- }, RETRY_MS);
1408
- this.retryTimer.unref?.();
1409
- }
1410
- replaceWith(page) {
1411
- this.rows = [];
1412
- this.bySeqStart.clear();
1413
- this.identities.clear();
1414
- this.pending.clear();
1415
- this.epoch = page.epoch;
1416
- this.lastSeq = page.window.maxSeq;
1417
- this.hasOlder = page.hasOlder;
1418
- this.startCursor = page.startCursor;
1419
- this.complete = !page.hasOlder;
1420
- for (const entry of page.entries) this.upsertFetched(entry, false);
1421
- this.buffer = this.buffer.filter((e) => e.epoch === this.epoch && e.seq > this.lastSeq);
1422
- this.pending.clear();
1423
- this.pendingReset = true;
1424
- this.scheduleFlush();
1425
- }
1426
- upsertFetched(entry, notify = true) {
1427
- const row = {
1428
- seqStart: entry.seqStart,
1429
- seqEnd: entry.seqEnd,
1430
- timestamp: entry.timestamp,
1431
- provider: entry.provider,
1432
- ...entry.turnId ? { turnId: entry.turnId } : {},
1433
- item: entry.item
1434
- };
1435
- const existing = this.bySeqStart.get(row.seqStart);
1436
- if (existing) {
1437
- Object.assign(existing, row);
1438
- if (!row.turnId) delete existing.turnId;
1439
- this.noteIdentity(existing);
1440
- if (notify) this.mark(existing.seqStart, true);
1441
- return;
1442
- }
1443
- this.insert(row, notify);
1444
- }
1445
- insert(row, notify = true) {
1446
- let index = this.rows.length;
1447
- if (index && this.rows[index - 1].seqStart > row.seqStart) {
1448
- let low = 0, high = index;
1449
- while (low < high) {
1450
- const middle = low + high >>> 1;
1451
- if (this.rows[middle].seqStart < row.seqStart) low = middle + 1;
1452
- else high = middle;
1453
- }
1454
- index = low;
1455
- }
1456
- if (index === this.rows.length) this.rows.push(row);
1457
- else this.rows.splice(index, 0, row);
1458
- this.bySeqStart.set(row.seqStart, row);
1459
- this.noteIdentity(row);
1460
- if (notify) this.mark(row.seqStart, true);
1461
- if (this.rows.length > MAX_ROWS) this.trim();
1462
- }
1463
- /** Like the daemon, an identity resolves to its most recent row. */
1464
- noteIdentity(row) {
1465
- const identity = timelineItemIdentity(row.item);
1466
- if (identity === null) return;
1467
- const current = this.identities.get(identity);
1468
- if (!current || current.seqStart <= row.seqStart) this.identities.set(identity, row);
1469
- }
1470
- trim() {
1471
- const removed = this.rows.splice(0, this.rows.length - KEEP_ROWS);
1472
- for (const row of removed) {
1473
- this.bySeqStart.delete(row.seqStart);
1474
- this.pending.delete(row.seqStart);
1475
- const identity = timelineItemIdentity(row.item);
1476
- if (identity !== null && this.identities.get(identity) === row) this.identities.delete(identity);
1477
- }
1478
- this.complete = false;
1479
- this.hasOlder = true;
1480
- this.startCursor = {
1481
- epoch: this.epoch,
1482
- seq: this.rows[0].seqStart
1483
- };
1484
- }
1485
- mark(seqStart, full, text = "") {
1486
- if (this.pendingReset) return;
1487
- const pending = this.pending.get(seqStart);
1488
- if (!pending) this.pending.set(seqStart, {
1489
- full,
1490
- text: full ? "" : text
1491
- });
1492
- else if (full) {
1493
- pending.full = true;
1494
- pending.text = "";
1495
- } else if (!pending.full) pending.text += text;
1496
- this.scheduleFlush();
1497
- }
1498
- scheduleFlush() {
1499
- if (this.flushTimer || !this.watchers.size) return;
1500
- this.flushTimer = setTimeout(() => this.flush(), FLUSH_MS);
1501
- }
1502
- flush() {
1503
- clearTimeout(this.flushTimer);
1504
- this.flushTimer = void 0;
1505
- if (this.pendingReset) {
1506
- this.pendingReset = false;
1507
- this.pending.clear();
1508
- return this.broadcast([this.resetOp()]);
1509
- }
1510
- if (!this.pending.size) return;
1511
- const ops = [];
1512
- for (const [seqStart, change] of this.pending) {
1513
- const row = this.bySeqStart.get(seqStart);
1514
- if (!row) continue;
1515
- ops.push(change.full ? {
1516
- type: "upsert",
1517
- row: { ...row }
1518
- } : {
1519
- type: "append",
1520
- seqStart,
1521
- seqEnd: row.seqEnd,
1522
- timestamp: row.timestamp,
1523
- text: change.text
1524
- });
1525
- }
1526
- this.pending.clear();
1527
- if (ops.length) this.broadcast(ops);
1528
- }
1529
- resetOp() {
1530
- const start = Math.max(0, this.rows.length - RESET_ROWS);
1531
- const rows = this.rows.slice(start).map((row) => ({ ...row }));
1532
- return {
1533
- type: "reset",
1534
- epoch: this.epoch,
1535
- rows,
1536
- hasOlder: this.hasOlder || start > 0,
1537
- startCursor: start > 0 ? {
1538
- epoch: this.epoch,
1539
- seq: rows[0].seqStart
1540
- } : this.startCursor
1541
- };
1542
- }
1543
- broadcast(ops) {
1544
- for (const watcher of this.watchers) watcher(ops);
1545
- }
1546
- };
1547
- // src/server/hosts.ts
1548
- var UnknownHostError = class extends Error {
1549
- constructor() {
1550
- super("Unknown host");
1551
- }
1552
- };
1553
- /** Idle grace before an unwatched timeline releases its daemon subscription. */
1554
- const TIMELINE_GRACE_MS = 3e4;
1555
- var Hosts = class {
1556
- agents = new VersionedCollection();
1557
- workspaces = new VersionedCollection();
1558
- clients = /* @__PURE__ */ new Map();
1559
- diagnostics = /* @__PURE__ */ new Map();
1560
- labels = /* @__PURE__ */ new Map();
1561
- timelines = /* @__PURE__ */ new Map();
1562
- agentListeners = /* @__PURE__ */ new Set();
1563
- hostListeners = /* @__PURE__ */ new Set();
1564
- transitionListeners = /* @__PURE__ */ new Set();
1565
- add(host) {
1566
- const driver = createHostClient(host.connection, {
1567
- clientId: `litepaseo-${host.id}`,
1568
- clientType: "cli",
1569
- connectTimeoutMs: 5e3,
1570
- reconnect: { enabled: true },
1571
- logger: {
1572
- debug() {},
1573
- info() {},
1574
- warn() {},
1575
- error() {}
1576
- }
1577
- });
1578
- this.labels.set(host.id, host.label);
1579
- this.attach(host.id, driver, createPaseoApi(driver));
1580
- driver.connect().catch((error) => {
1581
- if (this.clients.get(host.id)?.driver !== driver) return;
1582
- this.noteFailure(host.id, error);
1583
- this.emit(this.hostListeners);
1584
- });
1585
- }
1586
- /** Wires a connected-or-connecting driver; separate from `add` so tests can inject doubles. */
1587
- attach(hostId, driver, api) {
1588
- const directory = new HostDirectory(hostId, driver, this.agents, () => this.emit(this.agentListeners), (previous, next) => {
1589
- for (const listener of this.transitionListeners) listener(previous, next);
1590
- });
1591
- const workspaces = new HostWorkspaces(hostId, driver, this.workspaces, () => this.emit(this.agentListeners));
1592
- const update = (state) => {
1593
- const previous = this.diagnostics.get(hostId) ?? {};
1594
- if (state.status === "connected") this.diagnostics.set(hostId, { lastConnectedAt: (/* @__PURE__ */ new Date()).toISOString() });
1595
- else if (state.status === "connecting") this.diagnostics.set(hostId, {
1596
- ...previous,
1597
- nextRetryAt: void 0,
1598
- attempt: state.attempt
1599
- });
1600
- else if (state.status === "disconnected") {
1601
- this.noteFailure(hostId, state);
1602
- const retry = state.nextRetryAt && Date.parse(state.nextRetryAt);
1603
- this.diagnostics.set(hostId, {
1604
- ...this.diagnostics.get(hostId),
1605
- nextRetryAt: retry && Number.isFinite(retry) ? new Date(retry).toISOString() : void 0
1606
- });
1607
- }
1608
- this.emit(this.hostListeners);
1609
- };
1610
- const stopStatus = driver.subscribeConnectionStatus(update);
1611
- update(driver.getConnectionState());
1612
- this.clients.set(hostId, {
1613
- driver,
1614
- api,
1615
- directory,
1616
- workspaces,
1617
- stopStatus
1618
- });
1619
- directory.start();
1620
- if (driver.observeWorkspaces) workspaces.start();
1621
- this.emit(this.hostListeners);
1622
- }
1623
- get(id) {
1624
- const c = this.clients.get(id);
1625
- if (!c) throw new UnknownHostError();
1626
- return c;
1627
- }
1628
- diagnostic(id) {
1629
- return this.diagnostics.get(id);
1630
- }
1631
- noteFailure(id, failure) {
1632
- const error = connectionProblem(failure);
1633
- const previous = this.diagnostics.get(id) ?? {};
1634
- if (previous.error?.code !== error.code) console.warn(JSON.stringify({
1635
- event: "host_connection_failed",
1636
- hostId: id,
1637
- code: error.code
1638
- }));
1639
- this.diagnostics.set(id, {
1640
- ...previous,
1641
- error
1642
- });
1643
- }
1644
- state(id) {
1645
- return this.clients.get(id)?.driver.getConnectionState().status ?? "offline";
1646
- }
1647
- async remove(id) {
1648
- const c = this.clients.get(id);
1649
- this.clients.delete(id);
1650
- const releases = [];
1651
- for (const [key, entry] of this.timelines) if (entry.hostId === id) {
1652
- clearTimeout(entry.idle);
1653
- releases.push(entry.view.dispose());
1654
- this.timelines.delete(key);
1655
- }
1656
- if (c) {
1657
- await Promise.all([
1658
- ...releases,
1659
- c.directory.dispose(),
1660
- c.workspaces.dispose()
1661
- ]);
1662
- c.stopStatus();
1663
- await c.api.dispose();
1664
- await c.driver.close();
1665
- }
1666
- this.diagnostics.delete(id);
1667
- this.labels.delete(id);
1668
- this.emit(this.hostListeners);
1669
- }
1670
- async close() {
1671
- await Promise.allSettled([...this.clients.keys()].map((id) => this.remove(id)));
1672
- }
1673
- onAgentsChanged(listener) {
1674
- this.agentListeners.add(listener);
1675
- return () => this.agentListeners.delete(listener);
1676
- }
1677
- /** Per-agent summary changes, for event detection (notifications). */
1678
- onTransition(listener) {
1679
- this.transitionListeners.add(listener);
1680
- return () => this.transitionListeners.delete(listener);
1681
- }
1682
- /** Whether some browser is looking at this conversation right now. */
1683
- isViewing(key) {
1684
- return (this.timelines.get(key)?.view.watcherCount ?? 0) > 0;
1685
- }
1686
- label(hostId) {
1687
- return this.labels.get(hostId) ?? "";
1688
- }
1689
- setLabel(hostId, label) {
1690
- this.labels.set(hostId, label);
1691
- }
1692
- onHostsChanged(listener) {
1693
- this.hostListeners.add(listener);
1694
- return () => this.hostListeners.delete(listener);
1695
- }
1696
- /** Shares one live timeline per agent across all watching browsers. */
1697
- watchTimeline(hostId, agentId, watcher) {
1698
- const client = this.get(hostId);
1699
- const key = `${hostId}:${agentId}`;
1700
- let entry = this.timelines.get(key);
1701
- if (!entry) {
1702
- const view = new TimelineView(client.driver, agentId);
1703
- entry = {
1704
- view,
1705
- hostId
1706
- };
1707
- this.timelines.set(key, entry);
1708
- view.start();
1709
- }
1710
- clearTimeout(entry.idle);
1711
- entry.idle = void 0;
1712
- const stop = entry.view.watch(watcher);
1713
- const current = entry;
1714
- return () => {
1715
- stop();
1716
- if (current.view.watcherCount || this.timelines.get(key) !== current) return;
1717
- current.idle = setTimeout(() => {
1718
- if (current.view.watcherCount || this.timelines.get(key) !== current) return;
1719
- current.view.dispose();
1720
- this.timelines.delete(key);
1721
- }, TIMELINE_GRACE_MS);
1722
- current.idle.unref?.();
1723
- };
1724
- }
1725
- emit(listeners) {
1726
- for (const listener of listeners) listener();
1727
- }
1728
- };
1729
- // src/server/sse.ts
1730
- const HEARTBEAT_MS = 2e4;
1731
- /** Server-sent events over a plain fetch response, so the bearer header still authenticates. */
1732
- function eventStream(signal, open, valid = () => true) {
1733
- const encoder = new TextEncoder();
1734
- let cleanup;
1735
- const stop = () => {
1736
- cleanup?.();
1737
- cleanup = void 0;
1738
- };
1739
- const body = new ReadableStream({
1740
- start(controller) {
1741
- const write = (text) => {
1742
- try {
1743
- controller.enqueue(encoder.encode(text));
1744
- } catch {
1745
- stop();
1746
- }
1747
- };
1748
- const heartbeat = setInterval(() => {
1749
- if (valid()) return write(": ping\n\n");
1750
- stop();
1751
- try {
1752
- controller.close();
1753
- } catch {}
1754
- }, HEARTBEAT_MS);
1755
- const close = open((data) => write(`data: ${JSON.stringify(data)}\n\n`));
1756
- cleanup = () => {
1757
- clearInterval(heartbeat);
1758
- close();
1759
- };
1760
- signal.addEventListener("abort", () => {
1761
- stop();
1762
- try {
1763
- controller.close();
1764
- } catch {}
1765
- });
1766
- },
1767
- cancel: stop
1768
- });
1769
- return new Response(body, { headers: {
1770
- "Content-Type": "text/event-stream",
1771
- "Cache-Control": "no-cache, no-transform",
1772
- "X-Accel-Buffering": "no"
1773
- } });
1774
- }
1775
- // src/server/media.ts
1776
- /** Raster images only: an SVG opened directly could run script on this origin. */
1777
- const IMAGE_MIME = {
1778
- png: "image/png",
1779
- jpg: "image/jpeg",
1780
- jpeg: "image/jpeg",
1781
- webp: "image/webp",
1782
- gif: "image/gif",
1783
- bmp: "image/bmp",
1784
- avif: "image/avif"
1785
- };
1786
- const MAX_IMAGE_BYTES = 16777216;
1787
- const extension = (path) => /\.([a-z0-9]+)$/i.exec(path)?.[1]?.toLowerCase() ?? "";
1788
- const imageMime = (path) => IMAGE_MIME[extension(path)] ?? null;
1789
- /** True when the daemon runs on this machine (loopback TCP/WebSocket or a local socket). */
1790
- function isLocalConnection(connection) {
1791
- try {
1792
- const target = parseHostTarget(connection);
1793
- if (target.kind !== "socket") return false;
1794
- if (target.socketPath) return true;
1795
- const host = new URL(target.url ?? "").hostname.replace(/^\[|\]$/g, "");
1796
- return host === "localhost" || host === "::1" || /^127\./.test(host);
1797
- } catch {
1798
- return false;
1799
- }
1800
- }
1801
- /**
1802
- * Images a provider returned inline (screenshots, `read` of a PNG) are written by the daemon to
1803
- * `<tmp>/paseo-attachments-XXXXXX/<sha256>.<ext>` and referenced from the message as file:// URLs.
1804
- * The daemon's file API is confined to the workspace, so these are read from disk, and only when
1805
- * the daemon shares this machine. The name pattern admits nothing but those materialized files.
1806
- */
1807
- function isMaterializedImagePath(path) {
1808
- if (!isAbsolute(path) || normalize(path) !== path || !imageMime(path)) return false;
1809
- const directory = dirname(path);
1810
- return /^[a-f0-9]{64}\.[a-z0-9]+$/.test(basename(path)) && /^paseo-attachments-[A-Za-z0-9_-]{1,32}$/.test(basename(directory)) && [tmpdir(), "/tmp"].includes(dirname(directory));
1811
- }
1812
- async function readMaterializedImage(path) {
1813
- if (!isMaterializedImagePath(path)) return null;
1814
- try {
1815
- const stats = await lstat(path);
1816
- if (!stats.isFile() || stats.size > 16777216) return null;
1817
- if (!isMaterializedImagePath(await realpath(path))) return null;
1818
- return await readFile(path);
1819
- } catch {
1820
- return null;
1821
- }
1822
- }
1823
- /** Small LRU for project icons: a sidebar asks for each project once per page load. */
1824
- var IconCache = class {
1825
- entries = /* @__PURE__ */ new Map();
1826
- limit;
1827
- ttlMs;
1828
- constructor(limit = 256, ttlMs = 6e5) {
1829
- this.limit = limit;
1830
- this.ttlMs = ttlMs;
1831
- }
1832
- get(key) {
1833
- const entry = this.entries.get(key);
1834
- if (!entry) return void 0;
1835
- if (Date.now() - entry.at > this.ttlMs) {
1836
- this.entries.delete(key);
1837
- return;
1838
- }
1839
- this.entries.delete(key);
1840
- this.entries.set(key, entry);
1841
- return entry.icon;
1842
- }
1843
- set(key, icon) {
1844
- this.entries.delete(key);
1845
- this.entries.set(key, {
1846
- at: Date.now(),
1847
- icon
1848
- });
1849
- if (this.entries.size > this.limit) this.entries.delete(this.entries.keys().next().value);
1850
- }
1851
- };
1852
- // src/server/workspace-routes.ts
1853
- /** Text files larger than this open truncated: the viewer is for reading, not for dumps. */
1854
- const MAX_TEXT_BYTES = 1048576;
1855
- const MAX_ENTRIES = 2e3;
1856
- /** Terminal output is coalesced into one event per frame-ish interval. */
1857
- const TERMINAL_FLUSH_MS = 16;
1858
- const path = z.string().min(1).max(4096).refine((p) => !p.includes("\0"));
1859
- /**
1860
- * The workspace side panel (files, terminals) and schedules. Every call goes to the host's
1861
- * daemon, which confines file access to the workspace and owns the terminals; nothing here
1862
- * keeps state beyond an open terminal stream.
1863
- */
1864
- function registerWorkspaceRoutes(app, hosts, store, valid) {
1865
- app.get("/api/hosts/:host/fs/list", async (c) => {
1866
- const cwd = path.parse(c.req.query("cwd"));
1867
- const dir = c.req.query("path") || ".";
1868
- const { driver } = hosts.get(c.req.param("host"));
1869
- try {
1870
- const result = await driver.listDirectory(cwd, dir);
1871
- const entries = (result.entries ?? []).map((e) => ({
1872
- name: e.name,
1873
- path: e.path,
1874
- kind: e.kind,
1875
- size: e.size
1876
- })).sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name, void 0, { numeric: true }) : a.kind === "directory" ? -1 : 1);
1877
- return c.json({
1878
- path: result.path,
1879
- entries: entries.slice(0, MAX_ENTRIES),
1880
- truncated: entries.length > MAX_ENTRIES
1881
- });
1882
- } catch (error) {
1883
- return c.json({ error: error.message || "Directory unavailable" }, 404);
1884
- }
1885
- });
1886
- app.get("/api/hosts/:host/fs/read", async (c) => {
1887
- const cwd = path.parse(c.req.query("cwd"));
1888
- const file = path.parse(c.req.query("path"));
1889
- const { driver } = hosts.get(c.req.param("host"));
1890
- try {
1891
- const result = await driver.readFile(cwd, file, void 0, 1048577);
1892
- const text = result.kind === "text" ? new TextDecoder().decode(result.bytes.subarray(0, MAX_TEXT_BYTES)) : void 0;
1893
- return c.json({
1894
- path: result.path,
1895
- kind: result.kind,
1896
- mime: result.mime,
1897
- size: result.size,
1898
- modifiedAt: result.modifiedAt,
1899
- ...text !== void 0 ? {
1900
- text,
1901
- truncated: result.size > MAX_TEXT_BYTES
1902
- } : {}
1903
- });
1904
- } catch (error) {
1905
- return c.json({ error: error.message || "File unavailable" }, 404);
1906
- }
1907
- });
1908
- app.get("/api/hosts/:host/fs/raw", async (c) => {
1909
- const cwd = path.parse(c.req.query("cwd"));
1910
- const file = path.parse(c.req.query("path"));
1911
- const mime = imageMime(file);
1912
- if (!mime) return c.json({ error: "Only images can be opened raw" }, 415);
1913
- const { driver } = hosts.get(c.req.param("host"));
1914
- try {
1915
- const result = await driver.readFile(cwd, file, void 0, MAX_IMAGE_BYTES);
1916
- return c.body(result.bytes, 200, {
1917
- "Content-Type": mime,
1918
- "Cache-Control": "private, max-age=60"
1919
- });
1920
- } catch {
1921
- return c.json({ error: "Image unavailable" }, 404);
1922
- }
1923
- });
1924
- app.get("/api/hosts/:host/terminals", async (c) => {
1925
- const cwd = path.parse(c.req.query("cwd"));
1926
- const result = await hosts.get(c.req.param("host")).driver.listTerminals(cwd);
1927
- return c.json((result.terminals ?? []).map((t) => ({
1928
- id: t.id,
1929
- name: t.name,
1930
- title: t.title ?? null,
1931
- cwd: t.cwd
1932
- })));
1933
- });
1934
- app.post("/api/hosts/:host/terminals", async (c) => {
1935
- const input = z.object({
1936
- cwd: path,
1937
- rows: z.number().int().min(4).max(500),
1938
- cols: z.number().int().min(10).max(1e3),
1939
- name: z.string().max(80).optional()
1940
- }).parse(await c.req.json());
1941
- const result = await hosts.get(c.req.param("host")).driver.createTerminal(input.cwd, input.name, void 0, { size: {
1942
- rows: input.rows,
1943
- cols: input.cols
1944
- } });
1945
- if (!result.terminal) return c.json({ error: result.error ?? "Could not open a terminal" }, 502);
1946
- return c.json({
1947
- id: result.terminal.id,
1948
- name: result.terminal.name,
1949
- title: result.terminal.title ?? null,
1950
- cwd: result.terminal.cwd
1951
- }, 201);
1952
- });
1953
- app.delete("/api/hosts/:host/terminals/:id", async (c) => {
1954
- await hosts.get(c.req.param("host")).driver.killTerminal(c.req.param("id"));
1955
- return c.json({ ok: true });
1956
- });
1957
- app.post("/api/hosts/:host/terminals/:id/input", async (c) => {
1958
- const input = z.union([z.object({ data: z.string().min(1).max(65536) }), z.object({
1959
- rows: z.number().int().min(4).max(500),
1960
- cols: z.number().int().min(10).max(1e3)
1961
- })]).parse(await c.req.json());
1962
- const { driver } = hosts.get(c.req.param("host"));
1963
- driver.sendTerminalInput(c.req.param("id"), "data" in input ? {
1964
- type: "input",
1965
- data: input.data
1966
- } : {
1967
- type: "resize",
1968
- rows: input.rows,
1969
- cols: input.cols
1970
- });
1971
- return c.json({ ok: true });
1972
- });
1973
- /** Live output as SSE: a full replay first (scrollback), then coalesced output chunks. */
1974
- app.get("/api/hosts/:host/terminals/:id/stream", (c) => {
1975
- const { driver } = hosts.get(c.req.param("host"));
1976
- const id = c.req.param("id");
1977
- const rows = Number(c.req.query("rows")) || 24, cols = Number(c.req.query("cols")) || 80;
1978
- return eventStream(c.req.raw.signal, (send) => {
1979
- let pending = [];
1980
- let timer;
1981
- const flush = () => {
1982
- timer = void 0;
1983
- if (!pending.length) return;
1984
- send({
1985
- t: "o",
1986
- d: Buffer.concat(pending).toString("base64")
1987
- });
1988
- pending = [];
1989
- };
1990
- const push = (bytes) => {
1991
- pending.push(bytes);
1992
- timer ??= setTimeout(flush, TERMINAL_FLUSH_MS);
1993
- };
1994
- const subscription = driver.observeTerminal(id, (event) => {
1995
- if (event.type === "output") push(event.data);
1996
- else if (event.replay.type === "begin") {
1997
- pending = [];
1998
- send({ t: "reset" });
1999
- } else if (event.replay.type === "data") push(event.replay.data);
2000
- }, { restore: {
2001
- mode: "full-snapshot",
2002
- scrollbackLines: 2e3,
2003
- size: {
2004
- rows,
2005
- cols
2006
- }
2007
- } });
2008
- const stop = subscription.subscribe({
2009
- snapshot: () => {},
2010
- update: (message) => {
2011
- if (message.type === "terminal_stream_exit") send({ t: "exit" });
2012
- },
2013
- error: () => send({ t: "exit" })
2014
- });
2015
- subscription.ready.catch(() => send({ t: "exit" }));
2016
- return () => {
2017
- clearTimeout(timer);
2018
- stop();
2019
- subscription.release().catch(() => {});
2020
- };
2021
- }, valid(c));
2022
- });
2023
- /** Every connected host's schedules; a host that fails reports its error instead. */
2024
- app.get("/api/schedules", async (c) => {
2025
- const results = await Promise.all(store.hosts().map(async (h) => {
2026
- try {
2027
- if (hosts.state(h.id) !== "connected") return {
2028
- hostId: h.id,
2029
- schedules: [],
2030
- error: "Host is offline"
2031
- };
2032
- const list = await hosts.get(h.id).driver.scheduleList();
2033
- return {
2034
- hostId: h.id,
2035
- schedules: list.schedules ?? [],
2036
- error: list.error ?? null
2037
- };
2038
- } catch (error) {
2039
- return {
2040
- hostId: h.id,
2041
- schedules: [],
2042
- error: error.message || "Schedules unavailable"
2043
- };
2044
- }
2045
- }));
2046
- return c.json(results);
2047
- });
2048
- app.post("/api/hosts/:host/schedules", async (c) => {
2049
- const input = z.object({
2050
- name: z.string().trim().max(120).optional(),
2051
- prompt: z.string().trim().min(1).max(2e4),
2052
- cron: z.string().trim().min(9).max(120),
2053
- timezone: z.string().max(80).optional(),
2054
- cwd: path,
2055
- provider: z.string().min(1).max(200),
2056
- model: z.string().min(1).max(300).optional(),
2057
- thinkingOptionId: z.string().min(1).max(200).optional(),
2058
- archiveOnFinish: z.boolean().default(true),
2059
- runOnCreate: z.boolean().default(false)
2060
- }).parse(await c.req.json());
2061
- const result = await hosts.get(c.req.param("host")).driver.scheduleCreate({
2062
- prompt: input.prompt,
2063
- name: input.name || null,
2064
- cadence: {
2065
- type: "cron",
2066
- expression: input.cron,
2067
- ...input.timezone ? { timezone: input.timezone } : {}
2068
- },
2069
- target: {
2070
- type: "new-agent",
2071
- config: {
2072
- provider: input.provider,
2073
- cwd: input.cwd,
2074
- ...input.model ? { model: input.model } : {},
2075
- ...input.thinkingOptionId ? { thinkingOptionId: input.thinkingOptionId } : {},
2076
- archiveOnFinish: input.archiveOnFinish,
2077
- isolation: "local",
2078
- title: input.name || null
2079
- }
2080
- },
2081
- runOnCreate: input.runOnCreate
2082
- });
2083
- if (result.error) return c.json({ error: result.error }, 400);
2084
- return c.json(result.schedule, 201);
2085
- });
2086
- app.patch("/api/hosts/:host/schedules/:id", async (c) => {
2087
- const input = z.object({
2088
- name: z.string().trim().max(120).nullable().optional(),
2089
- prompt: z.string().trim().min(1).max(2e4).optional(),
2090
- cron: z.string().trim().min(9).max(120).optional(),
2091
- timezone: z.string().max(80).optional(),
2092
- cwd: path.optional(),
2093
- provider: z.string().min(1).max(200).optional(),
2094
- model: z.string().min(1).max(300).nullable().optional(),
2095
- archiveOnFinish: z.boolean().optional()
2096
- }).parse(await c.req.json());
2097
- const agentConfig = {
2098
- ...input.provider ? { provider: input.provider } : {},
2099
- ...input.model !== void 0 ? { model: input.model } : {},
2100
- ...input.cwd ? { cwd: input.cwd } : {},
2101
- ...input.archiveOnFinish !== void 0 ? { archiveOnFinish: input.archiveOnFinish } : {}
2102
- };
2103
- const result = await hosts.get(c.req.param("host")).driver.scheduleUpdate({
2104
- id: c.req.param("id"),
2105
- ...input.name !== void 0 ? { name: input.name || null } : {},
2106
- ...input.prompt ? { prompt: input.prompt } : {},
2107
- ...input.cron ? { cadence: {
2108
- type: "cron",
2109
- expression: input.cron,
2110
- ...input.timezone ? { timezone: input.timezone } : {}
2111
- } } : {},
2112
- ...Object.keys(agentConfig).length ? { newAgentConfig: agentConfig } : {}
2113
- });
2114
- if (result?.error) return c.json({ error: result.error }, 400);
2115
- return c.json(result?.schedule ?? { ok: true });
2116
- });
2117
- const action = (name) => async (c) => {
2118
- const { driver } = hosts.get(c.req.param("host"));
2119
- const options = { id: c.req.param("id") };
2120
- const result = name === "pause" ? await driver.schedulePause(options) : name === "resume" ? await driver.scheduleResume(options) : name === "run" ? await driver.scheduleRunOnce(options) : name === "delete" ? await driver.scheduleDelete(options) : await driver.scheduleLogs(options);
2121
- if (result?.error) return c.json({ error: result.error }, 400);
2122
- return c.json(name === "logs" ? { runs: (result.runs ?? []).slice(-50).reverse() } : { ok: true });
2123
- };
2124
- app.post("/api/hosts/:host/schedules/:id/pause", action("pause"));
2125
- app.post("/api/hosts/:host/schedules/:id/resume", action("resume"));
2126
- app.post("/api/hosts/:host/schedules/:id/run", action("run"));
2127
- app.delete("/api/hosts/:host/schedules/:id", action("delete"));
2128
- app.get("/api/hosts/:host/schedules/:id/logs", action("logs"));
2129
- }
2130
- // src/server/attachments.ts
2131
- const MAX_FILE_BYTES = 8388608;
2132
- const MAX_TOTAL = 67108864;
2133
- const TTL = 12e5;
2134
- const IMAGE_TYPES = /* @__PURE__ */ new Set([
2135
- "image/png",
2136
- "image/jpeg",
2137
- "image/webp",
2138
- "image/gif"
2139
- ]);
2140
- const MAX_FILES = 256;
2141
- var Attachments = class {
2142
- /** Insertion order is expiry order (fixed TTL), so pruning stops at the first live entry. */
2143
- entries = /* @__PURE__ */ new Map();
2144
- totalBytes = 0;
2145
- owners = /* @__PURE__ */ new Map();
2146
- timer = setInterval(() => this.prune(), 6e4);
2147
- constructor() {
2148
- this.timer.unref();
2149
- }
2150
- close() {
2151
- clearInterval(this.timer);
2152
- this.entries.clear();
2153
- this.owners.clear();
2154
- this.totalBytes = 0;
2155
- }
2156
- delete(id) {
2157
- const entry = this.entries.get(id);
2158
- if (!entry) return;
2159
- this.entries.delete(id);
2160
- this.totalBytes -= entry.bytes.length;
2161
- const own = this.owners.get(entry.owner);
2162
- own.bytes -= entry.bytes.length;
2163
- if (!--own.files) this.owners.delete(entry.owner);
2164
- }
2165
- /** O(expired entries). */
2166
- prune(now = Date.now()) {
2167
- for (const [id, entry] of this.entries) {
2168
- if (entry.expires > now) break;
2169
- this.delete(id);
2170
- }
2171
- }
2172
- clearOwner(owner) {
2173
- if (!this.owners.has(owner)) return;
2174
- for (const [id, entry] of this.entries) if (entry.owner === owner) this.delete(id);
2175
- }
2176
- put(owner, host, agent, name, mime, bytes) {
2177
- this.prune();
2178
- if (!name || name.length > 200 || /[\x00-\x1f/\\]/.test(name)) throw new Error("Use a file name without path separators.");
2179
- if (!bytes.length || bytes.length > 8388608) throw new Error("Files must be between 1 byte and 8 MiB.");
2180
- const own = this.owners.get(owner) ?? {
2181
- bytes: 0,
2182
- files: 0
2183
- };
2184
- if (this.totalBytes + bytes.length > MAX_TOTAL || own.bytes + bytes.length > 25165824 || own.files >= 16 || this.entries.size >= MAX_FILES) throw new Error("Attachment staging is full. Remove files or wait for them to expire.");
2185
- if (IMAGE_TYPES.has(mime)) {
2186
- if (!(mime === "image/png" ? bytes.subarray(0, 8).equals(Buffer.from([
2187
- 137,
2188
- 80,
2189
- 78,
2190
- 71,
2191
- 13,
2192
- 10,
2193
- 26,
2194
- 10
2195
- ])) : mime === "image/jpeg" ? bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255 : mime === "image/gif" ? /^GIF8[79]a/.test(bytes.subarray(0, 6).toString()) : bytes.subarray(0, 4).toString() === "RIFF" && bytes.subarray(8, 12).toString() === "WEBP")) throw new Error("Image content does not match its file type.");
2196
- }
2197
- const entry = {
2198
- id: randomUUID(),
2199
- owner,
2200
- host,
2201
- agent,
2202
- name,
2203
- mime,
2204
- bytes,
2205
- expires: Date.now() + TTL
2206
- };
2207
- this.entries.set(entry.id, entry);
2208
- this.totalBytes += bytes.length;
2209
- this.owners.set(owner, {
2210
- bytes: own.bytes + bytes.length,
2211
- files: own.files + 1
2212
- });
2213
- return {
2214
- id: entry.id,
2215
- name,
2216
- mimeType: mime,
2217
- size: bytes.length,
2218
- expires: entry.expires
2219
- };
2220
- }
2221
- get(id, owner, host, agent) {
2222
- this.prune();
2223
- const entry = this.entries.get(id);
2224
- if (entry && entry.expires <= Date.now()) this.delete(id);
2225
- if (!entry || entry.expires <= Date.now() || entry.owner !== owner || entry.host !== host || entry.agent !== agent) throw new Error("Attachment expired or belongs to another session. Select it again.");
2226
- return entry;
2227
- }
2228
- remove(id, owner, host, agent) {
2229
- this.get(id, owner, host, agent);
2230
- this.delete(id);
2231
- }
2232
- async capabilities(hosts, host, agent) {
2233
- const client = hosts.get(host);
2234
- let facts = client.directory.facts(agent);
2235
- if (!facts) {
2236
- const ref = client.api.agents.ref(agent);
2237
- await ref.refresh();
2238
- facts = {
2239
- provider: ref.current()?.provider,
2240
- capabilities: ref.capabilities
2241
- };
2242
- }
2243
- const provider = facts.provider ?? "";
2244
- return {
2245
- images: [
2246
- "codex",
2247
- "claude",
2248
- "pi"
2249
- ].includes(provider) && facts.capabilities?.supportsImages !== false,
2250
- files: facts.capabilities?.supportsToolInvocations === true,
2251
- maxBytes: MAX_FILE_BYTES,
2252
- note: "Images require a vision-capable model. Other files are uploaded to the daemon for the agent to read with its tools."
2253
- };
2254
- }
2255
- async prepare(hosts, owner, host, agent, ids) {
2256
- const entries = ids.map((id) => this.get(id, owner, host, agent));
2257
- if (!entries.length) return {
2258
- images: [],
2259
- attachments: []
2260
- };
2261
- const caps = await this.capabilities(hosts, host, agent).catch(() => {
2262
- throw new Error("Could not verify attachment support. Reconnect the host and retry.");
2263
- });
2264
- const images = [], attachments = [];
2265
- for (const entry of entries) if (IMAGE_TYPES.has(entry.mime)) {
2266
- if (!caps.images) throw new Error("This provider does not support image attachments.");
2267
- images.push({
2268
- data: entry.bytes.toString("base64"),
2269
- mimeType: entry.mime
2270
- });
2271
- } else {
2272
- if (!caps.files) throw new Error("This agent cannot read uploaded files.");
2273
- if (!entry.remote) {
2274
- const uploaded = await hosts.get(host).driver.uploadFile({
2275
- fileName: entry.name,
2276
- mimeType: entry.mime,
2277
- bytes: entry.bytes
2278
- }).catch(() => {
2279
- throw new Error("Daemon file upload failed. Retry the upload before sending.");
2280
- });
2281
- if (uploaded.error || !uploaded.file) throw new Error("Daemon file upload failed. Retry the upload before sending.");
2282
- entry.remote = uploaded.file;
2283
- }
2284
- attachments.push(entry.remote);
2285
- }
2286
- return {
2287
- images,
2288
- attachments
2289
- };
2290
- }
2291
- consumed(ids) {
2292
- for (const id of ids) this.delete(id);
2293
- }
2294
- };
2295
- // src/server/message-status.ts
2296
- /** Positive evidence only. Missing, rewound, or out-of-window messages remain uncertain. */
2297
- async function confirmedMessages(driver, agentId, ids, maxPages = 5) {
2298
- const wanted = new Set(ids), confirmed = /* @__PURE__ */ new Set();
2299
- let cursor = null;
2300
- const seen = /* @__PURE__ */ new Set();
2301
- for (let pageNumber = 0; pageNumber < maxPages && confirmed.size < wanted.size; pageNumber++) {
2302
- const page = await driver.fetchAgentTimeline(agentId, {
2303
- direction: cursor ? "before" : "tail",
2304
- ...cursor ? { cursor } : {},
2305
- limit: 200,
2306
- projection: "projected"
2307
- });
2308
- for (const entry of page.entries) {
2309
- const item = entry.item;
2310
- if (item.type !== "user_message") continue;
2311
- const id = item.clientMessageId ?? item.messageId;
2312
- if (typeof id === "string" && wanted.has(id)) confirmed.add(id);
2313
- }
2314
- if (!page.hasOlder || !page.startCursor) break;
2315
- const key = JSON.stringify(page.startCursor);
2316
- if (seen.has(key)) break;
2317
- seen.add(key);
2318
- cursor = page.startCursor;
2319
- }
2320
- return [...confirmed];
2321
- }
2322
- // src/server/auth.ts
2323
- /** Sliding session lifetime: a device that keeps using the console stays signed in. */
2324
- const SESSION_TTL_MS = 2592e6;
2325
- const TOUCH_INTERVAL_MS = 36e5;
2326
- const TOTP_PERIOD_S = 30;
2327
- const TOTP_DIGITS = 6;
2328
- /** Only clients that know the access token can reach TOTP verification.
2329
- * Code attempts have a persistent server-wide budget across IPs and restarts.
2330
- * Exhausting it doubles the lockout from 15 minutes to at most 24 hours.
2331
- */
2332
- const WINDOW_MS = 9e5;
2333
- const MAX_CODE_FAILURES_PER_CLIENT = 5;
2334
- const MAX_CODE_FAILURES_GLOBAL = 20;
2335
- const MAX_LOCK_MS = 864e5;
2336
- const MAX_TOKEN_FAILURES_PER_CLIENT = 10;
2337
- const BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
2338
- function base32Encode(bytes) {
2339
- let bits = 0, value = 0, out = "";
2340
- for (const byte of bytes) {
2341
- value = value << 8 | byte;
2342
- bits += 8;
2343
- while (bits >= 5) {
2344
- out += BASE32[value >>> bits - 5 & 31];
2345
- bits -= 5;
738
+ const WINDOW_MS = 9e5;
739
+ const MAX_CODE_FAILURES_PER_CLIENT = 5;
740
+ const MAX_CODE_FAILURES_GLOBAL = 20;
741
+ const MAX_LOCK_MS = 864e5;
742
+ const MAX_TOKEN_FAILURES_PER_CLIENT = 10;
743
+ const BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
744
+ function base32Encode(bytes) {
745
+ let bits = 0, value = 0, out = "";
746
+ for (const byte of bytes) {
747
+ value = value << 8 | byte;
748
+ bits += 8;
749
+ while (bits >= 5) {
750
+ out += BASE32[value >>> bits - 5 & 31];
751
+ bits -= 5;
2346
752
  }
2347
753
  }
2348
754
  if (bits > 0) out += BASE32[value << 5 - bits & 31];
@@ -2564,1825 +970,94 @@ var Auth = class {
2564
970
  stillValid(sessionId, now = Date.now()) {
2565
971
  const session = this.store.sessionById(sessionId);
2566
972
  return !!session && session.expires >= now;
2567
- }
2568
- revoke(sessionId) {
2569
- this.store.revokeSessions(sessionId);
2570
- }
2571
- beginTotp(sessionId, now = Date.now()) {
2572
- if (this.totpEnabled()) throw new Error("Disable the current authenticator before replacing it");
2573
- const secret = base32Encode(randomBytes(20));
2574
- this.pendingTotp = {
2575
- secret,
2576
- sessionId,
2577
- expires: now + 6e5
2578
- };
2579
- return {
2580
- secret,
2581
- uri: `otpauth://totp/LitePaseo?secret=${secret}&issuer=LitePaseo&algorithm=SHA1&digits=6&period=30`
2582
- };
2583
- }
2584
- /** Enables the pending secret once the user proves their app produces matching codes. */
2585
- confirmTotp(sessionId, code, now = Date.now()) {
2586
- if (this.totpEnabled()) return false;
2587
- const pending = this.pendingTotp;
2588
- if (!pending || pending.sessionId !== sessionId || pending.expires < now) return false;
2589
- const step = matchTotp(base32Decode(pending.secret), code, now);
2590
- if (step === null) return false;
2591
- this.store.db.exec("BEGIN IMMEDIATE");
2592
- try {
2593
- this.store.setSetting("totp_secret", pending.secret);
2594
- this.store.setSetting("totp_last_step", String(step));
2595
- this.store.db.prepare("DELETE FROM push_subscriptions WHERE session_id<>?").run(sessionId);
2596
- this.store.db.prepare("DELETE FROM sessions WHERE id<>?").run(sessionId);
2597
- this.resetCodeLimit();
2598
- this.store.db.exec("COMMIT");
2599
- } catch (error) {
2600
- this.store.db.exec("ROLLBACK");
2601
- throw error;
2602
- }
2603
- this.pendingTotp = null;
2604
- return true;
2605
- }
2606
- disableTotp(code, now = Date.now()) {
2607
- if (this.limited("settings", true, now)) return false;
2608
- const secret = this.store.setting("totp_secret");
2609
- const step = secret ? matchTotp(base32Decode(secret), code, now) : null;
2610
- if (step === null || !this.store.advanceSetting("totp_last_step", step)) {
2611
- this.fail("settings", true, now);
2612
- return false;
2613
- }
2614
- this.store.setSetting("totp_secret", null);
2615
- this.resetCodeLimit();
2616
- return true;
2617
- }
2618
- resetCodeLimit() {
2619
- this.global = {
2620
- count: 0,
2621
- reset: 0,
2622
- lockMs: WINDOW_MS
2623
- };
2624
- this.store.setSetting("totp_login_limit", JSON.stringify(this.global));
2625
- }
2626
- limited(client, usesCode, now) {
2627
- if (usesCode && this.global.reset > now && this.global.count >= MAX_CODE_FAILURES_GLOBAL) return Math.ceil((this.global.reset - now) / 1e3);
2628
- const map = usesCode ? this.codeFailures : this.tokenFailures;
2629
- if (!map.has(client) && map.size >= 1e4) client = "overflow";
2630
- const entry = map.get(client);
2631
- const max = usesCode ? MAX_CODE_FAILURES_PER_CLIENT : MAX_TOKEN_FAILURES_PER_CLIENT;
2632
- if (entry && entry.reset > now && entry.count >= max) return Math.ceil((entry.reset - now) / 1e3);
2633
- return 0;
2634
- }
2635
- fail(client, usesCode, now) {
2636
- if (usesCode) {
2637
- if (this.global.reset <= now) this.global.count = 0;
2638
- this.global.count++;
2639
- if (this.global.count === MAX_CODE_FAILURES_GLOBAL) {
2640
- this.global.reset = now + this.global.lockMs;
2641
- this.global.lockMs = Math.min(this.global.lockMs * 2, MAX_LOCK_MS);
2642
- } else if (this.global.reset <= now) this.global.reset = now + WINDOW_MS;
2643
- this.store.setSetting("totp_login_limit", JSON.stringify(this.global));
2644
- }
2645
- const map = usesCode ? this.codeFailures : this.tokenFailures;
2646
- if (!map.has(client) && map.size >= 1e4) client = "overflow";
2647
- let entry = map.get(client);
2648
- if (!entry || entry.reset <= now) map.set(client, entry = {
2649
- count: 0,
2650
- reset: now + WINDOW_MS
2651
- });
2652
- entry.count++;
2653
- }
2654
- };
2655
- // src/shared/wire.ts
2656
- /** "Run npm test" → "run npm test", for use mid-sentence ("wants to run npm test"). */
2657
- const midSentence = (text) => /^[A-Z][a-z]/.test(text) ? text[0].toLowerCase() + text.slice(1) : text;
2658
- // src/server/notifier.ts
2659
- /** Repeats of the same event for the same session within this window are dropped. */
2660
- const DEDUPE_MS = 15e3;
2661
- /** Turn ends older than this (seen late, e.g. after a reconnect) are not announced. */
2662
- const STALE_MS = 6e5;
2663
- function vapidKeys(store) {
2664
- const saved = store.setting("vapid");
2665
- if (saved) return JSON.parse(saved);
2666
- const keys = webpush.generateVAPIDKeys();
2667
- store.setSetting("vapid", JSON.stringify(keys));
2668
- return keys;
2669
- }
2670
- /** Real delivery through the browser vendor's push service. */
2671
- function webPushSender(store, subject) {
2672
- const keys = vapidKeys(store);
2673
- return { async send(subscription, payload) {
2674
- await webpush.sendNotification({
2675
- endpoint: subscription.endpoint,
2676
- keys: {
2677
- p256dh: subscription.p256dh,
2678
- auth: subscription.auth
2679
- }
2680
- }, payload, {
2681
- vapidDetails: {
2682
- subject,
2683
- publicKey: keys.publicKey,
2684
- privateKey: keys.privateKey
2685
- },
2686
- TTL: 21600,
2687
- urgency: "high"
2688
- });
2689
- } };
2690
- }
2691
- /**
2692
- * Turns directory transitions into push notifications: a session starting to need the user
2693
- * (a permission or question appears) and a turn finishing or failing. Detection is per
2694
- * transition, O(1); delivery fans out to the (few) subscribed devices.
2695
- */
2696
- var Notifier = class {
2697
- store;
2698
- sender;
2699
- isViewing;
2700
- hostLabel;
2701
- waiting = /* @__PURE__ */ new Set();
2702
- recent = /* @__PURE__ */ new Map();
2703
- now;
2704
- constructor(options) {
2705
- this.store = options.store;
2706
- this.sender = options.sender;
2707
- this.isViewing = options.isViewing;
2708
- this.hostLabel = options.hostLabel;
2709
- this.now = options.now ?? Date.now;
2710
- }
2711
- get waitingCount() {
2712
- return this.waiting.size;
2713
- }
2714
- /** Feed every summary transition here (HostDirectory → Hosts.onTransition). */
2715
- transition(previous, next) {
2716
- const key = next?.key ?? previous.key;
2717
- if (next?.attention) this.waiting.add(key);
2718
- else this.waiting.delete(key);
2719
- if (!previous || !next) return;
2720
- const newPermission = next.pendingPermissions.some((p) => !previous.pendingPermissions.some((q) => q.id === p.id));
2721
- if (next.attention && !previous.attention || newPermission) {
2722
- const permission = next.pendingPermissions[0];
2723
- const what = permission ? permission.kind === "question" ? `asks: ${permission.title || permission.name}` : `wants to ${midSentence(permission.title || permission.name)}` : "is waiting for you";
2724
- this.emit("attention", next, `${next.project} · needs your input`, `${next.title || "Session"} ${what}`);
2725
- } else if (previous.status === "running" && next.status !== "running") {
2726
- if (this.now() - next.activityAt > STALE_MS) return;
2727
- const failed = next.status === "error";
2728
- this.emit(failed ? "turn-failed" : "turn-done", next, `${next.project} · ${failed ? "turn failed" : "turn finished"}`, next.title || "Session");
2729
- }
2730
- }
2731
- async test(sessionId) {
2732
- const subs = this.store.pushSubscriptions().filter((s) => s.sessionId === sessionId);
2733
- await Promise.all(subs.map((s) => this.deliver(s, {
2734
- title: "LitePaseo notifications work",
2735
- body: "You'll hear from your agents when they need you or finish a turn.",
2736
- tag: "litepaseo-test",
2737
- url: "/",
2738
- kind: "test",
2739
- badge: this.waiting.size
2740
- })));
2741
- return subs.length;
2742
- }
2743
- emit(kind, agent, title, body) {
2744
- const dedupeKey = `${kind}:${agent.key}`;
2745
- const now = this.now();
2746
- if (now - (this.recent.get(dedupeKey) ?? -Infinity) < DEDUPE_MS) return;
2747
- this.recent.set(dedupeKey, now);
2748
- if (this.recent.size > 5e3) this.recent.clear();
2749
- const message = {
2750
- title,
2751
- body: `${body} — ${this.hostLabel(agent.hostId)}`.slice(0, 240),
2752
- tag: agent.key,
2753
- url: `/?session=${encodeURIComponent(agent.key)}`,
2754
- kind,
2755
- badge: this.waiting.size
2756
- };
2757
- const pref = kind === "attention" ? "attention" : "turns";
2758
- for (const subscription of this.store.pushSubscriptions()) if (subscription.prefs[pref] && !this.isViewing(agent.key, subscription.sessionId)) this.deliver(subscription, message);
2759
- }
2760
- async deliver(subscription, message) {
2761
- const session = this.store.sessionById(subscription.sessionId);
2762
- if (!session || session.expires <= this.now()) {
2763
- this.store.removePushSubscription(subscription.endpoint, subscription.sessionId);
2764
- return;
2765
- }
2766
- try {
2767
- await this.sender.send(subscription, JSON.stringify(message));
2768
- } catch (error) {
2769
- const status = error.statusCode;
2770
- if (status === 404 || status === 410) this.store.removePushSubscription(subscription.endpoint);
2771
- }
2772
- }
2773
- };
2774
- // src/server/usage.ts
2775
- /** Paseo's daemon caches usage for 5 minutes; reading more often only re-reads its copy. */
2776
- const FRESH_MS = 3e5;
2777
- const FAILED_RETRY_MS = 6e4;
2778
- /**
2779
- * Usage across every connected host. Each host is read at most once per freshness window and
2780
- * only when someone asks (nothing polls while no screen shows usage); concurrent requests share
2781
- * one in-flight read per host.
2782
- */
2783
- var UsageService = class {
2784
- hosts;
2785
- cache = /* @__PURE__ */ new Map();
2786
- inflight = /* @__PURE__ */ new Map();
2787
- now;
2788
- constructor(hosts, now = Date.now) {
2789
- this.hosts = hosts;
2790
- this.now = now;
2791
- }
2792
- async report(force = false) {
2793
- const ids = [...this.hosts.clients.keys()].filter((id) => this.hosts.state(id) === "connected");
2794
- const results = await Promise.all(ids.map(async (id) => [id, await this.read(id, force)]));
2795
- const accounts = /* @__PURE__ */ new Map();
2796
- const unavailableHosts = [];
2797
- let newest = 0;
2798
- for (const [hostId, usage] of results) {
2799
- const label = this.hosts.label(hostId) || hostId;
2800
- if (!usage.ok) {
2801
- unavailableHosts.push({
2802
- hostId,
2803
- label,
2804
- error: usage.error ?? "Usage unavailable"
2805
- });
2806
- continue;
2807
- }
2808
- newest = Math.max(newest, usage.at);
2809
- for (const p of usage.providers) {
2810
- const windows = (p.windows ?? []).map((w) => ({
2811
- id: String(w.id),
2812
- label: String(w.label),
2813
- shortLabel: w.shortLabel ?? null,
2814
- remainingPct: typeof w.remainingPct === "number" ? w.remainingPct : typeof w.usedPct === "number" ? Math.max(0, 100 - w.usedPct) : null,
2815
- resetsAt: w.resetsAt ?? null,
2816
- tone: w.tone ?? null
2817
- }));
2818
- if (!windows.length && p.status === "unavailable") continue;
2819
- const key = [
2820
- p.providerId,
2821
- p.planLabel ?? "",
2822
- p.sourceLabel ?? "",
2823
- ...windows.map((w) => `${w.id}@${w.resetsAt ?? ""}`)
2824
- ].join("|");
2825
- const existing = accounts.get(key);
2826
- if (existing) existing.hosts.push(label);
2827
- else accounts.set(key, {
2828
- key,
2829
- providerId: String(p.providerId),
2830
- name: String(p.displayName ?? p.providerId),
2831
- plan: p.planLabel ?? null,
2832
- source: p.sourceLabel ?? null,
2833
- status: String(p.status),
2834
- error: p.error ?? null,
2835
- windows,
2836
- hosts: [label]
2837
- });
2838
- }
2839
- }
2840
- return {
2841
- fetchedAt: newest ? new Date(newest).toISOString() : null,
2842
- accounts: [...accounts.values()].sort((a, b) => a.name.localeCompare(b.name) || (a.plan ?? "").localeCompare(b.plan ?? "") || a.key.localeCompare(b.key)),
2843
- unavailableHosts
2844
- };
2845
- }
2846
- read(hostId, force) {
2847
- const cached = this.cache.get(hostId);
2848
- const age = cached ? this.now() - cached.at : Infinity;
2849
- if (cached && age < (cached.ok ? FRESH_MS : FAILED_RETRY_MS) && !(force && age > 3e4)) return Promise.resolve(cached);
2850
- const pending = this.inflight.get(hostId);
2851
- if (pending) return pending;
2852
- const request = (async () => {
2853
- try {
2854
- const result = await this.hosts.get(hostId).api.providers.listUsage();
2855
- return {
2856
- at: this.now(),
2857
- ok: true,
2858
- providers: result.providers ?? []
2859
- };
2860
- } catch (error) {
2861
- return {
2862
- at: this.now(),
2863
- ok: false,
2864
- providers: [],
2865
- error: error.message || "Usage unavailable"
2866
- };
2867
- }
2868
- })().then((usage) => {
2869
- this.cache.set(hostId, usage);
2870
- this.inflight.delete(hostId);
2871
- return usage;
2872
- });
2873
- this.inflight.set(hostId, request);
2874
- return request;
2875
- }
2876
- };
2877
- // src/server/dictation.ts
2878
- /**
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.
2882
- *
2883
- * Request shape differs by model generation (OpenAI speech-to-text guide, 2026):
2884
- * - `gpt-transcribe` takes `languages[]` (several expected languages, for code-switching) and
2885
- * `keywords[]`; it "replaces the singular `language` field. Don't send both fields."
2886
- * - `whisper-1`, `gpt-4o(-mini)-transcribe` and most compatible providers (Groq, local Whisper
2887
- * servers) take a single `language` and a free-text `prompt`.
2888
- * Paseo always sends `language` (default "en"), which is what breaks `gpt-transcribe` there.
2889
- * Here the shape follows the model name, and a 400 about the language field retries once with
2890
- * the other shape, so unknown models on compatible providers still work.
2891
- */
2892
- const DEFAULT_BASE_URL = "https://api.openai.com/v1";
2893
- /** Five minutes of 16 kHz, 16-bit mono speech (9.6 MB as WAV, under the 25 MB upload limit). */
2894
- const MAX_DICTATION_BYTES = 96e5;
2895
- const SETTING = "dictation";
2896
- const UPSTREAM_TIMEOUT_MS = 11e4;
2897
- /** Whisper reads at most 224 prompt tokens; keep the folded vocabulary well under that. */
2898
- const LEGACY_PROMPT_CHARS = 600;
2899
- const baseUrl = z.string().trim().max(500).transform((v) => (v || "https://api.openai.com/v1").replace(/\/+$/, "")).refine((v) => {
2900
- try {
2901
- return ["http:", "https:"].includes(new URL(v).protocol);
2902
- } catch {
2903
- return false;
2904
- }
2905
- }, "Base URL must be an http(s) address");
2906
- 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");
2907
- /** The API rejects the whole request for a keyword with <, > or a line break. */
2908
- 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 >");
2909
- const unique = (values) => [...new Set(values)];
2910
- const DictationUpdate = z.object({
2911
- baseUrl: baseUrl.optional().default(DEFAULT_BASE_URL),
2912
- /** Omitted or empty keeps the saved key. */
2913
- apiKey: z.string().trim().max(1e3).optional(),
2914
- model: z.string().trim().max(200).optional().transform((v) => v || "gpt-transcribe"),
2915
- languages: z.array(languageCode).max(10, "At most 10 languages").optional().default([]).transform(unique),
2916
- keywords: z.array(keyword).max(100, "At most 100 vocabulary terms").optional().default([]).transform(unique)
2917
- });
2918
- function dictationConfig(store) {
2919
- const raw = store.setting(SETTING);
2920
- if (!raw) return null;
2921
- try {
2922
- const value = JSON.parse(raw);
2923
- if (!value.apiKey || !value.baseUrl || !value.model) return null;
2924
- return {
2925
- baseUrl: value.baseUrl,
2926
- apiKey: value.apiKey,
2927
- model: value.model,
2928
- languages: value.languages ?? [],
2929
- keywords: value.keywords ?? []
2930
- };
2931
- } catch {
2932
- return null;
2933
- }
2934
- }
2935
- function dictationSettings(store) {
2936
- const config = dictationConfig(store);
2937
- return {
2938
- configured: !!config,
2939
- baseUrl: config?.baseUrl ?? "https://api.openai.com/v1",
2940
- model: config?.model ?? "gpt-transcribe",
2941
- languages: config?.languages ?? [],
2942
- keywords: config?.keywords ?? [],
2943
- keyHint: config ? "…" + config.apiKey.slice(-4) : ""
2944
- };
2945
- }
2946
- function saveDictation(store, input) {
2947
- const update = DictationUpdate.parse(input);
2948
- const apiKey = update.apiKey || dictationConfig(store)?.apiKey;
2949
- if (!apiKey) throw new Error("An API key is required");
2950
- const config = {
2951
- baseUrl: update.baseUrl,
2952
- apiKey,
2953
- model: update.model,
2954
- languages: update.languages,
2955
- keywords: update.keywords
2956
- };
2957
- store.setSetting(SETTING, JSON.stringify(config));
2958
- return dictationSettings(store);
2959
- }
2960
- function clearDictation(store) {
2961
- store.setSetting(SETTING, null);
2962
- }
2963
- /** A 44-byte RIFF header makes raw PCM16 a file every transcription API accepts. */
2964
- function wav(pcm, rate) {
2965
- const out = Buffer.alloc(44 + pcm.length);
2966
- out.write("RIFF", 0);
2967
- out.writeUInt32LE(36 + pcm.length, 4);
2968
- out.write("WAVE", 8);
2969
- out.write("fmt ", 12);
2970
- out.writeUInt32LE(16, 16);
2971
- out.writeUInt16LE(1, 20);
2972
- out.writeUInt16LE(1, 22);
2973
- out.writeUInt32LE(rate, 24);
2974
- out.writeUInt32LE(rate * 2, 28);
2975
- out.writeUInt16LE(2, 32);
2976
- out.writeUInt16LE(16, 34);
2977
- out.write("data", 36);
2978
- out.writeUInt32LE(pcm.length, 40);
2979
- out.set(pcm, 44);
2980
- return out;
2981
- }
2982
- const shapeFor = (model) => /(^|\/)gpt-transcribe\b/i.test(model) ? "hints" : "single";
2983
- /** The multipart fields besides the file, for one request shape. */
2984
- function transcriptionFields(config, shape) {
2985
- const fields = [["model", config.model], ["response_format", "json"]];
2986
- if (shape === "hints") {
2987
- for (const code of config.languages) fields.push(["languages[]", code]);
2988
- for (const term of config.keywords) fields.push(["keywords[]", term]);
2989
- return fields;
2990
- }
2991
- if (config.languages.length === 1) fields.push(["language", config.languages[0].split("-")[0]]);
2992
- if (config.keywords.length) {
2993
- let prompt = "";
2994
- for (const term of config.keywords) {
2995
- const next = prompt ? `${prompt}, ${term}` : term;
2996
- if (next.length > LEGACY_PROMPT_CHARS) break;
2997
- prompt = next;
2998
- }
2999
- fields.push(["prompt", prompt]);
3000
- }
3001
- return fields;
3002
- }
3003
- var DictationError = class extends Error {
3004
- status;
3005
- constructor(message, status) {
3006
- super(message);
3007
- this.status = status;
3008
- }
3009
- };
3010
- async function send(config, file, shape, fetchImpl, signal) {
3011
- const form = new FormData();
3012
- form.append("file", file, "dictation.wav");
3013
- for (const [name, value] of transcriptionFields(config, shape)) form.append(name, value);
3014
- let response;
3015
- try {
3016
- response = await fetchImpl(config.baseUrl + "/audio/transcriptions", {
3017
- method: "POST",
3018
- headers: { authorization: `Bearer ${config.apiKey}` },
3019
- body: form,
3020
- signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)]) : AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
3021
- });
3022
- } catch (error) {
3023
- const timeout = error.name === "TimeoutError";
3024
- 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);
3025
- }
3026
- const body = await response.text();
3027
- let data = {};
3028
- try {
3029
- data = JSON.parse(body);
3030
- } catch {}
3031
- const detail = typeof data.error === "string" ? data.error : typeof data.error?.message === "string" ? data.error.message : response.ok ? "" : body;
3032
- return {
3033
- ok: response.ok,
3034
- status: response.status,
3035
- text: typeof data.text === "string" ? data.text : void 0,
3036
- detail: String(detail)
3037
- };
3038
- }
3039
- async function transcribe(config, pcm, rate, fetchImpl = fetch, signal) {
3040
- const file = new Blob([wav(pcm, rate)], { type: "audio/wav" });
3041
- const shape = shapeFor(config.model);
3042
- let result = await send(config, file, shape, fetchImpl, signal);
3043
- const hinted = config.languages.length > 0 || config.keywords.length > 0;
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);
3045
- if (!result.ok) {
3046
- const scrubbed = result.detail.split(config.apiKey).join("…").replace(/\s+/g, " ").trim().slice(0, 200);
3047
- throw new DictationError(`Transcription failed (${result.status})${scrubbed ? ": " + scrubbed : ""}`, 502);
3048
- }
3049
- if (result.text === void 0) throw new DictationError("The transcription service returned no text", 502);
3050
- return result.text.trim();
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 {};
3491
- // src/server/app.ts
3492
- const AGENT_FLUSH_MS = 100;
3493
- const HOST_FLUSH_MS = 100;
3494
- function parseJson(text) {
3495
- try {
3496
- return JSON.parse(text ?? "null");
3497
- } catch {
3498
- return null;
3499
- }
3500
- }
3501
- const card = z.object({
3502
- id: z.string().uuid(),
3503
- title: z.string().min(1).max(300),
3504
- column: z.enum([
3505
- "Todo",
3506
- "Doing",
3507
- "Done"
3508
- ]),
3509
- hostId: z.string().nullable(),
3510
- agentId: z.string().nullable()
3511
- }).refine((c) => c.hostId === null === (c.agentId === null));
3512
- const SESSION_COOKIE = "lp_session";
3513
- /** Cookie-authenticated writes must carry this header; a cross-site form or image cannot. */
3514
- const CSRF_HEADER = "x-litepaseo";
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). */
3528
- function createApp(store, hosts, token, webRoot, options = {}) {
3529
- const app = new Hono();
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
- })));
3535
- const attachments = new Attachments();
3536
- const projectIcons = new IconCache();
3537
- const viewers = /* @__PURE__ */ new Map();
3538
- const notifier = new Notifier({
3539
- store,
3540
- sender: options.pushSender ?? webPushSender(store, options.pushSubject ?? "mailto:litepaseo@example.com"),
3541
- isViewing: (key, sessionId) => (viewers.get(key)?.get(sessionId) ?? 0) > 0,
3542
- hostLabel: (id) => hosts.label(id) || store.hosts().find((h) => h.id === id)?.label || ""
3543
- });
3544
- hosts.onTransition((previous, next) => notifier.transition(previous, next));
3545
- const usage = new UsageService(hosts);
3546
- store.pruneSessions(Date.now());
3547
- const secure = (c) => c.req.header("x-forwarded-proto") === "https" || c.req.url.startsWith("https:");
3548
- const clientId = (c) => c.req.header("cf-connecting-ip") ?? c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? "direct";
3549
- app.use("*", async (c, next) => {
3550
- await next();
3551
- c.header("X-Content-Type-Options", "nosniff");
3552
- c.header("Referrer-Policy", "no-referrer");
3553
- 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'");
3554
- });
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));
3556
- app.use("/api/*", async (c, next) => {
3557
- c.header("Cache-Control", "no-store");
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
- }
3566
- c.set("session", null);
3567
- c.set("bearer", bearer);
3568
- return next();
3569
- }
3570
- const secret = getCookie(c, SESSION_COOKIE);
3571
- const found = auth.authenticate(secret);
3572
- const session = found?.session ?? null;
3573
- if (found?.renewed && secret && c.req.path !== "/api/login" && c.req.path !== "/api/logout") setCookie(c, SESSION_COOKIE, secret, {
3574
- httpOnly: true,
3575
- secure: secure(c),
3576
- sameSite: "Strict",
3577
- path: "/",
3578
- maxAge: Math.floor(SESSION_TTL_MS / 1e3)
3579
- });
3580
- if (PUBLIC_API.has(c.req.path)) {
3581
- c.set("session", session);
3582
- return next();
3583
- }
3584
- if (!session) return c.json({ error: "Sign in required" }, 401);
3585
- if (!["GET", "HEAD"].includes(c.req.method) && c.req.header(CSRF_HEADER) !== "1") return c.json({ error: "Missing request header" }, 403);
3586
- c.set("session", session);
3587
- await next();
3588
- });
3589
- app.get("/api/auth", (c) => c.json({
3590
- authenticated: !!c.get("session"),
3591
- totp: auth.totpEnabled()
3592
- }));
3593
- app.post("/api/login", async (c) => {
3594
- const input = z.object({
3595
- token: z.string().min(1).max(200).optional(),
3596
- code: z.string().regex(/^\d{6}$/).optional()
3597
- }).refine((x) => !!x.token || !!x.code).parse(await c.req.json());
3598
- const userAgent = c.req.header("user-agent") ?? "";
3599
- const label = (/iPhone|iPad/.test(userAgent) ? "iOS" : /Android/.test(userAgent) ? "Android" : /Mac OS/.test(userAgent) ? "macOS" : /Windows/.test(userAgent) ? "Windows" : /Linux/.test(userAgent) ? "Linux" : "Browser") + (/Edg\//.test(userAgent) ? " · Edge" : /Chrome\//.test(userAgent) ? " · Chrome" : /Firefox\//.test(userAgent) ? " · Firefox" : /Safari\//.test(userAgent) ? " · Safari" : "");
3600
- const result = auth.login(input, clientId(c), label);
3601
- if (!result.ok) {
3602
- if (result.retryAfter) c.header("Retry-After", String(result.retryAfter));
3603
- return c.json({ error: result.status === 429 ? "Too many attempts. Try again later." : "That did not match." }, result.status);
3604
- }
3605
- setCookie(c, SESSION_COOKIE, result.secret, {
3606
- httpOnly: true,
3607
- secure: secure(c),
3608
- sameSite: "Strict",
3609
- path: "/",
3610
- maxAge: SESSION_TTL_MS / 1e3
3611
- });
3612
- return c.json({ ok: true });
3613
- });
3614
- app.post("/api/logout", (c) => {
3615
- const session = c.get("session");
3616
- if (session) {
3617
- auth.revoke(session.id);
3618
- attachments.clearOwner(session.id);
3619
- }
3620
- deleteCookie(c, SESSION_COOKIE, { path: "/" });
3621
- return c.json({ ok: true });
3622
- });
3623
- app.get("/api/sessions", (c) => c.json(store.sessions().map((s) => ({
3624
- id: s.id,
3625
- label: s.label,
3626
- created: s.created,
3627
- lastSeen: s.lastSeen,
3628
- current: s.id === c.get("session")?.id
3629
- }))));
3630
- app.delete("/api/sessions/:id", (c) => {
3631
- auth.revoke(c.req.param("id"));
3632
- if (c.req.param("id") === c.get("session")?.id) deleteCookie(c, SESSION_COOKIE, { path: "/" });
3633
- return c.json({ ok: true });
3634
- });
3635
- app.post("/api/sessions/revoke-all", (c) => {
3636
- auth.revoke();
3637
- deleteCookie(c, SESSION_COOKIE, { path: "/" });
3638
- return c.json({ ok: true });
3639
- });
3640
- const requireSession = (session) => {
3641
- if (!session) throw new z.ZodError([{
3642
- code: "custom",
3643
- path: [],
3644
- message: "A browser session is required",
3645
- input: null
3646
- }]);
3647
- return session;
3648
- };
3649
- app.post("/api/totp/setup", async (c) => {
3650
- const session = requireSession(c.get("session"));
3651
- if (auth.totpEnabled()) return c.json({ error: "Disable the current authenticator before replacing it." }, 409);
3652
- const { secret, uri } = auth.beginTotp(session.id);
3653
- const qr = await QRCode.toString(uri, {
3654
- type: "svg",
3655
- margin: 1,
3656
- errorCorrectionLevel: "M"
3657
- });
3658
- return c.json({
3659
- secret,
3660
- uri,
3661
- qr: "data:image/svg+xml;base64," + Buffer.from(qr).toString("base64")
3662
- });
3663
- });
3664
- app.post("/api/totp/confirm", async (c) => {
3665
- const session = requireSession(c.get("session"));
3666
- const { code } = z.object({ code: z.string().regex(/^\d{6}$/) }).parse(await c.req.json());
3667
- if (!auth.confirmTotp(session.id, code)) return c.json({ error: "That code did not match. Try the next one." }, 400);
3668
- return c.json({ ok: true });
3669
- });
3670
- app.post("/api/totp/disable", async (c) => {
3671
- const { code } = z.object({ code: z.string().regex(/^\d{6}$/) }).parse(await c.req.json());
3672
- if (!auth.disableTotp(code)) return c.json({ error: "That code did not match." }, 400);
3673
- return c.json({ ok: true });
3674
- });
3675
- const prefsSchema = z.object({
3676
- attention: z.boolean(),
3677
- turns: z.boolean()
3678
- });
3679
- app.get("/api/push/key", (c) => c.json({ publicKey: vapidKeys(store).publicKey }));
3680
- app.post("/api/push/subscribe", async (c) => {
3681
- const session = requireSession(c.get("session"));
3682
- const input = z.object({
3683
- subscription: z.object({
3684
- endpoint: z.string().url().max(2e3).refine((u) => u.startsWith("https://")),
3685
- keys: z.object({
3686
- p256dh: z.string().min(1).max(200),
3687
- auth: z.string().min(1).max(100)
3688
- })
3689
- }),
3690
- prefs: prefsSchema
3691
- }).parse(await c.req.json());
3692
- store.savePushSubscription({
3693
- endpoint: input.subscription.endpoint,
3694
- sessionId: session.id,
3695
- p256dh: input.subscription.keys.p256dh,
3696
- auth: input.subscription.keys.auth,
3697
- prefs: input.prefs,
3698
- created: Date.now()
3699
- });
3700
- return c.json({ ok: true });
3701
- });
3702
- app.post("/api/push/status", async (c) => {
3703
- const { endpoint } = z.object({ endpoint: z.string().max(2e3) }).parse(await c.req.json());
3704
- const found = store.pushSubscriptions().find((s) => s.endpoint === endpoint);
3705
- return c.json(found ? {
3706
- subscribed: true,
3707
- prefs: found.prefs
3708
- } : { subscribed: false });
3709
- });
3710
- app.post("/api/push/unsubscribe", async (c) => {
3711
- const { endpoint } = z.object({ endpoint: z.string().max(2e3) }).parse(await c.req.json());
3712
- store.removePushSubscription(endpoint);
3713
- return c.json({ ok: true });
3714
- });
3715
- app.post("/api/push/test", async (c) => {
3716
- const session = requireSession(c.get("session"));
3717
- return c.json({ sent: await notifier.test(session.id) });
3718
- });
3719
- app.onError((error, c) => {
3720
- if (error instanceof UnknownHostError) return c.json({ error: "Unknown host" }, 404);
3721
- if (error instanceof z.ZodError) return c.json({
3722
- error: "Invalid request",
3723
- detail: error.issues
3724
- }, 400);
3725
- const requestId = randomUUID();
3726
- const failure = error;
3727
- const cause = failure.cause instanceof Error ? failure.cause : null;
3728
- console.error(JSON.stringify({
3729
- event: "api_operation_failed",
3730
- requestId,
3731
- method: c.req.method,
3732
- path: c.req.path,
3733
- route: c.req.routePath,
3734
- error: failure.name,
3735
- ...typeof failure.code === "string" ? { code: failure.code } : {},
3736
- message: String(failure.message ?? "").slice(0, 500),
3737
- ...cause ? { cause: `${cause.name}: ${cause.message}`.slice(0, 300) } : {},
3738
- at: failure.stack?.split("\n").slice(1, 4).map((line) => line.trim())
3739
- }));
3740
- return c.json({
3741
- error: "Operation failed; refresh state before retrying",
3742
- requestId
3743
- }, 502);
3744
- });
3745
- app.get("/api/health", (c) => c.json({
3746
- ok: true,
3747
- version: VERSION,
3748
- waiting: notifier.waitingCount
3749
- }));
3750
- const hostStates = () => store.hosts().map((h) => ({
3751
- id: h.id,
3752
- label: h.label,
3753
- state: hosts.state(h.id),
3754
- diagnostic: hosts.diagnostic(h.id)
3755
- }));
3756
- app.get("/api/hosts", (c) => c.json(hostStates()));
3757
- const directoryStreams = /* @__PURE__ */ new Set();
3758
- let agentFlush;
3759
- let hostFlush;
3760
- /** Set on shutdown: closing the hosts still reports changes, but the store is about to close. */
3761
- let disposed = false;
3762
- const deliverAgents = (stream) => {
3763
- deliverWorkspaces(stream);
3764
- const { agents } = hosts;
3765
- const changes = agents.changesSince(stream.last);
3766
- if (changes === null) stream.send({
3767
- type: "snapshot",
3768
- generation: agents.generation,
3769
- seq: agents.seq,
3770
- agents: agents.snapshot()
3771
- });
3772
- else if (changes.length) stream.send({
3773
- type: "changes",
3774
- generation: agents.generation,
3775
- seq: agents.seq,
3776
- changes
3777
- });
3778
- stream.last = agents.seq;
3779
- };
3780
- const deliverWorkspaces = (stream) => {
3781
- const { workspaces } = hosts;
3782
- const changes = workspaces.changesSince(stream.lastWorkspaces);
3783
- if (changes === null) stream.send({
3784
- type: "workspaces-snapshot",
3785
- generation: workspaces.generation,
3786
- seq: workspaces.seq,
3787
- workspaces: workspaces.snapshot()
3788
- });
3789
- else if (changes.length) stream.send({
3790
- type: "workspaces-changes",
3791
- generation: workspaces.generation,
3792
- seq: workspaces.seq,
3793
- changes
3794
- });
3795
- stream.lastWorkspaces = workspaces.seq;
3796
- };
3797
- hosts.onAgentsChanged(() => {
3798
- if (disposed || agentFlush || !directoryStreams.size) return;
3799
- agentFlush = setTimeout(() => {
3800
- agentFlush = void 0;
3801
- for (const stream of directoryStreams) deliverAgents(stream);
3802
- }, AGENT_FLUSH_MS);
3803
- });
3804
- hosts.onHostsChanged(() => {
3805
- if (disposed || hostFlush || !directoryStreams.size) return;
3806
- hostFlush = setTimeout(() => {
3807
- hostFlush = void 0;
3808
- const message = {
3809
- type: "hosts",
3810
- hosts: hostStates()
3811
- };
3812
- for (const stream of directoryStreams) stream.send(message);
3813
- }, HOST_FLUSH_MS);
3814
- });
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
- };
3821
- app.get("/api/stream", (c) => {
3822
- const since = Number(c.req.query("since"));
3823
- const resumable = c.req.query("generation") === hosts.agents.generation && Number.isInteger(since);
3824
- const wsince = Number(c.req.query("wsince"));
3825
- const wresumable = c.req.query("wgeneration") === hosts.workspaces.generation && Number.isInteger(wsince);
3826
- return eventStream(c.req.raw.signal, (send) => {
3827
- const stream = {
3828
- last: resumable ? since : -1,
3829
- lastWorkspaces: wresumable ? wsince : -1,
3830
- send
3831
- };
3832
- send({
3833
- type: "hosts",
3834
- hosts: hostStates()
3835
- });
3836
- deliverAgents(stream);
3837
- directoryStreams.add(stream);
3838
- return () => directoryStreams.delete(stream);
3839
- }, streamValidity(c));
3840
- });
3841
- app.post("/api/hosts", async (c) => {
3842
- const input = z.object({
3843
- label: z.string().trim().min(1).max(80),
3844
- connection: z.string().trim().min(1).max(16e3)
3845
- }).parse(await c.req.json());
3846
- parseHostTarget(input.connection);
3847
- const host = store.addHost(input.label, input.connection);
3848
- try {
3849
- hosts.add(host);
3850
- } catch (e) {
3851
- store.removeHost(host.id);
3852
- throw e;
3853
- }
3854
- return c.json({
3855
- id: host.id,
3856
- label: host.label
3857
- }, 201);
3858
- });
3859
- app.delete("/api/hosts/:host", async (c) => {
3860
- await hosts.remove(c.req.param("host"));
3861
- store.removeHost(c.req.param("host"));
3862
- return c.json({ ok: true });
3863
- });
3864
- /** Providers the host can start right now, read from the daemon's provider snapshot. */
3865
- app.get("/api/hosts/:host/providers", async (c) => {
3866
- const providers = (await hosts.get(c.req.param("host")).api.providers.snapshot()).entries.filter((entry) => entry.enabled !== false && entry.status !== "unavailable").map((entry) => ({
3867
- id: entry.provider,
3868
- label: entry.label ?? entry.provider,
3869
- status: entry.status,
3870
- ...entry.error ? { error: entry.error } : {},
3871
- defaultModeId: entry.defaultModeId ?? null,
3872
- modes: (entry.modes ?? []).map((m) => ({
3873
- id: m.id,
3874
- label: m.label,
3875
- ...m.description ? { description: m.description } : {}
3876
- })),
3877
- models: (entry.models ?? []).filter((m) => m.isSelectable !== false).map((m) => ({
3878
- id: m.id,
3879
- label: m.label,
3880
- ...m.description ? { description: m.description } : {},
3881
- isDefault: m.isDefault === true,
3882
- thinking: (m.thinkingOptions ?? []).map((t) => ({
3883
- id: t.id,
3884
- label: t.label
3885
- })),
3886
- defaultThinkingId: m.defaultThinkingOptionId ?? null
3887
- }))
3888
- }));
3889
- return c.json(providers);
3890
- });
3891
- /** Projects the daemon knows, as starting points for a new session. */
3892
- app.get("/api/hosts/:host/projects", async (c) => {
3893
- const projects = (await hosts.get(c.req.param("host")).api.projects.list()).projects.map((p) => ({
3894
- key: p.projectKey ?? p.projectId,
3895
- name: p.projectCustomName || p.projectDisplayName,
3896
- rootPath: p.projectRootPath,
3897
- kind: p.projectKind
3898
- }));
3899
- return c.json(projects);
3900
- });
3901
- /**
3902
- * Starts a session. The browser's idempotency key travels to the daemon, so retrying after an
3903
- * unknown outcome cannot create a second session.
3904
- */
3905
- app.post("/api/hosts/:host/agents", async (c) => {
3906
- const input = z.object({
3907
- idempotencyKey: z.string().uuid(),
3908
- cwd: z.string().trim().min(1).max(4096),
3909
- provider: z.string().trim().min(1).max(200).regex(/^[^/]+$/),
3910
- model: z.string().trim().min(1).max(300).optional(),
3911
- modeId: z.string().trim().min(1).max(200).optional(),
3912
- thinkingOptionId: z.string().trim().min(1).max(200).optional(),
3913
- prompt: z.string().max(1e5).optional(),
3914
- worktreeBranch: z.string().trim().min(1).max(200).optional()
3915
- }).parse(await c.req.json());
3916
- const hostId = c.req.param("host");
3917
- const { api } = hosts.get(hostId);
3918
- try {
3919
- let model = input.model;
3920
- if (!model) {
3921
- const models = (await api.providers.snapshot()).entries.find((p) => p.provider === input.provider && p.enabled !== false && p.status !== "unavailable")?.models?.filter((m) => m.isSelectable !== false) ?? [];
3922
- model = models.find((m) => m.isDefault)?.id ?? models[0]?.id;
3923
- if (!model) return c.json({ error: "No selectable model is available for this provider. Refresh providers and select a model." }, 400);
3924
- }
3925
- const agent = await api.agents.create({
3926
- idempotencyKey: input.idempotencyKey,
3927
- cwd: input.cwd,
3928
- config: {
3929
- provider: `${input.provider}/${model}`,
3930
- ...input.modeId ? { modeId: input.modeId } : {},
3931
- ...input.thinkingOptionId ? { thinkingOptionId: input.thinkingOptionId } : {}
3932
- },
3933
- ...input.prompt?.trim() ? { prompt: input.prompt } : {},
3934
- ...input.worktreeBranch ? { worktree: {
3935
- mode: "branch-off",
3936
- newBranch: input.worktreeBranch
3937
- } } : {}
3938
- });
3939
- return c.json({
3940
- id: agent.id,
3941
- key: `${hostId}:${agent.id}`
3942
- }, 201);
3943
- } catch (error) {
3944
- return c.json({ error: error instanceof Error && error.message ? `Could not start the session: ${error.message}` : "Creation outcome unknown. Check the session list before retrying." }, 502);
3945
- }
3946
- });
3947
- app.get("/api/hosts/:host/agents/:agent/timeline/stream", (c) => {
3948
- hosts.get(c.req.param("host"));
3949
- return eventStream(c.req.raw.signal, (send) => {
3950
- const sessionId = c.get("session")?.id;
3951
- const key = `${c.req.param("host")}:${c.req.param("agent")}`;
3952
- const stop = hosts.watchTimeline(c.req.param("host"), c.req.param("agent"), (ops) => send({
3953
- type: "ops",
3954
- ops
3955
- }));
3956
- if (sessionId) {
3957
- let devices = viewers.get(key);
3958
- if (!devices) viewers.set(key, devices = /* @__PURE__ */ new Map());
3959
- devices.set(sessionId, (devices.get(sessionId) ?? 0) + 1);
3960
- }
3961
- return () => {
3962
- stop();
3963
- const devices = viewers.get(key);
3964
- if (sessionId && devices) {
3965
- const count = (devices.get(sessionId) ?? 1) - 1;
3966
- if (count) devices.set(sessionId, count);
3967
- else devices.delete(sessionId);
3968
- if (!devices.size) viewers.delete(key);
3969
- }
3970
- };
3971
- }, streamValidity(c));
3972
- });
3973
- /** Bounded history pages; the browser bookmarks boundaries for forward navigation. */
3974
- app.get("/api/hosts/:host/agents/:agent/timeline", async (c) => {
3975
- const cursor = z.object({
3976
- epoch: z.string().min(1),
3977
- seq: z.number().int().nonnegative()
3978
- }).parse(parseJson(c.req.query("cursor")));
3979
- const page = await hosts.get(c.req.param("host")).driver.fetchAgentTimeline(c.req.param("agent"), {
3980
- direction: "before",
3981
- cursor,
3982
- limit: 100,
3983
- projection: "projected",
3984
- wholeTurns: false
3985
- });
3986
- return c.json({
3987
- epoch: page.epoch,
3988
- hasOlder: page.hasOlder,
3989
- startCursor: page.startCursor,
3990
- rows: page.entries.map((e) => ({
3991
- seqStart: e.seqStart,
3992
- seqEnd: e.seqEnd,
3993
- timestamp: e.timestamp,
3994
- provider: e.provider,
3995
- ...e.turnId ? { turnId: e.turnId } : {},
3996
- item: e.item
3997
- }))
3998
- });
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
- });
4040
- /**
4041
- * An image an agent referenced in a message (`![](file:///…)`, an absolute or workspace path).
4042
- * Workspace files go through the daemon's file API; images the daemon materialized from
4043
- * provider output live outside the workspace and are read from disk when the daemon is local.
4044
- */
4045
- app.get("/api/hosts/:host/agents/:agent/image", async (c) => {
4046
- const hostId = c.req.param("host");
4047
- const path = z.string().min(1).max(4096).refine((p) => !p.includes("\0")).parse(c.req.query("path"));
4048
- const mime = imageMime(path);
4049
- if (!mime) return c.json({ error: "Not an image" }, 415);
4050
- const { driver } = hosts.get(hostId);
4051
- const cwd = hosts.agents.get(`${hostId}:${c.req.param("agent")}`)?.cwd;
4052
- let bytes = null;
4053
- if (isMaterializedImagePath(path)) {
4054
- const host = store.hosts().find((h) => h.id === hostId);
4055
- if (host && isLocalConnection(host.connection)) bytes = await readMaterializedImage(path);
4056
- } else if (cwd) try {
4057
- const file = await driver.readFile(cwd, path, void 0, MAX_IMAGE_BYTES);
4058
- if (file.size <= 16777216) bytes = file.bytes;
4059
- } catch {
4060
- bytes = null;
4061
- }
4062
- if (!bytes) return c.json({ error: "Image unavailable from this host" }, 404);
4063
- return c.body(bytes, 200, {
4064
- "Content-Type": mime,
4065
- "Cache-Control": "private, max-age=86400",
4066
- "Content-Disposition": "inline"
4067
- });
4068
- });
4069
- /** A project's icon (favicon/logo the daemon found in its root), cached briefly per host. */
4070
- app.get("/api/hosts/:host/project-icon", async (c) => {
4071
- const hostId = c.req.param("host");
4072
- const cwd = z.string().min(1).max(4096).parse(c.req.query("cwd"));
4073
- const key = `${hostId}\n${cwd}`;
4074
- let icon = projectIcons.get(key);
4075
- if (icon === void 0) {
4076
- try {
4077
- const result = await hosts.get(hostId).driver.requestProjectIcon(cwd);
4078
- icon = result.icon && /^image\/(png|jpeg|webp|gif|x-icon|vnd\.microsoft\.icon)$/.test(result.icon.mimeType) ? {
4079
- data: Buffer.from(result.icon.data, "base64"),
4080
- mimeType: result.icon.mimeType
4081
- } : null;
4082
- } catch (error) {
4083
- if (error instanceof UnknownHostError) throw error;
4084
- return c.json({ error: "Icon unavailable" }, 502);
4085
- }
4086
- projectIcons.set(key, icon);
4087
- }
4088
- if (!icon) return c.body(null, 204, { "Cache-Control": "private, max-age=600" });
4089
- return c.body(icon.data, 200, {
4090
- "Content-Type": icon.mimeType,
4091
- "Cache-Control": "private, max-age=600"
4092
- });
4093
- });
4094
- /** What the open agent can switch to. Modes/features come from the live directory (no round trip). */
4095
- app.get("/api/hosts/:host/agents/:agent/config", async (c) => {
4096
- const hostId = c.req.param("host");
4097
- const client = hosts.get(hostId);
4098
- const facts = client.directory.facts(c.req.param("agent"));
4099
- if (!facts) return c.json({ error: "Unknown agent" }, 404);
4100
- const options = {
4101
- models: ((await client.api.providers.snapshot()).entries.find((p) => p.provider === facts.provider)?.models ?? []).filter((m) => m.isSelectable !== false).map((m) => ({
4102
- id: m.id,
4103
- label: m.label,
4104
- thinking: (m.thinkingOptions ?? []).map((t) => ({
4105
- id: t.id,
4106
- label: t.label
4107
- })),
4108
- defaultThinkingId: m.defaultThinkingOptionId ?? null
4109
- })),
4110
- modes: facts.availableModes.map((m) => ({
4111
- id: m.id,
4112
- label: m.label,
4113
- ...m.description ? { description: m.description } : {}
4114
- })),
4115
- features: facts.features.map((f) => f.type === "toggle" ? {
4116
- type: "toggle",
4117
- id: f.id,
4118
- label: f.label,
4119
- ...f.tooltip ? { tooltip: f.tooltip } : {},
4120
- value: f.value
4121
- } : {
4122
- type: "select",
4123
- id: f.id,
4124
- label: f.label,
4125
- ...f.tooltip ? { tooltip: f.tooltip } : {},
4126
- value: f.value,
4127
- options: f.options.map((o) => ({
4128
- id: o.id,
4129
- label: o.label
4130
- }))
4131
- })
4132
- };
4133
- return c.json(options);
4134
- });
4135
- app.post("/api/hosts/:host/agents/:agent/config", async (c) => {
4136
- const change = z.object({
4137
- model: z.string().min(1).max(300).optional(),
4138
- thinkingOptionId: z.string().min(1).max(200).optional(),
4139
- modeId: z.string().min(1).max(200).optional(),
4140
- feature: z.object({
4141
- id: z.string().min(1).max(200),
4142
- value: z.union([z.string().max(200), z.boolean()])
4143
- }).optional()
4144
- }).refine((v) => Object.values(v).filter((x) => x !== void 0).length === 1).parse(await c.req.json());
4145
- const { driver } = hosts.get(c.req.param("host"));
4146
- const agent = c.req.param("agent");
4147
- let notice = null;
4148
- if (change.model) await driver.setAgentModel(agent, change.model);
4149
- else if (change.thinkingOptionId) notice = await driver.setAgentThinkingOption(agent, change.thinkingOptionId);
4150
- else if (change.modeId) notice = await driver.setAgentMode(agent, change.modeId);
4151
- else if (change.feature) await driver.setAgentFeature(agent, change.feature.id, change.feature.value);
4152
- return c.json({
4153
- ok: true,
4154
- notice
4155
- });
4156
- });
4157
- /**
4158
- * Speech to text through the transcription service configured here, once for every host. The
4159
- * browser streams PCM over a short-lived socket. The file endpoint remains for older
4160
- * clients. The API key never leaves the server.
4161
- */
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
- });
4172
- app.put("/api/dictation", async (c) => {
4173
- try {
4174
- return c.json(saveDictation(store, await c.req.json()));
4175
- } catch (error) {
4176
- const message = error instanceof z.ZodError ? error.issues[0]?.message ?? "Invalid settings" : error.message;
4177
- return c.json({ error: message }, 400);
4178
- }
4179
- });
4180
- app.delete("/api/dictation", (c) => {
4181
- clearDictation(store);
4182
- return c.json(dictationSettings(store));
4183
- });
4184
- app.post("/api/dictation/transcribe", async (c) => {
4185
- const config = dictationConfig(store);
4186
- if (!config) return c.json({ error: "Voice input is not set up. Add a transcription service in Settings." }, 409);
4187
- const format = /^audio\/pcm;rate=(\d{4,6});bits=16$/.exec(c.req.header("x-audio-format") ?? "");
4188
- if (!format) return c.json({ error: "Unsupported audio format" }, 415);
4189
- const audio = new Uint8Array(await c.req.arrayBuffer());
4190
- if (audio.length < 3200 || audio.length % 2) return c.json({ error: "Recording too short" }, 400);
4191
- try {
4192
- return c.json({ text: await transcribe(config, audio, Number(format[1]), options.fetch) });
4193
- } catch (error) {
4194
- if (error instanceof DictationError) return c.json({ error: error.message }, error.status);
4195
- throw error;
4196
- }
4197
- });
4198
- const attachmentOwner = (c) => c.get("session")?.id ?? "bearer";
4199
- app.get("/api/hosts/:host/agents/:agent/attachments/capabilities", async (c) => c.json(await attachments.capabilities(hosts, c.req.param("host"), c.req.param("agent"))));
4200
- app.post("/api/hosts/:host/agents/:agent/attachments", async (c) => {
4201
- hosts.get(c.req.param("host"));
4202
- try {
4203
- const name = decodeURIComponent(c.req.header("x-file-name") ?? "");
4204
- const mime = c.req.header("content-type")?.split(";")[0] ?? "application/octet-stream";
4205
- return c.json(attachments.put(attachmentOwner(c), c.req.param("host"), c.req.param("agent"), name, mime, Buffer.from(await c.req.arrayBuffer())), 201);
4206
- } catch (error) {
4207
- return c.json({ error: error.message }, 400);
4208
- }
4209
- });
4210
- app.delete("/api/hosts/:host/agents/:agent/attachments/:id", (c) => {
4211
- try {
4212
- attachments.remove(c.req.param("id"), attachmentOwner(c), c.req.param("host"), c.req.param("agent"));
4213
- } catch {
4214
- return c.json({ error: "Attachment already expired or unavailable" }, 404);
4215
- }
4216
- return c.json({ ok: true });
4217
- });
4218
- app.post("/api/hosts/:host/agents/:agent/messages/status", async (c) => {
4219
- const { messageIds } = z.object({ messageIds: z.array(z.string().uuid()).min(1).max(20) }).parse(await c.req.json());
4220
- const { driver } = hosts.get(c.req.param("host"));
4221
- return c.json({ confirmed: await confirmedMessages(driver, c.req.param("agent"), messageIds) });
4222
- });
4223
- app.post("/api/hosts/:host/agents/:agent/messages", async (c) => {
4224
- const input = z.object({
4225
- text: z.string().trim().max(1e5),
4226
- attachmentIds: z.array(z.string().uuid()).max(4).refine((ids) => new Set(ids).size === ids.length).default([]),
4227
- messageId: z.string().uuid(),
4228
- behavior: z.enum(["steer", "interrupt"])
4229
- }).refine((input) => !!input.text || input.attachmentIds.length > 0).parse(await c.req.json());
4230
- let prepared;
4231
- try {
4232
- prepared = await attachments.prepare(hosts, attachmentOwner(c), c.req.param("host"), c.req.param("agent"), input.attachmentIds);
4233
- } catch (error) {
4234
- return c.json({
4235
- error: error.message,
4236
- delivery: "not-sent"
4237
- }, 400);
4238
- }
4239
- try {
4240
- await hosts.get(c.req.param("host")).api.agents.ref(c.req.param("agent")).send(input.text, {
4241
- messageId: input.messageId,
4242
- activeTurnBehavior: input.behavior,
4243
- ...prepared.images.length ? { images: prepared.images } : {},
4244
- ...prepared.attachments.length ? { attachments: prepared.attachments } : {}
4245
- });
4246
- attachments.consumed(input.attachmentIds);
4247
- return c.json({
4248
- status: "acknowledged",
4249
- messageId: input.messageId
4250
- });
4251
- } catch {
4252
- return c.json({
4253
- error: "Delivery outcome unknown. Refresh the conversation before retrying.",
4254
- messageId: input.messageId
4255
- }, 502);
4256
- }
4257
- });
4258
- app.post("/api/hosts/:host/agents/:agent/stop", async (c) => {
4259
- await hosts.get(c.req.param("host")).driver.cancelAgent(c.req.param("agent"));
4260
- return c.json({ status: "acknowledged" });
4261
- });
4262
- app.post("/api/hosts/:host/agents/:agent/permissions/:permission", async (c) => {
4263
- const response = AgentPermissionResponseSchema.parse(await c.req.json());
4264
- const agent = hosts.get(c.req.param("host")).api.agents.ref(c.req.param("agent"));
4265
- await agent.refresh();
4266
- if (!agent.pendingPermissions?.some((p) => p.id === c.req.param("permission"))) return c.json({ error: "Permission no longer pending. Refresh the conversation." }, 409);
4267
- await agent.respondToPermission({
4268
- requestId: c.req.param("permission"),
4269
- response
4270
- });
4271
- return c.json({ status: "acknowledged" });
4272
- });
4273
- /** Marks a settled turn as seen (Paseo's attention flag), moving it out of "review". */
4274
- app.post("/api/hosts/:host/agents/:agent/read", async (c) => {
4275
- await hosts.get(c.req.param("host")).driver.clearAgentAttention(c.req.param("agent"));
4276
- return c.json({ ok: true });
4277
- });
4278
- app.post("/api/hosts/:host/agents/:agent/archive", async (c) => {
4279
- await hosts.get(c.req.param("host")).api.agents.ref(c.req.param("agent")).archive();
4280
- return c.json({ ok: true });
4281
- });
4282
- const workspace = (c) => ({
4283
- driver: hosts.get(c.req.param("host")).driver,
4284
- id: c.req.param("workspace")
4285
- });
4286
- /** Rename; null resets to the name derived from the branch or directory. */
4287
- app.post("/api/hosts/:host/workspaces/:workspace/title", async (c) => {
4288
- const { title } = z.object({ title: z.string().trim().max(200).nullable() }).parse(await c.req.json());
4289
- const { driver, id } = workspace(c);
4290
- await driver.setWorkspaceTitle(id, title ? title : null);
4291
- return c.json({ ok: true });
4292
- });
4293
- app.post("/api/hosts/:host/workspaces/:workspace/pin", async (c) => {
4294
- const { pinned } = z.object({ pinned: z.boolean() }).parse(await c.req.json());
4295
- const { driver, id } = workspace(c);
4296
- await driver.setWorkspacePinned(id, pinned);
4297
- return c.json({ ok: true });
4298
- });
4299
- app.post("/api/hosts/:host/workspaces/:workspace/unread", async (c) => {
4300
- const { driver, id } = workspace(c);
4301
- await driver.markWorkspaceUnread(id);
4302
- return c.json({ ok: true });
4303
- });
4304
- app.post("/api/hosts/:host/workspaces/:workspace/read", async (c) => {
4305
- const { driver, id } = workspace(c);
4306
- await driver.clearWorkspaceAttention(id);
4307
- return c.json({ ok: true });
4308
- });
4309
- app.post("/api/hosts/:host/workspaces/:workspace/archive", async (c) => {
4310
- const { driver, id } = workspace(c);
4311
- await driver.archiveWorkspace(id);
4312
- return c.json({ ok: true });
4313
- });
4314
- /**
4315
- * next-input: the daemon appends a placeholder row after a completed turn; prediction runs only
4316
- * when a client that shows the row asks. Only this one plugin method is reachable from here.
4317
- */
4318
- app.post("/api/hosts/:host/agents/:agent/suggestion", async (c) => {
4319
- const { token } = z.object({ token: z.string().min(1).max(200) }).parse(await c.req.json());
973
+ }
974
+ revoke(sessionId) {
975
+ this.store.revokeSessions(sessionId);
976
+ }
977
+ beginTotp(sessionId, now = Date.now()) {
978
+ if (this.totpEnabled()) throw new Error("Disable the current authenticator before replacing it");
979
+ const secret = base32Encode(randomBytes(20));
980
+ this.pendingTotp = {
981
+ secret,
982
+ sessionId,
983
+ expires: now + 6e5
984
+ };
985
+ return {
986
+ secret,
987
+ uri: `otpauth://totp/LitePaseo?secret=${secret}&issuer=LitePaseo&algorithm=SHA1&digits=6&period=30`
988
+ };
989
+ }
990
+ /** Enables the pending secret once the user proves their app produces matching codes. */
991
+ confirmTotp(sessionId, code, now = Date.now()) {
992
+ if (this.totpEnabled()) return false;
993
+ const pending = this.pendingTotp;
994
+ if (!pending || pending.sessionId !== sessionId || pending.expires < now) return false;
995
+ const step = matchTotp(base32Decode(pending.secret), code, now);
996
+ if (step === null) return false;
997
+ this.store.db.exec("BEGIN IMMEDIATE");
4320
998
  try {
4321
- const output = await hosts.get(c.req.param("host")).driver.invokePluginRpc("next-input", "suggestions.predict", {
4322
- agentId: c.req.param("agent"),
4323
- token
4324
- });
4325
- return c.json({
4326
- status: String(output?.status ?? "error"),
4327
- text: String(output?.text ?? "")
4328
- });
999
+ this.store.setSetting("totp_secret", pending.secret);
1000
+ this.store.setSetting("totp_last_step", String(step));
1001
+ this.store.db.prepare("DELETE FROM push_subscriptions WHERE session_id<>?").run(sessionId);
1002
+ this.store.db.prepare("DELETE FROM sessions WHERE id<>?").run(sessionId);
1003
+ this.resetCodeLimit();
1004
+ this.store.db.exec("COMMIT");
4329
1005
  } catch (error) {
4330
- if (error instanceof UnknownHostError) throw error;
4331
- return c.json({
4332
- status: "unavailable",
4333
- text: ""
4334
- });
1006
+ this.store.db.exec("ROLLBACK");
1007
+ throw error;
4335
1008
  }
4336
- });
4337
- registerWorkspaceRoutes(app, hosts, store, (c) => streamValidity(c));
4338
- app.get("/api/usage", async (c) => c.json(await usage.report(c.req.query("refresh") === "1")));
4339
- app.get("/api/board", (c) => c.json(store.board()));
4340
- app.put("/api/board", async (c) => {
4341
- const b = z.object({
4342
- revision: z.number().int().nonnegative(),
4343
- cards: z.array(card).max(1e3)
4344
- }).parse(await c.req.json());
4345
- if (new Set(b.cards.map((c) => c.id)).size !== b.cards.length) return c.json({ error: "Duplicate card ID" }, 400);
4346
- if (!store.saveBoard(b.revision, b.cards)) return c.json({ error: "Board changed. Reload before editing." }, 409);
4347
- return c.json(store.board());
4348
- });
4349
- app.all("/api/*", (c) => c.json({ error: "Not found" }, 404));
4350
- for (const [file, type] of [["sw.js", "text/javascript; charset=utf-8"], ["manifest.webmanifest", "application/manifest+json"]]) app.get("/" + file, (c) => {
4351
- try {
4352
- return c.body(readFileSync(join(webRoot, file)), 200, {
4353
- "Content-Type": type,
4354
- "Cache-Control": "no-cache"
4355
- });
4356
- } catch {
4357
- return c.notFound();
1009
+ this.pendingTotp = null;
1010
+ return true;
1011
+ }
1012
+ disableTotp(code, now = Date.now()) {
1013
+ if (this.limited("settings", true, now)) return false;
1014
+ const secret = this.store.setting("totp_secret");
1015
+ const step = secret ? matchTotp(base32Decode(secret), code, now) : null;
1016
+ if (step === null || !this.store.advanceSetting("totp_last_step", step)) {
1017
+ this.fail("settings", true, now);
1018
+ return false;
4358
1019
  }
4359
- });
4360
- app.use("/assets/*", async (c, next) => {
4361
- await next();
4362
- if (c.res.ok) c.header("Cache-Control", "public, max-age=31536000, immutable");
4363
- });
4364
- app.use("/*", async (c, next) => {
4365
- await next();
4366
- if (c.res.headers.get("Content-Type")?.startsWith("text/html")) c.header("Cache-Control", "no-cache");
4367
- });
4368
- app.use("/*", serveStatic({
4369
- root: webRoot,
4370
- precompressed: true
4371
- }));
4372
- return Object.assign(app, {
4373
- dictationStreams,
4374
- /** Open directory streams; lets tests prove that disconnects release them. */
4375
- openStreams: () => directoryStreams.size,
4376
- dispose: () => {
4377
- disposed = true;
4378
- clearTimeout(agentFlush);
4379
- clearTimeout(hostFlush);
4380
- agentFlush = hostFlush = void 0;
4381
- attachments.close();
4382
- dictationStreams.close();
1020
+ this.store.setSetting("totp_secret", null);
1021
+ this.resetCodeLimit();
1022
+ return true;
1023
+ }
1024
+ resetCodeLimit() {
1025
+ this.global = {
1026
+ count: 0,
1027
+ reset: 0,
1028
+ lockMs: WINDOW_MS
1029
+ };
1030
+ this.store.setSetting("totp_login_limit", JSON.stringify(this.global));
1031
+ }
1032
+ limited(client, usesCode, now) {
1033
+ if (usesCode && this.global.reset > now && this.global.count >= MAX_CODE_FAILURES_GLOBAL) return Math.ceil((this.global.reset - now) / 1e3);
1034
+ const map = usesCode ? this.codeFailures : this.tokenFailures;
1035
+ if (!map.has(client) && map.size >= 1e4) client = "overflow";
1036
+ const entry = map.get(client);
1037
+ const max = usesCode ? MAX_CODE_FAILURES_PER_CLIENT : MAX_TOKEN_FAILURES_PER_CLIENT;
1038
+ if (entry && entry.reset > now && entry.count >= max) return Math.ceil((entry.reset - now) / 1e3);
1039
+ return 0;
1040
+ }
1041
+ fail(client, usesCode, now) {
1042
+ if (usesCode) {
1043
+ if (this.global.reset <= now) this.global.count = 0;
1044
+ this.global.count++;
1045
+ if (this.global.count === MAX_CODE_FAILURES_GLOBAL) {
1046
+ this.global.reset = now + this.global.lockMs;
1047
+ this.global.lockMs = Math.min(this.global.lockMs * 2, MAX_LOCK_MS);
1048
+ } else if (this.global.reset <= now) this.global.reset = now + WINDOW_MS;
1049
+ this.store.setSetting("totp_login_limit", JSON.stringify(this.global));
4383
1050
  }
4384
- });
4385
- }
1051
+ const map = usesCode ? this.codeFailures : this.tokenFailures;
1052
+ if (!map.has(client) && map.size >= 1e4) client = "overflow";
1053
+ let entry = map.get(client);
1054
+ if (!entry || entry.reset <= now) map.set(client, entry = {
1055
+ count: 0,
1056
+ reset: now + WINDOW_MS
1057
+ });
1058
+ entry.count++;
1059
+ }
1060
+ };
4386
1061
  // src/server/config.ts
4387
1062
  /**
4388
1063
  * Settings that used to need an environment variable on every start. `litepaseo config set`
@@ -4452,213 +1127,6 @@ function effectiveConfig(store, env) {
4452
1127
  });
4453
1128
  return Object.fromEntries(entries.map((entry) => [entry.key, entry]));
4454
1129
  }
4455
- // src/server/worker.ts
4456
- async function runWorker(directory, webRoot) {
4457
- if (!process.send) throw new Error("worker is an internal supervised command");
4458
- const tokenPath = join(directory, "token");
4459
- if (!existsSync(tokenPath)) writeFileSync(tokenPath, generateToken(), {
4460
- mode: 384,
4461
- flag: "wx"
4462
- });
4463
- const store = new Store(directory), hosts = new Hosts();
4464
- for (const host of store.hosts()) try {
4465
- hosts.add(host);
4466
- } catch {
4467
- console.error("Could not initialize host", host.id);
4468
- }
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 });
4472
- const server = serve({
4473
- fetch: app.fetch,
4474
- port,
4475
- hostname
4476
- });
4477
- app.dictationStreams.attach(server);
4478
- let stopping = false;
4479
- const shutdown = async () => {
4480
- if (stopping) return;
4481
- stopping = true;
4482
- setTimeout(() => process.exit(1), 5e3).unref();
4483
- app.dispose();
4484
- await hosts.close();
4485
- if ("closeAllConnections" in server) server.closeAllConnections();
4486
- await new Promise((resolve) => server.close(() => resolve()));
4487
- store.close();
4488
- if (process.connected) process.disconnect();
4489
- };
4490
- process.once("SIGINT", () => void shutdown());
4491
- process.once("SIGTERM", () => void shutdown());
4492
- process.once("disconnect", () => void shutdown());
4493
- server.once("error", (error) => {
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;
4495
- console.error(message);
4496
- process.send?.({
4497
- type: "fatal",
4498
- error: message
4499
- });
4500
- process.exitCode = 1;
4501
- shutdown();
4502
- });
4503
- server.once("listening", () => {
4504
- const address = server.address();
4505
- const actualPort = typeof address === "object" && address ? address.port : port;
4506
- const url = `http://${hostname}:${actualPort}`;
4507
- console.log(`LitePaseo ready at ${url}`);
4508
- process.send?.({
4509
- type: "ready",
4510
- url
4511
- });
4512
- });
4513
- }
4514
- // src/server/backup.ts
4515
- const FILES = ["litepaseo.sqlite", "token"];
4516
- const digest = (path) => createHash("sha256").update(readFileSync(path)).digest("hex");
4517
- /** A consistent SQLite snapshot includes committed WAL data; never copy a live database file. */
4518
- function backup(directory, destination) {
4519
- destination = resolve(destination);
4520
- if (!existsSync(join(directory, FILES[0])) || !existsSync(join(directory, "token"))) throw new Error("No initialized LitePaseo data to back up.");
4521
- mkdirSync(destination, { mode: 448 });
4522
- let store;
4523
- try {
4524
- store = new Store(directory);
4525
- store.db.prepare("VACUUM INTO ?").run(join(destination, FILES[0]));
4526
- copyFileSync(join(directory, "token"), join(destination, "token"), constants.COPYFILE_EXCL);
4527
- for (const file of FILES) chmodSync(join(destination, file), 384);
4528
- writeFileSync(join(destination, "manifest.json"), JSON.stringify({
4529
- format: 1,
4530
- schema: 1,
4531
- created: (/* @__PURE__ */ new Date()).toISOString(),
4532
- files: Object.fromEntries(FILES.map((file) => [file, digest(join(destination, file))]))
4533
- }, null, 2) + "\n", {
4534
- mode: 384,
4535
- flag: "wx"
4536
- });
4537
- } catch (error) {
4538
- rmSync(destination, {
4539
- recursive: true,
4540
- force: true
4541
- });
4542
- throw error;
4543
- } finally {
4544
- store?.close();
4545
- }
4546
- }
4547
- /** Restore only into an empty home; the same exclusive socket binding prevents concurrent startup. */
4548
- async function restore(source, directory) {
4549
- source = resolve(source);
4550
- mkdirSync(directory, {
4551
- recursive: true,
4552
- mode: 448
4553
- });
4554
- chmodSync(directory, 448);
4555
- const releaseRuntime = acquireRuntimeLock(directory);
4556
- const lock = createServer((socket) => socket.destroy());
4557
- await new Promise((resolve, reject) => {
4558
- lock.once("error", reject);
4559
- lock.listen(join(directory, "control.sock"), resolve);
4560
- }).catch((error) => {
4561
- releaseRuntime();
4562
- throw error;
4563
- });
4564
- const stage = join(directory, ".restore-staging");
4565
- let ownsStage = false;
4566
- try {
4567
- if (readdirSync(directory).some((file) => file !== "control.sock" && file !== "service-lock.sqlite" && file !== "service-lock.sqlite-journal")) throw new Error("Restore requires an empty LITEPASEO_HOME. Restore to a new directory, then start it.");
4568
- mkdirSync(stage, { mode: 448 });
4569
- ownsStage = true;
4570
- const manifest = JSON.parse(readFileSync(join(source, "manifest.json"), "utf8"));
4571
- if (manifest.format !== 1 || manifest.schema !== 1) throw new Error("Unsupported backup format or schema version.");
4572
- for (const file of FILES) {
4573
- copyFileSync(join(source, file), join(stage, file), constants.COPYFILE_EXCL);
4574
- chmodSync(join(stage, file), 384);
4575
- if (manifest.files?.[file] !== digest(join(stage, file))) throw new Error(`Backup checksum failed: ${file}`);
4576
- }
4577
- const db = new DatabaseSync(join(stage, FILES[0]), { readOnly: true });
4578
- try {
4579
- if (schemaVersion(db) !== 1 || db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("Backup database failed validation.");
4580
- for (const table of [
4581
- "hosts",
4582
- "board",
4583
- "settings",
4584
- "sessions",
4585
- "push_subscriptions"
4586
- ]) db.prepare(`SELECT * FROM ${table} LIMIT 0`).all();
4587
- } finally {
4588
- db.close();
4589
- }
4590
- if (!/^[\x21-\x7e]{1,200}$/.test(readFileSync(join(stage, "token"), "utf8").trim())) throw new Error("Invalid backup access token.");
4591
- writeFileSync(join(directory, ".restore-incomplete"), "Restore interrupted: restore the backup to a fresh home.\n", {
4592
- mode: 384,
4593
- flag: "wx"
4594
- });
4595
- renameSync(join(stage, "token"), join(directory, "token"));
4596
- renameSync(join(stage, FILES[0]), join(directory, FILES[0]));
4597
- rmSync(join(directory, ".restore-incomplete"));
4598
- } finally {
4599
- if (ownsStage) rmSync(stage, {
4600
- recursive: true,
4601
- force: true
4602
- });
4603
- await new Promise((resolve) => lock.close(() => resolve()));
4604
- releaseRuntime();
4605
- }
4606
- }
4607
- // src/server/data-dir.ts
4608
- /** Locations before ~/.litepaseo: the platform data directories. */
4609
- function legacyDirectory(env, home, platform) {
4610
- return platform === "darwin" ? join(home, "Library/Application Support/LitePaseo") : join(env.XDG_DATA_HOME ?? join(home, ".local/share"), "litepaseo");
4611
- }
4612
- /** Whether a LitePaseo process answers on this control socket. */
4613
- function socketIsLive(path, timeoutMs = 500) {
4614
- return new Promise((done) => {
4615
- if (!existsSync(path)) return done(false);
4616
- const s = connect(path);
4617
- const finish = (live) => {
4618
- s.destroy();
4619
- done(live);
4620
- };
4621
- s.setTimeout(timeoutMs, () => finish(false));
4622
- s.once("connect", () => finish(true));
4623
- s.once("error", () => finish(false));
4624
- });
4625
- }
4626
- /**
4627
- * LitePaseo keeps everything in one directory, like Paseo's ~/.paseo: ~/.litepaseo, or
4628
- * LITEPASEO_HOME (LITEPASEO_DATA_DIR still works). Data from the old platform location moves
4629
- * over once, but never out from under a running instance: that one keeps its directory until
4630
- * it is stopped.
4631
- */
4632
- async function resolveDataDirectory(env, home, platform, isLive = socketIsLive) {
4633
- const configured = env.LITEPASEO_HOME || env.LITEPASEO_DATA_DIR;
4634
- if (configured) return { directory: resolve(configured) };
4635
- const target = join(home, ".litepaseo");
4636
- const legacy = legacyDirectory(env, home, platform);
4637
- if (!existsSync(legacy) || existsSync(target)) return { directory: target };
4638
- if (await isLive(join(legacy, "control.sock"))) return {
4639
- directory: legacy,
4640
- notice: `LitePaseo is running from ${legacy}. Run "litepaseo stop", then start it again to move its data to ${target}.`
4641
- };
4642
- try {
4643
- renameSync(legacy, target);
4644
- } catch (error) {
4645
- if (error.code !== "EXDEV") throw error;
4646
- cpSync(legacy, target, {
4647
- recursive: true,
4648
- preserveTimestamps: true
4649
- });
4650
- rmSync(legacy, {
4651
- recursive: true,
4652
- force: true
4653
- });
4654
- }
4655
- const socket = join(target, "control.sock");
4656
- if (existsSync(socket)) unlinkSync(socket);
4657
- return {
4658
- directory: target,
4659
- notice: `Moved LitePaseo data from ${legacy} to ${target}.`
4660
- };
4661
- }
4662
1130
  // src/server/cli-format.ts
4663
1131
  const json = {
4664
1132
  name: "json",
@@ -5245,7 +1713,11 @@ async function version(args) {
5245
1713
  async function run() {
5246
1714
  if (name === "--version" || name === "-v" || name === "-V") return console.log(VERSION);
5247
1715
  if (name === "--help" || name === "-h") return console.log(mainHelp(VERSION, displayDirectory(), out));
5248
- if (name === "worker") return runWorker((await dataDirectory()).directory, fileURLToPath(new URL("../web/", import.meta.url)));
1716
+ if (name === "worker") {
1717
+ const paths = await dataDirectory();
1718
+ const { runWorker } = await import("./worker-BxtQnBVZ.mjs");
1719
+ return runWorker(paths.directory, fileURLToPath(new URL("../web/", import.meta.url)));
1720
+ }
5249
1721
  const command = findCommand(name);
5250
1722
  if (!command) {
5251
1723
  const guess = suggest(name, COMMANDS.map((c) => c.name));
@@ -5335,4 +1807,4 @@ run().catch(async (error) => {
5335
1807
  } catch {}
5336
1808
  process.exitCode = 1;
5337
1809
  });
5338
- export {};
1810
+ export { tokenFile as a, generateToken as i, Auth as n, Store as o, SESSION_TTL_MS as r, VERSION as s, effectiveConfig as t };