### Tool Interface and Custom Tool Implementation Source: https://context7.com/projectbarks/gopher-code/llms.txt Defines the Tool interface and ToolContext, with an example of implementing and registering a custom tool. ```go package tools import ( "context" "encoding/json" ) // Tool is the interface every built-in or plugin tool must implement. type Tool interface { Name() string Description() string InputSchema() json.RawMessage Execute(ctx context.Context, tc *ToolContext, input json.RawMessage) (*ToolOutput, error) IsReadOnly() bool } // ToolOutput represents the result of executing a tool. type ToolOutput struct { Content string `json:"content"` IsError bool `json:"is_error"` Metadata json.RawMessage `json:"metadata,omitempty"` Display any `json:"-"` // UI-only structured payload } // ToolContext provides execution context to tools type ToolContext struct { CWD string Permissions PermissionPolicy SessionID string ProjectDir string SandboxEnabled bool PlanMode bool Hooks HookRunner ReadFileState *ReadFileState } // Example: Implementing a custom tool type MyTool struct{} func (t *MyTool) Name() string { return "MyTool" } func (t *MyTool) Description() string { return "Does something useful" } func (t *MyTool) IsReadOnly() bool { return true } func (t *MyTool) InputSchema() json.RawMessage { return json.RawMessage(`{ "type": "object", "properties": { "input": {"type": "string", "description": "The input value"} }, "required": ["input"] }`) } func (t *MyTool) Execute(ctx context.Context, tc *ToolContext, input json.RawMessage) (*ToolOutput, error) { var in struct { Input string `json:"input"` } if err := json.Unmarshal(input, &in); err != nil { return ErrorOutput(fmt.Sprintf("invalid input: %s", err)), nil } return SuccessOutput(fmt.Sprintf("Processed: %s", in.Input)), nil } // Register the tool registry := tools.NewRegistry() registry.Register(&MyTool{}) // Get all tool definitions for API request defs := registry.ToolDefinitions() // Returns []provider.ToolDefinition ``` -------------------------------- ### Query Engine Interface and Event Handling Source: https://context7.com/projectbarks/gopher-code/llms.txt Defines the Query function signature and event types for managing agent lifecycle, along with an example of executing a query with a callback. ```go package query import ( "context" "github.com/projectbarks/gopher-code/pkg/provider" "github.com/projectbarks/gopher-code/pkg/session" "github.com/projectbarks/gopher-code/pkg/tools" ) // Query is the recursive agent loop — the beating heart of the runtime. // It builds model requests, streams responses, executes tools, and loops. func Query( ctx context.Context, sess *session.SessionState, prov provider.ModelProvider, registry *tools.ToolRegistry, orchestrator *tools.ToolOrchestrator, onEvent EventCallback, ) error // EventCallback receives query lifecycle events type EventCallback func(QueryEvent) // QueryEvent types for callback handling const ( QEventTextDelta = "text_delta" // Streaming text from assistant QEventToolUseStart = "tool_use_start" // Tool execution beginning QEventToolResult = "tool_result" // Tool execution completed QEventUsage = "usage" // Token usage update QEventTurnComplete = "turn_complete" // Model turn finished ) // Example: Running a query with event handling sess.PushMessage(message.UserMessage("List all Go files in the current directory")) err := query.Query(ctx, sess, prov, registry, orchestrator, func(evt query.QueryEvent) { switch evt.Type { case query.QEventTextDelta: fmt.Print(evt.Text) // Stream text to stdout case query.QEventToolUseStart: fmt.Printf("\n[Executing: %s]\n", evt.ToolName) case query.QEventToolResult: if evt.IsError { fmt.Printf("[Tool error: %s]\n", evt.Content) } case query.QEventUsage: fmt.Printf("\n[Tokens: %d in, %d out]\n", evt.InputTokens, evt.OutputTokens) } }) ``` -------------------------------- ### Initialize project Source: https://context7.com/projectbarks/gopher-code/llms.txt Set up a new project configuration. ```bash gopher-code --init ``` -------------------------------- ### Initialize and Run Gopher Code CLI Source: https://context7.com/projectbarks/gopher-code/llms.txt Demonstrates the main entry point for initializing the Anthropic provider, tool registry, session, and executing the query loop. ```go package main import ( "context" "github.com/projectbarks/gopher-code/pkg/auth" "github.com/projectbarks/gopher-code/pkg/provider" "github.com/projectbarks/gopher-code/pkg/query" "github.com/projectbarks/gopher-code/pkg/session" "github.com/projectbarks/gopher-code/pkg/tools" ) func main() { // Get API key from environment or keyring apiKey, err := auth.GetAPIKey() if err != nil { panic(err) } // Create Anthropic provider prov := provider.NewAnthropicProvider(apiKey, "claude-sonnet-4-20250514") // Create tool registry with 33 built-in tools registry := tools.NewRegistry() tools.RegisterDefaults(registry) // Create session with default config cwd := "/path/to/project" cfg := session.DefaultConfig() sess := session.New(cfg, cwd) // Run the query loop orchestrator := tools.NewOrchestrator(registry) ctx := context.Background() err = query.Query(ctx, sess, prov, registry, orchestrator, func(evt query.QueryEvent) { switch evt.Type { case query.QEventTextDelta: fmt.Print(evt.Text) case query.QEventToolUseStart: fmt.Printf("Running tool: %s\n", evt.ToolName) } }) } ``` -------------------------------- ### Gopher Code CLI Entry Point Source: https://context7.com/projectbarks/gopher-code/llms.txt Demonstrates the main entry point for the Gopher Code CLI, including setting up the Anthropic provider, tool registry, and session, then initiating the query loop. ```APIDOC ## CLI Entry Point The main entry point provides a full-featured command-line interface with support for interactive REPL mode, headless mode, session management, and various configuration options. ### Code Example ```go package main import ( "context" "fmt" "github.com/projectbarks/gopher-code/pkg/auth" "github.com/projectbarks/gopher-code/pkg/provider" "github.com/projectbarks/gopher-code/pkg/query" "github.com/projectbarks/gopher-code/pkg/session" "github.com/projectbarks/gopher-code/pkg/tools" ) func main() { // Get API key from environment or keyring apiKey, err := auth.GetAPIKey() if err != nil { panic(err) } // Create Anthropic provider prov := provider.NewAnthropicProvider(apiKey, "claude-sonnet-4-20250514") // Create tool registry with 33 built-in tools registry := tools.NewRegistry() tools.RegisterDefaults(registry) // Create session with default config cwd := "/path/to/project" cfg := session.DefaultConfig() sess := session.New(cfg, cwd) // Run the query loop orchestrator := tools.NewOrchestrator(registry) ctx := context.Background() err = query.Query(ctx, sess, prov, registry, orchestrator, func(evt query.QueryEvent) { switch evt.Type { case query.QEventTextDelta: fmt.Print(evt.Text) case query.QEventToolUseStart: fmt.Printf("Running tool: %s\n", evt.ToolName) } }) if err != nil { panic(err) } } ``` ``` -------------------------------- ### Execute subcommands Source: https://context7.com/projectbarks/gopher-code/llms.txt Manage authentication, MCP servers, plugins, and system health. ```bash gopher-code auth login gopher-code mcp list gopher-code mcp add gopher-code plugin list gopher-code update gopher-code doctor ``` -------------------------------- ### Manage MCP Server Connections Source: https://context7.com/projectbarks/gopher-code/llms.txt Handles loading MCP configurations and registering external tools. ```go package mcp // Manager handles MCP server connections type Manager struct{} // ServerConfig defines an MCP server type ServerConfig struct { Command string Args []string Env map[string]string Headers map[string]string } // Example: Loading and connecting to MCP servers mcpMgr := mcp.NewManager() mcpCfg, _ := mcp.LoadConfig() // From .claude/settings.json for name, serverCfg := range mcpCfg.Servers { if err := mcpMgr.Connect(ctx, name, serverCfg); err != nil { log.Printf("MCP server %s failed: %v", name, err) continue } } // Register MCP tools with the registry mcpMgr.RegisterTools(ctx, registry) defer mcpMgr.CloseAll() // CLI: Add MCP server // gopher-code mcp add myserver npx -y @mcp/server -e API_KEY=xxx ``` -------------------------------- ### CLI Usage and Flags Source: https://github.com/projectbarks/gopher-code/blob/main/README.md Reference for available command-line flags and their usage patterns. ```text Usage: gopher-code [flags] Flags: -p, --print string Run a single query in headless mode -m, --model string Model to use (default: claude-sonnet-4-20250514) -c, --cwd string Working directory -r, --resume string Resume a previous session by ID -o, --output string Output format: text, json, stream-json -v, --verbose Enable verbose logging ``` -------------------------------- ### Build and Check Waterfall Permission Policy in Go Source: https://context7.com/projectbarks/gopher-code/llms.txt Demonstrates how to build a waterfall permission policy using deny and allow rules loaded from a persister. The policy is then used to check if a specific tool is allowed to execute, with different outcomes based on the decision. ```go package permissions import "context" // PermissionMode defines the permission checking behavior type PermissionMode string const ( ModeDefault PermissionMode = "default" ModeAcceptEdits PermissionMode = "acceptEdits" ModeBypassPermissions PermissionMode = "bypassPermissions" ModeDontAsk PermissionMode = "dontAsk" ModePlan PermissionMode = "plan" ModeAuto PermissionMode = "auto" ) // PermissionPolicy checks whether a tool is allowed to execute type PermissionPolicy interface { Check(ctx context.Context, toolName string, toolID string) PermissionDecision } // PermissionDecision is a sealed interface for permission check results type PermissionDecision interface { isPermissionDecision() } type AllowDecision struct{} type DenyDecision struct{ Reason string } type AskDecision struct{ Message string } // Example: Building a permission policy homeDir, _ := os.UserHomeDir() persister := permissions.NewPermissionRulePersister(homeDir, cwd) toolPermCtx := persister.LoadPermissionContext(string(permissions.ModeDefault)) // Parse rules from settings denyRules := parseRules(toolPermCtx.AllDenyRules()) allowRules := parseRules(toolPermCtx.AllAllowRules()) // Create waterfall policy policy := permissions.NewWaterfallPolicy( permissions.ModeDefault, denyRules, allowRules, nil, // ask rules false, // isBypassAvailable ) // Check permission for a tool decision := policy.Check(ctx, "Bash", "tool_123") switch d := decision.(type) { case permissions.AllowDecision: // Tool allowed, proceed case permissions.DenyDecision: fmt.Printf("Denied: %s\n", d.Reason) case permissions.AskDecision: // Prompt user for approval fmt.Printf("Approval needed: %s\n", d.Message) } ``` -------------------------------- ### Implement and Use ModelProvider Interface Source: https://context7.com/projectbarks/gopher-code/llms.txt Defines the contract for LLM backends and demonstrates how to configure and stream requests using the Anthropic provider. ```go package provider import "context" // ModelProvider is the interface every LLM backend must implement. type ModelProvider interface { // Stream sends a request and returns a channel of StreamResults. // The channel is closed when the stream ends. Stream(ctx context.Context, req ModelRequest) (<-chan StreamResult, error) // Name returns a human-readable provider name. Name() string } // ModelRequest contains all parameters for an API call type ModelRequest struct { Model string System string Messages []RequestMessage MaxTokens int Tools []ToolDefinition Temperature *float64 Thinking *ThinkingConfig JSONSchema json.RawMessage } // StreamResult wraps either a stream event or an error type StreamResult struct { Event *StreamEvent Err error } // Example: Creating and using an Anthropic provider prov := provider.NewAnthropicProvider(apiKey, "claude-sonnet-4-20250514") prov.SetBaseURL("https://api.anthropic.com") // Optional custom endpoint prov.SetExtraHeaders(map[string]string{ "x-anthropic-billing-header": "billing-attribution-value", }) // Stream a request ch, err := prov.Stream(ctx, ModelRequest{ Model: "claude-sonnet-4-20250514", System: "You are a helpful assistant.", Messages: []RequestMessage{{Role: "user", Content: []RequestContent{{Type: "text", Text: "Hello"}}}}, MaxTokens: 4096, }) if err != nil { log.Fatal(err) } for result := range ch { if result.Err != nil { log.Printf("Stream error: %v", result.Err) continue } switch result.Event.Type { case EventTextDelta: fmt.Print(result.Event.Text) case EventMessageDone: fmt.Printf("\nUsage: %d input, %d output tokens\n", result.Event.Response.Usage.InputTokens, result.Event.Response.Usage.OutputTokens) } } ``` -------------------------------- ### Manage Token Budgets and Compaction Source: https://context7.com/projectbarks/gopher-code/llms.txt Defines the TokenBudget structure and demonstrates how to check thresholds and perform message compaction. ```go package compact // TokenBudget manages the context window budget for the agent loop type TokenBudget struct { ContextWindow int MaxOutputTokens int CompactThreshold float64 // e.g. 0.8 } // DefaultBudget returns a sensible default budget func DefaultBudget() TokenBudget { return TokenBudget{ ContextWindow: 200000, MaxOutputTokens: 16000, CompactThreshold: 0.8, } } // InputBudget returns the max tokens available for input func (b TokenBudget) InputBudget() int { return b.ContextWindow - b.MaxOutputTokens } // ShouldCompact returns true if current token count exceeds threshold func (b TokenBudget) ShouldCompact(currentTokens int) bool { return float64(currentTokens) > float64(b.InputBudget())*b.CompactThreshold } // Example: Using token budget in query loop budget := compact.DefaultBudget() if budget.ShouldCompact(sess.LastInputTokens) { query.CompactSession(sess) } // MicroCompactMessages truncates large tool results compacted, savedTokens := compact.MicroCompactMessages(sess.Messages, 2) // keep 2 recent if savedTokens > 0 { sess.Messages = compacted } // TruncateHeadForPTLRetry removes oldest messages truncated := compact.TruncateHeadForPTLRetry(msgs, 0.2) // drop 20% ``` -------------------------------- ### Execute Bash Tool Source: https://context7.com/projectbarks/gopher-code/llms.txt Executes shell commands with security validation and sandboxing. ```go package tools // BashTool executes shell commands with security validation and sandboxing type BashTool struct{} // Input schema // { // "command": "string (required)", // "description": "string (optional)", // "timeout": "integer (optional, default 120000ms, max 600000ms)", // "run_in_background": "boolean (optional)", // "dangerouslyDisableSandbox": "boolean (optional)" // } // Example: Bash tool execution input := json.RawMessage(`{ "command": "git status", "description": "Check git repository status", "timeout": 30000 }`) bash := &tools.BashTool{} output, err := bash.Execute(ctx, toolCtx, input) // output.Content: "On branch main\nnothing to commit, working tree clean" ``` -------------------------------- ### Configure output formats Source: https://context7.com/projectbarks/gopher-code/llms.txt Set the output format to JSON or stream-json for programmatic consumption. ```bash gopher-code -p "query" --output-format json gopher-code -p "query" --output-format stream-json ``` -------------------------------- ### Load CLAUDE.md Configuration Source: https://context7.com/projectbarks/gopher-code/llms.txt Utility to load and concatenate CLAUDE.md files from global and project-specific paths. ```go // LoadClaudeMDPublic loads CLAUDE.md files from the project hierarchy memory := query.LoadClaudeMDPublic("/path/to/project") // Returns concatenated content from: // 1. ~/.claude/CLAUDE.md (global) // 2. Walk up from CWD for CLAUDE.md (up to 10 levels) // 3. .claude/CLAUDE.md in CWD ``` -------------------------------- ### Manage Conversation State with Session Source: https://context7.com/projectbarks/gopher-code/llms.txt Use the session package to manage conversation state, including messages, token usage, cost tracking, and configuration. Sessions can be persisted and resumed. ```go package session import ( "time" "github.com/projectbarks/gopher-code/pkg/compact" "github.com/projectbarks/gopher-code/pkg/message" "github.com/projectbarks/gopher-code/pkg/permissions" ) // SessionConfig holds configuration for a session type SessionConfig struct { Model string SystemPrompt string MaxTurns int TokenBudget compact.TokenBudget PermissionMode permissions.PermissionMode ThinkingEnabled bool ThinkingBudget int JSONSchema string MaxBudgetUSD float64 FallbackModel string } // SessionState holds the mutable state of a conversation session type SessionState struct { ID string Config SessionConfig Messages []message.Message CWD string TurnCount int TotalInputTokens int TotalOutputTokens int TotalCostUSD float64 CreatedAt time.Time // ... many more fields for tracking state } // DefaultConfig returns sensible defaults func DefaultConfig() SessionConfig { return SessionConfig{ Model: "claude-sonnet-4-20250514", MaxTurns: 100, TokenBudget: compact.DefaultBudget(), PermissionMode: permissions.AutoApprove, } } ``` ```go // Example: Creating and using a session cfg := session.DefaultConfig() cfg.Model = "claude-sonnet-4-20250514" cfg.ThinkingEnabled = true cfg.ThinkingBudget = 16000 sess := session.New(cfg, "/path/to/project") // Add a user message sess.PushMessage(message.UserMessage("Explain this codebase")) // Track costs sess.AddCost("claude-sonnet-4-20250514", 0.015, provider.TokenUsage{ InputTokens: 1000, OutputTokens: 500, }) fmt.Printf("Session %s: %d turns, $%.4f total cost\n", sess.ID, sess.TurnCount, sess.TotalCostUSD) // Convert messages to API format apiMsgs := sess.ToRequestMessages() // Session persistence session.Save(sess) loaded, err := session.Load(sess.ID) latest, err := session.LoadLatest("/path/to/project") // Resume most recent ``` -------------------------------- ### Create and Normalize Messages in Go Source: https://context7.com/projectbarks/gopher-code/llms.txt Provides helper functions to create user, text, tool use, and tool result blocks, and a function to normalize messages for API compatibility. Normalization handles edge cases and consecutive messages from the same role. ```go // Example: Creating messages userMsg := message.UserMessage("Hello, Claude!") assistantMsg := message.Message{ Role: message.RoleAssistant, Content: []message.ContentBlock{ message.TextBlock("I'll help you with that."), message.ToolUseBlock("tool_123", "Read", json.RawMessage(`{"file_path": "main.go"}`)), }, } toolResultMsg := message.Message{ Role: message.RoleUser, Content: []message.ContentBlock{ message.ToolResultBlock("tool_123", "package main\n\nfunc main() {...}", false), }, } // Normalize messages for API (handles edge cases, smooshes consecutive same-role messages) normalized := message.NormalizeForAPI([]message.Message{userMsg, assistantMsg, toolResultMsg}) ``` -------------------------------- ### Build and Run Gopher Code Source: https://github.com/projectbarks/gopher-code/blob/main/README.md Commands to clone, build, and execute the Gopher CLI in interactive or headless modes, including cross-compilation instructions. ```bash # Clone git clone https://github.com/projectbarks/gopher.git cd gopher # Build go build -o gopher ./cmd/gopher # Run interactive REPL ./gopher # Run headless ./gopher -p "explain this codebase" # Cross-compile for Linux ARM64 GOOS=linux GOARCH=arm64 go build -o gopher-linux-arm64 ./cmd/gopher ``` -------------------------------- ### Run CLI Commands Source: https://context7.com/projectbarks/gopher-code/llms.txt Common CLI commands for interacting with Gopher Code. ```bash # Run interactive REPL gopher-code # Run headless query gopher-code -p "explain this codebase" ``` -------------------------------- ### Execute with model selection Source: https://context7.com/projectbarks/gopher-code/llms.txt Specify a model for the coding task using the -p flag. ```bash gopher-code -p "fix the bug" --model claude-opus-4-6 ``` -------------------------------- ### Execute Read Tool Source: https://context7.com/projectbarks/gopher-code/llms.txt Reads file contents with support for line offsets and limits. ```go package tools // FileReadTool reads files with line numbers type FileReadTool struct{} // Input schema // { // "file_path": "string (required, absolute path)", // "offset": "integer (optional, 1-indexed line to start from)", // "limit": "integer (optional, number of lines to read)", // "pages": "string (optional, PDF page range like '1-5')" // } // Example: Read tool execution input := json.RawMessage(`{ "file_path": "/path/to/main.go", "limit": 50 }`) readTool := &tools.FileReadTool{} output, err := readTool.Execute(ctx, toolCtx, input) // output.Content: "1\tpackage main\n2\t\n3\timport (...)\n..." ``` -------------------------------- ### Execute Grep Tool Source: https://context7.com/projectbarks/gopher-code/llms.txt Searches file contents using ripgrep with configurable output modes. ```go package tools // GrepTool searches file contents using ripgrep type GrepTool struct{} // Input schema // { // "pattern": "string (required, regex pattern)", // "path": "string (optional)", // "glob": "string (optional, file filter like '*.go')", // "output_mode": "string (optional, 'content'|'files_with_matches'|'count')", // "-A/-B/-C": "integer (optional, context lines)" // } // Example: Search for function definitions input := json.RawMessage(`{ "pattern": "func.*Query", "glob": "*.go", "output_mode": "content", "-A": 3 }`) ``` -------------------------------- ### Execute Glob Tool Source: https://context7.com/projectbarks/gopher-code/llms.txt Finds files matching specific glob patterns within a directory. ```go package tools // GlobTool finds files matching glob patterns type GlobTool struct{} // Input schema // { // "pattern": "string (required, glob pattern like '**/*.go')", // "path": "string (optional, directory to search)" // } // Example: Find all Go test files input := json.RawMessage(`{ "pattern": "**/*_test.go", "path": "/path/to/project" }`) ``` -------------------------------- ### Enable extended thinking Source: https://context7.com/projectbarks/gopher-code/llms.txt Configure the agent's reasoning effort level. ```bash gopher-code --thinking enabled --effort high ``` -------------------------------- ### Manage sessions Source: https://context7.com/projectbarks/gopher-code/llms.txt Resume previous coding sessions using session identifiers or the continue flag. ```bash gopher-code -c # Continue most recent gopher-code -r # Resume specific session ``` -------------------------------- ### Run Go Tests Source: https://github.com/projectbarks/gopher-code/blob/main/README.md Standard commands for running tests in the Gopher Code project. Use the race detector for concurrent issues and the -update flag to refresh golden files. ```bash go test ./... ``` ```bash go test -race ./... ``` ```bash go test ./... -update ``` -------------------------------- ### Set permission modes Source: https://context7.com/projectbarks/gopher-code/llms.txt Control tool execution security by choosing between auto-approval, interactive prompts, or bypassing checks. ```bash gopher-code --permission-mode auto # Auto-approve all gopher-code --permission-mode interactive # Prompt for approval gopher-code --dangerously-skip-permissions # Bypass all checks ``` -------------------------------- ### Execute Tool Calls with Orchestrator Source: https://context7.com/projectbarks/gopher-code/llms.txt Use the ToolOrchestrator to execute batches of tool calls. Read-only tools run concurrently, while mutating tools run sequentially. Set a progress callback for real-time updates. ```go package tools // ToolOrchestrator executes batches of tool calls with concurrency management type ToolOrchestrator struct { registry *ToolRegistry hookRunner HookRunner onProgress ProgressCallback } // NewOrchestrator creates a new orchestrator backed by a registry func NewOrchestrator(registry *ToolRegistry) *ToolOrchestrator // ExecuteBatch executes a batch of tool calls // Read-only tools run concurrently; mutating tools run sequentially func (o *ToolOrchestrator) ExecuteBatch(ctx context.Context, calls []ToolCall, tc *ToolContext) []ToolCallResult // ToolCall represents a pending tool call from the model type ToolCall struct { ID string Name string Input json.RawMessage } // ToolCallResult is the result of executing a single tool call type ToolCallResult struct { ToolUseID string Output ToolOutput } ``` ```go // Example: Executing tools from model response orchestrator := tools.NewOrchestrator(registry) orchestrator.SetProgressCallback(func(toolUseID, toolName string, event ProgressEvent) { fmt.Printf("[%s] %s: %s\n", toolUseID, toolName, event.Type) }) calls := []tools.ToolCall{ {ID: "tool_1", Name: "Read", Input: json.RawMessage(`{"file_path": "/etc/hosts"}`)}, {ID: "tool_2", Name: "Glob", Input: json.RawMessage(`{"pattern": "**/*.go"}`)}, } toolCtx := &tools.ToolContext{ CWD: "/home/user/project", Permissions: permPolicy, SessionID: sess.ID, } results := orchestrator.ExecuteBatch(ctx, calls, toolCtx) for _, r := range results { if r.Output.IsError { fmt.Printf("Tool %s failed: %s\n", r.ToolUseID, r.Output.Content) } else { fmt.Printf("Tool %s result: %s\n", r.ToolUseID, r.Output.Content[:100]) } } ``` -------------------------------- ### Tool Interface and Registry Source: https://context7.com/projectbarks/gopher-code/llms.txt Defines the standard interface for tools, the structure for tool outputs and contexts, and how to register and retrieve tool definitions. ```APIDOC ## Tool Interface and Registry Tools implement a standard interface and are registered in a thread-safe registry. The orchestrator executes tools with automatic concurrency management. ### Tool Interface ```go type Tool interface { Name() string Description() string InputSchema() json.RawMessage Execute(ctx context.Context, tc *ToolContext, input json.RawMessage) (*ToolOutput, error) IsReadOnly() bool } ``` ### Tool Output Structure ```go type ToolOutput struct { Content string `json:"content"` IsError bool `json:"is_error"` Metadata json.RawMessage `json:"metadata,omitempty"` Display any `json:"-"` // UI-only structured payload } ``` ### Tool Context ```go type ToolContext struct { CWD string Permissions PermissionPolicy SessionID string ProjectDir string SandboxEnabled bool PlanMode bool Hooks HookRunner ReadFileState *ReadFileState } ``` ### Example: Implementing a Custom Tool ```go type MyTool struct{} func (t *MyTool) Name() string { return "MyTool" } func (t *MyTool) Description() string { return "Does something useful" } func (t *MyTool) IsReadOnly() bool { return true } func (t *MyTool) InputSchema() json.RawMessage { return json.RawMessage(`{ "type": "object", "properties": { "input": {"type": "string", "description": "The input value"} }, "required": ["input"] }`) } func (t *MyTool) Execute(ctx context.Context, tc *ToolContext, input json.RawMessage) (*ToolOutput, error) { var in struct { Input string `json:"input"` } if err := json.Unmarshal(input, &in); err != nil { return ErrorOutput(fmt.Sprintf("invalid input: %s", err)), nil } return SuccessOutput(fmt.Sprintf("Processed: %s", in.Input)), nil } ``` ### Registering and Retrieving Tools ```go // Register the tool registry := tools.NewRegistry() registry.Register(&MyTool{}) // Get all tool definitions for API request defs := registry.ToolDefinitions() // Returns []provider.ToolDefinition ``` ``` -------------------------------- ### ModelProvider Interface Source: https://context7.com/projectbarks/gopher-code/llms.txt Defines the contract for LLM backends, with the Anthropic provider implementing SSE streaming for real-time token delivery. ```APIDOC ## ModelProvider Interface The provider interface defines the contract for LLM backends. The Anthropic provider implements SSE streaming for real-time token delivery. ### Interface Definition ```go package provider import "context" // ModelProvider is the interface every LLM backend must implement. type ModelProvider interface { // Stream sends a request and returns a channel of StreamResults. // The channel is closed when the stream ends. Stream(ctx context.Context, req ModelRequest) (<-chan StreamResult, error) // Name returns a human-readable provider name. Name() string } // ModelRequest contains all parameters for an API call type ModelRequest struct { Model string System string Messages []RequestMessage MaxTokens int Tools []ToolDefinition Temperature *float64 Thinking *ThinkingConfig JSONSchema json.RawMessage } // StreamResult wraps either a stream event or an error type StreamResult struct { Event *StreamEvent Err error } ``` ### Anthropic Provider Usage Example ```go // Example: Creating and using an Anthropic provider prov := provider.NewAnthropicProvider(apiKey, "claude-sonnet-4-20250514") prov.SetBaseURL("https://api.anthropic.com") // Optional custom endpoint prov.SetExtraHeaders(map[string]string{ "x-anthropic-billing-header": "billing-attribution-value", }) // Stream a request ch, err := prov.Stream(ctx, ModelRequest{ Model: "claude-sonnet-4-20250514", System: "You are a helpful assistant.", Messages: []RequestMessage{{Role: "user", Content: []RequestContent{{Type: "text", Text: "Hello"}}}}, MaxTokens: 4096, }) if err != nil { log.Fatal(err) } for result := range ch { if result.Err != nil { log.Printf("Stream error: %v", result.Err) continue } switch result.Event.Type { case EventTextDelta: fmt.Print(result.Event.Text) case EventMessageDone: fmt.Printf("\nUsage: %d input, %d output tokens\n", result.Event.Response.Usage.InputTokens, result.Event.Response.Usage.OutputTokens) } } ``` ``` -------------------------------- ### Define Permission System Interfaces and Modes in Go Source: https://context7.com/projectbarks/gopher-code/llms.txt Defines the PermissionMode enum, PermissionPolicy interface, and PermissionDecision types (Allow, Deny, Ask) for the permission system. These are used to control tool execution based on defined policies. ```go package permissions import "context" // PermissionMode defines the permission checking behavior type PermissionMode string const ( ModeDefault PermissionMode = "default" ModeAcceptEdits PermissionMode = "acceptEdits" ModeBypassPermissions PermissionMode = "bypassPermissions" ModeDontAsk PermissionMode = "dontAsk" ModePlan PermissionMode = "plan" ModeAuto PermissionMode = "auto" ) // PermissionPolicy checks whether a tool is allowed to execute type PermissionPolicy interface { Check(ctx context.Context, toolName string, toolID string) PermissionDecision } // PermissionDecision is a sealed interface for permission check results type PermissionDecision interface { isPermissionDecision() } type AllowDecision struct{} type DenyDecision struct{ Reason string } type AskDecision struct{ Message string } ``` -------------------------------- ### Define Message Structure and Roles in Go Source: https://context7.com/projectbarks/gopher-code/llms.txt Defines the Role and ContentBlockType enums, and the ContentBlock and Message structs for representing conversation turns. Use these types to structure messages for the API. ```go package message import "encoding/json" // Role identifies the message sender type Role string const ( RoleUser Role = "user" RoleAssistant Role = "assistant" ) // ContentBlockType identifies the block type type ContentBlockType string const ( ContentText ContentBlockType = "text" ContentToolUse ContentBlockType = "tool_use" ContentToolResult ContentBlockType = "tool_result" ContentThinking ContentBlockType = "thinking" ) // ContentBlock is a tagged union for message content type ContentBlock struct { Type ContentBlockType `json:"type"` Text string `json:"text,omitempty"` ID string `json:"id,omitempty"` // for tool_use Name string `json:"name,omitempty"` // for tool_use Input json.RawMessage `json:"input,omitempty"` // for tool_use ToolUseID string `json:"tool_use_id,omitempty"` // for tool_result Content string `json:"content,omitempty"` // for tool_result IsError bool `json:"is_error,omitempty"` // for tool_result } // Message represents a conversation turn type Message struct { Role Role `json:"role"` Content []ContentBlock `json:"content"` } ``` -------------------------------- ### Query Engine Source: https://context7.com/projectbarks/gopher-code/llms.txt The query engine drives multi-turn conversations by handling model requests, tool execution, context management, and error recovery. It provides a callback mechanism for receiving lifecycle events. ```APIDOC ## Query Engine The query engine is the recursive agent loop that drives multi-turn conversations. It handles model requests, tool execution, context compaction, and error recovery. ### Function Signature ```go func Query( ctx context.Context, sess *session.SessionState, prov provider.ModelProvider, registry *tools.ToolRegistry, orchestrator *tools.ToolOrchestrator, onEvent EventCallback, ) error ``` ### Event Callback `EventCallback` receives query lifecycle events. Common `QueryEvent` types include: - `QEventTextDelta`: Streaming text from the assistant. - `QEventToolUseStart`: Tool execution beginning. - `QEventToolResult`: Tool execution completed. - `QEventUsage`: Token usage update. - `QEventTurnComplete`: Model turn finished. ### Example: Running a Query with Event Handling ```go sess.PushMessage(message.UserMessage("List all Go files in the current directory")) err := query.Query(ctx, sess, prov, registry, orchestrator, func(evt query.QueryEvent) { switch evt.Type { case query.QEventTextDelta: fmt.Print(evt.Text) // Stream text to stdout case query.QEventToolUseStart: fmt.Printf("\n[Executing: %s]\n", evt.ToolName) case query.QEventToolResult: if evt.IsError { fmt.Printf("[Tool error: %s]\n", evt.Content) } case query.QEventUsage: fmt.Printf("\n[Tokens: %d in, %d out]\n", evt.InputTokens, evt.OutputTokens) } }) ``` ### Loading Public Memory Files ```go // LoadClaudeMDPublic loads CLAUDE.md files from the project hierarchy memory := query.LoadClaudeMDPublic("/path/to/project") // Returns concatenated content from: // 1. ~/.claude/CLAUDE.md (global) // 2. Walk up from CWD for CLAUDE.md (up to 10 levels) // 3. .claude/CLAUDE.md in CWD ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.