@eigenpal/sdk 0.25.14 → 1.0.0-rc.2
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/README.md +27 -105
- package/dist/client.d.ts +164 -0
- package/dist/client.js +234 -0
- package/dist/core.d.ts +82 -0
- package/dist/core.js +311 -0
- package/dist/errors.d.ts +64 -0
- package/dist/errors.js +132 -0
- package/dist/generated/operations.gen.d.ts +336 -0
- package/dist/generated/operations.gen.js +135 -0
- package/dist/generated/public.gen.d.ts +2 -0
- package/dist/generated/public.gen.js +2 -0
- package/dist/generated/resources.gen.d.ts +490 -0
- package/dist/generated/resources.gen.js +659 -0
- package/dist/generated/types.gen.d.ts +2457 -0
- package/dist/generated/types.gen.js +2 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +15 -0
- package/dist/lib/fetch-body.d.ts +23 -0
- package/dist/lib/fetch-body.js +66 -0
- package/dist/lib/files.d.ts +134 -0
- package/dist/lib/files.js +296 -0
- package/dist/lib/upload-app-chunked.d.ts +36 -0
- package/dist/lib/upload-app-chunked.js +94 -0
- package/dist/lib/upload-limits.d.ts +32 -0
- package/dist/lib/upload-limits.js +60 -0
- package/dist/lib/upload-presigned-multipart.d.ts +74 -0
- package/dist/lib/upload-presigned-multipart.js +212 -0
- package/dist/page.d.ts +30 -0
- package/dist/page.js +38 -0
- package/dist/resources.d.ts +85 -0
- package/dist/resources.js +247 -0
- package/dist/telemetry.d.ts +20 -0
- package/{src/telemetry.ts → dist/telemetry.js} +26 -31
- package/dist/upload-file.d.ts +31 -0
- package/dist/upload-file.js +286 -0
- package/{src/upload.ts → dist/upload.d.ts} +4 -4
- package/dist/upload.js +12 -0
- package/package.json +19 -15
- package/src/client.ts +0 -656
- package/src/errors.ts +0 -130
- package/src/generated/client/client.gen.ts +0 -277
- package/src/generated/client/index.ts +0 -27
- package/src/generated/client/types.gen.ts +0 -218
- package/src/generated/client/utils.gen.ts +0 -316
- package/src/generated/client.gen.ts +0 -18
- package/src/generated/core/auth.gen.ts +0 -48
- package/src/generated/core/bodySerializer.gen.ts +0 -82
- package/src/generated/core/params.gen.ts +0 -178
- package/src/generated/core/pathSerializer.gen.ts +0 -171
- package/src/generated/core/queryKeySerializer.gen.ts +0 -117
- package/src/generated/core/serverSentEvents.gen.ts +0 -242
- package/src/generated/core/types.gen.ts +0 -110
- package/src/generated/core/utils.gen.ts +0 -140
- package/src/generated/index.ts +0 -4
- package/src/generated/sdk.gen.ts +0 -1361
- package/src/generated/types.gen.ts +0 -9282
- package/src/index.ts +0 -120
- package/src/lib/fetch-body.ts +0 -92
- package/src/lib/files.ts +0 -390
- package/src/lib/upload-app-chunked.ts +0 -121
- package/src/lib/upload-limits.ts +0 -72
- package/src/lib/upload-presigned-multipart.ts +0 -285
- package/src/resources/auth.ts +0 -18
- package/src/resources/automations.ts +0 -830
- package/src/resources/dataset-review-requests.ts +0 -38
- package/src/resources/email-servers.ts +0 -95
- package/src/resources/files.ts +0 -592
- package/src/resources/folders.ts +0 -77
- package/src/resources/human-reviews.ts +0 -106
- package/src/resources/models.ts +0 -37
- package/src/resources/runs.ts +0 -350
- package/src/resources/templates.ts +0 -153
- package/src/runtime-config.ts +0 -14
package/src/client.ts
DELETED
|
@@ -1,656 +0,0 @@
|
|
|
1
|
-
import { EigenpalError, EigenpalTimeoutError, errorFromResponse } from './errors';
|
|
2
|
-
import { createClient, createConfig, type Client, type Config } from './generated/client';
|
|
3
|
-
import type {
|
|
4
|
-
ApiErrorEnvelope,
|
|
5
|
-
RunsStartResponse as GeneratedRunStartResponse,
|
|
6
|
-
Run,
|
|
7
|
-
} from './generated/types.gen';
|
|
8
|
-
import {
|
|
9
|
-
buildRunJsonBody,
|
|
10
|
-
buildRunMultipart,
|
|
11
|
-
hasFileInput,
|
|
12
|
-
isFileInput,
|
|
13
|
-
isPathFileInput,
|
|
14
|
-
isReadStream,
|
|
15
|
-
resolveFileBlob,
|
|
16
|
-
statUploadSize,
|
|
17
|
-
type FileInput,
|
|
18
|
-
type PathFileInput,
|
|
19
|
-
} from './lib/files';
|
|
20
|
-
import { DEFAULT_MULTIPART_MAX_BYTES, keysRequiringPreUpload } from './lib/upload-limits';
|
|
21
|
-
import { sleep } from './lib/upload-presigned-multipart';
|
|
22
|
-
import { AuthResource } from './resources/auth';
|
|
23
|
-
import { AutomationsResource } from './resources/automations';
|
|
24
|
-
import { DatasetReviewRequestsResource } from './resources/dataset-review-requests';
|
|
25
|
-
import { EmailServersResource } from './resources/email-servers';
|
|
26
|
-
import { FilesResource } from './resources/files';
|
|
27
|
-
import { FoldersResource } from './resources/folders';
|
|
28
|
-
import { HumanReviewsResource } from './resources/human-reviews';
|
|
29
|
-
import { ModelsResource } from './resources/models';
|
|
30
|
-
import { RunsResource } from './resources/runs';
|
|
31
|
-
import { TemplatesResource } from './resources/templates';
|
|
32
|
-
import { buildTelemetryHeaders } from './telemetry';
|
|
33
|
-
|
|
34
|
-
export interface EigenpalOptions {
|
|
35
|
-
/**
|
|
36
|
-
* API key issued from Settings → API Keys (`eg_…`).
|
|
37
|
-
*
|
|
38
|
-
* Falls back to the `EIGENPAL_API_KEY` environment variable when omitted,
|
|
39
|
-
* so most users only need `new EigenpalClient()`.
|
|
40
|
-
*/
|
|
41
|
-
apiKey?: string;
|
|
42
|
-
/**
|
|
43
|
-
* Override the API base URL.
|
|
44
|
-
*
|
|
45
|
-
* Defaults to `EIGENPAL_BASE_URL` if set, otherwise `https://api.eigenpal.com`.
|
|
46
|
-
*/
|
|
47
|
-
baseUrl?: string;
|
|
48
|
-
/** Per-request timeout in milliseconds. Defaults to 60_000. */
|
|
49
|
-
timeoutMs?: number;
|
|
50
|
-
/**
|
|
51
|
-
* Maximum total HTTP multipart body size before run files are pre-uploaded.
|
|
52
|
-
*
|
|
53
|
-
* Defaults to `EIGENPAL_MULTIPART_MAX_BYTES` or 4.5 MiB. Set `null` (or the
|
|
54
|
-
* environment value `none`) to disable pre-uploads and keep every file on
|
|
55
|
-
* the run's multipart request, typically for self-hosted deployments.
|
|
56
|
-
*/
|
|
57
|
-
multipartMaxBytes?: number | null;
|
|
58
|
-
/** How many times to retry on 5xx / 429 / network errors. Defaults to 3. */
|
|
59
|
-
maxRetries?: number;
|
|
60
|
-
/** Inject a custom fetch implementation (testing). Defaults to global fetch. */
|
|
61
|
-
fetch?: typeof globalThis.fetch;
|
|
62
|
-
/** Extra headers attached to every request (debug ids, custom user-agent suffix, etc.). */
|
|
63
|
-
defaultHeaders?: Record<string, string>;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
const DEFAULT_BASE_URL = 'https://api.eigenpal.com';
|
|
67
|
-
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
68
|
-
const DEFAULT_MAX_RETRIES = 3;
|
|
69
|
-
|
|
70
|
-
/**
|
|
71
|
-
* Result shape returned by hey-api operation calls. We let hey-api default
|
|
72
|
-
* to `throwOnError: false` so we can centralize error mapping and retries
|
|
73
|
-
* in `_request`. The `error` field carries the parsed `ApiErrorEnvelope`
|
|
74
|
-
* for non-2xx responses; `data` is the success payload. `response` is
|
|
75
|
-
* optional only because hey-api's types declare it that way — at runtime
|
|
76
|
-
* it's always present once the fetch resolves.
|
|
77
|
-
*/
|
|
78
|
-
export interface OperationResult<T> {
|
|
79
|
-
data?: T;
|
|
80
|
-
error?: unknown;
|
|
81
|
-
response?: Response;
|
|
82
|
-
request?: Request;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
export interface RequestDispatchOptions {
|
|
86
|
-
responseKind?: 'json' | 'binary';
|
|
87
|
-
/**
|
|
88
|
-
* The request is not idempotent (run start, rerun): a lost response may mean
|
|
89
|
-
* the server already acted. Retry only when the server explicitly refused
|
|
90
|
-
* the request (429, or 503 with `Retry-After`); never on network errors,
|
|
91
|
-
* timeouts or other 5xx, which would create duplicate runs.
|
|
92
|
-
*/
|
|
93
|
-
nonIdempotent?: boolean;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
export type RunTarget =
|
|
97
|
-
| string
|
|
98
|
-
| {
|
|
99
|
-
type: 'workflow' | 'agent';
|
|
100
|
-
id?: string;
|
|
101
|
-
slug?: string;
|
|
102
|
-
version?: string;
|
|
103
|
-
};
|
|
104
|
-
|
|
105
|
-
export type RunInput = Record<string, unknown>;
|
|
106
|
-
|
|
107
|
-
/** Third argument to `client.run()` — transport knobs, not workflow/agent input. */
|
|
108
|
-
export interface RunCallOptions {
|
|
109
|
-
tags?: string | string[];
|
|
110
|
-
waitForCompletion?: number;
|
|
111
|
-
overrides?: { steps?: Record<string, Record<string, unknown>> };
|
|
112
|
-
metadata?: Record<string, unknown>;
|
|
113
|
-
signal?: AbortSignal;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
export interface RerunOptions {
|
|
117
|
-
version?: 'latest' | 'original' | string;
|
|
118
|
-
waitForCompletion?: number;
|
|
119
|
-
signal?: AbortSignal;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* Run-start response — async bodies are `{ id, type, finished: false }` (201);
|
|
124
|
-
* wait-expired bodies use the same shape (202); sync terminal completion matches
|
|
125
|
-
* `client.runs.get(id)` (200).
|
|
126
|
-
* Aliases the generated OpenAPI type so the handwritten and generated surfaces
|
|
127
|
-
* can never diverge.
|
|
128
|
-
*/
|
|
129
|
-
export type RunStartResponse = GeneratedRunStartResponse;
|
|
130
|
-
|
|
131
|
-
/** Narrow `RunStartResponse` to a terminal run with `output` and related fields. */
|
|
132
|
-
export function isRunFinished(run: RunStartResponse): run is Run {
|
|
133
|
-
return run.finished === true;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* The EigenPal SDK client.
|
|
138
|
-
*
|
|
139
|
-
* ```ts
|
|
140
|
-
* import { EigenpalClient } from '@eigenpal/sdk';
|
|
141
|
-
*
|
|
142
|
-
* // Reads EIGENPAL_API_KEY from env automatically.
|
|
143
|
-
* const client = new EigenpalClient();
|
|
144
|
-
*
|
|
145
|
-
* // Async — enqueue and poll later.
|
|
146
|
-
* const { id } = await client.run('workflows.extract-invoice', { language: 'en' });
|
|
147
|
-
*
|
|
148
|
-
* // Sync (server holds the connection up to 60s).
|
|
149
|
-
* const result = await client.run(
|
|
150
|
-
* 'workflows.extract-invoice',
|
|
151
|
-
* { language: 'en' },
|
|
152
|
-
* { waitForCompletion: 60 }
|
|
153
|
-
* );
|
|
154
|
-
*
|
|
155
|
-
* // Inspect the final run later.
|
|
156
|
-
* const final = await client.runs.get(id);
|
|
157
|
-
* ```
|
|
158
|
-
*/
|
|
159
|
-
export class EigenpalClient {
|
|
160
|
-
/** API key identity and current tenant context. */
|
|
161
|
-
public readonly auth: AuthResource;
|
|
162
|
-
/** Configured text, vision, and OCR models for this tenant environment. */
|
|
163
|
-
public readonly models: ModelsResource;
|
|
164
|
-
/** Automation metadata across workflows and agents. Start runs with `client.run(...)`. */
|
|
165
|
-
public readonly automations: AutomationsResource;
|
|
166
|
-
/** Tenant-wide dataset review inbox. Reviewer-facing: no workflow access required. */
|
|
167
|
-
public readonly datasetReviewRequests: DatasetReviewRequestsResource;
|
|
168
|
-
/** Workflow and template folder trees. Nested agent directories in Git are not folders. */
|
|
169
|
-
public readonly folders: FoldersResource;
|
|
170
|
-
/** Tenant-wide run operations across workflow, agent, manual, and eval runs. */
|
|
171
|
-
public readonly runs: RunsResource;
|
|
172
|
-
/** Reusable uploaded files that can be referenced by later runs. */
|
|
173
|
-
public readonly files: FilesResource;
|
|
174
|
-
/** Human review queue tasks created by workflow and agent runs. */
|
|
175
|
-
public readonly humanReviews: HumanReviewsResource;
|
|
176
|
-
/** Tenant-scoped DOCX/XLSX templates with immutable content revisions. */
|
|
177
|
-
public readonly templates: TemplatesResource;
|
|
178
|
-
/** Outbound email servers for workflow Email actions. Secrets are never returned. */
|
|
179
|
-
public readonly emailServers: EmailServersResource;
|
|
180
|
-
|
|
181
|
-
/** Underlying hey-api client. Use `getRawClient()` for advanced cases. */
|
|
182
|
-
private readonly client: Client;
|
|
183
|
-
private readonly maxRetries: number;
|
|
184
|
-
private readonly timeoutMs: number;
|
|
185
|
-
private readonly multipartMaxBytes: number | null;
|
|
186
|
-
|
|
187
|
-
constructor(options: EigenpalOptions = {}) {
|
|
188
|
-
const apiKey = options.apiKey ?? readEnv('EIGENPAL_API_KEY');
|
|
189
|
-
if (!apiKey) {
|
|
190
|
-
throw new EigenpalError(
|
|
191
|
-
'Missing API key. Pass `new EigenpalClient({ apiKey })` or set the EIGENPAL_API_KEY environment variable.',
|
|
192
|
-
{ status: 0 }
|
|
193
|
-
);
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
|
|
197
|
-
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
198
|
-
this.multipartMaxBytes = resolveMultipartMaxBytes(options.multipartMaxBytes);
|
|
199
|
-
|
|
200
|
-
const baseUrl = options.baseUrl ?? readEnv('EIGENPAL_BASE_URL') ?? DEFAULT_BASE_URL;
|
|
201
|
-
const config: Config = createConfig({
|
|
202
|
-
baseUrl,
|
|
203
|
-
headers: {
|
|
204
|
-
Authorization: `Bearer ${apiKey}`,
|
|
205
|
-
// SDK telemetry headers (X-Eigenpal-Sdk-*) + a richer User-Agent.
|
|
206
|
-
// User-supplied defaultHeaders override these so callers can opt out
|
|
207
|
-
// of telemetry by passing their own User-Agent / X-Eigenpal-Sdk.
|
|
208
|
-
...buildTelemetryHeaders(),
|
|
209
|
-
...(options.defaultHeaders ?? {}),
|
|
210
|
-
},
|
|
211
|
-
});
|
|
212
|
-
|
|
213
|
-
this.client = createClient(config);
|
|
214
|
-
if (options.fetch) {
|
|
215
|
-
// hey-api's Config types `fetch` as `typeof fetch` (DOM type that
|
|
216
|
-
// includes `preconnect`). At runtime any `(Request) => Promise<Response>`
|
|
217
|
-
// works; cast to bypass the structural mismatch.
|
|
218
|
-
this.client.setConfig({ fetch: options.fetch as never });
|
|
219
|
-
}
|
|
220
|
-
this.installTimeoutInterceptor();
|
|
221
|
-
|
|
222
|
-
this.auth = new AuthResource(this.client, this._request.bind(this));
|
|
223
|
-
this.models = new ModelsResource(this.client, this._request.bind(this));
|
|
224
|
-
this.automations = new AutomationsResource(this.client, this._request.bind(this));
|
|
225
|
-
this.datasetReviewRequests = new DatasetReviewRequestsResource(
|
|
226
|
-
this.client,
|
|
227
|
-
this._request.bind(this)
|
|
228
|
-
);
|
|
229
|
-
this.folders = new FoldersResource(this.client, this._request.bind(this));
|
|
230
|
-
this.runs = new RunsResource(this.client, this._request.bind(this));
|
|
231
|
-
this.files = new FilesResource(this.client, this._request.bind(this));
|
|
232
|
-
this.humanReviews = new HumanReviewsResource(this.client, this._request.bind(this));
|
|
233
|
-
this.templates = new TemplatesResource(this.client, this._request.bind(this), this.files);
|
|
234
|
-
this.emailServers = new EmailServersResource(this.client, this._request.bind(this));
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
/** Expose the underlying hey-api client for advanced use (custom interceptors, etc.). */
|
|
238
|
-
getRawClient(): Client {
|
|
239
|
-
return this.client;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
async run(
|
|
243
|
-
target: RunTarget,
|
|
244
|
-
input?: RunInput,
|
|
245
|
-
options: RunCallOptions = {}
|
|
246
|
-
): Promise<RunStartResponse> {
|
|
247
|
-
assertRunTarget(target);
|
|
248
|
-
assertInputNotOptionsBag(input);
|
|
249
|
-
|
|
250
|
-
const { pathTarget, version } = pathTargetFromRunTarget(target);
|
|
251
|
-
const query = runQuery({
|
|
252
|
-
waitForCompletion: options.waitForCompletion,
|
|
253
|
-
version,
|
|
254
|
-
});
|
|
255
|
-
|
|
256
|
-
const preparedInput = input ? await this.prepareRunFileInputs(input, options.signal) : input;
|
|
257
|
-
|
|
258
|
-
if (hasFileInput(preparedInput)) {
|
|
259
|
-
// Small files stay on the explicit multipart contract (and on-prem has no
|
|
260
|
-
// Vercel body ceiling). Large values were already replaced with $fileId.
|
|
261
|
-
const { formData } = await buildRunMultipart({
|
|
262
|
-
target: pathTarget,
|
|
263
|
-
input: preparedInput,
|
|
264
|
-
overrides: options.overrides,
|
|
265
|
-
metadata: options.metadata,
|
|
266
|
-
tags: options.tags,
|
|
267
|
-
});
|
|
268
|
-
return this._request<RunStartResponse>(
|
|
269
|
-
() =>
|
|
270
|
-
this.client.post({
|
|
271
|
-
url: '/v1/runs',
|
|
272
|
-
query,
|
|
273
|
-
body: formData,
|
|
274
|
-
bodySerializer: null,
|
|
275
|
-
headers: { 'Content-Type': null },
|
|
276
|
-
signal: options.signal,
|
|
277
|
-
}) as Promise<OperationResult<RunStartResponse>>,
|
|
278
|
-
{ nonIdempotent: true }
|
|
279
|
-
);
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
const body = {
|
|
283
|
-
...buildRunJsonBody(pathTarget, preparedInput, options.overrides, options.metadata),
|
|
284
|
-
...(options.tags !== undefined ? { tags: options.tags } : {}),
|
|
285
|
-
};
|
|
286
|
-
return this._request<RunStartResponse>(
|
|
287
|
-
() =>
|
|
288
|
-
this.client.post({
|
|
289
|
-
url: '/v1/runs',
|
|
290
|
-
query,
|
|
291
|
-
body,
|
|
292
|
-
signal: options.signal,
|
|
293
|
-
}) as Promise<OperationResult<RunStartResponse>>,
|
|
294
|
-
{ nonIdempotent: true }
|
|
295
|
-
);
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
/**
|
|
299
|
-
* Pre-upload file values when the aggregate multipart payload (all file
|
|
300
|
-
* bytes + envelope headroom) would exceed the configured body limit.
|
|
301
|
-
* Remaining small files keep the multipart path for a single round-trip;
|
|
302
|
-
* a null limit keeps every file there.
|
|
303
|
-
*/
|
|
304
|
-
private async prepareRunFileInputs(input: RunInput, signal?: AbortSignal): Promise<RunInput> {
|
|
305
|
-
if (!hasFileInput(input)) return input;
|
|
306
|
-
|
|
307
|
-
const resolved: Array<{ key: string; file: FileInput; filename: string; size: number }> = [];
|
|
308
|
-
for (const [key, value] of Object.entries(input)) {
|
|
309
|
-
if (!isFileInput(value)) continue;
|
|
310
|
-
if (isPathFileInput(value)) {
|
|
311
|
-
try {
|
|
312
|
-
const meta = await statUploadSize(value);
|
|
313
|
-
resolved.push({
|
|
314
|
-
key,
|
|
315
|
-
file: value,
|
|
316
|
-
filename: meta.filename,
|
|
317
|
-
size: meta.size,
|
|
318
|
-
});
|
|
319
|
-
continue;
|
|
320
|
-
} catch {
|
|
321
|
-
// Fake or unreadable stream paths still drain, matching prior SDK behavior.
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
if (isReadStream(value) && typeof value.path === 'string') {
|
|
325
|
-
try {
|
|
326
|
-
const meta = await statUploadSize(value);
|
|
327
|
-
const pathInput: PathFileInput = { path: value.path };
|
|
328
|
-
resolved.push({
|
|
329
|
-
key,
|
|
330
|
-
file: pathInput,
|
|
331
|
-
filename: meta.filename,
|
|
332
|
-
size: meta.size,
|
|
333
|
-
});
|
|
334
|
-
continue;
|
|
335
|
-
} catch {
|
|
336
|
-
// Fake or unreadable stream paths still drain, matching prior SDK behavior.
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
const { blob, filename } = await resolveFileBlob(value);
|
|
340
|
-
resolved.push({ key, file: blob, filename, size: blob.size });
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
const preUploadKeys = keysRequiringPreUpload(
|
|
344
|
-
resolved.map(({ key, size }) => ({ key, size })),
|
|
345
|
-
this.multipartMaxBytes
|
|
346
|
-
);
|
|
347
|
-
|
|
348
|
-
const next: RunInput = { ...input };
|
|
349
|
-
for (const { key, file, filename } of resolved) {
|
|
350
|
-
if (preUploadKeys.has(key)) {
|
|
351
|
-
const uploaded = await this.files.upload(file, {
|
|
352
|
-
filename,
|
|
353
|
-
signal,
|
|
354
|
-
purpose: 'run-input',
|
|
355
|
-
});
|
|
356
|
-
next[key] = { $fileId: uploaded.id };
|
|
357
|
-
continue;
|
|
358
|
-
}
|
|
359
|
-
// Prefer a concrete Blob/File so drained streams can still be multiparted.
|
|
360
|
-
if (typeof Blob !== 'undefined' && file instanceof Blob) {
|
|
361
|
-
next[key] =
|
|
362
|
-
typeof File !== 'undefined'
|
|
363
|
-
? new File([file], filename, { type: file.type || 'application/octet-stream' })
|
|
364
|
-
: file;
|
|
365
|
-
continue;
|
|
366
|
-
}
|
|
367
|
-
next[key] = file;
|
|
368
|
-
}
|
|
369
|
-
return next;
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
async rerun(runId: string, options: RerunOptions = {}): Promise<RunStartResponse> {
|
|
373
|
-
const query: { version?: string; wait_for_completion?: number } = {};
|
|
374
|
-
if (options.version && options.version !== 'latest') {
|
|
375
|
-
query.version = options.version;
|
|
376
|
-
}
|
|
377
|
-
if (options.waitForCompletion !== undefined) {
|
|
378
|
-
query.wait_for_completion = options.waitForCompletion;
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
return this._request<RunStartResponse>(
|
|
382
|
-
() =>
|
|
383
|
-
this.client.post({
|
|
384
|
-
url: '/v1/runs/{id}/rerun',
|
|
385
|
-
path: { id: runId },
|
|
386
|
-
query: Object.keys(query).length > 0 ? query : undefined,
|
|
387
|
-
signal: options.signal,
|
|
388
|
-
}) as Promise<OperationResult<RunStartResponse>>
|
|
389
|
-
);
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
/**
|
|
393
|
-
* Run an operation with automatic retries on 5xx / 429 / network errors,
|
|
394
|
-
* and centralized error mapping into typed `EigenpalError` subclasses.
|
|
395
|
-
* Non-idempotent calls (`options.nonIdempotent`) retry only on 429 and on
|
|
396
|
-
* 503 with `Retry-After`.
|
|
397
|
-
*
|
|
398
|
-
* Resources call this via the bound `_request` they receive at construction.
|
|
399
|
-
* The retry budget is `maxRetries`; backoff is exponential (250ms × 2^attempt)
|
|
400
|
-
* unless the response carries a `Retry-After` header.
|
|
401
|
-
*/
|
|
402
|
-
private async _request<T>(
|
|
403
|
-
call: () => Promise<OperationResult<T>>,
|
|
404
|
-
options: RequestDispatchOptions = {}
|
|
405
|
-
): Promise<T> {
|
|
406
|
-
for (let attempt = 0; ; attempt++) {
|
|
407
|
-
try {
|
|
408
|
-
const result = await call();
|
|
409
|
-
const response = result.response;
|
|
410
|
-
const status = response?.status ?? 0;
|
|
411
|
-
// Guard against misconfigured `baseUrl` pointed at an HTML host
|
|
412
|
-
// (e.g. `https://eigenpal.com` instead of `https://api.eigenpal.com`).
|
|
413
|
-
// Fires for both 2xx and non-2xx so a 4xx with HTML surfaces a typed
|
|
414
|
-
// baseUrl-pointing error instead of a misleading NotFoundError or a
|
|
415
|
-
// downstream JSON-parse crash. 0.4.10 shipped with this footgun.
|
|
416
|
-
//
|
|
417
|
-
// Don't run on retriable statuses — a 503 maintenance page from a
|
|
418
|
-
// CDN is transient and should consume retry budget, not throw on
|
|
419
|
-
// attempt zero. Only fire when we're about to surface the response
|
|
420
|
-
// as a final result or final error.
|
|
421
|
-
const retriable = options.nonIdempotent
|
|
422
|
-
? isRefusedStatus(status, response)
|
|
423
|
-
: isRetriableStatus(status);
|
|
424
|
-
const willRetry = retriable && attempt < this.maxRetries;
|
|
425
|
-
if (response && !willRetry) {
|
|
426
|
-
if (options.responseKind === 'binary') assertBinaryResponse(response);
|
|
427
|
-
else assertJsonResponse(response);
|
|
428
|
-
}
|
|
429
|
-
if (response && response.ok && result.data !== undefined) {
|
|
430
|
-
return result.data;
|
|
431
|
-
}
|
|
432
|
-
// Non-2xx (or response missing — treat as opaque failure).
|
|
433
|
-
if (willRetry) {
|
|
434
|
-
await sleep(retryDelay(response, attempt));
|
|
435
|
-
continue;
|
|
436
|
-
}
|
|
437
|
-
const envelope = asEnvelope(result.error);
|
|
438
|
-
const retryAfter = parseRetryAfter(response?.headers.get('retry-after') ?? null);
|
|
439
|
-
throw errorFromResponse(status, envelope, retryAfter);
|
|
440
|
-
} catch (err) {
|
|
441
|
-
// Re-throw mapped EigenpalError subclasses as-is.
|
|
442
|
-
if (err instanceof EigenpalError) throw err;
|
|
443
|
-
// Network/abort error — retry if budget allows. AbortSignal aborts
|
|
444
|
-
// surface as DOMException — we treat them as terminal (don't retry).
|
|
445
|
-
if (isAbortError(err)) throw err;
|
|
446
|
-
if (!options.nonIdempotent && attempt < this.maxRetries) {
|
|
447
|
-
await sleep(backoff(attempt));
|
|
448
|
-
continue;
|
|
449
|
-
}
|
|
450
|
-
throw err;
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
/**
|
|
456
|
-
* Add a request-level default timeout. The hey-api client honors any
|
|
457
|
-
* `signal` the caller passes; we only attach a fresh AbortController when
|
|
458
|
-
* none is provided (so per-call signals always win).
|
|
459
|
-
*/
|
|
460
|
-
private installTimeoutInterceptor(): void {
|
|
461
|
-
const timeoutMs = this.timeoutMs;
|
|
462
|
-
if (timeoutMs <= 0) return;
|
|
463
|
-
|
|
464
|
-
this.client.interceptors.request.use(async (req) => {
|
|
465
|
-
if (req.signal) return req;
|
|
466
|
-
const ctrl = new AbortController();
|
|
467
|
-
const timer = setTimeout(() => ctrl.abort(new EigenpalTimeoutError()), timeoutMs);
|
|
468
|
-
// unref keeps the timer from holding the Node.js event loop open after
|
|
469
|
-
// the request resolves. Browsers don't have unref — guard with `?.`.
|
|
470
|
-
timer.unref?.();
|
|
471
|
-
return new Request(req, { signal: ctrl.signal });
|
|
472
|
-
});
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
function pathTargetFromRunTarget(target: RunTarget): { pathTarget: string; version?: string } {
|
|
477
|
-
if (typeof target === 'string') {
|
|
478
|
-
const [pathTarget, version, extra] = target.split('@');
|
|
479
|
-
if (!pathTarget || version === '' || extra !== undefined) {
|
|
480
|
-
throw new EigenpalError('Run target strings must be <target> or <target>@<version>.', {
|
|
481
|
-
status: 0,
|
|
482
|
-
});
|
|
483
|
-
}
|
|
484
|
-
return { pathTarget, version: version && version !== 'latest' ? version : undefined };
|
|
485
|
-
}
|
|
486
|
-
const idOrSlug = target.slug ?? target.id;
|
|
487
|
-
if (!idOrSlug) {
|
|
488
|
-
throw new EigenpalError('Run target objects require `slug` or `id`.', { status: 0 });
|
|
489
|
-
}
|
|
490
|
-
const name =
|
|
491
|
-
target.type === 'agent'
|
|
492
|
-
? agentPathTarget(idOrSlug)
|
|
493
|
-
: `workflows.${idOrSlug.split('/').join('.')}`;
|
|
494
|
-
return {
|
|
495
|
-
pathTarget: name,
|
|
496
|
-
version: target.version && target.version !== 'latest' ? target.version : undefined,
|
|
497
|
-
};
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
function agentPathTarget(idOrSlug: string): string {
|
|
501
|
-
if (!idOrSlug.includes('.')) return `agents.${idOrSlug.split('/').join('.')}`;
|
|
502
|
-
if (!idOrSlug.startsWith('agents.')) {
|
|
503
|
-
throw new EigenpalError(`Agent target must be rooted at "agents.", got "${idOrSlug}".`, {
|
|
504
|
-
status: 0,
|
|
505
|
-
});
|
|
506
|
-
}
|
|
507
|
-
return idOrSlug;
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
function runQuery(options: {
|
|
511
|
-
waitForCompletion?: number;
|
|
512
|
-
version?: string;
|
|
513
|
-
}): { wait_for_completion?: number; version?: string } | undefined {
|
|
514
|
-
const query: { wait_for_completion?: number; version?: string } = {};
|
|
515
|
-
if (options.waitForCompletion !== undefined)
|
|
516
|
-
query.wait_for_completion = options.waitForCompletion;
|
|
517
|
-
if (options.version) query.version = options.version;
|
|
518
|
-
return Object.keys(query).length > 0 ? query : undefined;
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
function assertJsonResponse(response: Response): void {
|
|
522
|
-
// 204 No Content has no body — accept silently.
|
|
523
|
-
if (response.status === 204) return;
|
|
524
|
-
const contentType = response.headers.get('content-type')?.toLowerCase() ?? '';
|
|
525
|
-
// Match `application/json`, `application/problem+json`, etc. Empty
|
|
526
|
-
// Content-Type is tolerated since some proxies strip it on small bodies.
|
|
527
|
-
if (
|
|
528
|
-
contentType === '' ||
|
|
529
|
-
contentType.includes('json') ||
|
|
530
|
-
contentType.includes('octet-stream') ||
|
|
531
|
-
contentType.includes('zip')
|
|
532
|
-
)
|
|
533
|
-
return;
|
|
534
|
-
throw new EigenpalError(
|
|
535
|
-
`Expected a JSON response from the API but got Content-Type "${contentType}". ` +
|
|
536
|
-
`This usually means \`baseUrl\` points at a non-API host (e.g. the marketing site or ` +
|
|
537
|
-
`a misconfigured proxy). Set \`baseUrl\` to your EigenPal instance root, ` +
|
|
538
|
-
`e.g. "https://api.eigenpal.com".`,
|
|
539
|
-
{ status: response.status }
|
|
540
|
-
);
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
function assertBinaryResponse(response: Response): void {
|
|
544
|
-
if (response.status === 204) return;
|
|
545
|
-
const contentType = response.headers.get('content-type')?.toLowerCase() ?? '';
|
|
546
|
-
if (contentType === '' || (!contentType.includes('html') && !contentType.includes('json'))) {
|
|
547
|
-
return;
|
|
548
|
-
}
|
|
549
|
-
throw new EigenpalError(
|
|
550
|
-
`Expected a binary response from the API but got Content-Type "${contentType}". ` +
|
|
551
|
-
`This usually means \`baseUrl\` points at a non-API host or a misconfigured proxy.`,
|
|
552
|
-
{ status: response.status }
|
|
553
|
-
);
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
function assertRunTarget(target: RunTarget): void {
|
|
557
|
-
if (typeof target === 'object' && target !== null && 'target' in target) {
|
|
558
|
-
throw new EigenpalError(
|
|
559
|
-
'Pass the run target as the first argument to client.run(target, input?, options?). ' +
|
|
560
|
-
'Do not wrap it in { target }.',
|
|
561
|
-
{ status: 0 }
|
|
562
|
-
);
|
|
563
|
-
}
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
function assertInputNotOptionsBag(input: RunInput | undefined): void {
|
|
567
|
-
if (!input || typeof input !== 'object') return;
|
|
568
|
-
if (
|
|
569
|
-
'waitForCompletion' in input ||
|
|
570
|
-
'overrides' in input ||
|
|
571
|
-
'metadata' in input ||
|
|
572
|
-
'signal' in input
|
|
573
|
-
) {
|
|
574
|
-
throw new EigenpalError(
|
|
575
|
-
'Pass workflow/agent input as the second argument and { waitForCompletion, overrides, metadata, signal } as the third.',
|
|
576
|
-
{ status: 0 }
|
|
577
|
-
);
|
|
578
|
-
}
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
function isRetriableStatus(status: number): boolean {
|
|
582
|
-
return status >= 500 || status === 429;
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
/** The server explicitly refused the request, so retrying cannot duplicate work. */
|
|
586
|
-
function isRefusedStatus(status: number, response: Response | undefined): boolean {
|
|
587
|
-
if (status === 429) return true;
|
|
588
|
-
return status === 503 && response?.headers.get('retry-after') != null;
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
function retryDelay(response: Response | undefined, attempt: number): number {
|
|
592
|
-
const retryAfterSec = parseRetryAfter(response?.headers.get('retry-after') ?? null);
|
|
593
|
-
return retryAfterSec !== undefined ? retryAfterSec * 1000 : backoff(attempt);
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
function backoff(attempt: number): number {
|
|
597
|
-
return 250 * 2 ** attempt; // 250, 500, 1000, 2000ms
|
|
598
|
-
}
|
|
599
|
-
|
|
600
|
-
function parseRetryAfter(value: string | null): number | undefined {
|
|
601
|
-
if (!value) return undefined;
|
|
602
|
-
const seconds = Number(value);
|
|
603
|
-
return Number.isFinite(seconds) && seconds >= 0 ? seconds : undefined;
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
function isAbortError(err: unknown): boolean {
|
|
607
|
-
if (err instanceof EigenpalTimeoutError) return true;
|
|
608
|
-
if (typeof err === 'object' && err !== null && 'name' in err) {
|
|
609
|
-
return (err as { name: string }).name === 'AbortError';
|
|
610
|
-
}
|
|
611
|
-
return false;
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
function asEnvelope(error: unknown): ApiErrorEnvelope | undefined {
|
|
615
|
-
if (error && typeof error === 'object' && Array.isArray((error as { issues?: unknown }).issues)) {
|
|
616
|
-
return error as ApiErrorEnvelope;
|
|
617
|
-
}
|
|
618
|
-
return undefined;
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
/**
|
|
622
|
-
* Read a single env var as a fallback for an explicit constructor option.
|
|
623
|
-
*
|
|
624
|
-
* The repo's `no-process-env` rule pushes other packages toward
|
|
625
|
-
* `@eigenpal/env`, but this is a published SDK — it can't pull internal
|
|
626
|
-
* env infrastructure. The disables below are scoped to this one helper.
|
|
627
|
-
*/
|
|
628
|
-
function readEnv(name: string): string | undefined {
|
|
629
|
-
// eslint-disable-next-line no-process-env
|
|
630
|
-
if (typeof process !== 'undefined' && process.env) {
|
|
631
|
-
// eslint-disable-next-line no-process-env
|
|
632
|
-
const v = process.env[name];
|
|
633
|
-
return v && v.length > 0 ? v : undefined;
|
|
634
|
-
}
|
|
635
|
-
return undefined;
|
|
636
|
-
}
|
|
637
|
-
|
|
638
|
-
function resolveMultipartMaxBytes(explicit: number | null | undefined): number | null {
|
|
639
|
-
if (explicit !== undefined) {
|
|
640
|
-
if (explicit === null) return null;
|
|
641
|
-
if (Number.isSafeInteger(explicit) && explicit >= 0) return explicit;
|
|
642
|
-
throw new EigenpalError('multipartMaxBytes must be a non-negative integer or null.', {
|
|
643
|
-
status: 0,
|
|
644
|
-
});
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
const raw = readEnv('EIGENPAL_MULTIPART_MAX_BYTES')?.trim().toLowerCase();
|
|
648
|
-
if (!raw) return DEFAULT_MULTIPART_MAX_BYTES;
|
|
649
|
-
if (raw === 'none' || raw === 'null' || raw === 'unlimited') return null;
|
|
650
|
-
const parsed = Number(raw);
|
|
651
|
-
if (Number.isSafeInteger(parsed) && parsed >= 0) return parsed;
|
|
652
|
-
throw new EigenpalError(
|
|
653
|
-
'EIGENPAL_MULTIPART_MAX_BYTES must be a non-negative integer or one of: none, null, unlimited.',
|
|
654
|
-
{ status: 0 }
|
|
655
|
-
);
|
|
656
|
-
}
|