Skip to content

Client

The default claude export is a pre-configured client ready to use. For custom defaults, create your own with createClient().

claude.ask(prompt, options?)

Send a one-shot prompt and get the complete result.

ts
const result = await claude.ask("Fix the bug in main.ts", {
  cwd: "/path/to/project",
  model: "haiku",
});

Returns: Promise<TAskResult>

ts
type TAskResult = {
  text: string;                        // concatenated text output
  costUsd: number;                     // total cost in USD
  tokens: {
    input: number;                     // total input (base + cache read + cache creation)
    output: number;
    cacheRead?: number;                // tokens read from prompt cache
    cacheCreation?: number;            // tokens written to prompt cache
  };
  duration: number | undefined;        // ms
  sessionId?: string;
  events: TRelayEvent[];               // all events
};

claude.askJson(prompt, schema, options?)

Send a prompt, parse the response as JSON, and validate it against a schema. Returns { data: T, raw: TAskResult }.

ts
import { z } from "zod";

const { data } = await claude.askJson(
  "List 3 colors as JSON: { colors: string[] }",
  z.object({ colors: z.array(z.string()) }),
);

console.log(data.colors); // ["red", "green", "blue"]

Accepts Standard Schema objects (Zod, Valibot, ArkType) for typed validation, or a raw JSON Schema string that gets forwarded to --json-schema for CLI-side constraint (parse-only, no TypeScript inference).

Throws JsonValidationError with { rawText, issues } when parsing or validation fails. See Errors.

Returns: Promise<IJsonResult<T>>

ts
type IJsonResult<T> = {
  data: T;            // validated and typed result
  raw: TAskResult;    // full ask result (text, cost, tokens, events)
};

claude.stream(prompt, options?)

Returns an IClaudeStream - an async iterable that yields events as they arrive.

ts
const stream = claude.stream("Explain this code");

// Option A: iterate events
for await (const event of stream) { /* ... */ }

// Option B: convenience methods (consumes the stream)
const text = await stream.text();
const cost = await stream.cost();
const result = await stream.result();

WARNING

Iteration and convenience methods are mutually exclusive. If you start iterating with for await, calling .text() / .result() will throw. Pick one approach.

claude.session(options?)

Create a persistent multi-turn session. See Session.

ts
const session = claude.session({ cwd: ".", model: "opus" });

claude.create(defaults)

Create a new client with preset defaults. All options are merged with per-call overrides.

ts
const myClient = claude.create({
  cwd: "/my/project",
  model: "haiku",
  maxCostUsd: 1.00,
});

const result = await myClient.ask("What does this do?");

IClaudeOptions

All methods accept these options:

OptionTypeDescription
cwdstringWorking directory for the Claude process
model"opus" | "sonnet" | "haiku" | stringModel to use
systemPromptstringOverride system prompt
appendSystemPromptstringAppend to default system prompt
allowedToolsstring[]Tools to allow (CLI-level). Pass [] to disable all tools including MCP servers.
toolHandlerIToolHandlerRuntime tool control (approve/deny/intercept)
maxCostUsdnumberSDK-side budget limit. Checked after each turn, throws BudgetExceededError and kills the process
maxBudgetUsdnumberClaude Code native budget via --max-budget-usd. Enforced by the CLI itself
disallowedToolsstring[]Tools to deny at CLI level
addDirsstring[]Additional directories for tool access
effort"low" | "medium" | "high" | "max"Effort level
includeHookEventsbooleanInclude hook lifecycle events in output
includePartialMessagesbooleanInclude partial message chunks for real-time streaming
barebooleanMinimal mode, no hooks
jsonSchemastringJSON schema for structured output validation
forkSessionbooleanWhen resuming, create a new session ID instead of reusing the original
noSessionPersistencebooleanDon't save session to disk
sessionIdstringUse a specific UUID for the session
onCostUpdate(cost: TCostSnapshot) => voidCalled after each turn with cost data
onWarning(message: string, cause?: unknown) => voidRoutes all library-emitted warnings. Defaults to console.warn prefixed with [claude-wire]; pass () => {} to silence.
signalAbortSignalAbort signal for cancellation
resumestringSession ID to resume
verbosebooleanEnable verbose output (default: true)
mcpConfigstringPath to MCP server config JSON
continueSessionbooleanContinue the most recent session
permissionModestringPermission mode: "default", "plan", "auto", "bypassPermissions", "acceptEdits", "dontAsk"
configDirstringOverride CLAUDE_CONFIG_DIR for the spawned process
envRecord<string, string>Custom environment variables for the spawned process
settingSourcesstringPass "" to skip loading CLAUDE.md, settings.json, and project instructions
disableSlashCommandsbooleanDisable slash command loading for faster startup

Session-only options

ISessionOptions extends IClaudeOptions with:

OptionTypeDescription
onRetry(attempt: number, error: unknown) => voidFires each time a transient failure triggers a respawn inside one ask(). Can also be passed per-ask. See Session → Resilience.

Per-ask options

session.ask(prompt, options?) accepts IAskOptions:

OptionTypeDescription
onRetry(attempt: number, error: unknown) => voidPer-ask retry observer. Fires alongside the session-level onRetry when both are set. Useful for request-scoped correlation.
signalAbortSignalPer-ask abort. Aborts this ask only (session stays alive). Composes with the session-level signal -- either firing aborts the ask.

Lightweight / Headless Mode

For fast startup (~1.5s instead of ~35s), disable tools, settings, and slash commands:

ts
claude.ask("Classify this text", {
  model: "haiku",
  allowedTools: [],
  settingSources: "",
  disableSlashCommands: true,
});

Dual Budget System

maxCostUsd is SDK-level budget enforcement (throws BudgetExceededError). maxBudgetUsd is CLI-level enforcement (passed as --max-budget-usd flag). They operate independently.

Which should I use?

  • For most SDK consumers, prefer maxCostUsd -- you get a catchable BudgetExceededError in JavaScript and a onCostUpdate hook for live monitoring.
  • Use maxBudgetUsd when you need the CLI to enforce the ceiling itself (e.g. the process is also accessible outside the SDK).
  • Setting both is fine; whichever fires first wins.

Not affiliated with or endorsed by Anthropic. Supported by LogicStar AI.