claudecode

package module
v0.0.0-...-87baf33 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

README

go-claudecode

A native Go SDK for programmatic interaction with the Claude Code CLI.

This is a Go port of the official claude-agent-sdk (Python), with built-in OS-level process sandboxing inspired by Anthropic's sandbox-runtime.

Requirements

  • Go 1.25+
  • Claude Code CLI (claude) installed and authenticated

Installation

go get github.com/bpowers/go-claudecode

Quick start

One-shot query
messages, err := claudecode.QuerySync(ctx, "What is 2+2?")
if err != nil {
    log.Fatal(err)
}
for _, msg := range messages {
    if am, ok := msg.(*claudecode.AssistantMessage); ok {
        fmt.Println(am.GetText())
    }
}
Multi-turn conversation
client := claudecode.NewClient(
    claudecode.WithModel("claude-sonnet-4-5"),
    claudecode.WithCWD("/path/to/project"),
)

if err := client.Connect(ctx); err != nil {
    log.Fatal(err)
}
defer client.Close(ctx)

if err := client.Query(ctx, "Help me understand this codebase", "default"); err != nil {
    log.Fatal(err)
}

for msg := range client.ReceiveResponse(ctx) {
    if msg.Err != nil {
        log.Printf("Error: %v", msg.Err)
        continue
    }
    switch m := msg.Message.(type) {
    case *claudecode.AssistantMessage:
        fmt.Println(m.GetText())
    case *claudecode.ResultMessage:
        fmt.Printf("Cost: $%.4f\n", *m.TotalCostUSD)
    }
}
OS-level sandboxing
policy := sandbox.DefaultPolicy()
policy.ReadWriteMounts = append(policy.ReadWriteMounts,
    sandbox.Mount{Source: "/my/project", Target: "/my/project"})
policy.AllowNetwork = false

cmd, err := policy.Command(ctx, "claude", "--print", "Hello")
if err != nil {
    log.Fatal(err)
}
output, err := cmd.CombinedOutput()

Supported features

SDK (package claudecode)

Feature parity with the Python claude-agent-sdk:

  • One-shot queries -- Query(), QuerySync() for simple request/response
  • Streaming queries -- QueryWithInput() with full bidirectional control protocol
  • Multi-turn client -- Client for stateful, interactive conversations
  • Custom tools -- In-process MCP servers via chat.Tool interface and WithSDKMCPServer()
  • External MCP servers -- stdio, SSE, and HTTP MCP server connections
  • Hooks -- PreToolUse, PostToolUse, UserPromptSubmit, Stop, SubagentStop, PreCompact
  • Tool permissions -- WithCanUseTool() callback for allow/deny/modify decisions
  • Subagents -- WithAgent() for custom agent definitions
  • Session management -- Continue, resume, and fork sessions
  • Transcript parsing -- Read Claude Code's JSONL transcripts back as typed messages
  • Full configuration -- Model selection, system prompts, budget limits, permission modes, etc.
Sandboxing (package sandbox)

A native Go reimplementation of Anthropic's sandbox-runtime:

  • macOS -- Seatbelt (sandbox-exec) with dynamically generated profiles
  • Linux -- bubblewrap (bwrap) with namespace isolation
  • Filesystem isolation -- Read-only and read-write mount control
  • Network filtering -- HTTP + SOCKS5 proxy with domain allow/deny lists
  • Environment control -- Custom env vars, TMPDIR handling
MCP server (package mcp)

A standalone MCP server implementation:

  • JSON-RPC 2.0 -- Protocol-compliant server over io.Reader/io.Writer
  • Tool registry -- Thread-safe tool registration with chat.Tool interface
  • MCP 2025-11-25 -- Current protocol version

Not supported (by design)

These features from the upstream reference implementations are intentionally excluded:

  • Violation monitoring -- The sandbox-runtime's macOS log store tapping and Linux strace-based violation detection are not ported. The Go sandbox enforces policy but does not report violations after the fact.
  • Seccomp BPF -- Unix socket restrictions via seccomp BPF filtering (from sandbox-runtime) are not implemented. Network filtering is handled entirely through the proxy.
  • Settings file configuration -- The sandbox-runtime's JSON settings file format is not used. Sandbox policy is configured programmatically via the sandbox.Policy struct.
  • BYOP (Bring Your Own Proxy) -- The sandbox-runtime's mode for plugging in an external proxy is not supported. The sandbox package runs its own built-in proxy.

Architecture

*.go                 SDK (package claudecode) for interacting with Claude Code CLI
  subprocess.go      Spawns and manages the claude CLI process
  protocol.go        Bidirectional JSON control protocol
  mcp.go             Routes MCP messages to in-process tool servers
  hooks.go           Hook registration and callback dispatch
  client.go          Multi-turn conversation state machine
  query.go           One-shot query helpers

chat/                Shared types (Tool, Message, Content)

sandbox/             OS-level process sandboxing (independent of SDK)
  exec_darwin.go     macOS Seatbelt implementation
  exec_linux.go      Linux bubblewrap implementation
  proxy.go           HTTP + SOCKS5 network filtering proxy

mcp/                 Standalone MCP server implementation

The SDK works by spawning the claude CLI as a subprocess and communicating over stdin/stdout using Claude Code's JSON streaming protocol. The sandbox package can optionally wrap this subprocess in an OS-level sandbox to restrict filesystem and network access.

Upstream tracking

This project tracks two upstream Anthropic repositories as git submodules in third_party/:

  • third_party/claude-agent-sdk-python -- The official Python SDK
  • third_party/sandbox-runtime -- The official sandbox runtime (TypeScript)

Updates are pulled on a 1-week delay from upstream releases. This delay is intentional: it reduces the risk of incorporating a supply-chain compromise before the community has time to notice it. A cron job runs Claude Code to check for upstream changes, pull updates that are at least 1 week old, and port relevant concepts to the Go code.

License

Apache License 2.0. See LICENSE.

Documentation

Overview

Package claudecode provides a Go SDK for interacting with Claude Code CLI.

This package enables programmatic interaction with Claude Code, including:

  • One-shot queries via Query() and QuerySync()
  • Multi-turn conversations via Client
  • Hook registration for tool interception
  • Custom tool permission callbacks
  • In-process MCP server integration

Quick Start

For simple one-shot queries:

messages, err := claudecode.QuerySync(ctx, "What is 2+2?")
if err != nil {
    log.Fatal(err)
}
for _, msg := range messages {
    if am, ok := msg.(*claudecode.AssistantMessage); ok {
        fmt.Println(am.GetText())
    }
}

Multi-Turn Conversations

For interactive conversations with state:

client := claudecode.NewClient(
    claudecode.WithModel("claude-sonnet-4-5"),
    claudecode.WithCWD("/path/to/project"),
)

if err := client.Connect(ctx); err != nil {
    log.Fatal(err)
}
defer client.Close(ctx)

// Send a query (sessionID "default" is used for single-session conversations)
if err := client.Query(ctx, "Help me understand this codebase", "default"); err != nil {
    log.Fatal(err)
}

// Receive the response
for msg := range client.ReceiveResponse(ctx) {
    if msg.Err != nil {
        log.Printf("Error: %v", msg.Err)
        continue
    }
    switch m := msg.Message.(type) {
    case *claudecode.AssistantMessage:
        fmt.Println(m.GetText())
    case *claudecode.ResultMessage:
        fmt.Printf("Cost: $%.4f\n", *m.TotalCostUSD)
    }
}

Hooks

Register hooks to intercept tool execution:

client := claudecode.NewClient(
    claudecode.WithHook(claudecode.HookPreToolUse, claudecode.HookMatcher{
        Matcher: "Bash",
        Hooks: []claudecode.HookCallback{
            func(ctx context.Context, input claudecode.HookInput, toolUseID *string) (claudecode.HookOutput, error) {
                // Inspect or modify the tool input
                if pi, ok := input.(claudecode.PreToolUseInput); ok {
                    fmt.Printf("Bash command: %v\n", pi.ToolInput["command"])
                }
                return claudecode.NewPreToolUseAllow(), nil
            },
        },
    }),
)

Tool Permissions

Implement custom tool permission logic:

client := claudecode.NewClient(
    claudecode.WithCanUseTool(func(ctx context.Context, toolName string, input map[string]any, permCtx claudecode.ToolPermissionContext) (claudecode.PermissionResult, error) {
        if toolName == "Bash" {
            // Deny dangerous commands
            if cmd, ok := input["command"].(string); ok {
                if strings.Contains(cmd, "rm -rf") {
                    return claudecode.PermissionDeny{
                        Message: "Dangerous command not allowed",
                    }, nil
                }
            }
        }
        return claudecode.PermissionAllow{}, nil
    }),
)

MCP Servers

Integrate in-process MCP servers with chat.Tool implementations:

client := claudecode.NewClient(
    claudecode.WithSDKMCPServer("calculator", myCalculatorTool),
    claudecode.WithAllowedTools("mcp__calculator__add"),
)

Configuration Options

The package supports extensive configuration via functional options:

  • WithModel: Set the AI model to use
  • WithSystemPrompt: Custom system prompt
  • WithTools: Explicit tool list
  • WithAllowedTools: Restrict available tools
  • WithPermissionMode: Set permission behavior
  • WithMaxTurns: Limit conversation length
  • WithMaxBudgetUSD: Set spending limit
  • WithCWD: Set working directory
  • WithHook: Register hook callbacks
  • WithCanUseTool: Custom permission callback
  • WithSDKMCPServer: Add in-process MCP server

See the Option type documentation for the complete list.

Package claudecode provides a Go SDK for interacting with Claude Code CLI.

Index

Constants

View Source
const (
	// DefaultControlTimeout is the default timeout for control requests.
	DefaultControlTimeout = 60 * time.Second
	// DefaultInitializeTimeout is the default timeout for initialize requests.
	DefaultInitializeTimeout = 60 * time.Second
)
View Source
const (
	// MinimumCLIVersion is the minimum supported Claude Code CLI version.
	MinimumCLIVersion = "2.0.0"

	// DefaultStreamCloseTimeout is the default timeout for closing stdin.
	DefaultStreamCloseTimeout = 60 * time.Second

	// SDKVersion is the version of this SDK.
	SDKVersion = "0.1.0"
)

Variables

View Source
var (
	// ErrCLINotFound indicates the Claude Code CLI binary was not found.
	ErrCLINotFound = errors.New("claude code CLI not found")
	// ErrConnection indicates a connection failure to Claude Code.
	ErrConnection = errors.New("connection to claude code failed")
	// ErrProcess indicates the Claude Code process encountered an error.
	ErrProcess = errors.New("claude code process error")
	// ErrJSONDecode indicates a failure to decode JSON from the CLI.
	ErrJSONDecode = errors.New("failed to decode JSON from CLI")
	// ErrProtocol indicates a control protocol error.
	ErrProtocol = errors.New("control protocol error")
	// ErrTimeout indicates an operation timed out.
	ErrTimeout = errors.New("operation timed out")
	// ErrNotConnected indicates the client is not connected.
	ErrNotConnected = errors.New("client not connected")
	// ErrStreamingRequired indicates an operation requires streaming mode.
	ErrStreamingRequired = errors.New("operation requires streaming mode")
	// ErrClientClosed indicates the client has been closed and cannot be reused.
	ErrClientClosed = errors.New("client has been closed and cannot be reused")
	// ErrUnknownMessageType indicates an unrecognized message type in a transcript.
	ErrUnknownMessageType = errors.New("unknown message type")
)

Sentinel errors for the claudecode package.

Functions

func ClaudeCodeProjectPath

func ClaudeCodeProjectPath(projectDir string) (string, error)

ClaudeCodeProjectPath computes the path to Claude Code's project directory for a given working directory. Claude Code escapes paths by replacing "/" with "-". For example, "/Users/bob/myproject" becomes "~/.claude/projects/-Users-bob-myproject".

func GetSessionMessagesFromTranscript

func GetSessionMessagesFromTranscript(projectDir, sessionID string) ([]chat.Message, error)

GetSessionMessagesFromTranscript reads a Claude Code transcript and converts it to chat.Message format. This reads directly from Claude Code's storage, making Claude Code the source of truth for conversation history.

func NewClaudeCodeSandboxPolicy

func NewClaudeCodeSandboxPolicy(workDir string, opts ...SandboxOptions) (*sandbox.Policy, error)

NewClaudeCodeSandboxPolicy creates an OS-level sandbox policy for running the Claude Code CLI. Access is restricted to:

  • Read-only: system dirs, Homebrew (/opt), Claude CLI binary (~/.local/share/claude, ~/.local/bin)
  • Read-write: project directory (workDir), Claude config (~/.claude/)
  • Network: allowed (required for Anthropic API)

Optional SandboxOptions can be provided to configure additional features like virtualenv activation.

func Query

func Query(ctx context.Context, prompt string, opts ...Option) <-chan MessageOrError

Query performs a one-shot query with a string prompt. Internally delegates to QueryWithInput using the streaming control protocol, which means hooks, SDK MCP servers, and canUseTool callbacks are all supported.

func QueryWithInput

func QueryWithInput(ctx context.Context, input <-chan InputMessage, opts ...Option) <-chan MessageOrError

QueryWithInput performs a query with a streaming input channel. This opens a bidirectional connection that supports the full control protocol, enabling multi-turn conversations, hooks, SDK MCP servers, and can_use_tool callbacks. Query delegates to this function internally.

func ToChatMessage

func ToChatMessage(msg Message) (chat.Message, error)

ToChatMessage converts a single claudecode.Message to chat.Message. Returns an error for unsupported message types (system, result, stream_event, control).

func ToChatMessages

func ToChatMessages(messages []Message) ([]chat.Message, error)

ToChatMessages converts a slice of claudecode messages to chat messages. Filters to only user and assistant messages, silently skipping others. Builds a lookup map to populate tool names on ToolResultBlock conversions.

func TranscriptPath

func TranscriptPath(projectDir, sessionID string) (string, error)

TranscriptPath returns the path to a Claude Code transcript file for a given project directory and session ID.

Types

type AgentDefinition

type AgentDefinition struct {
	Description string   `json:"description"`
	Prompt      string   `json:"prompt"`
	Tools       []string `json:"tools,omitzero"`
	Model       string   `json:"model,omitzero"` // "sonnet", "opus", "haiku", "inherit"
}

AgentDefinition defines a custom agent.

type AssistantMessage

type AssistantMessage struct {
	Content         []ContentBlock        `json:"content"`
	Model           string                `json:"model"`
	ParentToolUseID string                `json:"parent_tool_use_id,omitzero"`
	Error           AssistantMessageError `json:"error,omitzero"`
}

AssistantMessage represents a message from the assistant.

func (*AssistantMessage) GetText

func (m *AssistantMessage) GetText() string

GetText returns all text content from an AssistantMessage.

func (*AssistantMessage) GetToolCalls

func (m *AssistantMessage) GetToolCalls() []ToolUseBlock

GetToolCalls returns all ToolUseBlocks from an AssistantMessage.

type AssistantMessageError

type AssistantMessageError string

AssistantMessageError represents an error in the assistant message.

const (
	ErrAuthenticationFailed AssistantMessageError = "authentication_failed"
	ErrBillingError         AssistantMessageError = "billing_error"
	ErrRateLimit            AssistantMessageError = "rate_limit"
	ErrInvalidRequest       AssistantMessageError = "invalid_request"
	ErrServerError          AssistantMessageError = "server_error"
	ErrUnknown              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,omitzero"`
}

BaseHookInput contains fields common to all hook inputs.

type Beta

type Beta string

Beta represents a beta feature flag.

type CanUseToolFunc

type CanUseToolFunc func(ctx context.Context, toolName string, input map[string]any, permCtx ToolPermissionContext) (PermissionResult, error)

CanUseToolFunc is the callback type for tool permission decisions.

type Client

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

Client provides bidirectional, interactive conversations with Claude Code.

func NewClient

func NewClient(opts ...Option) *Client

NewClient creates a new client with the given options.

func NewClientWithTransport

func NewClientWithTransport(transport Transport, opts ...Option) *Client

NewClientWithTransport creates a client with a custom transport.

func (*Client) Close

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

Close closes the client and releases resources.

func (*Client) Connect

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

Connect starts the CLI and prepares for interactive communication. This opens a connection without sending an initial prompt. Use Query or QueryStream to send messages after connecting.

func (*Client) ConnectWithPrompt

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

ConnectWithPrompt starts the CLI and sends an initial string prompt. Use ReceiveResponse to get the response messages.

func (*Client) ConnectWithStream

func (c *Client) ConnectWithStream(ctx context.Context, input <-chan InputMessage) error

ConnectWithStream starts the CLI with a streaming input channel. Messages from the input channel are forwarded to the CLI.

func (*Client) GetMCPStatus

func (c *Client) GetMCPStatus(ctx context.Context) (map[string]any, error)

GetMCPStatus returns the MCP server connection status.

func (*Client) GetServerInfo

func (c *Client) GetServerInfo() map[string]any

GetServerInfo returns the cached initialization result.

func (*Client) Interrupt

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

Interrupt sends an interrupt signal.

func (*Client) Query

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

Query sends a string prompt to Claude. sessionID identifies the conversation session (use "default" for the default session).

func (*Client) QueryStream

func (c *Client) QueryStream(ctx context.Context, input <-chan InputMessage, sessionID string) error

QueryStream sends messages from a channel to Claude. sessionID identifies the conversation session (use "default" for the default session).

func (*Client) ReceiveMessages

func (c *Client) ReceiveMessages(ctx context.Context) <-chan MessageOrError

ReceiveMessages returns all messages from the CLI. Control messages are already routed by the internal routeMessages goroutine.

func (*Client) ReceiveResponse

func (c *Client) ReceiveResponse(ctx context.Context) <-chan MessageOrError

ReceiveResponse returns messages until and including a ResultMessage. Unlike ReceiveMessages, this reads directly from the internal channel to avoid leaking goroutines when stopping early at ResultMessage.

func (*Client) RewindFiles

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

RewindFiles rewinds tracked files to a specific user message.

func (*Client) SessionID

func (c *Client) SessionID() string

SessionID returns the current session ID.

func (*Client) SetModel

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

SetModel changes the AI model.

func (*Client) SetPermissionMode

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

SetPermissionMode changes the permission mode.

func (*Client) StreamError

func (c *Client) StreamError() error

StreamError returns any error that occurred during input streaming. Returns nil if no error has occurred.

type ContentBlock

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

ContentBlock is a marker interface for all content block types.

type ControlCancelRequest

type ControlCancelRequest struct {
	Type      string `json:"type"`
	RequestID string `json:"request_id"`
}

ControlCancelRequest represents a request to cancel an operation.

type ControlRequest

type ControlRequest struct {
	Type      string          `json:"type"`
	RequestID string          `json:"request_id"`
	Request   json.RawMessage `json:"request"`
}

ControlRequest represents an incoming control request from the CLI.

type ControlResponse

type ControlResponse struct {
	Type     string          `json:"type"`
	Response json.RawMessage `json:"response"`
}

ControlResponse represents a control response to send to the CLI.

type ControlRouter

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

ControlRouter manages the control protocol for bidirectional communication.

func NewControlRouter

func NewControlRouter(transport Transport, opts *Options) *ControlRouter

NewControlRouter creates a new control router.

func (*ControlRouter) GetMCPStatus

func (r *ControlRouter) GetMCPStatus(ctx context.Context) (map[string]any, error)

GetMCPStatus returns the MCP server status.

func (*ControlRouter) GetServerInfo

func (r *ControlRouter) GetServerInfo() map[string]any

GetServerInfo returns the cached initialization result.

func (*ControlRouter) HandleMessage

func (r *ControlRouter) HandleMessage(ctx context.Context, msg Message, raw []byte) (bool, error)

HandleMessage processes an incoming message and routes control messages. Returns true if the message was a control message and was handled.

func (*ControlRouter) Initialize

func (r *ControlRouter) Initialize(ctx context.Context) (map[string]any, error)

Initialize performs the initialization handshake with the CLI.

func (*ControlRouter) Interrupt

func (r *ControlRouter) Interrupt(ctx context.Context) error

Interrupt sends an interrupt control request.

func (*ControlRouter) RewindFiles

func (r *ControlRouter) RewindFiles(ctx context.Context, userMessageUUID string) error

RewindFiles rewinds tracked files to a specific user message.

func (*ControlRouter) SetModel

func (r *ControlRouter) SetModel(ctx context.Context, model string) error

SetModel changes the model.

func (*ControlRouter) SetPermissionMode

func (r *ControlRouter) SetPermissionMode(ctx context.Context, mode PermissionMode) error

SetPermissionMode changes the permission mode.

type HookCallback

type HookCallback func(ctx context.Context, input HookInput, toolUseID *string) (HookOutput, error)

HookCallback is the function signature for hook callbacks. toolUseID is nil for non-tool hooks, non-nil for tool hooks (may be empty string).

type HookEvent

type HookEvent string

HookEvent represents the type of hook event.

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

type HookInput

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

HookInput is a marker interface for all hook input types.

type HookMatcher

type HookMatcher struct {
	// Matcher is a tool name pattern (e.g., "Bash", "Write|MultiEdit|Edit").
	Matcher string
	// Hooks are the callback functions to invoke.
	Hooks []HookCallback
	// Timeout is the maximum time to wait for the hook (default: 60s).
	Timeout time.Duration
}

HookMatcher configures when and how hooks are invoked.

type HookOutput

type HookOutput struct {
	// Async execution (mutually exclusive with sync fields)
	Async        bool `json:"async,omitzero"`
	AsyncTimeout int  `json:"asyncTimeout,omitzero"` // milliseconds

	// Sync control fields
	// Continue is nil to use protocol default (true), or explicitly set to control flow.
	// The protocol specifies that omitting this field means "continue".
	Continue       *bool  `json:"continue,omitzero"`
	SuppressOutput bool   `json:"suppressOutput,omitzero"`
	StopReason     string `json:"stopReason,omitzero"`

	// Decision fields
	Decision      string `json:"decision,omitzero"` // "block"
	SystemMessage string `json:"systemMessage,omitzero"`
	Reason        string `json:"reason,omitzero"`

	// Event-specific output
	HookSpecificOutput any `json:"hookSpecificOutput,omitzero"`
}

HookOutput is the response from a hook callback.

The Continue field uses *bool because the Claude Code CLI protocol specifies that when the "continue" field is omitted (nil), execution should continue (equivalent to continue: true). This is NOT fallback behavior - it's the protocol specification. Using *bool allows us to distinguish between:

  • nil: use protocol default (continue)
  • true: explicitly continue
  • false: explicitly block

func NewHookOutputBlock

func NewHookOutputBlock(reason string) HookOutput

NewHookOutputBlock creates a hook output that blocks execution.

func NewHookOutputContinue

func NewHookOutputContinue() HookOutput

NewHookOutputContinue creates a hook output that allows execution to continue.

func NewPostToolUseContext

func NewPostToolUseContext(context string) HookOutput

NewPostToolUseContext creates a PostToolUse output with additional context.

func NewPreToolUseAllow

func NewPreToolUseAllow() HookOutput

NewPreToolUseAllow creates a PreToolUse output that allows the tool to run.

func NewPreToolUseDeny

func NewPreToolUseDeny(reason string) HookOutput

NewPreToolUseDeny creates a PreToolUse output that denies the tool.

func NewPreToolUseModify

func NewPreToolUseModify(updatedInput map[string]any) HookOutput

NewPreToolUseModify creates a PreToolUse output that modifies the tool input.

type InputContent

type InputContent struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

InputContent represents the content of an input message.

type InputMessage

type InputMessage struct {
	Type            string       `json:"type"`
	Message         InputContent `json:"message"`
	ParentToolUseID string       `json:"parent_tool_use_id,omitzero"`
	SessionID       string       `json:"session_id,omitzero"`
}

InputMessage represents a message to send to Claude.

func NewUserInput

func NewUserInput(content string) InputMessage

NewUserInput creates a new user input message.

func (InputMessage) WithParentToolUseID

func (m InputMessage) WithParentToolUseID(toolUseID string) InputMessage

WithParentToolUseID sets the parent tool use ID for the input message.

func (InputMessage) WithSessionID

func (m InputMessage) WithSessionID(sessionID string) InputMessage

WithSessionID sets the session ID for the input message.

type JSONDecodeError

type JSONDecodeError struct {
	Line          string
	OriginalError error
}

JSONDecodeError represents a JSON decoding error from CLI output.

func (*JSONDecodeError) Error

func (e *JSONDecodeError) Error() string

Error implements the error interface.

func (*JSONDecodeError) Unwrap

func (e *JSONDecodeError) Unwrap() error

Unwrap returns the underlying error.

type MCPHTTPConfig

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

MCPHTTPConfig configures an MCP server via HTTP.

type MCPSDKConfig

type MCPSDKConfig struct {
	Name  string
	Tools []chat.Tool
}

MCPSDKConfig configures an in-process MCP server using chat.Tool instances.

type MCPSSEConfig

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

MCPSSEConfig configures an MCP server via SSE.

type MCPServerConfig

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

MCPServerConfig is a marker interface for MCP server configurations.

type MCPStdioConfig

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

MCPStdioConfig configures an MCP server via stdio.

type Message

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

Message is a marker interface for all message types.

func ParseTranscript

func ParseTranscript(path string) ([]Message, error)

ParseTranscript reads a JSONL transcript file and returns parsed messages. Empty lines are skipped. Returns an error with line number for malformed JSON.

func QuerySync

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

QuerySync blocks until the query completes and returns all messages.

type MessageOrError

type MessageOrError struct {
	Message Message
	Raw     []byte
	Err     error
}

MessageOrError represents either a message or an error from the transport.

type MessageParseError

type MessageParseError struct {
	Message string
	Data    map[string]any
}

MessageParseError represents an error parsing a message from CLI output.

func (*MessageParseError) Error

func (e *MessageParseError) Error() string

Error implements the error interface.

type NotificationInput

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

NotificationInput is the input for Notification hooks.

type NotificationSpecificOutput

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

NotificationSpecificOutput is hook-specific output for Notification.

type Option

type Option func(*Options)

Option is a functional option for configuring a Claude Code session.

func WithAddDirs

func WithAddDirs(dirs ...string) Option

WithAddDirs adds directories to the allowed paths.

func WithAgent

func WithAgent(name string, def AgentDefinition) Option

WithAgent adds a custom agent definition.

func WithAllowedTools

func WithAllowedTools(tools ...string) Option

WithAllowedTools sets the allowed tools.

func WithBetas

func WithBetas(betas ...Beta) Option

WithBetas enables beta features.

func WithCLIPath

func WithCLIPath(path string) Option

WithCLIPath sets the path to the Claude CLI.

func WithCWD

func WithCWD(cwd string) Option

WithCWD sets the working directory.

func WithCanUseTool

func WithCanUseTool(fn CanUseToolFunc) Option

WithCanUseTool sets the tool permission callback (requires streaming mode).

func WithContinueConversation

func WithContinueConversation() Option

WithContinueConversation enables continuing the previous conversation.

func WithDisallowedTools

func WithDisallowedTools(tools ...string) Option

WithDisallowedTools sets the disallowed tools.

func WithDiscardStderr

func WithDiscardStderr() Option

WithDiscardStderr discards all stderr output from the CLI. By default, stderr is written to os.Stderr.

func WithEffort

func WithEffort(level string) Option

WithEffort sets the effort level ("low", "medium", "high", "max").

func WithEnableFileCheckpointing

func WithEnableFileCheckpointing() Option

WithEnableFileCheckpointing enables file change tracking.

func WithEnv

func WithEnv(key, value string) Option

WithEnv adds an environment variable.

func WithExtraArg

func WithExtraArg(flag string, value *string) Option

WithExtraArg adds an extra CLI argument. value=nil means --flag, value="" means --flag "", value="x" means --flag x.

func WithFallbackModel

func WithFallbackModel(model string) Option

WithFallbackModel sets the fallback model.

func WithForkSession

func WithForkSession() Option

WithForkSession forks the resumed session instead of continuing it.

func WithHook

func WithHook(event HookEvent, matcher HookMatcher) Option

WithHook registers a hook for the given event.

func WithIncludePartialMessages

func WithIncludePartialMessages() Option

WithIncludePartialMessages includes partial messages in the stream.

func WithJSONSchemaOutput

func WithJSONSchemaOutput(schema map[string]any) Option

WithJSONSchemaOutput sets the JSON schema for structured output.

func WithMCPServer

func WithMCPServer(name string, config MCPServerConfig) Option

WithMCPServer adds an MCP server configuration.

func WithMCPServersJSON

func WithMCPServersJSON(jsonStr string) Option

WithMCPServersJSON sets the MCP servers as a JSON string.

func WithMCPServersPath

func WithMCPServersPath(path string) Option

WithMCPServersPath sets the path to an MCP servers JSON file.

func WithMaxBudgetUSD

func WithMaxBudgetUSD(budget float64) Option

WithMaxBudgetUSD sets the maximum budget in USD.

func WithMaxThinkingTokens

func WithMaxThinkingTokens(tokens int) Option

WithMaxThinkingTokens sets the maximum thinking tokens.

func WithMaxTurns

func WithMaxTurns(turns int) Option

WithMaxTurns sets the maximum number of conversation turns.

func WithModel

func WithModel(model string) Option

WithModel sets the model to use.

func WithOSSandboxPolicy

func WithOSSandboxPolicy(policy *sandbox.Policy) Option

WithOSSandboxPolicy sets an OS-level sandbox policy for the Claude Code CLI process. This restricts the CLI's filesystem access at the operating system level.

func WithOutputFormat

func WithOutputFormat(format map[string]any) Option

WithOutputFormat sets the output format configuration. The format should follow the structure {"type":"json_schema","schema":{...}}. When set, this takes precedence over WithJSONSchemaOutput for the CLI arg.

func WithPermissionMode

func WithPermissionMode(mode PermissionMode) Option

WithPermissionMode sets the permission mode.

func WithPermissionPromptToolName

func WithPermissionPromptToolName(name string) Option

WithPermissionPromptToolName sets the permission prompt tool name.

func WithPlugin

func WithPlugin(config PluginConfig) Option

WithPlugin adds a plugin configuration.

func WithResume

func WithResume(sessionID string) Option

WithResume resumes a specific session by ID.

func WithSDKMCPServer

func WithSDKMCPServer(name string, tools ...chat.Tool) Option

WithSDKMCPServer adds an in-process MCP server from chat.Tool instances.

func WithSandbox

func WithSandbox(settings SandboxSettings) Option

WithSandbox configures sandbox settings.

func WithSettingSources

func WithSettingSources(sources ...SettingSource) Option

WithSettingSources sets which setting sources to load.

func WithSettings

func WithSettings(settings string) Option

WithSettings sets the settings JSON string or file path.

func WithStderr

func WithStderr(fn func(string)) Option

WithStderr sets a callback for stderr output from the CLI. By default, stderr is written to os.Stderr. Use this to handle it differently.

func WithSystemPrompt

func WithSystemPrompt(prompt string) Option

WithSystemPrompt sets a custom system prompt.

func WithSystemPromptPreset

func WithSystemPromptPreset(append string) Option

WithSystemPromptPreset uses the default system prompt and appends additional text.

func WithThinking

func WithThinking(config ThinkingConfig) Option

WithThinking configures the model's thinking behavior. When set, this takes precedence over WithMaxThinkingTokens.

func WithTools

func WithTools(tools ...string) Option

WithTools sets explicit tool list. Empty list means --tools "".

func WithToolsPreset

func WithToolsPreset() Option

WithToolsPreset uses the default tools preset (--tools default).

type Options

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

Options holds all configuration for a Claude Code session.

type PermissionAllow

type PermissionAllow struct {
	UpdatedInput       map[string]any
	UpdatedPermissions []PermissionUpdate
}

PermissionAllow allows tool execution, optionally with modifications.

type PermissionDeny

type PermissionDeny struct {
	Message   string
	Interrupt bool
}

PermissionDeny denies tool execution.

type PermissionMode

type PermissionMode string

PermissionMode represents the permission mode for Claude Code.

const (
	PermissionDefault           PermissionMode = "default"
	PermissionAcceptEdits       PermissionMode = "acceptEdits"
	PermissionPlan              PermissionMode = "plan"
	PermissionBypassPermissions PermissionMode = "bypassPermissions"
)

type PermissionRequestInput

type PermissionRequestInput struct {
	BaseHookInput
	ToolName              string         `json:"tool_name"`
	ToolInput             map[string]any `json:"tool_input"`
	PermissionSuggestions []any          `json:"permission_suggestions,omitzero"`
}

PermissionRequestInput is the input for PermissionRequest hooks.

type PermissionRequestSpecificOutput

type PermissionRequestSpecificOutput struct {
	HookEventName string         `json:"hookEventName"` // "PermissionRequest"
	Decision      map[string]any `json:"decision,omitzero"`
}

PermissionRequestSpecificOutput is hook-specific output for PermissionRequest.

type PermissionResult

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

PermissionResult is a marker interface for permission decisions.

type PermissionRuleValue

type PermissionRuleValue struct {
	ToolName    string
	RuleContent string
}

PermissionRuleValue represents a permission rule.

type PermissionUpdate

type PermissionUpdate struct {
	Type        string // "addRules", "replaceRules", "removeRules", "setMode", "addDirectories", "removeDirectories"
	Rules       []PermissionRuleValue
	Behavior    string // "allow", "deny", "ask"
	Mode        PermissionMode
	Directories []string
	Destination string // "userSettings", "projectSettings", "localSettings", "session"
}

PermissionUpdate represents a permission update request.

func (PermissionUpdate) ToMap

func (p PermissionUpdate) ToMap() map[string]any

ToMap converts PermissionUpdate to a map with correct camelCase JSON keys.

type PluginConfig

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

PluginConfig configures a plugin.

type PostToolUseFailureInput

type PostToolUseFailureInput struct {
	BaseHookInput
	ToolName    string         `json:"tool_name"`
	ToolInput   map[string]any `json:"tool_input"`
	ToolUseID   string         `json:"tool_use_id"`
	Error       string         `json:"error"`
	IsInterrupt bool           `json:"is_interrupt"`
}

PostToolUseFailureInput is the input for PostToolUseFailure hooks.

type PostToolUseFailureSpecificOutput

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

PostToolUseFailureSpecificOutput is hook-specific output for PostToolUseFailure.

type PostToolUseInput

type PostToolUseInput struct {
	BaseHookInput
	ToolName     string         `json:"tool_name"`
	ToolInput    map[string]any `json:"tool_input"`
	ToolResponse any            `json:"tool_response"`
	ToolUseID    string         `json:"tool_use_id"`
}

PostToolUseInput is the input for PostToolUse hooks.

type PostToolUseSpecificOutput

type PostToolUseSpecificOutput struct {
	HookEventName        string `json:"hookEventName"` // "PostToolUse"
	AdditionalContext    string `json:"additionalContext,omitzero"`
	UpdatedMCPToolOutput any    `json:"updatedMCPToolOutput,omitzero"`
}

PostToolUseSpecificOutput is hook-specific output for PostToolUse.

type PreCompactInput

type PreCompactInput struct {
	BaseHookInput
	Trigger            string `json:"trigger"` // "manual" or "auto"
	CustomInstructions string `json:"custom_instructions,omitzero"`
}

PreCompactInput is the input for PreCompact hooks.

type PreToolUseInput

type PreToolUseInput struct {
	BaseHookInput
	ToolName  string         `json:"tool_name"`
	ToolInput map[string]any `json:"tool_input"`
	ToolUseID string         `json:"tool_use_id"`
}

PreToolUseInput is the input for PreToolUse hooks.

type PreToolUseSpecificOutput

type PreToolUseSpecificOutput struct {
	HookEventName            string         `json:"hookEventName"`               // "PreToolUse"
	PermissionDecision       string         `json:"permissionDecision,omitzero"` // "allow", "deny", "ask"
	PermissionDecisionReason string         `json:"permissionDecisionReason,omitzero"`
	UpdatedInput             map[string]any `json:"updatedInput,omitzero"`
	AdditionalContext        string         `json:"additionalContext,omitzero"`
}

PreToolUseSpecificOutput is hook-specific output for PreToolUse.

type ProcessError

type ProcessError struct {
	ExitCode int
	Stderr   string
}

ProcessError represents an error from the Claude Code CLI process.

func (*ProcessError) Error

func (e *ProcessError) Error() string

Error implements the error interface.

func (*ProcessError) Unwrap

func (e *ProcessError) Unwrap() error

Unwrap returns the underlying error.

type ResultMessage

type ResultMessage struct {
	Subtype          string      `json:"subtype"`
	DurationMS       int         `json:"duration_ms"`
	DurationAPIMS    int         `json:"duration_api_ms"`
	IsError          bool        `json:"is_error"`
	NumTurns         int         `json:"num_turns"`
	SessionID        string      `json:"session_id"`
	TotalCostUSD     *float64    `json:"total_cost_usd,omitzero"`
	Usage            *UsageStats `json:"usage,omitzero"`
	Result           string      `json:"result,omitzero"`
	StructuredOutput any         `json:"structured_output,omitzero"`
}

ResultMessage represents the final result of a conversation.

type SandboxIgnoreViolations

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

SandboxIgnoreViolations configures violations to ignore.

type SandboxNetworkConfig

type SandboxNetworkConfig struct {
	AllowUnixSockets    []string `json:"allowUnixSockets,omitzero"`
	AllowAllUnixSockets bool     `json:"allowAllUnixSockets,omitzero"`
	AllowLocalBinding   bool     `json:"allowLocalBinding,omitzero"`
	HTTPProxyPort       int      `json:"httpProxyPort,omitzero"`
	SOCKSProxyPort      int      `json:"socksProxyPort,omitzero"`
}

SandboxNetworkConfig configures network access in sandbox.

type SandboxOptions

type SandboxOptions struct {
	// VirtualEnvPath is the absolute path to a Python virtualenv to activate.
	// When set, the sandbox will:
	//   - Set VIRTUAL_ENV to this path
	//   - Prepend the virtualenv's bin directory to PATH
	//   - Mount the virtualenv directory as read-only
	// This enables Python scripts executed by Claude Code's Bash tool to use
	// packages installed in the virtualenv.
	VirtualEnvPath string

	// SessionDisplayDir is the host path to a session-specific directory for
	// generated images and visualizations. When set, the sandbox will mount
	// this directory as read-write at <workDir>/session-display/. Claude Code
	// can then save images to session-display/ which will be accessible via
	// the Display tool.
	SessionDisplayDir string

	// MplConfigDir is the absolute path to a matplotlib configuration directory.
	// When set, the sandbox will:
	//   - Mount this directory as read-write
	//   - Set the MPLCONFIGDIR environment variable
	// This prevents matplotlib from trying to write to ~/.matplotlib (which
	// is not writable in the sandbox) and allows font cache persistence.
	MplConfigDir string
}

SandboxOptions configures optional features for the Claude Code sandbox.

type SandboxSettings

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

SandboxSettings configures the sandbox for bash commands.

type SettingSource

type SettingSource string

SettingSource represents a settings source.

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

type StopInput

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

StopInput is the input for Stop hooks.

type StreamEvent

type StreamEvent struct {
	UUID            string         `json:"uuid"`
	SessionID       string         `json:"session_id"`
	Event           map[string]any `json:"event"`
	ParentToolUseID string         `json:"parent_tool_use_id,omitzero"`
}

StreamEvent represents a partial message update during streaming.

type SubagentStartInput

type SubagentStartInput struct {
	BaseHookInput
	AgentID   string `json:"agent_id"`
	AgentType string `json:"agent_type"`
}

SubagentStartInput is the input for SubagentStart hooks.

type SubagentStartSpecificOutput

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

SubagentStartSpecificOutput is hook-specific output for SubagentStart.

type SubagentStopInput

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

SubagentStopInput is the input for SubagentStop hooks.

type SubprocessTransport

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

SubprocessTransport implements Transport using the Claude Code CLI subprocess.

func NewSubprocessTransport

func NewSubprocessTransport(opts *Options) *SubprocessTransport

NewSubprocessTransport creates a new subprocess transport with the given options.

func (*SubprocessTransport) Close

func (t *SubprocessTransport) Close(ctx context.Context) error

Close closes the transport and releases resources.

func (*SubprocessTransport) Connect

func (t *SubprocessTransport) Connect(ctx context.Context) error

Connect starts the Claude Code CLI subprocess.

func (*SubprocessTransport) EndInput

func (t *SubprocessTransport) EndInput(ctx context.Context) error

EndInput closes stdin to signal end of input.

func (*SubprocessTransport) IsReady

func (t *SubprocessTransport) IsReady() bool

IsReady returns true if the transport is ready for communication.

func (*SubprocessTransport) ReadMessages

func (t *SubprocessTransport) ReadMessages(ctx context.Context) <-chan MessageOrError

ReadMessages returns a channel that yields messages from the transport.

func (*SubprocessTransport) Write

func (t *SubprocessTransport) Write(ctx context.Context, data string) error

Write sends data to the transport.

type SystemMessage

type SystemMessage struct {
	Subtype string         `json:"subtype"`
	Data    map[string]any `json:"data,omitzero"`
}

SystemMessage represents a system message with metadata.

type TextBlock

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

TextBlock represents text content.

type ThinkingAdaptive

type ThinkingAdaptive struct{}

ThinkingAdaptive lets the model decide when to think.

type ThinkingBlock

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

ThinkingBlock represents thinking/reasoning content.

type ThinkingConfig

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

ThinkingConfig configures the model's thinking behavior.

type ThinkingDisabled

type ThinkingDisabled struct{}

ThinkingDisabled disables thinking.

type ThinkingEnabled

type ThinkingEnabled struct {
	BudgetTokens int
}

ThinkingEnabled enables thinking with a token budget.

type ToolPermissionContext

type ToolPermissionContext struct {
	Suggestions []PermissionUpdate
	BlockedPath string // path that triggered the permission check
}

ToolPermissionContext provides context for permission decisions.

type ToolResultBlock

type ToolResultBlock struct {
	ToolUseID string `json:"tool_use_id"`
	Content   any    `json:"content,omitzero"` // string or []ContentBlock
	IsError   bool   `json:"is_error,omitzero"`
}

ToolResultBlock represents the result of a tool execution.

type ToolUseBlock

type ToolUseBlock struct {
	ID    string         `json:"id"`
	Name  string         `json:"name"`
	Input map[string]any `json:"input"`
}

ToolUseBlock represents a tool invocation.

type Transport

type Transport interface {
	// Connect establishes the connection to Claude Code.
	Connect(ctx context.Context) error

	// Write sends data to the transport.
	Write(ctx context.Context, data string) error

	// ReadMessages returns a channel that yields messages from the transport.
	// The channel is closed when the transport is closed or an error occurs.
	ReadMessages(ctx context.Context) <-chan MessageOrError

	// EndInput signals the end of input (closes stdin for process transports).
	EndInput(ctx context.Context) error

	// Close closes the transport and releases resources.
	Close(ctx context.Context) error

	// IsReady returns true if the transport is ready for communication.
	IsReady() bool
}

Transport is the low-level I/O interface for Claude communication. Exposed for custom transport implementations (e.g., remote connections).

type UnknownContentBlock

type UnknownContentBlock struct {
	Type string         `json:"type"`
	Data map[string]any `json:"-"` // Raw data preserved for inspection
}

UnknownContentBlock represents an unrecognized content block type. This enables forward compatibility when the CLI introduces new block types.

type UsageStats

type UsageStats struct {
	InputTokens  int `json:"input_tokens"`
	OutputTokens int `json:"output_tokens"`
	CacheRead    int `json:"cache_read,omitzero"`
	CacheWrite   int `json:"cache_write,omitzero"`
}

UsageStats represents token usage statistics.

type UserMessage

type UserMessage struct {
	Content         any    `json:"-"` // string or []ContentBlock
	UUID            string `json:"uuid,omitzero"`
	ParentToolUseID string `json:"parent_tool_use_id,omitzero"`
	ToolUseResult   any    `json:"tool_use_result,omitzero"` // map[string]any or []any
}

UserMessage represents a message from the user.

func (*UserMessage) GetText

func (m *UserMessage) GetText() string

GetText returns the text content from a UserMessage. If content is a string, returns it directly. If content is []ContentBlock, concatenates all TextBlock texts.

type UserPromptSubmitInput

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

UserPromptSubmitInput is the input for UserPromptSubmit hooks.

type UserPromptSubmitSpecificOutput

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

UserPromptSubmitSpecificOutput is hook-specific output for UserPromptSubmit.

Directories

Path Synopsis
Package chat defines the core types for LLM tool interaction.
Package chat defines the core types for LLM tool interaction.
internal
testing/fstools
Package fstools provides filesystem tools for testing MCP server implementations.
Package fstools provides filesystem tools for testing MCP server implementations.
Package mcp provides a JSON-RPC based Model Context Protocol (MCP) server implementation.
Package mcp provides a JSON-RPC based Model Context Protocol (MCP) server implementation.
Package sandbox provides secure command execution by spawning child processes in isolated sandboxes.
Package sandbox provides secure command execution by spawning child processes in isolated sandboxes.

Jump to

Keyboard shortcuts

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