agent-contracts-runtime 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,23 +10,28 @@ It generates typed contracts, handoff validators, and guardrail hooks from your
10
10
  ## What it does
11
11
 
12
12
  - **Generate** typed TypeScript contracts, Zod handoff schemas, and guardrail hooks from `agent-contracts.yaml`
13
- - **Run** multi-step agent workflows with mechanical orchestration (retry, gate, escalation)
13
+ - **Run** multi-step agent workflows with mechanical orchestration (followUp, retry, gate, escalation)
14
14
  - **Validate** every LLM output against handoff schemas before proceeding to the next step
15
- - **Enforce** guardrails (command, file path, file content) before SDK execution
15
+ - **Enforce** guardrails (command, file path, file content) via binding-defined checks
16
16
  - **Extend** with project-specific plugins (lifecycle hooks, prompt enhancement, custom guardrails)
17
17
  - **Adapt** to any SDK through a pluggable adapter interface
18
18
 
19
19
  ## Architecture
20
20
 
21
21
  ```
22
- agent-contracts.yaml (SSoT)
22
+ agent-contracts.yaml (DSL) bindings/runtime.yaml (guardrail impl)
23
+ │ │
24
+ ▼ ▼
25
+ agent-runtime generate ──────────────┘
23
26
  │
24
- ▼
25
- agent-runtime generate
26
- │
27
- ├── agent/generated/contracts/ (agents, tasks, workflows, handoffs)
28
- ├── agent/generated/hooks/ (guardrails, SDK hook adapters)
29
- └── agent/generated/manifest.ts (DSL hash, generation metadata)
27
+ ├── agent/generated/agents.ts (AgentContract + registry)
28
+ ├── agent/generated/tasks.ts (TaskContract + registry)
29
+ ├── agent/generated/workflows.ts (WorkflowContract + registry)
30
+ ├── agent/generated/handoffs.ts (Zod schemas + registry)
31
+ ├── agent/generated/index.ts (barrel re-export)
32
+ ├── agent/generated/hooks/guardrails.ts (check functions)
33
+ ├── agent/generated/hooks/index.ts (unified hook adapter)
34
+ └── agent/generated/.manifest.json (DSL hash, metadata)
30
35
 
31
36
  agent/src/ (user plugins, project guardrails)
32
37
  │
@@ -39,8 +44,10 @@ agent-contracts.yaml (SSoT)
39
44
  │ ├── SDK Adapter: send prompt to LLM
40
45
  │ ├── Extract structured result (YAML/JSON)
41
46
  │ ├── Validate against Zod handoff schema
47
+ │ ├── followUp (lightweight, same session) on validation error
48
+ │ ├── retry (heavyweight, new session) on persistent failure
42
49
  │ ├── Plugin: afterTask
43
- │ └── Retry on validation failure
50
+ │ └── decideRetryStrategy callback for custom recovery logic
44
51
  └── Plugin: afterWorkflow
45
52
  ```
46
53
 
@@ -50,12 +57,13 @@ agent-contracts.yaml (SSoT)
50
57
  |-------|------|-------|-------------|
51
58
  | **Generated** | `agent/generated/` | Auto-generated | DSL-derived contracts and hooks. Never edit manually. |
52
59
  | **User code** | `agent/src/` | You | Plugins, project guardrails, interceptors. |
53
- | **Runtime** | `node_modules/agent-contracts-runtime/` | npm package | Workflow runner, task runner, SDK adapters. |
60
+ | **Runtime** | `node_modules/agent-contracts-runtime/` | npm package | Workflow runner, task runner, SDK adapters, generator. |
54
61
 
55
62
  ## Install
56
63
 
57
64
  ```bash
58
- npm install -D agent-contracts agent-contracts-runtime
65
+ npm install agent-contracts-runtime
66
+ npm install -D agent-contracts
59
67
  ```
60
68
 
61
69
  ## Quick start
@@ -92,16 +100,78 @@ agent-runtime doctor
92
100
  Key options:
93
101
 
94
102
  ```bash
95
- agent-runtime generate --check # CI: verify generated files are up to date
96
- agent-runtime generate --clean # Delete and regenerate
97
- agent-runtime run ... --dry-run # Simulate without calling SDK
98
- agent-runtime run ... --adapter mock # Use mock adapter for testing
103
+ agent-runtime generate --check # CI: verify generated files are up to date
104
+ agent-runtime generate --clean # Delete and regenerate
105
+ agent-runtime generate -t ./my-tpl # Use custom Handlebars templates
106
+ agent-runtime run ... --dry-run # Simulate without calling SDK
107
+ agent-runtime run ... --adapter mock # Use mock adapter for testing
99
108
  ```
100
109
 
101
110
  For full CLI reference with exit codes and output schemas, see [docs/cli-reference.md](docs/cli-reference.md).
102
111
 
103
112
  The CLI specification is managed contract-first via [`cli-contracts`](https://www.npmjs.com/package/cli-contracts) in [`cli-contract.yaml`](cli-contract.yaml).
104
113
 
114
+ ## Code generation
115
+
116
+ The `generate` command reads your `agent-contracts.yaml` DSL and optional binding YAML files, then produces TypeScript contracts and guardrail hooks using Handlebars templates.
117
+
118
+ ### Two-phase generation
119
+
120
+ | Phase | Input | Output | Description |
121
+ |-------|-------|--------|-------------|
122
+ | **1. Contracts** | DSL (`agents`, `tasks`, `workflow`, `handoff_types`) | `agents.ts`, `tasks.ts`, `workflows.ts`, `handoffs.ts`, `index.ts` | Typed contract interfaces + registries |
123
+ | **2. Guardrails** | DSL guardrails + binding `guardrail_impl` + active policy | `hooks/guardrails.ts`, `hooks/index.ts` | Check functions for command, file path, file content |
124
+
125
+ Phase 2 requires a binding YAML (following the `agent-contracts` `SoftwareBinding` schema). If no bindings are configured, guardrail hooks are skipped.
126
+
127
+ ### Custom templates
128
+
129
+ Override any built-in Handlebars template by placing a file with the same name in a custom templates directory:
130
+
131
+ ```bash
132
+ agent-runtime generate --templates ./my-templates
133
+ ```
134
+
135
+ Or set `templates_dir` in `agent-runtime.config.yaml`.
136
+
137
+ ### Binding file
138
+
139
+ Binding files define how DSL guardrails are implemented with concrete matchers:
140
+
141
+ ```yaml
142
+ # bindings/runtime.yaml
143
+ software: agent-runtime
144
+ version: 1
145
+
146
+ guardrail_impl:
147
+ no-force-push:
148
+ checks:
149
+ - matcher:
150
+ type: command_regex
151
+ pattern: "(^|[|;&]\\s*)git\\s+push\\s.*(--force|-f)\\b"
152
+ message: "Force push is forbidden."
153
+ block-env-files:
154
+ checks:
155
+ - matcher:
156
+ type: file_glob
157
+ pattern: "**/{.env,.env.*}"
158
+ message: "Writing to .env file is blocked."
159
+ ```
160
+
161
+ ### Programmatic API
162
+
163
+ ```typescript
164
+ import { generate, checkFreshness } from "agent-contracts-runtime/generator";
165
+
166
+ const result = await generate({
167
+ configPath: "./agent-runtime.config.yaml",
168
+ clean: true,
169
+ });
170
+ console.log(result.filesGenerated);
171
+
172
+ const isFresh = await checkFreshness("./agent-runtime.config.yaml");
173
+ ```
174
+
105
175
  ## Programmatic API
106
176
 
107
177
  ### Run a workflow
@@ -136,19 +206,43 @@ console.log(`${result.workflow_id}: ${result.status} (${result.total_elapsed_ms}
136
206
  ```typescript
137
207
  import { runTask } from "agent-contracts-runtime";
138
208
 
139
- const outcome = await runTask(adapter, "run-tests", {
209
+ const result = await runTask(adapter, "run-tests", {
140
210
  user_request: "Run all tests and report results",
141
211
  });
142
212
 
143
- if (outcome.status === "success") {
144
- console.log("Completed:", outcome.data);
145
- } else if (outcome.status === "validation_error") {
146
- console.error("Schema mismatch:", outcome.errors.message);
147
- } else if (outcome.status === "escalation") {
148
- console.warn("Escalation:", outcome.reason);
213
+ if (result.outcome.status === "success") {
214
+ console.log("Completed:", result.outcome.data);
215
+ } else if (result.outcome.status === "validation_error") {
216
+ console.error("Schema mismatch — followUps used:", result.follow_ups_used);
217
+ } else if (result.outcome.status === "escalation") {
218
+ console.warn("Escalation:", result.outcome.reason);
149
219
  }
150
220
  ```
151
221
 
222
+ ### Recovery: followUp vs retry
223
+
224
+ | | followUp | retry |
225
+ |---|---|---|
226
+ | **Method** | `adapter.followUp()` | `adapter.send()` |
227
+ | **Cost** | Lightweight | Heavy |
228
+ | **Use case** | Output format correction | Full task re-execution |
229
+ | **Default limit** | `maxFollowUps: 2` | `maxRetries: 0` (opt-in) |
230
+ | **Trigger** | Zod schema validation error | Empty output, or `decideRetryStrategy` |
231
+ | **Session** | Same session continues | New session |
232
+
233
+ Inject custom recovery logic via `decideRetryStrategy`:
234
+
235
+ ```typescript
236
+ const result = await runTask(adapter, "plan-and-implement", {
237
+ user_request: "Add login",
238
+ decideRetryStrategy: async (outcome, attempt) => {
239
+ if (attempt >= 2) return "abort";
240
+ if (outcome.status === "validation_error") return "follow_up";
241
+ return "retry";
242
+ },
243
+ });
244
+ ```
245
+
152
246
  ### Register a plugin
153
247
 
154
248
  ```typescript
@@ -186,14 +280,6 @@ interface AgentPlugin {
186
280
  }
187
281
  ```
188
282
 
189
- Built-in sample plugins:
190
-
191
- | Plugin | Purpose |
192
- |--------|---------|
193
- | `observability` | Emit structured events for workflow/task lifecycle |
194
- | `project-guardrails` | Block dangerous packages, protect migration files |
195
- | `test-enforcer` | Require test files in implementation task results |
196
-
197
283
  ## SDK adapters
198
284
 
199
285
  | Adapter | SDK | Status |
@@ -215,35 +301,32 @@ interface SdkAdapter {
215
301
 
216
302
  Guardrails evaluate commands, file paths, and file content before execution.
217
303
 
218
- DSL-generated guardrails and plugin custom guardrails are merged and evaluated together, producing one of four actions:
304
+ Generated guardrail hooks (from DSL + binding) and plugin custom guardrails are merged and evaluated together, producing one of four actions:
219
305
 
220
306
  | Action | Effect |
221
307
  |--------|--------|
222
308
  | `block` | Deny the operation |
223
309
  | `warn` | Allow with warning (can fail with `fail_on_guardrail_warning`) |
224
- | `info` | Allow with informational context |
310
+ | `info` | Allow with informational context to user/agent |
225
311
  | `shadow` | Log only, no effect on execution |
226
312
 
313
+ 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:
314
+
315
+ - `command_regex` — Match shell commands against regex patterns
316
+ - `file_glob` — Match file paths against glob patterns
317
+ - `content_regex` — Match file content against regex patterns
318
+
227
319
  ## Configuration
228
320
 
229
321
  `agent-runtime.config.yaml`:
230
322
 
231
323
  ```yaml
232
- contracts:
233
- dsl: ./agent-contracts.yaml
234
- generated_dir: ./agent/generated
235
-
236
- runtime:
237
- adapter: cursor
238
- plugins: ./agent/src/plugins/index.ts
239
-
240
- execution:
241
- default_max_retries: 2
242
- require_structured_output: true
243
-
244
- observability:
245
- provider: local
246
- output_dir: ./.agent-runs
324
+ dsl: ./agent-contracts.yaml
325
+ generated_dir: ./agent/generated # default: ./agent/generated
326
+ bindings: # optional, for guardrail hook generation
327
+ - ./bindings/runtime.yaml
328
+ active_guardrail_policy: default # which guardrail_policy to activate
329
+ templates_dir: ./custom-templates # optional, overrides built-in templates
247
330
  ```
248
331
 
249
332
  ## CI integration
@@ -255,11 +338,21 @@ observability:
255
338
  - run: agent-runtime doctor
256
339
  ```
257
340
 
341
+ ## Exports
342
+
343
+ | Import path | Description |
344
+ |-------------|-------------|
345
+ | `agent-contracts-runtime` | Core runtime API (`runWorkflow`, `runTask`, `pluginRegistry`) |
346
+ | `agent-contracts-runtime/generator` | Generator API (`generate`, `checkFreshness`, `buildContractContext`) |
347
+ | `agent-contracts-runtime/adapters/cursor-sdk` | Cursor SDK adapter |
348
+ | `agent-contracts-runtime/adapters/claude-agent-sdk` | Claude Agent SDK adapter |
349
+ | `agent-contracts-runtime/adapters/mock` | Mock adapter for testing |
350
+
258
351
  ## Requirements
259
352
 
260
353
  - Node.js 20+
261
354
  - TypeScript 5.x (ESM, strict mode)
262
- - `agent-contracts` (peer dependency)
355
+ - `agent-contracts` (optional peer dependency for DSL resolution)
263
356
 
264
357
  ## License
265
358
 
package/cli-contract.yaml CHANGED
@@ -122,6 +122,12 @@ commandSets:
122
122
  type: boolean
123
123
  default: false
124
124
 
125
+ - name: templates
126
+ aliases: [t]
127
+ description: Custom templates directory. Overrides built-in templates.
128
+ schema:
129
+ type: string
130
+
125
131
  exits:
126
132
  "0":
127
133
  description: Generation completed successfully (or --check found no differences).