@x-tech-laboratories/x-app 0.128.0 → 0.130.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +28 -4
  2. package/dist/agent/claude_stream.d.ts +1 -22
  3. package/dist/agent/claude_stream.js +2 -85
  4. package/dist/agent/client.d.ts +1 -35
  5. package/dist/agent/client.js +2 -169
  6. package/dist/agent/commands.d.ts +1 -22
  7. package/dist/agent/commands.js +2 -80
  8. package/dist/agent/desktop_notify.d.ts +1 -54
  9. package/dist/agent/desktop_notify.js +2 -229
  10. package/dist/agent/firefox_bookmarks.d.ts +1 -29
  11. package/dist/agent/firefox_bookmarks.js +2 -147
  12. package/dist/agent/git.d.ts +1 -37
  13. package/dist/agent/git.js +2 -121
  14. package/dist/agent/github.d.ts +1 -81
  15. package/dist/agent/github.js +2 -185
  16. package/dist/agent/inhibit.d.ts +1 -32
  17. package/dist/agent/inhibit.js +2 -141
  18. package/dist/agent/keys.d.ts +1 -26
  19. package/dist/agent/keys.js +2 -161
  20. package/dist/agent/local_socket.d.ts +1 -18
  21. package/dist/agent/local_socket.js +2 -106
  22. package/dist/agent/long_runs.d.ts +1 -45
  23. package/dist/agent/long_runs.js +2 -419
  24. package/dist/agent/programs.d.ts +1 -60
  25. package/dist/agent/programs.js +2 -237
  26. package/dist/agent/protocol.d.ts +1 -172
  27. package/dist/agent/protocol.js +2 -249
  28. package/dist/agent/scheduled_notices.d.ts +1 -21
  29. package/dist/agent/scheduled_notices.js +2 -38
  30. package/dist/agent/session.d.ts +1 -61
  31. package/dist/agent/session.js +2 -335
  32. package/dist/agent/ssh_config.d.ts +1 -12
  33. package/dist/agent/ssh_config.js +2 -72
  34. package/dist/agent/stalls.d.ts +1 -44
  35. package/dist/agent/stalls.js +2 -176
  36. package/dist/agent/tasks.d.ts +1 -17
  37. package/dist/agent/tasks.js +2 -15
  38. package/dist/agent/wake.d.ts +1 -14
  39. package/dist/agent/wake.js +2 -88
  40. package/dist/agent/worktree_files.d.ts +1 -20
  41. package/dist/agent/worktree_files.js +2 -69
  42. package/dist/app/define.d.ts +10 -1
  43. package/dist/app/define.js +1 -0
  44. package/dist/app/desktop.js +29 -9
  45. package/dist/app/outside_fetch.d.ts +40 -0
  46. package/dist/app/outside_fetch.js +94 -0
  47. package/dist/app/outside_route.d.ts +3 -0
  48. package/dist/app/outside_route.js +51 -0
  49. package/dist/app/preload.js +2 -0
  50. package/dist/app/protocol.d.ts +1 -0
  51. package/dist/app/server.js +3 -0
  52. package/dist/app/web/app_page.js +33 -4
  53. package/dist/app/web/hosts.d.ts +2 -2
  54. package/dist/app/web/hosts.js +12 -1
  55. package/dist/app/web/settings_page.d.ts +1 -0
  56. package/dist/config/capacitor.js +1 -1
  57. package/dist/daemon_link.d.ts +2 -1
  58. package/dist/daemon_link.js +4 -2
  59. package/dist/durations.d.ts +1 -15
  60. package/dist/durations.js +2 -52
  61. package/dist/site/build.d.ts +1 -1
  62. package/dist/site/build.js +28 -8
  63. package/dist/site/content.js +6 -8
  64. package/dist/site/links.d.ts +11 -0
  65. package/dist/site/links.js +55 -0
  66. package/dist/site/markdown.d.ts +5 -2
  67. package/dist/site/markdown.js +14 -11
  68. package/dist/site/model.d.ts +2 -1
  69. package/dist/site/model.js +12 -3
  70. package/dist/web/react/phone.js +2 -1
  71. package/package.json +5 -3
@@ -1,176 +1,2 @@
1
- // What a stalled long run is doing, read from /proc: the programs it still runs, the file locks they wait for, and the
2
- // processes holding those locks; and a watch that writes this into the run's output once it has been quiet a while,
3
- // again each half hour it stays quiet. Everything here is readable by any user, so it works for root's programs too.
4
- // ── Imports ──────────────────────────────────────────────────────────────────
5
- import { readdirSync, readFileSync, statSync } from "node:fs";
6
- import { join } from "node:path";
7
- import { format_duration } from "../durations.js";
8
- // ── Settings ─────────────────────────────────────────────────────────────────
9
- export const first_note_in_seconds = 300;
10
- export const later_notes_in_seconds = 1800;
11
- const look_interval_in_milliseconds = 30_000;
12
- // Clock ticks per second in /proc's start times, which Linux fixes at 100 for user space.
13
- const ticks_per_second = 100;
14
- // How many holders a note names before counting the rest.
15
- const holders_named = 6;
16
- // ── Reading /proc ────────────────────────────────────────────────────────────
17
- export function read_processes(proc = "/proc") {
18
- const uptime = Number(read_text(join(proc, "uptime")).split(" ")[0]) || 0;
19
- const processes = new Map();
20
- for (const entry of list(proc)) {
21
- if (!/^\d+$/.test(entry))
22
- continue;
23
- const stat = read_text(join(proc, entry, "stat"));
24
- const open = stat.indexOf("(");
25
- const close = stat.lastIndexOf(")");
26
- if (open === -1 || close === -1)
27
- continue;
28
- // The fields after the name start at the state, the third field; the start time is the 22nd.
29
- const fields = stat.slice(close + 2).split(" ");
30
- const started = Number(fields[19]) / ticks_per_second;
31
- processes.set(Number(entry), { pid: Number(entry), ppid: Number(fields[1]), name: stat.slice(open + 1, close), age_in_seconds: Math.max(0, uptime - started) });
32
- }
33
- return processes;
34
- }
35
- export function read_locks(proc = "/proc") {
36
- const entries = [];
37
- for (const line of read_text(join(proc, "locks")).split("\n")) {
38
- const words = line.trim().split(/\s+/);
39
- const waiting = words[1] === "->";
40
- // A line is its number, the lock's kind and class, its mode, then the process and the file; a waiter's has "->" first.
41
- const [, , , mode, pid, file] = waiting ? words.slice(1) : words;
42
- if (pid === undefined || file === undefined || (mode !== "READ" && mode !== "WRITE"))
43
- continue;
44
- entries.push({ pid: Number(pid), waiting, mode, file });
45
- }
46
- return entries;
47
- }
48
- // How /proc/locks names a file: its device's major and minor numbers in hex, then its inode.
49
- export function lock_file_id(path) {
50
- try {
51
- const { dev, ino } = statSync(path, { bigint: true });
52
- const major = ((dev >> 8n) & 0xfffn) | ((dev >> 32n) & ~0xfffn);
53
- const minor = (dev & 0xffn) | ((dev >> 12n) & ~0xffn);
54
- return `${major.toString(16).padStart(2, "0")}:${minor.toString(16).padStart(2, "0")}:${ino}`;
55
- }
56
- catch {
57
- return null;
58
- }
59
- }
60
- // The /proc/locks ids of the files that exist, by path.
61
- export function lock_file_ids(paths) {
62
- const files = {};
63
- for (const path of paths) {
64
- const id = lock_file_id(path);
65
- if (id !== null)
66
- files[path] = id;
67
- }
68
- return files;
69
- }
70
- // ── Questions ────────────────────────────────────────────────────────────────
71
- // Every process started under the root, at any depth.
72
- export function descendants(processes, root) {
73
- const children = new Map();
74
- for (const info of processes.values())
75
- children.set(info.ppid, [...(children.get(info.ppid) ?? []), info]);
76
- const found = [];
77
- const next = [...(children.get(root) ?? [])];
78
- while (next.length > 0) {
79
- const info = next.shift();
80
- found.push(info);
81
- next.push(...(children.get(info.pid) ?? []));
82
- }
83
- return found;
84
- }
85
- // The processes holding a lock on the file, other than those given.
86
- export function lock_holders(path, except = new Set(), proc = "/proc", file_id = lock_file_id(path)) {
87
- if (file_id === null)
88
- return [];
89
- const processes = read_processes(proc);
90
- const pids = new Set(read_locks(proc).filter((entry) => !entry.waiting && entry.file === file_id && !except.has(entry.pid)).map((entry) => entry.pid));
91
- return [...pids].map((pid) => processes.get(pid)).filter((info) => info !== undefined);
92
- }
93
- // Names a process the way a note shows it.
94
- export function show_process(info) {
95
- return `${info.name} (pid ${info.pid}, running for ${format_duration(info.age_in_seconds, { largest_unit: "days" })})`;
96
- }
97
- export function show_holders(holders) {
98
- const named = holders.slice(0, holders_named).map(show_process).join(", ");
99
- return holders.length > holders_named ? `${named} and ${holders.length - holders_named} more` : named;
100
- }
101
- // ── Notes ────────────────────────────────────────────────────────────────────
102
- // The lines a run prints once it has been quiet for the given time: what it still runs, and what any of it waits for.
103
- export function describe_stall(root, quiet_in_seconds, options = {}) {
104
- const proc = options.proc ?? "/proc";
105
- const known = options.known_locks ?? {};
106
- const files = options.lock_files ?? lock_file_ids(Object.keys(known));
107
- const processes = read_processes(proc);
108
- const under = descendants(processes, root);
109
- const own = new Set(under.map((info) => info.pid));
110
- const parents = new Set(under.map((info) => info.ppid));
111
- const chains = under.filter((info) => !parents.has(info.pid)).slice(0, 3).map((leaf) => chain_to(processes, root, leaf));
112
- const lines = [`No output for ${format_duration(quiet_in_seconds)}; still running ${chains.length > 0 ? chains.join("; ") : "nothing under the run"}`];
113
- const locks = read_locks(proc);
114
- for (const wait of locks.filter((entry) => entry.waiting && own.has(entry.pid))) {
115
- const waiter = processes.get(wait.pid);
116
- const path = Object.entries(files).find(([, id]) => id === wait.file)?.[0] ?? null;
117
- const lock = path === null ? undefined : known[path];
118
- const holders = [...new Set(locks.filter((entry) => !entry.waiting && entry.file === wait.file && entry.pid !== wait.pid).map((entry) => entry.pid))]
119
- .map((pid) => processes.get(pid))
120
- .filter((info) => info !== undefined);
121
- const what = lock === undefined ? `a lock on file ${wait.file}` : `${lock.name} (${path})`;
122
- lines.push(`${waiter.name} (pid ${waiter.pid}) waits for ${what}, held by ${holders.length > 0 ? show_holders(holders) : "nothing it can see"}`);
123
- if (lock?.hint !== undefined)
124
- lines.push(lock.hint);
125
- }
126
- return options.mark === undefined ? lines : lines.map((line) => `${options.mark} ${line}`);
127
- }
128
- // The programs from the root down to the leaf, as "a › b › c (pid N)".
129
- function chain_to(processes, root, leaf) {
130
- const names = [];
131
- for (let info = leaf; info !== undefined && info.pid !== root; info = processes.get(info.ppid))
132
- names.unshift(info.name);
133
- return `${names.join(" › ")} (pid ${leaf.pid})`;
134
- }
135
- // Watches the run started by the root process, writing a note once it has printed nothing for a while.
136
- export function watch_for_stalls(root, write, options = {}) {
137
- const now = options.now ?? Date.now;
138
- const first_note = (options.first_note_in_seconds ?? first_note_in_seconds) * 1000;
139
- const later_notes = (options.later_notes_in_seconds ?? later_notes_in_seconds) * 1000;
140
- let last_heard = now();
141
- let next_note = last_heard + first_note;
142
- const look = () => {
143
- if (now() < next_note)
144
- return;
145
- const lines = describe_stall(root, (now() - last_heard) / 1000, options);
146
- write(`${lines.join("\n")}\n`);
147
- next_note = now() + later_notes;
148
- };
149
- const timer = setInterval(look, look_interval_in_milliseconds);
150
- timer.unref();
151
- return {
152
- heard: () => {
153
- last_heard = now();
154
- next_note = last_heard + first_note;
155
- },
156
- look,
157
- stop: () => clearInterval(timer),
158
- };
159
- }
160
- // ── Helpers ──────────────────────────────────────────────────────────────────
161
- function read_text(path) {
162
- try {
163
- return readFileSync(path, "utf8");
164
- }
165
- catch {
166
- return "";
167
- }
168
- }
169
- function list(path) {
170
- try {
171
- return readdirSync(path);
172
- }
173
- catch {
174
- return [];
175
- }
176
- }
1
+ // Moved to @x-tech-laboratories/x-app-agent, which a host agent installs without the rest of X-App.
2
+ export * from "@x-tech-laboratories/x-app-agent/stalls";
@@ -1,17 +1 @@
1
- import { type CommandStream } from "./commands.ts";
2
- import type { RunResult } from "./protocol.ts";
3
- export interface LongRunLaunch {
4
- program: string;
5
- args: string[];
6
- }
7
- export interface TaskRunner<Task> {
8
- run(task: Task, options: {
9
- timeout_in_seconds: number;
10
- stdin?: string | null;
11
- }): Promise<RunResult>;
12
- stream?(task: Task, options: {
13
- stdin?: string | null;
14
- }): CommandStream;
15
- launch(task: Task, folder: string, has_stdin: boolean): LongRunLaunch;
16
- }
17
- export declare function shell_runner(process_name: string): TaskRunner<string>;
1
+ export * from "@x-tech-laboratories/x-app-agent/tasks";
@@ -1,15 +1,2 @@
1
- // How an agent carries out the app's tasks: to their end, as a stream, or as a long run's own process. Shell tasks, a
2
- // command line run by sh, come built in; an app with typed operations gives its own.
3
- // ── Imports ──────────────────────────────────────────────────────────────────
4
- import { run_command, stream_command } from "./commands.js";
5
- // ── Shell ────────────────────────────────────────────────────────────────────
6
- // The outer shell runs the command with its output in the run's folder, then writes the exit code in one rename.
7
- const wrapper = 'sh -c "$2" > "$1/out" 2>&1; echo $? > "$1/exit.part"; mv -f "$1/exit.part" "$1/exit"';
8
- // Runs each task as a command line under sh; `process_name`, such as "x-backups-run", is what ps shows for a long run.
9
- export function shell_runner(process_name) {
10
- return {
11
- run: (command, options) => run_command(command, options),
12
- stream: (command, options) => stream_command(command, options),
13
- launch: (command, folder) => ({ program: "sh", args: ["-c", wrapper, process_name, folder, command] }),
14
- };
15
- }
1
+ // Moved to @x-tech-laboratories/x-app-agent, which a host agent installs without the rest of X-App.
2
+ export * from "@x-tech-laboratories/x-app-agent/tasks";
@@ -1,14 +1 @@
1
- export interface WakeTarget {
2
- mac: string;
3
- broadcast: string;
4
- port: number;
5
- password?: string | null;
6
- }
7
- export declare const default_broadcast = "255.255.255.255";
8
- export declare const default_port = 9;
9
- export declare function parse_mac(mac: unknown): Buffer;
10
- export declare function parse_password(password: unknown): Buffer;
11
- export declare function magic_packet(mac: unknown, password?: string | null): Buffer;
12
- export declare function send_wake_packet(packet: Buffer, address?: string, port?: number, times?: number): Promise<void>;
13
- export declare function send_magic_packet(target: WakeTarget): Promise<void>;
14
- export declare function remote_send_command(packet: Buffer, address?: string, port?: number, missing_message?: string): string;
1
+ export * from "@x-tech-laboratories/x-app-agent/wake";
@@ -1,88 +1,2 @@
1
- // Wake-on-LAN: the magic packet that wakes a sleeping machine, with a SecureOn password when the card asks for one, sent
2
- // by a server or by an agent on that machine's network, or by a shell command run on a host that reaches it.
3
- // ── Imports ──────────────────────────────────────────────────────────────────
4
- import { createSocket } from "node:dgram";
5
- // ── Settings ─────────────────────────────────────────────────────────────────
6
- // How many copies of the packet go out, as a single one may be dropped.
7
- const copies = 3;
8
- export const default_broadcast = "255.255.255.255";
9
- export const default_port = 9;
10
- // Sends the hex bytes in argv[1] to argv[2]:argv[3] as one broadcast UDP datagram.
11
- const python_sender = "import socket,sys;" +
12
- "s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM);" +
13
- "s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1);" +
14
- "s.sendto(bytes.fromhex(sys.argv[1]),(sys.argv[2],int(sys.argv[3])))";
15
- // ── Packet ───────────────────────────────────────────────────────────────────
16
- // A MAC address's six bytes, written with colons, dashes, dots or no separators at all.
17
- export function parse_mac(mac) {
18
- const digits = String(mac ?? "").replace(/[:\-.\s]/g, "");
19
- if (!/^[0-9A-Fa-f]{12}$/.test(digits))
20
- throw new Error(`'${String(mac ?? "")}' is not a MAC address`);
21
- return Buffer.from(digits, "hex");
22
- }
23
- // A SecureOn password's bytes: six written like a MAC address, or four written like an IPv4 address.
24
- export function parse_password(password) {
25
- const text = String(password).trim();
26
- if (/^\d{1,3}(\.\d{1,3}){3}$/.test(text)) {
27
- const parts = text.split(".").map(Number);
28
- if (parts.every((part) => part <= 255))
29
- return Buffer.from(parts);
30
- }
31
- try {
32
- return parse_mac(text);
33
- }
34
- catch {
35
- throw new Error(`'${String(password)}' is not a SecureOn password (six hex bytes or a dotted quad)`);
36
- }
37
- }
38
- // Six 0xff bytes, then the MAC address sixteen times, then the SecureOn password when there is one.
39
- export function magic_packet(mac, password = null) {
40
- const address = parse_mac(mac);
41
- const parts = [Buffer.alloc(6, 0xff), ...Array.from({ length: 16 }, () => address)];
42
- if (password)
43
- parts.push(parse_password(password));
44
- return Buffer.concat(parts);
45
- }
46
- // ── Sending ──────────────────────────────────────────────────────────────────
47
- // Sends a ready packet as UDP datagrams from this machine, once unless `times` says more, rejecting when the network refuses.
48
- export async function send_wake_packet(packet, address = default_broadcast, port = default_port, times = 1) {
49
- const socket = createSocket("udp4");
50
- try {
51
- await new Promise((resolve, reject) => {
52
- socket.once("error", reject);
53
- socket.bind(() => resolve());
54
- });
55
- socket.setBroadcast(true);
56
- for (let sent = 0; sent < times; sent++) {
57
- await new Promise((resolve, reject) => socket.send(packet, Math.trunc(port), address, (error) => (error ? reject(error) : resolve())));
58
- }
59
- }
60
- finally {
61
- socket.close();
62
- }
63
- }
64
- // Sends a few copies of the target's packet.
65
- export async function send_magic_packet(target) {
66
- await send_wake_packet(magic_packet(target.mac, target.password ?? null), target.broadcast, target.port, copies);
67
- }
68
- // A shell command that sends the packet from whichever host runs it, with python3 or else socat, failing with 127 and
69
- // `missing_message` when it has neither.
70
- export function remote_send_command(packet, address = default_broadcast, port = default_port, missing_message = "sending a wake packet needs python3 or socat on this host") {
71
- const target = shell_word(address);
72
- const port_number = Math.trunc(port);
73
- const octal = [...packet].map((byte) => `\\${byte.toString(8).padStart(3, "0")}`).join("");
74
- return ("if command -v python3 >/dev/null 2>&1; then " +
75
- `python3 -c ${shell_word(python_sender)} ${packet.toString("hex")} ${target} ${port_number}; ` +
76
- "elif command -v socat >/dev/null 2>&1; then " +
77
- `printf '${octal}' | socat -u - UDP-DATAGRAM:${target}:${port_number},broadcast; ` +
78
- `else echo ${shell_word(missing_message)} >&2; ` +
79
- "exit 127; fi");
80
- }
81
- // A word the shell reads back unchanged, quoted only when it needs to be, as Python's shlex.quote does.
82
- function shell_word(text) {
83
- if (text === "")
84
- return "''";
85
- if (/^[\w@%+=:,./-]+$/.test(text))
86
- return text;
87
- return `'${text.replaceAll("'", "'\"'\"'")}'`;
88
- }
1
+ // Moved to @x-tech-laboratories/x-app-agent, which a host agent installs without the rest of X-App.
2
+ export * from "@x-tech-laboratories/x-app-agent/wake";
@@ -1,20 +1 @@
1
- export interface WorktreeFiles {
2
- paths: string[];
3
- truncated: boolean;
4
- }
5
- export interface WorktreeFile {
6
- path: string;
7
- size: number;
8
- symlink: boolean;
9
- text: string | null;
10
- reason: "" | "binary" | "too_large";
11
- }
12
- export interface WorktreeFileLimits {
13
- most_files?: number;
14
- most_bytes?: number;
15
- skipped_folders?: readonly string[];
16
- }
17
- export declare const default_worktree_file_limits: Required<WorktreeFileLimits>;
18
- export declare function list_worktree_files(worktree: string, limits?: WorktreeFileLimits): Promise<WorktreeFiles>;
19
- export declare function confined_path(worktree: string, path: string, limits?: WorktreeFileLimits): string;
20
- export declare function read_worktree_file(worktree: string, path: string, limits?: WorktreeFileLimits): WorktreeFile;
1
+ export * from "@x-tech-laboratories/x-app-agent/worktree_files";
@@ -1,69 +1,2 @@
1
- // A git worktree's files for a page to browse read-only: every file git tracks or would track there, and one file's
2
- // text, never inside a skipped folder such as .git or node_modules, and never by a path that leads out of the worktree
3
- // through "..", an absolute path or a symlink; a binary or too large file comes back without its text.
4
- // ── Imports ──────────────────────────────────────────────────────────────────
5
- import { closeSync, lstatSync, openSync, readSync, realpathSync, statSync } from "node:fs";
6
- import { isAbsolute, join, relative, sep } from "node:path";
7
- import { git } from "./git.js";
8
- export const default_worktree_file_limits = { most_files: 20_000, most_bytes: 1_000_000, skipped_folders: [".git", "node_modules"] };
9
- // How much of a file is looked at to tell text from binary.
10
- const sniff_bytes = 8_000;
11
- function limits_of(limits) {
12
- return { ...default_worktree_file_limits, ...limits };
13
- }
14
- function is_skipped(path, skipped_folders) {
15
- return path.split("/").some((part) => skipped_folders.includes(part));
16
- }
17
- // ── Listing ──────────────────────────────────────────────────────────────────
18
- // The worktree's files, tracked and new alike, ignored ones left out, by path.
19
- export async function list_worktree_files(worktree, limits = {}) {
20
- const { most_files, skipped_folders } = limits_of(limits);
21
- const text = await git(["ls-files", "--cached", "--others", "--exclude-standard", "-z"], worktree);
22
- const paths = [...new Set(text.split("\0").filter((path) => path && !is_skipped(path, skipped_folders)))].sort((first, second) => first.localeCompare(second));
23
- return { paths: paths.slice(0, most_files), truncated: paths.length > most_files };
24
- }
25
- // ── Reading ──────────────────────────────────────────────────────────────────
26
- // The file's real place on disk, refused when the path leads out of the worktree or into a skipped folder.
27
- export function confined_path(worktree, path, limits = {}) {
28
- const { skipped_folders } = limits_of(limits);
29
- if (!path || isAbsolute(path) || path.split(/[\\/]/).includes(".."))
30
- throw new Error(`${path} is not a path inside the worktree`);
31
- if (is_skipped(path.replaceAll("\\", "/"), skipped_folders))
32
- throw new Error(`${path} is in a folder that is not shown`);
33
- let real;
34
- try {
35
- real = realpathSync(join(worktree, path));
36
- }
37
- catch {
38
- throw new Error(`${path} does not exist in the worktree`);
39
- }
40
- const inside = relative(realpathSync(worktree), real);
41
- if (inside === "" || inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside))
42
- throw new Error(`${path} leads out of the worktree`);
43
- if (is_skipped(inside.split(sep).join("/"), skipped_folders))
44
- throw new Error(`${path} leads into a folder that is not shown`);
45
- return real;
46
- }
47
- // One file's text, or why it is not shown: binary or too large; refused when it is not a file.
48
- export function read_worktree_file(worktree, path, limits = {}) {
49
- const { most_bytes } = limits_of(limits);
50
- const real = confined_path(worktree, path, limits);
51
- const link = lstatSync(join(worktree, path));
52
- const stats = statSync(real);
53
- if (!stats.isFile())
54
- throw new Error(`${path} is not a file`);
55
- const base = { path, size: stats.size, symlink: link.isSymbolicLink() };
56
- if (stats.size > most_bytes)
57
- return { ...base, text: null, reason: "too_large" };
58
- const handle = openSync(real, "r");
59
- try {
60
- const buffer = Buffer.alloc(stats.size);
61
- readSync(handle, buffer, 0, stats.size, 0);
62
- if (buffer.subarray(0, sniff_bytes).includes(0))
63
- return { ...base, text: null, reason: "binary" };
64
- return { ...base, text: buffer.toString("utf8"), reason: "" };
65
- }
66
- finally {
67
- closeSync(handle);
68
- }
69
- }
1
+ // Moved to @x-tech-laboratories/x-app-agent, which a host agent installs without the rest of X-App.
2
+ export * from "@x-tech-laboratories/x-app-agent/worktree_files";
@@ -5,7 +5,7 @@ import { type Caller } from "../caller.ts";
5
5
  import { type CertificateMethods } from "../certificate_protocol.ts";
6
6
  import { type ConnectionMethods } from "../connection_protocol.ts";
7
7
  import { type Bridge } from "../electron/bridge.ts";
8
- import type { FetchMethod } from "../electron/fetch.ts";
8
+ import type { FetchMethod, StreamCancelMethod, StreamChunk, StreamStartMethod } from "../electron/fetch.ts";
9
9
  import { type EventsBridge } from "../electron/events.ts";
10
10
  import type { History } from "../history.ts";
11
11
  import type { ScopeSpec } from "../server/declared_tokens.ts";
@@ -16,6 +16,7 @@ import { type SyncedTable } from "../sync_engine.ts";
16
16
  import { type PeerListeningMethods, type SyncDeviceMethods, type SyncStatus } from "../sync_protocol.ts";
17
17
  import { type RemoteAccessMethods } from "../remote_access_protocol.ts";
18
18
  import type { SecurityHeadersOptions } from "../server/security_headers.ts";
19
+ import type { OutsideSites } from "./outside_fetch.ts";
19
20
  import { type DataChange, type DesktopMethods, type DesktopSettingSpec, type HostAbilityMethods } from "./protocol.ts";
20
21
  export type StoreMethod = (database: SqlDatabase, ...args: never[]) => unknown;
21
22
  export type KeptHistory = Pick<History<unknown>, "synced_table" | "install" | "forget_touched" | "record" | "prune"> & Partial<Pick<History<unknown>, "drop_triggers">>;
@@ -106,6 +107,7 @@ export interface AppOptions<Features extends readonly Feature[]> {
106
107
  limit_key?: string;
107
108
  };
108
109
  security_headers?: boolean | SecurityHeadersOptions;
110
+ outside?: OutsideSites;
109
111
  }
110
112
  export declare const base_setting_defaults: {
111
113
  history_days: number;
@@ -123,7 +125,12 @@ export type AppEvents = {
123
125
  event: string;
124
126
  data: unknown;
125
127
  };
128
+ outside_chunk: StreamChunk;
126
129
  };
130
+ export interface OutsideMethods {
131
+ outside_stream: StreamStartMethod;
132
+ outside_stream_cancel: StreamCancelMethod;
133
+ }
127
134
  export interface AppBridges<Methods extends Record<keyof Methods, (...args: never[]) => unknown>> {
128
135
  calls: Bridge<Methods>;
129
136
  device: Bridge<SyncDeviceMethods>;
@@ -139,6 +146,7 @@ export interface AppBridges<Methods extends Record<keyof Methods, (...args: neve
139
146
  fetch: Bridge<{
140
147
  http_fetch: FetchMethod;
141
148
  }>;
149
+ outside: Bridge<OutsideMethods>;
142
150
  host_tables: Readonly<Record<string, Bridge<Record<string, (...args: never[]) => unknown>>>>;
143
151
  }
144
152
  export declare function define_app<const Features extends readonly Feature[]>(options: AppOptions<Features>): {
@@ -191,6 +199,7 @@ export declare function define_app<const Features extends readonly Feature[]>(op
191
199
  limit_key?: string;
192
200
  };
193
201
  security_headers?: boolean | SecurityHeadersOptions;
202
+ outside?: OutsideSites;
194
203
  features: readonly Feature<Record<string, StoreMethod>>[];
195
204
  settings_store: SettingsStore;
196
205
  setting_defaults: Readonly<import("../settings.ts").Settings>;
@@ -267,6 +267,7 @@ export function define_app(options) {
267
267
  events: define_events(`${prefix}_events`),
268
268
  host: define_bridge(`${prefix}_host`, host_ability_method_names),
269
269
  fetch: define_bridge(`${prefix}_fetch`, ["http_fetch"]),
270
+ outside: define_bridge(`${prefix}_outside`, ["outside_stream", "outside_stream_cancel"]),
270
271
  // Letting other devices reach this computer's daemon, answered over its socket alone.
271
272
  remote_access: define_bridge(`${prefix}_remote`, remote_access_method_names),
272
273
  host_tables: Object.fromEntries(Object.entries(options.host_tables ?? {}).map(([name, table]) => [name, define_bridge(`${prefix}_${name}`, Object.keys(table.api))])),
@@ -24,7 +24,8 @@ import { peer_listening_method_names, sync_device_method_names } from "../sync_p
24
24
  import { route_of_link } from "./links.js";
25
25
  import { remote_access_method_names } from "../remote_access_protocol.js";
26
26
  import { file_response, register_file_scheme } from "../electron/file_protocol.js";
27
- import { create_main_fetch } from "../electron/fetch.js";
27
+ import { create_main_fetch, create_main_stream_fetch } from "../electron/fetch.js";
28
+ import { with_site_headers } from "./outside_fetch.js";
28
29
  import { no_server_text, server_headers, server_url } from "./server_fetch.js";
29
30
  import { folder_file_store } from "../node_file_store.js";
30
31
  import { read_plugin_file } from "../plugin_folder.js";
@@ -64,6 +65,8 @@ export function run_desktop(app, electron, options) {
64
65
  const own_command = (args) => launch_command({ launcher: env[`${prefix}_LAUNCHER`] ?? null, is_packaged: electron.app.isPackaged, app_path: electron.app.getAppPath(), args });
65
66
  // Opening the app replaces a daemon another build left running, such as one from before an upgrade. Only opening does:
66
67
  // two windows of different builds that both replaced on reconnecting would stop each other's daemon in turn.
68
+ // Settles once the daemon opening the app started answers; set by start_app, which opens the window without waiting for it.
69
+ let daemon_ready = Promise.resolve();
67
70
  function ensure_daemon(replace_other_build = false) {
68
71
  if (portal)
69
72
  return Promise.resolve("portal");
@@ -90,7 +93,7 @@ export function run_desktop(app, electron, options) {
90
93
  watchFile(certificates_file, { interval: 2000 }, trust_certificates);
91
94
  // This computer's daemon, and servers each signed in once with a token of this device's own.
92
95
  const connections = create_connections({ storage: connection_file_storage(join(profile, "connections.json")), offers_local: !portal, device_name: `${app.name} on ${hostname()}` });
93
- const link = create_daemon_link({ connections, socket_path });
96
+ const link = create_daemon_link({ connections, socket_path, local_ready: () => daemon_ready });
94
97
  const windows = () => BrowserWindow.getAllWindows();
95
98
  // A daemon elsewhere tells of its notices as events; this computer shows them by its own switches, as its own
96
99
  // daemon shows its own.
@@ -111,7 +114,11 @@ export function run_desktop(app, electron, options) {
111
114
  connections,
112
115
  link,
113
116
  ...(portal ? {} : {
114
- call_local: (path, args, headers) => call_socket(socket_path, path, args, headers),
117
+ // The window opens while the daemon starts, so a call to it waits until it answers.
118
+ call_local: async (path, args, headers) => {
119
+ await daemon_ready;
120
+ return call_socket(socket_path, path, args, headers);
121
+ },
115
122
  restart_local: () => ensure_daemon(),
116
123
  }),
117
124
  local_tables: portal ? [] : [...default_local_tables, "peer_listening", "remote", ...own_tables],
@@ -310,6 +317,12 @@ export function run_desktop(app, electron, options) {
310
317
  bridges.remote_access.handle(ipcMain, forwarded(remote_access_method_names, "remote"), handle_options);
311
318
  bridges.host.handle(ipcMain, forwarded(host_ability_method_names, "host"), handle_options);
312
319
  bridges.fetch.handle(ipcMain, { http_fetch }, handle_options);
320
+ // The app's outside sites, sent from here whichever host the window works on, each answer streamed to the windows.
321
+ const outside = app.outside;
322
+ if (outside) {
323
+ const stream = create_main_stream_fetch({ hosts: outside.hosts }, (chunk) => app.bridges.events.emit(windows(), "outside_chunk", chunk));
324
+ bridges.outside.handle(ipcMain, { outside_stream: (request) => stream.start({ ...request, headers: with_site_headers(request.headers, outside) }), outside_stream_cancel: stream.cancel }, handle_options);
325
+ }
313
326
  for (const [name, bridge] of Object.entries(bridges.host_tables))
314
327
  bridge.handle(ipcMain, forwarded(Object.keys(app.host_tables[name].api), name), handle_options);
315
328
  const desktop = {
@@ -345,21 +358,28 @@ export function run_desktop(app, electron, options) {
345
358
  // ── Start ────────────────────────────────────────────────────────────
346
359
  function start_app() {
347
360
  void electron.app.whenReady().then(async () => {
361
+ // The daemon starts while the window opens, which matters most on a slow computer such as a phone; the page's
362
+ // calls wait for it.
363
+ daemon_ready = ensure_daemon(true);
364
+ daemon_ready.catch(() => undefined);
365
+ if (synced_files && electron.protocol)
366
+ electron.protocol.handle(file_scheme_of(app.id), file_answer);
367
+ register_bridges();
368
+ // `--hidden`, as a login entry may pass it, starts in the tray, unless there is no tray to open the window from.
369
+ if (!argv.includes("--hidden"))
370
+ show_window(route_in(argv));
348
371
  try {
349
- await ensure_daemon(true);
372
+ await daemon_ready;
350
373
  }
351
374
  catch (error) {
352
375
  dialog.showErrorBox(`${app.name} could not start`, `${error instanceof Error ? error.message : String(error)}\n\nSee ${log_file}.`);
353
376
  electron.app.exit(1);
354
377
  return;
355
378
  }
356
- if (synced_files && electron.protocol)
357
- electron.protocol.handle(file_scheme_of(app.id), file_answer);
358
- register_bridges();
359
379
  router.start();
360
380
  await apply_window_settings().catch(() => undefined);
361
- // `--hidden`, as a login entry may pass it, starts in the tray, unless there is no tray to open the window from.
362
- if (!(argv.includes("--hidden") && tray?.is_shown()))
381
+ // The tray is known only once the daemon gives the settings, so a hidden start without one shows the window now.
382
+ if (argv.includes("--hidden") && !tray?.is_shown())
363
383
  show_window(route_in(argv));
364
384
  });
365
385
  electron.app.on("will-quit", () => {
@@ -0,0 +1,40 @@
1
+ import { type HeaderList } from "../electron/fetch.ts";
2
+ export interface OutsideSites {
3
+ hosts: readonly string[];
4
+ headers?: Readonly<Record<string, string>>;
5
+ }
6
+ export declare function with_site_headers(headers: HeaderList, sites: OutsideSites): HeaderList;
7
+ export interface OutsideRequest {
8
+ url: string;
9
+ method: string;
10
+ headers: HeaderList;
11
+ body?: string;
12
+ }
13
+ export declare const outside_route = "/outside";
14
+ export declare const outside_path = "api/outside";
15
+ export declare const status_header = "x-outside-status";
16
+ export declare const status_text_header = "x-outside-status-text";
17
+ export declare const headers_header = "x-outside-headers";
18
+ export declare const NULL_BODY_STATUSES: Set<number>;
19
+ export declare const DROPPED_HEADERS: Set<string>;
20
+ export declare function is_outside_request(value: unknown): value is OutsideRequest;
21
+ export declare function bytes_of_base64(text: string): Uint8Array<ArrayBuffer>;
22
+ export declare function base64_of_bytes(bytes: Uint8Array): string;
23
+ type Fetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
24
+ export declare function web_outside_fetch(post?: typeof fetch): Fetch;
25
+ export interface NativeHttp {
26
+ request(options: {
27
+ url: string;
28
+ method: string;
29
+ headers: Record<string, string>;
30
+ data?: string;
31
+ dataType?: "file";
32
+ responseType: "arraybuffer";
33
+ }): Promise<{
34
+ status: number;
35
+ headers: Record<string, string>;
36
+ data: unknown;
37
+ }>;
38
+ }
39
+ export declare function phone_outside_fetch(http: NativeHttp, sites: OutsideSites): Fetch;
40
+ export {};