Skip to main content

@flow-state-dev/claude-code

Classes​

ClaudeCodeAgentAbortedError​

The caller's signal fired. A stopped run is a throw and never a handle, and this is what tells "you stopped it" from "it broke" for a host deciding whether to retry.

A host tells it with core's isAbortLike, whatever stopped the run: the root of its cause chain is always an AbortError, whose message is the signal's reason. The reason itself (a deadline's TimeoutError, a plain Error, or none) is on reason.

Extends​

  • Error

Constructors​

Constructor​
new ClaudeCodeAgentAbortedError(sessionId, reason?): ClaudeCodeAgentAbortedError;
Parameters​
sessionId​

string | null

The session Claude Code had named when the run was stopped, which a host resumes; null before it named one.

reason?​

unknown

The stopping signal's reason, as the caller gave it.

Returns​

ClaudeCodeAgentAbortedError

Overrides​

Error.constructor

Properties​

cause?​
cause?: unknown;
Inherited from​

Error.cause

code​
readonly code: "CLAUDE_CODE_AGENT_ABORTED" = "CLAUDE_CODE_AGENT_ABORTED";
message​
message: string;
Inherited from​

Error.message

name​
name: string;
Inherited from​

Error.name

reason?​
readonly reason?: unknown;

The stopping signal's reason, as the caller gave it.

sessionId​
readonly sessionId: string | null;

The session Claude Code had named when the run was stopped, which a host resumes; null before it named one.

stack?​
stack?: string;
Inherited from​

Error.stack


ClaudeCodeAgentRunError​

The SDK query() loop threw mid-stream. Wraps the underlying error so the caller sees a stable class while the original message is preserved on detail.cause. The agent block emits an error item and rethrows this.

Extends​

  • Error

Implements​

  • ClassifiedHarnessError

Constructors​

Constructor​
new ClaudeCodeAgentRunError(
message,
detail?,
harnessFailure?
): ClaudeCodeAgentRunError;
Parameters​
message​

string

detail?​
cause?​

string

harnessFailure?​

"unknown-conversation" | null

Returns​

ClaudeCodeAgentRunError

Overrides​

Error.constructor

Properties​

cause?​
cause?: unknown;
Implementation of​

ClassifiedHarnessError.cause

Inherited from​

Error.cause

code​
readonly code: "CLAUDE_AGENT_RUN_FAILED" = "CLAUDE_AGENT_RUN_FAILED";
detail?​
readonly detail?: object;
cause?​
cause?: string;
harnessFailure​
readonly harnessFailure: "unknown-conversation" | null;

The failure in core's neutral vocabulary, read with core's harnessFailureKind. "unknown-conversation" when Claude Code refused to continue the conversation the run asked to resume; null for every other failure. See isUnknownConversationFailure.

Implementation of​

ClassifiedHarnessError.harnessFailure

message​
message: string;
Implementation of​

ClassifiedHarnessError.message

Inherited from​

Error.message

name​
name: string;
Implementation of​

ClassifiedHarnessError.name

Inherited from​

Error.name

stack?​
stack?: string;
Implementation of​

ClassifiedHarnessError.stack

Inherited from​

Error.stack


ClaudeCodeSdkNotInstalledError​

The optional @anthropic-ai/claude-agent-sdk peer dependency is not installed. Fatal: the agent block cannot run its query() loop without it.

Extends​

  • Error

Constructors​

Constructor​
new ClaudeCodeSdkNotInstalledError(message?, detail?): ClaudeCodeSdkNotInstalledError;
Parameters​
message?​

string

detail?​
cause?​

string

Returns​

ClaudeCodeSdkNotInstalledError

Overrides​

Error.constructor

Properties​

cause?​
cause?: unknown;
Inherited from​

Error.cause

code​
readonly code: "CLAUDE_AGENT_SDK_NOT_INSTALLED" = "CLAUDE_AGENT_SDK_NOT_INSTALLED";
detail?​
readonly detail?: object;
cause?​
cause?: string;
message​
message: string;
Inherited from​

Error.message

name​
name: string;
Inherited from​

Error.name

stack?​
stack?: string;
Inherited from​

Error.stack

Interfaces​

ClaudeCodeAgentHandle​

Handle for a single in-process Agent SDK run.

The framework's neutral harness handle plus Claude's own extras. Unlike the fire-and-forget CLI handle, the SDK path observes the run to completion, so status reaches "completed"/"errored" and the handle carries the final assistant text, the tools the SDK exercised, and usage/cost when the SDK reported them. Usage and cost are null when the SDK result omitted them — values are never invented.

Extends​

  • HarnessRunHandle

Properties​

cost​
cost: HarnessRunCost | null;

What the run cost and how that was arrived at, or null when neither is known.

Inherited from​

HarnessRunHandle.cost

dispatchedAt​
dispatchedAt: number;

Epoch millis when the handle was created.

Inherited from​

HarnessRunHandle.dispatchedAt

finalMessage​
finalMessage: string | null;

The run's last assistant text, or null if it produced none.

Inherited from​

HarnessRunHandle.finalMessage

outcome​
outcome: HarnessRunOutcome | null;

How the run ended, or null while it is unknown.

Inherited from​

HarnessRunHandle.outcome

resultSubtype​
resultSubtype: ClaudeCodeResultSubtype | null;

The SDK's terminal result.subtype, or null if the run never produced one.

sessionId​
sessionId: string | null;

The harness's own session/run id, when one could be determined.

Inherited from​

HarnessRunHandle.sessionId

source​
source: "claude-code/sdk";

Which harness and door produced this — see HarnessSource.

Overrides​

HarnessRunHandle.source

status​
status: "running" | "completed" | "errored";
Overrides​

HarnessRunHandle.status

toolsObserved​
toolsObserved: string[];

Distinct SDK tool names observed during the run, in first-seen order.

url​
url: string | null;

Human-openable URL for the run, when the harness exposes one.

Inherited from​

HarnessRunHandle.url

usage​
usage: HarnessRunUsage | null;

Token usage, or null when the harness reported none.

Inherited from​

HarnessRunHandle.usage


ClaudeCodeAgentOptions​

Public surface of @flow-state-dev/claude-code: the in-process Agent SDK handler block, its opt-in capability, the resolver seam, the start-time account probe and model list, the environment pass-list a run needs, the readiness check, the session-continuity provider, the two collections the work recorder writes, the workspace capability, the types of the tools mcpTools relays, handle and wire types, and typed errors.

Every name here carries the package's name (ClaudeCode, claudeCode, CLAUDE_CODE_), as Codex's and Cursor's carry theirs. Shapes every harness shares (the plan record, the model list, the readiness answer) are core's, on @flow-state-dev/core/harness.

Properties​

agents?​
agents?: unknown;

Sub-agent definitions forwarded to the SDK agents option.

allowedTools?​
allowedTools?: string[];

Tools the run may use without asking, forwarded to the SDK with Claude Code's to-do tools (TaskCreate, TaskUpdate, TaskGet, TaskList) added. Outside its terminal, Claude Code offers those on its current models only when they are named here, and they need no permission, so naming them allows nothing else. Under bypassPermissions its search tools (Grep, Glob) are added too, which Claude Code also offers only when named; in other modes naming them would skip path prompts, so they are left to the host. To keep a run from any of them, list them in disallowedTools.

cwd?​
cwd?: HarnessResolver<string>;

The directory this run works in. Default: unset, which is the directory the server process itself is running in — byte for byte what every existing caller has today.

This is the canonical explanation; everywhere else links here.

Set it and the run's file tools address paths inside that directory, and recordWork's index of what the run touched is keyed there too. Those are two halves of one thing, and doing only the first is the trap: forward the directory to the SDK without threading it into the record and the index describes a checkout the run never touched — nothing throws, nothing is empty, the rows are simply keyed somewhere else. See canonicalFilePathKey, which is where the second half lands.

A resolver, not a constant, because one flow build serves many runs. It is called once per invocation, before query, and is handed the block's context and nothing else.

The prompt is deliberately not reachable from here. It used to be the resolver's first argument, which undid the paragraph below: the prompt is the one value a caller — or a model holding this block as a tool — controls, so a resolver that could see it could be written to put the run's directory wherever the caller asked. HarnessResolver in @flow-state-dev/core/types carries the full argument.

import { mkdir, mkdtemp } from "node:fs/promises";
import { join } from "node:path";

const CHECKOUT_ROOT = "/var/agent-checkouts";

claudeCodeAgent({
// A fresh directory per run, created by the server. No caller input
// reaches the path.
cwd: async () => {
// `mkdtemp` creates the leaf, not the parent, and fails ENOENT if the
// root is missing — which on a fresh machine it is.
await mkdir(CHECKOUT_ROOT, { recursive: true });
return mkdtemp(join(CHECKOUT_ROOT, "run-"));
},
// A per-run directory needs a per-run conversation: by default the SDK
// is handed a `resume` handle from the last run in this session, which
// would resume it inside a tree that has nothing to do with it.
detached: true,
})

Reusing a directory across runs is the harder case, and it is where the sharp edges are. This is the example to copy — the guard is part of it rather than a footnote, because a snippet is what actually gets pasted:

import { createHash } from "node:crypto";
import { mkdir } from "node:fs/promises";
import { isAbsolute, join, relative } from "node:path";

function segment(value: string | undefined): string {
return value === undefined
? "0"
: `1${createHash("sha256")
.update(Buffer.from(value, "utf16le"))
.digest("hex")}`;
}

function checkoutFor(tenantId: string | undefined, key: string): string {
const dir = join(CHECKOUT_ROOT, segment(tenantId), segment(key));
const rel = relative(CHECKOUT_ROOT, dir);
if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) {
throw new Error(`refusing a checkout outside ${CHECKOUT_ROOT}`);
}
return dir;
}

claudeCodeAgent({
cwd: async (ctx) => {
const dir = checkoutFor(
ctx.session.identity.tenantId,
ctx.session.identity.id,
);
await mkdir(dir, { recursive: true });
return dir;
},
})

Five rules, one line each; the guide carries the derivation so it lives in one place and three copies cannot drift into contradicting each other:

  • Derive, never validate. A grammar of forbidden shapes is a list nobody finishes — separators, .., Windows' stripped trailing dots, reserved device names, case folding.
  • Bound the output; never truncate to bound it. Filenames stop at 255 characters and a reversible encoding grows with its input, so a digest is fixed-width where hex is not. Trimming a reversible encoding instead would map two long ids onto one directory — the collision the derivation exists to prevent. The honest cost: distinctness rests on SHA-256 rather than on arithmetic, and the path stops being readable.
  • Hash UTF-16 code units, not UTF-8 bytes. UTF-8 cannot represent a lone surrogate, so transcoding through it maps every one of them onto the replacement character and distinct session ids would share a tree.
  • Tag presence; never substitute a stand-in. A ?? "default" fallback merges an un-tenanted host with a tenant named default. The tag also keeps each segment non-empty, since join discards an empty one.
  • One segment per value, and confirm containment with path.relative rather than a string prefix, which rejects every valid value on Windows.
  • Serialize runs that share a checkout. Deriving the same directory twice is the point; two live runs in it is not. Actions run concurrently by default, so declare concurrency: "queue" (or "reject") on the action — it arbitrates on the session, the same value the checkout is derived from. It arbitrates DISPATCHES, so it does not cover two invocations in one dispatch (a model calling this tool twice in one step), nor two external workers unless their queue adapter supplies a shared lease backend (JobQueueAdapter.leaseBackend). Reuse a checkout for one agent step per run on a single-instance host, or on workers sharing a lease backend; derive a fresh directory otherwise.

The authenticated tenant is ctx.session.identity.tenantId; ctx.session.identity.id is deliberately bare, because two tenants can hold one session id. Prefer a key the server assigned over one that arrived with the request — both reach the server from the caller, so the encoding is what makes an untrusted one safe to build a path from.

The resolver may be async, for a directory that has to be looked up or provisioned first.

An option, never a field on the block's input — a correctness constraint rather than a style preference. The same block is exposed as a model-facing tool through the agent capability, so a working directory reachable from the input is one the model can choose. The block's input stays the prompt.

It is a working directory, not a boundary: the run can still address paths outside it, and the file record is a log of what its tools did rather than a fence around where they may go.

detached?​
detached?: boolean;

Run the agent as dispatched background work — the block a task board worker's dispatcher({ type: "task" }) targets, declared on the flow under task: { actions } and run in a child session. Default false: an in-session agent that keeps conversation state — the sdkSessionId resume handle and the sdkAgentRuns log — which is the behaviour every existing caller has.

This is the canonical explanation; everywhere else links here.

defineFlow refuses a dispatched entry whose block authors a sessionStateSchema (assertDispatchEntrySupported), because the block runs in a child session it may share with other rows, where two blocks choosing the same key with different shapes corrupt each other silently.

A background job is one run in one child session, so nothing on that path reads the resume handle back and the run log's job belongs to the child session's own item stream. true therefore suppresses three things together, and they are one decision rather than three: the declaration, the reads and writes that go with it (a value written under an undeclared key is not a smaller version of the same behaviour), and the SDK resume — the session provider is not consulted at all, so a custom provider cannot hand back a saved id that silently resumes a prior conversation.

Everything else is identical: the items the run emits, the handle it returns, and how failures surface. The one deliberate consequence is that a second task addressed to the same child session starts the agent fresh, while the child session's own item history continues as normal.

disallowedTools?​
disallowedTools?: string[];

Disallowed tool names forwarded to the SDK.

env?​
env?: Record<string, string | undefined>;

Environment variables for the run's own process. Default: unset, which hands the run only Claude Code's pass list, harnessEnv({ pass: CLAUDE_CODE_PASS }), read when each run starts. A server variable outside that list (a database URL, another service's key) never reaches the run, whose model has a shell.

Setting it REPLACES the environment rather than adding to it, which is the SDK's own behaviour. To pass more, build your own list: env: harnessEnv({ pass: [...CLAUDE_CODE_PASS, "MY_VAR"] }). Name PATH in it: the run's shell commands and git are found through it. Passing process.env hands the run the server's whole environment.

The pass list covers signing in with ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN only. A host that signs in any other way adds the names that way reads: ANTHROPIC_AUTH_TOKEN or ANTHROPIC_BASE_URL for a gateway, CLAUDE_CODE_USE_BEDROCK with its AWS_* variables, CLAUDE_CODE_USE_VERTEX with its GOOGLE_* / CLOUD_ML_REGION variables, and CLAUDE_CONFIG_DIR for a sign-in stored outside HOME.

includePartialMessages?​
includePartialMessages?: boolean;

Whether to request partial-message deltas. Default: true.

maxTurns?​
maxTurns?: number;

Max turns forwarded to the SDK.

mcpTools?​
mcpTools?:
| ClaudeCodeMcpTools
| ((ctx) =>
| ClaudeCodeMcpTools
| Promise<ClaudeCodeMcpTools>);

Tools this process serves to the run, grouped by server name: a value, or a resolver called once per run with the run's context only (like cwd). Default: unset, which hands the SDK exactly today's options.

This is the canonical explanation; everywhere else links here.

Each entry becomes an MCP server inside this process, named by its key; the run calls its tools as mcp__<server>__<tool>. A tool is a name, a description, a JSON Schema for its input and a call function, so the option can't carry an address or headers: where a tool's work happens and what credential it uses stay with the host.

Set, even to {}, it is the run's whole MCP set: strictMcpConfig keeps out servers from .mcp.json, settings files and plugins, and disableClaudeAiConnectors keeps out the signed-in account's claude.ai connectors. If the run still reports a server it wasn't handed, a status item says so. The tools are allowed without asking; name one in disallowedTools to keep it out. Each server's close is called when the run ends, however it ends, and once when several servers share it. An abort while the resolver is still connecting stops the wait; what it answers afterwards is closed.

model?​
model?: string | HarnessResolver<string | null | undefined>;

Which model the run uses: a fixed id, or a resolver called once per invocation, like cwd and resume, so one block can run a different model for each run (each session of a host, say). Forwarded to the SDK as its model, on a fresh run and a resumed one alike.

null, "" and undefined from the resolver all mean "no model named": the SDK runs Claude Code's own default. The resolver is handed the context alone, never the prompt, for the reason cwd is.

name?​
name?: string;

Block name. Default "claude-code-agent".

onActivity?​
onActivity?: HarnessActivityHook;

Called with each completed assistant message and each tool call the run starts, so a host can say how the run is doing. Default: unset. Not awaited, and a throw is logged and swallowed.

onErrored?​
onErrored?: (error, ctx) => void | Promise<void>;

Ran after this block's execution threw, with the error and the block's own context — the standard block lifecycle hook, forwarded.

Reachable only through this option because nothing else can supply it: a capability contributes resources, state and tools, never lifecycle hooks, so anything that has to run when a run FAILS has nowhere else to hook. Releasing something the run was holding is the case that made it necessary.

It does not swallow the error; the run still fails.

Parameters​
error​

Error

ctx​

HarnessCallbackContext

Returns​

void | Promise<void>

onEvent?​
onEvent?: HarnessEventHook;

Called on every event the run sends, of any kind, so a host can tell a working run from a silent one. Not awaited, and a throw is logged and swallowed.

onSession?​
onSession?: HarnessSessionHook;

Called the moment the SDK names the session this run is in, so a host can record the id it will later hand back through ClaudeCodeAgentOptions.resume. Default: unset.

Background path only, refused in-session for the reason resume is: the block already persists the id to session state there, and a second writer racing it is two owners of one field.

It fires DURING the run, before the next streamed message is consumed — not after it, and not from the returned handle. The distinction is the whole reason the hook exists: a run the host's deadline kills returns no handle at all, and a run that ends in a throw returns none either, so a host that only learned the id at the end has nothing to continue in exactly the case it wanted to. Called once per distinct session id rather than once per message, because every message carries one and the host's write is durable.

It is not a place to do work. Whatever it does happens inline on the stream, so a slow hook slows the run and a throwing one fails it.

onToolApproval?​
onToolApproval?: (req, ctx) =>
| ClaudeCodeToolApprovalDecision
| Promise<ClaudeCodeToolApprovalDecision>;

Optional approval seam. When set, it is adapted onto the SDK canUseTool callback: each tool call routes through it, and the decision is noted via a status item. When unset, HITL degrades to the SDK's own permissionMode. A tool in allowedTools is pre-allowed by the SDK and never reaches it. A held decision stops the turn with the call unrun, for a host that waits for a person outside the run (approveTools on a harness manager). The run's stop after a held call is that wait, not a failure: the run still throws its signal's reason, but leaves no error item.

Parameters​
req​

ClaudeCodeToolApprovalRequest

ctx​

HarnessCallbackContext

Returns​

| ClaudeCodeToolApprovalDecision | Promise<ClaudeCodeToolApprovalDecision>

onUsage?​
onUsage?: HarnessUsageHook;

Called with each subscription usage window Claude Code reports during the run (its rate_limit_event), so a host can record how much of the subscription is left. Default: unset, and the events are dropped.

The report names claude-code, the window, when it was observed, when the run started, and the account the run is signed in as (its accountInfo() email, asked once at the first event; null when it names none). An event that names no window, as on an API key, is not reported.

Awaited like onSession, so no write lands after the run ends, but a throw is logged and swallowed: a usage write never fails the run. Unlike onSession, it is allowed in-session too: it owns no part of the conversation, so it races nothing.

permissionMode?​
permissionMode?: string;

Permission mode forwarded to the SDK (HITL default behavior).

prompt?​
prompt?: (input, ctx) => string;

Derive the prompt from input/ctx. Default: input.prompt.

Parameters​
input​
prompt​

string

ctx​

HarnessCallbackContext

Returns​

string

recordPullRequests?​
recordPullRequests?: boolean;

Record each pull request the run opens in core's pull-request record (observed-pull-requests). Default true: the block declares the collection and starts core's recorder. A gh pr create or a create-pull-request tool whose result names a pull request is a row; a gh pr view is not. false declares nothing and records nothing.

recordWork?​
recordWork?: boolean;

Record what the run DID, alongside the items that record what it said. Default false, which is byte-identical to the behaviour every existing caller has: nothing recorded, no resources declared.

This is the canonical explanation; everywhere else links here.

Set true and the block declares three session-scoped resource collections and writes into them as the run goes:

  • observed-file-ops — one entry per path the run's file-writing and file-editing tools touched: how, when, and how the attempt settled. Not the contents.
  • observed-plan — one entry per item on the run's own to-do list, carrying its wording and its current and previous status. Deliberately NOT the work queue that dispatched the run, so a run that decides to do five more things cannot start five more jobs by writing a to-do list.
  • observed-gaps — one entry per mutation the recorder recognised and could not record, so a missing row is never confused with a mutation that never happened.

All three are readable over the resource route that already ships, keyed under the run's own request id so a child session reused across runs answers "what did this run do" rather than "what has this child session ever done".

What the file record is, precisely. It is a log of the file operations the run's file TOOLS performed, not an index of everything that changed on disk. A run that edits a file through the shell — a sed -i, a redirect, a mv, a formatter — performs no file-tool call, so nothing is recorded and the file does not appear.

Recording never fails the run: anything the recorder cannot handle is skipped, written to observed-gaps, and noted as a status item. The gap ROW is the durable half — a status note dedupes on its own message and renders into a latest-wins slot, so two identical skips collapse to one.

resolveClaudeAgent?​
resolveClaudeAgent?: ResolveClaudeCodeAgent;

Host hook resolving the SDK query. Default: lazy SDK import.

resume?​
resume?: HarnessResolver<string | null | undefined>;

Which conversation this background run continues. Default: unset — a fresh session, byte for byte today's detached: true behaviour.

Background path only (detached: true), and set it in-session and this factory throws. In-session the block's own conversation state already owns continuity — it reads the last run's id off session state and resumes it — so an explicit id would be a second owner of one decision, and which of the two won would depend on the order two lines happen to run in. Refused at construction rather than resolved and ignored, because a host that asked for a resume and silently did not get one has no way to find out.

A resolver, not a value, for the reason ClaudeCodeAgentOptions.cwd gives: one flow build serves many runs, and the session to continue is per run. It is called once per invocation, before query.

null and "" both mean "start fresh" and reach the SDK as no resume at all. That matters more than it reads: a host's state carries null on the first attempt, an over-eager ?? "" produces the other, and an empty resume key is a value the SDK is entitled to interpret.

Pair it with ClaudeCodeAgentOptions.onSession. A host that resumes without recording the id the run confirms cannot continue a run that died mid-flight — which is the case resume mostly exists for.

An option and never a field on the block's input, for the same reason cwd is one: the input schema is model-facing through the agent capability's tool preset, so a session id reachable from it is a session a model could choose to continue.

sandbox?​
sandbox?:
| ClaudeCodeSandboxSettings
| ((ctx) =>
| ClaudeCodeSandboxSettings
| Promise<ClaudeCodeSandboxSettings>);

The SDK's sandbox settings, forwarded verbatim. Default: unset — no sandbox, as today.

A value or a resolver, and the resolver is not a convenience. The settings that confine a run to its own directory name that directory — filesystem.allowWrite is a list of paths — and the directory is per run while one flow build serves many. A build-time constant can express "sandboxed" but not "sandboxed to THIS run's workspace", which is the only form of it that contains anything. Same reason cwd is a resolver.

The resolver is handed the context alone, like cwd and resume and for the sharper version of their reason: these settings are the FENCE, and a fence derived from the prompt is a fence the caller drew. See HarnessResolver in @flow-state-dev/core/types, which carries the argument once.

Loosely typed for the same reason agents is: this package treats the Agent SDK as an optional peer, so its types are not imported here. An open object rather than unknown, because unknown | fn collapses to unknown and the resolver form — the one that matters — would then get no contextual typing and its parameter would be an implicit any.

sessionProvider?​
sessionProvider?: BindingProvider<ClaudeCodeSession>;

Session-continuity provider. Default: resume-by-id provider.

settings?​
settings?: Record<string, unknown>;

Settings for this run, in Claude Code's settings.json shape, handed to the SDK on top of { disableAllHooks: true }. Default: unset, which hands the SDK only that: every hook off.

They sit above every source settingSources loads, so a key here beats the same key in the repository's .claude/settings.json. That is why hooks are off by default: a repository's hooks run by themselves and show in no transcript, and a run that loads "project" settings (the default loads all three sources) would otherwise run whatever hooks the repository it works in declares. A host that trusts the repository sets settingSources: ["project"] to load its CLAUDE.md and skills, and the hooks stay off. A host that wants them passes settings: { disableAllHooks: false }; a key given here always wins.

With mcpTools set, the run's settings also carry disableClaudeAiConnectors: true, whatever this says: mcpTools is the run's whole MCP set. The object is not modified.

settingSources?​
settingSources?: ClaudeCodeSettingSource[];

Which filesystem settings this run loads — "user", "project", "local". Default: unset, which loads all three, exactly as today.

This is the canonical explanation; everywhere else links here.

"project" is the load-bearing one: it is what makes the run read CLAUDE.md and .claude/settings.json out of its working directory. When that directory is one the server assembled from an application's own resources, its contents are caller-controllable input, and a run reading configuration out of them means callers configure the agent. Pass [] to load none.

Left unset by default deliberately: this option is the plumbing, not the policy. Nothing changes for a caller who does not set it.

systemPrompt?​
systemPrompt?: ClaudeCodeSystemPrompt;

The system prompt the run starts from, forwarded to the SDK as given; the shapes are on ClaudeCodeSystemPrompt. Omitted, the run starts from Claude Code's own prompt, the one the claude CLI uses.

No prompt makes the agent keep a to-do list. recordWork's plan half fills only when the agent chooses to use its to-do tools, which every run is offered (see allowedTools).

uses?​
uses?: UsesSlot;

Capabilities installed on the block this factory returns — the same uses slot any other block takes, forwarded to handler().

Without it, a caller who wants the agent to carry a capability has to stop using this factory and hand-roll the block. That is the whole reason the slot is here rather than a wrapper around it.


ClaudeCodeHarnessOptions​

Options for claudeCodeHarness.

Properties​

disableSkillShellExecution?​
disableSkillShellExecution?: boolean;

When true, shell snippets embedded in skill files do not run. Defaults to false so harness runs match an interactive Claude Code session; set true when Skill is pre-approved but those snippets should stay fenced off from Bash.

extraAllowedTools?​
extraAllowedTools?: string[];

Tools appended to the kit default (Read, Write, Edit, Bash) without asking. The agent block still adds Claude Code's to-do tools. Applies in both acceptEdits and plan mode; the SDK still enforces the selected mode. Under acceptEdits, name Skill, Grep and Glob explicitly to offer them (they are not auto-injected like under bypassPermissions). Pre-approving search skips path prompts, including for paths outside the working directory; this is no sandbox. To drop a default tool, use disallowedTools on a custom agent block instead of this harness.

plan?​
plan?: boolean;

Plan only: the value is claude-code-plan ("Claude Code (plan)"), whose runs work in plan permission mode. Fill both values for an app that has workers of each kind.


ClaudeCodeMcpTool​

One tool the host serves to a run.

Properties​

description?​
description?: string;
inputSchema​
inputSchema: Record<string, unknown>;

The tool's input as a JSON Schema object, handed to Claude Code unchanged.

name​
name: string;

The tool's name on its server; the run sees it as mcp__<server>__<name>.

Methods​

call()​
call(args, options): Promise<unknown>;

Run the tool. Resolve to an MCP CallToolResult ({ content, isError? }) to answer with it as is, or to any other value, which the run reads as JSON text. A throw answers the run with an error result. signal aborts when the run cancels the call.

Parameters​
args​

Record<string, unknown>

options​
signal?​

AbortSignal

Returns​

Promise<unknown>


ClaudeCodeMcpToolServer​

One server's worth of tools, and what to call when the run ends.

Properties​

close?​
close?: () => void | Promise<void>;

Called once when the run ends, however it ends.

Returns​

void | Promise<void>

tools​
tools: ClaudeCodeMcpTool[];

ClaudeCodeQueryOptions​

Options forwarded to the SDK query() call. Loosely typed by design.

Properties​

abortController?​
abortController?: AbortController;

Forwarded to the SDK so an aborted ctx.signal stops the run.

agents?​
agents?: unknown;
allowedTools?​
allowedTools?: string[];
canUseTool?​
canUseTool?: ClaudeCodeCanUseTool;
cwd?​
cwd?: string;

The directory the run works in. The SDK's own file tools address paths relative to it, and the block keys its record of what the run touched there too — see ClaudeCodeAgentOptions.cwd, which is canonical for both halves.

disallowedTools?​
disallowedTools?: string[];
env?​
env?: Record<string, string | undefined>;

Environment variables for the run's own process.

includePartialMessages?​
includePartialMessages?: boolean;
maxTurns?​
maxTurns?: number;
mcpServers?​
mcpServers?: Record<string, unknown>;

MCP servers for the run. Set only from mcpTools, so every entry is an in-process server ({ type: "sdk", name, instance }); loosely typed because the SDK's own type is not imported.

model?​
model?: string;
permissionMode?​
permissionMode?: string;
resume?​
resume?: string;
sandbox?​
sandbox?: unknown;

The SDK's sandbox settings, forwarded verbatim.

Loosely typed for the same reason as agents: this package treats the SDK as an optional peer, and importing its types here would make a scripted fake need the real dependency.

settings?​
settings?: Record<string, unknown>;

Settings for the run, above every loaded source: the host's own (ClaudeCodeAgentOptions.settings), with mcpTools' connector switch merged in when it is set.

settingSources?​
settingSources?: ClaudeCodeSettingSource[];

Which filesystem settings the run loads — user, project, local.

Omitted and the SDK loads all of them, matching the CLI. [] loads none. The distinction matters more than it looks: project is what makes the run read CLAUDE.md and .claude/settings.json from its working directory, so a directory the run did not come with can otherwise configure the agent working in it.

spawnClaudeCodeProcess?​
spawnClaudeCodeProcess?: (options) => unknown;

The SDK's process-spawn hook. The block sets it so it holds the real process and can wait for it to exit on abort; a scripted query may ignore it.

Parameters​
options​

ClaudeCodeSpawnOptions

Returns​

unknown

strictMcpConfig?​
strictMcpConfig?: boolean;

Use only mcpServers: no .mcp.json, settings-file or plugin servers.

systemPrompt?​
systemPrompt?: ClaudeCodeSystemPrompt;

ClaudeCodeReadinessOptions​

Options for checkClaudeCodeReadiness: the probe's, and how the installed SDK is read.

Extends​

Properties​

env​
env: Record<string, string>;

The environment Claude Code is started with. Pass the one the run gets (for example harnessEnv({ pass })), so a credential the run can't see isn't counted.

Inherited from​

ProbeClaudeCodeAccountOptions.env

importSdk?​
importSdk?: ClaudeCodeSdkImporter;

How the SDK module is loaded. A seam for tests; the default imports the installed SDK.

Inherited from​

ProbeClaudeCodeAccountOptions.importSdk

readInstalledSdkVersion?​
readInstalledSdkVersion?: InstalledSdkVersionReader;

Which @anthropic-ai/claude-agent-sdk is installed. Default: the one beside this package. A seam for a host's own check and for tests; the block itself always reads the installed one.

signal?​
signal?: AbortSignal;

Stops waiting and closes Claude Code when it aborts; the answer is then none, as on a timeout.

Inherited from​

ProbeClaudeCodeAccountOptions.signal

timeoutMs?​
timeoutMs?: number;

How long to wait for Claude Code's answer before reading it as none. Default 10 000 ms.

Inherited from​

ProbeClaudeCodeAccountOptions.timeoutMs


ClaudeCodeSession​

The portable session record. sdkSessionId is the SDK session_id to resume, or null for a fresh run. key echoes the resolution key for diagnostics.

Properties​

sdkSessionId​
sdkSessionId: string | null;

ClaudeCodeSpawnOptions​

What the SDK hands spawnClaudeCodeProcess. Declared here so the SDK stays an optional peer.

Properties​

args​
args: string[];
command​
command: string;
cwd?​
cwd?: string;
env​
env: Record<string, string | undefined>;
signal​
signal: AbortSignal;

ClaudeCodeToolApprovalRequest​

An approval request handed to ClaudeCodeAgentOptions.onToolApproval.

Properties​

input​
input: unknown;
signal?​
signal?: AbortSignal;

The SDK's per-call abort signal (extra.signal from canUseTool), when present. A host UI can observe it to cancel a pending approval prompt.

toolName​
toolName: string;

ClaudeCodeWorkspaceCapabilityOptions​

Extends​

Properties​

agents?​
agents?: unknown;

Sub-agent definitions forwarded to the SDK agents option.

Inherited from​

ClaudeCodeAgentOptions.agents

allowedTools?​
allowedTools?: string[];

Tools the run may use without asking, forwarded to the SDK with Claude Code's to-do tools (TaskCreate, TaskUpdate, TaskGet, TaskList) added. Outside its terminal, Claude Code offers those on its current models only when they are named here, and they need no permission, so naming them allows nothing else. Under bypassPermissions its search tools (Grep, Glob) are added too, which Claude Code also offers only when named; in other modes naming them would skip path prompts, so they are left to the host. To keep a run from any of them, list them in disallowedTools.

Inherited from​

ClaudeCodeAgentOptions.allowedTools

collections?​
collections?: ClaudeCodeWorkspaceCollectionSpec[];

Which collections to mount. Default: every collection on ctx.resources whose pattern gives a directory to mount it at.

contain?​
contain?: boolean;

Confine the run to the workspace it was given. Default true.

This is the canonical explanation; everywhere else links here. Three settings, answering different halves of the same question.

settingSources: [] stops the run reading its CONFIGURATION out of the workspace. A projected directory holds whatever the mounted collections hold, and in an application those are written by its users — so a CLAUDE.md or a .claude/settings.json among them is user input the run would otherwise obey.

The sandbox settings are what constrain the run's WRITES. cwd is a working directory, not a fence: absolute paths still resolve, so the boundary has to be declared. enabled: true is the boundary, and allowUnsandboxedCommands: false closes the escape a command can ask for by itself.

filesystem.allowWrite is ADDITIVE, not a fence — the SDK's own types call it "additional paths to allow writing within the sandbox", merged with the paths its permission rules already allow. Naming the root here adds it to what the run may write, which it needs because the root is not the process's own directory. It does not narrow anything, and reading it as the boundary would credit it with work enabled is doing.

And disallowedTools takes away the tools that would move the run OUT of the workspace — see RELOCATION_TOOLS. A confined directory the run has already left is not a boundary.

Setting settingSources or sandbox explicitly wins over the default — containment is a default, not a lock. disallowedTools merges instead, so a caller adding their own does not silently take the relocation ones away. contain: false turns all three off, which is what a trusted-workspace deployment wants and what nothing else should.

detached?​
detached?: boolean;

Run the agent as dispatched background work — the block a task board worker's dispatcher({ type: "task" }) targets, declared on the flow under task: { actions } and run in a child session. Default false: an in-session agent that keeps conversation state — the sdkSessionId resume handle and the sdkAgentRuns log — which is the behaviour every existing caller has.

This is the canonical explanation; everywhere else links here.

defineFlow refuses a dispatched entry whose block authors a sessionStateSchema (assertDispatchEntrySupported), because the block runs in a child session it may share with other rows, where two blocks choosing the same key with different shapes corrupt each other silently.

A background job is one run in one child session, so nothing on that path reads the resume handle back and the run log's job belongs to the child session's own item stream. true therefore suppresses three things together, and they are one decision rather than three: the declaration, the reads and writes that go with it (a value written under an undeclared key is not a smaller version of the same behaviour), and the SDK resume — the session provider is not consulted at all, so a custom provider cannot hand back a saved id that silently resumes a prior conversation.

Everything else is identical: the items the run emits, the handle it returns, and how failures surface. The one deliberate consequence is that a second task addressed to the same child session starts the agent fresh, while the child session's own item history continues as normal.

Inherited from​

ClaudeCodeAgentOptions.detached

disallowedTools?​
disallowedTools?: string[];

Disallowed tool names forwarded to the SDK.

Inherited from​

ClaudeCodeAgentOptions.disallowedTools

env?​
env?: Record<string, string | undefined>;

Environment variables for the run's own process. Default: unset, which hands the run only Claude Code's pass list, harnessEnv({ pass: CLAUDE_CODE_PASS }), read when each run starts. A server variable outside that list (a database URL, another service's key) never reaches the run, whose model has a shell.

Setting it REPLACES the environment rather than adding to it, which is the SDK's own behaviour. To pass more, build your own list: env: harnessEnv({ pass: [...CLAUDE_CODE_PASS, "MY_VAR"] }). Name PATH in it: the run's shell commands and git are found through it. Passing process.env hands the run the server's whole environment.

The pass list covers signing in with ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN only. A host that signs in any other way adds the names that way reads: ANTHROPIC_AUTH_TOKEN or ANTHROPIC_BASE_URL for a gateway, CLAUDE_CODE_USE_BEDROCK with its AWS_* variables, CLAUDE_CODE_USE_VERTEX with its GOOGLE_* / CLOUD_ML_REGION variables, and CLAUDE_CONFIG_DIR for a sign-in stored outside HOME.

Inherited from​

ClaudeCodeAgentOptions.env

exclude?​
exclude?: string[];

Accessor keys to skip during auto-discovery.

includePartialMessages?​
includePartialMessages?: boolean;

Whether to request partial-message deltas. Default: true.

Inherited from​

ClaudeCodeAgentOptions.includePartialMessages

maxTurns?​
maxTurns?: number;

Max turns forwarded to the SDK.

Inherited from​

ClaudeCodeAgentOptions.maxTurns

mcpTools?​
mcpTools?:
| ClaudeCodeMcpTools
| ((ctx) =>
| ClaudeCodeMcpTools
| Promise<ClaudeCodeMcpTools>);

Tools this process serves to the run, grouped by server name: a value, or a resolver called once per run with the run's context only (like cwd). Default: unset, which hands the SDK exactly today's options.

This is the canonical explanation; everywhere else links here.

Each entry becomes an MCP server inside this process, named by its key; the run calls its tools as mcp__<server>__<tool>. A tool is a name, a description, a JSON Schema for its input and a call function, so the option can't carry an address or headers: where a tool's work happens and what credential it uses stay with the host.

Set, even to {}, it is the run's whole MCP set: strictMcpConfig keeps out servers from .mcp.json, settings files and plugins, and disableClaudeAiConnectors keeps out the signed-in account's claude.ai connectors. If the run still reports a server it wasn't handed, a status item says so. The tools are allowed without asking; name one in disallowedTools to keep it out. Each server's close is called when the run ends, however it ends, and once when several servers share it. An abort while the resolver is still connecting stops the wait; what it answers afterwards is closed.

Inherited from​

ClaudeCodeAgentOptions.mcpTools

model?​
model?: string | HarnessResolver<string | null | undefined>;

Which model the run uses: a fixed id, or a resolver called once per invocation, like cwd and resume, so one block can run a different model for each run (each session of a host, say). Forwarded to the SDK as its model, on a fresh run and a resumed one alike.

null, "" and undefined from the resolver all mean "no model named": the SDK runs Claude Code's own default. The resolver is handed the context alone, never the prompt, for the reason cwd is.

Inherited from​

ClaudeCodeAgentOptions.model

name?​
name?: string;

Block name. Default "workspace-agent".

Overrides​

ClaudeCodeAgentOptions.name

onActivity?​
onActivity?: HarnessActivityHook;

Called with each completed assistant message and each tool call the run starts, so a host can say how the run is doing. Default: unset. Not awaited, and a throw is logged and swallowed.

Inherited from​

ClaudeCodeAgentOptions.onActivity

onErrored?​
onErrored?: (error, ctx) => void | Promise<void>;

Ran after this block's execution threw, with the error and the block's own context — the standard block lifecycle hook, forwarded.

Reachable only through this option because nothing else can supply it: a capability contributes resources, state and tools, never lifecycle hooks, so anything that has to run when a run FAILS has nowhere else to hook. Releasing something the run was holding is the case that made it necessary.

It does not swallow the error; the run still fails.

Parameters​
error​

Error

ctx​

HarnessCallbackContext

Returns​

void | Promise<void>

Inherited from​

ClaudeCodeAgentOptions.onErrored

onEvent?​
onEvent?: HarnessEventHook;

Called on every event the run sends, of any kind, so a host can tell a working run from a silent one. Not awaited, and a throw is logged and swallowed.

Inherited from​

ClaudeCodeAgentOptions.onEvent

onSession?​
onSession?: HarnessSessionHook;

Called the moment the SDK names the session this run is in, so a host can record the id it will later hand back through ClaudeCodeAgentOptions.resume. Default: unset.

Background path only, refused in-session for the reason resume is: the block already persists the id to session state there, and a second writer racing it is two owners of one field.

It fires DURING the run, before the next streamed message is consumed — not after it, and not from the returned handle. The distinction is the whole reason the hook exists: a run the host's deadline kills returns no handle at all, and a run that ends in a throw returns none either, so a host that only learned the id at the end has nothing to continue in exactly the case it wanted to. Called once per distinct session id rather than once per message, because every message carries one and the host's write is durable.

It is not a place to do work. Whatever it does happens inline on the stream, so a slow hook slows the run and a throwing one fails it.

Inherited from​

ClaudeCodeAgentOptions.onSession

onToolApproval?​
onToolApproval?: (req, ctx) =>
| ClaudeCodeToolApprovalDecision
| Promise<ClaudeCodeToolApprovalDecision>;

Optional approval seam. When set, it is adapted onto the SDK canUseTool callback: each tool call routes through it, and the decision is noted via a status item. When unset, HITL degrades to the SDK's own permissionMode. A tool in allowedTools is pre-allowed by the SDK and never reaches it. A held decision stops the turn with the call unrun, for a host that waits for a person outside the run (approveTools on a harness manager). The run's stop after a held call is that wait, not a failure: the run still throws its signal's reason, but leaves no error item.

Parameters​
req​

ClaudeCodeToolApprovalRequest

ctx​

HarnessCallbackContext

Returns​

| ClaudeCodeToolApprovalDecision | Promise<ClaudeCodeToolApprovalDecision>

Inherited from​

ClaudeCodeAgentOptions.onToolApproval

onUsage?​
onUsage?: HarnessUsageHook;

Called with each subscription usage window Claude Code reports during the run (its rate_limit_event), so a host can record how much of the subscription is left. Default: unset, and the events are dropped.

The report names claude-code, the window, when it was observed, when the run started, and the account the run is signed in as (its accountInfo() email, asked once at the first event; null when it names none). An event that names no window, as on an API key, is not reported.

Awaited like onSession, so no write lands after the run ends, but a throw is logged and swallowed: a usage write never fails the run. Unlike onSession, it is allowed in-session too: it owns no part of the conversation, so it races nothing.

Inherited from​

ClaudeCodeAgentOptions.onUsage

permissionMode?​
permissionMode?: string;

Permission mode forwarded to the SDK (HITL default behavior).

Inherited from​

ClaudeCodeAgentOptions.permissionMode

prompt?​
prompt?: (input, ctx) => string;

Derive the prompt from input/ctx. Default: input.prompt.

Parameters​
input​
prompt​

string

ctx​

HarnessCallbackContext

Returns​

string

Inherited from​

ClaudeCodeAgentOptions.prompt

recordPullRequests?​
recordPullRequests?: boolean;

Record each pull request the run opens in core's pull-request record (observed-pull-requests). Default true: the block declares the collection and starts core's recorder. A gh pr create or a create-pull-request tool whose result names a pull request is a row; a gh pr view is not. false declares nothing and records nothing.

Inherited from​

ClaudeCodeAgentOptions.recordPullRequests

recordWork?​
recordWork?: boolean;

Record what the run DID, alongside the items that record what it said. Default false, which is byte-identical to the behaviour every existing caller has: nothing recorded, no resources declared.

This is the canonical explanation; everywhere else links here.

Set true and the block declares three session-scoped resource collections and writes into them as the run goes:

  • observed-file-ops — one entry per path the run's file-writing and file-editing tools touched: how, when, and how the attempt settled. Not the contents.
  • observed-plan — one entry per item on the run's own to-do list, carrying its wording and its current and previous status. Deliberately NOT the work queue that dispatched the run, so a run that decides to do five more things cannot start five more jobs by writing a to-do list.
  • observed-gaps — one entry per mutation the recorder recognised and could not record, so a missing row is never confused with a mutation that never happened.

All three are readable over the resource route that already ships, keyed under the run's own request id so a child session reused across runs answers "what did this run do" rather than "what has this child session ever done".

What the file record is, precisely. It is a log of the file operations the run's file TOOLS performed, not an index of everything that changed on disk. A run that edits a file through the shell — a sed -i, a redirect, a mv, a formatter — performs no file-tool call, so nothing is recorded and the file does not appear.

Recording never fails the run: anything the recorder cannot handle is skipped, written to observed-gaps, and noted as a status item. The gap ROW is the durable half — a status note dedupes on its own message and renders into a latest-wins slot, so two identical skips collapse to one.

Inherited from​

ClaudeCodeAgentOptions.recordWork

resolveClaudeAgent?​
resolveClaudeAgent?: ResolveClaudeCodeAgent;

Host hook resolving the SDK query. Default: lazy SDK import.

Inherited from​

ClaudeCodeAgentOptions.resolveClaudeAgent

resume?​
resume?: HarnessResolver<string | null | undefined>;

Which conversation this background run continues. Default: unset — a fresh session, byte for byte today's detached: true behaviour.

Background path only (detached: true), and set it in-session and this factory throws. In-session the block's own conversation state already owns continuity — it reads the last run's id off session state and resumes it — so an explicit id would be a second owner of one decision, and which of the two won would depend on the order two lines happen to run in. Refused at construction rather than resolved and ignored, because a host that asked for a resume and silently did not get one has no way to find out.

A resolver, not a value, for the reason ClaudeCodeAgentOptions.cwd gives: one flow build serves many runs, and the session to continue is per run. It is called once per invocation, before query.

null and "" both mean "start fresh" and reach the SDK as no resume at all. That matters more than it reads: a host's state carries null on the first attempt, an over-eager ?? "" produces the other, and an empty resume key is a value the SDK is entitled to interpret.

Pair it with ClaudeCodeAgentOptions.onSession. A host that resumes without recording the id the run confirms cannot continue a run that died mid-flight — which is the case resume mostly exists for.

An option and never a field on the block's input, for the same reason cwd is one: the input schema is model-facing through the agent capability's tool preset, so a session id reachable from it is a session a model could choose to continue.

Inherited from​

ClaudeCodeAgentOptions.resume

root​
root: HarnessResolver<string>;

Where the projection lands on disk, resolved once per run.

A resolver rather than a constant, and not merely by convention: two runs sharing one directory would each hydrate over the other's files and flush the result back. Give each run its own.

Handed the context and nothing else, like cwd, sandbox and resume on the agent block, and for the same reason. This used to also receive the run's input — whose prompt is the one value a caller, or a model holding this capability's agent as a tool, controls. A host that could read it could be written, in ordinary-looking code, to put the run's workspace wherever the caller asked. HarnessResolver in @flow-state-dev/core/types carries the full argument; this is the same hazard cwd has, under a different name.

sandbox?​
sandbox?:
| ClaudeCodeSandboxSettings
| ((ctx) =>
| ClaudeCodeSandboxSettings
| Promise<ClaudeCodeSandboxSettings>);

The SDK's sandbox settings, forwarded verbatim. Default: unset — no sandbox, as today.

A value or a resolver, and the resolver is not a convenience. The settings that confine a run to its own directory name that directory — filesystem.allowWrite is a list of paths — and the directory is per run while one flow build serves many. A build-time constant can express "sandboxed" but not "sandboxed to THIS run's workspace", which is the only form of it that contains anything. Same reason cwd is a resolver.

The resolver is handed the context alone, like cwd and resume and for the sharper version of their reason: these settings are the FENCE, and a fence derived from the prompt is a fence the caller drew. See HarnessResolver in @flow-state-dev/core/types, which carries the argument once.

Loosely typed for the same reason agents is: this package treats the Agent SDK as an optional peer, so its types are not imported here. An open object rather than unknown, because unknown | fn collapses to unknown and the resolver form — the one that matters — would then get no contextual typing and its parameter would be an implicit any.

Inherited from​

ClaudeCodeAgentOptions.sandbox

sessionProvider?​
sessionProvider?: BindingProvider<ClaudeCodeSession>;

Session-continuity provider. Default: resume-by-id provider.

Inherited from​

ClaudeCodeAgentOptions.sessionProvider

settings?​
settings?: Record<string, unknown>;

Settings for this run, in Claude Code's settings.json shape, handed to the SDK on top of { disableAllHooks: true }. Default: unset, which hands the SDK only that: every hook off.

They sit above every source settingSources loads, so a key here beats the same key in the repository's .claude/settings.json. That is why hooks are off by default: a repository's hooks run by themselves and show in no transcript, and a run that loads "project" settings (the default loads all three sources) would otherwise run whatever hooks the repository it works in declares. A host that trusts the repository sets settingSources: ["project"] to load its CLAUDE.md and skills, and the hooks stay off. A host that wants them passes settings: { disableAllHooks: false }; a key given here always wins.

With mcpTools set, the run's settings also carry disableClaudeAiConnectors: true, whatever this says: mcpTools is the run's whole MCP set. The object is not modified.

Inherited from​

ClaudeCodeAgentOptions.settings

settingSources?​
settingSources?: ClaudeCodeSettingSource[];

Which filesystem settings this run loads — "user", "project", "local". Default: unset, which loads all three, exactly as today.

This is the canonical explanation; everywhere else links here.

"project" is the load-bearing one: it is what makes the run read CLAUDE.md and .claude/settings.json out of its working directory. When that directory is one the server assembled from an application's own resources, its contents are caller-controllable input, and a run reading configuration out of them means callers configure the agent. Pass [] to load none.

Left unset by default deliberately: this option is the plumbing, not the policy. Nothing changes for a caller who does not set it.

Inherited from​

ClaudeCodeAgentOptions.settingSources

systemPrompt?​
systemPrompt?: ClaudeCodeSystemPrompt;

The system prompt the run starts from, forwarded to the SDK as given; the shapes are on ClaudeCodeSystemPrompt. Omitted, the run starts from Claude Code's own prompt, the one the claude CLI uses.

No prompt makes the agent keep a to-do list. recordWork's plan half fills only when the agent chooses to use its to-do tools, which every run is offered (see allowedTools).

Inherited from​

ClaudeCodeAgentOptions.systemPrompt

uses?​
uses?: UsesSlot;

Capabilities installed on the block this factory returns — the same uses slot any other block takes, forwarded to handler().

Without it, a caller who wants the agent to carry a capability has to stop using this factory and hand-roll the block. That is the whole reason the slot is here rather than a wrapper around it.

Inherited from​

ClaudeCodeAgentOptions.uses


ListClaudeCodeModelsOptions​

Options for listClaudeCodeModels.

Properties​

env​
env: Record<string, string>;

The environment Claude Code is started with. Pass the one the run gets.

importSdk?​
importSdk?: ClaudeCodeSdkImporter;

How the SDK module is loaded. A seam for tests; the default imports the installed SDK.

timeoutMs?​
timeoutMs?: number;

How long to wait for Claude Code's answer. Default 10 000 ms.


ProbeClaudeCodeAccountOptions​

Options for probeClaudeCodeAccount.

Extended by​

Properties​

env​
env: Record<string, string>;

The environment Claude Code is started with. Pass the one the run gets (for example harnessEnv({ pass })), so a credential the run can't see isn't counted.

importSdk?​
importSdk?: ClaudeCodeSdkImporter;

How the SDK module is loaded. A seam for tests; the default imports the installed SDK.

signal?​
signal?: AbortSignal;

Stops waiting and closes Claude Code when it aborts; the answer is then none, as on a timeout.

timeoutMs?​
timeoutMs?: number;

How long to wait for Claude Code's answer before reading it as none. Default 10 000 ms.


ResolvedClaudeCodeAgent​

What a ResolveClaudeCodeAgent returns: the SDK's query entry point.

Properties​

query​
query: ClaudeCodeQuery;

Type Aliases​

ClaudeCodeAccountProbe​

type ClaudeCodeAccountProbe =
| {
apiKeySource?: string;
email?: string;
status: "account";
subscriptionType?: string;
tokenSource?: string;
}
| {
reason: string;
status: "none";
unanswered?: true;
}
| {
reason: string;
status: "sdk-missing";
};

What probeClaudeCodeAccount found.

Union Members​

Type Literal​
{
apiKeySource?: string;
email?: string;
status: "account";
subscriptionType?: string;
tokenSource?: string;
}

A credential source came back: the SDK's apiKeySource, its tokenSource, or a sign-in (email, subscriptionType). A subscription login (the keychain or ~/.claude) is reported by the last pair alone.


Type Literal​
{
reason: string;
status: "none";
unanswered?: true;
}

No credential source, or no answer. reason says which, for a message to a person; unanswered is set when Claude Code timed out, was stopped, or failed, so nothing is known about the credential.


Type Literal​
{
reason: string;
status: "sdk-missing";
}

@anthropic-ai/claude-agent-sdk could not be loaded. reason carries the load error.


ClaudeCodeCanUseTool​

type ClaudeCodeCanUseTool = (toolName, input, extra) => Promise<ClaudeCodeSdkToolDecision>;

The SDK's canUseTool callback shape (HITL seam target).

Parameters​

toolName​

string

input​

unknown

extra​
signal?​

AbortSignal

suggestions?​

unknown

Returns​

Promise<ClaudeCodeSdkToolDecision>


ClaudeCodeFileOpKind​

type ClaudeCodeFileOpKind = "created" | "edited";

How a file tool touched a path.


ClaudeCodeMcpTools​

type ClaudeCodeMcpTools = Record<string, ClaudeCodeMcpToolServer>;

The tools a run is handed, grouped by server name.


ClaudeCodeQuery​

type ClaudeCodeQuery = (args) => AsyncIterable<ClaudeCodeSdkMessage>;

The SDK query() function shape this package calls. Structural so a scripted fake satisfies it in tests without importing the SDK. Returns an async iterable of ClaudeCodeSdkMessage.

Parameters​

args​
options?​

ClaudeCodeQueryOptions

prompt​

string | AsyncIterable<unknown>

Returns​

AsyncIterable<ClaudeCodeSdkMessage>


ClaudeCodeResultSubtype​

type ClaudeCodeResultSubtype =
| "success"
| "error_max_turns"
| "error_max_budget_usd"
| "error_during_execution"
| "error_max_structured_output_retries";

Terminal result subtype reported by the SDK's result message.


ClaudeCodeSandboxSettings​

type ClaudeCodeSandboxSettings = Record<string, unknown>;

The Agent SDK's sandbox settings, as this package sees them.

An open object, not the SDK's own type: the Agent SDK is an optional peer here, so its types are not imported. The settings are forwarded verbatim, and the SDK validates them.


ClaudeCodeSdkImporter​

type ClaudeCodeSdkImporter = () => Promise<{
query?: unknown;
}>;

How the resolver loads the SDK module. Defaults to a lazy dynamic import; overridable so the absent-SDK path is testable without depending on whether the optional peer dependency happens to be installed.

Returns​

Promise<{ query?: unknown; }>


ClaudeCodeSdkMessage​

type ClaudeCodeSdkMessage =
| {
attempt?: number;
description?: string;
last_tool_name?: string;
max_retries?: number;
mcp_servers?: object[];
model?: string;
retry_delay_ms?: number;
session_id?: string;
subtype?: "init" | "compact_boundary" | string;
summary?: string;
type: "system";
}
| {
message?: {
content?: (
| {
text: string;
type: "text";
}
| {
thinking: string;
type: "thinking";
}
| {
id: string;
input?: unknown;
name: string;
type: "tool_use";
})[];
id?: string;
usage?: | {
cache_creation_input_tokens?: number | null;
cache_read_input_tokens?: number | null;
input_tokens?: number;
output_tokens?: number;
}
| null;
};
parent_tool_use_id?: string | null;
session_id?: string;
type: "assistant";
}
| {
message?: {
content?: object[];
};
parent_tool_use_id?: string | null;
session_id?: string;
tool_use_result?: unknown;
type: "user";
}
| {
event?: {
delta?: {
partial_json?: string;
text?: string;
thinking?: string;
type?: "text_delta" | "thinking_delta" | "input_json_delta" | string;
};
type?: string;
};
parent_tool_use_id?: string | null;
session_id?: string;
type: "stream_event";
}
| {
rate_limit_info?: unknown;
session_id?: string;
type: "rate_limit_event";
}
| {
errors?: string[];
is_error?: boolean;
modelUsage?: | Record<string, {
cacheCreationInputTokens?: number;
cacheReadInputTokens?: number;
inputTokens?: number;
outputTokens?: number;
}>
| null;
result?: string;
session_id?: string;
subtype?: ClaudeCodeResultSubtype | string;
total_cost_usd?: number | null;
type: "result";
usage?: | {
cache_creation_input_tokens?: number | null;
cache_read_input_tokens?: number | null;
input_tokens?: number;
output_tokens?: number;
}
| null;
};

Structural subset of the SDK's SDKMessage union — only the fields this package reads. Declared locally so ./sdk never statically imports the SDK's types (the SDK is an optional peer dependency). Discriminated by type.

Union Members​

Type Literal​
{
attempt?: number;
description?: string;
last_tool_name?: string;
max_retries?: number;
mcp_servers?: object[];
model?: string;
retry_delay_ms?: number;
session_id?: string;
subtype?: "init" | "compact_boundary" | string;
summary?: string;
type: "system";
}
attempt?​
attempt?: number;

On api_retry: the failed call's retry attempt, its limit and the wait before it.

description?​
description?: string;

On task_progress: what a sub-agent is on.

last_tool_name?​
last_tool_name?: string;
max_retries?​
max_retries?: number;
mcp_servers?​
mcp_servers?: object[];

On init: every MCP server the run connected to, or tried to.

model?​
model?: string;

On init: the model the run uses, as Claude Code names it.

retry_delay_ms?​
retry_delay_ms?: number;
session_id?​
session_id?: string;
subtype?​
subtype?: "init" | "compact_boundary" | string;
summary?​
summary?: string;
type​
type: "system";

Type Literal​
{
message?: {
content?: (
| {
text: string;
type: "text";
}
| {
thinking: string;
type: "thinking";
}
| {
id: string;
input?: unknown;
name: string;
type: "tool_use";
})[];
id?: string;
usage?: | {
cache_creation_input_tokens?: number | null;
cache_read_input_tokens?: number | null;
input_tokens?: number;
output_tokens?: number;
}
| null;
};
parent_tool_use_id?: string | null;
session_id?: string;
type: "assistant";
}
message?​
message?: object;
message.content?​
content?: (
| {
text: string;
type: "text";
}
| {
thinking: string;
type: "thinking";
}
| {
id: string;
input?: unknown;
name: string;
type: "tool_use";
})[];
message.id?​
id?: string;

The model message's id. A parallel tool call splits one model message into several assistant messages that share it, each repeating its usage.

message.usage?​
usage?:
| {
cache_creation_input_tokens?: number | null;
cache_read_input_tokens?: number | null;
input_tokens?: number;
output_tokens?: number;
}
| null;

The model message's token usage, repeated on every assistant message that shares its id.

parent_tool_use_id?​
parent_tool_use_id?: string | null;

The container tool-use id when this message was produced inside a sub-agent (Task/Agent) loop; null/absent at the top level. Used to nest the sub-agent's own assistant/tool items under its container.

session_id?​
session_id?: string;
type​
type: "assistant";

Type Literal​
{
message?: {
content?: object[];
};
parent_tool_use_id?: string | null;
session_id?: string;
tool_use_result?: unknown;
type: "user";
}
message?​
message?: object;
message.content?​
content?: object[];
parent_tool_use_id?​
parent_tool_use_id?: string | null;
session_id?​
session_id?: string;
tool_use_result?​
tool_use_result?: unknown;

The tool's full structured Output object — a MESSAGE-level sibling of the content blocks below, not a field on one. The two carry different things and must not be conflated: content[].tool_result.content is the prose string shown to the model ("File created successfully at: …"), while this carries the declared Output (filePath, structuredPatch, task.id, …). Optional and untyped on purpose — it is absent on older messages and its shape is the vendor's, so every read of it is a tolerated probe rather than a contract.

type​
type: "user";

Type Literal​
{
event?: {
delta?: {
partial_json?: string;
text?: string;
thinking?: string;
type?: "text_delta" | "thinking_delta" | "input_json_delta" | string;
};
type?: string;
};
parent_tool_use_id?: string | null;
session_id?: string;
type: "stream_event";
}

Type Literal​
{
rate_limit_info?: unknown;
session_id?: string;
type: "rate_limit_event";
}
rate_limit_info?​
rate_limit_info?: unknown;
session_id?​
session_id?: string;
type​
type: "rate_limit_event";

Sent when the subscription's limits change; read by onUsage (./usage), never translated to an item.


Type Literal​
{
errors?: string[];
is_error?: boolean;
modelUsage?: | Record<string, {
cacheCreationInputTokens?: number;
cacheReadInputTokens?: number;
inputTokens?: number;
outputTokens?: number;
}>
| null;
result?: string;
session_id?: string;
subtype?: ClaudeCodeResultSubtype | string;
total_cost_usd?: number | null;
type: "result";
usage?: | {
cache_creation_input_tokens?: number | null;
cache_read_input_tokens?: number | null;
input_tokens?: number;
output_tokens?: number;
}
| null;
}
errors?​
errors?: string[];

Present only on error-subtype results (replaces result).

is_error?​
is_error?: boolean;

The SDK's failure flag. On a success subtype it marks a turn that ended on an API error, with the error text in result, so it is read beside the subtype, never instead of it.

modelUsage?​
modelUsage?:
| Record<string, {
cacheCreationInputTokens?: number;
cacheReadInputTokens?: number;
inputTokens?: number;
outputTokens?: number;
}>
| null;

The whole query's tokens by model: sub-agents and auxiliary calls included.

result?​
result?: string;

Present only on the success result variant.

session_id?​
session_id?: string;
subtype?​
subtype?: ClaudeCodeResultSubtype | string;
total_cost_usd?​
total_cost_usd?: number | null;
type​
type: "result";
usage?​
usage?:
| {
cache_creation_input_tokens?: number | null;
cache_read_input_tokens?: number | null;
input_tokens?: number;
output_tokens?: number;
}
| null;

NonNullableUsage carries input_tokens/output_tokens (+ cache). Main agent loop only.


ClaudeCodeSdkToolDecision​

type ClaudeCodeSdkToolDecision =
| {
behavior: "allow";
updatedInput: unknown;
}
| {
behavior: "deny";
interrupt?: boolean;
message: string;
};

A tool-approval decision in the SDK's canUseTool vocabulary.


ClaudeCodeSettingSource​

type ClaudeCodeSettingSource = "user" | "project" | "local";

A filesystem settings source the run may load from.

Declared here rather than imported from the SDK so the option is usable — and typo-proof — without the optional peer installed.


ClaudeCodeSystemPrompt​

type ClaudeCodeSystemPrompt =
| string
| string[]
| {
[field: string]: unknown;
append?: string;
preset: "claude_code";
type: "preset";
};

The system prompt a run starts from, in the Agent SDK's own shapes.

  • a string replaces Claude Code's own prompt; "" starts with none at all
  • a string array is the same custom prompt, split into blocks
  • { type: "preset", preset: "claude_code" } is Claude Code's own prompt, the one the claude CLI uses; append adds text after it

Declared here rather than imported, like ClaudeCodeSettingSource, because the SDK is an optional peer. The preset object stays open so a field the SDK adds later passes through: the value is forwarded verbatim and the SDK validates it.


ClaudeCodeToolApprovalDecision​

type ClaudeCodeToolApprovalDecision =
| {
decision: "allow";
updatedInput?: unknown;
}
| {
decision: "deny";
message?: string;
}
| {
decision: "held";
message?: string;
};

A decision returned by ClaudeCodeAgentOptions.onToolApproval.

  • allow runs the call, with updatedInput when given.
  • deny refuses it; the model is told, with message, and the turn goes on.
  • held refuses it for now, because a person decides it outside this run (a harness manager stops the run and resumes its session after the answer). The call does not run, the turn stops (the SDK's interrupt), and it is recorded as waiting on a person, not as denied.

ClaudeCodeWorkspaceCollectionSpec​

type ClaudeCodeWorkspaceCollectionSpec =
| string
| {
key: string;
writable?: boolean;
};

A collection selection entry. A bare string is { key, writable: true }.


ReadClaudeCodeUsageOptions​

type ReadClaudeCodeUsageOptions = ProbeClaudeCodeAccountOptions & object;

Options for readClaudeCodeUsage: the probe's.

Type Declaration​

probe?​
probe?: (options) => Promise<ClaudeCodeAccountProbe>;

How the account is asked for. A seam for tests; default probeClaudeCodeAccount.

Parameters​
options​

ProbeClaudeCodeAccountOptions

Returns​

Promise<ClaudeCodeAccountProbe>


ResolveClaudeCodeAgent​

type ResolveClaudeCodeAgent = (ctx) =>
| ResolvedClaudeCodeAgent
| Promise<ResolvedClaudeCodeAgent>;

Host hook resolving the SDK query for a given block invocation. Accepts the block context loosely so a fully parameterized execute context passes without a cast at the call site.

Parameters​

ctx​

BlockContext<any, any, any, any, any, any, any, any, any>

Returns​

| ResolvedClaudeCodeAgent | Promise<ResolvedClaudeCodeAgent>

Variables​

CLAUDE_CODE_AGENT_RUNS_KEY​

const CLAUDE_CODE_AGENT_RUNS_KEY: "sdkAgentRuns";

Session-state key under which run handles accumulate.


CLAUDE_CODE_FILE_OPS​

const CLAUDE_CODE_FILE_OPS: "observed-file-ops";

Accessor key AND storage prefix for the observed file operations. The two are deliberately the same string: the HTTP resource route addresses a collection by its accessor key in flow.resources, while the store keys rows by the pattern prefix, so keeping them equal means one name appears in the URL, in ctx.resources, and in the storage key.


CLAUDE_CODE_GAPS​

const CLAUDE_CODE_GAPS: "observed-gaps";

Accessor key AND storage prefix for the mutations the recorder could not record.


CLAUDE_CODE_HARNESS​

const CLAUDE_CODE_HARNESS: "claude-code" = "claude-code";

The usage record's name for Claude Code.


CLAUDE_CODE_PASS​

const CLAUDE_CODE_PASS: readonly ["PATH", "HOME", "USER", "SHELL", "TMPDIR", "HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy", "ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "NODE_EXTRA_CA_CERTS"];

The only variables of the server's environment a Claude Code run needs, for harnessEnv({ pass: CLAUDE_CODE_PASS }) from @flow-state-dev/core/harness, and what claudeCodeAgent hands a run whose host sets no env. A run given the server's whole process.env would hold every key, token and connection string in it, and its model has a shell.

Core's HARNESS_BASE_PASS and this harness's own names: PATH (its shell commands and git are found through it), HOME, USER and SHELL (its sign-in, git identity and Bash tool), TMPDIR, the two ways it can be given a credential (ANTHROPIC_API_KEY, CLAUDE_CODE_OAUTH_TOKEN), and the proxy and CA settings a proxied network needs. The proxy names come in both cases because the tools a run shells out to disagree: curl reads only lowercase http_proxy, git and most others take either.

It filters what a run starts with, not what it can read: a command the run starts as the server's OS user can still read the server's own environment (on Linux, from /proc). Pass the same environment to probeClaudeCodeAccount, listClaudeCodeModels and readClaudeCodeUsage, so they see the account the run sees. A host that needs more passes its own list.


CLAUDE_CODE_SESSION_ID_KEY​

const CLAUDE_CODE_SESSION_ID_KEY: "sdkSessionId";

Session-state key holding the SDK session id to resume across requests.


CLAUDE_CODE_SIGN_IN_REMEDY​

const CLAUDE_CODE_SIGN_IN_REMEDY: "Sign in with `claude`, or set ANTHROPIC_API_KEY" = "Sign in with `claude`, or set ANTHROPIC_API_KEY";

What the user does when Claude Code has no credential.


CLAUDE_CODE_SOURCE​

const CLAUDE_CODE_SOURCE: "claude-code/sdk";

This door's <package>/<door> name, the convention every writer of a harness handle's source follows.


CLAUDE_CODE_WORKSPACE_OUTCOMES​

const CLAUDE_CODE_WORKSPACE_OUTCOMES: "workspace-outcomes";

Accessor key AND storage prefix. One string deliberately: the resource route addresses a collection by its accessor key while the store keys rows by the pattern prefix, so the same name appears in the URL, in ctx.resources, and in storage.


claudeCodeAgentHandleSchema​

const claudeCodeAgentHandleSchema: z.ZodObject<object & object, "strip", z.ZodTypeAny, {
cost: | {
basis: "estimated" | "reported";
usd: number;
}
| null;
dispatchedAt: number;
finalMessage: string | null;
outcome: "failed" | "finished" | "stopped-at-limit" | null;
resultSubtype: | "error_during_execution"
| "error_max_budget_usd"
| "error_max_structured_output_retries"
| "error_max_turns"
| "success"
| null;
sessionId: string | null;
source: "claude-code/sdk";
status: "completed" | "errored" | "running";
toolsObserved: string[];
url: string | null;
usage: | {
inputTokens: number;
outputTokens: number;
}
| null;
}, {
cost?: | {
basis: "estimated" | "reported";
usd: number;
}
| null;
dispatchedAt: number;
finalMessage?: string | null;
outcome?: "failed" | "finished" | "stopped-at-limit" | null;
resultSubtype: | "error_during_execution"
| "error_max_budget_usd"
| "error_max_structured_output_retries"
| "error_max_turns"
| "success"
| null;
sessionId: string | null;
source: "claude-code/sdk";
status: "completed" | "errored" | "running";
toolsObserved: string[];
url: string | null;
usage?: | {
inputTokens: number;
outputTokens: number;
}
| null;
}>;

Runtime validator for ClaudeCodeAgentHandle.

A handle persisted before outcome/cost existed picks them up as null from the neutral schema's defaults.

costUsd is gone and is not rejected. It was a dual carried beside the neutral cost for one release, while the run manager still read it; the manager reads cost now, so nothing reads the dual. Handles persisted with it still parse — zod strips the unknown key rather than failing — which is enough for a field that was only ever a copy of one still here.


claudeCodeFileOpsCollection​

const claudeCodeFileOpsCollection: object & ResourceCollectionConfig & object;

**, not *: a key carries the run id and then a whole file path, so it has many segments. prefetchMode: "lazy" is the other half of that — rows are namespaced per run and a child session is reused across runs, so an eager collection would bulk-load every historical row of every previous run before the current one touched a single key. The recorder only ever upserts by exact key, which the lazy accessor serves with a single-key read; list()/count() are what would trigger a full-prefix load, so the recorder must never call them.

Type Declaration​

client​
readonly client: object;
client.expose​
readonly expose: readonly ["lastKind", "outcome", "lastTouchedAt", "appliedCount"];
client.state​
readonly state: object;
client.state.read​
readonly read: true;
pattern​
readonly pattern: "observed-file-ops/**";
prefetchMode​
readonly prefetchMode: "lazy";
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: z.ZodObject<{
appliedCount: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
lastKind: z.ZodDefault<z.ZodNullable<z.ZodEnum<["created", "edited"]>>>;
lastTouchedAt: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
outcome: z.ZodDefault<z.ZodNullable<z.ZodEnum<["pending", "applied", "failed"]>>>;
}, "strip", z.ZodTypeAny, {
appliedCount: number | null;
lastKind: "created" | "edited" | null;
lastTouchedAt: number | null;
outcome: "applied" | "failed" | "pending" | null;
}, {
appliedCount?: number | null;
lastKind?: "created" | "edited" | null;
lastTouchedAt?: number | null;
outcome?: "applied" | "failed" | "pending" | null;
}>;
__brand​
readonly __brand: "ResourceCollection";
ClientType​
ClientType: Pick<{
appliedCount: number | null;
lastKind: "created" | "edited" | null;
lastTouchedAt: number | null;
outcome: "applied" | "failed" | "pending" | null;
}, "appliedCount" | "lastKind" | "lastTouchedAt" | "outcome">;
StateType​
StateType: object;
StateType.appliedCount​
appliedCount: number | null;
StateType.lastKind​
lastKind: "created" | "edited" | null;
StateType.lastTouchedAt​
lastTouchedAt: number | null;
StateType.outcome​
outcome: "applied" | "failed" | "pending" | null;

claudeCodeFileOpStateSchema​

const claudeCodeFileOpStateSchema: z.ZodObject<{
appliedCount: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
lastKind: z.ZodDefault<z.ZodNullable<z.ZodEnum<["created", "edited"]>>>;
lastTouchedAt: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
outcome: z.ZodDefault<z.ZodNullable<z.ZodEnum<["pending", "applied", "failed"]>>>;
}, "strip", z.ZodTypeAny, {
appliedCount: number | null;
lastKind: "created" | "edited" | null;
lastTouchedAt: number | null;
outcome: "applied" | "failed" | "pending" | null;
}, {
appliedCount?: number | null;
lastKind?: "created" | "edited" | null;
lastTouchedAt?: number | null;
outcome?: "applied" | "failed" | "pending" | null;
}>;

One observed file operation, keyed by <runId>/<canonical path>.

Every field is nullable with a null default so a row written by an older or newer shape still parses instead of throwing inside a recorder that is required never to break the run.


claudeCodeGapsCollection​

const claudeCodeGapsCollection: object & ResourceCollectionConfig & object;

One row per mutation the recorder RECOGNISED and then could not record faithfully — whether it recorded nothing, or recorded it under a key the harness disagrees with.

Without this a skip is indistinguishable from a mutation that never happened, which is the exact blindness the rest of this feature exists to remove: a reader comparing the run's tool activity against the file record could see a Write with no matching row and have no way to tell "we lost it" from "we saw it and could not key it".

Keyed by run id and an ordinal, deliberately never by the failing value. The commonest skip is a path that cannot be normalized into a key — so keying this record by the path would fail in exactly the case it exists to cover. The path goes in the STATE instead, where a control character is just a character. The ordinal is zero-padded so the route's lexicographic key order is also chronological order.

One row per gap rather than a count plus a capped reason list: a row per event needs no cap policy, no truncation flag, and no array that grows inside a single state blob — and the count is rows.length.

A status note is emitted too, but it cannot be the record. ctx.emit.status dedupes on the message string and renders into a single latest-wins slot, so two identical skips collapse to one, and reading a gap back out of prose is the substring-grading mistake this codebase keeps paying for.

Type Declaration​

client​
readonly client: object;
client.expose​
readonly expose: readonly ["kind", "reason", "rawPath", "at"];
client.state​
readonly state: object;
client.state.read​
readonly read: true;
pattern​
readonly pattern: "observed-gaps/**";
prefetchMode​
readonly prefetchMode: "lazy";
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: z.ZodObject<{
at: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
kind: z.ZodDefault<z.ZodNullable<z.ZodEnum<["file", "plan", "run"]>>>;
rawPath: z.ZodDefault<z.ZodNullable<z.ZodString>>;
reason: z.ZodDefault<z.ZodNullable<z.ZodString>>;
}, "strip", z.ZodTypeAny, {
at: number | null;
kind: "file" | "plan" | "run" | null;
rawPath: string | null;
reason: string | null;
}, {
at?: number | null;
kind?: "file" | "plan" | "run" | null;
rawPath?: string | null;
reason?: string | null;
}>;
__brand​
readonly __brand: "ResourceCollection";
ClientType​
ClientType: Pick<{
at: number | null;
kind: "file" | "plan" | "run" | null;
rawPath: string | null;
reason: string | null;
}, "at" | "kind" | "rawPath" | "reason">;
StateType​
StateType: object;
StateType.at​
at: number | null;
StateType.kind​
kind: "file" | "plan" | "run" | null;
StateType.rawPath​
rawPath: string | null;
StateType.reason​
reason: string | null;

claudeCodeSessionStateSchema​

const claudeCodeSessionStateSchema: z.ZodObject<{
sdkAgentRuns: z.ZodDefault<z.ZodArray<z.ZodObject<object & object, "strip", z.ZodTypeAny, {
cost: | {
basis: "estimated" | "reported";
usd: number;
}
| null;
dispatchedAt: number;
finalMessage: string | null;
outcome: "failed" | "finished" | "stopped-at-limit" | null;
resultSubtype: | "error_during_execution"
| "error_max_budget_usd"
| "error_max_structured_output_retries"
| "error_max_turns"
| "success"
| null;
sessionId: string | null;
source: "claude-code/sdk";
status: "completed" | "errored" | "running";
toolsObserved: string[];
url: string | null;
usage: | {
inputTokens: number;
outputTokens: number;
}
| null;
}, {
cost?: | {
basis: "estimated" | "reported";
usd: number;
}
| null;
dispatchedAt: number;
finalMessage?: string | null;
outcome?: "failed" | "finished" | "stopped-at-limit" | null;
resultSubtype: | "error_during_execution"
| "error_max_budget_usd"
| "error_max_structured_output_retries"
| "error_max_turns"
| "success"
| null;
sessionId: string | null;
source: "claude-code/sdk";
status: "completed" | "errored" | "running";
toolsObserved: string[];
url: string | null;
usage?: | {
inputTokens: number;
outputTokens: number;
}
| null;
}>, "many">>;
sdkSessionId: z.ZodDefault<z.ZodNullable<z.ZodString>>;
}, "strip", z.ZodTypeAny, {
sdkAgentRuns: object[];
sdkSessionId: string | null;
}, {
sdkAgentRuns?: object[];
sdkSessionId?: string | null;
}>;

Session-state schema the agent block declares, reads, and appends to.


claudeCodeWorkRecorderResources​

const claudeCodeWorkRecorderResources: Record<string, DeclaredResourceEntry>;

The resource map the agent block and the capability both declare when recordWork is on. One object so the two declaration sites cannot drift.

Typed as the widened entry map rather than left to const inference on purpose: a literal type here would narrow the agent block's ctx.resources to these two accessors, and every helper that takes a plain BlockContext would stop accepting that context. The recorder reads the two refs by name at run time anyway, so the narrower type buys nothing.


claudeCodeWorkspaceOutcomesCollection​

const claudeCodeWorkspaceOutcomesCollection: object & ResourceCollectionConfig & object;

See CLAUDE_CODE_WORKSPACE_OUTCOMES for why the key and prefix are one string.

Type Declaration​

client​
readonly client: object;
client.expose​
readonly expose: readonly ["kind", "path", "base", "theirs", "ours", "at"];
client.state​
readonly state: object;
client.state.read​
readonly read: true;
pattern​
readonly pattern: "workspace-outcomes/**";
prefetchMode​
readonly prefetchMode: "lazy";
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: z.ZodObject<{
at: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
base: z.ZodDefault<z.ZodNullable<z.ZodString>>;
kind: z.ZodDefault<z.ZodNullable<z.ZodEnum<["orphan", "conflict", "contested"]>>>;
ours: z.ZodDefault<z.ZodNullable<z.ZodString>>;
path: z.ZodDefault<z.ZodNullable<z.ZodString>>;
theirs: z.ZodDefault<z.ZodNullable<z.ZodString>>;
}, "strip", z.ZodTypeAny, {
at: number | null;
base: string | null;
kind: "conflict" | "contested" | "orphan" | null;
ours: string | null;
path: string | null;
theirs: string | null;
}, {
at?: number | null;
base?: string | null;
kind?: "conflict" | "contested" | "orphan" | null;
ours?: string | null;
path?: string | null;
theirs?: string | null;
}>;
__brand​
readonly __brand: "ResourceCollection";
ClientType​
ClientType: Pick<{
at: number | null;
base: string | null;
kind: "conflict" | "contested" | "orphan" | null;
ours: string | null;
path: string | null;
theirs: string | null;
}, "at" | "base" | "kind" | "ours" | "path" | "theirs">;
StateType​
StateType: object;
StateType.at​
at: number | null;
StateType.base​
base: string | null;
StateType.kind​
kind: "conflict" | "contested" | "orphan" | null;
StateType.ours​
ours: string | null;
StateType.path​
path: string | null;
StateType.theirs​
theirs: string | null;

claudeCodeWorkspaceOutcomeStateSchema​

const claudeCodeWorkspaceOutcomeStateSchema: z.ZodObject<{
at: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
base: z.ZodDefault<z.ZodNullable<z.ZodString>>;
kind: z.ZodDefault<z.ZodNullable<z.ZodEnum<["orphan", "conflict", "contested"]>>>;
ours: z.ZodDefault<z.ZodNullable<z.ZodString>>;
path: z.ZodDefault<z.ZodNullable<z.ZodString>>;
theirs: z.ZodDefault<z.ZodNullable<z.ZodString>>;
}, "strip", z.ZodTypeAny, {
at: number | null;
base: string | null;
kind: "conflict" | "contested" | "orphan" | null;
ours: string | null;
path: string | null;
theirs: string | null;
}, {
at?: number | null;
base?: string | null;
kind?: "conflict" | "contested" | "orphan" | null;
ours?: string | null;
path?: string | null;
theirs?: string | null;
}>;

One outcome a flush could not settle, keyed by <runId>/<path>.

Every field nullable with a null default so a row written by an older or newer shape parses rather than throwing inside a flush that must not break the run.


claudeCodeWorkspaceResources​

const claudeCodeWorkspaceResources: Record<string, DeclaredResourceEntry>;

The resource map the capability declares. One object so a second declaration site cannot drift from this one.

Typed as the widened entry map rather than left to const inference, for the same reason claudeCodeWorkRecorderResources is: a literal type would narrow ctx.resources on the blocks carrying it, and every helper taking a plain BlockContext would stop accepting that context.


defaultResolveClaudeCodeAgent​

const defaultResolveClaudeCodeAgent: ResolveClaudeCodeAgent;

Default resolver: lazily imports the SDK and returns its query. The import is deferred to call time so merely importing this package (without the SDK installed) never fails.

Functions​

checkClaudeCodeReadiness()​

function checkClaudeCodeReadiness(options): Promise<HarnessReadiness>;

Whether Claude Code can run on this machine, as core's neutral readiness: an installed SDK in the range this package tested, then the answer of probeClaudeCodeAccount, with what to do when there is no credential. A cold start can miss the probe's window, so an unanswered probe is asked once more before it counts. Never throws.

Parameters​

options​

ClaudeCodeReadinessOptions

Returns​

Promise<HarnessReadiness>


claudeCodeAgent()​

function claudeCodeAgent(options?): BlockDefinition<ZodObject<{
attachments: ZodOptional<ZodArray<ZodObject<{
data: ZodEffects<ZodString, string, string>;
filename: ZodOptional<ZodString>;
mediaType: ZodString;
type: ZodLiteral<"file">;
}, "strip", ZodTypeAny, {
data: string;
filename?: string;
mediaType: string;
type: "file";
}, {
data: string;
filename?: string;
mediaType: string;
type: "file";
}>, "many">>;
prompt: ZodString;
}, "strip", ZodTypeAny, {
attachments?: object[];
prompt: string;
}, {
attachments?: object[];
prompt: string;
}>, ZodObject<object & object, "strip", ZodTypeAny, {
cost: | {
basis: "reported" | "estimated";
usd: number;
}
| null;
dispatchedAt: number;
finalMessage: string | null;
outcome: "finished" | "stopped-at-limit" | "failed" | null;
resultSubtype: | "success"
| "error_max_turns"
| "error_max_budget_usd"
| "error_during_execution"
| "error_max_structured_output_retries"
| null;
sessionId: string | null;
source: "claude-code/sdk";
status: "running" | "completed" | "errored";
toolsObserved: string[];
url: string | null;
usage: | {
inputTokens: number;
outputTokens: number;
}
| null;
}, {
cost?: | {
basis: "reported" | "estimated";
usd: number;
}
| null;
dispatchedAt: number;
finalMessage?: string | null;
outcome?: "finished" | "stopped-at-limit" | "failed" | null;
resultSubtype: | "success"
| "error_max_turns"
| "error_max_budget_usd"
| "error_during_execution"
| "error_max_structured_output_retries"
| null;
sessionId: string | null;
source: "claude-code/sdk";
status: "running" | "completed" | "errored";
toolsObserved: string[];
url: string | null;
usage?: | {
inputTokens: number;
outputTokens: number;
}
| null;
}>, {
attachments?: object[];
prompt: string;
}, ClaudeCodeAgentHandle> & object;

Public surface of @flow-state-dev/claude-code: the in-process Agent SDK handler block, its opt-in capability, the resolver seam, the start-time account probe and model list, the environment pass-list a run needs, the readiness check, the session-continuity provider, the two collections the work recorder writes, the workspace capability, the types of the tools mcpTools relays, handle and wire types, and typed errors.

Every name here carries the package's name (ClaudeCode, claudeCode, CLAUDE_CODE_), as Codex's and Cursor's carry theirs. Shapes every harness shares (the plan record, the model list, the readiness answer) are core's, on @flow-state-dev/core/harness.

Parameters​

options?​

ClaudeCodeAgentOptions

Returns​

BlockDefinition<ZodObject<{ attachments: ZodOptional<ZodArray<ZodObject<{ data: ZodEffects<ZodString, string, string>; filename: ZodOptional<ZodString>; mediaType: ZodString; type: ZodLiteral<"file">; }, "strip", ZodTypeAny, { data: string; filename?: string; mediaType: string; type: "file"; }, { data: string; filename?: string; mediaType: string; type: "file"; }>, "many">>; prompt: ZodString; }, "strip", ZodTypeAny, { attachments?: object[]; prompt: string; }, { attachments?: object[]; prompt: string; }>, ZodObject<object & object, "strip", ZodTypeAny, { cost: | { basis: "reported" | "estimated"; usd: number; } | null; dispatchedAt: number; finalMessage: string | null; outcome: "finished" | "stopped-at-limit" | "failed" | null; resultSubtype: | "success" | "error_max_turns" | "error_max_budget_usd" | "error_during_execution" | "error_max_structured_output_retries" | null; sessionId: string | null; source: "claude-code/sdk"; status: "running" | "completed" | "errored"; toolsObserved: string[]; url: string | null; usage: | { inputTokens: number; outputTokens: number; } | null; }, { cost?: | { basis: "reported" | "estimated"; usd: number; } | null; dispatchedAt: number; finalMessage?: string | null; outcome?: "finished" | "stopped-at-limit" | "failed" | null; resultSubtype: | "success" | "error_max_turns" | "error_max_budget_usd" | "error_during_execution" | "error_max_structured_output_retries" | null; sessionId: string | null; source: "claude-code/sdk"; status: "running" | "completed" | "errored"; toolsObserved: string[]; url: string | null; usage?: | { inputTokens: number; outputTokens: number; } | null; }>, { attachments?: object[]; prompt: string; }, ClaudeCodeAgentHandle> & object


claudeCodeContainmentSandbox()​

function claudeCodeContainmentSandbox(root): object;

The sandbox settings for a run working in root. See contain.

enabled and allowUnsandboxedCommands: false are the constraint; allowWrite adds the root to what the run may write, because the root is not the directory the process itself is in. It is additive, not a fence.

Parameters​

root​

string

Returns​

object

allowUnsandboxedCommands​
allowUnsandboxedCommands: boolean;
enabled​
enabled: boolean;
filesystem​
filesystem: object;
filesystem.allowWrite​
allowWrite: string[];

claudeCodeHarness()​

function claudeCodeHarness(options?): Harness;

Claude Code as a harness value.

Parameters​

options?​

ClaudeCodeHarnessOptions

Returns​

Harness

Example​

createFlowState({
kits: [workforce({ … }), harnesses({ workspace })],
fill: { [harnesses.slots.harnesses]: [claudeCodeHarness(), claudeCodeHarness({ plan: true })] },
});

createClaudeCodeAgentCapability()​

function createClaudeCodeAgentCapability(options?): DefinedCapability<"claude-code-agent", Record<string, never>, "default" | "tools", Record<string, PresetDef<any>>, ZodObject<{
sdkAgentRuns: ZodDefault<ZodArray<ZodObject<object & object, "strip", ZodTypeAny, {
cost: | {
basis: ... | ...;
usd: number;
}
| null;
dispatchedAt: number;
finalMessage: string | null;
outcome: "finished" | "stopped-at-limit" | "failed" | null;
resultSubtype: | "success"
| "error_max_turns"
| "error_max_budget_usd"
| "error_during_execution"
| "error_max_structured_output_retries"
| null;
sessionId: string | null;
source: "claude-code/sdk";
status: "running" | "completed" | "errored";
toolsObserved: string[];
url: string | null;
usage: | {
inputTokens: number;
outputTokens: number;
}
| null;
}, {
cost?: | {
basis: ... | ...;
usd: number;
}
| null;
dispatchedAt: number;
finalMessage?: string | null;
outcome?: "finished" | "stopped-at-limit" | "failed" | null;
resultSubtype: | "success"
| "error_max_turns"
| "error_max_budget_usd"
| "error_during_execution"
| "error_max_structured_output_retries"
| null;
sessionId: string | null;
source: "claude-code/sdk";
status: "running" | "completed" | "errored";
toolsObserved: string[];
url: string | null;
usage?: | {
inputTokens: number;
outputTokens: number;
}
| null;
}>, "many">>;
sdkSessionId: ZodDefault<ZodNullable<ZodString>>;
}, "strip", ZodTypeAny, {
sdkAgentRuns: object[];
sdkSessionId: string | null;
}, {
sdkAgentRuns?: object[];
sdkSessionId?: string | null;
}>, {
[x: string]: DeclaredResourceEntry;
}, undefined, undefined, undefined> & object;

Create the Claude Code Agent SDK capability. Forwards all agent options (resolver, session provider, model, HITL seam) to the underlying handler. Has a single tools preset (on by default) carrying the agent block, and declares the session-state schema the block depends on.

Parameters​

options?​

ClaudeCodeAgentOptions

Returns​

DefinedCapability<"claude-code-agent", Record<string, never>, "default" | "tools", Record<string, PresetDef<any>>, ZodObject<{ sdkAgentRuns: ZodDefault<ZodArray<ZodObject<object & object, "strip", ZodTypeAny, { cost: | { basis: ... | ...; usd: number; } | null; dispatchedAt: number; finalMessage: string | null; outcome: "finished" | "stopped-at-limit" | "failed" | null; resultSubtype: | "success" | "error_max_turns" | "error_max_budget_usd" | "error_during_execution" | "error_max_structured_output_retries" | null; sessionId: string | null; source: "claude-code/sdk"; status: "running" | "completed" | "errored"; toolsObserved: string[]; url: string | null; usage: | { inputTokens: number; outputTokens: number; } | null; }, { cost?: | { basis: ... | ...; usd: number; } | null; dispatchedAt: number; finalMessage?: string | null; outcome?: "finished" | "stopped-at-limit" | "failed" | null; resultSubtype: | "success" | "error_max_turns" | "error_max_budget_usd" | "error_during_execution" | "error_max_structured_output_retries" | null; sessionId: string | null; source: "claude-code/sdk"; status: "running" | "completed" | "errored"; toolsObserved: string[]; url: string | null; usage?: | { inputTokens: number; outputTokens: number; } | null; }>, "many">>; sdkSessionId: ZodDefault<ZodNullable<ZodString>>; }, "strip", ZodTypeAny, { sdkAgentRuns: object[]; sdkSessionId: string | null; }, { sdkAgentRuns?: object[]; sdkSessionId?: string | null; }>, { [x: string]: DeclaredResourceEntry; }, undefined, undefined, undefined> & object


createClaudeCodeSessionProvider()​

function createClaudeCodeSessionProvider(): BindingProvider<ClaudeCodeSession>;

Create a BindingProvider for ClaudeCodeSession.

resolve(key) treats a non-empty key as the SDK session id to resume and an empty key as "no prior session". release is defined and safe to call but does nothing — resume-by-id is cheap and stateless, so there is nothing to dispose.

Returns​

BindingProvider<ClaudeCodeSession>


createClaudeCodeWorkspaceCapability()​

function createClaudeCodeWorkspaceCapability(options): DefinedCapability<string, Record<string, never>, "default" | "tools", Record<string, PresetDef<any>>, undefined, Record<string, DeclaredResourceEntry>, undefined, undefined, undefined> & object;

Create the workspace-agent capability.

Every claudeCodeAgent option is forwarded except cwd, which this capability owns: the directory is the projection's, and a caller setting it would point the run at a tree the projection never filled.

Parameters​

options​

ClaudeCodeWorkspaceCapabilityOptions

Returns​

DefinedCapability<string, Record<string, never>, "default" | "tools", Record<string, PresetDef<any>>, undefined, Record<string, DeclaredResourceEntry>, undefined, undefined, undefined> & object


createDefaultResolveClaudeCodeAgent()​

function createDefaultResolveClaudeCodeAgent(importSdk?): ResolveClaudeCodeAgent;

Build a resolver that loads the SDK via importSdk and returns its query. Throws ClaudeCodeSdkNotInstalledError if the module can't be loaded or lacks a query export. Exported mainly so tests can supply an importer that rejects (simulating an absent SDK); production uses defaultResolveClaudeCodeAgent.

Parameters​

importSdk?​

ClaudeCodeSdkImporter

Returns​

ResolveClaudeCodeAgent


listClaudeCodeModels()​

function listClaudeCodeModels(options): Promise<HarnessModelList>;

Ask Claude Code for its models, without a model turn.

Parameters​

options​

ListClaudeCodeModelsOptions

The environment to start Claude Code with, and how long to wait.

Returns​

Promise<HarnessModelList>

models, or failed with a reason. Never throws.


probeClaudeCodeAccount()​

function probeClaudeCodeAccount(options): Promise<ClaudeCodeAccountProbe>;

Ask Claude Code whether it has a credential, without a model turn.

Parameters​

options​

ProbeClaudeCodeAccountOptions

The environment to start Claude Code with, and how long to wait.

Returns​

Promise<ClaudeCodeAccountProbe>

account with the source(s) the SDK named, none with a reason, or sdk-missing. Never throws for any of those.


readClaudeCodeUsage()​

function readClaudeCodeUsage(options): Promise<HarnessUsageReading>;

Read who Claude Code is signed in as, for the usage record: a HarnessUsageReader once its options are bound.

An API key is api-key. A sign-in or an OAuth token is windows, with the email as the account id when there is one (the store keeps a hash) and the plan, and no windows: the windows come from runs. Nobody signed in is signed-out. An SDK that won't load, or a probe that got no answer, is unavailable, which leaves a stored reading in place. Never throws.

Parameters​

options​

ReadClaudeCodeUsageOptions

Returns​

Promise<HarnessUsageReading>