Overview

The TypeScript SDK wraps the local Autohand 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.
Recommended path

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.

Compatibility 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.

The examples on this page are grounded in the TypeScript wrapper repository: `src/index.ts`, `src/sdk/agent.ts`, `src/sdk/index.ts`, `src/types/index.ts`, `examples/24-high-level-agent.ts`, `examples/25-structured-json.ts`, and `docs/API_REFERENCE.md`.

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`.

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.

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.

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.

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.

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?: string names the expected shape in the prompt.
  • schema?: unknown is serialized and shown to the agent as a schema or example shape.
  • outputInstructions?: string adds output rules for this call.
  • validate?: (value: unknown) => T transforms 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.

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.

agent.stream(input, options?) is the shortest high-level path. sdk.streamPrompt(params) is the lower-level path when you need full runtime control.

Permissions

Interactive runs surface `permission_request` events. Your host decides whether the agent continues.

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.

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.

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.tools
  • sdk.skills
  • sdk.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.

Group Methods Notes
Lifecycle start(), stop(), close(), isStarted(), isConnected() `close()` is an alias for `stop()`. Call it in `finally` blocks for long-running hosts.
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.
Files rewindFiles(), seedReadState() These support checkpointing and read-state flows when the underlying runtime provides them.

State and sessions

Long-lived hosts usually need more than prompting. They need state, history, stats, metadata, session persistence, and memory-aware workflows.

Runtime state

Inspect the live session

  • sdk.getState(params?)
  • sdk.getMessages(params?)
Context and metadata

Inspect the runtime surface

  • sdk.getContextUsage()
  • sdk.supportedCommands()
  • sdk.supportedModels()
  • sdk.supportedAgents()
  • sdk.accountInfo()
Persistence

Save, resume, and measure

  • sdk.getStats()
  • sdk.getSessionMetadata()
  • sdk.saveSession()
  • sdk.resumeSession(sessionId)
  • sdk.getConfig()
  • sdk.updateConfig(config)

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.

CLI hook management

Manage hooks at runtime

  • sdk.getHooks()
  • sdk.addHook(hook)
  • sdk.removeHook(event, index)
  • sdk.toggleHook(event, index)
  • sdk.testHook(hook)
  • sdk.setHooksSettings(settings)
Project guidance

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.

JSON-RPC layer

RPCClient

  • start() and stop() manage the connection.
  • prompt(), abort(), getState(), and getMessages() map closely to CLI RPC methods.
  • permissionResponse() and request() expose direct RPC calls.
  • events() yields `SDKEvent` notifications directly.
Subprocess layer

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`.

Configuration

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.
Common shapes
PromptParams
Prompt input with `message`, optional `context.files`, `context.selection`, `images`, `thinkingLevel`, and `agentsMd`.
RunResult
Final run state: `id`, `status`, `text`, and the full `events` trace.
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 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.
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, SessionMetadata, SessionStats Persist sessions, resume by ID, or display cost and token counters.
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.

See also