claudecode

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2026 License: MIT Imports: 22 Imported by: 0

README

eino-claude-code

Claude Code CLI 作为 eino 框架的一等公民 Agent。

把 Claude Code 变成一个标准的 eino AgentTool,可以直接用 Runner.Run()、参与多 Agent 协作、被 callback/middleware 观测,就像用 eino 自带的 ChatModelAgent 一样

// 和任何 eino agent 完全相同的用法
agent, _ := claudecode.New(claudecode.WithMaxTurns(5))
runner := adk.NewRunner(ctx, adk.RunnerConfig{Agent: agent})
events := runner.Run(ctx, []adk.Message{schema.UserMessage("Hello!")})

安装

go get github.com/239what475/eino-claude-code

前置条件claude CLI 已安装并在 $PATH 中。

核心概念

Claude Code CLI 是一个自包含的完整 Agent——它内部有自己的 ReAct 循环、工具执行、会话管理。eino-claude-code 不做的事情:把 CLI 拆开、模拟 ChatModel。它做的事情:给 CLI 套上 eino 的 Agent 接口,使其能无缝融入 eino 的多 Agent 编排、流式输出、中断恢复、可观测性体系。

四种集成模式

模式 1:直接 Agent(最简单)
agent, _ := claudecode.New(
    claudecode.WithSystemPrompt("You are a Go expert."),
    claudecode.WithTools("Read", "Write", "Bash"),
    claudecode.WithModel("claude-sonnet-4-6"),
    claudecode.WithMaxTurns(10),
    claudecode.WithPermissionMode("acceptEdits"),
)

runner := adk.NewRunner(ctx, adk.RunnerConfig{Agent: agent})
events := runner.Run(ctx, []adk.Message{
    schema.UserMessage("Refactor the authentication module."),
})

适用场景:把 Claude Code 当作一个独立 Agent,直接对话。

流式输出

runner := adk.NewRunner(ctx, adk.RunnerConfig{
    Agent:          agent,
    EnableStreaming: true, // 开启流式
})
events := runner.Run(ctx, messages)
for {
    evt, ok := events.Next()
    if !ok { break }
    if evt.Output.MessageOutput.IsStreaming {
        for {
            chunk, err := evt.Output.MessageOutput.MessageStream.Recv()
            if err == io.EOF { break }
            fmt.Print(chunk.Content) // 逐块输出
        }
    }
}
模式 2:作为 Tool 被 eino Agent 调度(推荐)

eino 的 ChatModelAgent 做"大脑"(决策调用哪个工具),Claude Code 做"双手"(执行复杂任务)。

// 把 Claude Code 包装成一个 Tool
ccTool, _ := claudecode.NewTool(
    claudecode.WithName("claude_code"),
    claudecode.WithDescription(
        "Delegate complex multi-step tasks to Claude Code. "+
        "Use for: file operations, shell commands, code analysis, git, web search.",
    ),
    claudecode.WithMaxTurns(10),
    claudecode.WithAllowedTools("Read", "Write", "Edit", "Bash", "Glob", "Grep"),
)

// 创建一个 ChatModelAgent(用任何 eino ChatModel:OpenAI、Claude API 等)
supervisor, _ := adk.NewChatModelAgent(ctx, &adk.ChatModelAgentConfig{
    Name:        "supervisor",
    Description: "Orchestrates complex tasks by delegating to Claude Code.",
    Instruction: "You are a supervisor. Delegate complex tasks to claude_code.",
    Model:       myChatModel, // 你的 ChatModel
    ToolsConfig: adk.ToolsConfig{
        ToolsNodeConfig: compose.ToolsNodeConfig{
            Tools: []tool.BaseTool{ccTool},
        },
    },
    MaxIterations: 5,
})

runner := adk.NewRunner(ctx, adk.RunnerConfig{Agent: supervisor})
events := runner.Run(ctx, []adk.Message{
    schema.UserMessage("Analyze the performance of the auth module and suggest improvements."),
})

执行流程:User → ChatModelAgent 决策 → 调用 claude_code tool → Claude Code CLI 执行(读文件、跑命令、分析) → 结果返回给 ChatModelAgent → 继续对话或结束。

适用场景:需要"思考+执行"分离。ChatModel 做决策,Claude Code 做具体工作。

模式 3:多 Agent 协作

ClaudeCodeAgent 可以作为子 Agent 参与 eino 的 DeepAgentPlanExecute 模式。

// DeepAgent:ChatModel 规划,ClaudeCodeAgent 执行
executor, _ := claudecode.New(
    claudecode.WithName("executor"),
    claudecode.WithDescription("Executes tasks using Claude Code CLI."),
    claudecode.WithMaxTurns(10),
)

deepAgent, _ := deep.New(ctx, &deep.Config{
    Name:        "deep-demo",
    Description: "Deep reasoning agent with Claude Code executor.",
    ChatModel:   myChatModel,
    SubAgents:   []adk.Agent{executor}, // ClaudeCodeAgent 作为子 Agent
    MaxIteration: 5,
})

// PlanExecute:ClaudeCodeAgent 可以担任 Planner、Executor、Replanner 任一角色
pe, _ := planexecute.New(ctx, &planexecute.Config{
    Planner:   plannerAgent,
    Executor:  executor,      // ClaudeCodeAgent 执行计划
    Replanner: replannerAgent,
})

适用场景:复杂的多步骤任务,需要规划-执行-反思循环。

模式 4:AgentTool 包装

adk.NewAgentTool 把 ClaudeCodeAgent 包装成标准 Tool,供任何 eino Agent 调用。

agent, _ := claudecode.New(...)
agentTool := adk.NewAgentTool(ctx, agent)
// agentTool 现在是标准的 tool.BaseTool,可以加入任何 ToolsConfig

配置选项

基础配置
Option 说明
WithName(name) Agent 名称(默认 "claude-code")
WithDescription(desc) Agent 描述
WithBin(path) CLI 路径(默认自动搜索)
Prompt
Option 说明
WithSystemPrompt(prompt) 系统提示词(替换默认)
WithAppendSystemPrompt(prompt) 追加到默认系统提示词
工具
Option 说明
WithTools(names...) 可用工具列表(nil=默认,空=无工具)
WithAllowedTools(names...) 自动批准的工具
WithDisallowedTools(names...) 禁用的工具
模型
Option 说明
WithModel(model) 模型名称,如 "claude-sonnet-4-6"
WithFallbackModel(model) 备用模型
WithEffort(level) 思考力度:"low", "medium", "high"
预算
Option 说明
WithMaxTurns(n) 最大回合数(0=默认)
WithMaxBudgetUSD(n) 费用上限(美元)
权限
Option 说明
WithPermissionMode(mode) "default", "acceptEdits", "plan", "bypassPermissions"
会话
Option 说明
WithContinueConversation() 恢复最近的对话
WithResume(sessionID) 恢复指定 session
WithSessionID(id) 创建命名 session
WithForkSession() 复制 session 到新 ID
MCP
Option 说明
WithMCPConfig(json) MCP 配置(内联 JSON)
WithMCPConfigPath(path) MCP 配置文件路径
高级
Option 说明
WithCWD(dir) CLI 进程工作目录
WithEnv(kv...) 环境变量(KEY=VALUE
WithStderr(fn) Stderr 回调(每行)
WithEmitToolEvents() 暴露 Claude Code 内部的工具调用为 AgentEvent
WithStructuredOutput(schema) JSON Schema 约束输出
WithBetas(betas...) 启用 beta 功能
WithSettings(json) 内联设置 JSON
WithAddDirs(dirs...) 添加工作目录
WithIncludePartialMessages() 请求部分消息流事件
WithExtraArgs(args) 透传额外 CLI 参数
eino 集成
Option 说明

与 eino 生态的兼容性

完全兼容
eino 功能 使用方式
Runner.Run() / Runner.Query() 和 ChatModelAgent 完全一样
callbacks.Handler OnStart/OnEnd/OnError 回调,通过 Runner.Query(ctx, prompt, WithCallbacks(h))
Tool Middleware ToolCallMiddlewares 可包装 ClaudeCodeTool 的每次调用
AgentTool adk.NewAgentTool(ctx, ccAgent) → 标准 tool.BaseTool
ResumableAgent 实现 adk.ResumableAgent,支持 eino checkpoint/interrupt
DeepAgent SubAgents: []adk.Agent{ccAgent}
PlanExecute Planner / Executor / Replanner 均可用 ClaudeCodeAgent
Streaming EnableStreaming: trueMessageStream 流式输出
Session 管理 WithResume / WithContinue / WithSessionID
间接可用(通过 Tool 模式)

这些 eino 功能设计给内部有 ChatModel 的 Agent,但当 ClaudeCodeAgent 作为 Tool 被 ChatModelAgent 调用时,ChatModelAgent 的这些功能仍然全部生效:

eino 功能 说明
ChatModelAgentMiddleware ChatModelAgent 的 middleware 可以观测到 claude_code 工具调用
Graph / Chain 通过 AgentTool → ChatModelAgent → compose.Graph 间接参与编排
Summarization middleware 上下文超限时自动摘要(ChatModelAgent 层面)
Skill middleware 技能模板加载(ChatModelAgent 层面)
有意的架构差异(不是缺陷)
方面 ClaudeCodeAgent ChatModelAgent 原因
工具执行 CLI 内部执行 eino ToolsNode 执行 Claude Code 是完整 Agent,自带工具生态
模型调用 CLI 管理 eino ChatModel 接口 Claude Code 自己选模型、管 retry
ReAct 循环 CLI 内部控制 eino compose.Graph 控制 两种有效架构,互不干扰
Prompt 模板 CLI 的 system prompt eino ChatTemplate CLI 有自己的 prompt 体系

局限性

架构层面
  • 不能作为 ChatModel 使用。Claude Code 是 Agent,不是 Token 生成器。不要把它塞进 model.BaseChatModel 接口——那是错误的抽象。
  • 不能替换 ChatModelAgent 内部的 ChatModel。Claude Code 自己管理模型调用、重试、工具执行。eino 的 ChatModelAgentMiddleware.WrapModel 对它无效。
  • 多 Agent transfer 不完全。Supervisor prebuilt 依赖 eino 内部的 transfer 机制,和 CLI 的 Task tool 不完全兼容。推荐用 AgentTool 模式替代。
运行环境
与 ChatModelAgent 的行为差异
  • 不经过 eino ChatModel 调用链。Callbacks 在 Agent 层面触发(OnStart:Agent/claude-code),不在 ChatModel 层面。
  • 会话状态在 CLI 内部。eino 的 session event history 和 CLI 的 --session-id 是两条独立的线。用 WithResume 来桥接。
  • Interrupt/Resume 依赖 CLI session。中断后恢复需要 CLI session ID,我们已经在 Resume() 中处理了状态序列化。

项目结构

├── constants.go          # Built-in tool & agent name constants\
├── mcpserver.go          # Embedded MCP server (eino tools → MCP)
├── agent.go              # ClaudeCodeAgent (adk.Agent + adk.ResumableAgent)
├── agent_test.go         # 单元测试(mock CLI)
├── args.go               # FindCLI + BuildArgs
├── cli.go                # CLI 子进程管理(Simple + Streaming 模式)
├── convertor.go          # CLI JSON ↔ eino AgentEvent 转换
├── errors.go             # CLIError, AgentError, sentinel errors
├── interrupt.go          # ResumableAgent 实现(checkpoint 状态序列化)
├── options.go            # Options 结构
├── options_funcs.go      # 35 个 With* 配置函数
├── session.go            # NewSessionID
├── tool.go               # ClaudeCodeTool (tool.InvokableTool)
├── types.go              # CLI JSON 消息类型
	├── examples/
	│   ├── helloworld/       # 最简示例
	│   ├── tool/             # ChatModelAgent 调度 ClaudeCodeTool
	│   ├── session/          # Session 跨轮共享上下文
	│   ├── customtools/      # eino 工具 → MCP 自动暴露
	│   ├── runas/            # 以自定义 agent 身份运行
	│   ├── delegate/         # MCP 工具版子 agent 委派
	│   ├── chain/            # Writer → Reviewer 串行编排
	│   └── parallel/         # 性能 + 安全 并行分析
	└── README.md

与相关项目的对比

eino-claude-code claude-agent-sdk-go trpc-agent-go ClaudeCodeAgent
定位 eino Agent 适配器 通用 Go SDK tRPC Agent 适配器
集成方式 实现 adk.Agent 独立 SDK 实现 agent.Agent
流式输出 ✅ MessageStream ✅ iter.Seq2 ❌ 批量
eino 多 Agent
eino Callback
MCP 管理 ⚠️ 配置透传 ✅ 完整 API ⚠️ 透传
依赖 eino + uuid 零依赖 tRPC 框架
CLI 路径发现
Stderr 回调

License

MIT

Documentation

Overview

Package claudecode wraps the Claude Code CLI as a first-class eino Agent and Tool.

It provides ClaudeCodeAgent (implements adk.Agent) and ClaudeCodeTool (implements tool.InvokableTool), enabling Claude Code to participate in eino's multi-agent orchestration, streaming, interrupt/resume, and callback systems — just like any built-in eino agent.

Quick start

agent, _ := claudecode.New(claudecode.WithMaxTurns(5))
runner := adk.NewRunner(ctx, adk.RunnerConfig{Agent: agent})
events := runner.Run(ctx, []adk.Message{schema.UserMessage("Hello!")})

Design

Each call to ClaudeCodeAgent.Run spawns a one-shot claude -p process. Session continuity across calls is achieved via WithSessionID / WithResume. SDK-appropriate defaults (bare mode, dontAsk permissions, prompt-cache optimization) are on by default — no configuration needed for basic use.

Custom tools

WithCustomTools exposes eino [tool.InvokableTool]s to Claude Code via an embedded MCP HTTP server. The server starts automatically on a random localhost port and is passed to the CLI via --mcp-config. Claude Code discovers and calls these tools during task execution without any additional setup.

Sub-agents

WithAgents defines custom agent types. WithAgent selects which agent to run the session as. Together they let you run Claude Code with a custom identity, prompt, tool set, and model — no need to pre-write agent files.

[agent_tool.go]: for using ClaudeCodeAgent as a tool callable by other eino agents, see [NewAgentTool] and ClaudeCodeTool.

Index

Constants

View Source
const (
	ToolBash      = "Bash"
	ToolRead      = "Read"
	ToolWrite     = "Write"
	ToolEdit      = "Edit"
	ToolGlob      = "Glob"
	ToolGrep      = "Grep"
	ToolWebFetch  = "WebFetch"
	ToolWebSearch = "WebSearch"
	ToolTask      = "Task"
)

Built-in tool names. Use these with WithTools, WithAllowedTools, WithDisallowedTools instead of raw strings for compile-time safety.

View Source
const (
	AgentDefault        = "claude"
	AgentExplore        = "Explore"
	AgentPlan           = "Plan"
	AgentGeneralPurpose = "general-purpose"
)

Built-in agent names. Use these with WithAgent instead of raw strings.

Variables

View Source
var (
	ErrCLINotFound = errors.New("claude CLI not found")
	ErrEmptyPrompt = errors.New("empty prompt")
)

Sentinel errors for programmatic error handling.

Functions

func FindCLI

func FindCLI(name string) string

FindCLI locates the claude CLI binary. If the given name is an absolute or relative path, it is returned as-is. Otherwise PATH is searched. Returns the original name if nothing is found (the exec layer will report a clear error when it can't start the process).

func NewSessionID

func NewSessionID() string

NewSessionID returns a new random UUID for use with WithSessionID and WithResume. Sessions persist conversation context across separate ClaudeCodeAgent.Run calls or program restarts.

Pass the returned ID to WithSessionID on the first call and WithResume on subsequent calls to continue the conversation. See examples/session for a complete example.

Types

type AgentDefinition

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

AgentDefinition defines a custom agent type for Claude Code's sub-agent system. It is serialized to JSON and passed via --agents.

type AgentError

type AgentError struct {
	Message string
	Cause   error
}

AgentError wraps an error that occurs during agent execution.

func (*AgentError) Error

func (e *AgentError) Error() string

func (*AgentError) Unwrap

func (e *AgentError) Unwrap() error

type CLIError

type CLIError struct {
	Message string
	Stderr  string
}

CLIError is returned when the Claude Code CLI process fails.

func (*CLIError) Error

func (e *CLIError) Error() string

type ClaudeCodeAgent

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

ClaudeCodeAgent is an eino Agent that invokes a locally installed Claude Code CLI in one-shot mode (claude -p). It implements adk.Agent and can be used with eino's runner, composed into multi-agent topologies, or wrapped as a tool.

Basic usage:

agent, _ := claudecode.New(
    claudecode.WithSystemPrompt("You are a helpful assistant."),
    claudecode.WithTools("Read", "Write", "Bash"),
)
runner := adk.NewRunner(ctx, adk.RunnerConfig{Agent: agent})
events := runner.run(ctx, []adk.Message{schema.UserMessage("Hello!")})

func New

func New(opts ...Option) (*ClaudeCodeAgent, error)

New creates a ClaudeCodeAgent with the given options.

func (*ClaudeCodeAgent) Description

func (a *ClaudeCodeAgent) Description(ctx context.Context) string

Description returns the agent description.

func (*ClaudeCodeAgent) Name

func (a *ClaudeCodeAgent) Name(ctx context.Context) string

Name returns the agent name.

func (*ClaudeCodeAgent) Resume

Resume restores the agent from a checkpoint and continues execution using the CLI --resume flag to reconnect to the saved session.

func (*ClaudeCodeAgent) Run

Run executes the Claude Code CLI and returns a stream of Agent events.

Each call spawns a new one-shot claude -p process. If WithCustomTools is configured, an embedded MCP HTTP server starts automatically and is passed to the CLI via --mcp-config; it shuts down when the CLI exits.

type ClaudeCodeTool

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

ClaudeCodeTool wraps a ClaudeCodeAgent as an eino Tool so it can be used by any eino ChatModelAgent as a "super tool" for delegating complex, multi-step tasks.

When invoked, it runs the Claude Code CLI with the given task and returns the result text. This integrates naturally with eino's ReAct loop — the parent agent decides when to delegate a task to Claude Code and receives the result.

func NewTool

func NewTool(opts ...Option) (*ClaudeCodeTool, error)

NewTool creates a ClaudeCodeTool backed by the given agent configuration.

func NewToolFromAgent added in v0.2.0

func NewToolFromAgent(agent *ClaudeCodeAgent) *ClaudeCodeTool

NewToolFromAgent wraps an existing ClaudeCodeAgent as a ClaudeCodeTool. The agent's name and description become the tool's metadata. This is useful when the same agent configuration needs to serve both as a standalone agent and as a callable tool in a multi-agent setup.

func (*ClaudeCodeTool) Info

Info returns the tool metadata for registration with eino.

func (*ClaudeCodeTool) InvokableRun

func (t *ClaudeCodeTool) InvokableRun(ctx context.Context, argumentsInJSON string, opts ...tool.Option) (string, error)

InvokableRun executes the tool. Expects {"task": "..."}.

type Option

type Option func(*Options)

Option is a functional option for configuring a ClaudeCodeAgent.

func WithAddDirs

func WithAddDirs(dirs ...string) Option

WithAddDirs adds directories to the CLI's workspace.

func WithAgent added in v0.2.0

func WithAgent(name string) Option

WithAgent selects which agent type to run as for this session. The name must match a key defined via WithAgents, or a built-in agent like "Plan" or "Explore". Passed to the CLI via --agent.

func WithAgents

func WithAgents(agents map[string]AgentDefinition) Option

WithAgents registers custom agent definitions for sub-agent delegation. Keys are agent type names (e.g., "reviewer", "tester"). The map is serialized to JSON and passed to the CLI via --agents.

func WithAllowedTools

func WithAllowedTools(tools ...string) Option

WithAllowedTools sets tools that are auto-approved without prompting.

func WithAppendSystemPrompt

func WithAppendSystemPrompt(prompt string) Option

WithAppendSystemPrompt appends to the default system prompt instead of replacing it.

func WithBare

func WithBare(v bool) Option

WithBare controls minimal mode (bare). Default: true. Bare mode skips hooks, LSP, plugin sync, attribution, auto-memory, keychain reads, and CLAUDE.md auto-discovery — appropriate for SDK/programmatic use. Set WithBare(false) if you need interactive initialization features.

func WithBetas

func WithBetas(betas ...string) Option

WithBetas enables beta features on the CLI.

func WithBin

func WithBin(bin string) Option

WithBin sets the path to the claude CLI executable.

func WithCWD

func WithCWD(dir string) Option

WithCWD sets the working directory for the CLI process.

func WithContinueConversation

func WithContinueConversation() Option

WithContinueConversation resumes the most recent conversation.

func WithCustomTools added in v0.2.0

func WithCustomTools(tools ...tool.InvokableTool) Option

WithCustomTools registers eino InvokableTools that are exposed to Claude Code via an embedded MCP HTTP server. The server starts on a random localhost port at agent.Run() time and is passed to the CLI via --mcp-config.

Claude Code discovers these tools automatically and can call them during task execution. This lets you extend Claude Code's capabilities with arbitrary Go code while keeping the black-box executor model.

func WithDebug

func WithDebug(filter string) Option

WithDebug enables debug mode with optional category filtering. Example filter: "api,hooks". Pass "" to enable all debug output.

func WithDebugFile

func WithDebugFile(path string) Option

WithDebugFile writes debug logs to the given file path. Implicitly enables debug mode. Use for capturing CLI debug output separately from stderr.

func WithDescription

func WithDescription(desc string) Option

WithDescription sets the agent description.

func WithDisallowedTools

func WithDisallowedTools(tools ...string) Option

WithDisallowedTools sets tools that are blocked.

func WithEffort

func WithEffort(effort string) Option

WithEffort sets the thinking effort level. Valid values: "low", "medium", "high", "xhigh", "max".

func WithEmitToolEvents

func WithEmitToolEvents() Option

WithEmitToolEvents enables surfacing Claude Code's internal tool calls as AgentEvents (with ToolCalls on the message). This gives parent agents visibility into what tools Claude Code is using.

func WithEnv

func WithEnv(env ...string) Option

WithEnv adds environment variables (KEY=VALUE) for the CLI process.

func WithExcludeDynamicSystemPromptSections

func WithExcludeDynamicSystemPromptSections(v bool) Option

WithExcludeDynamicSystemPromptSections controls whether per-machine sections (cwd, env info, git status) are moved from the system prompt into the first user message. Default: true. Improves Anthropic prompt-cache reuse. Ignored when a custom SystemPrompt is set.

func WithExtraArgs

func WithExtraArgs(args map[string]string) Option

WithExtraArgs passes additional CLI flags through. Key is the flag name (without leading dash), value is the flag value (empty string for boolean flags).

func WithFallbackModel

func WithFallbackModel(model string) Option

WithFallbackModel specifies a fallback model if the primary is unavailable.

func WithForkSession

func WithForkSession() Option

WithForkSession forks a resumed session to a new session ID.

func WithIncludePartialMessages

func WithIncludePartialMessages() Option

WithIncludePartialMessages enables partial streaming events from the CLI.

func WithMCPConfig

func WithMCPConfig(configJSON string) Option

WithMCPConfig sets inline MCP server configuration (JSON format). Example: `{"github":{"type":"http","url":"..."}}`.

func WithMCPConfigPath

func WithMCPConfigPath(path string) Option

WithMCPConfigPath sets the path to an MCP configuration file.

func WithMaxBudgetUSD

func WithMaxBudgetUSD(budget float64) Option

WithMaxBudgetUSD sets a spending cap in USD.

func WithMaxTurns

func WithMaxTurns(n int) Option

WithMaxTurns sets the maximum number of agent turns.

func WithModel

func WithModel(model string) Option

WithModel specifies the model to use.

func WithName

func WithName(name string) Option

WithName sets the agent name.

func WithNoSessionPersistence

func WithNoSessionPersistence(v bool) Option

WithNoSessionPersistence disables writing sessions to disk. Use for stateless one-shot tasks where sessions don't need to be resumed. Default: false. Only works with one-shot mode (--print).

func WithPermissionMode

func WithPermissionMode(mode string) Option

WithPermissionMode sets the permission mode. Valid values: "default", "acceptEdits", "plan", "bypassPermissions", "auto", "dontAsk". Default: "dontAsk".

func WithPluginDir

func WithPluginDir(path string) Option

WithPluginDir adds a plugin directory or .zip file to load for this session. Repeatable — each call appends another path.

func WithPluginURL

func WithPluginURL(url string) Option

WithPluginURL adds a URL to fetch a plugin .zip from for this session. Repeatable — each call appends another URL.

func WithResume

func WithResume(sessionID string) Option

WithResume resumes a specific session by ID.

func WithRunner added in v0.2.0

func WithRunner(r Runner) Option

WithRunner overrides the CLI runner (for testing).

func WithSessionID

func WithSessionID(id string) Option

WithSessionID creates a new session with the given session ID.

func WithSettingSources

func WithSettingSources(sources ...string) Option

WithSettingSources controls which settings files to load. nil = CLI default. Empty slice = no settings.

func WithSettings

func WithSettings(settingsJSON string) Option

WithSettings sets inline JSON settings for the CLI.

func WithStderr

func WithStderr(fn func(string)) Option

WithStderr sets a callback that receives each line of stderr output from the CLI process. Useful for debugging CLI issues.

func WithStrictMCPConfig

func WithStrictMCPConfig(v bool) Option

WithStrictMCPConfig controls whether only --mcp-config servers are used. When true (default), local .mcp.json files are ignored — appropriate for SDK use where MCP configuration should be explicit.

func WithStructuredOutput

func WithStructuredOutput(schema string) Option

WithStructuredOutput sets a JSON Schema for structured output.

func WithSystemPrompt

func WithSystemPrompt(prompt string) Option

WithSystemPrompt sets the system prompt.

func WithTools

func WithTools(tools ...string) Option

WithTools sets the list of tools the agent can use. nil = default CLI tools. Empty slice = no tools.

type Options

type Options struct {
	// Name is the agent name (default: "claude-code").
	Name string
	// Description is a short description of the agent.
	Description string
	// Bin is the path to the claude CLI executable (default: auto-discovered).
	Bin string

	// --- Prompt options ---
	// SystemPrompt sets the system prompt (replaces default).
	SystemPrompt string
	// AppendSystemPrompt appends to the default system prompt.
	AppendSystemPrompt string

	// --- Tool options ---
	// Tools is the list of tool names the agent can use.
	// nil means default CLI tools; empty slice means no tools.
	Tools []string
	// AllowedTools is the list of tools auto-approved without prompting.
	AllowedTools []string
	// DisallowedTools is the list of tools blocked from the agent.
	DisallowedTools []string

	// --- Model options ---
	// Model specifies the model to use (e.g., "claude-sonnet-4-6").
	Model string
	// FallbackModel specifies a fallback model if the primary is unavailable.
	FallbackModel string

	// --- Budget options ---
	// MaxTurns limits the number of agent turns (0 = default).
	MaxTurns int
	// MaxBudgetUSD sets a spending cap in USD (0 = no limit).
	MaxBudgetUSD float64

	// --- Permission options ---
	// PermissionMode sets the permission mode.
	// Valid: "default", "acceptEdits", "plan", "bypassPermissions", "auto", "dontAsk".
	// Default: "dontAsk" (no interactive prompts — appropriate for SDK use).
	PermissionMode string
	// PermissionPromptToolName sets the tool used for permission prompts (default: auto when hooks are set).
	PermissionPromptToolName string

	// --- Session options ---
	// ContinueConversation resumes the most recent conversation.
	ContinueConversation bool
	// Resume resumes a specific session by ID.
	Resume string
	// SessionID creates a new session with the given ID.
	SessionID string
	// ForkSession forks the resumed session to a new session ID.
	ForkSession bool
	// NoSessionPersistence disables writing sessions to disk.
	// When true, sessions cannot be resumed. Only works with --print (one-shot mode).
	// Default: false (sessions are persisted for cross-agent context sharing).
	NoSessionPersistence bool

	// --- MCP options ---
	// MCPConfig is inline MCP server configuration in JSON format.
	MCPConfig string
	// MCPConfigPath is the path to an MCP configuration file.
	MCPConfigPath string

	// StrictMCPConfig ignores all MCP servers except those from --mcp-config.
	// Default: true (SDK should not load local .mcp.json).
	StrictMCPConfig bool

	// --- Config options ---
	// Bare enables minimal mode: skip hooks, LSP, plugin sync, attribution,
	// auto-memory, keychain reads, and CLAUDE.md auto-discovery.
	// Default: true (SDK/programmatic use doesn't need interactive initialization).
	Bare bool
	// ExcludeDynamicSystemPromptSections moves per-machine sections (cwd, env,
	// git status) from the system prompt into the first user message, improving
	// Anthropic prompt-cache reuse. Default: true. Ignored when SystemPrompt is set.
	ExcludeDynamicSystemPromptSections bool
	// SettingSources controls which settings files to load (nil = default, empty = none).
	SettingSources []string
	// Settings is JSON settings to pass inline.
	Settings string
	// AddDirs adds directories to the CLI's workspace.
	AddDirs []string
	// Betas enables beta features.
	Betas []string
	// Agents is a JSON string defining custom agent types for sub-agent delegation.
	// Use WithAgents(map[string]AgentDefinition{...}) to build it.
	Agents string
	// Agent selects which agent type to run the session as.
	// Must match a key in Agents or a built-in agent.
	// Passed to the CLI via --agent.
	Agent string
	// PluginDirs are paths to plugin directories or .zip files to load.
	PluginDirs []string
	// PluginURLs are URLs to fetch plugin .zip files from.
	PluginURLs []string

	// --- Environment options ---
	// CWD sets the working directory for the CLI process.
	CWD string
	// Env adds environment variables (KEY=VALUE) for the CLI process.
	Env []string

	// --- Advanced options ---
	// IncludePartialMessages requests partial message streaming events.
	IncludePartialMessages bool
	// Effort sets the thinking effort level.
	// Valid: "low", "medium", "high", "xhigh", "max".
	Effort string
	// StructuredOutput sets a JSON Schema for structured output.
	StructuredOutput string
	// Debug enables debug mode. Default: false.
	Debug bool
	// DebugFilter is an optional category filter for debug output (e.g. "api,hooks").
	// Only used when Debug is true.
	DebugFilter string
	// DebugFile writes debug logs to a specific file path.
	// Implicitly enables debug mode.
	DebugFile string

	// --- eino integration options ---
	// EmitToolEvents controls whether Claude Code's internal tool calls are surfaced
	// as AgentEvents with ToolCalls.
	EmitToolEvents bool
	// CustomTools are eino InvokableTools exposed to Claude Code via an embedded
	// MCP HTTP server. The server is started on a random localhost port and
	// passed to the CLI via --mcp-config.
	CustomTools []tool.InvokableTool

	// --- Callbacks ---
	// Stderr receives each line of stderr output from the CLI process.
	Stderr func(string)

	// ExtraArgs are additional CLI flags to pass through.
	// Key is the flag name (without leading dash), value is the flag value
	// (empty string for boolean flags).
	ExtraArgs map[string]string

	// --- Internal / testing ---
	// Runner allows custom CLI execution (default: execRunner).
	Runner Runner
}

Options holds all configuration for a ClaudeCodeAgent.

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions returns the recommended default configuration.

func (*Options) BuildArgs

func (o *Options) BuildArgs(prompt string) []string

BuildArgs constructs the CLI argument list for one-shot mode (claude -p).

func (*Options) BuildFlags added in v0.2.0

func (o *Options) BuildFlags() []string

BuildFlags returns the CLI flags without the positional prompt. This allows callers to insert additional flags before the prompt.

type Runner added in v0.2.0

type Runner interface {
	// Run executes the CLI and returns all responses (batch mode).
	Run(ctx context.Context, args []string) ([]cliResponse, error)
	// RunStreaming reads CLI responses as they arrive on stdout.
	// The channel is closed when the CLI process exits or ctx is cancelled.
	RunStreaming(ctx context.Context, args []string) <-chan StreamEvent
}

Runner abstracts CLI process execution for testability and custom deployment (e.g. Docker containers, SSH remotes). The default implementation is [execRunner].

type StreamEvent added in v0.2.0

type StreamEvent struct {
	Response cliResponse
	Err      error
}

StreamEvent is a single event from the streaming CLI reader.

Directories

Path Synopsis
examples
chain command
customtools command
delegate command
helloworld command
parallel command
runas command
session command
tool command

Jump to

Keyboard shortcuts

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