@agentspec/codegen 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,151 @@
1
+ # @agentspec/codegen
2
+
3
+ Provider-agnostic code generation for AgentSpec. Reads an `agent.yaml` manifest and generates complete, runnable agent code for any supported framework.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @agentspec/codegen
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import { generateCode, resolveProvider } from '@agentspec/codegen'
15
+ import { loadManifest } from '@agentspec/sdk'
16
+
17
+ const { manifest } = loadManifest('./agent.yaml')
18
+ const provider = resolveProvider() // auto-detects Claude CLI > OpenAI-compatible > Anthropic API
19
+
20
+ const result = await generateCode(manifest, {
21
+ framework: 'langgraph',
22
+ provider,
23
+ })
24
+
25
+ console.log(Object.keys(result.files)) // ['agent.py', 'tools.py', ...]
26
+ ```
27
+
28
+ ## Providers
29
+
30
+ Three built-in providers, auto-detected in priority order:
31
+
32
+ | Provider | Class | Requires |
33
+ |----------|-------|----------|
34
+ | Claude subscription | `ClaudeSubscriptionProvider` | `claude` CLI authenticated |
35
+ | OpenAI-compatible | `OpenAICompatibleProvider` | `AGENTSPEC_LLM_API_KEY` + `AGENTSPEC_LLM_MODEL` |
36
+ | Anthropic API | `AnthropicApiProvider` | `ANTHROPIC_API_KEY` env var |
37
+
38
+ The OpenAI-compatible provider works with any endpoint that speaks the OpenAI wire format: OpenRouter, Groq, Together, Ollama, Nvidia NIM, OpenAI.com, and others. Set `AGENTSPEC_LLM_BASE_URL` to point at a non-OpenAI endpoint.
39
+
40
+ ### Auto-detection
41
+
42
+ ```typescript
43
+ import { resolveProvider } from '@agentspec/codegen'
44
+
45
+ const provider = resolveProvider() // auto-detect
46
+ const provider = resolveProvider('openai-compatible') // force specific provider
47
+ ```
48
+
49
+ Override via env var: `AGENTSPEC_CODEGEN_PROVIDER=openai-compatible`. Valid values: `auto`, `claude-sub`, `claude-subscription`, `openai-compatible`, `anthropic-api`.
50
+
51
+ ### Direct instantiation
52
+
53
+ ```typescript
54
+ import { AnthropicApiProvider, OpenAICompatibleProvider } from '@agentspec/codegen'
55
+
56
+ // Anthropic
57
+ const anthropic = new AnthropicApiProvider('sk-ant-...', 'https://proxy.example.com')
58
+
59
+ // OpenAI-compatible (e.g. OpenRouter)
60
+ const openrouter = new OpenAICompatibleProvider(
61
+ 'sk-or-v1-...',
62
+ 'qwen/qwen3-235b-a22b',
63
+ 'https://openrouter.ai/api/v1',
64
+ )
65
+ ```
66
+
67
+ ## Frameworks
68
+
69
+ List available frameworks at runtime:
70
+
71
+ ```typescript
72
+ import { listFrameworks } from '@agentspec/codegen'
73
+ console.log(listFrameworks()) // ['langgraph', 'crewai', 'mastra', ...]
74
+ ```
75
+
76
+ Add a new framework by creating a skill file in `src/skills/<name>.md` — no TypeScript code needed.
77
+
78
+ ## Streaming
79
+
80
+ Stream generation progress via `onChunk`:
81
+
82
+ ```typescript
83
+ const result = await generateCode(manifest, {
84
+ framework: 'langgraph',
85
+ provider,
86
+ onChunk: (chunk) => {
87
+ if (chunk.type === 'delta') {
88
+ process.stdout.write(chunk.text)
89
+ }
90
+ },
91
+ })
92
+ ```
93
+
94
+ Chunk types:
95
+ - `delta` — text fragment with `text`, `accumulated`, and `elapsedSec`
96
+ - `heartbeat` — keep-alive with `elapsedSec`
97
+ - `done` — final result with `result` string and `elapsedSec`
98
+
99
+ ## Utilities
100
+
101
+ ### `collect(stream)`
102
+
103
+ Drain a provider stream to a single string:
104
+
105
+ ```typescript
106
+ import { collect, resolveProvider } from '@agentspec/codegen'
107
+
108
+ const provider = resolveProvider()
109
+ const text = await collect(provider.stream(systemPrompt, userPrompt, {}))
110
+ ```
111
+
112
+ ### `repairYaml(provider, yaml, errors)`
113
+
114
+ Ask the LLM to fix schema validation errors in an `agent.yaml`:
115
+
116
+ ```typescript
117
+ import { repairYaml, resolveProvider } from '@agentspec/codegen'
118
+
119
+ const fixed = await repairYaml(resolveProvider(), badYaml, validationErrors)
120
+ ```
121
+
122
+ ### `probeProviders()`
123
+
124
+ Diagnostic probe for all codegen providers (used by `agentspec provider-status`):
125
+
126
+ ```typescript
127
+ import { probeProviders } from '@agentspec/codegen'
128
+
129
+ const report = await probeProviders()
130
+ console.log(report.results) // ProviderProbeResult[]: one per probe
131
+ console.log(report.env.resolvedProvider) // 'claude-subscription' | 'openai-compatible' | 'anthropic-api' | null
132
+ ```
133
+
134
+ ## Error Handling
135
+
136
+ All errors are typed as `CodegenError` with a `code` property:
137
+
138
+ ```typescript
139
+ import { CodegenError } from '@agentspec/codegen'
140
+
141
+ try {
142
+ await generateCode(manifest, { framework: 'langgraph', provider })
143
+ } catch (err) {
144
+ if (err instanceof CodegenError) {
145
+ console.error(err.code, err.message)
146
+ // err.code: 'auth_failed' | 'generation_failed' | 'parse_failed' | ...
147
+ }
148
+ }
149
+ ```
150
+
151
+ Error codes: `auth_failed`, `quota_exceeded`, `rate_limited`, `model_not_found`, `generation_failed`, `parse_failed`, `provider_unavailable`, `response_invalid`
@@ -0,0 +1,129 @@
1
+ import { AgentSpecManifest, GeneratedAgent } from '@agentspec/sdk';
2
+
3
+ type CodegenErrorCode = 'auth_failed' | 'quota_exceeded' | 'rate_limited' | 'model_not_found' | 'generation_failed' | 'parse_failed' | 'provider_unavailable' | 'response_invalid';
4
+ declare class CodegenError extends Error {
5
+ readonly code: CodegenErrorCode;
6
+ readonly cause?: unknown | undefined;
7
+ constructor(code: CodegenErrorCode, message: string, cause?: unknown | undefined);
8
+ }
9
+ type CodegenChunk = {
10
+ type: 'delta';
11
+ text: string;
12
+ accumulated: string;
13
+ elapsedSec: number;
14
+ } | {
15
+ type: 'heartbeat';
16
+ elapsedSec: number;
17
+ } | {
18
+ type: 'done';
19
+ result: string;
20
+ elapsedSec: number;
21
+ };
22
+ interface CodegenCallOptions {
23
+ model?: string;
24
+ }
25
+ interface CodegenProvider {
26
+ readonly name: string;
27
+ stream(system: string, user: string, opts: CodegenCallOptions): AsyncIterable<CodegenChunk>;
28
+ }
29
+ type ProviderProbeResult = {
30
+ status: 'ready';
31
+ provider: string;
32
+ details: Record<string, unknown>;
33
+ } | {
34
+ status: 'misconfigured';
35
+ provider: string;
36
+ reason: string;
37
+ details: Record<string, unknown>;
38
+ } | {
39
+ status: 'unreachable';
40
+ provider: string;
41
+ reason: string;
42
+ details: Record<string, unknown>;
43
+ } | {
44
+ status: 'not-configured';
45
+ provider: string;
46
+ };
47
+ interface ProviderProbe {
48
+ readonly name: string;
49
+ probe(env: NodeJS.ProcessEnv): Promise<ProviderProbeResult>;
50
+ }
51
+
52
+ declare function resolveProvider(override?: string): CodegenProvider;
53
+
54
+ /** Drain a CodegenProvider stream and return the final result string. */
55
+ declare function collect(stream: AsyncIterable<CodegenChunk>): Promise<string>;
56
+
57
+ declare function listFrameworks(): string[];
58
+
59
+ declare class AnthropicApiProvider implements CodegenProvider {
60
+ private readonly apiKey;
61
+ private readonly baseURL?;
62
+ readonly name = "anthropic-api";
63
+ constructor(apiKey: string, baseURL?: string | undefined);
64
+ stream(system: string, user: string, opts: CodegenCallOptions): AsyncIterable<CodegenChunk>;
65
+ }
66
+
67
+ declare class ClaudeSubscriptionProvider implements CodegenProvider {
68
+ readonly name = "claude-subscription";
69
+ stream(system: string, user: string, opts: CodegenCallOptions): AsyncIterable<CodegenChunk>;
70
+ }
71
+
72
+ declare class OpenAICompatibleProvider implements CodegenProvider {
73
+ private readonly apiKey;
74
+ private readonly model;
75
+ private readonly baseURL;
76
+ readonly name = "openai-compatible";
77
+ constructor(apiKey: string, model: string, baseURL?: string);
78
+ stream(system: string, user: string, opts: CodegenCallOptions): AsyncIterable<CodegenChunk>;
79
+ }
80
+
81
+ /**
82
+ * Thin probe orchestrator.
83
+ *
84
+ * Delegates to each provider adapter's ProviderProbe export and collects the
85
+ * results into a single report. Never throws; all failures land in either a
86
+ * ProviderProbeResult variant or in env.resolveError.
87
+ *
88
+ * Used by `agentspec provider-status` to render diagnostic output.
89
+ */
90
+
91
+ interface ProviderEnvProbe {
92
+ providerOverride: string | null;
93
+ resolvedProvider: string | null;
94
+ resolveError: string | null;
95
+ }
96
+ interface ProviderProbeReport {
97
+ results: ProviderProbeResult[];
98
+ env: ProviderEnvProbe;
99
+ }
100
+
101
+ declare function probeProviders(): Promise<ProviderProbeReport>;
102
+
103
+ /**
104
+ * YAML repair via LLM — asks the provider to fix schema validation errors.
105
+ */
106
+
107
+ /**
108
+ * Ask the LLM to fix an agent.yaml string that failed schema validation.
109
+ * Returns the repaired YAML string, ready to be re-validated by the caller.
110
+ */
111
+ declare function repairYaml(provider: CodegenProvider, yamlStr: string, validationErrors: string): Promise<string>;
112
+
113
+ interface CodegenOptions {
114
+ framework: string;
115
+ model?: string;
116
+ manifestDir?: string;
117
+ contextFiles?: string[];
118
+ provider?: CodegenProvider;
119
+ onChunk?: (chunk: CodegenChunk) => void;
120
+ }
121
+ /**
122
+ * Generate agent code from a manifest.
123
+ *
124
+ * Selects a provider automatically (Claude subscription → OpenAI-compatible →
125
+ * Anthropic API) or uses the one passed in `options.provider`.
126
+ */
127
+ declare function generateCode(manifest: AgentSpecManifest, options: CodegenOptions): Promise<GeneratedAgent>;
128
+
129
+ export { AnthropicApiProvider, ClaudeSubscriptionProvider, type CodegenCallOptions, type CodegenChunk, CodegenError, type CodegenErrorCode, type CodegenOptions, type CodegenProvider, OpenAICompatibleProvider, type ProviderEnvProbe, type ProviderProbe, type ProviderProbeReport, type ProviderProbeResult, collect, generateCode, listFrameworks, probeProviders, repairYaml, resolveProvider };