@parcha/agentrun 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,171 @@
1
+ # agentrun
2
+
3
+ A dependency-free Node.js client for agentrun's headless API.
4
+
5
+ ```sh
6
+ npm install @parcha/agentrun
7
+ ```
8
+
9
+ ```ts
10
+ import { Agent } from '@parcha/agentrun';
11
+ const agent = new Agent({
12
+ apiKey: process.env.AGENTRUN_API_KEY!,
13
+ name: 'Verifier',
14
+ instructions: 'Verify the company and cite evidence.',
15
+ // Set baseURL to your agentrun deployment while running locally.
16
+ });
17
+ const run = await agent.run('Verify acme.example', { idempotencyKey: 'acme-001' });
18
+ const result = await agent.wait(run.id);
19
+ console.log(result.status, result.report);
20
+ ```
21
+
22
+ `create()` saves an agent without starting a run. Reuse an existing agent with `id` instead of `name` and `instructions`. `getRun(id)` reads progress; `cancelRun(id)` requests cancellation. `wait(id)` returns completed, failed, blocked, or cancelled results; inspect `status` before using the report. Aborting a local request or polling deadline does not cancel an already accepted run.
23
+
24
+ Credentials belong in your server environment. The SDK never retries creation or execution automatically. Use stable idempotency keys for run retries. Recover the agent ID after an ambiguous create timeout instead of blindly creating it again.
25
+
26
+ Build and pack from the parent website with `npm run sdk:pack`. The generated tarball can be installed directly for local testing.
27
+
28
+ ## Discover skills and tools
29
+
30
+ ```ts
31
+ import { AgentRun } from '@parcha/agentrun';
32
+ const client = new AgentRun({ apiKey: process.env.AGENTRUN_API_KEY! });
33
+ const skills = await client.listSkills({ query: 'company', limit: 500 });
34
+ const tools = await client.listIntegrations({ query: 'company', limit: 500 });
35
+ const agent = client.agent({
36
+ name: 'Company verifier',
37
+ instructions: 'Verify the company and cite evidence.',
38
+ skills: skills.skills.map(skill => skill.name),
39
+ tools: tools.tools.filter(tool => !tool.always_on).map(tool => tool.name),
40
+ });
41
+ ```
42
+
43
+ `listAgents()`, `getAgent(id)`, `updateAgent(id, definition)`, and `deleteAgent(id)` manage your definitions. `listRuns({cursor, limit})` reads run history. Run reports expose Markdown through `result.report?.markdown` and optional structured fields through `result.structured_output`.
44
+
45
+ ## Build an agent from plain English
46
+
47
+ ```ts
48
+ const agent = await Agent.create({
49
+ apiKey: process.env.AGENTRUN_API_KEY!,
50
+ prompt: 'Research companies and cite sources.',
51
+ });
52
+ // Save agent.buildId to resume if this process stops.
53
+ await agent.waitUntilReady();
54
+ const run = await agent.run('Research acme.example');
55
+ const result = await agent.wait(run.id);
56
+ ```
57
+
58
+ Creation can take a few minutes. `waitUntilReady({ timeoutMs, intervalMs, signal })` polls the build and activates its draft; its defaults are 20 minutes and one-second polling. `run()` also waits automatically. A failed build throws `AgentBuildError`. A timeout or abort stops local waiting, not the remote build. Resume with `new Agent({ apiKey, buildId })`; inspect with `client.getBuild(buildId)`. No creation request is retried automatically. Caller-defined agents still use `new Agent({name, instructions, apiKey})` and the instance `create()` method without a generation job.
59
+
60
+ ## Reusable skills
61
+
62
+ ```ts
63
+ import { Skill } from '@parcha/agentrun';
64
+ const skill = await Skill.create({
65
+ apiKey: process.env.AGENTRUN_API_KEY!,
66
+ name: 'source-check',
67
+ description: 'Verify each claim against its primary source.',
68
+ content: '# Source check\nFind a primary source for every claim. Cite evidence and flag any gaps.',
69
+ });
70
+ ```
71
+
72
+ Attach `skill.name` in an agent definition's `skills` array. `client.createSkill(definition)` provides the same operation, and `client.getSkill(name)` reads its Markdown. Creating a skill with the same name updates your own existing skill (`created: false`); use a new name to preserve the previous one. Requires agent write permission.
73
+
74
+ ## Batch lists and CSV inputs
75
+
76
+ ```ts
77
+ const batch = await agent.batch(['Research acme.example', 'Research beta.example'], {
78
+ name: 'Company checks', maxConcurrent: 2, idempotencyKey: 'checks-001',
79
+ });
80
+ const status = await agent.waitBatch(batch.id);
81
+ const results = await agent.getBatchResults(batch.id);
82
+ // csv may be a string or an uploaded File/Blob; headers must be unique.
83
+ const uploaded = await agent.batch({ csv, inputColumn: 'input' }, { name: 'CSV checks' });
84
+ ```
85
+
86
+ Each batch accepts 1–100 nonblank inputs (up to 8,000 characters each). CSV is limited to 1 MB and additional columns are retained as row data. Quotes, escaped quotes, commas, and embedded newlines are supported. Oversized batches are rejected before agent creation; the SDK never silently splits or retries paid work. Batch execution must be enabled for the upstream account.
87
+
88
+ `getBatch`, `listBatches`, `getBatchResults`, `cancelBatch`, and `retryBatch` expose the lifecycle. `waitBatch` returns on completion, partial failure, failure, cancellation, or a pause reason that requires attention. Inspect row outcomes and follow each `run_id` with `getRun` for full reports. Cancellation stops new dispatches; running rows settle on their own. Explicit retries can consume more credits. Options support `maxCredits`, `maxConcurrent` (1–20), effort, output schema, language, and cancellation. Generated agents are awaited before batch submission. Use agent.loop() for recurring work.
89
+
90
+ ## Campaigns
91
+
92
+ Campaign endpoints require an upstream deployment with the public campaign adapter and campaign access enabled for the account. A configured agent can start its existing campaign template with `await agent.campaign({ sector: 'energy' }, { idempotencyKey: 'energy-001' })`. This immediately creates and approves work using that agent's template. Set run_mode, campaign_plan, and input_form in the agent definition to configure one.
93
+
94
+ For a caller-defined campaign plan, save and review before executing:
95
+
96
+ ```ts
97
+ const draft = await client.createCampaign(plan, { idempotencyKey: 'discovery-001' });
98
+ // Review draft.stages, draft.deliverables, and draft.objective first.
99
+ const started = await client.approveCampaign(draft.id, draft.review_digest);
100
+ const current = await client.getCampaign(started.id);
101
+ // When an artifact is ready, use its deliverable_key:
102
+ const file = await client.downloadCampaignArtifact(started.id, deliverableKey);
103
+ ```
104
+
105
+ `listCampaigns` lists your campaigns; `cancelCampaign` stops pending work. Approval requires the digest of the exact reviewed plan; stale approval returns a conflict. Result downloads return a Blob containing the original artifact bytes. Requests are never retried automatically. MCP exposes `create_campaign`, `get_campaign`, `approve_campaign`, `cancel_campaign`, and `campaign_agent` with the same caller authorization and approval behavior.
106
+
107
+ Automatic goal-to-plan generation is still planned. Campaign templates can be defined and updated entirely through the SDK.
108
+
109
+ ## Scheduled loops
110
+
111
+ ```ts
112
+ const loop = await agent.loop('Check acme.example', {
113
+ frequency: 'weekly',
114
+ schedule_config: { hour: 9, minute: 0, day_of_week: 1 },
115
+ timezone: 'America/New_York',
116
+ }, { name: 'Weekly checks', maxCredits: 20, idempotencyKey: 'weekly-checks-001' });
117
+ const history = await agent.getLoop(loop.id);
118
+ const results = await agent.getBatchResults(history.runs[0].id);
119
+ await agent.pauseLoop(loop.id);
120
+ await agent.resumeLoop(loop.id);
121
+ await agent.deleteLoop(loop.id, { cancelActive: true });
122
+ ```
123
+
124
+ The first batch starts immediately; later occurrences follow the cadence. Inputs may be a string, a list of up to 100 inputs, or the same CSV object accepted by `batch`. Frequency is daily, weekly, or monthly; hour/minute are local to the IANA timezone (UTC by default). Weekly schedules accept day_of_week (0=Monday); monthly schedules use day_of_month (1–28).
125
+
126
+ Each occurrence is billed as a batch. `maxCredits` limits each batch, not total lifetime spending. Pause or delete the loop to stop future work. Already running rows may finish; `deleteLoop({cancelActive:true})` also cancels pending rows in the latest batch. `updateLoop` changes the name or cadence but never the frozen inputs. `runLoopNow` starts an extra batch without shifting the cadence; overlapping active work returns a conflict. Reads include skip reasons and batch history, whose IDs work with `getBatch` and `getBatchResults`.
127
+
128
+ The upstream deployment must include the public schedule-management adapter and enable recurring batch access for your account. MCP provides `loop_agent`, `get_loop`, `update_loop`, `pause_loop`, `resume_loop`, `delete_loop`, and `run_loop_now`.
129
+
130
+ ## Define a campaign agent
131
+
132
+ Create an agent with `run_mode: 'campaign'`, a `campaign_plan`, and its `input_form`. Template strings use `{{field_label}}` to insert input values. The backend validates the template and refuses undeclared placeholders or a campaign mode without a plan. `getAgent` returns the configuration; `updateAgent` can replace it. To return to ordinary runs, update with `{ run_mode: 'job', campaign_plan: null }`.
133
+
134
+ ```ts
135
+ const agent = new Agent({
136
+ apiKey: process.env.AGENTRUN_API_KEY!,
137
+ name: 'Company discovery',
138
+ instructions: 'Find verifiable company information and cite evidence.',
139
+ run_mode: 'campaign',
140
+ input_form: [{ label: 'goal', type: 'text', required: true }],
141
+ campaign_plan: {
142
+ name: 'Company discovery', objective: '{{goal}}',
143
+ stages: [
144
+ { key: 'discover', title: 'Find companies', op: 'agent',
145
+ instruction: 'Find companies matching this goal: {{goal}}',
146
+ entity_key_field: 'company_website', records_field: 'companies' },
147
+ { key: 'inspect', title: 'Verify each company', op: 'agent',
148
+ instruction: 'Verify this company against the goal: {{goal}}. Cite evidence.',
149
+ fanout: 'per_entity', entity_key_field: 'company_website', depends_on: ['discover'],
150
+ output_schema: { type: 'object', properties: { evidence: { type: 'string' } } } },
151
+ { key: 'join', title: 'Combine findings', op: 'join', depends_on: ['discover', 'inspect'] },
152
+ { key: 'export', title: 'Export results', op: 'export', depends_on: ['join'],
153
+ filename: 'companies.xlsx', entity_key_field: 'company_website',
154
+ columns: ['company_website', 'company', 'evidence'], requested: 10 },
155
+ ],
156
+ deliverables: [{ key: 'companies', title: 'Verified companies', kind: 'dataset', from_stage: 'export' }],
157
+ },
158
+ });
159
+ await agent.create();
160
+ const campaign = await agent.campaign({ goal: 'Find UK cloud infrastructure companies' }, {
161
+ idempotencyKey: 'company-discovery-001',
162
+ });
163
+ ```
164
+
165
+ This call renders and starts the configured campaign immediately. Use `getCampaign(campaign.id)` to inspect stage progress and download a ready artifact with `downloadCampaignArtifact(campaign.id, 'companies')`. The same configuration fields are accepted by MCP `create_agent`.
166
+
167
+ ## Campaign progress and result pages
168
+
169
+ `await client.waitCampaign(id, { intervalMs, timeoutMs, signal })` waits for completion, cancellation, failure, or `needs_attention`. It returns a draft immediately so you can review it. The defaults are one-second polling and a 20-minute deadline. Timeout or abort stops only local waiting; it never approves, cancels, or retries remote work.
170
+
171
+ Use `client.getCampaignPortfolio(id, stageKey, { cursor, limit, status, search })` to read stage results. The response includes coverage, typed items, and `next_cursor`; pass that cursor to read subsequent pages. Each result preserves caller-authored content and exposes `run_id` for its full report. MCP offers `get_campaign_portfolio` with the same filters.
@@ -0,0 +1,434 @@
1
+ export interface ClientOptions {
2
+ apiKey: string;
3
+ baseURL?: string;
4
+ timeoutMs?: number;
5
+ }
6
+ export interface AgentInputField {
7
+ label: string;
8
+ type?: "text" | "textarea" | "number" | "date" | "email" | "url" | "address" | "boolean" | "file" | "single_select" | "multi_select";
9
+ required?: boolean;
10
+ options?: string[];
11
+ }
12
+ export interface AgentDefinition {
13
+ run_mode?: "job" | "campaign";
14
+ campaign_plan?: Record<string, unknown> | null;
15
+ input_form?: AgentInputField[];
16
+ buildId?: string;
17
+ id?: string;
18
+ name?: string;
19
+ instructions?: string;
20
+ skills?: string[];
21
+ tools?: string[];
22
+ }
23
+ export interface AgentOptions extends ClientOptions, AgentDefinition {
24
+ }
25
+ export interface AgentRecord {
26
+ run_mode?: "job" | "campaign";
27
+ campaign_plan?: Record<string, unknown> | null;
28
+ input_form?: AgentInputField[];
29
+ id: string;
30
+ name: string;
31
+ status: string;
32
+ instructions?: string | null;
33
+ skills: string[];
34
+ tools?: string[];
35
+ [key: string]: unknown;
36
+ }
37
+ export interface AgentBuild {
38
+ id: string;
39
+ status: "queued" | "running" | "registering" | "succeeded" | "failed";
40
+ agent?: {
41
+ agent_id?: string | null;
42
+ status?: string | null;
43
+ } | null;
44
+ error?: string | null;
45
+ }
46
+ export interface WaitOptions {
47
+ signal?: AbortSignal;
48
+ timeoutMs?: number;
49
+ intervalMs?: number;
50
+ }
51
+ export declare class AgentBuildError extends Error {
52
+ readonly build: AgentBuild;
53
+ constructor(build: AgentBuild);
54
+ }
55
+ export interface Run {
56
+ id: string;
57
+ status: string;
58
+ report?: {
59
+ markdown: string;
60
+ revision_sha?: string | null;
61
+ widgets?: unknown[] | null;
62
+ } | null;
63
+ structured_output?: Record<string, unknown> | null;
64
+ error_kind?: string | null;
65
+ [key: string]: unknown;
66
+ }
67
+ export interface Campaign {
68
+ id: string;
69
+ name: string;
70
+ status: string;
71
+ revision: number;
72
+ objective: string;
73
+ review_digest: string;
74
+ agent_id?: string | null;
75
+ agent_name?: string | null;
76
+ stages: Record<string, unknown>[];
77
+ deliverables: Record<string, unknown>[];
78
+ artifacts?: {
79
+ deliverable_key: string;
80
+ filename: string;
81
+ media_type: string;
82
+ byte_size: number;
83
+ sha256: string;
84
+ }[];
85
+ }
86
+ export interface CampaignPortfolio {
87
+ id: string;
88
+ revision: number;
89
+ status: string;
90
+ stage_key: string;
91
+ output_schema?: Record<string, unknown> | null;
92
+ fields: Record<string, unknown>[];
93
+ entity_key_field?: string | null;
94
+ coverage: {
95
+ entity_count: number;
96
+ accepted: number;
97
+ pending: number;
98
+ failed: number;
99
+ excluded_count: number;
100
+ scope_complete: boolean;
101
+ };
102
+ items: {
103
+ entity_key: string;
104
+ stage_key: string;
105
+ status: "accepted" | "pending" | "failed" | "excluded";
106
+ content?: Record<string, unknown> | null;
107
+ run_id?: string | null;
108
+ batch_id?: string | null;
109
+ run_path?: string | null;
110
+ row_number?: number | null;
111
+ rejection_reason?: string | null;
112
+ result_id?: string | null;
113
+ retry_eligible?: boolean;
114
+ }[];
115
+ next_cursor: string | null;
116
+ }
117
+ export interface CampaignOptions {
118
+ signal?: AbortSignal;
119
+ idempotencyKey?: string;
120
+ }
121
+ export interface LoopCadence {
122
+ frequency: "daily" | "weekly" | "monthly";
123
+ schedule_config: {
124
+ hour: number;
125
+ minute: number;
126
+ day_of_week?: number | string;
127
+ day_of_month?: number;
128
+ };
129
+ timezone?: string;
130
+ }
131
+ export interface Loop extends LoopCadence {
132
+ id: string;
133
+ name: string;
134
+ is_active: boolean;
135
+ deleted_at?: string | null;
136
+ next_run_at?: string | null;
137
+ last_run_at?: string | null;
138
+ run_count: number;
139
+ consecutive_failures: number;
140
+ latest_batch_id?: string | null;
141
+ last_skip_reason?: string | null;
142
+ }
143
+ export interface LoopCreated {
144
+ id: string;
145
+ first_batch_id: string;
146
+ status: string;
147
+ }
148
+ export interface Batch {
149
+ loop_id?: string | null;
150
+ loop?: Loop | null;
151
+ id: string;
152
+ status: string;
153
+ total_rows: number;
154
+ processed_rows?: number;
155
+ paused_reason?: string | null;
156
+ rows?: BatchRow[];
157
+ credits_spent?: number;
158
+ [key: string]: unknown;
159
+ }
160
+ export interface BatchRow {
161
+ row_number: number;
162
+ status: string;
163
+ input?: string;
164
+ run_id?: string | null;
165
+ error_code?: string | null;
166
+ structured_output?: Record<string, unknown> | null;
167
+ [key: string]: unknown;
168
+ }
169
+ export interface BatchOptions {
170
+ name?: string;
171
+ signal?: AbortSignal;
172
+ idempotencyKey?: string;
173
+ effort?: "low" | "medium" | "high" | "build";
174
+ responseLanguage?: string;
175
+ maxConcurrent?: number;
176
+ maxCredits?: number;
177
+ outputSchema?: Record<string, unknown>;
178
+ }
179
+ /** Parse CSV cells without losing quoted commas, escaped quotes, or embedded newlines. */
180
+ export declare function parseBatchCSV(csv: string, inputColumn: string): {
181
+ inputs: string[];
182
+ rows: Record<string, string>[];
183
+ };
184
+ export interface Skill {
185
+ name: string;
186
+ category: string;
187
+ description?: string | null;
188
+ suggested_tools: string[];
189
+ tags: string[];
190
+ is_custom: boolean;
191
+ }
192
+ export interface SkillDefinition {
193
+ name: string;
194
+ description: string;
195
+ content: string;
196
+ }
197
+ export interface SkillRecord {
198
+ name: string;
199
+ skill_id: string;
200
+ created: boolean;
201
+ }
202
+ export interface SkillContent {
203
+ name: string;
204
+ content: string;
205
+ is_custom: boolean;
206
+ source: "catalog" | "custom";
207
+ }
208
+ /** Create or update a reusable skill in the caller's library. */
209
+ export declare const Skill: {
210
+ create(options: ClientOptions & SkillDefinition & {
211
+ signal?: AbortSignal;
212
+ }): Promise<SkillRecord>;
213
+ };
214
+ export interface Integration {
215
+ name: string;
216
+ short_name: string;
217
+ server: string;
218
+ category: string;
219
+ description?: string | null;
220
+ is_default: boolean;
221
+ always_on: boolean;
222
+ }
223
+ export interface CatalogFilter {
224
+ query?: string;
225
+ category?: string;
226
+ limit?: number;
227
+ }
228
+ export declare class AgentAPIError extends Error {
229
+ readonly status: number;
230
+ constructor(status: number, message: string);
231
+ }
232
+ /** Headless agentrun client. Credentials belong in server-side code. */
233
+ export declare class AgentRun {
234
+ private readonly baseURL;
235
+ protected readonly options: ClientOptions;
236
+ constructor(options: ClientOptions);
237
+ protected response(path: string, init?: RequestInit): Promise<Response>;
238
+ protected request<T>(path: string, init?: RequestInit): Promise<T>;
239
+ agent(definition: AgentDefinition): Agent;
240
+ private query;
241
+ listAgents(options?: {
242
+ signal?: AbortSignal;
243
+ }): Promise<{
244
+ agents: AgentRecord[];
245
+ count: number;
246
+ }>;
247
+ getBuild(id: string, options?: {
248
+ signal?: AbortSignal;
249
+ }): Promise<AgentBuild>;
250
+ getAgent(id: string): Promise<AgentRecord>;
251
+ updateAgent(id: string, definition: Omit<AgentDefinition, "id">): Promise<AgentRecord>;
252
+ deleteAgent(id: string): Promise<{
253
+ success: boolean;
254
+ agent_id: string;
255
+ status: string;
256
+ }>;
257
+ createSkill(definition: SkillDefinition, options?: {
258
+ signal?: AbortSignal;
259
+ }): Promise<SkillRecord>;
260
+ getSkill(name: string, options?: {
261
+ signal?: AbortSignal;
262
+ }): Promise<SkillContent>;
263
+ listSkills(filter?: CatalogFilter, options?: {
264
+ signal?: AbortSignal;
265
+ }): Promise<{
266
+ skills: Skill[];
267
+ categories: string[];
268
+ count: number;
269
+ total: number;
270
+ }>;
271
+ listIntegrations(filter?: CatalogFilter & {
272
+ server?: string;
273
+ }, options?: {
274
+ signal?: AbortSignal;
275
+ }): Promise<{
276
+ tools: Integration[];
277
+ servers: string[];
278
+ count: number;
279
+ total: number;
280
+ }>;
281
+ listRuns(filter?: {
282
+ cursor?: string;
283
+ limit?: number;
284
+ }, options?: {
285
+ signal?: AbortSignal;
286
+ }): Promise<{
287
+ items: Run[];
288
+ next_cursor: string | null;
289
+ }>;
290
+ createCampaign(plan: Record<string, unknown>, options?: CampaignOptions & {
291
+ records?: Record<string, unknown>[];
292
+ }): Promise<Campaign>;
293
+ listCampaigns(filter?: {
294
+ cursor?: string;
295
+ limit?: number;
296
+ }, options?: {
297
+ signal?: AbortSignal;
298
+ }): Promise<{
299
+ items: Campaign[];
300
+ next_cursor: string | null;
301
+ }>;
302
+ getCampaign(id: string, options?: {
303
+ signal?: AbortSignal;
304
+ }): Promise<Campaign>;
305
+ getCampaignPortfolio(id: string, stageKey: string, filter?: {
306
+ cursor?: string;
307
+ limit?: number;
308
+ entity_key?: string;
309
+ status?: "accepted" | "pending" | "failed" | "excluded";
310
+ search?: string;
311
+ filter_field?: string;
312
+ filter_value?: string;
313
+ }, options?: {
314
+ signal?: AbortSignal;
315
+ }): Promise<CampaignPortfolio>;
316
+ waitCampaign(id: string, options?: WaitOptions): Promise<Campaign>;
317
+ approveCampaign(id: string, reviewDigest: string, options?: {
318
+ signal?: AbortSignal;
319
+ }): Promise<Campaign>;
320
+ cancelCampaign(id: string, options?: {
321
+ signal?: AbortSignal;
322
+ }): Promise<Campaign>;
323
+ downloadCampaignArtifact(id: string, deliverableKey: string, options?: {
324
+ signal?: AbortSignal;
325
+ }): Promise<Blob>;
326
+ getLoop(id: string, options?: {
327
+ signal?: AbortSignal;
328
+ }): Promise<{
329
+ loop: Loop;
330
+ runs: Batch[];
331
+ }>;
332
+ updateLoop(id: string, changes: Partial<LoopCadence> & {
333
+ name?: string;
334
+ }, options?: {
335
+ signal?: AbortSignal;
336
+ }): Promise<Loop>;
337
+ pauseLoop(id: string, options?: {
338
+ signal?: AbortSignal;
339
+ }): Promise<Loop>;
340
+ resumeLoop(id: string, options?: {
341
+ signal?: AbortSignal;
342
+ }): Promise<Loop>;
343
+ runLoopNow(id: string, options?: {
344
+ signal?: AbortSignal;
345
+ }): Promise<{
346
+ batch_id: string;
347
+ run_number: number;
348
+ }>;
349
+ private loopAction;
350
+ deleteLoop(id: string, options?: {
351
+ cancelActive?: boolean;
352
+ signal?: AbortSignal;
353
+ }): Promise<Loop>;
354
+ listBatches(filter?: {
355
+ cursor?: string;
356
+ limit?: number;
357
+ status?: string;
358
+ }, options?: {
359
+ signal?: AbortSignal;
360
+ }): Promise<{
361
+ items: Batch[];
362
+ next_cursor: string | null;
363
+ }>;
364
+ getBatch(id: string, options?: {
365
+ signal?: AbortSignal;
366
+ includeRows?: boolean;
367
+ }): Promise<Batch>;
368
+ getBatchResults(id: string, options?: {
369
+ signal?: AbortSignal;
370
+ rowStatus?: "queued" | "running" | "completed" | "failed";
371
+ }): Promise<Batch & {
372
+ results: BatchRow[];
373
+ }>;
374
+ cancelBatch(id: string, options?: {
375
+ signal?: AbortSignal;
376
+ }): Promise<Batch>;
377
+ retryBatch(id: string, options?: {
378
+ signal?: AbortSignal;
379
+ rowNumber?: number;
380
+ }): Promise<Batch>;
381
+ waitBatch(id: string, options?: WaitOptions): Promise<Batch>;
382
+ getRun(jobId: string, options?: {
383
+ signal?: AbortSignal;
384
+ }): Promise<Run>;
385
+ cancelRun(runId: string, options?: {
386
+ signal?: AbortSignal;
387
+ }): Promise<Run>;
388
+ /** Poll to a terminal state. Failed/cancelled/blocked runs are returned for inspection. */
389
+ wait(runId: string, options?: {
390
+ signal?: AbortSignal;
391
+ timeoutMs?: number;
392
+ intervalMs?: number;
393
+ }): Promise<Run>;
394
+ }
395
+ /** Define an agent and call run(). Creation is lazy and shared across concurrent calls. */
396
+ export declare class Agent extends AgentRun {
397
+ private readonly definition;
398
+ private agentId?;
399
+ private creation?;
400
+ constructor(definition: AgentOptions);
401
+ /** Start a managed build from plain English. Save buildId to resume waiting later. */
402
+ static create(options: ClientOptions & {
403
+ prompt: string;
404
+ context?: string;
405
+ depth?: "standard" | "deep";
406
+ signal?: AbortSignal;
407
+ }): Promise<Agent>;
408
+ get buildId(): string | undefined;
409
+ /** Wait for generation and activation. A local timeout does not cancel the build. */
410
+ waitUntilReady(options?: WaitOptions): Promise<this>;
411
+ get id(): string | undefined;
412
+ /** Persist the definition without starting a run. */
413
+ create(): Promise<string>;
414
+ private ensureAgent;
415
+ /** Runs an existing agent's configured campaign template with its form inputs. */
416
+ campaign(inputs: Record<string, unknown>, options?: CampaignOptions): Promise<Campaign>;
417
+ batch(input: string[] | {
418
+ csv: string | Blob;
419
+ inputColumn: string;
420
+ }, options?: BatchOptions): Promise<Batch>;
421
+ loop(input: string | string[] | {
422
+ csv: string | Blob;
423
+ inputColumn: string;
424
+ }, cadence: LoopCadence, options?: BatchOptions): Promise<LoopCreated>;
425
+ private submitBatch;
426
+ run(question: string, options?: {
427
+ signal?: AbortSignal;
428
+ idempotencyKey?: string;
429
+ effort?: "low" | "medium" | "high" | "build";
430
+ maxCostUsd?: number;
431
+ responseLanguage?: string;
432
+ outputSchema?: Record<string, unknown>;
433
+ }): Promise<Run>;
434
+ }
package/dist/agent.js ADDED
@@ -0,0 +1,653 @@
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
+ }
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@parcha/agentrun",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Headless agentrun client: define an agent and call agent.run()",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/agent.d.ts",
9
+ "import": "./dist/agent.js"
10
+ }
11
+ },
12
+ "files": [
13
+ "dist",
14
+ "README.md"
15
+ ],
16
+ "engines": {
17
+ "node": ">=20.9.0"
18
+ },
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "homepage": "https://agentrun.ai"
23
+ }