@agentspec/cli 0.2.3 → 0.4.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.
Files changed (4) hide show
  1. package/LICENSE +183 -0
  2. package/dist/cli.js +1049 -291
  3. package/dist/cli.js.map +1 -1
  4. package/package.json +12 -13
package/dist/cli.js CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { Command } from "commander";
5
- import { readFileSync as readFileSync6 } from "fs";
5
+ import { readFileSync as readFileSync8 } from "fs";
6
6
  import { fileURLToPath } from "url";
7
- import { dirname as dirname3, join as join5 } from "path";
7
+ import { dirname as dirname4, join as join7 } from "path";
8
8
 
9
9
  // src/commands/validate.ts
10
10
  import chalk2 from "chalk";
@@ -149,11 +149,37 @@ function registerValidateCommand(program2) {
149
149
  }
150
150
 
151
151
  // src/commands/health.ts
152
+ import { existsSync, readFileSync } from "fs";
153
+ import { dirname, join, resolve } from "path";
152
154
  import chalk3 from "chalk";
153
155
  import { loadManifest as loadManifest2, runHealthCheck } from "@agentspec/sdk";
156
+ function loadDotEnv(envPath) {
157
+ let raw;
158
+ try {
159
+ raw = readFileSync(envPath, "utf-8");
160
+ } catch {
161
+ return;
162
+ }
163
+ for (const line of raw.split("\n")) {
164
+ const trimmed = line.trim();
165
+ if (!trimmed || trimmed.startsWith("#")) continue;
166
+ const eqIdx = trimmed.indexOf("=");
167
+ if (eqIdx < 1) continue;
168
+ const key = trimmed.slice(0, eqIdx).trim();
169
+ const val = trimmed.slice(eqIdx + 1).trim().replace(/^["']|["']$/g, "");
170
+ if (key && !(key in process.env)) {
171
+ process.env[key] = val;
172
+ }
173
+ }
174
+ }
154
175
  function registerHealthCommand(program2) {
155
- program2.command("health <file>").description("Run runtime health checks against all declared dependencies").option("--json", "Output as JSON").option("--format <fmt>", "Output format: table|json", "table").option("--fail-on <level>", "Exit 1 on: error|warning|info", "error").option("--no-model", "Skip model API reachability checks").option("--no-mcp", "Skip MCP server checks").option("--no-memory", "Skip memory backend checks").action(
176
+ program2.command("health <file>").description("Run runtime health checks against all declared dependencies").option("--json", "Output as JSON").option("--format <fmt>", "Output format: table|json", "table").option("--fail-on <level>", "Exit 1 on: error|warning|info", "error").option("--no-model", "Skip model API reachability checks").option("--no-mcp", "Skip MCP server checks").option("--no-memory", "Skip memory backend checks").option("--env-file <path>", "Load env vars from a .env file before running checks").action(
156
177
  async (file, opts) => {
178
+ const manifestDir = dirname(resolve(file));
179
+ const envFilePath = opts.envFile ? resolve(opts.envFile) : join(manifestDir, ".env");
180
+ if (existsSync(envFilePath)) {
181
+ loadDotEnv(envFilePath);
182
+ }
157
183
  let manifest;
158
184
  try {
159
185
  manifest = loadManifest2(file, { resolve: false });
@@ -426,123 +452,30 @@ function renderDualModeViolations(violations, report, sidecarUrl) {
426
452
  }
427
453
 
428
454
  // src/commands/init.ts
429
- import { writeFileSync as writeFileSync2, existsSync } from "fs";
430
- import { resolve, join } from "path";
455
+ import { writeFileSync as writeFileSync2, existsSync as existsSync2, mkdirSync } from "fs";
456
+ import { resolve as resolve2, join as join2 } from "path";
431
457
  import chalk5 from "chalk";
432
458
  import * as p from "@clack/prompts";
433
- function registerInitCommand(program2) {
434
- program2.command("init [dir]").description("Interactive wizard to create a new agent.yaml manifest").option("--yes", "Skip prompts, create a minimal manifest").action(async (dir = ".", opts) => {
435
- const outDir = resolve(dir);
436
- const outFile = join(outDir, "agent.yaml");
437
- printHeader("AgentSpec Init");
438
- if (existsSync(outFile) && !opts.yes) {
439
- const overwrite = await p.confirm({
440
- message: `agent.yaml already exists at ${outFile}. Overwrite?`,
441
- initialValue: false
442
- });
443
- if (!overwrite || p.isCancel(overwrite)) {
444
- p.cancel("Init cancelled.");
445
- return;
446
- }
447
- }
448
- let name = "my-agent";
449
- let description = "An AI agent";
450
- let version2 = "0.1.0";
451
- let provider = "openai";
452
- let modelId = "gpt-4o-mini";
453
- let includeMemory = false;
454
- let includeGuardrails = true;
455
- let includeEval = false;
456
- if (!opts.yes) {
457
- p.intro(chalk5.cyan("Creating your agent.yaml"));
458
- const answers = await p.group(
459
- {
460
- name: () => p.text({
461
- message: "Agent name (slug)",
462
- placeholder: "my-agent",
463
- validate: (v) => /^[a-z0-9-]+$/.test(v) ? void 0 : "Must be lowercase slug (a-z, 0-9, -)"
464
- }),
465
- description: () => p.text({
466
- message: "Description",
467
- placeholder: "An AI agent that..."
468
- }),
469
- version: () => p.text({
470
- message: "Version",
471
- placeholder: "0.1.0",
472
- initialValue: "0.1.0"
473
- }),
474
- provider: () => p.select({
475
- message: "Model provider",
476
- options: [
477
- { value: "openai", label: "OpenAI" },
478
- { value: "anthropic", label: "Anthropic" },
479
- { value: "groq", label: "Groq" },
480
- { value: "google", label: "Google" },
481
- { value: "mistral", label: "Mistral" },
482
- { value: "azure", label: "Azure OpenAI" }
483
- ]
484
- }),
485
- modelId: () => p.text({
486
- message: "Model ID",
487
- placeholder: "gpt-4o-mini"
488
- }),
489
- includeMemory: () => p.confirm({
490
- message: "Include memory configuration?",
491
- initialValue: false
492
- }),
493
- includeGuardrails: () => p.confirm({
494
- message: "Include guardrails?",
495
- initialValue: true
496
- }),
497
- includeEval: () => p.confirm({
498
- message: "Include evaluation configuration?",
499
- initialValue: false
500
- })
501
- },
502
- {
503
- onCancel: () => {
504
- p.cancel("Init cancelled.");
505
- process.exit(0);
506
- }
507
- }
508
- );
509
- name = String(answers.name || "my-agent");
510
- description = String(answers.description || "An AI agent");
511
- version2 = String(answers.version || "0.1.0");
512
- provider = String(answers.provider || "openai");
513
- modelId = String(answers.modelId || "gpt-4o-mini");
514
- includeMemory = Boolean(answers.includeMemory);
515
- includeGuardrails = Boolean(answers.includeGuardrails);
516
- includeEval = Boolean(answers.includeEval);
517
- }
518
- const apiKeyEnv = `${provider.toUpperCase()}_API_KEY`;
519
- const yaml3 = generateManifest({
520
- name,
521
- description,
522
- version: version2,
523
- provider,
524
- modelId,
525
- apiKeyEnv,
526
- includeMemory,
527
- includeGuardrails,
528
- includeEval
529
- });
530
- writeFileSync2(outFile, yaml3, "utf-8");
531
- if (!opts.yes) p.outro(chalk5.green(`\u2713 Created ${outFile}`));
532
- else console.log(chalk5.green(`
533
- \u2713 Created ${outFile}
534
- `));
535
- console.log(chalk5.gray(" Next steps:"));
536
- console.log(chalk5.gray(` 1. Edit ${outFile} to customize your agent`));
537
- console.log(chalk5.gray(` 2. Run: npx agentspec validate agent.yaml`));
538
- console.log(chalk5.gray(` 3. Run: npx agentspec health agent.yaml`));
539
- console.log(chalk5.gray(` 4. Run: npx agentspec audit agent.yaml`));
540
- console.log();
541
- });
542
- }
543
- function generateManifest(opts) {
544
- const sections = [
545
- `apiVersion: agentspec.io/v1
459
+
460
+ // src/commands/init-helpers.ts
461
+ var PROVIDER_DEFAULTS = {
462
+ openai: "gpt-4o-mini",
463
+ anthropic: "claude-sonnet-4-6",
464
+ groq: "llama-3.3-70b-versatile",
465
+ google: "gemini-2.0-flash",
466
+ mistral: "mistral-large-latest",
467
+ azure: "gpt-4o"
468
+ };
469
+ var PROVIDER_ENV_KEYS = {
470
+ openai: "OPENAI_API_KEY",
471
+ anthropic: "ANTHROPIC_API_KEY",
472
+ groq: "GROQ_API_KEY",
473
+ google: "GOOGLE_API_KEY",
474
+ mistral: "MISTRAL_API_KEY",
475
+ azure: "AZURE_OPENAI_API_KEY"
476
+ };
477
+ function generateMetadataSection(opts) {
478
+ return `apiVersion: agentspec.io/v1
546
479
  kind: AgentSpec
547
480
 
548
481
  metadata:
@@ -553,12 +486,16 @@ metadata:
553
486
  author: ""
554
487
  license: MIT
555
488
 
556
- spec:
489
+ spec:`;
490
+ }
491
+ function generateModelSection(opts) {
492
+ const apiKeyEnv = PROVIDER_ENV_KEYS[opts.provider] ?? `${opts.provider.toUpperCase()}_API_KEY`;
493
+ return `
557
494
  # \u2500\u2500 MODEL \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
558
495
  model:
559
496
  provider: ${opts.provider}
560
497
  id: ${opts.modelId}
561
- apiKey: $env:${opts.apiKeyEnv}
498
+ apiKey: $env:${apiKeyEnv}
562
499
  parameters:
563
500
  temperature: 0.7
564
501
  maxTokens: 2000
@@ -568,14 +505,31 @@ spec:
568
505
  # id: gpt-4o-mini
569
506
  # apiKey: $env:OPENAI_API_KEY
570
507
  # triggerOn: [rate_limit, timeout, error_5xx]
571
- # maxRetries: 2
572
-
508
+ # maxRetries: 2`;
509
+ }
510
+ function generatePromptsSection() {
511
+ return `
573
512
  # \u2500\u2500 PROMPTS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
574
513
  prompts:
575
514
  system: $file:prompts/system.md
576
515
  fallback: "I'm experiencing difficulties. Please try again."
577
- hotReload: false
578
-
516
+ hotReload: false`;
517
+ }
518
+ function generateToolsSection(include) {
519
+ if (include) {
520
+ return `
521
+ # \u2500\u2500 TOOLS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
522
+ tools:
523
+ - name: my-tool
524
+ type: function
525
+ description: "Description of what this tool does"
526
+ module: $file:tools/my_tool.py
527
+ function: my_tool_function
528
+ annotations:
529
+ readOnlyHint: true
530
+ destructiveHint: false`;
531
+ }
532
+ return `
579
533
  # \u2500\u2500 TOOLS (optional) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
580
534
  # tools:
581
535
  # - name: my-tool
@@ -585,22 +539,58 @@ spec:
585
539
  # function: my_tool_function
586
540
  # annotations:
587
541
  # readOnlyHint: true
588
- # destructiveHint: false`
589
- ];
590
- if (opts.includeMemory) {
591
- sections.push(`
542
+ # destructiveHint: false`;
543
+ }
544
+ function generateMemorySection(opts) {
545
+ const backend = opts.memoryBackend ?? "in-memory";
546
+ let connectionLine = "";
547
+ if (backend === "redis") {
548
+ connectionLine = "\n connection: $env:REDIS_URL";
549
+ } else if (backend === "sqlite") {
550
+ connectionLine = "\n connection: file:./data/memory.db";
551
+ }
552
+ return `
592
553
  # \u2500\u2500 MEMORY \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
593
554
  memory:
594
555
  shortTerm:
595
- backend: in-memory
556
+ backend: ${backend}
596
557
  maxTurns: 20
597
- maxTokens: 8000
558
+ maxTokens: 8000${connectionLine}
598
559
  hygiene:
599
560
  piiScrubFields: []
600
- auditLog: false`);
601
- }
602
- if (opts.includeGuardrails) {
603
- sections.push(`
561
+ auditLog: false`;
562
+ }
563
+ function generateDefaultApiSection() {
564
+ return `
565
+ # \u2500\u2500 API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
566
+ api:
567
+ type: rest
568
+ port: 8000
569
+ pathPrefix: /v1
570
+ corsOrigins: ["*"]`;
571
+ }
572
+ function generateApiSection(opts) {
573
+ const apiType = opts.apiType ?? "rest";
574
+ const port = opts.apiPort ?? 3e3;
575
+ if (apiType === "mcp") {
576
+ return `
577
+ # \u2500\u2500 API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
578
+ api:
579
+ type: mcp
580
+ port: ${port}`;
581
+ }
582
+ return `
583
+ # \u2500\u2500 API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
584
+ api:
585
+ type: rest
586
+ port: ${port}
587
+ chat:
588
+ path: /v1/chat
589
+ protocol: openai-compatible
590
+ streaming: true`;
591
+ }
592
+ function generateGuardrailsSection() {
593
+ return `
604
594
  # \u2500\u2500 GUARDRAILS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
605
595
  guardrails:
606
596
  input:
@@ -610,10 +600,10 @@ spec:
610
600
  output:
611
601
  - type: toxicity-filter
612
602
  threshold: 0.7
613
- action: reject`);
614
- }
615
- if (opts.includeEval) {
616
- sections.push(`
603
+ action: reject`;
604
+ }
605
+ function generateEvalSection() {
606
+ return `
617
607
  # \u2500\u2500 EVALUATION \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
618
608
  evaluation:
619
609
  framework: deepeval
@@ -625,27 +615,399 @@ spec:
625
615
  - hallucination
626
616
  thresholds:
627
617
  hallucination: 0.05
628
- ciGate: false`);
629
- }
630
- sections.push(`
618
+ ciGate: false`;
619
+ }
620
+ function generateObservabilitySection(opts) {
621
+ const backend = opts.tracingBackend ?? "langfuse";
622
+ let tracingConfig;
623
+ if (backend === "langfuse") {
624
+ tracingConfig = ` backend: langfuse
625
+ publicKey: $env:LANGFUSE_PUBLIC_KEY
626
+ secretKey: $env:LANGFUSE_SECRET_KEY`;
627
+ } else if (backend === "otel") {
628
+ tracingConfig = ` backend: otel
629
+ endpoint: $env:OTEL_EXPORTER_OTLP_ENDPOINT`;
630
+ } else {
631
+ tracingConfig = ` backend: datadog
632
+ endpoint: $env:DD_TRACE_AGENT_URL`;
633
+ }
634
+ return `
635
+ # \u2500\u2500 OBSERVABILITY \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
636
+ observability:
637
+ tracing:
638
+ ${tracingConfig}
639
+ logging:
640
+ level: info
641
+ structured: true`;
642
+ }
643
+ function generateComplianceSection() {
644
+ return `
631
645
  # \u2500\u2500 COMPLIANCE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
632
646
  compliance:
633
647
  packs:
634
648
  - owasp-llm-top10
635
649
  - model-resilience
636
- - memory-hygiene
637
-
650
+ - memory-hygiene`;
651
+ }
652
+ function generateRequiresSection(envVars) {
653
+ const envLines = envVars.map((v) => ` - ${v}`).join("\n");
654
+ return `
638
655
  # \u2500\u2500 RUNTIME REQUIREMENTS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
639
656
  requires:
640
657
  envVars:
641
- - ${opts.apiKeyEnv}
642
- `);
658
+ ${envLines}
659
+ `;
660
+ }
661
+ function collectRequiredEnvVars(opts) {
662
+ const vars = [];
663
+ const providerKey = PROVIDER_ENV_KEYS[opts.provider] ?? `${opts.provider.toUpperCase()}_API_KEY`;
664
+ vars.push(providerKey);
665
+ if (opts.includeMemory && opts.memoryBackend === "redis") {
666
+ vars.push("REDIS_URL");
667
+ }
668
+ if (opts.includeObservability) {
669
+ const backend = opts.tracingBackend ?? "langfuse";
670
+ if (backend === "langfuse") {
671
+ vars.push("LANGFUSE_PUBLIC_KEY", "LANGFUSE_SECRET_KEY");
672
+ } else if (backend === "otel") {
673
+ vars.push("OTEL_EXPORTER_OTLP_ENDPOINT");
674
+ } else if (backend === "datadog") {
675
+ vars.push("DD_TRACE_AGENT_URL");
676
+ }
677
+ }
678
+ return vars;
679
+ }
680
+ function generateManifest(opts) {
681
+ const envVars = collectRequiredEnvVars(opts);
682
+ const sections = [
683
+ generateMetadataSection(opts),
684
+ generateModelSection(opts),
685
+ generatePromptsSection(),
686
+ generateToolsSection(opts.includeToolsStarter)
687
+ ];
688
+ if (opts.includeMemory) sections.push(generateMemorySection(opts));
689
+ if (opts.includeApi) sections.push(opts.apiType || opts.apiPort ? generateApiSection(opts) : generateDefaultApiSection());
690
+ if (opts.includeGuardrails) sections.push(generateGuardrailsSection());
691
+ if (opts.includeEval) sections.push(generateEvalSection());
692
+ if (opts.includeObservability) sections.push(generateObservabilitySection(opts));
693
+ sections.push(generateComplianceSection());
694
+ sections.push(generateRequiresSection(envVars));
643
695
  return sections.join("\n");
644
696
  }
697
+ function generateSystemPrompt(name, description) {
698
+ const title = name.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
699
+ return `# ${title}
700
+
701
+ ${description}
702
+
703
+ ## Instructions
704
+
705
+ - Be helpful and concise
706
+ - Follow the user's instructions carefully
707
+ - Ask for clarification when the request is ambiguous
708
+ `;
709
+ }
710
+ async function fetchAvailableModels(provider) {
711
+ const controller = new AbortController();
712
+ const timeout = setTimeout(() => controller.abort(), 5e3);
713
+ try {
714
+ const res = await fetch("https://openrouter.ai/api/v1/models", {
715
+ signal: controller.signal
716
+ });
717
+ if (!res.ok) return null;
718
+ const json = await res.json();
719
+ if (!json.data || !Array.isArray(json.data)) return null;
720
+ const prefix = provider + "/";
721
+ return json.data.map((m) => m.id).filter((id) => id.startsWith(prefix) && !id.endsWith(":free")).map((id) => id.slice(prefix.length)).sort();
722
+ } catch {
723
+ return null;
724
+ } finally {
725
+ clearTimeout(timeout);
726
+ }
727
+ }
728
+ function generateEnvExample(name, envVars) {
729
+ const placeholders = {
730
+ OPENAI_API_KEY: "sk-your-openai-api-key",
731
+ ANTHROPIC_API_KEY: "sk-ant-your-anthropic-api-key",
732
+ GROQ_API_KEY: "gsk_your-groq-api-key",
733
+ GOOGLE_API_KEY: "your-google-api-key",
734
+ MISTRAL_API_KEY: "your-mistral-api-key",
735
+ AZURE_OPENAI_API_KEY: "your-azure-openai-api-key",
736
+ REDIS_URL: "redis://localhost:6379",
737
+ LANGFUSE_PUBLIC_KEY: "pk-lf-your-langfuse-public-key",
738
+ LANGFUSE_SECRET_KEY: "sk-lf-your-langfuse-secret-key",
739
+ OTEL_EXPORTER_OTLP_ENDPOINT: "http://localhost:4318",
740
+ DD_TRACE_AGENT_URL: "http://localhost:8126"
741
+ };
742
+ const lines = [`# Environment variables for ${name}`];
743
+ for (const v of envVars) {
744
+ lines.push(`${v}=${placeholders[v] ?? "your-value-here"}`);
745
+ }
746
+ return lines.join("\n") + "\n";
747
+ }
748
+
749
+ // src/commands/init.ts
750
+ function buildDefaultOptions() {
751
+ return {
752
+ name: "my-agent",
753
+ description: "An AI agent",
754
+ version: "0.1.0",
755
+ provider: "openai",
756
+ modelId: "gpt-4o-mini",
757
+ includeMemory: false,
758
+ includeApi: false,
759
+ includeObservability: false,
760
+ includeGuardrails: true,
761
+ includeEval: false,
762
+ includeToolsStarter: false
763
+ };
764
+ }
765
+ async function runPhase1() {
766
+ const basics = await p.group(
767
+ {
768
+ name: () => p.text({
769
+ message: "Agent name (slug)",
770
+ placeholder: "my-agent",
771
+ validate: (v) => /^[a-z0-9-]+$/.test(v) ? void 0 : "Must be lowercase slug (a-z, 0-9, -)"
772
+ }),
773
+ description: () => p.text({
774
+ message: "Description",
775
+ placeholder: "An AI agent that..."
776
+ }),
777
+ version: () => p.text({
778
+ message: "Version",
779
+ placeholder: "0.1.0",
780
+ initialValue: "0.1.0"
781
+ }),
782
+ provider: () => p.select({
783
+ message: "Model provider",
784
+ options: [
785
+ { value: "openai", label: "OpenAI" },
786
+ { value: "anthropic", label: "Anthropic" },
787
+ { value: "groq", label: "Groq" },
788
+ { value: "google", label: "Google" },
789
+ { value: "mistral", label: "Mistral" },
790
+ { value: "azure", label: "Azure OpenAI" }
791
+ ]
792
+ })
793
+ },
794
+ {
795
+ onCancel: () => {
796
+ p.cancel("Init cancelled.");
797
+ process.exit(0);
798
+ }
799
+ }
800
+ );
801
+ const provider = String(basics.provider || "openai");
802
+ const modelId = await selectModel(provider);
803
+ return {
804
+ ...basics,
805
+ modelId
806
+ };
807
+ }
808
+ async function selectModel(provider) {
809
+ const s = p.spinner();
810
+ s.start("Fetching available models...");
811
+ const models = await fetchAvailableModels(provider);
812
+ if (models && models.length > 0) {
813
+ s.stop("Models loaded");
814
+ const defaultModel = PROVIDER_DEFAULTS[provider];
815
+ const selected = await p.select({
816
+ message: "Model",
817
+ options: models.map((id) => ({ value: id, label: id })),
818
+ initialValue: models.includes(defaultModel) ? defaultModel : models[0]
819
+ });
820
+ if (p.isCancel(selected)) {
821
+ p.cancel("Init cancelled.");
822
+ process.exit(0);
823
+ }
824
+ return String(selected);
825
+ }
826
+ s.stop("Could not fetch models");
827
+ const modelId = await p.text({
828
+ message: "Model ID",
829
+ placeholder: PROVIDER_DEFAULTS[provider] ?? "gpt-4o-mini",
830
+ initialValue: PROVIDER_DEFAULTS[provider] ?? "gpt-4o-mini"
831
+ });
832
+ if (p.isCancel(modelId)) {
833
+ p.cancel("Init cancelled.");
834
+ process.exit(0);
835
+ }
836
+ return String(modelId);
837
+ }
838
+ async function runPhase2() {
839
+ const answers = await p.group(
840
+ {
841
+ includeMemory: () => p.confirm({
842
+ message: "Include memory configuration?",
843
+ initialValue: false
844
+ }),
845
+ includeApi: () => p.confirm({
846
+ message: "Include API endpoint configuration?",
847
+ initialValue: false
848
+ }),
849
+ includeObservability: () => p.confirm({
850
+ message: "Include observability (tracing/logging)?",
851
+ initialValue: false
852
+ }),
853
+ includeGuardrails: () => p.confirm({
854
+ message: "Include guardrails?",
855
+ initialValue: true
856
+ }),
857
+ includeEval: () => p.confirm({
858
+ message: "Include evaluation configuration?",
859
+ initialValue: false
860
+ }),
861
+ includeToolsStarter: () => p.confirm({
862
+ message: "Include starter tool template?",
863
+ initialValue: false
864
+ })
865
+ },
866
+ {
867
+ onCancel: () => {
868
+ p.cancel("Init cancelled.");
869
+ process.exit(0);
870
+ }
871
+ }
872
+ );
873
+ return answers;
874
+ }
875
+ async function runPhase3(phase2) {
876
+ const result = {};
877
+ if (phase2.includeMemory) {
878
+ const backend = await p.select({
879
+ message: "Memory backend",
880
+ options: [
881
+ { value: "in-memory", label: "In-memory (no persistence)" },
882
+ { value: "redis", label: "Redis" },
883
+ { value: "sqlite", label: "SQLite" }
884
+ ]
885
+ });
886
+ if (p.isCancel(backend)) {
887
+ p.cancel("Init cancelled.");
888
+ process.exit(0);
889
+ }
890
+ result.memoryBackend = backend;
891
+ }
892
+ if (phase2.includeApi) {
893
+ const apiType = await p.select({
894
+ message: "API type",
895
+ options: [
896
+ { value: "rest", label: "REST (OpenAI-compatible)" },
897
+ { value: "mcp", label: "MCP (Model Context Protocol)" }
898
+ ]
899
+ });
900
+ if (p.isCancel(apiType)) {
901
+ p.cancel("Init cancelled.");
902
+ process.exit(0);
903
+ }
904
+ result.apiType = apiType;
905
+ const port = await p.text({
906
+ message: "API port",
907
+ placeholder: "3000",
908
+ initialValue: "3000",
909
+ validate: (v) => {
910
+ const n = parseInt(v, 10);
911
+ return isNaN(n) || n < 1 || n > 65535 ? "Must be a valid port (1-65535)" : void 0;
912
+ }
913
+ });
914
+ if (p.isCancel(port)) {
915
+ p.cancel("Init cancelled.");
916
+ process.exit(0);
917
+ }
918
+ result.apiPort = parseInt(String(port), 10);
919
+ }
920
+ if (phase2.includeObservability) {
921
+ const backend = await p.select({
922
+ message: "Tracing backend",
923
+ options: [
924
+ { value: "langfuse", label: "Langfuse" },
925
+ { value: "otel", label: "OpenTelemetry (OTLP)" },
926
+ { value: "datadog", label: "Datadog" }
927
+ ]
928
+ });
929
+ if (p.isCancel(backend)) {
930
+ p.cancel("Init cancelled.");
931
+ process.exit(0);
932
+ }
933
+ result.tracingBackend = backend;
934
+ }
935
+ return result;
936
+ }
937
+ function scaffoldFiles(outDir, opts) {
938
+ const promptsDir = join2(outDir, "prompts");
939
+ const systemMdPath = join2(promptsDir, "system.md");
940
+ const envExamplePath = join2(outDir, ".env.example");
941
+ const envVars = collectRequiredEnvVars(opts);
942
+ mkdirSync(promptsDir, { recursive: true });
943
+ if (existsSync2(systemMdPath)) {
944
+ p.log.warn(`Skipped prompts/system.md (already exists)`);
945
+ } else {
946
+ writeFileSync2(systemMdPath, generateSystemPrompt(opts.name, opts.description), "utf-8");
947
+ }
948
+ if (existsSync2(envExamplePath)) {
949
+ p.log.warn(`Skipped .env.example (already exists)`);
950
+ } else {
951
+ writeFileSync2(envExamplePath, generateEnvExample(opts.name, envVars), "utf-8");
952
+ }
953
+ }
954
+ function registerInitCommand(program2) {
955
+ program2.command("init [dir]").description("Interactive wizard to create a new agent.yaml manifest").option("--yes", "Skip prompts, create a minimal manifest").action(async (dir = ".", cmdOpts) => {
956
+ const outDir = resolve2(dir);
957
+ const outFile = join2(outDir, "agent.yaml");
958
+ printHeader("AgentSpec Init");
959
+ if (existsSync2(outFile) && !cmdOpts.yes) {
960
+ const overwrite = await p.confirm({
961
+ message: `agent.yaml already exists at ${outFile}. Overwrite?`,
962
+ initialValue: false
963
+ });
964
+ if (!overwrite || p.isCancel(overwrite)) {
965
+ p.cancel("Init cancelled.");
966
+ return;
967
+ }
968
+ }
969
+ let opts;
970
+ if (cmdOpts.yes) {
971
+ opts = buildDefaultOptions();
972
+ } else {
973
+ p.intro(chalk5.cyan("Creating your agent.yaml"));
974
+ const phase1 = await runPhase1();
975
+ const phase2 = await runPhase2();
976
+ const phase3 = await runPhase3(phase2);
977
+ opts = {
978
+ name: String(phase1.name || "my-agent"),
979
+ description: String(phase1.description || "An AI agent"),
980
+ version: String(phase1.version || "0.1.0"),
981
+ provider: String(phase1.provider || "openai"),
982
+ modelId: String(phase1.modelId || "gpt-4o-mini"),
983
+ includeMemory: Boolean(phase2.includeMemory),
984
+ includeApi: Boolean(phase2.includeApi),
985
+ includeObservability: Boolean(phase2.includeObservability),
986
+ includeGuardrails: Boolean(phase2.includeGuardrails),
987
+ includeEval: Boolean(phase2.includeEval),
988
+ includeToolsStarter: Boolean(phase2.includeToolsStarter),
989
+ ...phase3
990
+ };
991
+ }
992
+ const yaml3 = generateManifest(opts);
993
+ writeFileSync2(outFile, yaml3, "utf-8");
994
+ scaffoldFiles(outDir, opts);
995
+ if (!cmdOpts.yes) p.outro(chalk5.green(`\u2713 Created ${outFile}`));
996
+ else console.log(chalk5.green(`
997
+ \u2713 Created ${outFile}
998
+ `));
999
+ console.log(chalk5.gray(" Next steps:"));
1000
+ console.log(chalk5.gray(` 1. Edit ${outFile} to customize your agent`));
1001
+ console.log(chalk5.gray(` 2. Run: npx agentspec validate agent.yaml`));
1002
+ console.log(chalk5.gray(` 3. Run: npx agentspec health agent.yaml`));
1003
+ console.log(chalk5.gray(` 4. Run: npx agentspec audit agent.yaml`));
1004
+ console.log();
1005
+ });
1006
+ }
645
1007
 
646
1008
  // src/commands/generate.ts
647
- import { existsSync as existsSync2, mkdirSync, readFileSync, writeFileSync as writeFileSync3 } from "fs";
648
- import { basename, dirname, join as join2, resolve as resolve2, sep } from "path";
1009
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "fs";
1010
+ import { basename, dirname as dirname2, join as join3, resolve as resolve3, sep } from "path";
649
1011
  import chalk6 from "chalk";
650
1012
 
651
1013
  // src/utils/spinner.ts
@@ -666,7 +1028,7 @@ function createFallbackSpinner() {
666
1028
  }
667
1029
  };
668
1030
  }
669
- function spinner() {
1031
+ function spinner2() {
670
1032
  if (process.stdout.isTTY) {
671
1033
  return clackSpinner();
672
1034
  }
@@ -675,7 +1037,7 @@ function spinner() {
675
1037
 
676
1038
  // src/commands/generate.ts
677
1039
  import { loadManifest as loadManifest4 } from "@agentspec/sdk";
678
- import { generateWithClaude, listFrameworks } from "@agentspec/adapter-claude";
1040
+ import { generateCode, listFrameworks, resolveProvider } from "@agentspec/codegen";
679
1041
 
680
1042
  // src/deploy/k8s.ts
681
1043
  var SIDECAR_IMAGE = "ghcr.io/agentspec/sidecar:latest";
@@ -815,29 +1177,29 @@ ${dataLines}
815
1177
  // src/commands/generate.ts
816
1178
  var DEPLOY_TARGETS = ["k8s", "helm"];
817
1179
  function writeGeneratedFiles(files, outDir) {
818
- const resolvedOutDir = resolve2(outDir);
819
- mkdirSync(resolvedOutDir, { recursive: true });
1180
+ const resolvedOutDir = resolve3(outDir);
1181
+ mkdirSync2(resolvedOutDir, { recursive: true });
820
1182
  const safeOutDir = resolvedOutDir.endsWith(sep) ? resolvedOutDir : resolvedOutDir + sep;
821
1183
  for (const [filename, content] of Object.entries(files)) {
822
- const outPath = resolve2(resolvedOutDir, filename);
1184
+ const outPath = resolve3(resolvedOutDir, filename);
823
1185
  if (!outPath.startsWith(safeOutDir) && outPath !== resolvedOutDir) {
824
1186
  throw new Error(`Rejected generated filename "${filename}" \u2014 path traversal detected`);
825
1187
  }
826
- mkdirSync(dirname(outPath), { recursive: true });
1188
+ mkdirSync2(dirname2(outPath), { recursive: true });
827
1189
  writeFileSync3(outPath, content, "utf-8");
828
1190
  console.log(` ${chalk6.green("\u2713")} ${filename}`);
829
1191
  }
830
1192
  }
831
1193
  function copyManifestToOutput(srcFile, outDir, alreadyGenerated) {
832
- const manifestSrc = resolve2(srcFile);
833
- const resolvedOutDir = resolve2(outDir);
834
- if (!existsSync2(manifestSrc) || alreadyGenerated[basename(manifestSrc)] !== void 0) {
1194
+ const manifestSrc = resolve3(srcFile);
1195
+ const resolvedOutDir = resolve3(outDir);
1196
+ if (!existsSync3(manifestSrc) || alreadyGenerated[basename(manifestSrc)] !== void 0) {
835
1197
  return;
836
1198
  }
837
1199
  try {
838
- let content = readFileSync(manifestSrc, "utf-8");
1200
+ let content = readFileSync2(manifestSrc, "utf-8");
839
1201
  content = content.replace(/\$secret:[^\s\n'"]+/g, "<redacted>");
840
- writeFileSync3(join2(resolvedOutDir, basename(manifestSrc)), content, "utf-8");
1202
+ writeFileSync3(join3(resolvedOutDir, basename(manifestSrc)), content, "utf-8");
841
1203
  console.log(` ${chalk6.green("\u2713")} ${basename(manifestSrc)} (manifest copy)`);
842
1204
  } catch {
843
1205
  }
@@ -848,12 +1210,16 @@ function validateFramework(framework) {
848
1210
  available = listFrameworks();
849
1211
  } catch {
850
1212
  printError(
851
- "Failed to load available frameworks. Is @agentspec/adapter-claude installed correctly?"
1213
+ "Failed to load available frameworks. Is @agentspec/codegen installed correctly?\n Try: pnpm --filter @agentspec/codegen build"
852
1214
  );
853
1215
  process.exit(1);
854
1216
  }
855
1217
  if (!available.includes(framework)) {
856
- printError(`Unknown framework "${framework}". Available: ${available.join(", ")}`);
1218
+ printError(
1219
+ `Framework "${framework}" is not supported.
1220
+ Available: ${available.join(", ")}
1221
+ Add a new one: packages/codegen/src/skills/${framework}.md`
1222
+ );
857
1223
  process.exit(1);
858
1224
  }
859
1225
  }
@@ -868,14 +1234,17 @@ function handleK8sGeneration(manifest, outDir, outputOpt) {
868
1234
  }
869
1235
  printSuccess(`Written to ${outputOpt}`);
870
1236
  }
871
- async function handleLLMGeneration(manifest, framework, manifestDir, spin, displayModel) {
1237
+ async function handleLLMGeneration(manifest, framework, manifestDir, spin, provider) {
872
1238
  try {
873
- return await generateWithClaude(manifest, {
1239
+ return await generateCode(manifest, {
874
1240
  framework,
875
1241
  manifestDir,
876
- onProgress: ({ outputChars }) => {
877
- const kb = (outputChars / 1024).toFixed(1);
878
- spin.message(`Generating with ${displayModel} \xB7 ${kb}k chars`);
1242
+ provider,
1243
+ onChunk: (chunk) => {
1244
+ if (chunk.type === "delta" || chunk.type === "heartbeat") {
1245
+ const kb = chunk.type === "delta" ? ` \xB7 ${(chunk.accumulated.length / 1024).toFixed(1)}k chars` : "";
1246
+ spin.message(`Generating with ${provider.name} \xB7 ${chunk.elapsedSec}s${kb}`);
1247
+ }
879
1248
  }
880
1249
  });
881
1250
  } catch (err) {
@@ -890,7 +1259,7 @@ function writePushModeEnv(outDir) {
890
1259
  "AGENTSPEC_KEY=<paste key from: agentspec register>",
891
1260
  ""
892
1261
  ].join("\n");
893
- writeFileSync3(join2(outDir, ".env.agentspec"), envContent, "utf-8");
1262
+ writeFileSync3(join3(outDir, ".env.agentspec"), envContent, "utf-8");
894
1263
  console.log(
895
1264
  ` ${chalk6.green("\u2713")} .env.agentspec (push mode \u2014 paste your key from agentspec register)`
896
1265
  );
@@ -923,7 +1292,7 @@ function printPostGeneration(generated, outputDir) {
923
1292
  }
924
1293
  printSuccess(`Written to ${outputDir}`);
925
1294
  }
926
- async function runDeployTarget(target, manifest, outDir) {
1295
+ async function runDeployTarget(target, manifest, outDir, provider) {
927
1296
  if (target === "k8s") {
928
1297
  console.log();
929
1298
  console.log(chalk6.bold(" Kubernetes manifests:"));
@@ -933,16 +1302,28 @@ async function runDeployTarget(target, manifest, outDir) {
933
1302
  }
934
1303
  if (target === "helm") {
935
1304
  console.log();
936
- console.log(chalk6.bold(" Helm chart (Claude-generated):"));
937
- const helmGenerated = await generateWithClaude(manifest, { framework: "helm" });
1305
+ console.log(chalk6.bold(" Helm chart (LLM-generated):"));
1306
+ let helmGenerated;
1307
+ try {
1308
+ helmGenerated = await generateCode(manifest, { framework: "helm", provider });
1309
+ } catch (err) {
1310
+ printError(`Helm generation failed: ${String(err)}`);
1311
+ process.exit(1);
1312
+ }
938
1313
  writeGeneratedFiles(helmGenerated.files, outDir);
939
1314
  }
940
1315
  }
941
1316
  function registerGenerateCommand(program2) {
942
- program2.command("generate <file>").description("Generate framework-specific agent code from a manifest").requiredOption("--framework <fw>", "Target framework (langgraph, crewai, mastra)").option("--output <dir>", "Output directory", "./generated").option("--dry-run", "Print generated files without writing them").option(
1317
+ program2.command("generate <file>").description("Generate framework-specific agent code from a manifest").requiredOption(
1318
+ "--framework <fw>",
1319
+ "Target framework (e.g. langgraph, crewai, mastra)"
1320
+ ).option("--output <dir>", "Output directory", "./generated").option("--dry-run", "Print generated files without writing them").option(
943
1321
  "--deploy <target>",
944
1322
  `Also generate deployment manifests: ${DEPLOY_TARGETS.join(", ")}`
945
- ).option("--push", "Write .env.agentspec with push mode env var placeholders").action(
1323
+ ).option("--push", "Write .env.agentspec with push mode env var placeholders").option(
1324
+ "--provider <name>",
1325
+ "Override codegen provider: claude-sub, anthropic-api, openai-compatible"
1326
+ ).action(
946
1327
  async (file, opts) => {
947
1328
  validateFramework(opts.framework);
948
1329
  if (opts.deploy && !DEPLOY_TARGETS.includes(opts.deploy)) {
@@ -959,26 +1340,28 @@ function registerGenerateCommand(program2) {
959
1340
  process.exit(1);
960
1341
  }
961
1342
  if (opts.deploy === "k8s") {
962
- handleK8sGeneration(parsed.manifest, resolve2(opts.output), opts.output);
1343
+ handleK8sGeneration(parsed.manifest, resolve3(opts.output), opts.output);
963
1344
  return;
964
1345
  }
965
- if (!process.env["ANTHROPIC_API_KEY"]) {
966
- printError(
967
- "ANTHROPIC_API_KEY is not set. AgentSpec generates code using Claude.\n Get a key at https://console.anthropic.com and add it to your environment."
968
- );
1346
+ printHeader(`AgentSpec Generate \u2014 ${opts.framework}`);
1347
+ const spin = spinner2();
1348
+ spin.start("Checking provider\u2026");
1349
+ let provider;
1350
+ try {
1351
+ provider = resolveProvider(opts.provider);
1352
+ } catch (err) {
1353
+ spin.stop("Provider unavailable");
1354
+ printError(`Codegen provider unavailable: ${String(err)}`);
969
1355
  process.exit(1);
970
1356
  }
971
- printHeader(`AgentSpec Generate \u2014 ${opts.framework}`);
972
- const displayModel = process.env["ANTHROPIC_MODEL"] ?? "claude-opus-4-6";
973
- const spin = spinner();
974
- spin.start(`Generating with ${displayModel}`);
975
- const manifestDir = dirname(resolve2(file));
1357
+ spin.message(`Generating with ${provider.name}`);
1358
+ const manifestDir = dirname2(resolve3(file));
976
1359
  const generated = await handleLLMGeneration(
977
1360
  parsed.manifest,
978
1361
  opts.framework,
979
1362
  manifestDir,
980
1363
  spin,
981
- displayModel
1364
+ provider
982
1365
  );
983
1366
  const totalKb = (Object.values(generated.files).reduce((n, c) => n + c.length, 0) / 1024).toFixed(1);
984
1367
  spin.stop(`Generated ${Object.keys(generated.files).length} files \xB7 ${totalKb}k chars`);
@@ -986,7 +1369,7 @@ function registerGenerateCommand(program2) {
986
1369
  printDryRunOutput(generated.files);
987
1370
  return;
988
1371
  }
989
- const outDir = resolve2(opts.output);
1372
+ const outDir = resolve3(opts.output);
990
1373
  console.log();
991
1374
  try {
992
1375
  writeGeneratedFiles(generated.files, outDir);
@@ -999,7 +1382,7 @@ function registerGenerateCommand(program2) {
999
1382
  writePushModeEnv(outDir);
1000
1383
  }
1001
1384
  if (opts.deploy === "helm") {
1002
- await runDeployTarget("helm", parsed.manifest, outDir);
1385
+ await runDeployTarget("helm", parsed.manifest, outDir, provider);
1003
1386
  }
1004
1387
  printPostGeneration(generated, opts.output);
1005
1388
  }
@@ -1092,8 +1475,8 @@ npx agentspec generate agent.yaml --framework langgraph --output ./generated/
1092
1475
  }
1093
1476
 
1094
1477
  // src/commands/migrate.ts
1095
- import { readFileSync as readFileSync2, writeFileSync as writeFileSync4 } from "fs";
1096
- import { resolve as resolve3 } from "path";
1478
+ import { readFileSync as readFileSync3, writeFileSync as writeFileSync4 } from "fs";
1479
+ import { resolve as resolve4 } from "path";
1097
1480
  import chalk7 from "chalk";
1098
1481
  import yaml from "js-yaml";
1099
1482
  import {
@@ -1105,10 +1488,10 @@ import {
1105
1488
  function registerMigrateCommand(program2) {
1106
1489
  program2.command("migrate <file>").description("Migrate an agent.yaml manifest to the latest schema version").option("--dry-run", "Show what would change without writing files").option("-o, --output <file>", "Write migrated manifest to a different file").action(async (file, opts) => {
1107
1490
  printHeader("AgentSpec Migrate");
1108
- const absPath = resolve3(file);
1491
+ const absPath = resolve4(file);
1109
1492
  let raw;
1110
1493
  try {
1111
- raw = readFileSync2(absPath, "utf-8");
1494
+ raw = readFileSync3(absPath, "utf-8");
1112
1495
  } catch (err) {
1113
1496
  printError(`Cannot read manifest: ${absPath}
1114
1497
  ${String(err)}`);
@@ -1149,7 +1532,7 @@ function registerMigrateCommand(program2) {
1149
1532
  console.log();
1150
1533
  return;
1151
1534
  }
1152
- const outputPath = opts.output ? resolve3(opts.output) : absPath;
1535
+ const outputPath = opts.output ? resolve4(opts.output) : absPath;
1153
1536
  try {
1154
1537
  writeFileSync4(outputPath, migratedYaml, "utf-8");
1155
1538
  } catch (err) {
@@ -1163,16 +1546,16 @@ function registerMigrateCommand(program2) {
1163
1546
 
1164
1547
  // src/commands/scan.ts
1165
1548
  import {
1166
- existsSync as existsSync3,
1549
+ existsSync as existsSync5,
1167
1550
  lstatSync,
1168
- readdirSync,
1169
- readFileSync as readFileSync3,
1551
+ readdirSync as readdirSync2,
1552
+ readFileSync as readFileSync5,
1170
1553
  realpathSync,
1171
1554
  writeFileSync as writeFileSync5
1172
1555
  } from "fs";
1173
- import { extname, join as join3, resolve as resolve4 } from "path";
1174
- import * as jsYaml from "js-yaml";
1175
- import { generateWithClaude as generateWithClaude2, repairYaml } from "@agentspec/adapter-claude";
1556
+ import { extname, join as join5, resolve as resolve6 } from "path";
1557
+ import * as jsYaml2 from "js-yaml";
1558
+ import { generateCode as generateCode2, repairYaml, resolveProvider as resolveProvider2 } from "@agentspec/codegen";
1176
1559
  import { ManifestSchema } from "@agentspec/sdk";
1177
1560
 
1178
1561
  // src/commands/scan-builder.ts
@@ -1339,6 +1722,149 @@ function buildManifestFromDetection(d) {
1339
1722
  };
1340
1723
  }
1341
1724
 
1725
+ // src/commands/scan-claude-code.ts
1726
+ import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync4 } from "fs";
1727
+ import { basename as basename2, join as join4, resolve as resolve5 } from "path";
1728
+ import * as jsYaml from "js-yaml";
1729
+ var DESTRUCTIVE_BUILTINS = /* @__PURE__ */ new Set(["Bash", "Write", "Edit", "MultiEdit", "NotebookEdit"]);
1730
+ var READONLY_BUILTINS = /* @__PURE__ */ new Set(["Read", "Grep", "Glob", "WebFetch", "WebSearch", "TodoWrite"]);
1731
+ function readJsonIfPresent(path) {
1732
+ if (!existsSync4(path)) return void 0;
1733
+ try {
1734
+ return JSON.parse(readFileSync4(path, "utf-8"));
1735
+ } catch {
1736
+ return void 0;
1737
+ }
1738
+ }
1739
+ function loadSettings(dir) {
1740
+ const base = readJsonIfPresent(join4(dir, ".claude", "settings.json")) ?? {};
1741
+ const local = readJsonIfPresent(join4(dir, ".claude", "settings.local.json")) ?? {};
1742
+ return {
1743
+ model: local.model ?? base.model,
1744
+ permissions: {
1745
+ allow: unionArrays(base.permissions?.allow, local.permissions?.allow),
1746
+ deny: unionArrays(base.permissions?.deny, local.permissions?.deny),
1747
+ ask: unionArrays(base.permissions?.ask, local.permissions?.ask)
1748
+ },
1749
+ mcpServers: { ...base.mcpServers, ...local.mcpServers }
1750
+ };
1751
+ }
1752
+ function unionArrays(a, b) {
1753
+ return [.../* @__PURE__ */ new Set([...a ?? [], ...b ?? []])];
1754
+ }
1755
+ function permissionToToolId(entry) {
1756
+ const withoutArgs = entry.split("(")[0]?.trim();
1757
+ return withoutArgs && withoutArgs.length > 0 ? withoutArgs : void 0;
1758
+ }
1759
+ function buildTool(toolId) {
1760
+ if (toolId.startsWith("mcp__")) {
1761
+ return {
1762
+ name: slugify(toolId),
1763
+ type: "mcp",
1764
+ description: `MCP tool exposed to Claude Code (${toolId})`
1765
+ };
1766
+ }
1767
+ const annotations = DESTRUCTIVE_BUILTINS.has(toolId) ? { destructiveHint: true } : READONLY_BUILTINS.has(toolId) ? { readOnlyHint: true } : void 0;
1768
+ return {
1769
+ name: slugify(toolId),
1770
+ type: "builtin",
1771
+ description: `Claude Code builtin tool (${toolId})`,
1772
+ ...annotations ? { annotations } : {}
1773
+ };
1774
+ }
1775
+ function buildTools2(settings) {
1776
+ const allow = settings.permissions?.allow ?? [];
1777
+ const seen = /* @__PURE__ */ new Set();
1778
+ const tools = [];
1779
+ for (const entry of allow) {
1780
+ const toolId = permissionToToolId(entry);
1781
+ if (!toolId) continue;
1782
+ const tool = buildTool(toolId);
1783
+ if (seen.has(tool.name)) continue;
1784
+ seen.add(tool.name);
1785
+ tools.push(tool);
1786
+ }
1787
+ return tools.length ? tools : void 0;
1788
+ }
1789
+ function normalizeTransport(raw) {
1790
+ if (raw.type === "http" || raw.type === "sse" || raw.type === "stdio") return raw.type;
1791
+ if (raw.url) return "http";
1792
+ return "stdio";
1793
+ }
1794
+ function buildMcp(dir, settings) {
1795
+ const fromFile = readJsonIfPresent(
1796
+ join4(dir, ".mcp.json")
1797
+ )?.mcpServers;
1798
+ const merged = { ...fromFile, ...settings.mcpServers };
1799
+ const servers = Object.entries(merged).map(([name, raw]) => ({
1800
+ name: slugify(name),
1801
+ transport: normalizeTransport(raw),
1802
+ ...raw.command ? { command: raw.command } : {},
1803
+ ...raw.args?.length ? { args: raw.args } : {},
1804
+ ...raw.url ? { url: raw.url } : {}
1805
+ }));
1806
+ return servers.length ? { servers } : void 0;
1807
+ }
1808
+ function parseAgentFrontmatterName(content, fallback) {
1809
+ const match = content.match(/^---\s*\n([\s\S]*?)\n---/);
1810
+ if (match?.[1]) {
1811
+ try {
1812
+ const fm = jsYaml.load(match[1]);
1813
+ if (fm?.name) return fm.name;
1814
+ } catch {
1815
+ }
1816
+ }
1817
+ return fallback;
1818
+ }
1819
+ function buildSubagents(dir) {
1820
+ const agentsDir = join4(dir, ".claude", "agents");
1821
+ if (!existsSync4(agentsDir)) return void 0;
1822
+ const subagents = [];
1823
+ for (const file of readdirSync(agentsDir).sort()) {
1824
+ if (!file.endsWith(".md")) continue;
1825
+ const abs = join4(agentsDir, file);
1826
+ let content = "";
1827
+ try {
1828
+ content = readFileSync4(abs, "utf-8");
1829
+ } catch {
1830
+ continue;
1831
+ }
1832
+ const rawName = parseAgentFrontmatterName(content, basename2(file, ".md"));
1833
+ subagents.push({
1834
+ name: slugify(rawName),
1835
+ ref: { agentspec: join4(".claude", "agents", file) },
1836
+ invocation: "on-demand",
1837
+ passContext: false
1838
+ });
1839
+ }
1840
+ return subagents.length ? subagents : void 0;
1841
+ }
1842
+ function buildDetection(dir, settings) {
1843
+ const hasClaudeMd = existsSync4(join4(dir, "CLAUDE.md"));
1844
+ return {
1845
+ name: basename2(resolve5(dir)) || "claude-code-agent",
1846
+ description: "Claude Code project agent (scanned from .claude/ config)",
1847
+ modelProvider: "anthropic",
1848
+ modelId: settings.model ?? "claude-sonnet-5",
1849
+ modelApiKeyEnv: "ANTHROPIC_API_KEY",
1850
+ ...hasClaudeMd ? { promptFile: "CLAUDE.md" } : {},
1851
+ // Tools are attached post-build with Claude-specific types — leave empty here.
1852
+ tools: [],
1853
+ envVars: ["ANTHROPIC_API_KEY"]
1854
+ };
1855
+ }
1856
+ function buildManifestFromClaudeConfig(dir) {
1857
+ const settings = loadSettings(dir);
1858
+ const manifest = buildManifestFromDetection(buildDetection(dir, settings));
1859
+ const tools = buildTools2(settings);
1860
+ const mcp = buildMcp(dir, settings);
1861
+ const subagents = buildSubagents(dir);
1862
+ if (tools) manifest.spec.tools = tools;
1863
+ if (mcp) manifest.spec.mcp = mcp;
1864
+ if (subagents) manifest.spec.subagents = subagents;
1865
+ return manifest;
1866
+ }
1867
+
1342
1868
  // src/commands/scan.ts
1343
1869
  var MAX_FILES = 50;
1344
1870
  var MAX_BYTES = 200 * 1024;
@@ -1364,29 +1890,26 @@ var SKIP_DIRS = /* @__PURE__ */ new Set([
1364
1890
  "out",
1365
1891
  ".turbo"
1366
1892
  ]);
1367
- function collectSourceFiles(srcDir, maxFiles = MAX_FILES, maxBytes = MAX_BYTES) {
1893
+ function collectSourceFilesWithCount(srcDir, maxFiles = MAX_FILES, maxBytes = MAX_BYTES) {
1368
1894
  let resolvedBase;
1369
1895
  try {
1370
- resolvedBase = realpathSync(resolve4(srcDir));
1896
+ resolvedBase = realpathSync(resolve6(srcDir));
1371
1897
  } catch {
1372
- resolvedBase = resolve4(srcDir);
1898
+ resolvedBase = resolve6(srcDir);
1373
1899
  }
1374
1900
  const results = [];
1375
1901
  let totalBytes = 0;
1902
+ let totalFound = 0;
1376
1903
  function walk(dir) {
1377
- if (results.length >= maxFiles) return;
1378
- if (totalBytes >= maxBytes) return;
1379
1904
  let entries;
1380
1905
  try {
1381
- entries = readdirSync(dir).sort();
1906
+ entries = readdirSync2(dir).sort();
1382
1907
  } catch {
1383
1908
  return;
1384
1909
  }
1385
1910
  for (const entry of entries) {
1386
- if (results.length >= maxFiles) break;
1387
- if (totalBytes >= maxBytes) break;
1388
1911
  if (entry.startsWith(".") || SKIP_DIRS.has(entry)) continue;
1389
- const fullPath = join3(dir, entry);
1912
+ const fullPath = join5(dir, entry);
1390
1913
  let stat;
1391
1914
  try {
1392
1915
  stat = lstatSync(fullPath);
@@ -1411,9 +1934,12 @@ function collectSourceFiles(srcDir, maxFiles = MAX_FILES, maxBytes = MAX_BYTES)
1411
1934
  continue;
1412
1935
  }
1413
1936
  if (!realPath.startsWith(resolvedBase + "/") && realPath !== resolvedBase) continue;
1937
+ totalFound++;
1938
+ if (results.length >= maxFiles) continue;
1939
+ if (totalBytes >= maxBytes) continue;
1414
1940
  let content;
1415
1941
  try {
1416
- content = readFileSync3(fullPath, "utf-8");
1942
+ content = readFileSync5(fullPath, "utf-8");
1417
1943
  } catch {
1418
1944
  continue;
1419
1945
  }
@@ -1427,35 +1953,34 @@ function collectSourceFiles(srcDir, maxFiles = MAX_FILES, maxBytes = MAX_BYTES)
1427
1953
  }
1428
1954
  }
1429
1955
  walk(resolvedBase);
1430
- return results;
1956
+ return { files: results, totalFound };
1431
1957
  }
1432
1958
  function resolveOutputPath(opts) {
1433
- if (opts.out) return resolve4(opts.out);
1434
- const defaultPath = join3(resolve4(opts.srcDir), "agent.yaml");
1959
+ if (opts.out) return resolve6(opts.out);
1960
+ const defaultPath = join5(resolve6(opts.srcDir), "agent.yaml");
1435
1961
  if (opts.update || opts.dryRun) return defaultPath;
1436
- if (existsSync3(defaultPath)) return join3(resolve4(opts.srcDir), "agent.yaml.new");
1962
+ if (existsSync5(defaultPath)) return join5(resolve6(opts.srcDir), "agent.yaml.new");
1437
1963
  return defaultPath;
1438
1964
  }
1439
1965
  function collectAndValidateSourceFiles(srcDir) {
1440
- const files = collectSourceFiles(srcDir);
1966
+ const { files, totalFound } = collectSourceFilesWithCount(srcDir);
1441
1967
  if (files.length === 0) {
1442
1968
  console.warn(`No source files found in ${srcDir}`);
1443
1969
  }
1444
- const rawCount = countSourceFiles(srcDir);
1445
- if (rawCount > MAX_FILES) {
1970
+ if (totalFound > MAX_FILES) {
1446
1971
  console.warn(
1447
- `Found ${rawCount} source files \u2014 truncating to ${MAX_FILES} files cap. Use a narrower --dir path to scan specific modules.`
1972
+ `Found ${totalFound} source files \u2014 truncating to ${MAX_FILES} files cap. Use a narrower --dir path to scan specific modules.`
1448
1973
  );
1449
1974
  }
1450
1975
  return files;
1451
1976
  }
1452
1977
  function parseDetection(rawResult) {
1453
1978
  if (!rawResult || typeof rawResult !== "object" || !("files" in rawResult) || typeof rawResult.files !== "object" || rawResult.files === null) {
1454
- throw new Error('Claude returned an unexpected response format (missing "files" object).');
1979
+ throw new Error('Provider returned an unexpected response format (missing "files" object).');
1455
1980
  }
1456
1981
  const detectionJson = rawResult.files["detection.json"];
1457
1982
  if (!detectionJson) {
1458
- throw new Error("Claude did not return detection.json in the output.");
1983
+ throw new Error("Provider did not return detection.json in the output.");
1459
1984
  }
1460
1985
  let detection;
1461
1986
  try {
@@ -1474,7 +1999,7 @@ function parseDetection(rawResult) {
1474
1999
  function validateManifestYaml(yamlStr) {
1475
2000
  let parsed;
1476
2001
  try {
1477
- parsed = jsYaml.load(yamlStr);
2002
+ parsed = jsYaml2.load(yamlStr);
1478
2003
  } catch (e) {
1479
2004
  return { valid: false, errors: `YAML parse error: ${e.message}`, errorCount: 1 };
1480
2005
  }
@@ -1483,28 +2008,58 @@ function validateManifestYaml(yamlStr) {
1483
2008
  const errors = result.error.errors.map((e) => ` - ${e.path.join(".") || "(root)"}: ${e.message}`).join("\n");
1484
2009
  return { valid: false, errors, errorCount: result.error.errors.length };
1485
2010
  }
2011
+ function runClaudeCodeProfile(srcDir) {
2012
+ const manifest = buildManifestFromClaudeConfig(srcDir);
2013
+ let agentYaml = jsYaml2.dump(manifest, { lineWidth: 120 });
2014
+ const validation = validateManifestYaml(agentYaml);
2015
+ if (!validation.valid) {
2016
+ agentYaml = `# agentspec validate errors \u2014 fix before committing:
2017
+ ` + validation.errors.split("\n").map((l) => `# ${l}`).join("\n") + "\n\n" + agentYaml;
2018
+ }
2019
+ return agentYaml;
2020
+ }
1486
2021
  function registerScanCommand(program2) {
1487
- program2.command("scan").description("Scan source code and generate an agent.yaml manifest (Claude-powered)").requiredOption("-d, --dir <src>", "Source directory to scan").option("--out <path>", "Explicit output path").option("--update", "Overwrite existing agent.yaml in place").option("--dry-run", "Print generated YAML to stdout without writing").action(async (opts) => {
1488
- if (!process.env["ANTHROPIC_API_KEY"]) {
1489
- console.error(
1490
- "ANTHROPIC_API_KEY is not set. agentspec scan uses Claude to analyse source code.\nGet a key at https://console.anthropic.com"
1491
- );
2022
+ program2.command("scan").description("Scan source code and generate an agent.yaml manifest (LLM-powered)").requiredOption("-d, --dir <src>", "Source directory to scan").option("--out <path>", "Explicit output path").option("--update", "Overwrite existing agent.yaml in place").option("--dry-run", "Print generated YAML to stdout without writing").option("--provider <name>", "Override codegen provider: claude-sub, anthropic-api, openai-compatible").option("--profile <name>", "Config profile for deterministic (no-LLM) scanning: claude-code").action(async (opts) => {
2023
+ if (opts.profile === "claude-code") {
2024
+ const srcDir2 = resolve6(opts.dir);
2025
+ const agentYaml2 = runClaudeCodeProfile(srcDir2);
2026
+ if (opts.dryRun) {
2027
+ console.log(agentYaml2);
2028
+ return;
2029
+ }
2030
+ const outPath2 = resolveOutputPath({ srcDir: srcDir2, out: opts.out, update: opts.update, dryRun: opts.dryRun });
2031
+ writeFileSync5(outPath2, agentYaml2, "utf-8");
2032
+ console.log(`\u2713 Written: ${outPath2}`);
2033
+ return;
2034
+ }
2035
+ if (opts.profile) {
2036
+ console.error(`Unknown --profile "${opts.profile}". Supported: claude-code`);
2037
+ process.exit(1);
2038
+ }
2039
+ const s = spinner2();
2040
+ s.start("Checking provider\u2026");
2041
+ let provider;
2042
+ try {
2043
+ provider = resolveProvider2(opts.provider);
2044
+ } catch (err) {
2045
+ s.stop("Provider unavailable");
2046
+ console.error(`Codegen provider unavailable: ${err.message}`);
1492
2047
  process.exit(1);
1493
2048
  }
1494
- const srcDir = resolve4(opts.dir);
2049
+ const srcDir = resolve6(opts.dir);
1495
2050
  const sourceFiles = collectAndValidateSourceFiles(srcDir);
1496
- const s = spinner();
1497
- s.start("Analysing source code\u2026");
2051
+ s.message(`Analysing source code with ${provider.name}\u2026`);
1498
2052
  let rawResult;
1499
2053
  try {
1500
- rawResult = await generateWithClaude2(
2054
+ rawResult = await generateCode2(
1501
2055
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1502
2056
  {},
1503
2057
  // empty manifest — the scan skill detects from source
1504
2058
  {
1505
2059
  framework: "scan",
1506
2060
  contextFiles: sourceFiles.map((f) => f.path),
1507
- manifestDir: srcDir
2061
+ manifestDir: srcDir,
2062
+ provider
1508
2063
  }
1509
2064
  );
1510
2065
  } catch (err) {
@@ -1517,7 +2072,7 @@ function registerScanCommand(program2) {
1517
2072
  s.message("Building manifest\u2026");
1518
2073
  const detection = parseDetection(rawResult);
1519
2074
  const manifest = buildManifestFromDetection(detection);
1520
- agentYaml = jsYaml.dump(manifest, { lineWidth: 120 });
2075
+ agentYaml = jsYaml2.dump(manifest, { lineWidth: 120 });
1521
2076
  } catch (err) {
1522
2077
  s.stop("Failed");
1523
2078
  console.error(`Build failed: ${err.message}`);
@@ -1529,7 +2084,7 @@ function registerScanCommand(program2) {
1529
2084
  `Fixing ${validation.errorCount} schema error(s) \u2014 attempt ${attempt}/${MAX_REPAIR_ITERATIONS}\u2026`
1530
2085
  );
1531
2086
  try {
1532
- agentYaml = await repairYaml(agentYaml, validation.errors);
2087
+ agentYaml = await repairYaml(provider, agentYaml, validation.errors);
1533
2088
  validation = validateManifestYaml(agentYaml);
1534
2089
  } catch (err) {
1535
2090
  s.stop("Failed");
@@ -1558,51 +2113,9 @@ function registerScanCommand(program2) {
1558
2113
  console.log(`\u2713 Written: ${outPath}`);
1559
2114
  });
1560
2115
  }
1561
- function countSourceFiles(srcDir) {
1562
- let resolvedBase;
1563
- try {
1564
- resolvedBase = realpathSync(resolve4(srcDir));
1565
- } catch {
1566
- resolvedBase = resolve4(srcDir);
1567
- }
1568
- let count = 0;
1569
- function walk(dir) {
1570
- let entries;
1571
- try {
1572
- entries = readdirSync(dir);
1573
- } catch {
1574
- return;
1575
- }
1576
- for (const entry of entries) {
1577
- if (entry.startsWith(".") || SKIP_DIRS.has(entry)) continue;
1578
- const fullPath = join3(dir, entry);
1579
- let stat;
1580
- try {
1581
- stat = lstatSync(fullPath);
1582
- } catch {
1583
- continue;
1584
- }
1585
- if (stat.isSymbolicLink()) continue;
1586
- if (stat.isDirectory()) {
1587
- let resolvedDir;
1588
- try {
1589
- resolvedDir = realpathSync(fullPath);
1590
- } catch {
1591
- continue;
1592
- }
1593
- if (!resolvedDir.startsWith(resolvedBase + "/") && resolvedDir !== resolvedBase) continue;
1594
- walk(fullPath);
1595
- } else if (stat.isFile() && SOURCE_EXTENSIONS.has(extname(entry))) {
1596
- count++;
1597
- }
1598
- }
1599
- }
1600
- walk(resolvedBase);
1601
- return count;
1602
- }
1603
2116
 
1604
2117
  // src/commands/diff.ts
1605
- import { readFileSync as readFileSync4 } from "fs";
2118
+ import { readFileSync as readFileSync6 } from "fs";
1606
2119
  import yaml2 from "js-yaml";
1607
2120
 
1608
2121
  // src/utils/diff-score.ts
@@ -1838,8 +2351,8 @@ function registerDiffCommand(program2) {
1838
2351
  let fromRaw;
1839
2352
  let toRaw;
1840
2353
  try {
1841
- fromRaw = yaml2.load(readFileSync4(fromPath, "utf-8"), { schema: yaml2.JSON_SCHEMA });
1842
- toRaw = yaml2.load(readFileSync4(toPath, "utf-8"), { schema: yaml2.JSON_SCHEMA });
2354
+ fromRaw = yaml2.load(readFileSync6(fromPath, "utf-8"), { schema: yaml2.JSON_SCHEMA });
2355
+ toRaw = yaml2.load(readFileSync6(toPath, "utf-8"), { schema: yaml2.JSON_SCHEMA });
1843
2356
  } catch (err) {
1844
2357
  console.error(`Error loading manifests: ${err.message}`);
1845
2358
  process.exit(1);
@@ -1870,8 +2383,8 @@ function registerDiffCommand(program2) {
1870
2383
  }
1871
2384
 
1872
2385
  // src/commands/generate-policy.ts
1873
- import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync6 } from "fs";
1874
- import { join as join4, resolve as resolve5 } from "path";
2386
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync6 } from "fs";
2387
+ import { join as join6, resolve as resolve7 } from "path";
1875
2388
  import { loadManifest as loadManifest6 } from "@agentspec/sdk";
1876
2389
  function sanitizePackageName(name) {
1877
2390
  return name.replace(/-/g, "_");
@@ -2020,13 +2533,13 @@ function registerGeneratePolicyCommand(program2) {
2020
2533
  process.exit(1);
2021
2534
  }
2022
2535
  const agentName = manifest.metadata.name;
2023
- const outputDir = resolve5(opts.out ?? join4("policies", agentName));
2536
+ const outputDir = resolve7(opts.out ?? join6("policies", agentName));
2024
2537
  const rego = generateRegoPolicy(manifest);
2025
2538
  const dataJson = generateDataJson(manifest);
2026
2539
  const rulesGenerated = (rego.match(/^deny contains/gm) ?? []).length;
2027
- mkdirSync2(outputDir, { recursive: true });
2028
- const regoPath = join4(outputDir, "policy.rego");
2029
- const dataPath = join4(outputDir, "data.json");
2540
+ mkdirSync3(outputDir, { recursive: true });
2541
+ const regoPath = join6(outputDir, "policy.rego");
2542
+ const dataPath = join6(outputDir, "data.json");
2030
2543
  writeFileSync6(regoPath, rego, "utf-8");
2031
2544
  writeFileSync6(dataPath, JSON.stringify(dataJson, null, 2), "utf-8");
2032
2545
  const result = {
@@ -2052,15 +2565,15 @@ function registerGeneratePolicyCommand(program2) {
2052
2565
  }
2053
2566
 
2054
2567
  // src/commands/evaluate.ts
2055
- import { readFileSync as readFileSync5, existsSync as existsSync4 } from "fs";
2056
- import { resolve as resolve6, dirname as dirname2 } from "path";
2568
+ import { readFileSync as readFileSync7, existsSync as existsSync6, realpathSync as realpathSync2 } from "fs";
2569
+ import { resolve as resolve8, dirname as dirname3, sep as sep2 } from "path";
2057
2570
  import chalk8 from "chalk";
2058
2571
  import { loadManifest as loadManifest7 } from "@agentspec/sdk";
2059
2572
  function loadDataset(datasetPath) {
2060
- if (!existsSync4(datasetPath)) {
2573
+ if (!existsSync6(datasetPath)) {
2061
2574
  throw new Error(`Dataset file not found: ${datasetPath}`);
2062
2575
  }
2063
- const content = readFileSync5(datasetPath, "utf-8");
2576
+ const content = readFileSync7(datasetPath, "utf-8");
2064
2577
  const samples = [];
2065
2578
  for (const line of content.split("\n")) {
2066
2579
  const trimmed = line.trim();
@@ -2203,7 +2716,7 @@ function registerEvaluateCommand(program2) {
2203
2716
  process.exit(1);
2204
2717
  }
2205
2718
  const { manifest } = parsed;
2206
- const manifestDir = dirname2(resolve6(file));
2719
+ const manifestDir = dirname3(resolve8(file));
2207
2720
  const timeoutMs = parseInt(opts.timeout, 10) || 1e4;
2208
2721
  const datasets = manifest.spec.evaluation?.datasets ?? [];
2209
2722
  const datasetEntry = datasets.find((d) => d.name === opts.dataset);
@@ -2215,10 +2728,37 @@ function registerEvaluateCommand(program2) {
2215
2728
  }
2216
2729
  const rawPath = datasetEntry.path;
2217
2730
  const relPath = rawPath.startsWith("$file:") ? rawPath.slice(6) : rawPath;
2218
- const absPath = resolve6(manifestDir, relPath);
2731
+ const absPath = resolve8(manifestDir, relPath);
2732
+ const safeBase = manifestDir.endsWith(sep2) ? manifestDir : manifestDir + sep2;
2733
+ if (absPath !== manifestDir && !absPath.startsWith(safeBase)) {
2734
+ printError(
2735
+ `Dataset path "${relPath}" resolves outside the manifest directory. Only paths within the same directory tree are allowed.`
2736
+ );
2737
+ process.exit(1);
2738
+ }
2739
+ let realAbsPath;
2740
+ try {
2741
+ realAbsPath = realpathSync2(absPath);
2742
+ } catch {
2743
+ printError(`Dataset path "${relPath}" could not be resolved: file may not exist.`);
2744
+ process.exit(1);
2745
+ }
2746
+ let realBase;
2747
+ try {
2748
+ realBase = realpathSync2(manifestDir);
2749
+ } catch {
2750
+ realBase = manifestDir;
2751
+ }
2752
+ const safeRealBase = realBase.endsWith(sep2) ? realBase : realBase + sep2;
2753
+ if (realAbsPath !== realBase && !realAbsPath.startsWith(safeRealBase)) {
2754
+ printError(
2755
+ `Dataset path "${relPath}" resolves via symlink outside the manifest directory. Only paths within the same directory tree are allowed.`
2756
+ );
2757
+ process.exit(1);
2758
+ }
2219
2759
  let samples;
2220
2760
  try {
2221
- samples = loadDataset(absPath);
2761
+ samples = loadDataset(realAbsPath);
2222
2762
  } catch (err) {
2223
2763
  printError(`Cannot load dataset: ${String(err)}`);
2224
2764
  process.exit(1);
@@ -2229,7 +2769,11 @@ function registerEvaluateCommand(program2) {
2229
2769
  if (opts.sampleSize) {
2230
2770
  const n = parseInt(opts.sampleSize, 10);
2231
2771
  if (n > 0 && n < samples.length) {
2232
- const shuffled = [...samples].sort(() => Math.random() - 0.5);
2772
+ const shuffled = [...samples];
2773
+ for (let i = shuffled.length - 1; i > 0; i--) {
2774
+ const j = Math.floor(Math.random() * (i + 1));
2775
+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
2776
+ }
2233
2777
  samples = shuffled.slice(0, n);
2234
2778
  }
2235
2779
  }
@@ -2248,7 +2792,7 @@ function registerEvaluateCommand(program2) {
2248
2792
 
2249
2793
  // src/commands/probe.ts
2250
2794
  import { spawnSync } from "child_process";
2251
- import { existsSync as existsSync5 } from "fs";
2795
+ import { existsSync as existsSync7 } from "fs";
2252
2796
  import chalk9 from "chalk";
2253
2797
  function registerProbeCommand(program2) {
2254
2798
  const probe = program2.command("probe").description("Run external probes to generate compliance proof records");
@@ -2273,7 +2817,7 @@ function registerProbeCommand(program2) {
2273
2817
  process.exit(1);
2274
2818
  }
2275
2819
  }
2276
- if (opts.logFile && !existsSync5(opts.logFile)) {
2820
+ if (opts.logFile && !existsSync7(opts.logFile)) {
2277
2821
  console.error(chalk9.red(` \u2717 Log file not found: ${opts.logFile}`));
2278
2822
  process.exit(1);
2279
2823
  }
@@ -2322,9 +2866,222 @@ function resolvePython() {
2322
2866
  return null;
2323
2867
  }
2324
2868
 
2869
+ // src/commands/provider-status.ts
2870
+ import chalk10 from "chalk";
2871
+ import {
2872
+ probeProviders
2873
+ } from "@agentspec/codegen";
2874
+ var tick = chalk10.green("\u2713");
2875
+ var cross = chalk10.red("\u2717");
2876
+ var dash = chalk10.dim("\u2013");
2877
+ var warn = chalk10.yellow("!");
2878
+ function printSection(title) {
2879
+ console.log();
2880
+ console.log(chalk10.bold.underline(title));
2881
+ }
2882
+ function row(label, value, icon) {
2883
+ const iconPart = icon ? `${icon} ` : " ";
2884
+ console.log(` ${iconPart}${chalk10.dim(label.padEnd(22))} ${value}`);
2885
+ }
2886
+ function getString(details, key) {
2887
+ const v = details[key];
2888
+ return typeof v === "string" ? v : null;
2889
+ }
2890
+ function getNumber(details, key) {
2891
+ const v = details[key];
2892
+ return typeof v === "number" ? v : null;
2893
+ }
2894
+ function providerLabel(name) {
2895
+ switch (name) {
2896
+ case "claude-subscription":
2897
+ return "Claude subscription";
2898
+ case "openai-compatible":
2899
+ return "OpenAI-compatible";
2900
+ case "anthropic-api":
2901
+ return "Anthropic API";
2902
+ default:
2903
+ return name;
2904
+ }
2905
+ }
2906
+ function renderClaudeSubscription(result) {
2907
+ printSection("Claude subscription");
2908
+ if (result.status === "not-configured") {
2909
+ row("Installed", chalk10.red("no"), cross);
2910
+ return;
2911
+ }
2912
+ const d = result.details;
2913
+ row("Installed", chalk10.green("yes"), tick);
2914
+ const version2 = getString(d, "version");
2915
+ if (version2) row("Version", chalk10.cyan(version2));
2916
+ if (result.status === "misconfigured") {
2917
+ row("Authenticated", chalk10.red("no, run: claude auth login"), cross);
2918
+ } else if (result.status === "ready") {
2919
+ row("Authenticated", chalk10.green("yes"), tick);
2920
+ }
2921
+ const email = getString(d, "accountEmail");
2922
+ if (email) row("Account", chalk10.cyan(email), tick);
2923
+ const plan = getString(d, "plan");
2924
+ if (plan) {
2925
+ const planColor = plan.toLowerCase().includes("max") || plan.toLowerCase().includes("pro") ? chalk10.green : chalk10.yellow;
2926
+ row("Plan", planColor(plan), tick);
2927
+ }
2928
+ const activeModel = getString(d, "activeModel");
2929
+ if (activeModel) row("Active model", chalk10.cyan(activeModel));
2930
+ const authStatusRaw = getString(d, "authStatusRaw");
2931
+ if (authStatusRaw && result.status === "misconfigured") {
2932
+ console.log();
2933
+ console.log(chalk10.dim(" Raw auth status output:"));
2934
+ for (const line of authStatusRaw.split("\n").slice(0, 8)) {
2935
+ console.log(chalk10.dim(` ${line}`));
2936
+ }
2937
+ }
2938
+ }
2939
+ function renderAnthropicApi(result) {
2940
+ printSection("Anthropic API");
2941
+ if (result.status === "not-configured") {
2942
+ row("ANTHROPIC_API_KEY", chalk10.red("not set"), cross);
2943
+ return;
2944
+ }
2945
+ const d = result.details;
2946
+ const keyPreview = getString(d, "keyPreview") ?? "";
2947
+ row("ANTHROPIC_API_KEY", chalk10.cyan(keyPreview), tick);
2948
+ if (result.status === "ready") {
2949
+ const httpStatus = getNumber(d, "httpStatus");
2950
+ row("Key status", chalk10.green(`valid (HTTP ${httpStatus ?? 200})`), tick);
2951
+ } else if (result.status === "unreachable") {
2952
+ row("Key status", chalk10.red(`rejected (${result.reason})`), cross);
2953
+ }
2954
+ const baseURL = getString(d, "baseURL");
2955
+ if (baseURL) {
2956
+ row("ANTHROPIC_BASE_URL", chalk10.cyan(baseURL), tick);
2957
+ } else {
2958
+ row("ANTHROPIC_BASE_URL", chalk10.dim("not set (using default)"), dash);
2959
+ }
2960
+ }
2961
+ function renderOpenAICompatible(result) {
2962
+ printSection("OpenAI-compatible");
2963
+ if (result.status === "not-configured") {
2964
+ row("AGENTSPEC_LLM_API_KEY", chalk10.red("not set"), cross);
2965
+ return;
2966
+ }
2967
+ const d = result.details;
2968
+ const keyPreview = getString(d, "apiKeyPreview") ?? "";
2969
+ row("AGENTSPEC_LLM_API_KEY", chalk10.cyan(keyPreview), tick);
2970
+ const baseURL = getString(d, "baseURL");
2971
+ if (baseURL) {
2972
+ row("AGENTSPEC_LLM_BASE_URL", chalk10.cyan(baseURL), tick);
2973
+ } else {
2974
+ row("AGENTSPEC_LLM_BASE_URL", chalk10.dim("not set (using default)"), dash);
2975
+ }
2976
+ if (result.status === "misconfigured") {
2977
+ row("AGENTSPEC_LLM_MODEL", chalk10.red("not set (required)"), cross);
2978
+ return;
2979
+ }
2980
+ const model = getString(d, "model");
2981
+ if (model) row("AGENTSPEC_LLM_MODEL", chalk10.cyan(model));
2982
+ if (result.status === "ready") {
2983
+ const httpStatus = getNumber(d, "httpStatus");
2984
+ row("Endpoint", chalk10.green(`reachable (HTTP ${httpStatus ?? 200})`), tick);
2985
+ } else if (result.status === "unreachable") {
2986
+ row("Endpoint", chalk10.red(`rejected (${result.reason})`), cross);
2987
+ }
2988
+ }
2989
+ function renderProbeResult(result) {
2990
+ switch (result.provider) {
2991
+ case "claude-subscription":
2992
+ renderClaudeSubscription(result);
2993
+ return;
2994
+ case "openai-compatible":
2995
+ renderOpenAICompatible(result);
2996
+ return;
2997
+ case "anthropic-api":
2998
+ renderAnthropicApi(result);
2999
+ return;
3000
+ default:
3001
+ printSection(result.provider);
3002
+ row("Status", result.status);
3003
+ }
3004
+ }
3005
+ function renderEnv(report) {
3006
+ const { env } = report;
3007
+ printSection("Environment & resolution");
3008
+ row(
3009
+ "Provider override",
3010
+ env.providerOverride ? chalk10.cyan(`AGENTSPEC_CODEGEN_PROVIDER=${env.providerOverride}`) : chalk10.dim("not set (auto-detect)"),
3011
+ env.providerOverride ? warn : dash
3012
+ );
3013
+ console.log();
3014
+ if (env.resolvedProvider) {
3015
+ console.log(` ${tick} ${chalk10.bold("Would use:")} ${chalk10.green(providerLabel(env.resolvedProvider))}`);
3016
+ } else {
3017
+ console.log(` ${cross} ${chalk10.bold("Would use:")} ${chalk10.red("nothing, no provider available")}`);
3018
+ if (env.resolveError) {
3019
+ console.log();
3020
+ console.log(chalk10.red(" Error:"));
3021
+ for (const line of env.resolveError.split("\n")) {
3022
+ console.log(` ${line}`);
3023
+ }
3024
+ }
3025
+ }
3026
+ }
3027
+ function renderSummary(report) {
3028
+ const { env, results } = report;
3029
+ console.log();
3030
+ console.log(chalk10.bold("\u2500".repeat(50)));
3031
+ if (!env.resolvedProvider) {
3032
+ console.log(`${cross} ${chalk10.bold.red("Not ready: no codegen provider available")}`);
3033
+ console.log();
3034
+ console.log(" Set up one of:");
3035
+ console.log(` ${chalk10.cyan("claude auth login")} ${chalk10.dim("(claude-subscription)")}`);
3036
+ console.log(` ${chalk10.cyan("export AGENTSPEC_LLM_API_KEY=... AGENTSPEC_LLM_MODEL=...")} ${chalk10.dim("(openai-compatible)")}`);
3037
+ console.log(` ${chalk10.cyan("export ANTHROPIC_API_KEY=sk-ant-...")} ${chalk10.dim("(anthropic-api)")}`);
3038
+ return;
3039
+ }
3040
+ const label = providerLabel(env.resolvedProvider);
3041
+ const resolvedResult = results.find((r) => r.provider === env.resolvedProvider);
3042
+ if (resolvedResult?.provider === "claude-subscription" && resolvedResult.status === "ready") {
3043
+ const d = resolvedResult.details;
3044
+ const plan = getString(d, "plan");
3045
+ const email = getString(d, "accountEmail");
3046
+ const planLabel = plan ? ` (${plan})` : "";
3047
+ const emailLabel = email ? ` \xB7 ${email}` : "";
3048
+ console.log(`${tick} ${chalk10.bold.green(`Ready: ${label}${planLabel}${emailLabel}`)}`);
3049
+ } else if (resolvedResult?.provider === "anthropic-api" && resolvedResult.status === "ready") {
3050
+ console.log(`${tick} ${chalk10.bold.green(`Ready: ${label} \xB7 key verified`)}`);
3051
+ } else if (resolvedResult?.provider === "openai-compatible" && resolvedResult.status === "ready") {
3052
+ const d = resolvedResult.details;
3053
+ const model = getString(d, "model");
3054
+ const modelHint = model ? ` \xB7 ${model}` : "";
3055
+ console.log(`${tick} ${chalk10.bold.green(`Ready: ${label}${modelHint}`)}`);
3056
+ } else {
3057
+ console.log(`${tick} ${chalk10.bold.green(`Ready: ${label}`)}`);
3058
+ }
3059
+ console.log(chalk10.dim(` agentspec generate and scan will use the ${env.resolvedProvider} provider`));
3060
+ }
3061
+ function registerProviderStatusCommand(program2) {
3062
+ program2.command("provider-status").description("Show codegen provider status: Claude subscription, OpenAI-compatible, Anthropic API, and active config").option("--json", "Output as JSON").action(async (opts) => {
3063
+ if (!opts.json) {
3064
+ printHeader("AgentSpec: Provider Status");
3065
+ }
3066
+ const report = await probeProviders();
3067
+ if (opts.json) {
3068
+ console.log(JSON.stringify(report, null, 2));
3069
+ process.exit(!report.env.resolvedProvider ? 1 : 0);
3070
+ return;
3071
+ }
3072
+ for (const result of report.results) {
3073
+ renderProbeResult(result);
3074
+ }
3075
+ renderEnv(report);
3076
+ renderSummary(report);
3077
+ console.log();
3078
+ process.exit(!report.env.resolvedProvider ? 1 : 0);
3079
+ });
3080
+ }
3081
+
2325
3082
  // src/cli.ts
2326
- var _dir = dirname3(fileURLToPath(import.meta.url));
2327
- var { version } = JSON.parse(readFileSync6(join5(_dir, "../package.json"), "utf8"));
3083
+ var _dir = dirname4(fileURLToPath(import.meta.url));
3084
+ var { version } = JSON.parse(readFileSync8(join7(_dir, "../package.json"), "utf8"));
2328
3085
  var program = new Command();
2329
3086
  program.name("agentspec").description("Universal Agent Manifest System \u2014 validate, health-check, audit, and generate agents").version(version);
2330
3087
  registerValidateCommand(program);
@@ -2339,5 +3096,6 @@ registerDiffCommand(program);
2339
3096
  registerGeneratePolicyCommand(program);
2340
3097
  registerEvaluateCommand(program);
2341
3098
  registerProbeCommand(program);
3099
+ registerProviderStatusCommand(program);
2342
3100
  program.parse(process.argv);
2343
3101
  //# sourceMappingURL=cli.js.map