@parcha/agentrun 0.2.1 → 0.3.5
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 +202 -0
- package/NOTICE +2 -0
- package/README.md +20 -191
- package/bin/agentrun.mjs +9 -0
- package/lib/start.mjs +145 -0
- package/package.json +23 -47
- package/CHANGELOG.md +0 -27
- package/dist/index.cjs +0 -1182
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -682
- package/dist/index.d.ts +0 -682
- package/dist/index.js +0 -1150
- package/dist/index.js.map +0 -1
package/dist/index.js
DELETED
|
@@ -1,1150 +0,0 @@
|
|
|
1
|
-
// src/batch.ts
|
|
2
|
-
var MAX_INPUTS = 100;
|
|
3
|
-
var MAX_INPUT_CHARS = 8e3;
|
|
4
|
-
var MAX_CSV_BYTES = 1e6;
|
|
5
|
-
function parseBatchCSV(csv, inputColumn = "input") {
|
|
6
|
-
if (new TextEncoder().encode(csv).length > MAX_CSV_BYTES) throw new Error("CSV must be at most 1 MB.");
|
|
7
|
-
const records = [];
|
|
8
|
-
let row = [];
|
|
9
|
-
let field = "";
|
|
10
|
-
let quoted = false;
|
|
11
|
-
let closed = false;
|
|
12
|
-
const cell = () => {
|
|
13
|
-
row.push(field);
|
|
14
|
-
field = "";
|
|
15
|
-
closed = false;
|
|
16
|
-
};
|
|
17
|
-
const record = () => {
|
|
18
|
-
cell();
|
|
19
|
-
if (row.some((value) => value.trim() !== "")) records.push(row);
|
|
20
|
-
row = [];
|
|
21
|
-
if (records.length > MAX_INPUTS + 1) throw new Error(`A batch accepts at most ${MAX_INPUTS} inputs.`);
|
|
22
|
-
};
|
|
23
|
-
csv = csv.replace(/^/, "");
|
|
24
|
-
for (let i = 0; i < csv.length; i++) {
|
|
25
|
-
const char = csv[i];
|
|
26
|
-
if (quoted) {
|
|
27
|
-
if (char === '"') {
|
|
28
|
-
if (csv[i + 1] === '"') {
|
|
29
|
-
field += '"';
|
|
30
|
-
i++;
|
|
31
|
-
} else {
|
|
32
|
-
quoted = false;
|
|
33
|
-
closed = true;
|
|
34
|
-
}
|
|
35
|
-
} else field += char;
|
|
36
|
-
} else if (char === ",") cell();
|
|
37
|
-
else if (char === "\n" || char === "\r") {
|
|
38
|
-
if (char === "\r" && csv[i + 1] === "\n") i++;
|
|
39
|
-
record();
|
|
40
|
-
} else if (char === '"' && field === "" && !closed) quoted = true;
|
|
41
|
-
else {
|
|
42
|
-
if (closed || char === '"') throw new Error("Malformed CSV quoting.");
|
|
43
|
-
field += char;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
if (quoted) throw new Error("CSV contains an unclosed quoted field.");
|
|
47
|
-
if (field !== "" || row.length || closed) record();
|
|
48
|
-
const headers = records.shift();
|
|
49
|
-
if (!headers) throw new Error("CSV is empty.");
|
|
50
|
-
if (headers.some((name) => !name.trim()) || new Set(headers).size !== headers.length)
|
|
51
|
-
throw new Error("CSV headers must be unique and non-blank.");
|
|
52
|
-
if (!headers.includes(inputColumn))
|
|
53
|
-
throw new Error(`CSV has no "${inputColumn}" column. Headers are: ${headers.join(", ")}.`);
|
|
54
|
-
const rows = records.map((values, index) => {
|
|
55
|
-
if (values.length !== headers.length)
|
|
56
|
-
throw new Error(`CSV row ${index + 2} has ${values.length} cells but there are ${headers.length} headers.`);
|
|
57
|
-
return Object.fromEntries(headers.map((name, i) => [name, values[i] ?? ""]));
|
|
58
|
-
});
|
|
59
|
-
return { rows, inputs: rows.map((r) => r[inputColumn] ?? "") };
|
|
60
|
-
}
|
|
61
|
-
async function prepareInputs(inputs) {
|
|
62
|
-
let questions;
|
|
63
|
-
let rows;
|
|
64
|
-
if (typeof inputs === "string") questions = [inputs];
|
|
65
|
-
else if (Array.isArray(inputs)) questions = [...inputs];
|
|
66
|
-
else {
|
|
67
|
-
if (typeof inputs.csv !== "string" && inputs.csv.size > MAX_CSV_BYTES) throw new Error("CSV must be at most 1 MB.");
|
|
68
|
-
const text = typeof inputs.csv === "string" ? inputs.csv : await inputs.csv.text();
|
|
69
|
-
({ inputs: questions, rows } = parseBatchCSV(text, inputs.inputColumn ?? "input"));
|
|
70
|
-
}
|
|
71
|
-
if (questions.length < 1 || questions.length > MAX_INPUTS) throw new Error(`Provide between 1 and ${MAX_INPUTS} inputs.`);
|
|
72
|
-
questions.forEach((value, index) => {
|
|
73
|
-
if (typeof value !== "string" || !value.trim()) throw new Error(`Input ${index} is blank.`);
|
|
74
|
-
if (value.length > MAX_INPUT_CHARS) throw new Error(`Input ${index} is longer than ${MAX_INPUT_CHARS} characters.`);
|
|
75
|
-
});
|
|
76
|
-
return { questions, rows };
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
// src/errors.ts
|
|
80
|
-
var AgentRunError = class extends Error {
|
|
81
|
-
name = "AgentRunError";
|
|
82
|
-
};
|
|
83
|
-
var APIConnectionError = class extends AgentRunError {
|
|
84
|
-
name = "APIConnectionError";
|
|
85
|
-
};
|
|
86
|
-
var APITimeoutError = class extends APIConnectionError {
|
|
87
|
-
name = "APITimeoutError";
|
|
88
|
-
};
|
|
89
|
-
var APIError = class extends AgentRunError {
|
|
90
|
-
name = "APIError";
|
|
91
|
-
/** The HTTP status code. */
|
|
92
|
-
statusCode;
|
|
93
|
-
/** The decoded JSON body, or the raw text when it was not JSON. */
|
|
94
|
-
body;
|
|
95
|
-
/** The server's request ID when present. Include it when reporting a problem. */
|
|
96
|
-
requestId;
|
|
97
|
-
constructor(message, statusCode, body2, requestId) {
|
|
98
|
-
super(message);
|
|
99
|
-
this.statusCode = statusCode;
|
|
100
|
-
this.body = body2;
|
|
101
|
-
this.requestId = requestId;
|
|
102
|
-
}
|
|
103
|
-
};
|
|
104
|
-
var AuthenticationError = class extends APIError {
|
|
105
|
-
name = "AuthenticationError";
|
|
106
|
-
};
|
|
107
|
-
var PermissionDeniedError = class extends APIError {
|
|
108
|
-
name = "PermissionDeniedError";
|
|
109
|
-
};
|
|
110
|
-
var NotFoundError = class extends APIError {
|
|
111
|
-
name = "NotFoundError";
|
|
112
|
-
};
|
|
113
|
-
var ConflictError = class extends APIError {
|
|
114
|
-
name = "ConflictError";
|
|
115
|
-
};
|
|
116
|
-
var UnprocessableEntityError = class extends APIError {
|
|
117
|
-
name = "UnprocessableEntityError";
|
|
118
|
-
};
|
|
119
|
-
var RateLimitError = class extends APIError {
|
|
120
|
-
name = "RateLimitError";
|
|
121
|
-
};
|
|
122
|
-
var ServiceUnavailableError = class extends APIError {
|
|
123
|
-
name = "ServiceUnavailableError";
|
|
124
|
-
};
|
|
125
|
-
var InternalServerError = class extends APIError {
|
|
126
|
-
name = "InternalServerError";
|
|
127
|
-
};
|
|
128
|
-
var InvalidResponseError = class extends AgentRunError {
|
|
129
|
-
name = "InvalidResponseError";
|
|
130
|
-
};
|
|
131
|
-
var BuildError = class extends AgentRunError {
|
|
132
|
-
constructor(build) {
|
|
133
|
-
super("Agent build failed. Read .build.error for the reason before starting another build.");
|
|
134
|
-
this.build = build;
|
|
135
|
-
}
|
|
136
|
-
build;
|
|
137
|
-
name = "BuildError";
|
|
138
|
-
};
|
|
139
|
-
var PollTimeoutError = class extends AgentRunError {
|
|
140
|
-
name = "PollTimeoutError";
|
|
141
|
-
};
|
|
142
|
-
var STATUS_ERRORS = {
|
|
143
|
-
401: AuthenticationError,
|
|
144
|
-
403: PermissionDeniedError,
|
|
145
|
-
404: NotFoundError,
|
|
146
|
-
409: ConflictError,
|
|
147
|
-
422: UnprocessableEntityError,
|
|
148
|
-
429: RateLimitError,
|
|
149
|
-
503: ServiceUnavailableError
|
|
150
|
-
};
|
|
151
|
-
function errorForStatus(statusCode, body2, headerRequestId) {
|
|
152
|
-
const Cls = STATUS_ERRORS[statusCode] ?? (statusCode >= 500 ? InternalServerError : APIError);
|
|
153
|
-
const detail = describe(body2);
|
|
154
|
-
let message = `AgentRun API request failed with HTTP ${statusCode}`;
|
|
155
|
-
if (statusCode === 503) message += ". The service is unavailable or this feature is not enabled for your account";
|
|
156
|
-
if (detail) message += `: ${detail}`;
|
|
157
|
-
return new Cls(message, statusCode, body2, headerRequestId ?? requestIdFrom(body2));
|
|
158
|
-
}
|
|
159
|
-
function isRecord(value) {
|
|
160
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
161
|
-
}
|
|
162
|
-
function requestIdFrom(body2) {
|
|
163
|
-
if (isRecord(body2) && isRecord(body2.error) && typeof body2.error.request_id === "string") return body2.error.request_id;
|
|
164
|
-
return null;
|
|
165
|
-
}
|
|
166
|
-
function describe(body2) {
|
|
167
|
-
if (!isRecord(body2)) return null;
|
|
168
|
-
const error = body2.error;
|
|
169
|
-
if (isRecord(error)) {
|
|
170
|
-
const message = error.message ?? error.code;
|
|
171
|
-
return typeof message === "string" && message ? message : null;
|
|
172
|
-
}
|
|
173
|
-
if (typeof error === "string") return error;
|
|
174
|
-
const detail = body2.detail;
|
|
175
|
-
if (typeof detail === "string") return detail;
|
|
176
|
-
if (Array.isArray(detail)) {
|
|
177
|
-
const parts = detail.map((item) => {
|
|
178
|
-
if (!isRecord(item)) return "";
|
|
179
|
-
const loc = Array.isArray(item.loc) ? item.loc.filter((p) => p !== "body").map(String).join(".") : "";
|
|
180
|
-
const msg = typeof item.msg === "string" ? item.msg : "";
|
|
181
|
-
return loc ? `${loc}: ${msg}` : msg;
|
|
182
|
-
});
|
|
183
|
-
return parts.filter(Boolean).join("; ") || null;
|
|
184
|
-
}
|
|
185
|
-
return null;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
// src/models.ts
|
|
189
|
-
var RUN_TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "blocked"]);
|
|
190
|
-
var BATCH_TERMINAL_STATUSES = /* @__PURE__ */ new Set([
|
|
191
|
-
"completed",
|
|
192
|
-
"completed_with_errors",
|
|
193
|
-
"failed",
|
|
194
|
-
"cancelled"
|
|
195
|
-
]);
|
|
196
|
-
var CAMPAIGN_TERMINAL_STATUSES = /* @__PURE__ */ new Set([
|
|
197
|
-
"draft",
|
|
198
|
-
"completed",
|
|
199
|
-
"cancelled",
|
|
200
|
-
"failed",
|
|
201
|
-
"needs_attention"
|
|
202
|
-
]);
|
|
203
|
-
var BUILD_ACTIVE_STATUSES = /* @__PURE__ */ new Set(["queued", "running", "registering"]);
|
|
204
|
-
var RUN_STATUS_MAP = {
|
|
205
|
-
submitted: "queued",
|
|
206
|
-
pending: "queued",
|
|
207
|
-
queued: "queued",
|
|
208
|
-
content_moderation: "moderation",
|
|
209
|
-
moderation: "moderation",
|
|
210
|
-
planning: "running",
|
|
211
|
-
"in progress": "running",
|
|
212
|
-
running: "running",
|
|
213
|
-
complete: "completed",
|
|
214
|
-
completed: "completed",
|
|
215
|
-
error: "failed",
|
|
216
|
-
failed: "failed",
|
|
217
|
-
cancelled: "cancelled",
|
|
218
|
-
canceled: "cancelled",
|
|
219
|
-
interrupted: "cancelled",
|
|
220
|
-
deleted: "cancelled",
|
|
221
|
-
retried: "cancelled",
|
|
222
|
-
locked: "blocked",
|
|
223
|
-
blocked: "blocked",
|
|
224
|
-
paused: "blocked",
|
|
225
|
-
needs_clarification: "blocked"
|
|
226
|
-
};
|
|
227
|
-
var BATCH_STATUS_MAP = {
|
|
228
|
-
pending: "queued",
|
|
229
|
-
processing: "running",
|
|
230
|
-
processed_successfully: "completed",
|
|
231
|
-
processed_with_errors: "completed_with_errors",
|
|
232
|
-
processing_failed: "failed",
|
|
233
|
-
failed: "failed",
|
|
234
|
-
cancelled: "cancelled"
|
|
235
|
-
};
|
|
236
|
-
var ROW_STATUS_MAP = {
|
|
237
|
-
PENDING: "queued",
|
|
238
|
-
PROCESSING: "running",
|
|
239
|
-
RETRYING: "running",
|
|
240
|
-
SUCCESS: "completed",
|
|
241
|
-
FAILED: "failed",
|
|
242
|
-
DLQ: "failed"
|
|
243
|
-
};
|
|
244
|
-
var Artifact = class extends Blob {
|
|
245
|
-
filename;
|
|
246
|
-
constructor(bytes, contentType, filename) {
|
|
247
|
-
super([bytes], contentType ? { type: contentType } : void 0);
|
|
248
|
-
this.filename = filename;
|
|
249
|
-
}
|
|
250
|
-
};
|
|
251
|
-
function str(value) {
|
|
252
|
-
return typeof value === "string" ? value : value == null ? null : String(value);
|
|
253
|
-
}
|
|
254
|
-
function firstString(wire, ...keys) {
|
|
255
|
-
for (const key of keys) {
|
|
256
|
-
const value = wire[key];
|
|
257
|
-
if (typeof value === "string" && value) return value;
|
|
258
|
-
}
|
|
259
|
-
return null;
|
|
260
|
-
}
|
|
261
|
-
function mapStatus(wire, mapping, ...keys) {
|
|
262
|
-
for (const key of keys) {
|
|
263
|
-
const raw = wire[key];
|
|
264
|
-
if (typeof raw === "string") return { status: mapping[raw] ?? mapping[raw.toLowerCase()] ?? raw, raw_status: raw };
|
|
265
|
-
}
|
|
266
|
-
return { status: "", raw_status: null };
|
|
267
|
-
}
|
|
268
|
-
function requireId(wire, what, ...keys) {
|
|
269
|
-
const id2 = firstString(wire, ...keys);
|
|
270
|
-
if (!id2) throw new TypeError(`${what} has no ${keys[0]}`);
|
|
271
|
-
return id2;
|
|
272
|
-
}
|
|
273
|
-
function list(value, parse2) {
|
|
274
|
-
return Array.isArray(value) ? value.filter(isWire).map(parse2) : [];
|
|
275
|
-
}
|
|
276
|
-
function isWire(value) {
|
|
277
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
278
|
-
}
|
|
279
|
-
var parse = {
|
|
280
|
-
agent(wire) {
|
|
281
|
-
const skills = Array.isArray(wire.skill_names) ? wire.skill_names : [];
|
|
282
|
-
const tools = Array.isArray(wire.mcp_tool_names) ? wire.mcp_tool_names : [];
|
|
283
|
-
return {
|
|
284
|
-
...wire,
|
|
285
|
-
id: requireId(wire, "agent", "id"),
|
|
286
|
-
name: str(wire.name) ?? "",
|
|
287
|
-
status: str(wire.status) ?? "",
|
|
288
|
-
instructions: str(wire.system_prompt),
|
|
289
|
-
skills,
|
|
290
|
-
tools,
|
|
291
|
-
skill_names: skills,
|
|
292
|
-
mcp_tool_names: tools,
|
|
293
|
-
input_form: Array.isArray(wire.input_form) ? wire.input_form : []
|
|
294
|
-
};
|
|
295
|
-
},
|
|
296
|
-
agents(wire) {
|
|
297
|
-
return list(wire.experts ?? wire.agents, parse.agent);
|
|
298
|
-
},
|
|
299
|
-
build(wire) {
|
|
300
|
-
const agent = isWire(wire.expert) ? wire.expert : isWire(wire.agent) ? wire.agent : null;
|
|
301
|
-
return {
|
|
302
|
-
...wire,
|
|
303
|
-
id: requireId(wire, "build", "job_id", "id"),
|
|
304
|
-
status: str(wire.status) ?? "",
|
|
305
|
-
agent,
|
|
306
|
-
agent_id: agent ? firstString(agent, "id", "expert_id", "agent_id") : null
|
|
307
|
-
};
|
|
308
|
-
},
|
|
309
|
-
run(wire) {
|
|
310
|
-
const report = isWire(wire.report) && typeof wire.report.markdown === "string" ? wire.report : null;
|
|
311
|
-
return {
|
|
312
|
-
...wire,
|
|
313
|
-
id: requireId(wire, "run", "job_id", "id"),
|
|
314
|
-
...mapStatus(wire, RUN_STATUS_MAP, "status"),
|
|
315
|
-
agent_id: firstString(wire, "expert_id", "agent_id"),
|
|
316
|
-
report,
|
|
317
|
-
structured_output: isWire(wire.structured_output) ? wire.structured_output : null
|
|
318
|
-
};
|
|
319
|
-
},
|
|
320
|
-
runSummary(wire) {
|
|
321
|
-
return {
|
|
322
|
-
...wire,
|
|
323
|
-
id: requireId(wire, "run", "job_id", "id"),
|
|
324
|
-
...mapStatus(wire, RUN_STATUS_MAP, "status"),
|
|
325
|
-
question: str(wire.question) ?? ""
|
|
326
|
-
};
|
|
327
|
-
},
|
|
328
|
-
cancel(wire) {
|
|
329
|
-
const previous = wire.previous_status;
|
|
330
|
-
return {
|
|
331
|
-
...wire,
|
|
332
|
-
id: requireId(wire, "run", "job_id", "id"),
|
|
333
|
-
...mapStatus(wire, RUN_STATUS_MAP, "status"),
|
|
334
|
-
previous_status: typeof previous === "string" ? RUN_STATUS_MAP[previous] ?? previous : null
|
|
335
|
-
};
|
|
336
|
-
},
|
|
337
|
-
row(wire) {
|
|
338
|
-
return {
|
|
339
|
-
...wire,
|
|
340
|
-
row_number: Number(wire.row_number ?? 0),
|
|
341
|
-
...mapStatus(wire, ROW_STATUS_MAP, "status"),
|
|
342
|
-
run_id: firstString(wire, "job_id", "run_id"),
|
|
343
|
-
run_status: firstString(wire, "job_status", "run_status")
|
|
344
|
-
};
|
|
345
|
-
},
|
|
346
|
-
batch(wire) {
|
|
347
|
-
return {
|
|
348
|
-
...wire,
|
|
349
|
-
id: requireId(wire, "batch", "batch_id", "id"),
|
|
350
|
-
...mapStatus(wire, BATCH_STATUS_MAP, "processing_status", "status"),
|
|
351
|
-
name: firstString(wire, "batch_name", "name"),
|
|
352
|
-
loop_id: firstString(wire, "schedule_id", "loop_id"),
|
|
353
|
-
rows: list(wire.rows, parse.row)
|
|
354
|
-
};
|
|
355
|
-
},
|
|
356
|
-
resultRow(wire) {
|
|
357
|
-
return {
|
|
358
|
-
...wire,
|
|
359
|
-
row_number: Number(wire.row_number ?? 0),
|
|
360
|
-
...mapStatus(wire, ROW_STATUS_MAP, "status"),
|
|
361
|
-
run_id: firstString(wire, "job_id", "run_id")
|
|
362
|
-
};
|
|
363
|
-
},
|
|
364
|
-
batchResults(wire) {
|
|
365
|
-
return { ...parse.batch(wire), results: list(wire.results, parse.resultRow) };
|
|
366
|
-
},
|
|
367
|
-
retry(wire) {
|
|
368
|
-
return parse.batch(wire);
|
|
369
|
-
},
|
|
370
|
-
loop(wire) {
|
|
371
|
-
return {
|
|
372
|
-
...wire,
|
|
373
|
-
id: requireId(wire, "loop", "schedule_id", "id"),
|
|
374
|
-
name: str(wire.name) ?? "",
|
|
375
|
-
frequency: str(wire.frequency) ?? "",
|
|
376
|
-
schedule_config: isWire(wire.schedule_config) ? wire.schedule_config : {},
|
|
377
|
-
timezone: str(wire.timezone) ?? "UTC",
|
|
378
|
-
is_active: wire.is_active !== false,
|
|
379
|
-
run_count: Number(wire.run_count ?? 0),
|
|
380
|
-
consecutive_failures: Number(wire.consecutive_failures ?? 0)
|
|
381
|
-
};
|
|
382
|
-
},
|
|
383
|
-
loopRun(wire) {
|
|
384
|
-
return {
|
|
385
|
-
...wire,
|
|
386
|
-
id: requireId(wire, "batch", "batch_id", "id"),
|
|
387
|
-
...mapStatus(wire, BATCH_STATUS_MAP, "processing_status", "status"),
|
|
388
|
-
total_rows: Number(wire.total_rows ?? 0),
|
|
389
|
-
processed_rows: Number(wire.processed_rows ?? 0)
|
|
390
|
-
};
|
|
391
|
-
},
|
|
392
|
-
loopDetail(wire) {
|
|
393
|
-
const schedule = isWire(wire.schedule) ? wire.schedule : isWire(wire.loop) ? wire.loop : null;
|
|
394
|
-
if (!schedule) throw new TypeError("loop detail has no schedule");
|
|
395
|
-
return { loop: parse.loop(schedule), runs: list(wire.runs, parse.loopRun) };
|
|
396
|
-
},
|
|
397
|
-
loopRunNow(wire) {
|
|
398
|
-
return { batch_id: requireId(wire, "loop run", "batch_id"), run_number: Number(wire.run_number ?? 0) };
|
|
399
|
-
},
|
|
400
|
-
skillList(wire) {
|
|
401
|
-
return {
|
|
402
|
-
skills: list(wire.skills, (s) => ({ ...s, name: str(s.name) ?? "" })),
|
|
403
|
-
count: Number(wire.count ?? 0),
|
|
404
|
-
total: Number(wire.total ?? 0),
|
|
405
|
-
categories: Array.isArray(wire.categories) ? wire.categories : []
|
|
406
|
-
};
|
|
407
|
-
},
|
|
408
|
-
skillContent(wire) {
|
|
409
|
-
return { ...wire, name: str(wire.name) ?? "", content: str(wire.content) ?? "" };
|
|
410
|
-
},
|
|
411
|
-
skillRecord(wire) {
|
|
412
|
-
return { id: requireId(wire, "skill", "skill_id", "id"), name: str(wire.name) ?? "", created: wire.created !== false };
|
|
413
|
-
},
|
|
414
|
-
integrationList(wire) {
|
|
415
|
-
return {
|
|
416
|
-
tools: list(wire.tools, (t) => ({ ...t, name: str(t.name) ?? "" })),
|
|
417
|
-
servers: Array.isArray(wire.servers) ? wire.servers : [],
|
|
418
|
-
count: Number(wire.count ?? 0),
|
|
419
|
-
total: Number(wire.total ?? 0)
|
|
420
|
-
};
|
|
421
|
-
},
|
|
422
|
-
campaign(wire) {
|
|
423
|
-
return {
|
|
424
|
-
...wire,
|
|
425
|
-
id: requireId(wire, "campaign", "campaign_id", "id"),
|
|
426
|
-
status: str(wire.status) ?? "",
|
|
427
|
-
agent_id: firstString(wire, "expert_id", "agent_id"),
|
|
428
|
-
stages: Array.isArray(wire.stages) ? wire.stages : [],
|
|
429
|
-
deliverables: Array.isArray(wire.deliverables) ? wire.deliverables : [],
|
|
430
|
-
capabilities: Array.isArray(wire.capabilities) ? wire.capabilities : []
|
|
431
|
-
};
|
|
432
|
-
},
|
|
433
|
-
portfolio(wire) {
|
|
434
|
-
return {
|
|
435
|
-
...wire,
|
|
436
|
-
campaign_id: requireId(wire, "portfolio", "campaign_id"),
|
|
437
|
-
stage_key: str(wire.stage_key) ?? "",
|
|
438
|
-
status: str(wire.status) ?? "",
|
|
439
|
-
items: Array.isArray(wire.items) ? wire.items : [],
|
|
440
|
-
fields: Array.isArray(wire.fields) ? wire.fields : [],
|
|
441
|
-
coverage: isWire(wire.coverage) ? wire.coverage : {},
|
|
442
|
-
next_cursor: str(wire.next_cursor)
|
|
443
|
-
};
|
|
444
|
-
},
|
|
445
|
-
usage(wire) {
|
|
446
|
-
return {
|
|
447
|
-
...wire,
|
|
448
|
-
total_credits_used: Number(wire.total_credits_used ?? 0),
|
|
449
|
-
total_cents_spent: Number(wire.total_cents_spent ?? 0),
|
|
450
|
-
job_count: Number(wire.job_count ?? 0),
|
|
451
|
-
by_effort: isWire(wire.by_effort) ? wire.by_effort : {}
|
|
452
|
-
};
|
|
453
|
-
},
|
|
454
|
-
page(item) {
|
|
455
|
-
return (wire) => ({
|
|
456
|
-
items: list(wire.items, item),
|
|
457
|
-
next_cursor: str(wire.next_cursor),
|
|
458
|
-
has_more: wire.has_more === true
|
|
459
|
-
});
|
|
460
|
-
},
|
|
461
|
-
raw(wire) {
|
|
462
|
-
return wire;
|
|
463
|
-
}
|
|
464
|
-
};
|
|
465
|
-
|
|
466
|
-
// src/http.ts
|
|
467
|
-
var DEFAULT_BASE_URL = "https://api.grep.ai/api/v2";
|
|
468
|
-
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
469
|
-
var VERSION = "0.2.1";
|
|
470
|
-
var LOCAL_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
471
|
-
function env(name) {
|
|
472
|
-
const g = globalThis;
|
|
473
|
-
return g.process?.env?.[name];
|
|
474
|
-
}
|
|
475
|
-
function resolveConfig(options) {
|
|
476
|
-
const apiKey = options.apiKey ?? env("AGENTRUN_API_KEY") ?? "";
|
|
477
|
-
if (!apiKey.trim()) throw new Error("An API key is required. Pass apiKey or set AGENTRUN_API_KEY.");
|
|
478
|
-
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
479
|
-
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("timeoutMs must be a positive number.");
|
|
480
|
-
const baseURL = validateBaseURL(options.baseURL ?? env("AGENTRUN_BASE_URL") ?? DEFAULT_BASE_URL);
|
|
481
|
-
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
482
|
-
if (typeof fetchImpl !== "function") throw new Error("No fetch available. Use Node 20.9+ or pass fetch.");
|
|
483
|
-
return { apiKey, baseURL, timeoutMs, fetch: fetchImpl };
|
|
484
|
-
}
|
|
485
|
-
function validateBaseURL(value) {
|
|
486
|
-
let url;
|
|
487
|
-
try {
|
|
488
|
-
url = new URL(value);
|
|
489
|
-
} catch {
|
|
490
|
-
throw new Error("baseURL must be an absolute URL.");
|
|
491
|
-
}
|
|
492
|
-
if (url.username || url.password || url.search || url.hash)
|
|
493
|
-
throw new Error("baseURL must be a plain URL with no credentials, query string, or fragment.");
|
|
494
|
-
if (url.protocol !== "https:" && !(url.protocol === "http:" && LOCAL_HOSTS.has(url.hostname)))
|
|
495
|
-
throw new Error("baseURL must use HTTPS. Plain HTTP is only allowed for localhost.");
|
|
496
|
-
return url.href.replace(/\/+$/, "");
|
|
497
|
-
}
|
|
498
|
-
function clean(values) {
|
|
499
|
-
const out = {};
|
|
500
|
-
for (const [k, v] of Object.entries(values ?? {})) if (v !== void 0 && v !== null) out[k] = v;
|
|
501
|
-
return out;
|
|
502
|
-
}
|
|
503
|
-
var Transport = class {
|
|
504
|
-
constructor(config) {
|
|
505
|
-
this.config = config;
|
|
506
|
-
}
|
|
507
|
-
config;
|
|
508
|
-
url(op) {
|
|
509
|
-
const query = new URLSearchParams();
|
|
510
|
-
for (const [k, v] of Object.entries(clean(op.params))) query.set(k, String(v));
|
|
511
|
-
const qs = query.toString();
|
|
512
|
-
return `${this.config.baseURL}${op.path}${qs ? `?${qs}` : ""}`;
|
|
513
|
-
}
|
|
514
|
-
async send(op, options = {}) {
|
|
515
|
-
options.signal?.throwIfAborted();
|
|
516
|
-
const deadline = new AbortController();
|
|
517
|
-
const timer = setTimeout(() => deadline.abort(), this.config.timeoutMs);
|
|
518
|
-
const signal = options.signal ? AbortSignal.any([options.signal, deadline.signal]) : deadline.signal;
|
|
519
|
-
const headers = {
|
|
520
|
-
Authorization: `Bearer ${this.config.apiKey}`,
|
|
521
|
-
Accept: "application/json, */*;q=0.5",
|
|
522
|
-
"User-Agent": `agentrun-js/${VERSION}`
|
|
523
|
-
};
|
|
524
|
-
if (op.idempotencyKey) headers["Idempotency-Key"] = op.idempotencyKey;
|
|
525
|
-
const init = { method: op.method, headers, signal, redirect: "error" };
|
|
526
|
-
if (op.json !== void 0) {
|
|
527
|
-
headers["Content-Type"] = "application/json";
|
|
528
|
-
init.body = JSON.stringify(clean(op.json));
|
|
529
|
-
}
|
|
530
|
-
let response;
|
|
531
|
-
try {
|
|
532
|
-
response = await this.config.fetch(this.url(op), init);
|
|
533
|
-
return await decode(op, response);
|
|
534
|
-
} catch (error) {
|
|
535
|
-
if (error instanceof AgentRunError) throw error;
|
|
536
|
-
if (options.signal?.aborted) throw options.signal.reason;
|
|
537
|
-
if (deadline.signal.aborted) throw new APITimeoutError(`Request timed out after ${this.config.timeoutMs}ms`);
|
|
538
|
-
const reason = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
539
|
-
throw new APIConnectionError(`Could not reach the AgentRun API: ${reason}`);
|
|
540
|
-
} finally {
|
|
541
|
-
clearTimeout(timer);
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
};
|
|
545
|
-
async function decode(op, response) {
|
|
546
|
-
const requestId = response.headers.get("x-request-id");
|
|
547
|
-
if (response.status >= 400) throw errorForStatus(response.status, await body(response), requestId);
|
|
548
|
-
if (op.raw) {
|
|
549
|
-
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
550
|
-
const artifact = new Artifact(bytes, response.headers.get("content-type"), filenameFrom(response.headers.get("content-disposition")));
|
|
551
|
-
return artifact;
|
|
552
|
-
}
|
|
553
|
-
const value = await body(response);
|
|
554
|
-
if (!isWire(value))
|
|
555
|
-
throw new InvalidResponseError(
|
|
556
|
-
`Expected a JSON object from ${op.method} ${op.path} but got ${response.headers.get("content-type") ?? "no content type"} (HTTP ${response.status}). Check baseURL points at the AgentRun API.`
|
|
557
|
-
);
|
|
558
|
-
try {
|
|
559
|
-
return op.parse(value);
|
|
560
|
-
} catch (error) {
|
|
561
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
562
|
-
throw new InvalidResponseError(`${op.method} ${op.path} returned an unexpected shape: ${reason}`);
|
|
563
|
-
}
|
|
564
|
-
}
|
|
565
|
-
async function body(response) {
|
|
566
|
-
const text = await response.text();
|
|
567
|
-
try {
|
|
568
|
-
return JSON.parse(text);
|
|
569
|
-
} catch {
|
|
570
|
-
return text;
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
function filenameFrom(disposition) {
|
|
574
|
-
if (!disposition) return null;
|
|
575
|
-
for (const part of disposition.split(";")) {
|
|
576
|
-
const trimmed = part.trim();
|
|
577
|
-
if (trimmed.toLowerCase().startsWith("filename=")) return trimmed.slice("filename=".length).replace(/^"|"$/g, "");
|
|
578
|
-
}
|
|
579
|
-
return null;
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
// src/ops.ts
|
|
583
|
-
var ROW_STATUS_WIRE = { queued: "PENDING", running: "PROCESSING", completed: "SUCCESS", failed: "FAILED" };
|
|
584
|
-
var BATCH_STATUS_WIRE = {
|
|
585
|
-
queued: "pending",
|
|
586
|
-
running: "processing",
|
|
587
|
-
completed: "processed_successfully",
|
|
588
|
-
completed_with_errors: "processed_with_errors",
|
|
589
|
-
failed: "processing_failed"
|
|
590
|
-
};
|
|
591
|
-
function id(value, what) {
|
|
592
|
-
if (!value || !value.trim()) throw new Error(`A ${what} is required.`);
|
|
593
|
-
return encodeURIComponent(value);
|
|
594
|
-
}
|
|
595
|
-
function length(value, what, low, high) {
|
|
596
|
-
const n = value.trim().length;
|
|
597
|
-
if (n < low || n > high) throw new Error(`${what} must be between ${low} and ${high} characters.`);
|
|
598
|
-
}
|
|
599
|
-
function cost(maxCostUsd) {
|
|
600
|
-
if (maxCostUsd !== void 0 && !(maxCostUsd >= 0.5 && maxCostUsd <= 1e3))
|
|
601
|
-
throw new Error("maxCostUsd must be between 0.5 and 1000.");
|
|
602
|
-
}
|
|
603
|
-
function schemaJSON(schema) {
|
|
604
|
-
if (schema === void 0) return void 0;
|
|
605
|
-
if ("toJSONSchema" in schema && typeof schema.toJSONSchema === "function") return schema.toJSONSchema();
|
|
606
|
-
return schema;
|
|
607
|
-
}
|
|
608
|
-
function listAgents(includePublic) {
|
|
609
|
-
return { method: "GET", path: "/agents/custom", parse: parse.agents, params: { include_public: includePublic } };
|
|
610
|
-
}
|
|
611
|
-
function getAgent(agentId) {
|
|
612
|
-
return { method: "GET", path: `/agents/${id(agentId, "agent ID")}`, parse: parse.agent };
|
|
613
|
-
}
|
|
614
|
-
function createAgent(d) {
|
|
615
|
-
length(d.name, "Agent name", 1, 255);
|
|
616
|
-
length(d.instructions, "Agent instructions", 1, 5e5);
|
|
617
|
-
if (d.description !== void 0) length(d.description, "Agent description", 0, 5e3);
|
|
618
|
-
return {
|
|
619
|
-
method: "POST",
|
|
620
|
-
path: "/agents",
|
|
621
|
-
parse: parse.agent,
|
|
622
|
-
json: {
|
|
623
|
-
name: d.name,
|
|
624
|
-
system_prompt: d.instructions,
|
|
625
|
-
skill_names: d.skills ?? [],
|
|
626
|
-
mcp_tool_names: d.tools ?? [],
|
|
627
|
-
status: "active",
|
|
628
|
-
description: d.description,
|
|
629
|
-
run_mode: d.run_mode,
|
|
630
|
-
campaign_plan: d.campaign_plan,
|
|
631
|
-
input_form: d.input_form,
|
|
632
|
-
output_schema: schemaJSON(d.outputSchema)
|
|
633
|
-
}
|
|
634
|
-
};
|
|
635
|
-
}
|
|
636
|
-
function updateAgent(agentId, changes) {
|
|
637
|
-
const body2 = { ...changes };
|
|
638
|
-
for (const [friendly, wire] of [["instructions", "system_prompt"], ["skills", "skill_names"], ["tools", "mcp_tool_names"]])
|
|
639
|
-
if (friendly in body2) {
|
|
640
|
-
body2[wire] = body2[friendly];
|
|
641
|
-
delete body2[friendly];
|
|
642
|
-
}
|
|
643
|
-
if ("outputSchema" in body2) {
|
|
644
|
-
body2.output_schema = schemaJSON(body2.outputSchema);
|
|
645
|
-
delete body2.outputSchema;
|
|
646
|
-
}
|
|
647
|
-
return { method: "PATCH", path: `/agents/${id(agentId, "agent ID")}`, parse: parse.agent, json: body2 };
|
|
648
|
-
}
|
|
649
|
-
function deleteAgent(agentId) {
|
|
650
|
-
return { method: "DELETE", path: `/agents/${id(agentId, "agent ID")}`, parse: parse.raw };
|
|
651
|
-
}
|
|
652
|
-
function activateAgent(agentId) {
|
|
653
|
-
return { method: "PATCH", path: `/agents/${id(agentId, "agent ID")}`, parse: parse.agent, json: { status: "active" } };
|
|
654
|
-
}
|
|
655
|
-
function startBuild(prompt, context, depth) {
|
|
656
|
-
const n = prompt.trim().length;
|
|
657
|
-
if (n < 3 || n > 500) throw new Error("Describe the agent in 3 to 500 characters. Put longer requirements in context.");
|
|
658
|
-
if (context !== void 0) length(context, "Build context", 0, 5e3);
|
|
659
|
-
return { method: "POST", path: "/agents/build", parse: parse.build, json: { domain: prompt, context, depth } };
|
|
660
|
-
}
|
|
661
|
-
function getBuild(buildId) {
|
|
662
|
-
return { method: "GET", path: `/agents/build/${id(buildId, "build ID")}`, parse: parse.build };
|
|
663
|
-
}
|
|
664
|
-
function createRun(question, agentId, o) {
|
|
665
|
-
if (!question.trim()) throw new Error("A non-empty question is required.");
|
|
666
|
-
cost(o.maxCostUsd);
|
|
667
|
-
return {
|
|
668
|
-
method: "POST",
|
|
669
|
-
path: "/runs",
|
|
670
|
-
parse: parse.run,
|
|
671
|
-
idempotencyKey: o.idempotencyKey,
|
|
672
|
-
json: {
|
|
673
|
-
question,
|
|
674
|
-
expert_id: agentId,
|
|
675
|
-
effort: o.effort ?? "low",
|
|
676
|
-
max_cost_usd: o.maxCostUsd,
|
|
677
|
-
response_language: o.responseLanguage,
|
|
678
|
-
json_schema: schemaJSON(o.outputSchema),
|
|
679
|
-
webhook_url: o.webhookUrl
|
|
680
|
-
}
|
|
681
|
-
};
|
|
682
|
-
}
|
|
683
|
-
function getRun(runId) {
|
|
684
|
-
return { method: "GET", path: `/runs/${id(runId, "run ID")}`, parse: parse.run };
|
|
685
|
-
}
|
|
686
|
-
function cancelRun(runId) {
|
|
687
|
-
return { method: "POST", path: `/runs/${id(runId, "run ID")}/cancel`, parse: parse.cancel, json: {} };
|
|
688
|
-
}
|
|
689
|
-
function listRuns(cursor, limit) {
|
|
690
|
-
return { method: "GET", path: "/runs", parse: parse.page(parse.runSummary), params: { cursor, limit } };
|
|
691
|
-
}
|
|
692
|
-
function createBatch(path, questions, rows, agentId, o, schedule) {
|
|
693
|
-
const name = o.name ?? (path === "/loops" ? "agentrun loop" : "agentrun batch");
|
|
694
|
-
length(name, "Batch name", 1, 200);
|
|
695
|
-
if (o.maxConcurrent !== void 0 && !(Number.isInteger(o.maxConcurrent) && o.maxConcurrent >= 1 && o.maxConcurrent <= 20))
|
|
696
|
-
throw new Error("maxConcurrent must be an integer between 1 and 20.");
|
|
697
|
-
if (o.maxCredits !== void 0 && !(o.maxCredits >= 1)) throw new Error("maxCredits must be at least 1.");
|
|
698
|
-
if (o.formInputs !== void 0 && o.formInputs.length !== questions.length)
|
|
699
|
-
throw new Error("formInputs must have one entry per input.");
|
|
700
|
-
return {
|
|
701
|
-
method: "POST",
|
|
702
|
-
path,
|
|
703
|
-
parse: parse.batch,
|
|
704
|
-
idempotencyKey: o.idempotencyKey,
|
|
705
|
-
json: {
|
|
706
|
-
batch_name: name,
|
|
707
|
-
questions,
|
|
708
|
-
rows,
|
|
709
|
-
inputs: o.formInputs,
|
|
710
|
-
expert_id: agentId,
|
|
711
|
-
effort: o.effort ?? "low",
|
|
712
|
-
response_language: o.responseLanguage,
|
|
713
|
-
max_concurrent: o.maxConcurrent,
|
|
714
|
-
max_credits: o.maxCredits,
|
|
715
|
-
custom_json_schema: schemaJSON(o.outputSchema),
|
|
716
|
-
schedule
|
|
717
|
-
}
|
|
718
|
-
};
|
|
719
|
-
}
|
|
720
|
-
function getBatch(batchId, includeRows) {
|
|
721
|
-
return { method: "GET", path: `/batches/${id(batchId, "batch ID")}`, parse: parse.batch, params: { include_rows: includeRows } };
|
|
722
|
-
}
|
|
723
|
-
function listBatches(f) {
|
|
724
|
-
const status = f.status ? BATCH_STATUS_WIRE[f.status] ?? f.status : void 0;
|
|
725
|
-
return { method: "GET", path: "/batches", parse: parse.page(parse.batch), params: { cursor: f.cursor, limit: f.limit, status, query: f.query } };
|
|
726
|
-
}
|
|
727
|
-
function getBatchResults(batchId, rowStatus) {
|
|
728
|
-
return {
|
|
729
|
-
method: "GET",
|
|
730
|
-
path: `/batches/${id(batchId, "batch ID")}/results`,
|
|
731
|
-
parse: parse.batchResults,
|
|
732
|
-
params: { row_status: rowStatus ? ROW_STATUS_WIRE[rowStatus] : void 0 }
|
|
733
|
-
};
|
|
734
|
-
}
|
|
735
|
-
function cancelBatch(batchId) {
|
|
736
|
-
return { method: "POST", path: `/batches/${id(batchId, "batch ID")}/cancel`, parse: parse.batch, json: {} };
|
|
737
|
-
}
|
|
738
|
-
function retryBatch(batchId, rowNumber) {
|
|
739
|
-
if (rowNumber !== void 0 && !(Number.isInteger(rowNumber) && rowNumber >= 0))
|
|
740
|
-
throw new Error("rowNumber must be zero or a positive integer.");
|
|
741
|
-
const action = rowNumber === void 0 ? "retry-failed" : `rows/${rowNumber}/retry`;
|
|
742
|
-
return { method: "POST", path: `/batches/${id(batchId, "batch ID")}/${action}`, parse: parse.retry, json: {} };
|
|
743
|
-
}
|
|
744
|
-
function getLoop(loopId) {
|
|
745
|
-
return { method: "GET", path: `/loops/${id(loopId, "loop ID")}`, parse: parse.loopDetail };
|
|
746
|
-
}
|
|
747
|
-
function updateLoop(loopId, changes) {
|
|
748
|
-
return { method: "PATCH", path: `/loops/${id(loopId, "loop ID")}`, parse: parse.loop, json: { ...changes } };
|
|
749
|
-
}
|
|
750
|
-
function loopAction(loopId, action) {
|
|
751
|
-
return { method: "POST", path: `/loops/${id(loopId, "loop ID")}/${action}`, parse: parse.loop, json: {} };
|
|
752
|
-
}
|
|
753
|
-
function runLoopNow(loopId) {
|
|
754
|
-
return { method: "POST", path: `/loops/${id(loopId, "loop ID")}/run-now`, parse: parse.loopRunNow, json: {} };
|
|
755
|
-
}
|
|
756
|
-
function deleteLoop(loopId, cancelActive) {
|
|
757
|
-
return { method: "DELETE", path: `/loops/${id(loopId, "loop ID")}`, parse: parse.loop, params: { cancel_active: cancelActive } };
|
|
758
|
-
}
|
|
759
|
-
function listSkills(f) {
|
|
760
|
-
return { method: "GET", path: "/skills", parse: parse.skillList, params: { query: f.query, category: f.category, limit: f.limit } };
|
|
761
|
-
}
|
|
762
|
-
function getSkill(name) {
|
|
763
|
-
return { method: "GET", path: `/skills/${id(name, "skill name")}`, parse: parse.skillContent };
|
|
764
|
-
}
|
|
765
|
-
function createSkill(name, description, content) {
|
|
766
|
-
length(name, "Skill name", 3, 100);
|
|
767
|
-
length(description, "Skill description", 10, 1e3);
|
|
768
|
-
length(content, "Skill content", 50, 2e5);
|
|
769
|
-
return { method: "POST", path: "/skills", parse: parse.skillRecord, json: { name, description, content } };
|
|
770
|
-
}
|
|
771
|
-
function listIntegrations(f) {
|
|
772
|
-
return {
|
|
773
|
-
method: "GET",
|
|
774
|
-
path: "/integrations",
|
|
775
|
-
parse: parse.integrationList,
|
|
776
|
-
params: { query: f.query, server: f.server, category: f.category, limit: f.limit }
|
|
777
|
-
};
|
|
778
|
-
}
|
|
779
|
-
function createCampaign(plan, records, idempotencyKey) {
|
|
780
|
-
return { method: "POST", path: "/campaigns", parse: parse.campaign, idempotencyKey, json: { plan, records } };
|
|
781
|
-
}
|
|
782
|
-
function runAgentCampaign(agentId, inputs, records, idempotencyKey) {
|
|
783
|
-
return {
|
|
784
|
-
method: "POST",
|
|
785
|
-
path: `/agents/${id(agentId, "agent ID")}/campaigns`,
|
|
786
|
-
parse: parse.campaign,
|
|
787
|
-
idempotencyKey,
|
|
788
|
-
json: { inputs, records }
|
|
789
|
-
};
|
|
790
|
-
}
|
|
791
|
-
function getCampaign(campaignId) {
|
|
792
|
-
return { method: "GET", path: `/campaigns/${id(campaignId, "campaign ID")}`, parse: parse.campaign };
|
|
793
|
-
}
|
|
794
|
-
function listCampaigns(cursor, limit) {
|
|
795
|
-
return { method: "GET", path: "/campaigns", parse: parse.page(parse.campaign), params: { cursor, limit } };
|
|
796
|
-
}
|
|
797
|
-
function approveCampaign(campaignId, reviewDigest) {
|
|
798
|
-
if (!/^[a-f0-9]{64}$/.test(reviewDigest))
|
|
799
|
-
throw new Error("reviewDigest must be the 64-character hex digest of the exact plan you reviewed.");
|
|
800
|
-
return { method: "POST", path: `/campaigns/${id(campaignId, "campaign ID")}/approve`, parse: parse.campaign, json: { review_digest: reviewDigest } };
|
|
801
|
-
}
|
|
802
|
-
function cancelCampaign(campaignId) {
|
|
803
|
-
return { method: "POST", path: `/campaigns/${id(campaignId, "campaign ID")}/cancel`, parse: parse.campaign, json: {} };
|
|
804
|
-
}
|
|
805
|
-
function getCampaignPortfolio(campaignId, stageKey, f) {
|
|
806
|
-
if (!stageKey.trim()) throw new Error("A stage key is required.");
|
|
807
|
-
return {
|
|
808
|
-
method: "GET",
|
|
809
|
-
path: `/campaigns/${id(campaignId, "campaign ID")}/portfolio`,
|
|
810
|
-
parse: parse.portfolio,
|
|
811
|
-
params: { stage_key: stageKey, ...f }
|
|
812
|
-
};
|
|
813
|
-
}
|
|
814
|
-
function downloadCampaignArtifact(campaignId, deliverableKey) {
|
|
815
|
-
return {
|
|
816
|
-
method: "GET",
|
|
817
|
-
path: `/campaigns/${id(campaignId, "campaign ID")}/artifacts/${id(deliverableKey, "deliverable key")}`,
|
|
818
|
-
parse: parse.raw,
|
|
819
|
-
raw: true
|
|
820
|
-
};
|
|
821
|
-
}
|
|
822
|
-
function getUsage(f) {
|
|
823
|
-
return { method: "GET", path: "/usage", parse: parse.usage, params: { period: f.period, from: f.from, to: f.to } };
|
|
824
|
-
}
|
|
825
|
-
|
|
826
|
-
// src/poll.ts
|
|
827
|
-
async function poll(fetch, done, options, defaults, what) {
|
|
828
|
-
const timeoutMs = options.timeoutMs ?? defaults.timeoutMs;
|
|
829
|
-
const intervalMs = options.intervalMs ?? defaults.intervalMs;
|
|
830
|
-
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || !Number.isFinite(intervalMs) || intervalMs <= 0)
|
|
831
|
-
throw new Error("timeoutMs and intervalMs must be positive.");
|
|
832
|
-
const deadline = Date.now() + timeoutMs;
|
|
833
|
-
for (; ; ) {
|
|
834
|
-
options.signal?.throwIfAborted();
|
|
835
|
-
const value = await fetch(options.signal);
|
|
836
|
-
if (done(value)) return value;
|
|
837
|
-
const remaining = deadline - Date.now();
|
|
838
|
-
if (remaining <= 0)
|
|
839
|
-
throw new PollTimeoutError(
|
|
840
|
-
`Gave up waiting for ${what} after ${timeoutMs}ms. The remote work continues; fetch it again later.`
|
|
841
|
-
);
|
|
842
|
-
await sleep(Math.min(intervalMs, remaining), options.signal);
|
|
843
|
-
}
|
|
844
|
-
}
|
|
845
|
-
function sleep(ms, signal) {
|
|
846
|
-
return new Promise((resolve, reject) => {
|
|
847
|
-
if (signal?.aborted) return reject(signal.reason);
|
|
848
|
-
const timer = setTimeout(() => {
|
|
849
|
-
signal?.removeEventListener("abort", onAbort);
|
|
850
|
-
resolve();
|
|
851
|
-
}, ms);
|
|
852
|
-
const onAbort = () => {
|
|
853
|
-
clearTimeout(timer);
|
|
854
|
-
reject(signal?.reason);
|
|
855
|
-
};
|
|
856
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
857
|
-
});
|
|
858
|
-
}
|
|
859
|
-
|
|
860
|
-
// src/client.ts
|
|
861
|
-
var RUN_WAIT = { timeoutMs: 6e5, intervalMs: 1e3 };
|
|
862
|
-
var BUILD_WAIT = { timeoutMs: 12e5, intervalMs: 2e3 };
|
|
863
|
-
var BATCH_WAIT = { timeoutMs: 12e5, intervalMs: 2e3 };
|
|
864
|
-
var CAMPAIGN_WAIT = { timeoutMs: 12e5, intervalMs: 1e3 };
|
|
865
|
-
var AgentRun = class {
|
|
866
|
-
http;
|
|
867
|
-
constructor(options = {}) {
|
|
868
|
-
this.http = new Transport(resolveConfig(options));
|
|
869
|
-
}
|
|
870
|
-
/** The resolved base URL. */
|
|
871
|
-
get baseURL() {
|
|
872
|
-
return this.http.config.baseURL;
|
|
873
|
-
}
|
|
874
|
-
// Agents
|
|
875
|
-
async listAgents(o = {}) {
|
|
876
|
-
return this.http.send(listAgents(o.includePublic ?? false), o);
|
|
877
|
-
}
|
|
878
|
-
async getAgent(agentId, o = {}) {
|
|
879
|
-
return this.http.send(getAgent(agentId), o);
|
|
880
|
-
}
|
|
881
|
-
/** Save an agent definition. Not retried: a timed-out call may still have created it. */
|
|
882
|
-
async createAgent(definition, o = {}) {
|
|
883
|
-
return this.http.send(createAgent(definition), o);
|
|
884
|
-
}
|
|
885
|
-
/** Change fields on an agent. Accepts `instructions`, `skills`, `tools`, `outputSchema` and any API field. */
|
|
886
|
-
async updateAgent(agentId, changes, o = {}) {
|
|
887
|
-
return this.http.send(updateAgent(agentId, changes), o);
|
|
888
|
-
}
|
|
889
|
-
async deleteAgent(agentId, o = {}) {
|
|
890
|
-
await this.http.send(deleteAgent(agentId), o);
|
|
891
|
-
}
|
|
892
|
-
async getBuild(buildId, o = {}) {
|
|
893
|
-
return this.http.send(getBuild(buildId), o);
|
|
894
|
-
}
|
|
895
|
-
/** Poll a build until it succeeds or fails. Does not activate the agent; `Agent` does that. */
|
|
896
|
-
async waitBuild(buildId, o = {}) {
|
|
897
|
-
return poll((signal) => this.getBuild(buildId, { signal }), (b) => !BUILD_ACTIVE_STATUSES.has(b.status), o, BUILD_WAIT, `build ${buildId}`);
|
|
898
|
-
}
|
|
899
|
-
// Runs
|
|
900
|
-
/** Start a run and return at once. Pass the same `idempotencyKey` to retry safely. */
|
|
901
|
-
async run(question, o = {}) {
|
|
902
|
-
return this.http.send(createRun(question, o.agentId, o), o);
|
|
903
|
-
}
|
|
904
|
-
async getRun(runId, o = {}) {
|
|
905
|
-
return this.http.send(getRun(runId), o);
|
|
906
|
-
}
|
|
907
|
-
async cancelRun(runId, o = {}) {
|
|
908
|
-
return this.http.send(cancelRun(runId), o);
|
|
909
|
-
}
|
|
910
|
-
/** Poll until the run is completed, failed, cancelled, or blocked. Check `run.status`. */
|
|
911
|
-
async waitRun(runId, o = {}) {
|
|
912
|
-
return poll((signal) => this.getRun(runId, { signal }), (r) => RUN_TERMINAL_STATUSES.has(r.status), o, RUN_WAIT, `run ${runId}`);
|
|
913
|
-
}
|
|
914
|
-
async listRuns(o = {}) {
|
|
915
|
-
return this.http.send(listRuns(o.cursor, o.limit), o);
|
|
916
|
-
}
|
|
917
|
-
/** Walk every run, newest first, fetching pages as needed. */
|
|
918
|
-
async *iterRuns(o = {}) {
|
|
919
|
-
let cursor;
|
|
920
|
-
for (; ; ) {
|
|
921
|
-
const page = await this.listRuns({ ...o, cursor, limit: o.pageSize });
|
|
922
|
-
yield* page.items;
|
|
923
|
-
if (!page.has_more || !page.next_cursor) return;
|
|
924
|
-
cursor = page.next_cursor;
|
|
925
|
-
}
|
|
926
|
-
}
|
|
927
|
-
// Batches
|
|
928
|
-
/** Fetch a batch. Pass `includeRows: false` to skip per-row data on large batches. */
|
|
929
|
-
async getBatch(batchId, o = {}) {
|
|
930
|
-
return this.http.send(getBatch(batchId, o.includeRows), o);
|
|
931
|
-
}
|
|
932
|
-
async listBatches(o = {}) {
|
|
933
|
-
return this.http.send(listBatches(o), o);
|
|
934
|
-
}
|
|
935
|
-
async getBatchResults(batchId, o = {}) {
|
|
936
|
-
return this.http.send(getBatchResults(batchId, o.rowStatus), o);
|
|
937
|
-
}
|
|
938
|
-
/** Stop dispatching new rows. Rows already running finish on their own. */
|
|
939
|
-
async cancelBatch(batchId, o = {}) {
|
|
940
|
-
return this.http.send(cancelBatch(batchId), o);
|
|
941
|
-
}
|
|
942
|
-
/** Retry every failed row, or one row. Retries spend credits. */
|
|
943
|
-
async retryBatch(batchId, o = {}) {
|
|
944
|
-
return this.http.send(retryBatch(batchId, o.rowNumber), o);
|
|
945
|
-
}
|
|
946
|
-
/** Poll until the batch finishes, fails, is cancelled, or pauses for attention. */
|
|
947
|
-
async waitBatch(batchId, o = {}) {
|
|
948
|
-
return poll(
|
|
949
|
-
(signal) => this.getBatch(batchId, { signal, includeRows: false }),
|
|
950
|
-
(b) => BATCH_TERMINAL_STATUSES.has(b.status) || Boolean(b.paused_reason),
|
|
951
|
-
o,
|
|
952
|
-
BATCH_WAIT,
|
|
953
|
-
`batch ${batchId}`
|
|
954
|
-
);
|
|
955
|
-
}
|
|
956
|
-
// Loops
|
|
957
|
-
async getLoop(loopId, o = {}) {
|
|
958
|
-
return this.http.send(getLoop(loopId), o);
|
|
959
|
-
}
|
|
960
|
-
/** Rename a loop or change its cadence. Inputs are frozen at creation. */
|
|
961
|
-
async updateLoop(loopId, changes, o = {}) {
|
|
962
|
-
return this.http.send(updateLoop(loopId, changes), o);
|
|
963
|
-
}
|
|
964
|
-
async pauseLoop(loopId, o = {}) {
|
|
965
|
-
return this.http.send(loopAction(loopId, "pause"), o);
|
|
966
|
-
}
|
|
967
|
-
async resumeLoop(loopId, o = {}) {
|
|
968
|
-
return this.http.send(loopAction(loopId, "resume"), o);
|
|
969
|
-
}
|
|
970
|
-
/** Start an extra batch without shifting the schedule. Conflicts if one is already running. */
|
|
971
|
-
async runLoopNow(loopId, o = {}) {
|
|
972
|
-
return this.http.send(runLoopNow(loopId), o);
|
|
973
|
-
}
|
|
974
|
-
async deleteLoop(loopId, o = {}) {
|
|
975
|
-
return this.http.send(deleteLoop(loopId, o.cancelActive ?? false), o);
|
|
976
|
-
}
|
|
977
|
-
// Skills and integrations
|
|
978
|
-
async listSkills(o = {}) {
|
|
979
|
-
return this.http.send(listSkills(o), o);
|
|
980
|
-
}
|
|
981
|
-
async getSkill(name, o = {}) {
|
|
982
|
-
return this.http.send(getSkill(name), o);
|
|
983
|
-
}
|
|
984
|
-
/** Save reusable Markdown. Reusing a name updates your existing skill (`created: false`). */
|
|
985
|
-
async createSkill(d, o = {}) {
|
|
986
|
-
return this.http.send(createSkill(d.name, d.description, d.content), o);
|
|
987
|
-
}
|
|
988
|
-
async listIntegrations(o = {}) {
|
|
989
|
-
return this.http.send(listIntegrations(o), o);
|
|
990
|
-
}
|
|
991
|
-
// Campaigns
|
|
992
|
-
/** Save a campaign as a draft. Review it, then `approveCampaign` to start work. */
|
|
993
|
-
async createCampaign(plan, o = {}) {
|
|
994
|
-
return this.http.send(createCampaign(plan, o.records, o.idempotencyKey), o);
|
|
995
|
-
}
|
|
996
|
-
async getCampaign(campaignId, o = {}) {
|
|
997
|
-
return this.http.send(getCampaign(campaignId), o);
|
|
998
|
-
}
|
|
999
|
-
async listCampaigns(o = {}) {
|
|
1000
|
-
return this.http.send(listCampaigns(o.cursor, o.limit), o);
|
|
1001
|
-
}
|
|
1002
|
-
/** Start a draft. `reviewDigest` must match the plan you reviewed or the API returns 409. */
|
|
1003
|
-
async approveCampaign(campaignId, reviewDigest, o = {}) {
|
|
1004
|
-
return this.http.send(approveCampaign(campaignId, reviewDigest), o);
|
|
1005
|
-
}
|
|
1006
|
-
async cancelCampaign(campaignId, o = {}) {
|
|
1007
|
-
return this.http.send(cancelCampaign(campaignId), o);
|
|
1008
|
-
}
|
|
1009
|
-
/** Poll until the campaign is a draft, done, cancelled, failed, or needs attention. */
|
|
1010
|
-
async waitCampaign(campaignId, o = {}) {
|
|
1011
|
-
return poll((signal) => this.getCampaign(campaignId, { signal }), (c) => CAMPAIGN_TERMINAL_STATUSES.has(c.status), o, CAMPAIGN_WAIT, `campaign ${campaignId}`);
|
|
1012
|
-
}
|
|
1013
|
-
async getCampaignPortfolio(campaignId, stageKey, o = {}) {
|
|
1014
|
-
const { signal, ...filter } = o;
|
|
1015
|
-
return this.http.send(getCampaignPortfolio(campaignId, stageKey, filter), { signal });
|
|
1016
|
-
}
|
|
1017
|
-
/** Fetch a finished deliverable. `artifact.content` holds the raw bytes. */
|
|
1018
|
-
async downloadCampaignArtifact(campaignId, deliverableKey, o = {}) {
|
|
1019
|
-
return this.http.send(downloadCampaignArtifact(campaignId, deliverableKey), o);
|
|
1020
|
-
}
|
|
1021
|
-
// Account
|
|
1022
|
-
async getUsage(o = {}) {
|
|
1023
|
-
return this.http.send(getUsage(o), o);
|
|
1024
|
-
}
|
|
1025
|
-
};
|
|
1026
|
-
|
|
1027
|
-
// src/agent.ts
|
|
1028
|
-
var FREQUENCIES = /* @__PURE__ */ new Set(["daily", "weekly", "monthly"]);
|
|
1029
|
-
var Agent = class _Agent extends AgentRun {
|
|
1030
|
-
#id;
|
|
1031
|
-
#buildId;
|
|
1032
|
-
#definition;
|
|
1033
|
-
#creation;
|
|
1034
|
-
constructor(options) {
|
|
1035
|
-
super(options);
|
|
1036
|
-
const { id: id2, buildId, name, instructions } = options;
|
|
1037
|
-
if (!id2 && !buildId && !(name?.trim() && instructions?.trim()))
|
|
1038
|
-
throw new Error("Provide id, buildId, or both name and instructions.");
|
|
1039
|
-
this.#id = id2;
|
|
1040
|
-
this.#buildId = buildId;
|
|
1041
|
-
this.#definition = name && instructions ? { ...options, name, instructions } : void 0;
|
|
1042
|
-
}
|
|
1043
|
-
/**
|
|
1044
|
-
* Start building an agent from a plain-English description. Returns at once.
|
|
1045
|
-
* Save `agent.buildId` if the process might stop, then resume with
|
|
1046
|
-
* `new Agent({ buildId })`. Building can take several minutes.
|
|
1047
|
-
*/
|
|
1048
|
-
static async create(prompt, options = {}) {
|
|
1049
|
-
const { context, depth, signal, ...client } = options;
|
|
1050
|
-
const build = await new AgentRun(client).http.send(startBuild(prompt, context, depth ?? "standard"), { signal });
|
|
1051
|
-
return new _Agent({ ...client, buildId: build.id });
|
|
1052
|
-
}
|
|
1053
|
-
/** The agent ID, or undefined until the agent has been saved or built. */
|
|
1054
|
-
get id() {
|
|
1055
|
-
return this.#id;
|
|
1056
|
-
}
|
|
1057
|
-
get buildId() {
|
|
1058
|
-
return this.#buildId;
|
|
1059
|
-
}
|
|
1060
|
-
/**
|
|
1061
|
-
* Wait for a build to finish and activate the agent, or save a defined agent.
|
|
1062
|
-
* Throws `BuildError` if the build failed and `PollTimeoutError` at the local
|
|
1063
|
-
* deadline. A timeout does not stop the build.
|
|
1064
|
-
*/
|
|
1065
|
-
async waitUntilReady(o = {}) {
|
|
1066
|
-
if (this.#id) return this;
|
|
1067
|
-
if (!this.#buildId) {
|
|
1068
|
-
await this.ensureId(o.signal);
|
|
1069
|
-
return this;
|
|
1070
|
-
}
|
|
1071
|
-
const buildId = this.#buildId;
|
|
1072
|
-
const build = await poll(
|
|
1073
|
-
(signal) => this.getBuild(buildId, { signal }),
|
|
1074
|
-
(b) => !BUILD_ACTIVE_STATUSES.has(b.status),
|
|
1075
|
-
o,
|
|
1076
|
-
BUILD_WAIT,
|
|
1077
|
-
`build ${buildId}`
|
|
1078
|
-
);
|
|
1079
|
-
if (build.status !== "succeeded") throw new BuildError(build);
|
|
1080
|
-
if (!build.agent_id) throw new InvalidResponseError(`Build ${build.id} succeeded but returned no agent ID.`);
|
|
1081
|
-
const active = await this.http.send(activateAgent(build.agent_id), { signal: o.signal });
|
|
1082
|
-
if (active.id !== build.agent_id || active.status !== "active")
|
|
1083
|
-
throw new InvalidResponseError(`Agent ${build.agent_id} was created but is not active (status=${active.status}).`);
|
|
1084
|
-
this.#id = build.agent_id;
|
|
1085
|
-
return this;
|
|
1086
|
-
}
|
|
1087
|
-
/** Save a defined agent without running it and return its ID. */
|
|
1088
|
-
async save(o = {}) {
|
|
1089
|
-
return this.ensureId(o.signal);
|
|
1090
|
-
}
|
|
1091
|
-
async ensureId(signal) {
|
|
1092
|
-
if (this.#id) return this.#id;
|
|
1093
|
-
if (this.#buildId) {
|
|
1094
|
-
await this.waitUntilReady({ signal });
|
|
1095
|
-
return this.#id;
|
|
1096
|
-
}
|
|
1097
|
-
this.#creation ??= this.http.send(createAgent(this.#definition), { signal }).then((record) => {
|
|
1098
|
-
this.#id = record.id;
|
|
1099
|
-
return record.id;
|
|
1100
|
-
});
|
|
1101
|
-
return this.#creation;
|
|
1102
|
-
}
|
|
1103
|
-
// Runs
|
|
1104
|
-
/** Start one run. Returns the queued run; call `wait` for the result. */
|
|
1105
|
-
async run(question, o = {}) {
|
|
1106
|
-
const agentId = await this.ensureId(o.signal);
|
|
1107
|
-
return super.run(question, { ...o, agentId });
|
|
1108
|
-
}
|
|
1109
|
-
/** Poll a run until it is completed, failed, cancelled, or blocked. */
|
|
1110
|
-
async wait(runId, o = {}) {
|
|
1111
|
-
return this.waitRun(runId, { ...RUN_WAIT, ...o });
|
|
1112
|
-
}
|
|
1113
|
-
// Batches and loops
|
|
1114
|
-
/** Run up to 100 inputs as one batch. Oversized batches are rejected before anything is sent. */
|
|
1115
|
-
async batch(inputs, o = {}) {
|
|
1116
|
-
const { questions, rows } = await prepareInputs(inputs);
|
|
1117
|
-
const agentId = await this.ensureId(o.signal);
|
|
1118
|
-
return this.http.send(createBatch("/batches", questions, rows, agentId, o, void 0), o);
|
|
1119
|
-
}
|
|
1120
|
-
/** Run the inputs now and again on a schedule. `maxCredits` caps each occurrence, not the total. */
|
|
1121
|
-
async loop(inputs, cadence, o = {}) {
|
|
1122
|
-
if (!FREQUENCIES.has(cadence.frequency)) throw new Error("Loop frequency must be daily, weekly, or monthly.");
|
|
1123
|
-
const { questions, rows } = await prepareInputs(inputs);
|
|
1124
|
-
const agentId = await this.ensureId(o.signal);
|
|
1125
|
-
const batch = await this.http.send(createBatch("/loops", questions, rows, agentId, o, cadence), o);
|
|
1126
|
-
if (!batch.loop_id)
|
|
1127
|
-
throw new InvalidResponseError(`Batch ${batch.id} was created but no loop ID came back. Inspect it before retrying.`);
|
|
1128
|
-
return { id: batch.loop_id, first_batch_id: batch.id, status: batch.status };
|
|
1129
|
-
}
|
|
1130
|
-
// Campaigns
|
|
1131
|
-
/** Start this agent's configured campaign template with form inputs. Work begins immediately. */
|
|
1132
|
-
async campaign(inputs, o = {}) {
|
|
1133
|
-
const agentId = await this.ensureId(o.signal);
|
|
1134
|
-
return this.http.send(runAgentCampaign(agentId, inputs, o.records, o.idempotencyKey), o);
|
|
1135
|
-
}
|
|
1136
|
-
};
|
|
1137
|
-
var Skill = {
|
|
1138
|
-
async create(d) {
|
|
1139
|
-
const { name, description, content, signal, ...client } = d;
|
|
1140
|
-
return new AgentRun(client).createSkill({ name, description, content }, { signal });
|
|
1141
|
-
},
|
|
1142
|
-
async read(name, options = {}) {
|
|
1143
|
-
const { signal, ...client } = options;
|
|
1144
|
-
return new AgentRun(client).getSkill(name, { signal });
|
|
1145
|
-
}
|
|
1146
|
-
};
|
|
1147
|
-
|
|
1148
|
-
export { APIConnectionError, APIError, APITimeoutError, Agent, AgentRun, AgentRunError, Artifact, AuthenticationError, BATCH_STATUS_MAP, BATCH_TERMINAL_STATUSES, BuildError, CAMPAIGN_TERMINAL_STATUSES, ConflictError, DEFAULT_BASE_URL, InternalServerError, InvalidResponseError, MAX_CSV_BYTES, MAX_INPUTS, MAX_INPUT_CHARS, NotFoundError, PermissionDeniedError, PollTimeoutError, ROW_STATUS_MAP, RUN_STATUS_MAP, RUN_TERMINAL_STATUSES, RateLimitError, ServiceUnavailableError, Skill, UnprocessableEntityError, VERSION, parseBatchCSV };
|
|
1149
|
-
//# sourceMappingURL=index.js.map
|
|
1150
|
-
//# sourceMappingURL=index.js.map
|