TypeScript API Reference
Reference for the current @autohandai/agent-sdk package. Start with Agent and Run for application code, then use AutohandSDK when you need direct control over the local CLI runtime.
Overview
The TypeScript SDK wraps the local Autohand Code CLI runtime through JSON-RPC. It ships as the @autohandai/agent-sdk ESM package, supports Node.js >=18.17.0, and exposes both a high-level API and the lower-level runtime wrapper.
| Surface | What it does | Use it when |
|---|---|---|
@autohandai/agent-sdk |
Published package name and public import path. | Install it in Node.js or Bun projects. |
Agent |
High-level session wrapper for application code. | You want the cleanest API for create, send, stream, and JSON output. |
Run |
One prompt submission with its own stream, result, and cancellation path. | You want to inspect or control one specific prompt execution. |
AutohandSDK |
Lower-level runtime wrapper around the CLI subprocess and RPC client. | You need full lifecycle and runtime control. |
SDKEvent |
The event union emitted while the agent works. | You are building a UI, approval flow, or logging pipeline. |
Use Agent first
Agent.create() starts the CLI runtime, agent.send() creates a Run, and run.stream() gives you events without exposing the RPC layer.
Use AutohandSDK for control
AutohandSDK owns the subprocess and maps to CLI RPC methods for prompts, permissions, plan mode, state, hooks, MCP, sessions, and config.
Installation
Install the ESM package in a Node.js or Bun project. The package exports ./dist/index.js and TypeScript declarations from ./dist/index.d.ts.
npm install @autohandai/agent-sdkpnpm add @autohandai/agent-sdkyarn add @autohandai/agent-sdkbun add @autohandai/agent-sdknub add @autohandai/agent-sdkaube add @autohandai/agent-sdkThe TypeScript SDK is published on npm as @autohandai/agent-sdk.
| Field | Value | Meaning |
|---|---|---|
| Package | @autohandai/agent-sdk |
The current package name in the TypeScript wrapper. |
| Module format | type: module |
Use ESM import syntax. |
| Runtime | node >= 18.17.0 |
The package can be used from Node.js and Bun projects. |
| Bundled CLI | cli/ |
The SDK auto-detects the platform CLI binary unless you pass cliPath. |
Quick start
The normal flow is: create an Agent, send a prompt, stream events, wait for the result, and close the session.
import { Agent } from '@autohandai/agent-sdk';
const agent = await Agent.create({
cwd: '.',
instructions: 'Prefer small, typed changes.',
permissionMode: 'interactive',
});
const run = await agent.send('Summarize what this repository does');
for await (const event of run.stream()) {
if (event.type === 'message_update') {
process.stdout.write(event.delta);
}
}
const result = await run.wait();
console.log('\n\nFinal answer:', result.text);
await agent.close();
Creating sessions
Start with Agent.create() for normal application code. Use Agent.fromSDK() when your host already owns an AutohandSDK instance. Use AutohandSDK directly when you need lower-level runtime control.
import { Agent } from '@autohandai/agent-sdk';
const agent = await Agent.create({
cwd: '.',
instructions: [
'You are reviewing a TypeScript SDK API.',
'Prefer small, typed, composable interfaces.',
].join('\n'),
permissionMode: 'interactive',
});import { Agent, AutohandSDK } from '@autohandai/agent-sdk';
const sdk = new AutohandSDK({ cwd: '.' });
await sdk.start();
const agent = Agent.fromSDK(sdk);
const result = await agent.run('Summarize the release risks');
console.log(result.text);
await agent.close();import { AutohandSDK } from '@autohandai/agent-sdk';
const sdk = new AutohandSDK({
cwd: process.cwd(),
debug: true,
});
await sdk.start();Agent.create()
Agent.create(options: AgentOptions = {}): Promise<Agent>
AgentOptions extends SDKConfig and adds instructions?: string for app-specific guidance.
Agent.fromSDK()
Agent.fromSDK(sdk: AutohandSDK): Agent
Wrap an existing SDK instance when you want the Run API without giving up lower-level ownership.
AutohandSDK
new AutohandSDK(config: SDKConfig)
The lower-level runtime surface that owns the CLI subprocess, RPC client, and direct session controls.
Sending messages
Agent gives you three main prompt paths: create a Run, wait for a final result directly, or request typed JSON output.
const run = await agent.send('List the next three hardening tasks');
for await (const event of run.stream()) {
if (event.type === 'message_update') {
process.stdout.write(event.delta);
}
}
const result = await run.wait();
console.log(result.id, result.status);const result = await agent.run('Summarize release risk');
console.log(result.text);type ReleaseRisk = {
summary: string;
risks: Array<{ title: string; severity: 'low' | 'medium' | 'high' }>;
};
const risk = await agent.runJson<ReleaseRisk>('Assess publish readiness', {
schemaName: 'ReleaseRisk',
schema: {
summary: 'string',
risks: [{ title: 'string', severity: 'low | medium | high' }],
},
validate: (value) => value as ReleaseRisk,
});
console.log(risk.summary);| API | Returns | Use it when |
|---|---|---|
agent.send(input, options?) |
Promise<Run> |
You want to stream, inspect, or abort the run. |
agent.run(input, options?) |
Promise<RunResult> |
You just want the final result. |
agent.runJson(input, options?) |
Promise<T> |
You want typed JSON output and validation. |
Run
A Run is one prompt execution. It owns the stream, final result, JSON parsing, and cancellation path.
run.stream(): AsyncGenerator<SDKEvent>run.wait(): Promise<RunResult>run.json<T>(options?): Promise<T>run.abort(): Promise<void>readonly run.id: string
Structured JSON
Structured output in the TypeScript SDK is SDK-level JSON mode. The SDK adds JSON-only instructions to the prompt, waits for the final text, parses direct, fenced, or embedded JSON, and then runs your optional validator.
import { z } from 'zod';
const ReleaseRiskSchema = z.object({
summary: z.string(),
risks: z.array(z.object({
title: z.string(),
severity: z.enum(['low', 'medium', 'high']),
})),
});
const risk = await agent.runJson('Assess publish readiness', {
schemaName: 'ReleaseRisk',
schema: {
summary: 'short string',
risks: [{ title: 'string', severity: 'low | medium | high' }],
},
validate: ReleaseRiskSchema.parse,
});import { parseJsonText, StructuredOutputError } from '@autohandai/agent-sdk';
try {
const value = parseJsonText('Here is the result:\n{"ok":true}');
console.log(value);
} catch (error) {
if (error instanceof StructuredOutputError) {
console.error(error.rawResponse);
}
}| API | Signature | Behavior |
|---|---|---|
agent.runJson |
runJson<T>(input, options?): Promise<T> |
Creates a prompt with JSON instructions, waits for completion, parses the final response, and returns T. |
run.json |
json<T>(options?): Promise<T> |
Parses the final text from an existing Run. |
parseJsonText |
parseJsonText(text: string): unknown |
Accepts plain JSON, fenced JSON blocks, or the first valid embedded object or array. |
StructuredOutputError |
class StructuredOutputError extends Error |
Thrown when JSON cannot be parsed. The full raw response is available as rawResponse. |
JsonRunOptions<T>
schemaName?: stringnames the expected shape in the prompt.schema?: unknownis serialized and shown to the agent as a schema or example shape.outputInstructions?: stringadds output rules for this call.validate?: (value: unknown) => Ttransforms or validates the parsed value.
Streaming
Streaming is the center of the SDK experience. The host sees assistant output, tool execution, file modifications, permission pauses, and errors as they happen.
const run = await agent.send('Find the risky APIs in src/');
for await (const event of run.stream()) {
switch (event.type) {
case 'message_update':
process.stdout.write(event.delta);
break;
case 'tool_start':
console.log('\n[tool]', event.toolName);
break;
case 'permission_request':
console.log('\n[permission]', event.tool, event.description);
break;
}
}for await (const event of sdk.streamPrompt({
message: 'Analyze the current directory structure',
})) {
switch (event.type) {
case 'message_update':
process.stdout.write(event.delta);
break;
case 'tool_start':
console.log('\n[tool:start]', event.toolName);
break;
case 'tool_end':
console.log('[tool:end]', event.toolName, event.success);
break;
}
}| Event type | What it means | Typical host behavior |
|---|---|---|
message_update |
Assistant text delta. | Append to the UI or terminal. |
tool_start, tool_update, tool_end |
Tool lifecycle activity. | Show progress, audit logs, or tool output. |
permission_request |
The runtime paused and needs a decision. | Ask, auto-approve, or deny. |
file_modified |
A file changed during execution. | Invalidate caches or show changed files. |
error |
Runtime or transport failure. | Report failure and recover cleanly. |
Per-step run control
Use stopWhen to return control to the host after a completed tool step without closing the agent or losing session history.
import {
hasToolCall,
isStepCount,
} from '@autohandai/agent-sdk';
const result = await agent.run('Inspect the repository.', {
stopWhen: [
isStepCount(3),
hasToolCall('write_file'),
],
});
if (result.status === 'stopped') {
console.log(result.steps);
await agent.run('Continue from the reviewed step.');
}
| API | Contract | Notes |
|---|---|---|
AgentSendOptions.stopWhen |
StopCondition | readonly StopCondition[] |
An array stops when any condition returns true. |
isStepCount(count) |
StopCondition |
Stops after at least count completed tool steps. The count must be a positive integer. |
hasToolCall(toolName) |
StopCondition |
Stops when the latest completed step called the named tool. The name must be non-empty. |
StopCondition |
({ steps }) => boolean | Promise<boolean> |
Receives all ordered completed steps for the current run. |
run.abort() does not wait for pending asynchronous conditions. Once the CLI ends the turn, run.wait() returns an aborted result and queued prompts are released; late predicate outcomes are ignored. The SDK cannot cancel resources owned by your predicate.
The SDKEvent union also includes HookRateLimitEvent with type: 'hook_rate_limit', required error and timestamp strings, and optional code, model, provider, retryAfterMs, and httpStatus fields. See rate-limit validation and retry semantics.
See Pause and resume agents with stopWhen for the full lifecycle and continuation pattern.
Permissions
Interactive runs surface permission_request events. Your host decides whether the agent continues.
for await (const event of sdk.streamPrompt({
message: 'Create a new file called test.txt with some content',
})) {
if (event.type === 'permission_request') {
console.log(event.description);
await sdk.allowPermission(event.requestId, 'once');
continue;
}
if (event.type === 'message_update') {
process.stdout.write(event.delta);
}
}await sdk.permissionResponse({
requestId: event.requestId,
allowed: false,
});Permission helpers
agent.allowPermission(requestId, scope?)agent.denyPermission(requestId, scope?)agent.suggestPermissionAlternative(requestId, alternative)agent.permissionResponse(params)
scope can be once, session, project, or user.
CLI 0.9.13 run options
Configure the CLI process through SDKConfig before startup.
maxRequests,maxDurationSecondsset the request budget and wall-clock limit in seconds.allowedTools,disallowedToolsaccept lists of tool patterns.profile,settingOverridesselect a saved profile and apply ordered run-only overrides.noDaemon,syncSettings,searchEnginecontrol background services, settings synchronization, and web search.
Use sdk.onNotification and the packet’s method and params properties to read original CLI notifications. See run option semantics and notification payloads.
Configuration and workflow patterns
The strongest TypeScript examples in the repo are the ones that configure the session for a real workflow instead of a toy prompt.
const sdk = new AutohandSDK({
cwd: process.cwd(),
model: process.env.AUTOHAND_MODEL,
planMode: true,
skills: ['typescript', 'testing'],
agentsMd: {
enable: true,
path: './AGENTS.md',
},
});
await sdk.start();
for await (const event of sdk.streamPrompt({
message: [
'We are in discovery for a production TypeScript SDK change.',
'Inspect the repository and produce an SDLC plan only.',
'Do not edit files.',
].join('\n'),
})) {
if (event.type === 'message_update') {
process.stdout.write(event.delta);
}
}const sdk = new AutohandSDK({
cwd: '.',
model: process.env.AUTOHAND_MODEL,
}).appendSystemPrompt([
'For this SDK repository, prefer Bun commands.',
'Call out permission-sensitive operations before recommending execution.',
'Keep responses focused on TypeScript SDK API design.',
].join('\n'));
await sdk.start();const skills = [
'typescript',
'testing',
// './skills/my-custom/SKILL.md',
];
const sdk = new AutohandSDK({
cwd: process.cwd(),
model: 'fantail2',
skills,
});
await sdk.start();
console.log('Skills loaded:', skills.join(', '));Session control
sdk.setPermissionMode(mode)sdk.setPlanMode(enabled)sdk.enablePlanMode()sdk.disablePlanMode()sdk.setModel(model?)sdk.setMaxThinkingTokens(maxThinkingTokens)sdk.applyFlagSettings(settings)
Prompt, skills, and runtime surface
sdk.setSystemPrompt(promptOrPath)sdk.appendSystemPrompt(promptOrPath)sdk.toolssdk.skillssdk.rewindFiles(userMessageId, options?)sdk.seedReadState(path, mtime)
Runtime control
Use AutohandSDK directly when your app owns lifecycle, model selection, permission policy, MCP, hooks, or session persistence.
const sdk = new AutohandSDK({
cwd: process.cwd(),
timeout: 300_000,
debug: process.env.AUTOHAND_DEBUG === '1',
});
await sdk.start();
try {
await sdk.prompt({ message: 'Prepare a short repo summary.' });
} finally {
await sdk.close();
}await sdk.setModel('openrouter/auto');
await sdk.setPermissionMode('restricted');
await sdk.setPlanMode(true);
await sdk.setMaxThinkingTokens(20_000);
await sdk.applyFlagSettings({
maxTurns: 20,
maxBudgetUsd: 5,
});import { AutohandSDK, loadWorkspaceConfig } from '@autohandai/agent-sdk';
const config = await loadWorkspaceConfig(process.cwd());
const sdk = new AutohandSDK({
...config,
cwd: process.cwd(),
});
await sdk.start();| Group | Methods | Notes |
|---|---|---|
| Lifecycle | start(), stop(), close(), isStarted(), isConnected() |
close() is an alias for stop(). Call it in finally blocks for long-running hosts. |
| Conversation and browser handoff | reset(), createBrowserHandoff(), attachBrowserHandoff(), attachLatestBrowserHandoff() |
Reset returns a fresh session ID. Treat one-time browser-handoff tokens as short-lived credentials. |
| Auto-mode | startAutomode(), getAutomodeStatus(), pauseAutomode(), resumeAutomode(), cancelAutomode(), getAutomodeLog() |
Start confirms CLI acceptance while execution continues asynchronously. |
| Prompting | prompt(), streamPrompt(), streamInput(), interrupt(), abort() |
streamPrompt() yields the event stream for one prompt. streamInput() handles sequential prompt streams. |
| Session policy | setPermissionMode(), setPlanMode(), enablePlanMode(), disablePlanMode() |
Plan mode is separate from permission mode. Default interactive startup does not need a permission-mode RPC call. |
| Model and budget | setModel(), setMaxThinkingTokens(), applyFlagSettings() |
These update runtime behavior for the active session where the CLI RPC surface supports it. |
| MCP | mcpServerStatus(), reloadPlugins(), reconnectMcpServer(), toggleMcpServer(), setMcpServers() |
Use these for hosts that expose runtime MCP server management. |
| Approval protocols | acknowledgePermission(), respondToDirectoryAccess(), acknowledgeDirectoryAccess(), decideChanges() |
Acknowledgement confirms receipt; it does not grant the action. Preserve request and batch IDs. |
| Saved sessions | getHistory(), getSession(), attachSession() |
Load or attach an exact session and handle typed business failures explicitly. |
| YOLO and VS Code MCP | setYolo(), setYoloCompat(), setVscodeMcpTools(), respondToMcpInvocation() |
Use a positive YOLO timeout and correlate MCP responses to the emitted invocation request. |
| Learning, tools, and context | getLearningRecommendations(), updateLearnedSkills(), generateSkill(), getToolsRegistry(), setContextCompact() |
These return validated CLI results for project learning, tool diagnostics, and live compaction state. |
| Files | rewindFiles(), seedReadState() |
These support checkpointing and read-state flows when the underlying runtime provides them. |
See Control the Autohand Code CLI from every SDK for cross-language method names and the shared protocol contracts.
State and sessions
Long-lived hosts usually need more than prompting. They need state, history, stats, metadata, session persistence, and memory-aware workflows.
const state = await sdk.getState();
const messages = await sdk.getMessages({ limit: 20 });
const usage = await sdk.getContextUsage();
const stats = await sdk.getStats();
const metadata = await sdk.getSessionMetadata();
console.log(state);
console.log(messages);
console.log(usage);
console.log(stats);
console.log(metadata);await sdk.saveSession();
const metadata = await sdk.getSessionMetadata();
await sdk.resumeSession(metadata.sessionId);const saveSdk = new AutohandSDK({ cliPath: '/path/to/autohand' });
await saveSdk.start();
for await (const event of saveSdk.streamPrompt({
message: 'Save this to memory: "The user prefers TypeScript and functional patterns."',
})) {
if (event.type === 'message_update') {
process.stdout.write(event.delta);
}
}
await saveSdk.stop();
const recallSdk = new AutohandSDK({ cliPath: '/path/to/autohand' });
await recallSdk.start();
for await (const event of recallSdk.streamPrompt({
message: 'Recall what you know about my programming preferences from memory.',
})) {
if (event.type === 'message_update') {
process.stdout.write(event.delta);
}
}Inspect the live session
sdk.getState(params?)sdk.getMessages(params?)
Inspect the runtime surface
sdk.getContextUsage()sdk.supportedCommands()sdk.supportedModels()sdk.supportedAgents()sdk.accountInfo()
Save, resume, and measure
sdk.getStats()sdk.getSessionMetadata()sdk.saveSession()sdk.resumeSession(sessionId)sdk.getConfig()sdk.updateConfig(config)
Inspect local peers
agent.getSessionPeers()sdk.getSessionPeers()rpcClient.getSessionPeers()
Configure sessions.awareness as passive, warn, or coordinate. The CLI default is warn.
Hooks and AGENTS.md
The repo does support real hook-management APIs. The earlier page did not show them properly. This section now includes both CLI hook management and the event-stream hook pattern that many hosts actually need.
await sdk.addHook({
event: 'pre-tool',
command: 'echo "About to run: {{tool}}"',
});
const hooks = await sdk.getHooks();
console.log(hooks);
await sdk.testHook({
event: 'pre-tool',
command: 'echo "About to run: {{tool}}"',
});
await sdk.toggleHook('pre-tool', 0);
await sdk.removeHook('pre-tool', 0);for await (const event of sdk.streamPrompt({ message: prompt })) {
switch (event.type) {
case 'tool_start':
logger.info('tool.start', { tool: event.toolName });
break;
case 'tool_end':
logger.info('tool.end', { tool: event.toolName });
break;
case 'file_modified':
cache.invalidate(event.filePath);
break;
case 'permission_request':
await sdk.permissionResponse({
requestId: event.requestId,
allowed: event.tool !== 'delete_path',
});
break;
}
}const content = await sdk.loadAgentsMd('./AGENTS.md');
console.log(content);
const template = sdk.createDefaultAgentsMd('My Project');
console.log(template);
await sdk.setAgentsMdAsPrompt('./AGENTS.md');Manage hooks at runtime
sdk.getHooks()sdk.addHook(hook)sdk.removeHook(event, index)sdk.toggleHook(event, index)sdk.testHook(hook)sdk.setHooksSettings(settings)
Work with AGENTS.md
sdk.loadAgentsMd(source)sdk.createDefaultAgentsMd(projectName?)sdk.setAgentsMdAsPrompt(source)
Appendix: lower-level APIs
You can skip this section unless you are building your own wrapper, approval layer, or direct RPC integration. Most product code should stay on Agent, Run, and a few AutohandSDK methods.
RPCClient
start()andstop()manage the connection.prompt(),abort(),getState(), andgetMessages()map closely to CLI RPC methods.permissionResponse()andrequest()expose direct RPC calls.getSessionPeers()returns other live local sessions in the same workspace.events()yieldsSDKEventnotifications directly.
Transport
start()spawns the CLI process.request()sends JSON-RPC requests.onNotification()wires notification handlers.isRunning()reports subprocess state.
Key types and helpers
Use this as the quick map for application wiring. The exported source lives in src/types/index.ts and src/sdk/agent.ts.
SDKConfig
The main config surface for AutohandSDK and Agent.create().
| Area | Fields | Use |
|---|---|---|
| Runtime | cwd, cliPath, debug, timeout |
Choose the workspace, binary, logs, and request timeout. |
| Model | provider, model, fallbackModel, apiKey, baseUrl |
Configure provider selection and credentials. |
| Budget | maxTurns, maxBudgetUsd, temperature, thinking, effort |
Bound runtime cost, turns, sampling, and reasoning. |
| Policy | permissionMode, planMode, permissions, sandbox |
Control write access, planning mode, approvals, and sandboxing. |
| Extensions | skills, skillRefs, mcpServers, hooks, plugins |
Add skills, MCP servers, hooks, and plugin configuration. |
| Coordination | sessions.awareness |
Choose passive presence, advisory warnings, or write-path coordination for concurrent local agents. |
| PromptParams | Prompt input with message, optional context.files, context.selection, images, thinkingLevel, and agentsMd. |
| RunResult | Final run state: id, status (completed, aborted, or stopped), text, the full events trace, and ordered steps. |
| AgentInput | A string prompt or a full PromptParams object. |
| Permission types | PermissionMode, LegacyPermissionMode, PermissionDecisionScope, PermissionSettings, and PermissionResponseParams. |
| Tool | Enum of CLI tool names for integrations that need a typed tool surface. |
| Helper functions | loadConfigFrom, loadWorkspaceConfig, loadAgentsMd, createDefaultAgentsMd, detectProviderFromModel, validateProviderConfig, and parseJsonText. |
SDKEvent
| Event | Key fields | Use |
|---|---|---|
agent_start, agent_end |
sessionId, model, workspace, reason |
Mark session lifecycle in logs and UI. |
turn_start, turn_end |
turnId, tokensUsed, durationMs, contextPercent, reason |
Track turn progress, usage, and latency. |
message_start, message_update, message_end |
messageId, delta, content, thought |
Render assistant output and collect final text. |
tool_start, tool_update, tool_end |
toolId, toolName, args, output, success |
Show tool progress, stdout, stderr, and result state. |
file_modified |
filePath, changeType, toolId |
Refresh editor state or changed-file panels. |
step_end |
stepId, step |
Inspect completed tool calls and results before a stop condition is evaluated. |
session_peer_joined, session_peer_updated, session_peer_left |
peer, previous, timestamp |
Update local concurrent-agent presence and coordination UI. |
session_awareness_error |
operation, message, recoverable |
Report a recoverable active-agent registry observation failure. |
automode_iteration, automode_complete, automode_error |
sessionId, iteration, actions, error |
Track asynchronous auto-mode progress and terminal state. |
permission_request |
requestId, tool, description, context, options |
Pause for user approval or apply host policy. |
error |
code, message, recoverable |
Report runtime or transport failures. |
Other exported type groups
| Group | Types | When you need them |
|---|---|---|
| Config loading | CLIConfig, AutohandEnvVars, ProviderName |
Build provider-aware app configuration or pass AUTOHAND_ variables to the CLI subprocess. |
| Permissions | PermissionSettings, PermissionRule, PermissionResponseParams |
Implement allow, deny, remember, or alternative approval flows. |
| Sessions | SessionSettings, SessionsSettings, SessionAwarenessTier, ActiveAgentRecord, SessionMetadata, SessionStats |
Persist sessions, resume by ID, inspect peers, or display cost and token counters. |
| Step control | StopCondition, StopConditionContext, AgentStep, AgentStepToolCall, AgentStepToolResult |
Stop at a completed tool boundary and inspect the step that triggered it. |
| Skills | SkillSettings, SkillReference, SkillDefinition, SkillSource |
Load named skills or direct SKILL.md paths into the runtime. |
| Hooks | HookDefinition, HooksSettings, HookEvent, hook result types |
Configure CLI hooks and inspect hook execution results. |
| RPC | JsonRpcRequest, JsonRpcResponse, JsonRpcError, JSON_RPC_ERROR_CODES |
Build direct RPC integrations or test transport behavior. |