agentcore

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: AGPL-3.0, Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package agentcore is the public entry point of the SDK. It aggregates the provider, tools, permission policy, and hooks into a stateful Session whose Prompt method streams the agent loop as a range-over-func iterator. The SDK injects no preset system prompt: the host controls it entirely via Options.SystemPrompt (design decision 1).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(ctx context.Context, opts Options, input string) (string, error)

Run is a one-shot convenience: it creates a Session, runs a single prompt to completion, and returns the assistant's final text (FR-07.4).

Types

type MemoryOptions

type MemoryOptions struct {
	Store *memory.Store
	// AutoInject prepends memories relevant to each prompt into the conversation.
	AutoInject bool
	// MaxInject caps auto-injected memories (default 3).
	MaxInject int
	// IncludeIndexInPrompt adds the memory index to the system prompt.
	IncludeIndexInPrompt bool
}

MemoryOptions configures long-term memory.

type Options

type Options struct {
	// Provider is the LLM backend (any Anthropic- or OpenAI-format endpoint, or
	// a custom implementation).
	Provider llm.Provider

	// SystemPrompt is the host-controlled system prompt, in segments. The SDK
	// injects nothing of its own. AppendSystemPrompt is added after it (e.g. for
	// SDK-managed dynamic context). DynamicBoundary marks the cacheable prefix.
	SystemPrompt       []string
	AppendSystemPrompt []string
	DynamicBoundary    int

	// Tools the agent may call. Defaults to tool.DefaultTools().
	Tools []tool.CoreTool

	// DeferredTools names tools whose schemas are withheld from the model (only
	// their names surface, e.g. via tool.RenderDeferredToolsBlock placed in the
	// system prompt). They stay callable through the auto-added ExecuteExtraTool
	// after discovery via SearchExtraTools. When non-empty the SDK auto-adds those
	// two access tools. Empty = classic behavior (all tool schemas sent).
	DeferredTools []string
	// UnlockSet gates which deferred tools are currently callable via
	// ExecuteExtraTool. Nil + non-empty DeferredTools → the SDK seeds one with all
	// DeferredTools unlocked. Hosts doing skill-gated disclosure pass their own set
	// (seeded with the globally-available subset) and Add() to it when a skill loads.
	UnlockSet *tool.UnlockSet

	// Permission policy.
	CanUseTool      permission.CanUseTool
	AllowedTools    []string
	DisallowedTools []string
	PermissionMode  permission.Mode

	// Hooks is optional lifecycle instrumentation (Phase 3).
	Hooks harness.HookRunner

	// Compaction, when non-nil, enables automatic context-window management,
	// summarizing with the same Provider. Ignored when Compactor is set.
	Compaction *compaction.Config

	// Compactor lets the host take over context management entirely. Setting it
	// means "I manage the context myself": the built-in Compaction is IGNORED.
	// The two are mutually exclusive — the session holds a single compactor, so
	// they can never both run.
	//
	// A Compactor that also implements harness.ContextView builds the request
	// message array itself, replacing llm.MessagesForAPI.
	Compactor harness.Compactor

	// OnWarn, when set, receives configuration warnings raised while building the
	// session — misconfigurations the SDK works around rather than rejecting. The
	// SDK writes nothing to stdout/stderr on its own, so a host that wants to see
	// these must wire them somewhere (log.Printf, a structured logger, a test
	// buffer). Called synchronously during NewSession.
	OnWarn func(string)

	// Plan, when non-nil, enables plan mode (read-only exploration → approval →
	// implementation) with EnterPlanMode/ExitPlanMode tools.
	Plan *PlanOptions

	// Memory, when non-nil, enables persistent long-term memory with
	// RecallMemory/RecordMemory tools and optional auto-injection.
	Memory *MemoryOptions

	// Skills, when non-nil, exposes a Skill tool for invoking named procedures.
	Skills *skill.Registry

	// EnableWebFetch adds the network-facing WebFetch tool (permission-gated).
	EnableWebFetch bool
	// WebFetchProxy, when set, routes WebFetch requests through this http(s) proxy
	// URL (e.g. a recording/intercepting proxy). Empty = direct connection.
	WebFetchProxy string
	// WebFetchCACert is a path to a PEM CA cert WebFetch adds to the system trust
	// pool — verifies HTTPS through a MITM proxy without disabling TLS (preferred
	// over WebFetchInsecureTLS).
	WebFetchCACert string
	// WebFetchInsecureTLS skips TLS verification for WebFetch (curl -k). Blunt
	// fallback when no CA cert is available; prefer WebFetchCACert.
	WebFetchInsecureTLS bool
	// EnableWebSearch adds the network-facing web_search tool (permission-gated).
	EnableWebSearch bool
	// WebSearchBackend selects the search backend: "ddgs" (DuckDuckGo, no key),
	// "brave-free" (Brave Search API), "tavily" (Tavily Search API), or
	// "deepseek" (DeepSeek's server-side search). Empty defaults to "ddgs".
	WebSearchBackend string
	// BraveSearchAPIKey authenticates the "brave-free" backend. Required only when
	// WebSearchBackend == "brave-free".
	BraveSearchAPIKey string
	// TavilySearchAPIKey authenticates the "tavily" backend. Required only when
	// WebSearchBackend == "tavily".
	TavilySearchAPIKey string
	// DeepSeekSearch* configure the "deepseek" backend, which has no search API
	// of its own: it spends one call on DeepSeek's Anthropic-format messages
	// endpoint per search (the web_search_20250305 server tool). BaseURL must be
	// the Anthropic-format root — DeepSeek's OpenAI-format endpoint rejects
	// server tools. All three are required when WebSearchBackend == "deepseek".
	DeepSeekSearchBaseURL string
	DeepSeekSearchAPIKey  string
	DeepSeekSearchModel   string
	// WebSearchProxy, when set, routes web_search requests through this http(s)
	// proxy URL — useful when the search endpoint is only reachable via a proxy.
	WebSearchProxy string
	// WebSearchCACert / WebSearchInsecureTLS mirror the WebFetch TLS options for
	// web_search when it runs through a MITM/recording proxy (prefer the CA cert).
	WebSearchCACert      string
	WebSearchInsecureTLS bool
	// Todos, when non-nil, adds the TodoWrite tool backed by this store, letting
	// the host observe the agent's plan/progress via Todos.List().
	Todos *tool.TodoStore
	// AskUser, when non-nil, adds the AskUserQuestion tool so the agent can pause
	// a long task to ask the user a structured multiple-choice question.
	AskUser tool.AskUserFunc

	// SystemReminderFunc, when set, is called before each Prompt and its return
	// value is included in the <system-reminder> prepended to the conversation.
	// The SDK always injects today's date into the reminder regardless of whether
	// this is set. Return "" to include only the date.
	SystemReminderFunc func() string

	MaxTurns int
	// MaxDuration bounds wall-clock run time, checked at the turn boundary (never
	// mid-stream), so a run ends cleanly rather than being aborted in flight (0 = off).
	MaxDuration time.Duration
	// Settlement, when set with a Prompt, runs a bounded wrap-up phase when a budget
	// (MaxTurns/MaxDuration) is hit — injecting the prompt and hiding DisabledTools —
	// so a budget-terminated run checkpoints its findings. See harness.Settlement.
	Settlement     *harness.Settlement
	MaxTokens      int
	Temperature    *float64
	MaxConcurrency int
	WorkingDir     string

	// ToolOutputDir, when set, makes oversized tool output spill to a file there
	// (full content preserved) and the tool return a head + pointer instead of
	// discarding the overflow (tool.Capture). MaxToolOutputChars caps the head
	// size fed to the model (0 = default 30000).
	ToolOutputDir      string
	MaxToolOutputChars int

	// BashEnv holds extra "KEY=VALUE" entries injected into the environment of
	// Bash subprocesses (foreground + background), overriding inherited values.
	// The agent's own process env is untouched. Empty = inherit unchanged. Used
	// e.g. to route child-command HTTP through a proxy and trust its CA.
	BashEnv []string

	// Transcript, when non-nil, persists the conversation to an append-only
	// JSONL log so the session can be resumed (see Session.Resume). Subagents
	// write their own sidechain files under the same store.
	Transcript *transcript.Store
	// SessionID names the transcript file. Empty generates a fresh id (read it
	// back via Session.SessionID).
	SessionID string

	// TokenBudget, when > 0, lets the agent keep working (with budget nudges)
	// after it would otherwise stop, until ~90% of the output-token budget or
	// diminishing returns.
	TokenBudget int
	// EscalateMaxTokens retries a max_tokens truncation with a raised output cap
	// before falling back to resume-recovery.
	EscalateMaxTokens bool

	// DisableBackgroundTasks, when true, prevents the SDK from injecting the
	// background-task management tools (TaskOutput, TaskStop, TaskList, Monitor)
	// into this session's registry. Use for focused single-purpose agents (e.g.
	// goal decomposers, structured-output callers) that should only see the tools
	// explicitly provided in Options.Tools. The global AGENT_CORE_DISABLE_BACKGROUND_TASKS
	// env var disables them for every session; this field is the per-session equivalent.
	DisableBackgroundTasks bool

	// NonStreaming runs every model call as a single non-streaming request
	// (Provider.Complete) instead of a token stream. The host still receives the
	// same event sequence (text/thinking/tool_use/usage), just delivered when the
	// full response arrives rather than incrementally. Zero value = streaming.
	NonStreaming bool

	// Deps optionally overrides side-effect boundaries (testing/advanced use).
	Deps harness.QueryDeps
}

Options configures a Session (FR-07).

type PlanOptions

type PlanOptions struct {
	// Approver decides whether a presented plan is accepted. Nil auto-approves.
	Approver plan.Approver
	// StartInPlanMode begins the session read-only (the agent must ExitPlanMode
	// to implement). If false, the agent enters plan mode itself via EnterPlanMode.
	StartInPlanMode bool
	// TargetMode is the permission mode after approval (default acceptEdits).
	TargetMode permission.Mode
}

PlanOptions configures plan mode.

type Session

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

Session is a long-lived conversation. Call Prompt repeatedly; state (messages, usage) persists across calls (FR-07.1/2). Not safe for concurrent Prompt calls on the same Session.

func NewSession

func NewSession(opts Options) *Session

NewSession builds a Session, applying defaults.

func (*Session) Close

func (s *Session) Close() error

Close releases session resources, killing any background tasks and removing their temporary output directory. Safe to call multiple times. Hosts running a long-lived Session should defer Close; Run does so automatically.

func (*Session) Messages

func (s *Session) Messages() []llm.Message

Messages returns the conversation history.

func (*Session) Prompt

func (s *Session) Prompt(ctx context.Context, input string) iter.Seq2[harness.Event, error]

Prompt appends a user message and streams the agent loop to completion. The final event is KindResult; Session state is updated when the consumer reaches it (FR-07.3).

func (*Session) Reset

func (s *Session) Reset()

Reset clears the conversation.

func (*Session) Resume

func (s *Session) Resume(sessionID string) error

Resume reloads a prior conversation from the transcript store, rebuilding the message history and cumulative usage so the next Prompt continues it. Requires Options.Transcript to be set. Subsequent messages append to the same file.

func (*Session) SessionID

func (s *Session) SessionID() string

SessionID returns the transcript session id (empty if persistence is off).

func (*Session) UnlockSet

func (s *Session) UnlockSet() *tool.UnlockSet

UnlockSet returns the session's deferred-tool call gate (nil when no deferred tools). Hosts Add() to it to unlock skill-gated tools at runtime.

func (*Session) Usage

func (s *Session) Usage() llm.Usage

Usage returns cumulative token usage.

Jump to

Keyboard shortcuts

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