Documentation
¶
Overview ¶
Package adaptor provides one API for running local coding agents.
The API is organized around six nouns:
- Agent is a configured, ready-to-run driver plus host defaults.
- Thread adds durable resume and fork semantics to an Agent.
- Stream represents one execution in progress.
- Event is one typed observation from that execution.
- Result is its final output and audit record.
- Driver is the provider integration SPI implemented in package driver.
Construct an Agent directly from a provider Driver. Multiple agents are ordinary Go variables; the package has no central SDK object or registry:
agent := adaptor.New(
codex.Driver(codex.Config{Model: "gpt-5.4"}),
adaptor.WithWorkspace("/repo"),
)
result, err := agent.Send(ctx, "Review this change").Result()
Send uses one execution pipeline for synchronous Result retrieval and asynchronous Events consumption. Agent and Thread both implement Runner, so bridges and host integrations do not need separate stateful and stateless paths.
On Windows, macOS, and Linux, built-in Drivers reuse one provider process across compatible Thread turns by default when the provider supports it. WithSpawn forces a fresh process for an Agent default or one call, and Agent.Close performs bounded, idempotent cleanup of processes owned by that Agent.
Options have explicit scopes. Option applies at construction, CallOption applies to one invocation, and SharedOption may be used in either place. Per-call values override Agent defaults; skills append, while other settings follow their documented replacement or merge rules.
Host-defined Tools use the provider-neutral tool package and the construction-only WithTools option. The Agent owns their runtime for its full lifetime; MCP delivery, authentication, and endpoint lifecycle remain internal implementation details. Existing external MCP servers continue to use WithMCP.
Agent.Send is stateless. Agent.Thread uses a per-Agent memory store by default; WithThreadStore supplies a shared or durable store. Agent.Thread continues or creates the host key, while Thread.Fork creates an independent child. The SDK coordinates leases, compatibility fingerprints, and atomic checkpoint persistence; provider resume identifiers remain Driver details.
Stream exposes one ordered typed Event channel. ApprovalRequest events carry their own exactly-once responder, allowing either callbacks or interactive hosts to approve, deny, or answer. Result separates assistant Text and Summary from Raw process streams, Transcript entries, runtime Services, and validated structured output. Business failures use RunError and retain the partial Result; infrastructure failures remain ordinary wrapped errors.
Index ¶
- Constants
- Variables
- type Agent
- func (a *Agent) Close(ctx context.Context) error
- func (a *Agent) Inspect() Inspector
- func (a *Agent) ProfileState(ctx context.Context) (ProfileSnapshot, error)
- func (a *Agent) SelectSkills(ctx context.Context, keys []string) (SkillSnapshot, error)
- func (a *Agent) Send(ctx context.Context, prompt string, opts ...CallOption) Stream
- func (a *Agent) SyncProfile(ctx context.Context) (ProfileSnapshot, error)
- func (a *Agent) Thread(key string, opts ...ThreadOption) *Thread
- type AgentProfile
- type AgentSettings
- func (s *AgentSettings) SetBlockingEvents()
- func (s *AgentSettings) SetEventBuffer(n int)
- func (s *AgentSettings) SetProfile(sel profile.Selection)
- func (s *AgentSettings) SetServiceManager(m ServiceManager)
- func (s *AgentSettings) SetSkillMaterializer(m SkillMaterializer)
- func (s *AgentSettings) SetSkillProvider(p SkillProvider)
- func (s *AgentSettings) SetThreadStore(store threadstore.Store)
- func (s *AgentSettings) SetWorkspaceManager(m WorkspaceManager)
- type ApprovalHandler
- type ApprovalKind
- type ApprovalMode
- type ApprovalPolicy
- type ApprovalRequest
- func (r *ApprovalRequest) Answer(_ context.Context, option string) error
- func (r *ApprovalRequest) Approve(_ context.Context) error
- func (r *ApprovalRequest) Deny(_ context.Context, reason string) error
- func (r *ApprovalRequest) Forward(o Origin) *ApprovalRequest
- func (c ApprovalRequest) Meta() EventMeta
- func (r *ApprovalRequest) Origin() Origin
- type Author
- type AuthorKind
- type CallOption
- type Checkpoint
- type Choice
- type ConfigSchema
- type Done
- type Driver
- type DriverManagedWorkspace
- type Dropped
- type EnvironmentCheck
- type EnvironmentReport
- type Event
- type EventMeta
- type EventSourceMeta
- type FailureReason
- type FallbackAction
- type FeatureLevel
- type GitWorktreeWorkspace
- type HumanDecisionModeUnsupportedError
- type Identity
- type Inspector
- func (in Inspector) ConfigSchema(ctx context.Context) (*ConfigSchema, error)
- func (in Inspector) Environment(ctx context.Context) (EnvironmentReport, error)
- func (in Inspector) Models(ctx context.Context) ([]ModelInfo, error)
- func (in Inspector) Quota(ctx context.Context) (QuotaReport, error)
- func (in Inspector) Skills(ctx context.Context) (SkillSnapshot, error)
- type InvalidDriverConfigError
- type InvalidOutputSchemaError
- type InvalidPolicyError
- type MessageContext
- type MessageError
- type MessageFailure
- type MessageOption
- type MessageOutcome
- type MessagePolicy
- type MessageState
- type MessageUpdate
- type ModelInfo
- type Notice
- type Option
- func WithBlockingEvents() Option
- func WithEventBuffer(n int) Option
- func WithProfile(sel profile.Selection) Option
- func WithServiceManager(m ServiceManager) Option
- func WithSkillMaterializer(m SkillMaterializer) Option
- func WithSkillProvider(p SkillProvider) Option
- func WithThreadStore(store threadstore.Store) Option
- func WithTools(definitions ...tool.Definition) Option
- func WithWorkspaceManager(m WorkspaceManager) Option
- type Origin
- type Phase
- type Policy
- type PolicyCapabilityUnsupportedError
- type ProcessInfo
- type ProfileKind
- type ProfileResourceKind
- type ProfileResourceMaterialization
- type ProfileResourceSupport
- type ProfileSnapshot
- type QuestionMode
- type QuotaReport
- type RawStreams
- type ResourceSnapshot
- type Result
- func (r *Result) Decode(v any) error
- func (r *Result) Messages() []MessageOutcome
- func (r *Result) Raw() RawStreams
- func (r *Result) Services() []ServiceReport
- func (r *Result) Subagents() []SubagentResult
- func (r *Result) Transcript() []TranscriptItem
- func (r *Result) Undelivered() []MessageOutcome
- func (r *Result) WithSubagents(subagents []SubagentResult) *Result
- type Role
- type RunAttachment
- type RunError
- type RunEventSource
- type RunFinished
- type RunServiceProvider
- type RunSettings
- func (s *RunSettings) AddRunServiceProvider(p RunServiceProvider)
- func (s *RunSettings) AddSkills(refs ...skill.Ref)
- func (s *RunSettings) CapMessageTurns(remaining int)
- func (s *RunSettings) SetAgents(specs []driver.AgentSpec)
- func (s *RunSettings) SetApprovalHandler(h ApprovalHandler)
- func (s *RunSettings) SetConfigPatches(patches []driver.ProfileConfigPatch)
- func (s *RunSettings) SetHooks(specs []driver.HookSpec)
- func (s *RunSettings) SetIdentity(id Identity)
- func (s *RunSettings) SetInstructions(text string)
- func (s *RunSettings) SetInstructionsBundle(ref *driver.InstructionsBundleRef)
- func (s *RunSettings) SetMCPServers(servers []mcp.Server)
- func (s *RunSettings) SetMetadata(k, v string)
- func (s *RunSettings) SetModel(m string)
- func (s *RunSettings) SetOutputSchema(schema driver.OutputSchema)
- func (s *RunSettings) SetOutputSchemaError(err error)
- func (s *RunSettings) SetPolicy(p Policy)
- func (s *RunSettings) SetServices(specs []ServiceSpec)
- func (s *RunSettings) SetSpawn()
- func (s *RunSettings) SetTimeout(d time.Duration)
- func (s *RunSettings) SetWorkspace(dir string)
- func (s *RunSettings) SetWorkspaceSpec(spec WorkspaceSpec)
- type RunStarted
- type Runner
- type SandboxLevel
- type SchemaOption
- func SchemaAllowAdditionalProperties() SchemaOption
- func SchemaDescription(desc string) SchemaOption
- func SchemaInlineReferences() SchemaOption
- func SchemaName(name string) SchemaOption
- func SchemaRequireExplicitTags() SchemaOption
- func SchemaReturnInvalid() SchemaOption
- func SchemaUseGoComments(base, path string) SchemaOption
- type ServiceManager
- type ServiceRef
- type ServiceReport
- type ServiceRequest
- type ServiceSpec
- type SharedOption
- func OnApproval(h ApprovalHandler) SharedOption
- func WithIdentity(id Identity) SharedOption
- func WithInstructions(text string) SharedOption
- func WithMCP(servers ...mcp.Server) SharedOption
- func WithMetadata(k, v string) SharedOption
- func WithModel(m string) SharedOption
- func WithPolicy(p Policy) SharedOption
- func WithProfileResources(res profile.Resources) SharedOption
- func WithRunServices(providers ...RunServiceProvider) SharedOption
- func WithServices(specs ...ServiceSpec) SharedOption
- func WithSkills(refs ...SkillRef) SharedOption
- func WithSpawn() SharedOption
- func WithTimeout(d time.Duration) SharedOption
- func WithWorkspace(dir string) SharedOption
- func WithWorkspaceSpec(spec WorkspaceSpec) SharedOption
- type SharedWorkspace
- type SkillKeyConflictError
- type SkillMaterializationError
- type SkillMaterializer
- type SkillProvider
- type SkillRef
- type SkillSnapshot
- type Standby
- type Stream
- type StructuredOutputUnsupportedError
- type SubagentEventKind
- type SubagentResult
- type SubagentUpdate
- type TerminalPayload
- type TextDelta
- type Thinking
- type Thread
- type ThreadOption
- type ThreadRunner
- type Timing
- type ToolCall
- type ToolResult
- type TranscriptItem
- type TranscriptMessage
- type TurnEnd
- type Usage
- type WorkspaceLease
- type WorkspaceManager
- type WorkspaceReleaseMode
- type WorkspaceRequest
- type WorkspaceSpec
Constants ¶
const ( // ProcessSpawn reports child-process launch details. ProcessSpawn = "spawn" // ProcessStdout carries a raw stdout chunk. ProcessStdout = "stdout" // ProcessStderr carries a raw stderr chunk. ProcessStderr = "stderr" )
ProcessInfo kinds.
const ( // NoticeInvocation describes the resolved invocation metadata. NoticeInvocation = "invocation" // NoticeLifecycle reports high-level run lifecycle markers and // SDK warnings (for example the approval-retry degradation warning, // Data["warning"] == "human_decision_retry_unsupported"). NoticeLifecycle = "lifecycle" // NoticeRuntime reports runtime-service preparation or cleanup. NoticeRuntime = "runtime" // NoticeStep marks a provider-defined work step boundary // (StreamKinds step.started / step.finished); Data["phase"] is // "started" or "finished" and Text carries the step name. NoticeStep = "step" // NoticeTranscriptItem carries one progressively parsed transcript // item. Item holds the normalized entry; the // complete ordered transcript remains available via Result.Transcript(). NoticeTranscriptItem = "transcript.item" // NoticeApprovalRequested broadcasts that an approval request was // routed to a callback handler or auto-resolved by policy (in event // form the *ApprovalRequest event itself is the request signal). NoticeApprovalRequested = "approval.requested" // NoticeApprovalResolved broadcasts the final outcome of an approval // request (Data: request_id / kind / result / choice / attempt). NoticeApprovalResolved = "approval.resolved" )
Notice kinds.
Variables ¶
var ( // ErrApprovalResolved is returned by Approve / Deny / Answer when the // request was already resolved — by an earlier response, by the // timeout fallback, or because the run ended. ErrApprovalResolved = errors.New("adaptor: approval request already resolved") // ErrApprovalKindMismatch is returned when the response method does // not fit the request kind: Approve on a Question, or Answer on a // Permission / PlanReview request. ErrApprovalKindMismatch = errors.New("adaptor: response does not match approval kind") // unbound request. Such values have no run-owned responder and therefore // can never be answered. ErrApprovalUnavailable = errors.New("adaptor: approval responder unavailable") // ErrApprovalExpired identifies a request whose response window or owning // run ended. It wraps ErrApprovalResolved so callers can treat every late // response as an already-resolved request while still detecting expiry. ErrApprovalExpired = fmt.Errorf("%w: request expired", ErrApprovalResolved) )
Approval response errors.
var ( // ErrAgentClosed is returned by an Agent or any Thread derived from it // after Agent.Close has begun. ErrAgentClosed = errors.New("adaptor: agent closed") // ErrApprovalDenied matches runs that failed because a human decision // was rejected. ErrApprovalDenied = errors.New("adaptor: approval denied") // ErrApprovalTimeout matches runs that failed because a human decision // timed out. ErrApprovalTimeout = errors.New("adaptor: approval timed out") // ErrAgentFailed matches driver-classified agent failures. ErrAgentFailed = errors.New("adaptor: agent failed") // ErrRunCancelled matches driver-classified cancellation failures. ErrRunCancelled = errors.New("adaptor: run cancelled") // ErrPolicyViolation matches policy validation failures. ErrPolicyViolation = errors.New("adaptor: policy violation") )
Sentinels for errors.Is matching. Each RunError unwraps to the sentinel matching its Reason.
var ( // ErrSkillNotFound: a bare skill key was requested (WithSkills / // SelectSkills) but the SkillProvider did not return it. ErrSkillNotFound = skill.ErrSkillNotFound // ErrSkillKeyConflict: two skill candidates share a key but differ // structurally. Unwrap to *SkillKeyConflictError for the sources. ErrSkillKeyConflict = skill.ErrSkillKeyConflict // ErrSkillMaterializationFailed: staging a skill's source to disk // failed. Unwrap to *SkillMaterializationError for the key. ErrSkillMaterializationFailed = skill.ErrSkillMaterializationFailed // ErrSkillSourceMissing: a skill declares no usable source. ErrSkillSourceMissing = skill.ErrSkillSourceMissing // ErrSkillKeyMissing: a concrete skill declaration has an empty key. ErrSkillKeyMissing = skill.ErrSkillKeyMissing // ErrInvalidMCPConfig: an MCP server spec is malformed (missing key, // transport/field mismatch, duplicate key). ErrInvalidMCPConfig = mcp.ErrInvalidConfig // ErrMCPUnsupported: the driver does not support MCP servers at all. ErrMCPUnsupported = mcp.ErrUnsupported // ErrMCPTransportUnsupported: the driver supports MCP but not this // server's transport. ErrMCPTransportUnsupported = mcp.ErrTransportUnsupported // ErrInvalidOutputSchema: the structured-output schema is invalid or // could not be derived. Unwrap to *InvalidOutputSchemaError. ErrInvalidOutputSchema = driver.ErrInvalidOutputSchema // ErrStructuredOutputUnsupported: the driver's capability matrix // cannot honor structured output through either supported mechanism. // Unwrap to *StructuredOutputUnsupportedError for Driver diagnostics. ErrStructuredOutputUnsupported = driver.ErrStructuredOutputUnsupported // ErrInvalidDriverConfig: Driver.ValidateConfig rejected the Driver's // captured construction-time configuration before launch. ErrInvalidDriverConfig = driver.ErrInvalidDriverConfig // ErrInvalidPolicy: a Policy field contains an out-of-domain value. ErrInvalidPolicy = driver.ErrInvalidPolicy // ErrPolicyCapabilityUnsupported: a valid, explicitly selected Sandbox, // WebSearch, or Browser value is unsupported by the Driver. ErrPolicyCapabilityUnsupported = driver.ErrPolicyCapabilityUnsupported // ErrHumanDecisionModeUnsupported: an explicitly selected approval mode // is not advertised by the Driver's RunPolicyCaps. ErrHumanDecisionModeUnsupported = driver.ErrHumanDecisionModeUnsupported )
var ( // ErrRunFinished means the execution no longer accepts messages. ErrRunFinished = errors.New("adaptor: execution finished") // ErrMessageUnsupported means the Driver cannot provide the requested delivery. ErrMessageUnsupported = errors.New("adaptor: message delivery unsupported") )
var ( // PolicyReadOnly is a read-only workspace policy (reviewers, planners). PolicyReadOnly = Policy{Sandbox: ReadOnly} // PolicyWorkspaceWrite allows writes inside the resolved workspace. PolicyWorkspaceWrite = Policy{Sandbox: WorkspaceWrite} // PolicyUnrestricted requests the driver's full-access sandbox. PolicyUnrestricted = Policy{Sandbox: Unrestricted} )
Common sandbox presets. Configure human-in-the-loop behavior independently through Policy.Approvals or an OnApproval handler.
var ( // ErrThreadNotFound: a resume-only thread (or a fork parent) has no // stored conversation under its key. ErrThreadNotFound = errors.New("adaptor: thread not found") // ErrThreadBusy: another run holds the thread's exclusivity lease // right now, or the Thread is on standby. Repeated Standby calls within // one Agent instead return the existing live handle. ErrThreadBusy = errors.New("adaptor: thread busy") // ErrThreadIncompatible: the stored conversation no longer matches the // current configured Driver, identity, model, resolved workspace, // profile/skill/MCP/instructions, or runtime-service environment, and // the thread is resume-only, so silently starting over is not allowed. ErrThreadIncompatible = errors.New("adaptor: thread incompatible with current configuration") // ErrThreadLeaseLost: the run lost its exclusivity lease mid-flight // (store outage or takeover); its state was not persisted. ErrThreadLeaseLost = errors.New("adaptor: thread lease lost") // ErrThreadCheckpointMissing: the driver finished without producing a // resumable checkpoint, so the thread state could not be persisted. ErrThreadCheckpointMissing = errors.New("adaptor: driver returned no resumable checkpoint") // ErrThreadAlreadyExists: Fork's target key already has an active // conversation. The parent and existing target remain unchanged. ErrThreadAlreadyExists = errors.New("adaptor: thread already exists") // ErrResumeRejected: the driver refused to resume from the stored // checkpoint and the thread mode does not allow a fresh start. ErrResumeRejected = errors.New("adaptor: driver rejected thread resume") )
Session-coordination failures are infrastructure errors: plain wrapped errors without a Result, classified by sentinel so hosts can branch with errors.Is.
var ApprovalsAutoDeny = ApprovalPolicy{ Permission: driver.HumanDecisionAutoReject, PlanReview: driver.HumanDecisionAutoReject, Question: driver.QuestionAutoReject, }
ApprovalsAutoDeny is the ApprovalPolicy preset that explicitly denies every approval kind without asking. The bound Driver must advertise AutoReject for all three kinds; use a zero ApprovalPolicy for the portable conservative defaults when that capability is unavailable.
Functions ¶
This section is empty.
Types ¶
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent is a configured, ready-to-talk agent: one driver plus agent-level default settings. Construct with New; multiple agents are multiple Go variables (there is no central SDK object or named registry).
func New ¶
New constructs an Agent from a driver and agent-level default options. It is the single construction entry point for built-in and third-party drivers alike.
New panics when d is nil: a nil driver is a programmer error best caught at startup, not on the first Send.
func (*Agent) Close ¶
Close prevents new runs, cancels and drains admitted runs, closes every persistent provider process owned by the configured Driver, then closes the Agent-owned Tool runtime. It is idempotent; concurrent callers wait for the first close attempt or return ctx.Err() when their own deadline wins. Drivers without persistent-process support skip the process-close phase.
func (*Agent) ProfileState ¶
func (a *Agent) ProfileState(ctx context.Context) (ProfileSnapshot, error)
ProfileState reports the desired vs observed profile resource state without changing anything. Drivers that implement the profile resource extension answer authoritatively; for everyone else the SDK builds the snapshot from the desired payload and reports non-skill resources as desired-but-not-observed (synced=false) — the truthful-materialization contract.
func (*Agent) SelectSkills ¶
SelectSkills installs a process-local skill selection override: the given keys replace the agent-default refs for every subsequent Send/Thread resolution and Inspect().Skills report, until the next SelectSkills call. Keys must reference skills visible through the SkillProvider or the inline defaults (bare-key selection semantics — inline Skill values can only be introduced via WithSkills); unknown keys fail with ErrSkillNotFound and the override is NOT installed. The resolved selection is synced to the driver before the override takes effect.
func (*Agent) Send ¶
Send starts an independent stateless execution and returns immediately. Options merge ("nearer scope wins; skills append, everything else replaces"); the agent defaults are never mutated.
Send never returns a separate error: startup failures surface through the normal contract (closed Events channel + Result() error).
func (*Agent) SyncProfile ¶
func (a *Agent) SyncProfile(ctx context.Context) (ProfileSnapshot, error)
SyncProfile pushes the desired profile resources to the driver and reports the resulting state. Drivers with the profile resource extension perform the full sync; for everyone else the SDK syncs the one portable resource (skills, via the driver's skill support) and reports the rest as not-materialized errors (synced=true) rather than pretending they applied.
func (*Agent) Thread ¶
func (a *Agent) Thread(key string, opts ...ThreadOption) *Thread
Thread returns the conversation handle for key, continuing the stored conversation when one exists and starting fresh otherwise (continue-or-start). key is the host's own opaque business string and is stored and compared verbatim.
Without WithThreadStore, the Agent uses its own in-memory store. Thread panics on an empty key (programmer error, symmetric with New's nil-driver panic).
type AgentProfile ¶
type AgentProfile = driver.AgentProfile
AgentProfile is the driver-local profile report.
type AgentSettings ¶
type AgentSettings struct {
// RunSettings contains the defaults inherited by each invocation.
RunSettings
// contains filtered or unexported fields
}
AgentSettings = RunSettings (dual-scope fields) + construction-scope-only fields. The subset relation is expressed by struct embedding: a CallOption receives *RunSettings, on which the construction-only fields simply do not exist — the writable field set is the scope boundary.
func (*AgentSettings) SetBlockingEvents ¶
func (s *AgentSettings) SetBlockingEvents()
SetBlockingEvents enables ordinary-event backpressure; see WithBlockingEvents for critical-event and Result-only consumption semantics.
func (*AgentSettings) SetEventBuffer ¶
func (s *AgentSettings) SetEventBuffer(n int)
SetEventBuffer sets the per-run ordinary-event capacity. Critical events enqueue immediately even when ordinary capacity is exhausted.
func (*AgentSettings) SetProfile ¶
func (s *AgentSettings) SetProfile(sel profile.Selection)
SetProfile replaces the driver-native profile selection.
func (*AgentSettings) SetServiceManager ¶
func (s *AgentSettings) SetServiceManager(m ServiceManager)
SetServiceManager injects the runtime-service orchestration backend.
func (*AgentSettings) SetSkillMaterializer ¶
func (s *AgentSettings) SetSkillMaterializer(m SkillMaterializer)
SetSkillMaterializer overrides the skill materialization strategy.
func (*AgentSettings) SetSkillProvider ¶
func (s *AgentSettings) SetSkillProvider(p SkillProvider)
SetSkillProvider injects the skill provider used to resolve bare keys.
func (*AgentSettings) SetThreadStore ¶
func (s *AgentSettings) SetThreadStore(store threadstore.Store)
SetThreadStore injects the thread storage backend (stateful conversations).
func (*AgentSettings) SetWorkspaceManager ¶
func (s *AgentSettings) SetWorkspaceManager(m WorkspaceManager)
SetWorkspaceManager injects the workspace provisioning backend.
type ApprovalHandler ¶
type ApprovalHandler func(ctx context.Context, req *ApprovalRequest) error
ApprovalHandler is the callback form (form A) of approval consumption, installed with OnApproval. The handler must resolve the request — call Approve, Deny, or Answer — and return nil, or return an error to abort the run.
func ApproveAll ¶
func ApproveAll() ApprovalHandler
ApproveAll returns a ready-made handler that approves every Permission and PlanReview request. Questions are denied: they have no legitimate synthesized answer.
func DenyAll ¶
func DenyAll(reason string) ApprovalHandler
DenyAll returns a ready-made handler that denies every request with the given reason.
type ApprovalKind ¶
type ApprovalKind string
ApprovalKind labels the semantic category of an approval request.
const ( // ApprovalPermission covers tool, command, file, or permission gates. ApprovalPermission ApprovalKind = ApprovalKind(driver.HumanDecisionPermission) // ApprovalPlanReview covers plan-mode approval before execution. ApprovalPlanReview ApprovalKind = ApprovalKind(driver.HumanDecisionPlanReview) // ApprovalQuestion covers structured clarification questions. ApprovalQuestion ApprovalKind = ApprovalKind(driver.HumanDecisionQuestion) )
type ApprovalMode ¶
type ApprovalMode = driver.HumanDecisionMode
ApprovalMode routes one binary approval kind (Permission / PlanReview).
const ( // ApprovalInherit falls back to the SDK default (ask). ApprovalInherit ApprovalMode = driver.HumanDecisionUnset // ApprovalAsk routes the request to the host (callback or event form). ApprovalAsk ApprovalMode = driver.HumanDecisionAsk // ApprovalAutoApprove approves without asking (driver bypass path). ApprovalAutoApprove ApprovalMode = driver.HumanDecisionAutoApprove // ApprovalAutoDeny denies without asking. ApprovalAutoDeny ApprovalMode = driver.HumanDecisionAutoReject )
type ApprovalPolicy ¶
type ApprovalPolicy = driver.HumanDecisionPolicy
ApprovalPolicy carries the timeout / fallback / retry knobs for approval requests, plus the per-kind routing modes. It aliases the driver SPI HumanDecisionPolicy. Zero-valued fields inherit the package defaults (Permission/PlanReview ask, Question auto-deny, 30s timeout, abort on timeout/reject, 3 max retries).
type ApprovalRequest ¶
type ApprovalRequest struct {
// ID identifies this request (unique per run, fresh per retry).
ID string
// RunID is the SDK execution identifier of the owning run.
RunID string
// Kind is the request category; it gates which responder methods apply.
Kind ApprovalKind
// Title is the human-readable prompt to display.
Title string
// Source names the requesting surface (tool name, plan stage, ...).
Source string
// ToolCallID correlates a Permission request with the tool call that
// triggered it (permission field group).
ToolCallID string
// Choices are the renderable options of a Question request (question
// field group). Answer accepts one of the choice keys or free text.
Choices []Choice
// Details carries driver-specific structured request data.
Details map[string]any
// CreatedAt is when the current approval attempt was created.
CreatedAt time.Time
// Deadline bounds the response window; after it the ApprovalPolicy
// OnTimeout fallback applies.
Deadline time.Time
// Attempt is the zero-based retry attempt (FallbackRetry re-asks).
Attempt int
// contains filtered or unexported fields
}
ApprovalRequest is a human-in-the-loop request that carries its own responder. It arrives either through the OnApproval callback (form A) or as a *ApprovalRequest event on the Stream (form B); in both forms exactly one of Approve / Deny / Answer resolves it. Late or duplicate responses return ErrApprovalResolved; if nobody responds before Deadline, the ApprovalPolicy timeout fallback applies.
func (*ApprovalRequest) Answer ¶
func (r *ApprovalRequest) Answer(_ context.Context, option string) error
Answer resolves a Question request with the chosen option: one of the Choices keys, or free text for open questions. Calling it on a Permission / PlanReview request returns ErrApprovalKindMismatch.
func (*ApprovalRequest) Approve ¶
func (r *ApprovalRequest) Approve(_ context.Context) error
Approve resolves a Permission or PlanReview request positively. Calling it on a Question returns ErrApprovalKindMismatch; calling it after the request was resolved returns ErrApprovalResolved.
func (*ApprovalRequest) Deny ¶
func (r *ApprovalRequest) Deny(_ context.Context, reason string) error
Deny resolves any request kind negatively with a reason. What happens next is the ApprovalPolicy OnReject fallback (abort by default).
func (*ApprovalRequest) Forward ¶
func (r *ApprovalRequest) Forward(o Origin) *ApprovalRequest
Forward returns an attributed copy sharing the original exactly-once responder. Answering either copy resolves both; nil receivers return nil.
func (*ApprovalRequest) Origin ¶
func (r *ApprovalRequest) Origin() Origin
Origin reports where the request originated.
type Author ¶
type Author struct {
// Kind identifies the author authority.
Kind AuthorKind
// ID is the host-owned author identifier.
ID string
// Name is the optional display name.
Name string
}
Author identifies the origin of a message.
type AuthorKind ¶
type AuthorKind uint8
AuthorKind identifies a message's authority.
const ( // AuthorHuman identifies additional human guidance. AuthorHuman AuthorKind = iota + 1 // AuthorAgent identifies peer input without human authority. AuthorAgent // AuthorSystem identifies a host policy notice. AuthorSystem )
type CallOption ¶
type CallOption interface {
// ApplyRun writes the option into this call's effective settings.
ApplyRun(*RunSettings)
}
CallOption is the set Send accept. It writes the effective settings of one invocation (a clone of the agent defaults).
CallOption intentionally does NOT embed Option: call-scope-only options passed to New fail to compile too ("missing method ApplyNew"), keeping the misuse feedback symmetric in both directions.
func WithSchema ¶
func WithSchema[T any](opts ...SchemaOption) CallOption
WithSchema requests structured output matching Go type T for this invocation. The JSON Schema document is derived from T at option construction time; a derivation failure fails the run before the driver launches (schema bugs are programmer errors, never silent degradation). The SDK always prefers native enforcement and automatically falls back to prompt validation. The default invalid policy fails the run.
Call scope only — passing WithSchema to New is a compile error ("missing method ApplyNew"): a schema belongs to one question, not to the Agent.
func WithSchemaJSON ¶
func WithSchemaJSON(schemaJSON []byte, opts ...SchemaOption) CallOption
WithSchemaJSON requests structured output matching a raw JSON Schema document — the escape hatch for schemas that do not originate from a Go type (contract files, registry-served schemas). Generation-side SchemaOptions (SchemaInlineReferences, ...) have no effect here; the request-side ones (SchemaName / SchemaDescription / SchemaReturnInvalid) apply as usual. Call scope only.
type Checkpoint ¶
type Checkpoint = driver.Checkpoint
Checkpoint is the driver resume handle exposed for audit purposes. It aliases the driver SPI checkpoint so hosts can inspect it without importing the SPI package.
type Choice ¶
type Choice = driver.DecisionChoice
Choice is a single renderable option attached to an ApprovalQuestion request. It aliases the driver SPI type.
type ConfigSchema ¶
type ConfigSchema = driver.ConfigSchema
ConfigSchema describes the driver's configuration surface.
type Done ¶
type Done struct {
// Result is the final or per-turn outcome; business failures carry their partial Result in RunError.
Result *Result
// Err is the execution error or wrapped admission cause.
Err error
// contains filtered or unexported fields
}
Done is the authoritative last event, published after all finalization. Result and Err are identical to Stream.Result, including pointer identity.
type Driver ¶
Driver is the provider integration SPI implemented by built-in and third-party agent integrations. It aliases the driver package interface so hosts can reference the type (struct fields, function signatures) without importing the SPI package.
type DriverManagedWorkspace ¶
type DriverManagedWorkspace struct{}
DriverManagedWorkspace lets the Driver choose or create its own workspace according to its native behavior.
type Dropped ¶
type Dropped struct {
// Count is how many events were dropped since the previous marker.
Count int
// ByKind breaks Count down by the public event kind.
ByKind map[string]int
// FirstSequence is the first sequence number reserved for a discarded event.
FirstSequence uint64
// LastSequence is the last sequence number reserved for a discarded event.
LastSequence uint64
// Reason explains why events were lost.
Reason string
// Source identifies the component that reported the loss.
Source string
// Details preserves additional loss-report fields.
Details map[string]any
// contains filtered or unexported fields
}
Dropped is the aggregated backpressure marker: under the default drop strategy, events discarded because the consumer was slow are counted and surfaced as one Dropped event as soon as the channel has room again. See WithEventBuffer / WithBlockingEvents.
type EnvironmentCheck ¶
type EnvironmentCheck = driver.EnvironmentCheck
EnvironmentCheck is a single environment check line item.
type EnvironmentReport ¶
type EnvironmentReport = driver.EnvironmentReport
EnvironmentReport is the result of an environment health check.
type Event ¶
type Event interface {
// Meta returns the SDK-owned event envelope. Sequence and Time describe
// the order in which the unified sink accepted events, not a provider's
// protocol cursor. Provider values, when present, remain in Source.
Meta() EventMeta
// contains filtered or unexported methods
}
Event is the sealed interface implemented by every stream event type.
The interface is sealed (unexported method): the set of event types is an SDK contract, exhaustively listed in this file. Consumers dispatch with a type switch:
for ev := range stream.Events() {
switch e := ev.(type) {
case adaptor.TextDelta: io.WriteString(w, e.Text)
case adaptor.ToolCall: renderToolCard(e.Name, e.Args)
case adaptor.Thinking: renderReasoning(e.Text)
case *adaptor.ApprovalRequest: _ = e.Approve(ctx)
}
}
func WithEventMeta ¶
WithEventMeta returns ev with meta restored on a value copy. It is the narrow replay hook for bridges and persistent event recorders, whose wire envelope stores EventMeta separately from the typed event payload. A live run's sink always overwrites restored coordinates with its own authoritative run order before publication.
type EventMeta ¶
type EventMeta struct {
// RunID is the package-assigned execution identifier.
RunID string
// ThreadKey is the host's opaque Thread key, or empty for an Agent run.
ThreadKey string
// Sequence is the authoritative receive order within the run.
Sequence uint64
// Time is when the unified event sink accepted the event.
Time time.Time
// TurnID identifies a provider turn when the protocol exposes one.
TurnID string
// Source preserves provider envelope coordinates, when available.
Source *EventSourceMeta
}
EventMeta is the common, SDK-owned envelope carried by every Event. Sequence is strictly increasing for one run and is assigned while the event sink serializes producers. ThreadKey is the host's opaque key; a provider thread/session identifier, if any, is kept in Source.ThreadID.
type EventSourceMeta ¶
type EventSourceMeta struct {
// RunID is the provider-reported run identifier.
RunID string
// ThreadID is the provider-reported conversation identifier.
ThreadID string
// TurnID is the provider-reported turn identifier.
TurnID string
// Sequence is the provider-reported event sequence.
Sequence uint64
// Timestamp is the provider-reported event time.
Timestamp time.Time
}
EventSourceMeta preserves provider/driver envelope coordinates without allowing them to compete with the SDK's authoritative EventMeta fields.
type FailureReason ¶
type FailureReason string
FailureReason classifies a business-level run failure.
const ( // ReasonLimitExceeded means unfinished work was aborted by an execution limit. ReasonLimitExceeded FailureReason = "limit_exceeded" // ReasonApprovalDenied means an approval was denied, including an // automatically denied request. ReasonApprovalDenied FailureReason = "approval_denied" // ReasonApprovalTimeout means an approval deadline elapsed. ReasonApprovalTimeout FailureReason = "approval_timeout" // ReasonAgentError: the driver classified an agent-level failure // (bad protocol, non-zero exit, handler panic, ...). ReasonAgentError FailureReason = "agent_error" // ReasonCancelled: the run was cancelled after producing a classified // business failure (as opposed to a bare context cancellation, which // surfaces as a plain error wrapping ctx.Err()). ReasonCancelled FailureReason = "cancelled" // ReasonPolicyViolation means policy validation failed. ReasonPolicyViolation FailureReason = "policy_violation" )
type FallbackAction ¶
type FallbackAction = driver.FailureAction
FallbackAction selects what happens when an approval times out (ApprovalPolicy.OnTimeout) or is denied (ApprovalPolicy.OnReject).
const ( // FallbackInherit falls back to the SDK default (abort). FallbackInherit FallbackAction = driver.FailureActionUnset // FallbackAbort terminates the run with a business failure. FallbackAbort FallbackAction = driver.FailureAbort // FallbackContinue forwards the outcome to the agent so the run can // progress. FallbackContinue FallbackAction = driver.FailureContinue // FallbackRetry re-asks the same decision, bounded by MaxRetries; // drivers without retry support degrade to abort with a warning // Notice on the stream. FallbackRetry FallbackAction = driver.FailureRetry )
type FeatureLevel ¶
type FeatureLevel = driver.FeatureLevel
FeatureLevel gates optional capabilities (web search, browser tooling).
const ( // FeatureInherit leaves the capability to the agent default or the // driver's own fallback. FeatureInherit FeatureLevel = driver.FeatureInherit // FeatureAllow explicitly enables the capability when supported. FeatureAllow FeatureLevel = driver.FeatureAllow // FeatureDeny explicitly disables the capability. FeatureDeny FeatureLevel = driver.FeatureDeny )
type GitWorktreeWorkspace ¶
type GitWorktreeWorkspace struct {
// BaseRef is the git revision from which the worktree is created.
BaseRef string
// BranchTemplate is the host-defined template for naming a worktree branch.
BranchTemplate string
// WorktreeParentDir is the directory under which worktrees are created.
WorktreeParentDir string
}
GitWorktreeWorkspace requests an isolated git worktree for the run.
type HumanDecisionModeUnsupportedError ¶
type HumanDecisionModeUnsupportedError = driver.HumanDecisionModeUnsupportedError
HumanDecisionModeUnsupportedError reports the rejected kind, mode, and Driver capability matrix.
type Identity ¶
type Identity struct {
// ID is the logical agent identifier.
ID string
// Tenant partitions catalogues and stores by tenant.
Tenant string
// Profile partitions user-private resources within a tenant.
Profile string
// Name is the logical agent display name.
Name string
}
Identity is host-supplied caller identity propagated into SDK hooks and the driver request. The SDK does not use these fields for routing; they exist so host-provided components (SkillProvider, WorkspaceManager, ServiceManager) can scope lookups without inventing their own context keys.
func IdentityFromContext ¶
IdentityFromContext returns the Identity the SDK injected into ctx before invoking provider hooks or the driver. Implementations that need scoping (Tenant for catalogue partitioning, Profile for user-private skills, ...) read it via this helper. The boolean is false when ctx carries no identity (e.g. a provider invoked directly in tests without SDK plumbing).
type Inspector ¶
type Inspector struct {
// contains filtered or unexported fields
}
Inspector is the read-only inspection panel of one Agent, obtained via Agent.Inspect(). Every method degrades honestly when the driver does not implement the corresponding probe: a descriptor-derived or explicitly "unsupported" report, never a fabricated success.
func (Inspector) ConfigSchema ¶
func (in Inspector) ConfigSchema(ctx context.Context) (*ConfigSchema, error)
ConfigSchema returns the driver's configuration schema (driver.ConfigSchemaProvider), falling back to the descriptor's static schema. The returned schema is a copy.
func (Inspector) Environment ¶
func (in Inspector) Environment(ctx context.Context) (EnvironmentReport, error)
Environment runs the driver's environment health check (driver.EnvironmentProbe). Drivers without the probe report a single informational "noop" check — visible, not invented.
func (Inspector) Models ¶
Models lists the models the agent can run (driver.ModelLister). Drivers without the prober fall back to the static descriptor model list.
func (Inspector) Quota ¶
func (in Inspector) Quota(ctx context.Context) (QuotaReport, error)
Quota reports live quota/billing state (driver.QuotaProbe). Drivers without the probe report Available=false with an explanatory error string.
func (Inspector) Skills ¶
func (in Inspector) Skills(ctx context.Context) (SkillSnapshot, error)
Skills resolves and reports the agent's effective skill set: the default refs (or the SelectSkills override when one is active) resolved against the provider, with the inline defaults + the provider catalogue as non-selected candidates. The snapshot's sync mode reports truthfully whether the Driver can observe installed skills through driver.SkillSupport or the SDK only knows the desired set.
type InvalidDriverConfigError ¶
type InvalidDriverConfigError = driver.InvalidDriverConfigError
InvalidDriverConfigError reports a rejected captured Driver config.
type InvalidOutputSchemaError ¶
type InvalidOutputSchemaError = driver.InvalidOutputSchemaError
InvalidOutputSchemaError reports an invalid or underivable schema.
type InvalidPolicyError ¶
type InvalidPolicyError = driver.InvalidPolicyError
InvalidPolicyError reports one out-of-domain Policy field.
type MessageContext ¶
type MessageContext struct {
// ID is the opaque message identifier.
ID string
// Text is the original unframed message, unless documented otherwise.
Text string
// From identifies the message author.
From Author
// Timing is the requested delivery timing.
Timing Timing
}
MessageContext is the input to a supplemental-message formatting function.
func MessageAttributes ¶
func MessageAttributes(opts ...CallOption) MessageContext
MessageAttributes reads message options from a call without generating an ID. Defaults are AuthorHuman and Soon; later options override earlier ones. Execution options are ignored, so inspecting attributes has no execution or resource side effects. Text is empty in the returned context.
type MessageError ¶
type MessageError struct {
// ID is the opaque message identifier.
ID string
// Text is the original unframed message, unless documented otherwise.
Text string
// Reason classifies delivery failure; it is empty on success.
Reason MessageFailure
// Err is the execution error or wrapped admission cause.
Err error
}
MessageError returns a rejected message's original text and wrapped cause.
func (*MessageError) Error ¶
func (e *MessageError) Error() string
Error describes the rejected message and its cause.
func (*MessageError) Unwrap ¶
func (e *MessageError) Unwrap() error
Unwrap exposes the admission error for errors.Is and errors.As.
type MessageFailure ¶
type MessageFailure string
MessageFailure explains why a message could not be delivered.
const ( // MessageCancelled means the execution or unclaimed sender was cancelled. MessageCancelled MessageFailure = "cancelled" // MessageProviderRejected means the provider rejected delivery. MessageProviderRejected MessageFailure = "provider_rejected" // MessageTimeout means delivery timed out. MessageTimeout MessageFailure = "timeout" // MessageLimitExceeded means no further turns may start. MessageLimitExceeded MessageFailure = "limit_exceeded" // MessageRunFailed means the execution failed before delivery. MessageRunFailed MessageFailure = "run_failed" )
type MessageOption ¶
type MessageOption interface {
CallOption
// contains filtered or unexported methods
}
MessageOption configures a message and is also accepted when starting an execution. Execution options such as WithModel do not implement this interface.
func From ¶
func From(a Author) MessageOption
From identifies the message's author. The default is AuthorHuman.
func MessageID ¶
func MessageID(id string) MessageOption
MessageID supplies an opaque Thread-scoped idempotency key. Empty generates one. Delivered IDs are retained for the most recent 1000 messages or seven days. Repeating a delivered ID acknowledges its receipt without another delivery; a duplicate starting prompt completes with zero Turns and empty Text.
func When ¶
func When(t Timing) MessageOption
When selects the supplemental delivery timing; starting prompts always start immediately.
type MessageOutcome ¶
type MessageOutcome struct {
// ID is the opaque message identifier.
ID string
// Text is the original unframed message, unless documented otherwise.
Text string
// From identifies the message author.
From Author
// Timing is the requested delivery timing.
Timing Timing
// State is the message or delegated task lifecycle state.
State MessageState
// Turn is the one-based provider turn; zero means delivery is not assigned yet.
Turn int
// Boundary is immediate, tool, stop, or turn_end when delivery was attempted.
Boundary string
// Mechanism names the provider or core delivery mechanism.
Mechanism string
// Reason classifies delivery failure; it is empty on success.
Reason MessageFailure
}
MessageOutcome is an admitted message's final outcome, in admission order. Text is always the original unframed text.
type MessagePolicy ¶
type MessagePolicy struct {
// Disabled omits Request.Messages and rejects supplemental sends.
Disabled bool
// Format replaces the built-in author framing; nil uses the built-in templates.
Format func(MessageContext) string
// MaxPending bounds unclaimed messages; zero means 32. Full queues block Send until space or context cancellation.
MaxPending int
// MaxTurns bounds provider turns in one execution; zero means 20.
// Stop continuations and interrupt restarts reserve a successor before
// delivery. If none remains, input stays pending and fails with
// MessageLimitExceeded and its original text when execution ends.
// With at least two turns, a limit.approaching notice is emitted after
// min(ceil(0.8*MaxTurns), MaxTurns-1) turns. Its AuthorSystem wrap-up
// instruction precedes host messages in a nonempty claim when the combined
// framed batch fits the Driver's resolved limit; otherwise it stays deferred.
// It never starts a turn by itself. Only successfully acknowledged delivery
// of this instruction appears in outcomes, transcripts and receipts.
MaxTurns int
}
MessagePolicy controls supplemental delivery and bounds execution growth. Zero MaxPending and MaxTurns mean 32 and 20 respectively.
type MessageState ¶
type MessageState uint8
MessageState is the public lifecycle of an admitted message.
const ( // MessageAccepted means the message is queued or claimed. MessageAccepted MessageState = iota + 1 // MessageDelivered means the provider accepted delivery. MessageDelivered // MessageFailed means delivery ended unsuccessfully. MessageFailed )
type MessageUpdate ¶
type MessageUpdate struct {
// ID is the opaque message identifier.
ID string
// State is the message or delegated task lifecycle state.
State MessageState
// Turn is the one-based provider turn; zero means delivery is not assigned yet.
Turn int
// Boundary is immediate, tool, stop, or turn_end when delivery was attempted.
Boundary string
// Mechanism names the provider or core delivery mechanism.
Mechanism string
// Reason classifies delivery failure; it is empty on success.
Reason MessageFailure
// Text is the original unframed message, unless documented otherwise.
Text string
// contains filtered or unexported fields
}
MessageUpdate records admission, delivery, requeue, or failure. It is never dropped. Text contains the original message on failure.
type Notice ¶
type Notice struct {
// Kind is one of the Notice* constants (unknown driver-specific kinds
// pass through verbatim so no information is lost).
Kind string
// Text is the human-readable message.
Text string
// Item is the transcript entry (NoticeTranscriptItem only).
Item *TranscriptItem
// Metadata carries short string tags from the driver.
Metadata map[string]string
// Data carries structured details.
Data map[string]any
// contains filtered or unexported fields
}
Notice is a low-frequency operational event: invocation metadata, lifecycle markers, runtime-service reports, progressive transcript items, and approval lifecycle broadcasts. Consumers that do not care simply omit the case.
type Option ¶
type Option interface {
// ApplyNew writes the option into the agent-level default settings.
ApplyNew(*AgentSettings)
}
Option is the full set New accepts. It writes agent-level defaults.
Passing an Option-only value (WithThreadStore, WithEventBuffer, ...) to Send does not compile: "adaptor.Option does not implement adaptor.CallOption (missing method ApplyRun)" means the option is construction-scope only.
func WithBlockingEvents ¶
func WithBlockingEvents() Option
WithBlockingEvents makes ordinary Emit/EmitStream producers wait while the combined channel and queue are at capacity. Waiting releases internal locks; Cancel and context cancellation release blocked producers. Critical lifecycle, message, turn, approval, notice and drop events always enqueue immediately. A Result-only caller discards ordinary events and retains a critical-only log with a Dropped summary; call Events first to consume ordinary events. Construction scope only.
func WithEventBuffer ¶
WithEventBuffer sets the per-run ordinary-event capacity (default 1024). Capacity counts buffered and queued events. Critical lifecycle, message, turn, approval, notice and drop events always enqueue immediately, even at capacity. Default drop mode aggregates discarded deltas into Dropped. Construction scope only.
func WithProfile ¶
WithProfile selects the driver-native profile strategy (profile.Native / profile.Dedicated / profile.CloneNative / profile.Default). Construction scope only: the profile is part of what the Agent is, participates in session fingerprints, and cannot be swapped per call.
func WithServiceManager ¶
func WithServiceManager(m ServiceManager) Option
WithServiceManager installs the backend that starts or locates the services declared with WithServices, and releases the run-scoped ones afterwards. Construction scope only.
func WithSkillMaterializer ¶
func WithSkillMaterializer(m SkillMaterializer) Option
WithSkillMaterializer overrides how non-path skill sources are staged to disk. Construction scope only.
func WithSkillProvider ¶
func WithSkillProvider(p SkillProvider) Option
WithSkillProvider installs the skill provider that resolves bare keys (and, when it implements a Catalogue method, feeds Inspect().Skills). Construction scope only: the provider is part of the Agent's identity, not a per-call knob.
func WithThreadStore ¶
func WithThreadStore(store threadstore.Store) Option
WithThreadStore injects the thread storage backend that enables stateful conversations: with it, Agent.Thread persists and resumes driver checkpoints across runs and processes (memory.NewStore() for single-process hosts, a durable implementation for services). Without it Threads use a private in-memory store. Construction scope only; passing it to Send is a compile error (missing method ApplyRun).
func WithTools ¶
func WithTools(definitions ...tool.Definition) Option
WithTools installs the immutable host-defined Tool set owned by this Agent. It is construction-scope only: Tools are a stable capability and authorization surface, so passing WithTools to Send is a compile error. Repeated WithTools options replace the whole set; WithTools() clears an earlier declaration.
Tool definitions and their schemas are validated before the Driver starts. The SDK exposes them to provider CLIs through a private, authenticated local runtime; applications do not need to configure MCP or manage another lifecycle object. Agent.Close closes that runtime.
func WithWorkspaceManager ¶
func WithWorkspaceManager(m WorkspaceManager) Option
WithWorkspaceManager installs the backend that turns a WorkspaceSpec into a concrete working-directory lease (git worktrees, sandboxes, an external workspace service). Without one, specs resolve through the SDK's passthrough manager, which leases the base directory unchanged. Construction scope only: the manager is infrastructure the Agent is built on, not a per-call knob.
type Origin ¶
type Origin struct {
// Member is the composite Runner's member key.
Member string
// Task is the delegated task identifier.
Task string
}
Origin attributes an approval to a composite Runner's member and task. Single-agent requests have a zero Origin.
type Phase ¶
type Phase string
Phase marks lifecycle boundaries on the streaming event types (TextDelta, Thinking, ToolCall). The zero value is the content-bearing middle of the lifecycle, so consumers that only care about content can ignore the field: start/end boundary events simply carry empty content.
type Policy ¶
type Policy struct {
// Messages bounds and formats supplemental messages in this execution.
Messages MessagePolicy
// Sandbox is the filesystem / process boundary strength.
Sandbox SandboxLevel
// WebSearch gates the provider's web-search capability.
WebSearch FeatureLevel
// Browser gates the provider's browser tooling.
Browser FeatureLevel
// Approvals routes and bounds human-in-the-loop requests: per-kind
// modes (ask / auto-approve / auto-deny), the response Timeout, the
// OnTimeout / OnReject fallbacks, and MaxRetries. Zero-valued fields
// inherit the package defaults (Permission/PlanReview ask, Question
// auto-deny, 30s timeout, abort on timeout/reject, 3 retries). See ApprovalPolicy
// and the ApprovalsAutoDeny preset.
Approvals ApprovalPolicy
}
Policy is the execution guardrail contract set via WithPolicy. Values are not CLI flag names: each driver maps them to provider-specific controls.
As an option value, Policy replaces as a whole ("nearer scope wins; everything but skills replaces"): a call-site WithPolicy substitutes the agent-default Policy entirely. Zero fields mean "inherit" at the driver boundary, so an all-zero Policy defers every dimension to the driver.
type PolicyCapabilityUnsupportedError ¶
type PolicyCapabilityUnsupportedError = driver.PolicyCapabilityUnsupportedError
PolicyCapabilityUnsupportedError reports the rejected dimension, value, and Driver.
type ProcessInfo ¶
type ProcessInfo struct {
// Kind is ProcessSpawn, ProcessStdout, or ProcessStderr.
Kind string
// Text is the human-readable description (spawn).
Text string
// Bytes is the raw chunk (stdout/stderr); it may not align to lines.
Bytes []byte
// Metadata carries short string tags from the driver.
Metadata map[string]string
// Data carries structured driver-specific extensions.
Data map[string]any
// contains filtered or unexported fields
}
ProcessInfo carries process-level operational signals: child-process spawn details and raw stdout/stderr chunks. Most consumers ignore it; debugging and audit tooling reads it from the same stream instead of a second channel.
type ProfileKind ¶
type ProfileKind string
ProfileKind classifies where the effective provider profile lives.
const ( // user configuration. ProfileKindShared ProfileKind = "shared" // ProfileKindHostManaged identifies a profile whose lifecycle is managed // by the embedding host. ProfileKindHostManaged ProfileKind = "host_managed" )
type ProfileResourceKind ¶
type ProfileResourceKind string
ProfileResourceKind names one provider-visible resource family.
const ( // ProfileResourceSkills identifies skill resources. ProfileResourceSkills ProfileResourceKind = "skills" // ProfileResourceMCP identifies MCP server resources. ProfileResourceMCP ProfileResourceKind = "mcp" // ProfileResourceAgents identifies sub-agent declarations. ProfileResourceAgents ProfileResourceKind = "agents" // ProfileResourceHooks identifies hook declarations. ProfileResourceHooks ProfileResourceKind = "hooks" // ProfileResourceInstructions identifies instruction resources. ProfileResourceInstructions ProfileResourceKind = "instructions" // ProfileResourceConfig identifies provider configuration patches. ProfileResourceConfig ProfileResourceKind = "config" )
type ProfileResourceMaterialization ¶
type ProfileResourceMaterialization string
ProfileResourceMaterialization describes how a desired resource became provider-visible.
const ( // ProfileResourceMaterializationNativeManaged means the provider manages // the resource natively. ProfileResourceMaterializationNativeManaged ProfileResourceMaterialization = "native_managed" // ProfileResourceMaterializationFileManaged means the package materialized // the resource as provider configuration files. ProfileResourceMaterializationFileManaged ProfileResourceMaterialization = "file_managed" // ProfileResourceMaterializationPromptInjected means the resource was // injected into the run instructions. ProfileResourceMaterializationPromptInjected ProfileResourceMaterialization = "prompt_injected" // ProfileResourceMaterializationFallback means a documented fallback was // used. ProfileResourceMaterializationFallback ProfileResourceMaterialization = "fallback" // ProfileResourceMaterializationNotMaterialized means the desired resource // was not made visible to the provider. ProfileResourceMaterializationNotMaterialized ProfileResourceMaterialization = "not_materialized" )
type ProfileResourceSupport ¶
type ProfileResourceSupport string
ProfileResourceSupport describes how portable a resource is for the bound driver.
const ( // ProfileResourceSupportPortableCore is supported by every conforming // Driver through the portable core contract. ProfileResourceSupportPortableCore ProfileResourceSupport = "portable_core" // ProfileResourceSupportPortableExtended is supported through an optional // portable Driver extension. ProfileResourceSupportPortableExtended ProfileResourceSupport = "portable_extended" // ProfileResourceSupportNativeEscape requires provider-native handling. ProfileResourceSupportNativeEscape ProfileResourceSupport = "native_escape" // ProfileResourceSupportFallback uses a documented fallback representation. ProfileResourceSupportFallback ProfileResourceSupport = "fallback" // ProfileResourceSupportUnsupported means the Driver cannot represent the // resource. ProfileResourceSupportUnsupported ProfileResourceSupport = "unsupported" )
type ProfileSnapshot ¶
type ProfileSnapshot struct {
// DriverType identifies the configured Driver.
DriverType string
// Profile is the Driver's observed native profile report.
Profile AgentProfile
// Kind classifies how the effective profile is managed.
Kind ProfileKind
// Fingerprint identifies the complete desired profile state.
Fingerprint string
// Resources reports desired and observed state by resource family.
Resources []ResourceSnapshot
// Warnings contains profile-wide non-fatal diagnostics.
Warnings []string
}
ProfileSnapshot reports the desired versus observed profile resource state returned by Agent.ProfileState and Agent.SyncProfile.
type QuestionMode ¶
type QuestionMode = driver.QuestionMode
QuestionMode routes the Question kind. Auto-approve is intentionally absent: a question has no legitimate synthesized answer.
const ( // QuestionInherit falls back to the SDK default (auto-deny). QuestionInherit QuestionMode = driver.QuestionUnset // QuestionAsk routes the question to the host. QuestionAsk QuestionMode = driver.QuestionAsk // QuestionAutoDeny denies questions without asking. QuestionAutoDeny QuestionMode = driver.QuestionAutoReject )
type QuotaReport ¶
type QuotaReport = driver.QuotaReport
QuotaReport is the live quota/billing snapshot (Available=false when the driver cannot observe quota).
type RawStreams ¶
type RawStreams = driver.RawStreams
RawStreams captures the complete raw stdout/stderr of one run.
type ResourceSnapshot ¶
type ResourceSnapshot struct {
// Kind identifies the resource family.
Kind ProfileResourceKind
// Fingerprint is the deterministic fingerprint of the desired resource.
Fingerprint string
// Managed lists resources controlled by this Agent's profile lifecycle.
Managed []string
// External lists provider-visible resources not controlled by this Agent.
External []string
// Support describes the Driver's portability level for the resource.
Support ProfileResourceSupport
// Materialization describes how the desired resource became visible to the
// provider.
Materialization ProfileResourceMaterialization
// Warnings contains non-fatal observation or materialization diagnostics.
Warnings []string
// Error contains a resource-specific failure message, or is empty when the
// resource has no reported failure.
Error string
}
ResourceSnapshot is one resource row inside a ProfileSnapshot.
type Result ¶
type Result struct {
// Turns is the number of provider turns in this execution.
Turns int
// RunID is the SDK-assigned execution identifier.
RunID string
// Model is the effective model reported by the driver.
Model string
// Provider is the upstream provider reported by the driver.
Provider string
// Text is the final assistant-facing text. It never contains raw
// stdout/stderr dumps, Summary text, or provider terminal JSON.
Text string
// Summary is a short host-facing label suitable for lists and logs,
// deliberately separate from Text.
Summary string
// Usage is normalized token/cost accounting. nil means the provider did
// not report usage; a non-nil zero value means usage was observed and all
// normalized metrics were explicitly zero.
Usage *Usage
// Metadata is Driver-reported result metadata.
Metadata map[string]string
// contains filtered or unexported fields
}
Result is the outcome of one successful run. High-frequency fields are flat; audit surfaces are gathered behind Raw() / Transcript() / Services(); structured output decodes via Decode.
A run that completed but failed at the business level does not return a Result directly — it returns a *RunError whose Result field carries this same value (see RunError).
func ComposeResults ¶
ComposeResults combines child executions in order using core's multi-turn aggregation. Nil parts are ignored. Text, model, summary, metadata and structured output come from the last part; usage and turns are summed; audit slices, messages and subagents are concatenated. Raw stdout/stderr are concatenated and the last observed terminal payload is retained (RawStreams has one terminal slot). Message turn numbers are rebased onto the composite turn sequence; zero (unassigned) stays zero. The result owns detached copies and uses runID.
func RunAs ¶
func RunAs[T any](ctx context.Context, r Runner, prompt string, opts ...CallOption) (T, *Result, error)
RunAs runs one prompt and decodes the structured output into T. It accepts any Runner, so stateless Agents and stateful Threads work interchangeably:
triage, res, err := adaptor.RunAs[Triage](ctx, agent, prompt)
RunAs prepends WithSchema[T]() to the call options; explicit options (including another WithSchema) apply after it and win. On a run error the zero T is returned together with Run's (*Result, error) contract; on success a decode failure surfaces as the returned error with the Result still available.
func (*Result) Decode ¶
Decode unmarshals the run's structured output into v.
When the run requested structured output (WithSchema[T] / RunAs[T]), the validated payload is the only source: invalid output (possible under SchemaReturnInvalid — the default policy fails the run instead) and empty RawJSON are errors. Runs without a schema fall back to interpreting Text as a JSON document — the schema-less convenience decode.
func (*Result) Messages ¶
func (r *Result) Messages() []MessageOutcome
Messages returns the final message outcomes in admission order.
func (*Result) Raw ¶
func (r *Result) Raw() RawStreams
Raw returns the complete raw stdout/stderr and exact provider terminal JSON captured during the run — the stable audit/replay surface. It is deliberately separate from Text and Transcript (the layers never contaminate each other). The returned Terminal and JSON bytes are deep copies.
func (*Result) Services ¶
func (r *Result) Services() []ServiceReport
Services returns the runtime-service execution reports for this run. Reports observed by the driver are merged by stable service ID with reports from services the SDK actually ensured; driver fields override matching SDK fields and missing fields are filled from the SDK observation. The returned values, including Metadata maps, are copies.
The report deliberately does not echo the typed ServiceRef.MCP declaration. Three reasons, in order of weight:
- Direction. ServiceRef.MCP is pre-run *input* the host itself authored (via WithServices or the provider it installed); ServiceReport is post-run *observation*. Echoing an input back as an observation invites hosts to read a declaration as evidence the server was actually reached, which no driver reports today.
- Fill honesty. Reports come from the driver (Response.RuntimeServices). A driver echoing a report cannot know the SDK-side MCP declaration, so the field would be populated on the SDK fallback path and empty on the driver path — the exact "sometimes true" shape the SDK avoids.
- Secrecy. The ref→report projection already drops SecretEnv on purpose. MCP carries the endpoint URL and BearerTokenEnvVar next to it; putting that pair into the surface hosts log wholesale works against the same rule.
Hosts that need the declaration have it: it is the value they passed in.
func (*Result) Subagents ¶
func (r *Result) Subagents() []SubagentResult
Subagents returns copies of the delegated task summaries.
func (*Result) Transcript ¶
func (r *Result) Transcript() []TranscriptItem
Transcript returns the normalized semantic item stream parsed by the driver. The returned slice is a copy.
func (*Result) Undelivered ¶
func (r *Result) Undelivered() []MessageOutcome
Undelivered returns failed messages with their original text.
func (*Result) WithSubagents ¶
func (r *Result) WithSubagents(subagents []SubagentResult) *Result
WithSubagents returns a detached copy with the supplied collected task snapshot. It preserves the other result fields, including observed Usage; replacing summaries does not add their usage again. A nil receiver is treated as an empty result.
type Role ¶
Role identifies the speaker of a text event. It aliases the driver SPI type; the zero value is RoleAssistant.
type RunAttachment ¶
type RunAttachment struct {
// Preamble is prepended to the execution prompt; it is excluded from Thread compatibility.
Preamble string
// Results is called once during finalization, before DetachRun, to collect task summaries.
Results func() []SubagentResult
// Services are the concrete endpoints this provider ensured for the run.
Services []ServiceRef
// Events optionally streams provider-side events into the run.
Events RunEventSource
}
RunAttachment is what one provider contributes to one run.
Services are merged into the run's runtime payload and — for every ref carrying a typed MCP field — appended to the driver's MCP server set. The host's own WithMCP declaration is preserved: attachment servers are added alongside it, never in place of it. A ref's URL, MCP.BearerTokenEnvVar, and SecretEnv together are how a per-run endpoint publishes an authenticated MCP server without the token ever entering a public report: SecretEnv reaches the driver process environment only.
Events, when non-nil, is folded straight into the run's single event channel, interleaved with the driver's own events — there is no second stream to merge and no wrapper goroutine on the driver's hot path.
type RunError ¶
type RunError struct {
// Reason classifies the failure.
Reason FailureReason
// Message is the human-readable failure message from the driver/SDK.
Message string
// Details carries driver-specific structured failure metadata.
Details map[string]any
// Result is the full result of the completed-but-failed run. It is
// always non-nil when the SDK returns a *RunError.
Result *Result
}
RunError is the typed error for a run that completed but failed at the business level (approval denied / timed out, policy violation, agent error). It follows the *exec.ExitError convention: the error carries the full execution Result, so partial output, usage, and the transcript stay accessible on the failure path.
type RunEventSource ¶
RunEventSource subscribes to one run's provider-side events, already projected onto the SDK event vocabulary (delegation providers emit SubagentUpdate).
Contract: the returned channel must be closed once ctx is done, and every event already published for the run must be delivered before that close. The SDK drains the channel to closure before it closes the run's event channel, so a source that abandons its tail on cancellation clips terminal events — flush first, then close. RunStarted and RunFinished are reserved for the core-owned merged-run envelope and are filtered if a source supplies them. A nil channel is treated as "no events".
type RunFinished ¶
type RunFinished struct {
// RunID is the run identifier reported by the Driver event.
RunID string
// ThreadID is the provider conversation identifier, when reported.
ThreadID string
// Usage is the token accounting reported on normal completion.
Usage *Usage
// Failed reports that this is a run.error terminal marker.
Failed bool
// Reason classifies the failure (Failed == true).
Reason FailureReason
// Message is the driver's failure message (Failed == true).
Message string
// contains filtered or unexported fields
}
RunFinished marks the end of a streamed run. Translated from run.finished (Failed == false, Usage populated when the driver reports it) and run.error (Failed == true with the classified Reason / Message).
RunFinished is informational: the authoritative outcome — including the full Result and the typed *RunError — comes from Done and Stream.Result().
type RunServiceProvider ¶
type RunServiceProvider interface {
// AttachRun binds the provider's service to one run.
AttachRun(ctx context.Context, runID string) (RunAttachment, error)
// DetachRun releases everything AttachRun bound to the run.
DetachRun(ctx context.Context, runID string) error
}
RunServiceProvider is the extension point ecosystem packages implement to bind a live, run-scoped service to every invocation of an Agent. It is the mechanism behind delegation.Service.Option(): the root package never learns the word "team" — it only knows that something asked to be attached to this run, and that whatever it returns must reach the driver and the event stream.
Lifecycle, per run:
AttachRun(ctx, runID) — after workspace and declared runtime services are
resolved, but before request/MCP resolution and
Driver dispatch. Returning an error is a pre-launch
failure: the Driver never starts, the error surfaces
through Result(), and every provider already attached
for this run is detached again.
... the run ...
DetachRun(ctx, runID) — after provider events have flushed, but before the
run's terminal event and channel close. The SDK uses
a cancellation-detached, bounded context so teardown
is attempted after cancellation without allowing a
broken hook to wedge Result. Errors are joined into
the observable run outcome.
Implementations must be safe for concurrent runs of the same Agent: AttachRun and DetachRun are keyed by run ID and may overlap.
type RunSettings ¶
type RunSettings struct {
// contains filtered or unexported fields
}
RunSettings collects every setting that can be overridden at the call site. Fields are unexported; ecosystem packages write through the exported methods below, whose semantics encode the merge rule (Set* replaces, Add* appends). The root package's own options go through the same methods so the extension surface stays self-validating.
func (*RunSettings) AddRunServiceProvider ¶
func (s *RunSettings) AddRunServiceProvider(p RunServiceProvider)
AddRunServiceProvider appends a run-scoped service provider — the controlled extension surface behind ecosystem options such as delegation.Service.Option(). Providers append rather than replace, and a provider already present is not added twice: the same option value used in both New and Send attaches exactly once, which is what keeps its MCP server key unique (a duplicate would fail the run before launch).
func (*RunSettings) AddSkills ¶
func (s *RunSettings) AddSkills(refs ...skill.Ref)
AddSkills appends skill references for the target scope — the single append-merged option family: call-site refs never displace the agent defaults, they extend them.
func (*RunSettings) CapMessageTurns ¶
func (s *RunSettings) CapMessageTurns(remaining int)
CapMessageTurns lowers the resolved turn budget without replacing other policy fields. Composite runners apply this after caller options to enforce their remaining budget. Nonpositive values panic as a programming error.
func (*RunSettings) SetAgents ¶
func (s *RunSettings) SetAgents(specs []driver.AgentSpec)
SetAgents replaces the sub-agent spec set and declares the resource. An empty slice declares "explicitly no sub-agents".
func (*RunSettings) SetApprovalHandler ¶
func (s *RunSettings) SetApprovalHandler(h ApprovalHandler)
SetApprovalHandler replaces the approval callback (form A of approval consumption). A nil handler restores event-form consumption.
func (*RunSettings) SetConfigPatches ¶
func (s *RunSettings) SetConfigPatches(patches []driver.ProfileConfigPatch)
SetConfigPatches replaces the profile config patch set and declares the resource. An empty slice declares "explicitly no patches".
func (*RunSettings) SetHooks ¶
func (s *RunSettings) SetHooks(specs []driver.HookSpec)
SetHooks replaces the hook spec set and declares the resource. An empty slice declares "explicitly no hooks".
func (*RunSettings) SetIdentity ¶
func (s *RunSettings) SetIdentity(id Identity)
SetIdentity replaces the caller identity propagated to host hooks and the driver.
func (*RunSettings) SetInstructions ¶
func (s *RunSettings) SetInstructions(text string)
SetInstructions replaces the extra instruction text handed to the driver and declares the instructions resource as host-managed. Empty text clears the effective instructions (an explicit clear still declares).
func (*RunSettings) SetInstructionsBundle ¶
func (s *RunSettings) SetInstructionsBundle(ref *driver.InstructionsBundleRef)
SetInstructionsBundle replaces the full instruction bundle (path- or content-based) and declares the instructions resource. A nil ref clears the effective bundle while still declaring the resource.
func (*RunSettings) SetMCPServers ¶
func (s *RunSettings) SetMCPServers(servers []mcp.Server)
SetMCPServers replaces the MCP server set as a whole value. An empty (or nil) slice is an explicit clear: it substitutes the agent default with "no servers" rather than inheriting it.
func (*RunSettings) SetMetadata ¶
func (s *RunSettings) SetMetadata(k, v string)
SetMetadata sets one audit metadata key. Keys merge per key: a call-site value overrides the same key from the agent defaults and leaves the other default keys intact.
func (*RunSettings) SetModel ¶
func (s *RunSettings) SetModel(m string)
SetModel replaces the effective model for the target scope. Empty and whitespace-only values mean no override, matching the Driver Request contract and preventing an all-space model name from reaching providers.
func (*RunSettings) SetOutputSchema ¶
func (s *RunSettings) SetOutputSchema(schema driver.OutputSchema)
SetOutputSchema replaces the structured output request for this run.
func (*RunSettings) SetOutputSchemaError ¶
func (s *RunSettings) SetOutputSchemaError(err error)
SetOutputSchemaError records a schema construction failure. The run fails with this error before the driver launches — schema bugs are programmer errors that must not silently degrade into unvalidated output. The error is sticky: a valid schema set later in the option list does not clear it.
func (*RunSettings) SetPolicy ¶
func (s *RunSettings) SetPolicy(p Policy)
SetPolicy replaces the whole execution policy ("everything else replaces": a call-site policy substitutes the agent-default policy as one value, it does not merge field-wise).
func (*RunSettings) SetServices ¶
func (s *RunSettings) SetServices(specs []ServiceSpec)
SetServices replaces the declared runtime-service set as a whole value. An empty (or nil) slice is an explicit clear: it substitutes the agent default with "no services" rather than inheriting it.
func (*RunSettings) SetSpawn ¶
func (s *RunSettings) SetSpawn()
SetSpawn forces a fresh provider process for the target scope.
func (*RunSettings) SetTimeout ¶
func (s *RunSettings) SetTimeout(d time.Duration)
SetTimeout replaces the wall-clock budget for one run. Zero means no SDK-imposed deadline.
func (*RunSettings) SetWorkspace ¶
func (s *RunSettings) SetWorkspace(dir string)
SetWorkspace replaces the working directory for the target scope.
func (*RunSettings) SetWorkspaceSpec ¶
func (s *RunSettings) SetWorkspaceSpec(spec WorkspaceSpec)
SetWorkspaceSpec replaces the workspace provisioning strategy. A non-nil spec routes the run through the WorkspaceManager (the passthrough manager when none is installed) instead of the direct lease synthesis.
type RunStarted ¶
type RunStarted struct {
// RunID is the run identifier reported by the Driver event.
RunID string
// ThreadID is the provider conversation identifier, when reported.
ThreadID string
// contains filtered or unexported fields
}
RunStarted marks the beginning of a streamed run (StreamKind run.started).
type Runner ¶
type Runner interface {
// Send starts an independent execution and returns its result and event handle.
Send(ctx context.Context, text string, opts ...CallOption) Stream
}
Runner is the single execution contract shared by Agent (stateless runs) and Thread (stateful conversations). Bridges, RunAs[T], and host decorators accept a Runner so both are interchangeable.
type SandboxLevel ¶
type SandboxLevel = driver.IsolationLevel
SandboxLevel controls filesystem and process boundary strength. It aliases the driver SPI type so policies flow to Drivers without conversion.
const ( // SandboxInherit leaves the sandbox to the agent default or the // driver's own fallback. SandboxInherit SandboxLevel = driver.IsolationInherit // ReadOnly requests a read-only workspace. ReadOnly SandboxLevel = driver.IsolationReadOnly // WorkspaceWrite allows writes inside the resolved workspace. WorkspaceWrite SandboxLevel = driver.IsolationWorkspaceWrite // Unrestricted maps to each agent's "full access" / danger sandbox // (or the closest available behavior). Unrestricted SandboxLevel = driver.IsolationUnrestricted )
type SchemaOption ¶
type SchemaOption func(*schemaSettings)
SchemaOption customizes WithSchema[T]: how the JSON Schema document is generated from the Go type, and how the structured-output request is shaped (name, description, invalid policy).
func SchemaAllowAdditionalProperties ¶
func SchemaAllowAdditionalProperties() SchemaOption
SchemaAllowAdditionalProperties relaxes the default strict-object behavior of generated schemas.
func SchemaDescription ¶
func SchemaDescription(desc string) SchemaOption
SchemaDescription sets a provider-facing schema description when supported.
func SchemaInlineReferences ¶
func SchemaInlineReferences() SchemaOption
SchemaInlineReferences asks the generator to inline referenced definitions. Useful for CLIs whose accepted schema subset rejects $defs/$ref. Inlining a recursive Go type is an error.
func SchemaName ¶
func SchemaName(name string) SchemaOption
SchemaName sets a provider-facing schema name when supported.
func SchemaRequireExplicitTags ¶
func SchemaRequireExplicitTags() SchemaOption
SchemaRequireExplicitTags makes only fields tagged jsonschema:"required" required in the generated schema.
func SchemaReturnInvalid ¶
func SchemaReturnInvalid() SchemaOption
SchemaReturnInvalid returns invalid structured output as StructuredOutput.Valid=false (readable via Result.Decode's error) instead of failing the run.
func SchemaUseGoComments ¶
func SchemaUseGoComments(base, path string) SchemaOption
SchemaUseGoComments adds Go comments from path under base as schema descriptions when the generator can resolve them.
type ServiceManager ¶
type ServiceManager interface {
// Ensure starts or locates the desired services and returns the endpoints
// actually made available to the run.
Ensure(ctx context.Context, req ServiceRequest) ([]ServiceRef, error)
// ReleaseByRun releases run-scoped services owned by runID.
ReleaseByRun(ctx context.Context, runID string) error
// ReleaseByLabels releases services selected by host-defined labels.
ReleaseByLabels(ctx context.Context, labels map[string]string) error
}
ServiceManager is the host hook that starts or locates runtime services. Install it with WithServiceManager. Implementations must be safe for concurrent runs of one Agent.
type ServiceRef ¶
type ServiceRef = driver.RuntimeServiceRef
ServiceRef is a concrete runtime service endpoint. Its MCP field is the typed way a service publishes an MCP server into the run, and its SecretEnv field is the subprocess-only channel for run-scoped secrets (bearer tokens) that never reach public reports.
type ServiceReport ¶
type ServiceReport = driver.RuntimeServiceReport
ServiceReport is the execution report for one ensured runtime service.
type ServiceRequest ¶
type ServiceRequest struct {
// RunID is the package-assigned execution identifier.
RunID string
// DriverType identifies the configured Driver.
DriverType string
// Agent is the effective host-supplied identity for the run.
Agent Identity
// Config is optional opaque Driver configuration. It is nil when the
// configured Driver retains its construction-time configuration internally.
Config any
// Workspace is the resolved workspace lease, if one was acquired.
Workspace WorkspaceLease
// Desired is the complete service declaration for the run.
Desired []ServiceSpec
// Metadata is the effective audit metadata for the run.
Metadata map[string]string
}
ServiceRequest is the immutable run envelope passed to ServiceManager.Ensure. Slice and map fields are owned by the SDK for the duration of the call; managers must copy values they retain afterwards.
type ServiceSpec ¶
type ServiceSpec = driver.RuntimeServiceSpec
ServiceSpec declares one runtime service a run needs — an already-known endpoint (URL) or a command/port a ServiceManager starts before the driver launches.
type SharedOption ¶
type SharedOption interface {
Option
CallOption
}
SharedOption is the return type of dual-scope options: used in New it is the Agent's default, used in Send it overrides this call only. Most options that configure execution values return it.
func OnApproval ¶
func OnApproval(h ApprovalHandler) SharedOption
OnApproval installs the approval callback — form A of approval consumption. Every human-in-the-loop request whose policy mode is "ask" invokes the handler with a live *ApprovalRequest; the handler resolves it (Approve / Deny / Answer) and returns nil, or returns an error to abort the run. When no handler is installed the request arrives as a *ApprovalRequest event on the Stream instead (form B); either way an unconsumed request times out into the Policy.Approvals fallback.
In New the handler is the agent default; in Send it overrides this invocation only ("nearer scope wins").
func WithIdentity ¶
func WithIdentity(id Identity) SharedOption
WithIdentity sets the caller identity (tenant / user / profile / agent scoping) propagated to host hooks and the driver. See Identity.
func WithInstructions ¶
func WithInstructions(text string) SharedOption
WithInstructions supplies extra instruction text alongside the prompt. Nearer scope replaces: a call-site value substitutes the agent default.
func WithMCP ¶
func WithMCP(servers ...mcp.Server) SharedOption
WithMCP replaces the MCP server set as a whole value ("everything else replaces"): in New it is the agent default, in Send it substitutes the default for this invocation only. Calling WithMCP() with no servers is an explicit clear — the run sees no MCP servers even when the agent default has some. Server specs are validated against the driver's declared MCP capability before the driver launches; unsupported transports fail the run with ErrMCPTransportUnsupported and the driver is never started.
func WithMetadata ¶
func WithMetadata(k, v string) SharedOption
WithMetadata attaches one audit metadata key/value to runs. Metadata merges per key: call-site keys override same-named default keys and leave the rest of the defaults intact.
func WithModel ¶
func WithModel(m string) SharedOption
WithModel selects the model. In New it is the Agent's default model; in Send it overrides this invocation only (delivered to the driver as the per-run model override).
func WithPolicy ¶
func WithPolicy(p Policy) SharedOption
WithPolicy sets the execution policy: sandbox, optional feature levels, and approvals. The policy replaces as a whole value; it does not merge field-wise with the agent default.
func WithProfileResources ¶
func WithProfileResources(res profile.Resources) SharedOption
WithProfileResources declares the desired profile-shaped resource set in one value. Each resource keeps its own merge rule (the same rules as the dedicated options):
- Skills append (like WithSkills);
- MCP replaces when non-nil (like WithMCP);
- Agents / Hooks / Config replace and declare when the field is non-nil — an explicitly empty slice declares "none";
- Instructions replace and declare when non-nil.
In New the resources are agent defaults; in Send they override this invocation only. Every declared resource lands in the run's ProfilePayload, and ProfileState reports truthfully whether the Driver actually materialized it.
func WithRunServices ¶
func WithRunServices(providers ...RunServiceProvider) SharedOption
WithRunServices attaches run-scoped service providers to every invocation: the generic form of what ecosystem packages ship as their own one-liner option (delegation.Service.Option()). Each provider is attached after the run ID is minted and before the driver is dispatched, contributes its endpoints to the run's runtime/MCP payload, may stream its own events into the run's event channel, and is detached once the run's events are done.
Providers append rather than replace, and the same provider is never attached twice — passing one option value in both New and Send is safe.
func WithServices ¶
func WithServices(specs ...ServiceSpec) SharedOption
WithServices declares the runtime services a run needs — dev servers, databases, tool sidecars. They are ensured through the installed ServiceManager before the driver launches, and the resulting endpoints reach the driver in the run's runtime payload; a service that publishes a typed ServiceRef.MCP additionally joins the run's MCP server set alongside (never in place of) WithMCP.
The declaration replaces as a whole value: calling WithServices() with no specs is an explicit clear. Without a ServiceManager the declaration is inert — the SDK never invents endpoints for services nobody manages.
func WithSkills ¶
func WithSkills(refs ...SkillRef) SharedOption
WithSkills appends skill references. This is the single append-merged option family: in New the refs are the agent's default skills, in Send they extend (never displace) the defaults for this invocation only. Bare keys (skill.Key) are resolved through the SkillProvider; inline values (skill.Dir / skill.FS / skill.Inline) are taken at face value. Duplicate keys must be structurally equal — conflicting duplicates fail the run with ErrSkillKeyConflict.
func WithSpawn ¶
func WithSpawn() SharedOption
WithSpawn forces a fresh provider process instead of reusing the driver's default persistent process. In New it applies to every invocation; in Send it overrides this invocation only. Stateless Agent runs and drivers without persistent-process support already spawn regardless.
func WithTimeout ¶
func WithTimeout(d time.Duration) SharedOption
WithTimeout bounds one run's wall-clock time. In New it is the default budget for every run; in Send it overrides this invocation only. The SDK enforces it via context deadline; a run that exceeds it fails with context.DeadlineExceeded.
func WithWorkspace ¶
func WithWorkspace(dir string) SharedOption
WithWorkspace sets the working directory the agent operates in.
func WithWorkspaceSpec ¶
func WithWorkspaceSpec(spec WorkspaceSpec) SharedOption
WithWorkspaceSpec selects how the run's workspace is provisioned — adaptor.SharedWorkspace{} to reuse the project directory, adaptor.GitWorktreeWorkspace{...} for an isolated worktree, adaptor.DriverManagedWorkspace{} to let the Driver choose. It replaces as a whole value: in New it is the agent default, in Send it overrides this invocation only.
WithWorkspace(dir) and WithWorkspaceSpec compose: the directory is the base CWD handed to the WorkspaceManager, the spec is the strategy. Setting either a spec or a manager routes the run through managed lease resolution; setting neither keeps the plain "run here" behavior.
type SharedWorkspace ¶
type SharedWorkspace struct{}
SharedWorkspace requests direct reuse of the project workspace.
type SkillKeyConflictError ¶
type SkillKeyConflictError = skill.SkillKeyConflictError
SkillKeyConflictError reports conflicting duplicate skill keys.
type SkillMaterializationError ¶
type SkillMaterializationError = skill.SkillMaterializationError
SkillMaterializationError reports a failed skill staging.
type SkillMaterializer ¶
type SkillMaterializer = skill.Materializer
SkillMaterializer converts non-path skill sources into on-disk skill directories before the driver launches.
type SkillProvider ¶
SkillProvider resolves bare skill keys to full skill descriptions. Implementations that also implement skill.Catalog (a Catalogue method) additionally power Inspect().Skills enumeration.
type SkillRef ¶
SkillRef references a skill for WithSkills: either a bare key resolved through the SkillProvider (skill.Key) or a fully described inline skill (skill.Dir / skill.FS / skill.Inline / skill.Require). Alias of the driver SPI type — skill package constructors produce values of exactly this type.
type SkillSnapshot ¶
type SkillSnapshot = driver.SkillSnapshot
SkillSnapshot reports the resolved skill set and its sync state.
type Standby ¶
type Standby interface {
// Send admits one message. The context bounds admission only; executions
// started by the Standby run under the Standby's own context. Options that
// configure an execution (for example WithModel) cannot join a running
// execution; such a message starts a new execution after the current one.
Send(ctx context.Context, text string, opts ...CallOption) error
// Events returns one channel carrying every execution's events in order.
// It closes after the Standby's context ends and the final events have
// been delivered. Before the first call events are discarded, not buffered;
// afterwards the Agent's normal backpressure policy applies.
Events() <-chan Event
// Cancel aborts the processing in progress, if any, and fails every
// message not yet delivered with MessageCancelled. The Standby stays
// alive and keeps accepting messages.
Cancel()
}
Standby is a Thread kept on standby: it keeps accepting messages until the context passed to Thread.Standby ends. A message sent while the Thread is processing joins that processing; a message sent while it is idle starts a new execution. Standby has no overall Result: every turn's result arrives as a TurnEnd event, and every execution still ends with its own Done event. Failed, undelivered messages carry into the next execution. Classified rate-limit, network and provider-server failures retry once, respecting a structured retry-after hint; otherwise the fallback delay is bounded.
type Stream ¶
type Stream interface {
// Send admits supplemental input into this execution. Delivery is reported
// by MessageUpdate and Result.Messages. Only message options are accepted.
// Prelaunch admission uses the Driver's declared capabilities; resolution
// may fail queued messages before delivery and returns their original text
// through MessageUpdate and Result.Undelivered.
Send(ctx context.Context, text string, opts ...MessageOption) error
// Events returns the unified typed event channel. It is closed when
// the run ends (after the final events, including the terminal
// Dropped marker when events were dropped, have been delivered).
// Call Events before consuming ordinary traffic. If execution finishes
// before Events is called, the closed log retains only lifecycle, message,
// turn, approval and notice events, plus a Dropped summary. Ordinary events
// are discarded; Result's raw streams and transcript remain available.
Events() <-chan Event
// Result blocks until the run ends and returns the final outcome —
// using the single error contract: (*Result, nil) on success, (nil, *RunError)
// on business failure, (nil, error) on infrastructure failure.
// Result may be called multiple times and from any goroutine. If Events
// has never been called, Result releases ordinary blocking producers and
// discards ordinary events, retaining critical events and one Dropped
// summary for a later Events call. Call Events first when both consumption
// forms are needed with complete ordinary-event delivery.
Result() (*Result, error)
// RunID returns the SDK-assigned execution identifier, available
// immediately (before the first event).
RunID() string
// Cancel aborts the run and immediately releases blocked event publishers
// and approval waiters. It is idempotent. Buffered Events may still be
// drained before reading Result().
Cancel()
}
Stream represents one execution. Send starts it; Send on this handle adds supplemental messages. Events ends with the authoritative Done, after all checkpoint persistence, validation and resource cleanup. Result returns the same Result pointer and error as Done and can be called concurrently.
Events may be read after Result. Critical events are retained even without a reader; the default backpressure policy can aggregate incremental deltas into Dropped. WithBlockingEvents applies backpressure to ordinary events while Events is consumed; a Result-only caller retains critical events and a drop summary. A subscriber which abandons Events should cancel the execution and drain its remaining critical events.
type StructuredOutputUnsupportedError ¶
type StructuredOutputUnsupportedError = driver.StructuredOutputUnsupportedError
StructuredOutputUnsupportedError reports a capability-matrix miss.
type SubagentEventKind ¶
type SubagentEventKind string
SubagentEventKind classifies a SubagentUpdate.
const ( // SubagentStarted marks a delegated subagent beginning work. SubagentStarted SubagentEventKind = "started" // SubagentDelta carries incremental subagent output. SubagentDelta SubagentEventKind = "delta" // SubagentMessage carries a peer message. SubagentMessage SubagentEventKind = "message" // SubagentState reports a task state change. SubagentState SubagentEventKind = "state" // SubagentFinished marks a delegated subagent completing. SubagentFinished SubagentEventKind = "finished" )
type SubagentResult ¶
type SubagentResult struct {
// Member is the delegated agent key.
Member string
// Task is the delegation identifier.
Task string
// State is the message or delegated task lifecycle state.
State string
// Summary is the task result summary.
Summary string
// Usage is observed token and cost accounting, or nil when unobserved.
Usage *Usage
// Unread contains peer messages not yet consumed by the task.
Unread []string
}
SubagentResult is a delegated task's summary and observed usage.
type SubagentUpdate ¶
type SubagentUpdate struct {
// Task is the delegation identifier.
Task string
// Member is the delegated agent key.
Member string
// State is the task lifecycle status.
State string
// Summary is the task result summary.
Summary string
// Kind classifies the update.
Kind SubagentEventKind
// Delta is the incremental output chunk (SubagentDelta).
Delta string
// Data carries structured details.
Data map[string]any
// contains filtered or unexported fields
}
SubagentUpdate reports remote progress of a delegated subagent on the parent Agent's own event stream. Optional delegation host components can publish it through a RunServiceProvider attachment.
type TerminalPayload ¶
type TerminalPayload = driver.TerminalPayload
TerminalPayload preserves the exact provider terminal JSON recognized by the driver parser and its provider-native event name.
type TextDelta ¶
type TextDelta struct {
// MessageID groups the deltas of one message lifecycle.
MessageID string
// Text is the incremental content chunk (empty on start/end phases).
Text string
// Role is the speaker; zero value RoleAssistant.
Role Role
// Phase discriminates lifecycle boundary events from content.
Phase Phase
// contains filtered or unexported fields
}
TextDelta is one assistant (or bridge-synthesized user) text event. Translated from StreamKinds text.start / text.content / text.end, discriminated by Phase; only PhaseContent events carry Text.
type Thinking ¶
type Thinking struct {
// MessageID groups the deltas of one reasoning lifecycle.
MessageID string
// Text is the incremental reasoning chunk (empty on start/end phases).
Text string
// Phase discriminates lifecycle boundary events from content.
Phase Phase
// contains filtered or unexported fields
}
Thinking is one reasoning/thinking text event. Translated from reasoning.start / reasoning.content / reasoning.end, discriminated by Phase; only PhaseContent events carry Text.
type Thread ¶
type Thread struct {
// contains filtered or unexported fields
}
Thread is a stateful conversation handle: the same Runner contract as Agent, plus continuity — every run resumes the driver checkpoint stored under the thread key and persists the new checkpoint afterwards.
The thread key is the host-owned, opaque conversation identity. The internal session ID and the Driver's native resume handle remain storage details, reachable only through Checkpoint for audit.
agent.Thread("tenant-1/issue-123") // continue_or_start
agent.Thread("k", adaptor.ResumeOnly()) // continue_only
th.Fork("tenant-1/issue-123/alt") // fork (first run)
A Thread handle is cheap: it holds no open resources, and any number of handles for the same key are interchangeable (state lives in the threadstore.Store). Concurrent runs on the same key are serialized by the store lease — the loser fails fast with ErrThreadBusy. The configured Driver must declare Sessions.SupportsResume and implement both driver.SessionCodecProvider and driver.SessionConfigFingerprinter; Send reject an incomplete contract before acquiring resources or touching the store.
func (*Thread) Checkpoint ¶
func (t *Thread) Checkpoint(ctx context.Context) (*Checkpoint, error)
Checkpoint returns the latest healthy driver resume handle, normalized through the driver's session codec (audit / debugging use — the SDK resumes threads by itself). During storage retries the newest in-process checkpoint is authoritative; otherwise the handle comes from the store. It fails with ErrThreadNotFound when the key has no active conversation. Corrupt or unusable durable state returns ErrThreadCheckpointMissing or ErrThreadIncompatible; Checkpoint never returns an invalid checkpoint with a nil error.
func (*Thread) Fork ¶
Fork branches the conversation to newKey — the "regenerate from here / try another direction" button. The first run on the returned Thread forks from t's current conversation (the parent stays intact and active under its own key); afterwards the fork continues independently under newKey.
The parent conversation is resolved when the fork's first run executes; if the parent thread has no stored conversation by then, the run fails with ErrThreadNotFound. Fork panics on an empty newKey.
func (*Thread) Send ¶
Send starts one execution under this Thread's exclusive lease. Supplemental messages belong on the returned Stream. A concurrent Send on the same Thread, or a live Standby even while idle, fails with ErrThreadBusy through Result and Done.
func (*Thread) Standby ¶
Standby gets or creates this Agent's live standby for the Thread key. Its lifetime belongs to the first caller's ctx, not to later callers or Send admission contexts. A store-validated, renewed ownership lease excludes task executions and other processes, including while the standby is idle. Shutdown releases that lease even when a checkpoint still needs persistence. Background recovery reacquires ownership and checks the durable version before writing; it never overwrites a Thread that another writer has advanced.
type ThreadOption ¶
type ThreadOption interface {
// contains filtered or unexported methods
}
ThreadOption tweaks how a Thread binds to its key. ResumeOnly is the sole Thread option.
func ResumeOnly ¶
func ResumeOnly() ThreadOption
ResumeOnly makes the Thread resume-only: runs fail with ErrThreadNotFound when no conversation exists under the key (instead of silently starting a fresh one) and with ErrThreadIncompatible when the stored conversation no longer matches the current configuration. Use it when starting over would be a bug — e.g. replying inside an existing support ticket.
type ThreadRunner ¶
type ThreadRunner interface {
Runner
// Key returns the host's conversation key.
Key() string
// Standby keeps the conversation accepting messages until ctx ends. Within
// one Agent a second call for the same conversation returns the live
// Standby.
Standby(ctx context.Context) (Standby, error)
// Checkpoint returns the conversation's current resume checkpoint.
Checkpoint(ctx context.Context) (*Checkpoint, error)
}
ThreadRunner is a conversation identified by a host key that can run in task mode (Send returns one execution) or on standby. *Thread implements it, and composite runners such as teams provide their own implementations.
type ToolCall ¶
type ToolCall struct {
// ID is the tool-call correlation identifier.
ID string
// Name is the tool name (PhaseStart).
Name string
// Args is the complete initial argument snapshot (PhaseStart, optional).
Args map[string]any
// ArgsDelta is one streamed argument fragment (PhaseContent).
ArgsDelta string
// Result is the optional result attached to the end marker (PhaseEnd).
Result map[string]any
// Phase discriminates start / argument-streaming / end.
Phase Phase
// contains filtered or unexported fields
}
ToolCall is one tool-call lifecycle event. Translated from tool_call.start / tool_call.args / tool_call.end, discriminated by Phase:
- PhaseStart: Name (and Args, when the driver sends a complete initial snapshot) identify the invocation — the natural "render the tool card" event.
- PhaseContent: ArgsDelta carries one streamed argument fragment (usually a JSON fragment) for drivers with argument streaming.
- PhaseEnd: closes the lifecycle; Result is populated when the driver attaches it to the end marker.
type ToolResult ¶
type ToolResult struct {
// ID correlates with the originating ToolCall.ID.
ID string
// Result is the structured tool result.
Result map[string]any
// contains filtered or unexported fields
}
ToolResult carries a completed tool result (StreamKind tool_call.result).
type TranscriptItem ¶
type TranscriptItem struct {
// Kind identifies the author authority or transcript item type.
Kind driver.TranscriptKind
// Text is the original unframed message, unless documented otherwise.
Text string
// Delta marks incremental transcript content.
Delta bool
// ToolUseID correlates a tool call and its result.
ToolUseID string
// ToolName identifies the tool.
ToolName string
// Input is the parsed tool input.
Input any
// IsError marks a provider-reported error item.
IsError bool
// Model is the provider-reported model.
Model string
// SessionID is the provider-reported session identifier.
SessionID string
// Usage is observed token and cost accounting, or nil when unobserved.
Usage *Usage
// CostUSD is provider-reported cost when available.
CostUSD *float64
// Subtype preserves the provider result subtype.
Subtype string
// Errors preserves provider error descriptions.
Errors []string
// Metadata preserves short provider tags.
Metadata map[string]string
// Data preserves structured provider extensions.
Data map[string]any
// Message is populated only for Kind "message" and describes actual core-observed delivery.
Message *TranscriptMessage
}
TranscriptItem is a parsed provider item or a core-recorded message delivery. Kind "message" has Message populated and does not imply a user role.
type TranscriptMessage ¶
type TranscriptMessage struct {
// ID is the opaque message identifier.
ID string
// From identifies the message author.
From Author
// Mechanism names the provider or core delivery mechanism.
Mechanism string
// Boundary is immediate, tool, stop, or turn_end when delivery was attempted.
Boundary string
// Text is the original unframed message, unless documented otherwise.
Text string
}
TranscriptMessage records actual supplemental delivery without asserting a provider-specific user role. Text is the original, unframed message.
type TurnEnd ¶
type TurnEnd struct {
// Turn is the one-based provider turn; zero means delivery is not assigned yet.
Turn int
// Result is the final or per-turn outcome; business failures carry their partial Result in RunError.
Result *Result
// Err is the execution error or wrapped admission cause.
Err error
// MessageIDs lists the messages processed by this turn, in admission order.
MessageIDs []string
// contains filtered or unexported fields
}
TurnEnd reports one provider turn. Turn is one-based within the execution. MessageIDs identifies the messages processed by this turn.
type Usage ¶
Usage is normalized token/cost accounting. Individual observed values may be zero; Result.Usage is nil when the provider reported no usage.
type WorkspaceLease ¶
type WorkspaceLease = driver.WorkspaceLease
WorkspaceLease is the concrete working directory a manager returns.
type WorkspaceManager ¶
type WorkspaceManager interface {
// Resolve provisions or selects a workspace and returns its concrete lease.
Resolve(ctx context.Context, req WorkspaceRequest) (WorkspaceLease, error)
// Release applies mode to a previously resolved lease.
Release(ctx context.Context, lease WorkspaceLease, mode WorkspaceReleaseMode) error
}
WorkspaceManager is the host hook that turns a WorkspaceSpec into a concrete lease. Install it with WithWorkspaceManager. Implementations must be safe for concurrent runs of one Agent.
type WorkspaceReleaseMode ¶
type WorkspaceReleaseMode string
WorkspaceReleaseMode tells a WorkspaceManager what to do after a run.
const ( // WorkspaceReleaseKeep leaves the workspace available after the run. WorkspaceReleaseKeep WorkspaceReleaseMode = "keep" // WorkspaceReleaseStop asks the manager to tear down run-scoped state. WorkspaceReleaseStop WorkspaceReleaseMode = "stop" )
type WorkspaceRequest ¶
type WorkspaceRequest struct {
// BaseCWD is the effective working directory before managed provisioning.
BaseCWD string
// Spec describes the requested provisioning strategy.
Spec WorkspaceSpec
// Metadata is the effective audit metadata for the run.
Metadata map[string]string
}
WorkspaceRequest is passed to WorkspaceManager.Resolve after agent defaults and per-call workspace options have been merged.
type WorkspaceSpec ¶
type WorkspaceSpec interface {
// contains filtered or unexported methods
}
WorkspaceSpec is the closed set of workspace provisioning requests: SharedWorkspace, GitWorktreeWorkspace, and DriverManagedWorkspace.
Source Files
¶
- agent.go
- approval.go
- doc.go
- errors.go
- event_broker.go
- events.go
- identity.go
- inspect.go
- invocation.go
- messages.go
- options.go
- policy.go
- profile_resources.go
- result.go
- runservices.go
- sink.go
- standby.go
- standby_runtime.go
- stream.go
- structured.go
- thread.go
- thread_continuity.go
- thread_runtime.go
- threadstore_engine.go
- tools.go
- wiring.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package adaptertest is the conformance suite for the driver SPI.
|
Package adaptertest is the conformance suite for the driver SPI. |
|
bridges
|
|
|
a2a
Package a2a exposes an adaptor Runner as an A2A-compatible agent.
|
Package a2a exposes an adaptor Runner as an A2A-compatible agent. |
|
agui
Package agui translates adaptor requests, events, and approvals to and from the AG-UI protocol.
|
Package agui translates adaptor requests, events, and approvals to and from the AG-UI protocol. |
|
agui/aguisession
Package aguisession provides optional recorded AG-UI execution and history.
|
Package aguisession provides optional recorded AG-UI execution and history. |
|
internal/bridgekey
Package bridgekey provides the collision-free encoding used when an external protocol identifier must be namespaced before it becomes an adaptor Thread key.
|
Package bridgekey provides the collision-free encoding used when an external protocol identifier must be namespaced before it becomes an adaptor Thread key. |
|
sse
Package sse exposes HTTP Server-Sent Events handlers for the adaptor v1 Runner/Event/Result contracts.
|
Package sse exposes HTTP Server-Sent Events handlers for the adaptor v1 Runner/Event/Result contracts. |
|
subagentstream
Package subagentstream projects typed SubagentUpdate events from a Runner's existing Event stream into a wire envelope.
|
Package subagentstream projects typed SubagentUpdate events from a Runner's existing Event stream into a wire envelope. |
|
Package claude provides the built-in Driver implementation for the Claude Code CLI.
|
Package claude provides the built-in Driver implementation for the Claude Code CLI. |
|
clients
|
|
|
a2a
Package a2a provides thin, host-oriented client primitives for remote A2A agents.
|
Package a2a provides thin, host-oriented client primitives for remote A2A agents. |
|
Package codebuddy provides the built-in Driver implementation for the CodeBuddy CLI.
|
Package codebuddy provides the built-in Driver implementation for the CodeBuddy CLI. |
|
Package codex provides the built-in Driver implementation for Codex.
|
Package codex provides the built-in Driver implementation for Codex. |
|
appserver
Package appserver is a typed client for the codex app-server JSON-RPC protocol over stdio.
|
Package appserver is a typed client for the codex app-server JSON-RPC protocol over stdio. |
|
Package cursor provides the built-in Driver implementation for the Cursor Agent CLI.
|
Package cursor provides the built-in Driver implementation for the Cursor Agent CLI. |
|
Package driver defines the SPI (service provider interface) implemented by agent CLI integrations.
|
Package driver defines the SPI (service provider interface) implemented by agent CLI integrations. |
|
examples
|
|
|
a2a-server
command
a2a-server starts an in-process A2A server around a real local Agent, then calls it through the A2A client.
|
a2a-server starts an in-process A2A server around a real local Agent, then calls it through the A2A client. |
|
inspect
command
inspect demonstrates read-only Driver probes and Agent inspection.
|
inspect demonstrates read-only Driver probes and Agent inspection. |
|
profiles
command
profiles materializes a complete provider profile — skills, MCP, hooks, sub-agent, instructions — and then proves on disk that the selected CLI really sees it.
|
profiles materializes a complete provider profile — skills, MCP, hooks, sub-agent, instructions — and then proves on disk that the selected CLI really sees it. |
|
profiles/hook
command
|
|
|
profiles/mcpserver
command
|
|
|
profiles/resources
command
profiles/resources shows the resource half of the profile vocabulary: not only *where* the provider profile lives, but *what must exist inside it*.
|
profiles/resources shows the resource half of the profile vocabulary: not only *where* the provider profile lives, but *what must exist inside it*. |
|
quickstart
command
quickstart constructs an Agent from a Driver, asks one question, and reads one Result.
|
quickstart constructs an Agent from a Driver, asks one question, and reads one Result. |
|
showcases/issue-daemon
command
Command issue-daemon exercises multica-style messaging against Codex or an offline scripted Driver, reporting every acceptance check as JSON.
|
Command issue-daemon exercises multica-style messaging against Codex or an offline scripted Driver, reporting every acceptance check as JSON. |
|
showcases/multica-routing
command
Command multica-routing exercises a small, explicit host routing contract inspired by Multica.
|
Command multica-routing exercises a small, explicit host routing contract inspired by Multica. |
|
showcases/sdlc-team
command
Command sdlc-team runs a small, auditable SDLC using real public SDK Teams.
|
Command sdlc-team runs a small, auditable SDLC using real public SDK Teams. |
|
showcases/team-agent-workflow
command
Host-side scaffolding for the team-agent-workflow showcase: the temporary task fixture, the workspace stage audit, the terminal renderer, and the protocol text handed to the leader.
|
Host-side scaffolding for the team-agent-workflow showcase: the temporary task fixture, the workspace stage audit, the terminal renderer, and the protocol text handed to the leader. |
|
skills
command
skills proves runtime skill injection end-to-end with a real local CLI: the agent is given a write-proof skill and only follows it if the skill actually reached the provider's skill directory.
|
skills proves runtime skill injection end-to-end with a real local CLI: the agent is given a write-proof skill and only follows it if the skill actually reached the provider's skill directory. |
|
streaming
command
streaming shows the unified typed event channel for one run, consumed with a single for-range + type switch, closed out by Result().
|
streaming shows the unified typed event channel for one run, consumed with a single for-range + type switch, closed out by Result(). |
|
streaming/chat
command
streaming/chat is a minimal typed-event chat UI in pure Go.
|
streaming/chat is a minimal typed-event chat UI in pure Go. |
|
structured-output
command
structured-output derives a JSON schema from a Go type, asks the Driver for structured output, validates it, and returns the decoded value with Result.
|
structured-output derives a JSON schema from a Go type, asks the Driver for structured output, validates it, and returns the decoded value with Result. |
|
threads
command
threads demonstrates persistent, resume-only, and forked conversation Threads on host-owned keys.
|
threads demonstrates persistent, resume-only, and forked conversation Threads on host-owned keys. |
|
threads/codec
command
threads/codec looks underneath the Thread abstraction at the driver-owned session codec.
|
threads/codec looks underneath the Thread abstraction at the driver-owned session codec. |
|
tools
command
tools gives a local coding agent one host-defined typed Go function.
|
tools gives a local coding agent one host-defined typed Go function. |
|
web-chat
command
web-chat exposes an Agent over AG-UI Server-Sent Events with a single bridge call.
|
web-chat exposes an Agent over AG-UI Server-Sent Events with a single bridge call. |
|
web-chat/assistant-ui
command
assistant-ui demonstrates recorded AG-UI history and optional active observation.
|
assistant-ui demonstrates recorded AG-UI history and optional active observation. |
|
hosttools
|
|
|
sessionrecorder
Package sessionrecorder is an opt-in host utility that records typed agent-adaptor events under a host-owned session key and serves them back by a cursor that stays monotonic across runs.
|
Package sessionrecorder is an opt-in host utility that records typed agent-adaptor events under a host-owned session key and serves them back by a cursor that stays monotonic across runs. |
|
team
Package team composes host-selected local and Remote A2A members with a delegation-first leader through the public adaptor.Runner contract.
|
Package team composes host-selected local and Remote A2A members with a delegation-first leader through the public adaptor.Runner contract. |
|
team/teamstoretest
Package teamstoretest provides deterministic conformance tests for durable team.TaskStore implementations.
|
Package teamstoretest provides deterministic conformance tests for durable team.TaskStore implementations. |
|
internal
|
|
|
cliversion
Package cliversion provides bounded, cached local CLI version probes.
|
Package cliversion provides bounded, cached local CLI version probes. |
|
engine
Package engine hosts private resolution, thread coordination, profile, and runtime-service operations used by the public Agent pipeline.
|
Package engine hosts private resolution, thread coordination, profile, and runtime-service operations used by the public Agent pipeline. |
|
jsonnumber
Package jsonnumber reads integer-valued JSON payloads without rounding.
|
Package jsonnumber reads integer-valued JSON payloads without rounding. |
|
keycodec
Package keycodec provides a collision-free encoding for composite keys used by internal indexes and lease targets.
|
Package keycodec provides a collision-free encoding for composite keys used by internal indexes and lease targets. |
|
testutil/apifreeze
Package apifreeze provides stable public API snapshots for contract tests.
|
Package apifreeze provides stable public API snapshots for contract tests. |
|
toolidentity
Package toolidentity owns the private constants shared by the Agent-owned Tool runtime and provider profile materializers.
|
Package toolidentity owns the private constants shared by the Agent-owned Tool runtime and provider profile materializers. |
|
toolruntime
Package toolruntime exposes an immutable provider-neutral Tool catalog over a process-wide, authenticated loopback gateway.
|
Package toolruntime exposes an immutable provider-neutral Tool catalog over a process-wide, authenticated loopback gateway. |
|
Package mcp is the v1 vocabulary for declaring Model Context Protocol (MCP) servers a host attaches to an agent, replacing hand-written configuration structs with one-line constructors:
|
Package mcp is the v1 vocabulary for declaring Model Context Protocol (MCP) servers a host attaches to an agent, replacing hand-written configuration structs with one-line constructors: |
|
Package memory provides a concurrency-safe, in-memory implementation of threadstore.Store.
|
Package memory provides a concurrency-safe, in-memory implementation of threadstore.Store. |
|
Package profile defines provider profile selection and profile resource declarations (see docs/api-reference.md §§10–11).
|
Package profile defines provider profile selection and profile resource declarations (see docs/api-reference.md §§10–11). |
|
Package skill is the consumer-facing vocabulary for agent skills.
|
Package skill is the consumer-facing vocabulary for agent skills. |
|
Package threadstore defines the storage contract behind stateful Threads (see docs/api-reference.md §13).
|
Package threadstore defines the storage contract behind stateful Threads (see docs/api-reference.md §13). |
|
Package tool defines provider-neutral tools implemented by Go functions.
|
Package tool defines provider-neutral tools implemented by Go functions. |