This document provides a complete API reference for KODE SDK v2.7.0.
The core class for creating and managing AI agents.
Creates a new Agent instance.
static async create(config: AgentConfig, deps: AgentDependencies): Promise<Agent>Parameters:
config: AgentConfig- Agent configurationdeps: AgentDependencies- Required dependencies
Example:
const agent = await Agent.create({
templateId: 'assistant',
modelConfig: {
provider: 'anthropic',
apiKey: process.env.ANTHROPIC_API_KEY!,
},
sandbox: { kind: 'local', workDir: './workspace' },
}, deps);Resumes an existing Agent from storage.
static async resume(
agentId: string,
config: AgentConfig,
deps: AgentDependencies,
opts?: { autoRun?: boolean; strategy?: ResumeStrategy }
): Promise<Agent>Parameters:
agentId: string- Agent ID to resumeconfig: AgentConfig- Agent configurationdeps: AgentDependencies- Required dependenciesopts.autoRun?: boolean- Continue processing after resume (default: false)opts.strategy?: ResumeStrategy-'crash'(auto-seal) or'manual'
Resumes an Agent using metadata from store (recommended).
static async resumeFromStore(
agentId: string,
deps: AgentDependencies,
opts?: { overrides?: Partial<AgentConfig>; autoRun?: boolean; strategy?: ResumeStrategy }
): Promise<Agent>Sends a message and returns the text response.
async send(message: string | ContentBlock[], options?: SendOptions): Promise<string>Sends a message and returns structured result with status.
async chat(input: string | ContentBlock[], opts?: StreamOptions): Promise<CompleteResult>Returns:
interface CompleteResult {
status: 'ok' | 'paused';
text?: string;
last?: Bookmark;
permissionIds?: string[];
}Alias for chat().
Responds to a permission request.
async decide(permissionId: string, decision: 'allow' | 'deny', note?: string): Promise<void>Interrupts the current processing.
async interrupt(opts?: { note?: string }): Promise<void>Creates a snapshot at the current Safe-Fork-Point.
async snapshot(label?: string): Promise<SnapshotId>Creates a forked Agent from a snapshot.
async fork(sel?: SnapshotId | { at?: string }): Promise<Agent>Returns current Agent status.
async status(): Promise<AgentStatus>Returns:
interface AgentStatus {
agentId: string;
state: AgentRuntimeState; // 'READY' | 'WORKING' | 'PAUSED'
stepCount: number;
lastSfpIndex: number;
lastBookmark?: Bookmark;
cursor: number;
breakpoint: BreakpointState;
}Returns Agent metadata.
async info(): Promise<AgentInfo>Sets the entire Todo list.
async setTodos(todos: TodoInput[]): Promise<void>Updates a single Todo item.
async updateTodo(todo: TodoInput): Promise<void>Deletes a Todo item.
async deleteTodo(id: string): Promise<void>Subscribes to Control and Monitor events. Returns an unsubscribe function.
on<T extends ControlEvent['type'] | MonitorEvent['type']>(
event: T,
handler: (evt: any) => void
): () => voidSupported events:
- Control:
'permission_required','permission_decided' - Monitor:
'state_changed','step_complete','error','token_usage','tool_executed','agent_resumed','todo_changed','file_changed'
Example:
// Monitor events
const unsubscribe = agent.on('tool_executed', (event) => {
console.log(`Tool ${event.call.name} executed`);
});
agent.on('error', (event) => {
console.error('Error:', event.error);
});
// Control events
agent.on('permission_required', (event) => {
console.log(`Permission needed for: ${event.call.name}`);
});
// Unsubscribe when done
unsubscribe();Note: For Progress events (
text_chunk,tool:start,done, etc.), useagent.subscribe(['progress'])instead.
Configuration for creating an Agent.
interface AgentConfig {
agentId?: string; // Auto-generated if not provided
templateId: string; // Required: template ID
templateVersion?: string; // Optional: template version
model?: ModelProvider; // Direct model provider
modelConfig?: ModelConfig; // Or model configuration
sandbox?: Sandbox | SandboxConfig; // Sandbox instance or config
tools?: string[]; // Tool names to enable
exposeThinking?: boolean; // Emit thinking events
retainThinking?: boolean; // Keep thinking in message history
overrides?: {
permission?: PermissionConfig;
todo?: TodoConfig;
subagents?: SubAgentConfig;
hooks?: Hooks;
};
context?: ContextManagerOptions;
metadata?: Record<string, any>;
}Required dependencies for Agent creation.
interface AgentDependencies {
store: Store; // Storage backend
templateRegistry: AgentTemplateRegistry;
sandboxFactory: SandboxFactory;
toolRegistry: ToolRegistry;
modelFactory?: ModelFactory; // Optional factory for model creation
skillsManager?: SkillsManager; // Optional skills manager
}Interface for Agent data persistence.
interface Store {
// Messages
saveMessages(agentId: string, messages: Message[]): Promise<void>;
loadMessages(agentId: string): Promise<Message[]>;
// Tool Records
saveToolCallRecords(agentId: string, records: ToolCallRecord[]): Promise<void>;
loadToolCallRecords(agentId: string): Promise<ToolCallRecord[]>;
// Todos
saveTodos(agentId: string, snapshot: TodoSnapshot): Promise<void>;
loadTodos(agentId: string): Promise<TodoSnapshot | undefined>;
// Events
appendEvent(agentId: string, timeline: Timeline): Promise<void>;
readEvents(agentId: string, opts?: { since?: Bookmark; channel?: AgentChannel }): AsyncIterable<Timeline>;
// Snapshots
saveSnapshot(agentId: string, snapshot: Snapshot): Promise<void>;
loadSnapshot(agentId: string, snapshotId: string): Promise<Snapshot | undefined>;
listSnapshots(agentId: string): Promise<Snapshot[]>;
// Metadata
saveInfo(agentId: string, info: AgentInfo): Promise<void>;
loadInfo(agentId: string): Promise<AgentInfo | undefined>;
// Lifecycle
exists(agentId: string): Promise<boolean>;
delete(agentId: string): Promise<void>;
list(prefix?: string): Promise<string[]>;
}| Class | Description |
|---|---|
JSONStore |
File-based storage (default) |
SqliteStore |
SQLite database storage |
PostgresStore |
PostgreSQL database storage |
import { createExtendedStore } from '@shareai-lab/kode-sdk';
// SQLite
const store = await createExtendedStore({
type: 'sqlite',
dbPath: './data/agents.db',
fileStoreBaseDir: './data/store',
});
// PostgreSQL
const store = await createExtendedStore({
type: 'postgres',
connection: {
host: 'localhost',
port: 5432,
database: 'kode_agents',
user: 'kode',
password: 'password',
},
fileStoreBaseDir: './data/store',
});Extended Store interface with query capabilities.
interface QueryableStore extends Store {
querySessions(filters: SessionFilters): Promise<SessionInfo[]>;
queryMessages(filters: MessageFilters): Promise<Message[]>;
queryToolCalls(filters: ToolCallFilters): Promise<ToolCallRecord[]>;
aggregateStats(agentId: string): Promise<AgentStats>;
}interface SessionFilters {
agentId?: string;
templateId?: string;
userId?: string;
startDate?: number; // Unix timestamp (ms)
endDate?: number;
limit?: number;
offset?: number;
sortBy?: 'created_at' | 'updated_at' | 'message_count';
sortOrder?: 'asc' | 'desc';
}interface MessageFilters {
agentId?: string;
role?: 'user' | 'assistant' | 'system';
startDate?: number;
endDate?: number;
limit?: number;
offset?: number;
}interface ToolCallFilters {
agentId?: string;
toolName?: string;
state?: ToolCallState;
startDate?: number;
endDate?: number;
limit?: number;
offset?: number;
}Store with advanced features.
interface ExtendedStore extends QueryableStore {
healthCheck(): Promise<StoreHealthStatus>;
checkConsistency(agentId: string): Promise<ConsistencyCheckResult>;
getMetrics(): Promise<StoreMetrics>;
acquireAgentLock(agentId: string, timeoutMs?: number): Promise<LockReleaseFn>;
batchFork(agentId: string, count: number): Promise<string[]>;
close(): Promise<void>;
}Registry for tool factories.
class ToolRegistry {
register(id: string, factory: ToolFactory): void;
has(id: string): boolean;
create(id: string, config?: Record<string, any>): ToolInstance;
list(): string[];
}interface ToolInstance {
name: string;
description: string;
input_schema: any; // JSON Schema
hooks?: Hooks;
prompt?: string | ((ctx: ToolContext) => string | Promise<string>);
exec(args: any, ctx: ToolContext): Promise<any>;
toDescriptor(): ToolDescriptor;
}Simplified API for creating tools.
import { defineTool } from '@shareai-lab/kode-sdk';
const myTool = defineTool({
name: 'my_tool',
description: 'Does something useful',
params: {
input: { type: 'string', description: 'Input value' },
count: { type: 'number', required: false, default: 1 },
},
attributes: {
readonly: true,
noEffect: true,
},
async exec(args, ctx) {
ctx.emit('custom_event', { data: 'value' });
return { result: args.input };
},
});Registry for Agent templates.
class AgentTemplateRegistry {
register(template: AgentTemplateDefinition): void;
bulkRegister(templates: AgentTemplateDefinition[]): void;
has(id: string): boolean;
get(id: string): AgentTemplateDefinition;
list(): string[];
}interface AgentTemplateDefinition {
id: string; // Required: unique identifier
name?: string; // Display name
desc?: string; // Description
version?: string; // Template version
systemPrompt: string; // Required: system prompt
model?: string; // Default model
sandbox?: Record<string, any>; // Sandbox configuration
tools?: '*' | string[]; // '*' for all, or specific tools
permission?: PermissionConfig; // Permission configuration
runtime?: TemplateRuntimeConfig; // Runtime options
hooks?: Hooks; // Hook functions
metadata?: Record<string, any>; // Custom metadata
}Manages multiple Agent instances.
class AgentPool {
constructor(opts: AgentPoolOptions);
async create(agentId: string, config: AgentConfig): Promise<Agent>;
get(agentId: string): Agent | undefined;
list(opts?: { prefix?: string }): string[];
async status(agentId: string): Promise<AgentStatus | undefined>;
async fork(agentId: string, snapshotSel?: SnapshotId | { at?: string }): Promise<Agent>;
async resume(agentId: string, config: AgentConfig, opts?: { autoRun?: boolean; strategy?: ResumeStrategy }): Promise<Agent>;
async destroy(agentId: string): Promise<void>;
}Multi-Agent collaboration space.
class Room {
constructor(pool: AgentPool);
join(name: string, agentId: string): void;
leave(name: string): void;
async say(from: string, text: string): Promise<void>;
getMembers(): RoomMember[];
}Example:
const pool = new AgentPool({ dependencies: deps });
const room = new Room(pool);
// Create and join agents
const agent1 = await pool.create('agent-1', config);
const agent2 = await pool.create('agent-2', config);
room.join('Alice', 'agent-1');
room.join('Bob', 'agent-2');
// Broadcast message
await room.say('Alice', 'Hello everyone!');
// Directed message
await room.say('Alice', '@Bob What do you think?');import { AnthropicProvider } from '@shareai-lab/kode-sdk';
const provider = new AnthropicProvider(
process.env.ANTHROPIC_API_KEY!,
process.env.ANTHROPIC_MODEL_ID ?? 'claude-sonnet-4-20250514',
{
thinking: { enabled: true, budgetTokens: 10000 },
cache: { breakpoints: 4 },
}
);import { OpenAIProvider } from '@shareai-lab/kode-sdk';
const provider = new OpenAIProvider(
process.env.OPENAI_API_KEY!,
process.env.OPENAI_MODEL_ID ?? 'gpt-4o',
{
api: 'responses',
responses: { reasoning: { effort: 'medium' } },
}
);import { GeminiProvider } from '@shareai-lab/kode-sdk';
const provider = new GeminiProvider(
process.env.GOOGLE_API_KEY!,
process.env.GEMINI_MODEL_ID ?? 'gemini-2.0-flash',
{
thinking: { level: 'medium', includeThoughts: true },
}
);| Tool | Description |
|---|---|
fs_read |
Read file content |
fs_write |
Create/overwrite file |
fs_edit |
Edit file with replacements |
fs_glob |
Match files with glob patterns |
fs_grep |
Search text/regex in files |
fs_multi_edit |
Batch edit multiple files |
bash_run |
Execute shell commands |
bash_logs |
Read background command output |
bash_kill |
Terminate background commands |
todo_read |
Read Todo list |
todo_write |
Write Todo list |
task_run |
Dispatch sub-Agent |
skills |
Load skills |
import { builtin, ToolRegistry } from '@shareai-lab/kode-sdk';
const registry = new ToolRegistry();
// builtin is an object with methods that return ToolInstance[]
for (const tool of [...builtin.fs(), ...builtin.bash(), ...builtin.todo()]) {
registry.register(tool.name, () => tool);
}
// Or register specific tool groups
builtin.fs().forEach(tool => registry.register(tool.name, () => tool));
builtin.bash().forEach(tool => registry.register(tool.name, () => tool));
builtin.todo().forEach(tool => registry.register(tool.name, () => tool));Available builtin groups:
builtin.fs()- File system tools:fs_read,fs_write,fs_edit,fs_glob,fs_grep,fs_multi_editbuiltin.bash()- Shell tools:bash_run,bash_logs,bash_killbuiltin.todo()- Todo tools:todo_read,todo_writebuiltin.task(templates)- Sub-agent tool:task_run(requires templates)
Manages skills at Agent runtime.
class SkillsManager {
constructor(skillsDir: string, whitelist?: string[]);
async getSkillsMetadata(): Promise<SkillMetadata[]>;
async loadSkillContent(skillName: string): Promise<SkillContent | null>;
}Generates a unique Agent ID.
import { generateAgentId } from '@shareai-lab/kode-sdk';
const agentId = generateAgentId(); // e.g., 'agt-abc123xyz'Cloud sandbox powered by E2B for isolated code execution.
new E2BSandbox(options?: E2BSandboxOptions)| Method | Signature | Description |
|---|---|---|
init() |
async init(): Promise<void> |
Initialize (create or connect) sandbox |
exec(cmd, opts?) |
async exec(cmd: string, opts?: { timeoutMs?: number }): Promise<SandboxExecResult> |
Execute a command |
dispose() |
async dispose(): Promise<void> |
Kill sandbox and cleanup |
getSandboxId() |
getSandboxId(): string |
Get sandbox ID for persistence |
getHostUrl(port) |
getHostUrl(port: number): string |
Get accessible URL for a port |
setTimeout(ms) |
async setTimeout(timeoutMs: number): Promise<void> |
Extend sandbox lifetime |
isRunning() |
async isRunning(): Promise<boolean> |
Check if sandbox is alive |
watchFiles(paths, listener) |
async watchFiles(...): Promise<string> |
Watch file changes |
unwatchFiles(id) |
unwatchFiles(id: string): void |
Stop watching |
getE2BInstance() |
getE2BInstance(): E2BSdk |
Access underlying E2B SDK |
| Property | Type | Description |
|---|---|---|
kind |
'e2b' |
Sandbox type identifier |
workDir |
string |
Working directory path |
fs |
SandboxFS |
File system operations |
Self-hosted sandbox powered by OpenSandbox for isolated code execution.
new OpenSandbox(options: OpenSandboxOptions)| Method | Signature | Description |
|---|---|---|
init() |
async init(): Promise<void> |
Initialize (create or connect) sandbox |
exec(cmd, opts?) |
async exec(cmd: string, opts?: { timeoutMs?: number }): Promise<SandboxExecResult> |
Execute a command |
dispose() |
async dispose(): Promise<void> |
Dispose sandbox by lifecycle policy |
getSandboxId() |
getSandboxId(): string | undefined |
Get sandbox ID for persistence |
isRunning() |
async isRunning(): Promise<boolean> |
Check if sandbox is alive |
watchFiles(paths, listener) |
async watchFiles(...): Promise<string> |
Watch file changes (polling fallback supported) |
unwatchFiles(id) |
unwatchFiles(id: string): void |
Stop watching |
getOpenSandbox() |
getOpenSandbox(): OpenSandboxClient |
Access underlying OpenSandbox client |
| Property | Type | Description |
|---|---|---|
kind |
'opensandbox' |
Sandbox type identifier |
workDir |
string |
Working directory path |
fs |
SandboxFS |
File system operations |
Static utility for building custom E2B sandbox templates.
static async build(
config: E2BTemplateConfig,
opts?: { apiKey?: string; onLog?: (log: string) => void }
): Promise<{ templateId: string; alias: string }>static async exists(alias: string, opts?: { apiKey?: string }): Promise<boolean>