agent-contracts-runtime 0.0.3 → 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.
@@ -0,0 +1,433 @@
1
+ // src/generator/index.ts
2
+ import { readFile as readFile3, writeFile, mkdir, rm } from "fs/promises";
3
+ import { resolve as resolve3, join as join2, relative } from "path";
4
+ import { createHash } from "crypto";
5
+ import YAML2 from "yaml";
6
+
7
+ // src/generator/config.ts
8
+ import { readFile } from "fs/promises";
9
+ import { resolve, dirname } from "path";
10
+ import { z } from "zod";
11
+ import YAML from "yaml";
12
+ var RuntimeConfigSchema = z.object({
13
+ dsl: z.string().default("./agent-contracts.yaml"),
14
+ generated_dir: z.string().default("./agent/generated"),
15
+ bindings: z.array(z.string()).default([]),
16
+ active_guardrail_policy: z.string().optional(),
17
+ templates_dir: z.string().optional()
18
+ });
19
+ async function loadConfig(configPath) {
20
+ const absPath = resolve(configPath);
21
+ const raw = await readFile(absPath, "utf8");
22
+ const parsed = YAML.parse(raw);
23
+ const config = RuntimeConfigSchema.parse(parsed);
24
+ const configDir = dirname(absPath);
25
+ return {
26
+ ...config,
27
+ configDir,
28
+ dslPath: resolve(configDir, config.dsl),
29
+ generatedDir: resolve(configDir, config.generated_dir),
30
+ bindingPaths: config.bindings.map((b) => resolve(configDir, b)),
31
+ templatesDir: config.templates_dir ? resolve(configDir, config.templates_dir) : void 0
32
+ };
33
+ }
34
+
35
+ // src/generator/template-engine.ts
36
+ import { readFile as readFile2 } from "fs/promises";
37
+ import { resolve as resolve2, join } from "path";
38
+ import { fileURLToPath } from "url";
39
+ import Handlebars from "handlebars";
40
+ import { existsSync } from "fs";
41
+ var __dirname = fileURLToPath(new URL(".", import.meta.url));
42
+ function findPackageRoot() {
43
+ let dir = __dirname;
44
+ for (let i = 0; i < 5; i++) {
45
+ if (existsSync(join(dir, "package.json"))) return dir;
46
+ dir = resolve2(dir, "..");
47
+ }
48
+ return resolve2(__dirname, "..");
49
+ }
50
+ var BUILTIN_TEMPLATES_DIR = join(findPackageRoot(), "templates");
51
+ function toCamelCase(str) {
52
+ return str.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
53
+ }
54
+ function toPascalCase(str) {
55
+ const camel = toCamelCase(str);
56
+ return camel.charAt(0).toUpperCase() + camel.slice(1);
57
+ }
58
+ var hbs = Handlebars.create();
59
+ hbs.registerHelper("camelCase", (str) => toCamelCase(str));
60
+ hbs.registerHelper("PascalCase", (str) => toPascalCase(str));
61
+ hbs.registerHelper("eq", (a, b) => a === b);
62
+ hbs.registerHelper(
63
+ "notEmpty",
64
+ (arr) => Array.isArray(arr) ? arr.length > 0 : !!arr
65
+ );
66
+ hbs.registerHelper(
67
+ "json",
68
+ (value) => new Handlebars.SafeString(JSON.stringify(value, null, 2))
69
+ );
70
+ hbs.registerHelper(
71
+ "jsonInline",
72
+ (value) => new Handlebars.SafeString(JSON.stringify(value))
73
+ );
74
+ hbs.registerHelper("indent", (text, spaces) => {
75
+ if (typeof text !== "string") return text;
76
+ const pad = " ".repeat(spaces);
77
+ return text.split("\n").map((line, i) => i === 0 ? line : pad + line).join("\n");
78
+ });
79
+ hbs.registerHelper("zodType", function zodType(schema) {
80
+ if (!schema || typeof schema !== "object") return "z.unknown()";
81
+ if (schema.enum) {
82
+ const vals = schema.enum.map((v) => `"${v}"`).join(", ");
83
+ return `z.enum([${vals}])`;
84
+ }
85
+ if (schema.const !== void 0) {
86
+ return `z.literal(${JSON.stringify(schema.const)})`;
87
+ }
88
+ const type = schema.type;
89
+ if (type === "string") return "z.string()";
90
+ if (type === "number" || type === "integer") return "z.number()";
91
+ if (type === "boolean") return "z.boolean()";
92
+ if (type === "array") {
93
+ const items = schema.items;
94
+ const inner = items ? zodType(items) : "z.unknown()";
95
+ return `z.array(${inner})`;
96
+ }
97
+ if (type === "object") {
98
+ const props = schema.properties;
99
+ if (!props) return "z.record(z.string(), z.unknown())";
100
+ const required = schema.required ?? [];
101
+ const fields = Object.entries(props).map(([key, val]) => {
102
+ const base = zodType(val);
103
+ const opt = required.includes(key) ? "" : ".optional()";
104
+ return ` ${key}: ${base}${opt},`;
105
+ }).join("\n");
106
+ return `z.object({
107
+ ${fields}
108
+ })`;
109
+ }
110
+ if (schema.allOf) {
111
+ const parts = schema.allOf.map(zodType);
112
+ if (parts.length === 1) return parts[0];
113
+ return parts.join(".merge(") + ")".repeat(parts.length - 1);
114
+ }
115
+ return "z.unknown()";
116
+ });
117
+ hbs.registerHelper("regexEscape", (str) => {
118
+ if (typeof str !== "string") return str;
119
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
120
+ });
121
+ hbs.registerHelper("stringArray", (arr) => {
122
+ if (!Array.isArray(arr)) return "[]";
123
+ return "[" + arr.map((s) => `"${s}"`).join(", ") + "]";
124
+ });
125
+ async function loadTemplate(name, customDir) {
126
+ if (customDir) {
127
+ try {
128
+ return await readFile2(join(customDir, name), "utf8");
129
+ } catch {
130
+ }
131
+ }
132
+ return readFile2(join(BUILTIN_TEMPLATES_DIR, name), "utf8");
133
+ }
134
+ async function renderTemplate(name, context, customDir) {
135
+ const source = await loadTemplate(name, customDir);
136
+ const compiled = hbs.compile(source, { noEscape: true });
137
+ return compiled(context);
138
+ }
139
+
140
+ // src/generator/context.ts
141
+ function isTaskOptional(taskId, workflows) {
142
+ for (const wf of Object.values(workflows)) {
143
+ for (const step of wf.steps) {
144
+ if (step.type === "delegate" && step.task === taskId && step.optional) {
145
+ return true;
146
+ }
147
+ }
148
+ }
149
+ return false;
150
+ }
151
+ function buildContractContext(dsl) {
152
+ const agents = dsl.agents ?? {};
153
+ const tasks = dsl.tasks ?? {};
154
+ const workflows = dsl.workflow ?? {};
155
+ const handoffTypes = dsl.handoff_types ?? {};
156
+ const agentEntries = Object.entries(agents).map(([id, agent]) => ({
157
+ id,
158
+ varName: toCamelCase(id),
159
+ role_name: agent.role_name ?? id,
160
+ purpose: agent.purpose ?? "",
161
+ mode: agent.mode ?? "read-write",
162
+ dispatch_only: agent.dispatch_only ?? false,
163
+ can_read_artifacts: agent.can_read_artifacts ?? [],
164
+ can_write_artifacts: agent.can_write_artifacts ?? [],
165
+ can_execute_tools: agent.can_execute_tools ?? [],
166
+ can_invoke_agents: agent.can_invoke_agents ?? [],
167
+ can_return_handoffs: agent.can_return_handoffs ?? [],
168
+ responsibilities: agent.responsibilities ?? [],
169
+ constraints: agent.constraints ?? [],
170
+ rules: agent.rules ?? [],
171
+ escalation_criteria: agent.escalation_criteria ?? []
172
+ }));
173
+ const taskEntries = Object.entries(tasks).map(([id, task]) => ({
174
+ id,
175
+ varName: toCamelCase(id),
176
+ description: task.description ?? "",
177
+ target_agent: task.target_agent ?? "",
178
+ allowed_from_agents: task.allowed_from_agents ?? [],
179
+ workflow: task.workflow ?? "",
180
+ invocation_handoff: task.invocation_handoff ?? "",
181
+ result_handoff: task.result_handoff ?? "",
182
+ input_artifacts: task.input_artifacts ?? [],
183
+ responsibilities: task.responsibilities ?? [],
184
+ completion_criteria: task.completion_criteria ?? [],
185
+ optional: isTaskOptional(id, workflows)
186
+ }));
187
+ const workflowEntries = Object.entries(workflows).map(
188
+ ([id, wf]) => {
189
+ const steps = (wf.steps ?? []).map((step) => {
190
+ const entry = { type: step.type };
191
+ if (step.type === "delegate") {
192
+ entry.task = step.task;
193
+ entry.from_agent = step.from_agent;
194
+ entry.description = step.description;
195
+ const wfStep = step;
196
+ entry.optional = isTaskOptional(
197
+ step.task,
198
+ workflows
199
+ );
200
+ entry.max_retries = wfStep.retry ? 1 : 0;
201
+ } else if (step.type === "gate") {
202
+ entry.gate_kind = step.gate_kind;
203
+ entry.description = step.description;
204
+ }
205
+ return entry;
206
+ });
207
+ return {
208
+ id,
209
+ varName: toCamelCase(id),
210
+ description: wf.description ?? "",
211
+ trigger: wf.trigger ?? "",
212
+ entry_conditions: wf.entry_conditions ?? [],
213
+ steps
214
+ };
215
+ }
216
+ );
217
+ const handoffEntries = Object.entries(handoffTypes).map(
218
+ ([id, ht]) => ({
219
+ id,
220
+ varName: toCamelCase(id),
221
+ pascalName: toPascalCase(id),
222
+ schemaName: toPascalCase(id) + "Schema",
223
+ description: ht.description ?? "",
224
+ schema: ht.schema ?? {}
225
+ })
226
+ );
227
+ return { agentEntries, taskEntries, workflowEntries, handoffEntries };
228
+ }
229
+ function buildGuardrailContext(dsl, binding, policyName) {
230
+ const empty = {
231
+ commandChecks: [],
232
+ fileChecks: [],
233
+ contentChecks: [],
234
+ allChecks: [],
235
+ hasGuardrails: false
236
+ };
237
+ if (!binding?.guardrail_impl) return empty;
238
+ const guardrails = dsl.guardrails ?? {};
239
+ const policies = dsl.guardrail_policies ?? {};
240
+ const policy = policyName ? policies[policyName] : void 0;
241
+ const allChecks = [];
242
+ for (const [guardrailId, impl] of Object.entries(
243
+ binding.guardrail_impl
244
+ )) {
245
+ const guardrail = guardrails[guardrailId];
246
+ const description = guardrail?.description ?? guardrailId;
247
+ const policyRule = policy?.rules?.find(
248
+ (r) => r.guardrail === guardrailId
249
+ );
250
+ const severity = policyRule?.severity ?? "warning";
251
+ const action = policyRule?.action ?? "warn";
252
+ for (const check of impl.checks) {
253
+ const matcher = check.matcher;
254
+ if (!matcher) continue;
255
+ allChecks.push({
256
+ guardrail_id: guardrailId,
257
+ description,
258
+ severity,
259
+ action,
260
+ matcher_type: matcher.type,
261
+ pattern: matcher.pattern,
262
+ message: check.message ?? description,
263
+ file_glob: matcher.file_glob,
264
+ exclude_glob: matcher.exclude_glob
265
+ });
266
+ }
267
+ }
268
+ return {
269
+ commandChecks: allChecks.filter((c) => c.matcher_type === "command_regex"),
270
+ fileChecks: allChecks.filter((c) => c.matcher_type === "file_glob"),
271
+ contentChecks: allChecks.filter((c) => c.matcher_type === "content_regex"),
272
+ allChecks,
273
+ hasGuardrails: allChecks.length > 0
274
+ };
275
+ }
276
+
277
+ // src/generator/index.ts
278
+ var DO_NOT_EDIT_HEADER = `/**
279
+ * AUTO-GENERATED by agent-contracts-runtime. DO NOT EDIT.
280
+ *
281
+ * Regenerate via: npx agent-runtime generate
282
+ */
283
+
284
+ `;
285
+ async function loadYaml(filePath) {
286
+ const raw = await readFile3(filePath, "utf8");
287
+ return YAML2.parse(raw);
288
+ }
289
+ function computeHash(data) {
290
+ return createHash("sha256").update(data).digest("hex");
291
+ }
292
+ async function loadDsl(dslPath) {
293
+ try {
294
+ const modName = "agent-contracts";
295
+ const mod = await import(
296
+ /* webpackIgnore: true */
297
+ modName
298
+ );
299
+ if (mod.loadDsl) {
300
+ const result = await mod.loadDsl(dslPath);
301
+ return result.data;
302
+ }
303
+ } catch {
304
+ }
305
+ return await loadYaml(dslPath);
306
+ }
307
+ var CONTRACT_TEMPLATES = [
308
+ { template: "agents.ts.hbs", output: "agents.ts" },
309
+ { template: "tasks.ts.hbs", output: "tasks.ts" },
310
+ { template: "workflows.ts.hbs", output: "workflows.ts" },
311
+ { template: "handoffs.ts.hbs", output: "handoffs.ts" },
312
+ { template: "contracts-index.ts.hbs", output: "index.ts" }
313
+ ];
314
+ var GUARDRAIL_TEMPLATES = [
315
+ { template: "guardrails.ts.hbs", output: "hooks/guardrails.ts" },
316
+ { template: "hooks-index.ts.hbs", output: "hooks/index.ts" }
317
+ ];
318
+ async function generate(options = {}) {
319
+ const configPath = options.configPath ?? "./agent-runtime.config.yaml";
320
+ const config = await loadConfig(configPath);
321
+ const templatesDir = options.templates ?? config.templatesDir;
322
+ const checkMode = options.check ?? false;
323
+ const cleaned = options.clean ?? false;
324
+ if (cleaned && !checkMode) {
325
+ try {
326
+ await rm(config.generatedDir, { recursive: true, force: true });
327
+ } catch {
328
+ }
329
+ }
330
+ const dsl = await loadDsl(config.dslPath);
331
+ const dslCanonical = JSON.stringify(dsl, Object.keys(dsl).sort(), 0);
332
+ const dslHash = computeHash(dslCanonical);
333
+ const contractCtx = buildContractContext(dsl);
334
+ const filesGenerated = [];
335
+ const generatedContents = /* @__PURE__ */ new Map();
336
+ for (const { template, output } of CONTRACT_TEMPLATES) {
337
+ const rendered = DO_NOT_EDIT_HEADER + await renderTemplate(template, contractCtx, templatesDir);
338
+ const outPath = join2(config.generatedDir, output);
339
+ filesGenerated.push(relative(config.configDir, outPath));
340
+ generatedContents.set(outPath, rendered);
341
+ }
342
+ if (config.bindingPaths.length > 0) {
343
+ for (const bindingPath of config.bindingPaths) {
344
+ const binding = await loadYaml(bindingPath);
345
+ const guardrailCtx = buildGuardrailContext(
346
+ dsl,
347
+ binding,
348
+ config.active_guardrail_policy
349
+ );
350
+ if (guardrailCtx.hasGuardrails) {
351
+ for (const { template, output } of GUARDRAIL_TEMPLATES) {
352
+ const rendered = DO_NOT_EDIT_HEADER + await renderTemplate(
353
+ template,
354
+ guardrailCtx,
355
+ templatesDir
356
+ );
357
+ const outPath = join2(config.generatedDir, output);
358
+ filesGenerated.push(relative(config.configDir, outPath));
359
+ generatedContents.set(outPath, rendered);
360
+ }
361
+ }
362
+ }
363
+ }
364
+ const generationInputParts = [dslCanonical];
365
+ for (const bp of config.bindingPaths) {
366
+ try {
367
+ generationInputParts.push(await readFile3(bp, "utf8"));
368
+ } catch {
369
+ }
370
+ }
371
+ const generationInputHash = computeHash(generationInputParts.join("\n---\n"));
372
+ let hasDifferences = false;
373
+ if (checkMode) {
374
+ for (const [outPath, content] of generatedContents) {
375
+ try {
376
+ const existing = await readFile3(outPath, "utf8");
377
+ if (existing !== content) {
378
+ hasDifferences = true;
379
+ break;
380
+ }
381
+ } catch {
382
+ hasDifferences = true;
383
+ break;
384
+ }
385
+ }
386
+ } else {
387
+ for (const [outPath, content] of generatedContents) {
388
+ const dir = resolve3(outPath, "..");
389
+ await mkdir(dir, { recursive: true });
390
+ await writeFile(outPath, content, "utf8");
391
+ }
392
+ const manifest = {
393
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
394
+ dslHash,
395
+ generationInputHash,
396
+ files: filesGenerated
397
+ };
398
+ const manifestPath = join2(config.generatedDir, ".manifest.json");
399
+ await mkdir(resolve3(manifestPath, ".."), { recursive: true });
400
+ await writeFile(manifestPath, JSON.stringify(manifest, null, 2) + "\n", "utf8");
401
+ }
402
+ return {
403
+ filesGenerated,
404
+ dslHash,
405
+ generationInputHash,
406
+ cleaned,
407
+ checkMode,
408
+ hasDifferences
409
+ };
410
+ }
411
+ async function checkFreshness(configPath) {
412
+ const config = await loadConfig(configPath ?? "./agent-runtime.config.yaml");
413
+ const manifestPath = join2(config.generatedDir, ".manifest.json");
414
+ try {
415
+ const raw = await readFile3(manifestPath, "utf8");
416
+ const manifest = JSON.parse(raw);
417
+ const dsl = await loadDsl(config.dslPath);
418
+ const dslCanonical = JSON.stringify(dsl, Object.keys(dsl).sort(), 0);
419
+ const currentHash = computeHash(dslCanonical);
420
+ return manifest.dslHash === currentHash;
421
+ } catch {
422
+ return false;
423
+ }
424
+ }
425
+
426
+ export {
427
+ loadConfig,
428
+ buildContractContext,
429
+ buildGuardrailContext,
430
+ generate,
431
+ checkFreshness
432
+ };
433
+ //# sourceMappingURL=chunk-DNTCPVJN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/generator/index.ts","../src/generator/config.ts","../src/generator/template-engine.ts","../src/generator/context.ts"],"sourcesContent":["/**\n * Generator — orchestrates DSL-to-TypeScript code generation\n */\n\nimport { readFile, writeFile, mkdir, rm, stat } from \"node:fs/promises\";\nimport { resolve, join, relative } from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport YAML from \"yaml\";\nimport { loadConfig, type ResolvedConfig } from \"./config.js\";\nimport { renderTemplate } from \"./template-engine.js\";\nimport { buildContractContext, buildGuardrailContext } from \"./context.js\";\n\nexport interface GenerateOptions {\n clean?: boolean;\n check?: boolean;\n templates?: string;\n configPath?: string;\n}\n\nexport interface GenerateResult {\n filesGenerated: string[];\n dslHash: string;\n generationInputHash: string;\n cleaned: boolean;\n checkMode: boolean;\n hasDifferences: boolean;\n}\n\nconst DO_NOT_EDIT_HEADER = `/**\n * AUTO-GENERATED by agent-contracts-runtime. DO NOT EDIT.\n *\n * Regenerate via: npx agent-runtime generate\n */\n\n`;\n\nasync function loadYaml(filePath: string): Promise<unknown> {\n const raw = await readFile(filePath, \"utf8\");\n return YAML.parse(raw);\n}\n\nfunction computeHash(data: string): string {\n return createHash(\"sha256\").update(data).digest(\"hex\");\n}\n\n/**\n * Load DSL — tries agent-contracts resolve if available, falls back to raw YAML.\n */\nasync function loadDsl(dslPath: string): Promise<Record<string, unknown>> {\n try {\n const modName = \"agent-contracts\";\n const mod = await import(/* webpackIgnore: true */ modName);\n if (mod.loadDsl) {\n const result = await mod.loadDsl(dslPath);\n return (result as { data: Record<string, unknown> }).data;\n }\n } catch {\n // agent-contracts not available — use raw YAML\n }\n return (await loadYaml(dslPath)) as Record<string, unknown>;\n}\n\nconst CONTRACT_TEMPLATES = [\n { template: \"agents.ts.hbs\", output: \"agents.ts\" },\n { template: \"tasks.ts.hbs\", output: \"tasks.ts\" },\n { template: \"workflows.ts.hbs\", output: \"workflows.ts\" },\n { template: \"handoffs.ts.hbs\", output: \"handoffs.ts\" },\n { template: \"contracts-index.ts.hbs\", output: \"index.ts\" },\n];\n\nconst GUARDRAIL_TEMPLATES = [\n { template: \"guardrails.ts.hbs\", output: \"hooks/guardrails.ts\" },\n { template: \"hooks-index.ts.hbs\", output: \"hooks/index.ts\" },\n];\n\nexport async function generate(options: GenerateOptions = {}): Promise<GenerateResult> {\n const configPath = options.configPath ?? \"./agent-runtime.config.yaml\";\n const config = await loadConfig(configPath);\n\n const templatesDir = options.templates ?? config.templatesDir;\n const checkMode = options.check ?? false;\n const cleaned = options.clean ?? false;\n\n if (cleaned && !checkMode) {\n try {\n await rm(config.generatedDir, { recursive: true, force: true });\n } catch {\n // directory may not exist\n }\n }\n\n const dsl = await loadDsl(config.dslPath);\n const dslCanonical = JSON.stringify(dsl, Object.keys(dsl).sort(), 0);\n const dslHash = computeHash(dslCanonical);\n\n const contractCtx = buildContractContext(dsl);\n\n const filesGenerated: string[] = [];\n const generatedContents: Map<string, string> = new Map();\n\n // Phase 1: Contract files\n for (const { template, output } of CONTRACT_TEMPLATES) {\n const rendered = DO_NOT_EDIT_HEADER + await renderTemplate(template, contractCtx as unknown as Record<string, unknown>, templatesDir);\n const outPath = join(config.generatedDir, output);\n filesGenerated.push(relative(config.configDir, outPath));\n generatedContents.set(outPath, rendered);\n }\n\n // Phase 2: Guardrail hooks (only if bindings are configured)\n if (config.bindingPaths.length > 0) {\n for (const bindingPath of config.bindingPaths) {\n const binding = await loadYaml(bindingPath);\n const guardrailCtx = buildGuardrailContext(\n dsl,\n binding,\n config.active_guardrail_policy,\n );\n\n if (guardrailCtx.hasGuardrails) {\n for (const { template, output } of GUARDRAIL_TEMPLATES) {\n const rendered = DO_NOT_EDIT_HEADER + await renderTemplate(\n template,\n guardrailCtx as unknown as Record<string, unknown>,\n templatesDir,\n );\n const outPath = join(config.generatedDir, output);\n filesGenerated.push(relative(config.configDir, outPath));\n generatedContents.set(outPath, rendered);\n }\n }\n }\n }\n\n // Compute generation input hash (DSL + binding + generator version)\n const generationInputParts = [dslCanonical];\n for (const bp of config.bindingPaths) {\n try {\n generationInputParts.push(await readFile(bp, \"utf8\"));\n } catch {\n // binding may not exist\n }\n }\n const generationInputHash = computeHash(generationInputParts.join(\"\\n---\\n\"));\n\n // Check mode — compare without writing\n let hasDifferences = false;\n if (checkMode) {\n for (const [outPath, content] of generatedContents) {\n try {\n const existing = await readFile(outPath, \"utf8\");\n if (existing !== content) {\n hasDifferences = true;\n break;\n }\n } catch {\n hasDifferences = true;\n break;\n }\n }\n } else {\n // Write files\n for (const [outPath, content] of generatedContents) {\n const dir = resolve(outPath, \"..\");\n await mkdir(dir, { recursive: true });\n await writeFile(outPath, content, \"utf8\");\n }\n\n // Write manifest\n const manifest = {\n generatedAt: new Date().toISOString(),\n dslHash,\n generationInputHash,\n files: filesGenerated,\n };\n const manifestPath = join(config.generatedDir, \".manifest.json\");\n await mkdir(resolve(manifestPath, \"..\"), { recursive: true });\n await writeFile(manifestPath, JSON.stringify(manifest, null, 2) + \"\\n\", \"utf8\");\n }\n\n return {\n filesGenerated,\n dslHash,\n generationInputHash,\n cleaned,\n checkMode,\n hasDifferences,\n };\n}\n\nexport async function checkFreshness(configPath?: string): Promise<boolean> {\n const config = await loadConfig(configPath ?? \"./agent-runtime.config.yaml\");\n const manifestPath = join(config.generatedDir, \".manifest.json\");\n\n try {\n const raw = await readFile(manifestPath, \"utf8\");\n const manifest = JSON.parse(raw) as { dslHash: string };\n\n const dsl = await loadDsl(config.dslPath);\n const dslCanonical = JSON.stringify(dsl, Object.keys(dsl).sort(), 0);\n const currentHash = computeHash(dslCanonical);\n\n return manifest.dslHash === currentHash;\n } catch {\n return false;\n }\n}\n\nexport { loadConfig, type ResolvedConfig } from \"./config.js\";\nexport { buildContractContext, buildGuardrailContext } from \"./context.js\";\n","/**\n * Generator configuration — loads and validates agent-runtime.config.yaml\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { resolve, dirname } from \"node:path\";\nimport { z } from \"zod\";\nimport YAML from \"yaml\";\n\nexport const RuntimeConfigSchema = z.object({\n dsl: z.string().default(\"./agent-contracts.yaml\"),\n generated_dir: z.string().default(\"./agent/generated\"),\n bindings: z.array(z.string()).default([]),\n active_guardrail_policy: z.string().optional(),\n templates_dir: z.string().optional(),\n});\n\nexport type RuntimeConfig = z.infer<typeof RuntimeConfigSchema>;\n\nexport interface ResolvedConfig extends RuntimeConfig {\n configDir: string;\n dslPath: string;\n generatedDir: string;\n bindingPaths: string[];\n templatesDir: string | undefined;\n}\n\nexport async function loadConfig(configPath: string): Promise<ResolvedConfig> {\n const absPath = resolve(configPath);\n const raw = await readFile(absPath, \"utf8\");\n const parsed = YAML.parse(raw);\n const config = RuntimeConfigSchema.parse(parsed);\n const configDir = dirname(absPath);\n\n return {\n ...config,\n configDir,\n dslPath: resolve(configDir, config.dsl),\n generatedDir: resolve(configDir, config.generated_dir),\n bindingPaths: config.bindings.map((b) => resolve(configDir, b)),\n templatesDir: config.templates_dir\n ? resolve(configDir, config.templates_dir)\n : undefined,\n };\n}\n","/**\n * Handlebars template engine with custom helpers for TypeScript code generation\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport Handlebars from \"handlebars\";\n\nimport { existsSync } from \"node:fs\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\n\nfunction findPackageRoot(): string {\n let dir = __dirname;\n for (let i = 0; i < 5; i++) {\n if (existsSync(join(dir, \"package.json\"))) return dir;\n dir = resolve(dir, \"..\");\n }\n return resolve(__dirname, \"..\");\n}\n\nconst BUILTIN_TEMPLATES_DIR = join(findPackageRoot(), \"templates\");\n\nfunction toCamelCase(str: string): string {\n return str.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());\n}\n\nfunction toPascalCase(str: string): string {\n const camel = toCamelCase(str);\n return camel.charAt(0).toUpperCase() + camel.slice(1);\n}\n\nconst hbs = Handlebars.create();\n\nhbs.registerHelper(\"camelCase\", (str: string) => toCamelCase(str));\nhbs.registerHelper(\"PascalCase\", (str: string) => toPascalCase(str));\n\nhbs.registerHelper(\"eq\", (a: unknown, b: unknown) => a === b);\nhbs.registerHelper(\"notEmpty\", (arr: unknown) =>\n Array.isArray(arr) ? arr.length > 0 : !!arr,\n);\n\nhbs.registerHelper(\"json\", (value: unknown) =>\n new Handlebars.SafeString(JSON.stringify(value, null, 2)),\n);\n\nhbs.registerHelper(\"jsonInline\", (value: unknown) =>\n new Handlebars.SafeString(JSON.stringify(value)),\n);\n\nhbs.registerHelper(\"indent\", (text: string, spaces: number) => {\n if (typeof text !== \"string\") return text;\n const pad = \" \".repeat(spaces);\n return text\n .split(\"\\n\")\n .map((line, i) => (i === 0 ? line : pad + line))\n .join(\"\\n\");\n});\n\nhbs.registerHelper(\"zodType\", function zodType(schema: Record<string, unknown>): string {\n if (!schema || typeof schema !== \"object\") return \"z.unknown()\";\n\n if (schema.enum) {\n const vals = (schema.enum as string[]).map((v) => `\"${v}\"`).join(\", \");\n return `z.enum([${vals}])`;\n }\n\n if (schema.const !== undefined) {\n return `z.literal(${JSON.stringify(schema.const)})`;\n }\n\n const type = schema.type as string | undefined;\n\n if (type === \"string\") return \"z.string()\";\n if (type === \"number\" || type === \"integer\") return \"z.number()\";\n if (type === \"boolean\") return \"z.boolean()\";\n\n if (type === \"array\") {\n const items = schema.items as Record<string, unknown> | undefined;\n const inner = items ? zodType(items) : \"z.unknown()\";\n return `z.array(${inner})`;\n }\n\n if (type === \"object\") {\n const props = schema.properties as Record<string, Record<string, unknown>> | undefined;\n if (!props) return \"z.record(z.string(), z.unknown())\";\n\n const required = (schema.required as string[]) ?? [];\n const fields = Object.entries(props)\n .map(([key, val]) => {\n const base = zodType(val);\n const opt = required.includes(key) ? \"\" : \".optional()\";\n return ` ${key}: ${base}${opt},`;\n })\n .join(\"\\n\");\n return `z.object({\\n${fields}\\n})`;\n }\n\n if (schema.allOf) {\n const parts = (schema.allOf as Record<string, unknown>[]).map(zodType);\n if (parts.length === 1) return parts[0];\n return parts.join(\".merge(\") + \")\".repeat(parts.length - 1);\n }\n\n return \"z.unknown()\";\n});\n\nhbs.registerHelper(\"regexEscape\", (str: string) => {\n if (typeof str !== \"string\") return str;\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n});\n\nhbs.registerHelper(\"stringArray\", (arr: unknown) => {\n if (!Array.isArray(arr)) return \"[]\";\n return \"[\" + arr.map((s) => `\"${s}\"`).join(\", \") + \"]\";\n});\n\n/**\n * Load a template by name, with custom dir override fallback to built-in.\n */\nasync function loadTemplate(\n name: string,\n customDir?: string,\n): Promise<string> {\n if (customDir) {\n try {\n return await readFile(join(customDir, name), \"utf8\");\n } catch {\n // fallback to built-in\n }\n }\n return readFile(join(BUILTIN_TEMPLATES_DIR, name), \"utf8\");\n}\n\nexport async function renderTemplate(\n name: string,\n context: Record<string, unknown>,\n customDir?: string,\n): Promise<string> {\n const source = await loadTemplate(name, customDir);\n const compiled = hbs.compile(source, { noEscape: true });\n return compiled(context);\n}\n\nexport { hbs, toCamelCase, toPascalCase };\n","/**\n * Build template contexts from resolved DSL data\n */\n\nimport { toCamelCase, toPascalCase } from \"./template-engine.js\";\n\nexport interface AgentEntry {\n id: string;\n varName: string;\n role_name: string;\n purpose: string;\n mode: string;\n dispatch_only: boolean;\n can_read_artifacts: string[];\n can_write_artifacts: string[];\n can_execute_tools: string[];\n can_invoke_agents: string[];\n can_return_handoffs: string[];\n responsibilities: string[];\n constraints: string[];\n rules: Array<{ id: string; description: string; severity: string }>;\n escalation_criteria: Array<{ condition: string; action: string }>;\n}\n\nexport interface TaskEntry {\n id: string;\n varName: string;\n description: string;\n target_agent: string;\n allowed_from_agents: string[];\n workflow: string;\n invocation_handoff: string;\n result_handoff: string;\n input_artifacts: string[];\n responsibilities: string[];\n completion_criteria: string[];\n optional: boolean;\n}\n\nexport interface WorkflowStepEntry {\n type: string;\n task?: string;\n from_agent?: string;\n description?: string;\n optional?: boolean;\n max_retries?: number;\n gate_kind?: string;\n}\n\nexport interface WorkflowEntry {\n id: string;\n varName: string;\n description: string;\n trigger: string;\n entry_conditions: string[];\n steps: WorkflowStepEntry[];\n}\n\nexport interface HandoffEntry {\n id: string;\n varName: string;\n pascalName: string;\n schemaName: string;\n description: string;\n schema: Record<string, unknown>;\n}\n\nexport interface ContractContext {\n agentEntries: AgentEntry[];\n taskEntries: TaskEntry[];\n workflowEntries: WorkflowEntry[];\n handoffEntries: HandoffEntry[];\n}\n\n/**\n * Determine if a task is optional by checking if any workflow step referencing it is optional.\n */\nfunction isTaskOptional(\n taskId: string,\n workflows: Record<string, { steps: Array<{ type: string; task?: string; optional?: boolean }> }>,\n): boolean {\n for (const wf of Object.values(workflows)) {\n for (const step of wf.steps) {\n if (step.type === \"delegate\" && step.task === taskId && step.optional) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Compute max_retries from workflow step or fallback to 0.\n */\nfunction getMaxRetries(\n taskId: string,\n workflows: Record<string, { steps: Array<Record<string, unknown>> }>,\n): number {\n for (const wf of Object.values(workflows)) {\n for (const step of wf.steps) {\n if (step.type === \"delegate\" && step.task === taskId) {\n const retry = step.retry as { condition: string } | undefined;\n return retry ? 1 : 0;\n }\n }\n }\n return 0;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function buildContractContext(dsl: any): ContractContext {\n const agents = (dsl.agents ?? {}) as Record<string, Record<string, unknown>>;\n const tasks = (dsl.tasks ?? {}) as Record<string, Record<string, unknown>>;\n const workflows = (dsl.workflow ?? {}) as Record<string, Record<string, unknown>>;\n const handoffTypes = (dsl.handoff_types ?? {}) as Record<string, Record<string, unknown>>;\n\n const agentEntries: AgentEntry[] = Object.entries(agents).map(([id, agent]) => ({\n id,\n varName: toCamelCase(id),\n role_name: (agent.role_name as string) ?? id,\n purpose: (agent.purpose as string) ?? \"\",\n mode: (agent.mode as string) ?? \"read-write\",\n dispatch_only: (agent.dispatch_only as boolean) ?? false,\n can_read_artifacts: (agent.can_read_artifacts as string[]) ?? [],\n can_write_artifacts: (agent.can_write_artifacts as string[]) ?? [],\n can_execute_tools: (agent.can_execute_tools as string[]) ?? [],\n can_invoke_agents: (agent.can_invoke_agents as string[]) ?? [],\n can_return_handoffs: (agent.can_return_handoffs as string[]) ?? [],\n responsibilities: (agent.responsibilities as string[]) ?? [],\n constraints: (agent.constraints as string[]) ?? [],\n rules: (agent.rules as AgentEntry[\"rules\"]) ?? [],\n escalation_criteria: (agent.escalation_criteria as AgentEntry[\"escalation_criteria\"]) ?? [],\n }));\n\n const taskEntries: TaskEntry[] = Object.entries(tasks).map(([id, task]) => ({\n id,\n varName: toCamelCase(id),\n description: (task.description as string) ?? \"\",\n target_agent: (task.target_agent as string) ?? \"\",\n allowed_from_agents: (task.allowed_from_agents as string[]) ?? [],\n workflow: (task.workflow as string) ?? \"\",\n invocation_handoff: (task.invocation_handoff as string) ?? \"\",\n result_handoff: (task.result_handoff as string) ?? \"\",\n input_artifacts: (task.input_artifacts as string[]) ?? [],\n responsibilities: (task.responsibilities as string[]) ?? [],\n completion_criteria: (task.completion_criteria as string[]) ?? [],\n optional: isTaskOptional(id, workflows as Record<string, { steps: Array<{ type: string; task?: string; optional?: boolean }> }>),\n }));\n\n const workflowEntries: WorkflowEntry[] = Object.entries(workflows).map(\n ([id, wf]) => {\n const steps = ((wf.steps as Array<Record<string, unknown>>) ?? []).map((step) => {\n const entry: WorkflowStepEntry = { type: step.type as string };\n if (step.type === \"delegate\") {\n entry.task = step.task as string;\n entry.from_agent = step.from_agent as string;\n entry.description = step.description as string;\n const wfStep = step as Record<string, unknown>;\n entry.optional = isTaskOptional(\n step.task as string,\n workflows as Record<string, { steps: Array<{ type: string; task?: string; optional?: boolean }> }>,\n );\n entry.max_retries = wfStep.retry ? 1 : 0;\n } else if (step.type === \"gate\") {\n entry.gate_kind = step.gate_kind as string;\n entry.description = step.description as string;\n }\n return entry;\n });\n\n return {\n id,\n varName: toCamelCase(id),\n description: (wf.description as string) ?? \"\",\n trigger: (wf.trigger as string) ?? \"\",\n entry_conditions: (wf.entry_conditions as string[]) ?? [],\n steps,\n };\n },\n );\n\n const handoffEntries: HandoffEntry[] = Object.entries(handoffTypes).map(\n ([id, ht]) => ({\n id,\n varName: toCamelCase(id),\n pascalName: toPascalCase(id),\n schemaName: toPascalCase(id) + \"Schema\",\n description: (ht.description as string) ?? \"\",\n schema: (ht.schema as Record<string, unknown>) ?? {},\n }),\n );\n\n return { agentEntries, taskEntries, workflowEntries, handoffEntries };\n}\n\nexport interface GuardrailCheckEntry {\n guardrail_id: string;\n description: string;\n severity: string;\n action: string;\n matcher_type: string;\n pattern: string;\n message: string;\n file_glob?: string;\n exclude_glob?: string;\n}\n\nexport interface GuardrailContext {\n commandChecks: GuardrailCheckEntry[];\n fileChecks: GuardrailCheckEntry[];\n contentChecks: GuardrailCheckEntry[];\n allChecks: GuardrailCheckEntry[];\n hasGuardrails: boolean;\n}\n\n/**\n * Build guardrail context from DSL guardrails, binding guardrail_impl, and active policy.\n * Mirrors the agent-contracts resolveChecks pattern.\n */\nexport function buildGuardrailContext(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n dsl: any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n binding: any,\n policyName?: string,\n): GuardrailContext {\n const empty: GuardrailContext = {\n commandChecks: [],\n fileChecks: [],\n contentChecks: [],\n allChecks: [],\n hasGuardrails: false,\n };\n\n if (!binding?.guardrail_impl) return empty;\n\n const guardrails = dsl.guardrails ?? {};\n const policies = dsl.guardrail_policies ?? {};\n const policy = policyName ? policies[policyName] : undefined;\n\n const allChecks: GuardrailCheckEntry[] = [];\n\n for (const [guardrailId, impl] of Object.entries(\n binding.guardrail_impl as Record<string, { checks: Array<Record<string, unknown>> }>,\n )) {\n const guardrail = guardrails[guardrailId] as Record<string, unknown> | undefined;\n const description = (guardrail?.description as string) ?? guardrailId;\n\n const policyRule = policy?.rules?.find(\n (r: Record<string, unknown>) => r.guardrail === guardrailId,\n );\n const severity = (policyRule?.severity as string) ?? \"warning\";\n const action = (policyRule?.action as string) ?? \"warn\";\n\n for (const check of impl.checks) {\n const matcher = check.matcher as Record<string, unknown> | undefined;\n if (!matcher) continue;\n\n allChecks.push({\n guardrail_id: guardrailId,\n description,\n severity,\n action,\n matcher_type: matcher.type as string,\n pattern: matcher.pattern as string,\n message: (check.message as string) ?? description,\n file_glob: matcher.file_glob as string | undefined,\n exclude_glob: matcher.exclude_glob as string | undefined,\n });\n }\n }\n\n return {\n commandChecks: allChecks.filter((c) => c.matcher_type === \"command_regex\"),\n fileChecks: allChecks.filter((c) => c.matcher_type === \"file_glob\"),\n contentChecks: allChecks.filter((c) => c.matcher_type === \"content_regex\"),\n allChecks,\n hasGuardrails: allChecks.length > 0,\n };\n}\n"],"mappings":";AAIA,SAAS,YAAAA,WAAU,WAAW,OAAO,UAAgB;AACrD,SAAS,WAAAC,UAAS,QAAAC,OAAM,gBAAgB;AACxC,SAAS,kBAAkB;AAC3B,OAAOC,WAAU;;;ACHjB,SAAS,gBAAgB;AAC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A,IACT;AACA,UAAM,eAAeD,MAAK,OAAO,cAAc,gBAAgB;AAC/D,UAAM,MAAMC,SAAQ,cAAc,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAC5D,UAAM,UAAU,cAAc,KAAK,UAAU,UAAU,MAAM,CAAC,IAAI,MAAM,MAAM;AAAA,EAChF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEA,eAAsB,eAAe,YAAuC;AAC1E,QAAM,SAAS,MAAM,WAAW,cAAc,6BAA6B;AAC3E,QAAM,eAAeD,MAAK,OAAO,cAAc,gBAAgB;AAE/D,MAAI;AACF,UAAM,MAAM,MAAMF,UAAS,cAAc,MAAM;AAC/C,UAAM,WAAW,KAAK,MAAM,GAAG;AAE/B,UAAM,MAAM,MAAM,QAAQ,OAAO,OAAO;AACxC,UAAM,eAAe,KAAK,UAAU,KAAK,OAAO,KAAK,GAAG,EAAE,KAAK,GAAG,CAAC;AACnE,UAAM,cAAc,YAAY,YAAY;AAE5C,WAAO,SAAS,YAAY;AAAA,EAC9B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["readFile","resolve","join","YAML","readFile","resolve","readFile","YAML","join","resolve"]}
package/dist/cli/index.js CHANGED
@@ -1,4 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ generate
4
+ } from "../chunk-DNTCPVJN.js";
2
5
 
3
6
  // src/generated/cli/program.ts
4
7
  import { Command } from "commander";
@@ -11,7 +14,7 @@ function createProgram(handlers2, version) {
11
14
  program2.command("init").description("Initialize runtime scaffolding for a project.").option("-a, --adapter <value>", "Default SDK adapter to configure.", "mock").option("-o, --output <value>", "Output directory for generated scaffolding.", ".").option("-f, --force", "Overwrite existing files without prompting.", false).action(async (opts, cmd) => {
12
15
  await handlers2.init(opts, cmd.optsWithGlobals());
13
16
  });
14
- program2.command("generate").description("Generate runtime contracts and hooks from DSL.").option("--clean", "Delete generated_dir before regenerating.\nRemoves stale files that may remain from previous generations.\n", false).option("--check", "Dry-run mode for CI. Does not write files.\nCompares current generated output with what would be regenerated.\nExits with code 1 if any differences are found.\n", false).action(async (opts, cmd) => {
17
+ program2.command("generate").description("Generate runtime contracts and hooks from DSL.").option("--clean", "Delete generated_dir before regenerating.\nRemoves stale files that may remain from previous generations.\n", false).option("--check", "Dry-run mode for CI. Does not write files.\nCompares current generated output with what would be regenerated.\nExits with code 1 if any differences are found.\n", false).option("-t, --templates <value>", "Custom templates directory. Overrides built-in templates.").action(async (opts, cmd) => {
15
18
  await handlers2.generate(opts, cmd.optsWithGlobals());
16
19
  });
17
20
  program2.command("run").description("Execute a workflow.").argument("<workflow-id>", "ID of the workflow to execute (e.g. feature-implement, issue-fix).").argument("<user-request>", "Natural language description of what to do.").option("-a, --adapter <value>", "SDK adapter to use. Overrides config.").option("-r, --max-retries <value>", "Override default max retries per step.").option("-n, --dry-run", "Simulate execution without calling the SDK adapter.", false).option("--auto-approve-gates", "Automatically approve all gate steps.", false).action(async (workflowId, userRequest, opts, cmd) => {
@@ -30,31 +33,50 @@ function createProgram(handlers2, version) {
30
33
  }
31
34
 
32
35
  // src/cli/index.ts
33
- var VERSION = "0.0.3";
36
+ var VERSION = "0.2.0";
34
37
  var handlers = {
35
38
  async init(options, _globalOpts) {
36
- console.log("agent-runtime init \u2014 not yet implemented (Phase 2)");
39
+ console.log("agent-runtime init \u2014 not yet implemented");
37
40
  console.log("Options:", JSON.stringify(options));
38
41
  },
39
- async generate(options, _globalOpts) {
40
- console.log("agent-runtime generate \u2014 not yet implemented (Phase 2)");
41
- console.log("Options:", JSON.stringify(options));
42
+ async generate(options, globalOpts) {
43
+ try {
44
+ const configPath = globalOpts.config ?? "./agent-runtime.config.yaml";
45
+ const result = await generate({
46
+ clean: options.clean,
47
+ check: options.check,
48
+ templates: options.templates,
49
+ configPath
50
+ });
51
+ if (result.checkMode) {
52
+ if (result.hasDifferences) {
53
+ console.error("Generated files are out of date. Run `agent-runtime generate` to update.");
54
+ process.exit(1);
55
+ }
56
+ console.log(JSON.stringify({ ...result, status: "up-to-date" }, null, 2));
57
+ } else {
58
+ console.log(JSON.stringify(result, null, 2));
59
+ }
60
+ } catch (err) {
61
+ console.error("Generate failed:", err.message);
62
+ process.exit(1);
63
+ }
42
64
  },
43
65
  async run(workflowId, userRequest, options, _globalOpts) {
44
- console.log("agent-runtime run \u2014 not yet implemented (Phase 2)");
66
+ console.log("agent-runtime run \u2014 not yet implemented");
45
67
  console.log(`Workflow: ${workflowId}, Request: ${userRequest}`);
46
68
  console.log("Options:", JSON.stringify(options));
47
69
  },
48
70
  async list(resource, options, _globalOpts) {
49
- console.log("agent-runtime list \u2014 not yet implemented (Phase 2)");
71
+ console.log("agent-runtime list \u2014 not yet implemented");
50
72
  console.log(`Resource: ${resource}`);
51
73
  console.log("Options:", JSON.stringify(options));
52
74
  },
53
75
  async doctor(_globalOpts) {
54
- console.log("agent-runtime doctor \u2014 not yet implemented (Phase 2)");
76
+ console.log("agent-runtime doctor \u2014 not yet implemented");
55
77
  },
56
78
  async replay(runDir, options, _globalOpts) {
57
- console.log("agent-runtime replay \u2014 not yet implemented (Phase 3)");
79
+ console.log("agent-runtime replay \u2014 not yet implemented");
58
80
  console.log(`Run dir: ${runDir}`);
59
81
  console.log("Options:", JSON.stringify(options));
60
82
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/generated/cli/program.ts","../../src/cli/index.ts"],"sourcesContent":["// Auto-generated by cli-contracts. Do not edit.\nimport { Command } from \"commander\";\n\nexport interface CommandHandlers {\n init: (options: { adapter?: string; output?: string; force?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n generate: (options: { clean?: boolean; check?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n run: (workflowId: string | undefined, userRequest: string | undefined, options: { adapter?: string; maxRetries?: string; dryRun?: boolean; autoApproveGates?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n list: (resource: string | undefined, options: { format?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n doctor: (parentOpts: Record<string, unknown>) => Promise<void>;\n replay: (runDir: string | undefined, options: { validateOnly?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n}\n\nexport function createProgram(\n handlers: CommandHandlers,\n version: string,\n): Command {\n const program = new Command();\n program\n .name(\"agent-runtime\")\n .version(version, \"-V, --version\")\n .description(\"CLI for agent-contracts-runtime — generate, run, and manage agent workflows.\");\n\n program.option(\"-c, --config <value>\", \"Path to agent-runtime.config.yaml.\", \"./agent-runtime.config.yaml\");\n program.option(\"-v, --verbose\", \"Enable verbose output.\", false);\n program.option(\"-q, --quiet\", \"Suppress non-error output.\", false);\n\n program\n .command(\"init\")\n .description(\"Initialize runtime scaffolding for a project.\")\n .option(\"-a, --adapter <value>\", \"Default SDK adapter to configure.\", \"mock\")\n .option(\"-o, --output <value>\", \"Output directory for generated scaffolding.\", \".\")\n .option(\"-f, --force\", \"Overwrite existing files without prompting.\", false)\n .action(async (opts, cmd) => {\n await handlers.init(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"generate\")\n .description(\"Generate runtime contracts and hooks from DSL.\")\n .option(\"--clean\", \"Delete generated_dir before regenerating.\\nRemoves stale files that may remain from previous generations.\\n\", false)\n .option(\"--check\", \"Dry-run mode for CI. Does not write files.\\nCompares current generated output with what would be regenerated.\\nExits with code 1 if any differences are found.\\n\", false)\n .action(async (opts, cmd) => {\n await handlers.generate(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"run\")\n .description(\"Execute a workflow.\")\n .argument(\"<workflow-id>\", \"ID of the workflow to execute (e.g. feature-implement, issue-fix).\")\n .argument(\"<user-request>\", \"Natural language description of what to do.\")\n .option(\"-a, --adapter <value>\", \"SDK adapter to use. Overrides config.\")\n .option(\"-r, --max-retries <value>\", \"Override default max retries per step.\")\n .option(\"-n, --dry-run\", \"Simulate execution without calling the SDK adapter.\", false)\n .option(\"--auto-approve-gates\", \"Automatically approve all gate steps.\", false)\n .action(async (workflowId, userRequest, opts, cmd) => {\n await handlers.run(workflowId, userRequest, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"list\")\n .description(\"List available workflows, tasks, or agents.\")\n .argument(\"<resource>\", \"Type of resource to list.\")\n .option(\"--format <value>\", \"Output format.\", \"table\")\n .action(async (resource, opts, cmd) => {\n await handlers.list(resource, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"doctor\")\n .description(\"Verify configuration, generated files, and SDK connectivity.\")\n .action(async (opts, cmd) => {\n await handlers.doctor({}, cmd.optsWithGlobals());\n });\n\n program\n .command(\"replay\")\n .description(\"Replay a past workflow execution from logs.\")\n .argument(\"<run-dir>\", \"Path to the .agent-runs/<run-id> directory.\")\n .option(\"--validate-only\", \"Only validate the run log without re-execution.\", false)\n .action(async (runDir, opts, cmd) => {\n await handlers.replay(runDir, opts, cmd.optsWithGlobals());\n });\n\n return program;\n}\n","#!/usr/bin/env node\n\n/**\n * agent-runtime CLI entry point\n *\n * Uses auto-generated program from cli-contract.yaml.\n * Handler implementations are stubs for v0.0.x — full logic in Phase 2.\n */\n\nimport { createProgram, type CommandHandlers } from \"../generated/cli/program.js\";\n\nconst VERSION = \"0.0.3\";\n\nconst handlers: CommandHandlers = {\n async init(options, _globalOpts) {\n console.log(\"agent-runtime init — not yet implemented (Phase 2)\");\n console.log(\"Options:\", JSON.stringify(options));\n },\n\n async generate(options, _globalOpts) {\n console.log(\"agent-runtime generate — not yet implemented (Phase 2)\");\n console.log(\"Options:\", JSON.stringify(options));\n },\n\n async run(workflowId, userRequest, options, _globalOpts) {\n console.log(\"agent-runtime run — not yet implemented (Phase 2)\");\n console.log(`Workflow: ${workflowId}, Request: ${userRequest}`);\n console.log(\"Options:\", JSON.stringify(options));\n },\n\n async list(resource, options, _globalOpts) {\n console.log(\"agent-runtime list — not yet implemented (Phase 2)\");\n console.log(`Resource: ${resource}`);\n console.log(\"Options:\", JSON.stringify(options));\n },\n\n async doctor(_globalOpts) {\n console.log(\"agent-runtime doctor — not yet implemented (Phase 2)\");\n },\n\n async replay(runDir, options, _globalOpts) {\n console.log(\"agent-runtime replay — not yet implemented (Phase 3)\");\n console.log(`Run dir: ${runDir}`);\n console.log(\"Options:\", JSON.stringify(options));\n },\n};\n\nconst program = createProgram(handlers, VERSION);\nprogram.parse();\n"],"mappings":";;;AACA,SAAS,eAAe;AAWjB,SAAS,cACdA,WACA,SACS;AACT,QAAMC,WAAU,IAAI,QAAQ;AAC5B,EAAAA,SACG,KAAK,eAAe,EACpB,QAAQ,SAAS,eAAe,EAChC,YAAY,mFAA8E;AAE7F,EAAAA,SAAQ,OAAO,wBAAwB,sCAAsC,6BAA6B;AAC1G,EAAAA,SAAQ,OAAO,iBAAiB,0BAA0B,KAAK;AAC/D,EAAAA,SAAQ,OAAO,eAAe,8BAA8B,KAAK;AAEjE,EAAAA,SACG,QAAQ,MAAM,EACd,YAAY,+CAA+C,EAC3D,OAAO,yBAAyB,qCAAqC,MAAM,EAC3E,OAAO,wBAAwB,+CAA+C,GAAG,EACjF,OAAO,eAAe,+CAA+C,KAAK,EAC1E,OAAO,OAAO,MAAM,QAAQ;AAC3B,UAAMD,UAAS,KAAK,MAAM,IAAI,gBAAgB,CAAC;AAAA,EACjD,CAAC;AAEH,EAAAC,SACG,QAAQ,UAAU,EAClB,YAAY,gDAAgD,EAC5D,OAAO,WAAW,+GAA+G,KAAK,EACtI,OAAO,WAAW,oKAAoK,KAAK,EAC3L,OAAO,OAAO,MAAM,QAAQ;AAC3B,UAAMD,UAAS,SAAS,MAAM,IAAI,gBAAgB,CAAC;AAAA,EACrD,CAAC;AAEH,EAAAC,SACG,QAAQ,KAAK,EACb,YAAY,qBAAqB,EACjC,SAAS,iBAAiB,oEAAoE,EAC9F,SAAS,kBAAkB,6CAA6C,EACxE,OAAO,yBAAyB,uCAAuC,EACvE,OAAO,6BAA6B,wCAAwC,EAC5E,OAAO,iBAAiB,uDAAuD,KAAK,EACpF,OAAO,wBAAwB,yCAAyC,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O,CAAC;AAAA,EACjD;AAAA,EAEA,MAAM,KAAK,UAAU,SAAS,aAAa;AACzC,YAAQ,IAAI,yDAAoD;AAChE,YAAQ,IAAI,aAAa,QAAQ,EAAE;AACnC,YAAQ,IAAI,YAAY,KAAK,UAAU,OAAO,CAAC;AAAA,EACjD;AAAA,EAEA,MAAM,OAAO,aAAa;AACxB,YAAQ,IAAI,2DAAsD;AAAA,EACpE;AAAA,EAEA,MAAM,OAAO,QAAQ,SAAS,aAAa;AACzC,YAAQ,IAAI,2DAAsD;AAClE,YAAQ,IAAI,YAAY,MAAM,EAAE;AAChC,YAAQ,IAAI,YAAY,KAAK,UAAU,OAAO,CAAC;AAAA,EACjD;AACF;AAEA,IAAM,UAAU,cAAc,UAAU,OAAO;AAC/C,QAAQ,MAAM;","names":["handlers","program"]}
1
+ {"version":3,"sources":["../../src/generated/cli/program.ts","../../src/cli/index.ts"],"sourcesContent":["// Auto-generated by cli-contracts. Do not edit.\nimport { Command } from \"commander\";\n\nexport interface CommandHandlers {\n init: (options: { adapter?: string; output?: string; force?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n generate: (options: { clean?: boolean; check?: boolean; templates?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n run: (workflowId: string | undefined, userRequest: string | undefined, options: { adapter?: string; maxRetries?: string; dryRun?: boolean; autoApproveGates?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n list: (resource: string | undefined, options: { format?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n doctor: (parentOpts: Record<string, unknown>) => Promise<void>;\n replay: (runDir: string | undefined, options: { validateOnly?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n}\n\nexport function createProgram(\n handlers: CommandHandlers,\n version: string,\n): Command {\n const program = new Command();\n program\n .name(\"agent-runtime\")\n .version(version, \"-V, --version\")\n .description(\"CLI for agent-contracts-runtime — generate, run, and manage agent workflows.\");\n\n program.option(\"-c, --config <value>\", \"Path to agent-runtime.config.yaml.\", \"./agent-runtime.config.yaml\");\n program.option(\"-v, --verbose\", \"Enable verbose output.\", false);\n program.option(\"-q, --quiet\", \"Suppress non-error output.\", false);\n\n program\n .command(\"init\")\n .description(\"Initialize runtime scaffolding for a project.\")\n .option(\"-a, --adapter <value>\", \"Default SDK adapter to configure.\", \"mock\")\n .option(\"-o, --output <value>\", \"Output directory for generated scaffolding.\", \".\")\n .option(\"-f, --force\", \"Overwrite existing files without prompting.\", false)\n .action(async (opts, cmd) => {\n await handlers.init(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"generate\")\n .description(\"Generate runtime contracts and hooks from DSL.\")\n .option(\"--clean\", \"Delete generated_dir before regenerating.\\nRemoves stale files that may remain from previous generations.\\n\", false)\n .option(\"--check\", \"Dry-run mode for CI. Does not write files.\\nCompares current generated output with what would be regenerated.\\nExits with code 1 if any differences are found.\\n\", false)\n .option(\"-t, --templates <value>\", \"Custom templates directory. Overrides built-in templates.\")\n .action(async (opts, cmd) => {\n await handlers.generate(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"run\")\n .description(\"Execute a workflow.\")\n .argument(\"<workflow-id>\", \"ID of the workflow to execute (e.g. feature-implement, issue-fix).\")\n .argument(\"<user-request>\", \"Natural language description of what to do.\")\n .option(\"-a, --adapter <value>\", \"SDK adapter to use. Overrides config.\")\n .option(\"-r, --max-retries <value>\", \"Override default max retries per step.\")\n .option(\"-n, --dry-run\", \"Simulate execution without calling the SDK adapter.\", false)\n .option(\"--auto-approve-gates\", \"Automatically approve all gate steps.\", false)\n .action(async (workflowId, userRequest, opts, cmd) => {\n await handlers.run(workflowId, userRequest, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"list\")\n .description(\"List available workflows, tasks, or agents.\")\n .argument(\"<resource>\", \"Type of resource to list.\")\n .option(\"--format <value>\", \"Output format.\", \"table\")\n .action(async (resource, opts, cmd) => {\n await handlers.list(resource, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"doctor\")\n .description(\"Verify configuration, generated files, and SDK connectivity.\")\n .action(async (opts, cmd) => {\n await handlers.doctor({}, cmd.optsWithGlobals());\n });\n\n program\n .command(\"replay\")\n .description(\"Replay a past workflow execution from logs.\")\n .argument(\"<run-dir>\", \"Path to the .agent-runs/<run-id> directory.\")\n .option(\"--validate-only\", \"Only validate the run log without re-execution.\", false)\n .action(async (runDir, opts, cmd) => {\n await handlers.replay(runDir, opts, cmd.optsWithGlobals());\n });\n\n return program;\n}\n","#!/usr/bin/env node\n\n/**\n * agent-runtime CLI entry point\n *\n * Uses auto-generated program from cli-contract.yaml.\n */\n\nimport { createProgram, type CommandHandlers } from \"../generated/cli/program.js\";\nimport { generate } from \"../generator/index.js\";\n\nconst VERSION = \"0.2.0\";\n\nconst handlers: CommandHandlers = {\n async init(options, _globalOpts) {\n console.log(\"agent-runtime init — not yet implemented\");\n console.log(\"Options:\", JSON.stringify(options));\n },\n\n async generate(options, globalOpts) {\n try {\n const configPath = (globalOpts.config as string) ?? \"./agent-runtime.config.yaml\";\n const result = await generate({\n clean: options.clean,\n check: options.check,\n templates: options.templates,\n configPath,\n });\n\n if (result.checkMode) {\n if (result.hasDifferences) {\n console.error(\"Generated files are out of date. Run `agent-runtime generate` to update.\");\n process.exit(1);\n }\n console.log(JSON.stringify({ ...result, status: \"up-to-date\" }, null, 2));\n } else {\n console.log(JSON.stringify(result, null, 2));\n }\n } catch (err) {\n console.error(\"Generate failed:\", (err as Error).message);\n process.exit(1);\n }\n },\n\n async run(workflowId, userRequest, options, _globalOpts) {\n console.log(\"agent-runtime run — not yet implemented\");\n console.log(`Workflow: ${workflowId}, Request: ${userRequest}`);\n console.log(\"Options:\", JSON.stringify(options));\n },\n\n async list(resource, options, _globalOpts) {\n console.log(\"agent-runtime list — not yet implemented\");\n console.log(`Resource: ${resource}`);\n console.log(\"Options:\", JSON.stringify(options));\n },\n\n async doctor(_globalOpts) {\n console.log(\"agent-runtime doctor — not yet implemented\");\n },\n\n async replay(runDir, options, _globalOpts) {\n console.log(\"agent-runtime replay — not yet implemented\");\n console.log(`Run dir: ${runDir}`);\n console.log(\"Options:\", JSON.stringify(options));\n },\n};\n\nconst program = createProgram(handlers, VERSION);\nprogram.parse();\n"],"mappings":";;;;;;AACA,SAAS,eAAe;AAWjB,SAAS,cACdA,WACA,SACS;AACT,QAAMC,WAAU,IAAI,QAAQ;AAC5B,EAAAA,SACG,KAAK,eAAe,EACpB,QAAQ,SAAS,eAAe,EAChC,YAAY,mFAA8E;AAE7F,EAAAA,SAAQ,OAAO,wBAAwB,sCAAsC,6BAA6B;AAC1G,EAAAA,SAAQ,OAAO,iBAAiB,0BAA0B,KAAK;AAC/D,EAAAA,SAAQ,OAAO,eAAe,8BAA8B,KAAK;AAEjE,EAAAA,SACG,QAAQ,MAAM,EACd,YAAY,+CAA+C,EAC3D,OAAO,yBAAyB,qCAAqC,MAAM,EAC3E,OAAO,wBAAwB,+CAA+C,GAAG,EACjF,OAAO,eAAe,+CAA+C,KAAK,EAC1E,OAAO,OAAO,MAAM,QAAQ;AAC3B,UAAMD,UAAS,KAAK,MAAM,IAAI,gBAAgB,CAAC;AAAA,EACjD,CAAC;AAEH,EAAAC,SACG,QAAQ,UAAU,EAClB,YAAY,gDAAgD,EAC5D,OAAO,WAAW,+GAA+G,KAAK,EACtI,OAAO,WAAW,oKAAoK,KAAK,EAC3L,OAAO,2BAA2B,2DAA2D,EAC7F,OAAO,OAAO,MAAM,QAAQ;AAC3B,UAAMD,UAAS,SAAS,MAAM,IAAI,gBAAgB,CAAC;AAAA,EACrD,CAAC;AAEH,EAAAC,SACG,QAAQ,KAAK,EACb,YAAY,qBAAqB,EACjC,SAAS,iBAAiB,oEAAoE,EAC9F,SAAS,kBAAkB,6CAA6C,EACxE,OAAO,yBAAyB,uCAAuC,EACvE,OAAO,6BAA6B,wCAAwC,EAC5E,OAAO,iBAAiB,uDAAuD,KAAK,EACpF,OAAO,wBAAwB,yCAAyC,KAAK,EAC7E,OAAO,OAAO,YAAY,aAAa,MAAM,QAAQ;A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