@x-tech-laboratories/x-app-agent 0.130.0 → 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.
@@ -0,0 +1,266 @@
1
+ // One connected agent, as the server sees it: sends it requests and matches each reply by id, and turns its streamed
2
+ // output back into a readable stream, granting the agent more credit only as the reader takes what has come. For an agent
3
+ // that asked for signed messages, it wraps each message it sends with a counter and the server key's signature.
4
+ import { Readable } from "node:stream";
5
+ import { server_message_text, sign_text } from "../../keys.js";
6
+ import { clip_text, decode_chunk, encode_message, encode_signed_message, is_agent_message, most_runs_in_reply, parse_agent_message, parse_long_run, parse_long_run_poll, parse_long_runs, parse_run_result, } from "../../protocol.js";
7
+ import { AgentError } from "./agent.js";
8
+ const socket_open = 1;
9
+ // A run's reply may come this long after its own timeout, which the agent enforces, before the server gives up.
10
+ const run_reply_slack_in_milliseconds = 30_000;
11
+ // The error an agent gives for a failed request is cut to this many characters.
12
+ const most_error_length = 16 * 1024;
13
+ // ── Incoming streams ─────────────────────────────────────────────────────────
14
+ // A stream's output arriving from the agent, readable as it comes.
15
+ class IncomingStream {
16
+ stdout;
17
+ done;
18
+ id;
19
+ connection;
20
+ window;
21
+ // Credit the agent still holds: bytes it may send before it hears from us again.
22
+ outstanding;
23
+ reader_full = false;
24
+ result = null;
25
+ stdout_closed = false;
26
+ settle;
27
+ constructor(id, connection, window) {
28
+ this.id = id;
29
+ this.connection = connection;
30
+ this.window = window;
31
+ this.outstanding = window;
32
+ this.done = new Promise((resolve) => (this.settle = resolve));
33
+ this.stdout = new Readable({
34
+ read: () => {
35
+ this.reader_full = false;
36
+ this.grant();
37
+ },
38
+ destroy: (error, callback) => {
39
+ if (this.result === null)
40
+ this.connection.send({ type: "cancel", id: this.id });
41
+ callback(error);
42
+ },
43
+ });
44
+ this.stdout.on("close", () => {
45
+ this.stdout_closed = true;
46
+ this.settle_when_done();
47
+ });
48
+ }
49
+ receive(data) {
50
+ this.outstanding -= data.length;
51
+ if (this.result !== null || this.stdout.destroyed)
52
+ return;
53
+ if (!this.stdout.push(data))
54
+ this.reader_full = true;
55
+ this.grant();
56
+ }
57
+ end(result) {
58
+ if (this.result !== null)
59
+ return;
60
+ this.result = result;
61
+ if (!this.stdout.destroyed)
62
+ this.stdout.push(null);
63
+ this.settle_when_done();
64
+ }
65
+ stop() {
66
+ this.stdout.destroy();
67
+ }
68
+ // Tops the agent's credit back up once half of it has been read.
69
+ grant() {
70
+ if (this.reader_full || this.result !== null || this.outstanding > this.window / 2)
71
+ return;
72
+ this.connection.send({ type: "credit", id: this.id, bytes: this.window - this.outstanding });
73
+ this.outstanding = this.window;
74
+ }
75
+ settle_when_done() {
76
+ if (this.result !== null && this.stdout_closed)
77
+ this.settle(this.result);
78
+ }
79
+ }
80
+ // ── Connection ───────────────────────────────────────────────────────────────
81
+ export class AgentConnection {
82
+ host;
83
+ hello;
84
+ connected_epoch = Math.floor(Date.now() / 1000);
85
+ // Takes the app's own messages from the agent that are not replies.
86
+ on_message = null;
87
+ socket;
88
+ app;
89
+ options;
90
+ pending = new Map();
91
+ streams = new Map();
92
+ next_id = 1;
93
+ last_heard = Date.now();
94
+ heartbeat;
95
+ closed_reason = null;
96
+ signing;
97
+ // The counter of the last signed message sent.
98
+ counter = 0;
99
+ constructor(socket, app, host, hello, options, signing = null) {
100
+ this.socket = socket;
101
+ this.signing = signing;
102
+ this.app = app;
103
+ this.host = host;
104
+ this.hello = hello;
105
+ this.options = options;
106
+ this.heartbeat = setInterval(() => this.beat(), options.heartbeat_in_milliseconds);
107
+ this.heartbeat.unref();
108
+ }
109
+ get is_open() {
110
+ return this.closed_reason === null;
111
+ }
112
+ // Whether every message to this agent goes signed with the server's key.
113
+ get signs_messages() {
114
+ return this.signing !== null;
115
+ }
116
+ // ── Agent ────────────────────────────────────────────────────────────────
117
+ async run(task, options) {
118
+ try {
119
+ const timeout = options.timeout_in_seconds * 1000 + run_reply_slack_in_milliseconds;
120
+ const reply = await this.send_request("run", { task, stdin: options.stdin ?? null, timeout_in_seconds: options.timeout_in_seconds }, timeout);
121
+ return parse_run_result(reply) ?? { exit_code: -1, stdout: "", stderr: this.malformed("run").message };
122
+ }
123
+ catch (error) {
124
+ return { exit_code: -1, stdout: "", stderr: error.message };
125
+ }
126
+ }
127
+ stream(task, options = {}) {
128
+ return this.open_stream((id, window) => ({ type: "stream", id, task, stdin: options.stdin ?? null, window }));
129
+ }
130
+ async start(run_id, task, options = {}) {
131
+ return parse_long_run(await this.send_request("start", { run_id, task, stdin: options.stdin ?? null })) ?? this.reject_malformed("start");
132
+ }
133
+ async poll(run_id, offset) {
134
+ return parse_long_run_poll(await this.send_request("poll", { run_id, offset })) ?? this.reject_malformed("poll");
135
+ }
136
+ attach(run_id, offset) {
137
+ return this.open_stream((id, window) => ({ type: "attach", id, run_id, offset, window }));
138
+ }
139
+ async stop(run_id) {
140
+ return parse_long_run(await this.send_request("stop", { run_id })) ?? this.reject_malformed("stop");
141
+ }
142
+ async forget(run_id) {
143
+ await this.send_request("forget", { run_id });
144
+ }
145
+ async runs() {
146
+ return parse_long_runs(await this.send_request("runs", {}), most_runs_in_reply) ?? this.reject_malformed("runs");
147
+ }
148
+ request(type, body = {}) {
149
+ return this.send_request(type, body);
150
+ }
151
+ // ── Socket ───────────────────────────────────────────────────────────────
152
+ send(message) {
153
+ if (!this.is_open || this.socket.readyState !== socket_open)
154
+ return;
155
+ const text = encode_message(message, this.app);
156
+ this.socket.send(this.signing === null ? text : this.seal(this.signing, text));
157
+ }
158
+ // The message's exact text wrapped with the next counter and the server's signature over this connection, the counter and that text.
159
+ seal(signing, text) {
160
+ this.counter++;
161
+ const signed_text = server_message_text(this.app.name, this.host, signing.server_nonce, signing.agent_nonce, this.counter, text);
162
+ return encode_signed_message(text, this.counter, sign_text(signing.server_key, signed_text));
163
+ }
164
+ // Handles one frame from the agent after its hello.
165
+ receive(data, is_binary) {
166
+ this.last_heard = Date.now();
167
+ if (is_binary) {
168
+ const chunk = decode_chunk(data);
169
+ if (chunk !== null)
170
+ this.streams.get(chunk.id)?.receive(chunk.data);
171
+ return;
172
+ }
173
+ const message = parse_agent_message(data.toString("utf8"), this.app);
174
+ if (message === null)
175
+ return;
176
+ if (!is_agent_message(message)) {
177
+ this.on_message?.(message);
178
+ return;
179
+ }
180
+ switch (message.type) {
181
+ case "ping":
182
+ this.send({ type: "pong", epoch_ms: message.epoch_ms });
183
+ return;
184
+ case "reply":
185
+ case "failed": {
186
+ const pending = this.pending.get(message.id);
187
+ if (pending === undefined)
188
+ return;
189
+ this.pending.delete(message.id);
190
+ clearTimeout(pending.timer);
191
+ // The agent answered that the request failed, which is not the host being out of reach.
192
+ if (message.type === "reply")
193
+ pending.resolve(message.value);
194
+ else
195
+ pending.reject(new AgentError(clip_text(message.error, most_error_length)));
196
+ return;
197
+ }
198
+ case "stream_end":
199
+ this.streams.get(message.id)?.end({ exit_code: message.exit_code, stderr: message.stderr });
200
+ this.streams.delete(message.id);
201
+ return;
202
+ default:
203
+ return;
204
+ }
205
+ }
206
+ // Fails what was waiting and ends each stream; the agent's long runs carry on.
207
+ closed(reason) {
208
+ if (this.closed_reason !== null)
209
+ return;
210
+ this.closed_reason = reason;
211
+ clearInterval(this.heartbeat);
212
+ for (const pending of this.pending.values()) {
213
+ clearTimeout(pending.timer);
214
+ pending.reject(new AgentError(reason, true));
215
+ }
216
+ this.pending.clear();
217
+ for (const stream of this.streams.values())
218
+ stream.end({ exit_code: -1, stderr: reason });
219
+ this.streams.clear();
220
+ }
221
+ close(code, reason) {
222
+ this.socket.close(code, reason);
223
+ this.closed(reason);
224
+ }
225
+ // ── Helpers ──────────────────────────────────────────────────────────────
226
+ // The error for a reply that is not the shape its request promises, which the caller may try again later.
227
+ malformed(type) {
228
+ return new AgentError(`The agent on ${this.host} answered a ${type} request with a malformed reply.`, true);
229
+ }
230
+ reject_malformed(type) {
231
+ throw this.malformed(type);
232
+ }
233
+ send_request(type, body, timeout = this.options.request_timeout_in_milliseconds) {
234
+ if (!this.is_open)
235
+ return Promise.reject(new AgentError(this.closed_reason, true));
236
+ const id = `r${this.next_id++}`;
237
+ return new Promise((resolve, reject) => {
238
+ const timer = setTimeout(() => {
239
+ this.pending.delete(id);
240
+ reject(new AgentError(`The agent on ${this.host} did not answer within ${Math.round(timeout / 1000)}s.`, true));
241
+ }, timeout);
242
+ this.pending.set(id, { resolve: resolve, reject, timer });
243
+ this.send({ ...body, type, id });
244
+ });
245
+ }
246
+ open_stream(message) {
247
+ const id = `s${this.next_id++}`;
248
+ const stream = new IncomingStream(id, this, this.options.window_in_bytes);
249
+ if (!this.is_open) {
250
+ stream.end({ exit_code: -1, stderr: this.closed_reason });
251
+ }
252
+ else {
253
+ this.streams.set(id, stream);
254
+ this.send(message(id, this.options.window_in_bytes));
255
+ }
256
+ return { stdout: stream.stdout, done: stream.done, stop: () => stream.stop() };
257
+ }
258
+ // Pings the agent, or drops one that has been silent for three beats.
259
+ beat() {
260
+ if (Date.now() - this.last_heard > 3 * this.options.heartbeat_in_milliseconds) {
261
+ this.close(4008, `The agent on ${this.host} stopped answering.`);
262
+ return;
263
+ }
264
+ this.send({ type: "ping", epoch_ms: Date.now() });
265
+ }
266
+ }
@@ -0,0 +1,110 @@
1
+ import type { KeyObject } from "node:crypto";
2
+ import { EventEmitter } from "node:events";
3
+ import type { IncomingHttpHeaders } from "node:http";
4
+ import { type AgentApp, type AppMessage, type LongRun, type LongRunPoll, type RunResult } from "../../protocol.ts";
5
+ import { type Agent, type AgentRunOptions, type AgentStreamOptions, type CommandStream } from "./agent.ts";
6
+ import { AgentConnection, type ConnectionOptions, type ServerSocket } from "./connection.ts";
7
+ export interface AgentTokenLookup {
8
+ host_for(token: string): string | null;
9
+ seen?(host: string): void;
10
+ }
11
+ export interface HubOptions<Task> {
12
+ app: AgentApp<Task>;
13
+ local?: {
14
+ host: string;
15
+ agent: Agent<Task>;
16
+ };
17
+ tokens?: AgentTokenLookup;
18
+ on_message?: (host: string, message: AppMessage, connection: AgentConnection<Task>) => void;
19
+ hello_timeout_in_milliseconds?: number;
20
+ most_pending_logins?: number;
21
+ most_pending_logins_per_address?: number;
22
+ connection?: Partial<ConnectionOptions>;
23
+ server_key?: KeyObject | null;
24
+ }
25
+ export interface AgentStatus {
26
+ host: string;
27
+ reported_host: string;
28
+ agent_version: string;
29
+ connected_epoch: number;
30
+ built_in: boolean;
31
+ login: AgentLogin | null;
32
+ signed_messages: boolean;
33
+ runs: LongRun[];
34
+ }
35
+ export type AgentLogin = "token" | "key";
36
+ export type Admission = {
37
+ host: string;
38
+ login: AgentLogin;
39
+ } | {
40
+ error: string;
41
+ reason: string;
42
+ };
43
+ export declare const admission_refused = "This agent cannot log in here.";
44
+ export declare const too_many_pending_logins = "Too many agents are logging in; try again shortly.";
45
+ export declare const pre_login_message_limit_in_bytes: number;
46
+ interface HubEvents {
47
+ connect: [status: AgentStatus];
48
+ disconnect: [host: string];
49
+ }
50
+ export declare const close_codes: {
51
+ readonly protocol: 4002;
52
+ readonly replaced: 4003;
53
+ readonly revoked: 4004;
54
+ readonly no_hello: 4005;
55
+ readonly bad_key: 4006;
56
+ readonly not_hello: 4007;
57
+ readonly too_large: 1009;
58
+ readonly bad_agent_nonce: 4010;
59
+ };
60
+ export interface AcceptHooks {
61
+ on_login?: () => void;
62
+ }
63
+ export declare class AgentHub<Task> extends EventEmitter<HubEvents> {
64
+ readonly app: AgentApp<Task>;
65
+ private readonly local;
66
+ private readonly tokens;
67
+ private readonly on_message;
68
+ private readonly hello_timeout;
69
+ private readonly most_pending_logins;
70
+ private readonly most_pending_logins_per_address;
71
+ private pending_logins;
72
+ private readonly pending_logins_by_address;
73
+ private readonly connection_options;
74
+ private readonly connections;
75
+ private readonly logins;
76
+ private agent_keys;
77
+ private readonly server_key;
78
+ constructor(options: HubOptions<Task>);
79
+ server_public_line(comment?: string): string | null;
80
+ server_key_fingerprint(): string | null;
81
+ set_local_host(host: string): void;
82
+ set_agent_keys(lines: Map<string, string>): void;
83
+ has_agent_key(host: string): boolean;
84
+ declared_hosts(): string[];
85
+ disconnect_token_login(host: string, reason: string): void;
86
+ authenticate(authorization: string | undefined): string | null;
87
+ admit(headers: IncomingHttpHeaders): Admission;
88
+ hold_pending_login(address: string): (() => void) | null;
89
+ accept(socket: ServerSocket, host: string, login: AgentLogin, hooks?: AcceptHooks): void;
90
+ private challenge;
91
+ private proves_key;
92
+ disconnect(host: string, code?: number, reason?: string): void;
93
+ close(): void;
94
+ is_connected(host: string): boolean;
95
+ status(host: string): AgentStatus | null;
96
+ statuses(): AgentStatus[];
97
+ agent(host: string): Agent<Task> | null;
98
+ run(host: string, task: Task, options: AgentRunOptions): Promise<RunResult>;
99
+ stream(host: string, task: Task, options?: AgentStreamOptions): CommandStream;
100
+ start(host: string, run_id: string, task: Task, options?: AgentStreamOptions): Promise<LongRun>;
101
+ poll(host: string, run_id: string, offset: number): Promise<LongRunPoll>;
102
+ attach(host: string, run_id: string, offset: number): CommandStream;
103
+ stop(host: string, run_id: string): Promise<LongRun>;
104
+ forget(host: string, run_id: string): Promise<void>;
105
+ runs(host: string): Promise<LongRun[]>;
106
+ request(host: string, type: string, body?: Record<string, unknown>): Promise<unknown>;
107
+ private require;
108
+ private status_of;
109
+ }
110
+ export {};