@parcha/agentrun 0.1.0 → 0.2.1
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/CHANGELOG.md +27 -0
- package/README.md +141 -113
- package/dist/index.cjs +1182 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +682 -0
- package/dist/index.d.ts +682 -0
- package/dist/index.js +1150 -0
- package/dist/index.js.map +1 -0
- package/package.json +46 -6
- package/dist/agent.d.ts +0 -434
- package/dist/agent.js +0 -653
package/dist/agent.js
DELETED
|
@@ -1,653 +0,0 @@
|
|
|
1
|
-
export class AgentBuildError extends Error {
|
|
2
|
-
build;
|
|
3
|
-
constructor(build) {
|
|
4
|
-
super("Agent creation failed. Inspect the build before starting a new one.");
|
|
5
|
-
this.build = build;
|
|
6
|
-
this.name = "AgentBuildError";
|
|
7
|
-
}
|
|
8
|
-
}
|
|
9
|
-
function pollingSignal(options, defaultTimeout) {
|
|
10
|
-
const interval = options.intervalMs ?? 1000;
|
|
11
|
-
const timeout = options.timeoutMs ?? defaultTimeout;
|
|
12
|
-
if (!Number.isFinite(interval) ||
|
|
13
|
-
interval <= 0 ||
|
|
14
|
-
!Number.isFinite(timeout) ||
|
|
15
|
-
timeout <= 0)
|
|
16
|
-
throw new Error("Polling interval and timeout must be positive.");
|
|
17
|
-
const deadline = AbortSignal.timeout(timeout);
|
|
18
|
-
return {
|
|
19
|
-
interval,
|
|
20
|
-
signal: options.signal
|
|
21
|
-
? AbortSignal.any([options.signal, deadline])
|
|
22
|
-
: deadline,
|
|
23
|
-
};
|
|
24
|
-
}
|
|
25
|
-
function delay(interval, signal) {
|
|
26
|
-
return new Promise((resolve, reject) => {
|
|
27
|
-
const done = () => {
|
|
28
|
-
signal.removeEventListener("abort", aborted);
|
|
29
|
-
resolve();
|
|
30
|
-
};
|
|
31
|
-
const timer = setTimeout(done, interval);
|
|
32
|
-
const aborted = () => {
|
|
33
|
-
clearTimeout(timer);
|
|
34
|
-
signal.removeEventListener("abort", aborted);
|
|
35
|
-
reject(signal.reason);
|
|
36
|
-
};
|
|
37
|
-
signal.addEventListener("abort", aborted, { once: true });
|
|
38
|
-
if (signal.aborted)
|
|
39
|
-
aborted();
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
/** Parse CSV cells without losing quoted commas, escaped quotes, or embedded newlines. */
|
|
43
|
-
export function parseBatchCSV(csv, inputColumn) {
|
|
44
|
-
if (new TextEncoder().encode(csv).length > 1000000)
|
|
45
|
-
throw new Error("CSV must be at most 1 MB.");
|
|
46
|
-
const records = [];
|
|
47
|
-
let row = [], field = "", quoted = false, closed = false;
|
|
48
|
-
const cell = () => {
|
|
49
|
-
row.push(field);
|
|
50
|
-
field = "";
|
|
51
|
-
closed = false;
|
|
52
|
-
};
|
|
53
|
-
const record = () => {
|
|
54
|
-
cell();
|
|
55
|
-
if (row.some((value) => value !== ""))
|
|
56
|
-
records.push(row);
|
|
57
|
-
row = [];
|
|
58
|
-
if (records.length > 101)
|
|
59
|
-
throw new Error("A batch accepts at most 100 inputs.");
|
|
60
|
-
};
|
|
61
|
-
csv = csv.replace(/^\uFEFF/, "");
|
|
62
|
-
for (let i = 0; i < csv.length; i++) {
|
|
63
|
-
const char = csv[i];
|
|
64
|
-
if (quoted) {
|
|
65
|
-
if (char === '"') {
|
|
66
|
-
if (csv[i + 1] === '"') {
|
|
67
|
-
field += '"';
|
|
68
|
-
i++;
|
|
69
|
-
}
|
|
70
|
-
else {
|
|
71
|
-
quoted = false;
|
|
72
|
-
closed = true;
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
else
|
|
76
|
-
field += char;
|
|
77
|
-
}
|
|
78
|
-
else if (char === ",")
|
|
79
|
-
cell();
|
|
80
|
-
else if (char === "\n" || char === "\r") {
|
|
81
|
-
if (char === "\r" && csv[i + 1] === "\n")
|
|
82
|
-
i++;
|
|
83
|
-
record();
|
|
84
|
-
}
|
|
85
|
-
else if (char === '"' && field === "" && !closed)
|
|
86
|
-
quoted = true;
|
|
87
|
-
else {
|
|
88
|
-
if (closed || char === '"')
|
|
89
|
-
throw new Error("Malformed CSV quoting.");
|
|
90
|
-
field += char;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
if (quoted)
|
|
94
|
-
throw new Error("CSV contains an unclosed quoted field.");
|
|
95
|
-
if (field !== "" || row.length || closed)
|
|
96
|
-
record();
|
|
97
|
-
const headers = records.shift();
|
|
98
|
-
if (!headers ||
|
|
99
|
-
headers.some((name) => !name.trim()) ||
|
|
100
|
-
new Set(headers).size !== headers.length ||
|
|
101
|
-
!headers.includes(inputColumn))
|
|
102
|
-
throw new Error("CSV needs unique nonblank headers and a matching inputColumn.");
|
|
103
|
-
const rows = records.map((values) => {
|
|
104
|
-
if (values.length !== headers.length)
|
|
105
|
-
throw new Error("CSV row length must match its headers.");
|
|
106
|
-
return Object.fromEntries(headers.map((name, index) => [name, values[index]]));
|
|
107
|
-
});
|
|
108
|
-
return { rows, inputs: rows.map((row) => row[inputColumn]) };
|
|
109
|
-
}
|
|
110
|
-
/** Create or update a reusable skill in the caller's library. */
|
|
111
|
-
export const Skill = {
|
|
112
|
-
create(options) {
|
|
113
|
-
return new AgentRun(options).createSkill({
|
|
114
|
-
name: options.name,
|
|
115
|
-
description: options.description,
|
|
116
|
-
content: options.content,
|
|
117
|
-
}, { signal: options.signal });
|
|
118
|
-
},
|
|
119
|
-
};
|
|
120
|
-
export class AgentAPIError extends Error {
|
|
121
|
-
status;
|
|
122
|
-
constructor(status, message) {
|
|
123
|
-
super(message);
|
|
124
|
-
this.status = status;
|
|
125
|
-
this.name = "AgentAPIError";
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
/** Headless agentrun client. Credentials belong in server-side code. */
|
|
129
|
-
export class AgentRun {
|
|
130
|
-
baseURL;
|
|
131
|
-
options;
|
|
132
|
-
constructor(options) {
|
|
133
|
-
this.options = {
|
|
134
|
-
apiKey: options.apiKey,
|
|
135
|
-
baseURL: options.baseURL,
|
|
136
|
-
timeoutMs: options.timeoutMs,
|
|
137
|
-
};
|
|
138
|
-
if (!options.apiKey?.trim())
|
|
139
|
-
throw new Error("An agentrun API key is required.");
|
|
140
|
-
if (options.timeoutMs !== undefined &&
|
|
141
|
-
(!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0))
|
|
142
|
-
throw new Error("timeoutMs must be positive.");
|
|
143
|
-
const url = new URL(options.baseURL || "https://api.agentrun.ai/v1");
|
|
144
|
-
if (url.username ||
|
|
145
|
-
url.password ||
|
|
146
|
-
url.search ||
|
|
147
|
-
url.hash ||
|
|
148
|
-
(url.protocol !== "https:" &&
|
|
149
|
-
!(url.protocol === "http:" &&
|
|
150
|
-
["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))))
|
|
151
|
-
throw new Error("Use HTTPS for the agentrun API.");
|
|
152
|
-
this.baseURL = url.href.replace(/\/$/, "");
|
|
153
|
-
}
|
|
154
|
-
async response(path, init = {}) {
|
|
155
|
-
const timeout = AbortSignal.timeout(this.options.timeoutMs ?? 30_000);
|
|
156
|
-
const signal = init.signal
|
|
157
|
-
? AbortSignal.any([init.signal, timeout])
|
|
158
|
-
: timeout;
|
|
159
|
-
const response = await fetch(`${this.baseURL}${path}`, {
|
|
160
|
-
...init,
|
|
161
|
-
signal,
|
|
162
|
-
redirect: "error",
|
|
163
|
-
headers: {
|
|
164
|
-
"Content-Type": "application/json",
|
|
165
|
-
Authorization: `Bearer ${this.options.apiKey}`,
|
|
166
|
-
...init.headers,
|
|
167
|
-
},
|
|
168
|
-
});
|
|
169
|
-
if (!response.ok) {
|
|
170
|
-
const message = response.status === 503
|
|
171
|
-
? "agentrun is unavailable or agent-creation API access is not enabled. Reuse an existing agent ID or check your account access."
|
|
172
|
-
: `agentrun API request failed (${response.status}). Check your API key, scopes, and request.`;
|
|
173
|
-
throw new AgentAPIError(response.status, message);
|
|
174
|
-
}
|
|
175
|
-
return response;
|
|
176
|
-
}
|
|
177
|
-
async request(path, init = {}) {
|
|
178
|
-
return (await this.response(path, init)).json();
|
|
179
|
-
}
|
|
180
|
-
agent(definition) {
|
|
181
|
-
return new Agent({ ...this.options, ...definition });
|
|
182
|
-
}
|
|
183
|
-
query(path, values) {
|
|
184
|
-
const query = new URLSearchParams();
|
|
185
|
-
for (const [name, value] of Object.entries(values))
|
|
186
|
-
if (value !== undefined)
|
|
187
|
-
query.set(name, String(value));
|
|
188
|
-
return query.size ? `${path}?${query}` : path;
|
|
189
|
-
}
|
|
190
|
-
listAgents(options = {}) {
|
|
191
|
-
return this.request("/agents", { signal: options.signal });
|
|
192
|
-
}
|
|
193
|
-
getBuild(id, options = {}) {
|
|
194
|
-
if (!id.trim())
|
|
195
|
-
throw new Error("A build ID is required.");
|
|
196
|
-
return this.request(`/agents/build/${encodeURIComponent(id)}`, {
|
|
197
|
-
signal: options.signal,
|
|
198
|
-
});
|
|
199
|
-
}
|
|
200
|
-
getAgent(id) {
|
|
201
|
-
return this.request(`/agents/${encodeURIComponent(id)}`);
|
|
202
|
-
}
|
|
203
|
-
updateAgent(id, definition) {
|
|
204
|
-
return this.request(`/agents/${encodeURIComponent(id)}`, {
|
|
205
|
-
method: "PATCH",
|
|
206
|
-
body: JSON.stringify(definition),
|
|
207
|
-
});
|
|
208
|
-
}
|
|
209
|
-
deleteAgent(id) {
|
|
210
|
-
return this.request(`/agents/${encodeURIComponent(id)}`, {
|
|
211
|
-
method: "DELETE",
|
|
212
|
-
});
|
|
213
|
-
}
|
|
214
|
-
createSkill(definition, options = {}) {
|
|
215
|
-
return this.request("/skills", {
|
|
216
|
-
method: "POST",
|
|
217
|
-
body: JSON.stringify(definition),
|
|
218
|
-
signal: options.signal,
|
|
219
|
-
});
|
|
220
|
-
}
|
|
221
|
-
getSkill(name, options = {}) {
|
|
222
|
-
if (!name.trim())
|
|
223
|
-
throw new Error("A skill name is required.");
|
|
224
|
-
return this.request(`/skills/${encodeURIComponent(name)}`, {
|
|
225
|
-
signal: options.signal,
|
|
226
|
-
});
|
|
227
|
-
}
|
|
228
|
-
listSkills(filter = {}, options = {}) {
|
|
229
|
-
return this.request(this.query("/skills", filter), {
|
|
230
|
-
signal: options.signal,
|
|
231
|
-
});
|
|
232
|
-
}
|
|
233
|
-
listIntegrations(filter = {}, options = {}) {
|
|
234
|
-
return this.request(this.query("/integrations", filter), {
|
|
235
|
-
signal: options.signal,
|
|
236
|
-
});
|
|
237
|
-
}
|
|
238
|
-
listRuns(filter = {}, options = {}) {
|
|
239
|
-
return this.request(this.query("/runs", filter), {
|
|
240
|
-
signal: options.signal,
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
createCampaign(plan, options = {}) {
|
|
244
|
-
return this.request("/campaigns", {
|
|
245
|
-
method: "POST",
|
|
246
|
-
signal: options.signal,
|
|
247
|
-
headers: options.idempotencyKey
|
|
248
|
-
? { "Idempotency-Key": options.idempotencyKey }
|
|
249
|
-
: {},
|
|
250
|
-
body: JSON.stringify({ plan, records: options.records }),
|
|
251
|
-
});
|
|
252
|
-
}
|
|
253
|
-
listCampaigns(filter = {}, options = {}) {
|
|
254
|
-
return this.request(this.query("/campaigns", filter), {
|
|
255
|
-
signal: options.signal,
|
|
256
|
-
});
|
|
257
|
-
}
|
|
258
|
-
getCampaign(id, options = {}) {
|
|
259
|
-
if (!id.trim())
|
|
260
|
-
throw new Error("A campaign ID is required.");
|
|
261
|
-
return this.request(`/campaigns/${encodeURIComponent(id)}`, {
|
|
262
|
-
signal: options.signal,
|
|
263
|
-
});
|
|
264
|
-
}
|
|
265
|
-
getCampaignPortfolio(id, stageKey, filter = {}, options = {}) {
|
|
266
|
-
if (!id.trim() || !stageKey.trim())
|
|
267
|
-
throw new Error("Campaign ID and stage key are required.");
|
|
268
|
-
return this.request(this.query(`/campaigns/${encodeURIComponent(id)}/portfolio`, {
|
|
269
|
-
...filter,
|
|
270
|
-
stage_key: stageKey,
|
|
271
|
-
}), { signal: options.signal });
|
|
272
|
-
}
|
|
273
|
-
async waitCampaign(id, options = {}) {
|
|
274
|
-
const { signal, interval } = pollingSignal(options, 20 * 60 * 1000);
|
|
275
|
-
while (true) {
|
|
276
|
-
signal.throwIfAborted();
|
|
277
|
-
const campaign = await this.getCampaign(id, { signal });
|
|
278
|
-
if ([
|
|
279
|
-
"draft",
|
|
280
|
-
"completed",
|
|
281
|
-
"cancelled",
|
|
282
|
-
"failed",
|
|
283
|
-
"needs_attention",
|
|
284
|
-
].includes(campaign.status))
|
|
285
|
-
return campaign;
|
|
286
|
-
await delay(interval, signal);
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
approveCampaign(id, reviewDigest, options = {}) {
|
|
290
|
-
if (!id.trim())
|
|
291
|
-
throw new Error("A campaign ID is required.");
|
|
292
|
-
if (!/^[a-f0-9]{64}$/.test(reviewDigest))
|
|
293
|
-
throw new Error("Use the review digest of the exact campaign plan you reviewed.");
|
|
294
|
-
return this.request(`/campaigns/${encodeURIComponent(id)}/approve`, {
|
|
295
|
-
method: "POST",
|
|
296
|
-
signal: options.signal,
|
|
297
|
-
body: JSON.stringify({ review_digest: reviewDigest }),
|
|
298
|
-
});
|
|
299
|
-
}
|
|
300
|
-
cancelCampaign(id, options = {}) {
|
|
301
|
-
if (!id.trim())
|
|
302
|
-
throw new Error("A campaign ID is required.");
|
|
303
|
-
return this.request(`/campaigns/${encodeURIComponent(id)}/cancel`, {
|
|
304
|
-
method: "POST",
|
|
305
|
-
signal: options.signal,
|
|
306
|
-
body: "{}",
|
|
307
|
-
});
|
|
308
|
-
}
|
|
309
|
-
async downloadCampaignArtifact(id, deliverableKey, options = {}) {
|
|
310
|
-
if (!id.trim() || !deliverableKey.trim())
|
|
311
|
-
throw new Error("Campaign ID and deliverable key are required.");
|
|
312
|
-
return (await this.response(`/campaigns/${encodeURIComponent(id)}/artifacts/${encodeURIComponent(deliverableKey)}`, { signal: options.signal })).blob();
|
|
313
|
-
}
|
|
314
|
-
getLoop(id, options = {}) {
|
|
315
|
-
if (!id.trim())
|
|
316
|
-
throw new Error("A loop ID is required.");
|
|
317
|
-
return this.request(`/loops/${encodeURIComponent(id)}`, {
|
|
318
|
-
signal: options.signal,
|
|
319
|
-
});
|
|
320
|
-
}
|
|
321
|
-
updateLoop(id, changes, options = {}) {
|
|
322
|
-
if (!id.trim())
|
|
323
|
-
throw new Error("A loop ID is required.");
|
|
324
|
-
return this.request(`/loops/${encodeURIComponent(id)}`, {
|
|
325
|
-
method: "PATCH",
|
|
326
|
-
body: JSON.stringify(changes),
|
|
327
|
-
signal: options.signal,
|
|
328
|
-
});
|
|
329
|
-
}
|
|
330
|
-
pauseLoop(id, options = {}) {
|
|
331
|
-
return this.loopAction(id, "pause", options);
|
|
332
|
-
}
|
|
333
|
-
resumeLoop(id, options = {}) {
|
|
334
|
-
return this.loopAction(id, "resume", options);
|
|
335
|
-
}
|
|
336
|
-
runLoopNow(id, options = {}) {
|
|
337
|
-
return this.loopAction(id, "run-now", options);
|
|
338
|
-
}
|
|
339
|
-
loopAction(id, action, options) {
|
|
340
|
-
if (!id.trim())
|
|
341
|
-
throw new Error("A loop ID is required.");
|
|
342
|
-
return this.request(`/loops/${encodeURIComponent(id)}/${action}`, {
|
|
343
|
-
method: "POST",
|
|
344
|
-
body: "{}",
|
|
345
|
-
signal: options.signal,
|
|
346
|
-
});
|
|
347
|
-
}
|
|
348
|
-
deleteLoop(id, options = {}) {
|
|
349
|
-
if (!id.trim())
|
|
350
|
-
throw new Error("A loop ID is required.");
|
|
351
|
-
return this.request(this.query(`/loops/${encodeURIComponent(id)}`, {
|
|
352
|
-
cancel_active: options.cancelActive,
|
|
353
|
-
}), { method: "DELETE", signal: options.signal });
|
|
354
|
-
}
|
|
355
|
-
listBatches(filter = {}, options = {}) {
|
|
356
|
-
return this.request(this.query("/batches", filter), {
|
|
357
|
-
signal: options.signal,
|
|
358
|
-
});
|
|
359
|
-
}
|
|
360
|
-
getBatch(id, options = {}) {
|
|
361
|
-
if (!id.trim())
|
|
362
|
-
throw new Error("A batch ID is required.");
|
|
363
|
-
return this.request(this.query(`/batches/${encodeURIComponent(id)}`, {
|
|
364
|
-
include_rows: options.includeRows,
|
|
365
|
-
}), { signal: options.signal });
|
|
366
|
-
}
|
|
367
|
-
getBatchResults(id, options = {}) {
|
|
368
|
-
if (!id.trim())
|
|
369
|
-
throw new Error("A batch ID is required.");
|
|
370
|
-
const statuses = {
|
|
371
|
-
queued: "PENDING",
|
|
372
|
-
running: "PROCESSING",
|
|
373
|
-
completed: "SUCCESS",
|
|
374
|
-
failed: "FAILED",
|
|
375
|
-
};
|
|
376
|
-
return this.request(this.query(`/batches/${encodeURIComponent(id)}/results`, {
|
|
377
|
-
row_status: options.rowStatus && statuses[options.rowStatus],
|
|
378
|
-
}), { signal: options.signal });
|
|
379
|
-
}
|
|
380
|
-
cancelBatch(id, options = {}) {
|
|
381
|
-
if (!id.trim())
|
|
382
|
-
throw new Error("A batch ID is required.");
|
|
383
|
-
return this.request(`/batches/${encodeURIComponent(id)}/cancel`, {
|
|
384
|
-
method: "POST",
|
|
385
|
-
body: "{}",
|
|
386
|
-
signal: options.signal,
|
|
387
|
-
});
|
|
388
|
-
}
|
|
389
|
-
retryBatch(id, options = {}) {
|
|
390
|
-
if (!id.trim())
|
|
391
|
-
throw new Error("A batch ID is required.");
|
|
392
|
-
if (options.rowNumber !== undefined &&
|
|
393
|
-
(!Number.isInteger(options.rowNumber) || options.rowNumber < 0))
|
|
394
|
-
throw new Error("rowNumber must be a nonnegative integer.");
|
|
395
|
-
const action = options.rowNumber === undefined
|
|
396
|
-
? "retry-failed"
|
|
397
|
-
: `rows/${options.rowNumber}/retry`;
|
|
398
|
-
return this.request(`/batches/${encodeURIComponent(id)}/${action}`, {
|
|
399
|
-
method: "POST",
|
|
400
|
-
body: "{}",
|
|
401
|
-
signal: options.signal,
|
|
402
|
-
});
|
|
403
|
-
}
|
|
404
|
-
async waitBatch(id, options = {}) {
|
|
405
|
-
const { signal, interval } = pollingSignal(options, 1200000);
|
|
406
|
-
while (true) {
|
|
407
|
-
signal.throwIfAborted();
|
|
408
|
-
const batch = await this.getBatch(id, { signal, includeRows: false });
|
|
409
|
-
if (["completed", "completed_with_errors", "failed", "cancelled"].includes(batch.status) ||
|
|
410
|
-
batch.paused_reason)
|
|
411
|
-
return batch;
|
|
412
|
-
await delay(interval, signal);
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
async getRun(jobId, options = {}) {
|
|
416
|
-
if (!jobId.trim())
|
|
417
|
-
throw new Error("A job ID is required.");
|
|
418
|
-
return this.request(`/runs/${encodeURIComponent(jobId)}`, {
|
|
419
|
-
signal: options.signal,
|
|
420
|
-
});
|
|
421
|
-
}
|
|
422
|
-
async cancelRun(runId, options = {}) {
|
|
423
|
-
if (!runId.trim())
|
|
424
|
-
throw new Error("A run ID is required.");
|
|
425
|
-
return this.request(`/runs/${encodeURIComponent(runId)}/cancel`, {
|
|
426
|
-
method: "POST",
|
|
427
|
-
body: "{}",
|
|
428
|
-
signal: options.signal,
|
|
429
|
-
});
|
|
430
|
-
}
|
|
431
|
-
/** Poll to a terminal state. Failed/cancelled/blocked runs are returned for inspection. */
|
|
432
|
-
async wait(runId, options = {}) {
|
|
433
|
-
const { interval, signal } = pollingSignal(options, 600000);
|
|
434
|
-
while (true) {
|
|
435
|
-
signal.throwIfAborted();
|
|
436
|
-
const run = await this.getRun(runId, { signal });
|
|
437
|
-
if (["completed", "failed", "cancelled", "blocked"].includes(run.status))
|
|
438
|
-
return run;
|
|
439
|
-
await delay(interval, signal);
|
|
440
|
-
}
|
|
441
|
-
}
|
|
442
|
-
}
|
|
443
|
-
/** Define an agent and call run(). Creation is lazy and shared across concurrent calls. */
|
|
444
|
-
export class Agent extends AgentRun {
|
|
445
|
-
definition;
|
|
446
|
-
agentId;
|
|
447
|
-
creation;
|
|
448
|
-
constructor(definition) {
|
|
449
|
-
super(definition);
|
|
450
|
-
this.definition = definition;
|
|
451
|
-
if (!definition.id &&
|
|
452
|
-
!definition.buildId &&
|
|
453
|
-
(!definition.name?.trim() || !definition.instructions?.trim()))
|
|
454
|
-
throw new Error("Provide an existing id, a buildId, or a name and instructions.");
|
|
455
|
-
this.agentId = definition.id;
|
|
456
|
-
}
|
|
457
|
-
/** Start a managed build from plain English. Save buildId to resume waiting later. */
|
|
458
|
-
static async create(options) {
|
|
459
|
-
if (options.prompt.trim().length < 3 || options.prompt.length > 500)
|
|
460
|
-
throw new Error("Describe the agent in 3–500 characters; use context for longer requirements.");
|
|
461
|
-
options.signal?.throwIfAborted();
|
|
462
|
-
const agent = new Agent({ ...options, buildId: "pending" });
|
|
463
|
-
const build = await agent.request("/agents/build", {
|
|
464
|
-
method: "POST",
|
|
465
|
-
signal: options.signal,
|
|
466
|
-
body: JSON.stringify({
|
|
467
|
-
prompt: options.prompt,
|
|
468
|
-
context: options.context,
|
|
469
|
-
depth: options.depth ?? "standard",
|
|
470
|
-
}),
|
|
471
|
-
});
|
|
472
|
-
if (!build.id)
|
|
473
|
-
throw new Error("agentrun did not return a build ID.");
|
|
474
|
-
return new Agent({
|
|
475
|
-
apiKey: options.apiKey,
|
|
476
|
-
baseURL: options.baseURL,
|
|
477
|
-
timeoutMs: options.timeoutMs,
|
|
478
|
-
buildId: build.id,
|
|
479
|
-
});
|
|
480
|
-
}
|
|
481
|
-
get buildId() {
|
|
482
|
-
return this.definition.buildId;
|
|
483
|
-
}
|
|
484
|
-
/** Wait for generation and activation. A local timeout does not cancel the build. */
|
|
485
|
-
async waitUntilReady(options = {}) {
|
|
486
|
-
const { interval, signal } = pollingSignal(options, 1200000);
|
|
487
|
-
signal.throwIfAborted();
|
|
488
|
-
if (!this.buildId) {
|
|
489
|
-
await this.ensureAgent();
|
|
490
|
-
signal.throwIfAborted();
|
|
491
|
-
return this;
|
|
492
|
-
}
|
|
493
|
-
if (this.agentId)
|
|
494
|
-
return this;
|
|
495
|
-
while (true) {
|
|
496
|
-
signal.throwIfAborted();
|
|
497
|
-
const build = await this.getBuild(this.buildId, { signal });
|
|
498
|
-
if (build.status === "failed")
|
|
499
|
-
throw new AgentBuildError(build);
|
|
500
|
-
if (build.status === "succeeded") {
|
|
501
|
-
const id = build.agent?.agent_id;
|
|
502
|
-
if (!id)
|
|
503
|
-
throw new Error("The completed build did not return an agent ID.");
|
|
504
|
-
const active = await this.request(`/agents/${encodeURIComponent(id)}`, {
|
|
505
|
-
method: "PATCH",
|
|
506
|
-
signal,
|
|
507
|
-
body: JSON.stringify({ status: "active" }),
|
|
508
|
-
});
|
|
509
|
-
if (active.id !== id || active.status !== "active")
|
|
510
|
-
throw new Error("The generated agent is not active yet.");
|
|
511
|
-
this.agentId = id;
|
|
512
|
-
return this;
|
|
513
|
-
}
|
|
514
|
-
if (!["queued", "running", "registering"].includes(build.status))
|
|
515
|
-
throw new Error("Unknown agent build status.");
|
|
516
|
-
await delay(interval, signal);
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
get id() {
|
|
520
|
-
return this.agentId;
|
|
521
|
-
}
|
|
522
|
-
/** Persist the definition without starting a run. */
|
|
523
|
-
async create() {
|
|
524
|
-
return this.ensureAgent();
|
|
525
|
-
}
|
|
526
|
-
async ensureAgent() {
|
|
527
|
-
if (this.agentId)
|
|
528
|
-
return this.agentId;
|
|
529
|
-
if (this.buildId) {
|
|
530
|
-
await this.waitUntilReady();
|
|
531
|
-
return this.agentId;
|
|
532
|
-
}
|
|
533
|
-
if (!this.creation) {
|
|
534
|
-
this.creation = this.request("/agents", {
|
|
535
|
-
method: "POST",
|
|
536
|
-
body: JSON.stringify({
|
|
537
|
-
name: this.definition.name,
|
|
538
|
-
instructions: this.definition.instructions,
|
|
539
|
-
skills: this.definition.skills ?? [],
|
|
540
|
-
tools: this.definition.tools ?? [],
|
|
541
|
-
status: "active",
|
|
542
|
-
run_mode: this.definition.run_mode,
|
|
543
|
-
campaign_plan: this.definition.campaign_plan,
|
|
544
|
-
input_form: this.definition.input_form,
|
|
545
|
-
}),
|
|
546
|
-
}).then((value) => {
|
|
547
|
-
if (!value.id)
|
|
548
|
-
throw new Error("agentrun did not return an agent ID.");
|
|
549
|
-
this.agentId = value.id;
|
|
550
|
-
return value.id;
|
|
551
|
-
});
|
|
552
|
-
}
|
|
553
|
-
// Retain a failed creation promise: a timed-out POST may have succeeded remotely.
|
|
554
|
-
// Explicitly create a new instance or recover the ID before attempting another create.
|
|
555
|
-
return this.creation;
|
|
556
|
-
}
|
|
557
|
-
/** Runs an existing agent's configured campaign template with its form inputs. */
|
|
558
|
-
async campaign(inputs, options = {}) {
|
|
559
|
-
options.signal?.throwIfAborted();
|
|
560
|
-
if (this.buildId)
|
|
561
|
-
await this.waitUntilReady({ signal: options.signal });
|
|
562
|
-
const id = await this.ensureAgent();
|
|
563
|
-
options.signal?.throwIfAborted();
|
|
564
|
-
return this.request(`/agents/${encodeURIComponent(id)}/campaigns`, {
|
|
565
|
-
method: "POST",
|
|
566
|
-
signal: options.signal,
|
|
567
|
-
headers: options.idempotencyKey
|
|
568
|
-
? { "Idempotency-Key": options.idempotencyKey }
|
|
569
|
-
: {},
|
|
570
|
-
body: JSON.stringify({ inputs }),
|
|
571
|
-
});
|
|
572
|
-
}
|
|
573
|
-
batch(input, options = {}) {
|
|
574
|
-
return this.submitBatch(input, options);
|
|
575
|
-
}
|
|
576
|
-
async loop(input, cadence, options = {}) {
|
|
577
|
-
if (!["daily", "weekly", "monthly"].includes(cadence.frequency))
|
|
578
|
-
throw new Error("Loop frequency must be daily, weekly, or monthly.");
|
|
579
|
-
const batch = await this.submitBatch(typeof input === "string" ? [input] : input, { ...options, name: options.name ?? "agentrun loop", schedule: cadence }, "/loops");
|
|
580
|
-
if (!batch.loop_id)
|
|
581
|
-
throw new Error("agentrun did not return a loop ID. Inspect the created batch before retrying.");
|
|
582
|
-
return {
|
|
583
|
-
id: batch.loop_id,
|
|
584
|
-
first_batch_id: batch.id,
|
|
585
|
-
status: batch.status,
|
|
586
|
-
};
|
|
587
|
-
}
|
|
588
|
-
async submitBatch(input, options = {}, path = "/batches") {
|
|
589
|
-
options.signal?.throwIfAborted();
|
|
590
|
-
let parsed;
|
|
591
|
-
if (Array.isArray(input))
|
|
592
|
-
parsed = { inputs: [...input] };
|
|
593
|
-
else {
|
|
594
|
-
if (typeof input.csv !== "string" && input.csv.size > 1000000)
|
|
595
|
-
throw new Error("CSV must be at most 1 MB.");
|
|
596
|
-
parsed = parseBatchCSV(typeof input.csv === "string" ? input.csv : await input.csv.text(), input.inputColumn);
|
|
597
|
-
}
|
|
598
|
-
if (parsed.inputs.length < 1 ||
|
|
599
|
-
parsed.inputs.length > 100 ||
|
|
600
|
-
parsed.inputs.some((value) => typeof value !== "string" || !value.trim() || value.length > 8000))
|
|
601
|
-
throw new Error("Provide 1–100 nonblank inputs of at most 8,000 characters each.");
|
|
602
|
-
options.signal?.throwIfAborted();
|
|
603
|
-
if (this.buildId)
|
|
604
|
-
await this.waitUntilReady({ signal: options.signal });
|
|
605
|
-
const id = await this.ensureAgent();
|
|
606
|
-
options.signal?.throwIfAborted();
|
|
607
|
-
return this.request(path, {
|
|
608
|
-
method: "POST",
|
|
609
|
-
signal: options.signal,
|
|
610
|
-
headers: options.idempotencyKey
|
|
611
|
-
? { "Idempotency-Key": options.idempotencyKey }
|
|
612
|
-
: undefined,
|
|
613
|
-
body: JSON.stringify({
|
|
614
|
-
name: options.name ?? "agentrun batch",
|
|
615
|
-
schedule: options.schedule,
|
|
616
|
-
...parsed,
|
|
617
|
-
agent_id: id,
|
|
618
|
-
effort: options.effort ?? "low",
|
|
619
|
-
response_language: options.responseLanguage,
|
|
620
|
-
max_concurrent: options.maxConcurrent,
|
|
621
|
-
max_credits: options.maxCredits,
|
|
622
|
-
output_schema: options.outputSchema,
|
|
623
|
-
}),
|
|
624
|
-
});
|
|
625
|
-
}
|
|
626
|
-
async run(question, options = {}) {
|
|
627
|
-
if (!question.trim())
|
|
628
|
-
throw new Error("A non-empty question is required.");
|
|
629
|
-
options.signal?.throwIfAborted();
|
|
630
|
-
if (this.buildId)
|
|
631
|
-
await this.waitUntilReady({ signal: options.signal });
|
|
632
|
-
const agentId = await this.ensureAgent();
|
|
633
|
-
options.signal?.throwIfAborted();
|
|
634
|
-
const run = await this.request("/runs", {
|
|
635
|
-
method: "POST",
|
|
636
|
-
signal: options.signal,
|
|
637
|
-
headers: options.idempotencyKey
|
|
638
|
-
? { "Idempotency-Key": options.idempotencyKey }
|
|
639
|
-
: undefined,
|
|
640
|
-
body: JSON.stringify({
|
|
641
|
-
input: question,
|
|
642
|
-
agent_id: agentId,
|
|
643
|
-
effort: options.effort ?? "low",
|
|
644
|
-
max_cost_usd: options.maxCostUsd,
|
|
645
|
-
response_language: options.responseLanguage,
|
|
646
|
-
output_schema: options.outputSchema,
|
|
647
|
-
}),
|
|
648
|
-
});
|
|
649
|
-
if (!run.id)
|
|
650
|
-
throw new Error("agentrun did not return a job ID.");
|
|
651
|
-
return run;
|
|
652
|
-
}
|
|
653
|
-
}
|