@x-tech-laboratories/x-app-agent 0.0.0-stage → 0.130.0

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 (44) hide show
  1. package/dist/claude_stream.d.ts +22 -0
  2. package/dist/claude_stream.js +85 -0
  3. package/dist/client.d.ts +35 -0
  4. package/dist/client.js +169 -0
  5. package/dist/commands.d.ts +22 -0
  6. package/dist/commands.js +80 -0
  7. package/dist/desktop_notify.d.ts +54 -0
  8. package/dist/desktop_notify.js +229 -0
  9. package/dist/durations.d.ts +15 -0
  10. package/dist/durations.js +52 -0
  11. package/dist/firefox_bookmarks.d.ts +29 -0
  12. package/dist/firefox_bookmarks.js +147 -0
  13. package/dist/git.d.ts +37 -0
  14. package/dist/git.js +121 -0
  15. package/dist/github.d.ts +81 -0
  16. package/dist/github.js +185 -0
  17. package/dist/inhibit.d.ts +32 -0
  18. package/dist/inhibit.js +141 -0
  19. package/dist/keys.d.ts +26 -0
  20. package/dist/keys.js +161 -0
  21. package/dist/local_socket.d.ts +18 -0
  22. package/dist/local_socket.js +106 -0
  23. package/dist/long_runs.d.ts +45 -0
  24. package/dist/long_runs.js +419 -0
  25. package/dist/programs.d.ts +60 -0
  26. package/dist/programs.js +237 -0
  27. package/dist/protocol.d.ts +172 -0
  28. package/dist/protocol.js +249 -0
  29. package/dist/scheduled_notices.d.ts +21 -0
  30. package/dist/scheduled_notices.js +38 -0
  31. package/dist/session.d.ts +61 -0
  32. package/dist/session.js +335 -0
  33. package/dist/ssh_config.d.ts +12 -0
  34. package/dist/ssh_config.js +72 -0
  35. package/dist/stalls.d.ts +44 -0
  36. package/dist/stalls.js +176 -0
  37. package/dist/tasks.d.ts +17 -0
  38. package/dist/tasks.js +15 -0
  39. package/dist/wake.d.ts +14 -0
  40. package/dist/wake.js +88 -0
  41. package/dist/worktree_files.d.ts +20 -0
  42. package/dist/worktree_files.js +69 -0
  43. package/package.json +30 -4
  44. package/README.md +0 -3
@@ -0,0 +1,22 @@
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;
@@ -0,0 +1,85 @@
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
+ }
@@ -0,0 +1,35 @@
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>;
package/dist/client.js ADDED
@@ -0,0 +1,169 @@
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
+ }
@@ -0,0 +1,22 @@
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;
@@ -0,0 +1,80 @@
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
+ }
@@ -0,0 +1,54 @@
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
+ }