@gaiventures/pilotfish 0.0.0-stage → 0.1.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/client.js ADDED
@@ -0,0 +1,385 @@
1
+ // The hosted client: pilotfish's REST API (https://pilotfish.gai.ventures/docs/api) with an API key from Org settings →
2
+ // API keys. Tasks run in pilotfish's cloud browser and are paid from your org's credits.
3
+ import { ConnectionError, errorFor, PilotfishError, WaitTimeoutError } from "./errors.js";
4
+ import { VERSION } from "./version.js";
5
+ export const DEFAULT_BASE_URL = "https://pilotfish-be.gai.ventures";
6
+ /** The text the app sends to carry a paused task on. */
7
+ export const CONTINUE_TEXT = "Continue the task from where you left off.";
8
+ const ENDED = new Set(["done", "failed", "cancelled"]);
9
+ const env = (k) => (typeof process !== "undefined" ? process.env?.[k] : undefined) || undefined;
10
+ const sleep = (ms, signal) => new Promise((resolve, reject) => {
11
+ if (signal?.aborted)
12
+ return reject(signal.reason);
13
+ const t = setTimeout(resolve, ms);
14
+ signal?.addEventListener("abort", () => (clearTimeout(t), reject(signal.reason)), { once: true });
15
+ });
16
+ export class Pilotfish {
17
+ baseUrl;
18
+ apiKey;
19
+ maxRetries;
20
+ timeoutMs;
21
+ fetchImpl;
22
+ tasks;
23
+ batches;
24
+ identities;
25
+ savedTasks;
26
+ schedules;
27
+ usage;
28
+ constructor(o = {}) {
29
+ const key = o.apiKey ?? env("PILOTFISH_API_KEY");
30
+ if (!key)
31
+ throw new PilotfishError(0, { error: "No API key: pass apiKey, or set PILOTFISH_API_KEY (Org settings → API keys).", code: "no_api_key" });
32
+ this.apiKey = key;
33
+ this.baseUrl = (o.baseUrl ?? env("PILOTFISH_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
34
+ this.maxRetries = o.maxRetries ?? 2;
35
+ this.timeoutMs = o.timeoutMs ?? 60_000;
36
+ this.fetchImpl = o.fetch ?? globalThis.fetch.bind(globalThis);
37
+ this.tasks = new Tasks(this);
38
+ this.batches = new Batches(this);
39
+ this.identities = new Identities(this);
40
+ this.savedTasks = new SavedTasks(this);
41
+ this.schedules = new Schedules(this);
42
+ this.usage = new UsageApi(this);
43
+ }
44
+ /** One API call: JSON in and out, typed errors, retries on 429 (after its `retryAfterS`) and, for reads, on 5xx and network failures. */
45
+ async request(method, path, o = {}) {
46
+ const res = await this.send(method, path, o);
47
+ if (o.raw)
48
+ return res;
49
+ if (res.status === 204)
50
+ return undefined;
51
+ return (await res.json());
52
+ }
53
+ /** The raw response of a call that returns a file (its bytes). */
54
+ async download(path, signal) {
55
+ const res = await this.send("GET", path, { ...(signal ? { signal } : {}) });
56
+ const cd = res.headers.get("content-disposition") ?? "";
57
+ const star = /filename\*=UTF-8''([^;]+)/i.exec(cd)?.[1];
58
+ const plain = /filename="([^"]+)"/i.exec(cd)?.[1];
59
+ return { data: new Uint8Array(await res.arrayBuffer()), contentType: res.headers.get("content-type") ?? "application/octet-stream", filename: star ? decodeURIComponent(star) : (plain ?? null) };
60
+ }
61
+ async send(method, path, o) {
62
+ const url = new URL(this.baseUrl + path);
63
+ for (const [k, v] of Object.entries(o.query ?? {}))
64
+ if (v !== undefined)
65
+ url.searchParams.set(k, String(v));
66
+ const read = method === "GET" || method === "HEAD";
67
+ for (let attempt = 0;; attempt++) {
68
+ const timeout = AbortSignal.timeout(this.timeoutMs);
69
+ const signal = o.signal ? AbortSignal.any([o.signal, timeout]) : timeout;
70
+ let res;
71
+ try {
72
+ res = await this.fetchImpl(url, {
73
+ method,
74
+ headers: {
75
+ authorization: `Bearer ${this.apiKey}`,
76
+ accept: "application/json",
77
+ "user-agent": `pilotfish-sdk-ts/${VERSION}`,
78
+ ...(o.body !== undefined ? { "content-type": "application/json" } : {}),
79
+ },
80
+ ...(o.body !== undefined ? { body: JSON.stringify(o.body) } : {}),
81
+ signal,
82
+ });
83
+ }
84
+ catch (e) {
85
+ if (o.signal?.aborted)
86
+ throw e;
87
+ if (read && attempt < this.maxRetries) {
88
+ await sleep(500 * 2 ** attempt, o.signal);
89
+ continue;
90
+ }
91
+ throw new ConnectionError(`${method} ${path}: ${e instanceof Error ? e.message : String(e)}`, e);
92
+ }
93
+ if (res.ok || (res.status >= 300 && res.status < 400))
94
+ return res;
95
+ const body = await res
96
+ .json()
97
+ .then((b) => (b && typeof b === "object" ? b : { error: String(b) }))
98
+ .catch(() => ({ error: `HTTP ${res.status}` }));
99
+ const header = res.headers.get("retry-after");
100
+ const retryAfter = typeof body["retryAfterS"] === "number" ? body["retryAfterS"] : header !== null && /^\d+$/.test(header.trim()) ? Number(header) : undefined;
101
+ // A 429 refused the request before anything was made, so it is safe to send again, whatever the method.
102
+ if (res.status === 429 && attempt < this.maxRetries) {
103
+ await sleep(Math.min(60, retryAfter ?? 2 ** attempt) * 1000, o.signal);
104
+ continue;
105
+ }
106
+ // 501 (a feature this server does not have, such as MP4 replays) is not retried: it will not change.
107
+ if (read && res.status >= 500 && res.status !== 501 && attempt < this.maxRetries) {
108
+ await sleep(500 * 2 ** attempt, o.signal);
109
+ continue;
110
+ }
111
+ throw errorFor(res.status, retryAfter !== undefined && body["retryAfterS"] === undefined ? { ...body, retryAfterS: retryAfter } : body);
112
+ }
113
+ }
114
+ }
115
+ const enc = encodeURIComponent;
116
+ /** Tasks (the API's jobs): run, watch, answer, steer, follow up, and read their files and replays. */
117
+ export class Tasks {
118
+ c;
119
+ constructor(c) {
120
+ this.c = c;
121
+ }
122
+ /** Start a task; returns at once with its id (and `url`, `appUrl`, `answerUrl`). */
123
+ create(req) {
124
+ return this.c.request("POST", "/jobs", { body: typeof req === "string" ? { task: req } : req });
125
+ }
126
+ /** Start a task and wait for it to end (or to wait on a question, unless `returnOnQuestion: false`). */
127
+ async run(req, o = {}) {
128
+ const t = await this.create(req);
129
+ return this.wait(t.id, o);
130
+ }
131
+ /** A task with its result, question, settings, cost so far and live view. */
132
+ get(id) {
133
+ return this.c.request("GET", `/jobs/${enc(id)}`);
134
+ }
135
+ /** Wait until the task ends, or waits on a question (unless `returnOnQuestion: false`). Throws WaitTimeoutError after `timeoutMs`. */
136
+ async wait(id, o = {}) {
137
+ const until = Date.now() + (o.timeoutMs ?? 30 * 60_000);
138
+ for (;;) {
139
+ const t = await this.get(id);
140
+ if (ENDED.has(t.status))
141
+ return t;
142
+ if (o.returnOnQuestion !== false && (t.status === "needs_input" || t.question))
143
+ return t;
144
+ if (Date.now() >= until)
145
+ throw new WaitTimeoutError(`Task ${id} is still ${t.status}: it carries on; wait again or cancel it.`);
146
+ await sleep(o.pollMs ?? 2_000, o.signal);
147
+ }
148
+ }
149
+ /** Your tasks, newest first (a key: the tasks it started). One page; `iterate` walks them all. */
150
+ async list(o = {}) {
151
+ const r = await this.c.request("GET", "/jobs", { query: { mine: 1, ...o } });
152
+ return { items: r.jobs, nextCursor: r.nextCursor };
153
+ }
154
+ /** Every task, page after page. */
155
+ async *iterate(o = {}) {
156
+ let cursor;
157
+ do {
158
+ const page = await this.list({ ...o, ...(cursor ? { cursor } : {}) });
159
+ yield* page.items;
160
+ cursor = page.nextCursor ?? undefined;
161
+ } while (cursor);
162
+ }
163
+ /** The task's events (steps, questions, files…), or those after `after` (an event's `seq`). */
164
+ async events(id, after) {
165
+ return (await this.c.request("GET", `/jobs/${enc(id)}/events`, { query: { after } })).events;
166
+ }
167
+ /** Each new event as it happens, until the task ends. */
168
+ async *stream(id, o = {}) {
169
+ let after = -1;
170
+ for (;;) {
171
+ const t = await this.get(id);
172
+ // Every event the API lists has a seq; one without (never expected) is yielded once by its position.
173
+ const seen = new Set();
174
+ const fresh = (events) => events.filter((e) => (e.seq !== undefined ? e.seq > after : !seen.has(JSON.stringify(e)) && (seen.add(JSON.stringify(e)), true)));
175
+ for (const e of fresh(await this.events(id, after >= 0 ? after : undefined))) {
176
+ after = Math.max(after, e.seq ?? after);
177
+ yield e;
178
+ }
179
+ if (ENDED.has(t.status)) {
180
+ for (const e of fresh(await this.events(id, after >= 0 ? after : undefined)))
181
+ yield e;
182
+ return;
183
+ }
184
+ await sleep(o.pollMs ?? 1_000, o.signal);
185
+ }
186
+ }
187
+ /** The next instruction in the same session: the same browser while it is kept, the same sign-ins, what earlier turns found. */
188
+ followUp(id, req) {
189
+ return this.c.request("POST", `/jobs/${enc(id)}/followup`, { body: typeof req === "string" ? { text: req } : req });
190
+ }
191
+ /** Carry a paused task on (`paused: true`, `next: "continue"`), as the app's Continue does. */
192
+ continue(id) {
193
+ return this.followUp(id, CONTINUE_TEXT);
194
+ }
195
+ /** Answer the task's open question (`task.question.id`). Codes and passwords go on its `answerUrl`, never here. */
196
+ async answer(id, questionId, answer) {
197
+ const a = typeof answer === "string" ? (["yes", "no", "done", "cancel", "skip"].includes(answer) ? { type: answer } : { type: "text", text: answer }) : answer;
198
+ await this.c.request("POST", `/jobs/${enc(id)}/answer`, { body: { questionId, answer: a } });
199
+ }
200
+ /** Tell a running task something in the person's words; it reads it before its next step. */
201
+ async message(id, text) {
202
+ await this.c.request("POST", `/jobs/${enc(id)}/message`, { body: { text } });
203
+ }
204
+ /** Stop a task for good (what it spent stays charged). */
205
+ async cancel(id) {
206
+ await this.c.request("DELETE", `/jobs/${enc(id)}`);
207
+ }
208
+ /** Take control: the agent stops at its next turn and the browser is the person's (the live view's control token). */
209
+ pause(id) {
210
+ return this.c.request("POST", `/jobs/${enc(id)}/pause`);
211
+ }
212
+ /** Hand the browser back: the agent carries on from where the person left it. */
213
+ resume(id) {
214
+ return this.c.request("POST", `/jobs/${enc(id)}/resume`);
215
+ }
216
+ /** The same task again with the same settings, as a new task in a new session. */
217
+ rerun(id) {
218
+ return this.c.request("POST", `/jobs/${enc(id)}/rerun`);
219
+ }
220
+ /** The task's whole session: its turns with their events, its files, and the browser kept for a follow-up. */
221
+ thread(id) {
222
+ return this.c.request("GET", `/jobs/${enc(id)}/thread`);
223
+ }
224
+ /** The session's files: attached, downloaded by the run, or PDFs it read. */
225
+ async files(id, o = {}) {
226
+ return this.c.request("GET", `/jobs/${enc(id)}/files`, { query: o });
227
+ }
228
+ /** One file's bytes, with its name and type. */
229
+ downloadFile(id, fileId) {
230
+ return this.c.download(`/jobs/${enc(id)}/files/${enc(fileId)}`);
231
+ }
232
+ /** The screenshots taken after the steps that changed the page. */
233
+ async frames(id) {
234
+ return (await this.c.request("GET", `/jobs/${enc(id)}/frames`)).frames;
235
+ }
236
+ /** The replay video (MP4), while it is kept (7 days by default). */
237
+ replayMp4(id) {
238
+ return this.c.download(`/jobs/${enc(id)}/replay.mp4`);
239
+ }
240
+ /** Delete the task's session from history (soft: its record and cost are kept for billing). */
241
+ async deleteSession(id) {
242
+ await this.c.request("DELETE", `/jobs/${enc(id)}/history`);
243
+ }
244
+ }
245
+ /** Batches: many tasks in one request, run one after another, their results collected together. */
246
+ export class Batches {
247
+ c;
248
+ constructor(c) {
249
+ this.c = c;
250
+ }
251
+ /** Start a batch (up to 100 tasks). Each task is charged when it runs; if credits run out the rest are skipped. */
252
+ create(req) {
253
+ return this.c.request("POST", "/batches", { body: Array.isArray(req) ? { tasks: req } : req });
254
+ }
255
+ /** Start a batch and wait for every task to end. */
256
+ async run(req, o = {}) {
257
+ const b = await this.create(req);
258
+ return this.wait(b.id, o);
259
+ }
260
+ /** A batch with each task's status, job id, cost and result. */
261
+ get(id) {
262
+ return this.c.request("GET", `/batches/${enc(id)}`);
263
+ }
264
+ /** Wait until the batch ends (done, cancelled or stopped). Throws WaitTimeoutError after `timeoutMs` (default 2 h). */
265
+ async wait(id, o = {}) {
266
+ const until = Date.now() + (o.timeoutMs ?? 2 * 3_600_000);
267
+ for (;;) {
268
+ const b = await this.get(id);
269
+ if (b.status !== "running")
270
+ return b;
271
+ if (Date.now() >= until)
272
+ throw new WaitTimeoutError(`Batch ${id} is still running: it carries on; wait again or cancel it.`);
273
+ await sleep(o.pollMs ?? 3_000, o.signal);
274
+ }
275
+ }
276
+ /** Your batches, newest first (without their items). */
277
+ async list(o = {}) {
278
+ const r = await this.c.request("GET", "/batches", { query: o });
279
+ return { items: r.batches, nextCursor: r.nextCursor };
280
+ }
281
+ /** Cancel: the running task is cancelled and the rest are skipped (never run, never charged). */
282
+ cancel(id) {
283
+ return this.c.request("POST", `/batches/${enc(id)}/cancel`);
284
+ }
285
+ }
286
+ /** Identities: your product's end users in a shared project (an org key's project), each with their own logins, sessions, IP and device. */
287
+ export class Identities {
288
+ c;
289
+ constructor(c) {
290
+ this.c = c;
291
+ }
292
+ /** Make one; with an `externalUserId` you already used, you get that one back (`existed: true`). */
293
+ create(o = {}) {
294
+ return this.c.request("POST", "/identities", { body: o });
295
+ }
296
+ get(id) {
297
+ return this.c.request("GET", `/identities/${enc(id)}`);
298
+ }
299
+ async list(o = {}) {
300
+ const r = await this.c.request("GET", "/identities", { query: o });
301
+ return { items: r.identities, nextCursor: r.nextCursor, total: r.total };
302
+ }
303
+ update(id, o) {
304
+ return this.c.request("PATCH", `/identities/${enc(id)}`, { body: o });
305
+ }
306
+ /** Wipes its logins, sessions and device; its tasks and their cost are kept. */
307
+ async delete(id) {
308
+ await this.c.request("DELETE", `/identities/${enc(id)}`);
309
+ }
310
+ /** What its tasks cost, since `since` (ms since the epoch; default: all of them). */
311
+ usage(id, o = {}) {
312
+ return this.c.request("GET", `/identities/${enc(id)}/usage`, { query: o });
313
+ }
314
+ /** Save a login for it from your own server (the values are sealed and never read back). */
315
+ addCredential(id, o) {
316
+ return this.c.request("POST", `/identities/${enc(id)}/credentials`, { body: o });
317
+ }
318
+ async credentials(id) {
319
+ return (await this.c.request("GET", `/identities/${enc(id)}/credentials`)).credentials;
320
+ }
321
+ async setDefaultCredential(id, credential) {
322
+ await this.c.request("PUT", `/identities/${enc(id)}/credentials/${enc(credential)}/default`);
323
+ }
324
+ async deleteCredential(id, credential) {
325
+ await this.c.request("DELETE", `/identities/${enc(id)}/credentials/${enc(credential)}`);
326
+ }
327
+ /** A one-time page where the end user types their own login for these sites. */
328
+ loginLink(id, o) {
329
+ return this.c.request("POST", `/identities/${enc(id)}/link`, { body: o });
330
+ }
331
+ }
332
+ /** Saved tasks (in your Personal project): run again with their settings, by hand or on a schedule. */
333
+ export class SavedTasks {
334
+ c;
335
+ constructor(c) {
336
+ this.c = c;
337
+ }
338
+ async list() {
339
+ return (await this.c.request("GET", "/saved-tasks")).tasks;
340
+ }
341
+ create(o) {
342
+ return this.c.request("POST", "/saved-tasks", { body: o });
343
+ }
344
+ update(id, o) {
345
+ return this.c.request("PUT", `/saved-tasks/${enc(id)}`, { body: o });
346
+ }
347
+ async delete(id) {
348
+ await this.c.request("DELETE", `/saved-tasks/${enc(id)}`);
349
+ }
350
+ /** Run it, with changes for this run only. */
351
+ run(id, o = {}) {
352
+ return this.c.request("POST", `/saved-tasks/${enc(id)}/run`, { body: o });
353
+ }
354
+ }
355
+ /** Schedules: a saved task run by itself. What would stop a run with nobody there is settled first (409 `not_ready`). */
356
+ export class Schedules {
357
+ c;
358
+ constructor(c) {
359
+ this.c = c;
360
+ }
361
+ async list() {
362
+ return (await this.c.request("GET", "/schedules")).schedules;
363
+ }
364
+ /** Schedule a saved task (`savedTaskId`), or a new task saved with it (`task`, `name`, `options`). */
365
+ create(o) {
366
+ return this.c.request("POST", "/schedules", { body: o });
367
+ }
368
+ update(savedTaskId, o) {
369
+ return this.c.request("PUT", `/schedules/${enc(savedTaskId)}`, { body: o });
370
+ }
371
+ async delete(savedTaskId) {
372
+ await this.c.request("DELETE", `/schedules/${enc(savedTaskId)}`);
373
+ }
374
+ }
375
+ /** Spending: yours (a key: its own), by kind, day, model and task, and what is left of an allowance. */
376
+ export class UsageApi {
377
+ c;
378
+ constructor(c) {
379
+ this.c = c;
380
+ }
381
+ /** The last `days` (default 30), or `from`/`to` (YYYY-MM-DD). */
382
+ get(o = {}) {
383
+ return this.c.request("GET", "/me/usage", { query: o });
384
+ }
385
+ }
@@ -0,0 +1,58 @@
1
+ /** One invalid field of a request (400 `invalid_request`, `invalid_schema`). */
2
+ export interface FieldError {
3
+ path: string;
4
+ message: string;
5
+ }
6
+ /** Any error the API answered with, or a request that never got an answer (`status` 0). */
7
+ export declare class PilotfishError extends Error {
8
+ /** HTTP status (0 when the request never got an answer). */
9
+ readonly status: number;
10
+ /** The error's code, e.g. `no_credits`, `one_session`, `not_found` (the HTTP status as text when the body had none). */
11
+ readonly code: string;
12
+ /** What to do about it, when the API says. */
13
+ readonly hint: string | undefined;
14
+ /** The documentation page for this error. */
15
+ readonly docs: string | undefined;
16
+ /** The invalid fields of a 400. */
17
+ readonly fields: FieldError[] | undefined;
18
+ /** Seconds to wait before trying again (429). */
19
+ readonly retryAfterS: number | undefined;
20
+ /** The whole response body (other figures some errors carry: `balanceUsd`, `limitUsd`, `threadId`…). */
21
+ readonly body: Record<string, unknown>;
22
+ constructor(status: number, body: Record<string, unknown>, message?: string);
23
+ }
24
+ /** 400: the request is not valid (`fields` says which parts). */
25
+ export declare class BadRequestError extends PilotfishError {
26
+ }
27
+ /** 401: no API key, or one that is wrong or revoked. */
28
+ export declare class AuthenticationError extends PilotfishError {
29
+ }
30
+ /** 402: out of credits (`no_credits`), an allowance used (`allocation_used`), or the org's monthly limit (`org_limit`). */
31
+ export declare class PaymentRequiredError extends PilotfishError {
32
+ }
33
+ /** 403: not allowed for this key or person (`admins_only`, `shared_project`…). */
34
+ export declare class PermissionDeniedError extends PilotfishError {
35
+ }
36
+ /** 404: no such task, batch or identity, or not one this key may see. */
37
+ export declare class NotFoundError extends PilotfishError {
38
+ }
39
+ /** 409: a task is already running (`one_session`, `identity_busy`), or the thing is not in a state for that. */
40
+ export declare class ConflictError extends PilotfishError {
41
+ }
42
+ /** 429: too many requests or tasks waiting (`rate_limited`, `queue_full`, `start_rate`); `retryAfterS` says when to try again. */
43
+ export declare class RateLimitError extends PilotfishError {
44
+ }
45
+ /** 5xx: the server failed. Safe to retry a read. */
46
+ export declare class ServerError extends PilotfishError {
47
+ }
48
+ /** The request never got an answer: the network, or the client's own timeout. */
49
+ export declare class ConnectionError extends PilotfishError {
50
+ readonly cause?: unknown | undefined;
51
+ constructor(message: string, cause?: unknown | undefined);
52
+ }
53
+ /** `wait()` gave up before the task or batch ended (the task carries on). */
54
+ export declare class WaitTimeoutError extends PilotfishError {
55
+ constructor(message: string);
56
+ }
57
+ /** The error class for a status. */
58
+ export declare function errorFor(status: number, body: Record<string, unknown>): PilotfishError;
package/dist/errors.js ADDED
@@ -0,0 +1,89 @@
1
+ // The API's errors as typed exceptions. Every error response is `{error, code, hint?, docs?, fields?, retryAfterS?}`
2
+ // (https://pilotfish.gai.ventures/docs/api#errors): the class says what kind it is, `code` exactly which.
3
+ /** Any error the API answered with, or a request that never got an answer (`status` 0). */
4
+ export class PilotfishError extends Error {
5
+ /** HTTP status (0 when the request never got an answer). */
6
+ status;
7
+ /** The error's code, e.g. `no_credits`, `one_session`, `not_found` (the HTTP status as text when the body had none). */
8
+ code;
9
+ /** What to do about it, when the API says. */
10
+ hint;
11
+ /** The documentation page for this error. */
12
+ docs;
13
+ /** The invalid fields of a 400. */
14
+ fields;
15
+ /** Seconds to wait before trying again (429). */
16
+ retryAfterS;
17
+ /** The whole response body (other figures some errors carry: `balanceUsd`, `limitUsd`, `threadId`…). */
18
+ body;
19
+ constructor(status, body, message) {
20
+ const text = message ?? (typeof body["error"] === "string" ? body["error"] : `HTTP ${status}`);
21
+ super(text);
22
+ this.name = new.target.name;
23
+ this.status = status;
24
+ this.body = body;
25
+ this.code = typeof body["code"] === "string" && body["code"] ? body["code"] : String(status);
26
+ this.hint = typeof body["hint"] === "string" ? body["hint"] : undefined;
27
+ this.docs = typeof body["docs"] === "string" ? body["docs"] : undefined;
28
+ this.fields = Array.isArray(body["fields"]) ? body["fields"] : undefined;
29
+ this.retryAfterS = typeof body["retryAfterS"] === "number" ? body["retryAfterS"] : undefined;
30
+ }
31
+ }
32
+ /** 400: the request is not valid (`fields` says which parts). */
33
+ export class BadRequestError extends PilotfishError {
34
+ }
35
+ /** 401: no API key, or one that is wrong or revoked. */
36
+ export class AuthenticationError extends PilotfishError {
37
+ }
38
+ /** 402: out of credits (`no_credits`), an allowance used (`allocation_used`), or the org's monthly limit (`org_limit`). */
39
+ export class PaymentRequiredError extends PilotfishError {
40
+ }
41
+ /** 403: not allowed for this key or person (`admins_only`, `shared_project`…). */
42
+ export class PermissionDeniedError extends PilotfishError {
43
+ }
44
+ /** 404: no such task, batch or identity, or not one this key may see. */
45
+ export class NotFoundError extends PilotfishError {
46
+ }
47
+ /** 409: a task is already running (`one_session`, `identity_busy`), or the thing is not in a state for that. */
48
+ export class ConflictError extends PilotfishError {
49
+ }
50
+ /** 429: too many requests or tasks waiting (`rate_limited`, `queue_full`, `start_rate`); `retryAfterS` says when to try again. */
51
+ export class RateLimitError extends PilotfishError {
52
+ }
53
+ /** 5xx: the server failed. Safe to retry a read. */
54
+ export class ServerError extends PilotfishError {
55
+ }
56
+ /** The request never got an answer: the network, or the client's own timeout. */
57
+ export class ConnectionError extends PilotfishError {
58
+ cause;
59
+ constructor(message, cause) {
60
+ super(0, { error: message, code: "connection_error" });
61
+ this.cause = cause;
62
+ }
63
+ }
64
+ /** `wait()` gave up before the task or batch ended (the task carries on). */
65
+ export class WaitTimeoutError extends PilotfishError {
66
+ constructor(message) {
67
+ super(0, { error: message, code: "wait_timeout" });
68
+ }
69
+ }
70
+ /** The error class for a status. */
71
+ export function errorFor(status, body) {
72
+ if (status === 400 || status === 422)
73
+ return new BadRequestError(status, body);
74
+ if (status === 401)
75
+ return new AuthenticationError(status, body);
76
+ if (status === 402)
77
+ return new PaymentRequiredError(status, body);
78
+ if (status === 403)
79
+ return new PermissionDeniedError(status, body);
80
+ if (status === 404 || status === 410)
81
+ return new NotFoundError(status, body);
82
+ if (status === 409)
83
+ return new ConflictError(status, body);
84
+ if (status === 429)
85
+ return new RateLimitError(status, body);
86
+ if (status >= 500)
87
+ return new ServerError(status, body);
88
+ return new PilotfishError(status, body);
89
+ }
@@ -0,0 +1,6 @@
1
+ export { Pilotfish, Tasks, Batches, Identities, SavedTasks, Schedules, UsageApi, DEFAULT_BASE_URL, CONTINUE_TEXT, type ClientOptions, type WaitOptions } from "./client.js";
2
+ export { LocalBrowser, LocalToolError, type LocalOptions, type LocalQuestion, type Step, type ToolResult } from "./local.js";
3
+ export { verifyWebhook, parseWebhook, signWebhook, type WebhookEvent } from "./webhooks.js";
4
+ export { PilotfishError, BadRequestError, AuthenticationError, PaymentRequiredError, PermissionDeniedError, NotFoundError, ConflictError, RateLimitError, ServerError, ConnectionError, WaitTimeoutError, type FieldError, } from "./errors.js";
5
+ export type * from "./types.js";
6
+ export { VERSION } from "./version.js";
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ // pilotfish SDK for TypeScript and JavaScript (https://pilotfish.gai.ventures/docs/sdk).
2
+ // Pilotfish the hosted client: tasks in pilotfish's cloud browser over the REST API, with an API key.
3
+ // LocalBrowser Chrome on your own machine, driven through the open MCP's browser tools: no key, no model calls.
4
+ export { Pilotfish, Tasks, Batches, Identities, SavedTasks, Schedules, UsageApi, DEFAULT_BASE_URL, CONTINUE_TEXT } from "./client.js";
5
+ export { LocalBrowser, LocalToolError } from "./local.js";
6
+ export { verifyWebhook, parseWebhook, signWebhook } from "./webhooks.js";
7
+ export { PilotfishError, BadRequestError, AuthenticationError, PaymentRequiredError, PermissionDeniedError, NotFoundError, ConflictError, RateLimitError, ServerError, ConnectionError, WaitTimeoutError, } from "./errors.js";
8
+ export { VERSION } from "./version.js";