agent-contracts-runtime 0.5.2 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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) workflows on Agent SDKs.
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 your multi-agent system as contracts.
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
- It generates typed contracts, handoff validators, and guardrail hooks from your DSL, then runs workflows through pluggable SDK adapters such as Cursor, Claude, or OpenAI Agents SDK.
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
- - **Generate** typed TypeScript contracts, Zod handoff schemas, and guardrail hooks from `agent-contracts.yaml`
13
- - **Run** multi-step agent workflows with mechanical orchestration (followUp, retry, gate, escalation)
14
- - **Validate** every LLM output against handoff schemas before proceeding to the next step
15
- - **Enforce** guardrails (command, file path, file content) via binding-defined checks
16
- - **Extend** with project-specific plugins (lifecycle hooks, prompt enhancement, custom guardrails)
17
- - **Adapt** to any SDK through a pluggable adapter interface
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
- ## Architecture
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)
@@ -27,7 +155,7 @@ agent-contracts.yaml (DSL) bindings/runtime.yaml (guardrail impl)
27
155
  ├── agent/generated/agents.ts (AgentContract + registry)
28
156
  ├── agent/generated/tasks.ts (TaskContract + registry)
29
157
  ├── agent/generated/workflows.ts (WorkflowContract + registry)
30
- ├── agent/generated/handoffs.ts (Zod schemas + registry)
158
+ ├── agent/generated/handoffs.ts (Zod schemas + registry + factories)
31
159
  ├── agent/generated/index.ts (barrel re-export)
32
160
  ├── agent/generated/hooks/guardrails.ts (check functions)
33
161
  ├── agent/generated/hooks/index.ts (unified hook adapter)
@@ -41,6 +169,7 @@ agent-contracts.yaml (DSL) bindings/runtime.yaml (guardrail impl)
41
169
  ├── Plugin: beforeWorkflow
42
170
  ├── For each step:
43
171
  │ ├── Plugin: beforeTask
172
+ │ ├── Plugin: contextEnhancer (enrich structured context)
44
173
  │ ├── Plugin: promptBuilder (full override) or default buildTaskPrompt
45
174
  │ ├── Plugin: promptEnhancer (post-process)
46
175
  │ ├── SDK Adapter: send prompt to LLM
@@ -57,79 +186,42 @@ agent-contracts.yaml (DSL) bindings/runtime.yaml (guardrail impl)
57
186
 
58
187
  | Layer | Path | Owner | Description |
59
188
  |-------|------|-------|-------------|
60
- | **Generated** | `agent/generated/` | Auto-generated | DSL-derived contracts and hooks. Never edit manually. |
189
+ | **Generated** | `agent/generated/` | Auto-generated | DSL-derived contracts, handoff factories, and hooks. Never edit manually. |
61
190
  | **User code** | `agent/src/` | You | Plugins, project guardrails, interceptors. |
62
191
  | **Runtime** | `node_modules/agent-contracts-runtime/` | npm package | Workflow runner, task runner, SDK adapters, generator. |
63
192
 
64
- ## Install
193
+ ## Generated contracts
65
194
 
66
- ```bash
67
- npm install agent-contracts-runtime
68
- npm install -D agent-contracts
69
- ```
70
-
71
- ## Quick start
72
-
73
- ```bash
74
- # 1. Initialize project scaffolding
75
- agent-runtime init
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.
76
196
 
77
- # 2. Validate and lint your DSL
78
- agent-contracts validate
79
- agent-contracts lint --strict
197
+ ### Two-phase generation
80
198
 
81
- # 3. Generate contracts and hooks
82
- agent-runtime generate
199
+ | Phase | Input | Output | Description |
200
+ |-------|-------|--------|-------------|
201
+ | **1. Contracts** | DSL (`agents`, `tasks`, `workflow`, `handoff_types`) | `agents.ts`, `tasks.ts`, `workflows.ts`, `handoffs.ts`, `index.ts` | Typed contract interfaces, registries, and handoff factories |
202
+ | **2. Guardrails** | DSL guardrails + binding `guardrail_impl` + active policy | `hooks/guardrails.ts`, `hooks/index.ts` | Check functions for command, file path, file content |
83
203
 
84
- # 4. Run a workflow
85
- agent-runtime run feature-implement "Add login endpoint with JWT"
204
+ Phase 2 requires a binding YAML (following the `agent-contracts` `SoftwareBinding` schema). If no bindings are configured, guardrail hooks are skipped.
86
205
 
87
- # 5. Verify project setup
88
- agent-runtime doctor
89
- ```
206
+ ### Handoff factories
90
207
 
91
- ## CLI
208
+ In addition to Zod schemas and type aliases, `handoffs.ts` generates type-safe factory functions for each handoff type:
92
209
 
93
- | Command | Description |
94
- |---------|-------------|
95
- | `agent-runtime init` | Initialize runtime scaffolding |
96
- | `agent-runtime generate` | Generate contracts and hooks from DSL |
97
- | `agent-runtime run <workflow> <request>` | Execute a workflow |
98
- | `agent-runtime list <resource>` | List workflows, tasks, or agents |
99
- | `agent-runtime show-prompt <task>` | Display the generated prompt for a task |
100
- | `agent-runtime doctor` | Verify configuration and connectivity |
101
- | `agent-runtime replay <run-dir>` | Replay a past execution |
102
-
103
- Key options:
210
+ ```typescript
211
+ import { handoffs } from "./agent/generated";
104
212
 
105
- ```bash
106
- agent-runtime generate --check # CI: verify generated files are up to date
107
- agent-runtime generate --clean # Delete and regenerate
108
- agent-runtime generate -t ./my-tpl # Use custom Handlebars templates
109
- agent-runtime run ... --dry-run # Simulate without calling SDK
110
- agent-runtime run ... --adapter mock # Use mock adapter for testing
111
- agent-runtime show-prompt plan-and-implement # Preview prompt
112
- agent-runtime show-prompt audit-tests -u "Check test quality" # With custom request
113
- agent-runtime show-prompt plan-and-implement --format json # JSON output
114
- agent-runtime show-prompt plan-and-implement --with-plugins # Apply plugin enhancers
213
+ const envelope = handoffs.featureImplementationRequest({
214
+ objective: "Add login endpoint with JWT",
215
+ inputs: { repository: "." },
216
+ expectedOutputs: ["implementation-diff"],
217
+ completionCriteria: ["tests_passed"],
218
+ });
219
+ // => { type: "feature-implementation-request", version: 1, payload: { ... } }
115
220
  ```
116
221
 
117
- For full CLI reference with exit codes and output schemas, see [docs/cli-reference.md](docs/cli-reference.md).
222
+ The factory validates the payload against the Zod schema at construction time, catching type errors before the workflow starts.
118
223
 
119
- The CLI specification is managed contract-first via [`cli-contracts`](https://www.npmjs.com/package/cli-contracts) in [`cli-contract.yaml`](cli-contract.yaml).
120
-
121
- ## Code generation
122
-
123
- The `generate` command reads your `agent-contracts.yaml` DSL and optional binding YAML files, then produces TypeScript contracts and guardrail hooks using Handlebars templates.
124
-
125
- ### Two-phase generation
126
-
127
- | Phase | Input | Output | Description |
128
- |-------|-------|--------|-------------|
129
- | **1. Contracts** | DSL (`agents`, `tasks`, `workflow`, `handoff_types`) | `agents.ts`, `tasks.ts`, `workflows.ts`, `handoffs.ts`, `index.ts` | Typed contract interfaces + registries |
130
- | **2. Guardrails** | DSL guardrails + binding `guardrail_impl` + active policy | `hooks/guardrails.ts`, `hooks/index.ts` | Check functions for command, file path, file content |
131
-
132
- Phase 2 requires a binding YAML (following the `agent-contracts` `SoftwareBinding` schema). If no bindings are configured, guardrail hooks are skipped.
224
+ YAML invocation files use the DSL-defined field names (snake_case). Generated TypeScript factories and APIs use camelCase.
133
225
 
134
226
  ### Custom templates
135
227
 
@@ -141,31 +233,7 @@ agent-runtime generate --templates ./my-templates
141
233
 
142
234
  Or set `templates_dir` in `agent-runtime.config.yaml`.
143
235
 
144
- ### Binding file
145
-
146
- Binding files define how DSL guardrails are implemented with concrete matchers:
147
-
148
- ```yaml
149
- # bindings/runtime.yaml
150
- software: agent-runtime
151
- version: 1
152
-
153
- guardrail_impl:
154
- no-force-push:
155
- checks:
156
- - matcher:
157
- type: command_regex
158
- pattern: "(^|[|;&]\\s*)git\\s+push\\s.*(--force|-f)\\b"
159
- message: "Force push is forbidden."
160
- block-env-files:
161
- checks:
162
- - matcher:
163
- type: file_glob
164
- pattern: "**/{.env,.env.*}"
165
- message: "Writing to .env file is blocked."
166
- ```
167
-
168
- ### Programmatic API
236
+ ### Programmatic generation API
169
237
 
170
238
  ```typescript
171
239
  import { generate, checkFreshness } from "agent-contracts-runtime/generator";
@@ -181,7 +249,54 @@ const isFresh = await checkFreshness("./agent-runtime.config.yaml");
181
249
 
182
250
  ## Programmatic API
183
251
 
184
- ### Run a workflow
252
+ The runtime provides three API levels:
253
+
254
+ | API | Use case | Input |
255
+ |-----|----------|-------|
256
+ | **Simple API** | Ad-hoc CLI-style invocation | `user_request: string` |
257
+ | **Structured API** | Application integration, CI | `WorkflowInvocation` with typed handoff |
258
+ | **Builder API** | Fluent programmatic usage | `createRuntime` → chained methods |
259
+
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:
185
300
 
186
301
  ```typescript
187
302
  import { runWorkflow } from "agent-contracts-runtime";
@@ -195,19 +310,102 @@ const adapter = await CursorSdkAdapter.create({
195
310
 
196
311
  const result = await runWorkflow(adapter, "feature-implement", {
197
312
  user_request: "Add login endpoint with JWT",
198
- maxFollowUps: 3, // override lightweight recovery attempts (default: 2)
199
- maxRetries: 1, // override heavyweight retry attempts (default: from DSL step.max_retries)
313
+ maxFollowUps: 3,
314
+ maxRetries: 1,
315
+ });
316
+
317
+ console.log(`${result.workflow_id}: ${result.status} (${result.total_elapsed_ms}ms)`);
318
+ ```
200
319
 
201
- onStepComplete: (event) => {
202
- console.log(`Step ${event.step_index + 1}: ${event.task_id} -> ${event.outcome_status}`);
320
+ For production integration, prefer the Structured API or Builder API so that input handoffs are validated before execution.
321
+
322
+ ### Structured API
323
+
324
+ Use `WorkflowInvocation` for typed handoff input with Zod validation on both input and output:
325
+
326
+ ```typescript
327
+ import { runWorkflow } from "agent-contracts-runtime";
328
+ import { handoffs } from "./agent/generated";
329
+
330
+ const result = await runWorkflow(adapter, {
331
+ workflow: "feature-implement",
332
+
333
+ handoff: handoffs.featureImplementationRequest({
334
+ objective: "Add login endpoint with JWT",
335
+ inputs: {
336
+ repository: ".",
337
+ apiSpec: "./docs/openapi.yaml",
338
+ },
339
+ constraints: {
340
+ allowedPaths: ["src/**", "test/**"],
341
+ deniedPaths: ["infra/**"],
342
+ },
343
+ expectedOutputs: ["implementation-diff", "test-report"],
344
+ completionCriteria: ["tests_passed", "review_approved"],
345
+ }),
346
+
347
+ runtime: {
348
+ maxFollowUps: 3,
349
+ maxRetries: 1,
203
350
  },
204
351
 
205
- onGate: async (gateKind, description) => {
206
- return true; // approve
352
+ hooks: {
353
+ onGate: async (gateKind, description) => true,
207
354
  },
208
355
  });
356
+ ```
209
357
 
210
- console.log(`${result.workflow_id}: ${result.status} (${result.total_elapsed_ms}ms)`);
358
+ The `WorkflowInvocation` envelope is SDK-independent. SDK-specific options belong on the adapter constructor:
359
+
360
+ ```typescript
361
+ const adapter = await CursorSdkAdapter.create({
362
+ apiKey: process.env.CURSOR_API_KEY!,
363
+ model: "composer-2",
364
+ cwd: process.cwd(),
365
+ });
366
+ ```
367
+
368
+ ### Builder API
369
+
370
+ For fluent programmatic usage:
371
+
372
+ ```typescript
373
+ import { createRuntime } from "agent-contracts-runtime";
374
+ import { CursorSdkAdapter } from "agent-contracts-runtime/adapters/cursor-sdk";
375
+ import { handoffs } from "./agent/generated";
376
+
377
+ const adapter = await CursorSdkAdapter.create({
378
+ apiKey: process.env.CURSOR_API_KEY!,
379
+ model: "composer-2",
380
+ cwd: process.cwd(),
381
+ });
382
+
383
+ const runtime = createRuntime({ adapter });
384
+
385
+ const result = await runtime
386
+ .workflow("feature-implement")
387
+ .handoff(handoffs.featureImplementationRequest({
388
+ objective: "Add login endpoint with JWT",
389
+ inputs: { repository: "." },
390
+ expectedOutputs: ["implementation-diff"],
391
+ completionCriteria: ["tests_passed"],
392
+ }))
393
+ .maxFollowUps(3)
394
+ .maxRetries(1)
395
+ .onStepComplete((event) => {
396
+ console.log(event.task_id, event.outcome_status);
397
+ })
398
+ .onGate(async () => true)
399
+ .run();
400
+ ```
401
+
402
+ The builder can also accept a plain string for quick usage:
403
+
404
+ ```typescript
405
+ const result = await runtime
406
+ .workflow("feature-implement")
407
+ .request("Add login endpoint with JWT")
408
+ .run();
211
409
  ```
212
410
 
213
411
  ### Run a single task
@@ -228,7 +426,143 @@ if (result.outcome.status === "success") {
228
426
  }
229
427
  ```
230
428
 
231
- ### Recovery: followUp vs retry
429
+ ### Workflow result
430
+
431
+ ```typescript
432
+ type WorkflowResult = {
433
+ workflow_id: string;
434
+ status: "success" | "failed" | "escalation" | "cancelled";
435
+ steps: StepResult[];
436
+ final_handoff?: HandoffEnvelope;
437
+ total_elapsed_ms: number;
438
+ run_dir?: string;
439
+ };
440
+ ```
441
+
442
+ Each step result includes task ID, outcome status, validation errors, follow-up count, retry count, and elapsed time.
443
+
444
+ ## CLI
445
+
446
+ | Command | Description |
447
+ |---------|-------------|
448
+ | `agent-runtime init` | Initialize runtime scaffolding |
449
+ | `agent-runtime generate` | Generate contracts and hooks from DSL |
450
+ | `agent-runtime run <workflow> <request>` | Execute a workflow |
451
+ | `agent-runtime run --file <path>` | Execute from a YAML invocation file |
452
+ | `agent-runtime list <resource>` | List workflows, tasks, or agents |
453
+ | `agent-runtime show-prompt <task>` | Display the generated prompt for a task |
454
+ | `agent-runtime doctor` | Verify configuration and connectivity |
455
+ | `agent-runtime replay <run-dir>` | Replay a recorded local execution for debugging |
456
+
457
+ Key options:
458
+
459
+ ```bash
460
+ agent-runtime generate --check # CI: verify generated files are up to date
461
+ agent-runtime generate --clean # Delete and regenerate
462
+ agent-runtime generate -t ./my-tpl # Use custom Handlebars templates
463
+ agent-runtime run ... --dry-run # Simulate without calling SDK
464
+ agent-runtime run ... --adapter mock # Use mock adapter for testing
465
+ agent-runtime run --file ./invocation.yaml # Run from YAML manifest
466
+ agent-runtime show-prompt plan-and-implement # Preview prompt
467
+ agent-runtime show-prompt audit-tests -u "Check test quality" # With custom request
468
+ agent-runtime show-prompt plan-and-implement --format json # JSON output
469
+ agent-runtime show-prompt plan-and-implement --with-plugins # Apply plugin enhancers
470
+ ```
471
+
472
+ ### YAML invocation file
473
+
474
+ For CI or programmatic invocation, define the full request as a YAML file:
475
+
476
+ ```yaml
477
+ # invocation.yaml
478
+ workflow: feature-implement
479
+ handoff:
480
+ type: feature-implementation-request
481
+ payload:
482
+ objective: Add login endpoint with JWT
483
+ inputs:
484
+ repository: .
485
+ expected_outputs:
486
+ - implementation-diff
487
+ completion_criteria:
488
+ - tests_passed
489
+ runtime:
490
+ max_follow_ups: 3
491
+ max_retries: 1
492
+ ```
493
+
494
+ ```bash
495
+ agent-runtime run --file ./invocation.yaml --adapter cursor
496
+ ```
497
+
498
+ For full CLI reference with exit codes and output schemas, see [docs/cli-reference.md](docs/cli-reference.md).
499
+
500
+ The CLI specification is managed contract-first via [`cli-contracts`](https://www.npmjs.com/package/cli-contracts) in [`cli-contract.yaml`](cli-contract.yaml).
501
+
502
+ ## SDK adapters
503
+
504
+ | Adapter | SDK | Status |
505
+ |---------|-----|--------|
506
+ | `cursor` | Cursor Cloud Agents (`@cursor/sdk`) | Implemented |
507
+ | `claude` | Claude Agent SDK (`@anthropic-ai/claude-agent-sdk`) | Stub |
508
+ | `openai` | OpenAI Agents SDK | Planned |
509
+ | `mock` | Simulated responses for testing/demo | Implemented |
510
+
511
+ ### Adapter interface
512
+
513
+ The minimal adapter interface requires only `send`:
514
+
515
+ ```typescript
516
+ interface SdkAdapter {
517
+ send(prompt: string, options: AdapterSendOptions): Promise<string>;
518
+ followUp?(message: string): Promise<string>;
519
+ }
520
+ ```
521
+
522
+ For adapters that need full contract context, implement `sendExecution`:
523
+
524
+ ```typescript
525
+ interface SdkAdapter {
526
+ send(prompt: string, options: AdapterSendOptions): Promise<string>;
527
+ followUp?(message: string): Promise<string>;
528
+ sendExecution?(request: AgentExecutionRequest): Promise<string>;
529
+ }
530
+ ```
531
+
532
+ 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.
533
+
534
+ ### Choosing adapter methods
535
+
536
+ | Method | Use when |
537
+ |--------|----------|
538
+ | `send(prompt, options)` | Your SDK only needs a prompt string |
539
+ | `sendExecution(request)` | Your SDK needs agent/task IDs, handoff metadata, schema info, tools, or context |
540
+ | `followUp(message)` | Your SDK supports continuing the same session after validation errors |
541
+
542
+ Adapters may start with `send` and later upgrade to `sendExecution` without changing workflow code.
543
+
544
+ SDK-specific options belong on the adapter constructor, not on the shared interface:
545
+
546
+ ```typescript
547
+ const adapter = await CursorSdkAdapter.create({
548
+ apiKey: process.env.CURSOR_API_KEY!,
549
+ model: "composer-2",
550
+ cwd: process.cwd(),
551
+ guardrailHooks,
552
+ });
553
+ ```
554
+
555
+ ## Handoff validation
556
+
557
+ The runtime validates both input and output handoffs against generated Zod schemas.
558
+
559
+ Input validation happens when a `WorkflowInvocation` includes a typed handoff (Structured API or Builder API). The handoff factory validates the payload at construction time.
560
+
561
+ 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.
562
+
563
+ If validation fails, the runtime attempts a followUp (lightweight, same session) to correct the output format before falling back to a full retry.
564
+
565
+ ## Follow-up and retry
232
566
 
233
567
  | | followUp | retry |
234
568
  |---|---|---|
@@ -239,7 +573,6 @@ if (result.outcome.status === "success") {
239
573
  | **DSL mapping** | Independent (always available) | `step.max_retries` in workflow DSL |
240
574
  | **Trigger** | Zod schema validation error | Empty output, or `decideRetryStrategy` |
241
575
  | **Session** | Same session continues | New session |
242
- | **Override** | `WorkflowRunOptions.maxFollowUps` | `WorkflowRunOptions.maxRetries` |
243
576
 
244
577
  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.
245
578
 
@@ -256,35 +589,15 @@ const result = await runTask(adapter, "plan-and-implement", {
256
589
  });
257
590
  ```
258
591
 
259
- ### Register a plugin
260
-
261
- ```typescript
262
- import { pluginRegistry, type AgentPlugin } from "agent-contracts-runtime";
263
-
264
- const myPlugin: AgentPlugin = {
265
- id: "my-plugin",
266
- async beforeTask(taskId, context) {
267
- return context; // return null to skip
268
- },
269
- async afterTask(taskId, outcome) {
270
- return outcome;
271
- },
272
- promptEnhancer(taskId, prompt) {
273
- return prompt + "\n\nAlways write tests first.";
274
- },
275
- };
276
-
277
- pluginRegistry.register(myPlugin);
278
- ```
279
-
280
- ## Plugin system
592
+ ## Runtime hooks and plugins
281
593
 
282
- Plugins inject mechanical logic into DSL-defined workflows without modifying the DSL or the runtime engine.
594
+ Plugins let project code customize execution around DSL-defined workflows without changing the DSL or runtime core.
283
595
 
284
596
  ```typescript
285
597
  interface AgentPlugin {
286
598
  readonly id: string;
287
599
  beforeTask?(taskId: string, context: TaskContext): Promise<TaskContext | null>;
600
+ contextEnhancer?(taskId: string, context: TaskContext): TaskContext;
288
601
  afterTask?(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;
289
602
  promptEnhancer?(taskId: string, prompt: string, context: TaskContext): string;
290
603
  promptBuilder?(args: PromptBuilderArgs): string | null;
@@ -294,47 +607,86 @@ interface AgentPlugin {
294
607
  }
295
608
  ```
296
609
 
297
- ### Prompt customization hooks
610
+ ### Hook execution order
298
611
 
299
- Two hooks control what prompt is sent to the SDK agent:
612
+ ```
613
+ beforeWorkflow
614
+ ↓
615
+ beforeTask ← skip task (return null) or modify context
616
+ ↓
617
+ contextEnhancer ← enrich structured context (variables, handoff_input, etc.)
618
+ ↓
619
+ promptBuilder ← full prompt override, or null to use default
620
+ ↓
621
+ promptEnhancer ← lightweight post-processing on prompt string
622
+ ↓
623
+ SDK Adapter send
624
+ ↓
625
+ afterTask
626
+ ↓
627
+ afterWorkflow
628
+ ```
300
629
 
301
- | Hook | Purpose | Execution order |
302
- |------|---------|-----------------|
303
- | `promptBuilder` | Full prompt override. Return a string to replace the default prompt, or `null` to use the default. | 1st (before `promptEnhancer`) |
304
- | `promptEnhancer` | Lightweight post-processor. Receives the built prompt and returns a modified version. | 2nd (after `promptBuilder`) |
630
+ ### beforeTask vs contextEnhancer
631
+
632
+ | Hook | Purpose | Side effects |
633
+ |------|---------|--------------|
634
+ | `beforeTask` | Skip task (return `null`), replace context entirely, perform gating decisions | May have side effects |
635
+ | `contextEnhancer` | Add structured variables, paths, or metadata to context | Should be side-effect free |
636
+
637
+ ### Context vs prompt
305
638
 
306
- Example: custom prompt builder that injects project-specific context:
639
+ 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:
307
640
 
308
641
  ```typescript
309
- const customPromptPlugin: AgentPlugin = {
310
- id: "custom-prompt",
311
- promptBuilder({ agent, task, context, options }) {
312
- if (task.id === "plan-and-implement") {
313
- return buildTaskPrompt(agent, task, {
314
- ...context,
315
- prior_context: `${context.prior_context ?? ""}\n\nProject uses NestJS with TypeORM.`,
316
- }, options);
317
- }
318
- return null; // use default for other tasks
642
+ const contextPlugin: AgentPlugin = {
643
+ id: "context-enricher",
644
+ contextEnhancer(taskId, context) {
645
+ return {
646
+ ...context,
647
+ relevant_paths: ["src/auth/**", "src/middleware/**"],
648
+ variables: {
649
+ ...context.variables,
650
+ dbType: "PostgreSQL",
651
+ orm: "TypeORM",
652
+ },
653
+ };
319
654
  },
320
655
  };
321
656
  ```
322
657
 
323
- ## SDK adapters
658
+ ### Prompt customization hooks
324
659
 
325
- | Adapter | SDK | Status |
326
- |---------|-----|--------|
327
- | `cursor` | Cursor Cloud Agents (`@cursor/sdk`) | Implemented |
328
- | `claude` | Claude Agent SDK (`@anthropic-ai/claude-agent-sdk`) | Stub |
329
- | `openai` | OpenAI Agents SDK | Planned |
330
- | `mock` | Simulated responses for testing/demo | Implemented |
660
+ | Hook | Purpose | Execution order |
661
+ |------|---------|-----------------|
662
+ | `promptBuilder` | Full prompt override. Return a string to replace the default prompt, or `null` to use the default. | 1st (before `promptEnhancer`) |
663
+ | `promptEnhancer` | Lightweight post-processor. Receives the built prompt and returns a modified version. | 2nd (after `promptBuilder`) |
331
664
 
332
- The adapter interface is minimal:
665
+ ### Register a plugin
333
666
 
334
667
  ```typescript
335
- interface SdkAdapter {
336
- send(prompt: string, options: { readonly: boolean }): Promise<string>;
337
- }
668
+ import { pluginRegistry, type AgentPlugin } from "agent-contracts-runtime";
669
+
670
+ const myPlugin: AgentPlugin = {
671
+ id: "my-plugin",
672
+ async beforeTask(taskId, context) {
673
+ return context; // return null to skip
674
+ },
675
+ contextEnhancer(taskId, context) {
676
+ return {
677
+ ...context,
678
+ variables: { ...context.variables, projectFramework: "NestJS" },
679
+ };
680
+ },
681
+ async afterTask(taskId, outcome) {
682
+ return outcome;
683
+ },
684
+ promptEnhancer(taskId, prompt) {
685
+ return prompt + "\n\nAlways write tests first.";
686
+ },
687
+ };
688
+
689
+ pluginRegistry.register(myPlugin);
338
690
  ```
339
691
 
340
692
  ## Guardrails
@@ -348,7 +700,7 @@ Generated guardrail hooks (from DSL + binding) and plugin custom guardrails are
348
700
  | `block` | Deny the operation |
349
701
  | `warn` | Allow with warning (can fail with `fail_on_guardrail_warning`) |
350
702
  | `info` | Allow with informational context to user/agent |
351
- | `shadow` | Log only, no effect on execution |
703
+ | `shadow` | Report only, no effect on execution |
352
704
 
353
705
  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:
354
706
 
@@ -356,6 +708,28 @@ Guardrail checks are defined in binding YAML files (not in the DSL directly), fo
356
708
  - `file_glob` — Match file paths against glob patterns
357
709
  - `content_regex` — Match file content against regex patterns
358
710
 
711
+ ### Binding file
712
+
713
+ ```yaml
714
+ # bindings/runtime.yaml
715
+ software: agent-runtime
716
+ version: 1
717
+
718
+ guardrail_impl:
719
+ no-force-push:
720
+ checks:
721
+ - matcher:
722
+ type: command_regex
723
+ pattern: "(^|[|;&]\\s*)git\\s+push\\s.*(--force|-f)\\b"
724
+ message: "Force push is forbidden."
725
+ block-env-files:
726
+ checks:
727
+ - matcher:
728
+ type: file_glob
729
+ pattern: "**/{.env,.env.*}"
730
+ message: "Writing to .env file is blocked."
731
+ ```
732
+
359
733
  ## Configuration
360
734
 
361
735
  `agent-runtime.config.yaml`:
@@ -369,20 +743,12 @@ active_guardrail_policy: default # which guardrail_policy to activate
369
743
  templates_dir: ./custom-templates # optional, overrides built-in templates
370
744
  ```
371
745
 
372
- ## CI integration
373
-
374
- ```yaml
375
- - run: agent-contracts validate
376
- - run: agent-contracts lint --strict
377
- - run: agent-runtime generate --check
378
- - run: agent-runtime doctor
379
- ```
380
-
381
746
  ## Exports
382
747
 
383
748
  | Import path | Description |
384
749
  |-------------|-------------|
385
- | `agent-contracts-runtime` | Core runtime API (`runWorkflow`, `runTask`, `buildTaskPrompt`, `pluginRegistry`, `zodSchemaToPromptDescription`) |
750
+ | `agent-contracts-runtime` | Core runtime API (`runWorkflow`, `runTask`, `createRuntime`, `buildTaskPrompt`, `pluginRegistry`, `zodSchemaToPromptDescription`) |
751
+ | `agent-contracts-runtime` | Types (`WorkflowInvocation`, `HandoffInput`, `AgentExecutionRequest`, `WorkflowRegistries`, `SdkAdapter`, `AdapterSendOptions`, `TaskContext`, `TaskOutcome`, etc.) |
386
752
  | `agent-contracts-runtime/generator` | Generator API (`generate`, `checkFreshness`, `buildContractContext`) |
387
753
  | `agent-contracts-runtime/adapters/cursor-sdk` | Cursor SDK adapter |
388
754
  | `agent-contracts-runtime/adapters/claude-agent-sdk` | Claude Agent SDK adapter |