agent

package
v1.4.13 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 9 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package agent is the public, embeddable SDK for driving a golder agent from your own Go program. It wraps golder's internal run-assembly, provider, and agent-loop packages behind a stable public surface of SDK-owned values and callbacks. No exported signature mentions a golder internal type, so golder can evolve its implementation packages without forcing consumers to depend on them.

Quick start

sess, err := agent.New(
	agent.WithModel("claude-opus-4-8"),
	agent.WithAPIKey(os.Getenv("ANTHROPIC_API_KEY")),
)
if err != nil {
	log.Fatal(err)
}
defer sess.Close()

reply, err := sess.Prompt(context.Background(), "Say hello in one word.")
fmt.Println(reply)

Model, provider, credentials

The model id selects the provider the same way the golder CLI does: "claude-opus-4-8" resolves to Anthropic, "openrouter/free" to OpenRouter, and so on. Point at any OpenAI- or Anthropic-compatible endpoint with WithBaseURL + WithProtocol, or a named provider from your config with WithProvider. The API key comes from WithAPIKey or, if unset, the provider's usual environment variable (e.g. ANTHROPIC_API_KEY). Keys are never logged.

Tools run automatically — read this

By default a session is created with golder's full built-in tool set (read, write, edit, bash, find, grep, and more) and those tools are executed WITHOUT any per-call confirmation prompt — equivalent to running the CLI with --approve. An agent can therefore read, modify, and delete files under its working directory and run shell commands on the host. This is the right default for an automated SDK, but it means you should only send prompts you trust, and run in a directory (and, ideally, a sandbox) you are willing to let the agent modify. To constrain or remove built-ins use WithTools (an allowlist), WithDisallowedTools (a denylist, which always wins), or WithoutTools. Explicit caller-owned tools can be added with WithCustomTools; combining WithoutTools with WithCustomTools creates a custom-only session.

Streaming

Session.Stream reports incremental assistant text. Session.StreamEvents reports SDK-owned structured message, thinking, tool, and usage events while returning the same final assistant text as Prompt.

Conversation state

A Session keeps the running conversation: each Session.Prompt, Session.Stream, or Session.StreamEvents call appends to the same history, so follow-up prompts see what came before. Call Session.Reset to start a fresh conversation on the same session, or Session.Close when you are done. A Session is NOT safe for concurrent use — drive it from one goroutine, or create one Session per goroutine.

Defaults

  • Tools: on (full built-in set, auto-executed; see the safety note above).
  • Skills: off — enable discovery of on-disk skills with WithSkills.
  • Memory: off — enable the persistent memory store with WithMemory.
  • Thinking: "medium" — override with WithThinkingLevel.

Skills and memory are off by default so an embedded session is hermetic: it does not read or write the machine's shared golder state unless you ask it to.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Event

type Event interface {
	EventType() EventType
	// contains filtered or unexported methods
}

Event is the sealed interface implemented by the public structured event types emitted by StreamEvents.

type EventType

type EventType string

EventType is the stable discriminant for structured Session events.

const (
	EventMessageDelta        EventType = "message_delta"
	EventMessageEnd          EventType = "message_end"
	EventThinkingDelta       EventType = "thinking_delta"
	EventToolExecutionStart  EventType = "tool_execution_start"
	EventToolExecutionUpdate EventType = "tool_execution_update"
	EventToolExecutionEnd    EventType = "tool_execution_end"
	EventUsage               EventType = "usage"
)

type MessageDeltaEvent

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

MessageDeltaEvent carries only newly appended assistant text. Deltas are best-effort appends: if a provider replaces already-streamed text, the replacement is re-emitted in full as a new delta, so concatenating deltas can repeat text. Treat MessageEndEvent.Text as authoritative for the complete message text.

func (MessageDeltaEvent) EventType

func (MessageDeltaEvent) EventType() EventType

type MessageEndEvent

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

MessageEndEvent carries the complete text of one finished assistant message.

func (MessageEndEvent) EventType

func (MessageEndEvent) EventType() EventType

type Option

type Option func(*config)

Option configures a Session at construction time. Options are applied in the order passed to New, so a later option overrides an earlier one that sets the same field. Because config is unexported, the only way to produce an Option is through the With* constructors below — which keeps the public surface free of internal types.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the API key for the resolved provider, overriding the provider's environment variable. When unset, the provider's usual environment variable is used (e.g. ANTHROPIC_API_KEY, OPENROUTER_API_KEY).

func WithAppendSystemPrompt

func WithAppendSystemPrompt(blocks ...string) Option

WithAppendSystemPrompt appends one or more blocks to the system prompt, leaving golder's built-in instruction in place. Repeated calls accumulate.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL points the session at a custom endpoint. Pair it with WithProtocol to say whether that endpoint speaks the OpenAI or Anthropic wire format.

func WithCustomTools

func WithCustomTools(tools ...Tool) Option

WithCustomTools explicitly registers caller-owned tools. Custom tools are installed after built-in policy resolution, so they remain available when WithoutTools is used. New validates tool names, schemas, execution modes, duplicate names, and collisions with any surviving built-in tool.

func WithDisallowedTools

func WithDisallowedTools(names ...string) Option

WithDisallowedTools removes the named built-in tools (a denylist, e.g. WithDisallowedTools("bash")). Deny always wins: a built-in named here is removed even if it also appears in WithTools. As with WithTools, an unknown built-in name makes New return an error. Explicit custom tools registered with WithCustomTools are not filtered by this built-in denylist.

func WithMemory

func WithMemory() Option

WithMemory enables golder's persistent memory store, letting the agent recall context saved by earlier runs and record new memories. Memory is off by default so an embedded session does not read or write shared state unless asked.

func WithModel

func WithModel(model string) Option

WithModel sets the model id, which also selects the provider the way the golder CLI does (e.g. "claude-opus-4-8" → Anthropic, "openrouter/free" → OpenRouter). The default is "openrouter/free".

func WithProtocol

func WithProtocol(protocol string) Option

WithProtocol selects the wire protocol for a custom endpoint: "openai" or "anthropic". It is only consulted when WithBaseURL is set.

func WithProvider

func WithProvider(name string) Option

WithProvider selects a named provider from your golder configuration instead of inferring one from the model id.

func WithSkills

func WithSkills() Option

WithSkills enables discovery of on-disk skills, which are advertised to the model and loadable during a run. Skills are off by default so an embedded session stays independent of the machine's shared skills directory.

func WithSystemPrompt

func WithSystemPrompt(prompt string) Option

WithSystemPrompt replaces golder's built-in base instruction with prompt. Use this for full control over the agent's persona and rules; use WithAppendSystemPrompt instead to keep the built-in instruction and add to it.

func WithThinkingLevel

func WithThinkingLevel(level string) Option

WithThinkingLevel sets the reasoning-effort level. Valid values are "off", "minimal", "low", "medium", "high", "xhigh", and "max". The default is "max". An invalid value makes New return an error.

func WithTools

func WithTools(names ...string) Option

WithTools restricts the session to the named built-in tools (an allowlist, e.g. WithTools("read", "grep")). Names are matched case-insensitively, so "Read" and "read" are equivalent. A name that matches no built-in makes New return an error rather than silently ignoring it. Combine with WithDisallowedTools; deny always wins over allow. Explicit custom tools registered with WithCustomTools are separate from this built-in allowlist.

func WithoutTools

func WithoutTools() Option

WithoutTools removes every built-in tool. It overrides WithTools and WithDisallowedTools, which become inert once the built-in set is empty. Explicit tools registered with WithCustomTools remain available, so WithoutTools plus WithCustomTools is the custom-only embedding pattern.

type Session

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

Session is a single, stateful golder agent conversation. Create one with New, drive it with Prompt or Stream, and release its resources with Close. The conversation history accumulates across calls, so follow-up prompts see the earlier exchange; call Reset to start over on the same session.

A Session is not safe for concurrent use. Drive it from a single goroutine, or give each goroutine its own Session.

func New

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

New builds a Session from the given options. It resolves the provider and credentials, assembles the tool set, and validates the tool policy and thinking level up front, so a configuration mistake (an unknown tool name, an invalid thinking level, an unresolvable provider) is returned here rather than surfacing on the first Prompt.

No network call is made by New: the provider is only contacted when you call Prompt or Stream. This makes New cheap and safe to use in tests.

See the package documentation for the default tool, skill, and memory behavior — in particular, that tools are enabled and auto-executed by default.

func (*Session) Close

func (s *Session) Close() error

Close releases resources held by the session: any loaded plugin manager and the persistent memory store (when WithMemory was used). It is safe to call once, and safe to call on a session that holds neither. After Close the session must not be used again.

func (*Session) Model

func (s *Session) Model() string

Model returns the model id the session was created with.

func (*Session) Prompt

func (s *Session) Prompt(ctx context.Context, prompt string) (string, error)

Prompt sends one user message, runs the agent loop to completion (executing any tool calls the model makes along the way), and returns the assistant's final text. The exchange is appended to the session history so later prompts have this context.

func (*Session) Provider

func (s *Session) Provider() string

Provider returns the resolved provider name (e.g. "anthropic", "openrouter"), which is inferred from the model id unless WithProvider was set.

func (*Session) Reset

func (s *Session) Reset()

Reset clears the conversation history, so the next Prompt starts a fresh exchange. The provider, tool set, and system prompt are unchanged.

func (*Session) Stream

func (s *Session) Stream(ctx context.Context, prompt string, onText func(string)) (string, error)

Stream is Prompt with incremental output: onText, if non-nil, is called with each chunk of assistant text as it arrives, and the complete final text is also returned. Tool calls still run automatically between text chunks. A nil onText makes Stream behave exactly like Prompt.

func (*Session) StreamEvents

func (s *Session) StreamEvents(ctx context.Context, prompt string, onEvent func(Event)) (string, error)

StreamEvents is Prompt with stable structured events. onEvent, if non-nil, receives message/thinking deltas, tool execution lifecycle events, message completion, and usage in agent-loop order. The complete final assistant text is also returned. A nil onEvent behaves exactly like Prompt.

func (*Session) ToolNames

func (s *Session) ToolNames() []string

ToolNames returns the names of the tools available to this session, in the order they are advertised to the model. It reflects both the applied built-in tool policy and explicitly registered custom tools. A WithoutTools session is empty unless WithCustomTools supplied an explicit custom set.

type ThinkingDeltaEvent

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

ThinkingDeltaEvent carries only newly appended assistant reasoning text.

func (ThinkingDeltaEvent) EventType

func (ThinkingDeltaEvent) EventType() EventType

type Tool

type Tool struct {
	Name          string
	Description   string
	Schema        json.RawMessage
	ExecutionMode ToolExecutionMode
	Execute       ToolExecuteFunc
}

Tool defines a custom tool explicitly registered by an SDK consumer. Schema is the JSON Schema advertised for Arguments.

type ToolCall

type ToolCall struct {
	ID        string          `json:"id"`
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments"`
}

ToolCall describes one model-requested invocation of a custom tool.

type ToolExecuteFunc

type ToolExecuteFunc func(ctx context.Context, call ToolCall, onUpdate func(ToolResult)) (ToolResult, error)

ToolExecuteFunc executes a custom tool. onUpdate may be nil; when non-nil the tool may publish partial results while it runs. Calls to onUpdate are safe from any goroutine and are serialized by the adapter; updates published after Execute returns are discarded.

type ToolExecutionEndEvent

type ToolExecutionEndEvent struct {
	ToolCallID string     `json:"toolCallId"`
	ToolName   string     `json:"toolName"`
	Result     ToolResult `json:"result"`
	IsError    bool       `json:"isError"`
}

ToolExecutionEndEvent carries the final tool result and its error status.

func (ToolExecutionEndEvent) EventType

func (ToolExecutionEndEvent) EventType() EventType

type ToolExecutionMode

type ToolExecutionMode string

ToolExecutionMode selects how a custom tool is scheduled relative to other tool calls in the same batch.

const (
	// ToolExecutionParallel allows the tool to run concurrently with peers.
	ToolExecutionParallel ToolExecutionMode = "parallel"
	// ToolExecutionSequential forces the containing tool batch to run serially.
	ToolExecutionSequential ToolExecutionMode = "sequential"
)

type ToolExecutionStartEvent

type ToolExecutionStartEvent struct {
	ToolCallID string          `json:"toolCallId"`
	ToolName   string          `json:"toolName"`
	Arguments  json.RawMessage `json:"arguments"`
}

ToolExecutionStartEvent is emitted immediately before a tool invocation.

func (ToolExecutionStartEvent) EventType

func (ToolExecutionStartEvent) EventType() EventType

type ToolExecutionUpdateEvent

type ToolExecutionUpdateEvent struct {
	ToolCallID string     `json:"toolCallId"`
	ToolName   string     `json:"toolName"`
	Result     ToolResult `json:"result"`
}

ToolExecutionUpdateEvent carries a partial tool result published while a tool runs. The executor offers this channel to built-in tools as well as custom ones, so the event may fire for any tool that streams partials.

func (ToolExecutionUpdateEvent) EventType

func (ToolExecutionUpdateEvent) EventType() EventType

type ToolResult

type ToolResult struct {
	Content   []ToolResultContent `json:"content"`
	Details   any                 `json:"details,omitempty"`
	Terminate *bool               `json:"terminate,omitempty"`
}

ToolResult is the result of a custom tool invocation. Details is application metadata and Terminate requests early agent-loop termination when true. For built-in tools surfaced through the event types, Details is tool-specific metadata whose shape may change without notice.

type ToolResultContent

type ToolResultContent struct {
	Type     ToolResultContentType `json:"type"`
	Text     string                `json:"text,omitempty"`
	Data     string                `json:"data,omitempty"`
	MIMEType string                `json:"mimeType,omitempty"`
}

ToolResultContent is one text or image block returned by a custom tool.

type ToolResultContentType

type ToolResultContentType string

ToolResultContentType identifies one supported custom-tool result block.

const (
	ToolResultContentText  ToolResultContentType = "text"
	ToolResultContentImage ToolResultContentType = "image"
)

type Usage

type Usage struct {
	InputTokens  int `json:"inputTokens"`
	OutputTokens int `json:"outputTokens"`
}

Usage is provider-reported token accounting for one assistant message.

type UsageEvent

type UsageEvent struct {
	Usage Usage `json:"usage"`
}

UsageEvent carries token accounting for one completed assistant message.

func (UsageEvent) EventType

func (UsageEvent) EventType() EventType

Jump to

Keyboard shortcuts

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