agent-contracts-runtime 0.6.0 → 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.
Files changed (2) hide show
  1. package/README.md +383 -250
  2. 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) 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, handoff factories, 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, handoff factory functions, and guardrail hooks from `agent-contracts.yaml`
13
- - **Run** multi-step agent workflows with mechanical orchestration (followUp, retry, gate, escalation)
14
- - **Validate** both input and output handoffs against Zod schemas before proceeding
15
- - **Enforce** guardrails (command, file path, file content) via binding-defined checks
16
- - **Extend** with project-specific plugins (lifecycle hooks, context enhancement, prompt customization, 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.
18
62
 
19
- ## Architecture
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
105
+
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
- ## Install
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
- ### Generated handoff factories
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
- expected_outputs: ["implementation-diff"],
190
- completion_criteria: ["tests_passed"],
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
- ### Binding file
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 for different use cases:
252
+ The runtime provides three API levels:
248
253
 
249
254
  | API | Use case | Input |
250
255
  |-----|----------|-------|
251
- | **Simple API** | CLI, PoC, quick scripts | `user_request: string` |
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
- ### 1. Simple API
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,14 @@ const result = await runWorkflow(adapter, "feature-implement", {
268
312
  user_request: "Add login endpoint with JWT",
269
313
  maxFollowUps: 3,
270
314
  maxRetries: 1,
271
-
272
- onStepComplete: (event) => {
273
- console.log(`Step ${event.step_index + 1}: ${event.task_id} -> ${event.outcome_status}`);
274
- },
275
-
276
- onGate: async (gateKind, description) => {
277
- return true;
278
- },
279
315
  });
280
316
 
281
317
  console.log(`${result.workflow_id}: ${result.status} (${result.total_elapsed_ms}ms)`);
282
318
  ```
283
319
 
284
- ### 2. Structured API
320
+ For production integration, prefer the Structured API or Builder API so that input handoffs are validated before execution.
321
+
322
+ ### Structured API
285
323
 
286
324
  Use `WorkflowInvocation` for typed handoff input with Zod validation on both input and output:
287
325
 
@@ -317,7 +355,7 @@ const result = await runWorkflow(adapter, {
317
355
  });
318
356
  ```
319
357
 
320
- The `WorkflowInvocation` envelope is SDK-independent. SDK-specific options (model, session mode, etc.) belong on the adapter constructor:
358
+ The `WorkflowInvocation` envelope is SDK-independent. SDK-specific options belong on the adapter constructor:
321
359
 
322
360
  ```typescript
323
361
  const adapter = await CursorSdkAdapter.create({
@@ -327,9 +365,9 @@ const adapter = await CursorSdkAdapter.create({
327
365
  });
328
366
  ```
329
367
 
330
- ### 3. Builder API
368
+ ### Builder API
331
369
 
332
- For the most natural programmatic experience, use `createRuntime` with method chaining:
370
+ For fluent programmatic usage:
333
371
 
334
372
  ```typescript
335
373
  import { createRuntime } from "agent-contracts-runtime";
@@ -388,7 +426,143 @@ if (result.outcome.status === "success") {
388
426
  }
389
427
  ```
390
428
 
391
- ### 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
392
566
 
393
567
  | | followUp | retry |
394
568
  |---|---|---|
@@ -399,7 +573,6 @@ if (result.outcome.status === "success") {
399
573
  | **DSL mapping** | Independent (always available) | `step.max_retries` in workflow DSL |
400
574
  | **Trigger** | Zod schema validation error | Empty output, or `decideRetryStrategy` |
401
575
  | **Session** | Same session continues | New session |
402
- | **Override** | `WorkflowRunOptions.maxFollowUps` | `WorkflowRunOptions.maxRetries` |
403
576
 
404
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.
405
578
 
@@ -416,36 +589,9 @@ const result = await runTask(adapter, "plan-and-implement", {
416
589
  });
417
590
  ```
418
591
 
419
- ### Register a plugin
592
+ ## Runtime hooks and plugins
420
593
 
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
447
-
448
- 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.
449
595
 
450
596
  ```typescript
451
597
  interface AgentPlugin {
@@ -481,6 +627,13 @@ afterTask
481
627
  afterWorkflow
482
628
  ```
483
629
 
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
+
484
637
  ### Context vs prompt
485
638
 
486
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:
@@ -509,64 +662,31 @@ const contextPlugin: AgentPlugin = {
509
662
  | `promptBuilder` | Full prompt override. Return a string to replace the default prompt, or `null` to use the default. | 1st (before `promptEnhancer`) |
510
663
  | `promptEnhancer` | Lightweight post-processor. Receives the built prompt and returns a modified version. | 2nd (after `promptBuilder`) |
511
664
 
512
- Example: custom prompt builder that injects project-specific context:
665
+ ### Register a plugin
513
666
 
514
667
  ```typescript
515
- const customPromptPlugin: AgentPlugin = {
516
- id: "custom-prompt",
517
- promptBuilder({ agent, task, context, options }) {
518
- if (task.id === "plan-and-implement") {
519
- return buildTaskPrompt(agent, task, {
520
- ...context,
521
- prior_context: `${context.prior_context ?? ""}\n\nProject uses NestJS with TypeORM.`,
522
- }, options);
523
- }
524
- return null; // use default for other tasks
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.";
525
686
  },
526
687
  };
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
688
 
542
- ```typescript
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
- });
689
+ pluginRegistry.register(myPlugin);
570
690
  ```
571
691
 
572
692
  ## Guardrails
@@ -580,7 +700,7 @@ Generated guardrail hooks (from DSL + binding) and plugin custom guardrails are
580
700
  | `block` | Deny the operation |
581
701
  | `warn` | Allow with warning (can fail with `fail_on_guardrail_warning`) |
582
702
  | `info` | Allow with informational context to user/agent |
583
- | `shadow` | Log only, no effect on execution |
703
+ | `shadow` | Report only, no effect on execution |
584
704
 
585
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:
586
706
 
@@ -588,6 +708,28 @@ Guardrail checks are defined in binding YAML files (not in the DSL directly), fo
588
708
  - `file_glob` — Match file paths against glob patterns
589
709
  - `content_regex` — Match file content against regex patterns
590
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
+
591
733
  ## Configuration
592
734
 
593
735
  `agent-runtime.config.yaml`:
@@ -601,15 +743,6 @@ active_guardrail_policy: default # which guardrail_policy to activate
601
743
  templates_dir: ./custom-templates # optional, overrides built-in templates
602
744
  ```
603
745
 
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
746
  ## Exports
614
747
 
615
748
  | Import path | Description |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-contracts-runtime",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "description": "Runtime bridge for executing agent-contracts workflows on Agent SDKs",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",