@parcha/agentrun 0.1.0 → 0.2.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/CHANGELOG.md +22 -0
- package/README.md +137 -114
- package/dist/index.cjs +1169 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +661 -0
- package/dist/index.d.ts +661 -0
- package/dist/index.js +1137 -0
- package/dist/index.js.map +1 -0
- package/package.json +46 -6
- package/dist/agent.d.ts +0 -434
- package/dist/agent.js +0 -653
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.2.0 (unreleased)
|
|
4
|
+
|
|
5
|
+
Rewrite targeting the unified v2 API. Requires the unified v2 backend.
|
|
6
|
+
|
|
7
|
+
- Default base URL is `https://api.grep.ai/api/v2`. `AGENTRUN_API_KEY` and `AGENTRUN_BASE_URL` are read from the environment in Node.
|
|
8
|
+
- Package restructured into `errors`, `models`, `ops`, `http`, `client`, `agent`, and `batch`, mirroring the Python SDK.
|
|
9
|
+
- Requests are serialised to the v2 vocabulary (`question`, `expert_id`, `domain`, `json_schema`, `batch_name`, `questions`, `inputs`). Every record exposes `id` whatever the API calls it.
|
|
10
|
+
- Run, batch, and row statuses are mapped to a short SDK vocabulary; the original is in `raw_status`.
|
|
11
|
+
- One error class per HTTP status family. Errors read the API's `{"error": {...}}` envelope and carry `statusCode`, `body`, and `requestId`. Non-JSON bodies raise `InvalidResponseError`; local deadlines raise `PollTimeoutError`.
|
|
12
|
+
- Every method returns a promise, so validation failures reject instead of throwing.
|
|
13
|
+
- Request limits from the API contract (skill lengths, `maxCostUsd`, batch name, build context) are checked locally.
|
|
14
|
+
- `formInputs` on batches and loops, `records` on campaigns, `includeRows` on `getBatch`, `getUsage`, `iterRuns`, `Agent.save`, `Skill.read`.
|
|
15
|
+
- `outputSchema` accepts a JSON schema or any object with `toJSONSchema()`.
|
|
16
|
+
- `downloadCampaignArtifact` returns an `Artifact`, a `Blob` with the server's `filename`.
|
|
17
|
+
- Dual ESM and CommonJS build with type declarations. No runtime dependencies.
|
|
18
|
+
- `tests/fixtures/public-v2.json` carries the backend's OpenAPI contract; every request is validated against it in tests.
|
|
19
|
+
|
|
20
|
+
## 0.1.0
|
|
21
|
+
|
|
22
|
+
Initial release against the pre-release website proxy.
|
package/README.md
CHANGED
|
@@ -1,171 +1,194 @@
|
|
|
1
|
-
#
|
|
1
|
+
# AgentRun TypeScript SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Create agents, run them on your inputs, and collect the results. Typed, promise-based, no runtime dependencies. Node 20.9 or newer, or any runtime with `fetch`.
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
6
|
npm install @parcha/agentrun
|
|
7
7
|
```
|
|
8
8
|
|
|
9
|
+
## Quick start
|
|
10
|
+
|
|
11
|
+
Set `AGENTRUN_API_KEY` in your environment, then:
|
|
12
|
+
|
|
9
13
|
```ts
|
|
10
|
-
import { Agent } from
|
|
14
|
+
import { Agent } from "@parcha/agentrun";
|
|
15
|
+
|
|
11
16
|
const agent = new Agent({
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
instructions: 'Verify the company and cite evidence.',
|
|
15
|
-
// Set baseURL to your agentrun deployment while running locally.
|
|
17
|
+
name: "Company verifier",
|
|
18
|
+
instructions: "Verify the company and cite primary sources.",
|
|
16
19
|
});
|
|
17
|
-
const run = await agent.run(
|
|
20
|
+
const run = await agent.run("Verify acme.example");
|
|
18
21
|
const result = await agent.wait(run.id);
|
|
19
|
-
console.log(result.status, result.report);
|
|
20
|
-
```
|
|
21
22
|
|
|
22
|
-
|
|
23
|
+
console.log(result.status); // "completed", "failed", "cancelled", or "blocked"
|
|
24
|
+
console.log(result.report?.markdown); // the report, or undefined
|
|
25
|
+
```
|
|
23
26
|
|
|
24
|
-
|
|
27
|
+
`Agent` saves itself on the first call that needs it. Save `agent.id` and pass `new Agent({ id })` next time to reuse it. Two things to know about `wait`. It returns for every terminal status, so check `result.status` before using the report. It gives up after 10 minutes by default and throws `PollTimeoutError`, but the run keeps going on the server. Call `agent.getRun(run.id)` later to fetch it.
|
|
25
28
|
|
|
26
|
-
|
|
29
|
+
Outside Node, or to avoid environment variables, pass `apiKey` to the constructor.
|
|
27
30
|
|
|
28
|
-
##
|
|
31
|
+
## Build an agent from a description
|
|
29
32
|
|
|
30
33
|
```ts
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
const
|
|
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
|
-
});
|
|
34
|
+
const agent = await Agent.create("Research companies and cite sources.");
|
|
35
|
+
// Save agent.buildId if this process might stop.
|
|
36
|
+
await agent.waitUntilReady(); // builds can take a few minutes
|
|
37
|
+
const run = await agent.run("Research acme.example");
|
|
41
38
|
```
|
|
42
39
|
|
|
43
|
-
|
|
40
|
+
Resume an unfinished build with `new Agent({ buildId })`. Any run method waits for the build first. A build that fails throws `BuildError`; read `error.build.error` for the reason.
|
|
44
41
|
|
|
45
|
-
##
|
|
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
|
-
```
|
|
42
|
+
## Structured output
|
|
57
43
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
## Reusable skills
|
|
44
|
+
Pass a JSON schema, or any object with a `toJSONSchema()` method, as `outputSchema`. The result's `structured_output` is the parsed object.
|
|
61
45
|
|
|
62
46
|
```ts
|
|
63
|
-
|
|
64
|
-
|
|
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.',
|
|
47
|
+
const run = await agent.run("Verify acme.example", {
|
|
48
|
+
outputSchema: { type: "object", properties: { verified: { type: "boolean" } } },
|
|
69
49
|
});
|
|
50
|
+
const { structured_output } = await agent.wait(run.id);
|
|
70
51
|
```
|
|
71
52
|
|
|
72
|
-
|
|
53
|
+
## Batches
|
|
73
54
|
|
|
74
|
-
|
|
55
|
+
Run up to 100 inputs at once. The SDK checks the limits before sending anything.
|
|
75
56
|
|
|
76
57
|
```ts
|
|
77
|
-
const batch = await agent.batch([
|
|
78
|
-
name:
|
|
58
|
+
const batch = await agent.batch(["Verify acme.example", "Verify beta.example"], {
|
|
59
|
+
name: "Q3 checks",
|
|
60
|
+
maxConcurrent: 5,
|
|
61
|
+
idempotencyKey: "q3-checks-001",
|
|
79
62
|
});
|
|
80
|
-
const
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
63
|
+
const done = await agent.waitBatch(batch.id);
|
|
64
|
+
for (const row of (await agent.getBatchResults(batch.id)).results) {
|
|
65
|
+
console.log(row.row_number, row.status, row.run_id);
|
|
66
|
+
}
|
|
84
67
|
```
|
|
85
68
|
|
|
86
|
-
|
|
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:
|
|
69
|
+
A CSV works too. Name the column that holds each input. The other columns come back as `row.row_data`.
|
|
95
70
|
|
|
96
71
|
```ts
|
|
97
|
-
const
|
|
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);
|
|
72
|
+
const batch = await agent.batch({ csv: csvText, inputColumn: "website" });
|
|
103
73
|
```
|
|
104
74
|
|
|
105
|
-
`
|
|
75
|
+
`csv` may be a string or a `Blob`, up to 1 MB. `waitBatch` returns when the batch completes, fails, is cancelled, or pauses for attention; check `batch.paused_reason`. `cancelBatch` stops new rows; rows already running finish. `retryBatch` re-runs failed rows and spends credits. `getBatch(id, { includeRows: false })` skips per-row data on large batches.
|
|
106
76
|
|
|
107
|
-
|
|
77
|
+
## Loops
|
|
108
78
|
|
|
109
|
-
|
|
79
|
+
A loop is a batch that repeats on a schedule. The first run starts immediately.
|
|
110
80
|
|
|
111
81
|
```ts
|
|
112
|
-
const loop = await agent.loop(
|
|
113
|
-
|
|
114
|
-
schedule_config: { hour: 9, minute: 0, day_of_week:
|
|
115
|
-
|
|
116
|
-
|
|
82
|
+
const loop = await agent.loop(
|
|
83
|
+
"Check acme.example for new filings",
|
|
84
|
+
{ frequency: "weekly", schedule_config: { hour: 9, minute: 0, day_of_week: 0 }, timezone: "America/New_York" },
|
|
85
|
+
{ name: "Weekly filings", maxCredits: 20 },
|
|
86
|
+
);
|
|
117
87
|
const history = await agent.getLoop(loop.id);
|
|
118
|
-
const results = await agent.getBatchResults(history.runs[0].id);
|
|
119
88
|
await agent.pauseLoop(loop.id);
|
|
120
|
-
await agent.resumeLoop(loop.id);
|
|
121
89
|
await agent.deleteLoop(loop.id, { cancelActive: true });
|
|
122
90
|
```
|
|
123
91
|
|
|
124
|
-
|
|
92
|
+
`frequency` is `daily`, `weekly`, or `monthly`. Weekly uses `day_of_week` with 0 as Monday. Monthly uses `day_of_month` from 1 to 28. `maxCredits` caps each occurrence, not the lifetime total. Inputs are frozen at creation; `updateLoop` changes only the name and cadence.
|
|
93
|
+
|
|
94
|
+
## Campaigns
|
|
125
95
|
|
|
126
|
-
|
|
96
|
+
A campaign is a multi-stage plan. Save it as a draft, review it, then approve it with the digest of the plan you reviewed.
|
|
127
97
|
|
|
128
|
-
|
|
98
|
+
```ts
|
|
99
|
+
const draft = await agent.createCampaign(plan);
|
|
100
|
+
// read draft.stages and draft.deliverables
|
|
101
|
+
const started = await agent.approveCampaign(draft.id, draft.review_digest!);
|
|
102
|
+
const final = await agent.waitCampaign(started.id);
|
|
103
|
+
const artifact = await agent.downloadCampaignArtifact(final.id, "companies");
|
|
104
|
+
await writeFile(artifact.filename ?? "companies.xlsx", await artifact.bytes());
|
|
105
|
+
```
|
|
129
106
|
|
|
130
|
-
|
|
107
|
+
`downloadCampaignArtifact` returns a `Blob` with an extra `filename`, so `arrayBuffer()`, `bytes()`, `text()`, and `type` all work. An agent configured with `run_mode: "campaign"` and a `campaign_plan` can start its template directly with `agent.campaign({ goal: "..." })`. That call starts work immediately. Approving with a stale digest throws `ConflictError`.
|
|
131
108
|
|
|
132
|
-
|
|
109
|
+
## Skills and integrations
|
|
133
110
|
|
|
134
111
|
```ts
|
|
112
|
+
import { AgentRun } from "@parcha/agentrun";
|
|
113
|
+
|
|
114
|
+
const client = new AgentRun();
|
|
115
|
+
const skills = await client.listSkills({ query: "company" });
|
|
116
|
+
const tools = await client.listIntegrations({ query: "company" });
|
|
117
|
+
|
|
135
118
|
const agent = new Agent({
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
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',
|
|
119
|
+
name: "Company verifier",
|
|
120
|
+
instructions: "Verify the company and cite evidence.",
|
|
121
|
+
skills: skills.skills.map((s) => s.name),
|
|
122
|
+
tools: tools.tools.filter((t) => !t.always_on).map((t) => t.name),
|
|
162
123
|
});
|
|
163
124
|
```
|
|
164
125
|
|
|
165
|
-
|
|
126
|
+
Save your own Markdown as a skill with `client.createSkill({ name, description, content })`. Creating a skill with an existing name updates it; the response has `created: false`.
|
|
127
|
+
|
|
128
|
+
## Statuses
|
|
129
|
+
|
|
130
|
+
The API reports progress in its own vocabulary. The SDK maps it to a short list so your code stays simple. The original value is always in `raw_status`.
|
|
131
|
+
|
|
132
|
+
| `run.status` | Means | Done |
|
|
133
|
+
| --- | --- | --- |
|
|
134
|
+
| `queued` | Accepted, not started. | no |
|
|
135
|
+
| `moderation` | Content check in progress. | no |
|
|
136
|
+
| `running` | Working. | no |
|
|
137
|
+
| `blocked` | Needs your input, or content was rejected. | yes |
|
|
138
|
+
| `completed` | Report is ready. | yes |
|
|
139
|
+
| `failed` | Ran and failed, or never ran. | yes |
|
|
140
|
+
| `cancelled` | Cancelled, deleted, or superseded. | yes |
|
|
141
|
+
|
|
142
|
+
Batches use `queued`, `running`, `completed`, `completed_with_errors`, `failed`, and `cancelled`. Batch rows use `queued`, `running`, `completed`, and `failed`. A status the SDK does not recognise passes through unchanged.
|
|
143
|
+
|
|
144
|
+
## Errors
|
|
145
|
+
|
|
146
|
+
Every method returns a promise, and every failure is a rejection with an error that extends `AgentRunError`.
|
|
147
|
+
|
|
148
|
+
| Error | When |
|
|
149
|
+
| --- | --- |
|
|
150
|
+
| `AuthenticationError` | 401. Bad or missing API key. |
|
|
151
|
+
| `PermissionDeniedError` | 403. The key lacks a scope or does not own the resource. |
|
|
152
|
+
| `NotFoundError` | 404. |
|
|
153
|
+
| `ConflictError` | 409. Stale review digest, or a loop already running. |
|
|
154
|
+
| `UnprocessableEntityError` | 422. `error.body.detail` lists the bad fields. |
|
|
155
|
+
| `RateLimitError` | 429. |
|
|
156
|
+
| `ServiceUnavailableError` | 503. Down, or the feature is not enabled for your account. |
|
|
157
|
+
| `APIConnectionError` | No HTTP response at all. `APITimeoutError` for a slow one. |
|
|
158
|
+
| `InvalidResponseError` | 2xx but not the JSON the SDK expects. Usually a wrong `baseURL`. |
|
|
159
|
+
| `BuildError` | An agent build failed. |
|
|
160
|
+
| `PollTimeoutError` | A `wait*` call hit its local deadline. |
|
|
166
161
|
|
|
167
|
-
|
|
162
|
+
`APIError` subclasses carry `statusCode`, `body`, and `requestId`. Include the request ID when you report a problem. The SDK checks the limits the API enforces before sending anything, such as skill content of at least 50 characters or `maxCostUsd` between 0.5 and 1000, and rejects with a plain `Error`. The SDK never retries a request on its own. Pass the same `idempotencyKey` to `run`, `batch`, `loop`, or `createCampaign` when you retry, so the server does not start the work twice.
|
|
163
|
+
|
|
164
|
+
Every method accepts `{ signal }` to cancel a request or a wait from your side. Aborting stops local waiting only; it never cancels remote work. Use `cancelRun`, `cancelBatch`, or `cancelCampaign` for that.
|
|
165
|
+
|
|
166
|
+
## Configuration
|
|
167
|
+
|
|
168
|
+
| Setting | Option | Environment variable | Default |
|
|
169
|
+
| --- | --- | --- | --- |
|
|
170
|
+
| API key | `apiKey` | `AGENTRUN_API_KEY` | required |
|
|
171
|
+
| API root | `baseURL` | `AGENTRUN_BASE_URL` | `https://api.grep.ai/api/v2` |
|
|
172
|
+
| Per-request timeout | `timeoutMs` | | 30000 |
|
|
173
|
+
| Fetch implementation | `fetch` | | `globalThis.fetch` |
|
|
174
|
+
|
|
175
|
+
`baseURL` must use HTTPS. Plain HTTP is allowed only for localhost. Redirects are never followed. Environment variables are read only where `process.env` exists.
|
|
176
|
+
|
|
177
|
+
## Types
|
|
178
|
+
|
|
179
|
+
The package ships ESM and CommonJS builds with declarations. Responses are plain objects typed as interfaces, so `run.status` and `batch.rows` have the types your editor shows. Records keep any field the server adds later, reachable as a property. `id` is always the record's ID, whatever the API calls it.
|
|
180
|
+
|
|
181
|
+
## Development
|
|
182
|
+
|
|
183
|
+
```sh
|
|
184
|
+
npm ci
|
|
185
|
+
npm run typecheck
|
|
186
|
+
npm run build
|
|
187
|
+
npm test
|
|
188
|
+
npm pack --dry-run
|
|
189
|
+
```
|
|
168
190
|
|
|
169
|
-
|
|
191
|
+
Tests run against a fake API behind a `fetch` function. Two tests tie the SDK to the backend:
|
|
170
192
|
|
|
171
|
-
|
|
193
|
+
- `tests/contract.test.ts` validates every request the SDK sends, and every canned response, against `tests/fixtures/public-v2.json`, the backend's generated OpenAPI document. Refresh it with `python scripts/update_contract.py <path-or-url>` when the API changes.
|
|
194
|
+
- `tests/packaged.test.ts` starts a real local HTTP server and runs the same script the backend uses to verify packaged SDKs, against the built `dist/`.
|