@agentspec/adapter-claude 0.2.3 → 0.5.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.
@@ -1,372 +0,0 @@
1
- # AgentSpec → Mastra Generation Skill
2
-
3
- You are generating production-ready TypeScript Mastra agent code from an AgentSpec manifest JSON.
4
-
5
- ## Output Format
6
-
7
- Return a single JSON object (wrapped in ```json ... ```) with this exact shape:
8
-
9
- ```json
10
- {
11
- "files": {
12
- "src/agent.ts": "...",
13
- "src/tools.ts": "...",
14
- "mastra.config.ts": "...",
15
- "package.json": "...",
16
- ".env.example": "...",
17
- "README.md": "..."
18
- },
19
- "installCommands": [
20
- "npm install",
21
- "cp .env.example .env"
22
- ],
23
- "envVars": ["OPENAI_API_KEY", "LANGFUSE_PUBLIC_KEY"]
24
- }
25
- ```
26
-
27
- **File generation rules:**
28
- | File | When to generate |
29
- |---|---|
30
- | `src/agent.ts` | Always |
31
- | `src/tools.ts` | When `spec.tools` is non-empty |
32
- | `mastra.config.ts` | Always |
33
- | `package.json` | Always |
34
- | `.env.example` | Always |
35
- | `README.md` | Always |
36
-
37
- **Invariants:**
38
- - Map **every** manifest field. Do not skip sections.
39
- - All string values embedded in TypeScript code must be properly escaped.
40
- - Never embed literal API keys — always use `process.env.VAR_NAME`.
41
- - Validate required env vars at startup with a `validateEnv()` function.
42
-
43
- ---
44
-
45
- ## Reference Syntax Resolution
46
-
47
- Resolve `$ref` values before generating TypeScript:
48
-
49
- | Manifest reference | TypeScript |
50
- |---|---|
51
- | `$env:VAR_NAME` | `process.env.VAR_NAME` |
52
- | `$env:VAR_NAME` (required) | `process.env.VAR_NAME` — list in `REQUIRED_ENV_VARS` |
53
- | `$secret:secret-name` | `process.env.AGENTSPEC_SECRET_SECRET_NAME` — transform: uppercase, `-` → `_`, prefix `AGENTSPEC_SECRET_` |
54
- | `$file:path/to/file` | `fs.readFileSync(path.join(__dirname, 'path/to/file'), 'utf-8')` |
55
- | `$func:now_iso` | `new Date().toISOString()` |
56
-
57
- Examples:
58
- - `$secret:langfuse-secret-key` → `process.env.AGENTSPEC_SECRET_LANGFUSE_SECRET_KEY`
59
- - `$env:OPENAI_API_KEY` → `process.env.OPENAI_API_KEY`
60
-
61
- ---
62
-
63
- ## Mapping Rules
64
-
65
- ### spec.model — AI SDK provider
66
-
67
- | Manifest field | TypeScript |
68
- |---|---|
69
- | `provider: openai` | `import { openai } from '@ai-sdk/openai'` |
70
- | `provider: anthropic` | `import { anthropic } from '@ai-sdk/anthropic'` |
71
- | `provider: google` | `import { google } from '@ai-sdk/google'` |
72
- | `provider: groq` | `import { createGroq } from '@ai-sdk/groq'` |
73
- | `provider: mistral` | `import { mistral } from '@ai-sdk/mistral'` |
74
- | `id` | First argument to provider function: `openai('gpt-4o')` |
75
- | `parameters.temperature` | `temperature: N` in `generate` / agent options |
76
- | `parameters.maxTokens` | `maxTokens: N` in generate options |
77
- | `apiKey: $env:VAR` | `apiKey: process.env.VAR` in provider factory options |
78
-
79
- ### spec.prompts
80
-
81
- ```typescript
82
- import * as fs from 'fs'
83
- import * as path from 'path'
84
-
85
- function loadSystemPrompt(): string {
86
- try {
87
- const template = fs.readFileSync(
88
- path.join(__dirname, '../prompts/system.md'),
89
- 'utf-8'
90
- )
91
- const variables: Record<string, string> = {
92
- unit_system: process.env.UNIT_SYSTEM ?? '',
93
- current_date: new Date().toISOString(),
94
- }
95
- return Object.entries(variables).reduce(
96
- (t, [k, v]) => t.replaceAll(`{{ ${k} }}`, v),
97
- template
98
- )
99
- } catch {
100
- return "I'm experiencing difficulties. Please try again."
101
- }
102
- }
103
- ```
104
-
105
- For `hotReload: true` — call `loadSystemPrompt()` on every agent invocation (no module-level caching).
106
-
107
- ### spec.tools — src/tools.ts
108
-
109
- ```typescript
110
- import { createTool } from '@mastra/core'
111
- import { z } from 'zod'
112
-
113
- export const logWorkout = createTool({
114
- id: 'log_workout',
115
- description: 'Log a completed training session with exercises, sets, reps, and duration',
116
- inputSchema: z.object({
117
- input: z.string().describe('Tool input'),
118
- }),
119
- execute: async ({ context }) => {
120
- throw new Error('Implement logWorkout')
121
- },
122
- })
123
-
124
- export const getWorkoutHistory = createTool({
125
- id: 'get_workout_history',
126
- description: 'Retrieve past training sessions with optional filters',
127
- inputSchema: z.object({
128
- input: z.string().describe('Tool input'),
129
- }),
130
- execute: async ({ context }) => {
131
- throw new Error('Implement getWorkoutHistory')
132
- },
133
- })
134
- ```
135
-
136
- Rules:
137
- - Tool `id`: `tool.function` if set, otherwise `snake_case(tool.name)`
138
- - Export name: `camelCase(tool.name)`
139
- - `description`: `tool.description`
140
- - `execute` body: `throw new Error('Implement {camelCaseName}')`
141
- - Input schema: `z.object({ input: z.string() })` as a sensible default
142
-
143
- **src/agent.ts imports tools:**
144
- ```typescript
145
- import { logWorkout, getWorkoutHistory } from './tools.js'
146
- const tools = { logWorkout, getWorkoutHistory }
147
- ```
148
-
149
- ### spec.memory
150
-
151
- ```typescript
152
- import { Memory } from '@mastra/core/memory'
153
- import { LibSQLStore } from '@mastra/libsql'
154
-
155
- const memory = new Memory({
156
- storage: new LibSQLStore({
157
- url: process.env.LIBSQL_URL ?? 'file:./agent.db',
158
- }),
159
- })
160
- ```
161
-
162
- Pass to agent: `new Agent({ ..., memory })`.
163
-
164
- For `spec.memory.shortTerm.backend = "redis"`:
165
- ```typescript
166
- // Redis-backed memory: configure REDIS_URL for Mastra's KV store
167
- // See Mastra docs for RedisStore integration
168
- ```
169
-
170
- ### spec.observability
171
-
172
- For Langfuse:
173
- ```typescript
174
- // ── Tracing: Langfuse ─────────────────────────────────────────────────────────
175
- // Mastra supports OpenTelemetry natively in mastra.config.ts
176
- // Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY for automatic tracing
177
- ```
178
-
179
- In `mastra.config.ts`:
180
- ```typescript
181
- import { Mastra } from '@mastra/core'
182
-
183
- export const mastra = new Mastra({
184
- agents: { myAgent },
185
- telemetry: {
186
- serviceName: '{service_name}', // from spec.observability.serviceName
187
- enabled: true,
188
- },
189
- })
190
- ```
191
-
192
- ### spec.requires
193
-
194
- ```typescript
195
- const REQUIRED_ENV_VARS = ['OPENAI_API_KEY'] // from spec.requires.envVars[]
196
-
197
- function validateEnv(): void {
198
- const missing = REQUIRED_ENV_VARS.filter(v => !process.env[v])
199
- if (missing.length > 0) {
200
- throw new Error(
201
- `Missing required environment variables: ${missing.join(', ')}\n` +
202
- 'Copy .env.example to .env and fill in the values.'
203
- )
204
- }
205
- }
206
-
207
- validateEnv()
208
- ```
209
-
210
- ---
211
-
212
- ## Complete src/agent.ts Structure
213
-
214
- Generate sections in this exact order:
215
-
216
- 1. **Imports**:
217
- - `import { Agent } from '@mastra/core'`
218
- - `import { Memory } from '@mastra/core/memory'` (if `spec.memory` is set)
219
- - `import { LibSQLStore } from '@mastra/libsql'` (if memory with libsql)
220
- - Provider import from `@ai-sdk/*`
221
- - Tool imports: `import { toolA, toolB } from './tools.js'` (if tools exist)
222
- - `import * as fs from 'fs'` and `import * as path from 'path'` (if `$file:` refs)
223
- 2. **Env var validation** (`validateEnv()` definition and call)
224
- 3. **System prompt loading** (with variable interpolation if variables defined)
225
- 4. **LLM model setup**: `const model = openai('gpt-4o')`
226
- 5. **Memory setup** (if `spec.memory` is set)
227
- 6. **Agent definition**:
228
- ```typescript
229
- export const myAgent = new Agent({
230
- name: '{agent_name}',
231
- instructions: loadSystemPrompt(),
232
- model,
233
- tools: { toolA, toolB },
234
- memory, // if spec.memory is set
235
- })
236
- ```
237
- 7. **`runAgent()` helper**:
238
- ```typescript
239
- export async function runAgent(userInput: string, threadId = 'default'): Promise<string> {
240
- const result = await myAgent.generate(userInput, {
241
- threadId,
242
- resourceId: 'user',
243
- })
244
- return result.text
245
- }
246
- ```
247
- 8. **`main()` block**:
248
- ```typescript
249
- if (import.meta.url === new URL(process.argv[1], 'file://').href) {
250
- const input = process.argv[2] ?? 'Hello, what can you help me with?'
251
- runAgent(input).then(console.log).catch(console.error)
252
- }
253
- ```
254
-
255
- ---
256
-
257
- ## mastra.config.ts Structure
258
-
259
- ```typescript
260
- import { Mastra } from '@mastra/core'
261
- import { myAgent } from './src/agent.js'
262
-
263
- export const mastra = new Mastra({
264
- agents: { myAgent },
265
- telemetry: {
266
- serviceName: '{service_name}',
267
- enabled: true,
268
- },
269
- })
270
- ```
271
-
272
- ---
273
-
274
- ## package.json Template
275
-
276
- ```json
277
- {
278
- "name": "{agent-name-kebab}",
279
- "version": "{version}",
280
- "description": "{description}",
281
- "type": "module",
282
- "scripts": {
283
- "start": "tsx src/agent.ts",
284
- "dev": "tsx --watch src/agent.ts",
285
- "build": "tsc",
286
- "typecheck": "tsc --noEmit"
287
- },
288
- "dependencies": {
289
- "@mastra/core": "^0.10.0",
290
- "@mastra/libsql": "^0.10.0",
291
- "@ai-sdk/openai": "^1.0.0",
292
- "zod": "^3.23.0"
293
- },
294
- "devDependencies": {
295
- "typescript": "^5.7.0",
296
- "tsx": "^4.19.0",
297
- "@types/node": "^20.17.0"
298
- }
299
- }
300
- ```
301
-
302
- Provider package map:
303
- | provider | package |
304
- |---|---|
305
- | `openai` | `@ai-sdk/openai` |
306
- | `anthropic` | `@ai-sdk/anthropic` |
307
- | `google` | `@ai-sdk/google` |
308
- | `groq` | `@ai-sdk/groq` |
309
- | `mistral` | `@ai-sdk/mistral` |
310
-
311
- Add `langfuse` if `spec.observability.tracing.backend === 'langfuse'`.
312
-
313
- ---
314
-
315
- ## .env.example Rules
316
-
317
- - One line per env var referenced in the manifest
318
- - Strip `$env:` prefix for the variable name
319
- - For `$secret:name`, the env var is `AGENTSPEC_SECRET_NAME` (uppercase, `-`→`_`)
320
- - Add a comment describing what each var is for
321
- - Group by concern: model, memory, observability, agent config
322
-
323
- ---
324
-
325
- ## README.md Template
326
-
327
- ```markdown
328
- # {agent_name}
329
-
330
- {description}
331
-
332
- **Generated by [AgentSpec](https://agentspec.io) v{version}**
333
-
334
- ## Stack
335
-
336
- | Component | Value |
337
- |-----------|-------|
338
- | Framework | Mastra |
339
- | Model | {provider}/{model_id} |
340
- | Memory | {memory_backend} |
341
- | Tracing | {tracing_backend} |
342
- | Tools | {tools_count} |
343
-
344
- ## Quick Start
345
-
346
- ```bash
347
- npm install
348
- cp .env.example .env # fill in your API keys
349
- npm start "Hello, what can you help me with?"
350
- ```
351
-
352
- ## Tools
353
-
354
- {tool_list}
355
-
356
- ## Environment Variables
357
-
358
- {env_var_list}
359
- ```
360
-
361
- ---
362
-
363
- ## Quality Checklist
364
-
365
- | Check | Verify |
366
- |---|---|
367
- | `$secret:` resolution | `$secret:langfuse-secret-key` → `AGENTSPEC_SECRET_LANGFUSE_SECRET_KEY` |
368
- | No literal keys | Search generated code for `sk-`, `pk-`, raw key strings |
369
- | `validateEnv()` called | At module top-level, before any connections |
370
- | `src/tools.ts` generated | When `spec.tools` is non-empty |
371
- | package.json complete | All `@ai-sdk/*` and `@mastra/*` packages match imports |
372
- | ESM imports | All local imports end with `.js` extension |
@@ -1,182 +0,0 @@
1
- # AgentSpec Scan Skill
2
-
3
- You are analysing source code to detect what kind of AI agent it implements.
4
-
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.
7
-
8
- ---
9
-
10
- ## Output Format
11
-
12
- Respond with **exactly one JSON object** in this shape:
13
-
14
- ```json
15
- {
16
- "files": {
17
- "detection.json": "<ScanDetection object as a JSON string>"
18
- },
19
- "installCommands": [],
20
- "envVars": ["OPENAI_API_KEY", "..."]
21
- }
22
- ```
23
-
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.
26
-
27
- ---
28
-
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
- ```
83
-
84
- **ONLY include fields you can confidently detect.** Omit unknown fields entirely.
85
-
86
- ---
87
-
88
- ## Detection Rules
89
-
90
- ### Model detection
91
-
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 |
101
-
102
- Always prefer the detected model ID literal over the default.
103
-
104
- Use the env var name that the code passes to the API client constructor for `modelApiKeyEnv`.
105
-
106
- ### Tool detection
107
-
108
- Detect from:
109
- - `@tool` decorator on a function
110
- - `StructuredTool.from_function(name="…")`
111
- - `Tool(name="…", func=…)`
112
- - `tools = [ToolClass()]` patterns
113
-
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`)
119
-
120
- Hints:
121
- - A tool decorated with `@tool` and only uses `SELECT`/`GET` → `readOnly: true`
122
- - A tool that deletes/updates data → `destructive: true`
123
-
124
- ### Memory backend detection
125
-
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` |
133
-
134
- For redis/sqlite, also detect `shortTermConnectionEnv` (the env var used to connect).
135
- For postgres/mongodb, detect `longTermConnectionStringEnv`.
136
-
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`.
172
-
173
- ---
174
-
175
- ## Important Rules
176
-
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.