@x-tech-laboratories/x-app-agent 0.0.0-stage → 0.134.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.
- package/dist/claude_stream.d.ts +22 -0
- package/dist/claude_stream.js +85 -0
- package/dist/client.d.ts +35 -0
- package/dist/client.js +169 -0
- package/dist/commands.d.ts +22 -0
- package/dist/commands.js +80 -0
- package/dist/config_watch.d.ts +15 -0
- package/dist/config_watch.js +75 -0
- package/dist/cron.d.ts +34 -0
- package/dist/cron.js +187 -0
- package/dist/desktop_notify.d.ts +54 -0
- package/dist/desktop_notify.js +229 -0
- package/dist/durations.d.ts +15 -0
- package/dist/durations.js +52 -0
- package/dist/firefox_bookmarks.d.ts +29 -0
- package/dist/firefox_bookmarks.js +147 -0
- package/dist/git.d.ts +37 -0
- package/dist/git.js +121 -0
- package/dist/github.d.ts +81 -0
- package/dist/github.js +185 -0
- package/dist/inhibit.d.ts +32 -0
- package/dist/inhibit.js +141 -0
- package/dist/keys.d.ts +26 -0
- package/dist/keys.js +161 -0
- package/dist/local_socket.d.ts +18 -0
- package/dist/local_socket.js +106 -0
- package/dist/log.d.ts +30 -0
- package/dist/log.js +85 -0
- package/dist/long_runs.d.ts +45 -0
- package/dist/long_runs.js +419 -0
- package/dist/plugin_folder.d.ts +24 -0
- package/dist/plugin_folder.js +107 -0
- package/dist/plugins.d.ts +138 -0
- package/dist/plugins.js +346 -0
- package/dist/programs.d.ts +60 -0
- package/dist/programs.js +237 -0
- package/dist/protocol.d.ts +172 -0
- package/dist/protocol.js +249 -0
- package/dist/python_text.d.ts +19 -0
- package/dist/python_text.js +363 -0
- package/dist/scheduled_notices.d.ts +21 -0
- package/dist/scheduled_notices.js +38 -0
- package/dist/server/agents/agent.d.ts +27 -0
- package/dist/server/agents/agent.js +16 -0
- package/dist/server/agents/connection.d.ts +63 -0
- package/dist/server/agents/connection.js +266 -0
- package/dist/server/agents/hub.d.ts +110 -0
- package/dist/server/agents/hub.js +327 -0
- package/dist/session.d.ts +61 -0
- package/dist/session.js +335 -0
- package/dist/sql.d.ts +27 -0
- package/dist/sql.js +61 -0
- package/dist/ssh_config.d.ts +12 -0
- package/dist/ssh_config.js +72 -0
- package/dist/stalls.d.ts +44 -0
- package/dist/stalls.js +176 -0
- package/dist/tasks.d.ts +17 -0
- package/dist/tasks.js +15 -0
- package/dist/wake.d.ts +14 -0
- package/dist/wake.js +88 -0
- package/dist/worktree_files.d.ts +20 -0
- package/dist/worktree_files.js +69 -0
- package/package.json +32 -4
- 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
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -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;
|
package/dist/commands.js
ADDED
|
@@ -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,15 @@
|
|
|
1
|
+
export interface ConfigWatchOptions {
|
|
2
|
+
path: string;
|
|
3
|
+
loaded_digest: () => string | null;
|
|
4
|
+
reload: () => Promise<unknown>;
|
|
5
|
+
interval_in_milliseconds?: number;
|
|
6
|
+
on_error?: (error: unknown) => void;
|
|
7
|
+
}
|
|
8
|
+
export interface ConfigWatch {
|
|
9
|
+
check(): Promise<boolean>;
|
|
10
|
+
stop(): void;
|
|
11
|
+
}
|
|
12
|
+
export declare const config_poll_in_milliseconds = 3000;
|
|
13
|
+
export declare function config_fingerprint(path: string): Promise<string | null>;
|
|
14
|
+
export declare function file_digest(path: string): Promise<string | null>;
|
|
15
|
+
export declare function watch_config(options: ConfigWatchOptions, start_timer?: boolean): ConfigWatch;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Reloads a config file when it changes. Every few seconds it reads a fingerprint of what the path points at (the real
|
|
2
|
+
// path through any symlink, its inode, change time and size), so a re-pointed symlink or a replaced file counts as a
|
|
3
|
+
// change; it waits one more check for the fingerprint to hold still, and reloads only when the content's hash differs
|
|
4
|
+
// from what was last loaded.
|
|
5
|
+
// ── Imports ──────────────────────────────────────────────────────────────────
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { readFile, realpath, stat } from "node:fs/promises";
|
|
8
|
+
// ── Settings ─────────────────────────────────────────────────────────────────
|
|
9
|
+
export const config_poll_in_milliseconds = 3000;
|
|
10
|
+
// ── Reading the file ─────────────────────────────────────────────────────────
|
|
11
|
+
// What the path points at and when it last changed, or null when it cannot be read.
|
|
12
|
+
export async function config_fingerprint(path) {
|
|
13
|
+
try {
|
|
14
|
+
const real = await realpath(path);
|
|
15
|
+
const info = await stat(real, { bigint: true });
|
|
16
|
+
return JSON.stringify([real, String(info.ino), String(info.mtimeNs), String(info.size)]);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
// The sha256 of the file's content in hex, or null when it cannot be read.
|
|
23
|
+
export async function file_digest(path) {
|
|
24
|
+
try {
|
|
25
|
+
return createHash("sha256").update(await readFile(path)).digest("hex");
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
// ── Watching ─────────────────────────────────────────────────────────────────
|
|
32
|
+
// Starts checking on a timer; `check` can also be called by hand, as a test does.
|
|
33
|
+
export function watch_config(options, start_timer = true) {
|
|
34
|
+
let seen = null;
|
|
35
|
+
let pending = null;
|
|
36
|
+
let timer;
|
|
37
|
+
let stopped = false;
|
|
38
|
+
const check = async () => {
|
|
39
|
+
const current = await config_fingerprint(options.path);
|
|
40
|
+
if (current === null || current === seen) {
|
|
41
|
+
pending = null;
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
if (current !== pending) {
|
|
45
|
+
pending = current;
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
seen = current;
|
|
49
|
+
pending = null;
|
|
50
|
+
if ((await file_digest(options.path)) === options.loaded_digest())
|
|
51
|
+
return false;
|
|
52
|
+
try {
|
|
53
|
+
await options.reload();
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
options.on_error?.(error);
|
|
57
|
+
}
|
|
58
|
+
return true;
|
|
59
|
+
};
|
|
60
|
+
const schedule = () => {
|
|
61
|
+
if (stopped)
|
|
62
|
+
return;
|
|
63
|
+
timer = setTimeout(() => void check().finally(schedule), options.interval_in_milliseconds ?? config_poll_in_milliseconds);
|
|
64
|
+
timer.unref?.();
|
|
65
|
+
};
|
|
66
|
+
if (start_timer)
|
|
67
|
+
schedule();
|
|
68
|
+
return {
|
|
69
|
+
check,
|
|
70
|
+
stop: () => {
|
|
71
|
+
stopped = true;
|
|
72
|
+
clearTimeout(timer);
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
package/dist/cron.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export declare class CronSchedule {
|
|
2
|
+
readonly expression: string;
|
|
3
|
+
readonly minutes: ReadonlySet<number>;
|
|
4
|
+
readonly hours: ReadonlySet<number>;
|
|
5
|
+
readonly days: ReadonlySet<number>;
|
|
6
|
+
readonly months: ReadonlySet<number>;
|
|
7
|
+
readonly weekdays: ReadonlySet<number>;
|
|
8
|
+
readonly any_day: boolean;
|
|
9
|
+
readonly any_weekday: boolean;
|
|
10
|
+
private constructor();
|
|
11
|
+
static parse(expression: string): CronSchedule;
|
|
12
|
+
matches_day(day: Date): boolean;
|
|
13
|
+
next_after(moment: Date): Date | null;
|
|
14
|
+
}
|
|
15
|
+
export type IntervalUnit = "minutes" | "hours" | "days";
|
|
16
|
+
export type RunSchedule = {
|
|
17
|
+
kind: "every";
|
|
18
|
+
every: number;
|
|
19
|
+
unit: IntervalUnit;
|
|
20
|
+
} | {
|
|
21
|
+
kind: "at";
|
|
22
|
+
time: string;
|
|
23
|
+
weekdays: number[];
|
|
24
|
+
};
|
|
25
|
+
export interface ScheduleLimits {
|
|
26
|
+
min_minutes?: number;
|
|
27
|
+
}
|
|
28
|
+
export declare function checked_schedule(given: unknown, limits?: ScheduleLimits): RunSchedule;
|
|
29
|
+
export declare function describe_schedule(schedule: RunSchedule): string;
|
|
30
|
+
export declare function schedule_cron(schedule: Extract<RunSchedule, {
|
|
31
|
+
kind: "at";
|
|
32
|
+
}>): CronSchedule;
|
|
33
|
+
export declare function next_due(schedule: RunSchedule, since: number): number;
|
|
34
|
+
export declare function is_due(schedule: RunSchedule, since: number, now: number): boolean;
|