@x-tech-laboratories/x-app 0.129.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 (47) hide show
  1. package/README.md +11 -2
  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/desktop.js +21 -8
  43. package/dist/daemon_link.d.ts +2 -1
  44. package/dist/daemon_link.js +4 -2
  45. package/dist/durations.d.ts +1 -15
  46. package/dist/durations.js +2 -52
  47. 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";
@@ -65,6 +65,8 @@ export function run_desktop(app, electron, options) {
65
65
  const own_command = (args) => launch_command({ launcher: env[`${prefix}_LAUNCHER`] ?? null, is_packaged: electron.app.isPackaged, app_path: electron.app.getAppPath(), args });
66
66
  // Opening the app replaces a daemon another build left running, such as one from before an upgrade. Only opening does:
67
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();
68
70
  function ensure_daemon(replace_other_build = false) {
69
71
  if (portal)
70
72
  return Promise.resolve("portal");
@@ -91,7 +93,7 @@ export function run_desktop(app, electron, options) {
91
93
  watchFile(certificates_file, { interval: 2000 }, trust_certificates);
92
94
  // This computer's daemon, and servers each signed in once with a token of this device's own.
93
95
  const connections = create_connections({ storage: connection_file_storage(join(profile, "connections.json")), offers_local: !portal, device_name: `${app.name} on ${hostname()}` });
94
- const link = create_daemon_link({ connections, socket_path });
96
+ const link = create_daemon_link({ connections, socket_path, local_ready: () => daemon_ready });
95
97
  const windows = () => BrowserWindow.getAllWindows();
96
98
  // A daemon elsewhere tells of its notices as events; this computer shows them by its own switches, as its own
97
99
  // daemon shows its own.
@@ -112,7 +114,11 @@ export function run_desktop(app, electron, options) {
112
114
  connections,
113
115
  link,
114
116
  ...(portal ? {} : {
115
- 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
+ },
116
122
  restart_local: () => ensure_daemon(),
117
123
  }),
118
124
  local_tables: portal ? [] : [...default_local_tables, "peer_listening", "remote", ...own_tables],
@@ -352,21 +358,28 @@ export function run_desktop(app, electron, options) {
352
358
  // ── Start ────────────────────────────────────────────────────────────
353
359
  function start_app() {
354
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));
355
371
  try {
356
- await ensure_daemon(true);
372
+ await daemon_ready;
357
373
  }
358
374
  catch (error) {
359
375
  dialog.showErrorBox(`${app.name} could not start`, `${error instanceof Error ? error.message : String(error)}\n\nSee ${log_file}.`);
360
376
  electron.app.exit(1);
361
377
  return;
362
378
  }
363
- if (synced_files && electron.protocol)
364
- electron.protocol.handle(file_scheme_of(app.id), file_answer);
365
- register_bridges();
366
379
  router.start();
367
380
  await apply_window_settings().catch(() => undefined);
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") && 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())
370
383
  show_window(route_in(argv));
371
384
  });
372
385
  electron.app.on("will-quit", () => {
@@ -4,9 +4,10 @@ export interface DaemonLinkOptions {
4
4
  connections: Pick<Connections, "current" | "subscribe">;
5
5
  socket_path: string;
6
6
  fetch?: typeof fetch;
7
+ local_ready?: () => Promise<unknown>;
7
8
  }
8
9
  export type DaemonLink = ReturnType<typeof create_daemon_link>;
9
- export declare function create_daemon_link({ connections, socket_path, fetch: given_fetch }: DaemonLinkOptions): {
10
+ export declare function create_daemon_link({ connections, socket_path, fetch: given_fetch, local_ready }: DaemonLinkOptions): {
10
11
  call: (path: string, args?: unknown[], headers?: Record<string, string>) => Promise<unknown>;
11
12
  follow_events: (path: string, on_event: (event: string, data: string) => void, options?: FollowOptions) => () => void;
12
13
  };
@@ -4,15 +4,17 @@
4
4
  // the user picks another.
5
5
  import { call_daemon, daemon_answer, follow_daemon_events, parse_event } from "./local_daemon.js";
6
6
  const no_daemon_text = "No daemon is chosen yet. Choose one under Settings → Connections.";
7
- export function create_daemon_link({ connections, socket_path, fetch: given_fetch }) {
7
+ export function create_daemon_link({ connections, socket_path, fetch: given_fetch, local_ready }) {
8
8
  const do_fetch = given_fetch ?? fetch;
9
9
  // Posts one call with its arguments as a JSON array and answers with what it returned; a refusal throws the daemon's words.
10
10
  async function call(path, args = [], headers = {}) {
11
11
  const daemon = connections.current();
12
12
  if (daemon === null)
13
13
  throw new Error(no_daemon_text);
14
- if (daemon.kind === "local")
14
+ if (daemon.kind === "local") {
15
+ await local_ready?.();
15
16
  return call_daemon(socket_path, path, args, headers);
17
+ }
16
18
  let response;
17
19
  try {
18
20
  response = await do_fetch(`${daemon.address}${path}`, {
@@ -1,15 +1 @@
1
- declare const unit_names: readonly [readonly ["months", 2592000], readonly ["weeks", 604800], readonly ["days", 86400], readonly ["hours", 3600], readonly ["minutes", 60], readonly ["seconds", 1]];
2
- export type DurationUnit = (typeof unit_names)[number][0];
3
- export interface DurationWording {
4
- separator?: string;
5
- largest_unit?: DurationUnit;
6
- }
7
- export declare function parse_duration(value: unknown, key: string): number;
8
- export declare function format_duration(seconds: number, wording?: DurationWording): string;
9
- export declare function format_age(seconds: number): string;
10
- export interface ClockOptions {
11
- empty?: string;
12
- hours?: "auto" | "always";
13
- }
14
- export declare function format_clock(milliseconds: number | null | undefined, options?: string | ClockOptions): string;
15
- export {};
1
+ export * from "@x-tech-laboratories/x-app-agent/durations";
package/dist/durations.js CHANGED
@@ -1,52 +1,2 @@
1
- // Reads durations such as "2h30m" from settings and writes them back in words, for the server and the agent alike.
2
- import parse from "parse-duration";
3
- // A month counts as 30 days.
4
- const unit_names = [["months", 2592000], ["weeks", 604800], ["days", 86400], ["hours", 3600], ["minutes", 60], ["seconds", 1]];
5
- const words = new Intl.DurationFormat("en", { style: "long" });
6
- // A duration in whole seconds; `key` names the setting in the error.
7
- export function parse_duration(value, key) {
8
- if (typeof value === "number" && Number.isFinite(value) && value >= 0)
9
- return Math.floor(value);
10
- const text = String(value).trim();
11
- // A bare number is seconds, where parse-duration would read milliseconds.
12
- const seconds = /^\d+$/.test(text) ? Number(text) : parse(text, "s");
13
- if (seconds === null || seconds === undefined || !Number.isFinite(seconds) || seconds < 0) {
14
- throw new Error(`\`${key}\` must be a duration such as "1w", "7d", "2h30m" or "60s", not ${JSON.stringify(value)}`);
15
- }
16
- return Math.floor(seconds);
17
- }
18
- // The two largest whole units, such as "1 day, 2 hours" or, with a space between, "1 week 2 days"; "less than a second" below one.
19
- export function format_duration(seconds, wording = {}) {
20
- if (seconds <= 0)
21
- return "0 seconds";
22
- if (seconds < 1)
23
- return "less than a second";
24
- const first_unit = unit_names.findIndex(([name]) => name === (wording.largest_unit ?? "months"));
25
- const parts = {};
26
- let remaining = Math.floor(seconds);
27
- for (const [name, size] of unit_names.slice(first_unit)) {
28
- if (Object.keys(parts).length === 2)
29
- break;
30
- if (remaining < size)
31
- continue;
32
- parts[name] = Math.floor(remaining / size);
33
- remaining %= size;
34
- }
35
- if (wording.separator === undefined)
36
- return words.format(parts);
37
- return Object.entries(parts).map(([name, count]) => words.format({ [name]: count })).join(wording.separator);
38
- }
39
- export function format_age(seconds) {
40
- return seconds < 0 ? "never" : `${format_duration(seconds)} ago`;
41
- }
42
- // A playing time as a clock, such as "3:07", or "1:02:03" from an hour; a string option is the empty text alone.
43
- export function format_clock(milliseconds, options = {}) {
44
- const { empty = "0:00", hours: show_hours = "auto" } = typeof options === "string" ? { empty: options } : options;
45
- if (milliseconds === null || milliseconds === undefined || !Number.isFinite(milliseconds))
46
- return empty;
47
- const total = Math.max(0, Math.round(milliseconds / 1000));
48
- const hours = Math.floor(total / 3600);
49
- const minutes = Math.floor((total % 3600) / 60);
50
- const seconds = String(total % 60).padStart(2, "0");
51
- return hours > 0 || show_hours === "always" ? `${hours}:${String(minutes).padStart(2, "0")}:${seconds}` : `${minutes}:${seconds}`;
52
- }
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/durations";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.129.0",
3
+ "version": "0.130.1",
4
4
  "description": "Code the X-apps share: agents and their long runs, passwords and sign-in, the Fastify server pieces, durations, and the web page's helpers and widgets",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {
@@ -11,6 +11,9 @@
11
11
  "engines": {
12
12
  "node": ">=24"
13
13
  },
14
+ "workspaces": [
15
+ "packages/agent"
16
+ ],
14
17
  "files": [
15
18
  "dist",
16
19
  "config",
@@ -240,6 +243,7 @@
240
243
  "@tiptap/pm": "^3.33.0",
241
244
  "@tiptap/react": "^3.33.0",
242
245
  "@tiptap/starter-kit": "^3.33.0",
246
+ "@x-tech-laboratories/x-app-agent": "0.130.0",
243
247
  "bonjour-service": "^1.4.4",
244
248
  "dayjs": "^1.11.23",
245
249
  "diff": "^9.0.0",
@@ -255,7 +259,6 @@
255
259
  "lucide-react": "^1.67.0",
256
260
  "marked": "^18.1.3",
257
261
  "parse-diff": "^0.12.0",
258
- "parse-duration": "^2.1.11",
259
262
  "pretty-bytes": "^7.2.0",
260
263
  "react-error-boundary": "^6.1.6",
261
264
  "react-grid-layout": "^2.3.0",
@@ -263,7 +266,6 @@
263
266
  "selfsigned": "^5.5.0",
264
267
  "semver": "^7.8.6",
265
268
  "spdx-satisfies": "^6.0.1",
266
- "sshpk": "^1.18.0",
267
269
  "tweetnacl": "^1.0.3"
268
270
  },
269
271
  "capacitor": {