sdk

package module
v0.0.31 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 42 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.

README

Golang Agent Harness SDK

Go Reference Go Report Card License

A powerful Golang SDK for building AI agents and making LLM calls across multiple providers with a unified API. Switch between OpenAI, Anthropic, Gemini, and more with just a single line change.

Features

  • 🔄 Multi-Provider Support - Unified API for OpenAI, Anthropic, Gemini, and more
  • 🧅 Gateway Middleware - Compose retries, provider fallback, and your own around every LLM call
  • 🤖 Agent SDK - Build sophisticated AI agents with tools, memory, and multi-step reasoning
  • 👤 Human-in-the-Loop - Integrate human feedback and approval workflows
  • 🛡️ Durable Execution - Create fault-tolerant agents with Restate or Temporal
  • 🔧 Tool Calling - Function calling and MCP (Model Context Protocol) tool integration
  • 🪝 Middlewares - Intercept tool calls and model calls for auth, budgets, and audit
  • 🏷️ Tool Annotations - MCP-style behavioural hints on both MCP and function tools
  • ⏰ Routines - Persistent datetime/cron agent tasks with HTTP APIs and agent tools (setup)
  • 💾 Conversation History - Maintain context across interactions with built-in persistence
  • 🧩 Sub-Agents & Handoffs - Call a specialist as a tool, or transfer the conversation to it
  • 🎚️ Steering - Send a correction into a run already in flight
  • ⚛️ React chat hooks - Standalone headless chat state, conversation lists, and reconnecting streams (package)
  • 🪁 CopilotKit integration - Use CopilotKit as the UI for HasteKit agents, with server-side stop, reconnecting runs, interrupts and client tools (package)
  • 🌊 Streaming Support - Real-time streaming responses for better UX
  • 🛑 Cancellation - Stop in-flight runs cleanly, including mid-stream and mid-tool-call
  • 📝 Structured Output - JSON schema validation for reliable structured responses

Table of Contents

Installation

go get -u github.com/hastekit/agent-sdk-go

Requirements:

  • Go 1.25.0 or higher

Quick Start

Simple Agent
package main

import (
	"context"
	"fmt"
	hastekit "github.com/hastekit/agent-sdk-go"
	"log"
	"os"
)

func main() {
	client := hastekit.NewLLMClient([]hastekit.ProviderConfig{
		{
			ProviderName: hastekit.ProviderOpenAI,
			ApiKeys: []*hastekit.APIKeyConfig{
				{
					Name:   "Key 1",
					APIKey: os.Getenv("OPENAI_API_KEY"),
				},
			},
		},
	})

	model := client.Model("OpenAI/gpt-4.1-mini")

	agent, err := hastekit.NewAgent(&hastekit.AgentConfig{
		Name: "Assistant", LLM: model, Instruction: hastekit.NewPrompt("You are a helpful assistant."),
	})
	if err != nil {
		log.Fatal(err)
	}
	result, err := agent.Run(context.Background(), &hastekit.Input{
		Message: hastekit.UserTurn("Hello!"),
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(result.Text())
}

Use Run(ctx, *Input) for a blocking result. Its context controls execution, including cooperative cancellation of remote work. Use Execute(ctx, *Input) for a detached execution with events:

handle, err := agent.Execute(ctx, &hastekit.Input{
    Message: hastekit.UserTurn("Research this topic"),
})
if err != nil { return err }
for event := range handle.Chunks {
    // Render event.
    _ = event
}
result, err := handle.Wait(waitCtx)
// To stop execution: handle.Stop(ctx).

Canceling Execute's context disconnects its subscription; execution continues. Canceling Wait's context stops only the wait. Local detached runs last only as long as the process; use a durable runtime to survive process exit.

Handles buffer up to 256 pending events. If a consumer falls behind, Wait reports ErrStreamOverflow alongside the execution result. Waiting without reading events never blocks execution, but may report overflow; use Run when only the result is needed. The legacy Result and Cancel methods remain aliases for Wait and Stop.

Input aliases agents.AgentInput: the same type supports ordinary messages, attachments, sender attribution, and conversation identifiers. Optional RunID selects the actual execution ID; omit it for generated IDs. Supplied IDs must be unique within the namespace. AGUI passes its client's runId through to history and stream events, so initial delivery and reconnects use the same identity.

Run-ID uniqueness is the persistence backend's responsibility. The SDK does not read history to check for duplicates or add a creation flag to save metadata. A database backend should enforce uniqueness when inserting new runs and handle incremental saves as updates. The built-in memory and file stores retain their append-on-save behavior for an existing run in the same thread.

Migrating existing applications
  • NewAgent now returns (*Agent, error) and validates configuration. Use LLM for the model provider and Instruction for the prompt provider. Use NewPrompt("...") for a static prompt.
  • NewFileHistory and OpenFileHistory return (*History, error). Call Close() once all agents sharing that history have stopped.
  • HTTP routing uses an explicit registry. Create NewRegistry(), explicitly Register(agent), and pass it to NewHTTPHandler(registry) or the AG-UI handler. Duplicate names in one registry return ErrAgentAlreadyRegistered.
  • Each agent gets its own default memory broker. To share one, pass it explicitly through WithRuntime(local_runtime.NewLocalRuntime(broker)); the global DefaultStreamBroker was removed.
  • Create durable agents with NewAgent(config, WithRuntime(rt)); their configurations register with that runtime instance. Replace rt.Start() with blocking rt.Serve(ctx) (Temporal) or rt.Serve(ctx, listenAddress) (Restate). Defer rt.Close(); the runtime closes its own client/server, while the caller owns supplied brokers and histories. NewAgent registers the configuration; Serve starts the worker.
  • MustNewAgent and MustNewFileHistory explicitly panic on setup errors. Some shorter configuration examples below use MustNewAgent; prefer the checked constructors when handling application setup errors.

Custom implementations of agents.Runtime must expose StreamBroker() agents.StreamBroker and RegisterAgent(*agents.AgentOptions) error. NewAgent calls RegisterAgent with the validated, resolved configuration; runtimes without registration needs can return nil. Registration errors are returned to the caller.

These constructor and registration changes are breaking API changes.

Usage

LLM Client

hastekit.NewLLMClient takes a list of provider configs and returns a client. Bind a model with client.Model("Provider/model") — the returned value satisfies the llm.Provider interface and exposes NewResponses, NewStreamingResponses, and friends.

// Single provider
client := hastekit.NewLLMClient([]hastekit.ProviderConfig{
    {
        ProviderName: hastekit.ProviderOpenAI,
        ApiKeys: []*hastekit.APIKeyConfig{
            {Name: "default", APIKey: os.Getenv("OPENAI_API_KEY")},
        },
    },
})

// Multiple providers — switch by changing the model string
client := hastekit.NewLLMClient([]hastekit.ProviderConfig{
    {
        ProviderName: hastekit.ProviderOpenAI,
        ApiKeys: []*hastekit.APIKeyConfig{
            {Name: "default", APIKey: os.Getenv("OPENAI_API_KEY")},
        },
    },
    {
        ProviderName: hastekit.ProviderAnthropic,
        ApiKeys: []*hastekit.APIKeyConfig{
            {Name: "default", APIKey: os.Getenv("ANTHROPIC_API_KEY")},
        },
    },
})

openai := client.Model("OpenAI/gpt-4o-mini")
claude := client.Model("Anthropic/claude-sonnet-4-5")

Provider constants: hastekit.ProviderOpenAI, ProviderAnthropic, ProviderGemini, ProviderXAI, ProviderBedrock, ProviderOllama, ProviderOpenRouter, ProviderElevenLabs, ProviderSarvam, ProviderDeepSeek, ProviderMoonshot (Kimi models), ProviderZAI (GLM models).

Middleware

Every call a client makes runs through a middleware chain. Nothing is installed unless you ask for it — a call that fails is otherwise reported as it happened — except tracing, which every client adds innermost so each attempt gets its own span.

import "github.com/hastekit/agent-sdk-go/pkg/gateway/middleware"

client := hastekit.NewLLMClient(configs, hastekit.WithMiddleware(
    middleware.NewFallbackModels("Anthropic/claude-sonnet-4-5"),
    middleware.NewRetry(middleware.RetryConfig{}),
))

The chain is written outermost first, and the order is yours to choose. Fallback belongs outside retry: that way a provider is retried on its own before the chain gives up on it, where the other way round a 503 that would have cleared on the second attempt costs you a switch to a different model instead.

Anything satisfying gateway.Middleware goes in the same list, so a budget check, a cache, or a request log sits alongside the built-in ones:

type auditLog struct{}

func (auditLog) HandleRequest(next gateway.RequestHandler) gateway.RequestHandler {
    return func(ctx context.Context, p llm.ProviderName, key string, r *llm.Request) (*llm.Response, error) {
        resp, err := next(ctx, p, key, r)
        record(p, r.GetRequestedModel(), err)
        return resp, err
    }
}

func (auditLog) HandleStreamingRequest(next gateway.StreamingRequestHandler) gateway.StreamingRequestHandler {
    return next
}

client := hastekit.NewLLMClient(configs, hastekit.WithMiddleware(auditLog{}, middleware.NewRetry(middleware.RetryConfig{})))

Middleware that needs the provider configuration — fallback, which resolves a key for a provider the caller never named — is handed it when the chain is installed, so you never pass a config store yourself.

Retries

middleware.NewRetry re-issues a call that failed for a reason another attempt could plausibly fix. The zero RetryConfig is a usable policy: three attempts, 500ms initial backoff doubling to a 30s ceiling, jittered. A provider that names its own delay in a Retry-After header is obeyed as given rather than jittered — it knows when its limit resets.

middleware.NewRetry(middleware.RetryConfig{
    MaxAttempts:    5,               // counts the first call
    InitialBackoff: time.Second,
    MaxBackoff:     time.Minute,
})

Retried: 408, 409, 425, 429, and 500/502/503/504, plus transport failures — timeouts, connection resets, truncated bodies. Not retried: a cancelled context, and every 4xx that describes the request itself, since the same request fails the same way on the next attempt.

Streaming is retried only up to the first chunk the caller sees. A stream that fails before delivering anything is indistinguishable from one that never opened, so it is retried transparently; once a chunk has been forwarded the attempt is committed, because there is no way to un-send it and no provider supports resuming a stream from the middle.

Fallback

middleware.NewFallbackModels sends a call to a different provider when the one you asked for fails. Each target is tried in order, and — where retry sits inside it — each target gets its own full retry budget before the chain moves on.

middleware.NewFallbackModels("Anthropic/claude-sonnet-4-5", "Gemini/gemini-2.5-flash")

// Or built explicitly, when you want to set the policy too.
middleware.NewFallback(middleware.FallbackConfig{
    Targets:      middleware.FallbackModels("Anthropic/claude-sonnet-4-5"),
    Fallbackable: func(err error) bool { return llm.StatusCodeOf(err) == 429 },
})

Each target's API key is resolved from the configs the client was built with, so every target needs one; a target without a key is skipped rather than failing the call. An id naming only a provider — "OpenRouter" — keeps the model the caller asked for and only redirects the provider, which is what a target on an OpenAI-compatible mirror wants.

Fallback moves on for almost any failure — a rate limit, an outage, an expired key, a retired model. The exceptions are a cancelled context and the two statuses that describe the request itself (400 and 422), since a request one provider could not parse will not parse anywhere else.

Streaming follows the same commit rule as retrying: a stream that fails before delivering a chunk can move to the next target, but one that has already delivered anything cannot — half an answer from one model finished by another is worse than a clean failure.

Per-Model Middleware

WithMiddleware on Model replaces the client's chain for that one model. There is no merging: a chain is an ordered whole, and picking entries out of one by type would not survive middleware you wrote yourself.

client := hastekit.NewLLMClient(configs, hastekit.WithMiddleware(
    middleware.NewRetry(middleware.RetryConfig{}),
))

// Inherits the client's chain.
fast := client.Model("OpenAI/gpt-4o-mini")

// Tries harder, and falls back.
critical := client.Model("OpenAI/gpt-4o", hastekit.WithMiddleware(
    middleware.NewFallbackModels("Anthropic/claude-opus-4-5", "Gemini/gemini-2.5-pro"),
    middleware.NewRetry(middleware.RetryConfig{MaxAttempts: 5}),
))

// An LLM judge, held to exactly what the provider did on the first attempt.
judge := client.Model("OpenAI/gpt-4o", hastekit.WithoutMiddleware())

A model naming its own chain builds one, so bind a model once at setup rather than per request.

Agents
Agent with Custom Tools

hastekit.NewTool turns any func(ctx, In) (Out, error) into a tool. The input JSON schema is derived from the argument struct, and arguments/results are marshalled for you:

type WeatherArgs struct {
    Location string `json:"location" jsonschema_description:"City name"`
}

type Weather struct {
    TempC     float64 `json:"temp_c"`
    Condition string  `json:"condition"`
}

func getWeather(ctx context.Context, args WeatherArgs) (Weather, error) {
    // Your logic here
    return Weather{TempC: 22.5, Condition: "Sunny"}, nil
}

weatherTool := hastekit.NewTool(getWeather,
    hastekit.WithName("get_weather"), // optional; defaults to the function name
    hastekit.WithDescription("Get current weather for a location"),
    hastekit.WithReadOnly(true), // optional behavioural hint
)

// Use the tool
agent := hastekit.MustNewAgent(&hastekit.AgentConfig{
    Name:        "Weather Assistant",
    Instruction: hastekit.NewPrompt("You help users check the weather."),
    LLM:         client.Model("OpenAI/gpt-4o-mini"),
    Tools:       []hastekit.Tool{weatherTool},
})

Tools that implement the agents.Tool interface directly also work and can be mixed into the same Tools slice. The interface is two methods — Execute, and GetToolDescriptor() *agents.BaseTool for the tool's schema, name and flags — and embedding agents.BaseTool supplies the second one, so a hand-written tool only defines Execute:

type DeleteUserTool struct {
    *agents.BaseTool
}

func NewDeleteUserTool() *DeleteUserTool {
    return &DeleteUserTool{
        BaseTool: &agents.BaseTool{
            RequiresApproval: true,
            ToolUnion: responses.ToolUnion{
                OfFunction: &responses.FunctionTool{
                    Name:        "delete_user",
                    Description: utils.Ptr("Permanently deletes a user account"),
                    Parameters: map[string]any{
                        "type":       "object",
                        "properties": map[string]any{"user_id": map[string]any{"type": "string"}},
                        "required":   []string{"user_id"},
                    },
                },
            },
        },
    }
}

func (t *DeleteUserTool) Execute(ctx context.Context, params *agents.ToolCall) (*agents.ToolCallResponse, error) {
    // Your logic here
}
Sub-Agents

An agent can be given to another agent as a tool, so a specialist is called the same way a function is — the caller stays in charge and gets the sub-agent's answer back as a tool result:

import "github.com/hastekit/agent-sdk-go/pkg/agents/tools"

researcher := hastekit.MustNewAgent(&hastekit.AgentConfig{
    Name:        "Researcher",
    Instruction: hastekit.NewPrompt("You research topics thoroughly."),
    LLM:         model,
})

agent := hastekit.MustNewAgent(&hastekit.AgentConfig{
    Name:        "Assistant",
    Instruction: hastekit.NewPrompt("You are a helpful assistant."),
    LLM:         model,
    Tools: []agents.Tool{
        tools.NewAgentTool(
            "research",
            "Research a topic in depth",
            researcher,
            tools.SubAgentContextModeNone,
        ),
    },
})

The context mode decides who keeps track of the sub-agent's conversation. Under SubAgentContextModeNone the calling model does: thread_id is one of the tool's parameters, and the thread the sub-agent ran on comes back in the result for it to pass in next time. Under SubAgentContextModeIsolated the tool does, holding the thread in the call's own state, so the sub-agent remembers its earlier turns without the model having to carry an id around.

A sub-agent that pauses for approval pauses the whole run, however deeply it is nested, and resuming resumes it in place rather than starting it again.

Handoffs

A handoff transfers the conversation instead of borrowing an answer: the target agent takes over the thread and replies to the user directly.

agent := hastekit.MustNewAgent(&hastekit.AgentConfig{
    Name:        "Triage",
    Instruction: hastekit.NewPrompt("Route the user to the right specialist."),
    LLM:         model,
    Handoffs: []*agents.Handoff{
        agents.NewHandoff("Billing", "Questions about invoices and payments", billingAgent),
        agents.NewHandoff("Support", "Technical troubleshooting", supportAgent),
    },
})

The model picks a target by calling the generated transfer_to_agent tool.

By default the next turn starts at the root agent again. Set StickyHandoff: true on the agent to keep the thread with whichever specialist last handled it, so a user mid-conversation with Billing is not re-triaged on every message — a later handoff moves the thread on, and a handoff back to the root unsticks it.

Streaming Chunks and Cancellation

agent.Execute returns a handle. Range over handle.Chunks to forward live deltas (UI, SSE, logs); call handle.Stop(ctx) to stop the run — it records a "Cancelled by user" assistant turn in history and emits run.completed cleanly.

Stop does not wait for an iteration boundary. It reaches work already in flight:

  • Mid-stream — the model call is cut off where it is, rather than waited out. Text that had already streamed still reached the client, but the turn is recorded as cancelled rather than as a half-answer the model never finished.
  • Mid-tool-call — a running tool has its context cancelled; a tool that ignores cancellation is abandoned after a grace period so the run still ends.

Either way the loop's invariant holds: every function_call in history is answered, so a stopped thread is still a valid thread to resume from.

handle, err := agent.Execute(ctx, &agents.AgentInput{
    Message: history.Message{
        Messages: []responses.InputMessageUnion{
            responses.UserMessage("Walk me through how to set up Postgres replication."),
        },
    },
})
if err != nil { log.Fatal(err) }

// Cancel after 5 seconds — the agent finishes its current step and stops gracefully.
go func() {
    time.Sleep(5 * time.Second)
    _ = handle.Stop(context.Background())
}()

for chunk := range handle.Chunks {
    if chunk.OfOutputTextDelta != nil {
        fmt.Print(chunk.OfOutputTextDelta.Delta)
    }
}

out, err := handle.Wait()

Provider streams now report terminal failures through ResponseChunk.OfError. Agent handles return those failures as errors; a stream that ends without response.completed also fails instead of returning a partial answer. Custom providers must emit a completion event on success.

The OpenAI, Anthropic, and Gemini clients attach the caller's context to HTTP requests and accept an optional ClientOptions.HTTPClient for custom timeouts and transports. Cancelling the request context stops both the HTTP request and blocked stream sends.

The StreamID on the handle (also returned in the X-Stream-Id HTTP header when serving over HTTP) lets you re-subscribe to the same broker channel — useful for resuming a stream after a page refresh, or for stopping the run from a different process.

Steering a Running Agent

A run does not have to be left alone until it finishes. The same broker that carries a stop can carry a message into a run already in flight — the loop drains the queue at iteration boundaries, the same cadence at which it checks for a stop, and once more when the model has finished answering, and folds what it finds into the conversation before the next model call:

err := broker.EnqueueMessage(ctx, streamID, history.Message{
    Messages: []responses.InputMessageUnion{
        responses.UserMessage("Actually, focus on the last quarter only."),
    },
})

The agent finishes the tool calls already running, then continues with the new instruction in context, so a correction lands without losing the work so far. A message that arrives during what would have been the final reply gets an answer of its own in the same run. A stop discards whatever is still queued, and a message is left unanswered if the run has used up MaxLoops or is a SingleTurn agent, or arrives after that last check, as the run is finishing. Clients should treat a message as delivered only once the run announces taking it in.

AG-UI

Agents are served to the browser over the AG-UI protocol — the standard event-stream protocol that frontend agent frameworks (CopilotKit, raw @ag-ui/client, etc.) speak. The pkg/agui package translates the SDK's streaming chunks into canonical AG-UI events (text messages, reasoning, tool calls, steps, human-in-the-loop interrupts) over SSE:

import "github.com/hastekit/agent-sdk-go/pkg/agui"

// Construct an agent, then register it explicitly.
agent := hastekit.MustNewAgent(&hastekit.AgentConfig{
    Name: "Assistant",
    // ...
})

registry := hastekit.NewRegistry()
if err := registry.Register(agent); err != nil { log.Fatal(err) }

// Exposes:
//   GET  /agents                                   → registered agent names
//   POST /agents/{agent}/run                       → AG-UI run endpoint (SSE)
//   GET  /agents/{agent}/threads/{thread}/stream   → rejoin the run in flight (SSE)
//   GET  /agents/{agent}/runs                      → long poll: runs in the resolved namespace
//   GET  /agents/{agent}/threads                   → stored conversation threads, newest first
//   GET  /agents/{agent}/threads/{thread}/messages → thread history as AG-UI messages
http.ListenAndServe(":8080", agui.NewHandler(agents.StaticRegistry(registry)))

// Or mount a single agent's run endpoint on an existing mux:
// mux.Handle("POST /assistant/run", agui.AgentHandler(agent))

For a zero-setup browser chat UI, the pkg/agui/web package embeds a ready-made CopilotKit chat into your binary with go:embed — no Node toolchain or separate frontend deploy needed to run it:

import "github.com/hastekit/agent-sdk-go/pkg/agui/web"

// Serves the embedded CopilotKit chat UI at / and the AG-UI protocol
// endpoints under /api/agui/*.
if err := web.Serve(":8080", agents.StaticRegistry(registry)); err != nil {
    log.Fatal(err)
}

Registered agents are also accessible through A2A 1.0 JSON-RPC:

  • GET /api/agui/a2a/ lists agents and their discovery URLs.
  • GET /api/agui/a2a/{agent}/.well-known/agent-card.json returns an agent card.
  • POST /api/agui/a2a/{agent} accepts A2A requests, including streaming, task lookup/listing, cancellation, and continuation after an input-required pause.

See A2A setup and protocol examples. The adapter supports text and JSON data; task state is isolated per agent and resolved namespace and is in memory by default. Configure shared A2A persistence/queues for multiple replicas.

The embedded UI lists registered agents, shows a sidebar of prior conversations (select one to resume it on the same thread), streams assistant text, reasoning, and tool calls live, and renders CopilotKit's useInterrupt approval cards inline when a run pauses for human-in-the-loop tool approval.

The messages endpoint is paginated:

GET /agents/{agent}/threads/{thread}/messages?limit=50
GET /agents/{agent}/threads/{thread}/messages?limit=50&cursor=<nextCursor>

The default page contains the latest 50 stored turns (limit: 1–200). A turn can contain several AG-UI messages; paging preserves complete turns rather than splitting their tool calls and results. Messages within each page are chronological. The response includes nextCursor and hasMore; prepend each older page to the messages already loaded. Invalid, expired, or wrong-namespace/thread cursors return 400. The run field always reflects the latest stored turn, including when requesting older messages.

The embedded chat loads older pages when scrolling up, with a load/retry button. Full-history mode fetches all pages to retain its existing behavior. SSE replay cursors remain separate from history cursors.

For efficient database queries, implement history.TranscriptPageReader. TranscriptPageOptions.BeforeRunID is an exclusive boundary in insertion order, not lexical run-ID order. Return chronological Rows, NextBeforeRunID when older rows remain, and Latest for current thread state. The built-in memory/file stores support this interface. Legacy adapters remain compatible through a full-transcript fallback, which bounds the HTTP response but not storage reads.

Conversation listing works when the agent's persistence adapter implements history.ThreadLister — the SDK's built-in in-memory and file adapters both do. For adapters that can't enumerate threads, the listing endpoint answers 501 and the UI hides the picker.

The CopilotKit UI is a Vite/React app under pkg/agui/web/ui; its build output is committed to pkg/agui/web/static, so go build never needs Node. Rebuild only when changing the UI source (cd pkg/agui/web/ui && pnpm install && pnpm build). CopilotKit v2 can't be loaded from a public ESM CDN (its dependency graph breaks esm.sh/jsDelivr), so it's bundled. To keep the embedded weight down to ~1MB (from ~17MB), the build aliases out CopilotKit's heaviest optional dependencies — the markdown renderer's Shiki/Mermaid/Cytoscape stack (swapped for a lightweight react-markdown shim), KaTeX's math fonts, and the dev-console web-inspector — none of which the chat needs.

Options (shared by agui.NewHandler, agui.AgentHandler, web.Handler, and web.Serve):

web.Serve(":8080", client,
    agui.WithNamespaceResolver(func(r *http.Request) (string, error) {
        // Resolve from identity supplied by your authentication middleware.
        return "user-123", nil
    }),
    agui.WithSenderID("alice"),     // sender attribution (default "user")
    agui.WithFullHistory(),         // forward the client's full message list
                                    // (only for agents without persistence)
    agui.WithKeepalive(10*time.Second), // SSE keep-alive interval (default 15s)
)

WithNamespace has been replaced by WithNamespaceResolver. The resolver runs once per API request after route matching, so request context and PathValue are available. Its namespace is used for runs, history, thread listing, stream rejoining, attachments, and the default run-feed scope. A nil resolver or an empty/whitespace-only result uses "default". Resolver errors return HTTP 403 without exposing the error text or falling back to another namespace.

The embedded UI has no namespace selector and sends no namespace overrides, including on run-feed requests. With no resolver configured, it uses "default" for every endpoint. A configured resolver can still derive identity from the same-origin session on the server.

Run feeds always use the resolved namespace. The old ?namespaces= parameter is rejected with HTTP 400; additional namespace selection is not supported.

Stop requests now require threadId in the JSON body or query. The server derives the stream ID from that thread and the resolved namespace. An optional streamId must match or the request returns HTTP 403. Raw stream-ID-only requests return HTTP 400. This is a breaking change for custom stop clients; the embedded UI has been updated.

POST /agents/Assistant/stop
Content-Type: application/json

{"threadId":"conversation-123"}

Rejoining streams supports SSE resume cursors. Each initial and replayed event has an opaque id:. After a connection drops, send the last complete event ID to receive only the events after it:

GET /agents/Assistant/threads/conversation-123/stream
Last-Event-ID: <last-received-event-id>

For clients that cannot set headers, ?lastEventId=<URL-encoded-event-id> is also supported. Supplying conflicting header/query values returns HTTP 400. Without either value, the endpoint replays all retained events for the latest run on that thread. This also works after the run finishes. Older conversation history is available through the thread's /messages endpoint; stream replay is bounded by the broker's retention window.

Cursors are scoped to the resolved namespace, thread, and run. Malformed or wrong-stream cursors return HTTP 400. An expired, trimmed, replaced, or unknown event cursor returns HTTP 410 instead of silently skipping data: reload thread history and reconnect without a cursor. Custom brokers must implement agents.StreamReplayReader to support cursor validation and completed replay; the built-in memory and Redis brokers implement it. Unsupported cursor requests return HTTP 501. A thread with neither a live run nor retained events returns 204.

The embedded UI reconnects after network errors, premature EOF, or a 45-second idle timeout. It retains the last complete event ID only within the current stream subscription and reconnects using GET, never repeating the POST that started the run. A full page reload sends no cursor. Expired replay is surfaced as an error so the user can reload history.

Every run ends with RUN_FINISHED carrying an AG-UI 1.0 outcome:

  • A run waiting on a person (a tool approval, or a form or URL elicitation) ends with {"type": "interrupt", "interrupts": [...]}. Each interrupt's id is the paused tool call's id; approvals have reason: "tool_call" and expect {"approved": boolean}, elicitations have reason: "input_required" with the form's schema as responseSchema. The client answers every open interrupt on the next POST with resume: [{"interruptId", "status": "resolved" | "cancelled", "payload"}]; CopilotKit's useInterrupt does this for you.
  • A run that left client tool calls ends with {"type": "success"} and those calls unanswered in the stream; the client answers them with tool messages (see Client tools). The outcome does not name them (pendingToolCallIds), because clients before AG-UI 1.0, including current CopilotKit releases, reject that field; 1.0 clients treat calls with no result as pending.
  • Otherwise {"type": "success"}. Token usage is reported in the top-level usage list.

The outcome is the only pause signal: pauses do not replace the client's agent state with a STATE_SNAPSHOT, and there is no on_interrupt CUSTOM event. Answers come only from resume; the pre-1.0 forwardedProps.command.resume.decisions[] form is not read.

Client tools

Tools a browser runs itself (CopilotKit's useFrontendTool, or clientTools in @hastekit/react) arrive with each run in RunAgentInput.tools. The model can call them like any other tool; server-side tools win name collisions. The client runs a call to one of its own tools as soon as the call has streamed in and sends the result as an ordinary tool message to POST /agents/{agent}/run. The run waits for it, 30 seconds by default, and carries on without a second request. If the result has not arrived by then, the run pauses on the call with a client_tool interrupt, and the tool message resumes it — which is what stock AG-UI clients such as CopilotKit send, after the run has ended. Client tools need no configuration; AgentConfig.ClientTools only changes the wait.

Inside the agent the two cases stay apart: a waiting call takes the client's tool output through the stream broker, and a paused call is resumed like any other interrupt, by a resolution approving it with the result as its Content. The AG-UI handler turns a tool message answering a paused client tool into that resolution once it has claimed the thread, so a result sent just as the run pauses still resumes it. A caller driving Agent.Execute directly resumes a paused client tool the same way it answers an approval; a tool output in a run's input is kept only alongside the call it answers (a full-history replay), and dropped otherwise.

The server knows a client's tools only from the request that starts a run, so a client sends them with every request, including tool results and resumes, as CopilotKit and both HasteKit packages do. A run the server starts itself, when a background task's result arrives on an idle thread, offers the tools of the run that started the task. A paused client tool call is still resolved by a request that omits them, but the rest of that run cannot call them.

hastekit.AgentConfig{
    // Wait up to two minutes. A negative timeout pauses at once, for clients
    // that only answer after the run has paused.
    ClientTools: agents.ClientToolOptions{Timeout: 2 * time.Minute},
}

A tool message that reaches a live run is not queued like other turns: the stream broker keeps it for its call, where the waiting tool reads it (StreamBroker.WaitToolResult). The built-in memory and Redis brokers do this (Redis for multiple replicas). Results are scoped to the thread's stream, which is derived from the namespace, and the first result for a call wins. A tool message for nothing the thread is waiting on, such as a result that arrives after its run moved on, is acknowledged (204) without starting a run. A turn sent just as a run ends waits for the run to release the thread and starts the next one, rather than joining the run that is finishing. Under Temporal the wait runs as a heartbeating activity; under Restate it runs in a journaled step, so set the Restate invocation timeouts above the client tool timeout. The embedded UI ships one browser tool, get_browser_context (time zone, locale, local time).

Context usage

After each model call the run reports the current context size as a hastekit.context_usage CUSTOM event: {tokens, agentName}. tokens is what the next prompt starts from (the call's measured prompt and reply). The thread messages endpoint returns the last figure as context, for a page that has just loaded. The embedded UI shows the token count under the composer, for example 9.1k tokens in context.

CopilotKit

@hastekit/copilotkit connects a CopilotKit app to these endpoints. Register a HastekitAgent with CopilotKitProvider, and the package's hooks handle interrupts and client tools; the embedded UI is built on it.

Tools
MCP Tools Integration

Define MCP servers through two configuration stores — the developer's and the users' — and give one client to the agent:

store, err := mcpclient.NewFileStore("./data/mcp-config.json") // users' connectors
if err != nil {
    log.Fatal(err)
}

// Servers defined in code are global, developer-owned and read-only.
builtins := mcpclient.NewInlineStore(mcpclient.ServerConfig{
    Name: "sample", Endpoint: "http://localhost:9001/sse", Transport: "sse",
    ToolPrefix: "sample__",
    ToolFilter: mcpclient.ToolFilter{Include: []string{"list_users", "get_user"}},
    Meta: map[string]any{"thread_id": "{{thread_id}}", "run_id": "{{run_id}}"},
})

agent := hastekit.MustNewAgent(&hastekit.AgentConfig{
    Name: "MCP Agent", LLM: model,
    Instruction: hastekit.NewPrompt("You are a helpful assistant."),
    MCPClient: mcpclient.NewClient(builtins, mcpclient.WithUserStore(store)),
})

NewClient(builtIn, mcpclient.WithUserStore(user)) reads the built-in store's servers as global — developer-owned, always on, and winning over a user's server with the same name — and the user store's as each namespace's own. A store does not know which role it plays: the client reads the built-in store under the empty namespace and the user store under the run's, so any store can fill either slot, one store can fill both, and either may be nil. NewInlineStore(configs...) serves servers written in code, NewMemoryStore() and NewFileStore(path) persist definitions by namespace, and you can implement mcpclient.Store for database storage. mcpclient.Filter(store, servers) gives an agent only the named servers of a store, each narrowed to the tools it names, such as mcpclient.Filter(builtins, map[string]mcpclient.ToolFilter{"docs": {}, "github": {Include: []string{"get_issue"}}}); filter either store, or both. Stores receive their namespace and the run context. AgentInput.MCP lets a run disable or narrow the user's own servers; global servers are mandatory and ignore it. Discovery returns tools and connector statuses for the prompt.

See MCP configuration stores for store composition, selection, caching, and connector management APIs.

  • ToolFilter accepts Include/Exclude lists of original server tool names. An empty Include allows all tools; Exclude wins.
  • DeferredTools: &mcpclient.ToolFilter{Exclude: []string{"search"}} defers all exposed tools except search. A nil DeferredTools leaves every tool available.
  • ToolPrefix: "fs__" exposes read_file as fs__read_file; filters and approval lists still use original tool names.
  • CacheTTLSeconds and DefaultCacheScope configure discovery caching. Supply a cache with the mcpclient.WithSchemaCache(cache) client option. Use public scope only when all users see the same tools; private is the default when the server omits its scope.
Per-call MCP metadata

ServerConfig.Meta supports nested {{key}} string templates resolved from ToolCall.RunContext immediately before execution. Use it for changing thread/run IDs instead of headers: metadata does not affect connection or schema cache keys. The MCP server reads req.Params.Meta. Resolution happens inside Temporal activities or Restate steps, so retries use the persisted run context.

MCP servers over stdio

Developer-owned configs can start an MCP process on demand:

store := mcpclient.NewInlineStore(mcpclient.ServerConfig{
    Name: "filesystem", Transport: mcpclient.TransportStdio,
    Command: []string{"npx", "-y", "@modelcontextprotocol/server-filesystem", "/tmp"},
    Env: map[string]string{"WORKSPACE": "{{workspace}}"},
    ToolPrefix: "fs__",
})
client := mcpclient.NewClient(store)

The child process inherits the host environment plus configured values. Filters, approvals, deferral, prefixes, and caching work across transports.

User connectors and OAuth

mcpclient.NewHandler(store, ...) lists visible connectors and lets users save or delete their namespace-owned HTTP configs in store, the client's user store. Pass the client's built-in store with mcpclient.WithBuiltInStore(builtins): its servers are listed and reserved, and can be connected with OAuth, but never written. ServerConfig.Authorization contains OAuth application settings. A shared OAuthCredentialProvider resolves and refreshes tokens stored by namespace + OAuthCredentialKey (owner, server name, and OAuth client), without a separate server registry.

client := mcpclient.NewClient(builtins, mcpclient.WithUserStore(store), mcpclient.WithCredentials(provider))
handler := web.Handler(registry,
    agui.WithNamespaceResolver(authenticatedNamespace),
    agui.WithMCPStore(store, mcpclient.WithBuiltInStore(builtins), mcpclient.WithOAuth(provider)),
)

The web routes live under /api/agui/mcp; OAuth connect/callback routes read settings from the store even before the first agent run. A server that publishes its authorization metadata needs only its URL and the callback: connecting discovers its authorization server and registers a client there (dynamic client registration), using the MCP Go SDK's authorization flow, and keeps the registration in the credential store. See persisted MCP credentials, discovery and Gmail setup and samples/new/main.go.

A server defined in code can instead carry a CredentialsProvider of its own, as each of the MCP Go SDK's transports takes its own OAuth handler; stored and user-owned definitions cannot. Write one for a server whose tokens come from somewhere the client's provider knows nothing about, such as a token service of the host's own. Servers with their own providers, OAuth, static-header and open servers mix in one client; see a server's own credentials provider.

Tool Annotations

Tools can advertise what they do. The hints mirror MCP's tool annotations, so hints read off an MCP server and hints declared on a local function tool are the same thing — one policy can read both:

readTool := hastekit.NewTool(listUsers,
    hastekit.WithName("list_users"),
    hastekit.WithTitle("List users"), // human-readable, for UI
    hastekit.WithReadOnly(true),
)

writeTool := hastekit.NewTool(deleteUser,
    hastekit.WithName("delete_user"),
    hastekit.WithDestructive(true),
    hastekit.WithIdempotent(false),
    hastekit.WithOpenWorld(false),
)

MCP tools carry whatever their server declared; nothing extra is needed to pick them up. Read the hints back off the tool's descriptor:

if tool.GetToolDescriptor().Annotations.IsDestructive() {
    // gate it — see Middlewares below
}

A tool call middleware is handed the same descriptor, which is where a policy usually reads them.

Every hint is a pointer, so "nothing was said" stays distinguishable from "false was said". Prefer the Is* helpers over reading fields directly: they are nil-safe and apply MCP's defaults, which are deliberately conservative — an unset DestructiveHint reads as destructive, an unset ReadOnlyHint as not read-only.

Hints are self-reported: they describe intent, not enforcement. Never let a hint from an untrusted MCP server widen what a tool is allowed to do.

Background Tool Execution

A tool that starts work outlasting the call answers with a TaskID. The run does not wait: the model reads the tool's immediate output, carries on, and the result is delivered later as its own turn.

hastekit.NewBackgroundTool is NewTool for that kind of work — write the long-running function and it handles the rest:

indexTool := hastekit.NewBackgroundTool(
    func(ctx context.Context, in IndexArgs, progress hastekit.ProgressReporter) (IndexResult, error) {
        for i, doc := range in.Docs {
            progress.Report(ctx, hastekit.ToolProgress{
                Progress: float64(i + 1), Total: float64(len(in.Docs)), Message: doc.Name,
            })
            index(doc)
        }
        return IndexResult{Indexed: len(in.Docs)}, nil
    },
    hastekit.WithName("index_docs"),
    hastekit.WithDescription("Index documents. Takes a while."),
)

The model gets an immediate answer naming the task, the run carries on, and whatever the function returns is delivered to the thread when it returns. Progress is nil-safe, so report freely whether or not anyone is listening, and WithStartedMessage replaces what the model is told at the moment the task starts. Every ordinary tool option — WithName, WithDestructive, WithNeedsApproval — works the same way it does on NewTool.

The return value is encoded like an ordinary tool's, unless it already is a tool output — then it travels as it is. That is how a task answers with an image or a file rather than a line of JSON:

chartTool := hastekit.NewBackgroundTool(
    func(ctx context.Context, in ChartArgs, progress hastekit.ProgressReporter) (*responses.FunctionCallOutputMessage, error) {
        png := render(in)
        return &responses.FunctionCallOutputMessage{
            Output: responses.FunctionCallOutputContentUnion{
                OfList: responses.InputContent{
                    {OfInputText: &responses.InputTextContent{Text: "chart rendered"}},
                    {OfInputImage: &responses.InputImageContent{ImageURL: utils.Ptr(png)}},
                },
            },
        }, nil
    },
    hastekit.WithName("render_chart"),
)

The function runs off the run's path, not inside it: in this process a goroutine of the agent's, and under Temporal or Restate whatever that runtime keeps for the task. That is why it is handed its arguments rather than closing over them — it may well run somewhere the call that started it never reached, so anything it needs has to travel in the arguments.

For work that has to be started now and only watched later — a job queued with another service — implement agents.BackgroundTool yourself, which splits starting from waiting:

func (t *indexTool) Execute(ctx context.Context, params *agents.ToolCall) (*agents.ToolCallResponse, error) {
    job, err := t.client.StartIndexing(ctx)
    if err != nil {
        return nil, err
    }
    return &agents.ToolCallResponse{
        FunctionCallOutputMessage: &responses.FunctionCallOutputMessage{
            ID: params.ID, CallID: params.CallID,
            Output: responses.FunctionCallOutputContentUnion{
                OfString: utils.Ptr("Indexing started, job " + job.ID),
            },
        },
        TaskID: job.ID,
    }, nil
}

// AwaitTask blocks until the job is done. Poll it, subscribe to it, wait on a
// channel — whatever the service offers.
func (t *indexTool) AwaitTask(ctx context.Context, task agents.BackgroundTaskRef, progress agents.ProgressReporter) (agents.BackgroundResult, error) {
    for {
        job, err := t.client.Job(ctx, task.TaskID)
        if err != nil {
            return agents.BackgroundResult{}, err
        }
        progress.Report(ctx, agents.ToolProgress{
            Progress: job.Done, Total: job.Total, Message: job.Phase,
        })
        if job.Finished {
            return agents.BackgroundResult{Output: job.Summary}, nil
        }
        time.Sleep(5 * time.Second)
    }
}

Implementing AwaitTask is what makes a tool a background tool, and NewBackgroundTool is one implementation of it. A TaskID from a tool without it fails the run — the work has already started, and nothing would ever report it. Anything the wait needs beyond the task id travels on ToolCallResponse.TaskPayload, and comes back as BackgroundTaskRef.Payload.

Where the result lands. When the task finishes, the agent looks at the thread:

  • a run is still going — the result joins its queue and is folded in at the next iteration boundary, the same cadence as a steering message;
  • the agent is idle — a new run starts with the result as its input, so the agent reports back without being asked.

After a handoff the task belongs to the agent the run entered at, not to the specialist that started it: a specialist reached by handoff is running inside someone else's run, so its own history is not that conversation and its own broker is not that stream. The result therefore wakes the root agent, which can route back into the specialist by sticky handoff.

Either way the result arrives as its own turn rather than as a second output for the original call, which is not something a provider will accept: that call was answered the moment the tool returned. BackgroundResult.Output is a *responses.FunctionCallOutputMessage — the same shape a tool returns from Execute — and its content blocks are carried into that turn intact, so an image or a file survives the trip.

Events on the run's stream. Starting a task emits a background_task.started chunk on the run that started it, carrying the tool call it belongs to and the stream the task will publish progress on:

{"type":"background_task.started","task_id":"job-41ff","call_id":"call_1",
 "tool_name":"index_docs","stream_id":"…"}

When the result lands, background_task.completed is published on the thread's stream carrying the same identifiers — announced by the delivery itself, which has the task, the call and the tool in hand. The agent loop is not involved: what it receives is an ordinary user turn, because the call that started the task was answered when the tool returned and a provider will not accept a second output against it, so it would have to be told what it was looking at.

On an idle thread the announcement is published in the moment between the delivery claiming the channel and the woken run opening on it — so it arrives before that run's first chunk. Readers hold back what precedes a run and emit it once the run has opened, which keeps RUN_STARTED first as AG-UI requires.

Over AG-UI both arrive as CUSTOM events (hastekit.background_task_started / ..._completed).

Progress. The reporter handed to AwaitTask publishes the same tool.progress chunks a tool can emit during Execute, keyed to the call that started the task — so a client updates the row it already drew rather than growing a new one.

Each task streams on a channel of its own, not the thread's. The thread's channel belongs to whichever run holds it, and a run claiming it resets the transcript — so a task publishing there would have its progress wiped by the next turn, and what survived would be interleaved into another run's stream keyed to a call that run never made. On its own channel, progress survives whatever the thread does, replays to a client that subscribes late, and the channel closes when the task ends.

The channel id is hastekit.StreamIDForTask(namespace, threadID, taskID), and is also recorded on the run's BackgroundTasks entry — so a UI can either derive it or read it, and decide for itself whether to watch:

taskStream := hastekit.StreamIDForTask("user-123", threadID, "job-41ff")
chunks, err := broker.Subscribe(ctx, taskStream)

Task ids are expected to be unique per task: two tasks sharing an id share a channel.

Waiting for tasks. agent.WaitForBackgroundTasks() blocks until everything in flight has been delivered. No run waits on it — that is the point — but a process shutting down should.

Under a durable runtime. The wait has to outlive the call that started it, which a goroutine cannot do once the activity or step it ran in has ended. Each runtime supplies its own way of keeping one, so the tool interface is unchanged and only the machinery behind it differs:

Runtime How the wait is kept How an idle thread is woken
Local a goroutine agent.Execute
Temporal a child workflow, ParentClosePolicy: ABANDON, running AwaitTask as a long activity a child _AgentWorkflow
Restate a one-way send to BackgroundTaskService, whose Await handler journals each step a one-way WorkflowSend to AgentWorkflow

The delivery decision itself — join a live run, or claim the thread and start one — is agents.DeliverBackgroundResult, shared by all three. Getting it wrong is the same mistake everywhere: joining a run that has ended strands the result, and starting one that has not leaves two runs writing a single stream.

An agent with no runner at all fails a tool that returns a TaskID, with agents.ErrBackgroundUnsupported, rather than starting work nothing will ever report. Supply your own with AgentOptions.BackgroundRunner to teach another runtime the trick.

MCP tools cannot start background tasks yet — the protocol has no task concept for the client to carry.

Skills

Configure one or more skill sources with AgentConfig.Skills. A filesystem source loads folders containing SKILL.md and optional supporting files:

skills/
├── changelog/
│   ├── SKILL.md
│   └── references/style.md
└── review/
    └── SKILL.md

Each SKILL.md needs YAML frontmatter with a description and an optional name (defaulting to the folder name), followed by the instructions.

builtins, err := hastekit.NewDirSkillStore("./skills")
if err != nil { log.Fatal(err) }
agent := hastekit.MustNewAgent(&hastekit.AgentConfig{
    Name: "Release_Agent",
    LLM: model,
    SkillClient: hastekit.NewSkillClient(builtins),
    Instruction: hastekit.NewPrompt("Help prepare releases.",
        prompts.WithResolver(prompts.DefaultResolvers()...)),
})

Skills work like MCP servers. skills.NewClient(builtIn, skills.WithUserStore(user)) reads two skills.Stores (List, Get): the built-in store's skills are global (developer-owned), the user store's are each namespace's own. A store does not know which role it plays — the client reads the built-in store under the empty namespace and the user store under the run's — so any store fills either slot: a folder (skills.NewDirStore), an embed.FS or other fs.FS (skills.NewFSStore), inline bundles (skills.NewInlineStore), a skills.MutableStore such as NewFileStore or NewS3Store, or your own skills.Store. Share the user store across agents and give each agent its own built-in store. The names match MCP's mcpclient.Store and mcpclient.MutableStore.

skills.Filter(store, names) gives an agent only the named skills of a store and drops the rest, including later uploads; filter either store, or both:

everything := skills.NewClient(builtins, skills.WithUserStore(store)) // default agent
custom := skills.NewClient(skills.Filter(builtins, picks), skills.WithUserStore(skills.Filter(store, picks))) // picks from both

Global skills are always on: users cannot turn them off, and a global shadows a user skill with the same name. Users' own skills are on unless the run disables them with Input.Skills.Disable. The /skills routes refuse the empty namespace, so users never write what a built-in store reads. Each run discovers added and removed skills without reconstructing the agent; its catalog becomes a snapshot for that run, and content is read on demand. An empty namespace sees globals only.

The prompt lists skill names such as changelog. One read_skill tool reads instructions and allowed resources for every enabled skill. Include ResolveSkills in the prompt resolvers to advertise the catalog. Resend the selection on new turns and approval resumes. The embedded UI's Skills menu lists the user's own skills from /skills, which is not scoped to an agent, and remembers choices once per browser. Temporal and Restate execute listing and reads within durable steps.

NewFileStore and NewS3Store implement the pluggable MutableStore interface for uploaded skills. Enable library APIs and uploads with web.Serve(":8080", registry, agui.WithSkillStore(store)); uploads cannot reuse a registered agent's global skill name. See persistent skills.

See the dynamic skills example for Go and UI usage.

Prompt resolvers

The system prompt is built by a chain of resolvers, each handed what the last produced along with the run's dependencies:

type PromptResolverFn func(prompt string, deps *agents.Dependencies) (string, error)

A prompt starts with an empty chain and is used exactly as written — nothing appended, no templating. prompts.DefaultResolvers() is the standard set: ResolveSkills, ResolveHandoffs, ResolveDeferredTools, ResolveTemplate — the sections the agent contributes, then the {{ placeholder }} pass over the whole thing. Pass what you want, in the order you want; repeated calls accumulate:

hastekit.NewPrompt("You help maintain this project's releases.",
    prompts.WithResolver(prompts.DefaultResolvers()...),
    prompts.WithResolver(func(prompt string, deps *agents.Dependencies) (string, error) {
        return prompt + "\n\n## House rules\n\nBe brief.", nil
    }),
)
Middlewares

A middleware wraps what the agent does, middleware-style, so cross-cutting concerns — auth, budgets, quotas, audit, attachments — live in one place instead of inside every tool. A middleware can observe a call, change what goes in or what comes out, or answer in place of the real call.

ToolCallMiddleware wraps every tool call; ModelCallMiddleware wraps every call to the model. hastekit.Middleware is both. Embed the no-op half you have nothing to say on:

// A budget check that has no interest in tools.
type credits struct {
    agents.NoopMiddleware
}

func (c *credits) WrapModelCall(next agents.ModelCallFunc) agents.ModelCallFunc {
    return func(ctx context.Context, call *agents.ModelCall, req *responses.Request) (*responses.Response, error) {
        if balanceFor(call.RunContext) <= 0 {
            // Answering is kinder than failing: the run ends with a message the
            // user can read rather than an error they cannot.
            return agents.ModelCallText("You're out of credits — top up to continue."), nil
        }
        resp, err := next(ctx, call, req)
        if err != nil {
            return nil, err
        }
        recordSpend(call.RunContext, resp.Usage) // this one call's usage
        return resp, nil
    }
}

agent := hastekit.MustNewAgent(&hastekit.AgentConfig{
    Name:  "Assistant",
    LLM:   client.Model("OpenAI/gpt-4o-mini"),
    Tools: []hastekit.Tool{weatherTool},
    Middlewares: []agents.Middleware{&credits{}},
})

The tool-call side is the same, with the tool the call is against handed over alongside it. Combined with annotations, a policy middleware is a few lines:

type policy struct {
    agents.NoopMiddleware
}

func (p *policy) WrapToolCall(next agents.ToolCallFunc) agents.ToolCallFunc {
    return func(ctx context.Context, tool *agents.BaseTool, call *agents.ToolCall) (*agents.ToolCallResponse, error) {
        if tool.Annotations.IsDestructive() && !allowed(call.RunContext, call.Name) {
            // The tool never runs, and this stands in as its output.
            return agents.ToolCallResult(call, "Denied by policy."), nil
        }
        resp, err := next(ctx, tool, call)
        audit(call.Name, call.RunContext, err)
        return resp, err
    }
}

Notes:

  • Answering is a return, not an error. Return a result without calling next and the real call never happens; the model reads what you returned. An error of your own ends the run, and under Temporal or Restate it is not retried — what you refused once you would refuse again (agents.IsToolCallAborted, agents.IsModelCallAborted). An error next hands back is the tool's or the provider's — pass it through as it came, wrapped or not, and it keeps the classification the runtime gives that kind of failure.
  • Run context comes along. call.RunContext is the per-run map you set on AgentInput, so per-tenant data (a JWT, an org id) is available without threading it through every tool.
  • The tool arrives as plain data. tool is the same *agents.BaseTool its GetToolDescriptor returns — name, schema, annotations, meta — because the real tool may be a proxy for one running in another process. It is always non-nil.
  • Middlewares nest in registration order, the first outermost. The first registered sees a request first and a result last. A middleware that answers without calling next skips every middleware inside it.
  • Wraps run inside the step that makes the call, never as steps of their own. Under Temporal and Restate that is the tool activity or run step and the LLM activity or run step; locally it is the loop. What a wrap hands next is what the tool or provider sees, and what it returns is what the loop keeps — so WrapToolCall can rewrite a result before it is journaled, which is how the attachment middleware keeps file bytes out of every journal and transcript. Because a wrap is not journaled, it may run again if its step retries: keep it idempotent, and never write to the request or result you were handed.
  • A note for this call only. To put something in front of the model once, hand next a copy of the request with a message appended. The loop keeps its own request, so the note is never stored and does not accumulate — the same treatment the loop gives its own "one turn left" reminder.
  • State is read-only here. call.State is a snapshot of the run's scratchpad, on model calls and tool calls alike. Tools write to it through ToolCallResponse.StateUpdates; a wrap reads what they wrote.

The SDK installs agents.StopMiddleware outside the configured tool and model middleware. It watches the call's stream while the entire chain runs, including attachment resolution. Tools retain their cancellation grace period; model calls unwind through their context so streaming callbacks cannot outlive the step. Custom model middleware must honor context cancellation.

Temporal installs it inside each tool/MCP/model activity, and Restate inside the corresponding restate.Run callback. Workflow proxies do not watch live stop signals. The worker translates stopped calls into non-retryable Temporal errors or terminal Restate errors, and replay consumes that recorded outcome. Background waits continue independently of the parent run's stop signal. RunStoppableTool has been replaced by StopMiddleware.WrapToolCall; the generic RunStoppable primitive remains available for custom runtime adapters.

History and prompt middleware use the same registration:

type promptPolicy struct { agents.NoopMiddleware }

func (p *promptPolicy) WrapGetPrompt(next agents.GetPromptFunc) agents.GetPromptFunc {
    return func(ctx context.Context, deps *agents.Dependencies) (string, error) {
        prompt, err := next(ctx, deps)
        if err != nil { return "", err }
        return prompt + "\nCite sources for factual claims.", nil
    }
}

// On agents.AgentOptions or AgentConfig:
// Middlewares: []agents.Middleware{&promptPolicy{}},

Implement WrapLoadMessages(next agents.LoadMessagesFunc) and WrapSaveMessages(next agents.SaveMessagesFunc) to wrap conversation persistence. Their request structs carry the namespace, thread/run IDs, and, for saves, messages and metadata. Return without calling next to serve cached history or skip a write. Pass copies when modifying inputs or returned messages. WrapGetPrompt(next agents.GetPromptFunc) receives the existing Dependencies. History/prompt errors follow the underlying operation's runtime retry policy.

Custom runtime adapters can use ExecuteLoadMessagesWithMiddleware, ExecuteSaveMessagesWithMiddleware, and ExecuteGetPromptWithMiddleware inside their existing steps, or bind the real providers with WrapHistoryPersistence and WrapPromptProvider. Middleware results are returned by that same step; there are no separate middleware activities. Summary writes, ID/clock generation, thread listing and full-transcript reads keep their existing behavior.

Agent retry and fallback policies can be configured alongside other middleware:

import agentmiddleware "github.com/hastekit/agent-sdk-go/pkg/agents/middleware"

// In agents.AgentOptions:
Middlewares: []agents.Middleware{
    agentmiddleware.NewFallbackModels("Anthropic/claude-sonnet-4-5"),
    agentmiddleware.NewRetry(agentmiddleware.RetryConfig{MaxAttempts: 3}),
    // Attempt tracing and attachment middleware go inside these policies.
},

Fallback is outermost so each model gets its own retry budget. Targets use Provider/model; the model client's existing provider configuration supplies credentials. The SDK's gateway-backed model client supports explicit targets; custom providers can implement agents.ModelTargetProvider. Changing targets never changes the agent's bound model or the request stored in history. Retry uses the gateway's transient-error classification, jittered backoff, and Retry-After handling. Context cancellation and agent stop always end the chain.

Retries and fallback stop after the first published chunk, including stream metadata. A failure after publication, or a policy's final failure, becomes a terminal model error in Temporal and Restate so runtime error retries do not restart the entire policy. All attempts execute inside the same model activity or run step; short backoff waits occupy that execution. Individual attempts are not separately journaled: worker loss or activity timeout can still restart the step, and external stream delivery is not exactly-once. Budget activity timeouts for the whole chain. Avoid also installing gateway retry/fallback middleware under an agent policy, which would multiply attempts.

Each attempt gets a fresh top-level request and call-metadata copy. As with all agent middleware, nested content is read-only: copy any nested values before modifying them. Middleware inside retry can execute more than once; accounting and tracing should distinguish attempts from the overall call. Model-specific options and provider-owned file IDs must be compatible with fallback targets; application attachment references can be resolved by attachment middleware.

Migration: Hooks is now Middlewares, agents.Hook is agents.Middleware, and ExecuteWrappedModelCall / ExecuteWrappedToolCall are now ExecuteModelCallWithMiddleware / ExecuteToolCallWithMiddleware. Built-in attachment middleware lives in pkg/agents/middleware as AttachmentMiddleware. Embed agents.NoopMiddleware for the operations you do not override. The root package exposes AgentMiddleware; its existing Middleware alias continues referring to gateway middleware.

Limiting tool response size

ToolResponseMiddleware replaces oversized tool output with a bounded text excerpt. When an attachment store is configured, it also saves the full response and includes file metadata. It runs inside the tool's execution step, before the result enters conversation or workflow history:

Middlewares: []agents.Middleware{
    middleware.NewToolResponseMiddleware(middleware.ToolResponseMiddlewareConfig{
        Store:            attachmentStore,
        MaxResponseBytes: 32 << 10, // 32 KiB, including the replacement metadata
        MaxSummaryBytes:  2 << 10,  // 2 KiB excerpt; no extra LLM call
    }),
    middleware.NewAttachmentMiddleware(middleware.AttachmentMiddlewareConfig{
        Store: attachmentStore,
    }),
},

Text output is saved verbatim as .txt or .json; multipart output is saved as a JSON array. Filenames use tool-response-<call_id>, remaining stable across retries of the same call. The store may choose a distinct stored filename to keep uploads immutable. The limit counts UTF-8 bytes for strings and JSON bytes for multipart content, rather than tokens. Output at or below the limit is unchanged. Zero or negative settings use the defaults shown above.

The replacement includes file_id, original_filename, mime_type, size_bytes, summary, and the store's mount_path when configured. The excerpt previews text; for multipart results it also reports content counts without repeating inline media bytes. It is shortened further if necessary to keep the replacement within MaxResponseBytes. Attachment hydration does not reload the offloaded file into the model request. Provide attachment-reading tools or a sandbox mount so the agent can inspect the saved response selectively.

Store is optional. Without it, the replacement includes only the original size, media type, excerpt, and guidance to request fewer results, paginate, filter, or use another tool to read smaller sections from the source. It explicitly says the full response was not saved and contains no file ID, filename, or mount path.

Uploads use ToolCall.Namespace and ToolCall.SessionID. IDs, state updates, interrupts, and background-task metadata are preserved and are not counted toward the output limit. Tool errors pass through unchanged. Upload or metadata failures from a configured store, and a limit too small to hold replacement metadata, abort the middleware instead of leaking the oversized result. The store's own upload limit still applies; configure it for the largest result you expect to offload. Retried tool steps may create another immutable attachment.

When combining the two middlewares, register the response limiter first as shown. Results pass through attachment externalization first, then through the size check.

Conversation History

Enable conversation memory across interactions:

// Create a file-backed conversation manager
memory, err := hastekit.OpenFileHistory("./conversations")
if err != nil { log.Fatal(err) }
defer memory.Close()

agent := hastekit.MustNewAgent(&hastekit.AgentConfig{
    Name:        "Memory Agent",
    Instruction: hastekit.NewPrompt("You are a helpful assistant."),
    LLM:         model,
    History:     memory, // Enable history
})

threadID := uuid.NewString()

// First interaction
handle, err := agent.Execute(context.Background(), &agents.AgentInput{
    Namespace: "user-123", // Bucket conversations by namespace
    ThreadID:  threadID,
    Message: history.Message{
        Messages: []responses.InputMessageUnion{
            responses.UserMessage("My name is Alice."),
        },
    },
})
out, err := handle.Result()

// Continue conversation — pass the same ThreadID to keep context.
handle, err = agent.Execute(context.Background(), &agents.AgentInput{
    Namespace: "user-123",
    ThreadID:  threadID,
    Message: history.Message{
        Messages: []responses.InputMessageUnion{
            responses.UserMessage("What's my name?"),
        },
    },
})
out, err = handle.Result()

The built-in memory and file history adapters scope thread IDs, run IDs, and summaries by namespace. The same IDs can coexist in different namespaces. Reads use the exact namespace, including the empty namespace; only ListThreads treats an empty namespace as a request to list all namespaces.

Passing ThreadID alone continues from the thread's tip. To branch from a specific earlier turn instead — a retry, or an edit of an earlier message — set PreviousRunID to the RunID of the run you want to continue from:

out, _ := handle.Result()

handle, err = agent.Execute(ctx, &agents.AgentInput{
    Namespace:     "user-123",
    ThreadID:      threadID,
    PreviousRunID: out.RunID, // continue from this run, not the thread tip
    Message:       history.Message{ /* ... */ },
})
Reading a thread back

To render a thread — a chat window, an audit view — use LoadTranscript:

transcript, err := memory.LoadTranscript(ctx, "user-123", threadID)

It returns the thread as written. That is deliberately not what the agent reads for itself: the agent's own history load is summary-aware, replacing the turns a summary covers with the summary, which is what keeps a long thread inside the context window. Right for the model, wrong for a UI — asking the summary-aware path for a whole summarized thread is exactly when the substitution kicks in, and the window loses its own early turns.

Adapters implement history.TranscriptReader to support this; the built-in in-memory and file adapters both do.

Durable Agents

Create fault-tolerant agents that survive crashes and failures:

Register worker agents with a runtime instance. Registrations are isolated by instance and must finish before Serve starts. Register specialists as well as entry agents when they execute through that runtime. Do not mutate handoffs or configuration while the worker is serving.

broker, err := hastekit.NewRedisStreamBroker("localhost:6379", "", 0)
if err != nil { log.Fatal(err) }

rt, err := hastekit.NewTemporalRuntime("localhost:7233", broker)
if err != nil { log.Fatal(err) }
defer rt.Close()

agent, err := hastekit.NewAgent(&hastekit.AgentConfig{
    Name: "DurableAgent", LLM: model,
    Instruction: hastekit.NewPrompt("You are a helpful assistant."),
}, hastekit.WithRuntime(rt))
if err != nil { log.Fatal(err) }

registry := hastekit.NewRegistry()
if err := registry.Register(agent); err != nil { log.Fatal(err) }
// The invoking application's HTTP server uses hastekit.NewHTTPHandler(registry).
// The worker process blocks here until ctx is canceled:
if err := rt.Serve(ctx); err != nil { log.Fatal(err) }

Both runtime constructors require a non-nil broker; there is no in-memory fallback. Use Redis or another shared broker across processes. An explicitly supplied in-memory broker is suitable only when callers and workers share the same instance in one process. WithRuntime(rt) gets the broker from the runtime; ordinary local agents still default to an in-memory broker.

For Restate, create NewRestateRuntime("http://localhost:8080", broker) with the Restate ingress URL. Construct agents with NewAgent and WithRuntime in the same way, then run rt.Serve(ctx, "localhost:9081"). Register that local service address as a Restate deployment. The ingress URL and the service listen address are separate. Serve waits for shutdown; Close stops serving and releases owned resources.

See the Temporal example and Restate example for worker and HTTP serving in one process with signal-driven shutdown.

Documentation

Examples

Explore complete working examples in the documentation repository:

Agents

Supported Providers

Provider Text Streaming Tool Calling Vision Embeddings Image Gen Image Edit Speech Transcription
OpenAI ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅
Anthropic ✅ ✅ ✅ ✅ ❌ ❌ ❌ ❌ ❌
Gemini ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅
xAI ✅ ✅ ✅ ✅ ❌ ✅ ✅ ✅¹ ❌
Bedrock ✅ ✅ ✅ ✅ ❌ ❌ ❌ ❌ ❌
ElevenLabs ❌ ❌ ❌ ❌ ❌ ❌ ❌ ✅ ✅
Sarvam ✅² ✅² ✅² ✅² ❌ ❌ ❌ ✅³ ✅
DeepSeek ✅² ✅² ✅² ✅² ❌ ❌ ❌ ❌ ❌
Moonshot (Kimi) ✅² ✅² ✅² ✅² ❌ ❌ ❌ ❌ ❌
Z.ai (GLM) ✅² ✅² ✅² ✅² ❌ ❌ ❌ ❌ ❌

¹ Non-streaming only — xAI has no NewStreamingSpeech. ² Served by the chat-completions bridge (see below); vision depends on the model. ³ NewStreamingSpeech synthesizes in one call and emits a single audio delta — Sarvam's incremental TTS is a WebSocket API, not an HTTP stream.

Text is the Responses API (NewResponses), which is what agents use. OpenAI additionally implements the older Chat Completions API (NewChatCompletion / NewStreamingChatCompletion); so do the bridged providers below.

Sarvam, DeepSeek, Moonshot and Z.ai speak the OpenAI /chat/completions format but have no /responses endpoint. They are served by providers/openaicompat, a generic translation in both directions: a native Responses request becomes a chat completion (instructions → system message, parallel function calls collapsed onto one assistant message, tool results → tool messages, text.format → response_format), and the reply — including a streamed one — is reassembled into Responses output items and events. reasoning_content becomes a native reasoning item. Server-side tools (web search, image generation, code interpreter) have no equivalent and are dropped from the request. Default base URLs: Sarvam https://api.sarvam.ai, DeepSeek https://api.deepseek.com, Moonshot https://api.moonshot.ai/v1, Z.ai https://api.z.ai/api/paas/v4 — each overridable through BaseURL on the provider config (Moonshot's mainland endpoint, Z.ai's Coding Plan or Zhipu endpoints, a self-hosted proxy).

Any other OpenAI-compatible endpoint can be added the same way: point openaicompat.NewClient at its base URL.

ProviderOllama and ProviderOpenRouter are not in the table because their capabilities aren't the SDK's to state: both are served by the OpenAI client, so every method is wired up and each call is passed straight through. What actually answers depends on the endpoint and the model behind it. OpenRouter defaults to https://openrouter.ai/api/v1; Ollama needs an explicit BaseURL on its provider config.

A ❌ is not a graceful "unsupported" error. Unimplemented methods fall through to the embedded base provider, where the text and embedding methods panic and the media methods return (nil, nil) — so a call for a capability a provider doesn't have will either crash or hand back a silent nil. Check this table before reaching for a non-text method on a non-OpenAI provider.

Architecture

agent-sdk-go/
└── pkg/
    ├── agents/              # Agent orchestration, middlewares, tool annotations
    │   ├── runtime/         # Durable execution runtimes
    │   │   ├── restate_runtime/
    │   │   └── temporal_runtime/
    │   ├── agentstate/      # Run status and state
    │   ├── history/         # Conversation management
    │   ├── mcpclient/       # MCP tool integration
    │   ├── prompts/         # Prompt construction
    │   ├── sandbox/         # Sandboxed execution
    │   ├── streambroker/    # Stream brokers (memory, Redis)
    │   └── tools/           # Built-in tools
    ├── agui/                # AG-UI protocol + embedded chat UI
    ├── gateway/             # LLM gateway
    │   ├── llm/             # LLM request/response types
    │   └── providers/       # Provider implementations
    │       ├── openai/      # anthropic, gemini, xai, bedrock,
    │       ├── openaicompat/# chat-completions <-> responses bridge
    │       └── sarvam/      # deepseek, moonshot, zai, elevenlabs, ...
    ├── hastekitgateway/     # HasteKit Gateway adapters
    ├── knowledge/           # Knowledge / retrieval
    ├── telemetry/           # Tracing and metrics
    └── utils/               # Utilities

Runnable examples live in the documentation repository — see Examples above.

Contributing

We welcome contributions! Please see our contributing guidelines for details.

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Support


Attachments backed by your own storage

Images and documents can use an immutable attachment://... reference in file_id instead of storing base64 in conversation history. The SDK includes a private filesystem store, replaceable Store/UploadStore interfaces, and a shared bounded cache. One middleware, middleware.NewAttachmentMiddleware, keeps the bytes out of everything durable in both directions: it stores what a tool returns inline and replaces it with a reference, externalizes complete model-generated images before the response leaves the model call, and resolves every reference back into inline provider data inside a later model call. Generated-image items keep the shared Responses shape by carrying the reference in image_generation_call.result. Complete live image events carry that reference too, while binary partial-image previews are suppressed; other streaming remains unchanged. Without the middleware, native provider streaming still passes through as before. Add the middleware to an agent to turn attachment support on for it; the LLM client is not involved, and sends exactly the request it is handed.

See owned attachments for local setup, caching, and Temporal/Restate configuration.

Pass agui.WithAttachmentStore(store) to the embedded web handler to enable /api/agui/attachments/ upload/download APIs and the chat file picker. The sample chat demonstrates the full attachment flow. Uploads accept original files including DOCX, CSV, TXT and audio. Images use image inputs; other files use native file inputs. The middleware resolves file references to base64 data with the stored MIME type and filename; it does not extract text, transcribe, or convert formats. The selected provider decides whether it supports a file's type. Non-image files are served as downloads, and upload/dispatch size limits still apply.

YAML workflows

Build workflows from YAML and expose them as agent tools with human-input pause/resume. See the workflow guide and the approval example.

Skill names have no source prefix. When names collide, the last entry in AgentConfig.Skills wins, replacing the description, policy, allowed files, and resolver. Within a source, the last listed entry wins. Selection policies apply after merging. Source names must still be unique for runtime registration.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ProviderOpenAI     = llm.ProviderNameOpenAI
	ProviderAnthropic  = llm.ProviderNameAnthropic
	ProviderBedrock    = llm.ProviderNameBedrock
	ProviderElevenLabs = llm.ProviderNameElevenLabs
	ProviderGemini     = llm.ProviderNameGemini
	ProviderXAI        = llm.ProviderNameXAI
	ProviderOllama     = llm.ProviderNameOllama
	ProviderOpenRouter = llm.ProviderNameOpenRouter
	ProviderSarvam     = llm.ProviderNameSarvam
	ProviderDeepSeek   = llm.ProviderNameDeepSeek
	ProviderMoonshot   = llm.ProviderNameMoonshot // Kimi models
	ProviderZAI        = llm.ProviderNameZAI      // GLM models
)
View Source
var ErrAgentAlreadyRegistered = errors.New("agent already registered")

ErrAgentAlreadyRegistered indicates a duplicate name in one registry.

View Source
var ErrStreamOverflow = agents.ErrStreamOverflow
View Source
var ErrWorkflowAlreadyRegistered = workflow.ErrAlreadyRegistered

ErrWorkflowAlreadyRegistered indicates a duplicate workflow name in a registry.

View Source
var FilterMCPStore = mcpclient.Filter

FilterMCPStore lists only the named servers of an MCP config store, each narrowed to the tools its ToolFilter allows.

View Source
var FilterSkillStore = skills.Filter

FilterSkillStore lists only the named skills of a store.

View Source
var NewDirSkillStore = skills.NewDirStore

NewDirSkillStore serves a folder of skills, rediscovered on every listing.

View Source
var NewFSSkillStore = skills.NewFSStore

NewFSSkillStore supports embed.FS and other io/fs implementations.

View Source
var NewHandoff = agents.NewHandoff
View Source
var NewMCPClient = mcpclient.NewClient

NewMCPClient reads global servers from a built-in store, such as an InlineStore, and each namespace's own from the store WithUserMCPStore gives.

View Source
var NewPrompt = prompts.New
View Source
var NewPromptWithLoader = prompts.NewWithLoader
View Source
var NewSkillClient = skills.NewClient

NewSkillClient reads global skills from a built-in store, such as a folder, and each namespace's own from the store WithUserSkillStore gives, such as one of users' uploads.

View Source
var WithMCPCredentials = mcpclient.WithCredentials

WithMCPCredentials supplies an MCP client's shared credential resolution.

View Source
var WithMCPSchemaCache = mcpclient.WithSchemaCache

WithMCPSchemaCache supplies an MCP client's shared discovery caching.

View Source
var WithUserMCPStore = mcpclient.WithUserStore

WithUserMCPStore reads each namespace's own MCP servers from a store.

View Source
var WithUserSkillStore = skills.WithUserStore

WithUserSkillStore reads each namespace's own skills from a store.

Functions

func NewOutputFormatJSONSchema

func NewOutputFormatJSONSchema(v any, strict bool) map[string]any

func NewOutputSchema

func NewOutputSchema(v any) map[string]any

func NewRedisStreamBroker

func NewRedisStreamBroker(redisEndpoint string, password string, db int) (agents.StreamBroker, error)

func NewRoutineService added in v0.0.17

func NewRoutineService(registry *AgentRegistry, store routines.Store) *routines.Service

NewRoutineService creates scheduled tasks targeting agents from this registry, which every namespace shares. For agents namespaces create at run time, use routines.NewService(store, &routines.AgentExecutor{Registry: agentconfigRegistry}). Share the service between routines.NewHTTPHandler, routines.Tools, and a routines.Scheduler implementation. The application owns the store and scheduler lifetime.

func NewStreamBroker

func NewStreamBroker() (agents.StreamBroker, error)

func NewWorkflowHTTPHandler added in v0.0.17

func NewWorkflowHTTPHandler(registry *AgentRegistry, config workflow.HTTPConfig) *workflow.HTTPHandler

NewWorkflowHTTPHandler serves independent workflow start/status/resume routes. Keep the returned handler for the server's lifetime: it owns bounded, in-memory HTTP run checkpoints. It does not require an agent or model.

func UserTurn added in v0.0.17

func UserTurn(text string) history.Message

UserTurn creates a user message bundle for Input.Message.

Types

type APIKeyConfig

type APIKeyConfig = gateway.APIKeyConfig

type Agent

type Agent = agents.Agent

func MustNewAgent added in v0.0.17

func MustNewAgent(cfg *AgentConfig, opts ...AgentOption) *Agent

MustNewAgent is NewAgent for static configuration where failure is a programmer error.

func NewAgent

func NewAgent(cfg *AgentConfig, opts ...AgentOption) (*Agent, error)

NewAgent validates configuration, constructs an agent, and registers its resolved configuration with the supplied runtime before returning. History, runtime and broker resources remain owned by the caller.

type AgentConfig

type AgentConfig struct {
	Name          string
	LLM           llm.Provider
	Output        map[string]any
	Tools         []Tool
	Handoffs      []*agents.Handoff
	MCPClient     agents.MCPClient
	MaxLoops      *int
	History       *history.CommonConversationManager
	Instruction   agents.SystemPromptProvider
	Parameters    responses.Parameters
	StickyHandoff bool

	// SkillClient lists the agent's global skills plus the namespace's own, and
	// serves enabled ones through read_skill. See skills.NewClient.
	SkillClient agents.SkillClient

	// ClientTools configures tools the client runs itself (AG-UI frontend
	// tools): how long a call waits for the client's result before the run
	// pauses on it. The zero value waits agents.DefaultClientToolTimeout.
	ClientTools agents.ClientToolOptions

	// Middlewares wrap model/tool calls, history loads/saves and prompt
	// retrieval. Embed agents.NoopMiddleware and override selected methods.
	Middlewares []agents.Middleware
}

type AgentMiddleware added in v0.0.17

type AgentMiddleware = agents.Middleware

AgentMiddleware wraps agent operations. Embed agents.NoopMiddleware and override the Wrap methods relevant to your implementation. The root Middleware alias remains the gateway/provider middleware API.

type AgentOption

type AgentOption func(options *agents.AgentOptions)

func WithRuntime

func WithRuntime(runtime agents.Runtime) AgentOption

WithRuntime selects a runtime and uses its StreamBroker. A nil runtime uses local execution with a default in-memory broker. NewAgent registers the resolved configuration with the runtime; start Temporal/Restate workers with Serve.

type AgentRegistry

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

AgentRegistry is an instance-owned, concurrency-safe registry of agents and workflows. Its zero value is ready to use. Names and registered graphs must not be mutated after registration.

func NewRegistry added in v0.0.17

func NewRegistry() *AgentRegistry

func (*AgentRegistry) Agent

func (r *AgentRegistry) Agent(name string) (*agents.Agent, bool)

func (*AgentRegistry) AgentNames

func (r *AgentRegistry) AgentNames() []string

func (*AgentRegistry) Register added in v0.0.17

func (r *AgentRegistry) Register(agent *Agent) error

func (*AgentRegistry) RegisterWorkflow added in v0.0.17

func (r *AgentRegistry) RegisterWorkflow(name string, compiled *workflow.Compiled, options ...workflow.InvokeOption) error

RegisterWorkflow registers an independently invokable workflow alongside agents.

func (*AgentRegistry) RunWorkflow added in v0.0.17

func (r *AgentRegistry) RunWorkflow(ctx context.Context, name string, in *workflow.Input, options ...workflow.InvokeOption) (*workflow.Input, error)

RunWorkflow executes or resumes a workflow by its registered name.

func (*AgentRegistry) Workflow added in v0.0.17

func (r *AgentRegistry) Workflow(name string) (*workflow.Compiled, bool)

func (*AgentRegistry) WorkflowNames added in v0.0.17

func (r *AgentRegistry) WorkflowNames() []string

type BackgroundFunctionTool added in v0.0.17

type BackgroundFunctionTool[T any, S any] struct {
	*FunctionTool[T, S]
	// contains filtered or unexported fields
}

BackgroundFunctionTool is NewTool for work that does not finish inside the call. See NewBackgroundTool.

func NewBackgroundTool added in v0.0.17

func NewBackgroundTool[T any, S any](work BackgroundToolFunc[T, S], opts ...ToolOption) *BackgroundFunctionTool[T, S]

NewBackgroundTool turns a long-running func into a tool that answers at once and reports its result when it is done.

indexTool := hastekit.NewBackgroundTool(
    func(ctx context.Context, in IndexArgs, progress hastekit.ProgressReporter) (IndexResult, error) {
        for i, doc := range in.Docs {
            progress.Report(ctx, hastekit.ToolProgress{
                Progress: float64(i), Total: float64(len(in.Docs)), Message: doc.Name,
            })
            index(doc)
        }
        return IndexResult{Indexed: len(in.Docs)}, nil
    },
    hastekit.WithName("index_docs"),
    hastekit.WithDescription("Index documents. Takes a while."),
)

The model gets an immediate answer naming the task, the run carries on, and whatever the func returns is delivered to the thread when it returns — into the run that started it if that is still going, otherwise as a new run.

The work runs off the run's path, not inside it: in this process that means a goroutine of the agent's, and under Temporal or Restate the activity or invocation that runtime keeps for the task. That is why the func is given the arguments rather than closing over them — it may well run somewhere the call that started it never reached. Anything else it needs must travel the same way, in the arguments.

Progress is nil-safe: report freely, whether or not anyone is listening.

The return value is encoded like an ordinary tool's, unless it already is a tool output — a *responses.FunctionCallOutputMessage, a FunctionCallOutputContentUnion, or a responses.InputContent — in which case it travels as it is. That is how a task answers with an image or a file.

For work that has to be *started* now and only watched later — a job queued with another service, say — implement agents.BackgroundTool directly, which splits starting from waiting.

func (*BackgroundFunctionTool[T, S]) AwaitTask added in v0.0.17

AwaitTask runs the work. This is where the tool actually does its job, on whatever the runtime keeps alive past the call that started it.

func (*BackgroundFunctionTool[T, S]) Execute added in v0.0.17

Execute starts the task: it answers immediately with a task id, and keeps the call's arguments for the wait.

func (*BackgroundFunctionTool[T, S]) SetStartedMessage added in v0.0.17

func (t *BackgroundFunctionTool[T, S]) SetStartedMessage(fn func(taskID string) string)

type BackgroundTaskRef added in v0.0.17

type BackgroundTaskRef = agents.BackgroundTaskRef

BackgroundTaskRef identifies a running background task to the tool that started it.

type BackgroundToolFunc added in v0.0.17

type BackgroundToolFunc[T any, S any] func(ctx context.Context, in T, progress ProgressReporter) (S, error)

BackgroundToolFunc is the work a background tool does. It is handed the call's arguments and somewhere to report progress, and runs for as long as it needs to — the run that called the tool is long gone by the time it returns.

type Config

type Config struct {
	// ProviderConfigs is the provider configs, used for LLM calls
	ProviderConfigs []ProviderConfig
}

type FunctionTool

type FunctionTool[T any, S any] struct {
	// contains filtered or unexported fields
}

func NewTool

func NewTool[T any, S any](fn ToolFunc[T, S], opts ...ToolOption) *FunctionTool[T, S]

func (*FunctionTool[T, S]) Execute

func (t *FunctionTool[T, S]) Execute(ctx context.Context, params *agents.ToolCall) (*agents.ToolCallResponse, error)

func (*FunctionTool[T, S]) GetAnnotations

func (t *FunctionTool[T, S]) GetAnnotations() *agents.ToolAnnotations

GetAnnotations implements ToolConfig, which is how the per-hint options (WithReadOnly, WithDestructive, ...) amend the set rather than clobber it.

func (*FunctionTool[T, S]) GetMeta added in v0.0.14

func (t *FunctionTool[T, S]) GetMeta() map[string]any

GetMeta implements ToolConfig, letting WithMeta add to what is already there.

func (*FunctionTool[T, S]) GetToolDescriptor added in v0.0.16

func (t *FunctionTool[T, S]) GetToolDescriptor() *agents.BaseTool

GetToolDescriptor implements agents.Tool. A function tool keeps its state in its own fields rather than an embedded BaseTool, so the projection is built here — schema included, from the input type's own shape. Name is left empty: the tool has one name, and it is the one in ToolUnion.

func (*FunctionTool[T, S]) SetAnnotations

func (t *FunctionTool[T, S]) SetAnnotations(annotations *agents.ToolAnnotations)

SetAnnotations replaces the tool's annotations wholesale. The hint options (WithReadOnly, WithDestructive, ...) go through here too, each filling in one field of the current set.

func (*FunctionTool[T, S]) SetDeferred

func (t *FunctionTool[T, S]) SetDeferred(deferred bool)

func (*FunctionTool[T, S]) SetDescription

func (t *FunctionTool[T, S]) SetDescription(description string)

func (*FunctionTool[T, S]) SetMeta added in v0.0.14

func (t *FunctionTool[T, S]) SetMeta(meta map[string]any)

func (*FunctionTool[T, S]) SetName

func (t *FunctionTool[T, S]) SetName(name string)

func (*FunctionTool[T, S]) SetNeedsApproval

func (t *FunctionTool[T, S]) SetNeedsApproval(needsApproval bool)

type HTTPHandler

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

func NewHTTPHandler

func NewHTTPHandler(registry *AgentRegistry) *HTTPHandler

func (*HTTPHandler) ServeHTTP

func (h *HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Handoff

type Handoff = agents.Handoff

type History

func MustNewFileHistory added in v0.0.17

func MustNewFileHistory(path string, opts ...history.ConversationManagerOptions) *History

MustNewFileHistory panics if the history cannot be opened. Prefer OpenFileHistory when the application can recover from initialization errors.

func NewFileHistory

func NewFileHistory(path string, opts ...history.ConversationManagerOptions) (*History, error)

NewFileHistory opens file-backed history. The caller must Close it after all agents sharing it have finished. Agents never close caller-owned history.

func OpenFileHistory added in v0.0.17

func OpenFileHistory(path string, opts ...history.ConversationManagerOptions) (*History, error)

OpenFileHistory is an alias for NewFileHistory.

type HistoryMiddleware added in v0.0.17

type HistoryMiddleware = agents.HistoryMiddleware

type Input added in v0.0.17

type Input = agents.Input

type LLMClient

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

func NewLLMClient

func NewLLMClient(configs []ProviderConfig, opts ...LLMOption) *LLMClient

NewLLMClient configures the providers a client can reach, and the middleware every model bound off it calls through.

func (*LLMClient) Model

func (c *LLMClient) Model(id string, opts ...LLMOption) llm.Provider

Model binds a "Provider/model" id to a provider the agent can call.

With no options it inherits the client's middleware. WithMiddleware replaces that chain wholesale for this one model — there is no merging, because a chain is an ordered whole and picking entries out of one by type would not survive middleware you wrote yourself:

fast := client.Model("OpenAI/gpt-4o-mini")

critical := client.Model("OpenAI/gpt-4o", hastekit.WithMiddleware(
    middleware.NewFallbackModels("Anthropic/claude-opus-4-5"),
    middleware.NewRetry(middleware.RetryConfig{MaxAttempts: 5}),
))

judge := client.Model("OpenAI/gpt-4o", hastekit.WithoutMiddleware())

A model naming its own chain builds one, so bind a model once at setup rather than per request.

type LLMOption added in v0.0.17

type LLMOption func(*llmOptions)

LLMOption configures the middleware a client, or one model bound off it, calls through.

func WithMiddleware added in v0.0.17

func WithMiddleware(m ...Middleware) LLMOption

WithMiddleware sets the chain, outermost first.

client := hastekit.NewLLMClient(configs, hastekit.WithMiddleware(
    middleware.NewFallbackModels("Anthropic/claude-sonnet-4-5"),
    middleware.NewRetry(middleware.RetryConfig{}),
))

Order is yours to choose and it matters.

Middleware needing the provider configuration receives it when the chain is installed, so nothing here has to be handed a config store.

func WithoutMiddleware added in v0.0.17

func WithoutMiddleware() LLMOption

WithoutMiddleware drops the chain, leaving only tracing. On a model it overrides the client's — an LLM judge, say, which should be held to exactly what the provider did on the first attempt, under a client that retries.

type ListedSkill added in v0.0.17

type ListedSkill = agents.ListedSkill

type MCPStore added in v0.0.31

type MCPStore = mcpclient.Store

MCPStore lists MCP server definitions by namespace — see mcpclient.Store. An MCP client reads one as its built-in store and one as its user store.

type Message added in v0.0.17

type Message = responses.InputMessageUnion

func User added in v0.0.17

func User(text string) Message

User constructs a user text message. Rich messages remain available through Message.

type Middleware added in v0.0.17

type Middleware = gateway.Middleware

Middleware wraps every call a client makes to a provider — retries, fallback, tracing, or anything you write yourself. Build the built-in ones with the constructors in pkg/gateway/middleware.

type Model

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

type ModelCallMiddleware added in v0.0.17

type ModelCallMiddleware = agents.ModelCallMiddleware

ModelCallMiddleware wraps a call to the model — see agents.ModelCallMiddleware.

type ModelParameters

type ModelParameters = responses.Parameters

type OutputSchema

type OutputSchema = jsonschema.Schema

type ProgressReporter added in v0.0.17

type ProgressReporter = agents.ProgressReporter

ProgressReporter is how a running tool says how far along it is.

type PromptMiddleware added in v0.0.17

type PromptMiddleware = agents.PromptMiddleware

type ProviderConfig

type ProviderConfig = gateway.ProviderConfig

type ProviderName

type ProviderName = llm.ProviderName

type RestateRuntime

type RestateRuntime struct {
	*restate_runtime.RestateRuntime
	// contains filtered or unexported fields
}

func NewRestateRuntime

func NewRestateRuntime(restateEndpoint string, broker agents.StreamBroker) (*RestateRuntime, error)

NewRestateRuntime requires an explicit broker shared by callers and service processes. An in-memory broker is only suitable for a single-process setup.

func (*RestateRuntime) Bind added in v0.0.31

func (r *RestateRuntime) Bind(snapshot *agentconfig.Snapshot) agents.Runtime

Bind runs a config-built agent's snapshot through the AgentBuilder workflow, making RestateRuntime an agentconfig.Runtime.

func (*RestateRuntime) Close added in v0.0.17

func (r *RestateRuntime) Close() error

func (*RestateRuntime) RegisterAgent added in v0.0.17

func (r *RestateRuntime) RegisterAgent(options *agents.AgentOptions) error

RegisterAgent registers an agent configuration before Serve starts.

func (*RestateRuntime) RegisterBuilder added in v0.0.31

func (r *RestateRuntime) RegisterBuilder(builder *agentconfig.Builder) error

RegisterBuilder serves config-built agents from builder, through the one AgentBuilder workflow, so agents written to its stores after Serve starts run durably. Call it before Serve. The builder must stream on this runtime's broker: build it with agentconfig.Dependencies.Runtime set to this runtime.

func (*RestateRuntime) Serve added in v0.0.17

func (r *RestateRuntime) Serve(ctx context.Context, address string) error

Serve blocks serving Restate invocations at address until ctx ends. The address is the local listen address, separate from the ingress endpoint.

func (*RestateRuntime) StreamBroker added in v0.0.17

func (r *RestateRuntime) StreamBroker() agents.StreamBroker

StreamBroker returns the broker configured for this runtime.

type Result added in v0.0.17

type Result = agents.AgentOutput

type RunHandle added in v0.0.17

type RunHandle = agents.AgentHandle

type Skill

type Skill = agents.Skill

Skill is one folder of instructions the agent can pull in on demand — see agents.Skill.

type SkillClient added in v0.0.25

type SkillClient = agents.SkillClient

SkillClient lists an agent's global and namespace skills — see skills.Client.

type SkillSelection added in v0.0.17

type SkillSelection = agents.SkillSelection

type SkillStore added in v0.0.31

type SkillStore = skills.Store

SkillStore lists and reads skills by namespace — see skills.Store. A skill client reads one as its built-in store and one as its user store.

type TemporalRuntime

type TemporalRuntime struct {
	*temporal_runtime.TemporalRuntime
	// contains filtered or unexported fields
}

func NewTemporalRuntime

func NewTemporalRuntime(temporalEndpoint string, broker agents.StreamBroker) (*TemporalRuntime, error)

NewTemporalRuntime requires an explicit broker. Use a shared broker such as Redis when the caller and workers run in different processes.

func (*TemporalRuntime) Bind added in v0.0.31

func (r *TemporalRuntime) Bind(snapshot *agentconfig.Snapshot) agents.Runtime

Bind runs a config-built agent's snapshot through the AgentBuilder workflow, making TemporalRuntime an agentconfig.Runtime.

func (*TemporalRuntime) Close added in v0.0.17

func (r *TemporalRuntime) Close() error

Close stops the worker and closes the client opened by NewTemporalRuntime. Brokers and histories supplied by the caller are not closed.

func (*TemporalRuntime) RegisterAgent added in v0.0.17

func (r *TemporalRuntime) RegisterAgent(options *agents.AgentOptions) error

RegisterAgent registers an agent configuration before Serve starts.

func (*TemporalRuntime) RegisterBuilder added in v0.0.31

func (r *TemporalRuntime) RegisterBuilder(builder *agentconfig.Builder) error

RegisterBuilder serves config-built agents from builder, through the one AgentBuilder workflow, so agents written to its stores after Serve starts run durably. Call it before Serve. The builder must stream on this runtime's broker: build it with agentconfig.Dependencies.Runtime set to this runtime.

func (*TemporalRuntime) Serve added in v0.0.17

func (r *TemporalRuntime) Serve(ctx context.Context) error

Serve runs the worker until ctx ends or startup fails. The caller owns the runtime and must Close it after Serve and outstanding executions finish.

func (*TemporalRuntime) StreamBroker added in v0.0.17

func (r *TemporalRuntime) StreamBroker() agents.StreamBroker

StreamBroker returns the broker configured for this runtime.

type Tool

type Tool = agents.Tool

type ToolAnnotations

type ToolAnnotations = agents.ToolAnnotations

ToolAnnotations describes what a tool does — read-only, destructive, idempotent, open-world — in the same shape MCP servers use, so a function tool and an MCP tool feed the same permission policy.

type ToolCallMiddleware added in v0.0.17

type ToolCallMiddleware = agents.ToolCallMiddleware

ToolCallMiddleware wraps a tool call — see agents.ToolCallMiddleware.

type ToolConfig

type ToolConfig interface {
	SetName(string)
	SetDescription(string)
	SetNeedsApproval(bool)
	SetDeferred(bool)
	SetAnnotations(*agents.ToolAnnotations)
	// GetAnnotations lets the per-hint options amend the current annotations
	// instead of overwriting them, so WithReadOnly and WithIdempotent can be
	// passed to the same tool.
	GetAnnotations() *agents.ToolAnnotations

	SetMeta(map[string]any)
	// GetMeta lets WithMeta add to what is already there, for the same reason
	// GetAnnotations exists.
	GetMeta() map[string]any
}

type ToolFunc

type ToolFunc[T any, S any] func(ctx context.Context, in T) (S, error)

type ToolOption

type ToolOption func(ToolConfig)

func WithAnnotations

func WithAnnotations(annotations *agents.ToolAnnotations) ToolOption

WithAnnotations sets the tool's behavioural hints in one go. Prefer the single-hint options below unless you already have a full set in hand.

func WithDeferred

func WithDeferred(deferred bool) ToolOption

func WithDescription

func WithDescription(desc string) ToolOption

func WithDestructive

func WithDestructive(destructive bool) ToolOption

WithDestructive declares whether the tool may destroy or overwrite state, as opposed to only adding to it. A tool that says nothing counts as destructive.

func WithIdempotent

func WithIdempotent(idempotent bool) ToolOption

WithIdempotent declares that repeating the call with the same arguments has no additional effect.

func WithMeta added in v0.0.14

func WithMeta(meta map[string]any) ToolOption

WithMeta attaches metadata to the tool. It is not sent to the model and has no meaning to the SDK: it rides along on the BaseTool, which is what a tool call middleware is shown, so a policy can key off where a tool came from or what it belongs to without having to recognise it by name.

Repeated use merges rather than replaces, so several options can each contribute a key, and a later one wins on a key both set. It works on a copy: a map handed to several tools must not pick up one tool's keys on another.

func WithName

func WithName(name string) ToolOption

func WithNeedsApproval

func WithNeedsApproval(needsApproval bool) ToolOption

func WithOpenWorld

func WithOpenWorld(openWorld bool) ToolOption

WithOpenWorld declares whether the tool reaches outside a closed, known set of entities — a web search does, a lookup in local memory does not.

func WithReadOnly

func WithReadOnly(readOnly bool) ToolOption

WithReadOnly declares that the tool does not modify anything. This is what a permission policy keys off to let a call run unattended, so only claim it when the tool truly has no side effects.

func WithStartedMessage added in v0.0.17

func WithStartedMessage(fn func(taskID string) string) ToolOption

WithStartedMessage replaces what the model is told the moment the task starts. It is given the task id.

The default says the work has started and that its result will follow, which is the thing the model most needs to know: that there is nothing to wait for and it should carry on.

It applies only to a background tool; on any other tool it does nothing.

func WithTitle

func WithTitle(title string) ToolOption

WithTitle sets a human-readable name for the tool, for UI use. The model still sees the tool by its name.

type ToolProgress added in v0.0.17

type ToolProgress = agents.ToolProgress

ToolProgress is one progress update. Total is optional; 0 means unknown.

Directories

Path Synopsis
examples
agents/14_agent_with_stdio_mcp_tools command
An agent whose tools come from an MCP server that runs as a child process rather than as a service — the stdio transport.
An agent whose tools come from an MCP server that runs as a child process rather than as a service — the stdio transport.
agents/15_dynamic_skills command
Run from the repository root with OPENAI_API_KEY set.
Run from the repository root with OPENAI_API_KEY set.
agents/16_dynamic_agents command
Dynamic agents: agents as data, created per namespace at run time.
Dynamic agents: agents as data, created per namespace at run time.
speech/1_speech command
workflow/programmatic command
This example builds and resumes a workflow entirely in Go.
This example builds and resumes a workflow entirely in Go.
workflow/temporal command
Run a local Temporal server first: temporal server start-dev Then: go run ./examples/workflow/temporal
Run a local Temporal server first: temporal server start-dev Then: go run ./examples/workflow/temporal
workflow/yaml command
internal
testutil
Package testutil supplies in-process fixtures for SDK tests.
Package testutil supplies in-process fixtures for SDK tests.
pkg
agents/agentconfig
Package agentconfig defines agents as data: a serializable Config, a Registry that finds the configs a namespace can run, and a Builder that turns them into a plain agents.Agent from dependencies held in code.
Package agentconfig defines agents as data: a serializable Config, a Registry that finds the configs a namespace can run, and a Builder that turns them into a plain agents.Agent from dependencies held in code.
agents/attachments
Package attachments resolves application-owned immutable files without putting their contents in conversation or workflow state.
Package attachments resolves application-owned immutable files without putting their contents in conversation or workflow state.
agents/eval
Package eval runs an agent against a fixed set of cases and scores what it did, so a change to a prompt, a model, or a tool can be measured instead of eyeballed.
Package eval runs an agent against a fixed set of cases and scores what it did, so a change to a prompt, a model, or a tool can be measured instead of eyeballed.
agents/runtime/local_runtime
Package local_runtime provides a goroutine-based agent runtime that streams via a StreamBroker, mirroring the structure of the Temporal and Restate runtimes.
Package local_runtime provides a goroutine-based agent runtime that streams via a StreamBroker, mirroring the structure of the Temporal and Restate runtimes.
agents/runtime/restate_agent_builder
Package restate_agent_builder runs config-built agents (see agentconfig) on Restate through one generic workflow, so an agent created after the service started runs durably without registering anything.
Package restate_agent_builder runs config-built agents (see agentconfig) on Restate through one generic workflow, so an agent created after the service started runs durably without registering anything.
agents/runtime/temporal_agent_builder
Package temporal_agent_builder runs config-built agents (see agentconfig) on Temporal through one generic workflow, so an agent created after the worker started runs durably without registering anything.
Package temporal_agent_builder runs config-built agents (see agentconfig) on Temporal through one generic workflow, so an agent created after the worker started runs durably without registering anything.
agents/sandbox/internal/execsandbox
Package execsandbox implements sandbox.Sandbox over a provider's native exec, for containers that run no process of ours.
Package execsandbox implements sandbox.Sandbox over a provider's native exec, for containers that run no process of ours.
agents/sandbox/internal/httpapi
Package httpapi contains transport shared by sandbox provider adapters.
Package httpapi contains transport shared by sandbox provider adapters.
agents/sandbox/internal/provision
Package provision contains configuration helpers for providers that create their own containers.
Package provision contains configuration helpers for providers that create their own containers.
agents/sandbox/internal/sandboxtest
Package sandboxtest checks what a provider's exec path promises against a real container, which is the only place these behaviours can be observed: they come from the container runtime, the shell and the tools in the image.
Package sandboxtest checks what a provider's exec path promises against a real container, which is the only place these behaviours can be observed: they come from the container runtime, the shell and the tools in the image.
agents/sandbox/providers/daytona
Package daytona implements sandbox.Provider using Daytona's control and toolbox APIs.
Package daytona implements sandbox.Provider using Daytona's control and toolbox APIs.
agents/sandbox/providers/docker
Package docker provisions sandboxes through the Docker Engine API and runs commands in them with its exec API.
Package docker provisions sandboxes through the Docker Engine API and runs commands in them with its exec API.
agents/sandbox/providers/e2b
Package e2b uses the E2B lifecycle API and envd's native Connect/file protocols.
Package e2b uses the E2B lifecycle API and envd's native Connect/file protocols.
agents/sandbox/providers/k8s
Package k8s provisions sandbox pods with the official Kubernetes client and runs commands in them through the API server's exec subresource.
Package k8s provisions sandbox pods with the official Kubernetes client and runs commands in them through the API server's exec subresource.
agents/skills
Package skills persists complete skill bundles independently of agent configuration.
Package skills persists complete skill bundles independently of agent configuration.
agui
Package agui implements the AG-UI Protocol (https://github.com/ag-ui-protocol/ag-ui) as a serving surface for agents.
Package agui implements the AG-UI Protocol (https://github.com/ag-ui-protocol/ag-ui) as a serving surface for agents.
agui/web
Package web embeds a ready-made browser chat client for the AG-UI protocol and serves it alongside the protocol endpoints.
Package web embeds a ready-made browser chat client for the AG-UI protocol and serves it alongside the protocol endpoints.
cache
Package cache provides byte-oriented cache implementations.
Package cache provides byte-oriented cache implementations.
gateway/middleware
Package middleware holds the gateway's built-in middleware: tracing, retry, and provider fallback.
Package middleware holds the gateway's built-in middleware: tracing, retry, and provider fallback.
gateway/providers/deepseek
Package deepseek is the provider client for DeepSeek.
Package deepseek is the provider client for DeepSeek.
gateway/providers/moonshot
Package moonshot is the provider client for Moonshot AI, which serves the Kimi model family.
Package moonshot is the provider client for Moonshot AI, which serves the Kimi model family.
gateway/providers/openaicompat
Package openaicompat is a provider client for any service that speaks the OpenAI /chat/completions wire format but does not implement the /responses API — Sarvam, DeepSeek, Kimi (Moonshot) and GLM (Z.ai) today.
Package openaicompat is a provider client for any service that speaks the OpenAI /chat/completions wire format but does not implement the /responses API — Sarvam, DeepSeek, Kimi (Moonshot) and GLM (Z.ai) today.
gateway/providers/sarvam
Package sarvam is the provider client for Sarvam AI - chat (the OpenAI-compatible /v1/chat/completions endpoint, bridged to the native Responses shape), text-to-speech and speech-to-text.
Package sarvam is the provider client for Sarvam AI - chat (the OpenAI-compatible /v1/chat/completions endpoint, bridged to the native Responses shape), text-to-speech and speech-to-text.
gateway/providers/zai
Package zai is the provider client for Z.ai (Zhipu AI), which serves the GLM model family.
Package zai is the provider client for Z.ai (Zhipu AI), which serves the GLM model family.
genai
Package genai holds the OpenTelemetry GenAI semantic-convention attribute keys and well-known values used across the SDK and the gateway.
Package genai holds the OpenTelemetry GenAI semantic-convention attribute keys and well-known values used across the SDK and the gateway.
genai/agentcore
Package agentcore exports OpenTelemetry spans to Amazon Bedrock AgentCore / CloudWatch GenAI Observability without an ADOT collector.
Package agentcore exports OpenTelemetry spans to Amazon Bedrock AgentCore / CloudWatch GenAI Observability without an ADOT collector.
knowledge/textsplitters
Package textsplitters provides text chunking by character length, token length, and allows adding more advanced strategies (semantic, sentence-aware, etc.) via the TextSplitter interface.
Package textsplitters provides text chunking by character length, token length, and allows adding more advanced strategies (semantic, sentence-aware, etc.) via the TextSplitter interface.
routines
Package routines provides persistent scheduled agent tasks.
Package routines provides persistent scheduled agent tasks.

Jump to

Keyboard shortcuts

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