@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,106 +1,2 @@
1
- // Messages one local process hands to others through a unix socket, one JSON object per line: the server end sends
2
- // every message to everyone connected, and a follower reconnects whenever the socket is not there, such as a desktop
3
- // session's agent following a system agent's notifications while their server is out of reach.
4
- // ── Imports ──────────────────────────────────────────────────────────────────
5
- import { chmodSync, unlinkSync } from "node:fs";
6
- import { createConnection, createServer } from "node:net";
7
- import { createInterface } from "node:readline";
8
- // ── Settings ─────────────────────────────────────────────────────────────────
9
- // How long a follower waits before trying the socket again.
10
- export const RETRY_SECONDS = 5.0;
11
- // ── Server ───────────────────────────────────────────────────────────────────
12
- // Sends each message as a JSON line to every process connected to a unix socket.
13
- export class LineServer {
14
- path;
15
- sockets = new Set();
16
- mode;
17
- server = null;
18
- // `mode` is the socket file's permissions; 0o666 unless set, so processes of other users may follow it.
19
- constructor(path, mode = 0o666) {
20
- this.path = path;
21
- this.mode = mode;
22
- }
23
- // Listens on the socket, replacing one a previous run left behind.
24
- async start() {
25
- try {
26
- unlinkSync(this.path);
27
- }
28
- catch {
29
- // Nothing was left behind.
30
- }
31
- const server = createServer((socket) => {
32
- this.sockets.add(socket);
33
- socket.on("error", () => undefined);
34
- socket.on("close", () => this.sockets.delete(socket));
35
- socket.resume();
36
- });
37
- await new Promise((resolve, reject) => {
38
- server.once("error", reject);
39
- server.listen(this.path, () => resolve());
40
- });
41
- this.server = server;
42
- chmodSync(this.path, this.mode);
43
- }
44
- // Hands one message to every connected process; one that has gone away is dropped.
45
- async send(message) {
46
- const line = `${JSON.stringify(message)}\n`;
47
- for (const socket of this.sockets) {
48
- try {
49
- await new Promise((resolve, reject) => socket.write(line, (error) => (error ? reject(error) : resolve())));
50
- }
51
- catch {
52
- this.sockets.delete(socket);
53
- }
54
- }
55
- }
56
- close() {
57
- for (const socket of this.sockets)
58
- socket.destroy();
59
- this.sockets.clear();
60
- this.server?.close();
61
- this.server = null;
62
- }
63
- }
64
- // Hands every message served on `path` to `handle`, reconnecting whenever the socket is not there, until the signal aborts.
65
- export async function follow_lines(path, handle, signal, options = {}) {
66
- const retry = options.retry_seconds ?? RETRY_SECONDS;
67
- const pause = () => new Promise((resolve) => {
68
- const timer = setTimeout(resolve, retry * 1000);
69
- signal.addEventListener("abort", () => {
70
- clearTimeout(timer);
71
- resolve();
72
- }, { once: true });
73
- });
74
- while (!signal.aborted) {
75
- const socket = createConnection(path);
76
- const ended = new Promise((resolve) => {
77
- socket.on("error", (error) => {
78
- options.on_disconnect?.(error.message);
79
- resolve();
80
- });
81
- socket.on("close", () => resolve());
82
- });
83
- const stop = () => socket.destroy();
84
- signal.addEventListener("abort", stop, { once: true });
85
- const lines = createInterface({ input: socket });
86
- // The reader passes the socket's errors on, and the socket's own listener already handles them.
87
- lines.on("error", () => undefined);
88
- lines.on("line", (line) => {
89
- let message;
90
- try {
91
- message = JSON.parse(line);
92
- }
93
- catch {
94
- return;
95
- }
96
- if (typeof message !== "object" || message === null || Array.isArray(message))
97
- return;
98
- if (options.accept && !options.accept(message))
99
- return;
100
- void handle(message);
101
- });
102
- await ended;
103
- signal.removeEventListener("abort", stop);
104
- await pause();
105
- }
106
- }
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/local_socket";
@@ -1,45 +1 @@
1
- import { type CommandStream } from "./commands.ts";
2
- import { type LongRun, type LongRunPoll } from "./protocol.ts";
3
- import type { TaskRunner } from "./tasks.ts";
4
- export declare const poll_limit_in_bytes: number;
5
- export interface LongRunOptions {
6
- kill_grace_in_milliseconds?: number;
7
- tail_interval_in_milliseconds?: number;
8
- unit?: LongRunUnit;
9
- }
10
- export interface LongRunUnit {
11
- prefix: string;
12
- slice?: string;
13
- properties?: Record<string, string>;
14
- environment?: Record<string, string>;
15
- start_command?: string[];
16
- stop_command?: string[];
17
- show_command?: string[];
18
- }
19
- export declare class LongRunError extends Error {
20
- constructor(message: string);
21
- }
22
- export declare class LongRuns<Task> {
23
- private readonly directory;
24
- private readonly grace;
25
- private readonly tail_interval;
26
- private readonly runner;
27
- private readonly unit;
28
- private readonly children;
29
- constructor(state_directory: string, runner: TaskRunner<Task>, options?: LongRunOptions);
30
- start(run_id: string, task: Task, stdin: string | null): LongRun;
31
- private start_unit;
32
- private show;
33
- list(): LongRun[];
34
- get(run_id: string): LongRun;
35
- poll(run_id: string, offset: number, limit?: number): Promise<LongRunPoll>;
36
- tail(run_id: string, offset: number): CommandStream;
37
- stop(run_id: string): Promise<LongRun>;
38
- forget(run_id: string): void;
39
- prune(max_age_in_seconds: number): void;
40
- private folder;
41
- private record;
42
- private require;
43
- private is_alive;
44
- private describe;
45
- }
1
+ export * from "@x-tech-laboratories/x-app-agent/long_runs";
@@ -1,419 +1,2 @@
1
- // Long runs: tasks that keep going on their own, in their own process group, so they outlive the connection that
2
- // started them and the agent itself. Each writes its output and exit code into its own folder under the state
3
- // directory, which is all a later agent needs to report on it, follow it, or stop it.
4
- //
5
- // A run's folder holds `run.json` (its pid and when the process began), `out` (stdout and stderr together), `exit`
6
- // once it has ended, and `stopped` once it has been asked to stop. Its stdin, which may carry a secret, is handed over
7
- // through a pipe and never written down.
8
- //
9
- // With the `unit` option each run is a transient systemd unit instead, in a slice of the caller's choosing, so stopping
10
- // it stops everything it started, however detached. Its stdin then passes through a named pipe in its folder.
11
- // ── Imports ──────────────────────────────────────────────────────────────────
12
- import { spawn, spawnSync } from "node:child_process";
13
- import { closeSync, constants as fs_constants, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
14
- import { open } from "node:fs/promises";
15
- import { constants } from "node:os";
16
- import { join } from "node:path";
17
- import { Readable } from "node:stream";
18
- import { kill_grace_in_milliseconds, signal_group } from "./commands.js";
19
- import { is_run_id, unknown_run_message } from "./protocol.js";
20
- // ── Settings ─────────────────────────────────────────────────────────────────
21
- // A poll returns at most this much output, and the next poll carries on from there.
22
- export const poll_limit_in_bytes = 1024 * 1024;
23
- // A followed run is read in pieces of this size.
24
- const tail_chunk_in_bytes = 64 * 1024;
25
- export class LongRunError extends Error {
26
- constructor(message) {
27
- super(message);
28
- this.name = "LongRunError";
29
- }
30
- }
31
- // ── Long runs ────────────────────────────────────────────────────────────────
32
- export class LongRuns {
33
- directory;
34
- grace;
35
- tail_interval;
36
- runner;
37
- unit;
38
- // The runs this agent started, whose exit it hears of directly.
39
- children = new Map();
40
- constructor(state_directory, runner, options = {}) {
41
- this.directory = join(state_directory, "runs");
42
- this.grace = options.kill_grace_in_milliseconds ?? kill_grace_in_milliseconds;
43
- this.tail_interval = options.tail_interval_in_milliseconds ?? 250;
44
- this.runner = runner;
45
- this.unit = options.unit;
46
- mkdirSync(this.directory, { recursive: true, mode: 0o700 });
47
- }
48
- // ── Starting ─────────────────────────────────────────────────────────────
49
- start(run_id, task, stdin) {
50
- const folder = this.folder(run_id);
51
- if (existsSync(folder))
52
- throw new LongRunError(`A run named '${run_id}' already exists.`);
53
- mkdirSync(folder, { mode: 0o700 });
54
- writeFileSync(join(folder, "out"), "", { mode: 0o600 });
55
- const launch = this.runner.launch(task, folder, stdin !== null);
56
- if (this.unit !== undefined)
57
- return this.start_unit(this.unit, run_id, folder, launch, stdin);
58
- const child = spawn(launch.program, launch.args, {
59
- detached: true,
60
- stdio: [stdin === null ? "ignore" : "pipe", "ignore", "ignore"],
61
- });
62
- if (child.pid === undefined) {
63
- rmSync(folder, { recursive: true, force: true });
64
- throw new LongRunError(`Could not start ${launch.program}.`);
65
- }
66
- if (stdin !== null) {
67
- child.stdin.on("error", () => { });
68
- child.stdin.end(stdin);
69
- }
70
- // A process killed before it could write its exit code is given the shell's code for that signal.
71
- child.on("exit", (code, signal) => {
72
- this.children.delete(run_id);
73
- const exit_file = join(folder, "exit");
74
- if (existsSync(folder) && !existsSync(exit_file)) {
75
- const exit_code = code ?? 128 + (signal === null ? 0 : constants.signals[signal]);
76
- writeFileSync(exit_file, `${exit_code}\n`);
77
- }
78
- });
79
- child.on("error", () => { });
80
- child.unref();
81
- this.children.set(run_id, child);
82
- const record = { run_id, pid: child.pid, start_ticks: start_ticks_of(child.pid), started_epoch: now_seconds() };
83
- write_atomically(join(folder, "run.json"), JSON.stringify(record));
84
- return this.describe(record);
85
- }
86
- // Starts the run as a transient unit and hands it its stdin through a named pipe once the unit opens it.
87
- start_unit(unit, run_id, folder, launch, stdin) {
88
- const name = `${unit.prefix}-${run_id}.service`;
89
- const environment_file = join(folder, "environment");
90
- writeFileSync(environment_file, environment_text(unit.environment ?? {}), { mode: 0o600 });
91
- const fifo = join(folder, "stdin");
92
- if (stdin !== null)
93
- mkfifo(fifo);
94
- const properties = {
95
- ExitType: "cgroup",
96
- TimeoutStopSec: `${this.grace}ms`,
97
- EnvironmentFile: environment_file,
98
- ...(stdin === null ? {} : { StandardInput: `file:${fifo}` }),
99
- ...unit.properties,
100
- };
101
- const [program, ...args] = unit.start_command ?? ["systemd-run"];
102
- const started = spawnSync(program, [
103
- ...args,
104
- `--unit=${name}`,
105
- "--quiet",
106
- "--collect",
107
- `--uid=${process.getuid?.() ?? 0}`,
108
- `--gid=${process.getgid?.() ?? 0}`,
109
- `--working-directory=${folder}`,
110
- ...(unit.slice === undefined ? [] : [`--slice=${unit.slice}`]),
111
- ...Object.entries(properties).flatMap(([key, value]) => ["--property", `${key}=${value}`]),
112
- "--",
113
- launch.program,
114
- ...launch.args,
115
- ], { encoding: "utf8", stdio: ["ignore", "ignore", "pipe"] });
116
- if (started.status !== 0) {
117
- rmSync(folder, { recursive: true, force: true });
118
- throw new LongRunError(`Could not start ${name}: ${(started.stderr ?? started.error?.message ?? "").trim()}`);
119
- }
120
- const pid = Number(this.show(unit, name, "MainPID")) || 0;
121
- if (stdin !== null)
122
- void hand_over(fifo, stdin, () => this.is_alive({ run_id, pid, start_ticks: null, started_epoch: 0 }));
123
- const record = { run_id, pid, unit: name, start_ticks: pid > 0 ? start_ticks_of(pid) : null, started_epoch: now_seconds() };
124
- write_atomically(join(folder, "run.json"), JSON.stringify(record));
125
- return this.describe(record);
126
- }
127
- show(unit, name, property) {
128
- const [program, ...args] = unit.show_command ?? ["systemctl", "show"];
129
- const shown = spawnSync(program, [...args, "--property", property, "--value", name], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
130
- return (shown.stdout ?? "").trim();
131
- }
132
- // ── Reading ──────────────────────────────────────────────────────────────
133
- // Every run in the state directory, as found now, so a new agent knows the ones an earlier one started.
134
- list() {
135
- const runs = [];
136
- for (const name of readdirSync(this.directory)) {
137
- const record = this.record(name);
138
- if (record !== null)
139
- runs.push(this.describe(record));
140
- }
141
- return runs.sort((first, second) => first.started_epoch - second.started_epoch || first.run_id.localeCompare(second.run_id));
142
- }
143
- get(run_id) {
144
- return this.describe(this.require(run_id));
145
- }
146
- async poll(run_id, offset, limit = poll_limit_in_bytes) {
147
- const record = this.require(run_id);
148
- // The state is read before the output, so output read after an ending is known to be complete.
149
- const run = this.describe(record);
150
- const out = join(this.folder(run_id), "out");
151
- const size = statSync(out).size;
152
- const start = Math.max(0, Math.min(Math.trunc(offset), size));
153
- let bytes = await read_range(out, start, Math.min(limit, size - start));
154
- if (start + bytes.length < size)
155
- bytes = whole_text(bytes);
156
- return {
157
- state: run.state,
158
- exit_code: run.exit_code,
159
- alive: run.state === "running",
160
- size,
161
- new_output: bytes.toString("utf8"),
162
- next_offset: start + bytes.length,
163
- };
164
- }
165
- // Follows a run's output from an offset as it is written, ending once the run has ended and all of it is read.
166
- tail(run_id, offset) {
167
- this.require(run_id);
168
- const out = join(this.folder(run_id), "out");
169
- let position = Math.max(0, Math.trunc(offset));
170
- let following = true;
171
- let reading = false;
172
- let wait_timer;
173
- let wake;
174
- let settle;
175
- const done = new Promise((resolve) => (settle = resolve));
176
- const pause = () => new Promise((resolve) => {
177
- wake = resolve;
178
- wait_timer = setTimeout(resolve, this.tail_interval);
179
- });
180
- const pump = async () => {
181
- if (reading || !following)
182
- return;
183
- reading = true;
184
- try {
185
- while (following) {
186
- const run = this.describe(this.require(run_id));
187
- const chunk = await read_range(out, position, tail_chunk_in_bytes);
188
- if (!following)
189
- return;
190
- if (chunk.length > 0) {
191
- position += chunk.length;
192
- if (!stdout.push(chunk))
193
- return;
194
- continue;
195
- }
196
- if (run.state !== "running") {
197
- following = false;
198
- stdout.push(null);
199
- settle({ exit_code: run.exit_code ?? -1, stderr: run.state === "exited" ? "" : `The run was ${run.state}.` });
200
- return;
201
- }
202
- await pause();
203
- }
204
- }
205
- catch (error) {
206
- following = false;
207
- stdout.destroy();
208
- settle({ exit_code: -1, stderr: `Could not follow the run: ${error.message}` });
209
- }
210
- finally {
211
- reading = false;
212
- }
213
- };
214
- const stdout = new Readable({
215
- read: () => void pump(),
216
- destroy: (error, callback) => {
217
- if (following)
218
- settle({ exit_code: -1, stderr: "Stopped following the run." });
219
- following = false;
220
- clearTimeout(wait_timer);
221
- wake?.();
222
- callback(error);
223
- },
224
- });
225
- return { stdout, done, stop: () => stdout.destroy() };
226
- }
227
- // ── Stopping ─────────────────────────────────────────────────────────────
228
- // Asks the run's process group to stop, kills it after the grace period, and settles once it has ended.
229
- async stop(run_id) {
230
- const record = this.require(run_id);
231
- if (this.describe(record).state !== "running")
232
- return this.describe(record);
233
- writeFileSync(join(this.folder(run_id), "stopped"), "");
234
- if (record.unit !== undefined && this.unit !== undefined) {
235
- const [program, ...args] = this.unit.stop_command ?? ["systemctl", "stop"];
236
- await new Promise((resolve) => {
237
- const stopping = spawn(program, [...args, record.unit], { stdio: "ignore" });
238
- stopping.on("error", () => resolve());
239
- stopping.on("exit", () => resolve());
240
- });
241
- while (this.is_alive(record))
242
- await new Promise((resolve) => setTimeout(resolve, 50));
243
- return this.describe(record);
244
- }
245
- signal_group(record.pid, "SIGTERM");
246
- const deadline = Date.now() + this.grace;
247
- while (this.is_alive(record)) {
248
- if (Date.now() >= deadline) {
249
- signal_group(record.pid, "SIGKILL");
250
- break;
251
- }
252
- await new Promise((resolve) => setTimeout(resolve, 50));
253
- }
254
- while (this.is_alive(record))
255
- await new Promise((resolve) => setTimeout(resolve, 50));
256
- return this.describe(record);
257
- }
258
- // Removes an ended run's folder.
259
- forget(run_id) {
260
- const record = this.require(run_id);
261
- if (this.describe(record).state === "running")
262
- throw new LongRunError(`The run '${run_id}' is still running.`);
263
- rmSync(this.folder(run_id), { recursive: true, force: true });
264
- }
265
- // Forgets runs that ended longer ago than the age given.
266
- prune(max_age_in_seconds) {
267
- const cutoff = Date.now() - max_age_in_seconds * 1000;
268
- for (const run of this.list()) {
269
- if (run.state === "running")
270
- continue;
271
- const exit_file = join(this.folder(run.run_id), "exit");
272
- const ended = existsSync(exit_file) ? statSync(exit_file).mtimeMs : run.started_epoch * 1000;
273
- if (ended < cutoff)
274
- this.forget(run.run_id);
275
- }
276
- }
277
- // ── Helpers ──────────────────────────────────────────────────────────────
278
- folder(run_id) {
279
- if (!is_run_id(run_id))
280
- throw new LongRunError(`'${run_id}' is not a valid run id.`);
281
- return join(this.directory, run_id);
282
- }
283
- record(run_id) {
284
- if (!is_run_id(run_id))
285
- return null;
286
- try {
287
- return JSON.parse(readFileSync(join(this.folder(run_id), "run.json"), "utf8"));
288
- }
289
- catch {
290
- return null;
291
- }
292
- }
293
- require(run_id) {
294
- const record = this.record(run_id);
295
- if (record === null)
296
- throw new LongRunError(unknown_run_message(run_id));
297
- return record;
298
- }
299
- is_alive(record) {
300
- const child = this.children.get(record.run_id);
301
- if (child !== undefined)
302
- return child.exitCode === null && child.signalCode === null;
303
- if (record.pid <= 0)
304
- return false;
305
- try {
306
- process.kill(record.pid, 0);
307
- }
308
- catch (error) {
309
- if (error.code !== "EPERM")
310
- return false;
311
- }
312
- return record.start_ticks === null || start_ticks_of(record.pid) === record.start_ticks;
313
- }
314
- describe(record) {
315
- const folder = this.folder(record.run_id);
316
- const stopped = existsSync(join(folder, "stopped"));
317
- const exit_code = read_exit_code(join(folder, "exit"));
318
- let state;
319
- if (exit_code !== null)
320
- state = stopped ? "stopped" : "exited";
321
- else if (this.is_alive(record))
322
- state = "running";
323
- else
324
- state = stopped ? "stopped" : "lost";
325
- return { run_id: record.run_id, pid: record.pid, started_epoch: record.started_epoch, state, exit_code };
326
- }
327
- }
328
- // ── Units ──────────────────────────────────────────────────────────────────
329
- // An environment file systemd reads as written: every value quoted, with nothing in it expanded.
330
- function environment_text(environment) {
331
- return Object.entries(environment)
332
- .map(([key, value]) => `${key}="${value.replace(/[\\"$`]/g, (character) => `\\${character}`)}"\n`)
333
- .join("");
334
- }
335
- function mkfifo(path) {
336
- const made = spawnSync("mkfifo", ["-m", "600", path], { encoding: "utf8", stdio: ["ignore", "ignore", "pipe"] });
337
- if (made.status !== 0)
338
- throw new LongRunError(`Could not make ${path}: ${(made.stderr ?? made.error?.message ?? "").trim()}`);
339
- }
340
- // Writes stdin into the named pipe once the unit has opened it, giving up if the run ends first.
341
- async function hand_over(fifo, stdin, alive) {
342
- for (;;) {
343
- let descriptor;
344
- try {
345
- descriptor = openSync(fifo, fs_constants.O_WRONLY | fs_constants.O_NONBLOCK);
346
- }
347
- catch {
348
- if (!alive())
349
- return;
350
- await new Promise((resolve) => setTimeout(resolve, 20));
351
- continue;
352
- }
353
- try {
354
- writeSync(descriptor, stdin);
355
- }
356
- catch {
357
- // The run closed its stdin without reading it.
358
- }
359
- finally {
360
- closeSync(descriptor);
361
- }
362
- return;
363
- }
364
- }
365
- // ── Files ────────────────────────────────────────────────────────────────────
366
- function read_exit_code(path) {
367
- try {
368
- const text = readFileSync(path, "utf8").trim();
369
- return /^-?\d+$/.test(text) ? Number(text) : null;
370
- }
371
- catch {
372
- return null;
373
- }
374
- }
375
- async function read_range(path, offset, length) {
376
- if (length <= 0)
377
- return Buffer.alloc(0);
378
- const handle = await open(path, "r");
379
- try {
380
- const buffer = Buffer.alloc(length);
381
- const { bytesRead } = await handle.read(buffer, 0, length, offset);
382
- return buffer.subarray(0, bytesRead);
383
- }
384
- finally {
385
- await handle.close();
386
- }
387
- }
388
- // Cuts a piece of output back to its last whole line, or failing that its last whole character.
389
- function whole_text(bytes) {
390
- const last_newline = bytes.lastIndexOf(0x0a);
391
- if (last_newline !== -1)
392
- return bytes.subarray(0, last_newline + 1);
393
- let start = bytes.length - 1;
394
- while (start > 0 && start > bytes.length - 4 && (bytes[start] & 0xc0) === 0x80)
395
- start--;
396
- const lead = bytes[start];
397
- const needed = lead >= 0xf0 ? 4 : lead >= 0xe0 ? 3 : lead >= 0xc0 ? 2 : 1;
398
- return bytes.length - start < needed ? bytes.subarray(0, start) : bytes;
399
- }
400
- function write_atomically(path, text) {
401
- writeFileSync(`${path}.part`, text, { mode: 0o600 });
402
- renameSync(`${path}.part`, path);
403
- }
404
- // When the process began, from /proc; null where /proc is missing.
405
- function start_ticks_of(pid) {
406
- try {
407
- const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
408
- // The fields after the command name, which may itself hold spaces and parentheses; start time is field 22.
409
- const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
410
- const ticks = Number(fields[19]);
411
- return Number.isFinite(ticks) ? ticks : null;
412
- }
413
- catch {
414
- return null;
415
- }
416
- }
417
- function now_seconds() {
418
- return Math.floor(Date.now() / 1000);
419
- }
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/long_runs";
@@ -1,60 +1 @@
1
- export interface Sink {
2
- write(chunk: Buffer | string): void;
3
- }
4
- export type StreamUse = "show" | "keep" | "both" | "drop";
5
- export interface ProgramOptions {
6
- stdin?: string | null;
7
- stdout?: StreamUse;
8
- stderr?: StreamUse;
9
- out?: Sink;
10
- err?: Sink;
11
- env?: NodeJS.ProcessEnv;
12
- cwd?: string;
13
- signal?: AbortSignal;
14
- own_group?: boolean;
15
- on_host?: boolean;
16
- }
17
- export interface ProgramResult {
18
- exit_code: number;
19
- stdout: string;
20
- stderr: string;
21
- }
22
- export declare const kill_grace_in_milliseconds = 5000;
23
- export declare const stdout_limit_in_bytes: number;
24
- export declare const stderr_limit_in_bytes: number;
25
- export declare const not_installed_exit_code = 127;
26
- export declare function signal_group(pid: number | undefined, signal: NodeJS.Signals): void;
27
- export declare class BoundedBuffer {
28
- private readonly chunks;
29
- private size;
30
- truncated: boolean;
31
- private readonly limit;
32
- constructor(limit: number);
33
- write(chunk: Buffer | string): void;
34
- text(): string;
35
- }
36
- export declare function on_path(name: string): Promise<string | null>;
37
- export declare function whole_lines(sink: Sink): Sink & {
38
- flush(): void;
39
- };
40
- export declare function in_flatpak(variables?: NodeJS.ProcessEnv): boolean;
41
- export declare function host_argv(argv: readonly string[], cwd?: string, variables?: NodeJS.ProcessEnv): string[];
42
- export declare function run_program(argv: readonly string[], options?: ProgramOptions): Promise<ProgramResult>;
43
- export interface LineProgramOptions {
44
- cwd?: string;
45
- env?: NodeJS.ProcessEnv;
46
- signal?: AbortSignal;
47
- on_host?: boolean;
48
- on_line: (line: string) => void;
49
- }
50
- export interface LineProgramExit {
51
- exit_code: number;
52
- stderr: string;
53
- }
54
- export interface LineProgram {
55
- write_line: (line: string) => void;
56
- end_input: () => void;
57
- is_open: () => boolean;
58
- finished: Promise<LineProgramExit>;
59
- }
60
- export declare function start_line_program(argv: readonly string[], options: LineProgramOptions): LineProgram;
1
+ export * from "@x-tech-laboratories/x-app-agent/programs";