litepaseo 0.4.1 → 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.
- package/CHANGELOG.md +20 -0
- package/dist/server/cli.mjs +238 -3847
- package/dist/server/worker-BxtQnBVZ.mjs +3619 -0
- package/dist/web/assets/{CodeBlockNode-fA2JfqDc.js → CodeBlockNode-Dg9n5ezc.js} +1 -1
- package/dist/web/assets/CodeBlockNode-Dg9n5ezc.js.br +0 -0
- package/dist/web/assets/CodeBlockNode-Dg9n5ezc.js.gz +0 -0
- package/dist/web/assets/{FileViewer-BNuFtV2I.js → FileViewer-BqAUo_AP.js} +1 -1
- package/dist/web/assets/FileViewer-BqAUo_AP.js.br +0 -0
- package/dist/web/assets/FileViewer-BqAUo_AP.js.gz +0 -0
- package/dist/web/assets/{FilesPanel-DSjOF49-.js → FilesPanel-Bl65Hz3k.js} +1 -1
- package/dist/web/assets/FilesPanel-Bl65Hz3k.js.br +0 -0
- package/dist/web/assets/FilesPanel-Bl65Hz3k.js.gz +0 -0
- package/dist/web/assets/{MarkdownMessage-D-TUJHkh.js → MarkdownMessage-j-M1z3-u.js} +5 -5
- package/dist/web/assets/MarkdownMessage-j-M1z3-u.js.br +0 -0
- package/dist/web/assets/MarkdownMessage-j-M1z3-u.js.gz +0 -0
- package/dist/web/assets/{PreCodeBlock-BW4D63KE.js → PreCodeBlock-B8fBuBdP.js} +1 -1
- package/dist/web/assets/{PreCodeBlock.vue_vue_type_style_index_0_lang-D4scN_Wl.js → PreCodeBlock.vue_vue_type_style_index_0_lang-Cj9vGyzE.js} +1 -1
- package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Cj9vGyzE.js.br +0 -0
- package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Cj9vGyzE.js.gz +0 -0
- package/dist/web/assets/TerminalPanel-ZkVJFLM1.js +3 -0
- package/dist/web/assets/TerminalPanel-ZkVJFLM1.js.br +0 -0
- package/dist/web/assets/TerminalPanel-ZkVJFLM1.js.gz +0 -0
- package/dist/web/assets/{TerminalPanel-DvfBWyiQ.css → TerminalPanel-mJ-uVP4H.css} +1 -1
- package/dist/web/assets/TerminalPanel-mJ-uVP4H.css.br +0 -0
- package/dist/web/assets/TerminalPanel-mJ-uVP4H.css.gz +0 -0
- package/dist/web/assets/{Tooltip-BQL5bLOR.js → Tooltip-Jdp8zjwT.js} +1 -1
- package/dist/web/assets/Tooltip-Jdp8zjwT.js.br +0 -0
- package/dist/web/assets/Tooltip-Jdp8zjwT.js.gz +0 -0
- package/dist/web/assets/addon-unicode11-C82cyeHQ.js +7 -0
- package/dist/web/assets/addon-unicode11-C82cyeHQ.js.br +0 -0
- package/dist/web/assets/addon-unicode11-C82cyeHQ.js.gz +0 -0
- package/dist/web/assets/addon-webgl-C3a5wC6k.js +64 -0
- package/dist/web/assets/addon-webgl-C3a5wC6k.js.br +0 -0
- package/dist/web/assets/addon-webgl-C3a5wC6k.js.gz +0 -0
- package/dist/web/assets/index-Cf1QB007.js +32 -0
- package/dist/web/assets/index-Cf1QB007.js.br +0 -0
- package/dist/web/assets/index-Cf1QB007.js.gz +0 -0
- package/dist/web/assets/{index10-D4jsjrRO.js → index10-EuskhiaE.js} +1 -1
- package/dist/web/assets/index10-EuskhiaE.js.br +0 -0
- package/dist/web/assets/index10-EuskhiaE.js.gz +0 -0
- package/dist/web/assets/index3-bqHD_tAN.js +1 -0
- package/dist/web/assets/index4-CnpLIN0Y.js +1 -0
- package/dist/web/assets/{index5-C3CXhRn6.js → index5-CIMd5e5U.js} +1 -1
- package/dist/web/assets/index5-CIMd5e5U.js.br +0 -0
- package/dist/web/assets/index5-CIMd5e5U.js.gz +0 -0
- package/dist/web/assets/{index6-cJmwBOxX.js → index6-DrnWk0rr.js} +1 -1
- package/dist/web/assets/index6-DrnWk0rr.js.br +0 -0
- package/dist/web/assets/index6-DrnWk0rr.js.gz +0 -0
- package/dist/web/assets/{index7-CzuTZoqm.js → index7-BCl4u4Ci.js} +1 -1
- package/dist/web/assets/index7-BCl4u4Ci.js.br +0 -0
- package/dist/web/assets/index7-BCl4u4Ci.js.gz +0 -0
- package/dist/web/assets/{index8-COvW1lHu.js → index8-tfhmdpKZ.js} +1 -1
- package/dist/web/assets/index8-tfhmdpKZ.js.br +0 -0
- package/dist/web/assets/index8-tfhmdpKZ.js.gz +0 -0
- package/dist/web/assets/{index9-CJgpHg38.js → index9-Co0BXJFT.js} +1 -1
- package/dist/web/assets/index9-Co0BXJFT.js.br +0 -0
- package/dist/web/assets/index9-Co0BXJFT.js.gz +0 -0
- package/dist/web/index.html +1 -1
- package/dist/web/index.html.br +0 -0
- package/dist/web/index.html.gz +0 -0
- package/package.json +5 -3
- package/dist/web/assets/CodeBlockNode-fA2JfqDc.js.br +0 -0
- package/dist/web/assets/CodeBlockNode-fA2JfqDc.js.gz +0 -0
- package/dist/web/assets/FileViewer-BNuFtV2I.js.br +0 -0
- package/dist/web/assets/FileViewer-BNuFtV2I.js.gz +0 -0
- package/dist/web/assets/FilesPanel-DSjOF49-.js.br +0 -0
- package/dist/web/assets/FilesPanel-DSjOF49-.js.gz +0 -0
- package/dist/web/assets/MarkdownMessage-D-TUJHkh.js.br +0 -0
- package/dist/web/assets/MarkdownMessage-D-TUJHkh.js.gz +0 -0
- package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-D4scN_Wl.js.br +0 -0
- package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-D4scN_Wl.js.gz +0 -0
- package/dist/web/assets/TerminalPanel-CmsmhtfJ.js +0 -3
- package/dist/web/assets/TerminalPanel-CmsmhtfJ.js.br +0 -0
- package/dist/web/assets/TerminalPanel-CmsmhtfJ.js.gz +0 -0
- package/dist/web/assets/TerminalPanel-DvfBWyiQ.css.br +0 -0
- package/dist/web/assets/TerminalPanel-DvfBWyiQ.css.gz +0 -0
- package/dist/web/assets/Tooltip-BQL5bLOR.js.br +0 -0
- package/dist/web/assets/Tooltip-BQL5bLOR.js.gz +0 -0
- package/dist/web/assets/index-B0E-zIZw.js +0 -32
- package/dist/web/assets/index-B0E-zIZw.js.br +0 -0
- package/dist/web/assets/index-B0E-zIZw.js.gz +0 -0
- package/dist/web/assets/index10-D4jsjrRO.js.br +0 -0
- package/dist/web/assets/index10-D4jsjrRO.js.gz +0 -0
- package/dist/web/assets/index3-CnYNShe0.js +0 -1
- package/dist/web/assets/index4-C7heBMis.js +0 -1
- package/dist/web/assets/index5-C3CXhRn6.js.br +0 -0
- package/dist/web/assets/index5-C3CXhRn6.js.gz +0 -0
- package/dist/web/assets/index6-cJmwBOxX.js.br +0 -0
- package/dist/web/assets/index6-cJmwBOxX.js.gz +0 -0
- package/dist/web/assets/index7-CzuTZoqm.js.br +0 -0
- package/dist/web/assets/index7-CzuTZoqm.js.gz +0 -0
- package/dist/web/assets/index8-COvW1lHu.js.br +0 -0
- package/dist/web/assets/index8-COvW1lHu.js.gz +0 -0
- package/dist/web/assets/index9-CJgpHg38.js.br +0 -0
- package/dist/web/assets/index9-CJgpHg38.js.gz +0 -0
package/dist/server/cli.mjs
CHANGED
|
@@ -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 {
|
|
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 {
|
|
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.
|
|
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 {
|
|
@@ -592,1770 +577,178 @@ var Store = class {
|
|
|
592
577
|
this.db.close();
|
|
593
578
|
}
|
|
594
579
|
};
|
|
595
|
-
// src/server/
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
if (/enotfound|eai_again|dns/.test(text)) return {
|
|
618
|
-
code: "dns",
|
|
619
|
-
message: "Host name could not be resolved. Check the address and DNS."
|
|
620
|
-
};
|
|
621
|
-
if (/econnrefused|connection refused/.test(text)) return {
|
|
622
|
-
code: "refused",
|
|
623
|
-
message: "Connection refused. Check that the daemon is running and the port is reachable."
|
|
624
|
-
};
|
|
625
|
-
if (/timed?.?out|timeout/.test(text)) return {
|
|
626
|
-
code: "timeout",
|
|
627
|
-
message: "Connection timed out. Check the network, tunnel and firewall."
|
|
628
|
-
};
|
|
629
|
-
if (/cert|tls|ssl/.test(text)) return {
|
|
630
|
-
code: "tls",
|
|
631
|
-
message: "Secure connection failed. Check the server certificate and TLS configuration."
|
|
632
|
-
};
|
|
633
|
-
return {
|
|
634
|
-
code: "disconnected",
|
|
635
|
-
message: "Connection lost. Check the daemon, network and connection settings."
|
|
636
|
-
};
|
|
637
|
-
}
|
|
638
|
-
// src/server/versioned-collection.ts
|
|
639
|
-
/**
|
|
640
|
-
* Keyed values ordered by their last change. Every write moves the entry to the tail, so
|
|
641
|
-
* `changesSince(seq)` walks back only over entries changed after `seq`: O(changes), never
|
|
642
|
-
* O(collection). Deletions stay as tombstones until the bounded tombstone budget evicts them;
|
|
643
|
-
* readers older than the evicted horizon (`floor`) must take a snapshot instead.
|
|
644
|
-
*/
|
|
645
|
-
var VersionedCollection = class {
|
|
646
|
-
generation = randomUUID();
|
|
647
|
-
nodes = /* @__PURE__ */ new Map();
|
|
648
|
-
head = null;
|
|
649
|
-
tail = null;
|
|
650
|
-
current = 0;
|
|
651
|
-
floor = 0;
|
|
652
|
-
live = 0;
|
|
653
|
-
tombstones = [];
|
|
654
|
-
tombstoneHead = 0;
|
|
655
|
-
maxTombstones;
|
|
656
|
-
constructor(maxTombstones = 4096) {
|
|
657
|
-
this.maxTombstones = maxTombstones;
|
|
658
|
-
}
|
|
659
|
-
get seq() {
|
|
660
|
-
return this.current;
|
|
661
|
-
}
|
|
662
|
-
get size() {
|
|
663
|
-
return this.live;
|
|
664
|
-
}
|
|
665
|
-
get(key) {
|
|
666
|
-
const node = this.nodes.get(key);
|
|
667
|
-
return node && node.value !== null ? node.value : void 0;
|
|
668
|
-
}
|
|
669
|
-
set(key, value) {
|
|
670
|
-
let node = this.nodes.get(key);
|
|
671
|
-
if (node) {
|
|
672
|
-
if (node.value === null) this.live++;
|
|
673
|
-
this.unlink(node);
|
|
674
|
-
} else {
|
|
675
|
-
node = {
|
|
676
|
-
key,
|
|
677
|
-
value,
|
|
678
|
-
seq: 0,
|
|
679
|
-
prev: null,
|
|
680
|
-
next: null
|
|
681
|
-
};
|
|
682
|
-
this.nodes.set(key, node);
|
|
683
|
-
this.live++;
|
|
684
|
-
}
|
|
685
|
-
node.value = value;
|
|
686
|
-
node.seq = ++this.current;
|
|
687
|
-
this.append(node);
|
|
688
|
-
}
|
|
689
|
-
delete(key) {
|
|
690
|
-
const node = this.nodes.get(key);
|
|
691
|
-
if (!node || node.value === null) return false;
|
|
692
|
-
this.live--;
|
|
693
|
-
node.value = null;
|
|
694
|
-
node.seq = ++this.current;
|
|
695
|
-
this.unlink(node);
|
|
696
|
-
this.append(node);
|
|
697
|
-
this.tombstones.push({
|
|
698
|
-
node,
|
|
699
|
-
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"
|
|
700
602
|
});
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
changesSince(after) {
|
|
706
|
-
if (after < this.floor || after > this.current) return null;
|
|
707
|
-
const out = [];
|
|
708
|
-
for (let node = this.tail; node && node.seq > after; node = node.prev) out.push({
|
|
709
|
-
key: node.key,
|
|
710
|
-
value: node.value
|
|
603
|
+
} catch (error) {
|
|
604
|
+
rmSync(destination, {
|
|
605
|
+
recursive: true,
|
|
606
|
+
force: true
|
|
711
607
|
});
|
|
712
|
-
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
snapshot() {
|
|
716
|
-
const out = [];
|
|
717
|
-
for (let node = this.head; node; node = node.next) if (node.value !== null) out.push(node.value);
|
|
718
|
-
return out;
|
|
608
|
+
throw error;
|
|
609
|
+
} finally {
|
|
610
|
+
store?.close();
|
|
719
611
|
}
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
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}`);
|
|
731
642
|
}
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
else this.head = node;
|
|
745
|
-
this.tail = node;
|
|
746
|
-
}
|
|
747
|
-
};
|
|
748
|
-
// src/server/host-directory.ts
|
|
749
|
-
const PAGE = 200;
|
|
750
|
-
const RETRY_MS$1 = 2e3;
|
|
751
|
-
const basename$1 = (path) => path.replace(/\/+$/, "").split("/").pop() || path;
|
|
752
|
-
const time = (value) => value ? Date.parse(value) || 0 : 0;
|
|
753
|
-
/**
|
|
754
|
-
* Mirrors one daemon directory into a shared collection. After the first snapshot it consumes
|
|
755
|
-
* only update deltas; reconnects resume from the daemon's directory-sync cursor, so
|
|
756
|
-
* steady-state cost is proportional to changes. Summaries that did not change are dropped.
|
|
757
|
-
*/
|
|
758
|
-
var HostMirror = class {
|
|
759
|
-
cursor;
|
|
760
|
-
members = /* @__PURE__ */ new Map();
|
|
761
|
-
subscription = null;
|
|
762
|
-
token = 0;
|
|
763
|
-
stopStatus = null;
|
|
764
|
-
retry;
|
|
765
|
-
/** Items touched by live updates while a paged (non-sync) snapshot is being read. */
|
|
766
|
-
liveTouched = null;
|
|
767
|
-
adapter;
|
|
768
|
-
hostId;
|
|
769
|
-
driver;
|
|
770
|
-
collection;
|
|
771
|
-
changed;
|
|
772
|
-
transition;
|
|
773
|
-
constructor(adapter, hostId, driver, collection, changed, transition = () => {}) {
|
|
774
|
-
this.adapter = adapter;
|
|
775
|
-
this.hostId = hostId;
|
|
776
|
-
this.driver = driver;
|
|
777
|
-
this.collection = collection;
|
|
778
|
-
this.changed = changed;
|
|
779
|
-
this.transition = transition;
|
|
780
|
-
}
|
|
781
|
-
/** What the adapter retained for a member, from the latest update; O(1). */
|
|
782
|
-
retained(id) {
|
|
783
|
-
return this.members.get(id)?.retained;
|
|
784
|
-
}
|
|
785
|
-
start() {
|
|
786
|
-
this.stopStatus = this.driver.subscribeConnectionStatus((state) => this.onStatus(state.status));
|
|
787
|
-
this.onStatus(this.driver.getConnectionState().status);
|
|
788
|
-
}
|
|
789
|
-
dispose() {
|
|
790
|
-
const released = this.close();
|
|
791
|
-
this.stopStatus?.();
|
|
792
|
-
for (const [id, member] of this.members) {
|
|
793
|
-
this.collection.delete(this.key(id));
|
|
794
|
-
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();
|
|
795
655
|
}
|
|
796
|
-
if (
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
key(id) {
|
|
801
|
-
return `${this.hostId}:${id}`;
|
|
802
|
-
}
|
|
803
|
-
onStatus(status) {
|
|
804
|
-
if (status === "connected") {
|
|
805
|
-
if (!this.subscription) this.open();
|
|
806
|
-
} else this.close();
|
|
807
|
-
}
|
|
808
|
-
open() {
|
|
809
|
-
clearTimeout(this.retry);
|
|
810
|
-
const token = ++this.token;
|
|
811
|
-
const sync = this.driver.getLastServerInfoMessage()?.features?.directorySync === true;
|
|
812
|
-
const { base } = this.adapter;
|
|
813
|
-
const subscription = this.adapter.observe(this.driver, sync ? {
|
|
814
|
-
...base,
|
|
815
|
-
sync: this.cursor ?? {}
|
|
816
|
-
} : {
|
|
817
|
-
...base,
|
|
818
|
-
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"
|
|
819
660
|
});
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
},
|
|
828
|
-
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
|
|
829
668
|
});
|
|
669
|
+
await new Promise((resolve) => lock.close(() => resolve()));
|
|
670
|
+
releaseRuntime();
|
|
830
671
|
}
|
|
831
|
-
close() {
|
|
832
|
-
this.token++;
|
|
833
|
-
clearTimeout(this.retry);
|
|
834
|
-
this.liveTouched = null;
|
|
835
|
-
const subscription = this.subscription;
|
|
836
|
-
this.subscription = null;
|
|
837
|
-
return subscription?.release().catch(() => {}) ?? Promise.resolve();
|
|
838
|
-
}
|
|
839
|
-
fail(token) {
|
|
840
|
-
if (token !== this.token) return;
|
|
841
|
-
this.close();
|
|
842
|
-
this.cursor = void 0;
|
|
843
|
-
this.retry = setTimeout(() => {
|
|
844
|
-
if (!this.subscription && this.driver.getConnectionState().status === "connected") this.open();
|
|
845
|
-
}, RETRY_MS$1);
|
|
846
|
-
this.retry.unref?.();
|
|
847
|
-
}
|
|
848
|
-
async onSnapshot(payload, token, sync) {
|
|
849
|
-
if (payload.sync?.mode === "changes") {
|
|
850
|
-
if (this.cursor?.generation !== payload.sync.generation) {
|
|
851
|
-
this.cursor = void 0;
|
|
852
|
-
this.close();
|
|
853
|
-
this.open();
|
|
854
|
-
return;
|
|
855
|
-
}
|
|
856
|
-
for (const e of payload.entries) {
|
|
857
|
-
const { raw, seq, extra } = this.adapter.entry(e);
|
|
858
|
-
this.upsert(raw, seq, false, extra);
|
|
859
|
-
}
|
|
860
|
-
for (const removal of payload.sync.removals) this.remove(removal.id, removal.seq);
|
|
861
|
-
this.cursor = {
|
|
862
|
-
generation: payload.sync.generation,
|
|
863
|
-
afterSeq: payload.sync.headSeq
|
|
864
|
-
};
|
|
865
|
-
return;
|
|
866
|
-
}
|
|
867
|
-
let entries = payload.entries;
|
|
868
|
-
if (!sync && payload.pageInfo.hasMore) {
|
|
869
|
-
this.liveTouched = /* @__PURE__ */ new Set();
|
|
870
|
-
entries = [...entries];
|
|
871
|
-
let next = payload.pageInfo.nextCursor;
|
|
872
|
-
while (next) {
|
|
873
|
-
const page = await this.adapter.fetch(this.driver, {
|
|
874
|
-
...this.adapter.base,
|
|
875
|
-
page: {
|
|
876
|
-
limit: PAGE,
|
|
877
|
-
cursor: next
|
|
878
|
-
}
|
|
879
|
-
});
|
|
880
|
-
if (token !== this.token) return;
|
|
881
|
-
entries.push(...page.entries);
|
|
882
|
-
next = page.pageInfo.hasMore ? page.pageInfo.nextCursor : null;
|
|
883
|
-
}
|
|
884
|
-
}
|
|
885
|
-
const seen = /* @__PURE__ */ new Set();
|
|
886
|
-
for (const e of entries) {
|
|
887
|
-
const { raw, seq, extra } = this.adapter.entry(e);
|
|
888
|
-
seen.add(this.adapter.id(raw));
|
|
889
|
-
this.upsert(raw, sync ? seq : void 0, sync, extra);
|
|
890
|
-
}
|
|
891
|
-
for (const id of [...this.members.keys()]) if (!seen.has(id) && !this.liveTouched?.has(id)) this.remove(id);
|
|
892
|
-
this.liveTouched = null;
|
|
893
|
-
this.cursor = payload.sync ? {
|
|
894
|
-
generation: payload.sync.generation,
|
|
895
|
-
afterSeq: payload.sync.headSeq
|
|
896
|
-
} : void 0;
|
|
897
|
-
}
|
|
898
|
-
onUpdate(update) {
|
|
899
|
-
if (update.generation && this.cursor && update.generation !== this.cursor.generation) {
|
|
900
|
-
this.cursor = void 0;
|
|
901
|
-
this.close();
|
|
902
|
-
this.open();
|
|
903
|
-
return;
|
|
904
|
-
}
|
|
905
|
-
const id = update.kind === "upsert" ? this.adapter.id(update.raw) : update.id;
|
|
906
|
-
this.liveTouched?.add(id);
|
|
907
|
-
if (update.kind === "upsert") this.upsert(update.raw, update.seq, false, update.extra);
|
|
908
|
-
else this.remove(update.id, update.seq);
|
|
909
|
-
if (update.seq !== void 0 && this.cursor) this.cursor.afterSeq = Math.max(this.cursor.afterSeq, update.seq);
|
|
910
|
-
}
|
|
911
|
-
upsert(raw, version, force = false, extra) {
|
|
912
|
-
const id = this.adapter.id(raw);
|
|
913
|
-
if (this.adapter.excluded(raw)) return this.remove(id, version, force);
|
|
914
|
-
const member = this.members.get(id);
|
|
915
|
-
if (!force && member?.version !== void 0 && version !== void 0 && version < member.version) return;
|
|
916
|
-
const kept = extra === void 0 ? member?.extra : extra;
|
|
917
|
-
const { summary, memo } = this.adapter.summarize(this.hostId, raw, kept, member?.memo);
|
|
918
|
-
const fingerprint = JSON.stringify(summary);
|
|
919
|
-
const next = {
|
|
920
|
-
fingerprint,
|
|
921
|
-
version,
|
|
922
|
-
extra: kept,
|
|
923
|
-
memo,
|
|
924
|
-
summary,
|
|
925
|
-
retained: this.adapter.retain?.(raw)
|
|
926
|
-
};
|
|
927
|
-
this.members.set(id, next);
|
|
928
|
-
if (member?.fingerprint === fingerprint) {
|
|
929
|
-
next.summary = member.summary;
|
|
930
|
-
return;
|
|
931
|
-
}
|
|
932
|
-
this.collection.set(summary.key, summary);
|
|
933
|
-
this.changed();
|
|
934
|
-
this.transition(member?.summary ?? null, summary);
|
|
935
|
-
}
|
|
936
|
-
remove(id, version, force = false) {
|
|
937
|
-
const member = this.members.get(id);
|
|
938
|
-
if (!member) return;
|
|
939
|
-
if (!force && member.version !== void 0 && version !== void 0 && version < member.version) return;
|
|
940
|
-
this.members.delete(id);
|
|
941
|
-
this.collection.delete(this.key(id));
|
|
942
|
-
this.changed();
|
|
943
|
-
this.transition(member.summary, null);
|
|
944
|
-
}
|
|
945
|
-
};
|
|
946
|
-
const isRunning = (agent) => agent.status === "running" || !!agent.activeTurn;
|
|
947
|
-
/**
|
|
948
|
-
* When the session was last *used*: the moment its most recent turn ended. It holds still while
|
|
949
|
-
* a turn runs and ignores idle metadata changes, so the sidebar does not reshuffle mid-turn.
|
|
950
|
-
* The daemon has no turn-end timestamp, so it is derived from observed transitions:
|
|
951
|
-
* - first sight, idle: the last change (normally the turn end);
|
|
952
|
-
* - first sight, running: the turn start, else the last user message;
|
|
953
|
-
* - running → idle: the change time at that moment;
|
|
954
|
-
* - idle, but a new user message appeared (a turn we missed while disconnected): the change time.
|
|
955
|
-
*/
|
|
956
|
-
function deriveActivity(current, previous) {
|
|
957
|
-
const memo = (activityAt) => ({
|
|
958
|
-
activityAt,
|
|
959
|
-
running: current.running,
|
|
960
|
-
lastUserMessageAt: current.lastUserMessageAt
|
|
961
|
-
});
|
|
962
|
-
if (!previous) return memo(current.running ? current.startedAt || current.lastUserMessageAt || current.changedAt : current.changedAt);
|
|
963
|
-
if (current.running) return memo(previous.activityAt);
|
|
964
|
-
if (previous.running || current.lastUserMessageAt > previous.lastUserMessageAt) return memo(Math.max(current.changedAt, previous.activityAt));
|
|
965
|
-
return memo(previous.activityAt);
|
|
966
672
|
}
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
pendingPermissionCount: permissions.length,
|
|
972
|
-
requiresAttention: agent.requiresAttention,
|
|
973
|
-
attentionReason: agent.attentionReason
|
|
974
|
-
});
|
|
975
|
-
const state = agent.status === "initializing" && bucket === "done" ? "running" : bucket === "attention" ? "unread" : bucket;
|
|
976
|
-
const turnActive = isRunning(agent) || agent.status === "initializing";
|
|
977
|
-
return {
|
|
978
|
-
key: `${hostId}:${agent.id}`,
|
|
979
|
-
hostId,
|
|
980
|
-
id: agent.id,
|
|
981
|
-
workspaceId: agent.workspaceId ?? null,
|
|
982
|
-
title: agent.title ?? null,
|
|
983
|
-
status: agent.status,
|
|
984
|
-
turnActive,
|
|
985
|
-
provider: agent.provider,
|
|
986
|
-
cwd: agent.cwd,
|
|
987
|
-
project: project?.projectName || basename$1(agent.cwd) || "Other",
|
|
988
|
-
projectKey: project?.projectKey ?? null,
|
|
989
|
-
activityAt: activity,
|
|
990
|
-
turnStartedAt: turnActive ? time(agent.activeTurn?.startedAt) || time(agent.lastUserMessageAt) || null : null,
|
|
991
|
-
attention: state === "needs_input",
|
|
992
|
-
state,
|
|
993
|
-
unread: agent.requiresAttention === true && state !== "needs_input",
|
|
994
|
-
lastError: agent.lastError ? agent.lastError.slice(0, 300) : null,
|
|
995
|
-
pendingPermissions: permissions,
|
|
996
|
-
model: agent.model ?? agent.runtimeInfo?.model ?? null,
|
|
997
|
-
thinking: agent.effectiveThinkingOptionId ?? agent.thinkingOptionId ?? agent.runtimeInfo?.thinkingOptionId ?? null,
|
|
998
|
-
modeId: agent.currentModeId ?? null,
|
|
999
|
-
contextUsed: agent.lastUsage?.contextWindowUsedTokens ?? null,
|
|
1000
|
-
contextMax: agent.lastUsage?.contextWindowMaxTokens ?? null,
|
|
1001
|
-
rewind: rewindModes(agent.capabilities)
|
|
1002
|
-
};
|
|
1003
|
-
}
|
|
1004
|
-
/** The rewind modes a provider supports, in Paseo's menu order. */
|
|
1005
|
-
function rewindModes(capabilities) {
|
|
1006
|
-
const c = capabilities ?? {};
|
|
1007
|
-
const modes = [];
|
|
1008
|
-
if (c.supportsRewindConversation === true) modes.push("conversation");
|
|
1009
|
-
if (c.supportsRewindFiles === true) modes.push("files");
|
|
1010
|
-
if (c.supportsRewindBoth === true) modes.push("both");
|
|
1011
|
-
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");
|
|
1012
677
|
}
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
raw: entry.agent,
|
|
1022
|
-
seq: entry.syncSeq,
|
|
1023
|
-
extra: entry.project
|
|
1024
|
-
};
|
|
1025
|
-
},
|
|
1026
|
-
update: (p) => {
|
|
1027
|
-
const u = p;
|
|
1028
|
-
return u.kind === "upsert" ? {
|
|
1029
|
-
kind: "upsert",
|
|
1030
|
-
raw: u.agent,
|
|
1031
|
-
extra: u.project,
|
|
1032
|
-
generation: u.generation,
|
|
1033
|
-
seq: u.seq
|
|
1034
|
-
} : {
|
|
1035
|
-
kind: "remove",
|
|
1036
|
-
id: u.agentId,
|
|
1037
|
-
generation: u.generation,
|
|
1038
|
-
seq: u.seq
|
|
1039
|
-
};
|
|
1040
|
-
},
|
|
1041
|
-
id: (agent) => agent.id,
|
|
1042
|
-
excluded: (agent) => !!agent.archivedAt || !!agent.internal,
|
|
1043
|
-
summarize: (hostId, agent, project, previous) => {
|
|
1044
|
-
const memo = deriveActivity({
|
|
1045
|
-
running: isRunning(agent),
|
|
1046
|
-
changedAt: time(agent.updatedAt),
|
|
1047
|
-
startedAt: time(agent.activeTurn?.startedAt),
|
|
1048
|
-
lastUserMessageAt: time(agent.lastUserMessageAt)
|
|
1049
|
-
}, previous);
|
|
1050
|
-
return {
|
|
1051
|
-
summary: summarize(hostId, agent, project, memo.activityAt),
|
|
1052
|
-
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);
|
|
1053
686
|
};
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
features: agent.features ?? []
|
|
1060
|
-
})
|
|
1061
|
-
};
|
|
1062
|
-
/** One daemon's active agents. */
|
|
1063
|
-
var HostDirectory = class extends HostMirror {
|
|
1064
|
-
constructor(hostId, driver, collection, changed, transition) {
|
|
1065
|
-
super(agentAdapter, hostId, driver, collection, changed, transition);
|
|
1066
|
-
}
|
|
1067
|
-
/** Provider and capabilities from the live directory; undefined if the agent is not listed. */
|
|
1068
|
-
facts(agentId) {
|
|
1069
|
-
return this.retained(agentId);
|
|
1070
|
-
}
|
|
1071
|
-
};
|
|
687
|
+
s.setTimeout(timeoutMs, () => finish(false));
|
|
688
|
+
s.once("connect", () => finish(true));
|
|
689
|
+
s.once("error", () => finish(false));
|
|
690
|
+
});
|
|
691
|
+
}
|
|
1072
692
|
/**
|
|
1073
|
-
*
|
|
1074
|
-
*
|
|
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.
|
|
1075
697
|
*/
|
|
1076
|
-
function
|
|
1077
|
-
const
|
|
1078
|
-
return {
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
projectKey: ws.project?.projectKey ?? ws.projectId,
|
|
1086
|
-
rootPath: ws.projectRootPath,
|
|
1087
|
-
directory: ws.workspaceDirectory ?? ws.projectRootPath,
|
|
1088
|
-
kind: ws.workspaceKind,
|
|
1089
|
-
branch: ws.gitRuntime?.currentBranch ?? null,
|
|
1090
|
-
pinnedAt: time(ws.pinnedAt),
|
|
1091
|
-
activityAt: activity,
|
|
1092
|
-
state,
|
|
1093
|
-
attention: state === "needs_input",
|
|
1094
|
-
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}.`
|
|
1095
707
|
};
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
entry: (e) => {
|
|
1109
|
-
const ws = e;
|
|
1110
|
-
return {
|
|
1111
|
-
raw: ws,
|
|
1112
|
-
seq: ws.syncSeq
|
|
1113
|
-
};
|
|
1114
|
-
},
|
|
1115
|
-
update: (p) => {
|
|
1116
|
-
const u = p;
|
|
1117
|
-
return u.kind === "upsert" ? {
|
|
1118
|
-
kind: "upsert",
|
|
1119
|
-
raw: u.workspace,
|
|
1120
|
-
generation: u.generation,
|
|
1121
|
-
seq: u.seq
|
|
1122
|
-
} : {
|
|
1123
|
-
kind: "remove",
|
|
1124
|
-
id: u.id,
|
|
1125
|
-
generation: u.generation,
|
|
1126
|
-
seq: u.seq
|
|
1127
|
-
};
|
|
1128
|
-
},
|
|
1129
|
-
id: (ws) => ws.id,
|
|
1130
|
-
excluded: (ws) => !!ws.archivingAt || !!ws.internal || !!ws.background,
|
|
1131
|
-
summarize: (hostId, ws, _extra, previous) => {
|
|
1132
|
-
const memo = deriveActivity({
|
|
1133
|
-
running: ws.status === "running",
|
|
1134
|
-
changedAt: time(ws.statusEnteredAt) || time(ws.activityAt),
|
|
1135
|
-
startedAt: ws.status === "running" ? time(ws.statusEnteredAt) : 0,
|
|
1136
|
-
lastUserMessageAt: time(ws.lastUserMessageAt)
|
|
1137
|
-
}, previous);
|
|
1138
|
-
const activity = previous || ws.status === "running" ? memo.activityAt : time(ws.activityAt) || memo.activityAt || time(ws.createdAt);
|
|
1139
|
-
return {
|
|
1140
|
-
summary: summarizeWorkspace(hostId, ws, activity),
|
|
1141
|
-
memo: {
|
|
1142
|
-
...memo,
|
|
1143
|
-
activityAt: activity
|
|
1144
|
-
}
|
|
1145
|
-
};
|
|
1146
|
-
}
|
|
1147
|
-
};
|
|
1148
|
-
/** One daemon's workspaces (Paseo's threads). */
|
|
1149
|
-
var HostWorkspaces = class extends HostMirror {
|
|
1150
|
-
constructor(hostId, driver, collection, changed) {
|
|
1151
|
-
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
|
+
});
|
|
1152
720
|
}
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
const MAX_ROWS = 600;
|
|
1159
|
-
const KEEP_ROWS = 500;
|
|
1160
|
-
/** Rows sent to a client that (re)joins; older ones load on demand. */
|
|
1161
|
-
const RESET_ROWS = 200;
|
|
1162
|
-
const MAX_BUFFER = 5e3;
|
|
1163
|
-
const FLUSH_MS = 500;
|
|
1164
|
-
const RETRY_MS = 2e3;
|
|
1165
|
-
/** Same fold the daemon's TimelineProjection applies when a tool call reports again. */
|
|
1166
|
-
function mergeToolCallItems(existing, incoming) {
|
|
1167
|
-
const a = existing.detail, b = incoming.detail;
|
|
1168
|
-
const detail = a?.type === "unknown" && b?.type !== "unknown" ? b : b?.type === "unknown" && a?.type !== "unknown" ? a : b;
|
|
1169
|
-
const metadata = existing.metadata || incoming.metadata ? {
|
|
1170
|
-
...existing.metadata,
|
|
1171
|
-
...incoming.metadata
|
|
1172
|
-
} : void 0;
|
|
1173
|
-
const merged = {
|
|
1174
|
-
...existing,
|
|
1175
|
-
...incoming,
|
|
1176
|
-
detail,
|
|
1177
|
-
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}.`
|
|
1178
726
|
};
|
|
1179
|
-
if (incoming.status === "failed") merged.error = incoming.error;
|
|
1180
|
-
else if (incoming.status === "completed" || incoming.status === "canceled") merged.error = null;
|
|
1181
|
-
else if (incoming.error !== void 0) merged.error = incoming.error;
|
|
1182
|
-
return merged;
|
|
1183
|
-
}
|
|
1184
|
-
function textMergeable(previous, entry) {
|
|
1185
|
-
const a = previous.item, b = entry.item;
|
|
1186
|
-
if (a.type !== b.type || previous.seqEnd + 1 !== entry.seqStart || previous.turnId !== entry.turnId) return false;
|
|
1187
|
-
if (a.type === "reasoning") return true;
|
|
1188
|
-
return a.type === "assistant_message" && (b.messageId === void 0 || a.messageId === b.messageId);
|
|
1189
727
|
}
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
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.
|
|
1195
737
|
*/
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
/** seqStart → pending change since the last flush; full means send the whole row. */
|
|
1211
|
-
pending = /* @__PURE__ */ new Map();
|
|
1212
|
-
pendingReset = false;
|
|
1213
|
-
flushTimer;
|
|
1214
|
-
retryTimer;
|
|
1215
|
-
subscription = null;
|
|
1216
|
-
token = 0;
|
|
1217
|
-
loads = 0;
|
|
1218
|
-
driver;
|
|
1219
|
-
agentId;
|
|
1220
|
-
constructor(driver, agentId) {
|
|
1221
|
-
this.driver = driver;
|
|
1222
|
-
this.agentId = agentId;
|
|
1223
|
-
}
|
|
1224
|
-
get watcherCount() {
|
|
1225
|
-
return this.watchers.size;
|
|
1226
|
-
}
|
|
1227
|
-
start() {
|
|
1228
|
-
const token = ++this.token;
|
|
1229
|
-
this.state = "loading";
|
|
1230
|
-
const subscription = this.driver.subscribeAgentTimeline(this.agentId, (message) => {
|
|
1231
|
-
if (token === this.token) this.onMessage(message);
|
|
1232
|
-
});
|
|
1233
|
-
this.subscription = subscription;
|
|
1234
|
-
subscription.ready.then(() => token === this.token ? this.reload() : void 0, () => this.fail(token));
|
|
1235
|
-
}
|
|
1236
|
-
dispose() {
|
|
1237
|
-
this.token++;
|
|
1238
|
-
this.state = "disposed";
|
|
1239
|
-
clearTimeout(this.flushTimer);
|
|
1240
|
-
clearTimeout(this.retryTimer);
|
|
1241
|
-
this.watchers.clear();
|
|
1242
|
-
const released = this.subscription?.release().catch(() => {}) ?? Promise.resolve();
|
|
1243
|
-
this.subscription = null;
|
|
1244
|
-
return released;
|
|
1245
|
-
}
|
|
1246
|
-
watch(watcher) {
|
|
1247
|
-
if (this.state === "live" || this.state === "catching-up") {
|
|
1248
|
-
this.flush();
|
|
1249
|
-
watcher([this.resetOp()]);
|
|
1250
|
-
}
|
|
1251
|
-
this.watchers.add(watcher);
|
|
1252
|
-
return () => this.watchers.delete(watcher);
|
|
1253
|
-
}
|
|
1254
|
-
onMessage(message) {
|
|
1255
|
-
switch (message.type) {
|
|
1256
|
-
case "agent_stream": {
|
|
1257
|
-
const payload = message.payload;
|
|
1258
|
-
if (payload.event.type !== "timeline" || payload.seq === void 0) return;
|
|
1259
|
-
if (this.state !== "live") return this.bufferEvent(payload);
|
|
1260
|
-
return this.process(payload);
|
|
1261
|
-
}
|
|
1262
|
-
case "agent.timeline.replacement":
|
|
1263
|
-
this.reload();
|
|
1264
|
-
return;
|
|
1265
|
-
case "agent.timeline.subscription_restored":
|
|
1266
|
-
this.state === "live" && this.catchUp();
|
|
1267
|
-
return;
|
|
1268
|
-
case "agent.timeline.error": return this.fail(this.token);
|
|
1269
|
-
}
|
|
1270
|
-
}
|
|
1271
|
-
bufferEvent(payload) {
|
|
1272
|
-
if (this.overflowed) return;
|
|
1273
|
-
if (this.buffer.length >= MAX_BUFFER) {
|
|
1274
|
-
this.buffer = [];
|
|
1275
|
-
this.overflowed = true;
|
|
1276
|
-
return;
|
|
1277
|
-
}
|
|
1278
|
-
this.buffer.push(payload);
|
|
1279
|
-
}
|
|
1280
|
-
process(payload) {
|
|
1281
|
-
const seq = payload.seq;
|
|
1282
|
-
if (payload.epoch !== void 0 && payload.epoch !== this.epoch) return void this.reload();
|
|
1283
|
-
if (seq <= this.lastSeq) return;
|
|
1284
|
-
if (seq > this.lastSeq + 1) {
|
|
1285
|
-
this.bufferEvent(payload);
|
|
1286
|
-
this.catchUp();
|
|
1287
|
-
return;
|
|
1288
|
-
}
|
|
1289
|
-
if (!this.applyLive(payload)) return void this.catchUp();
|
|
1290
|
-
this.lastSeq = seq;
|
|
1291
|
-
}
|
|
1292
|
-
/** Folds one source event; false when the view cannot decide locally. */
|
|
1293
|
-
applyLive(payload) {
|
|
1294
|
-
const entry = {
|
|
1295
|
-
seqStart: payload.seq,
|
|
1296
|
-
seqEnd: payload.seq,
|
|
1297
|
-
timestamp: payload.timestamp,
|
|
1298
|
-
provider: payload.event.provider ?? "",
|
|
1299
|
-
...payload.event.turnId ? { turnId: payload.event.turnId } : {},
|
|
1300
|
-
item: payload.event.item
|
|
1301
|
-
};
|
|
1302
|
-
const identity = timelineItemIdentity(entry.item);
|
|
1303
|
-
if (identity !== null) {
|
|
1304
|
-
const existing = this.identities.get(identity);
|
|
1305
|
-
if (existing) {
|
|
1306
|
-
if (entry.item.type === "tool_call") {
|
|
1307
|
-
if (existing.item.type === "tool_call" && existing.turnId === entry.turnId) {
|
|
1308
|
-
existing.item = mergeToolCallItems(existing.item, entry.item);
|
|
1309
|
-
existing.timestamp = entry.timestamp;
|
|
1310
|
-
existing.seqEnd = Math.max(existing.seqEnd, entry.seqEnd);
|
|
1311
|
-
this.mark(existing.seqStart, true);
|
|
1312
|
-
return true;
|
|
1313
|
-
}
|
|
1314
|
-
} else if (entry.item.type === "plugin" && existing.item.type === "plugin") {
|
|
1315
|
-
Object.assign(existing, {
|
|
1316
|
-
...entry,
|
|
1317
|
-
seqStart: existing.seqStart
|
|
1318
|
-
});
|
|
1319
|
-
this.mark(existing.seqStart, true);
|
|
1320
|
-
return true;
|
|
1321
|
-
}
|
|
1322
|
-
} else if (!this.complete) return false;
|
|
1323
|
-
}
|
|
1324
|
-
const previous = this.rows.at(-1);
|
|
1325
|
-
if (previous && textMergeable(previous, entry)) {
|
|
1326
|
-
const text = entry.item.text ?? "";
|
|
1327
|
-
previous.item = {
|
|
1328
|
-
type: previous.item.type,
|
|
1329
|
-
text: (previous.item.text ?? "") + text,
|
|
1330
|
-
...previous.item.type === "assistant_message" && previous.item.messageId ? { messageId: previous.item.messageId } : {}
|
|
1331
|
-
};
|
|
1332
|
-
previous.timestamp = entry.timestamp;
|
|
1333
|
-
previous.seqEnd = entry.seqEnd;
|
|
1334
|
-
this.mark(previous.seqStart, false, text);
|
|
1335
|
-
return true;
|
|
1336
|
-
}
|
|
1337
|
-
this.insert(entry);
|
|
1338
|
-
return true;
|
|
1339
|
-
}
|
|
1340
|
-
async reload() {
|
|
1341
|
-
const token = this.token;
|
|
1342
|
-
const load = ++this.loads;
|
|
1343
|
-
this.state = "loading";
|
|
1344
|
-
try {
|
|
1345
|
-
const page = await this.driver.fetchAgentTimeline(this.agentId, {
|
|
1346
|
-
direction: "tail",
|
|
1347
|
-
limit: TAIL_LIMIT,
|
|
1348
|
-
projection: "projected",
|
|
1349
|
-
wholeTurns: true
|
|
1350
|
-
});
|
|
1351
|
-
if (token !== this.token || load !== this.loads) return;
|
|
1352
|
-
this.replaceWith(page);
|
|
1353
|
-
this.settle();
|
|
1354
|
-
} catch {
|
|
1355
|
-
this.fail(token);
|
|
1356
|
-
}
|
|
1357
|
-
}
|
|
1358
|
-
async catchUp() {
|
|
1359
|
-
if (this.state === "catching-up" || this.state === "loading") return;
|
|
1360
|
-
const token = this.token;
|
|
1361
|
-
this.state = "catching-up";
|
|
1362
|
-
try {
|
|
1363
|
-
for (;;) {
|
|
1364
|
-
const page = await this.driver.fetchAgentTimeline(this.agentId, {
|
|
1365
|
-
direction: "after",
|
|
1366
|
-
cursor: {
|
|
1367
|
-
epoch: this.epoch,
|
|
1368
|
-
seq: Math.max(0, this.lastSeq)
|
|
1369
|
-
},
|
|
1370
|
-
limit: CATCH_UP_PAGE,
|
|
1371
|
-
projection: "projected"
|
|
1372
|
-
});
|
|
1373
|
-
if (token !== this.token) return;
|
|
1374
|
-
if (page.reset || page.epoch !== this.epoch) {
|
|
1375
|
-
this.replaceWith(page);
|
|
1376
|
-
break;
|
|
1377
|
-
}
|
|
1378
|
-
for (const entry of page.entries) this.upsertFetched(entry);
|
|
1379
|
-
const end = page.endCursor?.seq ?? (page.hasNewer ? null : page.window.maxSeq);
|
|
1380
|
-
if (end === null) break;
|
|
1381
|
-
this.lastSeq = Math.max(this.lastSeq, end);
|
|
1382
|
-
if (!page.hasNewer) break;
|
|
1383
|
-
}
|
|
1384
|
-
this.settle();
|
|
1385
|
-
} catch {
|
|
1386
|
-
this.fail(token);
|
|
1387
|
-
}
|
|
1388
|
-
}
|
|
1389
|
-
/** Back to live: replay what arrived meanwhile, or reload if the buffer overflowed. */
|
|
1390
|
-
settle() {
|
|
1391
|
-
if (this.overflowed) {
|
|
1392
|
-
this.overflowed = false;
|
|
1393
|
-
this.buffer = [];
|
|
1394
|
-
this.reload();
|
|
1395
|
-
return;
|
|
1396
|
-
}
|
|
1397
|
-
this.state = "live";
|
|
1398
|
-
const events = this.buffer;
|
|
1399
|
-
this.buffer = [];
|
|
1400
|
-
for (let i = 0; i < events.length; i++) {
|
|
1401
|
-
if (this.state !== "live") {
|
|
1402
|
-
this.buffer = events.slice(i).concat(this.buffer);
|
|
1403
|
-
return;
|
|
1404
|
-
}
|
|
1405
|
-
this.process(events[i]);
|
|
1406
|
-
}
|
|
1407
|
-
}
|
|
1408
|
-
fail(token) {
|
|
1409
|
-
if (token !== this.token || this.state === "disposed") return;
|
|
1410
|
-
this.state = "failed";
|
|
1411
|
-
this.broadcast([{
|
|
1412
|
-
type: "error",
|
|
1413
|
-
message: "Timeline sync interrupted; retrying"
|
|
1414
|
-
}]);
|
|
1415
|
-
clearTimeout(this.retryTimer);
|
|
1416
|
-
this.retryTimer = setTimeout(() => {
|
|
1417
|
-
if (this.state !== "failed" || token !== this.token) return;
|
|
1418
|
-
this.subscription?.release().catch(() => {});
|
|
1419
|
-
this.start();
|
|
1420
|
-
}, RETRY_MS);
|
|
1421
|
-
this.retryTimer.unref?.();
|
|
1422
|
-
}
|
|
1423
|
-
replaceWith(page) {
|
|
1424
|
-
this.rows = [];
|
|
1425
|
-
this.bySeqStart.clear();
|
|
1426
|
-
this.identities.clear();
|
|
1427
|
-
this.pending.clear();
|
|
1428
|
-
this.epoch = page.epoch;
|
|
1429
|
-
this.lastSeq = page.window.maxSeq;
|
|
1430
|
-
this.hasOlder = page.hasOlder;
|
|
1431
|
-
this.startCursor = page.startCursor;
|
|
1432
|
-
this.complete = !page.hasOlder;
|
|
1433
|
-
for (const entry of page.entries) this.upsertFetched(entry, false);
|
|
1434
|
-
this.buffer = this.buffer.filter((e) => e.epoch === this.epoch && e.seq > this.lastSeq);
|
|
1435
|
-
this.pending.clear();
|
|
1436
|
-
this.pendingReset = true;
|
|
1437
|
-
this.scheduleFlush();
|
|
1438
|
-
}
|
|
1439
|
-
upsertFetched(entry, notify = true) {
|
|
1440
|
-
const row = {
|
|
1441
|
-
seqStart: entry.seqStart,
|
|
1442
|
-
seqEnd: entry.seqEnd,
|
|
1443
|
-
timestamp: entry.timestamp,
|
|
1444
|
-
provider: entry.provider,
|
|
1445
|
-
...entry.turnId ? { turnId: entry.turnId } : {},
|
|
1446
|
-
item: entry.item
|
|
1447
|
-
};
|
|
1448
|
-
const existing = this.bySeqStart.get(row.seqStart);
|
|
1449
|
-
if (existing) {
|
|
1450
|
-
Object.assign(existing, row);
|
|
1451
|
-
if (!row.turnId) delete existing.turnId;
|
|
1452
|
-
this.noteIdentity(existing);
|
|
1453
|
-
if (notify) this.mark(existing.seqStart, true);
|
|
1454
|
-
return;
|
|
1455
|
-
}
|
|
1456
|
-
this.insert(row, notify);
|
|
1457
|
-
}
|
|
1458
|
-
insert(row, notify = true) {
|
|
1459
|
-
let index = this.rows.length;
|
|
1460
|
-
if (index && this.rows[index - 1].seqStart > row.seqStart) {
|
|
1461
|
-
let low = 0, high = index;
|
|
1462
|
-
while (low < high) {
|
|
1463
|
-
const middle = low + high >>> 1;
|
|
1464
|
-
if (this.rows[middle].seqStart < row.seqStart) low = middle + 1;
|
|
1465
|
-
else high = middle;
|
|
1466
|
-
}
|
|
1467
|
-
index = low;
|
|
1468
|
-
}
|
|
1469
|
-
if (index === this.rows.length) this.rows.push(row);
|
|
1470
|
-
else this.rows.splice(index, 0, row);
|
|
1471
|
-
this.bySeqStart.set(row.seqStart, row);
|
|
1472
|
-
this.noteIdentity(row);
|
|
1473
|
-
if (notify) this.mark(row.seqStart, true);
|
|
1474
|
-
if (this.rows.length > MAX_ROWS) this.trim();
|
|
1475
|
-
}
|
|
1476
|
-
/** Like the daemon, an identity resolves to its most recent row. */
|
|
1477
|
-
noteIdentity(row) {
|
|
1478
|
-
const identity = timelineItemIdentity(row.item);
|
|
1479
|
-
if (identity === null) return;
|
|
1480
|
-
const current = this.identities.get(identity);
|
|
1481
|
-
if (!current || current.seqStart <= row.seqStart) this.identities.set(identity, row);
|
|
1482
|
-
}
|
|
1483
|
-
trim() {
|
|
1484
|
-
const removed = this.rows.splice(0, this.rows.length - KEEP_ROWS);
|
|
1485
|
-
for (const row of removed) {
|
|
1486
|
-
this.bySeqStart.delete(row.seqStart);
|
|
1487
|
-
this.pending.delete(row.seqStart);
|
|
1488
|
-
const identity = timelineItemIdentity(row.item);
|
|
1489
|
-
if (identity !== null && this.identities.get(identity) === row) this.identities.delete(identity);
|
|
1490
|
-
}
|
|
1491
|
-
this.complete = false;
|
|
1492
|
-
this.hasOlder = true;
|
|
1493
|
-
this.startCursor = {
|
|
1494
|
-
epoch: this.epoch,
|
|
1495
|
-
seq: this.rows[0].seqStart
|
|
1496
|
-
};
|
|
1497
|
-
}
|
|
1498
|
-
mark(seqStart, full, text = "") {
|
|
1499
|
-
if (this.pendingReset) return;
|
|
1500
|
-
const pending = this.pending.get(seqStart);
|
|
1501
|
-
if (!pending) this.pending.set(seqStart, {
|
|
1502
|
-
full,
|
|
1503
|
-
text: full ? "" : text
|
|
1504
|
-
});
|
|
1505
|
-
else if (full) {
|
|
1506
|
-
pending.full = true;
|
|
1507
|
-
pending.text = "";
|
|
1508
|
-
} else if (!pending.full) pending.text += text;
|
|
1509
|
-
this.scheduleFlush();
|
|
1510
|
-
}
|
|
1511
|
-
scheduleFlush() {
|
|
1512
|
-
if (this.flushTimer || !this.watchers.size) return;
|
|
1513
|
-
this.flushTimer = setTimeout(() => this.flush(), FLUSH_MS);
|
|
1514
|
-
}
|
|
1515
|
-
flush() {
|
|
1516
|
-
clearTimeout(this.flushTimer);
|
|
1517
|
-
this.flushTimer = void 0;
|
|
1518
|
-
if (this.pendingReset) {
|
|
1519
|
-
this.pendingReset = false;
|
|
1520
|
-
this.pending.clear();
|
|
1521
|
-
return this.broadcast([this.resetOp()]);
|
|
1522
|
-
}
|
|
1523
|
-
if (!this.pending.size) return;
|
|
1524
|
-
const ops = [];
|
|
1525
|
-
for (const [seqStart, change] of this.pending) {
|
|
1526
|
-
const row = this.bySeqStart.get(seqStart);
|
|
1527
|
-
if (!row) continue;
|
|
1528
|
-
ops.push(change.full ? {
|
|
1529
|
-
type: "upsert",
|
|
1530
|
-
row: { ...row }
|
|
1531
|
-
} : {
|
|
1532
|
-
type: "append",
|
|
1533
|
-
seqStart,
|
|
1534
|
-
seqEnd: row.seqEnd,
|
|
1535
|
-
timestamp: row.timestamp,
|
|
1536
|
-
text: change.text
|
|
1537
|
-
});
|
|
1538
|
-
}
|
|
1539
|
-
this.pending.clear();
|
|
1540
|
-
if (ops.length) this.broadcast(ops);
|
|
1541
|
-
}
|
|
1542
|
-
resetOp() {
|
|
1543
|
-
const start = Math.max(0, this.rows.length - RESET_ROWS);
|
|
1544
|
-
const rows = this.rows.slice(start).map((row) => ({ ...row }));
|
|
1545
|
-
return {
|
|
1546
|
-
type: "reset",
|
|
1547
|
-
epoch: this.epoch,
|
|
1548
|
-
rows,
|
|
1549
|
-
hasOlder: this.hasOlder || start > 0,
|
|
1550
|
-
startCursor: start > 0 ? {
|
|
1551
|
-
epoch: this.epoch,
|
|
1552
|
-
seq: rows[0].seqStart
|
|
1553
|
-
} : this.startCursor
|
|
1554
|
-
};
|
|
1555
|
-
}
|
|
1556
|
-
broadcast(ops) {
|
|
1557
|
-
for (const watcher of this.watchers) watcher(ops);
|
|
1558
|
-
}
|
|
1559
|
-
};
|
|
1560
|
-
// src/server/hosts.ts
|
|
1561
|
-
var UnknownHostError = class extends Error {
|
|
1562
|
-
constructor() {
|
|
1563
|
-
super("Unknown host");
|
|
1564
|
-
}
|
|
1565
|
-
};
|
|
1566
|
-
/** Idle grace before an unwatched timeline releases its daemon subscription. */
|
|
1567
|
-
const TIMELINE_GRACE_MS = 3e4;
|
|
1568
|
-
var Hosts = class {
|
|
1569
|
-
agents = new VersionedCollection();
|
|
1570
|
-
workspaces = new VersionedCollection();
|
|
1571
|
-
clients = /* @__PURE__ */ new Map();
|
|
1572
|
-
diagnostics = /* @__PURE__ */ new Map();
|
|
1573
|
-
labels = /* @__PURE__ */ new Map();
|
|
1574
|
-
timelines = /* @__PURE__ */ new Map();
|
|
1575
|
-
agentListeners = /* @__PURE__ */ new Set();
|
|
1576
|
-
hostListeners = /* @__PURE__ */ new Set();
|
|
1577
|
-
transitionListeners = /* @__PURE__ */ new Set();
|
|
1578
|
-
add(host) {
|
|
1579
|
-
const driver = createHostClient(host.connection, {
|
|
1580
|
-
clientId: `litepaseo-${host.id}`,
|
|
1581
|
-
clientType: "cli",
|
|
1582
|
-
connectTimeoutMs: 5e3,
|
|
1583
|
-
reconnect: { enabled: true },
|
|
1584
|
-
logger: {
|
|
1585
|
-
debug() {},
|
|
1586
|
-
info() {},
|
|
1587
|
-
warn() {},
|
|
1588
|
-
error() {}
|
|
1589
|
-
}
|
|
1590
|
-
});
|
|
1591
|
-
this.labels.set(host.id, host.label);
|
|
1592
|
-
this.attach(host.id, driver, createPaseoApi(driver));
|
|
1593
|
-
driver.connect().catch((error) => {
|
|
1594
|
-
if (this.clients.get(host.id)?.driver !== driver) return;
|
|
1595
|
-
this.noteFailure(host.id, error);
|
|
1596
|
-
this.emit(this.hostListeners);
|
|
1597
|
-
});
|
|
1598
|
-
}
|
|
1599
|
-
/** Wires a connected-or-connecting driver; separate from `add` so tests can inject doubles. */
|
|
1600
|
-
attach(hostId, driver, api) {
|
|
1601
|
-
const directory = new HostDirectory(hostId, driver, this.agents, () => this.emit(this.agentListeners), (previous, next) => {
|
|
1602
|
-
for (const listener of this.transitionListeners) listener(previous, next);
|
|
1603
|
-
});
|
|
1604
|
-
const workspaces = new HostWorkspaces(hostId, driver, this.workspaces, () => this.emit(this.agentListeners));
|
|
1605
|
-
const update = (state) => {
|
|
1606
|
-
const previous = this.diagnostics.get(hostId) ?? {};
|
|
1607
|
-
if (state.status === "connected") this.diagnostics.set(hostId, { lastConnectedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
1608
|
-
else if (state.status === "connecting") this.diagnostics.set(hostId, {
|
|
1609
|
-
...previous,
|
|
1610
|
-
nextRetryAt: void 0,
|
|
1611
|
-
attempt: state.attempt
|
|
1612
|
-
});
|
|
1613
|
-
else if (state.status === "disconnected") {
|
|
1614
|
-
this.noteFailure(hostId, state);
|
|
1615
|
-
const retry = state.nextRetryAt && Date.parse(state.nextRetryAt);
|
|
1616
|
-
this.diagnostics.set(hostId, {
|
|
1617
|
-
...this.diagnostics.get(hostId),
|
|
1618
|
-
nextRetryAt: retry && Number.isFinite(retry) ? new Date(retry).toISOString() : void 0
|
|
1619
|
-
});
|
|
1620
|
-
}
|
|
1621
|
-
this.emit(this.hostListeners);
|
|
1622
|
-
};
|
|
1623
|
-
const stopStatus = driver.subscribeConnectionStatus(update);
|
|
1624
|
-
update(driver.getConnectionState());
|
|
1625
|
-
this.clients.set(hostId, {
|
|
1626
|
-
driver,
|
|
1627
|
-
api,
|
|
1628
|
-
directory,
|
|
1629
|
-
workspaces,
|
|
1630
|
-
stopStatus
|
|
1631
|
-
});
|
|
1632
|
-
directory.start();
|
|
1633
|
-
if (driver.observeWorkspaces) workspaces.start();
|
|
1634
|
-
this.emit(this.hostListeners);
|
|
1635
|
-
}
|
|
1636
|
-
get(id) {
|
|
1637
|
-
const c = this.clients.get(id);
|
|
1638
|
-
if (!c) throw new UnknownHostError();
|
|
1639
|
-
return c;
|
|
1640
|
-
}
|
|
1641
|
-
diagnostic(id) {
|
|
1642
|
-
return this.diagnostics.get(id);
|
|
1643
|
-
}
|
|
1644
|
-
noteFailure(id, failure) {
|
|
1645
|
-
const error = connectionProblem(failure);
|
|
1646
|
-
const previous = this.diagnostics.get(id) ?? {};
|
|
1647
|
-
if (previous.error?.code !== error.code) console.warn(JSON.stringify({
|
|
1648
|
-
event: "host_connection_failed",
|
|
1649
|
-
hostId: id,
|
|
1650
|
-
code: error.code
|
|
1651
|
-
}));
|
|
1652
|
-
this.diagnostics.set(id, {
|
|
1653
|
-
...previous,
|
|
1654
|
-
error
|
|
1655
|
-
});
|
|
1656
|
-
}
|
|
1657
|
-
state(id) {
|
|
1658
|
-
return this.clients.get(id)?.driver.getConnectionState().status ?? "offline";
|
|
1659
|
-
}
|
|
1660
|
-
async remove(id) {
|
|
1661
|
-
const c = this.clients.get(id);
|
|
1662
|
-
this.clients.delete(id);
|
|
1663
|
-
const releases = [];
|
|
1664
|
-
for (const [key, entry] of this.timelines) if (entry.hostId === id) {
|
|
1665
|
-
clearTimeout(entry.idle);
|
|
1666
|
-
releases.push(entry.view.dispose());
|
|
1667
|
-
this.timelines.delete(key);
|
|
1668
|
-
}
|
|
1669
|
-
if (c) {
|
|
1670
|
-
await Promise.all([
|
|
1671
|
-
...releases,
|
|
1672
|
-
c.directory.dispose(),
|
|
1673
|
-
c.workspaces.dispose()
|
|
1674
|
-
]);
|
|
1675
|
-
c.stopStatus();
|
|
1676
|
-
await c.api.dispose();
|
|
1677
|
-
await c.driver.close();
|
|
1678
|
-
}
|
|
1679
|
-
this.diagnostics.delete(id);
|
|
1680
|
-
this.labels.delete(id);
|
|
1681
|
-
this.emit(this.hostListeners);
|
|
1682
|
-
}
|
|
1683
|
-
async close() {
|
|
1684
|
-
await Promise.allSettled([...this.clients.keys()].map((id) => this.remove(id)));
|
|
1685
|
-
}
|
|
1686
|
-
onAgentsChanged(listener) {
|
|
1687
|
-
this.agentListeners.add(listener);
|
|
1688
|
-
return () => this.agentListeners.delete(listener);
|
|
1689
|
-
}
|
|
1690
|
-
/** Per-agent summary changes, for event detection (notifications). */
|
|
1691
|
-
onTransition(listener) {
|
|
1692
|
-
this.transitionListeners.add(listener);
|
|
1693
|
-
return () => this.transitionListeners.delete(listener);
|
|
1694
|
-
}
|
|
1695
|
-
/** Whether some browser is looking at this conversation right now. */
|
|
1696
|
-
isViewing(key) {
|
|
1697
|
-
return (this.timelines.get(key)?.view.watcherCount ?? 0) > 0;
|
|
1698
|
-
}
|
|
1699
|
-
label(hostId) {
|
|
1700
|
-
return this.labels.get(hostId) ?? "";
|
|
1701
|
-
}
|
|
1702
|
-
setLabel(hostId, label) {
|
|
1703
|
-
this.labels.set(hostId, label);
|
|
1704
|
-
}
|
|
1705
|
-
onHostsChanged(listener) {
|
|
1706
|
-
this.hostListeners.add(listener);
|
|
1707
|
-
return () => this.hostListeners.delete(listener);
|
|
1708
|
-
}
|
|
1709
|
-
/** Shares one live timeline per agent across all watching browsers. */
|
|
1710
|
-
watchTimeline(hostId, agentId, watcher) {
|
|
1711
|
-
const client = this.get(hostId);
|
|
1712
|
-
const key = `${hostId}:${agentId}`;
|
|
1713
|
-
let entry = this.timelines.get(key);
|
|
1714
|
-
if (!entry) {
|
|
1715
|
-
const view = new TimelineView(client.driver, agentId);
|
|
1716
|
-
entry = {
|
|
1717
|
-
view,
|
|
1718
|
-
hostId
|
|
1719
|
-
};
|
|
1720
|
-
this.timelines.set(key, entry);
|
|
1721
|
-
view.start();
|
|
1722
|
-
}
|
|
1723
|
-
clearTimeout(entry.idle);
|
|
1724
|
-
entry.idle = void 0;
|
|
1725
|
-
const stop = entry.view.watch(watcher);
|
|
1726
|
-
const current = entry;
|
|
1727
|
-
return () => {
|
|
1728
|
-
stop();
|
|
1729
|
-
if (current.view.watcherCount || this.timelines.get(key) !== current) return;
|
|
1730
|
-
current.idle = setTimeout(() => {
|
|
1731
|
-
if (current.view.watcherCount || this.timelines.get(key) !== current) return;
|
|
1732
|
-
current.view.dispose();
|
|
1733
|
-
this.timelines.delete(key);
|
|
1734
|
-
}, TIMELINE_GRACE_MS);
|
|
1735
|
-
current.idle.unref?.();
|
|
1736
|
-
};
|
|
1737
|
-
}
|
|
1738
|
-
emit(listeners) {
|
|
1739
|
-
for (const listener of listeners) listener();
|
|
1740
|
-
}
|
|
1741
|
-
};
|
|
1742
|
-
// src/server/sse.ts
|
|
1743
|
-
const HEARTBEAT_MS = 2e4;
|
|
1744
|
-
/** Server-sent events over a plain fetch response, so the bearer header still authenticates. */
|
|
1745
|
-
function eventStream(signal, open, valid = () => true) {
|
|
1746
|
-
const encoder = new TextEncoder();
|
|
1747
|
-
let cleanup;
|
|
1748
|
-
const stop = () => {
|
|
1749
|
-
cleanup?.();
|
|
1750
|
-
cleanup = void 0;
|
|
1751
|
-
};
|
|
1752
|
-
const body = new ReadableStream({
|
|
1753
|
-
start(controller) {
|
|
1754
|
-
const write = (text) => {
|
|
1755
|
-
try {
|
|
1756
|
-
controller.enqueue(encoder.encode(text));
|
|
1757
|
-
} catch {
|
|
1758
|
-
stop();
|
|
1759
|
-
}
|
|
1760
|
-
};
|
|
1761
|
-
const heartbeat = setInterval(() => {
|
|
1762
|
-
if (valid()) return write(": ping\n\n");
|
|
1763
|
-
stop();
|
|
1764
|
-
try {
|
|
1765
|
-
controller.close();
|
|
1766
|
-
} catch {}
|
|
1767
|
-
}, HEARTBEAT_MS);
|
|
1768
|
-
const close = open((data) => write(`data: ${JSON.stringify(data)}\n\n`));
|
|
1769
|
-
cleanup = () => {
|
|
1770
|
-
clearInterval(heartbeat);
|
|
1771
|
-
close();
|
|
1772
|
-
};
|
|
1773
|
-
signal.addEventListener("abort", () => {
|
|
1774
|
-
stop();
|
|
1775
|
-
try {
|
|
1776
|
-
controller.close();
|
|
1777
|
-
} catch {}
|
|
1778
|
-
});
|
|
1779
|
-
},
|
|
1780
|
-
cancel: stop
|
|
1781
|
-
});
|
|
1782
|
-
return new Response(body, { headers: {
|
|
1783
|
-
"Content-Type": "text/event-stream",
|
|
1784
|
-
"Cache-Control": "no-cache, no-transform",
|
|
1785
|
-
"X-Accel-Buffering": "no"
|
|
1786
|
-
} });
|
|
1787
|
-
}
|
|
1788
|
-
// src/server/media.ts
|
|
1789
|
-
/** Raster images only: an SVG opened directly could run script on this origin. */
|
|
1790
|
-
const IMAGE_MIME = {
|
|
1791
|
-
png: "image/png",
|
|
1792
|
-
jpg: "image/jpeg",
|
|
1793
|
-
jpeg: "image/jpeg",
|
|
1794
|
-
webp: "image/webp",
|
|
1795
|
-
gif: "image/gif",
|
|
1796
|
-
bmp: "image/bmp",
|
|
1797
|
-
avif: "image/avif"
|
|
1798
|
-
};
|
|
1799
|
-
const MAX_IMAGE_BYTES = 16777216;
|
|
1800
|
-
const extension = (path) => /\.([a-z0-9]+)$/i.exec(path)?.[1]?.toLowerCase() ?? "";
|
|
1801
|
-
const imageMime = (path) => IMAGE_MIME[extension(path)] ?? null;
|
|
1802
|
-
/** True when the daemon runs on this machine (loopback TCP/WebSocket or a local socket). */
|
|
1803
|
-
function isLocalConnection(connection) {
|
|
1804
|
-
try {
|
|
1805
|
-
const target = parseHostTarget(connection);
|
|
1806
|
-
if (target.kind !== "socket") return false;
|
|
1807
|
-
if (target.socketPath) return true;
|
|
1808
|
-
const host = new URL(target.url ?? "").hostname.replace(/^\[|\]$/g, "");
|
|
1809
|
-
return host === "localhost" || host === "::1" || /^127\./.test(host);
|
|
1810
|
-
} catch {
|
|
1811
|
-
return false;
|
|
1812
|
-
}
|
|
1813
|
-
}
|
|
1814
|
-
/**
|
|
1815
|
-
* Images a provider returned inline (screenshots, `read` of a PNG) are written by the daemon to
|
|
1816
|
-
* `<tmp>/paseo-attachments-XXXXXX/<sha256>.<ext>` and referenced from the message as file:// URLs.
|
|
1817
|
-
* The daemon's file API is confined to the workspace, so these are read from disk, and only when
|
|
1818
|
-
* the daemon shares this machine. The name pattern admits nothing but those materialized files.
|
|
1819
|
-
*/
|
|
1820
|
-
function isMaterializedImagePath(path) {
|
|
1821
|
-
if (!isAbsolute(path) || normalize(path) !== path || !imageMime(path)) return false;
|
|
1822
|
-
const directory = dirname(path);
|
|
1823
|
-
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));
|
|
1824
|
-
}
|
|
1825
|
-
async function readMaterializedImage(path) {
|
|
1826
|
-
if (!isMaterializedImagePath(path)) return null;
|
|
1827
|
-
try {
|
|
1828
|
-
const stats = await lstat(path);
|
|
1829
|
-
if (!stats.isFile() || stats.size > 16777216) return null;
|
|
1830
|
-
if (!isMaterializedImagePath(await realpath(path))) return null;
|
|
1831
|
-
return await readFile(path);
|
|
1832
|
-
} catch {
|
|
1833
|
-
return null;
|
|
1834
|
-
}
|
|
1835
|
-
}
|
|
1836
|
-
/** Small LRU for project icons: a sidebar asks for each project once per page load. */
|
|
1837
|
-
var IconCache = class {
|
|
1838
|
-
entries = /* @__PURE__ */ new Map();
|
|
1839
|
-
limit;
|
|
1840
|
-
ttlMs;
|
|
1841
|
-
constructor(limit = 256, ttlMs = 6e5) {
|
|
1842
|
-
this.limit = limit;
|
|
1843
|
-
this.ttlMs = ttlMs;
|
|
1844
|
-
}
|
|
1845
|
-
get(key) {
|
|
1846
|
-
const entry = this.entries.get(key);
|
|
1847
|
-
if (!entry) return void 0;
|
|
1848
|
-
if (Date.now() - entry.at > this.ttlMs) {
|
|
1849
|
-
this.entries.delete(key);
|
|
1850
|
-
return;
|
|
1851
|
-
}
|
|
1852
|
-
this.entries.delete(key);
|
|
1853
|
-
this.entries.set(key, entry);
|
|
1854
|
-
return entry.icon;
|
|
1855
|
-
}
|
|
1856
|
-
set(key, icon) {
|
|
1857
|
-
this.entries.delete(key);
|
|
1858
|
-
this.entries.set(key, {
|
|
1859
|
-
at: Date.now(),
|
|
1860
|
-
icon
|
|
1861
|
-
});
|
|
1862
|
-
if (this.entries.size > this.limit) this.entries.delete(this.entries.keys().next().value);
|
|
1863
|
-
}
|
|
1864
|
-
};
|
|
1865
|
-
// src/server/workspace-routes.ts
|
|
1866
|
-
/** Text files larger than this open truncated: the viewer is for reading, not for dumps. */
|
|
1867
|
-
const MAX_TEXT_BYTES = 1048576;
|
|
1868
|
-
const MAX_ENTRIES = 2e3;
|
|
1869
|
-
/** Terminal output is coalesced into one event per frame-ish interval. */
|
|
1870
|
-
const TERMINAL_FLUSH_MS = 16;
|
|
1871
|
-
const path = z.string().min(1).max(4096).refine((p) => !p.includes("\0"));
|
|
1872
|
-
/**
|
|
1873
|
-
* The workspace side panel (files, terminals) and schedules. Every call goes to the host's
|
|
1874
|
-
* daemon, which confines file access to the workspace and owns the terminals; nothing here
|
|
1875
|
-
* keeps state beyond an open terminal stream.
|
|
1876
|
-
*/
|
|
1877
|
-
function registerWorkspaceRoutes(app, hosts, store, valid) {
|
|
1878
|
-
app.get("/api/hosts/:host/fs/list", async (c) => {
|
|
1879
|
-
const cwd = path.parse(c.req.query("cwd"));
|
|
1880
|
-
const dir = c.req.query("path") || ".";
|
|
1881
|
-
const { driver } = hosts.get(c.req.param("host"));
|
|
1882
|
-
try {
|
|
1883
|
-
const result = await driver.listDirectory(cwd, dir);
|
|
1884
|
-
const entries = (result.entries ?? []).map((e) => ({
|
|
1885
|
-
name: e.name,
|
|
1886
|
-
path: e.path,
|
|
1887
|
-
kind: e.kind,
|
|
1888
|
-
size: e.size
|
|
1889
|
-
})).sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name, void 0, { numeric: true }) : a.kind === "directory" ? -1 : 1);
|
|
1890
|
-
return c.json({
|
|
1891
|
-
path: result.path,
|
|
1892
|
-
entries: entries.slice(0, MAX_ENTRIES),
|
|
1893
|
-
truncated: entries.length > MAX_ENTRIES
|
|
1894
|
-
});
|
|
1895
|
-
} catch (error) {
|
|
1896
|
-
return c.json({ error: error.message || "Directory unavailable" }, 404);
|
|
1897
|
-
}
|
|
1898
|
-
});
|
|
1899
|
-
app.get("/api/hosts/:host/fs/read", async (c) => {
|
|
1900
|
-
const cwd = path.parse(c.req.query("cwd"));
|
|
1901
|
-
const file = path.parse(c.req.query("path"));
|
|
1902
|
-
const { driver } = hosts.get(c.req.param("host"));
|
|
1903
|
-
try {
|
|
1904
|
-
const result = await driver.readFile(cwd, file, void 0, 1048577);
|
|
1905
|
-
const text = result.kind === "text" ? new TextDecoder().decode(result.bytes.subarray(0, MAX_TEXT_BYTES)) : void 0;
|
|
1906
|
-
return c.json({
|
|
1907
|
-
path: result.path,
|
|
1908
|
-
kind: result.kind,
|
|
1909
|
-
mime: result.mime,
|
|
1910
|
-
size: result.size,
|
|
1911
|
-
modifiedAt: result.modifiedAt,
|
|
1912
|
-
...text !== void 0 ? {
|
|
1913
|
-
text,
|
|
1914
|
-
truncated: result.size > MAX_TEXT_BYTES
|
|
1915
|
-
} : {}
|
|
1916
|
-
});
|
|
1917
|
-
} catch (error) {
|
|
1918
|
-
return c.json({ error: error.message || "File unavailable" }, 404);
|
|
1919
|
-
}
|
|
1920
|
-
});
|
|
1921
|
-
app.get("/api/hosts/:host/fs/raw", async (c) => {
|
|
1922
|
-
const cwd = path.parse(c.req.query("cwd"));
|
|
1923
|
-
const file = path.parse(c.req.query("path"));
|
|
1924
|
-
const mime = imageMime(file);
|
|
1925
|
-
if (!mime) return c.json({ error: "Only images can be opened raw" }, 415);
|
|
1926
|
-
const { driver } = hosts.get(c.req.param("host"));
|
|
1927
|
-
try {
|
|
1928
|
-
const result = await driver.readFile(cwd, file, void 0, MAX_IMAGE_BYTES);
|
|
1929
|
-
return c.body(result.bytes, 200, {
|
|
1930
|
-
"Content-Type": mime,
|
|
1931
|
-
"Cache-Control": "private, max-age=60"
|
|
1932
|
-
});
|
|
1933
|
-
} catch {
|
|
1934
|
-
return c.json({ error: "Image unavailable" }, 404);
|
|
1935
|
-
}
|
|
1936
|
-
});
|
|
1937
|
-
app.get("/api/hosts/:host/terminals", async (c) => {
|
|
1938
|
-
const cwd = path.parse(c.req.query("cwd"));
|
|
1939
|
-
const result = await hosts.get(c.req.param("host")).driver.listTerminals(cwd);
|
|
1940
|
-
return c.json((result.terminals ?? []).map((t) => ({
|
|
1941
|
-
id: t.id,
|
|
1942
|
-
name: t.name,
|
|
1943
|
-
title: t.title ?? null,
|
|
1944
|
-
cwd: t.cwd
|
|
1945
|
-
})));
|
|
1946
|
-
});
|
|
1947
|
-
app.post("/api/hosts/:host/terminals", async (c) => {
|
|
1948
|
-
const input = z.object({
|
|
1949
|
-
cwd: path,
|
|
1950
|
-
rows: z.number().int().min(4).max(500),
|
|
1951
|
-
cols: z.number().int().min(10).max(1e3),
|
|
1952
|
-
name: z.string().max(80).optional()
|
|
1953
|
-
}).parse(await c.req.json());
|
|
1954
|
-
const result = await hosts.get(c.req.param("host")).driver.createTerminal(input.cwd, input.name, void 0, { size: {
|
|
1955
|
-
rows: input.rows,
|
|
1956
|
-
cols: input.cols
|
|
1957
|
-
} });
|
|
1958
|
-
if (!result.terminal) return c.json({ error: result.error ?? "Could not open a terminal" }, 502);
|
|
1959
|
-
return c.json({
|
|
1960
|
-
id: result.terminal.id,
|
|
1961
|
-
name: result.terminal.name,
|
|
1962
|
-
title: result.terminal.title ?? null,
|
|
1963
|
-
cwd: result.terminal.cwd
|
|
1964
|
-
}, 201);
|
|
1965
|
-
});
|
|
1966
|
-
app.delete("/api/hosts/:host/terminals/:id", async (c) => {
|
|
1967
|
-
await hosts.get(c.req.param("host")).driver.killTerminal(c.req.param("id"));
|
|
1968
|
-
return c.json({ ok: true });
|
|
1969
|
-
});
|
|
1970
|
-
app.post("/api/hosts/:host/terminals/:id/input", async (c) => {
|
|
1971
|
-
const input = z.union([z.object({ data: z.string().min(1).max(65536) }), z.object({
|
|
1972
|
-
rows: z.number().int().min(4).max(500),
|
|
1973
|
-
cols: z.number().int().min(10).max(1e3)
|
|
1974
|
-
})]).parse(await c.req.json());
|
|
1975
|
-
const { driver } = hosts.get(c.req.param("host"));
|
|
1976
|
-
driver.sendTerminalInput(c.req.param("id"), "data" in input ? {
|
|
1977
|
-
type: "input",
|
|
1978
|
-
data: input.data
|
|
1979
|
-
} : {
|
|
1980
|
-
type: "resize",
|
|
1981
|
-
rows: input.rows,
|
|
1982
|
-
cols: input.cols
|
|
1983
|
-
});
|
|
1984
|
-
return c.json({ ok: true });
|
|
1985
|
-
});
|
|
1986
|
-
/** Live output as SSE: a full replay first (scrollback), then coalesced output chunks. */
|
|
1987
|
-
app.get("/api/hosts/:host/terminals/:id/stream", (c) => {
|
|
1988
|
-
const { driver } = hosts.get(c.req.param("host"));
|
|
1989
|
-
const id = c.req.param("id");
|
|
1990
|
-
const rows = Number(c.req.query("rows")) || 24, cols = Number(c.req.query("cols")) || 80;
|
|
1991
|
-
return eventStream(c.req.raw.signal, (send) => {
|
|
1992
|
-
let pending = [];
|
|
1993
|
-
let timer;
|
|
1994
|
-
const flush = () => {
|
|
1995
|
-
timer = void 0;
|
|
1996
|
-
if (!pending.length) return;
|
|
1997
|
-
send({
|
|
1998
|
-
t: "o",
|
|
1999
|
-
d: Buffer.concat(pending).toString("base64")
|
|
2000
|
-
});
|
|
2001
|
-
pending = [];
|
|
2002
|
-
};
|
|
2003
|
-
const push = (bytes) => {
|
|
2004
|
-
pending.push(bytes);
|
|
2005
|
-
timer ??= setTimeout(flush, TERMINAL_FLUSH_MS);
|
|
2006
|
-
};
|
|
2007
|
-
const subscription = driver.observeTerminal(id, (event) => {
|
|
2008
|
-
if (event.type === "output") push(event.data);
|
|
2009
|
-
else if (event.replay.type === "begin") {
|
|
2010
|
-
pending = [];
|
|
2011
|
-
send({ t: "reset" });
|
|
2012
|
-
} else if (event.replay.type === "data") push(event.replay.data);
|
|
2013
|
-
}, { restore: {
|
|
2014
|
-
mode: "full-snapshot",
|
|
2015
|
-
scrollbackLines: 2e3,
|
|
2016
|
-
size: {
|
|
2017
|
-
rows,
|
|
2018
|
-
cols
|
|
2019
|
-
}
|
|
2020
|
-
} });
|
|
2021
|
-
const stop = subscription.subscribe({
|
|
2022
|
-
snapshot: () => {},
|
|
2023
|
-
update: (message) => {
|
|
2024
|
-
if (message.type === "terminal_stream_exit") send({ t: "exit" });
|
|
2025
|
-
},
|
|
2026
|
-
error: () => send({ t: "exit" })
|
|
2027
|
-
});
|
|
2028
|
-
subscription.ready.catch(() => send({ t: "exit" }));
|
|
2029
|
-
return () => {
|
|
2030
|
-
clearTimeout(timer);
|
|
2031
|
-
stop();
|
|
2032
|
-
subscription.release().catch(() => {});
|
|
2033
|
-
};
|
|
2034
|
-
}, valid(c));
|
|
2035
|
-
});
|
|
2036
|
-
/** Every connected host's schedules; a host that fails reports its error instead. */
|
|
2037
|
-
app.get("/api/schedules", async (c) => {
|
|
2038
|
-
const results = await Promise.all(store.hosts().map(async (h) => {
|
|
2039
|
-
try {
|
|
2040
|
-
if (hosts.state(h.id) !== "connected") return {
|
|
2041
|
-
hostId: h.id,
|
|
2042
|
-
schedules: [],
|
|
2043
|
-
error: "Host is offline"
|
|
2044
|
-
};
|
|
2045
|
-
const list = await hosts.get(h.id).driver.scheduleList();
|
|
2046
|
-
return {
|
|
2047
|
-
hostId: h.id,
|
|
2048
|
-
schedules: list.schedules ?? [],
|
|
2049
|
-
error: list.error ?? null
|
|
2050
|
-
};
|
|
2051
|
-
} catch (error) {
|
|
2052
|
-
return {
|
|
2053
|
-
hostId: h.id,
|
|
2054
|
-
schedules: [],
|
|
2055
|
-
error: error.message || "Schedules unavailable"
|
|
2056
|
-
};
|
|
2057
|
-
}
|
|
2058
|
-
}));
|
|
2059
|
-
return c.json(results);
|
|
2060
|
-
});
|
|
2061
|
-
app.post("/api/hosts/:host/schedules", async (c) => {
|
|
2062
|
-
const input = z.object({
|
|
2063
|
-
name: z.string().trim().max(120).optional(),
|
|
2064
|
-
prompt: z.string().trim().min(1).max(2e4),
|
|
2065
|
-
cron: z.string().trim().min(9).max(120),
|
|
2066
|
-
timezone: z.string().max(80).optional(),
|
|
2067
|
-
cwd: path,
|
|
2068
|
-
provider: z.string().min(1).max(200),
|
|
2069
|
-
model: z.string().min(1).max(300).optional(),
|
|
2070
|
-
thinkingOptionId: z.string().min(1).max(200).optional(),
|
|
2071
|
-
archiveOnFinish: z.boolean().default(true),
|
|
2072
|
-
runOnCreate: z.boolean().default(false)
|
|
2073
|
-
}).parse(await c.req.json());
|
|
2074
|
-
const result = await hosts.get(c.req.param("host")).driver.scheduleCreate({
|
|
2075
|
-
prompt: input.prompt,
|
|
2076
|
-
name: input.name || null,
|
|
2077
|
-
cadence: {
|
|
2078
|
-
type: "cron",
|
|
2079
|
-
expression: input.cron,
|
|
2080
|
-
...input.timezone ? { timezone: input.timezone } : {}
|
|
2081
|
-
},
|
|
2082
|
-
target: {
|
|
2083
|
-
type: "new-agent",
|
|
2084
|
-
config: {
|
|
2085
|
-
provider: input.provider,
|
|
2086
|
-
cwd: input.cwd,
|
|
2087
|
-
...input.model ? { model: input.model } : {},
|
|
2088
|
-
...input.thinkingOptionId ? { thinkingOptionId: input.thinkingOptionId } : {},
|
|
2089
|
-
archiveOnFinish: input.archiveOnFinish,
|
|
2090
|
-
isolation: "local",
|
|
2091
|
-
title: input.name || null
|
|
2092
|
-
}
|
|
2093
|
-
},
|
|
2094
|
-
runOnCreate: input.runOnCreate
|
|
2095
|
-
});
|
|
2096
|
-
if (result.error) return c.json({ error: result.error }, 400);
|
|
2097
|
-
return c.json(result.schedule, 201);
|
|
2098
|
-
});
|
|
2099
|
-
app.patch("/api/hosts/:host/schedules/:id", async (c) => {
|
|
2100
|
-
const input = z.object({
|
|
2101
|
-
name: z.string().trim().max(120).nullable().optional(),
|
|
2102
|
-
prompt: z.string().trim().min(1).max(2e4).optional(),
|
|
2103
|
-
cron: z.string().trim().min(9).max(120).optional(),
|
|
2104
|
-
timezone: z.string().max(80).optional(),
|
|
2105
|
-
cwd: path.optional(),
|
|
2106
|
-
provider: z.string().min(1).max(200).optional(),
|
|
2107
|
-
model: z.string().min(1).max(300).nullable().optional(),
|
|
2108
|
-
archiveOnFinish: z.boolean().optional()
|
|
2109
|
-
}).parse(await c.req.json());
|
|
2110
|
-
const agentConfig = {
|
|
2111
|
-
...input.provider ? { provider: input.provider } : {},
|
|
2112
|
-
...input.model !== void 0 ? { model: input.model } : {},
|
|
2113
|
-
...input.cwd ? { cwd: input.cwd } : {},
|
|
2114
|
-
...input.archiveOnFinish !== void 0 ? { archiveOnFinish: input.archiveOnFinish } : {}
|
|
2115
|
-
};
|
|
2116
|
-
const result = await hosts.get(c.req.param("host")).driver.scheduleUpdate({
|
|
2117
|
-
id: c.req.param("id"),
|
|
2118
|
-
...input.name !== void 0 ? { name: input.name || null } : {},
|
|
2119
|
-
...input.prompt ? { prompt: input.prompt } : {},
|
|
2120
|
-
...input.cron ? { cadence: {
|
|
2121
|
-
type: "cron",
|
|
2122
|
-
expression: input.cron,
|
|
2123
|
-
...input.timezone ? { timezone: input.timezone } : {}
|
|
2124
|
-
} } : {},
|
|
2125
|
-
...Object.keys(agentConfig).length ? { newAgentConfig: agentConfig } : {}
|
|
2126
|
-
});
|
|
2127
|
-
if (result?.error) return c.json({ error: result.error }, 400);
|
|
2128
|
-
return c.json(result?.schedule ?? { ok: true });
|
|
2129
|
-
});
|
|
2130
|
-
const action = (name) => async (c) => {
|
|
2131
|
-
const { driver } = hosts.get(c.req.param("host"));
|
|
2132
|
-
const options = { id: c.req.param("id") };
|
|
2133
|
-
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);
|
|
2134
|
-
if (result?.error) return c.json({ error: result.error }, 400);
|
|
2135
|
-
return c.json(name === "logs" ? { runs: (result.runs ?? []).slice(-50).reverse() } : { ok: true });
|
|
2136
|
-
};
|
|
2137
|
-
app.post("/api/hosts/:host/schedules/:id/pause", action("pause"));
|
|
2138
|
-
app.post("/api/hosts/:host/schedules/:id/resume", action("resume"));
|
|
2139
|
-
app.post("/api/hosts/:host/schedules/:id/run", action("run"));
|
|
2140
|
-
app.delete("/api/hosts/:host/schedules/:id", action("delete"));
|
|
2141
|
-
app.get("/api/hosts/:host/schedules/:id/logs", action("logs"));
|
|
2142
|
-
}
|
|
2143
|
-
// src/server/attachments.ts
|
|
2144
|
-
const MAX_FILE_BYTES = 8388608;
|
|
2145
|
-
const MAX_TOTAL = 67108864;
|
|
2146
|
-
const TTL = 12e5;
|
|
2147
|
-
const IMAGE_TYPES = /* @__PURE__ */ new Set([
|
|
2148
|
-
"image/png",
|
|
2149
|
-
"image/jpeg",
|
|
2150
|
-
"image/webp",
|
|
2151
|
-
"image/gif"
|
|
2152
|
-
]);
|
|
2153
|
-
const MAX_FILES = 256;
|
|
2154
|
-
var Attachments = class {
|
|
2155
|
-
/** Insertion order is expiry order (fixed TTL), so pruning stops at the first live entry. */
|
|
2156
|
-
entries = /* @__PURE__ */ new Map();
|
|
2157
|
-
totalBytes = 0;
|
|
2158
|
-
owners = /* @__PURE__ */ new Map();
|
|
2159
|
-
timer = setInterval(() => this.prune(), 6e4);
|
|
2160
|
-
constructor() {
|
|
2161
|
-
this.timer.unref();
|
|
2162
|
-
}
|
|
2163
|
-
close() {
|
|
2164
|
-
clearInterval(this.timer);
|
|
2165
|
-
this.entries.clear();
|
|
2166
|
-
this.owners.clear();
|
|
2167
|
-
this.totalBytes = 0;
|
|
2168
|
-
}
|
|
2169
|
-
delete(id) {
|
|
2170
|
-
const entry = this.entries.get(id);
|
|
2171
|
-
if (!entry) return;
|
|
2172
|
-
this.entries.delete(id);
|
|
2173
|
-
this.totalBytes -= entry.bytes.length;
|
|
2174
|
-
const own = this.owners.get(entry.owner);
|
|
2175
|
-
own.bytes -= entry.bytes.length;
|
|
2176
|
-
if (!--own.files) this.owners.delete(entry.owner);
|
|
2177
|
-
}
|
|
2178
|
-
/** O(expired entries). */
|
|
2179
|
-
prune(now = Date.now()) {
|
|
2180
|
-
for (const [id, entry] of this.entries) {
|
|
2181
|
-
if (entry.expires > now) break;
|
|
2182
|
-
this.delete(id);
|
|
2183
|
-
}
|
|
2184
|
-
}
|
|
2185
|
-
clearOwner(owner) {
|
|
2186
|
-
if (!this.owners.has(owner)) return;
|
|
2187
|
-
for (const [id, entry] of this.entries) if (entry.owner === owner) this.delete(id);
|
|
2188
|
-
}
|
|
2189
|
-
put(owner, host, agent, name, mime, bytes) {
|
|
2190
|
-
this.prune();
|
|
2191
|
-
if (!name || name.length > 200 || /[\x00-\x1f/\\]/.test(name)) throw new Error("Use a file name without path separators.");
|
|
2192
|
-
if (!bytes.length || bytes.length > 8388608) throw new Error("Files must be between 1 byte and 8 MiB.");
|
|
2193
|
-
const own = this.owners.get(owner) ?? {
|
|
2194
|
-
bytes: 0,
|
|
2195
|
-
files: 0
|
|
2196
|
-
};
|
|
2197
|
-
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.");
|
|
2198
|
-
if (IMAGE_TYPES.has(mime)) {
|
|
2199
|
-
if (!(mime === "image/png" ? bytes.subarray(0, 8).equals(Buffer.from([
|
|
2200
|
-
137,
|
|
2201
|
-
80,
|
|
2202
|
-
78,
|
|
2203
|
-
71,
|
|
2204
|
-
13,
|
|
2205
|
-
10,
|
|
2206
|
-
26,
|
|
2207
|
-
10
|
|
2208
|
-
])) : 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.");
|
|
2209
|
-
}
|
|
2210
|
-
const entry = {
|
|
2211
|
-
id: randomUUID(),
|
|
2212
|
-
owner,
|
|
2213
|
-
host,
|
|
2214
|
-
agent,
|
|
2215
|
-
name,
|
|
2216
|
-
mime,
|
|
2217
|
-
bytes,
|
|
2218
|
-
expires: Date.now() + TTL
|
|
2219
|
-
};
|
|
2220
|
-
this.entries.set(entry.id, entry);
|
|
2221
|
-
this.totalBytes += bytes.length;
|
|
2222
|
-
this.owners.set(owner, {
|
|
2223
|
-
bytes: own.bytes + bytes.length,
|
|
2224
|
-
files: own.files + 1
|
|
2225
|
-
});
|
|
2226
|
-
return {
|
|
2227
|
-
id: entry.id,
|
|
2228
|
-
name,
|
|
2229
|
-
mimeType: mime,
|
|
2230
|
-
size: bytes.length,
|
|
2231
|
-
expires: entry.expires
|
|
2232
|
-
};
|
|
2233
|
-
}
|
|
2234
|
-
get(id, owner, host, agent) {
|
|
2235
|
-
this.prune();
|
|
2236
|
-
const entry = this.entries.get(id);
|
|
2237
|
-
if (entry && entry.expires <= Date.now()) this.delete(id);
|
|
2238
|
-
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.");
|
|
2239
|
-
return entry;
|
|
2240
|
-
}
|
|
2241
|
-
remove(id, owner, host, agent) {
|
|
2242
|
-
this.get(id, owner, host, agent);
|
|
2243
|
-
this.delete(id);
|
|
2244
|
-
}
|
|
2245
|
-
async capabilities(hosts, host, agent) {
|
|
2246
|
-
const client = hosts.get(host);
|
|
2247
|
-
let facts = client.directory.facts(agent);
|
|
2248
|
-
if (!facts) {
|
|
2249
|
-
const ref = client.api.agents.ref(agent);
|
|
2250
|
-
await ref.refresh();
|
|
2251
|
-
facts = {
|
|
2252
|
-
provider: ref.current()?.provider,
|
|
2253
|
-
capabilities: ref.capabilities
|
|
2254
|
-
};
|
|
2255
|
-
}
|
|
2256
|
-
const provider = facts.provider ?? "";
|
|
2257
|
-
return {
|
|
2258
|
-
images: [
|
|
2259
|
-
"codex",
|
|
2260
|
-
"claude",
|
|
2261
|
-
"pi"
|
|
2262
|
-
].includes(provider) && facts.capabilities?.supportsImages !== false,
|
|
2263
|
-
files: facts.capabilities?.supportsToolInvocations === true,
|
|
2264
|
-
maxBytes: MAX_FILE_BYTES,
|
|
2265
|
-
note: "Images require a vision-capable model. Other files are uploaded to the daemon for the agent to read with its tools."
|
|
2266
|
-
};
|
|
2267
|
-
}
|
|
2268
|
-
async prepare(hosts, owner, host, agent, ids) {
|
|
2269
|
-
const entries = ids.map((id) => this.get(id, owner, host, agent));
|
|
2270
|
-
if (!entries.length) return {
|
|
2271
|
-
images: [],
|
|
2272
|
-
attachments: []
|
|
2273
|
-
};
|
|
2274
|
-
const caps = await this.capabilities(hosts, host, agent).catch(() => {
|
|
2275
|
-
throw new Error("Could not verify attachment support. Reconnect the host and retry.");
|
|
2276
|
-
});
|
|
2277
|
-
const images = [], attachments = [];
|
|
2278
|
-
for (const entry of entries) if (IMAGE_TYPES.has(entry.mime)) {
|
|
2279
|
-
if (!caps.images) throw new Error("This provider does not support image attachments.");
|
|
2280
|
-
images.push({
|
|
2281
|
-
data: entry.bytes.toString("base64"),
|
|
2282
|
-
mimeType: entry.mime
|
|
2283
|
-
});
|
|
2284
|
-
} else {
|
|
2285
|
-
if (!caps.files) throw new Error("This agent cannot read uploaded files.");
|
|
2286
|
-
if (!entry.remote) {
|
|
2287
|
-
const uploaded = await hosts.get(host).driver.uploadFile({
|
|
2288
|
-
fileName: entry.name,
|
|
2289
|
-
mimeType: entry.mime,
|
|
2290
|
-
bytes: entry.bytes
|
|
2291
|
-
}).catch(() => {
|
|
2292
|
-
throw new Error("Daemon file upload failed. Retry the upload before sending.");
|
|
2293
|
-
});
|
|
2294
|
-
if (uploaded.error || !uploaded.file) throw new Error("Daemon file upload failed. Retry the upload before sending.");
|
|
2295
|
-
entry.remote = uploaded.file;
|
|
2296
|
-
}
|
|
2297
|
-
attachments.push(entry.remote);
|
|
2298
|
-
}
|
|
2299
|
-
return {
|
|
2300
|
-
images,
|
|
2301
|
-
attachments
|
|
2302
|
-
};
|
|
2303
|
-
}
|
|
2304
|
-
consumed(ids) {
|
|
2305
|
-
for (const id of ids) this.delete(id);
|
|
2306
|
-
}
|
|
2307
|
-
};
|
|
2308
|
-
// src/server/message-status.ts
|
|
2309
|
-
/** Positive evidence only. Missing, rewound, or out-of-window messages remain uncertain. */
|
|
2310
|
-
async function confirmedMessages(driver, agentId, ids, maxPages = 5) {
|
|
2311
|
-
const wanted = new Set(ids), confirmed = /* @__PURE__ */ new Set();
|
|
2312
|
-
let cursor = null;
|
|
2313
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2314
|
-
for (let pageNumber = 0; pageNumber < maxPages && confirmed.size < wanted.size; pageNumber++) {
|
|
2315
|
-
const page = await driver.fetchAgentTimeline(agentId, {
|
|
2316
|
-
direction: cursor ? "before" : "tail",
|
|
2317
|
-
...cursor ? { cursor } : {},
|
|
2318
|
-
limit: 200,
|
|
2319
|
-
projection: "projected"
|
|
2320
|
-
});
|
|
2321
|
-
for (const entry of page.entries) {
|
|
2322
|
-
const item = entry.item;
|
|
2323
|
-
if (item.type !== "user_message") continue;
|
|
2324
|
-
const id = item.clientMessageId ?? item.messageId;
|
|
2325
|
-
if (typeof id === "string" && wanted.has(id)) confirmed.add(id);
|
|
2326
|
-
}
|
|
2327
|
-
if (!page.hasOlder || !page.startCursor) break;
|
|
2328
|
-
const key = JSON.stringify(page.startCursor);
|
|
2329
|
-
if (seen.has(key)) break;
|
|
2330
|
-
seen.add(key);
|
|
2331
|
-
cursor = page.startCursor;
|
|
2332
|
-
}
|
|
2333
|
-
return [...confirmed];
|
|
2334
|
-
}
|
|
2335
|
-
// src/server/auth.ts
|
|
2336
|
-
/** Sliding session lifetime: a device that keeps using the console stays signed in. */
|
|
2337
|
-
const SESSION_TTL_MS = 2592e6;
|
|
2338
|
-
const TOUCH_INTERVAL_MS = 36e5;
|
|
2339
|
-
const TOTP_PERIOD_S = 30;
|
|
2340
|
-
const TOTP_DIGITS = 6;
|
|
2341
|
-
/** Only clients that know the access token can reach TOTP verification.
|
|
2342
|
-
* Code attempts have a persistent server-wide budget across IPs and restarts.
|
|
2343
|
-
* Exhausting it doubles the lockout from 15 minutes to at most 24 hours.
|
|
2344
|
-
*/
|
|
2345
|
-
const WINDOW_MS = 9e5;
|
|
2346
|
-
const MAX_CODE_FAILURES_PER_CLIENT = 5;
|
|
2347
|
-
const MAX_CODE_FAILURES_GLOBAL = 20;
|
|
2348
|
-
const MAX_LOCK_MS = 864e5;
|
|
2349
|
-
const MAX_TOKEN_FAILURES_PER_CLIENT = 10;
|
|
2350
|
-
const BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
2351
|
-
function base32Encode(bytes) {
|
|
2352
|
-
let bits = 0, value = 0, out = "";
|
|
2353
|
-
for (const byte of bytes) {
|
|
2354
|
-
value = value << 8 | byte;
|
|
2355
|
-
bits += 8;
|
|
2356
|
-
while (bits >= 5) {
|
|
2357
|
-
out += BASE32[value >>> bits - 5 & 31];
|
|
2358
|
-
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;
|
|
2359
752
|
}
|
|
2360
753
|
}
|
|
2361
754
|
if (bits > 0) out += BASE32[value << 5 - bits & 31];
|
|
@@ -2585,1885 +978,86 @@ var Auth = class {
|
|
|
2585
978
|
if (this.totpEnabled()) throw new Error("Disable the current authenticator before replacing it");
|
|
2586
979
|
const secret = base32Encode(randomBytes(20));
|
|
2587
980
|
this.pendingTotp = {
|
|
2588
|
-
secret,
|
|
2589
|
-
sessionId,
|
|
2590
|
-
expires: now + 6e5
|
|
2591
|
-
};
|
|
2592
|
-
return {
|
|
2593
|
-
secret,
|
|
2594
|
-
uri: `otpauth://totp/LitePaseo?secret=${secret}&issuer=LitePaseo&algorithm=SHA1&digits=6&period=30`
|
|
2595
|
-
};
|
|
2596
|
-
}
|
|
2597
|
-
/** Enables the pending secret once the user proves their app produces matching codes. */
|
|
2598
|
-
confirmTotp(sessionId, code, now = Date.now()) {
|
|
2599
|
-
if (this.totpEnabled()) return false;
|
|
2600
|
-
const pending = this.pendingTotp;
|
|
2601
|
-
if (!pending || pending.sessionId !== sessionId || pending.expires < now) return false;
|
|
2602
|
-
const step = matchTotp(base32Decode(pending.secret), code, now);
|
|
2603
|
-
if (step === null) return false;
|
|
2604
|
-
this.store.db.exec("BEGIN IMMEDIATE");
|
|
2605
|
-
try {
|
|
2606
|
-
this.store.setSetting("totp_secret", pending.secret);
|
|
2607
|
-
this.store.setSetting("totp_last_step", String(step));
|
|
2608
|
-
this.store.db.prepare("DELETE FROM push_subscriptions WHERE session_id<>?").run(sessionId);
|
|
2609
|
-
this.store.db.prepare("DELETE FROM sessions WHERE id<>?").run(sessionId);
|
|
2610
|
-
this.resetCodeLimit();
|
|
2611
|
-
this.store.db.exec("COMMIT");
|
|
2612
|
-
} catch (error) {
|
|
2613
|
-
this.store.db.exec("ROLLBACK");
|
|
2614
|
-
throw error;
|
|
2615
|
-
}
|
|
2616
|
-
this.pendingTotp = null;
|
|
2617
|
-
return true;
|
|
2618
|
-
}
|
|
2619
|
-
disableTotp(code, now = Date.now()) {
|
|
2620
|
-
if (this.limited("settings", true, now)) return false;
|
|
2621
|
-
const secret = this.store.setting("totp_secret");
|
|
2622
|
-
const step = secret ? matchTotp(base32Decode(secret), code, now) : null;
|
|
2623
|
-
if (step === null || !this.store.advanceSetting("totp_last_step", step)) {
|
|
2624
|
-
this.fail("settings", true, now);
|
|
2625
|
-
return false;
|
|
2626
|
-
}
|
|
2627
|
-
this.store.setSetting("totp_secret", null);
|
|
2628
|
-
this.resetCodeLimit();
|
|
2629
|
-
return true;
|
|
2630
|
-
}
|
|
2631
|
-
resetCodeLimit() {
|
|
2632
|
-
this.global = {
|
|
2633
|
-
count: 0,
|
|
2634
|
-
reset: 0,
|
|
2635
|
-
lockMs: WINDOW_MS
|
|
2636
|
-
};
|
|
2637
|
-
this.store.setSetting("totp_login_limit", JSON.stringify(this.global));
|
|
2638
|
-
}
|
|
2639
|
-
limited(client, usesCode, now) {
|
|
2640
|
-
if (usesCode && this.global.reset > now && this.global.count >= MAX_CODE_FAILURES_GLOBAL) return Math.ceil((this.global.reset - now) / 1e3);
|
|
2641
|
-
const map = usesCode ? this.codeFailures : this.tokenFailures;
|
|
2642
|
-
if (!map.has(client) && map.size >= 1e4) client = "overflow";
|
|
2643
|
-
const entry = map.get(client);
|
|
2644
|
-
const max = usesCode ? MAX_CODE_FAILURES_PER_CLIENT : MAX_TOKEN_FAILURES_PER_CLIENT;
|
|
2645
|
-
if (entry && entry.reset > now && entry.count >= max) return Math.ceil((entry.reset - now) / 1e3);
|
|
2646
|
-
return 0;
|
|
2647
|
-
}
|
|
2648
|
-
fail(client, usesCode, now) {
|
|
2649
|
-
if (usesCode) {
|
|
2650
|
-
if (this.global.reset <= now) this.global.count = 0;
|
|
2651
|
-
this.global.count++;
|
|
2652
|
-
if (this.global.count === MAX_CODE_FAILURES_GLOBAL) {
|
|
2653
|
-
this.global.reset = now + this.global.lockMs;
|
|
2654
|
-
this.global.lockMs = Math.min(this.global.lockMs * 2, MAX_LOCK_MS);
|
|
2655
|
-
} else if (this.global.reset <= now) this.global.reset = now + WINDOW_MS;
|
|
2656
|
-
this.store.setSetting("totp_login_limit", JSON.stringify(this.global));
|
|
2657
|
-
}
|
|
2658
|
-
const map = usesCode ? this.codeFailures : this.tokenFailures;
|
|
2659
|
-
if (!map.has(client) && map.size >= 1e4) client = "overflow";
|
|
2660
|
-
let entry = map.get(client);
|
|
2661
|
-
if (!entry || entry.reset <= now) map.set(client, entry = {
|
|
2662
|
-
count: 0,
|
|
2663
|
-
reset: now + WINDOW_MS
|
|
2664
|
-
});
|
|
2665
|
-
entry.count++;
|
|
2666
|
-
}
|
|
2667
|
-
};
|
|
2668
|
-
// src/shared/wire.ts
|
|
2669
|
-
/** "Run npm test" → "run npm test", for use mid-sentence ("wants to run npm test"). */
|
|
2670
|
-
const midSentence = (text) => /^[A-Z][a-z]/.test(text) ? text[0].toLowerCase() + text.slice(1) : text;
|
|
2671
|
-
// src/server/notifier.ts
|
|
2672
|
-
/** Repeats of the same event for the same session within this window are dropped. */
|
|
2673
|
-
const DEDUPE_MS = 15e3;
|
|
2674
|
-
/** Turn ends older than this (seen late, e.g. after a reconnect) are not announced. */
|
|
2675
|
-
const STALE_MS = 6e5;
|
|
2676
|
-
function vapidKeys(store) {
|
|
2677
|
-
const saved = store.setting("vapid");
|
|
2678
|
-
if (saved) return JSON.parse(saved);
|
|
2679
|
-
const keys = webpush.generateVAPIDKeys();
|
|
2680
|
-
store.setSetting("vapid", JSON.stringify(keys));
|
|
2681
|
-
return keys;
|
|
2682
|
-
}
|
|
2683
|
-
/** Real delivery through the browser vendor's push service. */
|
|
2684
|
-
function webPushSender(store, subject) {
|
|
2685
|
-
const keys = vapidKeys(store);
|
|
2686
|
-
return { async send(subscription, payload) {
|
|
2687
|
-
await webpush.sendNotification({
|
|
2688
|
-
endpoint: subscription.endpoint,
|
|
2689
|
-
keys: {
|
|
2690
|
-
p256dh: subscription.p256dh,
|
|
2691
|
-
auth: subscription.auth
|
|
2692
|
-
}
|
|
2693
|
-
}, payload, {
|
|
2694
|
-
vapidDetails: {
|
|
2695
|
-
subject,
|
|
2696
|
-
publicKey: keys.publicKey,
|
|
2697
|
-
privateKey: keys.privateKey
|
|
2698
|
-
},
|
|
2699
|
-
TTL: 21600,
|
|
2700
|
-
urgency: "high"
|
|
2701
|
-
});
|
|
2702
|
-
} };
|
|
2703
|
-
}
|
|
2704
|
-
/**
|
|
2705
|
-
* Turns directory transitions into push notifications: a session starting to need the user
|
|
2706
|
-
* (a permission or question appears) and a turn finishing or failing. Detection is per
|
|
2707
|
-
* transition, O(1); delivery fans out to the (few) subscribed devices.
|
|
2708
|
-
*/
|
|
2709
|
-
var Notifier = class {
|
|
2710
|
-
store;
|
|
2711
|
-
sender;
|
|
2712
|
-
isViewing;
|
|
2713
|
-
hostLabel;
|
|
2714
|
-
waiting = /* @__PURE__ */ new Set();
|
|
2715
|
-
recent = /* @__PURE__ */ new Map();
|
|
2716
|
-
now;
|
|
2717
|
-
constructor(options) {
|
|
2718
|
-
this.store = options.store;
|
|
2719
|
-
this.sender = options.sender;
|
|
2720
|
-
this.isViewing = options.isViewing;
|
|
2721
|
-
this.hostLabel = options.hostLabel;
|
|
2722
|
-
this.now = options.now ?? Date.now;
|
|
2723
|
-
}
|
|
2724
|
-
get waitingCount() {
|
|
2725
|
-
return this.waiting.size;
|
|
2726
|
-
}
|
|
2727
|
-
/** Feed every summary transition here (HostDirectory → Hosts.onTransition). */
|
|
2728
|
-
transition(previous, next) {
|
|
2729
|
-
const key = next?.key ?? previous.key;
|
|
2730
|
-
if (next?.attention) this.waiting.add(key);
|
|
2731
|
-
else this.waiting.delete(key);
|
|
2732
|
-
if (!previous || !next) return;
|
|
2733
|
-
const newPermission = next.pendingPermissions.some((p) => !previous.pendingPermissions.some((q) => q.id === p.id));
|
|
2734
|
-
if (next.attention && !previous.attention || newPermission) {
|
|
2735
|
-
const permission = next.pendingPermissions[0];
|
|
2736
|
-
const what = permission ? permission.kind === "question" ? `asks: ${permission.title || permission.name}` : `wants to ${midSentence(permission.title || permission.name)}` : "is waiting for you";
|
|
2737
|
-
this.emit("attention", next, `${next.project} · needs your input`, `${next.title || "Session"} ${what}`);
|
|
2738
|
-
} else if (previous.status === "running" && next.status !== "running") {
|
|
2739
|
-
if (this.now() - next.activityAt > STALE_MS) return;
|
|
2740
|
-
const failed = next.status === "error";
|
|
2741
|
-
this.emit(failed ? "turn-failed" : "turn-done", next, `${next.project} · ${failed ? "turn failed" : "turn finished"}`, next.title || "Session");
|
|
2742
|
-
}
|
|
2743
|
-
}
|
|
2744
|
-
async test(sessionId) {
|
|
2745
|
-
const subs = this.store.pushSubscriptions().filter((s) => s.sessionId === sessionId);
|
|
2746
|
-
await Promise.all(subs.map((s) => this.deliver(s, {
|
|
2747
|
-
title: "LitePaseo notifications work",
|
|
2748
|
-
body: "You'll hear from your agents when they need you or finish a turn.",
|
|
2749
|
-
tag: "litepaseo-test",
|
|
2750
|
-
url: "/",
|
|
2751
|
-
kind: "test",
|
|
2752
|
-
badge: this.waiting.size
|
|
2753
|
-
})));
|
|
2754
|
-
return subs.length;
|
|
2755
|
-
}
|
|
2756
|
-
emit(kind, agent, title, body) {
|
|
2757
|
-
const dedupeKey = `${kind}:${agent.key}`;
|
|
2758
|
-
const now = this.now();
|
|
2759
|
-
if (now - (this.recent.get(dedupeKey) ?? -Infinity) < DEDUPE_MS) return;
|
|
2760
|
-
this.recent.set(dedupeKey, now);
|
|
2761
|
-
if (this.recent.size > 5e3) this.recent.clear();
|
|
2762
|
-
const message = {
|
|
2763
|
-
title,
|
|
2764
|
-
body: `${body} — ${this.hostLabel(agent.hostId)}`.slice(0, 240),
|
|
2765
|
-
tag: agent.key,
|
|
2766
|
-
url: `/?session=${encodeURIComponent(agent.key)}`,
|
|
2767
|
-
kind,
|
|
2768
|
-
badge: this.waiting.size
|
|
2769
|
-
};
|
|
2770
|
-
const pref = kind === "attention" ? "attention" : "turns";
|
|
2771
|
-
for (const subscription of this.store.pushSubscriptions()) if (subscription.prefs[pref] && !this.isViewing(agent.key, subscription.sessionId)) this.deliver(subscription, message);
|
|
2772
|
-
}
|
|
2773
|
-
async deliver(subscription, message) {
|
|
2774
|
-
const session = this.store.sessionById(subscription.sessionId);
|
|
2775
|
-
if (!session || session.expires <= this.now()) {
|
|
2776
|
-
this.store.removePushSubscription(subscription.endpoint, subscription.sessionId);
|
|
2777
|
-
return;
|
|
2778
|
-
}
|
|
2779
|
-
try {
|
|
2780
|
-
await this.sender.send(subscription, JSON.stringify(message));
|
|
2781
|
-
} catch (error) {
|
|
2782
|
-
const status = error.statusCode;
|
|
2783
|
-
if (status === 404 || status === 410) this.store.removePushSubscription(subscription.endpoint);
|
|
2784
|
-
}
|
|
2785
|
-
}
|
|
2786
|
-
};
|
|
2787
|
-
// src/server/usage.ts
|
|
2788
|
-
/** Paseo's daemon caches usage for 5 minutes; reading more often only re-reads its copy. */
|
|
2789
|
-
const FRESH_MS = 3e5;
|
|
2790
|
-
const FAILED_RETRY_MS = 6e4;
|
|
2791
|
-
/**
|
|
2792
|
-
* Usage across every connected host. Each host is read at most once per freshness window and
|
|
2793
|
-
* only when someone asks (nothing polls while no screen shows usage); concurrent requests share
|
|
2794
|
-
* one in-flight read per host.
|
|
2795
|
-
*/
|
|
2796
|
-
var UsageService = class {
|
|
2797
|
-
hosts;
|
|
2798
|
-
cache = /* @__PURE__ */ new Map();
|
|
2799
|
-
inflight = /* @__PURE__ */ new Map();
|
|
2800
|
-
now;
|
|
2801
|
-
constructor(hosts, now = Date.now) {
|
|
2802
|
-
this.hosts = hosts;
|
|
2803
|
-
this.now = now;
|
|
2804
|
-
}
|
|
2805
|
-
async report(force = false) {
|
|
2806
|
-
const ids = [...this.hosts.clients.keys()].filter((id) => this.hosts.state(id) === "connected");
|
|
2807
|
-
const results = await Promise.all(ids.map(async (id) => [id, await this.read(id, force)]));
|
|
2808
|
-
const accounts = /* @__PURE__ */ new Map();
|
|
2809
|
-
const unavailableHosts = [];
|
|
2810
|
-
let newest = 0;
|
|
2811
|
-
for (const [hostId, usage] of results) {
|
|
2812
|
-
const label = this.hosts.label(hostId) || hostId;
|
|
2813
|
-
if (!usage.ok) {
|
|
2814
|
-
unavailableHosts.push({
|
|
2815
|
-
hostId,
|
|
2816
|
-
label,
|
|
2817
|
-
error: usage.error ?? "Usage unavailable"
|
|
2818
|
-
});
|
|
2819
|
-
continue;
|
|
2820
|
-
}
|
|
2821
|
-
newest = Math.max(newest, usage.at);
|
|
2822
|
-
for (const p of usage.providers) {
|
|
2823
|
-
const windows = (p.windows ?? []).map((w) => ({
|
|
2824
|
-
id: String(w.id),
|
|
2825
|
-
label: String(w.label),
|
|
2826
|
-
shortLabel: w.shortLabel ?? null,
|
|
2827
|
-
remainingPct: typeof w.remainingPct === "number" ? w.remainingPct : typeof w.usedPct === "number" ? Math.max(0, 100 - w.usedPct) : null,
|
|
2828
|
-
resetsAt: w.resetsAt ?? null,
|
|
2829
|
-
tone: w.tone ?? null
|
|
2830
|
-
}));
|
|
2831
|
-
if (!windows.length && p.status === "unavailable") continue;
|
|
2832
|
-
const key = [
|
|
2833
|
-
p.providerId,
|
|
2834
|
-
p.planLabel ?? "",
|
|
2835
|
-
p.sourceLabel ?? "",
|
|
2836
|
-
...windows.map((w) => `${w.id}@${w.resetsAt ?? ""}`)
|
|
2837
|
-
].join("|");
|
|
2838
|
-
const existing = accounts.get(key);
|
|
2839
|
-
if (existing) existing.hosts.push(label);
|
|
2840
|
-
else accounts.set(key, {
|
|
2841
|
-
key,
|
|
2842
|
-
providerId: String(p.providerId),
|
|
2843
|
-
name: String(p.displayName ?? p.providerId),
|
|
2844
|
-
plan: p.planLabel ?? null,
|
|
2845
|
-
source: p.sourceLabel ?? null,
|
|
2846
|
-
status: String(p.status),
|
|
2847
|
-
error: p.error ?? null,
|
|
2848
|
-
windows,
|
|
2849
|
-
hosts: [label]
|
|
2850
|
-
});
|
|
2851
|
-
}
|
|
2852
|
-
}
|
|
2853
|
-
return {
|
|
2854
|
-
fetchedAt: newest ? new Date(newest).toISOString() : null,
|
|
2855
|
-
accounts: [...accounts.values()].sort((a, b) => a.name.localeCompare(b.name) || (a.plan ?? "").localeCompare(b.plan ?? "") || a.key.localeCompare(b.key)),
|
|
2856
|
-
unavailableHosts
|
|
2857
|
-
};
|
|
2858
|
-
}
|
|
2859
|
-
read(hostId, force) {
|
|
2860
|
-
const cached = this.cache.get(hostId);
|
|
2861
|
-
const age = cached ? this.now() - cached.at : Infinity;
|
|
2862
|
-
if (cached && age < (cached.ok ? FRESH_MS : FAILED_RETRY_MS) && !(force && age > 3e4)) return Promise.resolve(cached);
|
|
2863
|
-
const pending = this.inflight.get(hostId);
|
|
2864
|
-
if (pending) return pending;
|
|
2865
|
-
const request = (async () => {
|
|
2866
|
-
try {
|
|
2867
|
-
const result = await this.hosts.get(hostId).api.providers.listUsage();
|
|
2868
|
-
return {
|
|
2869
|
-
at: this.now(),
|
|
2870
|
-
ok: true,
|
|
2871
|
-
providers: result.providers ?? []
|
|
2872
|
-
};
|
|
2873
|
-
} catch (error) {
|
|
2874
|
-
return {
|
|
2875
|
-
at: this.now(),
|
|
2876
|
-
ok: false,
|
|
2877
|
-
providers: [],
|
|
2878
|
-
error: error.message || "Usage unavailable"
|
|
2879
|
-
};
|
|
2880
|
-
}
|
|
2881
|
-
})().then((usage) => {
|
|
2882
|
-
this.cache.set(hostId, usage);
|
|
2883
|
-
this.inflight.delete(hostId);
|
|
2884
|
-
return usage;
|
|
2885
|
-
});
|
|
2886
|
-
this.inflight.set(hostId, request);
|
|
2887
|
-
return request;
|
|
2888
|
-
}
|
|
2889
|
-
};
|
|
2890
|
-
// src/server/dictation.ts
|
|
2891
|
-
/**
|
|
2892
|
-
* File transcription for phrases from dictation-stream and complete clips from older clients.
|
|
2893
|
-
* Wraps mono PCM as WAV for an OpenAI-compatible `/audio/transcriptions` endpoint.
|
|
2894
|
-
* Voice input is configured in LitePaseo; no Paseo host is involved.
|
|
2895
|
-
*
|
|
2896
|
-
* Request shape differs by model generation (OpenAI speech-to-text guide, 2026):
|
|
2897
|
-
* - `gpt-transcribe` takes `languages[]` (several expected languages, for code-switching) and
|
|
2898
|
-
* `keywords[]`; it "replaces the singular `language` field. Don't send both fields."
|
|
2899
|
-
* - `whisper-1`, `gpt-4o(-mini)-transcribe` and most compatible providers (Groq, local Whisper
|
|
2900
|
-
* servers) take a single `language` and a free-text `prompt`.
|
|
2901
|
-
* Paseo always sends `language` (default "en"), which is what breaks `gpt-transcribe` there.
|
|
2902
|
-
* Here the shape follows the model name, and a 400 about the language field retries once with
|
|
2903
|
-
* the other shape, so unknown models on compatible providers still work.
|
|
2904
|
-
*/
|
|
2905
|
-
const DEFAULT_BASE_URL = "https://api.openai.com/v1";
|
|
2906
|
-
/** Five minutes of 16 kHz, 16-bit mono speech (9.6 MB as WAV, under the 25 MB upload limit). */
|
|
2907
|
-
const MAX_DICTATION_BYTES = 96e5;
|
|
2908
|
-
const SETTING = "dictation";
|
|
2909
|
-
const UPSTREAM_TIMEOUT_MS = 11e4;
|
|
2910
|
-
/** Whisper reads at most 224 prompt tokens; keep the folded vocabulary well under that. */
|
|
2911
|
-
const LEGACY_PROMPT_CHARS = 600;
|
|
2912
|
-
const baseUrl = z.string().trim().max(500).transform((v) => (v || "https://api.openai.com/v1").replace(/\/+$/, "")).refine((v) => {
|
|
2913
|
-
try {
|
|
2914
|
-
return ["http:", "https:"].includes(new URL(v).protocol);
|
|
2915
|
-
} catch {
|
|
2916
|
-
return false;
|
|
2917
|
-
}
|
|
2918
|
-
}, "Base URL must be an http(s) address");
|
|
2919
|
-
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");
|
|
2920
|
-
/** The API rejects the whole request for a keyword with <, > or a line break. */
|
|
2921
|
-
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 >");
|
|
2922
|
-
const unique = (values) => [...new Set(values)];
|
|
2923
|
-
const DictationUpdate = z.object({
|
|
2924
|
-
baseUrl: baseUrl.optional().default(DEFAULT_BASE_URL),
|
|
2925
|
-
/** Omitted or empty keeps the saved key. */
|
|
2926
|
-
apiKey: z.string().trim().max(1e3).optional(),
|
|
2927
|
-
model: z.string().trim().max(200).optional().transform((v) => v || "gpt-transcribe"),
|
|
2928
|
-
languages: z.array(languageCode).max(10, "At most 10 languages").optional().default([]).transform(unique),
|
|
2929
|
-
keywords: z.array(keyword).max(100, "At most 100 vocabulary terms").optional().default([]).transform(unique)
|
|
2930
|
-
});
|
|
2931
|
-
function dictationConfig(store) {
|
|
2932
|
-
const raw = store.setting(SETTING);
|
|
2933
|
-
if (!raw) return null;
|
|
2934
|
-
try {
|
|
2935
|
-
const value = JSON.parse(raw);
|
|
2936
|
-
if (!value.apiKey || !value.baseUrl || !value.model) return null;
|
|
2937
|
-
return {
|
|
2938
|
-
baseUrl: value.baseUrl,
|
|
2939
|
-
apiKey: value.apiKey,
|
|
2940
|
-
model: value.model,
|
|
2941
|
-
languages: value.languages ?? [],
|
|
2942
|
-
keywords: value.keywords ?? []
|
|
2943
|
-
};
|
|
2944
|
-
} catch {
|
|
2945
|
-
return null;
|
|
2946
|
-
}
|
|
2947
|
-
}
|
|
2948
|
-
function dictationSettings(store) {
|
|
2949
|
-
const config = dictationConfig(store);
|
|
2950
|
-
return {
|
|
2951
|
-
configured: !!config,
|
|
2952
|
-
baseUrl: config?.baseUrl ?? "https://api.openai.com/v1",
|
|
2953
|
-
model: config?.model ?? "gpt-transcribe",
|
|
2954
|
-
languages: config?.languages ?? [],
|
|
2955
|
-
keywords: config?.keywords ?? [],
|
|
2956
|
-
keyHint: config ? "…" + config.apiKey.slice(-4) : ""
|
|
2957
|
-
};
|
|
2958
|
-
}
|
|
2959
|
-
function saveDictation(store, input) {
|
|
2960
|
-
const update = DictationUpdate.parse(input);
|
|
2961
|
-
const apiKey = update.apiKey || dictationConfig(store)?.apiKey;
|
|
2962
|
-
if (!apiKey) throw new Error("An API key is required");
|
|
2963
|
-
const config = {
|
|
2964
|
-
baseUrl: update.baseUrl,
|
|
2965
|
-
apiKey,
|
|
2966
|
-
model: update.model,
|
|
2967
|
-
languages: update.languages,
|
|
2968
|
-
keywords: update.keywords
|
|
2969
|
-
};
|
|
2970
|
-
store.setSetting(SETTING, JSON.stringify(config));
|
|
2971
|
-
return dictationSettings(store);
|
|
2972
|
-
}
|
|
2973
|
-
function clearDictation(store) {
|
|
2974
|
-
store.setSetting(SETTING, null);
|
|
2975
|
-
}
|
|
2976
|
-
/** A 44-byte RIFF header makes raw PCM16 a file every transcription API accepts. */
|
|
2977
|
-
function wav(pcm, rate) {
|
|
2978
|
-
const out = Buffer.alloc(44 + pcm.length);
|
|
2979
|
-
out.write("RIFF", 0);
|
|
2980
|
-
out.writeUInt32LE(36 + pcm.length, 4);
|
|
2981
|
-
out.write("WAVE", 8);
|
|
2982
|
-
out.write("fmt ", 12);
|
|
2983
|
-
out.writeUInt32LE(16, 16);
|
|
2984
|
-
out.writeUInt16LE(1, 20);
|
|
2985
|
-
out.writeUInt16LE(1, 22);
|
|
2986
|
-
out.writeUInt32LE(rate, 24);
|
|
2987
|
-
out.writeUInt32LE(rate * 2, 28);
|
|
2988
|
-
out.writeUInt16LE(2, 32);
|
|
2989
|
-
out.writeUInt16LE(16, 34);
|
|
2990
|
-
out.write("data", 36);
|
|
2991
|
-
out.writeUInt32LE(pcm.length, 40);
|
|
2992
|
-
out.set(pcm, 44);
|
|
2993
|
-
return out;
|
|
2994
|
-
}
|
|
2995
|
-
const shapeFor = (model) => /(^|\/)gpt-transcribe\b/i.test(model) ? "hints" : "single";
|
|
2996
|
-
/** The multipart fields besides the file, for one request shape. */
|
|
2997
|
-
function transcriptionFields(config, shape) {
|
|
2998
|
-
const fields = [["model", config.model], ["response_format", "json"]];
|
|
2999
|
-
if (shape === "hints") {
|
|
3000
|
-
for (const code of config.languages) fields.push(["languages[]", code]);
|
|
3001
|
-
for (const term of config.keywords) fields.push(["keywords[]", term]);
|
|
3002
|
-
return fields;
|
|
3003
|
-
}
|
|
3004
|
-
if (config.languages.length === 1) fields.push(["language", config.languages[0].split("-")[0]]);
|
|
3005
|
-
if (config.keywords.length) {
|
|
3006
|
-
let prompt = "";
|
|
3007
|
-
for (const term of config.keywords) {
|
|
3008
|
-
const next = prompt ? `${prompt}, ${term}` : term;
|
|
3009
|
-
if (next.length > LEGACY_PROMPT_CHARS) break;
|
|
3010
|
-
prompt = next;
|
|
3011
|
-
}
|
|
3012
|
-
fields.push(["prompt", prompt]);
|
|
3013
|
-
}
|
|
3014
|
-
return fields;
|
|
3015
|
-
}
|
|
3016
|
-
var DictationError = class extends Error {
|
|
3017
|
-
status;
|
|
3018
|
-
constructor(message, status) {
|
|
3019
|
-
super(message);
|
|
3020
|
-
this.status = status;
|
|
3021
|
-
}
|
|
3022
|
-
};
|
|
3023
|
-
async function send(config, file, shape, fetchImpl, signal) {
|
|
3024
|
-
const form = new FormData();
|
|
3025
|
-
form.append("file", file, "dictation.wav");
|
|
3026
|
-
for (const [name, value] of transcriptionFields(config, shape)) form.append(name, value);
|
|
3027
|
-
let response;
|
|
3028
|
-
try {
|
|
3029
|
-
response = await fetchImpl(config.baseUrl + "/audio/transcriptions", {
|
|
3030
|
-
method: "POST",
|
|
3031
|
-
headers: { authorization: `Bearer ${config.apiKey}` },
|
|
3032
|
-
body: form,
|
|
3033
|
-
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)]) : AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
|
|
3034
|
-
});
|
|
3035
|
-
} catch (error) {
|
|
3036
|
-
const timeout = error.name === "TimeoutError";
|
|
3037
|
-
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);
|
|
3038
|
-
}
|
|
3039
|
-
const body = await response.text();
|
|
3040
|
-
let data = {};
|
|
3041
|
-
try {
|
|
3042
|
-
data = JSON.parse(body);
|
|
3043
|
-
} catch {}
|
|
3044
|
-
const detail = typeof data.error === "string" ? data.error : typeof data.error?.message === "string" ? data.error.message : response.ok ? "" : body;
|
|
3045
|
-
return {
|
|
3046
|
-
ok: response.ok,
|
|
3047
|
-
status: response.status,
|
|
3048
|
-
text: typeof data.text === "string" ? data.text : void 0,
|
|
3049
|
-
detail: String(detail)
|
|
3050
|
-
};
|
|
3051
|
-
}
|
|
3052
|
-
async function transcribe(config, pcm, rate, fetchImpl = fetch, signal) {
|
|
3053
|
-
const file = new Blob([wav(pcm, rate)], { type: "audio/wav" });
|
|
3054
|
-
const shape = shapeFor(config.model);
|
|
3055
|
-
let result = await send(config, file, shape, fetchImpl, signal);
|
|
3056
|
-
const hinted = config.languages.length > 0 || config.keywords.length > 0;
|
|
3057
|
-
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);
|
|
3058
|
-
if (!result.ok) {
|
|
3059
|
-
const scrubbed = result.detail.split(config.apiKey).join("…").replace(/\s+/g, " ").trim().slice(0, 200);
|
|
3060
|
-
throw new DictationError(`Transcription failed (${result.status})${scrubbed ? ": " + scrubbed : ""}`, 502);
|
|
3061
|
-
}
|
|
3062
|
-
if (result.text === void 0) throw new DictationError("The transcription service returned no text", 502);
|
|
3063
|
-
return result.text.trim();
|
|
3064
|
-
}
|
|
3065
|
-
// src/server/dictation-stream.ts
|
|
3066
|
-
const DICTATION_RATE = 24e3;
|
|
3067
|
-
const BYTES_PER_SECOND = DICTATION_RATE * 2;
|
|
3068
|
-
const MAX_BYTES = BYTES_PER_SECOND * 300;
|
|
3069
|
-
const MAX_BUFFERED = BYTES_PER_SECOND * 10;
|
|
3070
|
-
/** One-use, short-lived tickets keep credentials out of WebSocket URLs. */
|
|
3071
|
-
var DictationStreams = class {
|
|
3072
|
-
tickets = /* @__PURE__ */ new Map();
|
|
3073
|
-
sessions = /* @__PURE__ */ new Set();
|
|
3074
|
-
unsupported = /* @__PURE__ */ new Map();
|
|
3075
|
-
wss = new WebSocketServer({
|
|
3076
|
-
noServer: true,
|
|
3077
|
-
maxPayload: BYTES_PER_SECOND,
|
|
3078
|
-
perMessageDeflate: false
|
|
3079
|
-
});
|
|
3080
|
-
fetchImpl;
|
|
3081
|
-
log;
|
|
3082
|
-
constructor(fetchImpl = fetch, log = () => {}) {
|
|
3083
|
-
this.fetchImpl = fetchImpl;
|
|
3084
|
-
this.log = log;
|
|
3085
|
-
}
|
|
3086
|
-
issue(config, valid) {
|
|
3087
|
-
for (const [key, ticket] of this.tickets) if (ticket.expires < Date.now()) this.tickets.delete(key);
|
|
3088
|
-
if (this.tickets.size + this.sessions.size >= 16) throw new Error("Too many voice sessions. Try again shortly.");
|
|
3089
|
-
const ticket = randomUUID();
|
|
3090
|
-
this.tickets.set(ticket, {
|
|
3091
|
-
config,
|
|
3092
|
-
valid,
|
|
3093
|
-
expires: Date.now() + 3e4
|
|
3094
|
-
});
|
|
3095
|
-
return {
|
|
3096
|
-
ticket,
|
|
3097
|
-
rate: DICTATION_RATE
|
|
3098
|
-
};
|
|
3099
|
-
}
|
|
3100
|
-
attach(server) {
|
|
3101
|
-
server.on("upgrade", (request, socket, head) => {
|
|
3102
|
-
const url = new URL(request.url ?? "/", "http://localhost");
|
|
3103
|
-
if (url.pathname !== "/api/dictation/stream") {
|
|
3104
|
-
socket.destroy();
|
|
3105
|
-
return;
|
|
3106
|
-
}
|
|
3107
|
-
const key = url.searchParams.get("ticket") ?? "";
|
|
3108
|
-
const ticket = this.tickets.get(key);
|
|
3109
|
-
this.tickets.delete(key);
|
|
3110
|
-
if (!ticket || ticket.expires < Date.now() || !ticket.valid()) {
|
|
3111
|
-
socket.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
|
|
3112
|
-
return;
|
|
3113
|
-
}
|
|
3114
|
-
this.wss.handleUpgrade(request, socket, head, (client) => {
|
|
3115
|
-
const cacheKey = ticket.config.baseUrl + ":" + ticket.config.model;
|
|
3116
|
-
const stream = new DictationStream(client, ticket.config, ticket.valid, {
|
|
3117
|
-
fetch: this.fetchImpl,
|
|
3118
|
-
skipRealtime: (this.unsupported.get(cacheKey) ?? 0) > Date.now(),
|
|
3119
|
-
unsupported: () => {
|
|
3120
|
-
for (const [key, until] of this.unsupported) if (until < Date.now()) this.unsupported.delete(key);
|
|
3121
|
-
this.unsupported.set(cacheKey, Date.now() + 3e5);
|
|
3122
|
-
},
|
|
3123
|
-
closed: () => this.sessions.delete(stream),
|
|
3124
|
-
log: this.log
|
|
3125
|
-
});
|
|
3126
|
-
this.sessions.add(stream);
|
|
3127
|
-
stream.start();
|
|
3128
|
-
});
|
|
3129
|
-
});
|
|
3130
|
-
}
|
|
3131
|
-
close() {
|
|
3132
|
-
for (const stream of this.sessions) stream.close();
|
|
3133
|
-
this.tickets.clear();
|
|
3134
|
-
this.unsupported.clear();
|
|
3135
|
-
this.wss.close();
|
|
3136
|
-
}
|
|
3137
|
-
};
|
|
3138
|
-
/** Audio flows while recording. Realtime is preferred; file-only services transcribe phrases. */
|
|
3139
|
-
var DictationStream = class {
|
|
3140
|
-
upstream;
|
|
3141
|
-
mode = "connecting";
|
|
3142
|
-
closed = false;
|
|
3143
|
-
finishing = false;
|
|
3144
|
-
totalBytes = 0;
|
|
3145
|
-
segmentBytes = 0;
|
|
3146
|
-
silenceBytes = 0;
|
|
3147
|
-
speech = false;
|
|
3148
|
-
chunks = [];
|
|
3149
|
-
segments = [];
|
|
3150
|
-
commits = [];
|
|
3151
|
-
items = /* @__PURE__ */ new Map();
|
|
3152
|
-
jobs = [];
|
|
3153
|
-
activeJobs = 0;
|
|
3154
|
-
abort = new AbortController();
|
|
3155
|
-
started = Date.now();
|
|
3156
|
-
stopped = 0;
|
|
3157
|
-
firstText = null;
|
|
3158
|
-
deadline;
|
|
3159
|
-
heartbeat;
|
|
3160
|
-
client;
|
|
3161
|
-
config;
|
|
3162
|
-
valid;
|
|
3163
|
-
options;
|
|
3164
|
-
constructor(client, config, valid, options) {
|
|
3165
|
-
this.client = client;
|
|
3166
|
-
this.config = config;
|
|
3167
|
-
this.valid = valid;
|
|
3168
|
-
this.options = options;
|
|
3169
|
-
this.heartbeat = setInterval(() => {
|
|
3170
|
-
if (!valid()) this.fail("Your session ended. Sign in again.");
|
|
3171
|
-
else if (Date.now() - this.started > 43e4) this.fail("Voice session timed out.");
|
|
3172
|
-
else if (client.readyState === WebSocket.OPEN) client.ping();
|
|
3173
|
-
}, 1e4);
|
|
3174
|
-
this.heartbeat.unref();
|
|
3175
|
-
client.on("message", (data, binary) => {
|
|
3176
|
-
if (this.closed) return;
|
|
3177
|
-
if (!valid()) {
|
|
3178
|
-
this.fail("Your session ended. Sign in again.");
|
|
3179
|
-
return;
|
|
3180
|
-
}
|
|
3181
|
-
try {
|
|
3182
|
-
if (binary) this.append(Buffer.from(data));
|
|
3183
|
-
else {
|
|
3184
|
-
const event = JSON.parse(data.toString());
|
|
3185
|
-
if (event.type === "stop") this.finish();
|
|
3186
|
-
else if (event.type === "cancel") this.close();
|
|
3187
|
-
else this.fail("Unknown voice command.");
|
|
3188
|
-
}
|
|
3189
|
-
} catch {
|
|
3190
|
-
this.fail("Invalid voice data.");
|
|
3191
|
-
}
|
|
3192
|
-
});
|
|
3193
|
-
client.on("error", () => this.close());
|
|
3194
|
-
client.on("close", () => this.close());
|
|
3195
|
-
}
|
|
3196
|
-
async start() {
|
|
3197
|
-
const realtimeModel = /^(gpt-transcribe|gpt-live-transcribe|gpt-4o(-mini)?-transcribe|whisper-1)$/.test(this.config.model);
|
|
3198
|
-
if (this.options.skipRealtime || !realtimeModel) {
|
|
3199
|
-
this.ready("segmented");
|
|
3200
|
-
return;
|
|
3201
|
-
}
|
|
3202
|
-
try {
|
|
3203
|
-
await this.connectRealtime();
|
|
3204
|
-
if (!this.closed) this.ready("realtime");
|
|
3205
|
-
} catch (error) {
|
|
3206
|
-
if (this.closed) return;
|
|
3207
|
-
if (error instanceof Unavailable) {
|
|
3208
|
-
this.options.unsupported();
|
|
3209
|
-
this.ready("segmented");
|
|
3210
|
-
} else this.fail(error.message);
|
|
3211
|
-
}
|
|
3212
|
-
}
|
|
3213
|
-
connectRealtime() {
|
|
3214
|
-
return new Promise((resolve, reject) => {
|
|
3215
|
-
const url = new URL(this.config.baseUrl + "/realtime");
|
|
3216
|
-
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
3217
|
-
url.searchParams.set("intent", "transcription");
|
|
3218
|
-
const ws = this.upstream = new WebSocket(url, {
|
|
3219
|
-
headers: { Authorization: `Bearer ${this.config.apiKey}` },
|
|
3220
|
-
handshakeTimeout: 4e3,
|
|
3221
|
-
maxPayload: 1048576
|
|
3222
|
-
});
|
|
3223
|
-
let settled = false;
|
|
3224
|
-
const finish = (error) => {
|
|
3225
|
-
if (settled) return;
|
|
3226
|
-
settled = true;
|
|
3227
|
-
clearTimeout(timeout);
|
|
3228
|
-
if (error) {
|
|
3229
|
-
this.upstream = void 0;
|
|
3230
|
-
ws.terminate();
|
|
3231
|
-
reject(error);
|
|
3232
|
-
} else resolve();
|
|
3233
|
-
};
|
|
3234
|
-
const timeout = setTimeout(() => finish(new Unavailable("Realtime connection timed out")), 5e3);
|
|
3235
|
-
ws.on("open", () => {
|
|
3236
|
-
const hints = /^(gpt-transcribe|gpt-live-transcribe)$/.test(this.config.model);
|
|
3237
|
-
const transcription = {
|
|
3238
|
-
model: this.config.model,
|
|
3239
|
-
...hints ? {
|
|
3240
|
-
...this.config.languages.length ? { languages: this.config.languages } : {},
|
|
3241
|
-
...this.config.keywords.length ? { keywords: this.config.keywords } : {}
|
|
3242
|
-
} : {
|
|
3243
|
-
...this.config.languages.length === 1 ? { language: this.config.languages[0].split("-")[0] } : {},
|
|
3244
|
-
...this.config.keywords.length ? { prompt: this.config.keywords.join(", ").slice(0, 600) } : {}
|
|
3245
|
-
}
|
|
3246
|
-
};
|
|
3247
|
-
ws.send(JSON.stringify({
|
|
3248
|
-
type: "session.update",
|
|
3249
|
-
session: {
|
|
3250
|
-
type: "transcription",
|
|
3251
|
-
audio: { input: {
|
|
3252
|
-
format: {
|
|
3253
|
-
type: "audio/pcm",
|
|
3254
|
-
rate: DICTATION_RATE
|
|
3255
|
-
},
|
|
3256
|
-
transcription,
|
|
3257
|
-
turn_detection: null
|
|
3258
|
-
} }
|
|
3259
|
-
}
|
|
3260
|
-
}));
|
|
3261
|
-
});
|
|
3262
|
-
ws.on("unexpected-response", (_, response) => {
|
|
3263
|
-
const status = response.statusCode;
|
|
3264
|
-
response.destroy();
|
|
3265
|
-
finish([
|
|
3266
|
-
400,
|
|
3267
|
-
404,
|
|
3268
|
-
405,
|
|
3269
|
-
501
|
|
3270
|
-
].includes(status ?? 0) ? new Unavailable("Realtime is not supported") : /* @__PURE__ */ new Error(`Voice connection failed (${status}). Check the transcription service settings.`));
|
|
3271
|
-
});
|
|
3272
|
-
ws.on("message", (data) => {
|
|
3273
|
-
let event;
|
|
3274
|
-
try {
|
|
3275
|
-
event = JSON.parse(data.toString());
|
|
3276
|
-
} catch {
|
|
3277
|
-
finish(/* @__PURE__ */ new Error("Invalid transcription service response."));
|
|
3278
|
-
return;
|
|
3279
|
-
}
|
|
3280
|
-
if (!settled) {
|
|
3281
|
-
if (event.type === "session.updated") finish();
|
|
3282
|
-
else if (event.type === "error") finish(new Unavailable("Realtime configuration is not supported"));
|
|
3283
|
-
} else if (this.mode === "realtime" && !this.closed) this.upstreamEvent(event);
|
|
3284
|
-
});
|
|
3285
|
-
ws.on("error", () => {
|
|
3286
|
-
if (!settled) finish(new Unavailable("Realtime is unavailable"));
|
|
3287
|
-
else if (this.mode === "realtime") this.fail("Voice connection interrupted. Please try again.");
|
|
3288
|
-
});
|
|
3289
|
-
ws.on("close", () => {
|
|
3290
|
-
if (!settled) finish(new Unavailable("Realtime is unavailable"));
|
|
3291
|
-
else if (this.mode === "realtime" && !this.closed) this.fail("Voice connection interrupted. Please try again.");
|
|
3292
|
-
});
|
|
3293
|
-
});
|
|
3294
|
-
}
|
|
3295
|
-
ready(mode) {
|
|
3296
|
-
if (this.closed) return;
|
|
3297
|
-
if (mode === "segmented" && this.config.model === "gpt-live-transcribe") {
|
|
3298
|
-
this.fail("This service does not support realtime transcription. Choose gpt-transcribe or a realtime-compatible service.");
|
|
3299
|
-
return;
|
|
3300
|
-
}
|
|
3301
|
-
this.mode = mode;
|
|
3302
|
-
this.send({
|
|
3303
|
-
type: "ready",
|
|
3304
|
-
mode,
|
|
3305
|
-
rate: DICTATION_RATE
|
|
3306
|
-
});
|
|
3307
|
-
}
|
|
3308
|
-
append(audio) {
|
|
3309
|
-
if (this.finishing || this.mode === "connecting") {
|
|
3310
|
-
this.fail("Voice session is not recording.");
|
|
3311
|
-
return;
|
|
3312
|
-
}
|
|
3313
|
-
if (!audio.length || audio.length % 2 || audio.length > BYTES_PER_SECOND) {
|
|
3314
|
-
this.fail("Invalid audio chunk.");
|
|
3315
|
-
return;
|
|
3316
|
-
}
|
|
3317
|
-
this.totalBytes += audio.length;
|
|
3318
|
-
if (this.totalBytes > MAX_BYTES) {
|
|
3319
|
-
this.fail("Recording exceeds five minutes.");
|
|
3320
|
-
return;
|
|
3321
|
-
}
|
|
3322
|
-
this.chunks.push(audio);
|
|
3323
|
-
this.segmentBytes += audio.length;
|
|
3324
|
-
let energy = 0;
|
|
3325
|
-
for (let i = 0; i < audio.length; i += 2) {
|
|
3326
|
-
const sample = audio.readInt16LE(i) / 32768;
|
|
3327
|
-
energy += sample * sample;
|
|
3328
|
-
}
|
|
3329
|
-
if (Math.sqrt(energy / (audio.length / 2)) >= .006) {
|
|
3330
|
-
this.speech = true;
|
|
3331
|
-
this.silenceBytes = 0;
|
|
3332
|
-
} else this.silenceBytes += audio.length;
|
|
3333
|
-
if (this.mode === "realtime") {
|
|
3334
|
-
if (!this.upstream || this.upstream.bufferedAmount > MAX_BUFFERED) {
|
|
3335
|
-
this.fail("Voice upload cannot keep up with recording.");
|
|
3336
|
-
return;
|
|
3337
|
-
}
|
|
3338
|
-
this.upstream.send(JSON.stringify({
|
|
3339
|
-
type: "input_audio_buffer.append",
|
|
3340
|
-
audio: audio.toString("base64")
|
|
3341
|
-
}));
|
|
3342
|
-
}
|
|
3343
|
-
if (this.speech && (this.segmentBytes >= BYTES_PER_SECOND && this.silenceBytes >= BYTES_PER_SECOND * .7 || this.segmentBytes >= BYTES_PER_SECOND * 30)) this.commit();
|
|
3344
|
-
else if (!this.speech && this.segmentBytes >= BYTES_PER_SECOND * 2) this.clearAudio();
|
|
3345
|
-
}
|
|
3346
|
-
clearAudio() {
|
|
3347
|
-
this.chunks = [];
|
|
3348
|
-
this.segmentBytes = this.silenceBytes = 0;
|
|
3349
|
-
this.speech = false;
|
|
3350
|
-
if (this.mode === "realtime") this.upstream?.send(JSON.stringify({ type: "input_audio_buffer.clear" }));
|
|
3351
|
-
}
|
|
3352
|
-
commit() {
|
|
3353
|
-
if (!this.segmentBytes) return;
|
|
3354
|
-
const segment = {
|
|
3355
|
-
text: "",
|
|
3356
|
-
done: false
|
|
3357
|
-
};
|
|
3358
|
-
this.segments.push(segment);
|
|
3359
|
-
if (this.mode === "realtime") {
|
|
3360
|
-
if (this.segmentBytes < BYTES_PER_SECOND / 10) this.upstream?.send(JSON.stringify({
|
|
3361
|
-
type: "input_audio_buffer.append",
|
|
3362
|
-
audio: Buffer.alloc(BYTES_PER_SECOND / 10 - this.segmentBytes).toString("base64")
|
|
3363
|
-
}));
|
|
3364
|
-
this.commits.push(segment);
|
|
3365
|
-
this.upstream?.send(JSON.stringify({ type: "input_audio_buffer.commit" }));
|
|
3366
|
-
} else {
|
|
3367
|
-
this.jobs.push({
|
|
3368
|
-
audio: Buffer.concat(this.chunks),
|
|
3369
|
-
segment
|
|
3370
|
-
});
|
|
3371
|
-
this.pump();
|
|
3372
|
-
}
|
|
3373
|
-
this.chunks = [];
|
|
3374
|
-
this.segmentBytes = this.silenceBytes = 0;
|
|
3375
|
-
this.speech = false;
|
|
3376
|
-
}
|
|
3377
|
-
pump() {
|
|
3378
|
-
while (!this.closed && this.activeJobs < 2 && this.jobs.length) {
|
|
3379
|
-
const job = this.jobs.shift();
|
|
3380
|
-
this.activeJobs++;
|
|
3381
|
-
transcribe(this.config, job.audio, DICTATION_RATE, this.options.fetch, this.abort.signal).then((text) => {
|
|
3382
|
-
if (this.closed) return;
|
|
3383
|
-
job.segment.text = text;
|
|
3384
|
-
job.segment.done = true;
|
|
3385
|
-
this.publish();
|
|
3386
|
-
}).catch(() => {
|
|
3387
|
-
if (!this.closed) this.fail("Transcription failed. Please try again or check the service settings.");
|
|
3388
|
-
}).finally(() => {
|
|
3389
|
-
this.activeJobs--;
|
|
3390
|
-
this.pump();
|
|
3391
|
-
});
|
|
3392
|
-
}
|
|
3393
|
-
}
|
|
3394
|
-
upstreamEvent(event) {
|
|
3395
|
-
const id = typeof event.item_id === "string" ? event.item_id : "";
|
|
3396
|
-
if (event.type === "input_audio_buffer.committed") {
|
|
3397
|
-
const segment = this.commits.shift();
|
|
3398
|
-
if (!segment || !id) {
|
|
3399
|
-
this.fail("Unexpected transcription sequence.");
|
|
3400
|
-
return;
|
|
3401
|
-
}
|
|
3402
|
-
const draft = this.items.get(id);
|
|
3403
|
-
if (draft) {
|
|
3404
|
-
segment.text = draft.text;
|
|
3405
|
-
segment.done = draft.done;
|
|
3406
|
-
}
|
|
3407
|
-
segment.id = id;
|
|
3408
|
-
this.items.set(id, segment);
|
|
3409
|
-
this.publish();
|
|
3410
|
-
} else if (event.type === "conversation.item.input_audio_transcription.delta" || event.type === "conversation.item.input_audio_transcription.completed") {
|
|
3411
|
-
let segment = this.items.get(id);
|
|
3412
|
-
if (!segment) {
|
|
3413
|
-
segment = {
|
|
3414
|
-
text: "",
|
|
3415
|
-
done: false,
|
|
3416
|
-
id
|
|
3417
|
-
};
|
|
3418
|
-
this.items.set(id, segment);
|
|
3419
|
-
}
|
|
3420
|
-
if (event.type.endsWith(".completed")) {
|
|
3421
|
-
segment.text = String(event.transcript ?? "");
|
|
3422
|
-
segment.done = true;
|
|
3423
|
-
} else if (!segment.done) segment.text += String(event.delta ?? "");
|
|
3424
|
-
this.publish();
|
|
3425
|
-
} else if (event.type === "error" || event.type === "conversation.item.input_audio_transcription.failed") this.fail("The transcription service could not process this recording.");
|
|
3426
|
-
}
|
|
3427
|
-
text() {
|
|
3428
|
-
const parts = [];
|
|
3429
|
-
for (const segment of this.segments) {
|
|
3430
|
-
if (segment.text.trim()) parts.push(segment.text.trim());
|
|
3431
|
-
if (!segment.done) break;
|
|
3432
|
-
}
|
|
3433
|
-
if (this.mode === "realtime" && this.config.model === "gpt-live-transcribe") {
|
|
3434
|
-
for (const segment of this.items.values()) if (!this.segments.includes(segment) && segment.text.trim()) parts.push(segment.text.trim());
|
|
3435
|
-
}
|
|
3436
|
-
return parts.join(" ");
|
|
3437
|
-
}
|
|
3438
|
-
publish() {
|
|
3439
|
-
if (this.closed) return;
|
|
3440
|
-
const text = this.text();
|
|
3441
|
-
if (text && this.firstText === null) this.firstText = Date.now() - this.started;
|
|
3442
|
-
if (this.finishing && this.segments.every((s) => s.done)) {
|
|
3443
|
-
this.options.log({
|
|
3444
|
-
mode: this.mode,
|
|
3445
|
-
audioMs: this.totalBytes / BYTES_PER_SECOND * 1e3,
|
|
3446
|
-
firstTextMs: this.firstText,
|
|
3447
|
-
finishMs: Date.now() - this.stopped
|
|
3448
|
-
});
|
|
3449
|
-
this.send({
|
|
3450
|
-
type: "done",
|
|
3451
|
-
text
|
|
3452
|
-
});
|
|
3453
|
-
this.close();
|
|
3454
|
-
} else this.send({
|
|
3455
|
-
type: "partial",
|
|
3456
|
-
text
|
|
3457
|
-
});
|
|
3458
|
-
}
|
|
3459
|
-
finish() {
|
|
3460
|
-
if (this.finishing || this.closed) return;
|
|
3461
|
-
if (this.mode === "connecting") {
|
|
3462
|
-
this.fail("Voice session is still connecting.");
|
|
3463
|
-
return;
|
|
3464
|
-
}
|
|
3465
|
-
this.finishing = true;
|
|
3466
|
-
this.stopped = Date.now();
|
|
3467
|
-
if (this.speech) this.commit();
|
|
3468
|
-
else this.clearAudio();
|
|
3469
|
-
this.deadline = setTimeout(() => this.fail("Timed out waiting for transcription."), 12e4);
|
|
3470
|
-
this.publish();
|
|
3471
|
-
}
|
|
3472
|
-
send(event) {
|
|
3473
|
-
if (this.client.readyState === WebSocket.OPEN) {
|
|
3474
|
-
if (this.client.bufferedAmount > 1048576) {
|
|
3475
|
-
this.close();
|
|
3476
|
-
return;
|
|
3477
|
-
}
|
|
3478
|
-
this.client.send(JSON.stringify(event));
|
|
3479
|
-
}
|
|
3480
|
-
}
|
|
3481
|
-
fail(message) {
|
|
3482
|
-
if (this.closed) return;
|
|
3483
|
-
this.send({
|
|
3484
|
-
type: "error",
|
|
3485
|
-
message,
|
|
3486
|
-
text: this.text()
|
|
3487
|
-
});
|
|
3488
|
-
this.close();
|
|
3489
|
-
}
|
|
3490
|
-
close() {
|
|
3491
|
-
if (this.closed) return;
|
|
3492
|
-
this.closed = true;
|
|
3493
|
-
clearInterval(this.heartbeat);
|
|
3494
|
-
clearTimeout(this.deadline);
|
|
3495
|
-
this.abort.abort();
|
|
3496
|
-
this.upstream?.terminate();
|
|
3497
|
-
this.chunks = [];
|
|
3498
|
-
this.jobs = [];
|
|
3499
|
-
this.client.close();
|
|
3500
|
-
this.options.closed();
|
|
3501
|
-
}
|
|
3502
|
-
};
|
|
3503
|
-
var Unavailable = class extends Error {};
|
|
3504
|
-
// src/server/app.ts
|
|
3505
|
-
const AGENT_FLUSH_MS = 100;
|
|
3506
|
-
const HOST_FLUSH_MS = 100;
|
|
3507
|
-
function parseJson(text) {
|
|
3508
|
-
try {
|
|
3509
|
-
return JSON.parse(text ?? "null");
|
|
3510
|
-
} catch {
|
|
3511
|
-
return null;
|
|
3512
|
-
}
|
|
3513
|
-
}
|
|
3514
|
-
const CARD_DESCRIPTION_MAX = 2e4;
|
|
3515
|
-
const CARD_COMMENT_MAX = 5e3;
|
|
3516
|
-
const cardComment = z.object({
|
|
3517
|
-
id: z.string().uuid(),
|
|
3518
|
-
text: z.string().trim().min(1).max(CARD_COMMENT_MAX),
|
|
3519
|
-
at: z.number().int().nonnegative()
|
|
3520
|
-
});
|
|
3521
|
-
const card = z.object({
|
|
3522
|
-
id: z.string().uuid(),
|
|
3523
|
-
title: z.string().min(1).max(300),
|
|
3524
|
-
column: z.enum([
|
|
3525
|
-
"Todo",
|
|
3526
|
-
"Doing",
|
|
3527
|
-
"Done"
|
|
3528
|
-
]),
|
|
3529
|
-
hostId: z.string().nullable(),
|
|
3530
|
-
agentId: z.string().nullable(),
|
|
3531
|
-
description: z.string().max(CARD_DESCRIPTION_MAX).optional(),
|
|
3532
|
-
comments: z.array(cardComment).max(200).optional(),
|
|
3533
|
-
createdAt: z.number().int().nonnegative().optional(),
|
|
3534
|
-
updatedAt: z.number().int().nonnegative().optional()
|
|
3535
|
-
}).refine((c) => c.hostId === null === (c.agentId === null));
|
|
3536
|
-
/** One card's editable fields; omitted fields are left as they are. */
|
|
3537
|
-
const cardPatch = z.object({
|
|
3538
|
-
title: z.string().trim().min(1).max(300),
|
|
3539
|
-
column: z.enum([
|
|
3540
|
-
"Todo",
|
|
3541
|
-
"Doing",
|
|
3542
|
-
"Done"
|
|
3543
|
-
]),
|
|
3544
|
-
description: z.string().max(CARD_DESCRIPTION_MAX),
|
|
3545
|
-
link: z.object({
|
|
3546
|
-
hostId: z.string(),
|
|
3547
|
-
agentId: z.string()
|
|
3548
|
-
}).nullable()
|
|
3549
|
-
}).partial();
|
|
3550
|
-
const SESSION_COOKIE = "lp_session";
|
|
3551
|
-
/** Cookie-authenticated writes must carry this header; a cross-site form or image cannot. */
|
|
3552
|
-
const CSRF_HEADER = "x-litepaseo";
|
|
3553
|
-
const PUBLIC_API = /* @__PURE__ */ new Set(["/api/auth", "/api/login"]);
|
|
3554
|
-
/**
|
|
3555
|
-
* Requests that arrived through a tunnel or reverse proxy. A bearer token is never accepted from
|
|
3556
|
-
* them: over the network, only the browser sign-in (with its rate limits and optional
|
|
3557
|
-
* authenticator code) admits anyone.
|
|
3558
|
-
*/
|
|
3559
|
-
const proxied = (c) => [
|
|
3560
|
-
"cf-connecting-ip",
|
|
3561
|
-
"x-forwarded-for",
|
|
3562
|
-
"x-real-ip",
|
|
3563
|
-
"forwarded"
|
|
3564
|
-
].some((name) => c.req.header(name) !== void 0);
|
|
3565
|
-
/** `token` is the access token, or a function returning the current one (it can be rotated). */
|
|
3566
|
-
function createApp(store, hosts, token, webRoot, options = {}) {
|
|
3567
|
-
const app = new Hono();
|
|
3568
|
-
const auth = new Auth(store, token);
|
|
3569
|
-
const dictationStreams = new DictationStreams(options.fetch, (metrics) => console.info(JSON.stringify({
|
|
3570
|
-
event: "dictation_complete",
|
|
3571
|
-
...metrics
|
|
3572
|
-
})));
|
|
3573
|
-
const attachments = new Attachments();
|
|
3574
|
-
const projectIcons = new IconCache();
|
|
3575
|
-
const viewers = /* @__PURE__ */ new Map();
|
|
3576
|
-
const notifier = new Notifier({
|
|
3577
|
-
store,
|
|
3578
|
-
sender: options.pushSender ?? webPushSender(store, options.pushSubject ?? "mailto:litepaseo@example.com"),
|
|
3579
|
-
isViewing: (key, sessionId) => (viewers.get(key)?.get(sessionId) ?? 0) > 0,
|
|
3580
|
-
hostLabel: (id) => hosts.label(id) || store.hosts().find((h) => h.id === id)?.label || ""
|
|
3581
|
-
});
|
|
3582
|
-
hosts.onTransition((previous, next) => notifier.transition(previous, next));
|
|
3583
|
-
const usage = new UsageService(hosts);
|
|
3584
|
-
store.pruneSessions(Date.now());
|
|
3585
|
-
const secure = (c) => c.req.header("x-forwarded-proto") === "https" || c.req.url.startsWith("https:");
|
|
3586
|
-
const clientId = (c) => c.req.header("cf-connecting-ip") ?? c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? "direct";
|
|
3587
|
-
app.use("*", async (c, next) => {
|
|
3588
|
-
await next();
|
|
3589
|
-
c.header("X-Content-Type-Options", "nosniff");
|
|
3590
|
-
c.header("Referrer-Policy", "no-referrer");
|
|
3591
|
-
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'");
|
|
3592
|
-
});
|
|
3593
|
-
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));
|
|
3594
|
-
app.use("/api/*", async (c, next) => {
|
|
3595
|
-
c.header("Cache-Control", "no-store");
|
|
3596
|
-
c.set("bearer", null);
|
|
3597
|
-
const bearer = /^Bearer (.+)$/.exec(c.req.header("authorization") ?? "")?.[1];
|
|
3598
|
-
if (bearer && !PUBLIC_API.has(c.req.path) && !auth.totpEnabled() && !proxied(c)) {
|
|
3599
|
-
const result = auth.bearer(bearer, clientId(c));
|
|
3600
|
-
if (!result.ok) {
|
|
3601
|
-
if (result.retryAfter) c.header("Retry-After", String(result.retryAfter));
|
|
3602
|
-
return c.json({ error: result.status === 429 ? "Too many attempts. Try again later." : "Sign in required" }, result.status);
|
|
3603
|
-
}
|
|
3604
|
-
c.set("session", null);
|
|
3605
|
-
c.set("bearer", bearer);
|
|
3606
|
-
return next();
|
|
3607
|
-
}
|
|
3608
|
-
const secret = getCookie(c, SESSION_COOKIE);
|
|
3609
|
-
const found = auth.authenticate(secret);
|
|
3610
|
-
const session = found?.session ?? null;
|
|
3611
|
-
if (found?.renewed && secret && c.req.path !== "/api/login" && c.req.path !== "/api/logout") setCookie(c, SESSION_COOKIE, secret, {
|
|
3612
|
-
httpOnly: true,
|
|
3613
|
-
secure: secure(c),
|
|
3614
|
-
sameSite: "Strict",
|
|
3615
|
-
path: "/",
|
|
3616
|
-
maxAge: Math.floor(SESSION_TTL_MS / 1e3)
|
|
3617
|
-
});
|
|
3618
|
-
if (PUBLIC_API.has(c.req.path)) {
|
|
3619
|
-
c.set("session", session);
|
|
3620
|
-
return next();
|
|
3621
|
-
}
|
|
3622
|
-
if (!session) return c.json({ error: "Sign in required" }, 401);
|
|
3623
|
-
if (!["GET", "HEAD"].includes(c.req.method) && c.req.header(CSRF_HEADER) !== "1") return c.json({ error: "Missing request header" }, 403);
|
|
3624
|
-
c.set("session", session);
|
|
3625
|
-
await next();
|
|
3626
|
-
});
|
|
3627
|
-
app.get("/api/auth", (c) => c.json({
|
|
3628
|
-
authenticated: !!c.get("session"),
|
|
3629
|
-
totp: auth.totpEnabled()
|
|
3630
|
-
}));
|
|
3631
|
-
app.post("/api/login", async (c) => {
|
|
3632
|
-
const input = z.object({
|
|
3633
|
-
token: z.string().min(1).max(200).optional(),
|
|
3634
|
-
code: z.string().regex(/^\d{6}$/).optional()
|
|
3635
|
-
}).refine((x) => !!x.token || !!x.code).parse(await c.req.json());
|
|
3636
|
-
const userAgent = c.req.header("user-agent") ?? "";
|
|
3637
|
-
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" : "");
|
|
3638
|
-
const result = auth.login(input, clientId(c), label);
|
|
3639
|
-
if (!result.ok) {
|
|
3640
|
-
if (result.retryAfter) c.header("Retry-After", String(result.retryAfter));
|
|
3641
|
-
return c.json({ error: result.status === 429 ? "Too many attempts. Try again later." : "That did not match." }, result.status);
|
|
3642
|
-
}
|
|
3643
|
-
setCookie(c, SESSION_COOKIE, result.secret, {
|
|
3644
|
-
httpOnly: true,
|
|
3645
|
-
secure: secure(c),
|
|
3646
|
-
sameSite: "Strict",
|
|
3647
|
-
path: "/",
|
|
3648
|
-
maxAge: SESSION_TTL_MS / 1e3
|
|
3649
|
-
});
|
|
3650
|
-
return c.json({ ok: true });
|
|
3651
|
-
});
|
|
3652
|
-
app.post("/api/logout", (c) => {
|
|
3653
|
-
const session = c.get("session");
|
|
3654
|
-
if (session) {
|
|
3655
|
-
auth.revoke(session.id);
|
|
3656
|
-
attachments.clearOwner(session.id);
|
|
3657
|
-
}
|
|
3658
|
-
deleteCookie(c, SESSION_COOKIE, { path: "/" });
|
|
3659
|
-
return c.json({ ok: true });
|
|
3660
|
-
});
|
|
3661
|
-
app.get("/api/sessions", (c) => c.json(store.sessions().map((s) => ({
|
|
3662
|
-
id: s.id,
|
|
3663
|
-
label: s.label,
|
|
3664
|
-
created: s.created,
|
|
3665
|
-
lastSeen: s.lastSeen,
|
|
3666
|
-
current: s.id === c.get("session")?.id
|
|
3667
|
-
}))));
|
|
3668
|
-
app.delete("/api/sessions/:id", (c) => {
|
|
3669
|
-
auth.revoke(c.req.param("id"));
|
|
3670
|
-
if (c.req.param("id") === c.get("session")?.id) deleteCookie(c, SESSION_COOKIE, { path: "/" });
|
|
3671
|
-
return c.json({ ok: true });
|
|
3672
|
-
});
|
|
3673
|
-
app.post("/api/sessions/revoke-all", (c) => {
|
|
3674
|
-
auth.revoke();
|
|
3675
|
-
deleteCookie(c, SESSION_COOKIE, { path: "/" });
|
|
3676
|
-
return c.json({ ok: true });
|
|
3677
|
-
});
|
|
3678
|
-
const requireSession = (session) => {
|
|
3679
|
-
if (!session) throw new z.ZodError([{
|
|
3680
|
-
code: "custom",
|
|
3681
|
-
path: [],
|
|
3682
|
-
message: "A browser session is required",
|
|
3683
|
-
input: null
|
|
3684
|
-
}]);
|
|
3685
|
-
return session;
|
|
3686
|
-
};
|
|
3687
|
-
app.post("/api/totp/setup", async (c) => {
|
|
3688
|
-
const session = requireSession(c.get("session"));
|
|
3689
|
-
if (auth.totpEnabled()) return c.json({ error: "Disable the current authenticator before replacing it." }, 409);
|
|
3690
|
-
const { secret, uri } = auth.beginTotp(session.id);
|
|
3691
|
-
const qr = await QRCode.toString(uri, {
|
|
3692
|
-
type: "svg",
|
|
3693
|
-
margin: 1,
|
|
3694
|
-
errorCorrectionLevel: "M"
|
|
3695
|
-
});
|
|
3696
|
-
return c.json({
|
|
3697
|
-
secret,
|
|
3698
|
-
uri,
|
|
3699
|
-
qr: "data:image/svg+xml;base64," + Buffer.from(qr).toString("base64")
|
|
3700
|
-
});
|
|
3701
|
-
});
|
|
3702
|
-
app.post("/api/totp/confirm", async (c) => {
|
|
3703
|
-
const session = requireSession(c.get("session"));
|
|
3704
|
-
const { code } = z.object({ code: z.string().regex(/^\d{6}$/) }).parse(await c.req.json());
|
|
3705
|
-
if (!auth.confirmTotp(session.id, code)) return c.json({ error: "That code did not match. Try the next one." }, 400);
|
|
3706
|
-
return c.json({ ok: true });
|
|
3707
|
-
});
|
|
3708
|
-
app.post("/api/totp/disable", async (c) => {
|
|
3709
|
-
const { code } = z.object({ code: z.string().regex(/^\d{6}$/) }).parse(await c.req.json());
|
|
3710
|
-
if (!auth.disableTotp(code)) return c.json({ error: "That code did not match." }, 400);
|
|
3711
|
-
return c.json({ ok: true });
|
|
3712
|
-
});
|
|
3713
|
-
const prefsSchema = z.object({
|
|
3714
|
-
attention: z.boolean(),
|
|
3715
|
-
turns: z.boolean()
|
|
3716
|
-
});
|
|
3717
|
-
app.get("/api/push/key", (c) => c.json({ publicKey: vapidKeys(store).publicKey }));
|
|
3718
|
-
app.post("/api/push/subscribe", async (c) => {
|
|
3719
|
-
const session = requireSession(c.get("session"));
|
|
3720
|
-
const input = z.object({
|
|
3721
|
-
subscription: z.object({
|
|
3722
|
-
endpoint: z.string().url().max(2e3).refine((u) => u.startsWith("https://")),
|
|
3723
|
-
keys: z.object({
|
|
3724
|
-
p256dh: z.string().min(1).max(200),
|
|
3725
|
-
auth: z.string().min(1).max(100)
|
|
3726
|
-
})
|
|
3727
|
-
}),
|
|
3728
|
-
prefs: prefsSchema
|
|
3729
|
-
}).parse(await c.req.json());
|
|
3730
|
-
store.savePushSubscription({
|
|
3731
|
-
endpoint: input.subscription.endpoint,
|
|
3732
|
-
sessionId: session.id,
|
|
3733
|
-
p256dh: input.subscription.keys.p256dh,
|
|
3734
|
-
auth: input.subscription.keys.auth,
|
|
3735
|
-
prefs: input.prefs,
|
|
3736
|
-
created: Date.now()
|
|
3737
|
-
});
|
|
3738
|
-
return c.json({ ok: true });
|
|
3739
|
-
});
|
|
3740
|
-
app.post("/api/push/status", async (c) => {
|
|
3741
|
-
const { endpoint } = z.object({ endpoint: z.string().max(2e3) }).parse(await c.req.json());
|
|
3742
|
-
const found = store.pushSubscriptions().find((s) => s.endpoint === endpoint);
|
|
3743
|
-
return c.json(found ? {
|
|
3744
|
-
subscribed: true,
|
|
3745
|
-
prefs: found.prefs
|
|
3746
|
-
} : { subscribed: false });
|
|
3747
|
-
});
|
|
3748
|
-
app.post("/api/push/unsubscribe", async (c) => {
|
|
3749
|
-
const { endpoint } = z.object({ endpoint: z.string().max(2e3) }).parse(await c.req.json());
|
|
3750
|
-
store.removePushSubscription(endpoint);
|
|
3751
|
-
return c.json({ ok: true });
|
|
3752
|
-
});
|
|
3753
|
-
app.post("/api/push/test", async (c) => {
|
|
3754
|
-
const session = requireSession(c.get("session"));
|
|
3755
|
-
return c.json({ sent: await notifier.test(session.id) });
|
|
3756
|
-
});
|
|
3757
|
-
app.onError((error, c) => {
|
|
3758
|
-
if (error instanceof UnknownHostError) return c.json({ error: "Unknown host" }, 404);
|
|
3759
|
-
if (error instanceof z.ZodError) return c.json({
|
|
3760
|
-
error: "Invalid request",
|
|
3761
|
-
detail: error.issues
|
|
3762
|
-
}, 400);
|
|
3763
|
-
const requestId = randomUUID();
|
|
3764
|
-
const failure = error;
|
|
3765
|
-
const cause = failure.cause instanceof Error ? failure.cause : null;
|
|
3766
|
-
console.error(JSON.stringify({
|
|
3767
|
-
event: "api_operation_failed",
|
|
3768
|
-
requestId,
|
|
3769
|
-
method: c.req.method,
|
|
3770
|
-
path: c.req.path,
|
|
3771
|
-
route: c.req.routePath,
|
|
3772
|
-
error: failure.name,
|
|
3773
|
-
...typeof failure.code === "string" ? { code: failure.code } : {},
|
|
3774
|
-
message: String(failure.message ?? "").slice(0, 500),
|
|
3775
|
-
...cause ? { cause: `${cause.name}: ${cause.message}`.slice(0, 300) } : {},
|
|
3776
|
-
at: failure.stack?.split("\n").slice(1, 4).map((line) => line.trim())
|
|
3777
|
-
}));
|
|
3778
|
-
return c.json({
|
|
3779
|
-
error: "Operation failed; refresh state before retrying",
|
|
3780
|
-
requestId
|
|
3781
|
-
}, 502);
|
|
3782
|
-
});
|
|
3783
|
-
app.get("/api/health", (c) => c.json({
|
|
3784
|
-
ok: true,
|
|
3785
|
-
version: VERSION,
|
|
3786
|
-
waiting: notifier.waitingCount
|
|
3787
|
-
}));
|
|
3788
|
-
const hostStates = () => store.hosts().map((h) => ({
|
|
3789
|
-
id: h.id,
|
|
3790
|
-
label: h.label,
|
|
3791
|
-
state: hosts.state(h.id),
|
|
3792
|
-
diagnostic: hosts.diagnostic(h.id)
|
|
3793
|
-
}));
|
|
3794
|
-
app.get("/api/hosts", (c) => c.json(hostStates()));
|
|
3795
|
-
const directoryStreams = /* @__PURE__ */ new Set();
|
|
3796
|
-
let agentFlush;
|
|
3797
|
-
let hostFlush;
|
|
3798
|
-
/** Set on shutdown: closing the hosts still reports changes, but the store is about to close. */
|
|
3799
|
-
let disposed = false;
|
|
3800
|
-
const deliverAgents = (stream) => {
|
|
3801
|
-
deliverWorkspaces(stream);
|
|
3802
|
-
const { agents } = hosts;
|
|
3803
|
-
const changes = agents.changesSince(stream.last);
|
|
3804
|
-
if (changes === null) stream.send({
|
|
3805
|
-
type: "snapshot",
|
|
3806
|
-
generation: agents.generation,
|
|
3807
|
-
seq: agents.seq,
|
|
3808
|
-
agents: agents.snapshot()
|
|
3809
|
-
});
|
|
3810
|
-
else if (changes.length) stream.send({
|
|
3811
|
-
type: "changes",
|
|
3812
|
-
generation: agents.generation,
|
|
3813
|
-
seq: agents.seq,
|
|
3814
|
-
changes
|
|
3815
|
-
});
|
|
3816
|
-
stream.last = agents.seq;
|
|
3817
|
-
};
|
|
3818
|
-
const deliverWorkspaces = (stream) => {
|
|
3819
|
-
const { workspaces } = hosts;
|
|
3820
|
-
const changes = workspaces.changesSince(stream.lastWorkspaces);
|
|
3821
|
-
if (changes === null) stream.send({
|
|
3822
|
-
type: "workspaces-snapshot",
|
|
3823
|
-
generation: workspaces.generation,
|
|
3824
|
-
seq: workspaces.seq,
|
|
3825
|
-
workspaces: workspaces.snapshot()
|
|
3826
|
-
});
|
|
3827
|
-
else if (changes.length) stream.send({
|
|
3828
|
-
type: "workspaces-changes",
|
|
3829
|
-
generation: workspaces.generation,
|
|
3830
|
-
seq: workspaces.seq,
|
|
3831
|
-
changes
|
|
3832
|
-
});
|
|
3833
|
-
stream.lastWorkspaces = workspaces.seq;
|
|
3834
|
-
};
|
|
3835
|
-
hosts.onAgentsChanged(() => {
|
|
3836
|
-
if (disposed || agentFlush || !directoryStreams.size) return;
|
|
3837
|
-
agentFlush = setTimeout(() => {
|
|
3838
|
-
agentFlush = void 0;
|
|
3839
|
-
for (const stream of directoryStreams) deliverAgents(stream);
|
|
3840
|
-
}, AGENT_FLUSH_MS);
|
|
3841
|
-
});
|
|
3842
|
-
hosts.onHostsChanged(() => {
|
|
3843
|
-
if (disposed || hostFlush || !directoryStreams.size) return;
|
|
3844
|
-
hostFlush = setTimeout(() => {
|
|
3845
|
-
hostFlush = void 0;
|
|
3846
|
-
const message = {
|
|
3847
|
-
type: "hosts",
|
|
3848
|
-
hosts: hostStates()
|
|
3849
|
-
};
|
|
3850
|
-
for (const stream of directoryStreams) stream.send(message);
|
|
3851
|
-
}, HOST_FLUSH_MS);
|
|
3852
|
-
});
|
|
3853
|
-
/** Re-checked on heartbeat: a revoked session, or a rotated token, loses its open streams. */
|
|
3854
|
-
const streamValidity = (c) => {
|
|
3855
|
-
const session = c.get("session"), bearer = c.get("bearer");
|
|
3856
|
-
if (session) return () => auth.stillValid(session.id);
|
|
3857
|
-
return () => !!bearer && !auth.totpEnabled() && auth.checkToken(bearer);
|
|
3858
|
-
};
|
|
3859
|
-
app.get("/api/stream", (c) => {
|
|
3860
|
-
const since = Number(c.req.query("since"));
|
|
3861
|
-
const resumable = c.req.query("generation") === hosts.agents.generation && Number.isInteger(since);
|
|
3862
|
-
const wsince = Number(c.req.query("wsince"));
|
|
3863
|
-
const wresumable = c.req.query("wgeneration") === hosts.workspaces.generation && Number.isInteger(wsince);
|
|
3864
|
-
return eventStream(c.req.raw.signal, (send) => {
|
|
3865
|
-
const stream = {
|
|
3866
|
-
last: resumable ? since : -1,
|
|
3867
|
-
lastWorkspaces: wresumable ? wsince : -1,
|
|
3868
|
-
send
|
|
3869
|
-
};
|
|
3870
|
-
send({
|
|
3871
|
-
type: "hosts",
|
|
3872
|
-
hosts: hostStates()
|
|
3873
|
-
});
|
|
3874
|
-
deliverAgents(stream);
|
|
3875
|
-
directoryStreams.add(stream);
|
|
3876
|
-
return () => directoryStreams.delete(stream);
|
|
3877
|
-
}, streamValidity(c));
|
|
3878
|
-
});
|
|
3879
|
-
app.post("/api/hosts", async (c) => {
|
|
3880
|
-
const input = z.object({
|
|
3881
|
-
label: z.string().trim().min(1).max(80),
|
|
3882
|
-
connection: z.string().trim().min(1).max(16e3)
|
|
3883
|
-
}).parse(await c.req.json());
|
|
3884
|
-
parseHostTarget(input.connection);
|
|
3885
|
-
const host = store.addHost(input.label, input.connection);
|
|
3886
|
-
try {
|
|
3887
|
-
hosts.add(host);
|
|
3888
|
-
} catch (e) {
|
|
3889
|
-
store.removeHost(host.id);
|
|
3890
|
-
throw e;
|
|
3891
|
-
}
|
|
3892
|
-
return c.json({
|
|
3893
|
-
id: host.id,
|
|
3894
|
-
label: host.label
|
|
3895
|
-
}, 201);
|
|
3896
|
-
});
|
|
3897
|
-
app.delete("/api/hosts/:host", async (c) => {
|
|
3898
|
-
await hosts.remove(c.req.param("host"));
|
|
3899
|
-
store.removeHost(c.req.param("host"));
|
|
3900
|
-
return c.json({ ok: true });
|
|
3901
|
-
});
|
|
3902
|
-
/** Providers the host can start right now, read from the daemon's provider snapshot. */
|
|
3903
|
-
app.get("/api/hosts/:host/providers", async (c) => {
|
|
3904
|
-
const providers = (await hosts.get(c.req.param("host")).api.providers.snapshot()).entries.filter((entry) => entry.enabled !== false && entry.status !== "unavailable").map((entry) => ({
|
|
3905
|
-
id: entry.provider,
|
|
3906
|
-
label: entry.label ?? entry.provider,
|
|
3907
|
-
status: entry.status,
|
|
3908
|
-
...entry.error ? { error: entry.error } : {},
|
|
3909
|
-
defaultModeId: entry.defaultModeId ?? null,
|
|
3910
|
-
modes: (entry.modes ?? []).map((m) => ({
|
|
3911
|
-
id: m.id,
|
|
3912
|
-
label: m.label,
|
|
3913
|
-
...m.description ? { description: m.description } : {}
|
|
3914
|
-
})),
|
|
3915
|
-
models: (entry.models ?? []).filter((m) => m.isSelectable !== false).map((m) => ({
|
|
3916
|
-
id: m.id,
|
|
3917
|
-
label: m.label,
|
|
3918
|
-
...m.description ? { description: m.description } : {},
|
|
3919
|
-
isDefault: m.isDefault === true,
|
|
3920
|
-
thinking: (m.thinkingOptions ?? []).map((t) => ({
|
|
3921
|
-
id: t.id,
|
|
3922
|
-
label: t.label
|
|
3923
|
-
})),
|
|
3924
|
-
defaultThinkingId: m.defaultThinkingOptionId ?? null
|
|
3925
|
-
}))
|
|
3926
|
-
}));
|
|
3927
|
-
return c.json(providers);
|
|
3928
|
-
});
|
|
3929
|
-
/** Projects the daemon knows, as starting points for a new session. */
|
|
3930
|
-
app.get("/api/hosts/:host/projects", async (c) => {
|
|
3931
|
-
const projects = (await hosts.get(c.req.param("host")).api.projects.list()).projects.map((p) => ({
|
|
3932
|
-
key: p.projectKey ?? p.projectId,
|
|
3933
|
-
name: p.projectCustomName || p.projectDisplayName,
|
|
3934
|
-
rootPath: p.projectRootPath,
|
|
3935
|
-
kind: p.projectKind
|
|
3936
|
-
}));
|
|
3937
|
-
return c.json(projects);
|
|
3938
|
-
});
|
|
3939
|
-
/**
|
|
3940
|
-
* Starts a session. The browser's idempotency key travels to the daemon, so retrying after an
|
|
3941
|
-
* unknown outcome cannot create a second session.
|
|
3942
|
-
*/
|
|
3943
|
-
app.post("/api/hosts/:host/agents", async (c) => {
|
|
3944
|
-
const input = z.object({
|
|
3945
|
-
idempotencyKey: z.string().uuid(),
|
|
3946
|
-
cwd: z.string().trim().min(1).max(4096),
|
|
3947
|
-
provider: z.string().trim().min(1).max(200).regex(/^[^/]+$/),
|
|
3948
|
-
model: z.string().trim().min(1).max(300).optional(),
|
|
3949
|
-
modeId: z.string().trim().min(1).max(200).optional(),
|
|
3950
|
-
thinkingOptionId: z.string().trim().min(1).max(200).optional(),
|
|
3951
|
-
prompt: z.string().max(1e5).optional(),
|
|
3952
|
-
worktreeBranch: z.string().trim().min(1).max(200).optional()
|
|
3953
|
-
}).parse(await c.req.json());
|
|
3954
|
-
const hostId = c.req.param("host");
|
|
3955
|
-
const { api } = hosts.get(hostId);
|
|
3956
|
-
try {
|
|
3957
|
-
let model = input.model;
|
|
3958
|
-
if (!model) {
|
|
3959
|
-
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) ?? [];
|
|
3960
|
-
model = models.find((m) => m.isDefault)?.id ?? models[0]?.id;
|
|
3961
|
-
if (!model) return c.json({ error: "No selectable model is available for this provider. Refresh providers and select a model." }, 400);
|
|
3962
|
-
}
|
|
3963
|
-
const agent = await api.agents.create({
|
|
3964
|
-
idempotencyKey: input.idempotencyKey,
|
|
3965
|
-
cwd: input.cwd,
|
|
3966
|
-
config: {
|
|
3967
|
-
provider: `${input.provider}/${model}`,
|
|
3968
|
-
...input.modeId ? { modeId: input.modeId } : {},
|
|
3969
|
-
...input.thinkingOptionId ? { thinkingOptionId: input.thinkingOptionId } : {}
|
|
3970
|
-
},
|
|
3971
|
-
...input.prompt?.trim() ? { prompt: input.prompt } : {},
|
|
3972
|
-
...input.worktreeBranch ? { worktree: {
|
|
3973
|
-
mode: "branch-off",
|
|
3974
|
-
newBranch: input.worktreeBranch
|
|
3975
|
-
} } : {}
|
|
3976
|
-
});
|
|
3977
|
-
return c.json({
|
|
3978
|
-
id: agent.id,
|
|
3979
|
-
key: `${hostId}:${agent.id}`
|
|
3980
|
-
}, 201);
|
|
3981
|
-
} catch (error) {
|
|
3982
|
-
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);
|
|
3983
|
-
}
|
|
3984
|
-
});
|
|
3985
|
-
app.get("/api/hosts/:host/agents/:agent/timeline/stream", (c) => {
|
|
3986
|
-
hosts.get(c.req.param("host"));
|
|
3987
|
-
return eventStream(c.req.raw.signal, (send) => {
|
|
3988
|
-
const sessionId = c.get("session")?.id;
|
|
3989
|
-
const key = `${c.req.param("host")}:${c.req.param("agent")}`;
|
|
3990
|
-
const stop = hosts.watchTimeline(c.req.param("host"), c.req.param("agent"), (ops) => send({
|
|
3991
|
-
type: "ops",
|
|
3992
|
-
ops
|
|
3993
|
-
}));
|
|
3994
|
-
if (sessionId) {
|
|
3995
|
-
let devices = viewers.get(key);
|
|
3996
|
-
if (!devices) viewers.set(key, devices = /* @__PURE__ */ new Map());
|
|
3997
|
-
devices.set(sessionId, (devices.get(sessionId) ?? 0) + 1);
|
|
3998
|
-
}
|
|
3999
|
-
return () => {
|
|
4000
|
-
stop();
|
|
4001
|
-
const devices = viewers.get(key);
|
|
4002
|
-
if (sessionId && devices) {
|
|
4003
|
-
const count = (devices.get(sessionId) ?? 1) - 1;
|
|
4004
|
-
if (count) devices.set(sessionId, count);
|
|
4005
|
-
else devices.delete(sessionId);
|
|
4006
|
-
if (!devices.size) viewers.delete(key);
|
|
4007
|
-
}
|
|
4008
|
-
};
|
|
4009
|
-
}, streamValidity(c));
|
|
4010
|
-
});
|
|
4011
|
-
/** Bounded history pages; the browser bookmarks boundaries for forward navigation. */
|
|
4012
|
-
app.get("/api/hosts/:host/agents/:agent/timeline", async (c) => {
|
|
4013
|
-
const cursor = z.object({
|
|
4014
|
-
epoch: z.string().min(1),
|
|
4015
|
-
seq: z.number().int().nonnegative()
|
|
4016
|
-
}).parse(parseJson(c.req.query("cursor")));
|
|
4017
|
-
const page = await hosts.get(c.req.param("host")).driver.fetchAgentTimeline(c.req.param("agent"), {
|
|
4018
|
-
direction: "before",
|
|
4019
|
-
cursor,
|
|
4020
|
-
limit: 100,
|
|
4021
|
-
projection: "projected",
|
|
4022
|
-
wholeTurns: false
|
|
4023
|
-
});
|
|
4024
|
-
return c.json({
|
|
4025
|
-
epoch: page.epoch,
|
|
4026
|
-
hasOlder: page.hasOlder,
|
|
4027
|
-
startCursor: page.startCursor,
|
|
4028
|
-
rows: page.entries.map((e) => ({
|
|
4029
|
-
seqStart: e.seqStart,
|
|
4030
|
-
seqEnd: e.seqEnd,
|
|
4031
|
-
timestamp: e.timestamp,
|
|
4032
|
-
provider: e.provider,
|
|
4033
|
-
...e.turnId ? { turnId: e.turnId } : {},
|
|
4034
|
-
item: e.item
|
|
4035
|
-
}))
|
|
4036
|
-
});
|
|
4037
|
-
});
|
|
4038
|
-
/** The conversation's user prompts (seq + short preview), for the outline rail. */
|
|
4039
|
-
app.get("/api/hosts/:host/agents/:agent/timeline/prompts", async (c) => {
|
|
4040
|
-
const client = hosts.get(c.req.param("host"));
|
|
4041
|
-
try {
|
|
4042
|
-
const page = await client.driver.listAgentTimelinePrompts(c.req.param("agent"), { timeout: 15e3 });
|
|
4043
|
-
return c.json({
|
|
4044
|
-
epoch: page.epoch,
|
|
4045
|
-
prompts: page.prompts.map((p) => ({
|
|
4046
|
-
seq: p.seq,
|
|
4047
|
-
preview: p.preview.replace(/\s+/g, " ").trim().slice(0, 240)
|
|
4048
|
-
}))
|
|
4049
|
-
});
|
|
4050
|
-
} catch (error) {
|
|
4051
|
-
return c.json({ error: error.message || "Prompt index unavailable" }, 501);
|
|
4052
|
-
}
|
|
4053
|
-
});
|
|
4054
|
-
/**
|
|
4055
|
-
* Rewinds to just before a user message: the conversation, the tracked files, or both, as
|
|
4056
|
-
* the provider supports. Cannot be undone; the timeline is replaced (new epoch) on success.
|
|
4057
|
-
*/
|
|
4058
|
-
app.post("/api/hosts/:host/agents/:agent/rewind", async (c) => {
|
|
4059
|
-
const { messageId, mode } = z.object({
|
|
4060
|
-
messageId: z.string().min(1).max(500),
|
|
4061
|
-
mode: z.enum([
|
|
4062
|
-
"conversation",
|
|
4063
|
-
"files",
|
|
4064
|
-
"both"
|
|
4065
|
-
])
|
|
4066
|
-
}).parse(await c.req.json());
|
|
4067
|
-
const client = hosts.get(c.req.param("host"));
|
|
4068
|
-
const facts = client.directory.facts(c.req.param("agent"));
|
|
4069
|
-
if (!facts) return c.json({ error: "Unknown agent" }, 404);
|
|
4070
|
-
if (!rewindModes(facts.capabilities).includes(mode)) return c.json({ error: "This agent cannot rewind that way." }, 400);
|
|
4071
|
-
try {
|
|
4072
|
-
await client.driver.rewindAgent(c.req.param("agent"), messageId, mode);
|
|
4073
|
-
return c.json({ ok: true });
|
|
4074
|
-
} catch (error) {
|
|
4075
|
-
return c.json({ error: error.message || "Rewind failed" }, 502);
|
|
4076
|
-
}
|
|
4077
|
-
});
|
|
4078
|
-
/**
|
|
4079
|
-
* An image an agent referenced in a message (``, an absolute or workspace path).
|
|
4080
|
-
* Workspace files go through the daemon's file API; images the daemon materialized from
|
|
4081
|
-
* provider output live outside the workspace and are read from disk when the daemon is local.
|
|
4082
|
-
*/
|
|
4083
|
-
app.get("/api/hosts/:host/agents/:agent/image", async (c) => {
|
|
4084
|
-
const hostId = c.req.param("host");
|
|
4085
|
-
const path = z.string().min(1).max(4096).refine((p) => !p.includes("\0")).parse(c.req.query("path"));
|
|
4086
|
-
const mime = imageMime(path);
|
|
4087
|
-
if (!mime) return c.json({ error: "Not an image" }, 415);
|
|
4088
|
-
const { driver } = hosts.get(hostId);
|
|
4089
|
-
const cwd = hosts.agents.get(`${hostId}:${c.req.param("agent")}`)?.cwd;
|
|
4090
|
-
let bytes = null;
|
|
4091
|
-
if (isMaterializedImagePath(path)) {
|
|
4092
|
-
const host = store.hosts().find((h) => h.id === hostId);
|
|
4093
|
-
if (host && isLocalConnection(host.connection)) bytes = await readMaterializedImage(path);
|
|
4094
|
-
} else if (cwd) try {
|
|
4095
|
-
const file = await driver.readFile(cwd, path, void 0, MAX_IMAGE_BYTES);
|
|
4096
|
-
if (file.size <= 16777216) bytes = file.bytes;
|
|
4097
|
-
} catch {
|
|
4098
|
-
bytes = null;
|
|
4099
|
-
}
|
|
4100
|
-
if (!bytes) return c.json({ error: "Image unavailable from this host" }, 404);
|
|
4101
|
-
return c.body(bytes, 200, {
|
|
4102
|
-
"Content-Type": mime,
|
|
4103
|
-
"Cache-Control": "private, max-age=86400",
|
|
4104
|
-
"Content-Disposition": "inline"
|
|
4105
|
-
});
|
|
4106
|
-
});
|
|
4107
|
-
/** A project's icon (favicon/logo the daemon found in its root), cached briefly per host. */
|
|
4108
|
-
app.get("/api/hosts/:host/project-icon", async (c) => {
|
|
4109
|
-
const hostId = c.req.param("host");
|
|
4110
|
-
const cwd = z.string().min(1).max(4096).parse(c.req.query("cwd"));
|
|
4111
|
-
const key = `${hostId}\n${cwd}`;
|
|
4112
|
-
let icon = projectIcons.get(key);
|
|
4113
|
-
if (icon === void 0) {
|
|
4114
|
-
try {
|
|
4115
|
-
const result = await hosts.get(hostId).driver.requestProjectIcon(cwd);
|
|
4116
|
-
icon = result.icon && /^image\/(png|jpeg|webp|gif|x-icon|vnd\.microsoft\.icon)$/.test(result.icon.mimeType) ? {
|
|
4117
|
-
data: Buffer.from(result.icon.data, "base64"),
|
|
4118
|
-
mimeType: result.icon.mimeType
|
|
4119
|
-
} : null;
|
|
4120
|
-
} catch (error) {
|
|
4121
|
-
if (error instanceof UnknownHostError) throw error;
|
|
4122
|
-
return c.json({ error: "Icon unavailable" }, 502);
|
|
4123
|
-
}
|
|
4124
|
-
projectIcons.set(key, icon);
|
|
4125
|
-
}
|
|
4126
|
-
if (!icon) return c.body(null, 204, { "Cache-Control": "private, max-age=600" });
|
|
4127
|
-
return c.body(icon.data, 200, {
|
|
4128
|
-
"Content-Type": icon.mimeType,
|
|
4129
|
-
"Cache-Control": "private, max-age=600"
|
|
4130
|
-
});
|
|
4131
|
-
});
|
|
4132
|
-
/** What the open agent can switch to. Modes/features come from the live directory (no round trip). */
|
|
4133
|
-
app.get("/api/hosts/:host/agents/:agent/config", async (c) => {
|
|
4134
|
-
const hostId = c.req.param("host");
|
|
4135
|
-
const client = hosts.get(hostId);
|
|
4136
|
-
const facts = client.directory.facts(c.req.param("agent"));
|
|
4137
|
-
if (!facts) return c.json({ error: "Unknown agent" }, 404);
|
|
4138
|
-
const options = {
|
|
4139
|
-
models: ((await client.api.providers.snapshot()).entries.find((p) => p.provider === facts.provider)?.models ?? []).filter((m) => m.isSelectable !== false).map((m) => ({
|
|
4140
|
-
id: m.id,
|
|
4141
|
-
label: m.label,
|
|
4142
|
-
thinking: (m.thinkingOptions ?? []).map((t) => ({
|
|
4143
|
-
id: t.id,
|
|
4144
|
-
label: t.label
|
|
4145
|
-
})),
|
|
4146
|
-
defaultThinkingId: m.defaultThinkingOptionId ?? null
|
|
4147
|
-
})),
|
|
4148
|
-
modes: facts.availableModes.map((m) => ({
|
|
4149
|
-
id: m.id,
|
|
4150
|
-
label: m.label,
|
|
4151
|
-
...m.description ? { description: m.description } : {}
|
|
4152
|
-
})),
|
|
4153
|
-
features: facts.features.map((f) => f.type === "toggle" ? {
|
|
4154
|
-
type: "toggle",
|
|
4155
|
-
id: f.id,
|
|
4156
|
-
label: f.label,
|
|
4157
|
-
...f.tooltip ? { tooltip: f.tooltip } : {},
|
|
4158
|
-
value: f.value
|
|
4159
|
-
} : {
|
|
4160
|
-
type: "select",
|
|
4161
|
-
id: f.id,
|
|
4162
|
-
label: f.label,
|
|
4163
|
-
...f.tooltip ? { tooltip: f.tooltip } : {},
|
|
4164
|
-
value: f.value,
|
|
4165
|
-
options: f.options.map((o) => ({
|
|
4166
|
-
id: o.id,
|
|
4167
|
-
label: o.label
|
|
4168
|
-
}))
|
|
4169
|
-
})
|
|
4170
|
-
};
|
|
4171
|
-
return c.json(options);
|
|
4172
|
-
});
|
|
4173
|
-
app.post("/api/hosts/:host/agents/:agent/config", async (c) => {
|
|
4174
|
-
const change = z.object({
|
|
4175
|
-
model: z.string().min(1).max(300).optional(),
|
|
4176
|
-
thinkingOptionId: z.string().min(1).max(200).optional(),
|
|
4177
|
-
modeId: z.string().min(1).max(200).optional(),
|
|
4178
|
-
feature: z.object({
|
|
4179
|
-
id: z.string().min(1).max(200),
|
|
4180
|
-
value: z.union([z.string().max(200), z.boolean()])
|
|
4181
|
-
}).optional()
|
|
4182
|
-
}).refine((v) => Object.values(v).filter((x) => x !== void 0).length === 1).parse(await c.req.json());
|
|
4183
|
-
const { driver } = hosts.get(c.req.param("host"));
|
|
4184
|
-
const agent = c.req.param("agent");
|
|
4185
|
-
let notice = null;
|
|
4186
|
-
if (change.model) await driver.setAgentModel(agent, change.model);
|
|
4187
|
-
else if (change.thinkingOptionId) notice = await driver.setAgentThinkingOption(agent, change.thinkingOptionId);
|
|
4188
|
-
else if (change.modeId) notice = await driver.setAgentMode(agent, change.modeId);
|
|
4189
|
-
else if (change.feature) await driver.setAgentFeature(agent, change.feature.id, change.feature.value);
|
|
4190
|
-
return c.json({
|
|
4191
|
-
ok: true,
|
|
4192
|
-
notice
|
|
4193
|
-
});
|
|
4194
|
-
});
|
|
4195
|
-
/**
|
|
4196
|
-
* Speech to text through the transcription service configured here, once for every host. The
|
|
4197
|
-
* browser streams PCM over a short-lived socket. The file endpoint remains for older
|
|
4198
|
-
* clients. The API key never leaves the server.
|
|
4199
|
-
*/
|
|
4200
|
-
app.get("/api/dictation", (c) => c.json(dictationSettings(store)));
|
|
4201
|
-
app.post("/api/dictation/session", (c) => {
|
|
4202
|
-
const config = dictationConfig(store);
|
|
4203
|
-
if (!config) return c.json({ error: "Voice input is not set up. Add a transcription service in Settings." }, 409);
|
|
4204
|
-
try {
|
|
4205
|
-
return c.json(dictationStreams.issue(config, streamValidity(c)));
|
|
4206
|
-
} catch (error) {
|
|
4207
|
-
return c.json({ error: error.message }, 429);
|
|
4208
|
-
}
|
|
4209
|
-
});
|
|
4210
|
-
app.put("/api/dictation", async (c) => {
|
|
4211
|
-
try {
|
|
4212
|
-
return c.json(saveDictation(store, await c.req.json()));
|
|
4213
|
-
} catch (error) {
|
|
4214
|
-
const message = error instanceof z.ZodError ? error.issues[0]?.message ?? "Invalid settings" : error.message;
|
|
4215
|
-
return c.json({ error: message }, 400);
|
|
4216
|
-
}
|
|
4217
|
-
});
|
|
4218
|
-
app.delete("/api/dictation", (c) => {
|
|
4219
|
-
clearDictation(store);
|
|
4220
|
-
return c.json(dictationSettings(store));
|
|
4221
|
-
});
|
|
4222
|
-
app.post("/api/dictation/transcribe", async (c) => {
|
|
4223
|
-
const config = dictationConfig(store);
|
|
4224
|
-
if (!config) return c.json({ error: "Voice input is not set up. Add a transcription service in Settings." }, 409);
|
|
4225
|
-
const format = /^audio\/pcm;rate=(\d{4,6});bits=16$/.exec(c.req.header("x-audio-format") ?? "");
|
|
4226
|
-
if (!format) return c.json({ error: "Unsupported audio format" }, 415);
|
|
4227
|
-
const audio = new Uint8Array(await c.req.arrayBuffer());
|
|
4228
|
-
if (audio.length < 3200 || audio.length % 2) return c.json({ error: "Recording too short" }, 400);
|
|
4229
|
-
try {
|
|
4230
|
-
return c.json({ text: await transcribe(config, audio, Number(format[1]), options.fetch) });
|
|
4231
|
-
} catch (error) {
|
|
4232
|
-
if (error instanceof DictationError) return c.json({ error: error.message }, error.status);
|
|
4233
|
-
throw error;
|
|
4234
|
-
}
|
|
4235
|
-
});
|
|
4236
|
-
const attachmentOwner = (c) => c.get("session")?.id ?? "bearer";
|
|
4237
|
-
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"))));
|
|
4238
|
-
app.post("/api/hosts/:host/agents/:agent/attachments", async (c) => {
|
|
4239
|
-
hosts.get(c.req.param("host"));
|
|
4240
|
-
try {
|
|
4241
|
-
const name = decodeURIComponent(c.req.header("x-file-name") ?? "");
|
|
4242
|
-
const mime = c.req.header("content-type")?.split(";")[0] ?? "application/octet-stream";
|
|
4243
|
-
return c.json(attachments.put(attachmentOwner(c), c.req.param("host"), c.req.param("agent"), name, mime, Buffer.from(await c.req.arrayBuffer())), 201);
|
|
4244
|
-
} catch (error) {
|
|
4245
|
-
return c.json({ error: error.message }, 400);
|
|
4246
|
-
}
|
|
4247
|
-
});
|
|
4248
|
-
app.delete("/api/hosts/:host/agents/:agent/attachments/:id", (c) => {
|
|
4249
|
-
try {
|
|
4250
|
-
attachments.remove(c.req.param("id"), attachmentOwner(c), c.req.param("host"), c.req.param("agent"));
|
|
4251
|
-
} catch {
|
|
4252
|
-
return c.json({ error: "Attachment already expired or unavailable" }, 404);
|
|
4253
|
-
}
|
|
4254
|
-
return c.json({ ok: true });
|
|
4255
|
-
});
|
|
4256
|
-
app.post("/api/hosts/:host/agents/:agent/messages/status", async (c) => {
|
|
4257
|
-
const { messageIds } = z.object({ messageIds: z.array(z.string().uuid()).min(1).max(20) }).parse(await c.req.json());
|
|
4258
|
-
const { driver } = hosts.get(c.req.param("host"));
|
|
4259
|
-
return c.json({ confirmed: await confirmedMessages(driver, c.req.param("agent"), messageIds) });
|
|
4260
|
-
});
|
|
4261
|
-
app.post("/api/hosts/:host/agents/:agent/messages", async (c) => {
|
|
4262
|
-
const input = z.object({
|
|
4263
|
-
text: z.string().trim().max(1e5),
|
|
4264
|
-
attachmentIds: z.array(z.string().uuid()).max(4).refine((ids) => new Set(ids).size === ids.length).default([]),
|
|
4265
|
-
messageId: z.string().uuid(),
|
|
4266
|
-
behavior: z.enum(["steer", "interrupt"])
|
|
4267
|
-
}).refine((input) => !!input.text || input.attachmentIds.length > 0).parse(await c.req.json());
|
|
4268
|
-
let prepared;
|
|
4269
|
-
try {
|
|
4270
|
-
prepared = await attachments.prepare(hosts, attachmentOwner(c), c.req.param("host"), c.req.param("agent"), input.attachmentIds);
|
|
4271
|
-
} catch (error) {
|
|
4272
|
-
return c.json({
|
|
4273
|
-
error: error.message,
|
|
4274
|
-
delivery: "not-sent"
|
|
4275
|
-
}, 400);
|
|
4276
|
-
}
|
|
4277
|
-
try {
|
|
4278
|
-
await hosts.get(c.req.param("host")).api.agents.ref(c.req.param("agent")).send(input.text, {
|
|
4279
|
-
messageId: input.messageId,
|
|
4280
|
-
activeTurnBehavior: input.behavior,
|
|
4281
|
-
...prepared.images.length ? { images: prepared.images } : {},
|
|
4282
|
-
...prepared.attachments.length ? { attachments: prepared.attachments } : {}
|
|
4283
|
-
});
|
|
4284
|
-
attachments.consumed(input.attachmentIds);
|
|
4285
|
-
return c.json({
|
|
4286
|
-
status: "acknowledged",
|
|
4287
|
-
messageId: input.messageId
|
|
4288
|
-
});
|
|
4289
|
-
} catch {
|
|
4290
|
-
return c.json({
|
|
4291
|
-
error: "Delivery outcome unknown. Refresh the conversation before retrying.",
|
|
4292
|
-
messageId: input.messageId
|
|
4293
|
-
}, 502);
|
|
4294
|
-
}
|
|
4295
|
-
});
|
|
4296
|
-
app.post("/api/hosts/:host/agents/:agent/stop", async (c) => {
|
|
4297
|
-
await hosts.get(c.req.param("host")).driver.cancelAgent(c.req.param("agent"));
|
|
4298
|
-
return c.json({ status: "acknowledged" });
|
|
4299
|
-
});
|
|
4300
|
-
app.post("/api/hosts/:host/agents/:agent/permissions/:permission", async (c) => {
|
|
4301
|
-
const response = AgentPermissionResponseSchema.parse(await c.req.json());
|
|
4302
|
-
const agent = hosts.get(c.req.param("host")).api.agents.ref(c.req.param("agent"));
|
|
4303
|
-
await agent.refresh();
|
|
4304
|
-
if (!agent.pendingPermissions?.some((p) => p.id === c.req.param("permission"))) return c.json({ error: "Permission no longer pending. Refresh the conversation." }, 409);
|
|
4305
|
-
await agent.respondToPermission({
|
|
4306
|
-
requestId: c.req.param("permission"),
|
|
4307
|
-
response
|
|
4308
|
-
});
|
|
4309
|
-
return c.json({ status: "acknowledged" });
|
|
4310
|
-
});
|
|
4311
|
-
/** Marks a settled turn as seen (Paseo's attention flag), moving it out of "review". */
|
|
4312
|
-
app.post("/api/hosts/:host/agents/:agent/read", async (c) => {
|
|
4313
|
-
await hosts.get(c.req.param("host")).driver.clearAgentAttention(c.req.param("agent"));
|
|
4314
|
-
return c.json({ ok: true });
|
|
4315
|
-
});
|
|
4316
|
-
app.post("/api/hosts/:host/agents/:agent/archive", async (c) => {
|
|
4317
|
-
await hosts.get(c.req.param("host")).api.agents.ref(c.req.param("agent")).archive();
|
|
4318
|
-
return c.json({ ok: true });
|
|
4319
|
-
});
|
|
4320
|
-
const workspace = (c) => ({
|
|
4321
|
-
driver: hosts.get(c.req.param("host")).driver,
|
|
4322
|
-
id: c.req.param("workspace")
|
|
4323
|
-
});
|
|
4324
|
-
/** Rename; null resets to the name derived from the branch or directory. */
|
|
4325
|
-
app.post("/api/hosts/:host/workspaces/:workspace/title", async (c) => {
|
|
4326
|
-
const { title } = z.object({ title: z.string().trim().max(200).nullable() }).parse(await c.req.json());
|
|
4327
|
-
const { driver, id } = workspace(c);
|
|
4328
|
-
await driver.setWorkspaceTitle(id, title ? title : null);
|
|
4329
|
-
return c.json({ ok: true });
|
|
4330
|
-
});
|
|
4331
|
-
app.post("/api/hosts/:host/workspaces/:workspace/pin", async (c) => {
|
|
4332
|
-
const { pinned } = z.object({ pinned: z.boolean() }).parse(await c.req.json());
|
|
4333
|
-
const { driver, id } = workspace(c);
|
|
4334
|
-
await driver.setWorkspacePinned(id, pinned);
|
|
4335
|
-
return c.json({ ok: true });
|
|
4336
|
-
});
|
|
4337
|
-
app.post("/api/hosts/:host/workspaces/:workspace/unread", async (c) => {
|
|
4338
|
-
const { driver, id } = workspace(c);
|
|
4339
|
-
await driver.markWorkspaceUnread(id);
|
|
4340
|
-
return c.json({ ok: true });
|
|
4341
|
-
});
|
|
4342
|
-
app.post("/api/hosts/:host/workspaces/:workspace/read", async (c) => {
|
|
4343
|
-
const { driver, id } = workspace(c);
|
|
4344
|
-
await driver.clearWorkspaceAttention(id);
|
|
4345
|
-
return c.json({ ok: true });
|
|
4346
|
-
});
|
|
4347
|
-
app.post("/api/hosts/:host/workspaces/:workspace/archive", async (c) => {
|
|
4348
|
-
const { driver, id } = workspace(c);
|
|
4349
|
-
await driver.archiveWorkspace(id);
|
|
4350
|
-
return c.json({ ok: true });
|
|
4351
|
-
});
|
|
4352
|
-
/**
|
|
4353
|
-
* next-input: the daemon appends a placeholder row after a completed turn; prediction runs only
|
|
4354
|
-
* when a client that shows the row asks. Only this one plugin method is reachable from here.
|
|
4355
|
-
*/
|
|
4356
|
-
app.post("/api/hosts/:host/agents/:agent/suggestion", async (c) => {
|
|
4357
|
-
const { token } = z.object({ token: z.string().min(1).max(200) }).parse(await c.req.json());
|
|
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");
|
|
4358
998
|
try {
|
|
4359
|
-
|
|
4360
|
-
|
|
4361
|
-
|
|
4362
|
-
|
|
4363
|
-
|
|
4364
|
-
|
|
4365
|
-
text: String(output?.text ?? "")
|
|
4366
|
-
});
|
|
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");
|
|
4367
1005
|
} catch (error) {
|
|
4368
|
-
|
|
4369
|
-
|
|
4370
|
-
status: "unavailable",
|
|
4371
|
-
text: ""
|
|
4372
|
-
});
|
|
1006
|
+
this.store.db.exec("ROLLBACK");
|
|
1007
|
+
throw error;
|
|
4373
1008
|
}
|
|
4374
|
-
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
|
|
4378
|
-
|
|
4379
|
-
const
|
|
4380
|
-
|
|
4381
|
-
|
|
4382
|
-
|
|
4383
|
-
|
|
4384
|
-
if (!store.saveBoard(b.revision, b.cards)) return c.json({ error: "Board changed. Reload before editing." }, 409);
|
|
4385
|
-
return c.json(store.board());
|
|
4386
|
-
});
|
|
4387
|
-
const cardEdit = (id, change) => store.updateCard(id, change) ? store.board() : null;
|
|
4388
|
-
app.patch("/api/board/cards/:id", async (c) => {
|
|
4389
|
-
const p = cardPatch.parse(await c.req.json());
|
|
4390
|
-
const board = cardEdit(c.req.param("id"), (card) => ({
|
|
4391
|
-
...card,
|
|
4392
|
-
...p.title !== void 0 ? { title: p.title } : {},
|
|
4393
|
-
...p.column !== void 0 ? { column: p.column } : {},
|
|
4394
|
-
...p.description !== void 0 ? { description: p.description } : {},
|
|
4395
|
-
...p.link !== void 0 ? {
|
|
4396
|
-
hostId: p.link?.hostId ?? null,
|
|
4397
|
-
agentId: p.link?.agentId ?? null
|
|
4398
|
-
} : {},
|
|
4399
|
-
updatedAt: Date.now()
|
|
4400
|
-
}));
|
|
4401
|
-
return board ? c.json(board) : c.json({ error: "Task not found" }, 404);
|
|
4402
|
-
});
|
|
4403
|
-
app.post("/api/board/cards/:id/comments", async (c) => {
|
|
4404
|
-
const { text } = z.object({ text: z.string().trim().min(1).max(CARD_COMMENT_MAX) }).parse(await c.req.json());
|
|
4405
|
-
let full = false;
|
|
4406
|
-
const board = cardEdit(c.req.param("id"), (card) => {
|
|
4407
|
-
const comments = card.comments ?? [];
|
|
4408
|
-
if (comments.length >= 200) return full = true, null;
|
|
4409
|
-
return {
|
|
4410
|
-
...card,
|
|
4411
|
-
comments: [...comments, {
|
|
4412
|
-
id: randomUUID(),
|
|
4413
|
-
text,
|
|
4414
|
-
at: Date.now()
|
|
4415
|
-
}],
|
|
4416
|
-
updatedAt: Date.now()
|
|
4417
|
-
};
|
|
4418
|
-
});
|
|
4419
|
-
if (full) return c.json({ error: `A task holds up to 200 comments.` }, 400);
|
|
4420
|
-
return board ? c.json(board, 201) : c.json({ error: "Task not found" }, 404);
|
|
4421
|
-
});
|
|
4422
|
-
app.delete("/api/board/cards/:id/comments/:comment", (c) => {
|
|
4423
|
-
const board = cardEdit(c.req.param("id"), (card) => ({
|
|
4424
|
-
...card,
|
|
4425
|
-
comments: (card.comments ?? []).filter((m) => m.id !== c.req.param("comment")),
|
|
4426
|
-
updatedAt: Date.now()
|
|
4427
|
-
}));
|
|
4428
|
-
return board ? c.json(board) : c.json({ error: "Task not found" }, 404);
|
|
4429
|
-
});
|
|
4430
|
-
app.all("/api/*", (c) => c.json({ error: "Not found" }, 404));
|
|
4431
|
-
for (const [file, type] of [["sw.js", "text/javascript; charset=utf-8"], ["manifest.webmanifest", "application/manifest+json"]]) app.get("/" + file, (c) => {
|
|
4432
|
-
try {
|
|
4433
|
-
return c.body(readFileSync(join(webRoot, file)), 200, {
|
|
4434
|
-
"Content-Type": type,
|
|
4435
|
-
"Cache-Control": "no-cache"
|
|
4436
|
-
});
|
|
4437
|
-
} catch {
|
|
4438
|
-
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;
|
|
4439
1019
|
}
|
|
4440
|
-
|
|
4441
|
-
|
|
4442
|
-
|
|
4443
|
-
|
|
4444
|
-
|
|
4445
|
-
|
|
4446
|
-
|
|
4447
|
-
|
|
4448
|
-
|
|
4449
|
-
|
|
4450
|
-
|
|
4451
|
-
|
|
4452
|
-
|
|
4453
|
-
|
|
4454
|
-
|
|
4455
|
-
|
|
4456
|
-
|
|
4457
|
-
|
|
4458
|
-
|
|
4459
|
-
|
|
4460
|
-
|
|
4461
|
-
|
|
4462
|
-
|
|
4463
|
-
|
|
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));
|
|
4464
1050
|
}
|
|
4465
|
-
|
|
4466
|
-
|
|
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
|
+
};
|
|
4467
1061
|
// src/server/config.ts
|
|
4468
1062
|
/**
|
|
4469
1063
|
* Settings that used to need an environment variable on every start. `litepaseo config set`
|
|
@@ -4533,213 +1127,6 @@ function effectiveConfig(store, env) {
|
|
|
4533
1127
|
});
|
|
4534
1128
|
return Object.fromEntries(entries.map((entry) => [entry.key, entry]));
|
|
4535
1129
|
}
|
|
4536
|
-
// src/server/worker.ts
|
|
4537
|
-
async function runWorker(directory, webRoot) {
|
|
4538
|
-
if (!process.send) throw new Error("worker is an internal supervised command");
|
|
4539
|
-
const tokenPath = join(directory, "token");
|
|
4540
|
-
if (!existsSync(tokenPath)) writeFileSync(tokenPath, generateToken(), {
|
|
4541
|
-
mode: 384,
|
|
4542
|
-
flag: "wx"
|
|
4543
|
-
});
|
|
4544
|
-
const store = new Store(directory), hosts = new Hosts();
|
|
4545
|
-
for (const host of store.hosts()) try {
|
|
4546
|
-
hosts.add(host);
|
|
4547
|
-
} catch {
|
|
4548
|
-
console.error("Could not initialize host", host.id);
|
|
4549
|
-
}
|
|
4550
|
-
const config = effectiveConfig(store, process.env);
|
|
4551
|
-
const port = Number(config.port.value), hostname = config.bind.value;
|
|
4552
|
-
const app = createApp(store, hosts, tokenFile(tokenPath), webRoot, { pushSubject: config["push-subject"].value });
|
|
4553
|
-
const server = serve({
|
|
4554
|
-
fetch: app.fetch,
|
|
4555
|
-
port,
|
|
4556
|
-
hostname
|
|
4557
|
-
});
|
|
4558
|
-
app.dictationStreams.attach(server);
|
|
4559
|
-
let stopping = false;
|
|
4560
|
-
const shutdown = async () => {
|
|
4561
|
-
if (stopping) return;
|
|
4562
|
-
stopping = true;
|
|
4563
|
-
setTimeout(() => process.exit(1), 5e3).unref();
|
|
4564
|
-
app.dispose();
|
|
4565
|
-
await hosts.close();
|
|
4566
|
-
if ("closeAllConnections" in server) server.closeAllConnections();
|
|
4567
|
-
await new Promise((resolve) => server.close(() => resolve()));
|
|
4568
|
-
store.close();
|
|
4569
|
-
if (process.connected) process.disconnect();
|
|
4570
|
-
};
|
|
4571
|
-
process.once("SIGINT", () => void shutdown());
|
|
4572
|
-
process.once("SIGTERM", () => void shutdown());
|
|
4573
|
-
process.once("disconnect", () => void shutdown());
|
|
4574
|
-
server.once("error", (error) => {
|
|
4575
|
-
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;
|
|
4576
|
-
console.error(message);
|
|
4577
|
-
process.send?.({
|
|
4578
|
-
type: "fatal",
|
|
4579
|
-
error: message
|
|
4580
|
-
});
|
|
4581
|
-
process.exitCode = 1;
|
|
4582
|
-
shutdown();
|
|
4583
|
-
});
|
|
4584
|
-
server.once("listening", () => {
|
|
4585
|
-
const address = server.address();
|
|
4586
|
-
const actualPort = typeof address === "object" && address ? address.port : port;
|
|
4587
|
-
const url = `http://${hostname}:${actualPort}`;
|
|
4588
|
-
console.log(`LitePaseo ready at ${url}`);
|
|
4589
|
-
process.send?.({
|
|
4590
|
-
type: "ready",
|
|
4591
|
-
url
|
|
4592
|
-
});
|
|
4593
|
-
});
|
|
4594
|
-
}
|
|
4595
|
-
// src/server/backup.ts
|
|
4596
|
-
const FILES = ["litepaseo.sqlite", "token"];
|
|
4597
|
-
const digest = (path) => createHash("sha256").update(readFileSync(path)).digest("hex");
|
|
4598
|
-
/** A consistent SQLite snapshot includes committed WAL data; never copy a live database file. */
|
|
4599
|
-
function backup(directory, destination) {
|
|
4600
|
-
destination = resolve(destination);
|
|
4601
|
-
if (!existsSync(join(directory, FILES[0])) || !existsSync(join(directory, "token"))) throw new Error("No initialized LitePaseo data to back up.");
|
|
4602
|
-
mkdirSync(destination, { mode: 448 });
|
|
4603
|
-
let store;
|
|
4604
|
-
try {
|
|
4605
|
-
store = new Store(directory);
|
|
4606
|
-
store.db.prepare("VACUUM INTO ?").run(join(destination, FILES[0]));
|
|
4607
|
-
copyFileSync(join(directory, "token"), join(destination, "token"), constants.COPYFILE_EXCL);
|
|
4608
|
-
for (const file of FILES) chmodSync(join(destination, file), 384);
|
|
4609
|
-
writeFileSync(join(destination, "manifest.json"), JSON.stringify({
|
|
4610
|
-
format: 1,
|
|
4611
|
-
schema: 1,
|
|
4612
|
-
created: (/* @__PURE__ */ new Date()).toISOString(),
|
|
4613
|
-
files: Object.fromEntries(FILES.map((file) => [file, digest(join(destination, file))]))
|
|
4614
|
-
}, null, 2) + "\n", {
|
|
4615
|
-
mode: 384,
|
|
4616
|
-
flag: "wx"
|
|
4617
|
-
});
|
|
4618
|
-
} catch (error) {
|
|
4619
|
-
rmSync(destination, {
|
|
4620
|
-
recursive: true,
|
|
4621
|
-
force: true
|
|
4622
|
-
});
|
|
4623
|
-
throw error;
|
|
4624
|
-
} finally {
|
|
4625
|
-
store?.close();
|
|
4626
|
-
}
|
|
4627
|
-
}
|
|
4628
|
-
/** Restore only into an empty home; the same exclusive socket binding prevents concurrent startup. */
|
|
4629
|
-
async function restore(source, directory) {
|
|
4630
|
-
source = resolve(source);
|
|
4631
|
-
mkdirSync(directory, {
|
|
4632
|
-
recursive: true,
|
|
4633
|
-
mode: 448
|
|
4634
|
-
});
|
|
4635
|
-
chmodSync(directory, 448);
|
|
4636
|
-
const releaseRuntime = acquireRuntimeLock(directory);
|
|
4637
|
-
const lock = createServer((socket) => socket.destroy());
|
|
4638
|
-
await new Promise((resolve, reject) => {
|
|
4639
|
-
lock.once("error", reject);
|
|
4640
|
-
lock.listen(join(directory, "control.sock"), resolve);
|
|
4641
|
-
}).catch((error) => {
|
|
4642
|
-
releaseRuntime();
|
|
4643
|
-
throw error;
|
|
4644
|
-
});
|
|
4645
|
-
const stage = join(directory, ".restore-staging");
|
|
4646
|
-
let ownsStage = false;
|
|
4647
|
-
try {
|
|
4648
|
-
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.");
|
|
4649
|
-
mkdirSync(stage, { mode: 448 });
|
|
4650
|
-
ownsStage = true;
|
|
4651
|
-
const manifest = JSON.parse(readFileSync(join(source, "manifest.json"), "utf8"));
|
|
4652
|
-
if (manifest.format !== 1 || manifest.schema !== 1) throw new Error("Unsupported backup format or schema version.");
|
|
4653
|
-
for (const file of FILES) {
|
|
4654
|
-
copyFileSync(join(source, file), join(stage, file), constants.COPYFILE_EXCL);
|
|
4655
|
-
chmodSync(join(stage, file), 384);
|
|
4656
|
-
if (manifest.files?.[file] !== digest(join(stage, file))) throw new Error(`Backup checksum failed: ${file}`);
|
|
4657
|
-
}
|
|
4658
|
-
const db = new DatabaseSync(join(stage, FILES[0]), { readOnly: true });
|
|
4659
|
-
try {
|
|
4660
|
-
if (schemaVersion(db) !== 1 || db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("Backup database failed validation.");
|
|
4661
|
-
for (const table of [
|
|
4662
|
-
"hosts",
|
|
4663
|
-
"board",
|
|
4664
|
-
"settings",
|
|
4665
|
-
"sessions",
|
|
4666
|
-
"push_subscriptions"
|
|
4667
|
-
]) db.prepare(`SELECT * FROM ${table} LIMIT 0`).all();
|
|
4668
|
-
} finally {
|
|
4669
|
-
db.close();
|
|
4670
|
-
}
|
|
4671
|
-
if (!/^[\x21-\x7e]{1,200}$/.test(readFileSync(join(stage, "token"), "utf8").trim())) throw new Error("Invalid backup access token.");
|
|
4672
|
-
writeFileSync(join(directory, ".restore-incomplete"), "Restore interrupted: restore the backup to a fresh home.\n", {
|
|
4673
|
-
mode: 384,
|
|
4674
|
-
flag: "wx"
|
|
4675
|
-
});
|
|
4676
|
-
renameSync(join(stage, "token"), join(directory, "token"));
|
|
4677
|
-
renameSync(join(stage, FILES[0]), join(directory, FILES[0]));
|
|
4678
|
-
rmSync(join(directory, ".restore-incomplete"));
|
|
4679
|
-
} finally {
|
|
4680
|
-
if (ownsStage) rmSync(stage, {
|
|
4681
|
-
recursive: true,
|
|
4682
|
-
force: true
|
|
4683
|
-
});
|
|
4684
|
-
await new Promise((resolve) => lock.close(() => resolve()));
|
|
4685
|
-
releaseRuntime();
|
|
4686
|
-
}
|
|
4687
|
-
}
|
|
4688
|
-
// src/server/data-dir.ts
|
|
4689
|
-
/** Locations before ~/.litepaseo: the platform data directories. */
|
|
4690
|
-
function legacyDirectory(env, home, platform) {
|
|
4691
|
-
return platform === "darwin" ? join(home, "Library/Application Support/LitePaseo") : join(env.XDG_DATA_HOME ?? join(home, ".local/share"), "litepaseo");
|
|
4692
|
-
}
|
|
4693
|
-
/** Whether a LitePaseo process answers on this control socket. */
|
|
4694
|
-
function socketIsLive(path, timeoutMs = 500) {
|
|
4695
|
-
return new Promise((done) => {
|
|
4696
|
-
if (!existsSync(path)) return done(false);
|
|
4697
|
-
const s = connect(path);
|
|
4698
|
-
const finish = (live) => {
|
|
4699
|
-
s.destroy();
|
|
4700
|
-
done(live);
|
|
4701
|
-
};
|
|
4702
|
-
s.setTimeout(timeoutMs, () => finish(false));
|
|
4703
|
-
s.once("connect", () => finish(true));
|
|
4704
|
-
s.once("error", () => finish(false));
|
|
4705
|
-
});
|
|
4706
|
-
}
|
|
4707
|
-
/**
|
|
4708
|
-
* LitePaseo keeps everything in one directory, like Paseo's ~/.paseo: ~/.litepaseo, or
|
|
4709
|
-
* LITEPASEO_HOME (LITEPASEO_DATA_DIR still works). Data from the old platform location moves
|
|
4710
|
-
* over once, but never out from under a running instance: that one keeps its directory until
|
|
4711
|
-
* it is stopped.
|
|
4712
|
-
*/
|
|
4713
|
-
async function resolveDataDirectory(env, home, platform, isLive = socketIsLive) {
|
|
4714
|
-
const configured = env.LITEPASEO_HOME || env.LITEPASEO_DATA_DIR;
|
|
4715
|
-
if (configured) return { directory: resolve(configured) };
|
|
4716
|
-
const target = join(home, ".litepaseo");
|
|
4717
|
-
const legacy = legacyDirectory(env, home, platform);
|
|
4718
|
-
if (!existsSync(legacy) || existsSync(target)) return { directory: target };
|
|
4719
|
-
if (await isLive(join(legacy, "control.sock"))) return {
|
|
4720
|
-
directory: legacy,
|
|
4721
|
-
notice: `LitePaseo is running from ${legacy}. Run "litepaseo stop", then start it again to move its data to ${target}.`
|
|
4722
|
-
};
|
|
4723
|
-
try {
|
|
4724
|
-
renameSync(legacy, target);
|
|
4725
|
-
} catch (error) {
|
|
4726
|
-
if (error.code !== "EXDEV") throw error;
|
|
4727
|
-
cpSync(legacy, target, {
|
|
4728
|
-
recursive: true,
|
|
4729
|
-
preserveTimestamps: true
|
|
4730
|
-
});
|
|
4731
|
-
rmSync(legacy, {
|
|
4732
|
-
recursive: true,
|
|
4733
|
-
force: true
|
|
4734
|
-
});
|
|
4735
|
-
}
|
|
4736
|
-
const socket = join(target, "control.sock");
|
|
4737
|
-
if (existsSync(socket)) unlinkSync(socket);
|
|
4738
|
-
return {
|
|
4739
|
-
directory: target,
|
|
4740
|
-
notice: `Moved LitePaseo data from ${legacy} to ${target}.`
|
|
4741
|
-
};
|
|
4742
|
-
}
|
|
4743
1130
|
// src/server/cli-format.ts
|
|
4744
1131
|
const json = {
|
|
4745
1132
|
name: "json",
|
|
@@ -5326,7 +1713,11 @@ async function version(args) {
|
|
|
5326
1713
|
async function run() {
|
|
5327
1714
|
if (name === "--version" || name === "-v" || name === "-V") return console.log(VERSION);
|
|
5328
1715
|
if (name === "--help" || name === "-h") return console.log(mainHelp(VERSION, displayDirectory(), out));
|
|
5329
|
-
if (name === "worker")
|
|
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
|
+
}
|
|
5330
1721
|
const command = findCommand(name);
|
|
5331
1722
|
if (!command) {
|
|
5332
1723
|
const guess = suggest(name, COMMANDS.map((c) => c.name));
|
|
@@ -5416,4 +1807,4 @@ run().catch(async (error) => {
|
|
|
5416
1807
|
} catch {}
|
|
5417
1808
|
process.exitCode = 1;
|
|
5418
1809
|
});
|
|
5419
|
-
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 };
|