Documentation
¶
Overview ¶
Package mycode implements a multi-turn tool-calling agent runtime with built-in provider adapters, tools, messages, attachments, and sessions.
Index ¶
- Constants
- func FlattenText(msg Message, includeThinking bool) string
- func InferProviderFromModel(model string) (string, bool)
- func ResolvePath(path, cwd string) string
- func ValidateMediaSupport(msg Message, supportsImage, supportsPDF bool) error
- type AfterToolHook
- type Agent
- type Attachment
- type BeforeToolHook
- type Block
- func Build(items []Attachment, cwd string) ([]Block, error)
- func DocumentBlock(data, mimeType, name string, meta map[string]any) Block
- func ImageBlock(data, mimeType, name string, meta map[string]any) Block
- func TextBlock(text string, meta map[string]any) Block
- func ThinkingBlock(text string, meta map[string]any) Block
- func ToolResultBlock(toolUseID, output string, metadata map[string]any, isError bool, ...) Block
- func ToolUseBlock(id, name string, input, meta map[string]any) Block
- type Call
- type Config
- type Event
- type Hooks
- type Message
- func AssistantMessage(blocks []Block, provider, model, providerMessageID, stopReason string, ...) Message
- func BuildMessage(role string, blocks []Block, meta map[string]any) Message
- func Clone(msg Message) Message
- func CloneMessages(msgs []Message) []Message
- func UserTextMessage(text string, meta map[string]any) Message
- type ModelMetadata
- type ModelOverride
- type Option
- type Provider
- type Result
- type SessionData
- type SessionMeta
- type SessionStore
- func (s *SessionStore) AppendMessage(sessionID string, msg Message, cwd string) error
- func (s *SessionStore) AppendRewind(sessionID string, rewindTo int) error
- func (s *SessionStore) ClearSession(sessionID string) error
- func (s *SessionStore) CreateSession(sessionID, cwd string) (SessionData, error)
- func (s *SessionStore) DeleteSession(sessionID string) error
- func (s *SessionStore) DraftSession(cwd string) SessionData
- func (s *SessionStore) LatestSession(cwd string) (*SessionSummary, error)
- func (s *SessionStore) ListSessions(cwd string) ([]SessionSummary, error)
- func (s *SessionStore) LoadSession(sessionID string) (*SessionData, error)
- func (s *SessionStore) MessagesPath(sessionID string) string
- func (s *SessionStore) SessionDir(sessionID string) string
- func (s *SessionStore) SessionExists(sessionID string) bool
- type SessionSummary
- type Tool
- type ToolCall
Constants ¶
const (
DefaultSessionTitle = "New chat"
)
Variables ¶
This section is empty.
Functions ¶
func FlattenText ¶
FlattenText returns plain text. Skips attachment blocks (large embedded payloads). Includes thinking blocks only when asked.
func InferProviderFromModel ¶
InferProviderFromModel returns the built-in provider id for a known model id. A leading "vendor/" prefix is dropped before matching, so both "claude-..." and "anthropic/claude-..." resolve to "anthropic".
func ResolvePath ¶
ResolvePath resolves path relative to cwd, expanding "~" and resolving symlinks in existing path components.
func ValidateMediaSupport ¶
ValidateMediaSupport rejects user input that includes image or document blocks the active model cannot consume.
Types ¶
type AfterToolHook ¶
BeforeToolHook runs before a tool executes; returning true short-circuits execution with the given result. AfterToolHook runs after execution; returning true replaces the result.
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent is the single orchestration loop. Construct via New.
func (*Agent) Cancel ¶
func (a *Agent) Cancel()
Cancel stops active tools. Provider cancellation is driven by ctx.
func (*Agent) Chat ¶
Chat runs one user turn from a prompt string, optionally with attachments resolved against the agent's CWD. It is the convenient entry point; use ChatMessage to pass a fully built message (e.g. multi-modal content).
func (*Agent) ChatMessage ¶
ChatMessage runs one user turn from a fully built user message. The turn loops provider → tool calls → provider until the assistant stops calling tools. Breaking out of the iteration stops the loop at the next phase boundary; cancel ctx to interrupt a provider stream or running tool.
type Attachment ¶
type Attachment struct {
// contains filtered or unexported fields
}
Attachment is one pending input item; convert to message blocks with Build. Construct with Path, PathWithName, Bytes, or Text.
func Bytes ¶
func Bytes(data []byte, mediaType, name string) Attachment
Bytes attaches raw image/* or application/pdf data without touching disk.
func Path ¶
func Path(path string) Attachment
Path attaches the file at path: images and PDFs become media blocks, UTF-8 text becomes a <file> text block. Relative paths resolve against Build's cwd.
func PathWithName ¶
func PathWithName(path, name string) Attachment
PathWithName is Path with an explicit display name instead of the basename.
func Text ¶
func Text(text, name string) Attachment
Text attaches an inline snippet as a named <file> text block.
type BeforeToolHook ¶
BeforeToolHook runs before a tool executes; returning true short-circuits execution with the given result. AfterToolHook runs after execution; returning true replaces the result.
type Block ¶
type Block struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
Data string `json:"data,omitempty"`
MIMEType string `json:"mime_type,omitempty"`
Name string `json:"name,omitempty"`
ID string `json:"id,omitempty"`
Input map[string]any `json:"input,omitempty"`
ToolUseID string `json:"tool_use_id,omitempty"`
Output string `json:"output,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
IsError *bool `json:"is_error,omitempty"`
Content []Block `json:"content,omitempty"`
Meta map[string]any `json:"meta,omitempty"`
}
Block is one canonical content block. Persisted in sessions and used in API responses; provider adapters translate it to/from native shapes.
func Build ¶
func Build(items []Attachment, cwd string) ([]Block, error)
Build converts attachments to message blocks in order, resolving relative paths against cwd.
func ToolResultBlock ¶
type Call ¶
Call carries the decoded, typed input for a tool defined with Define, plus the runtime handles the handler may need. Emit is only meaningful for tools created with WithStreaming.
type Config ¶
type Config struct {
// Provider
Model string
Provider string // optional; inferred from Model when empty
APIKey string
APIBase string
// Runtime
CWD string
System string
Tools []Tool
Hooks Hooks
MaxTurns int
Temperature *float64
ReasoningEffort string
CompactThreshold float64 // fraction of the context window that triggers compaction; 0 (default) disables it
// Model capabilities. Nil resolves from the bundled catalog (falling back
// to 16384 output tokens / 128000 context); set to use exactly these values.
Metadata *ModelMetadata
// Session persistence (optional)
Store *SessionStore // nil keeps the run in memory
SessionID string // empty generates a random id
Messages []Message // explicit history; nil auto-resumes from Store; rejected when SessionID already exists
}
Config describes one agent runtime.
type Hooks ¶
type Hooks struct {
BeforeTool []BeforeToolHook
AfterTool []AfterToolHook
}
Hooks intercept tool execution; each slice runs in order.
type Message ¶
type Message struct {
Role string `json:"role"`
Content []Block `json:"content,omitempty"`
Meta map[string]any `json:"meta,omitempty"`
}
Message is the single runtime and persistence message format.
func AssistantMessage ¶
func AssistantMessage(blocks []Block, provider, model, providerMessageID, stopReason string, totalTokens int, nativeMeta map[string]any) Message
AssistantMessage normalizes provider response data into the canonical assistant message shape, dropping zero-valued meta keys.
func CloneMessages ¶
type ModelMetadata ¶
type ModelMetadata struct {
ContextWindow int `json:"context_window"`
MaxOutputTokens int `json:"max_output_tokens"`
SupportsReasoning bool `json:"supports_reasoning"`
SupportsImageInput bool `json:"supports_image_input"`
SupportsPDFInput bool `json:"supports_pdf_input"`
}
ModelMetadata is the resolved capability set for a model. Fields the catalog does not specify stay at their zero value.
func ResolveModel ¶
func ResolveModel(providerType, model string, ov ModelOverride) ModelMetadata
ResolveModel returns catalog metadata for (providerType, model) with non-zero override fields layered on top. Unknown values stay at zero; callers apply their own defaults.
type ModelOverride ¶
type ModelOverride struct {
ContextWindow int
MaxOutputTokens int
SupportsReasoning *bool
SupportsImageInput *bool
SupportsPDFInput *bool
}
ModelOverride carries optional per-model overrides layered on top of the bundled catalog. A zero int or nil pointer means "not overridden".
type Option ¶
type Option func(*Tool)
Option configures a Tool built by Define.
func WithStreaming ¶
func WithStreaming() Option
WithStreaming marks a tool as emitting incremental output via Call.Emit.
type Provider ¶
type Provider struct {
ID string
Label string
DefaultBaseURL string
EnvAPIKeyNames []string
DefaultModels []string
SupportsReasoningEffort bool
AutoDiscoverable bool
}
Provider is the static metadata for one built-in provider type.
func LookupProvider ¶
LookupProvider returns one built-in provider spec.
type Result ¶
type Result struct {
Output string `json:"output"`
Content []Block `json:"content,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
IsError bool `json:"is_error"`
}
Result is the canonical tool result. Output is provider-facing text; Content carries optional structured blocks (e.g. inline images); Metadata carries optional structured info for the UI (e.g. edit patches).
type SessionData ¶
type SessionData struct {
Session SessionSummary `json:"session"`
Messages []Message `json:"messages"`
}
type SessionMeta ¶
type SessionMeta struct {
CWD string `json:"cwd"`
Title string `json:"title"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
SessionMeta is the JSON saved in meta.json.
type SessionStore ¶
type SessionStore struct {
// contains filtered or unexported fields
}
SessionStore keeps a per-session mutex so concurrent operations on the same session can't interleave, while different sessions remain concurrent.
func NewSessionStore ¶
func NewSessionStore(dataDir string) (*SessionStore, error)
func (*SessionStore) AppendMessage ¶
func (s *SessionStore) AppendMessage(sessionID string, msg Message, cwd string) error
AppendMessage appends one message and refreshes meta. The first non-empty user turn becomes the session title (truncated to 48 runes).
func (*SessionStore) AppendRewind ¶
func (s *SessionStore) AppendRewind(sessionID string, rewindTo int) error
func (*SessionStore) ClearSession ¶
func (s *SessionStore) ClearSession(sessionID string) error
ClearSession resets messages but keeps meta so the session id stays addressable.
func (*SessionStore) CreateSession ¶
func (s *SessionStore) CreateSession(sessionID, cwd string) (SessionData, error)
func (*SessionStore) DeleteSession ¶
func (s *SessionStore) DeleteSession(sessionID string) error
func (*SessionStore) DraftSession ¶
func (s *SessionStore) DraftSession(cwd string) SessionData
DraftSession returns an in-memory session that has not been written to disk.
func (*SessionStore) LatestSession ¶
func (s *SessionStore) LatestSession(cwd string) (*SessionSummary, error)
func (*SessionStore) ListSessions ¶
func (s *SessionStore) ListSessions(cwd string) ([]SessionSummary, error)
ListSessions returns sessions (filtered by cwd when non-empty), sorted by updated_at desc.
func (*SessionStore) LoadSession ¶
func (s *SessionStore) LoadSession(sessionID string) (*SessionData, error)
LoadSession returns the visible (post-rewind) history. `compact` markers stay inline; the agent substitutes them when calling the provider. Orphan tool_use blocks are closed by the provider adapter at replay time.
func (*SessionStore) MessagesPath ¶
func (s *SessionStore) MessagesPath(sessionID string) string
MessagesPath returns the JSONL transcript path for a session.
func (*SessionStore) SessionDir ¶
func (s *SessionStore) SessionDir(sessionID string) string
func (*SessionStore) SessionExists ¶
func (s *SessionStore) SessionExists(sessionID string) bool
type SessionSummary ¶
type SessionSummary struct {
ID string `json:"id"`
SessionMeta
}
type Tool ¶
type Tool struct {
Name string
Description string
InputSchema map[string]any
StreamsOutput bool
Runner func(context.Context, ToolCall) Result
}
Tool is the provider-facing tool definition plus its runner. Build custom tools with Define or use ReadTool, WriteTool, EditTool, and BashTool.
func Define ¶
func Define[T any](name, description string, run func(context.Context, Call[T]) Result, opts ...Option) Tool
Define builds a Tool from a typed handler. The provider input schema is reflected from T; at call time the raw input map is decoded into T before run is invoked. It is the single entry point for custom tools.