claude

package
v0.93.0 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2026 License: BSD-2-Clause Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// AgentStatusDone indicates the task completed successfully.
	AgentStatusDone = agentlib.AgentStatusDone
	// AgentStatusFailed indicates the task failed.
	AgentStatusFailed = agentlib.AgentStatusFailed
	// AgentStatusNeedsInput indicates the task requires additional user input.
	AgentStatusNeedsInput = agentlib.AgentStatusNeedsInput
)

Variables

This section is empty.

Functions

func BuildPrompt

func BuildPrompt(
	instructions string,
	envContext map[string]string,
	taskContent string,
) string

BuildPrompt combines instructions with environment context and task content.

func BuildResultSection

func BuildResultSection(result AgentResultLike) string

BuildResultSection renders the default ## Result markdown block for any AgentResultLike.

func NewAgentStep

func NewAgentStep(cfg AgentStepConfig) agentlib.Step

NewAgentStep wraps a single Claude invocation as an agentlib.Step.

Used by AI-heavy agents (trade-analysis, pr-reviewer style). The LLM reads the marshaled task content (frontmatter + body) and writes its output verbatim under the configured section heading.

For boundary parsing (markdown → typed Go struct), use agentlib.NewParseStep with an AIParser implementation instead.

func NewSession added in v0.92.0

func NewSession(config ClaudeRunnerConfig, decider PermissionDecider) agentlib.Session

NewSession returns a Session backed by one long-lived claude process.

The process is started on the first Prompt and held for the session's life, so a second prompt reaches the same process and the same conversation. The session's constructor performs no I/O because the shared session interface's factory is construction-only by contract; the spawn is therefore deferred to the first turn.

config is the same ClaudeRunnerConfig the one-shot runner takes, so there is no second configuration to keep in sync. decider receives every mid-turn tool decision; a nil decider fails a turn that raises one rather than blocking.

func NewSessionFactory added in v0.92.0

func NewSessionFactory(base ClaudeRunnerConfig, decider PermissionDecider) agentlib.SessionFactory

NewSessionFactory returns a SessionFactory that builds one claude-backed session per session id.

Every id gets its own session and therefore its own process. The id is not part of the spawn: continuity comes from the held process, not from a CLI flag, so the argv is identical for every id and no id can reach the argument vector.

func PrintResult

func PrintResult(ctx context.Context, result AgentResult) error

PrintResult marshals an AgentResult to JSON and prints to stdout.

Types

type AgentDir

type AgentDir string

AgentDir is the path to the agent directory containing .claude/ config.

func (AgentDir) Resolve

func (a AgentDir) Resolve(ctx context.Context) (string, error)

Resolve expands a leading "~/" to the user's home directory. See ClaudeConfigDir.Resolve for full semantics.

func (AgentDir) String

func (a AgentDir) String() string

String returns the raw path string as configured.

type AgentResult

type AgentResult struct {
	Status    AgentStatus `json:"status"`
	Message   string      `json:"message,omitempty"`
	Files     []string    `json:"files,omitempty"`
	NextPhase string      `json:"next_phase,omitempty"`
	// Output is the payload the agent declares for the configured output
	// section — typically a heading plus a fenced JSON block, with newlines
	// escaped as they are on the wire. It is the value AgentStep.Run writes
	// into the output section, so the next phase can parse that section
	// directly instead of unwrapping the result envelope first.
	//
	// Distinct from AgentResultInfo.Output, which carries a fully rendered
	// section body including its heading, produced by BuildResultSection on
	// the single-shot task-runner path. The two must not be conflated: this
	// field is an input from the agent, that one is rendered output.
	Output string `json:"output,omitempty"`
}

AgentResult is the structured output written to stdout for the task/executor to read.

func (AgentResult) GetFiles

func (r AgentResult) GetFiles() []string

func (AgentResult) GetMessage

func (r AgentResult) GetMessage() string

func (AgentResult) GetNextPhase

func (r AgentResult) GetNextPhase() string

GetNextPhase returns the requested next task phase, or empty string for default behavior.

func (AgentResult) GetStatus

func (r AgentResult) GetStatus() AgentStatus

func (AgentResult) RenderResultSection

func (r AgentResult) RenderResultSection() string

type AgentResultLike

type AgentResultLike interface {
	GetStatus() AgentStatus
	GetMessage() string
	GetFiles() []string
	GetNextPhase() string
	RenderResultSection() string
}

AgentResultLike is the constraint for types that can be delivered as task results.

type AgentStatus

type AgentStatus = agentlib.AgentStatus

AgentStatus is the shared agent status type.

type AgentStepConfig

type AgentStepConfig struct {
	// Name is the step name for logs.
	Name string

	// Runner is the Claude CLI invocation backend (pre-configured with
	// AllowedTools, Model, ClaudeConfigDir via ClaudeRunnerConfig).
	Runner ClaudeRunner

	// Instructions is the system prompt for this step.
	Instructions Instructions

	// EnvContext is forwarded to the Claude CLI tool-invocation environment.
	EnvContext map[string]string

	// OutputSection is the body section heading for the LLM's output
	// (e.g. "## Analysis", "## Review").
	OutputSection string

	// NextPhase is the phase to advance to on success. Empty means
	// in-place save (multi-step phase intermediate).
	NextPhase string
}

AgentStepConfig bundles everything an agent Step needs at construction time.

The Runner is pre-configured with AllowedTools + Model via ClaudeRunnerConfig at construction; per-step Instructions + EnvContext are supplied here so a single Runner can serve multiple steps with different prompts.

type AllowedTools

type AllowedTools []string

AllowedTools is a list of tool names permitted in headless Claude sessions.

func ParseAllowedTools

func ParseAllowedTools(s string) AllowedTools

ParseAllowedTools parses a comma-separated string into AllowedTools.

func (AllowedTools) String

func (a AllowedTools) String() string

String returns the comma-separated tool list for the CLI --allowedTools flag.

type ClaudeConfigDir

type ClaudeConfigDir string

ClaudeConfigDir is the path to the Claude Code configuration directory (~/.claude).

func (ClaudeConfigDir) Resolve

func (c ClaudeConfigDir) Resolve(ctx context.Context) (string, error)

Resolve expands a leading "~/" to the user's home directory. Empty input returns empty string. Absolute paths and paths without a tilde prefix are returned unchanged. Use at the trust boundary — when emitting the path into a subprocess env var, opening a file, or constructing a filesystem operation — so configuration like CLAUDE_CONFIG_DIR=~/.claude works on every consumer regardless of whether the consumer expands tildes itself.

func (ClaudeConfigDir) String

func (c ClaudeConfigDir) String() string

String returns the raw path string as configured. Use Resolve when the path will cross into a subprocess or filesystem call — String preserves the literal "~/" prefix that environment variables and child processes generally do not expand.

type ClaudeModel

type ClaudeModel string

ClaudeModel identifies which Claude model to use.

const (
	SonnetClaudeModel ClaudeModel = "sonnet"
	OpusClaudeModel   ClaudeModel = "opus"
)

func (ClaudeModel) String

func (c ClaudeModel) String() string

String returns the model name.

type ClaudeResult

type ClaudeResult struct {
	Result string `json:"result"`
	// Partial is the assistant text the CLI streamed before the run ended, bounded
	// to the most recent 16 KiB. Empty when the CLI streamed no assistant text.
	Partial string `json:"partial,omitempty"`
	// InputTokens is the count of fresh (non-cached) input tokens the session consumed.
	InputTokens int64 `json:"input_tokens,omitempty"`
	// OutputTokens is the count of output tokens the session produced.
	OutputTokens int64 `json:"output_tokens,omitempty"`
	// CacheCreationTokens is the count of input tokens written into the prompt cache.
	CacheCreationTokens int64 `json:"cache_creation_tokens,omitempty"`
	// CacheReadTokens is the count of input tokens served from the prompt cache.
	CacheReadTokens int64 `json:"cache_read_input_tokens,omitempty"`
	// NumTurns is the number of conversation turns the session took. Zero when the
	// CLI reported no usage summary.
	NumTurns int64 `json:"num_turns,omitempty"`
	// SessionID is the CLI session identifier the stream reported. Empty when the CLI
	// reported no session id.
	SessionID string `json:"session_id,omitempty"`
	// InteractionCount is the number of human-authored entries the session's own
	// transcript recorded. Nil when the evidence was unavailable — no session id, no
	// transcript, or an unreadable or unparseable transcript. A non-nil zero is an
	// observation: the transcript was read and contained no human-authored entry.
	InteractionCount *int64 `json:"interaction_count,omitempty"`
}

ClaudeResult holds the parsed output from a Claude Code CLI session.

type ClaudeRunner

type ClaudeRunner interface {
	Run(ctx context.Context, prompt string) (*ClaudeResult, error)
}

ClaudeRunner spawns a headless Claude Code CLI session with a prompt and MCP tools.

func NewClaudeRunner

func NewClaudeRunner(config ClaudeRunnerConfig) ClaudeRunner

NewClaudeRunner creates a ClaudeRunner that spawns claude --print with MCP tools.

type ClaudeRunnerConfig

type ClaudeRunnerConfig struct {
	// ClaudeConfigDir overrides the Claude CLI config directory via CLAUDE_CONFIG_DIR.
	ClaudeConfigDir ClaudeConfigDir
	// AllowedTools is passed to claude --allowedTools to restrict tool access.
	AllowedTools AllowedTools
	// Model selects the Claude model (e.g. "sonnet", "opus").
	Model ClaudeModel
	// WorkingDirectory sets the CLI process working directory.
	WorkingDirectory AgentDir
	// Env holds extra KEY=VALUE entries appended to the subprocess environment
	// AFTER the allowlist + CLAUDE_CONFIG_DIR layers (see buildSubprocessEnv in claude-runner.go). This is
	// the escape hatch for passing through secrets or vars the allowlist would
	// otherwise strip (e.g. GH_TOKEN for gh CLI auth). Values here cross the
	// trust boundary into the Claude CLI subprocess — only add what the agent
	// genuinely needs.
	Env map[string]string
}

ClaudeRunnerConfig holds configuration for spawning Claude Code CLI.

type Instruction

type Instruction struct {
	Name    string
	Content string
}

Instruction is a named prompt section wrapped in XML tags.

func (Instruction) String

func (i Instruction) String() string

String renders the instruction as an XML-tagged block.

type Instructions

type Instructions []Instruction

Instructions is a list of named prompt sections.

func (Instructions) String

func (ii Instructions) String() string

String renders all instructions separated by newlines.

func (Instructions) Strings

func (ii Instructions) Strings() []string

Strings returns each instruction rendered as an XML-tagged string.

type PermissionDecider added in v0.92.0

type PermissionDecider interface {
	DecidePermission(ctx context.Context, request PermissionRequest) (PermissionDecision, error)
}

PermissionDecider decides whether a tool invocation the CLI raised mid-turn is allowed. It is the one place this package accepts an instruction from outside the process. The pod's HTTP surface implements it; a nil decider is invalid.

type PermissionDecision added in v0.92.0

type PermissionDecision struct {
	// Allow reports whether the tool invocation may proceed.
	Allow bool
	// Message is an optional explanation returned to the CLI on denial.
	Message string
}

PermissionDecision is the verdict returned for a PermissionRequest.

type PermissionRequest added in v0.92.0

type PermissionRequest struct {
	// ToolName is the name of the tool the CLI wants to invoke.
	ToolName string
	// Description is the CLI's human-readable description of the invocation.
	Description string
	// InputPreview is a preview of the tool input. It is not logged.
	InputPreview string
}

PermissionRequest describes a tool invocation the CLI raised mid-turn and is waiting on. It carries no conversation content: only the tool's name, a human-readable description, and a preview of the tool input.

type PluginCommander

type PluginCommander interface {
	Run(ctx context.Context, name string, args ...string) (string, error)
}

PluginCommander runs an external command and returns its combined stdout.

func NewExecPluginCommander

func NewExecPluginCommander() PluginCommander

NewExecPluginCommander returns a PluginCommander that uses os/exec to run real processes.

type PluginInstaller

type PluginInstaller interface {
	EnsureInstalled(ctx context.Context, specs []PluginSpec) error
}

PluginInstaller ensures a list of Claude plugins are installed or updated.

func NewPluginInstaller

func NewPluginInstaller(commander PluginCommander) PluginInstaller

NewPluginInstaller returns a PluginInstaller that uses the given PluginCommander to manage Claude plugins.

type PluginSpec

type PluginSpec struct {
	Marketplace string // e.g. "bborbe/coding"
	Name        string // e.g. "coding"
}

PluginSpec identifies a Claude Code plugin to ensure is installed.

type ResultDeliverer

type ResultDeliverer[T AgentResultLike] interface {
	DeliverResult(ctx context.Context, result T) error
}

ResultDeliverer publishes a task result back after execution completes.

func NewNoopResultDeliverer

func NewNoopResultDeliverer() ResultDeliverer[AgentResult]

NewNoopResultDeliverer creates a ResultDeliverer[AgentResult] that does nothing.

func NewResultDelivererAdapter

func NewResultDelivererAdapter[T AgentResultLike](
	inner agentlib.ResultDeliverer,
) ResultDeliverer[T]

NewResultDelivererAdapter wraps a agentlib.ResultDeliverer to accept any AgentResultLike.

type TaskRunner

type TaskRunner[T AgentResultLike] interface {
	Run(ctx context.Context, taskContent string) (*T, error)
}

TaskRunner orchestrates task execution by launching a single Claude Code session.

func NewTaskRunner

func NewTaskRunner[T AgentResultLike](
	runner ClaudeRunner,
	instructions Instructions,
	envContext map[string]string,
	deliverer ResultDeliverer[T],
) TaskRunner[T]

NewTaskRunner creates a TaskRunner with injected dependencies.

Jump to

Keyboard shortcuts

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