@agentspec/adapter-claude 0.1.11 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -51,5 +51,18 @@ interface ClaudeAdapterOptions {
51
51
  * Throws if Claude does not return a parseable JSON response.
52
52
  */
53
53
  declare function generateWithClaude(manifest: AgentSpecManifest, options: ClaudeAdapterOptions): Promise<GeneratedAgent>;
54
+ interface RepairOptions {
55
+ /** Claude model ID. Defaults to claude-opus-4-6. */
56
+ model?: string;
57
+ }
58
+ /**
59
+ * Ask Claude to fix an agent.yaml string that failed schema validation.
60
+ *
61
+ * Reuses the scan skill as the system prompt (it carries full schema knowledge).
62
+ * Returns the repaired YAML string, ready to be re-validated by the caller.
63
+ *
64
+ * Throws if ANTHROPIC_API_KEY is not set or Claude does not return a parseable response.
65
+ */
66
+ declare function repairYaml(yamlStr: string, validationErrors: string, options?: RepairOptions): Promise<string>;
54
67
 
55
- export { type ClaudeAdapterOptions, type GenerationProgress, generateWithClaude, listFrameworks };
68
+ export { type ClaudeAdapterOptions, type GenerationProgress, type RepairOptions, generateWithClaude, listFrameworks, repairYaml };
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import { readFileSync } from "fs";
9
9
  import { join } from "path";
10
10
  function extractFileRefs(manifest, baseDir) {
11
11
  const refs = [];
12
- for (const tool of manifest.spec.tools ?? []) {
12
+ for (const tool of manifest.spec?.tools ?? []) {
13
13
  const mod = tool.module;
14
14
  if (typeof mod === "string" && mod.startsWith("$file:")) {
15
15
  refs.push(join(baseDir, mod.slice(6)));
@@ -63,16 +63,36 @@ function loadSkill(framework) {
63
63
  }
64
64
  return guidelines + readFileSync2(join2(skillsDir, `${framework}.md`), "utf-8");
65
65
  }
66
- async function generateWithClaude(manifest, options) {
66
+ function initClaudeClient() {
67
67
  const apiKey = process.env["ANTHROPIC_API_KEY"];
68
68
  if (!apiKey) {
69
69
  throw new Error(
70
70
  "ANTHROPIC_API_KEY is not set. AgentSpec generates code using Claude.\nGet a key at https://console.anthropic.com and add it to your environment."
71
71
  );
72
72
  }
73
- const skillMd = loadSkill(options.framework);
74
73
  const baseURL = process.env["ANTHROPIC_BASE_URL"];
75
- const client = new Anthropic({ apiKey, ...baseURL ? { baseURL } : {} });
74
+ return new Anthropic({ apiKey, ...baseURL ? { baseURL } : {} });
75
+ }
76
+ var REPAIR_SYSTEM_PROMPT = `You are an AgentSpec v1 YAML schema fixer.
77
+ Fix the agent.yaml provided by the user so it complies with the AgentSpec v1 schema.
78
+ Return ONLY a JSON object with this exact shape (no other text):
79
+ {"files":{"agent.yaml":"<corrected YAML>"},"installCommands":[],"envVars":[]}
80
+
81
+ ## AgentSpec v1 schema rules (enforce all of these):
82
+ - Top-level keys: apiVersion: "agentspec.io/v1", kind: "AgentSpec"
83
+ - metadata: name (slug a-z0-9-), version (semver), description
84
+ - spec.model: provider, id (never "name"), apiKey: "$env:VAR"
85
+ - spec.model.fallback: provider, id, apiKey, triggerOn (array of strings)
86
+ - spec.tools[]: name (slug), type: "function", description
87
+ - spec.memory.shortTerm.backend: "redis" | "in-memory" | "sqlite"
88
+ - spec.memory.longTerm.backend: "postgres" | "sqlite" | "mongodb"
89
+ - spec.guardrails.input: array of guardrail objects (not a scalar)
90
+ - spec.guardrails.output: array of guardrail objects (not a scalar)
91
+ - spec.requires.envVars: array of strings (key is "envVars", not "env")
92
+ - spec.requires.services[]: {type, connection: "$env:VAR"}`;
93
+ async function generateWithClaude(manifest, options) {
94
+ const client = initClaudeClient();
95
+ const skillMd = loadSkill(options.framework);
76
96
  const context = buildContext({
77
97
  manifest,
78
98
  contextFiles: options.contextFiles,
@@ -101,6 +121,38 @@ async function generateWithClaude(manifest, options) {
101
121
  }
102
122
  return extractGeneratedAgent(text, options.framework);
103
123
  }
124
+ async function repairYaml(yamlStr, validationErrors, options = {}) {
125
+ const client = initClaudeClient();
126
+ const model = options.model ?? process.env["ANTHROPIC_MODEL"] ?? "claude-opus-4-6";
127
+ const userMessage = `The following agent.yaml failed AgentSpec v1 schema validation.
128
+ Fix ALL the errors listed below and return the corrected file in the same JSON format.
129
+
130
+ ## Current (invalid) YAML:
131
+ \`\`\`yaml
132
+ ${yamlStr}
133
+ \`\`\`
134
+
135
+ ## Validation errors:
136
+ \`\`\`
137
+ ${validationErrors}
138
+ \`\`\`
139
+
140
+ Return ONLY a JSON object (no other text):
141
+ \`\`\`json
142
+ {"files":{"agent.yaml":"<corrected YAML>"},"installCommands":[],"envVars":[]}
143
+ \`\`\``;
144
+ const response = await client.messages.create({
145
+ model,
146
+ max_tokens: 16384,
147
+ system: REPAIR_SYSTEM_PROMPT,
148
+ messages: [{ role: "user", content: userMessage }]
149
+ });
150
+ const text = response.content.filter((block) => block.type === "text").map((block) => block.text).join("");
151
+ const result = extractGeneratedAgent(text, "scan");
152
+ const fixed = result.files["agent.yaml"];
153
+ if (!fixed) throw new Error("Claude did not return agent.yaml in repair response.");
154
+ return fixed;
155
+ }
104
156
  function extractGeneratedAgent(text, framework) {
105
157
  const candidates = [];
106
158
  const trimmed = text.trim();
@@ -148,6 +200,7 @@ ${text.slice(0, 500)}`
148
200
  }
149
201
  export {
150
202
  generateWithClaude,
151
- listFrameworks
203
+ listFrameworks,
204
+ repairYaml
152
205
  };
153
206
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/context-builder.ts"],"sourcesContent":["/**\n * @agentspec/adapter-claude\n *\n * Agentic code generation using Claude API.\n * Claude receives the full manifest JSON + a framework-specific skill file as system prompt and\n * generates production-ready code covering all manifest fields.\n *\n * Requires: ANTHROPIC_API_KEY environment variable.\n *\n * Usage:\n * import { generateWithClaude, listFrameworks } from '@agentspec/adapter-claude'\n * const result = await generateWithClaude(manifest, { framework: 'langgraph' })\n * const frameworks = listFrameworks() // ['crewai', 'langgraph', 'mastra']\n */\n\nimport Anthropic from '@anthropic-ai/sdk'\nimport { readFileSync, readdirSync } from 'node:fs'\nimport { join, dirname } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { AgentSpecManifest, GeneratedAgent } from '@agentspec/sdk'\nimport { buildContext } from './context-builder.js'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\nconst skillsDir = join(__dirname, 'skills')\n\n/**\n * Returns the list of supported framework names (based on .md files in skills/).\n * Excludes guidelines.md which is a universal base layer, not a framework.\n */\nexport function listFrameworks(): string[] {\n return readdirSync(skillsDir)\n .filter((f) => f.endsWith('.md') && f !== 'guidelines.md')\n .map((f) => f.slice(0, -3))\n .sort()\n}\n\n/**\n * Load the skill file for a given framework, prepended with universal guidelines.\n * Throws a descriptive error if the framework is not supported.\n */\nfunction loadSkill(framework: string): string {\n const available = listFrameworks()\n if (!available.includes(framework)) {\n throw new Error(\n `Framework '${framework}' is not supported. Available: ${available.join(', ')}`,\n )\n }\n const guidelinesPath = join(skillsDir, 'guidelines.md')\n let guidelines = ''\n try {\n guidelines = readFileSync(guidelinesPath, 'utf-8') + '\\n\\n---\\n\\n'\n } catch {\n // guidelines.md is optional — skip if missing\n }\n return guidelines + readFileSync(join(skillsDir, `${framework}.md`), 'utf-8')\n}\n\nexport interface GenerationProgress {\n /** Cumulative output characters received so far during streaming. */\n outputChars: number\n}\n\nexport interface ClaudeAdapterOptions {\n /** Target framework (e.g. 'langgraph', 'crewai', 'mastra'). */\n framework: string\n /** Claude model ID. Defaults to claude-opus-4-6. */\n model?: string\n /** Optional source files to append to the user message for richer context. */\n contextFiles?: string[]\n /**\n * Base directory of the manifest file. When provided, $file: references in\n * spec.tools[].module are automatically resolved and included as context files.\n */\n manifestDir?: string\n /**\n * Called on each streamed chunk with cumulative char count.\n * When provided, generation uses the streaming API so the caller can show\n * a live progress indicator. Omit to use a single blocking request.\n */\n onProgress?: (progress: GenerationProgress) => void\n}\n\n/**\n * Generate agent code using Claude API.\n *\n * Throws if ANTHROPIC_API_KEY is not set (with a helpful remediation message).\n * Throws if the framework is not supported.\n * Throws if Claude does not return a parseable JSON response.\n */\nexport async function generateWithClaude(\n manifest: AgentSpecManifest,\n options: ClaudeAdapterOptions,\n): Promise<GeneratedAgent> {\n const apiKey = process.env['ANTHROPIC_API_KEY']\n if (!apiKey) {\n throw new Error(\n 'ANTHROPIC_API_KEY is not set. AgentSpec generates code using Claude.\\n' +\n 'Get a key at https://console.anthropic.com and add it to your environment.',\n )\n }\n\n const skillMd = loadSkill(options.framework)\n\n const baseURL = process.env['ANTHROPIC_BASE_URL']\n const client = new Anthropic({ apiKey, ...(baseURL ? { baseURL } : {}) })\n const context = buildContext({\n manifest,\n contextFiles: options.contextFiles,\n manifestDir: options.manifestDir,\n })\n const model = options.model ?? process.env['ANTHROPIC_MODEL'] ?? 'claude-opus-4-6'\n\n const requestParams = {\n model,\n max_tokens: 32768,\n system: skillMd,\n messages: [{ role: 'user' as const, content: context }],\n }\n\n let text: string\n\n if (options.onProgress) {\n // Streaming path — yields chunks so the caller can show live progress.\n let accumulated = ''\n for await (const event of client.messages.stream(requestParams)) {\n if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {\n accumulated += event.delta.text\n options.onProgress({ outputChars: accumulated.length })\n }\n }\n text = accumulated\n } else {\n // Blocking path — single request, no progress callbacks.\n const response = await client.messages.create(requestParams)\n text = response.content\n .filter((block): block is Anthropic.TextBlock => block.type === 'text')\n .map((block) => block.text)\n .join('')\n }\n\n return extractGeneratedAgent(text, options.framework)\n}\n\n// ── Response parsing ──────────────────────────────────────────────────────────\n\ninterface ClaudeGenerationResult {\n files: Record<string, string>\n installCommands?: string[]\n envVars?: string[]\n}\n\nfunction extractGeneratedAgent(text: string, framework: string): GeneratedAgent {\n // Build candidates in priority order and return the first one that parses\n // correctly. Multiple strategies are needed because:\n //\n // 1. Claude may return bare JSON (no fence).\n // 2. Claude may wrap in ```json … ``` but the generated code inside the\n // JSON string values can contain backtick sequences that fool a naive\n // non-greedy regex — so we use lastIndexOf('\\n```') as the close marker.\n // 3. As a last resort, pull the outermost {...} from the text.\n const candidates: string[] = []\n\n const trimmed = text.trim()\n\n // Strategy 1: bare JSON\n if (trimmed.startsWith('{')) {\n candidates.push(trimmed)\n }\n\n // Strategy 2: ```json fence — close at the last newline+``` to survive\n // backtick sequences embedded inside generated code strings.\n const fenceOpen = text.indexOf('```json')\n if (fenceOpen !== -1) {\n const contentStart = text.indexOf('\\n', fenceOpen) + 1\n const fenceClose = text.lastIndexOf('\\n```')\n if (fenceClose > contentStart) {\n candidates.push(text.slice(contentStart, fenceClose))\n }\n }\n\n // Strategy 3: greedy brace match\n const braceMatch = text.match(/(\\{[\\s\\S]*\\})/)\n if (braceMatch?.[1]) candidates.push(braceMatch[1])\n\n let parsedAny = false\n for (const candidate of candidates) {\n let parsed: unknown\n try {\n parsed = JSON.parse(candidate)\n } catch {\n continue\n }\n parsedAny = true\n if (!parsed || typeof parsed !== 'object' || !('files' in parsed)) continue\n\n const result = parsed as ClaudeGenerationResult\n return {\n framework,\n files: result.files,\n installCommands: result.installCommands ?? [],\n envVars: result.envVars ?? [],\n readme: result.files['README.md'] ?? '',\n }\n }\n\n if (parsedAny) {\n throw new Error('Claude response JSON is missing the required \"files\" field.')\n }\n\n throw new Error(\n `Claude did not return a valid JSON response.\\n\\nReceived:\\n${text.slice(0, 500)}`,\n )\n}\n","import type { AgentSpecManifest } from '@agentspec/sdk'\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nexport interface BuildContextOptions {\n manifest: AgentSpecManifest\n contextFiles?: string[]\n /** Base directory for resolving $file: references in spec.tools[].module */\n manifestDir?: string\n}\n\n/**\n * Scan spec.tools[].module for $file: references and return resolved absolute paths.\n * This gives Claude the actual tool implementations to reference when generating typed wrappers.\n */\nfunction extractFileRefs(manifest: AgentSpecManifest, baseDir: string): string[] {\n const refs: string[] = []\n for (const tool of manifest.spec.tools ?? []) {\n const mod = (tool as Record<string, unknown>).module as string | undefined\n if (typeof mod === 'string' && mod.startsWith('$file:')) {\n refs.push(join(baseDir, mod.slice(6)))\n }\n }\n return refs\n}\n\n/**\n * Build the user-message context for Claude from a manifest + optional source files.\n * The manifest is serialised as JSON. Context files are appended verbatim so Claude\n * can infer tool signatures, existing patterns, etc.\n *\n * When manifestDir is provided, $file: references in spec.tools[].module are automatically\n * resolved and included as context files.\n */\nexport function buildContext(options: BuildContextOptions): string {\n const { manifest, contextFiles = [], manifestDir } = options\n\n const resolvedRefs = manifestDir ? extractFileRefs(manifest, manifestDir) : []\n const allContextFiles = [...resolvedRefs, ...contextFiles]\n\n const parts: string[] = [\n '## Agent Manifest (JSON)',\n '```json',\n JSON.stringify(manifest, null, 2),\n '```',\n ]\n\n for (const filePath of allContextFiles) {\n try {\n const content = readFileSync(filePath, 'utf-8')\n const ext = filePath.split('.').pop() ?? ''\n parts.push(`\\n## Context File: ${filePath}`)\n parts.push(`\\`\\`\\`${ext}`)\n parts.push(content)\n parts.push('```')\n } catch {\n // Silently skip unreadable context files\n }\n }\n\n return parts.join('\\n')\n}\n"],"mappings":";AAeA,OAAO,eAAe;AACtB,SAAS,gBAAAA,eAAc,mBAAmB;AAC1C,SAAS,QAAAC,OAAM,eAAe;AAC9B,SAAS,qBAAqB;;;ACjB9B,SAAS,oBAAoB;AAC7B,SAAS,YAAY;AAarB,SAAS,gBAAgB,UAA6B,SAA2B;AAC/E,QAAM,OAAiB,CAAC;AACxB,aAAW,QAAQ,SAAS,KAAK,SAAS,CAAC,GAAG;AAC5C,UAAM,MAAO,KAAiC;AAC9C,QAAI,OAAO,QAAQ,YAAY,IAAI,WAAW,QAAQ,GAAG;AACvD,WAAK,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,CAAC,CAAC;AAAA,IACvC;AAAA,EACF;AACA,SAAO;AACT;AAUO,SAAS,aAAa,SAAsC;AACjE,QAAM,EAAE,UAAU,eAAe,CAAC,GAAG,YAAY,IAAI;AAErD,QAAM,eAAe,cAAc,gBAAgB,UAAU,WAAW,IAAI,CAAC;AAC7E,QAAM,kBAAkB,CAAC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AAY,KAAK,QAAQ,SAAS;AACxC,MAAI,cAAc,IAAI;AACpB,UAAM,eAAe,KAAK,QAAQ,MAAM,SAAS,IAAI;AACrD,UAAM,aAAa,KAAK,YAAY,OAAO;AAC3C,QAAI,aAAa,cAAc;AAC7B,iBAAW,KAAK,KAAK,MAAM,cAAc,UAAU,CAAC;AAAA,IACtD;AAAA,EACF;AAGA,QAAM,aAAa,KAAK,MAAM,eAAe;AAC7C,MAAI,aAAa,CAAC,EAAG,YAAW,KAAK,WAAW,CAAC,CAAC;AAElD,MAAI,YAAY;AAChB,aAAW,aAAa,YAAY;AAClC,QAAI;AACJ,QAAI;AACF,eAAS,KAAK,MAAM,SAAS;AAAA,IAC/B,QAAQ;AACN;AAAA,IACF;AACA,gBAAY;AACZ,QAAI,CAAC,UAAU,OAAO,WAAW,YAAY,EAAE,WAAW,QAAS;AAEnE,UAAM,SAAS;AACf,WAAO;AAAA,MACL;AAAA,MACA,OAAO,OAAO;AAAA,MACd,iBAAiB,OAAO,mBAAmB,CAAC;AAAA,MAC5C,SAAS,OAAO,WAAW,CAAC;AAAA,MAC5B,QAAQ,OAAO,MAAM,WAAW,KAAK;AAAA,IACvC;AAAA,EACF;AAEA,MAAI,WAAW;AACb,UAAM,IAAI,MAAM,6DAA6D;AAAA,EAC/E;AAEA,QAAM,IAAI;AAAA,IACR;AAAA;AAAA;AAAA,EAA8D,KAAK,MAAM,GAAG,GAAG,CAAC;AAAA,EAClF;AACF;","names":["readFileSync","join","join","readFileSync"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/context-builder.ts"],"sourcesContent":["/**\n * @agentspec/adapter-claude\n *\n * Agentic code generation using Claude API.\n * Claude receives the full manifest JSON + a framework-specific skill file as system prompt and\n * generates production-ready code covering all manifest fields.\n *\n * Requires: ANTHROPIC_API_KEY environment variable.\n *\n * Usage:\n * import { generateWithClaude, listFrameworks } from '@agentspec/adapter-claude'\n * const result = await generateWithClaude(manifest, { framework: 'langgraph' })\n * const frameworks = listFrameworks() // ['crewai', 'langgraph', 'mastra']\n */\n\nimport Anthropic from '@anthropic-ai/sdk'\nimport { readFileSync, readdirSync } from 'node:fs'\nimport { join, dirname } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { AgentSpecManifest, GeneratedAgent } from '@agentspec/sdk'\nimport { buildContext } from './context-builder.js'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\nconst skillsDir = join(__dirname, 'skills')\n\n/**\n * Returns the list of supported framework names (based on .md files in skills/).\n * Excludes guidelines.md which is a universal base layer, not a framework.\n */\nexport function listFrameworks(): string[] {\n return readdirSync(skillsDir)\n .filter((f) => f.endsWith('.md') && f !== 'guidelines.md')\n .map((f) => f.slice(0, -3))\n .sort()\n}\n\n/**\n * Load the skill file for a given framework, prepended with universal guidelines.\n * Throws a descriptive error if the framework is not supported.\n */\nfunction loadSkill(framework: string): string {\n const available = listFrameworks()\n if (!available.includes(framework)) {\n throw new Error(\n `Framework '${framework}' is not supported. Available: ${available.join(', ')}`,\n )\n }\n const guidelinesPath = join(skillsDir, 'guidelines.md')\n let guidelines = ''\n try {\n guidelines = readFileSync(guidelinesPath, 'utf-8') + '\\n\\n---\\n\\n'\n } catch {\n // guidelines.md is optional — skip if missing\n }\n return guidelines + readFileSync(join(skillsDir, `${framework}.md`), 'utf-8')\n}\n\n/**\n * Guard ANTHROPIC_API_KEY and return a configured Anthropic client.\n * Throws with a remediation message if the key is missing.\n */\nfunction initClaudeClient(): Anthropic {\n const apiKey = process.env['ANTHROPIC_API_KEY']\n if (!apiKey) {\n throw new Error(\n 'ANTHROPIC_API_KEY is not set. AgentSpec generates code using Claude.\\n' +\n 'Get a key at https://console.anthropic.com and add it to your environment.',\n )\n }\n const baseURL = process.env['ANTHROPIC_BASE_URL']\n return new Anthropic({ apiKey, ...(baseURL ? { baseURL } : {}) })\n}\n\n/** System prompt used exclusively by repairYaml — knows AgentSpec v1 schema rules. */\nconst REPAIR_SYSTEM_PROMPT =\n `You are an AgentSpec v1 YAML schema fixer.\\n` +\n `Fix the agent.yaml provided by the user so it complies with the AgentSpec v1 schema.\\n` +\n `Return ONLY a JSON object with this exact shape (no other text):\\n` +\n `{\"files\":{\"agent.yaml\":\"<corrected YAML>\"},\"installCommands\":[],\"envVars\":[]}\\n\\n` +\n `## AgentSpec v1 schema rules (enforce all of these):\\n` +\n `- Top-level keys: apiVersion: \"agentspec.io/v1\", kind: \"AgentSpec\"\\n` +\n `- metadata: name (slug a-z0-9-), version (semver), description\\n` +\n `- spec.model: provider, id (never \"name\"), apiKey: \"$env:VAR\"\\n` +\n `- spec.model.fallback: provider, id, apiKey, triggerOn (array of strings)\\n` +\n `- spec.tools[]: name (slug), type: \"function\", description\\n` +\n `- spec.memory.shortTerm.backend: \"redis\" | \"in-memory\" | \"sqlite\"\\n` +\n `- spec.memory.longTerm.backend: \"postgres\" | \"sqlite\" | \"mongodb\"\\n` +\n `- spec.guardrails.input: array of guardrail objects (not a scalar)\\n` +\n `- spec.guardrails.output: array of guardrail objects (not a scalar)\\n` +\n `- spec.requires.envVars: array of strings (key is \"envVars\", not \"env\")\\n` +\n `- spec.requires.services[]: {type, connection: \"$env:VAR\"}`\n\nexport interface GenerationProgress {\n /** Cumulative output characters received so far during streaming. */\n outputChars: number\n}\n\nexport interface ClaudeAdapterOptions {\n /** Target framework (e.g. 'langgraph', 'crewai', 'mastra'). */\n framework: string\n /** Claude model ID. Defaults to claude-opus-4-6. */\n model?: string\n /** Optional source files to append to the user message for richer context. */\n contextFiles?: string[]\n /**\n * Base directory of the manifest file. When provided, $file: references in\n * spec.tools[].module are automatically resolved and included as context files.\n */\n manifestDir?: string\n /**\n * Called on each streamed chunk with cumulative char count.\n * When provided, generation uses the streaming API so the caller can show\n * a live progress indicator. Omit to use a single blocking request.\n */\n onProgress?: (progress: GenerationProgress) => void\n}\n\n/**\n * Generate agent code using Claude API.\n *\n * Throws if ANTHROPIC_API_KEY is not set (with a helpful remediation message).\n * Throws if the framework is not supported.\n * Throws if Claude does not return a parseable JSON response.\n */\nexport async function generateWithClaude(\n manifest: AgentSpecManifest,\n options: ClaudeAdapterOptions,\n): Promise<GeneratedAgent> {\n const client = initClaudeClient()\n const skillMd = loadSkill(options.framework)\n\n const context = buildContext({\n manifest,\n contextFiles: options.contextFiles,\n manifestDir: options.manifestDir,\n })\n const model = options.model ?? process.env['ANTHROPIC_MODEL'] ?? 'claude-opus-4-6'\n\n const requestParams = {\n model,\n max_tokens: 32768,\n system: skillMd,\n messages: [{ role: 'user' as const, content: context }],\n }\n\n let text: string\n\n if (options.onProgress) {\n // Streaming path — yields chunks so the caller can show live progress.\n let accumulated = ''\n for await (const event of client.messages.stream(requestParams)) {\n if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {\n accumulated += event.delta.text\n options.onProgress({ outputChars: accumulated.length })\n }\n }\n text = accumulated\n } else {\n // Blocking path — single request, no progress callbacks.\n const response = await client.messages.create(requestParams)\n text = response.content\n .filter((block): block is Anthropic.TextBlock => block.type === 'text')\n .map((block) => block.text)\n .join('')\n }\n\n return extractGeneratedAgent(text, options.framework)\n}\n\n// ── YAML repair ──────────────────────────────────────────────────────────────\n\nexport interface RepairOptions {\n /** Claude model ID. Defaults to claude-opus-4-6. */\n model?: string\n}\n\n/**\n * Ask Claude to fix an agent.yaml string that failed schema validation.\n *\n * Reuses the scan skill as the system prompt (it carries full schema knowledge).\n * Returns the repaired YAML string, ready to be re-validated by the caller.\n *\n * Throws if ANTHROPIC_API_KEY is not set or Claude does not return a parseable response.\n */\nexport async function repairYaml(\n yamlStr: string,\n validationErrors: string,\n options: RepairOptions = {},\n): Promise<string> {\n const client = initClaudeClient()\n const model = options.model ?? process.env['ANTHROPIC_MODEL'] ?? 'claude-opus-4-6'\n\n const userMessage =\n `The following agent.yaml failed AgentSpec v1 schema validation.\\n` +\n `Fix ALL the errors listed below and return the corrected file in the same JSON format.\\n\\n` +\n `## Current (invalid) YAML:\\n\\`\\`\\`yaml\\n${yamlStr}\\n\\`\\`\\`\\n\\n` +\n `## Validation errors:\\n\\`\\`\\`\\n${validationErrors}\\n\\`\\`\\`\\n\\n` +\n `Return ONLY a JSON object (no other text):\\n` +\n `\\`\\`\\`json\\n{\"files\":{\"agent.yaml\":\"<corrected YAML>\"},\"installCommands\":[],\"envVars\":[]}\\n\\`\\`\\``\n\n const response = await client.messages.create({\n model,\n max_tokens: 16384,\n system: REPAIR_SYSTEM_PROMPT,\n messages: [{ role: 'user' as const, content: userMessage }],\n })\n\n const text = response.content\n .filter((block): block is Anthropic.TextBlock => block.type === 'text')\n .map(block => block.text)\n .join('')\n\n const result = extractGeneratedAgent(text, 'scan')\n const fixed = result.files['agent.yaml']\n if (!fixed) throw new Error('Claude did not return agent.yaml in repair response.')\n return fixed\n}\n\n// ── Response parsing ──────────────────────────────────────────────────────────\n\ninterface ClaudeGenerationResult {\n files: Record<string, string>\n installCommands?: string[]\n envVars?: string[]\n}\n\nfunction extractGeneratedAgent(text: string, framework: string): GeneratedAgent {\n // Build candidates in priority order and return the first one that parses\n // correctly. Multiple strategies are needed because:\n //\n // 1. Claude may return bare JSON (no fence).\n // 2. Claude may wrap in ```json … ``` but the generated code inside the\n // JSON string values can contain backtick sequences that fool a naive\n // non-greedy regex — so we use lastIndexOf('\\n```') as the close marker.\n // 3. As a last resort, pull the outermost {...} from the text.\n const candidates: string[] = []\n\n const trimmed = text.trim()\n\n // Strategy 1: bare JSON\n if (trimmed.startsWith('{')) {\n candidates.push(trimmed)\n }\n\n // Strategy 2: ```json fence — close at the last newline+``` to survive\n // backtick sequences embedded inside generated code strings.\n const fenceOpen = text.indexOf('```json')\n if (fenceOpen !== -1) {\n const contentStart = text.indexOf('\\n', fenceOpen) + 1\n const fenceClose = text.lastIndexOf('\\n```')\n if (fenceClose > contentStart) {\n candidates.push(text.slice(contentStart, fenceClose))\n }\n }\n\n // Strategy 3: greedy brace match\n const braceMatch = text.match(/(\\{[\\s\\S]*\\})/)\n if (braceMatch?.[1]) candidates.push(braceMatch[1])\n\n let parsedAny = false\n for (const candidate of candidates) {\n let parsed: unknown\n try {\n parsed = JSON.parse(candidate)\n } catch {\n continue\n }\n parsedAny = true\n if (!parsed || typeof parsed !== 'object' || !('files' in parsed)) continue\n\n const result = parsed as ClaudeGenerationResult\n return {\n framework,\n files: result.files,\n installCommands: result.installCommands ?? [],\n envVars: result.envVars ?? [],\n readme: result.files['README.md'] ?? '',\n }\n }\n\n if (parsedAny) {\n throw new Error('Claude response JSON is missing the required \"files\" field.')\n }\n\n throw new Error(\n `Claude did not return a valid JSON response.\\n\\nReceived:\\n${text.slice(0, 500)}`,\n )\n}\n","import type { AgentSpecManifest } from '@agentspec/sdk'\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nexport interface BuildContextOptions {\n manifest: AgentSpecManifest\n contextFiles?: string[]\n /** Base directory for resolving $file: references in spec.tools[].module */\n manifestDir?: string\n}\n\n/**\n * Scan spec.tools[].module for $file: references and return resolved absolute paths.\n * This gives Claude the actual tool implementations to reference when generating typed wrappers.\n */\nfunction extractFileRefs(manifest: AgentSpecManifest, baseDir: string): string[] {\n const refs: string[] = []\n for (const tool of manifest.spec?.tools ?? []) {\n const mod = (tool as Record<string, unknown>).module as string | undefined\n if (typeof mod === 'string' && mod.startsWith('$file:')) {\n refs.push(join(baseDir, mod.slice(6)))\n }\n }\n return refs\n}\n\n/**\n * Build the user-message context for Claude from a manifest + optional source files.\n * The manifest is serialised as JSON. Context files are appended verbatim so Claude\n * can infer tool signatures, existing patterns, etc.\n *\n * When manifestDir is provided, $file: references in spec.tools[].module are automatically\n * resolved and included as context files.\n */\nexport function buildContext(options: BuildContextOptions): string {\n const { manifest, contextFiles = [], manifestDir } = options\n\n const resolvedRefs = manifestDir ? extractFileRefs(manifest, manifestDir) : []\n const allContextFiles = [...resolvedRefs, ...contextFiles]\n\n const parts: string[] = [\n '## Agent Manifest (JSON)',\n '```json',\n JSON.stringify(manifest, null, 2),\n '```',\n ]\n\n for (const filePath of allContextFiles) {\n try {\n const content = readFileSync(filePath, 'utf-8')\n const ext = filePath.split('.').pop() ?? ''\n parts.push(`\\n## Context File: ${filePath}`)\n parts.push(`\\`\\`\\`${ext}`)\n parts.push(content)\n parts.push('```')\n } catch {\n // Silently skip unreadable context files\n }\n }\n\n return parts.join('\\n')\n}\n"],"mappings":";AAeA,OAAO,eAAe;AACtB,SAAS,gBAAAA,eAAc,mBAAmB;AAC1C,SAAS,QAAAC,OAAM,eAAe;AAC9B,SAAS,qBAAqB;;;ACjB9B,SAAS,oBAAoB;AAC7B,SAAS,YAAY;AAarB,SAAS,gBAAgB,UAA6B,SAA2B;AAC/E,QAAM,OAAiB,CAAC;AACxB,aAAW,QAAQ,SAAS,MAAM,SAAS,CAAC,GAAG;AAC7C,UAAM,MAAO,KAAiC;AAC9C,QAAI,OAAO,QAAQ,YAAY,IAAI,WAAW,QAAQ,GAAG;AACvD,WAAK,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,CAAC,CAAC;AAAA,IACvC;AAAA,EACF;AACA,SAAO;AACT;AAUO,SAAS,aAAa,SAAsC;AACjE,QAAM,EAAE,UAAU,eAAe,CAAC,GAAG,YAAY,IAAI;AAErD,QAAM,eAAe,cAAc,gBAAgB,UAAU,WAAW,IAAI,CAAC;AAC7E,QAAM,kBAAkB,CAAC,GAAG,cAAc,GAAG,YAAY;AAEzD,QAAM,QAAkB;AAAA,IACtB;AAAA,IACA;AAAA,IACA,KAAK,UAAU,UAAU,MAAM,CAAC;AAAA,IAChC;AAAA,EACF;AAEA,aAAW,YAAY,iBAAiB;AACtC,QAAI;AACF,YAAM,UAAU,aAAa,UAAU,OAAO;AAC9C,YAAM,MAAM,SAAS,MAAM,GAAG,EAAE,IAAI,KAAK;AACzC,YAAM,KAAK;AAAA,mBAAsB,QAAQ,EAAE;AAC3C,YAAM,KAAK,SAAS,GAAG,EAAE;AACzB,YAAM,KAAK,OAAO;AAClB,YAAM,KAAK,KAAK;AAAA,IAClB,QAAQ;AAAA,IAER;AAAA,EACF;AAEA,SAAO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EA,QAAM,IAAI;AAAA,IACR;AAAA;AAAA;AAAA,EAA8D,KAAK,MAAM,GAAG,GAAG,CAAC;AAAA,EAClF;AACF;","names":["readFileSync","join","join","readFileSync"]}
@@ -1,10 +1,9 @@
1
1
  # AgentSpec Scan Skill
2
2
 
3
- You are analysing source code to produce a valid `agent.yaml` manifest.
3
+ You are analysing source code to detect what kind of AI agent it implements.
4
4
 
5
- The caller will provide one or more source files embedded in the context.
6
- Your job is to extract everything the agent declares and express it as
7
- a complete `agent.yaml` that conforms to the AgentSpec v1 schema.
5
+ Your **only job** is to return a `detection.json` file containing raw facts you find in the source.
6
+ **Do NOT generate YAML.** TypeScript will convert your detection to a valid manifest.
8
7
 
9
8
  ---
10
9
 
@@ -15,181 +14,169 @@ Respond with **exactly one JSON object** in this shape:
15
14
  ```json
16
15
  {
17
16
  "files": {
18
- "agent.yaml": "<full YAML content as a string>"
17
+ "detection.json": "<ScanDetection object as a JSON string>"
19
18
  },
20
19
  "installCommands": [],
21
20
  "envVars": ["OPENAI_API_KEY", "..."]
22
21
  }
23
22
  ```
24
23
 
25
- - The `agent.yaml` value must be a valid YAML string (escape `\n` as literal newlines inside the JSON string value).
26
- - Do NOT include any text outside the JSON object.
27
- - Do NOT truncate the YAML.
24
+ The `detection.json` value must be a **valid JSON string** encoding a `ScanDetection` object (see interface below).
25
+ Do NOT include any text outside the JSON object. Do NOT generate YAML.
28
26
 
29
27
  ---
30
28
 
31
- ## Detection Rules
29
+ ## ScanDetection Interface
30
+
31
+ Return raw values only — do NOT slugify or normalise. The builder handles that.
32
+
33
+ ```typescript
34
+ interface ScanDetection {
35
+ name: string // agent name (raw — can have underscores, spaces)
36
+ description: string
37
+ version?: string // semver if found, omit otherwise
38
+ tags?: string[]
39
+ modelProvider: string // "openai" | "anthropic" | "groq" | "google" | "mistral" | "azure" | "bedrock"
40
+ modelId: string // exact model ID found in source
41
+ modelApiKeyEnv: string // env var name for the API key (e.g. "OPENAI_API_KEY")
42
+ modelTemperature?: number
43
+ modelMaxTokens?: number
44
+ fallbackProvider?: string
45
+ fallbackModelId?: string
46
+ fallbackApiKeyEnv?: string
47
+ promptFile?: string // path if a prompt file is loaded (e.g. "app/prompts/system.txt")
48
+ tools?: Array<{
49
+ name: string // raw tool/function name
50
+ description: string
51
+ module?: string // file path relative to scanned dir, e.g. "app/tools/expense.py" — NO $file: prefix
52
+ function?: string // callable name in that module, e.g. "create_expense"
53
+ readOnly?: boolean
54
+ destructive?: boolean
55
+ idempotent?: boolean
56
+ }>
57
+ shortTermBackend?: "redis" | "in-memory" | "sqlite"
58
+ shortTermConnectionEnv?: string // env var for redis/sqlite connection
59
+ shortTermMaxTurns?: number
60
+ shortTermTtlSeconds?: number
61
+ longTermBackend?: "postgres" | "sqlite" | "mongodb"
62
+ longTermConnectionStringEnv?: string
63
+ hasPromptInjection?: boolean
64
+ hasTopicFilter?: boolean
65
+ blockedTopics?: string[]
66
+ hasToxicityFilter?: boolean
67
+ toxicityThreshold?: number
68
+ hasPiiDetector?: boolean
69
+ hasRestApi?: boolean
70
+ apiStreaming?: boolean
71
+ apiAuthType?: "jwt" | "apikey" | "oauth2" | "none"
72
+ apiPort?: number
73
+ tracingBackend?: "langfuse" | "langsmith" | "agentops" | "otel" | "honeycomb" | "datadog"
74
+ metricsBackend?: "opentelemetry" | "prometheus" | "datadog"
75
+ loggingStructured?: boolean
76
+ envVars: string[] // ALL env vars detected in source (REQUIRED, can be empty [])
77
+ services?: Array<{
78
+ type: "postgres" | "redis" | "mysql" | "mongodb" | "elasticsearch"
79
+ connectionEnv: string // env var name for the connection string
80
+ }>
81
+ }
82
+ ```
32
83
 
33
- Work through the source files and detect:
34
-
35
- ### 1. Model
36
-
37
- | Pattern | Meaning |
38
- |---------|---------|
39
- | `import openai` / `from openai import` | provider: openai |
40
- | `import anthropic` / `from anthropic import` | provider: anthropic |
41
- | `from langchain_openai import` | provider: openai |
42
- | `from langchain_anthropic import` | provider: anthropic |
43
- | `from langchain_groq import` | provider: groq |
44
- | `OpenAI(model="…")` | model.name |
45
- | `ChatOpenAI(model_name="…")` | model.name |
46
- | `Anthropic(model="…")` | model.name |
47
- | `os.getenv("OPENAI_API_KEY")` | model.apiKey: $env:OPENAI_API_KEY |
48
- | `os.getenv("ANTHROPIC_API_KEY")` | model.apiKey: $env:ANTHROPIC_API_KEY |
49
- | `process.env.OPENAI_API_KEY` | model.apiKey: $env:OPENAI_API_KEY |
50
-
51
- ### 2. Tools
52
-
53
- | Pattern | Meaning |
54
- |---------|---------|
55
- | `@tool` decorator on a function | add to spec.tools[] |
56
- | `Tool(name="…", func=…)` | add to spec.tools[] |
57
- | `StructuredTool.from_function(name="…")` | add to spec.tools[] |
58
- | `tools = [ToolClass()]` or similar | add each detected tool |
59
-
60
- For each tool, extract:
61
- - `name`: the function or tool name (snake_case)
62
- - `description`: the docstring or `description=` argument
63
-
64
- ### 3. MCP Servers
65
-
66
- | Pattern | Meaning |
67
- |---------|---------|
68
- | `MCPClient(…)` | add to spec.mcp[] |
69
- | `mcp_servers = [{"url": "…"}]` | add each to spec.mcp[] |
70
-
71
- ### 4. Guardrails
72
-
73
- | Pattern | Meaning |
74
- |---------|---------|
75
- | Content filter / moderation call | spec.guardrails.content_filter.enabled: true |
76
- | Rate limiter class or decorator | spec.guardrails.rate_limit.enabled: true |
77
- | Output validator / schema check | spec.guardrails.output_validator.enabled: true |
78
- | PII scrubbing library import | spec.guardrails.pii_scrubber.enabled: true |
79
-
80
- ### 5. Evaluation Hooks
81
-
82
- | Pattern | Meaning |
83
- |---------|---------|
84
- | `import deepeval` | spec.eval.hooks: [deepeval] |
85
- | `import pytest` + eval functions | spec.eval.hooks: [pytest] |
86
- | Custom eval class | spec.eval.hooks: [custom] |
87
-
88
- ### 6. Required Environment Variables
89
-
90
- Scan for all:
91
- - `os.getenv("VAR_NAME")` / `os.environ["VAR_NAME"]`
92
- - `process.env.VAR_NAME`
93
- - `$env:VAR_NAME`
94
-
95
- Collect unique names and list them in `spec.requires.env[]` AND in `envVars` in your JSON response.
96
-
97
- ### 7. Memory Backend
98
-
99
- | Pattern | Meaning |
100
- |---------|---------|
101
- | Redis import + connection | spec.memory.backend: redis |
102
- | pgvector / psycopg import | spec.memory.backend: postgres |
103
- | Pinecone / Weaviate / Qdrant | spec.memory.backend: vector-<name> |
104
- | SQLite | spec.memory.backend: sqlite |
105
-
106
- ### 8. Services (Databases, APIs)
107
-
108
- | Pattern | Meaning |
109
- |---------|---------|
110
- | DB connection string env var | spec.requires.services[].name: database |
111
- | External API base URL pattern | spec.requires.services[].name: <api-name> |
112
-
113
- ### 9. Compliance Estimate
114
-
115
- Count detected fields and estimate a compliance score (0–100):
116
-
117
- | Detected | Score contribution |
118
- |----------|-------------------|
119
- | model.provider + apiKey | +20 |
120
- | tools (at least 1) | +10 |
121
- | guardrails.content_filter | +15 |
122
- | guardrails.rate_limit | +10 |
123
- | eval.hooks (at least 1) | +15 |
124
- | memory backend | +10 |
125
- | requires.env (at least 1) | +5 |
126
- | observability.metrics | +10 |
127
- | observability.tracing | +5 |
128
-
129
- Include the estimate as a comment at the top of the generated YAML:
130
- `# Compliance estimate: <score>/100`
84
+ **ONLY include fields you can confidently detect.** Omit unknown fields entirely.
131
85
 
132
86
  ---
133
87
 
134
- ## Output Schema
88
+ ## Detection Rules
89
+
90
+ ### Model detection
135
91
 
136
- Generate a `agent.yaml` with this structure (include only sections that have detected values):
92
+ | Pattern | `modelProvider` | `modelId` default |
93
+ |---------|-----------------|-------------------|
94
+ | `from langchain_openai import` / `import openai` | `openai` | `gpt-4o-mini` |
95
+ | `from langchain_anthropic import` / `import anthropic` | `anthropic` | `claude-sonnet-4-6` |
96
+ | `from langchain_groq import` / `ChatGroq` | `groq` | `llama-3.3-70b-versatile` |
97
+ | `from langchain_google_genai import` | `google` | `gemini-2.0-flash` |
98
+ | `from langchain_mistralai import` | `mistral` | `mistral-large-latest` |
99
+ | `AzureChatOpenAI` / `azure` in env vars | `azure` | `gpt-4o` |
100
+ | Literal `model="…"` or `model_name="…"` | — | use the literal value |
137
101
 
138
- ```yaml
139
- # Compliance estimate: <N>/100
140
- # Generated by agentspec scan — review and adjust before committing
102
+ Always prefer the detected model ID literal over the default.
141
103
 
142
- agentspec: v1
104
+ Use the env var name that the code passes to the API client constructor for `modelApiKeyEnv`.
143
105
 
144
- metadata:
145
- name: <detected-or-inferred-agent-name>
146
- description: <one-line description inferred from the code>
147
- version: 0.1.0
106
+ ### Tool detection
148
107
 
149
- spec:
150
- model:
151
- provider: <openai|anthropic|groq|...>
152
- name: <model-id>
153
- apiKey: $env:<API_KEY_VAR>
108
+ Detect from:
109
+ - `@tool` decorator on a function
110
+ - `StructuredTool.from_function(name="…")`
111
+ - `Tool(name="…", func=…)`
112
+ - `tools = [ToolClass()]` patterns
154
113
 
155
- tools:
156
- - name: <tool_name>
157
- description: <tool description>
114
+ For each tool, return:
115
+ - `name`: raw function/tool name (do NOT convert underscores)
116
+ - `description`: docstring or description string
117
+ - `module`: file path where the tool is defined, **relative to the scanned directory root** (e.g. `app/tools/expense_tools.py`). Do NOT include `$file:` prefix — the builder adds it.
118
+ - `function`: the callable Python/JS function name in that module (e.g. `create_expense`)
158
119
 
159
- # (only if MCP detected)
160
- mcp:
161
- - name: <mcp-server-name>
162
- url: $env:<MCP_URL_VAR>
120
+ Hints:
121
+ - A tool decorated with `@tool` and only uses `SELECT`/`GET` → `readOnly: true`
122
+ - A tool that deletes/updates data → `destructive: true`
163
123
 
164
- # (only if guardrails detected)
165
- guardrails:
166
- content_filter:
167
- enabled: true
168
- rate_limit:
169
- enabled: true
124
+ ### Memory backend detection
170
125
 
171
- # (only if memory detected)
172
- memory:
173
- backend: <redis|postgres|...>
174
- url: $env:<MEMORY_URL_VAR>
126
+ | Pattern | Field | `backend` value |
127
+ |---------|-------|-----------------|
128
+ | Redis / Upstash REST URL / `aioredis` / `redis-py` | `shortTermBackend` | `redis` |
129
+ | `MemorySaver` (LangGraph in-memory) | `shortTermBackend` | `in-memory` |
130
+ | SQLite checkpointer | `shortTermBackend` | `sqlite` |
131
+ | PostgreSQL / asyncpg / SQLAlchemy + postgres | `longTermBackend` | `postgres` |
132
+ | MongoDB / motor | `longTermBackend` | `mongodb` |
175
133
 
176
- # (only if eval detected)
177
- eval:
178
- hooks:
179
- - <deepeval|pytest|...>
134
+ For redis/sqlite, also detect `shortTermConnectionEnv` (the env var used to connect).
135
+ For postgres/mongodb, detect `longTermConnectionStringEnv`.
180
136
 
181
- requires:
182
- env:
183
- - <VAR_NAME>
184
- ```
137
+ ### Guardrail detection
138
+
139
+ - Prompt injection detection library / check → `hasPromptInjection: true`
140
+ - Topic blocking / content filter on input → `hasTopicFilter: true`, list `blockedTopics`
141
+ - PII scrubbing / Presidio / anonymisation → `hasPiiDetector: true`
142
+ - Toxicity filter / moderation on output → `hasToxicityFilter: true`, include `toxicityThreshold` if found
143
+ - Hallucination detection on output → (omit, not in interface)
144
+
145
+ ### API detection
146
+
147
+ - FastAPI / Flask / Express app with chat endpoint → `hasRestApi: true`
148
+ - SSE streaming / `StreamingResponse` → `apiStreaming: true`
149
+ - JWT / OAuth2 / API key middleware → `apiAuthType`
150
+ - Port from `uvicorn.run(..., port=N)` or `app.listen(N)` → `apiPort`
151
+
152
+ ### Env var detection
153
+
154
+ Scan for:
155
+ - Python: `os.getenv("VAR")`, `os.environ["VAR"]`, `os.environ.get("VAR")`
156
+ - TypeScript/JS: `process.env.VAR`, `process.env["VAR"]`
157
+ - Frameworks: `settings.VAR`, `config.VAR`
158
+
159
+ Collect ALL unique env var names → `envVars` array (REQUIRED, even if empty `[]`).
160
+
161
+ ### Services detection
162
+
163
+ | Pattern | `type` |
164
+ |---------|--------|
165
+ | PostgreSQL / asyncpg / SQLAlchemy | `postgres` |
166
+ | Redis / aioredis / Upstash | `redis` |
167
+ | MySQL | `mysql` |
168
+ | MongoDB / motor | `mongodb` |
169
+ | Elasticsearch | `elasticsearch` |
170
+
171
+ For each detected service, find the env var that holds the connection string → `connectionEnv`.
185
172
 
186
173
  ---
187
174
 
188
175
  ## Important Rules
189
176
 
190
- 1. If a value cannot be detected, omit the field (never guess API keys or URLs).
191
- 2. All secrets and API keys MUST use `$env:VAR_NAME` syntax — never hardcode values.
192
- 3. The agent name should be snake_case, inferred from the file or class name.
193
- 4. If no source files are provided, generate a minimal valid manifest with a comment
194
- explaining that no source was available.
195
- 5. Always include at least `agentspec: v1`, `metadata.name`, and `spec.model` in the output.
177
+ 1. **Return `detection.json` — NEVER `agent.yaml`** — YAML generation is TypeScript's job.
178
+ 2. **Return raw names** — do NOT convert underscores to hyphens; the builder slugifies.
179
+ 3. **`envVars` is required** — always include it, even as `[]` if no env vars found.
180
+ 4. **Omit unknown fields** — do not guess values you cannot find in the source.
181
+ 5. **Use exact enum values** — `modelProvider` must be one of the listed strings.
182
+ 6. **Do not invent services** — only list services that are actually imported/used.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentspec/adapter-claude",
3
- "version": "0.1.11",
3
+ "version": "0.2.1",
4
4
  "description": "AgentSpec agentic adapter — uses Claude API to generate complete agent code from agent.yaml",
5
5
  "author": "Sallah Kokaina <sallah.kokaina@gmail.com>",
6
6
  "license": "Apache-2.0",
@@ -43,7 +43,7 @@
43
43
  "prepublishOnly": "pnpm build"
44
44
  },
45
45
  "dependencies": {
46
- "@agentspec/sdk": "0.1.11",
46
+ "@agentspec/sdk": "0.2.1",
47
47
  "@anthropic-ai/sdk": "^0.36.0"
48
48
  },
49
49
  "devDependencies": {