Help us shape the future of Go! Take the 2026 Go Developer Survey

claude

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 16, 2026 License: MIT Imports: 19 Imported by: 0

README

agent-sdk-go

Lint Test

A Go SDK for building agents with Claude Code — a faithful, idiomatic-Go port of Anthropic's official Claude Agent SDK (Python and TypeScript). Addresses claude-agent-sdk-python#498, the upstream request for a Go SDK.

Like the official SDKs, this is not a reimplementation of the agent loop. It drives the user-installed claude Code CLI as a subprocess, speaking newline-delimited stream-json over stdin/stdout plus a bidirectional JSON control protocol on the same stream. The CLI owns the agent loop, built-in tools, and context management; this SDK owns process lifecycle, framing, control-protocol correlation, and dispatch of in-process callbacks (permissions, hooks, and SDK MCP tools).

Verified against Claude Code CLI 2.1.178 (the version the upstream SDK bundles, pinned as claude.SupportedCLIVersion) — statically (126/126 public names, 45/45 options) and behaviorally (an integration suite that runs against the real binary). claude.CheckCLIVersion reports the installed binary's version and whether it matches the pin.

Installation

go get github.com/shindakun/agent-sdk-go

Requirements:

  • Go 1.26+
  • A working claude binary on PATH (or via WithCLIPath): npm install -g @anthropic-ai/claude-code
  • Claude Code auth — either ANTHROPIC_API_KEY in the environment, or an active Claude Code session.

Quick start

package main

import (
	"context"
	"fmt"

	claude "github.com/shindakun/agent-sdk-go"
)

func main() {
	ctx := context.Background()
	for msg, err := range claude.Query(ctx, "What files are in this directory?",
		claude.WithAllowedTools("Bash", "Glob")) {
		if err != nil {
			panic(err)
		}
		if r, ok := msg.(*claude.ResultMessage); ok {
			fmt.Println(r.Result)
		}
	}
}

Basic usage: Query

Query runs a single prompt to completion and returns an iter.Seq2[Message, error]. Type-switch on the concrete message types:

for msg, err := range claude.Query(ctx, "Find and fix the bug in auth.go",
	claude.WithAllowedTools("Read", "Edit", "Bash"),
	claude.WithModel("claude-sonnet-4-6"),
) {
	if err != nil { return err }
	switch m := msg.(type) {
	case *claude.AssistantMessage:
		// m.Content holds TextBlock / ToolUseBlock / ThinkingBlock / ...
	case *claude.ResultMessage:
		fmt.Println(m.Result)
	}
}

claude.Collect(ctx, prompt, opts...) gathers all messages into a slice for callers that don't need streaming.

Interactive sessions: Client

For multi-turn, full-duplex use (interleaved sends/receives, runtime control):

client := claude.NewClient(claude.WithAllowedTools("Read", "Grep"))
if err := client.Connect(ctx); err != nil { return err }
defer client.Close()

client.Query(ctx, "Summarize the package.")
for res := range client.Receive() {
	if res.Err != nil { return res.Err }
	// handle res.Message
}

client.SetModel(ctx, "opus")      // runtime control
client.Interrupt(ctx)             // stop the current turn

Custom tools (in-process SDK MCP servers)

Define a tool in Go; it runs in your process and is called by the agent — no external MCP subprocess:

type addArgs struct {
	A int `json:"a"`
	B int `json:"b"`
}

calc := claude.NewSdkMcpServer("calc").AddTool(
	claude.NewTool("add", "Add two integers", func(ctx context.Context, in addArgs) (claude.ToolResult, error) {
		return claude.TextResult(fmt.Sprint(in.A + in.B)), nil
	}))

claude.Query(ctx, "Use the add tool to compute 2+3.",
	claude.WithSDKMCPServer("calc", calc),
	claude.WithAllowedTools("mcp__calc__add"))

Hooks

Run Go code at lifecycle points (validate, log, block):

claude.WithHooks(map[claude.HookEvent][]claude.HookMatcher{
	claude.HookPreToolUse: {{
		Matcher: "Bash",
		Callbacks: []claude.HookCallback{func(ctx context.Context, input json.RawMessage, toolUseID string) (claude.HookOutput, error) {
			in, _ := claude.DecodePreToolUse(input)
			log.Printf("about to run %s", in.ToolName)
			return claude.HookOutput{}, nil
		}},
	}},
})

Permissions

claude.WithCanUseTool(func(ctx context.Context, tool string, input json.RawMessage, pc claude.PermissionContext) (claude.PermissionResult, error) {
	if strings.HasPrefix(tool, "Write") {
		return claude.PermissionDeny{Message: "writes disabled"}, nil
	}
	return claude.PermissionAllow{}, nil
})

Types

The streamed Message union: AssistantMessage, UserMessage, SystemMessage, ResultMessage, StreamEvent, TaskStartedMessage, TaskProgressMessage, TaskNotificationMessage, TaskUpdatedMessage, RateLimitEvent, MirrorErrorMessage. Content blocks: TextBlock, ThinkingBlock, ToolUseBlock, ToolResultBlock, ServerToolUseBlock, ServerToolResultBlock.

Error handling

Errors are typed values — use errors.As: CLINotFoundError, ProcessError, ConnectionError, JSONDecodeError, MessageParseError, ControlProtocolError, and the ErrClosed sentinel.

Sessions

Read on-disk transcripts (no running CLI needed): ListSessions, GetSessionInfo, GetSessionMessages, ListSubagents, GetSubagentMessages. A SessionStore interface with InMemorySessionStore, *ViaStore mutations, FoldSessionSummary, and ImportSessionToStore mirrors the upstream session API. Live mirroring is available via WithSessionStore.

Examples

See examples/ — 16 runnable programs mapped 1:1 to the upstream Python examples (plus a few Go-idiomatic extras). Each maps to its counterpart in examples/README.md.

Development

go build ./...          # library + examples
go vet ./...
gofmt -l .
golangci-lint run       # see .golangci.yml (lints integration/e2e files too)
go test -race ./...                       # unit tests
go test -tags integration -timeout 600s   # smoke tier against a real claude binary
go test -tags e2e -timeout 1200s          # full e2e tier (paid API calls)
bash scripts/run-examples.sh              # run every example against the binary
CI

GitHub Actions:

  • Lint and Test run on every pull request and push to main — gofmt/go vet/build, and go test -race across Linux/macOS/Windows. Free, no secrets.
  • E2E is manual (workflow_dispatch): it installs claude, runs the e2e-tagged tests and every example against the real binary. It needs an ANTHROPIC_API_KEY repo secret and makes paid API calls, so it is not run automatically.
  • Upstream watch runs daily (and on demand): it watches anthropics/claude-agent-sdk-python for new commits and files triage issues here. Pure CLI-version bumps roll into one Upstream CLI version bumps issue; commits touching SDK source are classified by Claude and get an individual labeled issue with the diff link and a port recommendation; docs/test/example commits are ignored. It needs the ANTHROPIC_API_KEY secret. The triage prompt treats commit messages and diffs as untrusted data (prompt-injection hardened), and the model can only suggest a label — it never decides whether to file or takes any action. Logic lives in scripts/upstream-watch.sh and is runnable locally with DRY_RUN=1.

See CLAUDE.md for the codebase map and the parity workflow.

Parity

Verified name-for-name and field-for-field against claude-agent-sdk-python (CLI 2.1.178): all 126 public __all__ names and 45 ClaudeAgentOptions fields covered (a handful of Python-runtime-specific names documented N/A), with behavioral checks against the real binary. See PARITY.md.

Design

See DESIGN.md for the architecture and protocol details.

License

MIT.

Documentation

Overview

Package claude is a Go SDK for building agents with Claude Code.

It is a faithful port of Anthropic's official Claude Agent SDK (Python and TypeScript). Like those SDKs, it does not reimplement the agent loop: it drives the user-installed `claude` Code CLI binary as a subprocess, speaking newline-delimited stream-json over the subprocess's stdin/stdout plus a bidirectional JSON control protocol layered on the same stream. The CLI owns the agent loop, built-in tools, and context management; this SDK owns process lifecycle, framing, control-protocol correlation, and dispatch of in-process callbacks (permissions, hooks, and SDK MCP tools).

The package offers two entry points:

  • Query for one-shot prompts, returning an iterator over typed messages.
  • Client for interactive, multi-turn, full-duplex sessions.

A working `claude` binary must be available on PATH (or supplied via WithCLIPath) and the appropriate credentials configured in the environment (for example ANTHROPIC_API_KEY).

Index

Constants

View Source
const SupportedCLIVersion = "2.1.178"

SupportedCLIVersion is the Claude Code CLI version this SDK was verified against — the version the upstream `claude-agent-sdk-python` bundles (`_cli_version.py`). Unlike the Python/TS SDKs, this SDK does not bundle the CLI; it requires `claude` on PATH. The pin records the known-good version for parity audits and lets callers warn on a mismatch via CheckCLIVersion.

View Source
const Version = "0.2.0"

Version is the SDK version.

Variables

View Source
var ErrClosed = errors.New("claude: closed")

ErrClosed is returned when an operation is attempted on a Client or transport that has already been closed.

View Source
var TerminalTaskStatuses = map[string]struct{}{
	"completed": {}, "failed": {}, "stopped": {}, "killed": {},
}

TerminalTaskStatuses are the statuses meaning a task has finished and should be cleared from any "active task" tracking. It spans both lifecycle vocabularies: task_notification reports "stopped" (the CLI's mapped form of a killed task) while task_updated reports the raw "killed". Mirrors the upstream TERMINAL_TASK_STATUSES set. Query membership via IsTerminalTaskStatus.

Functions

func CLIVersion

func CLIVersion(ctx context.Context, cliPath string) (string, error)

CLIVersion returns the version reported by the installed `claude` binary (from `claude --version`). cliPath may be empty to use discovery; see WithCLIPath for the same resolution rules. The returned string is the bare version (for example "2.1.159"), parsed from the CLI's output.

func CheckCLIVersion

func CheckCLIVersion(ctx context.Context, cliPath string) (string, error)

CheckCLIVersion compares the installed CLI version against SupportedCLIVersion. It returns the installed version and a non-nil error (a CLIVersionMismatch) when they differ, so callers can warn without failing. A nil error means the installed CLI matches the verified version.

func DeleteSessionViaStore

func DeleteSessionViaStore(ctx context.Context, store SessionStore, key SessionKey) error

DeleteSessionViaStore removes a session from the store.

func ImportSessionToStore

func ImportSessionToStore(ctx context.Context, sessionID string, store SessionStore, opts ...ImportOption) error

ImportSessionToStore replays a local session transcript into a SessionStore, streaming the on-disk JSONL and appending in batches. The destination project key is the on-disk project directory name, so an imported session is indistinguishable from a live-mirrored one.

func IsNotAMessage

func IsNotAMessage(err error) bool

IsNotAMessage reports whether err indicates a non-message stream frame (a control-protocol envelope or sentinel) rather than a decode failure.

func IsTerminalTaskStatus added in v0.2.0

func IsTerminalTaskStatus(status string) bool

IsTerminalTaskStatus reports whether status means a task has finished, across both the TaskNotificationMessage ("stopped") and TaskUpdatedMessage ("killed") vocabularies.

func ListSubagents

func ListSubagents(sessionID, directory string) ([]string, error)

ListSubagents returns the distinct subagent ids referenced in a session.

func ProjectKeyForDirectory

func ProjectKeyForDirectory(directory string) string

ProjectKeyForDirectory returns the project key (the sanitized directory name) the CLI uses for sessions under the given working directory.

func Query

func Query(ctx context.Context, prompt string, opts ...Option) iter.Seq2[Message, error]

Query runs a single prompt to completion and returns an iterator over the messages the CLI emits. Iteration ends after the terminal result message (or on error); breaking out of the range loop early cancels the CLI subprocess and releases all resources.

A working `claude` binary must be available (see WithCLIPath). Errors — binary discovery, connection, decode, or a non-zero CLI exit — are delivered as the second value of the iterator and terminate iteration.

for msg, err := range claude.Query(ctx, "hello") {
    if err != nil { return err }
    // type-switch on msg
}

func RenameSessionViaStore

func RenameSessionViaStore(ctx context.Context, store SessionStore, key SessionKey, title string) error

RenameSessionViaStore records a custom title for a session in the store.

func SessionsDir

func SessionsDir(directory string) (string, error)

SessionsDir returns the directory holding session files for the given working directory, applying the same sanitization the CLI uses. When directory is empty, the current working directory is used.

func TagSessionViaStore

func TagSessionViaStore(ctx context.Context, store SessionStore, key SessionKey, tag string) error

TagSessionViaStore records a tag for a session in the store.

Types

type AgentDefinition

type AgentDefinition struct {
	Description     string   `json:"description"`
	Prompt          string   `json:"prompt"`
	Tools           []string `json:"tools,omitempty"`
	DisallowedTools []string `json:"disallowedTools,omitempty"`
	Model           string   `json:"model,omitempty"`
	Skills          []string `json:"skills,omitempty"`
	Memory          string   `json:"memory,omitempty"` // "user" | "project" | "local"
	MCPServers      []string `json:"mcpServers,omitempty"`
	InitialPrompt   string   `json:"initialPrompt,omitempty"`
	MaxTurns        int      `json:"maxTurns,omitempty"`
	Background      bool     `json:"background,omitempty"`
	Effort          string   `json:"effort,omitempty"`
	PermissionMode  string   `json:"permissionMode,omitempty"`
}

AgentDefinition declares a subagent the main agent can delegate to via the Agent tool. Wire keys use the camelCase the CLI expects.

type AssistantMessage

type AssistantMessage struct {
	Content []ContentBlock
	Model   string
	// ParentToolUseID is set when this message originates inside a subagent's
	// context, identifying the Agent tool call that spawned it.
	ParentToolUseID string
	MessageID       string          `json:"message_id,omitempty"`
	StopReason      string          `json:"stop_reason,omitempty"`
	SessionID       string          `json:"session_id,omitempty"`
	UUID            string          `json:"uuid,omitempty"`
	Usage           *Usage          `json:"usage,omitempty"`
	Error           json.RawMessage `json:"error,omitempty"`
	// Raw is the undecoded JSON of the message for forward-compatibility.
	Raw json.RawMessage
}

AssistantMessage is a response turn from the model.

type BaseHookInput

type BaseHookInput struct {
	HookEventName  string `json:"hook_event_name"`
	SessionID      string `json:"session_id"`
	TranscriptPath string `json:"transcript_path"`
	Cwd            string `json:"cwd"`
	PermissionMode string `json:"permission_mode,omitempty"`
}

BaseHookInput holds fields common to every hook event.

type CLINotFoundError

type CLINotFoundError struct {
	// Path is the path that was tried, if an explicit one was configured.
	Path string
	// Hint is a human-readable suggestion for resolving the problem.
	Hint string
}

CLINotFoundError indicates the `claude` Code CLI binary could not be located.

func (*CLINotFoundError) Error

func (e *CLINotFoundError) Error() string

type CLIVersionMismatch

type CLIVersionMismatch struct {
	Installed string
	Supported string
}

CLIVersionMismatch reports that the installed CLI differs from the version this SDK was verified against. It is advisory — the SDK still operates.

func (*CLIVersionMismatch) Error

func (e *CLIVersionMismatch) Error() string

type CanUseTool

type CanUseTool func(ctx context.Context, toolName string, input json.RawMessage, pc PermissionContext) (PermissionResult, error)

CanUseTool is a callback invoked when the CLI asks the SDK to decide whether a tool may run. It returns either a PermissionAllow or a PermissionDeny.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a long-lived, full-duplex session with the CLI. Unlike Query, which runs a single prompt to completion, a Client supports multiple prompts, runtime control (model/permission changes, interrupts), and interleaved sending and receiving.

A Client must be connected with Client.Connect before use and released with Client.Close. It is safe for one sender and one receiver to operate concurrently; concurrent prompts are serialized by the CLI, which processes one turn at a time.

func NewClient

func NewClient(opts ...Option) *Client

NewClient creates an unconnected Client.

func (*Client) Close

func (c *Client) Close() error

Close shuts the session down and waits for the read loop to finish. It returns any process error from the CLI.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) error

Connect spawns the CLI subprocess and completes the initialize handshake. The provided context governs the subprocess lifetime; canceling it terminates the session.

func (*Client) GetContextUsage

func (c *Client) GetContextUsage(ctx context.Context) (ContextUsage, error)

GetContextUsage returns the current context-window usage breakdown.

func (*Client) GetServerInfo

func (c *Client) GetServerInfo(ctx context.Context) (json.RawMessage, error)

GetServerInfo returns the CLI's initialization info captured during Client.Connect — available commands, output styles, and server capabilities. It returns nil if the client is not connected.

func (*Client) Interrupt

func (c *Client) Interrupt(ctx context.Context) error

Interrupt stops the current turn.

func (*Client) McpReconnect

func (c *Client) McpReconnect(ctx context.Context, serverName string) error

McpReconnect reconnects a failed MCP server.

func (*Client) McpStatus

func (c *Client) McpStatus(ctx context.Context) (McpStatusResponse, error)

McpStatus returns the status of configured MCP servers.

func (*Client) McpToggle

func (c *Client) McpToggle(ctx context.Context, serverName string, enabled bool) error

McpToggle enables or disables an MCP server.

func (*Client) Messages

func (c *Client) Messages(ctx context.Context) iter.Seq2[Message, error]

Messages is an iterator over streamed messages, sugar over Client.Receive. Iteration ends when the session ends or ctx is canceled.

func (*Client) Query

func (c *Client) Query(ctx context.Context, prompt string) error

Query sends a user prompt. It does not wait for the response; consume it via Client.Receive or Client.Messages.

func (*Client) QuerySession

func (c *Client) QuerySession(ctx context.Context, prompt, sessionID string) error

QuerySession sends a prompt addressed to a specific session id, for routing within a multi-session connection (mirrors the session_id argument of the official client.query). An empty sessionID behaves like Client.Query.

func (*Client) Receive

func (c *Client) Receive() <-chan Result

Receive returns the channel of streamed results. The channel is closed when the session ends.

func (*Client) ReceiveResponse

func (c *Client) ReceiveResponse(ctx context.Context) iter.Seq2[Message, error]

ReceiveResponse is like Client.Messages but terminates after the next ResultMessage (which is itself yielded) — convenient for consuming a single turn's response. If no result arrives, it iterates until ctx is canceled or the session ends.

func (*Client) RewindFiles

func (c *Client) RewindFiles(ctx context.Context, userMessageID string) error

RewindFiles rewinds tracked files to their state at the given user message. userMessageID is the uuid of a UserMessage received during the conversation. Requires WithEnableFileCheckpointing and the "replay-user-messages" extra arg.

func (*Client) SetModel

func (c *Client) SetModel(ctx context.Context, model string) error

SetModel switches the active model for subsequent turns.

func (*Client) SetPermissionMode

func (c *Client) SetPermissionMode(ctx context.Context, mode PermissionMode) error

SetPermissionMode changes the permission mode at runtime.

func (*Client) StopTask

func (c *Client) StopTask(ctx context.Context, taskID string) error

StopTask stops a running task by id.

type ConnectionError

type ConnectionError struct {
	Err error
}

ConnectionError wraps a lower-level failure establishing or maintaining the connection to the CLI subprocess.

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

type ContentBlock

type ContentBlock interface {
	// contains filtered or unexported methods
}

ContentBlock is one block of content within a message. The concrete types are TextBlock, ThinkingBlock, ToolUseBlock, and ToolResultBlock.

type ContextUsage

type ContextUsage struct {
	Raw json.RawMessage
}

ContextUsage reports the context-window breakdown returned by the CLI. Raw holds the full payload; use ContextUsage.Typed for structured access.

func (ContextUsage) Typed

Typed decodes the raw payload into a ContextUsageResponse.

type ContextUsageCategory

type ContextUsageCategory struct {
	Name       string `json:"name"`
	Tokens     int    `json:"tokens"`
	Color      string `json:"color"`
	IsDeferred bool   `json:"isDeferred,omitempty"`
}

ContextUsageCategory is one slice of the context-window breakdown.

type ContextUsageResponse

type ContextUsageResponse struct {
	Categories           []ContextUsageCategory `json:"categories"`
	TotalTokens          int                    `json:"totalTokens"`
	MaxTokens            int                    `json:"maxTokens"`
	RawMaxTokens         int                    `json:"rawMaxTokens"`
	Percentage           float64                `json:"percentage"`
	Model                string                 `json:"model"`
	IsAutoCompactEnabled bool                   `json:"isAutoCompactEnabled"`
	MemoryFiles          json.RawMessage        `json:"memoryFiles,omitempty"`
	McpTools             json.RawMessage        `json:"mcpTools,omitempty"`
	Agents               json.RawMessage        `json:"agents,omitempty"`
	GridRows             json.RawMessage        `json:"gridRows,omitempty"`
	AutoCompactThreshold int                    `json:"autoCompactThreshold,omitempty"`
	DeferredBuiltinTools json.RawMessage        `json:"deferredBuiltinTools,omitempty"`
	SystemTools          json.RawMessage        `json:"systemTools,omitempty"`
	SystemPromptSections json.RawMessage        `json:"systemPromptSections,omitempty"`
	SlashCommands        json.RawMessage        `json:"slashCommands,omitempty"`
	Skills               json.RawMessage        `json:"skills,omitempty"`
	MessageBreakdown     json.RawMessage        `json:"messageBreakdown,omitempty"`
	APIUsage             json.RawMessage        `json:"apiUsage,omitempty"`
}

ContextUsageResponse is the typed form of a get_context_usage result. Decode it from ContextUsage.Raw with ContextUsage.Typed.

type ControlProtocolError

type ControlProtocolError struct {
	Subtype   string
	RequestID string
	Message   string
}

ControlProtocolError reports a failure in the bidirectional control protocol, such as an error response to a control request.

func (*ControlProtocolError) Error

func (e *ControlProtocolError) Error() string

type DeferredToolUse

type DeferredToolUse struct {
	ID    string          `json:"id"`
	Name  string          `json:"name"`
	Input json.RawMessage `json:"input"`
}

DeferredToolUse is a tool call deferred to the caller, surfaced on a result.

type EffortLevel

type EffortLevel string

EffortLevel selects the model's reasoning effort.

const (
	EffortLow    EffortLevel = "low"
	EffortMedium EffortLevel = "medium"
	EffortHigh   EffortLevel = "high"
	EffortXHigh  EffortLevel = "xhigh"
	EffortMax    EffortLevel = "max"
)

type ForkSessionResult

type ForkSessionResult struct {
	SessionID string
}

ForkSessionResult reports the new session id produced by a fork.

func ForkSessionViaStore

func ForkSessionViaStore(ctx context.Context, store SessionStore, key SessionKey, newSessionID string) (ForkSessionResult, error)

ForkSessionViaStore copies a session's entries under a new session id within the same project, returning the new id.

type HTTPMcpServer

type HTTPMcpServer struct {
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers,omitempty"`
}

HTTPMcpServer is an external MCP server reached over streamable HTTP.

type HookCallback

type HookCallback func(ctx context.Context, input json.RawMessage, toolUseID string) (HookOutput, error)

HookCallback runs custom logic at a hook point. input is the raw event payload (its shape depends on the event); toolUseID identifies the associated tool call for tool-related events and is empty otherwise.

type HookEvent

type HookEvent string

HookEvent names a point in the agent lifecycle at which a hook may run.

const (
	HookPreToolUse         HookEvent = "PreToolUse"
	HookPostToolUse        HookEvent = "PostToolUse"
	HookPostToolUseFailure HookEvent = "PostToolUseFailure"
	HookUserPromptSubmit   HookEvent = "UserPromptSubmit"
	HookStop               HookEvent = "Stop"
	HookSubagentStop       HookEvent = "SubagentStop"
	HookSubagentStart      HookEvent = "SubagentStart"
	HookPreCompact         HookEvent = "PreCompact"
	HookNotification       HookEvent = "Notification"
	HookPermissionRequest  HookEvent = "PermissionRequest"
)

type HookEventMessage

type HookEventMessage struct {
	Subtype       string // "hook_started" | "hook_response"
	HookEventName string
	SessionID     string
	UUID          string
	Data          json.RawMessage
	Raw           json.RawMessage
}

HookEventMessage is a hook lifecycle event emitted on the stream when WithIncludeHookEvents is set. It arrives as a system message with subtype "hook_started" (a hook begins) or "hook_response" (a hook completes). HookEventName identifies the event (PreToolUse, PostToolUse, Stop, …); the full payload is in Data.

type HookMatcher

type HookMatcher struct {
	Matcher   string
	Callbacks []HookCallback
	Timeout   time.Duration
}

HookMatcher binds a set of callbacks to events whose subject matches Matcher. For tool events Matcher is a tool-name pattern (for example "Edit|Write"); an empty Matcher matches all subjects.

type HookOutput

type HookOutput struct {
	// Decision, when set (for example "block"), affects whether the action
	// proceeds.
	Decision string
	// SystemMessage is injected into the conversation as a system note.
	SystemMessage string
	// Continue, when non-nil and false, halts the agent.
	Continue *bool
	// SuppressOutput hides the hook's stdout from the transcript.
	SuppressOutput bool
	// HookSpecificOutput carries event-specific structured output, such as a
	// PreToolUse permission decision.
	HookSpecificOutput json.RawMessage
}

HookOutput is returned by a HookCallback to influence agent behavior. A zero value is a no-op that lets execution proceed.

type ImportOption

type ImportOption func(*importConfig)

ImportOption configures ImportSessionToStore.

func ImportBatchSize

func ImportBatchSize(n int) ImportOption

ImportBatchSize sets the maximum entries per store Append call.

func ImportDirectory

func ImportDirectory(dir string) ImportOption

ImportDirectory sets the project directory the session lives under (same semantics as ListSessions).

func ImportIncludeSubagents

func ImportIncludeSubagents(v bool) ImportOption

ImportIncludeSubagents toggles importing subagent transcripts.

type InMemorySessionStore

type InMemorySessionStore struct {
	// contains filtered or unexported fields
}

InMemorySessionStore is an in-memory SessionStore, suitable for tests and ephemeral mirrors. It maintains monotonically increasing mtimes for staleness detection, mirroring the official implementation.

func NewInMemorySessionStore

func NewInMemorySessionStore() *InMemorySessionStore

NewInMemorySessionStore creates an empty in-memory store.

func (*InMemorySessionStore) Append

func (s *InMemorySessionStore) Append(ctx context.Context, key SessionKey, entries []SessionStoreEntry) error

func (*InMemorySessionStore) Delete

func (s *InMemorySessionStore) Delete(ctx context.Context, key SessionKey) error

func (*InMemorySessionStore) ListSessionSummaries

func (s *InMemorySessionStore) ListSessionSummaries(ctx context.Context, projectKey string) ([]SessionSummaryEntry, error)

func (*InMemorySessionStore) ListSessions

func (s *InMemorySessionStore) ListSessions(ctx context.Context, projectKey string) ([]SessionStoreListEntry, error)

func (*InMemorySessionStore) ListSubkeys

func (s *InMemorySessionStore) ListSubkeys(ctx context.Context, key SessionListSubkeysKey) ([]string, error)

func (*InMemorySessionStore) Load

type JSONDecodeError

type JSONDecodeError struct {
	Line []byte
	Err  error
}

JSONDecodeError reports a stream-json line that could not be decoded.

func (*JSONDecodeError) Error

func (e *JSONDecodeError) Error() string

func (*JSONDecodeError) Unwrap

func (e *JSONDecodeError) Unwrap() error

type McpServerConfig

type McpServerConfig interface {
	// contains filtered or unexported methods
}

McpServerConfig describes an MCP server made available to the agent. The concrete types are StdioMcpServer, HTTPMcpServer, SSEMcpServer (external servers, serialized into --mcp-config) and *SdkMcpServer (in-process, serviced by this SDK over the control protocol).

type McpServerConnectionStatus

type McpServerConnectionStatus string

McpServerConnectionStatus is an MCP server's connection state.

type McpServerInfo

type McpServerInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

McpServerInfo is an MCP server's reported identity.

type McpServerStatusInfo

type McpServerStatusInfo struct {
	Name       string          `json:"name"`
	Status     string          `json:"status"`
	ServerInfo *McpServerInfo  `json:"serverInfo,omitempty"`
	Error      string          `json:"error,omitempty"`
	Scope      string          `json:"scope,omitempty"`
	Tools      []McpToolInfo   `json:"tools,omitempty"`
	Config     json.RawMessage `json:"config,omitempty"`
}

McpServerStatusInfo is the typed status of one MCP server (the official SDK calls this McpServerStatus; that name is used here for the control-method return type, so the typed status carries the "Info" suffix).

type McpStatusResponse

type McpStatusResponse struct {
	McpServers []McpServerStatusInfo `json:"mcpServers"`
}

McpStatusResponse is the typed form of an mcp_status result.

type McpToolAnnotations

type McpToolAnnotations struct {
	ReadOnly    bool `json:"readOnly,omitempty"`
	Destructive bool `json:"destructive,omitempty"`
	OpenWorld   bool `json:"openWorld,omitempty"`
}

McpToolAnnotations describes a tool's behavior hints.

type McpToolInfo

type McpToolInfo struct {
	Name        string              `json:"name"`
	Description string              `json:"description,omitempty"`
	Annotations *McpToolAnnotations `json:"annotations,omitempty"`
}

McpToolInfo describes one tool offered by an MCP server.

type Message

type Message interface {
	// contains filtered or unexported methods
}

Message is a single item in the stream emitted by the CLI. The concrete types are AssistantMessage, UserMessage, SystemMessage, ResultMessage, StreamEvent, and [TaskNotification].

Decode the stream by type-switching on the concrete types; the discriminated union is sealed (only this package defines implementations).

func Collect

func Collect(ctx context.Context, prompt string, opts ...Option) ([]Message, error)

Collect runs a prompt to completion and returns all emitted messages. It is a convenience wrapper over Query for callers that do not need streaming.

func UnmarshalMessage

func UnmarshalMessage(b []byte) (Message, error)

UnmarshalMessage decodes a single stream-json line into the concrete Message type identified by its "type" (and where relevant "subtype") field.

Control-protocol envelopes (control_request, control_response, control_cancel_request) and the transcript_mirror frame are not [Message]s; they are handled by the transport/protocol layers and UnmarshalMessage reports them via [ErrNotAMessage] so callers can skip them.

type MessageParseError

type MessageParseError struct {
	Type string
	Raw  []byte
	Err  error
}

MessageParseError reports a decoded JSON object that could not be mapped onto a concrete Message type.

func (*MessageParseError) Error

func (e *MessageParseError) Error() string

func (*MessageParseError) Unwrap

func (e *MessageParseError) Unwrap() error

type MirrorErrorMessage

type MirrorErrorMessage struct {
	Key   *SessionKey `json:"key,omitempty"`
	Error string      `json:"error"`
	Raw   json.RawMessage
}

MirrorErrorMessage is emitted when a SessionStore append fails during live mirroring. It is non-fatal: the on-disk transcript is already durable.

type NotificationHookInput

type NotificationHookInput struct {
	BaseHookInput
	Message          string `json:"message"`
	Title            string `json:"title,omitempty"`
	NotificationType string `json:"notification_type,omitempty"`
}

NotificationHookInput is the payload for HookNotification.

func DecodeNotification

func DecodeNotification(raw json.RawMessage) (NotificationHookInput, error)

DecodeNotification decodes a HookNotification payload.

type NotificationHookSpecificOutput

type NotificationHookSpecificOutput struct {
	HookEventName     string `json:"hookEventName"` // "Notification"
	AdditionalContext string `json:"additionalContext,omitempty"`
}

NotificationHookSpecificOutput is the typed hook-specific output for Notification events.

type Option

type Option func(*Options)

Option mutates an Options.

func WithAddDir

func WithAddDir(dirs ...string) Option

WithAddDir grants the agent access to additional directories.

func WithAgents

func WithAgents(agents map[string]AgentDefinition) Option

WithAgents registers subagent definitions.

func WithAllowedTools

func WithAllowedTools(tools ...string) Option

WithAllowedTools pre-approves the named tools.

func WithAppendSystemPrompt

func WithAppendSystemPrompt(prompt string) Option

WithAppendSystemPrompt appends prompt to the default system prompt.

func WithBetas

func WithBetas(betas ...string) Option

WithBetas enables the named API beta flags.

func WithCLIPath

func WithCLIPath(path string) Option

WithCLIPath overrides discovery of the `claude` binary.

func WithCanUseTool

func WithCanUseTool(fn CanUseTool) Option

WithCanUseTool registers a permission callback.

func WithContinueConversation

func WithContinueConversation() Option

WithContinueConversation continues the most recent conversation.

func WithCwd

func WithCwd(dir string) Option

WithCwd sets the working directory for the CLI subprocess.

func WithDisallowedTools

func WithDisallowedTools(tools ...string) Option

WithDisallowedTools blocks the named tools.

func WithEffort

func WithEffort(level EffortLevel) Option

WithEffort sets the reasoning effort independently of thinking config (maps to --effort).

func WithEnableFileCheckpointing

func WithEnableFileCheckpointing() Option

WithEnableFileCheckpointing enables SDK file checkpointing (sets CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING=true for the subprocess).

func WithEnv

func WithEnv(env map[string]string) Option

WithEnv adds environment variables for the CLI subprocess.

func WithExcludeDynamicSections

func WithExcludeDynamicSections() Option

WithExcludeDynamicSections omits dynamic system-prompt sections.

func WithExtraArgs

func WithExtraArgs(args map[string]*string) Option

WithExtraArgs passes raw flags through to the CLI for forward-compatibility. A nil value yields a boolean flag (--name); a non-nil value yields --name value.

func WithFallbackModel

func WithFallbackModel(model string) Option

WithFallbackModel sets a fallback model used if the primary is unavailable.

func WithForkSession

func WithForkSession() Option

WithForkSession forks the resumed session (when combined with WithResume) rather than continuing it in place.

func WithHooks

func WithHooks(hooks map[HookEvent][]HookMatcher) Option

WithHooks registers lifecycle hooks.

func WithIncludeHookEvents

func WithIncludeHookEvents() Option

WithIncludeHookEvents surfaces hook lifecycle events on the stream (maps to --include-hook-events).

func WithIncludePartialMessages

func WithIncludePartialMessages() Option

WithIncludePartialMessages enables partial/streaming message events (StreamEvent).

func WithJSONSchema

func WithJSONSchema(schema json.RawMessage) Option

WithJSONSchema constrains the final result to the given JSON Schema.

func WithLoadTimeout

func WithLoadTimeout(d time.Duration) Option

WithLoadTimeout overrides the initialize-handshake timeout.

func WithMCPConfig

func WithMCPConfig(pathOrJSON string) Option

WithMCPConfig passes an MCP configuration directly to --mcp-config as either a file path or a JSON string, mirroring the official SDK's string/path form of mcp_servers. It takes precedence over WithMCPServers / WithSDKMCPServer.

func WithMCPServers

func WithMCPServers(servers map[string]McpServerConfig) Option

WithMCPServers registers MCP servers by name. Values may be external configs (StdioMcpServer, HTTPMcpServer, SSEMcpServer) or in-process *SdkMcpServer instances.

func WithMaxBudgetUSD

func WithMaxBudgetUSD(usd float64) Option

WithMaxBudgetUSD caps the total spend for the session in US dollars.

func WithMaxBufferSize

func WithMaxBufferSize(bytes int) Option

WithMaxBufferSize caps the size of a single stream-json line the transport will buffer before erroring. Zero uses the default.

func WithMaxThinkingTokens

func WithMaxThinkingTokens(n int) Option

WithMaxThinkingTokens sets the thinking token budget via the deprecated scalar path (maps to --max-thinking-tokens). Prefer WithThinkingConfig with ThinkingConfigEnabled.

func WithMaxTurns

func WithMaxTurns(n int) Option

WithMaxTurns caps the number of agent turns.

func WithModel

func WithModel(model string) Option

WithModel sets the model (for example "claude-sonnet-4-6" or an alias like "opus").

func WithPermissionMode

func WithPermissionMode(mode PermissionMode) Option

WithPermissionMode sets the initial permission mode.

func WithPermissionPromptToolName

func WithPermissionPromptToolName(name string) Option

WithPermissionPromptToolName sets the MCP tool the CLI uses to prompt for permission decisions. This is independent of WithCanUseTool, which receives decisions over the control protocol.

func WithPluginDir

func WithPluginDir(dirs ...string) Option

WithPluginDir adds plugin directories.

func WithPlugins

func WithPlugins(plugins ...SdkPluginConfig) Option

WithPlugins registers structured local plugin configs. Each adds its path as a plugin directory.

func WithResume

func WithResume(sessionID string) Option

WithResume resumes a prior session by ID.

func WithSDKMCPServer

func WithSDKMCPServer(name string, server *SdkMcpServer) Option

WithSDKMCPServer registers a single in-process MCP server under name.

func WithSandbox

func WithSandbox(s SandboxSettings) Option

WithSandbox configures the CLI command sandbox.

func WithSessionID

func WithSessionID(id string) Option

WithSessionID sets an explicit session id (maps to --session-id).

func WithSessionStore

func WithSessionStore(store SessionStore, flush SessionStoreFlushMode) Option

WithSessionStore mirrors the live transcript into store using the given flush mode. Append failures surface as a MirrorErrorMessage on the stream.

func WithSettingSources

func WithSettingSources(sources ...string) Option

WithSettingSources controls which filesystem settings sources the CLI loads (for example "user", "project", "local"). When unset, the CLI default applies.

func WithSettings

func WithSettings(settings string) Option

WithSettings points the CLI at a settings file or JSON string.

func WithSkills

func WithSkills(skills ...string) Option

WithSkills enables the named skills.

func WithStderr

func WithStderr(w io.Writer) Option

WithStderr directs the CLI subprocess's stderr to w.

func WithStrictMcpConfig

func WithStrictMcpConfig() Option

WithStrictMcpConfig restricts MCP servers to those in the provided config (maps to --strict-mcp-config).

func WithSystemPrompt

func WithSystemPrompt(prompt string) Option

WithSystemPrompt replaces the system prompt with prompt.

func WithSystemPromptFile

func WithSystemPromptFile(path string) Option

WithSystemPromptFile loads the system prompt from the file at path (maps to --system-prompt-file).

func WithTaskBudget

func WithTaskBudget(b TaskBudget) Option

WithTaskBudget caps the task token budget (maps to --task-budget).

func WithThinkingConfig

func WithThinkingConfig(cfg ThinkingConfig) Option

WithThinkingConfig sets the extended-thinking configuration. Pass one of ThinkingConfigAdaptive, ThinkingConfigEnabled, or ThinkingConfigDisabled. It takes precedence over WithMaxThinkingTokens.

func WithThinkingDisplay

func WithThinkingDisplay(d ThinkingDisplay) Option

WithThinkingDisplay controls how thinking output is shown (maps to --thinking-display). Applies to adaptive and enabled thinking.

func WithToolList

func WithToolList(tools ...string) Option

WithToolList sets the explicit tool list (maps to --tools). An empty slice disables all tools. (Named WithToolList to avoid colliding with the SdkMcpServer option WithTools.)

func WithToolsPreset

func WithToolsPreset() Option

WithToolsPreset selects the default tool preset (maps to --tools default).

func WithUser

func WithUser(uid, gid int) Option

WithUser runs the CLI subprocess as the given OS user/group id (Unix only).

type Options

type Options struct {
	// contains filtered or unexported fields
}

Options configures a Query or Client. Construct it with the With* functional options rather than setting fields directly.

type PermissionAllow

type PermissionAllow struct {
	// UpdatedInput, if non-nil, replaces the tool's input arguments.
	UpdatedInput json.RawMessage
	// UpdatedPermissions, if non-nil, updates the permission ruleset.
	UpdatedPermissions json.RawMessage
}

PermissionAllow approves a tool call, optionally rewriting its input.

type PermissionContext

type PermissionContext struct {
	ToolUseID      string
	Suggestions    json.RawMessage
	AgentID        string
	BlockedPath    string
	DecisionReason string
	Title          string
	DisplayName    string
	Description    string
}

PermissionContext carries additional information about a permission request.

type PermissionDeny

type PermissionDeny struct {
	Message string
	// Interrupt, when true, stops the current turn rather than letting the
	// model continue without the tool.
	Interrupt bool
}

PermissionDeny rejects a tool call.

type PermissionMode

type PermissionMode string

PermissionMode controls how the CLI handles tool-permission decisions when no explicit allow/deny rule applies.

const (
	// PermissionDefault prompts (or defers to CanUseTool) for each decision.
	PermissionDefault PermissionMode = "default"
	// PermissionAcceptEdits auto-approves file edits.
	PermissionAcceptEdits PermissionMode = "acceptEdits"
	// PermissionBypass approves all tool use without prompting.
	PermissionBypass PermissionMode = "bypassPermissions"
	// PermissionPlan runs in read-only planning mode.
	PermissionPlan PermissionMode = "plan"
	// PermissionDontAsk proceeds without prompting but does not bypass rules.
	PermissionDontAsk PermissionMode = "dontAsk"
	// PermissionAuto lets the CLI choose the mode automatically.
	PermissionAuto PermissionMode = "auto"
)

type PermissionRequestHookInput

type PermissionRequestHookInput struct {
	BaseHookInput
	ToolName              string          `json:"tool_name"`
	ToolInput             json.RawMessage `json:"tool_input"`
	ToolUseID             string          `json:"tool_use_id,omitempty"`
	PermissionSuggestions json.RawMessage `json:"permission_suggestions,omitempty"`
}

PermissionRequestHookInput is the payload for a permission-request hook.

type PermissionRequestHookSpecificOutput

type PermissionRequestHookSpecificOutput struct {
	HookEventName string          `json:"hookEventName"` // "PermissionRequest"
	Decision      json.RawMessage `json:"decision"`
}

PermissionRequestHookSpecificOutput is the typed hook-specific output for permission-request events.

type PermissionResult

type PermissionResult interface {
	// contains filtered or unexported methods
}

PermissionResult is the outcome of a CanUseTool callback. The concrete types are PermissionAllow and PermissionDeny.

type PermissionUpdate

type PermissionUpdate struct {
	Type        string          `json:"type"` // addRules | replaceRules | removeRules | setMode | addDirectories | removeDirectories
	Rules       json.RawMessage `json:"rules,omitempty"`
	Behavior    string          `json:"behavior,omitempty"`
	Mode        PermissionMode  `json:"mode,omitempty"`
	Directories []string        `json:"directories,omitempty"`
	Destination string          `json:"destination,omitempty"`
}

PermissionUpdate describes a runtime change to the permission ruleset.

type PluginInfo

type PluginInfo struct {
	Name   string `json:"name"`
	Path   string `json:"path"`
	Source string `json:"source,omitempty"`
}

PluginInfo describes a plugin loaded into the session, as reported in the "init" system message.

type PostToolUseFailureHookInput

type PostToolUseFailureHookInput struct {
	BaseHookInput
	ToolName    string          `json:"tool_name"`
	ToolInput   json.RawMessage `json:"tool_input"`
	ToolUseID   string          `json:"tool_use_id"`
	Error       string          `json:"error"`
	IsInterrupt bool            `json:"is_interrupt,omitempty"`
}

PostToolUseFailureHookInput is the payload for a post-tool-use-failure hook.

func DecodePostToolUseFailure

func DecodePostToolUseFailure(raw json.RawMessage) (PostToolUseFailureHookInput, error)

DecodePostToolUseFailure decodes a post-tool-use-failure payload.

type PostToolUseFailureHookSpecificOutput

type PostToolUseFailureHookSpecificOutput struct {
	HookEventName     string `json:"hookEventName"` // "PostToolUseFailure"
	AdditionalContext string `json:"additionalContext,omitempty"`
}

PostToolUseFailureHookSpecificOutput is the typed hook-specific output for post-tool-use-failure events.

type PostToolUseHookInput

type PostToolUseHookInput struct {
	BaseHookInput
	ToolName     string          `json:"tool_name"`
	ToolInput    json.RawMessage `json:"tool_input"`
	ToolResponse json.RawMessage `json:"tool_response"`
	ToolUseID    string          `json:"tool_use_id"`
	AgentID      string          `json:"agent_id,omitempty"`
	AgentType    string          `json:"agent_type,omitempty"`
}

PostToolUseHookInput is the payload for HookPostToolUse.

func DecodePostToolUse

func DecodePostToolUse(raw json.RawMessage) (PostToolUseHookInput, error)

DecodePostToolUse decodes a HookPostToolUse payload.

type PreCompactHookInput

type PreCompactHookInput struct {
	BaseHookInput
	Trigger            string `json:"trigger,omitempty"`
	CustomInstructions string `json:"custom_instructions,omitempty"`
}

PreCompactHookInput is the payload for HookPreCompact.

type PreToolUseHookInput

type PreToolUseHookInput struct {
	BaseHookInput
	ToolName  string          `json:"tool_name"`
	ToolInput json.RawMessage `json:"tool_input"`
	ToolUseID string          `json:"tool_use_id"`
	AgentID   string          `json:"agent_id,omitempty"`
	AgentType string          `json:"agent_type,omitempty"`
}

PreToolUseHookInput is the payload for HookPreToolUse.

func DecodePreToolUse

func DecodePreToolUse(raw json.RawMessage) (PreToolUseHookInput, error)

DecodePreToolUse decodes a HookPreToolUse payload.

type ProcessError

type ProcessError struct {
	ExitCode int
	Stderr   string
}

ProcessError reports that the CLI subprocess exited with a non-zero status.

func (*ProcessError) Error

func (e *ProcessError) Error() string

type RateLimitEvent

type RateLimitEvent struct {
	RateLimitInfo RateLimitInfo `json:"rate_limit_info"`
	UUID          string        `json:"uuid"`
	SessionID     string        `json:"session_id"`
}

RateLimitEvent wraps a rate-limit update. It is also a Message emitted on the stream as a rate_limit_event frame.

type RateLimitInfo

type RateLimitInfo struct {
	Status                RateLimitStatus  `json:"status"`
	ResetsAt              *int64           `json:"resets_at,omitempty"`
	RateLimitType         *RateLimitType   `json:"rate_limit_type,omitempty"`
	Utilization           *float64         `json:"utilization,omitempty"`
	OverageStatus         *RateLimitStatus `json:"overage_status,omitempty"`
	OverageResetsAt       *int64           `json:"overage_resets_at,omitempty"`
	OverageDisabledReason *string          `json:"overage_disabled_reason,omitempty"`
	Raw                   json.RawMessage  `json:"-"`
}

RateLimitInfo describes the current rate-limit posture.

type RateLimitStatus

type RateLimitStatus string

RateLimitStatus is the state of a rate limit.

const (
	RateLimitAllowed        RateLimitStatus = "allowed"
	RateLimitAllowedWarning RateLimitStatus = "allowed_warning"
	RateLimitRejected       RateLimitStatus = "rejected"
)

type RateLimitType

type RateLimitType string

RateLimitType identifies which rate-limit window applies.

const (
	RateLimitFiveHour       RateLimitType = "five_hour"
	RateLimitSevenDay       RateLimitType = "seven_day"
	RateLimitSevenDayOpus   RateLimitType = "seven_day_opus"
	RateLimitSevenDaySonnet RateLimitType = "seven_day_sonnet"
	RateLimitOverage        RateLimitType = "overage"
)

type Result

type Result struct {
	Message Message
	Err     error
}

Result pairs a streamed Message with a terminal error. Exactly one is set: a non-nil Err (other than io.EOF, which is not surfaced) ends the stream.

type ResultMessage

type ResultMessage struct {
	Subtype           string           `json:"subtype"`
	IsError           bool             `json:"is_error"`
	Errors            []string         `json:"errors,omitempty"`
	DurationMs        int              `json:"duration_ms"`
	DurationAPIMs     int              `json:"duration_api_ms,omitempty"`
	NumTurns          int              `json:"num_turns"`
	StopReason        string           `json:"stop_reason,omitempty"`
	TotalCostUSD      float64          `json:"total_cost_usd,omitempty"`
	Usage             Usage            `json:"usage"`
	ModelUsage        json.RawMessage  `json:"model_usage,omitempty"`
	Result            string           `json:"result,omitempty"`
	StructuredOutput  json.RawMessage  `json:"structured_output,omitempty"`
	PermissionDenials json.RawMessage  `json:"permission_denials,omitempty"`
	DeferredToolUse   *DeferredToolUse `json:"deferred_tool_use,omitempty"`
	APIErrorStatus    *int             `json:"api_error_status,omitempty"`
	SessionID         string           `json:"session_id"`
	UUID              string           `json:"uuid,omitempty"`
	Raw               json.RawMessage
}

ResultMessage terminates a turn, summarizing cost, duration, and outcome.

type SDKSessionInfo

type SDKSessionInfo struct {
	SessionID    string `json:"session_id"`
	Summary      string `json:"summary"`
	LastModified int64  `json:"last_modified"` // epoch milliseconds
	FileSize     int64  `json:"file_size"`
	CustomTitle  string `json:"custom_title,omitempty"`
	FirstPrompt  string `json:"first_prompt,omitempty"`
	GitBranch    string `json:"git_branch,omitempty"`
	Cwd          string `json:"cwd,omitempty"`
	Tag          string `json:"tag,omitempty"`
	CreatedAt    int64  `json:"created_at,omitempty"`
}

SDKSessionInfo is metadata about a stored session.

func GetSessionInfo

func GetSessionInfo(sessionID, directory string) (SDKSessionInfo, error)

GetSessionInfo returns metadata for a single session by id.

func ListSessions

func ListSessions(directory string, limit, offset int) ([]SDKSessionInfo, error)

ListSessions returns metadata for sessions in directory, newest first. A limit of 0 means no limit; offset skips that many entries.

type SSEMcpServer

type SSEMcpServer struct {
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers,omitempty"`
}

SSEMcpServer is an external MCP server reached over server-sent events.

type SandboxIgnoreViolations

type SandboxIgnoreViolations struct {
	File    []string `json:"file,omitempty"`
	Network []string `json:"network,omitempty"`
}

SandboxIgnoreViolations lists violations the sandbox should ignore.

type SandboxNetworkConfig

type SandboxNetworkConfig struct {
	AllowedDomains          []string `json:"allowedDomains,omitempty"`
	DeniedDomains           []string `json:"deniedDomains,omitempty"`
	AllowManagedDomainsOnly bool     `json:"allowManagedDomainsOnly,omitempty"`
	AllowUnixSockets        []string `json:"allowUnixSockets,omitempty"`
	AllowAllUnixSockets     bool     `json:"allowAllUnixSockets,omitempty"`
	AllowLocalBinding       bool     `json:"allowLocalBinding,omitempty"`
	AllowMachLookup         []string `json:"allowMachLookup,omitempty"`
	HTTPProxyPort           int      `json:"httpProxyPort,omitempty"`
	SOCKSProxyPort          int      `json:"socksProxyPort,omitempty"`
}

SandboxNetworkConfig configures sandbox network access.

type SandboxSettings

type SandboxSettings struct {
	Enabled                   bool                     `json:"enabled,omitempty"`
	AutoAllowBashIfSandboxed  bool                     `json:"autoAllowBashIfSandboxed,omitempty"`
	ExcludedCommands          []string                 `json:"excludedCommands,omitempty"`
	AllowUnsandboxedCommands  bool                     `json:"allowUnsandboxedCommands,omitempty"`
	Network                   *SandboxNetworkConfig    `json:"network,omitempty"`
	IgnoreViolations          *SandboxIgnoreViolations `json:"ignoreViolations,omitempty"`
	EnableWeakerNestedSandbox bool                     `json:"enableWeakerNestedSandbox,omitempty"`
}

SandboxSettings configures the CLI's command sandbox.

type SdkBeta

type SdkBeta string

SdkBeta names an API beta the SDK understands.

const SdkBetaContext1M SdkBeta = "context-1m-2025-08-07"

type SdkMcpServer

type SdkMcpServer struct {
	Name    string
	Version string
	// contains filtered or unexported fields
}

SdkMcpServer is an in-process MCP server whose tools run inside the host program. Register it with WithSDKMCPServer; the SDK answers the CLI's MCP requests for this server over the control protocol.

func NewSdkMcpServer

func NewSdkMcpServer(name string, opts ...SdkMcpServerOption) *SdkMcpServer

NewSdkMcpServer creates an in-process MCP server named name.

func (*SdkMcpServer) AddTool

func (s *SdkMcpServer) AddTool(t Tool) *SdkMcpServer

AddTool registers a tool and returns the server for chaining.

type SdkMcpServerOption

type SdkMcpServerOption func(*SdkMcpServer)

SdkMcpServerOption configures an SdkMcpServer.

func WithServerVersion

func WithServerVersion(v string) SdkMcpServerOption

WithServerVersion sets the server's advertised version.

func WithTools

func WithTools(tools ...Tool) SdkMcpServerOption

WithTools adds tools to the server.

type SdkPluginConfig

type SdkPluginConfig struct {
	Type string `json:"type"` // always "local"
	Path string `json:"path"`
}

SdkPluginConfig configures a local plugin directory.

type ServerToolName

type ServerToolName string

ServerToolName names a built-in server-side tool.

const (
	ServerToolAdvisor            ServerToolName = "advisor"
	ServerToolWebSearch          ServerToolName = "web_search"
	ServerToolWebFetch           ServerToolName = "web_fetch"
	ServerToolCodeExecution      ServerToolName = "code_execution"
	ServerToolBashCodeExecution  ServerToolName = "bash_code_execution"
	ServerToolTextEditorCodeExec ServerToolName = "text_editor_code_execution"
	ServerToolSearchRegex        ServerToolName = "tool_search_tool_regex"
	ServerToolSearchBM25         ServerToolName = "tool_search_tool_bm25"
)

type ServerToolResultBlock

type ServerToolResultBlock struct {
	ToolUseID string          `json:"tool_use_id"`
	Content   json.RawMessage `json:"content"`
}

ServerToolResultBlock is a server-side tool result.

type ServerToolUseBlock

type ServerToolUseBlock struct {
	ID    string          `json:"id"`
	Name  ServerToolName  `json:"name"`
	Input json.RawMessage `json:"input"`
}

ServerToolUseBlock is a server-side tool invocation.

type SessionKey

type SessionKey struct {
	ProjectKey string
	SessionID  string
	Subpath    string
}

SessionKey identifies a session (optionally a subagent subpath) within a project.

type SessionListSubkeysKey

type SessionListSubkeysKey struct {
	ProjectKey string
	SessionID  string
}

SessionListSubkeysKey identifies a session whose subkeys are being listed.

type SessionMessage

type SessionMessage struct {
	Type            string          `json:"type"` // "user" | "assistant"
	UUID            string          `json:"uuid"`
	SessionID       string          `json:"session_id"`
	ParentToolUseID string          `json:"parent_tool_use_id,omitempty"`
	Message         json.RawMessage `json:"message"`
}

SessionMessage is one transcript entry from a session file.

func GetSessionMessages

func GetSessionMessages(sessionID, directory string, limit, offset int) ([]SessionMessage, error)

GetSessionMessages reads the conversation transcript for a session. A limit of 0 means all messages; offset skips that many entries.

func GetSubagentMessages

func GetSubagentMessages(sessionID, agentID, directory string, limit, offset int) ([]SessionMessage, error)

GetSubagentMessages reads the transcript for one subagent within a session.

type SessionStore

type SessionStore interface {
	Append(ctx context.Context, key SessionKey, entries []SessionStoreEntry) error
	Load(ctx context.Context, key SessionKey) ([]SessionStoreEntry, error)
	ListSessions(ctx context.Context, projectKey string) ([]SessionStoreListEntry, error)
	ListSessionSummaries(ctx context.Context, projectKey string) ([]SessionSummaryEntry, error)
	ListSubkeys(ctx context.Context, key SessionListSubkeysKey) ([]string, error)
	Delete(ctx context.Context, key SessionKey) error
}

SessionStore is an abstract transcript store, mirroring the official SDK's SessionStore. Implementations persist session entries keyed by project and session id; InMemorySessionStore is the built-in implementation.

type SessionStoreEntry

type SessionStoreEntry struct {
	Data json.RawMessage
}

SessionStoreEntry is one stored transcript line (a raw JSON object).

type SessionStoreFlushMode

type SessionStoreFlushMode string

SessionStoreFlushMode controls when a store flushes pending writes.

const (
	// FlushBatched flushes on each result message (explicit flush points).
	FlushBatched SessionStoreFlushMode = "batched"
	// FlushEager flushes eagerly as entries arrive.
	FlushEager SessionStoreFlushMode = "eager"
)

type SessionStoreListEntry

type SessionStoreListEntry struct {
	SessionID string
	Mtime     int64
}

SessionStoreListEntry is a session id with its last-modified marker.

type SessionSummaryEntry

type SessionSummaryEntry struct {
	SessionID string
	Summary   string
	Mtime     int64
	// Data holds derived summary state (first_prompt, created_at, cwd, ...)
	// persisted verbatim by stores. It mirrors the official SDK's opaque
	// summary data dict.
	Data map[string]any
}

SessionSummaryEntry is a session summary with its last-modified marker.

func FoldSessionSummary

func FoldSessionSummary(prev *SessionSummaryEntry, key SessionKey, entries []SessionStoreEntry) SessionSummaryEntry

FoldSessionSummary folds a batch of appended entries into the running summary for key, without re-reading the transcript. prev is the previous summary for the same key (or nil for the first append). Mtime is left for the adapter to stamp after persisting (0 for a new summary), matching the official SDK.

Do not call this for keys with a Subpath — subagent transcripts must not contribute to the main session's summary.

type SettingSource

type SettingSource string

SettingSource names a filesystem settings source the CLI may load.

const (
	SettingSourceUser    SettingSource = "user"
	SettingSourceProject SettingSource = "project"
	SettingSourceLocal   SettingSource = "local"
)

type StdioMcpServer

type StdioMcpServer struct {
	Command string            `json:"command"`
	Args    []string          `json:"args,omitempty"`
	Env     map[string]string `json:"env,omitempty"`
}

StdioMcpServer is an external MCP server launched as a subprocess by the CLI.

type StopHookInput

type StopHookInput struct {
	BaseHookInput
	StopHookActive bool `json:"stop_hook_active"`
}

StopHookInput is the payload for HookStop and HookSubagentStop.

func DecodeStop

func DecodeStop(raw json.RawMessage) (StopHookInput, error)

DecodeStop decodes a HookStop or HookSubagentStop payload.

type StreamEvent

type StreamEvent struct {
	UUID            string          `json:"uuid,omitempty"`
	SessionID       string          `json:"session_id"`
	ParentToolUseID string          `json:"parent_tool_use_id,omitempty"`
	Event           json.RawMessage `json:"event"`
	Raw             json.RawMessage
}

StreamEvent is a partial/delta event, emitted only when partial messages are enabled. Event holds the raw streaming event payload.

type SubagentStartHookInput

type SubagentStartHookInput struct {
	BaseHookInput
	AgentID   string `json:"agent_id,omitempty"`
	AgentType string `json:"agent_type,omitempty"`
}

SubagentStartHookInput is the payload for a subagent-start hook.

type SubagentStartHookSpecificOutput

type SubagentStartHookSpecificOutput struct {
	HookEventName     string `json:"hookEventName"` // "SubagentStart"
	AdditionalContext string `json:"additionalContext,omitempty"`
}

SubagentStartHookSpecificOutput is the typed hook-specific output for subagent-start events.

type SubagentStopHookInput

type SubagentStopHookInput struct {
	BaseHookInput
	StopHookActive      bool   `json:"stop_hook_active"`
	AgentID             string `json:"agent_id,omitempty"`
	AgentTranscriptPath string `json:"agent_transcript_path,omitempty"`
	AgentType           string `json:"agent_type,omitempty"`
}

SubagentStopHookInput is the payload for HookSubagentStop.

func DecodeSubagentStop

func DecodeSubagentStop(raw json.RawMessage) (SubagentStopHookInput, error)

DecodeSubagentStop decodes a HookSubagentStop payload.

type SystemMessage

type SystemMessage struct {
	Subtype   string
	SessionID string
	// Tools is populated for the "init" subtype.
	Tools []string
	// Plugins is populated for the "init" subtype with the loaded plugins.
	Plugins []PluginInfo
	// Data is the full system payload for subtype-specific access.
	Data json.RawMessage
	Raw  json.RawMessage
}

SystemMessage carries out-of-band events from the CLI. Subtype distinguishes the payload (for example "init" or "session_state_changed"); subtype-specific fields are populated where known, and Data holds the full payload.

type SystemPromptMode

type SystemPromptMode int

SystemPromptMode selects how the system prompt is configured.

type TaskBudget

type TaskBudget struct {
	Total int `json:"total"`
}

TaskBudget caps a task's token budget.

type TaskNotificationMessage

type TaskNotificationMessage struct {
	TaskID     string                 `json:"task_id"`
	Status     TaskNotificationStatus `json:"status"`
	Summary    string                 `json:"summary"`
	OutputFile string                 `json:"output_file"`
	SessionID  string                 `json:"session_id"`
	UUID       string                 `json:"uuid,omitempty"`
	ToolUseID  string                 `json:"tool_use_id,omitempty"`
	Usage      *TaskUsage             `json:"usage,omitempty"`
	Raw        json.RawMessage
}

TaskNotificationMessage reports a task completion/failure/stop from the CLI. Typed fields are populated where present; Raw holds the full payload.

type TaskNotificationStatus

type TaskNotificationStatus string

TaskNotificationStatus is the terminal state of a task.

const (
	TaskCompleted TaskNotificationStatus = "completed"
	TaskFailed    TaskNotificationStatus = "failed"
	TaskStopped   TaskNotificationStatus = "stopped"
)

type TaskProgressMessage

type TaskProgressMessage struct {
	TaskID       string    `json:"task_id"`
	Description  string    `json:"description"`
	Usage        TaskUsage `json:"usage"`
	UUID         string    `json:"uuid"`
	SessionID    string    `json:"session_id"`
	ToolUseID    string    `json:"tool_use_id,omitempty"`
	LastToolName string    `json:"last_tool_name,omitempty"`
	Raw          json.RawMessage
}

TaskProgressMessage reports incremental progress for a running task.

type TaskStartedMessage

type TaskStartedMessage struct {
	TaskID      string `json:"task_id"`
	Description string `json:"description"`
	UUID        string `json:"uuid"`
	SessionID   string `json:"session_id"`
	ToolUseID   string `json:"tool_use_id,omitempty"`
	TaskType    string `json:"task_type,omitempty"`
	Raw         json.RawMessage
}

TaskStartedMessage reports that a (sub)task has started.

type TaskUpdatedMessage added in v0.2.0

type TaskUpdatedMessage struct {
	TaskID    string            `json:"task_id"`
	Patch     json.RawMessage   `json:"patch"`
	Status    TaskUpdatedStatus `json:"-"` // extracted from patch.status
	SessionID string            `json:"session_id,omitempty"`
	UUID      string            `json:"uuid,omitempty"`
	Raw       json.RawMessage
}

TaskUpdatedMessage is emitted as a background task's state changes (system/task_updated). Patch carries the changed fields (e.g. status, end_time); Status mirrors patch.status when present. A task's terminal state can arrive *only* here (no accompanying TaskNotificationMessage) — for example a task stopped via StopTask reports Status "killed". Use IsTerminalTaskStatus to detect completion across both message types.

type TaskUpdatedStatus added in v0.2.0

type TaskUpdatedStatus string

TaskUpdatedStatus is the status reported inside a task_updated patch. pending/running/paused are non-terminal; completed/failed/killed are terminal. task_updated reports the raw "killed"; the CLI maps that to "stopped" only when it also emits a task_notification.

const (
	TaskUpdatedPending   TaskUpdatedStatus = "pending"
	TaskUpdatedRunning   TaskUpdatedStatus = "running"
	TaskUpdatedPaused    TaskUpdatedStatus = "paused"
	TaskUpdatedCompleted TaskUpdatedStatus = "completed"
	TaskUpdatedFailed    TaskUpdatedStatus = "failed"
	TaskUpdatedKilled    TaskUpdatedStatus = "killed"
)

type TaskUsage

type TaskUsage struct {
	TotalTokens int `json:"total_tokens"`
	ToolUses    int `json:"tool_uses"`
	DurationMs  int `json:"duration_ms"`
}

TaskUsage summarizes resource use for a task.

type TextBlock

type TextBlock struct {
	Text string `json:"text"`
}

TextBlock is plain text content.

type ThinkingBlock

type ThinkingBlock struct {
	Thinking  string `json:"thinking"`
	Signature string `json:"signature,omitempty"`
}

ThinkingBlock is extended-thinking content emitted by the model.

type ThinkingConfig

type ThinkingConfig interface {
	// contains filtered or unexported methods
}

ThinkingConfig is the union of thinking configuration shapes: ThinkingConfigAdaptive, ThinkingConfigEnabled, ThinkingConfigDisabled.

type ThinkingConfigAdaptive

type ThinkingConfigAdaptive struct {
	Type    string          `json:"type"` // "adaptive"
	Display ThinkingDisplay `json:"display,omitempty"`
}

ThinkingConfigAdaptive enables adaptive thinking.

type ThinkingConfigDisabled

type ThinkingConfigDisabled struct {
	Type string `json:"type"` // "disabled"
}

ThinkingConfigDisabled disables thinking.

type ThinkingConfigEnabled

type ThinkingConfigEnabled struct {
	Type         string          `json:"type"` // "enabled"
	BudgetTokens int             `json:"budget_tokens"`
	Display      ThinkingDisplay `json:"display,omitempty"`
}

ThinkingConfigEnabled enables thinking with a fixed token budget.

type ThinkingDisplay

type ThinkingDisplay string

ThinkingDisplay controls how thinking output is shown.

const (
	ThinkingDisplaySummarized ThinkingDisplay = "summarized"
	ThinkingDisplayOmitted    ThinkingDisplay = "omitted"
)

type Tool

type Tool struct {
	Name        string
	Description string
	// InputSchema is the tool's JSON Schema. When nil, an empty object schema
	// is advertised.
	InputSchema json.RawMessage
	// Annotations advertises behavior hints (read-only, destructive, ...).
	Annotations *ToolAnnotations
	Handler     ToolHandler
}

Tool is an in-process tool exposed to the agent through an SdkMcpServer.

func NewTool

func NewTool[T any](name, description string, fn func(ctx context.Context, in T) (ToolResult, error)) Tool

NewTool builds a typed tool. The input JSON Schema is derived from T's struct fields (using `json` tags for names), and the handler receives T already decoded from the model's arguments. This is the ergonomic way to define a tool; for full control over the schema, construct a Tool directly.

type ToolAnnotations

type ToolAnnotations = McpToolAnnotations

ToolAnnotations is an alias of McpToolAnnotations for parity with the official naming.

type ToolHandler

type ToolHandler func(ctx context.Context, args json.RawMessage) (ToolResult, error)

ToolHandler executes an in-process tool. args holds the raw JSON arguments provided by the model.

type ToolResult

type ToolResult struct {
	// Content is the result payload, typically one or more [TextBlock]s.
	Content []ContentBlock
	IsError bool
}

ToolResult is the outcome of a ToolHandler.

func ErrorResult

func ErrorResult(text string) ToolResult

ErrorResult is a convenience constructor for an error text ToolResult.

func TextResult

func TextResult(text string) ToolResult

TextResult is a convenience constructor for a successful text ToolResult.

type ToolResultBlock

type ToolResultBlock struct {
	ToolUseID string          `json:"tool_use_id"`
	Content   json.RawMessage `json:"content,omitempty"`
	IsError   bool            `json:"is_error,omitempty"`
}

ToolResultBlock is the result of a tool invocation, referenced back to the originating ToolUseBlock by ToolUseID. Content is the raw JSON of the result, which the CLI may encode as a string or as an array of nested content blocks; use ToolResultBlock.Text or decode Content directly.

func (*ToolResultBlock) Text

func (b *ToolResultBlock) Text() (string, bool)

Text returns the textual content of the result when it is encoded as a plain string. The second return value reports whether Content was a JSON string.

type ToolUseBlock

type ToolUseBlock struct {
	ID    string          `json:"id"`
	Name  string          `json:"name"`
	Input json.RawMessage `json:"input"`
}

ToolUseBlock is a request by the model to invoke a tool. Input holds the raw JSON arguments; decode it into a concrete type as needed.

type Usage

type Usage struct {
	InputTokens              int `json:"input_tokens"`
	OutputTokens             int `json:"output_tokens"`
	CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
	CacheReadInputTokens     int `json:"cache_read_input_tokens,omitempty"`
}

Usage reports token usage for a turn or result.

type UserMessage

type UserMessage struct {
	Content         []ContentBlock
	ParentToolUseID string
	UUID            string          `json:"uuid,omitempty"`
	ToolUseResult   json.RawMessage `json:"tool_use_result,omitempty"`
	Raw             json.RawMessage
}

UserMessage is a user turn, including synthesized tool-result turns.

type UserPromptSubmitHookInput

type UserPromptSubmitHookInput struct {
	BaseHookInput
	Prompt string `json:"prompt"`
}

UserPromptSubmitHookInput is the payload for HookUserPromptSubmit.

func DecodeUserPromptSubmit

func DecodeUserPromptSubmit(raw json.RawMessage) (UserPromptSubmitHookInput, error)

DecodeUserPromptSubmit decodes a HookUserPromptSubmit payload.

Directories

Path Synopsis
examples
agents command
Command agents demonstrates defining a subagent the main agent can delegate to via the Agent tool.
Command agents demonstrates defining a subagent the main agent can delegate to via the Agent tool.
collect command
Command collect demonstrates the Collect convenience (gather all messages at once) and reading typed fields off the result.
Command collect demonstrates the Collect convenience (gather all messages at once) and reading typed fields off the result.
customtool command
Command customtool demonstrates exposing an in-process Go tool to the agent via an SDK MCP server.
Command customtool demonstrates exposing an in-process Go tool to the agent via an SDK MCP server.
filesystem command
Command filesystem demonstrates an agent reading, writing, and editing files in a working directory.
Command filesystem demonstrates an agent reading, writing, and editing files in a working directory.
hooks command
Command hooks demonstrates lifecycle hooks: a PreToolUse hook logs and can block tool calls, using the typed hook-input decoder.
Command hooks demonstrates lifecycle hooks: a PreToolUse hook logs and can block tool calls, using the typed hook-input decoder.
interactive command
Command interactive is a multi-turn example using the bidirectional Client: it reads prompts from stdin, streams each response, and supports runtime control (here, switching the model after the first turn).
Command interactive is a multi-turn example using the bidirectional Client: it reads prompts from stdin, streams each response, and supports runtime control (here, switching the model after the first turn).
interrupt command
Command interrupt demonstrates interrupting an in-flight turn with the bidirectional Client.
Command interrupt demonstrates interrupting an in-flight turn with the bidirectional Client.
options command
Command options demonstrates several configuration options at once: a custom system prompt, setting sources, a budget cap, partial-message streaming, and an stderr sink.
Command options demonstrates several configuration options at once: a custom system prompt, setting sources, a budget cap, partial-message streaming, and an stderr sink.
partial_messages command
Command partial_messages demonstrates streaming partial message events as they arrive.
Command partial_messages demonstrates streaming partial message events as they arrive.
permission command
Command permission demonstrates a CanUseTool callback that approves reads but denies writes, rewriting tool input where useful.
Command permission demonstrates a CanUseTool callback that approves reads but denies writes, rewriting tool input where useful.
plugins command
Command plugins demonstrates loading a local plugin and confirming it loaded by inspecting the init system message.
Command plugins demonstrates loading a local plugin and confirming it loaded by inspecting the init system message.
query command
Command query is a one-shot example: it sends a single prompt and prints the final result.
Command query is a one-shot example: it sends a single prompt and prints the final result.
sessions command
Command sessions lists stored Claude Code sessions for the current directory and prints the transcript of the most recent one.
Command sessions lists stored Claude Code sessions for the current directory and prints the transcript of the most recent one.
stderr command
Command stderr demonstrates capturing the CLI subprocess's stderr for logging and debugging.
Command stderr demonstrates capturing the CLI subprocess's stderr for logging and debugging.
thinking command
Command thinking demonstrates configuring extended thinking via the typed ThinkingConfig union.
Command thinking demonstrates configuring extended thinking via the typed ThinkingConfig union.
tools_option command
Command tools_option demonstrates restricting the agent's available tools with the --tools option.
Command tools_option demonstrates restricting the agent's available tools with the --tools option.
internal
protocol
Package protocol implements the bidirectional control protocol layered on the CLI's stream-json connection: request/response correlation by request_id, the initialize handshake, and dispatch of inbound control requests (permissions, hooks, MCP) to handlers supplied by the root package.
Package protocol implements the bidirectional control protocol layered on the CLI's stream-json connection: request/response correlation by request_id, the initialize handshake, and dispatch of inbound control requests (permissions, hooks, MCP) to handlers supplied by the root package.
transport
Package transport manages the `claude` CLI subprocess and the newline- delimited stream-json framing on its stdin/stdout.
Package transport manages the `claude` CLI subprocess and the newline- delimited stream-json framing on its stdin/stdout.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL