LevelCode

SDK & Programmatic Access

Run LevelCode agents from your own code with @levelcode/sdk.

Installation

npm install @levelcode/sdk

Prerequisites

API key: levelcode.vercel.app/api-keys

Quick Start

Use the base agent (or any agent from the Agent Store) to run tasks:

import { LevelCodeClient } from '@levelcode/sdk'
const client = new LevelCodeClient({
apiKey: process.env.LEVELCODE_API_KEY,
cwd: process.cwd(),
})
const result = await client.run({
agent: 'levelcode/base@0.0.16',
prompt: 'Create a simple calculator class',
handleEvent: (event) => {
console.log('Event:', event.type)
},
})

Continuing Conversations

Pass the previous run state to keep context:

// First run
const run1 = await client.run({
agent: 'levelcode/base@0.0.16',
prompt: 'Create a calculator class',
})
// Continue the conversation
const run2 = await client.run({
agent: 'levelcode/base@0.0.16',
prompt: 'Add unit tests for the calculator',
previousRun: run1, // Maintains conversation context
})

Custom Agents

import type { AgentDefinition } from '@levelcode/sdk'
const myAgent: AgentDefinition = {
id: 'my-custom-agent',
model: 'anthropic/claude-sonnet-4.5',
displayName: 'My Custom Agent',
toolNames: ['read_files', 'write_file'],
instructionsPrompt: 'You are a helpful coding assistant.',
}
await client.run({
agent: 'my-custom-agent',
prompt: 'Help me refactor this code',
agentDefinitions: [myAgent],
})

Custom Tools

import { z } from 'zod/v4'
import { getCustomToolDefinition } from '@levelcode/sdk'
const fetchTool = getCustomToolDefinition({
toolName: 'fetch_api_data',
description: 'Fetch data from an API endpoint',
inputSchema: z.object({
url: z.url(),
method: z.enum(['GET', 'POST']).default('GET'),
}),
execute: async ({ url, method }) => {
const response = await fetch(url, { method })
const data = await response.text()
return [{ type: 'json', value: { data } }]
},
})
await client.run({
agent: 'my-custom-agent',
prompt: 'Fetch the latest data',
customToolDefinitions: [fetchTool],
})

Loading Local Agents

import { loadLocalAgents, LevelCodeClient } from '@levelcode/sdk'
const agents = await loadLocalAgents({ verbose: true })
const client = new LevelCodeClient({ apiKey: process.env.LEVELCODE_API_KEY })
await client.run({
agent: 'my-local-agent',
agentDefinitions: Object.values(agents),
prompt: 'Hello',
})

API Reference

LevelCodeClient

const client = new LevelCodeClient({
apiKey: string, // Required: Your LevelCode API key
cwd?: string, // Working directory for file operations
})

client.run(options)

ParameterTypeDescription
agentstringAgent ID from the store or custom agent ID
promptstringThe user prompt
paramsobjectAdditional parameters for the agent
handleEventfunctionCallback for streaming events
previousRunRunStatePrevious run state to continue conversation
projectFilesobjectProject files as { path: content }
knowledgeFilesobjectKnowledge files to inject into context
agentDefinitionsarrayCustom agent definitions
customToolDefinitionsarrayCustom tool definitions
maxAgentStepsnumberMaximum steps before stopping (default: ~20)

Event Types

  • agent_start / agent_finish - Agent lifecycle
  • tool_call / tool_result - Tool execution
  • text - Text responses
  • error - Error events

Return Value

RunState object:

  • sessionState - Internal state for continuing conversations
  • output - The agent's output (text, error, or structured data)

Use Cases

  • CI/CD pipelines: code review, test generation, refactoring
  • Batch processing
  • VS Code extensions, web apps
  • Automation scripts

Examples

Test Generation

import { LevelCodeClient } from '@levelcode/sdk'
const CODE_TO_TEST = `
function add(a: number, b: number): number {
return a + b;
}
function divide(a: number, b: number): number {
if (b === 0) throw new Error('Division by zero');
return a / b;
}
`
async function generateTests(code: string) {
const client = new LevelCodeClient({
apiKey: process.env.LEVELCODE_API_KEY,
})
const { output } = await client.run({
agent: 'levelcode/base@latest',
prompt: `Generate unit tests for these functions using Jest:\n\n${code}`,
})
return output
}

Code Review in CI

Use the reviewer agent for automated code review:

import { LevelCodeClient } from '@levelcode/sdk'
async function reviewPullRequest(diff: string) {
const client = new LevelCodeClient({
apiKey: process.env.LEVELCODE_API_KEY,
})
const { output } = await client.run({
agent: 'levelcode/reviewer@latest',
prompt: `Review this code change for bugs, security issues, and best practices:\n\n${diff}`,
})
return output
}

Batch Processing

import { LevelCodeClient } from '@levelcode/sdk'
import * as fs from 'fs'
import * as path from 'path'
async function addDocstringsToFiles(filePaths: string[]) {
const client = new LevelCodeClient({
apiKey: process.env.LEVELCODE_API_KEY,
})
const results = []
for (const filePath of filePaths) {
const code = fs.readFileSync(filePath, 'utf-8')
const { output } = await client.run({
agent: 'levelcode/base@latest',
prompt: `Add JSDoc comments to all functions in this file:\n\n${code}`,
})
results.push({ filePath, output })
}
return results
}
// Usage
const files = ['src/utils.ts', 'src/helpers.ts', 'src/api.ts']
await addDocstringsToFiles(files)

Code Refactoring

import { LevelCodeClient } from '@levelcode/sdk'
const LEGACY_CODE = `
function processData(data) {
let result = [];
for (let i = 0; i < data.length; i++) {
if (data[i].active === true) {
result.push({
id: data[i].id,
name: data[i].name.toUpperCase()
});
}
}
return result;
}
`
async function refactorCode(code: string) {
const client = new LevelCodeClient({
apiKey: process.env.LEVELCODE_API_KEY,
})
const { output } = await client.run({
agent: 'levelcode/base@latest',
prompt: `Refactor this code to use modern JavaScript (arrow functions,
destructuring, array methods like filter/map):\n\n${code}`,
})
return output
}

Providing Project Context

import { LevelCodeClient } from '@levelcode/sdk'
import * as fs from 'fs'
async function generateComponentWithContext() {
const client = new LevelCodeClient({
apiKey: process.env.LEVELCODE_API_KEY,
})
// Provide existing files as context
const projectFiles = {
'src/types.ts': fs.readFileSync('src/types.ts', 'utf-8'),
'src/components/Button.tsx': fs.readFileSync('src/components/Button.tsx', 'utf-8'),
}
const { output } = await client.run({
agent: 'levelcode/base@latest',
prompt: 'Create a new Card component that follows the same patterns as Button',
projectFiles,
})
return output
}

GitHub Actions Example

name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get diff
id: diff
run: echo "diff=$(git diff origin/main...HEAD)" >> $GITHUB_OUTPUT
- name: Run AI Review
run: |
npx ts-node scripts/ai-review.ts "${{ steps.diff.outputs.diff }}"
env:
LEVELCODE_API_KEY: ${{ secrets.LEVELCODE_API_KEY }}

Resources