agent-contracts-runtime 0.1.0 → 0.3.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
  │
@@ -35,12 +40,16 @@ agent-contracts.yaml (SSoT)
35
40
  │
36
41
  ├── Plugin: beforeWorkflow
37
42
  ├── For each step:
38
- │ ├── Plugin: beforeTask / promptEnhancer
43
+ │ ├── Plugin: beforeTask
44
+ │ ├── Plugin: promptBuilder (full override) or default buildTaskPrompt
45
+ │ ├── Plugin: promptEnhancer (post-process)
39
46
  │ ├── SDK Adapter: send prompt to LLM
40
47
  │ ├── Extract structured result (YAML/JSON)
41
48
  │ ├── Validate against Zod handoff schema
49
+ │ ├── followUp (lightweight, same session) on validation error
50
+ │ ├── retry (heavyweight, new session) on persistent failure
42
51
  │ ├── Plugin: afterTask
43
- │ └── Retry on validation failure
52
+ │ └── decideRetryStrategy callback for custom recovery logic
44
53
  └── Plugin: afterWorkflow
45
54
  ```
46
55
 
@@ -50,12 +59,13 @@ agent-contracts.yaml (SSoT)
50
59
  |-------|------|-------|-------------|
51
60
  | **Generated** | `agent/generated/` | Auto-generated | DSL-derived contracts and hooks. Never edit manually. |
52
61
  | **User code** | `agent/src/` | You | Plugins, project guardrails, interceptors. |
53
- | **Runtime** | `node_modules/agent-contracts-runtime/` | npm package | Workflow runner, task runner, SDK adapters. |
62
+ | **Runtime** | `node_modules/agent-contracts-runtime/` | npm package | Workflow runner, task runner, SDK adapters, generator. |
54
63
 
55
64
  ## Install
56
65
 
57
66
  ```bash
58
- npm install -D agent-contracts agent-contracts-runtime
67
+ npm install agent-contracts-runtime
68
+ npm install -D agent-contracts
59
69
  ```
60
70
 
61
71
  ## Quick start
@@ -86,22 +96,89 @@ agent-runtime doctor
86
96
  | `agent-runtime generate` | Generate contracts and hooks from DSL |
87
97
  | `agent-runtime run <workflow> <request>` | Execute a workflow |
88
98
  | `agent-runtime list <resource>` | List workflows, tasks, or agents |
99
+ | `agent-runtime show-prompt <task>` | Display the generated prompt for a task |
89
100
  | `agent-runtime doctor` | Verify configuration and connectivity |
90
101
  | `agent-runtime replay <run-dir>` | Replay a past execution |
91
102
 
92
103
  Key options:
93
104
 
94
105
  ```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
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
99
115
  ```
100
116
 
101
117
  For full CLI reference with exit codes and output schemas, see [docs/cli-reference.md](docs/cli-reference.md).
102
118
 
103
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).
104
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.
133
+
134
+ ### Custom templates
135
+
136
+ Override any built-in Handlebars template by placing a file with the same name in a custom templates directory:
137
+
138
+ ```bash
139
+ agent-runtime generate --templates ./my-templates
140
+ ```
141
+
142
+ Or set `templates_dir` in `agent-runtime.config.yaml`.
143
+
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
169
+
170
+ ```typescript
171
+ import { generate, checkFreshness } from "agent-contracts-runtime/generator";
172
+
173
+ const result = await generate({
174
+ configPath: "./agent-runtime.config.yaml",
175
+ clean: true,
176
+ });
177
+ console.log(result.filesGenerated);
178
+
179
+ const isFresh = await checkFreshness("./agent-runtime.config.yaml");
180
+ ```
181
+
105
182
  ## Programmatic API
106
183
 
107
184
  ### Run a workflow
@@ -118,6 +195,8 @@ const adapter = await CursorSdkAdapter.create({
118
195
 
119
196
  const result = await runWorkflow(adapter, "feature-implement", {
120
197
  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)
121
200
 
122
201
  onStepComplete: (event) => {
123
202
  console.log(`Step ${event.step_index + 1}: ${event.task_id} -> ${event.outcome_status}`);
@@ -136,19 +215,47 @@ console.log(`${result.workflow_id}: ${result.status} (${result.total_elapsed_ms}
136
215
  ```typescript
137
216
  import { runTask } from "agent-contracts-runtime";
138
217
 
139
- const outcome = await runTask(adapter, "run-tests", {
218
+ const result = await runTask(adapter, "run-tests", {
140
219
  user_request: "Run all tests and report results",
141
220
  });
142
221
 
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);
222
+ if (result.outcome.status === "success") {
223
+ console.log("Completed:", result.outcome.data);
224
+ } else if (result.outcome.status === "validation_error") {
225
+ console.error("Schema mismatch — followUps used:", result.follow_ups_used);
226
+ } else if (result.outcome.status === "escalation") {
227
+ console.warn("Escalation:", result.outcome.reason);
149
228
  }
150
229
  ```
151
230
 
231
+ ### Recovery: followUp vs retry
232
+
233
+ | | followUp | retry |
234
+ |---|---|---|
235
+ | **Method** | `adapter.followUp()` | `adapter.send()` |
236
+ | **Cost** | Lightweight | Heavy |
237
+ | **Use case** | Output format correction | Full task re-execution |
238
+ | **Default limit** | `maxFollowUps: 2` | `maxRetries: 0` (opt-in) |
239
+ | **DSL mapping** | Independent (always available) | `step.max_retries` in workflow DSL |
240
+ | **Trigger** | Zod schema validation error | Empty output, or `decideRetryStrategy` |
241
+ | **Session** | Same session continues | New session |
242
+ | **Override** | `WorkflowRunOptions.maxFollowUps` | `WorkflowRunOptions.maxRetries` |
243
+
244
+ 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
+
246
+ Inject custom recovery logic via `decideRetryStrategy`:
247
+
248
+ ```typescript
249
+ const result = await runTask(adapter, "plan-and-implement", {
250
+ user_request: "Add login",
251
+ decideRetryStrategy: async (outcome, attempt) => {
252
+ if (attempt >= 2) return "abort";
253
+ if (outcome.status === "validation_error") return "follow_up";
254
+ return "retry";
255
+ },
256
+ });
257
+ ```
258
+
152
259
  ### Register a plugin
153
260
 
154
261
  ```typescript
@@ -180,19 +287,38 @@ interface AgentPlugin {
180
287
  beforeTask?(taskId: string, context: TaskContext): Promise<TaskContext | null>;
181
288
  afterTask?(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;
182
289
  promptEnhancer?(taskId: string, prompt: string, context: TaskContext): string;
290
+ promptBuilder?(args: PromptBuilderArgs): string | null;
183
291
  customGuardrails?: { /* evaluateCommand, evaluateFilePath, evaluateFileContent */ };
184
292
  beforeWorkflow?(workflowId: string, userRequest: string): Promise<void>;
185
293
  afterWorkflow?(workflowId: string, result: WorkflowResult): Promise<void>;
186
294
  }
187
295
  ```
188
296
 
189
- Built-in sample plugins:
297
+ ### Prompt customization hooks
298
+
299
+ Two hooks control what prompt is sent to the SDK agent:
300
+
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`) |
190
305
 
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 |
306
+ Example: custom prompt builder that injects project-specific context:
307
+
308
+ ```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
319
+ },
320
+ };
321
+ ```
196
322
 
197
323
  ## SDK adapters
198
324
 
@@ -215,35 +341,32 @@ interface SdkAdapter {
215
341
 
216
342
  Guardrails evaluate commands, file paths, and file content before execution.
217
343
 
218
- DSL-generated guardrails and plugin custom guardrails are merged and evaluated together, producing one of four actions:
344
+ Generated guardrail hooks (from DSL + binding) and plugin custom guardrails are merged and evaluated together, producing one of four actions:
219
345
 
220
346
  | Action | Effect |
221
347
  |--------|--------|
222
348
  | `block` | Deny the operation |
223
349
  | `warn` | Allow with warning (can fail with `fail_on_guardrail_warning`) |
224
- | `info` | Allow with informational context |
350
+ | `info` | Allow with informational context to user/agent |
225
351
  | `shadow` | Log only, no effect on execution |
226
352
 
353
+ 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
+
355
+ - `command_regex` — Match shell commands against regex patterns
356
+ - `file_glob` — Match file paths against glob patterns
357
+ - `content_regex` — Match file content against regex patterns
358
+
227
359
  ## Configuration
228
360
 
229
361
  `agent-runtime.config.yaml`:
230
362
 
231
363
  ```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
364
+ dsl: ./agent-contracts.yaml
365
+ generated_dir: ./agent/generated # default: ./agent/generated
366
+ bindings: # optional, for guardrail hook generation
367
+ - ./bindings/runtime.yaml
368
+ active_guardrail_policy: default # which guardrail_policy to activate
369
+ templates_dir: ./custom-templates # optional, overrides built-in templates
247
370
  ```
248
371
 
249
372
  ## CI integration
@@ -255,11 +378,21 @@ observability:
255
378
  - run: agent-runtime doctor
256
379
  ```
257
380
 
381
+ ## Exports
382
+
383
+ | Import path | Description |
384
+ |-------------|-------------|
385
+ | `agent-contracts-runtime` | Core runtime API (`runWorkflow`, `runTask`, `buildTaskPrompt`, `pluginRegistry`, `zodSchemaToPromptDescription`) |
386
+ | `agent-contracts-runtime/generator` | Generator API (`generate`, `checkFreshness`, `buildContractContext`) |
387
+ | `agent-contracts-runtime/adapters/cursor-sdk` | Cursor SDK adapter |
388
+ | `agent-contracts-runtime/adapters/claude-agent-sdk` | Claude Agent SDK adapter |
389
+ | `agent-contracts-runtime/adapters/mock` | Mock adapter for testing |
390
+
258
391
  ## Requirements
259
392
 
260
393
  - Node.js 20+
261
394
  - TypeScript 5.x (ESM, strict mode)
262
- - `agent-contracts` (peer dependency)
395
+ - `agent-contracts` (optional peer dependency for DSL resolution)
263
396
 
264
397
  ## License
265
398
 
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).
@@ -288,6 +294,65 @@ commandSets:
288
294
  idempotent: true
289
295
  sideEffects: []
290
296
 
297
+ # -----------------------------------------------------------------------
298
+ # show-prompt
299
+ # -----------------------------------------------------------------------
300
+ show-prompt:
301
+ summary: Display the generated prompt for a task.
302
+ description: |
303
+ Builds and displays the full prompt that would be sent to an SDK agent
304
+ for a given task. Useful for inspecting, debugging, and validating
305
+ prompt content before execution.
306
+
307
+ Shows the agent role, responsibilities, constraints, task details,
308
+ completion criteria, handoff schema fields, and output format example.
309
+ arguments:
310
+ - name: task-id
311
+ required: true
312
+ description: ID of the task to show the prompt for (e.g. plan-and-implement, audit-tests).
313
+ schema:
314
+ type: string
315
+
316
+ options:
317
+ - name: user-request
318
+ aliases: [u]
319
+ description: User request text to include in the prompt preview.
320
+ schema:
321
+ type: string
322
+ default: "(preview)"
323
+
324
+ - name: format
325
+ description: Output format.
326
+ schema:
327
+ type: string
328
+ enum: [markdown, raw, json]
329
+ default: markdown
330
+
331
+ - name: with-plugins
332
+ description: Apply registered plugin prompt enhancers to the output.
333
+ schema:
334
+ type: boolean
335
+ default: false
336
+
337
+ exits:
338
+ "0":
339
+ description: Prompt displayed successfully.
340
+ stdout:
341
+ format: json
342
+ schema:
343
+ $ref: "#/components/schemas/ShowPromptResult"
344
+
345
+ "1":
346
+ description: Failed to build prompt (unknown task, missing contracts, etc.).
347
+ stderr:
348
+ format: text
349
+
350
+ x-agent:
351
+ riskLevel: none
352
+ requiresConfirmation: false
353
+ idempotent: true
354
+ sideEffects: []
355
+
291
356
  # -----------------------------------------------------------------------
292
357
  # doctor
293
358
  # -----------------------------------------------------------------------
@@ -503,6 +568,29 @@ components:
503
568
  description:
504
569
  type: string
505
570
 
571
+ # -------------------------------------------------------------------------
572
+ # show-prompt
573
+ # -------------------------------------------------------------------------
574
+ ShowPromptResult:
575
+ type: object
576
+ required: [task_id, agent_id, prompt]
577
+ properties:
578
+ task_id:
579
+ type: string
580
+ description: The task ID used to build the prompt.
581
+ agent_id:
582
+ type: string
583
+ description: The target agent ID for this task.
584
+ prompt:
585
+ type: string
586
+ description: The full generated prompt text.
587
+ handoff_schema:
588
+ type: string
589
+ description: The handoff schema ID for the task result.
590
+ plugins_applied:
591
+ type: boolean
592
+ description: Whether plugin prompt enhancers were applied.
593
+
506
594
  # -------------------------------------------------------------------------
507
595
  # doctor
508
596
  # -------------------------------------------------------------------------
@@ -1,4 +1,4 @@
1
- import { S as SdkAdapter } from '../task-runner-CuYWldNc.js';
1
+ import { S as SdkAdapter } from '../task-runner-MQO5VR1Y.js';
2
2
  import 'zod';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { S as SdkAdapter } from '../task-runner-CuYWldNc.js';
1
+ import { S as SdkAdapter } from '../task-runner-MQO5VR1Y.js';
2
2
  import 'zod';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { S as SdkAdapter } from '../task-runner-CuYWldNc.js';
1
+ import { S as SdkAdapter } from '../task-runner-MQO5VR1Y.js';
2
2
  import 'zod';
3
3
 
4
4
  /**