@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
package/README.md CHANGED
@@ -5,6 +5,13 @@
5
5
  Code the X-apps share, published as one npm package, `@x-tech-laboratories/x-app`, with a subpath per module. It was X-Libs (`@x-tech-laboratories/x-libs`) until 0.97.0, the last release under that name;
6
6
  an app moves over by changing the package name in its imports and its `x-libs-*` commands to `x-app-*`.
7
7
 
8
+ The host agent's side, `agent/*` and `durations`, is also its own package, `@x-tech-laboratories/x-app-agent` in
9
+ `packages/agent`, released at the same version as X-App, so an app's agent installs on each host with sshpk and
10
+ parse-duration alone in place of the whole of X-App, React and Fastify included. Its modules keep the same names
11
+ (`@x-tech-laboratories/x-app-agent/session`), and X-App's own `agent/*` and `durations` re-export them, so an app's
12
+ server and pages import them from either. An app packages its agent from a folder with its own `package.json` that
13
+ depends on the agent package alone.
14
+
8
15
  ## Modules
9
16
 
10
17
  | Import | What it holds |
@@ -283,6 +290,13 @@ An app whose work needs a computer, such as one that runs programs on checkouts,
283
290
  - **Sign-in from the config**: `admin_name` names the admin a bare hash in the accounts file signs in as, and
284
291
  `proxy_user_header` (with `trusted_proxies`, 127.0.0.1 and ::1 unless set) signs in whoever a reverse proxy on those
285
292
  addresses names; `define_app`'s `check_access` checks a user's access when an admin sets it, such as a list of grants.
293
+ - **Outside sites**: `outside: { hosts, headers }` names the sites the page reaches with `page().outside_fetch`, such
294
+ as a video site's API, which a browser's cross-origin rules would block: the desktop sends each request from its main
295
+ process with the answer streamed back, the server for a signed-in browser at `POST /api/outside`, and a phone with
296
+ Android's own HTTP (`app/outside_fetch`). Each host refuses any other host and sets `headers` last, such as an
297
+ `Origin` the site insists on, which a page cannot set itself.
298
+ - **A start page the user picks**: `render_app`'s `default_page_setting` names the setting holding the page an empty
299
+ route opens, such as `"stream.startup_page"`; `default_page` while it names none of the pages.
286
300
  - **Keys in a settings export**: `render_app`'s `exports_secrets: true` offers "Include keys and tokens" on exporting
287
301
  the settings, for an app whose settings hold other services' keys.
288
302
  - **Links to other apps**: `run_desktop`'s `external_schemes`, such as `["stremio:", "steam:"]`, opens those links in
@@ -306,6 +320,8 @@ The rest of an app's files are short calls into X-App too:
306
320
  - **Nix**: X-App's flake has a `lib` with `package`, `desktop_package`, `module`, `shell` and `android_shell`, each
307
321
  taking the app's package set and its `nix/app.nix` (name, display name, variables' prefix, port, database file and
308
322
  words); the app's `nix/flake.nix` takes `github:x-tech-laboratories/X-App` as an input and calls them.
323
+ `webview_package`, given the app's `github:x-tech-laboratories/X-WebView` input first, builds the desktop app on
324
+ X-WebView for Linux phones such as the PinePhone, under the same `<name>-desktop` program.
309
325
  An app with git dependencies names each lock entry's https URL in `git_dependencies`, which the packages fetch and
310
326
  copy in, and `link_scheme`, such as `"codex"`, makes the desktop entry open its links; `desktop_path`, such as
311
327
  `pkgs: [ pkgs.libnotify ]`, puts programs the desktop app runs on its PATH, and `state_name` keeps an older service's
@@ -800,7 +816,8 @@ it, MDX's own compiler reads the pages (with GitHub's tables and task lists), Sh
800
816
  Pagefind indexes the built pages for search. Each page is drawn to HTML at build time and picked up again in the browser,
801
817
  so it reads without JavaScript and its search, outline, menus and theme work with it.
802
818
 
803
- - **Pages**: `content/**/*.md(x)` with a `title` in the frontmatter, `index` files at their folder; `template: splash` makes a
819
+ - **Pages**: `content/**/*.md(x)` with a `title` in the frontmatter, `index` files at their folder, and a `README` at its
820
+ folder when the folder has no `index` (with both, the `README` is a page of its own); `template: splash` makes a
804
821
  landing page with a `hero` (title, tagline, image, actions); `sidebar.order`, `sidebar.label` and `sidebar.hidden` place a
805
822
  page; `toc: false` hides its outline. MDX imports `Card`, `CardGrid`, `LinkCard` and `Aside` from `web/react/site`, and the
806
823
  site's own React components.
@@ -820,8 +837,15 @@ so it reads without JavaScript and its search, outline, menus and theme work wit
820
837
  - **GitHub's own Markdown**: alerts such as `> [!TIP]` show as asides and raw HTML such as a table of pictures is
821
838
  kept, so a page reads the same on GitHub and on the site; a page with no `title` takes its opening `# heading`, which
822
839
  is then not drawn twice, so an MDX page can show a README with `import Readme from "../README.md"`; links that start at the root move under the base in Markdown and in a component's `href` or `src`.
840
+ - **Relative links and pictures, as on GitHub**: a link written relative to its page, such as `[Merge](../decisions/merge.md#why)`
841
+ or `[Decisions](../decisions/)`, goes to that page, or the folder's `index` or `README` page, keeping its anchor; a
842
+ picture or other file inside the content folder, such as `![Map](../diagrams/map.png)` or a linked `.drawio` or
843
+ `.pdf`, is served at its own path in `dev` and copied into `dist/` by `build`, and only files a page uses are copied. A
844
+ link to anything else, such as a source file outside the content folder, is left as written, and a link to a Markdown
845
+ file that is not there is too, named in a list at the end of the build rather than failing it, so archived pages
846
+ with links that were already dead on GitHub still build.
823
847
  - **Diagrams**: images like any other. Draw them in [draw.io](https://www.drawio.com/), keep the `.drawio` source beside
824
- its PNG export in `public/`, and show the PNG; a ```` ```mermaid ```` block is only code.
848
+ its PNG export, in `public/` or beside the pages, and show the PNG; a ```` ```mermaid ```` block is only code.
825
849
  - **Pages beside a package**: the scan skips `node_modules`, `dist`, `public` and hidden folders, so a site can live in
826
850
  an app's `docs/` folder with a `package.json` of its own.
827
851
 
@@ -912,7 +936,7 @@ command worked out from `change.base`, the commit `read_change` resolved, so the
912
936
  ```sh
913
937
  nix-shell # Node 24 and ssh-keygen, which the key tests use
914
938
  npm install
915
- npm run build # compiles src/ into dist/
939
+ npm run build # compiles packages/agent/src/ and src/ into their dist/
916
940
  npm test
917
941
  npm run coverage # raises the coverage floor in vitest.config.ts; commit it
918
942
  npm run lint
@@ -920,7 +944,7 @@ npm run lint
920
944
 
921
945
  The coverage floor in `vitest.config.ts` only rises: CI fails when coverage drops below it or a raised floor is not committed.
922
946
 
923
- A release is a version bump merged into `main`: the Publish workflow then publishes that version from CI with npm provenance, through npm's trusted publishing for this repository. `npm pack` and `npm publish` build first.
947
+ A release is a version bump merged into `main`: the Publish workflow then publishes that version from CI with npm provenance, through npm's trusted publishing for this repository. `npm pack` and `npm publish` build first. Bump `packages/agent/package.json` to the same version and X-App's exact dependency on it with it; the workflow publishes the agent package first. The tests read the agent package from its sources (an alias in `vitest.config.ts`), so they need no build.
924
948
 
925
949
  ## License
926
950
 
@@ -1,22 +1 @@
1
- import { type LineProgramExit } from "./programs.ts";
2
- export type StreamMessage = Record<string, unknown>;
3
- export interface ClaudeStreamOptions {
4
- cwd?: string;
5
- env?: NodeJS.ProcessEnv;
6
- signal?: AbortSignal;
7
- on_line: (line: string, message: StreamMessage | null) => void;
8
- on_request?: (request_id: string, request: StreamMessage) => boolean;
9
- control_timeout_in_milliseconds?: number;
10
- }
11
- export interface ClaudeStream {
12
- send_user: (text: string, id: string) => void;
13
- control: (request: StreamMessage) => Promise<StreamMessage>;
14
- respond: (request_id: string, response: StreamMessage) => void;
15
- end_input: () => void;
16
- is_open: () => boolean;
17
- finished: Promise<LineProgramExit>;
18
- }
19
- export declare function user_message_line(text: string, id: string): string;
20
- export declare function allow_tool(input: StreamMessage): StreamMessage;
21
- export declare function deny_tool(message: string): StreamMessage;
22
- export declare function start_claude_stream(argv: readonly string[], options: ClaudeStreamOptions): ClaudeStream;
1
+ export * from "@x-tech-laboratories/x-app-agent/claude_stream";
@@ -1,85 +1,2 @@
1
- // A Claude Code session driven over its stream-json protocol, as `claude -p --input-format stream-json
2
- // --output-format stream-json` speaks it: user messages written to its input at any time, control requests such as an
3
- // interrupt or a change of permission mode answered by id, the session's own requests, such as asking whether a tool
4
- // may run, answered back, and every other line it prints handed on whole and parsed.
5
- // ── Imports ──────────────────────────────────────────────────────────────────
6
- import { randomUUID } from "node:crypto";
7
- import { start_line_program } from "./programs.js";
8
- const default_control_timeout_in_milliseconds = 30_000;
9
- // ── Messages ─────────────────────────────────────────────────────────────────
10
- // The line that writes a user message to the session.
11
- export function user_message_line(text, id) {
12
- return JSON.stringify({ type: "user", message: { role: "user", content: [{ type: "text", text }] }, parent_tool_use_id: null, uuid: id });
13
- }
14
- // The answer allowing a tool call the session asked about, with the input it may run with.
15
- export function allow_tool(input) {
16
- return { behavior: "allow", updatedInput: input };
17
- }
18
- // The answer refusing a tool call, with the reason the agent is given.
19
- export function deny_tool(message) {
20
- return { behavior: "deny", message: message || "The user refused this tool call." };
21
- }
22
- // ── Session ──────────────────────────────────────────────────────────────────
23
- export function start_claude_stream(argv, options) {
24
- const waiting = new Map();
25
- const timeout = options.control_timeout_in_milliseconds ?? default_control_timeout_in_milliseconds;
26
- function on_line(line) {
27
- if (!line.trim())
28
- return;
29
- let message = null;
30
- try {
31
- message = JSON.parse(line);
32
- }
33
- catch {
34
- message = null;
35
- }
36
- if (message?.type === "control_response") {
37
- const response = (message.response ?? {});
38
- const waiter = waiting.get(String(response.request_id ?? ""));
39
- if (!waiter)
40
- return;
41
- waiting.delete(String(response.request_id));
42
- clearTimeout(waiter.timer);
43
- if (response.subtype === "error")
44
- waiter.reject(new Error(String(response.error ?? "the session refused the request")));
45
- else
46
- waiter.resolve((response.response ?? {}));
47
- return;
48
- }
49
- if (message?.type === "control_request") {
50
- const request_id = String(message.request_id ?? "");
51
- const taken = options.on_request?.(request_id, (message.request ?? {})) ?? false;
52
- if (!taken)
53
- program.write_line(JSON.stringify({ type: "control_response", response: { subtype: "error", request_id, error: "This program does not answer this request" } }));
54
- return;
55
- }
56
- options.on_line(line, message);
57
- }
58
- const program = start_line_program(argv, { cwd: options.cwd, env: options.env, signal: options.signal, on_line });
59
- const finished = program.finished.then((exit) => {
60
- for (const [id, waiter] of waiting) {
61
- clearTimeout(waiter.timer);
62
- waiter.reject(new Error("the session ended before it answered"));
63
- waiting.delete(id);
64
- }
65
- return exit;
66
- });
67
- return {
68
- send_user: (text, id) => program.write_line(user_message_line(text, id)),
69
- control: (request) => new Promise((resolve, reject) => {
70
- if (!program.is_open())
71
- return reject(new Error("the session is no longer taking requests"));
72
- const request_id = randomUUID();
73
- const timer = setTimeout(() => {
74
- waiting.delete(request_id);
75
- reject(new Error("the session did not answer in time"));
76
- }, timeout);
77
- waiting.set(request_id, { resolve, reject, timer });
78
- program.write_line(JSON.stringify({ type: "control_request", request_id, request }));
79
- }),
80
- respond: (request_id, response) => program.write_line(JSON.stringify({ type: "control_response", response: { subtype: "success", request_id, response } })),
81
- end_input: program.end_input,
82
- is_open: program.is_open,
83
- finished,
84
- };
85
- }
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/claude_stream";
@@ -1,35 +1 @@
1
- import type { KeyObject } from "node:crypto";
2
- import { LongRuns, type LongRunOptions } from "./long_runs.ts";
3
- import { type AgentApp } from "./protocol.ts";
4
- import { AgentSession, type SessionHooks } from "./session.ts";
5
- import type { TaskRunner } from "./tasks.ts";
6
- export interface AgentConfig<Task> extends SessionHooks<Task> {
7
- app: AgentApp<Task>;
8
- runner: TaskRunner<Task>;
9
- url: string;
10
- key_file?: string;
11
- token_file?: string;
12
- server_keys?: readonly string[];
13
- challenge_timeout_in_milliseconds?: number;
14
- state_directory: string;
15
- host: string;
16
- agent_version: string;
17
- heartbeat_in_milliseconds?: number;
18
- backoff_initial_in_milliseconds?: number;
19
- backoff_longest_in_milliseconds?: number;
20
- long_runs?: LongRunOptions;
21
- log?: (line: string) => void;
22
- }
23
- export declare class AgentConfigError extends Error {
24
- constructor(message: string);
25
- }
26
- export declare function check_url(text: string): URL;
27
- export declare function read_key_file(file: string): KeyObject;
28
- export declare function read_server_keys(lines: readonly string[]): Map<string, KeyObject>;
29
- export interface RunningAgent<Task> {
30
- readonly runs: LongRuns<Task>;
31
- connected(): boolean;
32
- session(): AgentSession<Task> | null;
33
- stop(): Promise<void>;
34
- }
35
- export declare function start_agent<Task>(config: AgentConfig<Task>): RunningAgent<Task>;
1
+ export * from "@x-tech-laboratories/x-app-agent/client";
@@ -1,169 +1,2 @@
1
- // The agent's connection to the server: dials out over a WebSocket with its host's key or token, hands the connection
2
- // to a session, and dials again with a growing, jittered wait whenever it drops. Given the server's public keys, it
3
- // answers only a server that signs with one of them.
4
- import { readFileSync } from "node:fs";
5
- import { AgentKeyError, parse_private_key, parse_server_keys } from "./keys.js";
6
- import { LongRuns } from "./long_runs.js";
7
- import { key_host_header } from "./protocol.js";
8
- import { AgentSession } from "./session.js";
9
- export class AgentConfigError extends Error {
10
- constructor(message) {
11
- super(message);
12
- this.name = "AgentConfigError";
13
- }
14
- }
15
- const local_names = new Set(["localhost", "[::1]", "::1"]);
16
- // ── Checks ───────────────────────────────────────────────────────────────────
17
- // The server's URL, which must be wss:// so secrets and output travel encrypted, unless it is this machine.
18
- export function check_url(text) {
19
- let url;
20
- try {
21
- url = new URL(text);
22
- }
23
- catch {
24
- throw new AgentConfigError(`'${text}' is not a URL.`);
25
- }
26
- if (url.protocol === "wss:")
27
- return url;
28
- if (url.protocol !== "ws:")
29
- throw new AgentConfigError(`The server URL must start with wss://, not ${url.protocol}//.`);
30
- const local = local_names.has(url.hostname) || /^127\.\d+\.\d+\.\d+$/.test(url.hostname);
31
- if (!local)
32
- throw new AgentConfigError(`ws:// is unencrypted, so it is only allowed to this machine; use wss://${url.host}${url.pathname}.`);
33
- return url;
34
- }
35
- function login_of(config) {
36
- const has_key = Boolean(config.key_file);
37
- const has_token = Boolean(config.token_file);
38
- if (has_key === has_token)
39
- throw new AgentConfigError("Give exactly one of a key file and a token file.");
40
- return has_key ? { kind: "key", file: config.key_file } : { kind: "token", file: config.token_file };
41
- }
42
- // The key in the file, or an AgentConfigError naming the file for one that is not a usable key.
43
- export function read_key_file(file) {
44
- const text = readFileSync(file, "utf8");
45
- try {
46
- return parse_private_key(text);
47
- }
48
- catch (error) {
49
- if (error instanceof AgentKeyError)
50
- throw new AgentConfigError(`The key file ${file} ${error.message}`);
51
- throw error;
52
- }
53
- }
54
- // The accepted server keys by fingerprint, or an AgentConfigError naming the line that is not an ed25519 public key.
55
- export function read_server_keys(lines) {
56
- const keys = new Map();
57
- for (const [index, line] of lines.entries()) {
58
- try {
59
- for (const [fingerprint, key] of parse_server_keys([line]))
60
- keys.set(fingerprint, key);
61
- }
62
- catch (error) {
63
- if (error instanceof AgentKeyError)
64
- throw new AgentConfigError(`Server key ${index + 1} ${error.message}`);
65
- throw error;
66
- }
67
- }
68
- return keys;
69
- }
70
- export function start_agent(config) {
71
- const url = check_url(config.url);
72
- const login = login_of(config);
73
- // A key that is there but unusable stops the agent at once; one not there yet, as before secrets are in place, is retried.
74
- if (login.kind === "key") {
75
- try {
76
- read_key_file(login.file);
77
- }
78
- catch (error) {
79
- if (error instanceof AgentConfigError)
80
- throw error;
81
- }
82
- }
83
- const server_keys = read_server_keys(config.server_keys ?? []);
84
- const runs = new LongRuns(config.state_directory, config.runner, config.long_runs);
85
- const log = config.log ?? ((line) => console.log(line));
86
- if (server_keys.size === 0) {
87
- log(`Warning: the server at ${url.origin} is proved by TLS alone; give the agent the server's public key in server_keys so it refuses requests the server did not sign.`);
88
- }
89
- const heartbeat = config.heartbeat_in_milliseconds ?? 15_000;
90
- const initial = config.backoff_initial_in_milliseconds ?? 1000;
91
- const longest = config.backoff_longest_in_milliseconds ?? 60_000;
92
- let socket = null;
93
- let session = null;
94
- let failures = 0;
95
- let stopping = false;
96
- let retry_timer;
97
- let closed_resolve = null;
98
- const dial_later = () => {
99
- if (stopping)
100
- return;
101
- // Half the wait is fixed and half random, so hosts that lost the server together do not all return at once.
102
- const wait = Math.min(longest, initial * 2 ** failures);
103
- failures++;
104
- retry_timer = setTimeout(dial, wait / 2 + Math.random() * (wait / 2));
105
- };
106
- const dial = () => {
107
- if (stopping)
108
- return;
109
- let headers;
110
- let key = null;
111
- try {
112
- if (login.kind === "key") {
113
- key = read_key_file(login.file);
114
- headers = { [key_host_header(config.app.name)]: config.host };
115
- }
116
- else {
117
- headers = { authorization: `Bearer ${readFileSync(login.file, "utf8").trim()}` };
118
- }
119
- }
120
- catch (error) {
121
- log(`Could not read the ${login.kind} file: ${error.message}`);
122
- dial_later();
123
- return;
124
- }
125
- // Node's WebSocket takes headers, which the browser's type has no room for.
126
- const current = new WebSocket(url, { headers });
127
- current.binaryType = "arraybuffer";
128
- socket = current;
129
- current.addEventListener("open", () => {
130
- failures = 0;
131
- log(`Connected to ${url.origin}`);
132
- session = new AgentSession(current, runs, {
133
- app: config.app, runner: config.runner, host: config.host, agent_version: config.agent_version, heartbeat_in_milliseconds: heartbeat, key,
134
- server_keys, challenge_timeout_in_milliseconds: config.challenge_timeout_in_milliseconds, log, requests: config.requests, on_message: config.on_message, on_hello: config.on_hello,
135
- });
136
- });
137
- current.addEventListener("message", (event) => {
138
- if (typeof event.data === "string")
139
- session?.receive(event.data);
140
- });
141
- current.addEventListener("error", () => { });
142
- current.addEventListener("close", (event) => {
143
- if (session !== null)
144
- log(`Disconnected from ${url.origin} (${event.code}${event.reason ? `: ${event.reason}` : ""})`);
145
- session?.close();
146
- session = null;
147
- socket = null;
148
- if (closed_resolve !== null)
149
- closed_resolve();
150
- else
151
- dial_later();
152
- });
153
- };
154
- dial();
155
- return {
156
- runs,
157
- connected: () => session !== null,
158
- session: () => session,
159
- stop: () => {
160
- stopping = true;
161
- clearTimeout(retry_timer);
162
- if (socket === null)
163
- return Promise.resolve();
164
- const closing = new Promise((resolve) => (closed_resolve = resolve));
165
- socket.close(1000, "The agent is stopping.");
166
- return closing;
167
- },
168
- };
169
- }
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/client";
@@ -1,22 +1 @@
1
- import type { Readable } from "node:stream";
2
- import { kill_grace_in_milliseconds, signal_group, stderr_limit_in_bytes } from "./programs.ts";
3
- import type { RunResult } from "./protocol.ts";
4
- export interface RunOptions {
5
- timeout_in_seconds: number;
6
- stdin?: string | null;
7
- }
8
- export interface StreamOptions {
9
- stdin?: string | null;
10
- }
11
- export interface CommandStream {
12
- stdout: Readable;
13
- done: Promise<{
14
- exit_code: number;
15
- stderr: string;
16
- }>;
17
- stop: () => void;
18
- }
19
- export declare const run_stdout_limit_in_bytes: number;
20
- export { kill_grace_in_milliseconds, signal_group, stderr_limit_in_bytes };
21
- export declare function run_command(command: string, options: RunOptions): Promise<RunResult>;
22
- export declare function stream_command(command: string, options?: StreamOptions): CommandStream;
1
+ export * from "@x-tech-laboratories/x-app-agent/commands";
@@ -1,80 +1,2 @@
1
- // Runs one shell command on this machine, either to its end with its output kept or with its stdout handed back as it
2
- // comes. Both the agent and the server's built-in agent run commands through here.
3
- // ── Imports ──────────────────────────────────────────────────────────────────
4
- import { spawn } from "node:child_process";
5
- import { BoundedBuffer, kill_grace_in_milliseconds, signal_group, stderr_limit_in_bytes, stdout_limit_in_bytes } from "./programs.js";
6
- // A run keeps at most this much stdout, since it travels whole in one message.
7
- export const run_stdout_limit_in_bytes = stdout_limit_in_bytes;
8
- export { kill_grace_in_milliseconds, signal_group, stderr_limit_in_bytes };
9
- // ── Helpers ──────────────────────────────────────────────────────────────────
10
- // Its own process group, so stopping it stops the command's children too.
11
- function spawn_shell(command, stdin) {
12
- const child = spawn("sh", ["-c", command], { detached: true, stdio: [stdin == null ? "ignore" : "pipe", "pipe", "pipe"] });
13
- if (stdin != null) {
14
- child.stdin.on("error", () => { });
15
- child.stdin.end(stdin);
16
- }
17
- return child;
18
- }
19
- // ── Running ──────────────────────────────────────────────────────────────────
20
- export function run_command(command, options) {
21
- return new Promise((resolve) => {
22
- const child = spawn_shell(command, options.stdin);
23
- const stdout = new BoundedBuffer(run_stdout_limit_in_bytes);
24
- const stderr = new BoundedBuffer(stderr_limit_in_bytes);
25
- let timed_out = false;
26
- let kill_timer;
27
- const timeout_timer = setTimeout(() => {
28
- timed_out = true;
29
- signal_group(child.pid, "SIGTERM");
30
- kill_timer = setTimeout(() => signal_group(child.pid, "SIGKILL"), kill_grace_in_milliseconds);
31
- }, options.timeout_in_seconds * 1000);
32
- child.stdout.on("data", (chunk) => stdout.write(chunk));
33
- child.stderr.on("data", (chunk) => stderr.write(chunk));
34
- child.on("error", (error) => {
35
- clearTimeout(timeout_timer);
36
- clearTimeout(kill_timer);
37
- resolve({ exit_code: -1, stdout: "", stderr: `Could not start sh: ${error.message}` });
38
- });
39
- child.on("close", (exit_code) => {
40
- clearTimeout(timeout_timer);
41
- clearTimeout(kill_timer);
42
- if (timed_out) {
43
- resolve({ exit_code: -1, stdout: stdout.text().trim(), stderr: `Timed out after ${options.timeout_in_seconds}s` });
44
- return;
45
- }
46
- const note = stdout.truncated ? `Output cut at ${run_stdout_limit_in_bytes} bytes` : "";
47
- resolve({ exit_code: exit_code ?? -1, stdout: stdout.text().trim(), stderr: [stderr.text().trim(), note].filter(Boolean).join("\n") });
48
- });
49
- });
50
- }
51
- // ── Streaming ────────────────────────────────────────────────────────────────
52
- // Runs the command with no timeout and hands back its stdout as it comes, for output too big to hold.
53
- export function stream_command(command, options = {}) {
54
- const child = spawn_shell(command, options.stdin);
55
- const stderr = new BoundedBuffer(stderr_limit_in_bytes);
56
- let ended = false;
57
- let kill_timer;
58
- child.stderr.on("data", (chunk) => stderr.write(chunk));
59
- const done = new Promise((resolve) => {
60
- child.on("error", (error) => {
61
- ended = true;
62
- resolve({ exit_code: -1, stderr: `Could not start sh: ${error.message}` });
63
- });
64
- child.on("close", (exit_code) => {
65
- ended = true;
66
- clearTimeout(kill_timer);
67
- resolve({ exit_code: exit_code ?? -1, stderr: stderr.text().trim() });
68
- });
69
- });
70
- const stop = () => {
71
- if (ended)
72
- return;
73
- signal_group(child.pid, "SIGTERM");
74
- // Output nobody reads any more is thrown away, so a full pipe cannot keep the command from ending.
75
- child.stdout.unpipe();
76
- child.stdout.destroy();
77
- kill_timer ??= setTimeout(() => signal_group(child.pid, "SIGKILL"), kill_grace_in_milliseconds);
78
- };
79
- return { stdout: child.stdout, done, stop };
80
- }
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/commands";
@@ -1,54 +1 @@
1
- export declare const URGENCIES: readonly ["low", "normal", "critical"];
2
- export declare const WAIT_SECONDS: number;
3
- export declare const ID_SECONDS = 10;
4
- export interface DesktopNotification {
5
- title?: unknown;
6
- body?: unknown;
7
- urgency?: unknown;
8
- url?: unknown;
9
- icon?: unknown;
10
- key?: unknown;
11
- timeout?: unknown;
12
- }
13
- export interface CommandOptions {
14
- app_name: string;
15
- icon?: string | null;
16
- replace_id?: number | null;
17
- timeout?: number;
18
- }
19
- export declare function notify_command(title: string, body: string, urgency: string, url: string | null, options: CommandOptions): string[];
20
- export declare function close_command(notification_id: number): string[];
21
- export interface DesktopProcess {
22
- first_line(): Promise<string | null>;
23
- finished(): Promise<[stdout: string, stderr: string]>;
24
- exit_code(): number | null;
25
- kill(): void;
26
- }
27
- export type StartProcess = (args: string[]) => Promise<DesktopProcess>;
28
- export declare const start_process: StartProcess;
29
- export interface NotifierOptions {
30
- app_name: string;
31
- default_title?: string;
32
- icons?: Record<string, string>;
33
- start?: StartProcess;
34
- on_error?: (message: string) => void;
35
- }
36
- export declare class Notifier {
37
- private readonly shown;
38
- private readonly queues;
39
- private readonly start;
40
- private readonly app_name;
41
- private readonly default_title;
42
- private readonly icons;
43
- private readonly report;
44
- constructor(options: NotifierOptions);
45
- command(title: string, body: string, urgency: string, url: string | null, icon?: string | null, replace_id?: number | null, timeout?: number): string[];
46
- private locked;
47
- show(frame: DesktopNotification | Record<string, unknown>): Promise<void>;
48
- dismiss(frame: {
49
- key?: unknown;
50
- } | Record<string, unknown>): Promise<void>;
51
- cancel_all(): void;
52
- close(notification_id: number): Promise<void>;
53
- private open;
54
- }
1
+ export * from "@x-tech-laboratories/x-app-agent/desktop_notify";