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

claude

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2026 License: MIT Imports: 28 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.291 (the version the upstream SDK bundles, pinned as claude.SupportedCLIVersion), statically (133/133 public names, 49/49 options) and behaviorally (integration and e2e suites that run 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. To send content a string cannot hold, such as images, pass user message frames to claude.QueryMessages (or Client.QueryMessages).

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
})
Shadowing

A CanUseTool callback is only consulted for tool calls that are not already approved. Two things auto-approve a call before the callback runs:

  • an WithAllowedTools entry that allows a whole tool ("Read", "Read()", "Read(*)"), as opposed to specific invocations ("Bash(ls:*)");
  • WithPermissionMode(claude.PermissionBypass), which approves everything.

The callback then simply never fires for those tools, which looks exactly like it having granted permission. When a WithStderr writer is set, the SDK writes a warning naming the shadowed tools on connect. To check programmatically:

opts := []claude.Option{
	claude.WithCanUseTool(cb),
	claude.WithAllowedTools("Read"),
}
if shadowed := claude.CanUseToolShadowed(opts...); len(shadowed) > 0 {
	log.Printf("CanUseTool will not fire for: %v", shadowed)
}
msgs, err := claude.Collect(ctx, prompt, opts...)

Shadowing is sometimes intentional (a callback that only gates tools outside allowedTools), so it is advisory rather than an error. To gate every tool call, use a PreToolUse hook instead, or narrow the entry so calls fall through to the callback. Allow rules in settings files can shadow the callback too, and are not visible to this check.

Untrusted prompt text

Claude Code expands an @/absolute/path mention in a prompt into that file's contents before the model runs, and dispatches a leading /name as a slash command. Neither depends on the tools you allow. If prompts include text the end user did not type (earlier turns, tool output, third-party content), set claude.WithVerbatimPrompts() so every prompt is delivered as written. This needs Claude Code 2.1.248 or later.

Types

The streamed Message union: AssistantMessage, UserMessage, SystemMessage, ResultMessage, StreamEvent, TaskStartedMessage, TaskProgressMessage, TaskNotificationMessage, TaskUpdatedMessage, RateLimitEvent, ConversationResetMessage, HookEventMessage, MirrorErrorMessage. Frame types the SDK does not know are skipped. UserMessage.Origin and ResultMessage.Origin tell your own turns from ones the session injected, such as background-task notifications. Content blocks: TextBlock, ThinkingBlock, ToolUseBlock, ToolResultBlock, ServerToolUseBlock, ServerToolResultBlock.

Error handling

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

When a run fails, the CLI sends a ResultMessage with IsError set and exits non-zero. The stream then ends with a *ResultError carrying that result's payload, so you can branch on why it failed. It unwraps to a *ProcessError.

var re *claude.ResultError
if errors.As(err, &re) {
	log.Printf("run failed: subtype=%s reason=%s: %s", re.Subtype, re.TerminalReason, re.Message)
}

Sessions

Read on-disk transcripts (no running CLI needed): ListSessions, GetSessionInfo, GetSessionMessages, ListSubagents, GetSubagentMessages; change them with RenameSession, TagSession, DeleteSession, and ForkSession. Pass a directory to scope to that project and its git worktrees, or "" for every project. A SessionStore interface with InMemorySessionStore, the *FromStore readers, the *ViaStore mutations, FoldSessionSummary, and ImportSessionToStore mirrors the upstream session API. Live mirroring is available via WithSessionStore. Adding WithResume or WithContinueConversation resumes the session from the store, so the local transcript does not need to exist; the caller's credentials and user settings carry over.

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.291): all 133 public __all__ names and all 49 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.291"

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.4.1"

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 ErrSessionNotFound = errors.New("claude: session not found")

ErrSessionNotFound reports that a session (or its summary) could not be found. Match it with errors.Is.

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 Bool added in v0.4.0

func Bool(v bool) *bool

Bool returns a pointer to v, for optional fields such as the ToolAnnotations hints.

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 CanUseToolShadowed added in v0.3.0

func CanUseToolShadowed(opts ...Option) []string

CanUseToolShadowed reports the tools for which a CanUseTool callback will never be invoked, because something auto-approves them first.

A tool call is auto-approved before the callback is consulted when WithPermissionMode is PermissionBypass, or when an WithAllowedTools entry allows a whole tool ("Read", "Read()", "Read(*)") rather than specific invocations ("Bash(ls:*)"). The result is a silent misconfiguration: the callback simply never fires for those tools, which is indistinguishable from it having granted permission.

It returns nil when no callback is configured or nothing is shadowed. Under bypassPermissions every tool is shadowed, which is reported as the single entry "*" since the set is not enumerable from the options alone.

This is advisory. Shadowing can be intentional, for example a callback used solely for tools outside allowedTools, so it is never an error. The SDK also writes this diagnostic to the WithStderr writer when one is set. Allow rules from settings files can shadow the callback too but are not visible here.

To gate every tool call regardless, use a PreToolUse hook instead, or narrow the allowedTools entry so calls fall through to the callback.

Pass the same options you would pass to Query, Collect, or NewClient:

shadowed := claude.CanUseToolShadowed(
	claude.WithCanUseTool(cb),
	claude.WithAllowedTools("Read"),
)

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 DeleteSession added in v0.4.0

func DeleteSession(sessionID, directory string) error

DeleteSession permanently removes a session's transcript and its subagent directory. For a soft delete, tag the session and filter on listing. Directory resolution is as for RenameSession.

func DeleteSessionViaStore

func DeleteSessionViaStore(ctx context.Context, store SessionStore, sessionID, directory string) error

DeleteSessionViaStore deletes a session from the store. A store without Delete support (errors.ErrUnsupported) makes this a no-op. Whether subagent transcripts go too depends on the store; InMemorySessionStore removes them.

func ImportSessionToStore

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

ImportSessionToStore replays a local session transcript into a store, appending in batches of up to the batch size or 1 MiB of lines. Use it to move local sessions to a remote store, or to fill a gap a MirrorErrorMessage reported. Stores should treat each entry's uuid as an idempotency key so a re-import is safe.

The project key is the name of the on-disk project directory the file was found in, the key the live mirror would have used, so an imported session resumes like a mirrored one. Subagent transcripts are imported under their subagents/... subpaths, each followed by its .meta.json sidecar as an agent_metadata entry.

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 ids of a session's subagents, from the agent-<id>.jsonl transcripts under <session>/subagents/.

func ListSubagentsFromStore added in v0.4.0

func ListSubagentsFromStore(ctx context.Context, store SessionStore, sessionID, directory string) ([]string, error)

ListSubagentsFromStore returns a session's subagent ids from a store's subagents/.../agent-<id> subkeys. It fails if the store does not support ListSubkeys.

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, which defaults to the current directory. The path is made absolute and symlinks are resolved first, as the CLI does, so keys match between local transcripts and store-mirrored ones.

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.

With hooks, WithCanUseTool or SDK MCP servers, stdin stays open past the result so the CLI can still ask the SDK questions: until the CLI reports the session idle (a background agent's completion can wake a follow-up turn), or until CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS (10 minutes by default, 0 for no limit) passes between turns with the CLI still busy. A CLI that does not report session state ends input at the first result with no background agent in flight.

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

func QueryMessages added in v0.4.0

func QueryMessages(ctx context.Context, msgs iter.Seq[map[string]any], opts ...Option) iter.Seq2[Message, error]

QueryMessages is Query with streamed user messages instead of a string prompt, the counterpart of passing an async iterable to the official query(). See Client.QueryMessages for the message shape. Input ends once every message is written (when callbacks need the control channel, once the last message's run has ended, as Query describes); if msgs yields nothing, it ends at once.

func RenameSession added in v0.4.0

func RenameSession(sessionID, title, directory string) error

RenameSession sets a session's title by appending a custom-title entry; the last one wins. The title is trimmed and must be non-empty. With a directory it looks in that project and its git worktrees; with "" it searches every project. A missing session returns an error wrapping ErrSessionNotFound.

func RenameSessionViaStore

func RenameSessionViaStore(ctx context.Context, store SessionStore, sessionID, title, directory string) error

RenameSessionViaStore sets a session's title by appending a custom-title entry to the store, under the project key for directory (the current directory when empty).

func SessionsDir

func SessionsDir(directory string) (string, error)

SessionsDir returns the directory holding session files for the given working directory (the current directory when empty), under the config dir (CLAUDE_CONFIG_DIR, else ~/.claude).

func TagSession added in v0.4.0

func TagSession(sessionID, tag, directory string) error

TagSession sets a session's tag by appending a tag entry; the last one wins, and "" clears it. Tags are stripped of invisible and formatting characters. Directory resolution is as for RenameSession.

func TagSessionViaStore

func TagSessionViaStore(ctx context.Context, store SessionStore, sessionID, tag, directory string) error

TagSessionViaStore sets a session's tag by appending a tag entry to the store; "" clears it. Tags are sanitized as by TagSession.

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 entries are server names (string) or inline configs
	// (map[string]any of name to config).
	MCPServers    []any  `json:"mcpServers,omitempty"`
	InitialPrompt string `json:"initialPrompt,omitempty"`
	MaxTurns      int    `json:"maxTurns,omitempty"`
	// Background, when set, runs the agent in the background (true) or the
	// foreground (false); nil leaves the choice to the model.
	Background *bool `json:"background,omitempty"`
	// Effort is an [EffortLevel] or an integer.
	Effort         any    `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 is set when the turn failed, such as ErrorRateLimit.
	Error AssistantMessageError `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 AssistantMessageError added in v0.4.0

type AssistantMessageError string

AssistantMessageError classifies a failed assistant turn.

const (
	ErrorAuthenticationFailed AssistantMessageError = "authentication_failed"
	ErrorBillingError         AssistantMessageError = "billing_error"
	ErrorRateLimit            AssistantMessageError = "rate_limit"
	ErrorInvalidRequest       AssistantMessageError = "invalid_request"
	ErrorServerError          AssistantMessageError = "server_error"
	ErrorUnknown              AssistantMessageError = "unknown"
)

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) QueryMessages added in v0.4.0

func (c *Client) QueryMessages(ctx context.Context, msgs iter.Seq[map[string]any]) error

QueryMessages streams user messages to the CLI, the counterpart of passing an async iterable to the official client.query. Each message is a stream-json user frame, such as

{"type": "user", "message": {"role": "user", "content": [...]}, "parent_tool_use_id": nil}

which can carry content blocks (images, documents) or an "origin" that a string prompt cannot. A message without session_id is sent to the "default" session. The caller's maps are not modified.

func (*Client) QueryMessagesSession added in v0.4.0

func (c *Client) QueryMessagesSession(ctx context.Context, msgs iter.Seq[map[string]any], sessionID string) error

QueryMessagesSession is Client.QueryMessages with a session id for messages that do not set one.

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), which is 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, as read from its TaskStartedMessage.

The CLI then reports the task's end as a TaskUpdatedMessage with a terminal status ("killed" for a stopped task). A TaskNotificationMessage with status "stopped" may follow but is sometimes suppressed, so clear the task id on a terminal status from either message (see IsTerminalTaskStatus).

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 ConversationResetMessage added in v0.4.0

type ConversationResetMessage struct {
	// NewConversationID identifies the fresh conversation, for keying an empty
	// transcript. It is not the SessionID of later messages; read that from
	// the next message.
	NewConversationID string `json:"new_conversation_id"`
	UUID              string `json:"uuid"`
	// SessionID is the session that was reset; later messages carry a new one.
	SessionID string `json:"session_id"`
	Raw       json.RawMessage
}

ConversationResetMessage reports that the session's conversation was replaced without ending the connection, for example after /clear. The reset clears the history and zeroes the running totals on later [ResultMessage]s (such as TotalCostUSD), so snapshot accumulated totals when it arrives.

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 ForkSession added in v0.4.0

func ForkSession(sessionID, directory, upToMessageID, title string) (ForkSessionResult, error)

ForkSession copies a session into a new one, remapping every message UUID and keeping the parentUuid chain, and returns the new id. upToMessageID, if set, keeps the transcript up to and including that message. title names the fork; when empty, the source's title with " (fork)" is used. File-history snapshots are not copied. Directory resolution is as for RenameSession.

func ForkSessionViaStore

func ForkSessionViaStore(ctx context.Context, store SessionStore, sessionID, directory, upToMessageID, title string) (ForkSessionResult, error)

ForkSessionViaStore forks a session within the store, as ForkSession does on disk. The entries pass through this process so every UUID is remapped; a storage-level copy would not be a fork.

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 to "block", blocks the action.
	Decision string
	// SystemMessage is a warning shown to the user.
	SystemMessage string
	// Reason is feedback for Claude about the decision.
	Reason string
	// Continue, when non-nil and false, halts the agent.
	Continue *bool
	// StopReason is the message shown when Continue is false.
	StopReason string
	// SuppressOutput hides the hook's stdout from the transcript.
	SuppressOutput bool
	// HookSpecificOutput carries event-specific structured output, such as a
	// [PreToolUseHookSpecificOutput] permission decision.
	HookSpecificOutput json.RawMessage
	// Async defers the hook: the CLI continues without waiting for it.
	// AsyncTimeout bounds the deferred run, in milliseconds.
	Async        bool
	AsyncTimeout int
}

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

type ImageBlock added in v0.4.0

type ImageBlock struct {
	Data     string `json:"data"`
	MimeType string `json:"mimeType"`
}

ImageBlock is base64-encoded image data, for in-process tool results.

type ImportOption

type ImportOption func(*importConfig)

ImportOption configures ImportSessionToStore.

func ImportBatchSize

func ImportBatchSize(n int) ImportOption

ImportBatchSize sets the maximum entries per Append call (default 500).

func ImportDirectory

func ImportDirectory(dir string) ImportOption

ImportDirectory sets the project directory to find the session in. When unset, every project directory is searched.

func ImportIncludeSubagents

func ImportIncludeSubagents(v bool) ImportOption

ImportIncludeSubagents sets whether subagent transcripts under <session>/subagents/ and their .meta.json sidecars are imported too (default true).

type InMemorySessionStore

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

InMemorySessionStore is an in-memory SessionStore, suitable for tests and ephemeral mirrors. It maintains folded session summaries on Append and strictly increasing wall-clock mtimes, as the official implementation does.

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

Delete removes a key; deleting a main transcript also removes its summary and subagent subkeys.

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 ListSessionsOption added in v0.4.0

type ListSessionsOption func(*listSessionsConfig)

ListSessionsOption configures ListSessions.

func ListIncludeWorktrees added in v0.4.0

func ListIncludeWorktrees(v bool) ListSessionsOption

ListIncludeWorktrees sets whether listing a directory inside a git repository also includes sessions from the repository's other worktrees. Default true.

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.

const (
	McpConnected McpServerConnectionStatus = "connected"
	McpFailed    McpServerConnectionStatus = "failed"
	McpNeedsAuth McpServerConnectionStatus = "needs-auth"
	McpPending   McpServerConnectionStatus = "pending"
	McpDisabled  McpServerConnectionStatus = "disabled"
)

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     McpServerConnectionStatus `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 is a tool's behavior hints as reported in MCP server status (see McpToolInfo).

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, RateLimitEvent, ConversationResetMessage, the task lifecycle messages (TaskStartedMessage, TaskProgressMessage, TaskNotificationMessage, TaskUpdatedMessage), HookEventMessage, and MirrorErrorMessage. Frame types this version does not know are skipped.

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 MessageOrigin added in v0.4.0

type MessageOrigin struct {
	Kind MessageOriginKind `json:"kind"`
	// Server is the MCP server a channel message arrived on.
	Server string `json:"server,omitempty"`
	// From is the sender address of a peer or observer message. It is asserted
	// by the sender: use it for routing and display, not as proof of identity.
	From string `json:"from,omitempty"`
	// Name is a peer sender's display name, normalized by the CLI.
	Name string `json:"name,omitempty"`
	// FromSession is a peer sender's host-openable session id, if provided.
	FromSession string `json:"fromSession,omitempty"`
	// SenderTaskID is the task id of the in-process background subagent that
	// sent a peer or observer message.
	SenderTaskID string `json:"senderTaskId,omitempty"`
	// Body is a peer message's decoded body with the envelope stripped, as the
	// model saw it.
	Body string `json:"body,omitempty"`
	// VerifiedPeerPid is the kernel-verified pid of the process that connected
	// to this session's messaging socket, when verifiable.
	VerifiedPeerPid *int `json:"verifiedPeerPid,omitempty"`
	// Subkind is set on a task-notification origin for a scheduled-task prompt
	// or a message from another of the user's sessions.
	Subkind TaskNotificationOriginSubkind `json:"subkind,omitempty"`
	Raw     json.RawMessage               `json:"-"`
}

MessageOrigin is the provenance of a user-role message and, on a ResultMessage, of the message that triggered the turn. In streaming use one connection interleaves the turns you send with turns the session injects (background-task notifications, scheduled-task prompts, MCP channel messages, messages relayed from peer sessions); the origin tells them apart. Prompts sent through Query or Client.Query carry no origin.

Only Kind is always present; the other fields depend on it. Raw holds the object as the CLI sent it, including keys this version does not model.

func (*MessageOrigin) UnmarshalJSON added in v0.4.0

func (o *MessageOrigin) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes an origin leniently: anything other than an object with a string kind leaves the zero value (no Raw), which the message decoders treat as absent, so a malformed origin never fails the message.

type MessageOriginKind added in v0.4.0

type MessageOriginKind string

MessageOriginKind is the kind of a MessageOrigin. Newer CLI versions may send kinds not listed here; treat an unrecognized kind as not human.

const (
	OriginHuman            MessageOriginKind = "human"
	OriginChannel          MessageOriginKind = "channel"
	OriginPeer             MessageOriginKind = "peer"
	OriginTaskNotification MessageOriginKind = "task-notification"
	OriginCoordinator      MessageOriginKind = "coordinator"
	OriginUnclassified     MessageOriginKind = "unclassified"
	OriginObserver         MessageOriginKind = "observer"
	OriginAutoContinuation MessageOriginKind = "auto-continuation"
	OriginObserverActivity MessageOriginKind = "observer-activity"
)

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 ModelUsage added in v0.3.0

type ModelUsage struct {
	InputTokens              int     `json:"inputTokens"`
	OutputTokens             int     `json:"outputTokens"`
	CacheReadInputTokens     int     `json:"cacheReadInputTokens"`
	CacheCreationInputTokens int     `json:"cacheCreationInputTokens"`
	WebSearchRequests        int     `json:"webSearchRequests"`
	CostUSD                  float64 `json:"costUSD"`
	ContextWindow            int     `json:"contextWindow"`
	MaxOutputTokens          int     `json:"maxOutputTokens"`

	// CanonicalModel is the model id used for the pricing lookup (for example
	// "claude-opus-5"). It may differ from the raw model string this entry is
	// keyed by, which can carry provider-specific ids or aliases.
	CanonicalModel string `json:"canonicalModel,omitempty"`

	// Provider is the API provider that served this model ("firstParty",
	// "bedrock", "vertex", "foundry", "anthropicAws", "anthropicGoogleCloud",
	// "mantle", "gateway").
	Provider string `json:"provider,omitempty"`
}

ModelUsage reports per-model token usage and cost, keyed in ResultMessage.ModelUsage by the raw model string the CLI billed.

The JSON keys here are camelCase, unlike the snake_case used elsewhere in the stream: the CLI passes its modelUsage value through verbatim. Verified against a live result frame from CLI 2.1.222.

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 WithAllSkills added in v0.4.0

func WithAllSkills() Option

WithAllSkills enables every discovered skill: it allows the Skill tool and, unless WithSettingSources is given, loads user and project settings.

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 WithForwardSubagentText added in v0.4.0

func WithForwardSubagentText() Option

WithForwardSubagentText forwards subagent text and thinking blocks on the stream. By default a subagent spawned with the Agent tool surfaces only its tool_use and tool_result blocks, as AssistantMessage and UserMessage values whose ParentToolUseID is the spawning Agent call. With this option its text and thinking arrive the same way, so the nested transcript can be rendered in full.

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 bounds each SessionStore call (Load, ListSessions, ListSubkeys) made while resuming a session from the store (see WithSessionStore). The default is 60 seconds; zero or less uses it. A store that does not answer in time fails the connect with an error instead of hanging.

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-5" 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 WithResumeDropsTurn added in v0.4.0

func WithResumeDropsTurn(uuid string) Option

WithResumeDropsTurn, with WithResumeSessionAt, names the user prompt whose turn the truncating resume means to discard. The CLI then checks that every transcript entry after the truncation point belongs to that turn, and refuses the resume otherwise (for example when the discarded range holds a queued message or task notification the caller never saw). A refusal fails the connect with a *ResultError whose message contains "Resume rejected by --resume-drops-turn:". Treat it as final: clear the fork target and resume plainly rather than retrying.

Set WithResumeSessionAt to the last entry of the turn you keep, and this to the prompt UUID of the turn right after it. An empty uuid is still sent, so the CLI rejects it as malformed rather than the check being silently off.

func WithResumeSessionAt added in v0.4.0

func WithResumeSessionAt(uuid string) Option

WithResumeSessionAt resumes only up to and including the transcript entry with this UUID. Use it with WithResume (usually also WithForkSession) to branch from an earlier point. It accepts any transcript-entry UUID, such as an AssistantMessage UUID seen live or a SessionMessage UUID from GetSessionMessages. See WithResumeDropsTurn for choosing the point.

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.

Combined with WithResume or WithContinueConversation, the session is resumed from the store rather than from a local transcript: it is written to a temporary config dir the CLI runs against (CLAUDE_CONFIG_DIR), seeded with the caller's credentials and user settings, and removed on close. The resume value must be a session UUID. Cannot be combined with WithEnableFileCheckpointing.

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. Called with no sources, the CLI loads no settings files.

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 only the named skills (a SKILL.md name or directory name, or plugin:skill). With no names, every skill is suppressed from the listing. Setting it also adds the matching Skill(name) rules to the allowed tools and, unless WithSettingSources is given, loads user and project settings so installed skills are found. When neither WithSkills nor WithAllSkills is set, the CLI's own defaults apply.

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 WithSystemPromptSnapshot added in v0.4.0

func WithSystemPromptSnapshot(keep bool) Option

WithSystemPromptSnapshot sets whether the session keeps the system prompt it recorded on its first request. It applies to WithSystemPrompt and WithAppendSystemPrompt. With keep true (the CLI default, except in bare mode), every later request, including after a resume, sends the recorded prompt, so a changed prompt has no effect until the session is compacted or a new one starts. With keep false the prompt is rebuilt on every request, for example while iterating on its wording across resumes of one session.

Requires Claude Code 2.1.257 or later. Before 2.1.265, a session with an appended or custom prompt recorded it only when keep was true.

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

func WithVerbatimPrompts added in v0.4.0

func WithVerbatimPrompts() Option

WithVerbatimPrompts delivers every prompt to Claude as written. Each user message the SDK sends is marked client_composed, so Claude Code does not expand @path file mentions or dispatch slash commands in it. Use it when prompt text includes content the end user did not type (prior turns, tool results, third-party text): otherwise an @/absolute/path inside it makes Claude Code read that file into the prompt, whatever tools are allowed.

A turn delivered this way also skips Claude Code's turn-start attachment pass: @server:resource MCP mentions are not expanded, and the prompt goes without the context normally attached to it (nested CLAUDE.md and rules files, skill and tool listings, per-turn reminders). The pass Claude Code runs between tool calls is unaffected, so most of that context arrives after the turn's first tool call.

Requires Claude Code 2.1.248 or later; older versions ignore the marker. When WithStderr is set, connecting to an older CLI with this option on writes a warning there.

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 PermissionRuleValue added in v0.4.0

type PermissionRuleValue struct {
	ToolName    string `json:"toolName"`
	RuleContent string `json:"ruleContent,omitempty"`
}

PermissionRuleValue is one rule in a PermissionUpdate's Rules (a JSON array of these).

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 PermissionUpdateDestination `json:"destination,omitempty"`
}

PermissionUpdate describes a runtime change to the permission ruleset.

type PermissionUpdateDestination added in v0.4.0

type PermissionUpdateDestination string

PermissionUpdateDestination is where a PermissionUpdate is saved.

const (
	DestinationUserSettings    PermissionUpdateDestination = "userSettings"
	DestinationProjectSettings PermissionUpdateDestination = "projectSettings"
	DestinationLocalSettings   PermissionUpdateDestination = "localSettings"
	DestinationSession         PermissionUpdateDestination = "session"
)

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 PostToolUseHookSpecificOutput added in v0.4.0

type PostToolUseHookSpecificOutput struct {
	HookEventName        string          `json:"hookEventName"` // "PostToolUse"
	AdditionalContext    string          `json:"additionalContext,omitempty"`
	UpdatedToolOutput    json.RawMessage `json:"updatedToolOutput,omitempty"`
	UpdatedMCPToolOutput json.RawMessage `json:"updatedMCPToolOutput,omitempty"`
}

PostToolUseHookSpecificOutput is the typed hook-specific output for PostToolUse events. UpdatedToolOutput replaces a built-in tool's output and UpdatedMCPToolOutput an MCP tool's.

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 PreToolUseHookSpecificOutput added in v0.4.0

type PreToolUseHookSpecificOutput struct {
	HookEventName            string          `json:"hookEventName"` // "PreToolUse"
	PermissionDecision       string          `json:"permissionDecision,omitempty"`
	PermissionDecisionReason string          `json:"permissionDecisionReason,omitempty"`
	UpdatedInput             json.RawMessage `json:"updatedInput,omitempty"`
	AdditionalContext        string          `json:"additionalContext,omitempty"`
}

PreToolUseHookSpecificOutput is the typed hook-specific output for PreToolUse events. PermissionDecision is "allow", "deny", "ask", or "defer".

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 ResultError added in v0.4.0

type ResultError struct {
	// Message is the text Error returns: the most informative of the result's
	// errors, result text, subtype, or HTTP status.
	Message string
	// Subtype is the result subtype ("error_max_turns",
	// "error_during_execution", ..., or "success" when the loop completed but
	// the last turn was an API error).
	Subtype string
	// Errors are the error strings the CLI reported (may be empty).
	Errors []string
	// Result is the result text; for API failures, the "API Error: ..." prose.
	Result string
	// APIErrorStatus is the HTTP status of the failing API call, if any.
	APIErrorStatus *int
	// TerminalReason is why the run ended ("api_error", "max_turns", ...).
	TerminalReason string
	SessionID      string
	// Data is the result message as the CLI sent it.
	Data     json.RawMessage
	ExitCode int
}

ResultError reports that the CLI exited after a terminal error result. The CLI ends a failed run with a result message (is_error true, delivered as a ResultMessage) and then exits non-zero; this error takes the place of the bare ProcessError for that case and carries the result's payload, so callers can branch on why the run failed:

var re *claude.ResultError
if errors.As(err, &re) && re.TerminalReason == "api_error" {
    // retry
}

It unwraps to a *ProcessError, so errors.As with a ProcessError target still matches. The same error fails a connect when the CLI rejects the session before answering initialize (a refused resume, for example).

func (*ResultError) Error added in v0.4.0

func (e *ResultError) Error() string

func (*ResultError) Unwrap added in v0.4.0

func (e *ResultError) Unwrap() error

Unwrap returns the process exit as a *ProcessError. Stderr is left empty: the result text is the real cause.

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"`
	TerminalReason    string                `json:"terminal_reason,omitempty"`
	TotalCostUSD      float64               `json:"total_cost_usd,omitempty"`
	Usage             Usage                 `json:"usage"`
	ModelUsage        map[string]ModelUsage `json:"modelUsage,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"`
	// Origin is the origin of the user message that triggered this turn. It
	// tells the result of your own prompt (nil) from results of turns the
	// session injected, such as background-task notifications.
	Origin *MessageOrigin `json:"origin,omitempty"`
	Raw    json.RawMessage
}

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

TerminalReason reports why the query loop ended. "aborted_streaming" or "aborted_tools" mean the turn was cancelled (via Client.Interrupt or an interrupt control request), which is how a cancelled turn is told apart from one that ran to completion. It is empty when the CLI reported no terminal reason: older CLI versions, or a result that bypassed the query loop such as a local slash command.

type SDKSessionInfo

type SDKSessionInfo struct {
	SessionID string `json:"session_id"`
	// Summary is the display title: the custom or AI title, else the last
	// prompt, the CLI's summary, or the first prompt.
	Summary      string `json:"summary"`
	LastModified int64  `json:"last_modified"` // epoch milliseconds
	// FileSize is the transcript's byte size; zero for store-backed sessions.
	FileSize    int64  `json:"file_size,omitempty"`
	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"` // epoch milliseconds
}

SDKSessionInfo is metadata about a stored session. Zero values mean the field is unknown.

func GetSessionInfo

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

GetSessionInfo returns metadata for one session. With a directory it looks in that project and its git worktrees; with "" it searches every project. It returns ErrSessionNotFound when the session is missing, is a sidechain, or has no summary.

func GetSessionInfoFromStore added in v0.4.0

func GetSessionInfoFromStore(ctx context.Context, store SessionStore, sessionID, directory string) (SDKSessionInfo, error)

GetSessionInfoFromStore returns one session's metadata from a store, or ErrSessionNotFound.

func ListSessions

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

ListSessions returns session metadata, newest first. With a directory it lists that project (and, by default, its git worktrees); with "" it lists every project. A limit of 0 means no limit; offset skips that many. Sidechain sessions and sessions with no title or prompt are omitted.

func ListSessionsFromStore added in v0.4.0

func ListSessionsFromStore(ctx context.Context, store SessionStore, directory string, limit, offset int) ([]SDKSessionInfo, error)

ListSessionsFromStore lists a project's sessions from a store, newest first, with the same metadata ListSessions derives from disk. directory selects the project key (the current directory when empty). A limit of 0 means no limit.

When the store supports ListSessionSummaries, it uses the folded summaries plus one ListSessions call to find sessions whose summary is missing or stale, and loads only those (after paging). Otherwise it loads every session (16 at a time). It fails if the store supports neither listing method.

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. Subagent subpaths mirror the on-disk layout, such as "subagents/agent-<id>".

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"`
	Message   json.RawMessage `json:"message"`
	// ParentToolUseID, for subagent messages, is the id of the Agent tool_use
	// in the parent session that spawned the subagent (from its metadata).
	// Empty for top-level session messages.
	ParentToolUseID string `json:"parent_tool_use_id,omitempty"`
	// ParentAgentID, for a nested subagent, is the agent id of the subagent
	// that spawned it. Empty otherwise.
	ParentAgentID string `json:"parent_agent_id,omitempty"`
}

SessionMessage is one user or assistant message of a session's conversation.

func GetSessionMessages

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

GetSessionMessages returns a session's conversation, oldest first: the transcript's main chain rebuilt from parentUuid links, as user and assistant messages. With a directory it looks in that project and its git worktrees; with "" it searches every project. A missing session yields no messages.

func GetSessionMessagesFromStore added in v0.4.0

func GetSessionMessagesFromStore(ctx context.Context, store SessionStore, sessionID, directory string, limit, offset int) ([]SessionMessage, error)

GetSessionMessagesFromStore returns a session's conversation from a store, as GetSessionMessages does from disk.

func GetSubagentMessages

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

GetSubagentMessages returns a subagent's conversation, oldest first. Each message's ParentToolUseID is the Agent tool call that spawned the subagent, and ParentAgentID the spawning subagent when nested, both read from the agent-<id>.meta.json sidecar (empty if it is missing or unusable).

func GetSubagentMessagesFromStore added in v0.4.0

func GetSubagentMessagesFromStore(ctx context.Context, store SessionStore, sessionID, agentID, directory string, limit, offset int) ([]SessionMessage, error)

GetSubagentMessagesFromStore returns a subagent's conversation from a store, as GetSubagentMessages does from disk; the parent ids come from the subagent's agent_metadata entry. Without ListSubkeys support it tries subagents/agent-<id> directly.

type SessionStartHookSpecificOutput added in v0.4.0

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

SessionStartHookSpecificOutput is the typed hook-specific output for SessionStart events.

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.

Append and Load are required. The other methods are optional in the official SDK; a store that does not support one returns an error wrapping errors.ErrUnsupported, and callers fall back or skip as upstream does: ListSessionSummaries falls back to ListSessions plus Load, ListSubkeys means no subagents, and Delete is a no-op (for append-only backends).

type SessionStoreEntry

type SessionStoreEntry struct {
	Data json.RawMessage
}

SessionStoreEntry is one stored transcript line (a raw JSON object). Stores treat it as an opaque blob.

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 is the last-modified time in epoch milliseconds.
	Mtime int64
}

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

type SessionSummaryEntry

type SessionSummaryEntry struct {
	SessionID string
	// Mtime is the storage write time of the summary in epoch milliseconds,
	// on the same clock as ListSessions' mtime for the session.
	Mtime int64
	Data  map[string]any
}

SessionSummaryEntry is an incrementally maintained session summary. Stores obtain it from FoldSessionSummary inside Append, persist it verbatim, and return the set from ListSessionSummaries. Data is SDK-owned state that stores must not interpret.

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 (nil for the first append). Every derived field is set-once or last-wins, so stores never re-read earlier entries.

Mtime is left as prev's (0 for a new summary): it is the store's write time, stamped by the store after persisting, on the same clock as ListSessions. Do not call this for keys with a Subpath; subagent transcripts must not feed 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 TaskNotificationOriginSubkind added in v0.4.0

type TaskNotificationOriginSubkind string

TaskNotificationOriginSubkind is MessageOrigin.Subkind for a task-notification origin.

const (
	// SubkindScheduledTrigger is the fired prompt of a scheduled task.
	SubkindScheduledTrigger TaskNotificationOriginSubkind = "scheduled-trigger"
	// SubkindPeerSendMessage is a message sent from another of the user's
	// sessions.
	SubkindPeerSendMessage TaskNotificationOriginSubkind = "peer-send-message"
)

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 struct {
	Title           string `json:"title,omitempty"`
	ReadOnlyHint    *bool  `json:"readOnlyHint,omitempty"`
	DestructiveHint *bool  `json:"destructiveHint,omitempty"`
	IdempotentHint  *bool  `json:"idempotentHint,omitempty"`
	OpenWorldHint   *bool  `json:"openWorldHint,omitempty"`
	// MaxResultSizeChars is a Claude Code hint rather than an MCP one: the
	// size, in characters, up to which Claude Code keeps this tool's result
	// inline instead of saving it to a file and showing a preview. It is sent
	// in the tool's _meta, not with the annotations.
	MaxResultSizeChars *int `json:"-"`
}

ToolAnnotations are the MCP behavior hints an in-process Tool advertises. A nil hint is not sent, so the MCP default applies (notably, a tool counts as destructive and open-world unless it says otherwise). Use Bool to set one.

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"`
	// Origin is the provenance of this message, or nil when the CLI did not
	// attribute it. It is set on turns the session injects (task
	// notifications, channel and peer messages, ...) and on user messages the
	// CLI replays; tool-result messages never carry it.
	Origin *MessageOrigin `json:"origin,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.

type UserPromptSubmitHookSpecificOutput added in v0.4.0

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

UserPromptSubmitHookSpecificOutput is the typed hook-specific output for UserPromptSubmit events.

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