@parcha/agentrun-client 0.0.0-placeholder → 0.1.0-beta.32

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/errors.js ADDED
@@ -0,0 +1,88 @@
1
+ /** What every error of this client is: `kind` says which outcome it is. */
2
+ export class AgentRunError extends Error {
3
+ }
4
+ /** The server answered and refused: a 4xx or 5xx other than 401, 403 and 501; a redirect it would take the key along
5
+ * to follow (`code` `redirect`); or an answer this client cannot read (`code` `bad_answer`). */
6
+ export class AgentRunRefused extends AgentRunError {
7
+ kind = "refused";
8
+ status;
9
+ code;
10
+ error;
11
+ /** How long the server asked to be left before the same request again (its Retry-After), in milliseconds. */
12
+ retryAfterMs;
13
+ constructor(route, status, code, error, why, retryAfterMs) {
14
+ super(why ?? `The server refused ${route}: ${status}${code ? ` ${code}` : ""}.`);
15
+ this.name = "AgentRunRefused";
16
+ this.status = status;
17
+ this.code = code;
18
+ this.error = error;
19
+ this.retryAfterMs = retryAfterMs;
20
+ }
21
+ }
22
+ /** No API key, one that is not a valid header value (refused before any request), or one the server refused (401, 403). */
23
+ export class AgentRunAuthError extends AgentRunError {
24
+ kind = "auth";
25
+ reason;
26
+ status;
27
+ code;
28
+ error;
29
+ constructor(reason, message, answer) {
30
+ super(message);
31
+ this.name = "AgentRunAuthError";
32
+ this.reason = reason;
33
+ this.status = answer?.status;
34
+ this.code = answer?.code;
35
+ this.error = answer?.error;
36
+ }
37
+ }
38
+ /** The server does not offer this operation here (501 `unsupported_here`); `capability` names what is off. */
39
+ export class AgentRunUnsupported extends AgentRunError {
40
+ kind = "unsupported";
41
+ by = "server";
42
+ capability;
43
+ status;
44
+ code;
45
+ error;
46
+ constructor(route, status, code, error) {
47
+ const capability = typeof error?.capability === "string" ? error.capability : undefined;
48
+ super(`The server does not offer ${route} here${capability ? ` (${capability} is off)` : ""}.`);
49
+ this.name = "AgentRunUnsupported";
50
+ this.capability = capability;
51
+ this.status = status;
52
+ this.code = code;
53
+ this.error = error;
54
+ }
55
+ }
56
+ /** The server could not be reached, or stopped answering. `cause` is the failure's code (ECONNREFUSED, timeout), never
57
+ * its message, which can quote a header. */
58
+ export class AgentRunUnreachable extends AgentRunError {
59
+ kind = "unreachable";
60
+ cause;
61
+ constructor(baseUrl, cause) {
62
+ super(`Cannot reach the server at ${baseUrl} (${cause}).`);
63
+ this.name = "AgentRunUnreachable";
64
+ this.cause = cause;
65
+ }
66
+ }
67
+ /** The call was wrong before anything was sent: a bad argument, base URL or option. */
68
+ export class AgentRunUsage extends AgentRunError {
69
+ kind = "usage";
70
+ reason;
71
+ constructor(reason) {
72
+ super(reason);
73
+ this.name = "AgentRunUsage";
74
+ this.reason = reason;
75
+ }
76
+ }
77
+ /** `runs.wait` passed its `timeoutMs`; the run goes on. `run` is the run as last read, when it was. */
78
+ export class AgentRunTimeout extends AgentRunError {
79
+ kind = "late";
80
+ runId;
81
+ run;
82
+ constructor(runId, timeoutMs, run) {
83
+ super(`Run ${runId} did not end or wait on a person within ${timeoutMs} ms; it goes on.`);
84
+ this.name = "AgentRunTimeout";
85
+ this.runId = runId;
86
+ this.run = run;
87
+ }
88
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ /** What the client's `send` takes: a request already checked, its path under the base URL. */
2
+ export interface Exchange {
3
+ method: string;
4
+ path: string;
5
+ route: string;
6
+ headers?: Record<string, string>;
7
+ body?: BodyInit;
8
+ retryable: boolean;
9
+ signal?: AbortSignal;
10
+ timeoutMs?: number;
11
+ /** When the whole call must end (a wait's timeout): past it, `send` throws LATE. */
12
+ deadline?: number;
13
+ /** The body carried a secret: a refusal keeps only its code. */
14
+ secret?: boolean;
15
+ /** The secret body's values: cut from a refusal before its code is read, as the API key is. */
16
+ secrets?: readonly string[];
17
+ /** The success's body is left to the caller, unread (a stream, a download asked for as a Response); else it is read
18
+ * whole inside the exchange, so a body cut midway is tried again or refused as any dropped connection is. */
19
+ streamed?: boolean;
20
+ }
21
+ /** Thrown by `send` once an exchange's deadline passed. */
22
+ export declare const LATE: unique symbol;
23
+ export declare const BAD_HEADER: RegExp;
24
+ /** The longest Retry-After waited out: past it a GET is not tried again (the call fails rather than hang), and a
25
+ * stream's reconnect waits this long. */
26
+ export declare const MAX_RETRY_AFTER_MS = 60000;
27
+ /** A count of milliseconds as timers take it: a whole number, at least 1 (AbortSignal.timeout throws on a fraction). */
28
+ export declare const wholeMs: (ms: number) => number;
29
+ /** The wait before try `tries + 1`: doubling up to its cap, and never under the server's own (`floor`). */
30
+ export declare const backoff: (tries: number, floor?: number) => number;
31
+ /** Waits `ms`, or rejects with the signal's reason once it aborts. */
32
+ export declare function pause(ms: number, signal?: AbortSignal): Promise<void>;
33
+ /** A path argument checked and encoded: whole, or, for a file path, segment by segment. One that fetch or the server
34
+ * would read as another route (empty, `.`, `..`, plain or encoded, or an encoded slash in a file path) is refused. */
35
+ export declare function segmentOf(value: unknown, name: string, multiSegment: boolean): string;
package/dist/http.js ADDED
@@ -0,0 +1,40 @@
1
+ // What the client and its live calls (live.ts) share: the request they hand to the client's `send`, timers, backoff, and
2
+ // the check of a path argument.
3
+ import { AgentRunUsage } from "./errors.js";
4
+ /** Thrown by `send` once an exchange's deadline passed. */
5
+ export const LATE = Symbol("late");
6
+ // A header value fetch takes: no line break or other control character, nothing outside Latin-1.
7
+ export const BAD_HEADER = /[\0-\x08\x0a-\x1f\x7f]|[^\0-\xff]/;
8
+ const BACKOFF_MS = 500;
9
+ /** The longest Retry-After waited out: past it a GET is not tried again (the call fails rather than hang), and a
10
+ * stream's reconnect waits this long. */
11
+ export const MAX_RETRY_AFTER_MS = 60_000;
12
+ const MAX_BACKOFF_MS = 30_000;
13
+ /** A count of milliseconds as timers take it: a whole number, at least 1 (AbortSignal.timeout throws on a fraction). */
14
+ export const wholeMs = (ms) => Math.max(1, Math.ceil(ms));
15
+ /** The wait before try `tries + 1`: doubling up to its cap, and never under the server's own (`floor`). */
16
+ export const backoff = (tries, floor = 0) => Math.max(floor, Math.min(MAX_BACKOFF_MS, BACKOFF_MS * 2 ** (tries - 1)));
17
+ /** Waits `ms`, or rejects with the signal's reason once it aborts. */
18
+ export function pause(ms, signal) {
19
+ return new Promise((resolve, reject) => {
20
+ if (signal?.aborted)
21
+ return reject(signal.reason);
22
+ const timer = setTimeout(() => (signal?.removeEventListener("abort", stop), resolve()), wholeMs(ms));
23
+ const stop = () => (clearTimeout(timer), reject(signal.reason));
24
+ signal?.addEventListener("abort", stop, { once: true });
25
+ });
26
+ }
27
+ /** A path argument checked and encoded: whole, or, for a file path, segment by segment. One that fetch or the server
28
+ * would read as another route (empty, `.`, `..`, plain or encoded, or an encoded slash in a file path) is refused. */
29
+ export function segmentOf(value, name, multiSegment) {
30
+ if (typeof value !== "string" || value === "")
31
+ throw new AgentRunUsage(`${name} must be a string that is not empty.`);
32
+ const segments = value.split("/");
33
+ if (segments.some((segment) => [".", ".."].includes(segment.replace(/%2e/gi, "."))))
34
+ throw new AgentRunUsage(`${name} may not hold a . or .. path segment, plain or encoded.`);
35
+ if (!multiSegment)
36
+ return encodeURIComponent(value);
37
+ if (segments.some((segment) => segment === "" || /%2f/i.test(segment)))
38
+ throw new AgentRunUsage(`${name} may not hold an empty segment or an encoded slash.`);
39
+ return segments.map(encodeURIComponent).join("/");
40
+ }
@@ -0,0 +1,5 @@
1
+ export { AgentRun, type ClientOptions } from "./client.js";
2
+ export { AgentRunAuthError, AgentRunError, AgentRunRefused, AgentRunTimeout, AgentRunUnreachable, AgentRunUnsupported, AgentRunUsage, type ServerError } from "./errors.js";
3
+ export type { FollowOptions, WaitOptions } from "./live.js";
4
+ export type * from "./operations.generated.js";
5
+ export type { AnswerKind, BodyOptions, DownloadOptions, Operation, RawBody, RequestOptions, Tagged } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ // @parcha/agentrun-client: a typed client for an AgentRun server.
2
+ export { AgentRun } from "./client.js";
3
+ export { AgentRunAuthError, AgentRunError, AgentRunRefused, AgentRunTimeout, AgentRunUnreachable, AgentRunUnsupported, AgentRunUsage } from "./errors.js";
package/dist/live.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { type Exchange } from "./http.js";
2
+ import type { Run, TimelinePage } from "./operations.generated.js";
3
+ type Send = (x: Exchange) => Promise<Response>;
4
+ export interface WaitOptions {
5
+ /** Stop waiting after this many milliseconds: AgentRunTimeout, and the run goes on. Default: no limit. */
6
+ timeoutMs?: number;
7
+ signal?: AbortSignal;
8
+ }
9
+ export interface FollowOptions {
10
+ /** How long the stream may stay silent, waiting on the server, before it counts as a dropped connection and is
11
+ * reconnected (default 45000: three of its 15 s keepalives missed). */
12
+ idleMs?: number;
13
+ /** Start after this change number (the timeline's `next_after`). */
14
+ after?: number;
15
+ /** Resume after this event id, as a reconnect does; wins over `after`. */
16
+ lastEventId?: string;
17
+ signal?: AbortSignal;
18
+ }
19
+ /** Long-polls the timeline from change to change and reads the run when a page says it ended or waits on a person. */
20
+ export declare function waitRun(send: Send, runId: string, options?: WaitOptions): Promise<Run>;
21
+ /** The timeline's event stream, each `rows` event's page as the server sent it (its rows, its drops, `reset` when the
22
+ * rows held go first). A dropped connection, an `end` with `reason: reconnect`, or a stream silent past three
23
+ * keepalives reconnects with Last-Event-ID; tries that get no event back off, never under the server's `retry`, and
24
+ * give up after a few in a row (AgentRunUnreachable). It ends at the server's `end` with `reason: terminal`. */
25
+ export declare function followRun(send: Send, baseUrl: string, runId: string, options?: FollowOptions): AsyncGenerator<TimelinePage, void, undefined>;
26
+ export {};
package/dist/live.js ADDED
@@ -0,0 +1,236 @@
1
+ // `runs.wait` and `runs.follow`: a run until it ends or waits on a person, and its timeline as it changes. Hand-written
2
+ // over the timeline route's two forms, the long-polled JSON page and the event stream, as the CLI's follow.mjs is.
3
+ import { backoff, LATE, MAX_RETRY_AFTER_MS, pause, segmentOf, wholeMs } from "./http.js";
4
+ import { AgentRunError, AgentRunRefused, AgentRunTimeout, AgentRunUnreachable, AgentRunUsage } from "./errors.js";
5
+ const TERMINAL = new Set(["completed", "failed", "cancelled"]);
6
+ // What moves only once a person acts: input_required (a question, the spend cap, a stopped turn) and a workflow's paused.
7
+ const PERSON = new Set(["input_required", "paused"]);
8
+ const MAX_WAIT_MS = 25_000; // the route's wait_ms maximum
9
+ const IDLE_MS = 45_000; // three of the stream's 15 s keepalives missed: the connection is gone
10
+ const LAST_READ_MS = 1_000; // the read of the run once a wait's time is up
11
+ const RETRIES = 5; // tries in a row that get no event before follow gives up
12
+ const TIMELINE = "GET /runs/{run_id}/timeline";
13
+ const RUN = "GET /runs/{run_id}";
14
+ /** GET `path` as a JSON object, retried as any GET is, ending by `deadline`. */
15
+ async function getJson(send, path, route, deadline, signal) {
16
+ const response = await send({ method: "GET", path, route, retryable: true, signal, deadline, timeoutMs: MAX_WAIT_MS + IDLE_MS });
17
+ const text = await response.text();
18
+ try {
19
+ const value = JSON.parse(text);
20
+ if (value && typeof value === "object" && !Array.isArray(value))
21
+ return value;
22
+ }
23
+ catch {
24
+ // refused below
25
+ }
26
+ throw new AgentRunRefused(route, response.status, "bad_answer", undefined, `The server's answer to ${route} is not a JSON object.`);
27
+ }
28
+ /** Long-polls the timeline from change to change and reads the run when a page says it ended or waits on a person. */
29
+ export async function waitRun(send, runId, options = {}) {
30
+ const id = segmentOf(runId, "runId", false);
31
+ const { timeoutMs, signal } = options;
32
+ if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs <= 0))
33
+ throw new AgentRunUsage("timeoutMs must be a number of milliseconds above 0.");
34
+ const deadline = timeoutMs === undefined ? Infinity : Date.now() + wholeMs(timeoutMs);
35
+ let after = 0;
36
+ let last;
37
+ const late = async () => {
38
+ try {
39
+ last = await getJson(send, `/runs/${id}`, RUN, Date.now() + LAST_READ_MS, signal);
40
+ }
41
+ catch (error) {
42
+ if (error !== LATE && !(error instanceof AgentRunUnreachable))
43
+ throw error;
44
+ }
45
+ throw new AgentRunTimeout(runId, wholeMs(timeoutMs), last);
46
+ };
47
+ const ended = (status, final) => (TERMINAL.has(status) && final) || PERSON.has(status);
48
+ try {
49
+ for (let first = true;; first = false) {
50
+ const left = deadline - Date.now();
51
+ if (left <= 0)
52
+ return await late();
53
+ const waitMs = first ? 0 : Math.min(MAX_WAIT_MS, Math.ceil(left));
54
+ const page = await getJson(send, `/runs/${id}/timeline?after=${after}&wait_ms=${waitMs}`, TIMELINE, deadline, signal);
55
+ if (!Number.isInteger(page.next_after) || typeof page.status !== "string")
56
+ throw new AgentRunRefused(TIMELINE, 200, "bad_answer", undefined, `The server's answer to ${TIMELINE} is not a timeline page.`);
57
+ after = page.next_after;
58
+ if (ended(page.status, page.final === true)) {
59
+ const run = await getJson(send, `/runs/${id}`, RUN, deadline, signal);
60
+ last = run;
61
+ // A message can reopen the run between the two reads: then it is waited for again.
62
+ if (ended(run.status, true))
63
+ return run;
64
+ }
65
+ if (page.unchanged && !page.has_more)
66
+ await pause(Math.min(page.poll_after_ms ?? 1000, Math.max(1, deadline - Date.now())), signal);
67
+ }
68
+ }
69
+ catch (error) {
70
+ if (error === LATE)
71
+ return late();
72
+ throw error;
73
+ }
74
+ }
75
+ /** The events of a `text/event-stream` body as the HTML standard parses them, each once its blank line came, so an
76
+ * event cut off midway is never seen. `id` is the last id field seen, carried from event to event; only digits, the
77
+ * route's change numbers, are kept, so nothing else is ever sent back as a header. */
78
+ async function* events(body, heard) {
79
+ const reader = body.getReader();
80
+ const decoder = new TextDecoder();
81
+ let buffer = "";
82
+ let event = { event: "", data: [] };
83
+ let id;
84
+ try {
85
+ for (;;) {
86
+ const { done, value } = await reader.read();
87
+ if (done)
88
+ return;
89
+ heard();
90
+ let text = buffer + decoder.decode(value, { stream: true });
91
+ // A CR at the end may be the first half of a CRLF still to come.
92
+ const held = text.endsWith("\r") ? "\r" : "";
93
+ if (held)
94
+ text = text.slice(0, -1);
95
+ const lines = text.split(/\r\n|\r|\n/);
96
+ buffer = lines.pop() + held;
97
+ for (const line of lines) {
98
+ if (line === "") {
99
+ if (event.data.length || event.retry !== undefined)
100
+ yield { event: event.data.length ? event.event || "message" : "", data: event.data.join("\n"), id, retry: event.retry };
101
+ event = { event: "", data: [] };
102
+ }
103
+ else if (!line.startsWith(":")) {
104
+ const colon = line.indexOf(":");
105
+ const field = colon < 0 ? line : line.slice(0, colon);
106
+ const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
107
+ if (field === "event")
108
+ event.event = value;
109
+ else if (field === "data")
110
+ event.data.push(value);
111
+ else if (field === "id" && /^\d+$/.test(value))
112
+ id = value;
113
+ else if (field === "retry" && /^\d+$/.test(value))
114
+ event.retry = Number(value);
115
+ }
116
+ }
117
+ }
118
+ }
119
+ finally {
120
+ reader.releaseLock();
121
+ }
122
+ }
123
+ const objectOf = (data, what) => {
124
+ try {
125
+ const value = JSON.parse(data);
126
+ if (value && typeof value === "object" && !Array.isArray(value))
127
+ return value;
128
+ }
129
+ catch {
130
+ // refused below
131
+ }
132
+ throw new AgentRunRefused(TIMELINE, 200, "bad_answer", undefined, `The server sent a ${what} event that is not a JSON object.`);
133
+ };
134
+ /** The timeline's event stream, each `rows` event's page as the server sent it (its rows, its drops, `reset` when the
135
+ * rows held go first). A dropped connection, an `end` with `reason: reconnect`, or a stream silent past three
136
+ * keepalives reconnects with Last-Event-ID; tries that get no event back off, never under the server's `retry`, and
137
+ * give up after a few in a row (AgentRunUnreachable). It ends at the server's `end` with `reason: terminal`. */
138
+ export async function* followRun(send, baseUrl, runId, options = {}) {
139
+ const id = segmentOf(runId, "runId", false);
140
+ const { after, signal } = options;
141
+ if (after !== undefined && (!Number.isInteger(after) || after < 0))
142
+ throw new AgentRunUsage("after must be a whole number, 0 or more.");
143
+ const idleMs = wholeMs(options.idleMs ?? IDLE_MS);
144
+ if (options.idleMs !== undefined && !(Number.isFinite(options.idleMs) && options.idleMs > 0))
145
+ throw new AgentRunUsage("idleMs must be a number of milliseconds above 0.");
146
+ if (options.lastEventId !== undefined && !/^\d+$/.test(options.lastEventId))
147
+ throw new AgentRunUsage("lastEventId must be an event id the server sent: digits only.");
148
+ const path = `/runs/${id}/timeline${after !== undefined ? `?after=${after}` : ""}`;
149
+ let last = options.lastEventId;
150
+ let retryMs = 0;
151
+ let reached = false;
152
+ for (let tries = 0;;) {
153
+ let progress = false;
154
+ let reconnect = false;
155
+ let cause = "stream_closed";
156
+ // A gateway's Retry-After: the least wait before the next try, capped as a GET's retry is.
157
+ let floor = 0;
158
+ const silent = new AbortController();
159
+ let timer;
160
+ const heard = () => {
161
+ clearTimeout(timer);
162
+ timer = setTimeout(() => silent.abort(new Error("stream_silent")), idleMs);
163
+ };
164
+ heard();
165
+ try {
166
+ let response;
167
+ try {
168
+ // No try timeout of its own: the idle timer bounds it.
169
+ response = await send({ method: "GET", path, route: TIMELINE, retryable: false, streamed: true, signal: signal ? AbortSignal.any([signal, silent.signal]) : silent.signal, timeoutMs: 2 ** 31 - 1, headers: { accept: "text/event-stream", ...(last !== undefined ? { "last-event-id": last } : {}) } });
170
+ reached = true;
171
+ }
172
+ catch (error) {
173
+ // A server that never answered is unreachable now; once it has, a dropped connection, silence or a gateway's
174
+ // 502, 503 or 504 reconnects. Every other refusal is the call's outcome.
175
+ if (signal?.aborted)
176
+ throw signal.reason;
177
+ const gateway = error instanceof AgentRunRefused && [502, 503, 504].includes(error.status);
178
+ if (!gateway && !(error instanceof AgentRunUnreachable && reached) && !silent.signal.aborted)
179
+ throw error;
180
+ reached = true;
181
+ cause = gateway ? `http_${error.status}` : error instanceof AgentRunUnreachable ? error.cause : "stream_silent";
182
+ if (gateway)
183
+ floor = Math.min(error.retryAfterMs ?? 0, MAX_RETRY_AFTER_MS);
184
+ }
185
+ if (response && !/^text\/event-stream\b/i.test(response.headers.get("content-type") ?? "")) {
186
+ await response.body?.cancel().catch(() => undefined);
187
+ throw new AgentRunRefused(TIMELINE, response.status, "bad_answer", undefined, `The server answered ${TIMELINE} with ${response.headers.get("content-type") ?? "no content type"}, not an event stream.`);
188
+ }
189
+ if (response) {
190
+ for await (const { event, data, id: seen, retry } of events(response.body, heard)) {
191
+ if (retry !== undefined)
192
+ retryMs = retry;
193
+ if (seen !== undefined)
194
+ last = seen;
195
+ if (event === "rows") {
196
+ progress = true;
197
+ const page = objectOf(data, "rows");
198
+ // The idle timer measures the server's silence, not the time the reader holds a page: off while yielded.
199
+ clearTimeout(timer);
200
+ yield page;
201
+ heard();
202
+ }
203
+ if (event === "end") {
204
+ if (objectOf(data, "end").reason === "terminal")
205
+ return;
206
+ reconnect = true;
207
+ break;
208
+ }
209
+ }
210
+ }
211
+ }
212
+ catch (error) {
213
+ // What broke while the stream was read is a dropped connection; an outcome of this client's is the call's.
214
+ if (signal?.aborted)
215
+ throw signal.reason;
216
+ if (error instanceof AgentRunError)
217
+ throw error;
218
+ cause = silent.signal.aborted ? "stream_silent" : "stream_broken";
219
+ }
220
+ finally {
221
+ clearTimeout(timer);
222
+ silent.abort();
223
+ }
224
+ if (reconnect) {
225
+ tries = 0;
226
+ if (retryMs)
227
+ await pause(retryMs, signal);
228
+ continue;
229
+ }
230
+ // The stream ended with no `end`, or broke: the connection dropped.
231
+ tries = progress ? 1 : tries + 1;
232
+ if (tries > RETRIES)
233
+ throw new AgentRunUnreachable(baseUrl, cause);
234
+ await pause(backoff(tries, Math.max(retryMs, floor)), signal);
235
+ }
236
+ }