@parcha/agentrun-client 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ AgentRun
2
+ Copyright 2026 Parcha Labs, Inc.
package/README.md CHANGED
@@ -1,3 +1,89 @@
1
- # Temporary Holding Version
1
+ # @parcha/agentrun-client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A typed TypeScript client for an AgentRun server you host yourself, the open platform's server: one method per operation of
4
+ its API, typed from the OpenAPI document it serves, plus waiting for a run and following its timeline. No dependencies: it
5
+ uses `fetch`, on Node.js 22.19 or newer.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @parcha/agentrun-client
11
+ ```
12
+
13
+ ## Construct
14
+
15
+ ```ts
16
+ import { AgentRun } from "@parcha/agentrun-client";
17
+
18
+ const client = new AgentRun({ baseUrl: "https://agentrun.example.com/v2", apiKey: process.env.AGENTRUN_API_KEY });
19
+ ```
20
+
21
+ `baseUrl` defaults to `AGENTRUN_BASE_URL` and `apiKey` to `AGENTRUN_API_KEY`. The base URL must be http or https with no
22
+ query, fragment, user or password, and the key must be a valid header value; both are checked here, before any request. The
23
+ client reads no file: finding the server started on this machine (its data directory and the address it records there) is
24
+ the CLI's job (`npx @parcha/agentrun`), not this package's. Other options: `timeoutMs` for one try of a request (default
25
+ 60000), `maxRetries` (default 4) and `fetch`.
26
+
27
+ Methods are grouped as the CLI's commands are: `agents create` is `client.agents.create(body)`, `runs start AGENT` is
28
+ `client.runs.start(agentId, body)`. Path parameters come first, then the body, then query and header parameters as one
29
+ object, then `{ signal, timeoutMs }`. An operation whose answer carries an ETag (`agents.get`, `learning.read`) resolves
30
+ to `{ body, etag }`: pass `etag` as the next write's `If-Match`.
31
+
32
+ ## Examples
33
+
34
+ Create an agent, start a run with a spend cap and wait for it:
35
+
36
+ ```ts
37
+ await client.agents.create({ definition: { id: "notes", version: 1, name: "Notes", instructions: "Write what you are asked to a file.", skills: [], tools: ["write", "ask_person"] } });
38
+ const started = await client.runs.start("notes", { input: { content: "Write notes.md about the Moon." }, max_cost_usd: 0.5 });
39
+ const run = await client.runs.wait(started.run_id, { timeoutMs: 120_000 });
40
+ console.log(run.status, run.cost.usd);
41
+ ```
42
+
43
+ `runs.wait` resolves once the run ends (`completed`, `failed`, `cancelled`) or waits on a person (`input_required`,
44
+ `paused`). Answer a question, or raise the cap of a run stopped at it, then wait again:
45
+
46
+ ```ts
47
+ if (run.pending?.kind === "question") await client.runs.message(run.run_id, { content: "Europe" });
48
+ if (run.pending?.kind === "budget") await client.runs.raiseCap(run.run_id, { max_cost_usd: 1 });
49
+ const done = await client.runs.wait(run.run_id);
50
+ ```
51
+
52
+ Follow the timeline as it changes, then read a file the run wrote:
53
+
54
+ ```ts
55
+ for await (const page of client.runs.follow(done.run_id)) {
56
+ for (const row of page.rows) console.log(row.kind);
57
+ }
58
+ const bytes = await client.runs.readFile(done.run_id, "notes.md"); // a Uint8Array, byte for byte
59
+ const response = await client.runs.readFile(done.run_id, "notes.md", undefined, { stream: true }); // the Response, unread
60
+ ```
61
+
62
+ `runs.follow` reads the route's event stream and resumes a dropped connection with `Last-Event-ID`, so no page comes twice.
63
+ Only the server's silence counts as a dropped connection (`idleMs`, default 45000), never the time your loop spends on a
64
+ page.
65
+
66
+ ## Errors
67
+
68
+ Every error is an `AgentRunError`, and its `kind` says which one:
69
+
70
+ | Class | `kind` | When | Fields |
71
+ |---|---|---|---|
72
+ | `AgentRunRefused` | `refused` | The server refused (4xx, 5xx); a redirect away from the base URL's origin (`code` `redirect`); an answer the client cannot read (`code` `bad_answer`) | `status`, `code`, `error` (the server's error object) |
73
+ | `AgentRunAuthError` | `auth` | No key (`reason` `no_token`), a key that is not a valid header value (`bad_header`), or a key the server refused, 401 or 403 (`refused`) | `reason`, `status`, `code`, `error` |
74
+ | `AgentRunUnsupported` | `unsupported` | The server does not offer the operation here (501) | `capability` |
75
+ | `AgentRunUnreachable` | `unreachable` | No answer: the server is down, or the connection dropped | `cause`, the failure's code |
76
+ | `AgentRunUsage` | `usage` | A bad argument, before anything was sent: a path argument with a `.` or `..` segment, a header value with a line break | `reason` |
77
+ | `AgentRunTimeout` | `late` | `runs.wait` passed its `timeoutMs`; the run goes on | `runId`, `run` as last read |
78
+
79
+ No message holds the API key or the server's own message text: a message names the route, the status and the server's
80
+ error code. The key goes only to the base URL's origin. A redirect is followed only for a GET within that origin. A secret
81
+ body (a tool key, an MCP server's credentials) has each of its values cut from the answer, as JSON values, and a refusal of
82
+ it keeps only its code.
83
+
84
+ A GET, or a request that carries an `Idempotency-Key`, is tried again after a 429, a 5xx or a dropped connection, with
85
+ backoff and never sooner than the server's `Retry-After`. Any other request is sent once. A server no connection reaches
86
+ (refused, unknown name, unreachable host) and a certificate the client refuses are unreachable at once.
87
+
88
+ The methods and types are generated from the server's OpenAPI document by `node scripts/generate-clients.mjs`, from the
89
+ same projection and resource map as the CLI's commands.
@@ -0,0 +1,35 @@
1
+ import { type FollowOptions, type WaitOptions } from "./live.js";
2
+ import { type Resources, type Run, type TimelinePage } from "./operations.generated.js";
3
+ export interface ClientOptions {
4
+ /** The server's API, ending /v2 (default: AGENTRUN_BASE_URL): http or https, with no query, fragment, user or password. */
5
+ baseUrl?: string;
6
+ /** The API key (default: AGENTRUN_API_KEY). */
7
+ apiKey?: string;
8
+ /** How long one try of a request may take, in milliseconds (default 60000). */
9
+ timeoutMs?: number;
10
+ /** How many times a GET, or a request with an Idempotency-Key, is tried again after a 429, a 5xx or a dropped connection (default 4). */
11
+ maxRetries?: number;
12
+ /** The fetch to send with (default: the global one). */
13
+ fetch?: typeof fetch;
14
+ }
15
+ type Runs = Resources["runs"] & {
16
+ /** Waits until the run ends (completed, failed or cancelled, every row in) or waits on a person (`input_required`,
17
+ * `paused`), and resolves to the run. Past `timeoutMs` it throws AgentRunTimeout, and the run goes on. */
18
+ wait(runId: string, options?: WaitOptions): Promise<Run>;
19
+ /** The run's timeline as it changes: each page the server's event stream sends, until the run ends. A dropped
20
+ * connection resumes with Last-Event-ID, so no change comes twice. */
21
+ follow(runId: string, options?: FollowOptions): AsyncGenerator<TimelinePage, void, undefined>;
22
+ };
23
+ export interface AgentRun extends Omit<Resources, "runs"> {
24
+ readonly runs: Runs;
25
+ }
26
+ /** A client for one AgentRun server. The local server's discovery (its data directory, its record of its address) is the
27
+ * CLI's: this client reads no file, only its options and the environment. */
28
+ export declare class AgentRun {
29
+ #private;
30
+ readonly baseUrl: string;
31
+ readonly timeoutMs: number;
32
+ readonly maxRetries: number;
33
+ constructor(options?: ClientOptions);
34
+ }
35
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,262 @@
1
+ // The client: `new AgentRun({ baseUrl, apiKey })`, a method per operation (operations.generated.ts), and the rules every
2
+ // client of the server keeps. The key goes only to its own base URL, in the Authorization header, and is checked to be a
3
+ // valid header value before any request; no error holds it. A path argument is encoded whole (a file path keeps its
4
+ // slashes), and one that would read as another route is refused before anything is sent. Only a GET, or a request that
5
+ // carries an Idempotency-Key, is tried again. A secret body's values are cut from the answer to it.
6
+ import { AgentRunAuthError, AgentRunError, AgentRunRefused, AgentRunUnreachable, AgentRunUnsupported, AgentRunUsage } from "./errors.js";
7
+ import { BAD_HEADER, backoff, LATE, MAX_RETRY_AFTER_MS, pause, segmentOf, wholeMs } from "./http.js";
8
+ import { followRun, waitRun } from "./live.js";
9
+ import { OPERATIONS, resources } from "./operations.generated.js";
10
+ import { scrubberOf, secretsOf } from "./scrub.js";
11
+ const JSON_TYPE = /^application\/(?:[\w.+-]+\+)?json\b/i;
12
+ const RETRIABLE = new Set([429, 500, 502, 503, 504]);
13
+ const REDIRECT = new Set([301, 302, 303, 307, 308]);
14
+ const MAX_HOPS = 5;
15
+ /** A failure's code, never its message: a fetch error's message can quote a header. */
16
+ const causeOf = (error) => {
17
+ const e = error;
18
+ if (e?.name === "TimeoutError")
19
+ return "timeout";
20
+ const code = e?.cause?.code ?? e?.code;
21
+ return typeof code === "string" && /^[A-Za-z0-9_]+$/.test(code) ? code : typeof e?.name === "string" && /^\w+$/.test(e.name) ? e.name : "unknown";
22
+ };
23
+ /** The causes of a connection that was never made: no server took it. Any other failure took a connection and dropped it. */
24
+ const NOT_CONNECTED = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EAI_NONAME", "EHOSTUNREACH", "ENETUNREACH", "EADDRNOTAVAIL", "UND_ERR_CONNECT_TIMEOUT"]);
25
+ /** The causes of a TLS handshake the client refused (a certificate it does not trust, a name it does not match). */
26
+ const UNTRUSTED = /CERT|TLS|SSL|UNABLE_TO_/;
27
+ /** Retry-After in milliseconds (seconds or an HTTP date), 0 when there is none. */
28
+ const retryAfterOf = (response) => {
29
+ const value = response.headers.get("retry-after");
30
+ if (!value)
31
+ return 0;
32
+ const ms = /^\d+$/.test(value.trim()) ? Number(value) * 1000 : Date.parse(value) - Date.now();
33
+ return Number.isFinite(ms) ? Math.max(0, ms) : 0;
34
+ };
35
+ const env = (name) => globalThis.process?.env?.[name];
36
+ /** A base URL as the client takes it; `where` names it in the refusal. The URL itself is never echoed: it may hold a password. */
37
+ function baseOf(given, where) {
38
+ if (given === undefined || given === "")
39
+ throw new AgentRunUsage("No server: pass baseUrl, or set AGENTRUN_BASE_URL, to the API's base (ending /v2).");
40
+ const url = URL.canParse(given) ? new URL(given) : undefined;
41
+ if (!url || !/^https?:$/.test(url.protocol) || /[?#]/.test(given) || url.username || url.password) {
42
+ throw new AgentRunUsage(`${where} must be an http or https URL with no query, fragment, user or password: the API's base, ending /v2.`);
43
+ }
44
+ return given.replace(/\/+$/, "");
45
+ }
46
+ const positive = (value, name, whole = false) => {
47
+ if (value !== undefined && (!Number.isFinite(value) || value < (whole ? 0 : 1) || (whole && !Number.isInteger(value))))
48
+ throw new AgentRunUsage(`${name} must be ${whole ? "a whole number, 0 or more" : "a number of milliseconds, 1 or more"}.`);
49
+ return value;
50
+ };
51
+ /** A client for one AgentRun server. The local server's discovery (its data directory, its record of its address) is the
52
+ * CLI's: this client reads no file, only its options and the environment. */
53
+ export class AgentRun {
54
+ baseUrl;
55
+ timeoutMs;
56
+ maxRetries;
57
+ #apiKey;
58
+ #fetch;
59
+ #reached = false;
60
+ constructor(options = {}) {
61
+ this.baseUrl = baseOf(options.baseUrl ?? env("AGENTRUN_BASE_URL"), options.baseUrl !== undefined ? "baseUrl" : "AGENTRUN_BASE_URL");
62
+ const key = options.apiKey ?? env("AGENTRUN_API_KEY");
63
+ if (!key)
64
+ throw new AgentRunAuthError("no_token", "No API key: pass apiKey, or set AGENTRUN_API_KEY.");
65
+ // Refused before it is sent: fetch would quote a bad header value in its error.
66
+ if (BAD_HEADER.test(key) || /\s/.test(key))
67
+ throw new AgentRunAuthError("bad_header", "The API key is not a valid header value (it holds a space, a line break, a control character or a character outside Latin-1).");
68
+ this.#apiKey = key;
69
+ this.timeoutMs = positive(options.timeoutMs, "timeoutMs") ?? 60_000;
70
+ this.maxRetries = positive(options.maxRetries, "maxRetries", true) ?? 4;
71
+ this.#fetch = options.fetch ?? globalThis.fetch;
72
+ const groups = resources((id, args, body, params, opts) => this.#call(id, args, body, params, opts));
73
+ Object.assign(this, groups, {
74
+ runs: { ...groups.runs, wait: (runId, opts) => waitRun(this.#send, runId, opts), follow: (runId, opts) => followRun(this.#send, this.baseUrl, runId, opts) },
75
+ });
76
+ }
77
+ /** One generated operation: its arguments checked, then sent, then its answer read. */
78
+ async #call(id, args, body, params, options) {
79
+ const op = OPERATIONS[id];
80
+ const route = `${op.method} ${op.path}`;
81
+ const path = op.path.replace(/\{([^}]+)\}/g, (_, name) => segmentOf(args[op.pathParams.indexOf(name)], name, op.multiSegment.includes(name)));
82
+ const given = (params ?? {});
83
+ const query = new URLSearchParams();
84
+ for (const name of op.query)
85
+ if (given[name] !== undefined && given[name] !== null)
86
+ query.set(name, String(given[name]));
87
+ const headers = {};
88
+ for (const name of op.headers) {
89
+ const value = given[name];
90
+ if (value === undefined)
91
+ continue;
92
+ if (typeof value !== "string" || BAD_HEADER.test(value))
93
+ throw new AgentRunUsage(`${name} is not a valid header value.`);
94
+ headers[name] = value;
95
+ }
96
+ let sent;
97
+ if (op.body && body !== undefined) {
98
+ const raw = typeof body === "string" || body instanceof Uint8Array || body instanceof ArrayBuffer || (typeof Blob !== "undefined" && body instanceof Blob);
99
+ const other = op.body.types.find((type) => !JSON_TYPE.test(type));
100
+ if (raw && other) {
101
+ const type = options?.contentType ?? (other === "*/*" ? "application/octet-stream" : other);
102
+ if (BAD_HEADER.test(type))
103
+ throw new AgentRunUsage("contentType is not a valid header value.");
104
+ headers["content-type"] = type;
105
+ sent = body;
106
+ }
107
+ else {
108
+ headers["content-type"] = "application/json";
109
+ sent = JSON.stringify(body);
110
+ }
111
+ }
112
+ else if (op.body?.required)
113
+ throw new AgentRunUsage(`${route} needs a body.`);
114
+ // A body bound for a secret route, the base URL's own path counted: its values are cut from the answer.
115
+ const url = `${this.baseUrl}${path}${query.size ? `?${query}` : ""}`;
116
+ const secretOp = op.secret ? op : secretAt(op.method, url);
117
+ if (secretOp && sent !== undefined && typeof sent !== "string")
118
+ throw new AgentRunUsage(`${route} under ${this.baseUrl} reaches ${secretOp.method} ${secretOp.path}, whose body is a secret: send it as JSON.`);
119
+ const secrets = secretOp && typeof sent === "string" ? secretsOf(sent, secretOp.publicFields) : [];
120
+ const response = await this.#send({
121
+ method: op.method, path: url.slice(this.baseUrl.length), route, headers, body: sent, signal: options?.signal, timeoutMs: options?.timeoutMs,
122
+ retryable: op.method === "GET" || headers["Idempotency-Key"] !== undefined, secret: secretOp !== undefined, secrets,
123
+ streamed: op.answer === "bytes" && options?.stream === true,
124
+ });
125
+ const answer = await readAnswer(op, route, response, options?.stream === true, secretOp ? scrubberOf(secrets) : undefined);
126
+ return op.tagged ? { body: answer, etag: response.headers.get("etag") } : answer;
127
+ }
128
+ /** One request to the server with the key: tried again when it may be, its redirects followed only within the base
129
+ * URL's origin, and any answer but a success thrown as its outcome. Resolves to the success's Response. */
130
+ #send = async (x) => {
131
+ const deadline = x.deadline ?? Infinity;
132
+ for (let tries = 1;; tries++) {
133
+ const left = deadline - Date.now();
134
+ if (left <= 0)
135
+ throw LATE;
136
+ const timeout = AbortSignal.timeout(wholeMs(Math.min(x.timeoutMs ?? this.timeoutMs, left)));
137
+ const signal = x.signal ? AbortSignal.any([x.signal, timeout]) : timeout;
138
+ let response;
139
+ try {
140
+ response = await this.#follow(x, signal);
141
+ this.#reached = true;
142
+ if (response.ok && !x.streamed)
143
+ response = await whole(response);
144
+ }
145
+ catch (error) {
146
+ if (x.signal?.aborted)
147
+ throw x.signal.reason;
148
+ if (error instanceof AgentRunError)
149
+ throw error;
150
+ if (Date.now() >= deadline)
151
+ throw LATE;
152
+ const cause = causeOf(error);
153
+ // A server never reached is unreachable at once; a dropped connection is tried again, even on the first request,
154
+ // and so is a refused one once the server has answered before (it may be restarting); a timeout is not.
155
+ // A certificate the client refuses stays refused, so it is never tried again.
156
+ const neverReached = !this.#reached && NOT_CONNECTED.has(cause);
157
+ if (!x.retryable || neverReached || UNTRUSTED.test(cause) || cause === "timeout" || tries > this.maxRetries)
158
+ throw new AgentRunUnreachable(this.baseUrl, cause);
159
+ await pause(Math.min(backoff(tries), deadline - Date.now()), x.signal);
160
+ continue;
161
+ }
162
+ if (x.retryable && RETRIABLE.has(response.status) && tries <= this.maxRetries && retryAfterOf(response) <= MAX_RETRY_AFTER_MS) {
163
+ const floor = retryAfterOf(response);
164
+ await response.body?.cancel().catch(() => undefined);
165
+ await pause(Math.min(backoff(tries, floor), Math.max(1, deadline - Date.now())), x.signal);
166
+ continue;
167
+ }
168
+ if (response.ok)
169
+ return response;
170
+ throw await refusal(x, response, this.#apiKey);
171
+ }
172
+ };
173
+ /** fetch with the key, following a redirect only for a GET and only within the base URL's origin: the key never goes
174
+ * to another server. Any other redirect is refused (`code` `redirect`). */
175
+ async #follow(x, signal) {
176
+ const origin = new URL(this.baseUrl).origin;
177
+ let url = `${this.baseUrl}${x.path}`;
178
+ for (let hops = 0;; hops++) {
179
+ const response = await this.#fetch(url, { method: x.method, headers: { accept: "application/json, */*", ...x.headers, authorization: `Bearer ${this.#apiKey}` }, body: x.body, signal, redirect: "manual" });
180
+ if (!REDIRECT.has(response.status))
181
+ return response;
182
+ await response.body?.cancel().catch(() => undefined);
183
+ const location = response.headers.get("location");
184
+ const next = location && URL.canParse(location, url) ? new URL(location, url) : undefined;
185
+ const home = next !== undefined && next.origin === origin && !next.username && !next.password;
186
+ if (!home || x.method !== "GET" || hops >= MAX_HOPS) {
187
+ throw new AgentRunRefused(x.route, response.status, "redirect", undefined, `The server answered ${x.route} with a redirect ${home ? "this client does not follow" : "to another origin"} (${response.status}); not followed, so the API key stays with ${this.baseUrl}.`);
188
+ }
189
+ url = next.href;
190
+ }
191
+ }
192
+ }
193
+ /** `response` with its body read whole: a body cut midway throws here, inside the exchange's rules. */
194
+ async function whole(response) {
195
+ const bytes = await response.arrayBuffer();
196
+ const empty = response.status === 204 || response.status === 205 || response.status === 304;
197
+ return new Response(empty ? null : bytes, { status: response.status, statusText: response.statusText, headers: response.headers });
198
+ }
199
+ /** The secret operation `method` on `url` reaches, its path normalized as fetch normalizes it: the route at the end of
200
+ * the path, whatever part of it the base URL holds. */
201
+ function secretAt(method, url) {
202
+ const pathname = new URL(url).pathname.replace(/\/{2,}/g, "/");
203
+ const route = (op) => new RegExp(`(?:^|/)${op.path.slice(1).split(/\{[^}]+\}/).map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[^/]+")}/?$`);
204
+ return Object.values(OPERATIONS).find((op) => op.secret && op.method === method && route(op).test(pathname));
205
+ }
206
+ /** A refused answer as its outcome. The server's error object is kept with every copy of the key cut from it; after a
207
+ * secret body, with the body's values cut too, only its code, and a code that held one is no code. Its text is never
208
+ * read into a message. A caller's abort while the body is still coming is thrown as the caller's own reason, and a read
209
+ * that ends at or past the exchange's deadline (a wait's timeout) as LATE: cancelled or late work is never reported as a
210
+ * refusal or a bad key. */
211
+ async function refusal(x, response, apiKey) {
212
+ let error;
213
+ try {
214
+ const parsed = JSON.parse(new TextDecoder().decode(await response.arrayBuffer()));
215
+ if (parsed?.error && typeof parsed.error === "object" && !Array.isArray(parsed.error))
216
+ error = scrubberOf([apiKey, ...(x.secrets ?? [])])(parsed.error);
217
+ }
218
+ catch {
219
+ if (x.signal?.aborted)
220
+ throw x.signal.reason;
221
+ if (Date.now() >= (x.deadline ?? Infinity))
222
+ throw LATE;
223
+ error = undefined;
224
+ }
225
+ const code = typeof error?.code === "string" && /^[a-z0-9_]+$/.test(error.code) ? error.code : undefined;
226
+ if (x.secret)
227
+ error = code ? { code } : undefined;
228
+ if (response.status === 401 || response.status === 403)
229
+ return new AgentRunAuthError("refused", `The server refused the API key for ${x.route}: ${response.status}${code ? ` ${code}` : ""}.`, { status: response.status, code, error });
230
+ if (response.status === 501)
231
+ return new AgentRunUnsupported(x.route, response.status, code, error);
232
+ const wait = retryAfterOf(response);
233
+ return new AgentRunRefused(x.route, response.status, code, error, undefined, wait > 0 ? wait : undefined);
234
+ }
235
+ const badAnswer = (route, status, what) => new AgentRunRefused(route, status, "bad_answer", undefined, `The server's answer to ${route} is not ${what}.`);
236
+ /** A success's body as the operation answers: JSON parsed (a secret body's values cut from it), text as a string, a
237
+ * file's bytes as they came, or the Response itself for a download asked to stream. */
238
+ async function readAnswer(op, route, response, stream, scrub) {
239
+ if (op.answer === "bytes" && !scrub)
240
+ return stream ? response : new Uint8Array(await response.arrayBuffer());
241
+ if (op.answer === "none")
242
+ return void (await response.body?.cancel().catch(() => undefined));
243
+ const bytes = new Uint8Array(await response.arrayBuffer());
244
+ if (response.status === 204 || bytes.length === 0)
245
+ return op.answer.includes("json") ? undefined : op.answer === "text" ? "" : bytes;
246
+ const type = response.headers.get("content-type") ?? "";
247
+ if (scrub || (op.answer.includes("json") && (JSON_TYPE.test(type) || op.answer === "json"))) {
248
+ if (!JSON_TYPE.test(type))
249
+ throw badAnswer(route, response.status, "JSON");
250
+ let value;
251
+ try {
252
+ value = JSON.parse(new TextDecoder().decode(bytes));
253
+ }
254
+ catch {
255
+ throw badAnswer(route, response.status, "JSON");
256
+ }
257
+ return scrub ? scrub(value) : value;
258
+ }
259
+ if (op.answer.includes("text") && (/^text\//i.test(type) || !op.answer.includes("bytes")))
260
+ return new TextDecoder().decode(bytes);
261
+ return bytes;
262
+ }
@@ -0,0 +1,61 @@
1
+ import type { Run } from "./operations.generated.js";
2
+ /** The server's error object (`{ code, message, ... }`), with every copy of the API key cut from its values and keys. */
3
+ export type ServerError = Record<string, unknown>;
4
+ /** What every error of this client is: `kind` says which outcome it is. */
5
+ export declare abstract class AgentRunError extends Error {
6
+ abstract readonly kind: "refused" | "auth" | "unsupported" | "unreachable" | "usage" | "late";
7
+ }
8
+ /** The server answered and refused: a 4xx or 5xx other than 401, 403 and 501; a redirect it would take the key along
9
+ * to follow (`code` `redirect`); or an answer this client cannot read (`code` `bad_answer`). */
10
+ export declare class AgentRunRefused extends AgentRunError {
11
+ readonly kind = "refused";
12
+ readonly status: number;
13
+ readonly code: string | undefined;
14
+ readonly error: ServerError | undefined;
15
+ /** How long the server asked to be left before the same request again (its Retry-After), in milliseconds. */
16
+ readonly retryAfterMs: number | undefined;
17
+ constructor(route: string, status: number, code: string | undefined, error: ServerError | undefined, why?: string, retryAfterMs?: number);
18
+ }
19
+ /** No API key, one that is not a valid header value (refused before any request), or one the server refused (401, 403). */
20
+ export declare class AgentRunAuthError extends AgentRunError {
21
+ readonly kind = "auth";
22
+ readonly reason: "no_token" | "bad_header" | "refused";
23
+ readonly status: number | undefined;
24
+ readonly code: string | undefined;
25
+ readonly error: ServerError | undefined;
26
+ constructor(reason: "no_token" | "bad_header" | "refused", message: string, answer?: {
27
+ status: number;
28
+ code?: string;
29
+ error?: ServerError;
30
+ });
31
+ }
32
+ /** The server does not offer this operation here (501 `unsupported_here`); `capability` names what is off. */
33
+ export declare class AgentRunUnsupported extends AgentRunError {
34
+ readonly kind = "unsupported";
35
+ readonly by = "server";
36
+ readonly capability: string | undefined;
37
+ readonly status: number;
38
+ readonly code: string | undefined;
39
+ readonly error: ServerError | undefined;
40
+ constructor(route: string, status: number, code: string | undefined, error: ServerError | undefined);
41
+ }
42
+ /** The server could not be reached, or stopped answering. `cause` is the failure's code (ECONNREFUSED, timeout), never
43
+ * its message, which can quote a header. */
44
+ export declare class AgentRunUnreachable extends AgentRunError {
45
+ readonly kind = "unreachable";
46
+ readonly cause: string;
47
+ constructor(baseUrl: string, cause: string);
48
+ }
49
+ /** The call was wrong before anything was sent: a bad argument, base URL or option. */
50
+ export declare class AgentRunUsage extends AgentRunError {
51
+ readonly kind = "usage";
52
+ readonly reason: string;
53
+ constructor(reason: string);
54
+ }
55
+ /** `runs.wait` passed its `timeoutMs`; the run goes on. `run` is the run as last read, when it was. */
56
+ export declare class AgentRunTimeout extends AgentRunError {
57
+ readonly kind = "late";
58
+ readonly runId: string;
59
+ readonly run: Run | undefined;
60
+ constructor(runId: string, timeoutMs: number, run: Run | undefined);
61
+ }