AgentSDK Go Framework

repository·main·Indexed 41 days ago

https://github.com/stellarlinkco/agentsdk-go

A modular agent development framework in Go implementing Claude Code-style runtime capabilities. It features support for Hooks, Model Context Protocol (MCP), Sandboxing, and Subagents, with an optional middleware layer for request/response interception. The SDK includes a thread-safe runtime for managing concurrent user sessions via session IDs and supports embedding configurations using Go's embed.FS for zero-dependency distribution.

Tokens
36.8K
Snippets
103
Records
164
Agent score
99%

What's inside AgentSDK Go

  1. Anthropic API Integration Status

    main

    This document tracks the integration status of agentsdk-go with the Anthropic API SDK (github.com/anthropics/anthropic-sdk-go v1.18.0).

    Supported Parameters

    • Model: Model selection
    • MaxTokens: Maximum generated tokens
    • Messages: Conversation messages
    • System: System prompt
    • Tools: Tool definitions
    • Temperature: Temperature parameter (0.0-1.0)
    • Metadata.UserID: User identifier (mapped from SessionID)
    • EnablePromptCache: Prompt cache control (v0.6.1+)

    Unsupported Parameters (Planned/In-Progress)

    • TopK: Sampling from top K options
    • TopP: Nucleus sampling
    • StopSequences: Custom stop sequences
    • ToolChoice: Tool usage strategy control
    • Thinking: Extended Thinking configuration
  2. Advanced Integrated Example Features Overview

    main

    The advanced example demonstrates the following core capabilities of the agentsdk-go ecosystem:

    • Middleware Chain: Implements logging, rate limiting, monitoring, and optional trace output via --enable-trace and --trace-dir.
    • Hooks: Lifecycle callbacks (e.g., shell hooks).
    • MCP (Model Context Protocol): Optional stdio MCP server integration (defaults to stdio://uvx mcp-server-time unless disabled).
    • Sandbox: Resource guarding for the filesystem, network, and other resources.
    • Skills: Supports both automatic and manual activation (using --force-skill).
    • Subagents: Includes a chooser mechanism with built-in and custom deployment guards.
  3. Overview of v2.1 Agent Execution Contract features

    main

    The following features are part of the v2.1 Agent Execution Contract:

    • Token Budget + Diminishing Returns: Stops the execution loop when output tokens drop below a specified threshold for $N$ consecutive iterations.
    • Micro-Compaction: Reduces context size at zero LLM cost by stripping reasoning blocks, media, and truncating old tool results.
    • Tool Concurrency Partitioning: Optimizes execution by running read-only tools concurrently while executing write tools serially.
    • Per-Tool Output Limit: Prevents context overflow by truncating tool output beyond a configurable byte limit.
    • Subagent Async Dispatch: Enables background execution of subagents with the ability to query task status.
    • SystemPromptBuilder: Provides priority-ordered section assembly for prompts with add, remove, and clone capabilities.
    • Deferred Tools: Improves initial request efficiency by excluding certain tools from the initial request until they are activated via ToolSearch.
    • Teams: Supports team fanout with explicit member assignment and automatic team selection via matcher-based auto-selection.
  4. Configure Sandbox isolation and permissions

    main

    The Sandbox manages filesystem roots, path traversal controls, network restrictions, and resource limits. It is managed by the tool execution layer (pkg/tool/) and can be configured via api.Options or the .agents/settings.json configuration file.

    Note that while .agents/settings.json still supports a permissions object for backward compatibility, v2 does not implement an interactive approval/ask workflow.

  5. Handle concurrency and SessionID isolation

    main

    The Runtime is thread-safe and supports concurrent execution, but follows specific rules regarding SessionID:

    1. Different SessionIDs: Requests can run in parallel across different goroutines.
    2. Same SessionID: Requests are mutually exclusive. If you attempt to run multiple requests with the same SessionID concurrently, the SDK will return ErrConcurrentExecution. You must serialize these requests yourself.
    3. Shutdown: Calling Runtime.Close() will wait for all ongoing requests to complete gracefully.

    Best Practice: Use unique SessionIDs for parallel tasks, and implement a queue or retry logic if you must use the same SessionID for multiple concurrent calls.

    // Different sessions execute in parallel
    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func(id int) {
            defer wg.Done()
            resp, err := rt.Run(ctx, api.Request{
                Prompt:    fmt.Sprintf("任务 %d", id),
                SessionID: fmt.Sprintf("session-%d", id), // Unique session per goroutine
            })
            // ... handle response
        }(i)
    }
    wg.Wait()
    
    // Same session requires serialization by the caller
    _, _ = rt.Run(ctx, api.Request{Prompt: "第一个", SessionID: "same"})
    _, _ = rt.Run(ctx, api.Request{Prompt: "第二个", SessionID: "same"})
  6. Core Interfaces in agentsdk-go v2

    main

    The v2 architecture simplifies the SDK around four primary core interfaces and types:

    1. model.Model: A single unified interface for model interactions. It replaces dual-interface patterns with methods like Complete and CompleteStream.
    2. tool.Tool: The interface for defining and executing tools within the agent ecosystem.
    3. middleware.Middleware: A four-stage execution pipeline used to intercept and modify agent behavior. The stages are:
      • BeforeAgent
      • BeforeTool
      • AfterTool
      • AfterAgent
    4. hooks.EventType: A set of 7 specific event types used for lifecycle hooks and observability.

    Note: The agent.Context abstraction has been removed in favor of using middleware.State directly for managing state throughout the execution lifecycle.

  7. How Prompt Compression Compaction works in v2

    main

    The compaction mechanism in v2 is designed to manage conversation history when it approaches a defined token limit.

    Trigger Condition: Compaction is triggered when the ratio of current tokens to the limit reaches a specific threshold: history.TokenCount() / TokenLimit >= Threshold.

    Compaction Behavior:

    1. Preservation: The most recent PreserveCount messages are kept in their original form.
    2. Compression: All older messages are compressed into a single summary using an LLM prompt compression call.

    Critical Constraint: When sending data to the compression model, the system automatically strips out tool-call and tool-result content. This means messages with role=tool and any ToolCalls or tool results are excluded from the compression input to ensure the summary remains focused on the conversation flow.

  8. How Shell-based Hooks work in agentsdk-go

    main

    Hooks are shell-based scripts that are automatically triggered by the agent during specific lifecycle events (e.g., before or after tool use). They allow you to intercept agent actions, validate inputs, or perform side effects without manual invocation.

    Execution Flow

    1. Trigger: The agent reaches a lifecycle event (like PreToolUse).
    2. Input: The agent passes a flattened JSON payload to the hook script via stdin.
    3. Execution: The script runs. You can configure it to run synchronously (blocking) or asynchronously.
    4. Output/Control: The hook can influence the agent via its exit code and stdout JSON output.
    {
      "hook_event_name": "PreToolUse",
      "session_id": "hooks-demo",
      "cwd": "/path/to/project",
      "tool_name": "Bash",
      "tool_input": {"command": "pwd"}
    }
  9. Understand the agent request processing flow

    main

    When calling Runtime.Run(ctx, Request), the agent follows a specific lifecycle to manage conversation history and tool execution:

    1. Session Setup: Resolves history and appends the user message.
    2. Agent Loop:
      • Executes BeforeAgent middleware (first iteration only).
      • Calls model.CompleteStream to get model response.
      • If tool calls are present, for each call:
        • Executes PreToolUse hook and safety checks.
        • Executes BeforeTool middleware.
        • Executes tool.Execute().
        • Executes AfterTool middleware and PostToolUse hook.
        • Appends tool result to history.
      • Compaction: If the token limit is reached, the history is compressed.
    3. Completion: Returns the final response to the user.
  10. How the file system loading priority works

    main

    The SDK implements a layered loading strategy that allows you to provide default configurations while still permitting runtime overrides. The priority order is:

    1. OS File System (Highest Priority): If a file exists in the local directory structure (e.g., .agents/settings.json), the SDK uses the local version.
    2. Embedded FS (Fallback): If the file is not found on the local OS file system, the SDK falls back to the version embedded within the binary.

    This pattern is ideal for CLI tools where you want to ship a single binary with sensible defaults that users can still customize by creating local configuration files.

  11. How subagent results are injected into parent context

    main

    In v2, when a subagent completes its task via Manager.Dispatch(), the parent agent does not receive a raw output. Instead, the system automatically formats a structured summary and injects it into the parent's conversation history as a user role message. This allows the model to treat the subagent's work as context to be addressed.

    Summary Format:

    [Subagent Result: {name}]
    Task: {instruction}
    Status: {success|error}
    Output: {result.Output, truncated to 2000 chars}
    {if error: Error: {result.Error}}

    Configuration: Summary injection is enabled by default. To disable it, set Options.DisableSubagentSummary to true.

    // Example of how the runtime handles the injection internally:
    summary := formatSubagentSummary(result)
    parentHistory.Append(message.Message{
        Role:    "user",
        Content: summary,
    })
  12. Implement custom permission and approval workflows

    main

    The built-in 'ask/approval queue' mechanism is no longer a core capability in v2. The system now follows a 'YOLO-default' approach combined with safety hooks and sandboxing.

    Available Security Features:

    • Sandbox: Provides isolation for the file system, network, and resources (pkg/sandbox/).
    • Safety Hook: A Go-native PreToolUse hook to intercept and block dangerous commands (e.g., catastrophic bash commands) via pkg/hooks/safety.go.
    • Disallowing Tools: You can still disable specific tools using disallowedTools in your settings.json or api.Options.

    How to implement approvals: If your application requires user confirmation before tool execution, you must implement this logic yourself using external decision services or by utilizing hooks.ShellHook.