agent-contracts-runtime 0.6.0 → 0.7.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 +442 -250
- package/dist/adapters/claude-agent-sdk.d.ts +62 -6
- package/dist/adapters/claude-agent-sdk.js +125 -47
- package/dist/adapters/claude-agent-sdk.js.map +1 -1
- package/dist/adapters/cursor-sdk.d.ts +1 -1
- package/dist/adapters/mock.d.ts +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/{task-runner-JLQ-vpHl.d.ts → task-runner-Bt2XiEUU.d.ts} +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,22 +1,150 @@
|
|
|
1
1
|
# agent-contracts-runtime
|
|
2
2
|
|
|
3
|
-
Runtime bridge for executing [`agent-contracts`](https://github.com/foo-ogawa/agent-contracts)
|
|
3
|
+
Runtime bridge for executing [`agent-contracts`](https://github.com/foo-ogawa/agent-contracts) agent teams from TypeScript programs.
|
|
4
4
|
|
|
5
|
-
`agent-contracts` defines
|
|
6
|
-
`agent-contracts-runtime` turns those contracts into an executable SDK runtime.
|
|
5
|
+
`agent-contracts` defines business-level agent behavior in DSL: agent roles, task boundaries, workflows, handoff schemas, validations, and guardrails.
|
|
7
6
|
|
|
8
|
-
|
|
7
|
+
`agent-contracts-runtime` makes those DSL-defined workflows callable from ordinary TypeScript code.
|
|
8
|
+
|
|
9
|
+
It sits between your program and Agent SDKs:
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
TypeScript program
|
|
13
|
+
↓
|
|
14
|
+
WorkflowInvocation
|
|
15
|
+
↓
|
|
16
|
+
agent-contracts-runtime
|
|
17
|
+
↓
|
|
18
|
+
DSL-derived contracts
|
|
19
|
+
↓
|
|
20
|
+
Agent SDK adapter
|
|
21
|
+
↓
|
|
22
|
+
Cursor / Claude / OpenAI Agents SDK / custom runner
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Agent SDKs execute LLM agents.
|
|
26
|
+
|
|
27
|
+
`agent-contracts-runtime` lets application code invoke reusable, DSL-defined agent workflows without hand-writing SDK-specific orchestration for each workflow.
|
|
28
|
+
|
|
29
|
+
## Why this exists
|
|
30
|
+
|
|
31
|
+
Agent SDKs are good at executing agents.
|
|
32
|
+
|
|
33
|
+
But business-level agent behavior often involves more than one prompt or one SDK call.
|
|
34
|
+
|
|
35
|
+
A real agent team may define:
|
|
36
|
+
|
|
37
|
+
- which agents exist
|
|
38
|
+
- which tasks they can perform
|
|
39
|
+
- who can delegate to whom
|
|
40
|
+
- what handoff shape is expected
|
|
41
|
+
- which workflow steps are allowed
|
|
42
|
+
- what validation must happen before the next step
|
|
43
|
+
- which guardrails apply
|
|
44
|
+
|
|
45
|
+
That behavior belongs in `agent-contracts` DSL.
|
|
46
|
+
|
|
47
|
+
`agent-contracts-runtime` exists so TypeScript programs can execute those DSL-defined workflows without rewriting the same SDK-specific orchestration code each time.
|
|
9
48
|
|
|
10
49
|
## What it does
|
|
11
50
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
-
|
|
51
|
+
`agent-contracts-runtime`:
|
|
52
|
+
|
|
53
|
+
- loads generated contracts from `agent-contracts`
|
|
54
|
+
- accepts workflow invocations from TypeScript or CLI
|
|
55
|
+
- resolves the DSL-defined workflow, task, agent, and handoff contracts
|
|
56
|
+
- builds an SDK execution request
|
|
57
|
+
- calls an Agent SDK through an adapter
|
|
58
|
+
- validates the returned handoff
|
|
59
|
+
- returns a structured workflow result
|
|
60
|
+
|
|
61
|
+
It is the execution bridge for DSL-defined agent teams.
|
|
62
|
+
|
|
63
|
+
## Why not call the SDK directly?
|
|
64
|
+
|
|
65
|
+
You can.
|
|
66
|
+
|
|
67
|
+
For simple one-off agents, direct SDK code is enough.
|
|
68
|
+
|
|
69
|
+
`agent-contracts-runtime` is useful when the agent behavior is defined as reusable contracts:
|
|
70
|
+
|
|
71
|
+
- multiple workflows use the same agent team
|
|
72
|
+
- handoff schemas should be generated and validated
|
|
73
|
+
- workflow steps should come from DSL, not scattered program code
|
|
74
|
+
- different SDK adapters should run the same contract
|
|
75
|
+
- application code should call business-level workflows, not low-level agent prompts
|
|
76
|
+
|
|
77
|
+
Instead of writing this repeatedly:
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
// resolve prompt
|
|
81
|
+
// choose agent
|
|
82
|
+
// build context
|
|
83
|
+
// call SDK
|
|
84
|
+
// parse output
|
|
85
|
+
// validate schema
|
|
86
|
+
// retry on malformed output
|
|
87
|
+
// route to next task
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
you call:
|
|
91
|
+
|
|
92
|
+
```typescript
|
|
93
|
+
const result = await runtime
|
|
94
|
+
.workflow("feature-implement")
|
|
95
|
+
.handoff(handoffs.featureImplementationRequest({
|
|
96
|
+
objective: "Add login endpoint with JWT",
|
|
97
|
+
inputs: { repository: "." },
|
|
98
|
+
expectedOutputs: ["implementation-diff"],
|
|
99
|
+
completionCriteria: ["tests_passed"],
|
|
100
|
+
}))
|
|
101
|
+
.run();
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Business behavior lives in the DSL
|
|
18
105
|
|
|
19
|
-
|
|
106
|
+
Prompts and SDK calls are execution details.
|
|
107
|
+
|
|
108
|
+
The reusable behavior of an agent team belongs in the DSL:
|
|
109
|
+
|
|
110
|
+
- agent roles and responsibilities
|
|
111
|
+
- task boundaries
|
|
112
|
+
- delegation rules
|
|
113
|
+
- workflow steps
|
|
114
|
+
- handoff schemas
|
|
115
|
+
- validations
|
|
116
|
+
- guardrails
|
|
117
|
+
|
|
118
|
+
`agent-contracts-runtime` executes those generated contracts instead of duplicating the workflow logic in application code.
|
|
119
|
+
|
|
120
|
+
## Install
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
npm install agent-contracts-runtime
|
|
124
|
+
npm install -D agent-contracts
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Quick start
|
|
128
|
+
|
|
129
|
+
```bash
|
|
130
|
+
# 1. Initialize project scaffolding
|
|
131
|
+
agent-runtime init
|
|
132
|
+
|
|
133
|
+
# 2. Validate and lint your DSL
|
|
134
|
+
agent-contracts validate
|
|
135
|
+
agent-contracts lint --strict
|
|
136
|
+
|
|
137
|
+
# 3. Generate contracts and hooks
|
|
138
|
+
agent-runtime generate
|
|
139
|
+
|
|
140
|
+
# 4. Run a workflow
|
|
141
|
+
agent-runtime run feature-implement "Add login endpoint with JWT"
|
|
142
|
+
|
|
143
|
+
# 5. Verify project setup
|
|
144
|
+
agent-runtime doctor
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## How it works
|
|
20
148
|
|
|
21
149
|
```
|
|
22
150
|
agent-contracts.yaml (DSL) bindings/runtime.yaml (guardrail impl)
|
|
@@ -54,22 +182,6 @@ agent-contracts.yaml (DSL) bindings/runtime.yaml (guardrail impl)
|
|
|
54
182
|
└── Plugin: afterWorkflow
|
|
55
183
|
```
|
|
56
184
|
|
|
57
|
-
### Invocation flow
|
|
58
|
-
|
|
59
|
-
```
|
|
60
|
-
Program / CLI / CI
|
|
61
|
-
↓
|
|
62
|
-
WorkflowInvocation (SDK-independent envelope)
|
|
63
|
-
↓
|
|
64
|
-
agent-contracts-runtime
|
|
65
|
-
↓
|
|
66
|
-
AgentExecutionRequest (resolved contract + context)
|
|
67
|
-
↓
|
|
68
|
-
SdkAdapter (Cursor / Claude / OpenAI)
|
|
69
|
-
↓
|
|
70
|
-
SDK-specific request
|
|
71
|
-
```
|
|
72
|
-
|
|
73
185
|
### Layer separation
|
|
74
186
|
|
|
75
187
|
| Layer | Path | Owner | Description |
|
|
@@ -78,92 +190,7 @@ SDK-specific request
|
|
|
78
190
|
| **User code** | `agent/src/` | You | Plugins, project guardrails, interceptors. |
|
|
79
191
|
| **Runtime** | `node_modules/agent-contracts-runtime/` | npm package | Workflow runner, task runner, SDK adapters, generator. |
|
|
80
192
|
|
|
81
|
-
##
|
|
82
|
-
|
|
83
|
-
```bash
|
|
84
|
-
npm install agent-contracts-runtime
|
|
85
|
-
npm install -D agent-contracts
|
|
86
|
-
```
|
|
87
|
-
|
|
88
|
-
## Quick start
|
|
89
|
-
|
|
90
|
-
```bash
|
|
91
|
-
# 1. Initialize project scaffolding
|
|
92
|
-
agent-runtime init
|
|
93
|
-
|
|
94
|
-
# 2. Validate and lint your DSL
|
|
95
|
-
agent-contracts validate
|
|
96
|
-
agent-contracts lint --strict
|
|
97
|
-
|
|
98
|
-
# 3. Generate contracts and hooks
|
|
99
|
-
agent-runtime generate
|
|
100
|
-
|
|
101
|
-
# 4. Run a workflow
|
|
102
|
-
agent-runtime run feature-implement "Add login endpoint with JWT"
|
|
103
|
-
|
|
104
|
-
# 5. Verify project setup
|
|
105
|
-
agent-runtime doctor
|
|
106
|
-
```
|
|
107
|
-
|
|
108
|
-
## CLI
|
|
109
|
-
|
|
110
|
-
| Command | Description |
|
|
111
|
-
|---------|-------------|
|
|
112
|
-
| `agent-runtime init` | Initialize runtime scaffolding |
|
|
113
|
-
| `agent-runtime generate` | Generate contracts and hooks from DSL |
|
|
114
|
-
| `agent-runtime run <workflow> <request>` | Execute a workflow |
|
|
115
|
-
| `agent-runtime run --file <path>` | Execute from a YAML invocation file |
|
|
116
|
-
| `agent-runtime list <resource>` | List workflows, tasks, or agents |
|
|
117
|
-
| `agent-runtime show-prompt <task>` | Display the generated prompt for a task |
|
|
118
|
-
| `agent-runtime doctor` | Verify configuration and connectivity |
|
|
119
|
-
| `agent-runtime replay <run-dir>` | Replay a past execution |
|
|
120
|
-
|
|
121
|
-
Key options:
|
|
122
|
-
|
|
123
|
-
```bash
|
|
124
|
-
agent-runtime generate --check # CI: verify generated files are up to date
|
|
125
|
-
agent-runtime generate --clean # Delete and regenerate
|
|
126
|
-
agent-runtime generate -t ./my-tpl # Use custom Handlebars templates
|
|
127
|
-
agent-runtime run ... --dry-run # Simulate without calling SDK
|
|
128
|
-
agent-runtime run ... --adapter mock # Use mock adapter for testing
|
|
129
|
-
agent-runtime run --file ./invocation.yaml # Run from YAML manifest
|
|
130
|
-
agent-runtime show-prompt plan-and-implement # Preview prompt
|
|
131
|
-
agent-runtime show-prompt audit-tests -u "Check test quality" # With custom request
|
|
132
|
-
agent-runtime show-prompt plan-and-implement --format json # JSON output
|
|
133
|
-
agent-runtime show-prompt plan-and-implement --with-plugins # Apply plugin enhancers
|
|
134
|
-
```
|
|
135
|
-
|
|
136
|
-
### YAML invocation file
|
|
137
|
-
|
|
138
|
-
For CI or programmatic invocation, define the full request as a YAML file:
|
|
139
|
-
|
|
140
|
-
```yaml
|
|
141
|
-
# invocation.yaml
|
|
142
|
-
workflow: feature-implement
|
|
143
|
-
handoff:
|
|
144
|
-
type: feature-implementation-request
|
|
145
|
-
payload:
|
|
146
|
-
objective: Add login endpoint with JWT
|
|
147
|
-
inputs:
|
|
148
|
-
repository: .
|
|
149
|
-
expected_outputs:
|
|
150
|
-
- implementation-diff
|
|
151
|
-
completion_criteria:
|
|
152
|
-
- tests_passed
|
|
153
|
-
runtime:
|
|
154
|
-
max_follow_ups: 3
|
|
155
|
-
max_retries: 1
|
|
156
|
-
```
|
|
157
|
-
|
|
158
|
-
```bash
|
|
159
|
-
agent-runtime run --file ./invocation.yaml --adapter cursor
|
|
160
|
-
```
|
|
161
|
-
|
|
162
|
-
For full CLI reference with exit codes and output schemas, see [docs/cli-reference.md](docs/cli-reference.md).
|
|
163
|
-
|
|
164
|
-
The CLI specification is managed contract-first via [`cli-contracts`](https://www.npmjs.com/package/cli-contracts) in [`cli-contract.yaml`](cli-contract.yaml).
|
|
165
|
-
|
|
166
|
-
## Code generation
|
|
193
|
+
## Generated contracts
|
|
167
194
|
|
|
168
195
|
The `generate` command reads your `agent-contracts.yaml` DSL and optional binding YAML files, then produces TypeScript contracts and guardrail hooks using Handlebars templates.
|
|
169
196
|
|
|
@@ -176,7 +203,7 @@ The `generate` command reads your `agent-contracts.yaml` DSL and optional bindin
|
|
|
176
203
|
|
|
177
204
|
Phase 2 requires a binding YAML (following the `agent-contracts` `SoftwareBinding` schema). If no bindings are configured, guardrail hooks are skipped.
|
|
178
205
|
|
|
179
|
-
###
|
|
206
|
+
### Handoff factories
|
|
180
207
|
|
|
181
208
|
In addition to Zod schemas and type aliases, `handoffs.ts` generates type-safe factory functions for each handoff type:
|
|
182
209
|
|
|
@@ -186,14 +213,16 @@ import { handoffs } from "./agent/generated";
|
|
|
186
213
|
const envelope = handoffs.featureImplementationRequest({
|
|
187
214
|
objective: "Add login endpoint with JWT",
|
|
188
215
|
inputs: { repository: "." },
|
|
189
|
-
|
|
190
|
-
|
|
216
|
+
expectedOutputs: ["implementation-diff"],
|
|
217
|
+
completionCriteria: ["tests_passed"],
|
|
191
218
|
});
|
|
192
219
|
// => { type: "feature-implementation-request", version: 1, payload: { ... } }
|
|
193
220
|
```
|
|
194
221
|
|
|
195
222
|
The factory validates the payload against the Zod schema at construction time, catching type errors before the workflow starts.
|
|
196
223
|
|
|
224
|
+
YAML invocation files use the DSL-defined field names (snake_case). Generated TypeScript factories and APIs use camelCase.
|
|
225
|
+
|
|
197
226
|
### Custom templates
|
|
198
227
|
|
|
199
228
|
Override any built-in Handlebars template by placing a file with the same name in a custom templates directory:
|
|
@@ -204,31 +233,7 @@ agent-runtime generate --templates ./my-templates
|
|
|
204
233
|
|
|
205
234
|
Or set `templates_dir` in `agent-runtime.config.yaml`.
|
|
206
235
|
|
|
207
|
-
###
|
|
208
|
-
|
|
209
|
-
Binding files define how DSL guardrails are implemented with concrete matchers:
|
|
210
|
-
|
|
211
|
-
```yaml
|
|
212
|
-
# bindings/runtime.yaml
|
|
213
|
-
software: agent-runtime
|
|
214
|
-
version: 1
|
|
215
|
-
|
|
216
|
-
guardrail_impl:
|
|
217
|
-
no-force-push:
|
|
218
|
-
checks:
|
|
219
|
-
- matcher:
|
|
220
|
-
type: command_regex
|
|
221
|
-
pattern: "(^|[|;&]\\s*)git\\s+push\\s.*(--force|-f)\\b"
|
|
222
|
-
message: "Force push is forbidden."
|
|
223
|
-
block-env-files:
|
|
224
|
-
checks:
|
|
225
|
-
- matcher:
|
|
226
|
-
type: file_glob
|
|
227
|
-
pattern: "**/{.env,.env.*}"
|
|
228
|
-
message: "Writing to .env file is blocked."
|
|
229
|
-
```
|
|
230
|
-
|
|
231
|
-
### Programmatic API
|
|
236
|
+
### Programmatic generation API
|
|
232
237
|
|
|
233
238
|
```typescript
|
|
234
239
|
import { generate, checkFreshness } from "agent-contracts-runtime/generator";
|
|
@@ -244,15 +249,54 @@ const isFresh = await checkFreshness("./agent-runtime.config.yaml");
|
|
|
244
249
|
|
|
245
250
|
## Programmatic API
|
|
246
251
|
|
|
247
|
-
The runtime provides three API levels
|
|
252
|
+
The runtime provides three API levels:
|
|
248
253
|
|
|
249
254
|
| API | Use case | Input |
|
|
250
255
|
|-----|----------|-------|
|
|
251
|
-
| **Simple API** | CLI
|
|
256
|
+
| **Simple API** | Ad-hoc CLI-style invocation | `user_request: string` |
|
|
252
257
|
| **Structured API** | Application integration, CI | `WorkflowInvocation` with typed handoff |
|
|
253
258
|
| **Builder API** | Fluent programmatic usage | `createRuntime` → chained methods |
|
|
254
259
|
|
|
255
|
-
###
|
|
260
|
+
### WorkflowInvocation
|
|
261
|
+
|
|
262
|
+
All API levels resolve to the same internal model:
|
|
263
|
+
|
|
264
|
+
```typescript
|
|
265
|
+
type WorkflowInvocation = {
|
|
266
|
+
workflow: string;
|
|
267
|
+
|
|
268
|
+
handoff: {
|
|
269
|
+
type: string;
|
|
270
|
+
version?: number;
|
|
271
|
+
payload: unknown;
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
runtime?: {
|
|
275
|
+
maxFollowUps?: number;
|
|
276
|
+
maxRetries?: number;
|
|
277
|
+
dryRun?: boolean;
|
|
278
|
+
readonly?: boolean;
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
hooks?: {
|
|
282
|
+
onStepComplete?: (event: StepCompleteEvent) => void;
|
|
283
|
+
onGate?: (gateKind: string, description: string) => Promise<boolean>;
|
|
284
|
+
decideRetryStrategy?: (
|
|
285
|
+
outcome: TaskOutcome,
|
|
286
|
+
attempt: number
|
|
287
|
+
) => Promise<"follow_up" | "retry" | "abort">;
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
context?: {
|
|
291
|
+
variables?: Record<string, unknown>;
|
|
292
|
+
artifacts?: Record<string, string>;
|
|
293
|
+
};
|
|
294
|
+
};
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
### Simple API
|
|
298
|
+
|
|
299
|
+
For quick scripts and CLI-compatible usage:
|
|
256
300
|
|
|
257
301
|
```typescript
|
|
258
302
|
import { runWorkflow } from "agent-contracts-runtime";
|
|
@@ -268,20 +312,31 @@ const result = await runWorkflow(adapter, "feature-implement", {
|
|
|
268
312
|
user_request: "Add login endpoint with JWT",
|
|
269
313
|
maxFollowUps: 3,
|
|
270
314
|
maxRetries: 1,
|
|
315
|
+
});
|
|
271
316
|
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
},
|
|
317
|
+
console.log(`${result.workflow_id}: ${result.status} (${result.total_elapsed_ms}ms)`);
|
|
318
|
+
```
|
|
275
319
|
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
320
|
+
Or with the Claude adapter:
|
|
321
|
+
|
|
322
|
+
```typescript
|
|
323
|
+
import { runWorkflow } from "agent-contracts-runtime";
|
|
324
|
+
import { ClaudeAgentSdkAdapter } from "agent-contracts-runtime/adapters/claude-agent-sdk";
|
|
325
|
+
|
|
326
|
+
const adapter = new ClaudeAgentSdkAdapter({
|
|
327
|
+
cwd: process.cwd(),
|
|
279
328
|
});
|
|
280
329
|
|
|
281
|
-
|
|
330
|
+
const result = await runWorkflow(adapter, "feature-implement", {
|
|
331
|
+
user_request: "Add login endpoint with JWT",
|
|
332
|
+
maxFollowUps: 3,
|
|
333
|
+
maxRetries: 1,
|
|
334
|
+
});
|
|
282
335
|
```
|
|
283
336
|
|
|
284
|
-
|
|
337
|
+
For production integration, prefer the Structured API or Builder API so that input handoffs are validated before execution.
|
|
338
|
+
|
|
339
|
+
### Structured API
|
|
285
340
|
|
|
286
341
|
Use `WorkflowInvocation` for typed handoff input with Zod validation on both input and output:
|
|
287
342
|
|
|
@@ -317,7 +372,7 @@ const result = await runWorkflow(adapter, {
|
|
|
317
372
|
});
|
|
318
373
|
```
|
|
319
374
|
|
|
320
|
-
The `WorkflowInvocation` envelope is SDK-independent. SDK-specific options
|
|
375
|
+
The `WorkflowInvocation` envelope is SDK-independent. SDK-specific options belong on the adapter constructor:
|
|
321
376
|
|
|
322
377
|
```typescript
|
|
323
378
|
const adapter = await CursorSdkAdapter.create({
|
|
@@ -327,9 +382,9 @@ const adapter = await CursorSdkAdapter.create({
|
|
|
327
382
|
});
|
|
328
383
|
```
|
|
329
384
|
|
|
330
|
-
###
|
|
385
|
+
### Builder API
|
|
331
386
|
|
|
332
|
-
For
|
|
387
|
+
For fluent programmatic usage:
|
|
333
388
|
|
|
334
389
|
```typescript
|
|
335
390
|
import { createRuntime } from "agent-contracts-runtime";
|
|
@@ -388,7 +443,183 @@ if (result.outcome.status === "success") {
|
|
|
388
443
|
}
|
|
389
444
|
```
|
|
390
445
|
|
|
391
|
-
###
|
|
446
|
+
### Workflow result
|
|
447
|
+
|
|
448
|
+
```typescript
|
|
449
|
+
type WorkflowResult = {
|
|
450
|
+
workflow_id: string;
|
|
451
|
+
status: "success" | "failed" | "escalation" | "cancelled";
|
|
452
|
+
steps: StepResult[];
|
|
453
|
+
final_handoff?: HandoffEnvelope;
|
|
454
|
+
total_elapsed_ms: number;
|
|
455
|
+
run_dir?: string;
|
|
456
|
+
};
|
|
457
|
+
```
|
|
458
|
+
|
|
459
|
+
Each step result includes task ID, outcome status, validation errors, follow-up count, retry count, and elapsed time.
|
|
460
|
+
|
|
461
|
+
## CLI
|
|
462
|
+
|
|
463
|
+
| Command | Description |
|
|
464
|
+
|---------|-------------|
|
|
465
|
+
| `agent-runtime init` | Initialize runtime scaffolding |
|
|
466
|
+
| `agent-runtime generate` | Generate contracts and hooks from DSL |
|
|
467
|
+
| `agent-runtime run <workflow> <request>` | Execute a workflow |
|
|
468
|
+
| `agent-runtime run --file <path>` | Execute from a YAML invocation file |
|
|
469
|
+
| `agent-runtime list <resource>` | List workflows, tasks, or agents |
|
|
470
|
+
| `agent-runtime show-prompt <task>` | Display the generated prompt for a task |
|
|
471
|
+
| `agent-runtime doctor` | Verify configuration and connectivity |
|
|
472
|
+
| `agent-runtime replay <run-dir>` | Replay a recorded local execution for debugging |
|
|
473
|
+
|
|
474
|
+
Key options:
|
|
475
|
+
|
|
476
|
+
```bash
|
|
477
|
+
agent-runtime generate --check # CI: verify generated files are up to date
|
|
478
|
+
agent-runtime generate --clean # Delete and regenerate
|
|
479
|
+
agent-runtime generate -t ./my-tpl # Use custom Handlebars templates
|
|
480
|
+
agent-runtime run ... --dry-run # Simulate without calling SDK
|
|
481
|
+
agent-runtime run ... --adapter mock # Use mock adapter for testing
|
|
482
|
+
agent-runtime run --file ./invocation.yaml # Run from YAML manifest
|
|
483
|
+
agent-runtime show-prompt plan-and-implement # Preview prompt
|
|
484
|
+
agent-runtime show-prompt audit-tests -u "Check test quality" # With custom request
|
|
485
|
+
agent-runtime show-prompt plan-and-implement --format json # JSON output
|
|
486
|
+
agent-runtime show-prompt plan-and-implement --with-plugins # Apply plugin enhancers
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
### YAML invocation file
|
|
490
|
+
|
|
491
|
+
For CI or programmatic invocation, define the full request as a YAML file:
|
|
492
|
+
|
|
493
|
+
```yaml
|
|
494
|
+
# invocation.yaml
|
|
495
|
+
workflow: feature-implement
|
|
496
|
+
handoff:
|
|
497
|
+
type: feature-implementation-request
|
|
498
|
+
payload:
|
|
499
|
+
objective: Add login endpoint with JWT
|
|
500
|
+
inputs:
|
|
501
|
+
repository: .
|
|
502
|
+
expected_outputs:
|
|
503
|
+
- implementation-diff
|
|
504
|
+
completion_criteria:
|
|
505
|
+
- tests_passed
|
|
506
|
+
runtime:
|
|
507
|
+
max_follow_ups: 3
|
|
508
|
+
max_retries: 1
|
|
509
|
+
```
|
|
510
|
+
|
|
511
|
+
```bash
|
|
512
|
+
agent-runtime run --file ./invocation.yaml --adapter claude
|
|
513
|
+
# or: --adapter cursor, --adapter mock
|
|
514
|
+
```
|
|
515
|
+
|
|
516
|
+
For full CLI reference with exit codes and output schemas, see [docs/cli-reference.md](docs/cli-reference.md).
|
|
517
|
+
|
|
518
|
+
The CLI specification is managed contract-first via [`cli-contracts`](https://www.npmjs.com/package/cli-contracts) in [`cli-contract.yaml`](cli-contract.yaml).
|
|
519
|
+
|
|
520
|
+
## SDK adapters
|
|
521
|
+
|
|
522
|
+
| Adapter | SDK | Status |
|
|
523
|
+
|---------|-----|--------|
|
|
524
|
+
| `cursor` | Cursor Cloud Agents (`@cursor/sdk`) | Implemented |
|
|
525
|
+
| `claude` | Claude Agent SDK (`@anthropic-ai/claude-agent-sdk`) | Implemented |
|
|
526
|
+
| `openai` | OpenAI Agents SDK | Planned |
|
|
527
|
+
| `mock` | Simulated responses for testing/demo | Implemented |
|
|
528
|
+
|
|
529
|
+
### Adapter interface
|
|
530
|
+
|
|
531
|
+
The minimal adapter interface requires only `send`:
|
|
532
|
+
|
|
533
|
+
```typescript
|
|
534
|
+
interface SdkAdapter {
|
|
535
|
+
send(prompt: string, options: AdapterSendOptions): Promise<string>;
|
|
536
|
+
followUp?(message: string): Promise<string>;
|
|
537
|
+
}
|
|
538
|
+
```
|
|
539
|
+
|
|
540
|
+
For adapters that need full contract context, implement `sendExecution`:
|
|
541
|
+
|
|
542
|
+
```typescript
|
|
543
|
+
interface SdkAdapter {
|
|
544
|
+
send(prompt: string, options: AdapterSendOptions): Promise<string>;
|
|
545
|
+
followUp?(message: string): Promise<string>;
|
|
546
|
+
sendExecution?(request: AgentExecutionRequest): Promise<string>;
|
|
547
|
+
}
|
|
548
|
+
```
|
|
549
|
+
|
|
550
|
+
When `sendExecution` is implemented, the runtime prefers it over `send` and passes the full `AgentExecutionRequest` containing agent/task IDs, handoff info, Zod schema metadata, and task context.
|
|
551
|
+
|
|
552
|
+
### Choosing adapter methods
|
|
553
|
+
|
|
554
|
+
| Method | Use when |
|
|
555
|
+
|--------|----------|
|
|
556
|
+
| `send(prompt, options)` | Your SDK only needs a prompt string |
|
|
557
|
+
| `sendExecution(request)` | Your SDK needs agent/task IDs, handoff metadata, schema info, tools, or context |
|
|
558
|
+
| `followUp(message)` | Your SDK supports continuing the same session after validation errors |
|
|
559
|
+
|
|
560
|
+
Adapters may start with `send` and later upgrade to `sendExecution` without changing workflow code.
|
|
561
|
+
|
|
562
|
+
SDK-specific options belong on the adapter constructor, not on the shared interface:
|
|
563
|
+
|
|
564
|
+
```typescript
|
|
565
|
+
// Cursor SDK
|
|
566
|
+
const cursorAdapter = await CursorSdkAdapter.create({
|
|
567
|
+
apiKey: process.env.CURSOR_API_KEY!,
|
|
568
|
+
model: "composer-2",
|
|
569
|
+
cwd: process.cwd(),
|
|
570
|
+
guardrailHooks,
|
|
571
|
+
});
|
|
572
|
+
|
|
573
|
+
// Claude Agent SDK
|
|
574
|
+
const claudeAdapter = new ClaudeAgentSdkAdapter({
|
|
575
|
+
model: "claude-sonnet-4-20250514",
|
|
576
|
+
cwd: process.cwd(),
|
|
577
|
+
guardrailHooks,
|
|
578
|
+
});
|
|
579
|
+
```
|
|
580
|
+
|
|
581
|
+
### Claude Agent SDK adapter
|
|
582
|
+
|
|
583
|
+
The Claude adapter wraps `@anthropic-ai/claude-agent-sdk`, which runs Claude as a stateful coding agent with built-in tool execution (Read, Edit, Bash, etc.).
|
|
584
|
+
|
|
585
|
+
```typescript
|
|
586
|
+
import { ClaudeAgentSdkAdapter } from "agent-contracts-runtime/adapters/claude-agent-sdk";
|
|
587
|
+
|
|
588
|
+
const adapter = new ClaudeAgentSdkAdapter({
|
|
589
|
+
cwd: process.cwd(),
|
|
590
|
+
model: "claude-sonnet-4-20250514", // optional, uses SDK default
|
|
591
|
+
permissionMode: "bypassPermissions", // default for automated workflows
|
|
592
|
+
maxTurns: 20, // optional turn limit
|
|
593
|
+
guardrailHooks, // optional guardrail enforcement
|
|
594
|
+
});
|
|
595
|
+
```
|
|
596
|
+
|
|
597
|
+
Internally the adapter calls the SDK's `query()` function, which returns an AsyncGenerator of SDK events. The adapter iterates the stream and extracts the final result text.
|
|
598
|
+
|
|
599
|
+
`followUp()` resumes the same session via the SDK's `resume` option, so the agent retains full conversation context when correcting output format.
|
|
600
|
+
|
|
601
|
+
| Config option | Description | Default |
|
|
602
|
+
|---------------|-------------|---------|
|
|
603
|
+
| `cwd` | Working directory | `process.cwd()` |
|
|
604
|
+
| `model` | Claude model identifier | SDK default |
|
|
605
|
+
| `tools` | Available tools (string array or `{ type: 'preset', preset: 'claude_code' }`) | Auto-selected based on `readonly` |
|
|
606
|
+
| `permissionMode` | `"default"` / `"acceptEdits"` / `"bypassPermissions"` / `"plan"` | `"bypassPermissions"` |
|
|
607
|
+
| `maxTurns` | Maximum conversation turns | No limit |
|
|
608
|
+
| `guardrailHooks` | Runtime guardrail hooks (mapped to SDK `PreToolUse` hooks) | None |
|
|
609
|
+
|
|
610
|
+
> **Note:** `@anthropic-ai/claude-agent-sdk` requires `zod@^4.0.0` as a peer dependency. If your project uses `zod@^3`, install the SDK in a separate workspace or use npm `--legacy-peer-deps`.
|
|
611
|
+
|
|
612
|
+
## Handoff validation
|
|
613
|
+
|
|
614
|
+
The runtime validates both input and output handoffs against generated Zod schemas.
|
|
615
|
+
|
|
616
|
+
Input validation happens when a `WorkflowInvocation` includes a typed handoff (Structured API or Builder API). The handoff factory validates the payload at construction time.
|
|
617
|
+
|
|
618
|
+
Output validation happens after each SDK execution. The runtime extracts the structured result from the agent's output and validates it against the expected handoff schema for that workflow step.
|
|
619
|
+
|
|
620
|
+
If validation fails, the runtime attempts a followUp (lightweight, same session) to correct the output format before falling back to a full retry.
|
|
621
|
+
|
|
622
|
+
## Follow-up and retry
|
|
392
623
|
|
|
393
624
|
| | followUp | retry |
|
|
394
625
|
|---|---|---|
|
|
@@ -398,8 +629,7 @@ if (result.outcome.status === "success") {
|
|
|
398
629
|
| **Default limit** | `maxFollowUps: 2` | `maxRetries: 0` (opt-in) |
|
|
399
630
|
| **DSL mapping** | Independent (always available) | `step.max_retries` in workflow DSL |
|
|
400
631
|
| **Trigger** | Zod schema validation error | Empty output, or `decideRetryStrategy` |
|
|
401
|
-
| **Session** | Same session continues | New session |
|
|
402
|
-
| **Override** | `WorkflowRunOptions.maxFollowUps` | `WorkflowRunOptions.maxRetries` |
|
|
632
|
+
| **Session** | Same session continues (Cursor: same agent, Claude: `resume` with session ID) | New session |
|
|
403
633
|
|
|
404
634
|
The prompt includes the full handoff schema field table and a YAML example, so the agent can produce valid output on the first attempt without guessing the format.
|
|
405
635
|
|
|
@@ -416,36 +646,9 @@ const result = await runTask(adapter, "plan-and-implement", {
|
|
|
416
646
|
});
|
|
417
647
|
```
|
|
418
648
|
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
```typescript
|
|
422
|
-
import { pluginRegistry, type AgentPlugin } from "agent-contracts-runtime";
|
|
423
|
-
|
|
424
|
-
const myPlugin: AgentPlugin = {
|
|
425
|
-
id: "my-plugin",
|
|
426
|
-
async beforeTask(taskId, context) {
|
|
427
|
-
return context; // return null to skip
|
|
428
|
-
},
|
|
429
|
-
contextEnhancer(taskId, context) {
|
|
430
|
-
return {
|
|
431
|
-
...context,
|
|
432
|
-
variables: { ...context.variables, projectFramework: "NestJS" },
|
|
433
|
-
};
|
|
434
|
-
},
|
|
435
|
-
async afterTask(taskId, outcome) {
|
|
436
|
-
return outcome;
|
|
437
|
-
},
|
|
438
|
-
promptEnhancer(taskId, prompt) {
|
|
439
|
-
return prompt + "\n\nAlways write tests first.";
|
|
440
|
-
},
|
|
441
|
-
};
|
|
442
|
-
|
|
443
|
-
pluginRegistry.register(myPlugin);
|
|
444
|
-
```
|
|
445
|
-
|
|
446
|
-
## Plugin system
|
|
649
|
+
## Runtime hooks and plugins
|
|
447
650
|
|
|
448
|
-
Plugins
|
|
651
|
+
Plugins let project code customize execution around DSL-defined workflows without changing the DSL or runtime core.
|
|
449
652
|
|
|
450
653
|
```typescript
|
|
451
654
|
interface AgentPlugin {
|
|
@@ -481,6 +684,13 @@ afterTask
|
|
|
481
684
|
afterWorkflow
|
|
482
685
|
```
|
|
483
686
|
|
|
687
|
+
### beforeTask vs contextEnhancer
|
|
688
|
+
|
|
689
|
+
| Hook | Purpose | Side effects |
|
|
690
|
+
|------|---------|--------------|
|
|
691
|
+
| `beforeTask` | Skip task (return `null`), replace context entirely, perform gating decisions | May have side effects |
|
|
692
|
+
| `contextEnhancer` | Add structured variables, paths, or metadata to context | Should be side-effect free |
|
|
693
|
+
|
|
484
694
|
### Context vs prompt
|
|
485
695
|
|
|
486
696
|
The runtime treats prompt as a **derived artifact** from structured context. Plugins should prefer modifying `TaskContext` via `contextEnhancer` over string manipulation in `promptEnhancer` when the data is structured:
|
|
@@ -509,64 +719,31 @@ const contextPlugin: AgentPlugin = {
|
|
|
509
719
|
| `promptBuilder` | Full prompt override. Return a string to replace the default prompt, or `null` to use the default. | 1st (before `promptEnhancer`) |
|
|
510
720
|
| `promptEnhancer` | Lightweight post-processor. Receives the built prompt and returns a modified version. | 2nd (after `promptBuilder`) |
|
|
511
721
|
|
|
512
|
-
|
|
722
|
+
### Register a plugin
|
|
513
723
|
|
|
514
724
|
```typescript
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
725
|
+
import { pluginRegistry, type AgentPlugin } from "agent-contracts-runtime";
|
|
726
|
+
|
|
727
|
+
const myPlugin: AgentPlugin = {
|
|
728
|
+
id: "my-plugin",
|
|
729
|
+
async beforeTask(taskId, context) {
|
|
730
|
+
return context; // return null to skip
|
|
731
|
+
},
|
|
732
|
+
contextEnhancer(taskId, context) {
|
|
733
|
+
return {
|
|
734
|
+
...context,
|
|
735
|
+
variables: { ...context.variables, projectFramework: "NestJS" },
|
|
736
|
+
};
|
|
737
|
+
},
|
|
738
|
+
async afterTask(taskId, outcome) {
|
|
739
|
+
return outcome;
|
|
740
|
+
},
|
|
741
|
+
promptEnhancer(taskId, prompt) {
|
|
742
|
+
return prompt + "\n\nAlways write tests first.";
|
|
525
743
|
},
|
|
526
744
|
};
|
|
527
|
-
```
|
|
528
|
-
|
|
529
|
-
## SDK adapters
|
|
530
|
-
|
|
531
|
-
| Adapter | SDK | Status |
|
|
532
|
-
|---------|-----|--------|
|
|
533
|
-
| `cursor` | Cursor Cloud Agents (`@cursor/sdk`) | Implemented |
|
|
534
|
-
| `claude` | Claude Agent SDK (`@anthropic-ai/claude-agent-sdk`) | Stub |
|
|
535
|
-
| `openai` | OpenAI Agents SDK | Planned |
|
|
536
|
-
| `mock` | Simulated responses for testing/demo | Implemented |
|
|
537
|
-
|
|
538
|
-
### Adapter interface
|
|
539
|
-
|
|
540
|
-
The minimal adapter interface requires only `send`:
|
|
541
745
|
|
|
542
|
-
|
|
543
|
-
interface SdkAdapter {
|
|
544
|
-
send(prompt: string, options: AdapterSendOptions): Promise<string>;
|
|
545
|
-
followUp?(message: string): Promise<string>;
|
|
546
|
-
}
|
|
547
|
-
```
|
|
548
|
-
|
|
549
|
-
For adapters that need full contract context, implement `sendExecution`:
|
|
550
|
-
|
|
551
|
-
```typescript
|
|
552
|
-
interface SdkAdapter {
|
|
553
|
-
send(prompt: string, options: AdapterSendOptions): Promise<string>;
|
|
554
|
-
followUp?(message: string): Promise<string>;
|
|
555
|
-
sendExecution?(request: AgentExecutionRequest): Promise<string>;
|
|
556
|
-
}
|
|
557
|
-
```
|
|
558
|
-
|
|
559
|
-
When `sendExecution` is implemented, the runtime prefers it over `send` and passes the full `AgentExecutionRequest` containing agent/task IDs, handoff info, Zod schema metadata, and task context. Adapters that only need a prompt string can omit it entirely.
|
|
560
|
-
|
|
561
|
-
SDK-specific options belong on the adapter constructor, not on the shared interface:
|
|
562
|
-
|
|
563
|
-
```typescript
|
|
564
|
-
const adapter = await CursorSdkAdapter.create({
|
|
565
|
-
apiKey: process.env.CURSOR_API_KEY!,
|
|
566
|
-
model: "composer-2",
|
|
567
|
-
cwd: process.cwd(),
|
|
568
|
-
guardrailHooks,
|
|
569
|
-
});
|
|
746
|
+
pluginRegistry.register(myPlugin);
|
|
570
747
|
```
|
|
571
748
|
|
|
572
749
|
## Guardrails
|
|
@@ -580,7 +757,7 @@ Generated guardrail hooks (from DSL + binding) and plugin custom guardrails are
|
|
|
580
757
|
| `block` | Deny the operation |
|
|
581
758
|
| `warn` | Allow with warning (can fail with `fail_on_guardrail_warning`) |
|
|
582
759
|
| `info` | Allow with informational context to user/agent |
|
|
583
|
-
| `shadow` |
|
|
760
|
+
| `shadow` | Report only, no effect on execution |
|
|
584
761
|
|
|
585
762
|
Guardrail checks are defined in binding YAML files (not in the DSL directly), following the `agent-contracts` `SoftwareBinding` schema with `guardrail_impl` entries. Three matcher types are supported:
|
|
586
763
|
|
|
@@ -588,6 +765,28 @@ Guardrail checks are defined in binding YAML files (not in the DSL directly), fo
|
|
|
588
765
|
- `file_glob` — Match file paths against glob patterns
|
|
589
766
|
- `content_regex` — Match file content against regex patterns
|
|
590
767
|
|
|
768
|
+
### Binding file
|
|
769
|
+
|
|
770
|
+
```yaml
|
|
771
|
+
# bindings/runtime.yaml
|
|
772
|
+
software: agent-runtime
|
|
773
|
+
version: 1
|
|
774
|
+
|
|
775
|
+
guardrail_impl:
|
|
776
|
+
no-force-push:
|
|
777
|
+
checks:
|
|
778
|
+
- matcher:
|
|
779
|
+
type: command_regex
|
|
780
|
+
pattern: "(^|[|;&]\\s*)git\\s+push\\s.*(--force|-f)\\b"
|
|
781
|
+
message: "Force push is forbidden."
|
|
782
|
+
block-env-files:
|
|
783
|
+
checks:
|
|
784
|
+
- matcher:
|
|
785
|
+
type: file_glob
|
|
786
|
+
pattern: "**/{.env,.env.*}"
|
|
787
|
+
message: "Writing to .env file is blocked."
|
|
788
|
+
```
|
|
789
|
+
|
|
591
790
|
## Configuration
|
|
592
791
|
|
|
593
792
|
`agent-runtime.config.yaml`:
|
|
@@ -601,15 +800,6 @@ active_guardrail_policy: default # which guardrail_policy to activate
|
|
|
601
800
|
templates_dir: ./custom-templates # optional, overrides built-in templates
|
|
602
801
|
```
|
|
603
802
|
|
|
604
|
-
## CI integration
|
|
605
|
-
|
|
606
|
-
```yaml
|
|
607
|
-
- run: agent-contracts validate
|
|
608
|
-
- run: agent-contracts lint --strict
|
|
609
|
-
- run: agent-runtime generate --check
|
|
610
|
-
- run: agent-runtime doctor
|
|
611
|
-
```
|
|
612
|
-
|
|
613
803
|
## Exports
|
|
614
804
|
|
|
615
805
|
| Import path | Description |
|
|
@@ -626,6 +816,8 @@ templates_dir: ./custom-templates # optional, overrides built-in templa
|
|
|
626
816
|
- Node.js 20+
|
|
627
817
|
- TypeScript 5.x (ESM, strict mode)
|
|
628
818
|
- `agent-contracts` (optional peer dependency for DSL resolution)
|
|
819
|
+
- `@anthropic-ai/claude-agent-sdk` (optional, for Claude adapter — requires zod ^4.0.0)
|
|
820
|
+
- `@cursor/sdk` (optional, for Cursor adapter)
|
|
629
821
|
|
|
630
822
|
## License
|
|
631
823
|
|
|
@@ -1,22 +1,78 @@
|
|
|
1
|
-
import { S as SdkAdapter, A as AdapterSendOptions } from '../task-runner-
|
|
1
|
+
import { S as SdkAdapter, A as AdapterSendOptions, a as AgentExecutionRequest } from '../task-runner-Bt2XiEUU.js';
|
|
2
2
|
import { G as GuardrailHooks } from '../guardrail-hooks-5MSNWxnl.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Claude Agent SDK Adapter — implements SdkAdapter for @anthropic-ai/claude-agent-sdk
|
|
7
|
+
*
|
|
8
|
+
* Uses the `query()` function from the Claude Agent SDK to run Claude as a
|
|
9
|
+
* stateful coding agent with tool execution (Read, Edit, Bash, etc.).
|
|
10
|
+
*
|
|
11
|
+
* Supports:
|
|
12
|
+
* - send() — start a new query session and return the result text
|
|
13
|
+
* - followUp() — resume the same session for output-format corrections
|
|
14
|
+
* - sendExecution() — rich path using full contract context
|
|
15
|
+
*
|
|
16
|
+
* The SDK returns an AsyncGenerator of SDKMessage events. The adapter iterates
|
|
17
|
+
* the stream, extracts the final result text from the SDKResultSuccess message,
|
|
18
|
+
* and captures the session_id for followUp via `resume`.
|
|
19
|
+
*
|
|
20
|
+
* GuardrailHooks are mapped to the SDK's PreToolUse hook system.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
type SDKMessage = {
|
|
24
|
+
type: string;
|
|
25
|
+
subtype?: string;
|
|
26
|
+
result?: string;
|
|
27
|
+
error?: string;
|
|
28
|
+
session_id?: string;
|
|
29
|
+
};
|
|
30
|
+
type QueryOptions = Record<string, unknown>;
|
|
31
|
+
type QueryFn = (params: {
|
|
32
|
+
prompt: string;
|
|
33
|
+
options?: QueryOptions;
|
|
34
|
+
}) => AsyncGenerator<SDKMessage, void>;
|
|
5
35
|
interface ClaudeAgentSdkAdapterConfig {
|
|
36
|
+
/** Working directory for the agent. Defaults to process.cwd(). */
|
|
6
37
|
cwd?: string;
|
|
38
|
+
/** Model identifier (e.g. "claude-sonnet-4-20250514"). Uses SDK default if omitted. */
|
|
7
39
|
model?: string;
|
|
40
|
+
/**
|
|
41
|
+
* Available tools. Defaults to read-only or read-write set based on AdapterSendOptions.
|
|
42
|
+
* Set to `{ type: 'preset', preset: 'claude_code' }` for all Claude Code tools.
|
|
43
|
+
*/
|
|
44
|
+
tools?: string[] | {
|
|
45
|
+
type: "preset";
|
|
46
|
+
preset: "claude_code";
|
|
47
|
+
};
|
|
48
|
+
/** Permission mode. Defaults to "bypassPermissions" for automated workflows. */
|
|
49
|
+
permissionMode?: "default" | "acceptEdits" | "bypassPermissions" | "plan";
|
|
50
|
+
/** Max turns before stopping. */
|
|
51
|
+
maxTurns?: number;
|
|
52
|
+
/** Runtime guardrail hooks enforced via PreToolUse SDK hooks. */
|
|
8
53
|
guardrailHooks?: GuardrailHooks;
|
|
9
54
|
}
|
|
10
55
|
declare class ClaudeAgentSdkAdapter implements SdkAdapter {
|
|
11
|
-
private agent;
|
|
12
56
|
private cwd;
|
|
13
57
|
private model;
|
|
14
|
-
private
|
|
15
|
-
private
|
|
16
|
-
|
|
17
|
-
private
|
|
58
|
+
private tools;
|
|
59
|
+
private permissionMode;
|
|
60
|
+
private maxTurns;
|
|
61
|
+
private guardrailHooks;
|
|
62
|
+
private lastSessionId;
|
|
63
|
+
private queryFn;
|
|
64
|
+
constructor(config?: ClaudeAgentSdkAdapterConfig);
|
|
65
|
+
private resolveQueryFn;
|
|
66
|
+
private buildOptions;
|
|
67
|
+
private runQuery;
|
|
18
68
|
send(prompt: string, options: AdapterSendOptions): Promise<string>;
|
|
19
69
|
followUp(message: string): Promise<string>;
|
|
70
|
+
sendExecution(request: AgentExecutionRequest): Promise<string>;
|
|
71
|
+
/**
|
|
72
|
+
* Inject a custom query function for testing.
|
|
73
|
+
* Bypasses the dynamic import of @anthropic-ai/claude-agent-sdk.
|
|
74
|
+
*/
|
|
75
|
+
static withQueryFn(queryFn: QueryFn, config?: ClaudeAgentSdkAdapterConfig): ClaudeAgentSdkAdapter;
|
|
20
76
|
}
|
|
21
77
|
|
|
22
78
|
export { ClaudeAgentSdkAdapter, type ClaudeAgentSdkAdapterConfig };
|
|
@@ -1,70 +1,148 @@
|
|
|
1
1
|
// src/adapters/claude-agent-sdk.ts
|
|
2
|
-
function buildClaudeHooks(
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
2
|
+
function buildClaudeHooks(guardrails) {
|
|
3
|
+
const preToolUseHook = {
|
|
4
|
+
hooks: [
|
|
5
|
+
(input) => {
|
|
6
|
+
const toolInput = input.tool_input;
|
|
7
|
+
const toolName = input.tool_name;
|
|
8
|
+
if (toolName === "Bash" || toolName === "Shell") {
|
|
9
|
+
const command = toolInput?.command ?? toolInput?.input;
|
|
10
|
+
if (command) {
|
|
11
|
+
const result = guardrails.beforeShellExecution({ command });
|
|
12
|
+
if (result.permission === "deny") {
|
|
13
|
+
return {
|
|
14
|
+
hookEventName: "PreToolUse",
|
|
15
|
+
permissionDecision: "deny",
|
|
16
|
+
permissionDecisionReason: result.user_message ?? result.agent_message
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
if (result.additionalContext) {
|
|
20
|
+
return { hookEventName: "PreToolUse", additionalContext: result.additionalContext };
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const filePath = toolInput?.file_path ?? toolInput?.path;
|
|
25
|
+
if (filePath) {
|
|
26
|
+
const pathResult = guardrails.preToolUse({
|
|
27
|
+
tool_name: toolName,
|
|
28
|
+
tool_input: { file_path: filePath }
|
|
29
|
+
});
|
|
30
|
+
if (pathResult.permission === "deny") {
|
|
31
|
+
return {
|
|
32
|
+
hookEventName: "PreToolUse",
|
|
33
|
+
permissionDecision: "deny",
|
|
34
|
+
permissionDecisionReason: pathResult.user_message ?? pathResult.agent_message
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
if (pathResult.additionalContext) {
|
|
38
|
+
return { hookEventName: "PreToolUse", additionalContext: pathResult.additionalContext };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return { hookEventName: "PreToolUse" };
|
|
42
|
+
}
|
|
43
|
+
]
|
|
16
44
|
};
|
|
45
|
+
return { PreToolUse: [preToolUseHook] };
|
|
17
46
|
}
|
|
18
|
-
|
|
19
|
-
if (response.permission === "deny") {
|
|
20
|
-
return {
|
|
21
|
-
decision: "deny",
|
|
22
|
-
message: response.user_message ?? response.agent_message
|
|
23
|
-
};
|
|
24
|
-
}
|
|
25
|
-
if (response.additionalContext) {
|
|
26
|
-
return { additionalContext: response.additionalContext };
|
|
27
|
-
}
|
|
28
|
-
return {};
|
|
29
|
-
}
|
|
30
|
-
var ClaudeAgentSdkAdapter = class {
|
|
31
|
-
agent = null;
|
|
47
|
+
var ClaudeAgentSdkAdapter = class _ClaudeAgentSdkAdapter {
|
|
32
48
|
cwd;
|
|
33
49
|
model;
|
|
34
|
-
|
|
50
|
+
tools;
|
|
51
|
+
permissionMode;
|
|
52
|
+
maxTurns;
|
|
35
53
|
guardrailHooks;
|
|
36
|
-
|
|
54
|
+
lastSessionId = null;
|
|
55
|
+
queryFn = null;
|
|
56
|
+
constructor(config = {}) {
|
|
37
57
|
this.cwd = config.cwd ?? process.cwd();
|
|
38
|
-
this.model = config.model
|
|
58
|
+
this.model = config.model;
|
|
59
|
+
this.tools = config.tools;
|
|
60
|
+
this.permissionMode = config.permissionMode ?? "bypassPermissions";
|
|
61
|
+
this.maxTurns = config.maxTurns;
|
|
39
62
|
this.guardrailHooks = config.guardrailHooks;
|
|
40
63
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
64
|
+
// -------------------------------------------------------------------------
|
|
65
|
+
// Internal helpers
|
|
66
|
+
// -------------------------------------------------------------------------
|
|
67
|
+
async resolveQueryFn() {
|
|
68
|
+
if (this.queryFn) return this.queryFn;
|
|
69
|
+
const sdk = await import("@anthropic-ai/claude-agent-sdk");
|
|
70
|
+
this.queryFn = sdk.query;
|
|
71
|
+
return this.queryFn;
|
|
72
|
+
}
|
|
73
|
+
buildOptions(readonly, resume) {
|
|
45
74
|
const opts = {
|
|
46
|
-
model: this.model,
|
|
47
75
|
cwd: this.cwd,
|
|
48
|
-
|
|
76
|
+
permissionMode: this.permissionMode,
|
|
77
|
+
allowDangerouslySkipPermissions: this.permissionMode === "bypassPermissions"
|
|
49
78
|
};
|
|
79
|
+
if (this.model) opts.model = this.model;
|
|
80
|
+
if (this.maxTurns) opts.maxTurns = this.maxTurns;
|
|
81
|
+
if (this.tools) {
|
|
82
|
+
opts.tools = this.tools;
|
|
83
|
+
} else {
|
|
84
|
+
opts.tools = readonly ? ["Read", "Glob", "Grep"] : ["Read", "Glob", "Grep", "Edit", "Write", "Bash"];
|
|
85
|
+
}
|
|
86
|
+
if (resume) opts.resume = resume;
|
|
50
87
|
if (this.guardrailHooks) {
|
|
51
|
-
|
|
88
|
+
opts.hooks = buildClaudeHooks(this.guardrailHooks);
|
|
89
|
+
}
|
|
90
|
+
return opts;
|
|
91
|
+
}
|
|
92
|
+
async runQuery(prompt, options) {
|
|
93
|
+
const queryFn = await this.resolveQueryFn();
|
|
94
|
+
const stream = queryFn({ prompt, options });
|
|
95
|
+
let resultText = "";
|
|
96
|
+
let sessionId = "";
|
|
97
|
+
for await (const message of stream) {
|
|
98
|
+
if (message.type === "result") {
|
|
99
|
+
sessionId = message.session_id ?? sessionId;
|
|
100
|
+
if (message.subtype === "success") {
|
|
101
|
+
resultText = message.result;
|
|
102
|
+
} else if (message.subtype === "error") {
|
|
103
|
+
throw new Error(`Claude Agent SDK error: ${message.error}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
52
106
|
}
|
|
53
|
-
|
|
54
|
-
return this.agent;
|
|
107
|
+
return { text: resultText, sessionId };
|
|
55
108
|
}
|
|
109
|
+
// -------------------------------------------------------------------------
|
|
110
|
+
// SdkAdapter interface
|
|
111
|
+
// -------------------------------------------------------------------------
|
|
56
112
|
async send(prompt, options) {
|
|
57
|
-
this.
|
|
58
|
-
const
|
|
59
|
-
const
|
|
60
|
-
|
|
113
|
+
this.lastSessionId = null;
|
|
114
|
+
const opts = this.buildOptions(options.readonly);
|
|
115
|
+
const { text, sessionId } = await this.runQuery(prompt, opts);
|
|
116
|
+
this.lastSessionId = sessionId;
|
|
117
|
+
return text;
|
|
61
118
|
}
|
|
62
119
|
async followUp(message) {
|
|
63
|
-
if (!this.
|
|
120
|
+
if (!this.lastSessionId) {
|
|
64
121
|
throw new Error("followUp() called before send() \u2014 no active session");
|
|
65
122
|
}
|
|
66
|
-
const
|
|
67
|
-
|
|
123
|
+
const opts = this.buildOptions(false, this.lastSessionId);
|
|
124
|
+
const { text, sessionId } = await this.runQuery(message, opts);
|
|
125
|
+
this.lastSessionId = sessionId;
|
|
126
|
+
return text;
|
|
127
|
+
}
|
|
128
|
+
async sendExecution(request) {
|
|
129
|
+
this.lastSessionId = null;
|
|
130
|
+
const opts = this.buildOptions(request.options.readonly);
|
|
131
|
+
const { text, sessionId } = await this.runQuery(request.prompt, opts);
|
|
132
|
+
this.lastSessionId = sessionId;
|
|
133
|
+
return text;
|
|
134
|
+
}
|
|
135
|
+
// -------------------------------------------------------------------------
|
|
136
|
+
// Test support
|
|
137
|
+
// -------------------------------------------------------------------------
|
|
138
|
+
/**
|
|
139
|
+
* Inject a custom query function for testing.
|
|
140
|
+
* Bypasses the dynamic import of @anthropic-ai/claude-agent-sdk.
|
|
141
|
+
*/
|
|
142
|
+
static withQueryFn(queryFn, config) {
|
|
143
|
+
const adapter = new _ClaudeAgentSdkAdapter(config);
|
|
144
|
+
adapter.queryFn = queryFn;
|
|
145
|
+
return adapter;
|
|
68
146
|
}
|
|
69
147
|
};
|
|
70
148
|
export {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/claude-agent-sdk.ts"],"sourcesContent":["/**\n * Claude Agent SDK Adapter — implements SdkAdapter for Claude Agent SDK\n *\n * Supports both send() (new session) and followUp() (same session continuation).\n * The Claude Agent SDK uses a stateful agent instance, so followUp() sends\n * an additional message within the same conversation.\n *\n * When guardrailHooks are provided, wraps each tool call with guardrail\n * evaluation. Shell commands are checked via checkCommand, file operations\n * via checkFilePath, and file edits via checkContent.\n */\n\nimport type { SdkAdapter } from \"../lib/task-runner.js\";\nimport type { GuardrailHooks, HookResponse } from \"../lib/guardrail-hooks.js\";\n\ntype ClaudeAgentInstance = {\n sendMessage(prompt: string): Promise<{ text: string }>;\n};\n\nexport interface ClaudeAgentSdkAdapterConfig {\n cwd?: string;\n model?: string;\n guardrailHooks?: GuardrailHooks;\n}\n\nfunction buildClaudeHooks(hooks: GuardrailHooks): Record<string, unknown> {\n return {\n beforeShellExecution: (input: { command?: string }) => {\n const result = hooks.beforeShellExecution(input);\n return claudeHookResult(result);\n },\n preToolUse: (input: { tool_name?: string; tool_input?: { file_path?: string; path?: string } }) => {\n const result = hooks.preToolUse(input);\n return claudeHookResult(result);\n },\n afterFileEdit: (input: { file_path?: string; content?: string }) => {\n const result = hooks.afterFileEdit(input);\n return claudeHookResult(result);\n },\n };\n}\n\nfunction claudeHookResult(response: HookResponse): Record<string, unknown> {\n if (response.permission === \"deny\") {\n return {\n decision: \"deny\",\n message: response.user_message ?? response.agent_message,\n };\n }\n if (response.additionalContext) {\n return { additionalContext: response.additionalContext };\n }\n return {};\n}\n\nexport class ClaudeAgentSdkAdapter implements SdkAdapter {\n private agent: ClaudeAgentInstance | null = null;\n private cwd: string;\n private model: string;\n private allowedTools: string[] = [];\n private guardrailHooks?: GuardrailHooks;\n\n constructor(config: ClaudeAgentSdkAdapterConfig) {\n this.cwd = config.cwd ?? process.cwd();\n this.model = config.model ?? \"claude-sonnet-4-20250514\";\n this.guardrailHooks = config.guardrailHooks;\n }\n\n private async getOrCreateAgent(readonly: boolean): Promise<ClaudeAgentInstance> {\n if (this.agent) return this.agent;\n\n this.allowedTools = readonly\n ? [\"Read\", \"Glob\", \"Grep\"]\n : [\"Read\", \"Glob\", \"Grep\", \"Edit\", \"Write\", \"Bash\"];\n\n // @ts-expect-error — @anthropic-ai/claude-agent-sdk is an optional peer dependency\n const { ClaudeAgent } = await import(\"@anthropic-ai/claude-agent-sdk\") as {\n ClaudeAgent: { create(opts: Record<string, unknown>): Promise<ClaudeAgentInstance> };\n };\n\n const opts: Record<string, unknown> = {\n model: this.model,\n cwd: this.cwd,\n allowedTools: this.allowedTools,\n };\n\n if (this.guardrailHooks) {\n Object.assign(opts, buildClaudeHooks(this.guardrailHooks));\n }\n\n this.agent = await ClaudeAgent.create(opts);\n return this.agent;\n }\n\n async send(prompt: string, options: import(\"../lib/task-runner.js\").AdapterSendOptions): Promise<string> {\n this.agent = null;\n const agent = await this.getOrCreateAgent(options.readonly);\n const result = await agent.sendMessage(prompt);\n return result.text;\n }\n\n async followUp(message: string): Promise<string> {\n if (!this.agent) {\n throw new Error(\"followUp() called before send() — no active session\");\n }\n const result = await this.agent.sendMessage(message);\n return result.text;\n }\n}\n"],"mappings":";AAyBA,SAAS,iBAAiB,OAAgD;AACxE,SAAO;AAAA,IACL,sBAAsB,CAAC,UAAgC;AACrD,YAAM,SAAS,MAAM,qBAAqB,KAAK;AAC/C,aAAO,iBAAiB,MAAM;AAAA,IAChC;AAAA,IACA,YAAY,CAAC,UAAsF;AACjG,YAAM,SAAS,MAAM,WAAW,KAAK;AACrC,aAAO,iBAAiB,MAAM;AAAA,IAChC;AAAA,IACA,eAAe,CAAC,UAAoD;AAClE,YAAM,SAAS,MAAM,cAAc,KAAK;AACxC,aAAO,iBAAiB,MAAM;AAAA,IAChC;AAAA,EACF;AACF;AAEA,SAAS,iBAAiB,UAAiD;AACzE,MAAI,SAAS,eAAe,QAAQ;AAClC,WAAO;AAAA,MACL,UAAU;AAAA,MACV,SAAS,SAAS,gBAAgB,SAAS;AAAA,IAC7C;AAAA,EACF;AACA,MAAI,SAAS,mBAAmB;AAC9B,WAAO,EAAE,mBAAmB,SAAS,kBAAkB;AAAA,EACzD;AACA,SAAO,CAAC;AACV;AAEO,IAAM,wBAAN,MAAkD;AAAA,EAC/C,QAAoC;AAAA,EACpC;AAAA,EACA;AAAA,EACA,eAAyB,CAAC;AAAA,EAC1B;AAAA,EAER,YAAY,QAAqC;AAC/C,SAAK,MAAM,OAAO,OAAO,QAAQ,IAAI;AACrC,SAAK,QAAQ,OAAO,SAAS;AAC7B,SAAK,iBAAiB,OAAO;AAAA,EAC/B;AAAA,EAEA,MAAc,iBAAiB,UAAiD;AAC9E,QAAI,KAAK,MAAO,QAAO,KAAK;AAE5B,SAAK,eAAe,WAChB,CAAC,QAAQ,QAAQ,MAAM,IACvB,CAAC,QAAQ,QAAQ,QAAQ,QAAQ,SAAS,MAAM;AAGpD,UAAM,EAAE,YAAY,IAAI,MAAM,OAAO,gCAAgC;AAIrE,UAAM,OAAgC;AAAA,MACpC,OAAO,KAAK;AAAA,MACZ,KAAK,KAAK;AAAA,MACV,cAAc,KAAK;AAAA,IACrB;AAEA,QAAI,KAAK,gBAAgB;AACvB,aAAO,OAAO,MAAM,iBAAiB,KAAK,cAAc,CAAC;AAAA,IAC3D;AAEA,SAAK,QAAQ,MAAM,YAAY,OAAO,IAAI;AAC1C,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM,KAAK,QAAgB,SAA8E;AACvG,SAAK,QAAQ;AACb,UAAM,QAAQ,MAAM,KAAK,iBAAiB,QAAQ,QAAQ;AAC1D,UAAM,SAAS,MAAM,MAAM,YAAY,MAAM;AAC7C,WAAO,OAAO;AAAA,EAChB;AAAA,EAEA,MAAM,SAAS,SAAkC;AAC/C,QAAI,CAAC,KAAK,OAAO;AACf,YAAM,IAAI,MAAM,0DAAqD;AAAA,IACvE;AACA,UAAM,SAAS,MAAM,KAAK,MAAM,YAAY,OAAO;AACnD,WAAO,OAAO;AAAA,EAChB;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/claude-agent-sdk.ts"],"sourcesContent":["/**\n * Claude Agent SDK Adapter — implements SdkAdapter for @anthropic-ai/claude-agent-sdk\n *\n * Uses the `query()` function from the Claude Agent SDK to run Claude as a\n * stateful coding agent with tool execution (Read, Edit, Bash, etc.).\n *\n * Supports:\n * - send() — start a new query session and return the result text\n * - followUp() — resume the same session for output-format corrections\n * - sendExecution() — rich path using full contract context\n *\n * The SDK returns an AsyncGenerator of SDKMessage events. The adapter iterates\n * the stream, extracts the final result text from the SDKResultSuccess message,\n * and captures the session_id for followUp via `resume`.\n *\n * GuardrailHooks are mapped to the SDK's PreToolUse hook system.\n */\n\nimport type {\n SdkAdapter,\n AdapterSendOptions,\n AgentExecutionRequest,\n} from \"../lib/task-runner.js\";\nimport type { GuardrailHooks } from \"../lib/guardrail-hooks.js\";\n\n// ---------------------------------------------------------------------------\n// Duck-typed SDK types (avoid hard compile-time dependency on zod v4)\n// ---------------------------------------------------------------------------\n\ntype SDKResultSuccess = {\n type: \"result\";\n subtype: \"success\";\n result: string;\n session_id: string;\n};\n\ntype SDKResultError = {\n type: \"result\";\n subtype: \"error\";\n error: string;\n session_id: string;\n};\n\ntype SDKMessage = {\n type: string;\n subtype?: string;\n result?: string;\n error?: string;\n session_id?: string;\n};\n\ntype HookCallbackInput = {\n hook_event_name: string;\n tool_name: string;\n tool_input: unknown;\n [key: string]: unknown;\n};\n\ntype HookCallbackOutput = {\n hookEventName: string;\n permissionDecision?: \"allow\" | \"deny\" | \"ask\";\n permissionDecisionReason?: string;\n additionalContext?: string;\n};\n\ntype HookCallbackMatcher = {\n tool_name?: string;\n hooks: Array<(input: HookCallbackInput) => HookCallbackOutput | Promise<HookCallbackOutput>>;\n};\n\ntype QueryOptions = Record<string, unknown>;\n\ntype QueryFn = (params: {\n prompt: string;\n options?: QueryOptions;\n}) => AsyncGenerator<SDKMessage, void>;\n\n// ---------------------------------------------------------------------------\n// Guardrail hook bridge\n// ---------------------------------------------------------------------------\n\nfunction buildClaudeHooks(\n guardrails: GuardrailHooks,\n): Partial<Record<string, HookCallbackMatcher[]>> {\n const preToolUseHook: HookCallbackMatcher = {\n hooks: [\n (input: HookCallbackInput): HookCallbackOutput => {\n const toolInput = input.tool_input as Record<string, unknown> | undefined;\n const toolName = input.tool_name;\n\n if (toolName === \"Bash\" || toolName === \"Shell\") {\n const command = (toolInput?.command ?? toolInput?.input) as string | undefined;\n if (command) {\n const result = guardrails.beforeShellExecution({ command });\n if (result.permission === \"deny\") {\n return {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: result.user_message ?? result.agent_message,\n };\n }\n if (result.additionalContext) {\n return { hookEventName: \"PreToolUse\", additionalContext: result.additionalContext };\n }\n }\n }\n\n const filePath = (toolInput?.file_path ?? toolInput?.path) as string | undefined;\n if (filePath) {\n const pathResult = guardrails.preToolUse({\n tool_name: toolName,\n tool_input: { file_path: filePath },\n });\n if (pathResult.permission === \"deny\") {\n return {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: pathResult.user_message ?? pathResult.agent_message,\n };\n }\n if (pathResult.additionalContext) {\n return { hookEventName: \"PreToolUse\", additionalContext: pathResult.additionalContext };\n }\n }\n\n return { hookEventName: \"PreToolUse\" };\n },\n ],\n };\n\n return { PreToolUse: [preToolUseHook] };\n}\n\n// ---------------------------------------------------------------------------\n// Config\n// ---------------------------------------------------------------------------\n\nexport interface ClaudeAgentSdkAdapterConfig {\n /** Working directory for the agent. Defaults to process.cwd(). */\n cwd?: string;\n /** Model identifier (e.g. \"claude-sonnet-4-20250514\"). Uses SDK default if omitted. */\n model?: string;\n /**\n * Available tools. Defaults to read-only or read-write set based on AdapterSendOptions.\n * Set to `{ type: 'preset', preset: 'claude_code' }` for all Claude Code tools.\n */\n tools?: string[] | { type: \"preset\"; preset: \"claude_code\" };\n /** Permission mode. Defaults to \"bypassPermissions\" for automated workflows. */\n permissionMode?: \"default\" | \"acceptEdits\" | \"bypassPermissions\" | \"plan\";\n /** Max turns before stopping. */\n maxTurns?: number;\n /** Runtime guardrail hooks enforced via PreToolUse SDK hooks. */\n guardrailHooks?: GuardrailHooks;\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\nexport class ClaudeAgentSdkAdapter implements SdkAdapter {\n private cwd: string;\n private model: string | undefined;\n private tools: string[] | { type: \"preset\"; preset: \"claude_code\" } | undefined;\n private permissionMode: string;\n private maxTurns: number | undefined;\n private guardrailHooks: GuardrailHooks | undefined;\n private lastSessionId: string | null = null;\n private queryFn: QueryFn | null = null;\n\n constructor(config: ClaudeAgentSdkAdapterConfig = {}) {\n this.cwd = config.cwd ?? process.cwd();\n this.model = config.model;\n this.tools = config.tools;\n this.permissionMode = config.permissionMode ?? \"bypassPermissions\";\n this.maxTurns = config.maxTurns;\n this.guardrailHooks = config.guardrailHooks;\n }\n\n // -------------------------------------------------------------------------\n // Internal helpers\n // -------------------------------------------------------------------------\n\n private async resolveQueryFn(): Promise<QueryFn> {\n if (this.queryFn) return this.queryFn;\n\n // @ts-expect-error — @anthropic-ai/claude-agent-sdk is an optional peer dependency\n const sdk = (await import(\"@anthropic-ai/claude-agent-sdk\")) as {\n query: QueryFn;\n };\n this.queryFn = sdk.query;\n return this.queryFn;\n }\n\n private buildOptions(readonly: boolean, resume?: string): QueryOptions {\n const opts: QueryOptions = {\n cwd: this.cwd,\n permissionMode: this.permissionMode,\n allowDangerouslySkipPermissions: this.permissionMode === \"bypassPermissions\",\n };\n\n if (this.model) opts.model = this.model;\n if (this.maxTurns) opts.maxTurns = this.maxTurns;\n\n if (this.tools) {\n opts.tools = this.tools;\n } else {\n opts.tools = readonly\n ? [\"Read\", \"Glob\", \"Grep\"]\n : [\"Read\", \"Glob\", \"Grep\", \"Edit\", \"Write\", \"Bash\"];\n }\n\n if (resume) opts.resume = resume;\n\n if (this.guardrailHooks) {\n opts.hooks = buildClaudeHooks(this.guardrailHooks);\n }\n\n return opts;\n }\n\n private async runQuery(\n prompt: string,\n options: QueryOptions,\n ): Promise<{ text: string; sessionId: string }> {\n const queryFn = await this.resolveQueryFn();\n const stream = queryFn({ prompt, options });\n\n let resultText = \"\";\n let sessionId = \"\";\n\n for await (const message of stream) {\n if (message.type === \"result\") {\n sessionId = message.session_id ?? sessionId;\n if (message.subtype === \"success\") {\n resultText = (message as SDKResultSuccess).result;\n } else if (message.subtype === \"error\") {\n throw new Error(`Claude Agent SDK error: ${(message as SDKResultError).error}`);\n }\n }\n }\n\n return { text: resultText, sessionId };\n }\n\n // -------------------------------------------------------------------------\n // SdkAdapter interface\n // -------------------------------------------------------------------------\n\n async send(\n prompt: string,\n options: AdapterSendOptions,\n ): Promise<string> {\n this.lastSessionId = null;\n const opts = this.buildOptions(options.readonly);\n const { text, sessionId } = await this.runQuery(prompt, opts);\n this.lastSessionId = sessionId;\n return text;\n }\n\n async followUp(message: string): Promise<string> {\n if (!this.lastSessionId) {\n throw new Error(\"followUp() called before send() — no active session\");\n }\n const opts = this.buildOptions(false, this.lastSessionId);\n const { text, sessionId } = await this.runQuery(message, opts);\n this.lastSessionId = sessionId;\n return text;\n }\n\n async sendExecution(request: AgentExecutionRequest): Promise<string> {\n this.lastSessionId = null;\n const opts = this.buildOptions(request.options.readonly);\n const { text, sessionId } = await this.runQuery(request.prompt, opts);\n this.lastSessionId = sessionId;\n return text;\n }\n\n // -------------------------------------------------------------------------\n // Test support\n // -------------------------------------------------------------------------\n\n /**\n * Inject a custom query function for testing.\n * Bypasses the dynamic import of @anthropic-ai/claude-agent-sdk.\n */\n static withQueryFn(\n queryFn: QueryFn,\n config?: ClaudeAgentSdkAdapterConfig,\n ): ClaudeAgentSdkAdapter {\n const adapter = new ClaudeAgentSdkAdapter(config);\n adapter.queryFn = queryFn;\n return adapter;\n }\n}\n"],"mappings":"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","names":[]}
|
package/dist/adapters/mock.d.ts
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { T as TaskOutcome,
|
|
2
|
-
export { A as AdapterSendOptions,
|
|
1
|
+
import { T as TaskOutcome, b as TaskContractLike, c as AgentContractLike, d as TaskContext, S as SdkAdapter, P as PromptBuilderOptions } from './task-runner-Bt2XiEUU.js';
|
|
2
|
+
export { A as AdapterSendOptions, a as AgentExecutionRequest, R as RetryDecision, e as TaskRunOptions, f as TaskRunResult, g as buildRetryFollowUp, h as buildTaskPrompt, i as extractStructuredResult, r as runTask, z as zodSchemaToPromptDescription, j as zodSchemaToYamlExample } from './task-runner-Bt2XiEUU.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
export { a as GuardrailCheckFunctions, b as GuardrailCheckResult, G as GuardrailHooks, H as HookContext, c as HookResponse, d as createGuardrailHooks, g as getBlockingViolations, e as getWarnings, h as hasBlockingViolation } from './guardrail-hooks-5MSNWxnl.js';
|
|
5
5
|
|
|
@@ -168,4 +168,4 @@ declare function runTask(adapter: SdkAdapter, taskId: string, context: TaskConte
|
|
|
168
168
|
};
|
|
169
169
|
}): Promise<TaskRunResult>;
|
|
170
170
|
|
|
171
|
-
export { type AdapterSendOptions as A, type PromptBuilderOptions as P, type RetryDecision as R, type SdkAdapter as S, type TaskOutcome as T, type
|
|
171
|
+
export { type AdapterSendOptions as A, type PromptBuilderOptions as P, type RetryDecision as R, type SdkAdapter as S, type TaskOutcome as T, type AgentExecutionRequest as a, type TaskContractLike as b, type AgentContractLike as c, type TaskContext as d, type TaskRunOptions as e, type TaskRunResult as f, buildRetryFollowUp as g, buildTaskPrompt as h, extractStructuredResult as i, zodSchemaToYamlExample as j, runTask as r, zodSchemaToPromptDescription as z };
|