mycode

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2026 License: MIT Imports: 35 Imported by: 0

Documentation

Overview

Package mycode implements a multi-turn tool-calling agent runtime with built-in provider adapters, tools, messages, attachments, and sessions.

Index

Constants

View Source
const (
	DefaultSessionTitle = "New chat"
)

Variables

This section is empty.

Functions

func FlattenText

func FlattenText(msg Message, includeThinking bool) string

FlattenText returns plain text. Skips attachment blocks (large embedded payloads). Includes thinking blocks only when asked.

func InferProviderFromModel

func InferProviderFromModel(model string) (string, bool)

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

func ResolvePath(path, cwd string) string

ResolvePath resolves path relative to cwd, expanding "~" and resolving symlinks in existing path components.

func ValidateMediaSupport

func ValidateMediaSupport(msg Message, supportsImage, supportsPDF bool) error

ValidateMediaSupport rejects user input that includes image or document blocks the active model cannot consume.

Types

type AfterToolHook

type AfterToolHook func(context.Context, ToolCall, Result) (Result, bool)

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 New

func New(cfg Config) (*Agent, error)

New fills defaults and returns a runnable Agent.

func (*Agent) Cancel

func (a *Agent) Cancel()

Cancel stops active tools. Provider cancellation is driven by ctx.

func (*Agent) Chat

func (a *Agent) Chat(ctx context.Context, prompt string, attachments ...Attachment) iter.Seq[Event]

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

func (a *Agent) ChatMessage(ctx context.Context, userInput Message) iter.Seq[Event]

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.

func (*Agent) Messages

func (a *Agent) Messages() []Message

Messages returns a copy of the conversation history accumulated so far.

func (*Agent) SessionID

func (a *Agent) SessionID() string

SessionID returns the session id, generated when Config left it empty.

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

type BeforeToolHook func(context.Context, ToolCall) (Result, bool)

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 DocumentBlock

func DocumentBlock(data, mimeType, name string, meta map[string]any) Block

func ImageBlock

func ImageBlock(data, mimeType, name string, meta map[string]any) Block

func TextBlock

func TextBlock(text string, meta map[string]any) Block

func ThinkingBlock

func ThinkingBlock(text string, meta map[string]any) Block

func ToolResultBlock

func ToolResultBlock(toolUseID, output string, metadata map[string]any, isError bool, content []Block, meta map[string]any) Block

func ToolUseBlock

func ToolUseBlock(id, name string, input, meta map[string]any) Block

ToolUseBlock keeps empty input as {} so persisted tool_use blocks have a stable shape across runtimes.

type Call

type Call[T any] struct {
	ID    string
	Input T
	CWD   string
	Emit  func(string)
}

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 Event

type Event struct {
	Type string
	Data map[string]any
}

Event is one normalized streaming event sent to the API and CLI.

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 BuildMessage

func BuildMessage(role string, blocks []Block, meta map[string]any) Message

func Clone

func Clone(msg Message) Message

func CloneMessages

func CloneMessages(msgs []Message) []Message

func UserTextMessage

func UserTextMessage(text string, meta map[string]any) Message

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

func LookupProvider(id string) (Provider, bool)

LookupProvider returns one built-in provider spec.

func Providers

func Providers() []Provider

Providers returns all built-in provider specs.

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 BashTool

func BashTool() Tool

BashTool returns the built-in shell execution tool.

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.

func EditTool

func EditTool() Tool

EditTool returns the built-in file editing tool.

func ReadTool

func ReadTool() Tool

ReadTool returns the built-in file reading tool.

func WriteTool

func WriteTool() Tool

WriteTool returns the built-in file writing tool.

type ToolCall

type ToolCall struct {
	ID    string
	Name  string
	Input map[string]any
	CWD   string
	Emit  func(string)
	// contains filtered or unexported fields
}

ToolCall is the raw invocation a Tool runner receives: the provider-supplied input map plus the run's working directory and streaming callback.

Jump to

Keyboard shortcuts

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