Documentation
¶
Overview ¶
Package driver defines the SPI (service provider interface) implemented by agent CLI integrations. It is the package for driver authors: anyone who wants to plug a new coding agent into the SDK implements Driver (plus any of the optional capability interfaces) against the request/response/event types declared here.
Application code that consumes the SDK normally imports only the root adaptor package and provider packages. This package is intentionally the extension-author boundary. The root package provides a convenience alias for Driver so an Agent can expose its required construction dependency, while the canonical SPI and every optional capability contract remain here.
The dependency direction is one-way: the root package imports driver, never the reverse. Provider packages may import driver to implement this SPI; driver must not import the root package, provider packages, bridges, or internal implementation packages.
Index ¶
- Constants
- Variables
- func CanonicalSessionConfigFingerprint(domain string, value any) (string, error)
- type AgentIdentity
- type AgentPayload
- type AgentProfile
- type AgentProfileSource
- type AgentSpec
- type AgentToolPolicy
- type Checkpoint
- type CloneProfileAuthMode
- type CloneProfileOptions
- type CommonConfig
- type ConfigField
- type ConfigOption
- type ConfigSchema
- type ConfigSchemaProvider
- type DecisionCapableSink
- type DecisionChoice
- type DecisionRequest
- type DecisionResponse
- type DecisionResult
- type Descriptor
- type DetectedModel
- type Driver
- type EnvBinding
- type EnvironmentCheck
- type EnvironmentProbe
- type EnvironmentReport
- type EnvironmentStatus
- type EventSink
- type FailureAction
- type FailureCode
- type FeatureLevel
- type HITLRequestedPayload
- type HITLResolvedPayload
- type HookEvent
- type HookFailPolicy
- type HookHandler
- type HookHandlerType
- type HookMatcher
- type HookMatcherSubject
- type HookMatcherSyntax
- type HookPayload
- type HookSpec
- type HumanDecisionFailure
- type HumanDecisionKind
- type HumanDecisionMode
- type HumanDecisionModeUnsupportedError
- type HumanDecisionPolicy
- type HumanDecisionSupport
- type InstructionMode
- type InstructionScope
- type InstructionsBundleRef
- type InstructionsCapability
- type InvalidDriverConfigError
- type InvalidOutputSchemaError
- type InvalidPolicyError
- type IsolationLevel
- type MCPCapability
- type MCPPayload
- type MCPServerSpec
- type MCPTransport
- type ModelDetector
- type ModelInfo
- type ModelLister
- type NativeConfigPatch
- type OutputFormat
- type OutputSchema
- type PolicyCapabilityUnsupportedError
- type ProcessCapability
- type ProcessLifecycleDriver
- type ProfileConfigFileKind
- type ProfileConfigPatch
- type ProfileConfigPayload
- type ProfileMode
- type ProfilePayload
- type ProfileReporter
- type ProfileResourceDeclarations
- type ProfileSelection
- type QuestionMode
- type QuestionSupport
- type QuotaProbe
- type QuotaReport
- type QuotaWindow
- type RawStreams
- type Request
- type ResolvedSkill
- type ResolvedSkills
- type Response
- type Role
- type RunEvent
- type RunEventType
- type RunFailure
- type RunPolicy
- type RunPolicyCapabilities
- type RuntimeCapability
- type RuntimePayload
- type RuntimeServiceHealth
- type RuntimeServiceLifecycle
- type RuntimeServiceRef
- type RuntimeServiceReport
- type RuntimeServiceSpec
- type RuntimeServiceStatus
- type SessionCapability
- type SessionCodec
- type SessionCodecProvider
- type SessionConfigFingerprintError
- type SessionConfigFingerprinter
- type SessionContext
- type SessionMode
- type SessionParams
- type SessionState
- type Skill
- type SkillCapability
- type SkillKey
- type SkillOrigin
- type SkillRef
- type SkillSnapshot
- type SkillSource
- type SkillState
- type SkillSupport
- type SkillSyncMode
- type SnapshotEntry
- type StreamCapability
- type StreamKind
- type StreamPayload
- type StreamSupport
- type StructuredOutput
- type StructuredOutputCapability
- type StructuredOutputInvalidPolicy
- type StructuredOutputSource
- type StructuredOutputUnsupportedError
- type TerminalPayload
- type TranscriptItem
- type TranscriptKind
- type Usage
- type WorkspaceCapability
- type WorkspaceLease
- type WorkspaceMode
- type WorkspaceRuntimeConfig
- type WorkspaceStrategy
- type WorkspaceStrategyType
Constants ¶
const ( // DefaultHumanDecisionTimeout is the timeout used for Ask decisions when // the host does not set HumanDecisionPolicy.Timeout. DefaultHumanDecisionTimeout = 30 * time.Second // DefaultHumanDecisionMaxRetries is the retry cap used when the host // requests FailureRetry without setting MaxRetries. DefaultHumanDecisionMaxRetries = 3 )
Defaults declared in docs/run-policy.md §1.3. Exposed as package constants so runner and driver tests can reference them without drift.
const ( // SessionParamCWD records the workspace directory captured in a session. SessionParamCWD = "cwd" // SessionParamWorkspaceID records the SDK workspace lease identifier. SessionParamWorkspaceID = "workspace_id" // SessionParamProfileFingerprint records the effective profile session // compatibility fingerprint captured by a resumable session. SessionParamProfileFingerprint = "profile_fingerprint" )
Well-known SessionParams.Values keys used by the built-in drivers.
Hosts should prefer SessionCodec over direct map access, but these constants define the stable meanings for the SDK's built-in drivers and examples, and they let out-of-tree drivers populate the same keys without importing the root adaptor package.
const ( // SkillMetadataRuntimeName overrides the directory name used when the // materializer writes the skill to disk (and when drivers such as // Cursor mount it under <home>/skills/<name>). Defaults to slug(Key). SkillMetadataRuntimeName = "_runtime_name" // SkillMetadataDisplayName is a host-UI-friendly label. SkillMetadataDisplayName = "_display_name" )
Reserved Metadata keys interpreted by the SDK / drivers.
Variables ¶
var ( // ErrInvalidDriverConfig reports that Driver.ValidateConfig rejected the // configured Driver before an invocation was launched. ErrInvalidDriverConfig = errors.New("agentadaptor: invalid driver config") // ErrInvalidPolicy reports an out-of-domain RunPolicy value. Capability // misses use one of the dedicated unsupported sentinels instead. ErrInvalidPolicy = errors.New("agentadaptor: invalid run policy") // ErrPolicyCapabilityUnsupported reports that a valid, explicitly // selected non-approval policy value is unsupported by the Driver. ErrPolicyCapabilityUnsupported = errors.New("agentadaptor: policy capability unsupported by driver") // ErrHumanDecisionModeUnsupported reports that an explicitly selected // human-decision mode is absent from Descriptor.RunPolicyCaps. ErrHumanDecisionModeUnsupported = errors.New("agentadaptor: human decision mode unsupported by driver") )
Stable pre-launch error categories shared by the root runner and Driver implementations. Keeping these identities in package driver lets both sides of the SPI wrap and match the same errors without depending on an internal package.
var ( // ErrStructuredOutputUnsupported is returned before driver launch when // the structured-output contract cannot be honored by the bound driver // or selected provider transport. ErrStructuredOutputUnsupported = errors.New("agentadaptor: structured output unsupported by driver") // ErrInvalidOutputSchema is returned before driver launch when a host // supplies malformed JSON, an unsupported output format, or a // JSON Schema document that cannot be compiled for local validation. ErrInvalidOutputSchema = errors.New("agentadaptor: invalid output schema") )
Structured-output errors live with the structured-output vocabulary. This gives the engine, root package, and third-party drivers one concrete error identity without making any public API depend on internal packages.
Functions ¶
func CanonicalSessionConfigFingerprint ¶
CanonicalSessionConfigFingerprint returns a SHA-256 compatibility token for value under a caller-owned version domain. The domain should identify the Driver and session-codec contract (for example, "acme/v2;codec/v1") and must change whenever the meaning of the encoded configuration changes.
Canonicalization is deliberately strict:
- map insertion order is ignored and map entries are sorted by encoded key;
- nil and empty maps/slices are equivalent because both mean "no values";
- nil pointers/interfaces remain distinct from present zero values;
- pointers are dereferenced and their addresses are never encoded;
- funcs, channels, unsafe pointers, uintptrs, cycles, and structs with unexported state are rejected rather than guessed;
- errors describe shape only and never include a field value or map key.
All exported struct fields, including zero-valued fields, participate. This makes newly-added provider Config fields fail closed by changing the token.
Types ¶
type AgentIdentity ¶
AgentIdentity is host-supplied caller identity propagated into SDK hooks.
The SDK does not use these fields for routing. They exist so host-provided components such as SkillProvider, WorkspaceManager, and ServiceManager can scope lookups by tenant, user/profile, or logical agent name without inventing their own context keys.
type AgentPayload ¶
AgentPayload is the normalized driver-facing agent resource state.
type AgentProfile ¶
type AgentProfile struct {
DriverType string
Supported bool
Dir string
EnvVar string
Source AgentProfileSource
Managed bool
Error string
}
AgentProfile reports the effective local operator profile directory for one configured Driver as observed during profile inspection or synchronization.
Dir is the effective directory the built-in driver will inspect or use for local profile semantics. Source tells whether that directory came from an explicit CommonConfig.Env override, profile option, process environment fallback, a driver-native default path, or a driver-managed home. Managed is true only when the driver actively synthesizes an isolated profile directory, such as Codex's managed CODEX_HOME.
type AgentProfileSource ¶
type AgentProfileSource string
AgentProfileSource identifies where a driver's effective local profile directory came from.
const ( // AgentProfileSourceBindingEnv means an explicit Driver config environment // override selected the profile. AgentProfileSourceBindingEnv AgentProfileSource = "binding_env" // AgentProfileSourceProfileOption means WithProfile selected the profile. AgentProfileSourceProfileOption AgentProfileSource = "profile_option" // AgentProfileSourceProcessEnv means a process environment variable selected the profile. AgentProfileSourceProcessEnv AgentProfileSource = "process_env" // AgentProfileSourceDefault means the driver used its native default path. AgentProfileSourceDefault AgentProfileSource = "default" // AgentProfileSourceManaged means the SDK/driver synthesized a managed profile. AgentProfileSourceManaged AgentProfileSource = "managed" // AgentProfileSourceUnsupported means the driver has no profile semantics. AgentProfileSourceUnsupported AgentProfileSource = "unsupported" )
type AgentSpec ¶
type AgentSpec struct {
Key string
RuntimeName string
Description string
Instructions string
SourcePath string
SourceFingerprint string
Model string
ReasoningEffort string
ToolPolicy *AgentToolPolicy
PermissionMode string
SandboxMode string
MCPServers []string
Skills []string
Hooks []HookSpec
Native map[string]any
Metadata map[string]string
}
AgentSpec describes one host-declared sub-agent/profile agent entry.
type AgentToolPolicy ¶
AgentToolPolicy captures provider-neutral tool allow/deny intent for a profile agent. Drivers map it to provider-native tool/sandbox/permission fields when they declare support.
type Checkpoint ¶
type Checkpoint struct {
State *SessionState
Valid bool
}
Checkpoint is returned by drivers only when the run produced session state that is proven safe to persist. A driver MUST set Valid=true only when all of the following hold: the provider process exited successfully, no signal or timeout occurred, Response.Failure is nil, the driver's official parser observed its successful terminal event, and that protocol supplied an explicit top-level resume/session identifier accepted by SessionCodec. Init/session announcements, partial output, guessed/nested identifiers and terminal error events are not sufficient. There is no failed-run exception: non-zero exit, cancellation, malformed protocol, missing terminal, or business failure MUST return nil or Valid=false. This prevents a failed run from replacing a previously healthy Thread checkpoint. Structurally, Valid=true also requires State != nil and a non-empty State.ResumeID that round-trips through the codec exposed by the same resume-capable Driver.
type CloneProfileAuthMode ¶
type CloneProfileAuthMode string
CloneProfileAuthMode controls how a clone selection seeds auth files from the source provider profile.
const ( // CloneProfileAuthNone leaves auth files out of the cloned profile. CloneProfileAuthNone CloneProfileAuthMode = "" // CloneProfileAuthCopy copies auth files into the cloned profile. This is // suitable for static API-key style auth, but can duplicate OAuth refresh // token state for CLIs that rotate tokens in-place. CloneProfileAuthCopy CloneProfileAuthMode = "copy" // CloneProfileAuthLink shares auth files with the source profile by // symlink, falling back to a hardlink when symlinks are unavailable. It // fails rather than silently copying if neither shared-file strategy works. CloneProfileAuthLink CloneProfileAuthMode = "link" )
type CloneProfileOptions ¶
type CloneProfileOptions struct {
IncludeSettings bool
IncludeMCP bool
IncludeSkills bool
// AuthMode controls auth-file handling. The zero value keeps auth out of
// the clone.
AuthMode CloneProfileAuthMode
}
CloneProfileOptions controls which parts of a source provider profile are copied by a clone selection created through package profile.
type CommonConfig ¶
type CommonConfig struct {
Command string
CWD string
Env []EnvBinding
Instructions *InstructionsBundleRef
PromptTemplate string
BootstrapPromptTemplate string
WorkspaceStrategy *WorkspaceStrategy
WorkspaceRuntime *WorkspaceRuntimeConfig
Timeout time.Duration
GracePeriod time.Duration
ExtraArgs []string
}
CommonConfig contains provider-independent process defaults shared by the built-in Driver configurations. It lives in the public Driver SPI package so provider Config values never expose internal engine implementation types.
Provider packages own their concrete Config types and explicitly translate every field into their private execution representation.
func (CommonConfig) Clone ¶
func (c CommonConfig) Clone() CommonConfig
Clone returns a deep copy of c. Built-in provider constructors use it to take an immutable construction-time snapshot: callers may safely reuse or mutate the slices, maps, and pointed-to values they used to build Config.
type ConfigField ¶
type ConfigField struct {
Name string
Label string
Type string
Required bool
Description string
Hint string
Default any
Options []ConfigOption
Group string
Meta map[string]string
}
ConfigField describes one configurable driver property.
Built-in drivers currently use these conventions:
- Type: "text", "textarea", "number", "toggle", or "select"
- Default: host-facing default value when the driver exposes one
- Options: selectable values for "select" fields
- Group: stable buckets such as "command", "model", "permissions", or "execution"
- Meta: driver-specific UI hints that do not change runtime semantics
type ConfigOption ¶
ConfigOption is one selectable value for a ConfigField with Type "select". Value is the serialized config value; Label and Description are display hints only.
type ConfigSchema ¶
type ConfigSchema struct {
Fields []ConfigField
}
ConfigSchema describes the host-facing configuration contract for one bound driver. Hosts can render these fields directly into settings UIs, CLIs, or diagnostics pages without changing the execution contract.
type ConfigSchemaProvider ¶
type ConfigSchemaProvider interface {
ConfigSchema(ctx context.Context, cfg any) (*ConfigSchema, error)
}
ConfigSchemaProvider lets drivers expose a runtime-hydrated config schema through Agent.Inspect().ConfigSchema without changing execution semantics.
type DecisionCapableSink ¶
type DecisionCapableSink interface {
EventSink
// RequestDecision blocks until the host resolves the decision, the
// policy Deadline elapses, or ctx is cancelled. The returned error is
// non-nil when the decision was aborted (cancellation or driver-visible
// abort); DecisionResponse carries the outcome otherwise.
RequestDecision(ctx context.Context, req DecisionRequest) (DecisionResponse, error)
}
DecisionCapableSink is an optional extension of EventSink. Drivers call RequestDecision to block on a HITL decision. The SDK's built-in sink implements this interface; custom or observer-only sinks do not need to.
type DecisionChoice ¶
DecisionChoice is a single renderable option returned by a driver.
type DecisionRequest ¶
type DecisionRequest struct {
RequestID string
RunID string
ThreadID string
Kind HumanDecisionKind
Source string
ToolCallID string
Prompt string
Payload map[string]any
Choices []DecisionChoice
DefaultDecision DecisionResult
CreatedAt time.Time
Deadline time.Time
RetryAttempt int
}
DecisionRequest is the cross-class request envelope drivers hand to the SDK. The SDK normalizes RequestID / CreatedAt / Deadline / RetryAttempt before routing and before emitting StreamHITLRequested.
type DecisionResponse ¶
type DecisionResponse struct {
RequestID string
Result DecisionResult
Choice string
Answer map[string]any
Text string
}
DecisionResponse is the normalized response returned to a driver after a typed ApprovalRequest or OnApproval callback is resolved. The root package's per-kind responses are converted to this envelope before the driver sees them.
type DecisionResult ¶
type DecisionResult string
DecisionResult is the cross-class outcome used in DecisionResponse and HumanDecisionFailure.Decision.
const ( // DecisionApproved is the normalized positive result for binary decisions. DecisionApproved DecisionResult = "approved" // DecisionRejected is the normalized negative result for binary decisions. DecisionRejected DecisionResult = "rejected" // DecisionAnswered carries a structured answer for Question decisions. DecisionAnswered DecisionResult = "answered" // DecisionTimedOut records that no host answer arrived before Deadline. DecisionTimedOut DecisionResult = "timed_out" // DecisionAborted records cancellation or another driver-visible abort. DecisionAborted DecisionResult = "aborted" )
type Descriptor ¶
type Descriptor struct {
// Type is the stable provider/driver identifier.
Type string
// DisplayName is the human-readable driver name.
DisplayName string
// Models lists statically known models; ModelLister may provide a live list.
Models []ModelInfo
// ConfigSchema is the static schema used when ConfigSchemaProvider is absent.
ConfigSchema *ConfigSchema
// Sessions declares resume support and its SessionCodec requirement.
Sessions SessionCapability
// Skills declares whether and how the driver consumes resolved skills.
Skills SkillCapability
// MCP declares the supported MCP transports.
MCP MCPCapability
// Instructions declares explicit instruction-bundle support.
Instructions InstructionsCapability
// Workspace declares support for SDK-resolved workspaces.
Workspace WorkspaceCapability
// Process declares the provider process lifecycle supported by this driver.
Process ProcessCapability
// RunPolicyCaps declares the policy dimensions the driver can enforce.
RunPolicyCaps RunPolicyCapabilities
// Runtime declares runtime-service reporting support.
Runtime RuntimeCapability
// StructuredOutput declares supported structured-output mechanisms.
StructuredOutput StructuredOutputCapability
}
Descriptor is the driver's static capability declaration. The SDK uses it to validate host requests before launching a driver; hosts can use it to disable unsupported UI controls instead of discovering failures late.
type DetectedModel ¶
DetectedModel reports the effective model inferred from config/profile state. Source names where the decision came from, such as explicit config or provider config file; Candidates records fallback values considered.
type Driver ¶
type Driver interface {
Descriptor() Descriptor
// ValidateConfig validates the Driver's construction-time configuration.
// A configured Driver MUST interpret nil as "validate the captured
// configuration". The root runner calls this before every launch and wraps
// failures in InvalidDriverConfigError.
ValidateConfig(cfg any) error
// Run executes exactly one resolved invocation. When req.Streaming is
// true, normalized payloads obey the lifecycle contract documented on
// StreamKind; all RunEventItem values emitted through sink must mirror the
// returned Response.Transcript. A Driver MUST apply the complete current
// Request on every invocation, including a resumed provider conversation;
// it must refresh provider-visible profile, MCP, skill, instruction, and
// runtime bindings rather than relying on values cached by an earlier
// process or turn. Resume/persistent guards use
// req.ProfilePayload.SessionFingerprint(), while materialization continues
// to use the exact payload and Fingerprint. A non-nil error is an
// infrastructure or execution error and makes any returned valid Checkpoint
// invalid.
Run(ctx context.Context, req Request, sink EventSink) (Response, error)
}
Driver is the canonical SPI implemented by built-in and third-party agent integrations. The SDK owns option merging, Thread coordination, workspace/runtime/skill resolution, and result archiving; drivers own provider-specific validation, process/protocol execution, transcript parsing, and checkpoint extraction.
type EnvBinding ¶
EnvBinding is one explicit environment variable override passed to a driver process or used during profile resolution.
type EnvironmentCheck ¶
EnvironmentCheck is one probe result within an EnvironmentReport. Code is the stable machine-facing identifier; Message, Detail, and Hint are host-facing text that can be rendered directly in diagnostics UIs.
type EnvironmentProbe ¶
type EnvironmentProbe interface {
CheckEnvironment(ctx context.Context, cfg any) (EnvironmentReport, error)
}
EnvironmentProbe is implemented by drivers that can perform preflight checks against local CLIs, auth files, profile directories, or other dependencies. Agent.Inspect().Environment uses it when present.
type EnvironmentReport ¶
type EnvironmentReport struct {
DriverType string
Status EnvironmentStatus
Healthy bool
Summary string
Checks []EnvironmentCheck
}
EnvironmentReport is the normalized health report returned by Agent.Inspect().Environment. Status and Checks are authoritative; Healthy reports whether Status is EnvironmentPass.
type EnvironmentStatus ¶
type EnvironmentStatus string
EnvironmentStatus summarizes the highest-severity environment check result.
const ( // EnvironmentPass means all checks passed. EnvironmentPass EnvironmentStatus = "pass" // EnvironmentWarn means the driver may run but host attention is useful. EnvironmentWarn EnvironmentStatus = "warn" // EnvironmentFail means the driver is not ready to run. EnvironmentFail EnvironmentStatus = "fail" )
type EventSink ¶
type EventSink interface {
// Emit publishes a RunEvent to the run-scoped Event sink.
Emit(event RunEvent) error
// EmitStream publishes a structured StreamPayload on the run-scoped
// Event sink. When the resolved provider transport is non-streaming the
// sink may discard the payload; this is independent of the public Run versus
// Stream method. Drivers MUST leave Sequence, Seq, and Timestamp zero; core
// assigns all three in receiver order.
EmitStream(payload StreamPayload) error
}
EventSink is the per-run event surface drivers write into while executing. Emit accepts operational RunEvent data; EmitStream accepts normalized token, tool, reasoning, and HITL payloads when provider streaming is enabled. Both methods feed the same public typed Event stream; they are not separate consumer channels. Drivers should not retain the sink after Run returns. Every RunEventItem emitted through Emit MUST appear in Response.Transcript in the same order, with no hidden or recomputed entries.
type FailureAction ¶
type FailureAction string
FailureAction is the value type for HumanDecisionPolicy.OnTimeout and HumanDecisionPolicy.OnReject. It describes what the SDK should do next when a decision surface produces a failure signal.
const ( // FailureActionUnset inherits the SDK default action. FailureActionUnset FailureAction = "" // FailureAbort terminates the run and emits a business failure with the // matching code (FailureReject or FailureTimeout). This is the default. FailureAbort FailureAction = "abort" // FailureContinue lets the driver forward the reject / timeout to the // agent as a tool_result so the run can progress. FailureContinue FailureAction = "continue" // FailureRetry re-triggers the same decision (bounded by MaxRetries). // When the driver cannot truly re-ask, the runner warns and degrades to // FailureAbort. FailureRetry FailureAction = "retry" )
type FailureCode ¶
type FailureCode string
FailureCode is the enumeration carried on RunFailure.Code.
const ( // FailureReject indicates that a HITL decision was rejected (including // AutoReject synthesis) and OnReject resolved to FailureAbort. FailureReject FailureCode = "decision_rejected" // FailureTimeout indicates that a HITL decision Deadline elapsed and // OnTimeout resolved to FailureAbort. FailureTimeout FailureCode = "decision_timeout" // FailureAgentError reports a driver-level failure (bad protocol, // non-zero exit, handler panic, …). FailureAgentError FailureCode = "agent_error" // FailureCancelled indicates that the run was cancelled (ctx.Cancel, // handler returned error, etc.). FailureCancelled FailureCode = "cancelled" // FailurePolicyError reports a policy validation error at start time. FailurePolicyError FailureCode = "policy_error" )
type FeatureLevel ¶
type FeatureLevel string
FeatureLevel is used for optional capabilities (search, browser tooling).
const ( // FeatureInherit leaves the capability to the Agent default or driver fallback. FeatureInherit FeatureLevel = "" // FeatureAllow explicitly enables the optional capability when supported. FeatureAllow FeatureLevel = "allow" // FeatureDeny explicitly disables the optional capability. FeatureDeny FeatureLevel = "deny" )
type HITLRequestedPayload ¶
type HITLRequestedPayload struct {
RequestID string
Kind HumanDecisionKind
Source string
ToolCallID string
Prompt string
Payload map[string]any
Choices []DecisionChoice
CreatedAt time.Time
Deadline time.Time
RetryAttempt int
}
HITLRequestedPayload is the structured body of a StreamHITLRequested StreamPayload. It is attached at StreamPayload.HITLRequested.
type HITLResolvedPayload ¶
type HITLResolvedPayload struct {
RequestID string
Kind HumanDecisionKind
Source string
RetryAttempt int
Result DecisionResult
Choice string
Answer map[string]any
ResolvedAt time.Time
Latency time.Duration
}
HITLResolvedPayload is the structured body of a StreamHITLResolved StreamPayload.
type HookEvent ¶
type HookEvent string
HookEvent is the SDK-level lifecycle event intent. Drivers translate these values into provider-native event names.
const ( // HookEventSessionStart runs when a provider session starts. HookEventSessionStart HookEvent = "session_start" // HookEventSessionEnd runs when a provider session ends. HookEventSessionEnd HookEvent = "session_end" // HookEventPromptSubmit runs when a prompt is submitted. HookEventPromptSubmit HookEvent = "prompt_submit" // HookEventPromptExpand runs when a provider expands a prompt. HookEventPromptExpand HookEvent = "prompt_expand" // HookEventPreTool runs before a tool invocation. HookEventPreTool HookEvent = "pre_tool" // HookEventPostTool runs after a successful tool invocation. HookEventPostTool HookEvent = "post_tool" // HookEventToolFailure runs after a failed tool invocation. HookEventToolFailure HookEvent = "tool_failure" // HookEventPermissionRequest runs when a permission decision is requested. HookEventPermissionRequest HookEvent = "permission_request" // HookEventPreShell runs before a shell command. HookEventPreShell HookEvent = "pre_shell" // HookEventPostShell runs after a shell command. HookEventPostShell HookEvent = "post_shell" // HookEventPreMCP runs before an MCP operation. HookEventPreMCP HookEvent = "pre_mcp" // HookEventPostMCP runs after an MCP operation. HookEventPostMCP HookEvent = "post_mcp" // HookEventPreFileRead runs before a file read. HookEventPreFileRead HookEvent = "pre_file_read" // HookEventPostFileEdit runs after a file edit. HookEventPostFileEdit HookEvent = "post_file_edit" // HookEventSubagentStart runs when a provider sub-agent starts. HookEventSubagentStart HookEvent = "subagent_start" // HookEventSubagentStop runs when a provider sub-agent stops. HookEventSubagentStop HookEvent = "subagent_stop" // HookEventPreCompact runs before provider context compaction. HookEventPreCompact HookEvent = "pre_compact" // HookEventPostCompact runs after provider context compaction. HookEventPostCompact HookEvent = "post_compact" // HookEventStop runs when provider execution stops normally. HookEventStop HookEvent = "stop" // HookEventStopFailure runs when provider execution stops with a failure. HookEventStopFailure HookEvent = "stop_failure" )
type HookFailPolicy ¶
type HookFailPolicy string
HookFailPolicy controls whether a hook failure stops the provider action.
const ( // HookFailPolicyProviderDefault delegates failure handling to the provider. HookFailPolicyProviderDefault HookFailPolicy = "" // HookFailPolicyOpen allows the provider action after a hook failure. HookFailPolicyOpen HookFailPolicy = "open" // HookFailPolicyClosed prevents the provider action after a hook failure. HookFailPolicyClosed HookFailPolicy = "closed" )
type HookHandler ¶
type HookHandler struct {
Type HookHandlerType
Command string
Args []string
Env map[string]string
Prompt string
URL string
Server string
Tool string
Input map[string]any
Agent string
}
HookHandler describes the action a hook runs. Command hooks are portable core; the other handler types are portable extended and require driver support.
type HookHandlerType ¶
type HookHandlerType string
HookHandlerType identifies the action executed for a hook.
const ( // HookHandlerCommand executes a local command. HookHandlerCommand HookHandlerType = "command" // HookHandlerPrompt invokes a provider prompt hook. HookHandlerPrompt HookHandlerType = "prompt" // HookHandlerHTTP invokes an HTTP endpoint. HookHandlerHTTP HookHandlerType = "http" // HookHandlerMCPTool invokes an MCP tool. HookHandlerMCPTool HookHandlerType = "mcp_tool" // HookHandlerAgent invokes a provider sub-agent. HookHandlerAgent HookHandlerType = "agent" )
type HookMatcher ¶
type HookMatcher struct {
Subject HookMatcherSubject
Syntax HookMatcherSyntax
Pattern string
}
HookMatcher describes what a hook filters on and which syntax the pattern uses. Drivers may use provider-native matchers or script-side filtering.
type HookMatcherSubject ¶
type HookMatcherSubject string
HookMatcherSubject identifies the value matched by a hook filter.
const ( // HookMatcherSubjectDefault delegates subject selection to the provider. HookMatcherSubjectDefault HookMatcherSubject = "" // HookMatcherSubjectTool matches tool names. HookMatcherSubjectTool HookMatcherSubject = "tool" // HookMatcherSubjectCommand matches shell commands. HookMatcherSubjectCommand HookMatcherSubject = "command" // HookMatcherSubjectMCP matches MCP servers or tools. HookMatcherSubjectMCP HookMatcherSubject = "mcp" // HookMatcherSubjectPath matches filesystem paths. HookMatcherSubjectPath HookMatcherSubject = "path" // HookMatcherSubjectPrompt matches prompt text. HookMatcherSubjectPrompt HookMatcherSubject = "prompt" // HookMatcherSubjectSubagent matches sub-agent identifiers. HookMatcherSubjectSubagent HookMatcherSubject = "subagent" // HookMatcherSubjectSource matches provider event sources. HookMatcherSubjectSource HookMatcherSubject = "source" )
type HookMatcherSyntax ¶
type HookMatcherSyntax string
HookMatcherSyntax identifies how a HookMatcher pattern is interpreted.
const ( // HookMatcherSyntaxProvider delegates pattern syntax to the provider. HookMatcherSyntaxProvider HookMatcherSyntax = "" // HookMatcherSyntaxExact requires an exact match. HookMatcherSyntaxExact HookMatcherSyntax = "exact" // HookMatcherSyntaxRegex interprets the pattern as a regular expression. HookMatcherSyntaxRegex HookMatcherSyntax = "regex" // HookMatcherSyntaxPrefix requires a matching prefix. HookMatcherSyntaxPrefix HookMatcherSyntax = "prefix" // HookMatcherSyntaxContains requires the value to contain the pattern. HookMatcherSyntaxContains HookMatcherSyntax = "contains" )
type HookPayload ¶
HookPayload is the normalized driver-facing hook resource state.
type HookSpec ¶
type HookSpec struct {
Key string
Event HookEvent
MatcherSpec HookMatcher
Handler HookHandler
Timeout time.Duration
FailPolicy HookFailPolicy
StatusMessage string
Disabled bool
Native map[string]any
Metadata map[string]string
}
HookSpec describes one host-declared provider hook.
type HumanDecisionFailure ¶
type HumanDecisionFailure struct {
Kind HumanDecisionKind
Source string
Decision DecisionResult
Request *DecisionRequest
Attempts int
}
HumanDecisionFailure is the structured attribution attached to RunFailure.HumanDecision when a HITL decision causes a run to terminate.
type HumanDecisionKind ¶
type HumanDecisionKind string
HumanDecisionKind labels the semantic category of a human-in-the-loop (HITL) decision event. See docs/run-policy.md for the public taxonomy.
const ( // HumanDecisionPermission covers tool, command, file, or permission gates. HumanDecisionPermission HumanDecisionKind = "permission" // HumanDecisionPlanReview covers plan-mode approval before execution. HumanDecisionPlanReview HumanDecisionKind = "plan_review" // HumanDecisionQuestion covers structured clarification questions. HumanDecisionQuestion HumanDecisionKind = "question" )
type HumanDecisionMode ¶
type HumanDecisionMode string
HumanDecisionMode expresses the host's intent for a Permission / PlanReview decision (binary-approval classes).
Semantic layering:
- Ask → route the request to OnApproval or an ApprovalRequest Event.
- AutoApprove → defer to the agent / CLI bypass / auto path.
- AutoReject → synthesize a rejection locally and emit a Failure.
- Unset ("") → fall back to the SDK default (see docs/run-policy.md §1.3).
Question uses the narrower QuestionMode because the values are not interchangeable: a Question result is structured (Answered), so "auto approve" has no legitimate synthesized value.
const ( // HumanDecisionUnset inherits the Agent or SDK default. HumanDecisionUnset HumanDecisionMode = "" // HumanDecisionAsk routes the decision to OnApproval or an ApprovalRequest Event. HumanDecisionAsk HumanDecisionMode = "ask" // HumanDecisionAutoApprove lets the driver take its provider-specific // automatic/bypass path for the decision class. HumanDecisionAutoApprove HumanDecisionMode = "auto_approve" // HumanDecisionAutoReject synthesizes a rejection locally. HumanDecisionAutoReject HumanDecisionMode = "auto_reject" )
type HumanDecisionModeUnsupportedError ¶
type HumanDecisionModeUnsupportedError struct {
Driver string
Kind HumanDecisionKind
Mode string
}
HumanDecisionModeUnsupportedError identifies the exact capability miss. Mode is textual because Permission/PlanReview and Question deliberately use different mode types.
func (*HumanDecisionModeUnsupportedError) Error ¶
func (e *HumanDecisionModeUnsupportedError) Error() string
Error implements error.
func (*HumanDecisionModeUnsupportedError) Unwrap ¶
func (e *HumanDecisionModeUnsupportedError) Unwrap() error
Unwrap exposes ErrHumanDecisionModeUnsupported for errors.Is.
type HumanDecisionPolicy ¶
type HumanDecisionPolicy struct {
Permission HumanDecisionMode
PlanReview HumanDecisionMode
Question QuestionMode
// Timeout is the maximum time the SDK waits for a host to resolve a
// decision when the field value is Ask. 0 means "SDK default" (30s);
// negative values mean "never time out".
Timeout time.Duration
// OnTimeout selects the SDK action when a decision times out.
OnTimeout FailureAction
// OnReject selects the SDK action when a decision resolves to a rejection
// (handler return value or AutoReject synthesis).
OnReject FailureAction
// MaxRetries caps the FailureRetry action. 0 means "SDK default" (3).
// Negative values are rejected during policy merging.
MaxRetries int
}
HumanDecisionPolicy is the RunPolicy-facing sub-struct that carries all HITL knobs. Zero-valued fields inherit the SDK defaults declared in docs/run-policy.md §1.3.
func EffectiveHumanDecisionPolicy ¶
func EffectiveHumanDecisionPolicy(p HumanDecisionPolicy) HumanDecisionPolicy
EffectiveHumanDecisionPolicy materializes SDK defaults for unset fields in a HumanDecisionPolicy. Drivers use it when they need to know the actual Timeout / OnTimeout / OnReject / MaxRetries values that the runner applies so they can surface consistent Deadline timestamps and failure messages.
type HumanDecisionSupport ¶
HumanDecisionSupport describes Permission / PlanReview support on a given driver. Fields set to false reject the matching host-facing setting before driver launch.
type InstructionMode ¶
type InstructionMode string
InstructionMode controls whether instructions extend or replace native ones.
const ( // InstructionModeAdditive adds the bundle to native instructions. InstructionModeAdditive InstructionMode = "" // InstructionModeReplace replaces native instructions where supported. InstructionModeReplace InstructionMode = "replace" )
type InstructionScope ¶
type InstructionScope string
InstructionScope identifies where an instruction bundle applies.
const ( // InstructionScopeDefault delegates scope selection to the driver. InstructionScopeDefault InstructionScope = "" // InstructionScopeUser applies instructions to the provider user profile. InstructionScopeUser InstructionScope = "user" // InstructionScopeProject applies instructions to the resolved project. InstructionScopeProject InstructionScope = "project" // InstructionScopeLocal applies instructions to the local workspace only. InstructionScopeLocal InstructionScope = "local" // InstructionScopeRun applies instructions only to the current invocation. InstructionScopeRun InstructionScope = "run" )
type InstructionsBundleRef ¶
type InstructionsBundleRef struct {
// ID is the stable host identity of the instruction bundle.
ID string
// Path locates instruction material already present on disk.
Path string
// Content carries inline instruction material.
Content string
// Fingerprint identifies the resolved provider-visible contents.
Fingerprint string
// Scope selects where the instructions apply.
Scope InstructionScope
// Mode selects additive or replacement semantics.
Mode InstructionMode
// Native carries provider-specific extensions.
Native map[string]any
}
InstructionsBundleRef points at host-supplied instruction material. The SDK treats it as desired state; drivers decide whether to materialize it as a provider-native file/rule or inject it into the prompt as a fallback.
type InstructionsCapability ¶
type InstructionsCapability struct {
Supported bool
}
InstructionsCapability declares whether the driver accepts explicit instruction bundles in addition to the prompt.
type InvalidDriverConfigError ¶
InvalidDriverConfigError identifies the configured Driver and preserves its validation error while unwrapping to ErrInvalidDriverConfig.
func (*InvalidDriverConfigError) Error ¶
func (e *InvalidDriverConfigError) Error() string
Error implements error.
func (*InvalidDriverConfigError) Unwrap ¶
func (e *InvalidDriverConfigError) Unwrap() error
Unwrap preserves the stable category and the Driver-provided cause.
type InvalidOutputSchemaError ¶
InvalidOutputSchemaError carries diagnostic detail while unwrapping to ErrInvalidOutputSchema.
func (*InvalidOutputSchemaError) Error ¶
func (e *InvalidOutputSchemaError) Error() string
func (*InvalidOutputSchemaError) Unwrap ¶
func (e *InvalidOutputSchemaError) Unwrap() error
Unwrap preserves both the public category and the lower-level cause.
type InvalidPolicyError ¶
InvalidPolicyError identifies one out-of-domain RunPolicy field. Value is formatted as text because the policy contains several distinct string enumerations plus MaxRetries.
func (*InvalidPolicyError) Error ¶
func (e *InvalidPolicyError) Error() string
Error implements error.
func (*InvalidPolicyError) Unwrap ¶
func (e *InvalidPolicyError) Unwrap() error
Unwrap exposes ErrInvalidPolicy for errors.Is.
type IsolationLevel ¶
type IsolationLevel string
IsolationLevel controls filesystem / process boundary strength.
const ( // IsolationInherit leaves isolation to the Agent default or driver fallback. IsolationInherit IsolationLevel = "" // IsolationReadOnly requests a read-only workspace. IsolationReadOnly IsolationLevel = "read_only" // IsolationWorkspaceWrite allows writes inside the resolved workspace. IsolationWorkspaceWrite IsolationLevel = "workspace_write" // IsolationUnrestricted maps to each agent's "full access" / danger // sandbox (or the closest available behavior). IsolationUnrestricted IsolationLevel = "unrestricted" )
type MCPCapability ¶
MCPCapability describes which MCP transports a driver supports. The SDK validates host-provided MCPConfig against this before invoking the driver.
type MCPPayload ¶
type MCPPayload struct {
Servers []MCPServerSpec
Fingerprint string
Warnings []string
}
MCPPayload is the normalized driver-facing MCP configuration after validation, capability checks, sorting, and fingerprinting.
type MCPServerSpec ¶
type MCPServerSpec struct {
Key string
Transport MCPTransport
Command string
Args []string
Env map[string]string
URL string
Headers map[string]string
BearerTokenEnvVar string
Required bool
RequiredReason string
}
MCPServerSpec is one host-declared MCP server. For stdio servers, Command and Args describe the process to launch. For HTTP/SSE servers, URL, Headers, and BearerTokenEnvVar describe the remote endpoint. Required marks servers the host expects to be present for the run.
type MCPTransport ¶
type MCPTransport string
MCPTransport identifies how a model-context-protocol server is reached. Built-in drivers translate these values into provider-specific profile or CLI configuration only when their descriptor advertises support.
const ( // MCPTransportStdio starts a local command and speaks MCP over stdio. MCPTransportStdio MCPTransport = "stdio" // MCPTransportHTTP connects to an HTTP MCP endpoint. MCPTransportHTTP MCPTransport = "http" // MCPTransportSSE connects to an SSE-based MCP endpoint. MCPTransportSSE MCPTransport = "sse" )
type ModelDetector ¶
type ModelDetector interface {
DetectModel(ctx context.Context, cfg any, profile *ProfileSelection) (*DetectedModel, error)
}
ModelDetector is implemented by drivers that can infer the effective model from config files, CLI defaults, profile state, or the supplied config.
type ModelInfo ¶
ModelInfo is a model option visible through a driver. ID is the value accepted by config; Label is display text for UIs.
type ModelLister ¶
ModelLister is implemented by drivers that can list visible model choices. Drivers may return static descriptor models or inspect local provider state when a live list is available.
type NativeConfigPatch ¶
type NativeConfigPatch struct {
Provider string
FileKind ProfileConfigFileKind
Path string
Section string
Values map[string]any
}
NativeConfigPatch identifies a provider-native structured config patch.
type OutputFormat ¶
type OutputFormat string
OutputFormat labels the final business-output contract requested by a host. It is distinct from driver protocol envelopes such as `stream-json`, which only make CLI events machine-readable.
const ( // OutputFormatJSONSchema requests a value governed by a JSON Schema. OutputFormatJSONSchema OutputFormat = "json_schema" )
type OutputSchema ¶
type OutputSchema struct {
Format OutputFormat
SchemaJSON json.RawMessage
Name string
Description string
OnInvalid StructuredOutputInvalidPolicy
}
OutputSchema is a per-run request for final structured JSON output. SchemaJSON is the raw JSON Schema document supplied by the host or generated by JSONSchemaFor. Public API intentionally exposes no third-party schema library types.
type PolicyCapabilityUnsupportedError ¶
PolicyCapabilityUnsupportedError identifies one valid policy dimension which the Driver cannot honor. Approval modes use the more specific HumanDecisionModeUnsupportedError.
func (*PolicyCapabilityUnsupportedError) Error ¶
func (e *PolicyCapabilityUnsupportedError) Error() string
Error implements error.
func (*PolicyCapabilityUnsupportedError) Unwrap ¶
func (e *PolicyCapabilityUnsupportedError) Unwrap() error
Unwrap exposes ErrPolicyCapabilityUnsupported for errors.Is.
type ProcessCapability ¶
type ProcessCapability struct {
Persistent bool
}
ProcessCapability declares provider-process lifecycle support. Persistent means a driver can reuse one provider process across turns of a stateful Thread and therefore MUST implement ProcessLifecycleDriver. Core still requests a one-shot process when Request.Spawn is true.
type ProcessLifecycleDriver ¶
ProcessLifecycleDriver is the lifecycle contract implemented by every Driver whose Descriptor.Process.Persistent is true. CloseProcesses must be idempotent, stop every process owned by that configured Driver (including child process groups), and treat ctx as a hard upper bound. A persistent declaration without this interface is a capability-contract violation.
type ProfileConfigFileKind ¶
type ProfileConfigFileKind string
ProfileConfigFileKind identifies the structured profile config format a patch targets.
const ( // ProfileConfigFileJSON selects a JSON profile configuration file. ProfileConfigFileJSON ProfileConfigFileKind = "json" // ProfileConfigFileTOML selects a TOML profile configuration file. ProfileConfigFileTOML ProfileConfigFileKind = "toml" )
type ProfileConfigPatch ¶
type ProfileConfigPatch struct {
Key string
Capability string
Values map[string]any
Native *NativeConfigPatch
}
ProfileConfigPatch is a structured config update. Hosts supply typed values; drivers/reconcilers own provider-native encoding.
type ProfileConfigPayload ¶
type ProfileConfigPayload struct {
Patches []ProfileConfigPatch
Fingerprint string
Warnings []string
}
ProfileConfigPayload is the normalized driver-facing config patch state.
type ProfileMode ¶
type ProfileMode string
ProfileMode describes how a built-in driver should choose its local provider profile directory for auth, config, MCP, and skill state.
const ( // ProfileModeUnset means "use the driver default behavior". ProfileModeUnset ProfileMode = "" // ProfileModeNative uses the provider's native profile/home resolution. ProfileModeNative ProfileMode = "native" // ProfileModeDedicated uses Dir as the provider home/profile directory. ProfileModeDedicated ProfileMode = "dedicated" // ProfileModeClone creates or refreshes a managed profile copied from From. ProfileModeClone ProfileMode = "clone" )
type ProfilePayload ¶
type ProfilePayload struct {
Skills ResolvedSkills
MCP MCPPayload
Agents AgentPayload
Hooks HookPayload
Instructions *InstructionsBundleRef
Config ProfileConfigPayload
Declared ProfileResourceDeclarations
Fingerprint string
SessionCompatibilityFingerprint string
Warnings []string
}
ProfilePayload is the driver-facing normalized profile desired state for a single resolved invocation. Fingerprint covers the exact provider-visible resources in this request. SessionCompatibilityFingerprint is the separate resume/persistent-process guard; core may normalize only Agent-owned, ephemeral transport allocations there while retaining the exact payload and Fingerprint for materialization.
func (ProfilePayload) SessionFingerprint ¶
func (p ProfilePayload) SessionFingerprint() string
SessionFingerprint returns the fingerprint Drivers must store in session params and use for resume and persistent-process guards. The fallback keeps manually constructed Request values and older hosts correct when they only populate Fingerprint.
type ProfileReporter ¶
type ProfileReporter interface {
GetProfile(ctx context.Context, cfg any, agent AgentIdentity, profile *ProfileSelection) (AgentProfile, error)
}
ProfileReporter lets drivers report the effective local profile directory used for auth, config, MCP, and skill semantics. Agent.ProfileState and Agent.SyncProfile use it when the driver does not implement richer profile resource inspection.
Built-in drivers use this to report effective CODEX_HOME, CLAUDE_CONFIG_DIR, or CURSOR_HOME resolution, including managed homes when the SDK synthesizes one.
type ProfileResourceDeclarations ¶
ProfileResourceDeclarations records which optional profile resource kinds were explicitly declared by the host. Empty declared resources mean "clear managed entries"; undeclared resources must not be reconciled as empty.
type ProfileSelection ¶
type ProfileSelection struct {
// Mode selects native, dedicated, cloned, or driver-default resolution.
Mode ProfileMode
// Dir is the dedicated or managed destination profile directory.
Dir string
// From is the optional source directory for clone mode.
From string
// Clone controls clone contents when Mode is ProfileModeClone.
Clone *CloneProfileOptions
}
ProfileSelection is the normalized Agent profile request. Application code normally constructs its public profile.Selection alias with package profile and supplies it to adaptor.WithProfile.
type QuestionMode ¶
type QuestionMode string
QuestionMode expresses the host's intent for the Question class. It is a strict subset of HumanDecisionMode: AutoApprove is intentionally absent.
const ( // QuestionUnset inherits the Agent or SDK default. QuestionUnset QuestionMode = "" // QuestionAsk routes the question to OnApproval or an ApprovalRequest Event. QuestionAsk QuestionMode = "ask" // QuestionAutoReject rejects questions without asking the host. QuestionAutoReject QuestionMode = "auto_reject" )
type QuestionSupport ¶
QuestionSupport describes Question support on a given driver. AutoApprove is intentionally absent—QuestionMode has no such value.
type QuotaProbe ¶
type QuotaProbe interface {
GetQuota(ctx context.Context, cfg any, profile *ProfileSelection) (QuotaReport, error)
}
QuotaProbe lets drivers expose provider quota or credit windows when the underlying CLI or local auth files support that probe.
type QuotaReport ¶
type QuotaReport struct {
DriverType string
Provider string
Source string
Available bool
Error string
Windows []QuotaWindow
}
QuotaReport is returned by Agent.Inspect().Quota.
type QuotaWindow ¶
type QuotaWindow struct {
Label string
UsedPercent *int
ResetsAt string
ValueLabel string
Detail string
}
QuotaWindow describes one quota/rate-limit/credit window reported by a driver-specific quota probe.
type RawStreams ¶
type RawStreams struct {
Stdout string
Stderr string
Terminal *TerminalPayload
}
RawStreams captures the complete raw stdout and stderr emitted during one run together with the provider terminal payload recognized from that same byte stream. It is the stable surface hosts should rely on for auditing, replay, debugging, or archival.
Contract:
- Stdout / Stderr hold the full untruncated bytes the child process wrote.
- No redaction, no semantic parsing, no line-wise transformation is applied.
- Terminal is nil when no official terminal event was observed.
- Both consumer Run and Stream.Result must return equivalent values.
type Request ¶
type Request struct {
RunID string
Prompt string
Config any
Agent AgentIdentity
Workspace WorkspaceLease
Runtime RuntimePayload
Skills ResolvedSkills
MCP MCPPayload
ProfilePayload ProfilePayload
Profile *ProfileSelection
Policy RunPolicy
Instructions *InstructionsBundleRef
Session *SessionContext
Metadata map[string]string
OutputSchema *OutputSchema
// StructuredOutputSource is the mechanism selected by core after
// capability and transport negotiation. It is non-empty exactly when
// OutputSchema is non-nil; Drivers consume it but do not renegotiate it.
StructuredOutputSource StructuredOutputSource
// Spawn forces this invocation onto a fresh provider process. The default
// false value allows a capable driver to reuse a process for a stateful
// Thread; stateless runs and drivers without Process.Persistent still spawn.
Spawn bool
// ModelOverride is the per-run model selected via WithModel. When
// non-empty it supersedes the construction model carried by Config for this
// invocation; drivers must prefer it over their Config model when
// resolving the provider-native model selection. Empty means "no
// override" and the driver falls back to its construction config.
ModelOverride string
// Streaming selects a provider-native streaming transport after the core
// has resolved the invocation. It is not derived from whether the consumer
// called Agent.Run or Agent.Stream: both consumer methods share one Event
// pipeline, and either may use a batch or streaming provider transport.
// Drivers that implement StreamSupport should use their declared native
// transport when this field is true.
//
// Drivers that do not implement StreamSupport are free to ignore
// this field. The public Event stream remains available, but it will not
// contain provider-native normalized deltas from that capability.
Streaming bool
}
Request is the fully resolved invocation the SDK passes to a driver. By the time a driver sees this value, Agent defaults and CallOption values have been merged, Thread state has been coordinated, workspace/runtime/skill/ MCP payloads have been resolved, and policy has been validated against the descriptor.
type ResolvedSkill ¶
type ResolvedSkill struct {
Key string
RuntimeName string
SourcePath string
Required bool
Reason string
Metadata map[string]string
}
ResolvedSkill carries the post-materialization information a driver needs to install or expose a single skill for the current run.
type ResolvedSkills ¶
type ResolvedSkills struct {
Mode SkillSyncMode
Entries []ResolvedSkill
Warnings []string
Fingerprint string
}
ResolvedSkills is the driver-facing view of a run's Selected skills. It is produced internally by the SDK and is not intended for host construction.
Contract between SDK and driver:
- Entries contains every selected skill after successful materialization. A selected skill that cannot be materialized fails resolution with ErrSkillMaterializationFailed before the driver is invoked.
- For the ListSkills / SyncSkills paths, the SDK additionally passes a parallel selected []string whose contents are exactly ResolvedSkills. Keys(). Drivers MAY rely on that equivalence; hosts MUST NOT observe divergence through the ResolvedSkills value alone.
- Warnings carries non-fatal messages. Materialization failures are fatal and are not represented as warnings.
- Fingerprint is a deterministic digest of Entries and Warnings. Two runs whose ResolvedSkills produce the same Fingerprint are guaranteed to have identical skill-visible state.
func (ResolvedSkills) Keys ¶
func (r ResolvedSkills) Keys() []string
Keys returns the list of ResolvedSkill keys in their current order.
type Response ¶
type Response struct {
// Output is final assistant-facing text only. It must not contain raw
// stdout/stderr dumps, Summary text, or provider terminal JSON.
Output string
// RawStreams carries complete raw stdout/stderr and the official provider
// terminal JSON (when the protocol defines one) for audit and debugging.
RawStreams *RawStreams
// Transcript is the normalized semantic item stream parsed by the driver.
Transcript []TranscriptItem
// ExitCode, Signal, and TimedOut preserve the observed subprocess
// outcome. Drivers should attach the more specific Failure parsed from an
// official provider error event when one exists. If they do not, core
// classifies any non-zero exit, signal, or timeout as FailureAgentError,
// except that cancellation of the outer invocation context retains its
// context.Canceled/context.DeadlineExceeded error identity. An abnormal
// process outcome can therefore never become a successful Result merely
// because the provider emitted no terminal error event.
ExitCode int
Signal string
TimedOut bool
Usage *Usage
Checkpoint *Checkpoint
Metadata map[string]string
Provider string
Model string
Summary string
StructuredOutput *StructuredOutput
RuntimeServices []RuntimeServiceReport
Failure *RunFailure
}
Response is the driver-facing execution result.
Built-in drivers must fill Output / RawStreams / Transcript / Summary / Checkpoint from the same pass that parses the CLI protocol; none of these fields may be recomputed by downstream helpers.
type Role ¶
type Role string
Role identifies the speaker for text-bearing StreamPayloads.
The zero value is RoleAssistant: every driver today emits text.start / text.content / text.end as assistant output, so leaving Role unset produces the canonical assistant encoding.
Role only carries semantics on text-lifecycle kinds (text.start / text.content / text.end). On every other Kind it MUST be left at the zero value; bridges treat non-zero Role on non-text kinds as a programming error and may ignore it.
RoleUser is exclusively produced by bridges or hosts that want the human turn to appear in the recorded / replayed StreamPayload stream (see bridges/agui.RunAgentInput.UserTurnPayloads). Drivers MUST NOT emit RoleUser themselves.
type RunEvent ¶
type RunEvent struct {
Type RunEventType
Seq uint64
Timestamp time.Time
Stream string
Bytes []byte
Item *TranscriptItem
Text string
Metadata map[string]string
Data map[string]any
}
RunEvent is the operational event envelope emitted into EventSink.
Field usage by Type:
- chunk: Stream ("stdout"|"stderr"), Bytes (raw chunk bytes, may be partial).
- item: Item (*TranscriptItem).
- invocation/spawn/runtime/lifecycle: Text, Metadata, Data.
Drivers MUST leave Seq zero. Core assigns it monotonically in Event sink receiver order. Collecting every RunEventItem in that order MUST reproduce the final Response.Transcript exactly, including any delta item the driver elects to retain there.
type RunEventType ¶
type RunEventType string
RunEventType describes the category of a streamed RunEvent.
There are two primary signals:
- RunEventChunk: raw stdout/stderr bytes. Chunks may not align to lines.
- RunEventItem: structured transcript entry emitted by the driver after parsing its own protocol.
The remaining types carry operational or lifecycle metadata.
const ( // RunEventChunk carries raw stdout/stderr bytes. RunEventChunk RunEventType = "chunk" // RunEventItem carries a parsed TranscriptItem. RunEventItem RunEventType = "item" // RunEventInvocation describes the resolved invocation metadata. RunEventInvocation RunEventType = "invocation" // RunEventSpawn reports child-process launch details. RunEventSpawn RunEventType = "spawn" // RunEventRuntime reports runtime-service preparation or cleanup. RunEventRuntime RunEventType = "runtime" // RunEventLifecycle reports high-level run lifecycle markers. RunEventLifecycle RunEventType = "lifecycle" )
type RunFailure ¶
type RunFailure struct {
Message string
Code FailureCode
Metadata map[string]any
HumanDecision *HumanDecisionFailure
}
RunFailure carries structured error information when the SDK or a driver classifies a failure more precisely than a plain stderr string.
HumanDecision is non-nil exactly when Code is FailureReject or FailureTimeout. Drivers MUST uphold this invariant on Response.Failure; adaptertest verifies it as RSP-02.
func (*RunFailure) IsHumanDecision ¶
func (f *RunFailure) IsHumanDecision() bool
IsHumanDecision reports whether the failure originated from a HITL decision (rejected or timed out). nil-safe.
func (*RunFailure) IsRejected ¶
func (f *RunFailure) IsRejected() bool
IsRejected reports whether the failure is a user-visible rejection (includes AutoReject synthesis). nil-safe.
func (*RunFailure) IsTimedOut ¶
func (f *RunFailure) IsTimedOut() bool
IsTimedOut reports whether the failure is a HITL decision timeout (OnTimeout=FailureAbort path). It is distinct from context.DeadlineExceeded on the outer context, which is returned by Run or Stream.Result. nil-safe.
type RunPolicy ¶
type RunPolicy struct {
Isolation IsolationLevel
WebSearch FeatureLevel
Browser FeatureLevel
HumanDecision HumanDecisionPolicy
}
RunPolicy is the only host-facing contract for execution guardrails. Values are not CLI flag names: each driver maps them to provider-specific controls. Empty fields (…Inherit) leave the dimension unspecified so the resolved Agent default or driver fallback applies. HumanDecision contains the complete HITL policy. See docs/run-policy.md for the public contract.
type RunPolicyCapabilities ¶
type RunPolicyCapabilities struct {
Isolation bool
WebSearch bool
Browser bool
Permission HumanDecisionSupport
PlanReview HumanDecisionSupport
Question QuestionSupport
}
RunPolicyCapabilities lists which RunPolicy dimensions a Driver can honor. False means unsupported: the root runner rejects an explicitly selected non-zero value before Driver.Run instead of silently ignoring host intent. Zero/inherit values remain portable and are not rejected. Permission / PlanReview / Question declare per-mode support via HumanDecisionSupport / QuestionSupport under the same explicit-value rule.
type RuntimeCapability ¶
type RuntimeCapability struct {
ReportsServices bool
}
RuntimeCapability declares whether a driver reports runtime-service state back in the run result's RuntimeServices.
type RuntimePayload ¶
type RuntimePayload struct {
Requested []RuntimeServiceSpec
Ensured []RuntimeServiceRef
SecretEnv []EnvBinding
Fingerprint string
}
RuntimePayload is the runtime-service equivalent of ResolvedSkills.
Requested contains the desired runtime services produced by Agent defaults, construction config, and CallOption overrides. Ensured contains the concrete service endpoints returned by the host ServiceManager.
type RuntimeServiceHealth ¶
type RuntimeServiceHealth string
RuntimeServiceHealth describes the observed service health when known.
const ( // RuntimeHealthUnknown means no health signal was observed. RuntimeHealthUnknown RuntimeServiceHealth = "unknown" // RuntimeHealthHealthy means the service passed health checks. RuntimeHealthHealthy RuntimeServiceHealth = "healthy" // RuntimeHealthUnhealthy means the service failed health checks. RuntimeHealthUnhealthy RuntimeServiceHealth = "unhealthy" )
type RuntimeServiceLifecycle ¶
type RuntimeServiceLifecycle string
RuntimeServiceLifecycle describes who owns service cleanup.
const ( RuntimeLifecycleShared RuntimeServiceLifecycle = "shared" // RuntimeLifecycleEphemeral means the service is scoped to one run. RuntimeLifecycleEphemeral RuntimeServiceLifecycle = "ephemeral" )
type RuntimeServiceRef ¶
type RuntimeServiceRef struct {
ID string
Name string
URL string
Status RuntimeServiceStatus
Lifecycle RuntimeServiceLifecycle
ReuseKey string
Command string
CWD string
Port int
OwnerAgentID string
Health RuntimeServiceHealth
// MCP, when non-nil, declares the MCP server this runtime service exposes
// to the run. Metadata is opaque and is never interpreted as an MCP
// declaration. MCPServerSpec's consumer-facing alias is mcp.Server, so
// hosts typically assign a value built with the mcp package constructors.
// An empty Key defaults to the ref's Name (then ID); an empty URL/Command
// defaults from the ref's URL/Command according to the transport.
MCP *MCPServerSpec
Metadata map[string]string
// SecretEnv carries subprocess-only runtime-issued secrets, such
// as per-run MCP bearer tokens. The SDK strips these bindings from public
// runtime refs/reports and injects them only into driver process env.
SecretEnv []EnvBinding
}
RuntimeServiceRef is a concrete service endpoint returned by the runtime manager and passed to drivers. URL is the primary connection string hosts expect agents to use.
type RuntimeServiceReport ¶
type RuntimeServiceReport struct {
ID string
Name string
URL string
Status RuntimeServiceStatus
Lifecycle RuntimeServiceLifecycle
ReuseKey string
Command string
CWD string
Port int
OwnerAgentID string
Health RuntimeServiceHealth
Metadata map[string]string
}
RuntimeServiceReport is the driver-facing execution report for one ensured runtime service. It records state actually observed during the invocation; an input declaration alone must not be reported as successful execution.
type RuntimeServiceSpec ¶
type RuntimeServiceSpec struct {
ID string
Name string
URL string
Description string
Lifecycle RuntimeServiceLifecycle
ReuseKey string
Command string
CWD string
Port int
Metadata map[string]string
}
RuntimeServiceSpec declares one service a run may need. Hosts can describe either an already-known endpoint (URL) or a command/port the runtime manager should start before invoking the driver.
type RuntimeServiceStatus ¶
type RuntimeServiceStatus string
RuntimeServiceStatus is the lifecycle state of a runtime service process.
const ( // RuntimeServiceStarting means the service is being prepared. RuntimeServiceStarting RuntimeServiceStatus = "starting" // RuntimeServiceRunning means the service is ready or already available. RuntimeServiceRunning RuntimeServiceStatus = "running" // RuntimeServiceStopped means the service has been stopped. RuntimeServiceStopped RuntimeServiceStatus = "stopped" // RuntimeServiceFailed means preparation or health checking failed. RuntimeServiceFailed RuntimeServiceStatus = "failed" )
type SessionCapability ¶
type SessionCapability struct {
SupportsResume bool
}
SessionCapability declares whether a driver can resume provider sessions. SupportsResume MUST be true if and only if the Driver implements SessionCodecProvider and returns a non-nil stable codec. When true, the Driver MUST additionally implement SessionConfigFingerprinter with a stable, non-empty construction-config identity.
type SessionCodec ¶
type SessionCodec interface {
Name() string
ToParams(state *SessionState) SessionParams
FromParams(params SessionParams) *SessionState
GuardFingerprint(params SessionParams) string
}
SessionCodec formalizes how one driver maps SessionState to stable, host-readable session parameters and how it derives a resume-guard fingerprint.
The codec does not introduce a second session model. Instead it gives hosts, tests, and drivers a stable way to normalize SessionState and inspect driver-specific parameters without guessing map keys.
Name MUST return a non-empty identifier stable across instances and processes. Every implementation MUST define the canonical empty mapping: ToParams(nil) returns the zero SessionParams, FromParams(SessionParams{}) returns nil, and GuardFingerprint accepts the zero value without panicking. For non-empty values, ToParams and FromParams MUST round-trip ResumeID, DisplayID and Values losslessly, and GuardFingerprint MUST be deterministic across processes for equivalent canonical parameters.
Built-in drivers store ProfilePayload.SessionFingerprint() in the session params so that GuardFingerprint changes whenever MCP, skills, agents, hooks, instructions, or structured config changes. Core may normalize only Agent-owned ephemeral transport allocation details in that value; ProfilePayload.Fingerprint remains the exact provider-visible materialization fingerprint. A Run invocation that supplies a resume ID whose GuardFingerprint no longer matches the current session fingerprint MUST be rejected before provider launch with a dedicated error. This keeps provider-visible profile resources consistent with the session they were captured for.
type SessionCodecProvider ¶
type SessionCodecProvider interface {
SessionCodec() SessionCodec
}
SessionCodecProvider exposes the stable, deterministic session mapping used for resume compatibility. A Driver MUST implement this interface with a non-nil, non-typed-nil codec if and only if Descriptor.Sessions.SupportsResume is true. Resume-capable Drivers MUST also implement SessionConfigFingerprinter; Thread prelaunch rejects either missing contract before acquiring store leases or invoking Driver.Run.
type SessionConfigFingerprintError ¶
SessionConfigFingerprintError reports that construction config cannot be represented by the strict canonical encoder. Path contains field names and generic collection positions only; it never contains map keys or values. Type and Kind describe the rejected Go shape without formatting its value.
func (*SessionConfigFingerprintError) Error ¶
func (e *SessionConfigFingerprintError) Error() string
type SessionConfigFingerprinter ¶
SessionConfigFingerprinter is the stable construction-config identity contract used when a Driver participates in a resumable Thread.
A resume-capable Driver used by Thread MUST implement this interface. The returned fingerprint MUST be non-empty, deterministic across processes, and cover every construction-time value visible to the provider as well as the Driver's session-codec/version contract. Implementations MUST return an error when they cannot represent a value stably; silently omitting such a value can resume a session under an incompatible configuration.
The fingerprint is an opaque compatibility token. Callers MUST NOT parse it or expose it as configuration, and implementations MUST NOT return raw configuration or secret values in errors.
type SessionContext ¶
type SessionContext struct {
EngineSessionID string
Mode SessionMode
State *SessionState
PreviousID string
}
SessionContext is the checkpoint state a resume-capable driver receives for one invocation. EngineSessionID is the provider handle to continue; State holds the full driver checkpoint; Mode tells the driver whether this is a fresh, continued, forked, or stateless invocation.
type SessionMode ¶
type SessionMode string
SessionMode controls how the SDK coordinates an invocation with a Thread store. Without a Thread store, runs are stateless and stateful modes return an error rather than silently pretending to resume.
const ( // SessionContinueOrStart resolves the Thread's single opaque host key and // resumes its active checkpoint when one exists; otherwise it starts fresh. SessionContinueOrStart SessionMode = "continue_or_start" // SessionContinueOnly requires a compatible active checkpoint for the // Thread key and fails when none exists. SessionContinueOnly SessionMode = "continue_only" // SessionFork starts from a parent checkpoint but persists the result under // the fork's distinct Thread key without modifying the parent. SessionFork SessionMode = "fork" // SessionStateless forces no session resolution or persistence for this run. SessionStateless SessionMode = "stateless" )
type SessionParams ¶
SessionParams is the structured host-facing view of one driver session.
ResumeID is the engine-owned token needed to continue the session. DisplayID is the user-facing label. Values stores driver-specific session parameters such as cwd or profile fingerprints used for resume guards.
type SessionState ¶
type SessionState struct {
ResumeID string
DisplayID string
// Data stores driver-specific session parameters such as cwd, effective
// profile fingerprints, or repo identifiers needed to validate a resume
// attempt.
Data map[string]string
}
SessionState is the driver-owned checkpoint payload persisted by the Thread store after a successful run. ResumeID is the provider session handle; Data contains driver-specific guards such as cwd or effective profile fingerprints.
type Skill ¶
type Skill struct {
// Key is the business-facing identifier of the skill. It is compared
// case-sensitively during merging; any two Skill values that share a Key
// must be structurally equal (see ErrSkillKeyConflict).
Key string
// Source describes how the SDK should locate / materialize the SKILL.md
// content. Source == nil is invalid; the SDK reports ErrSkillSourceMissing
// while resolving Agent defaults or a Run/Stream invocation.
Source SkillSource
// Required marks the skill as must-install. Required skills are added to
// the Selected set for every run regardless of what the caller passed in
// WithSkills.
Required bool
// Reason is a human-readable explanation attached to Required skills.
// Rendered by host UIs; ignored when Required is false.
Reason string
// Metadata carries optional extension fields. Keys with an underscore
// prefix are reserved for SDK-level interpretation; the currently defined
// keys are SkillMetadataRuntimeName and SkillMetadataDisplayName.
Metadata map[string]string
}
Skill is the canonical description of one skill: who it is (Key), where it comes from (Source), and whether it must participate in every run that sees it (Required). See docs/api-reference.md §11.1 for the public contract.
Skill also acts as a SkillRef so callers can pass a Skill value directly to adaptor.WithSkills without first registering it in a provider.
type SkillCapability ¶
type SkillCapability struct {
Supported bool
Mode SkillSyncMode
}
SkillCapability declares whether a driver consumes resolved skills and whether its skill state is ephemeral per run or persistent in the profile.
type SkillOrigin ¶
type SkillOrigin string
SkillOrigin describes who owns or installed one skill snapshot entry.
const ( // SkillOriginManaged marks SDK/host-managed skills. SkillOriginManaged SkillOrigin = "company_managed" // SkillOriginRequired marks skills selected because the provider declared // them Required. SkillOriginRequired SkillOrigin = "paperclip_required" // SkillOriginUser marks skills installed by the operator/user. SkillOriginUser SkillOrigin = "user_installed" // SkillOriginUnknown marks externally discovered skills whose owner is unknown. SkillOriginUnknown SkillOrigin = "external_unknown" )
type SkillRef ¶
type SkillRef interface {
// contains filtered or unexported methods
}
SkillRef is accepted by adaptor.WithSkills. It is either a catalogue key (SkillKey) or a fully-defined Skill value.
type SkillSnapshot ¶
type SkillSnapshot struct {
DriverType string
Supported bool
Mode SkillSyncMode
Selected []string
Resolved []Skill
Entries []SnapshotEntry
Warnings []string
Fingerprint string
}
SkillSnapshot is the inspection and synchronization report returned through Agent.Inspect().Skills, Agent.SelectSkills, and Agent.SyncProfile.
type SkillSource ¶
type SkillSource interface {
// SkillSource is the marker method. It MUST be a no-op; its only
// purpose is to constrain types that can be assigned to a Source
// field. Custom types implement it as `func (T) SkillSource() {}`.
SkillSource()
}
SkillSource is the open marker for a Skill's origin. Built-in sources and constructors live in package skill. Hosts MAY define custom source types as long as a matching skill.Materializer is installed with adaptor.WithSkillMaterializer.
SDK never branches on host-defined source types itself; it only routes them to the configured materializer. This keeps the SDK closed against host ontology while letting hosts own their fetch / unpack / cache strategy. See docs/api-reference.md §11.1 for the materializer contract.
type SkillState ¶
type SkillState string
SkillState describes driver-layer status for one skill snapshot entry.
const ( // SkillStateAvailable means the skill is known to the catalogue but not selected. SkillStateAvailable SkillState = "available" // SkillStateConfigured means the driver/profile has the skill configured. SkillStateConfigured SkillState = "configured" // SkillStateInstalled means the required files are present in the driver runtime. SkillStateInstalled SkillState = "installed" // SkillStateMissing means a selected skill could not be found where expected. SkillStateMissing SkillState = "missing" // SkillStateStale means a persistent skill exists but differs from the SDK input. SkillStateStale SkillState = "stale" // SkillStateExternal means the driver found a skill outside SDK management. SkillStateExternal SkillState = "external" )
type SkillSupport ¶
type SkillSupport interface {
ListSkills(ctx context.Context, cfg any, payload ResolvedSkills, selected []string, resolved []Skill, profile *ProfileSelection) (SkillSnapshot, error)
InjectSkills(ctx context.Context, cfg any, payload ResolvedSkills, profile *ProfileSelection) error
SyncSkills(ctx context.Context, cfg any, payload ResolvedSkills, selected []string, resolved []Skill, profile *ProfileSelection) (SkillSnapshot, error)
}
SkillSupport is the optional driver contract for skill-capable drivers. Drivers that do not implement it simply ignore skills; the SDK still reports an unsupported snapshot through Agent.Inspect().Skills.
The design splits concerns across three methods:
- ListSkills reports the read-only inspection snapshot. selected is the final selection set (required skills plus Agent defaults and any active SelectSkills selection) and matches payload.Keys(); resolved is the full merged catalogue (provider candidates plus selected skills). Drivers should pass resolved through to SkillSnapshot.Resolved so the inspection API can render the "available but unselected" view without re-enumerating the provider.
- InjectSkills is invoked exactly once per resolved invocation after skill resolution and before the driver starts. It is an optional pre-launch materialization hook and should stay non-destructive unless the driver can prove the run cannot later be rejected. Built-in drivers treat it as a no-op and reconcile profile-local resources inside Run() after resume guards pass, because the effective profile directory is only known there.
- SyncSkills is invoked by Agent.SelectSkills and Agent.SyncProfile to reconcile the persistent or ephemeral provider layout with the selected set. It receives both the selected keys and the full resolved catalogue for the same reason as ListSkills.
Invariants the SDK guarantees to drivers:
- selected == payload.Keys() for both ListSkills and SyncSkills. Drivers MAY rely on this equality when building snapshots.
- resolved is always a superset of payload.Entries (by Key): every materialised entry has a Skill in resolved, but resolved may additionally contain unselected candidates.
Invariants drivers MUST preserve:
- The Resolved slice returned in SkillSnapshot MUST describe the full merged catalogue the SDK passed in. Drivers are free to clone or reorder it; they MUST NOT silently drop entries.
type SkillSyncMode ¶
type SkillSyncMode string
SkillSyncMode describes how a driver surfaces skills for one run.
const ( // SkillSyncUnsupported means the driver ignores SDK-resolved skills or // cannot report observed skill state through Agent.Inspect().Skills. SkillSyncUnsupported SkillSyncMode = "unsupported" // SkillSyncEphemeral means skills are materialized for the current run or // managed profile and do not represent durable user configuration. SkillSyncEphemeral SkillSyncMode = "ephemeral" // SkillSyncPersistent means the driver exposes or updates a durable // provider-side skill installation. SkillSyncPersistent SkillSyncMode = "persistent" )
type SnapshotEntry ¶
type SnapshotEntry struct {
Key string
RuntimeName string
Selected bool
Managed bool
Required bool
RequiredReason string
State SkillState
Origin SkillOrigin
OriginLabel string
LocationLabel string
ReadOnly bool
SourcePath string
TargetPath string
Detail string
}
SnapshotEntry is one observed or desired skill status entry in a SkillSnapshot.
type StreamCapability ¶
type StreamCapability struct {
// Native reports whether the driver speaks a natively event-based
// protocol with the underlying CLI or service (as opposed to parsing
// free-form stdout).
Native bool
// TokenLevel reports whether text deltas arrive at character granularity
// or finer (i.e. multiple deltas per assistant message).
TokenLevel bool
// Reasoning reports whether reasoning / thinking deltas are exposed.
Reasoning bool
// ToolCallArgs reports whether tool-call argument streaming is exposed
// (StreamToolCallArgs events). When false, StreamToolCallStart carries a
// complete Args snapshot instead.
ToolCallArgs bool
// HITL reports whether human-in-the-loop approval / user-input events
// are exposed as typed events. The response path, when supported, still
// goes through DecisionCapableSink and the ApprovalRequest carried by the
// public Event.
HITL bool
}
StreamCapability describes what kinds of streaming fidelity a driver can deliver. Every field is additive: bridges should degrade gracefully when a capability is false (e.g. synthesize a single TOOL_CALL_START when ToolCallArgs is false).
type StreamKind ¶
type StreamKind string
StreamKind enumerates the protocol-agnostic streaming events drivers emit via EventSink.EmitStream when streaming is enabled. Bridges (bridges/*) translate these into host-facing protocols such as AG-UI without having to know the concrete driver.
The full list is the union of what codex / claude / cursor can expose. A StreamSupport driver may emit a subset of content kinds, but for every Request with Streaming=true it MUST emit exactly one run.started first and exactly one terminal run.finished or run.error last. All opened text, reasoning, tool and step lifecycles MUST close before that terminal. No payload may follow the terminal frame.
const ( // StreamRunStarted marks the beginning of a streamed run. StreamRunStarted StreamKind = "run.started" // StreamRunFinished marks normal completion of a streamed run. StreamRunFinished StreamKind = "run.finished" // StreamRunError marks terminal failure of a streamed run. StreamRunError StreamKind = "run.error" // StreamStepStarted marks a provider-defined work step beginning. StreamStepStarted StreamKind = "step.started" // StreamStepFinished marks a provider-defined work step ending. StreamStepFinished StreamKind = "step.finished" // StreamTextStart opens an assistant text message lifecycle. StreamTextStart StreamKind = "text.start" // StreamTextContent carries one assistant text delta. StreamTextContent StreamKind = "text.content" // StreamTextEnd closes an assistant text message lifecycle. StreamTextEnd StreamKind = "text.end" // StreamToolCallStart opens a tool-call lifecycle. StreamToolCallStart StreamKind = "tool_call.start" // StreamToolCallArgs carries streamed tool arguments or command output. StreamToolCallArgs StreamKind = "tool_call.args" // StreamToolCallEnd closes a tool-call lifecycle. StreamToolCallEnd StreamKind = "tool_call.end" // StreamToolCallResult carries a completed tool result. StreamToolCallResult StreamKind = "tool_call.result" // StreamReasoningStart opens a reasoning/thinking lifecycle. StreamReasoningStart StreamKind = "reasoning.start" // StreamReasoningContent carries one reasoning/thinking delta. StreamReasoningContent StreamKind = "reasoning.content" // StreamReasoningEnd closes a reasoning/thinking lifecycle. StreamReasoningEnd StreamKind = "reasoning.end" // StreamHITLRequested broadcasts a human-decision request. StreamHITLRequested StreamKind = "hitl.requested" // StreamHITLResolved broadcasts the final human-decision result. StreamHITLResolved StreamKind = "hitl.resolved" // StreamDropped reports StreamPayloads dropped because the host was slow. // Raw["dropped_count"] reports how many. StreamDropped StreamKind = "stream.dropped" )
type StreamPayload ¶
type StreamPayload struct {
Kind StreamKind
Sequence uint64
Seq uint64
RunID string
ThreadID string
TurnID string
MessageID string
ToolCallID string
Name string
Delta string
Args map[string]any
Result map[string]any
Usage *Usage
Error *RunFailure
Timestamp time.Time
// HITLRequested is populated when Kind == StreamHITLRequested.
HITLRequested *HITLRequestedPayload
// HITLResolved is populated when Kind == StreamHITLResolved.
HITLResolved *HITLResolvedPayload
// Role identifies the speaker for text.* kinds. Zero value =
// RoleAssistant; see Role docs. Drivers
// MUST leave Role at zero on every Kind they emit.
Role Role
// Raw carries provider-specific structured data that does not fit the
// normalized fields. Bridges may pass it through opaquely.
Raw map[string]any
}
StreamPayload is a single structured streaming event emitted by a stream-aware driver. It is intentionally a superset capable of carrying text deltas, tool-call lifecycles, reasoning, lifecycle markers, and opaque provider payloads.
Field usage by Kind:
- run.started / run.finished / run.error: RunID, ThreadID, Usage (on finished), Error (on error). MessageID / ToolCallID empty.
- step.started / step.finished: Name required.
- text.start / text.end: MessageID required. Role optional; zero value is treated as RoleAssistant. RoleUser MUST be paired with a non-empty MessageID that stays stable across the start/content/end triple of a single user turn.
- text.content: MessageID required; Delta non-empty. Role optional (see text.start).
- tool_call.start: ToolCallID and Name required; Args optional (complete initial snapshot when the driver does not stream args).
- tool_call.args: ToolCallID required; Delta non-empty (incremental argument chunk, usually JSON fragment).
- tool_call.end / tool_call.result: ToolCallID required; Result optional.
- reasoning.*: MessageID required; Delta for reasoning.content.
- hitl.requested / hitl.resolved: HITLRequested / HITLResolved carry the normalized decision envelope; Raw may carry driver-specific payload.
- stream.dropped: Raw["dropped_count"] reports the count.
Drivers MUST leave Sequence, Seq, and Timestamp at their zero values. Core assigns all three monotonically/in receiver order in EmitStream; they have one authority even when multiple driver goroutines emit concurrently.
Sequence and Seq are reserved SPI placeholders. Drivers MUST leave both zero; consumers use the single authoritative sequence in the root Event metadata, which core assigns in receiver order.
type StreamSupport ¶
type StreamSupport interface {
StreamCapability() StreamCapability
}
StreamSupport is the optional fidelity contract implemented by drivers that can produce normalized StreamPayload events. Core and bridges use it to understand provider-transport detail such as token-level deltas; it does not change the Runner execution contract.
In particular, StreamSupport MUST NOT be interpreted as an A2A transport capability. Every Runner has Stream; remote A2A streaming availability is negotiated from the remote AgentCard, not by querying a local Driver.
type StructuredOutput ¶
type StructuredOutput struct {
Format OutputFormat
Source StructuredOutputSource
RawJSON json.RawMessage
Value any
Valid bool
ValidationErrors []string
SchemaHash string
}
StructuredOutput is the portable final business value for structured-output runs. RawJSON is never raw stdout and never a provider terminal wrapper; it is the final assistant JSON value validated against the requested schema.
type StructuredOutputCapability ¶
type StructuredOutputCapability struct {
JSONSchemaNative bool
JSONSchemaPromptValidate bool
WorksWithRun bool
WorksWithStreaming bool
WorksWithHITL bool
Notes string
}
StructuredOutputCapability is a truthful matrix for structured-output resolution. JSONSchemaNative means the driver can pass a schema through an official provider/CLI surface and return the provider-produced value. JSONSchemaPromptValidate means the driver can accept core's explicit exact-JSON prompt while core performs local validation. At least one of those mechanisms MUST be true before any WorksWith* field is true, and a declared mechanism MUST set WorksWithRun because the SDK has one execution pipeline shared by consumer Run and Stream.
WorksWithStreaming applies only when Request.Streaming selects the provider-native streaming transport; it does not describe the consumer Stream method. WorksWithHITL applies when the effective policy contains an Ask decision. Core always selects native enforcement when that mechanism is eligible, otherwise prompt-validation when it is eligible, and rejects the invocation before launch when neither works. Drivers consume the resolved Request.StructuredOutputSource and must not renegotiate it. Every mechanism additionally requires WorksWithStreaming when Request.Streaming is true and WorksWithHITL when any effective decision mode is Ask.
type StructuredOutputInvalidPolicy ¶
type StructuredOutputInvalidPolicy string
StructuredOutputInvalidPolicy selects how prompt-validation failures are surfaced after the driver returns.
const ( // StructuredOutputFailRun marks the run with FailurePolicyError when the // final JSON is absent or fails local validation. StructuredOutputFailRun StructuredOutputInvalidPolicy = "fail_run" // StructuredOutputReturnInvalid returns StructuredOutput.Valid=false but // does not turn the run into a failure. StructuredOutputReturnInvalid StructuredOutputInvalidPolicy = "return_invalid" )
type StructuredOutputSource ¶
type StructuredOutputSource string
StructuredOutputSource reports which mechanism produced the final JSON.
const ( // StructuredOutputSourceNative means the provider enforced the schema. StructuredOutputSourceNative StructuredOutputSource = "native" // StructuredOutputSourcePromptValidate means core prompted for exact JSON // and validated the returned value locally. StructuredOutputSourcePromptValidate StructuredOutputSource = "prompt_validate" )
type StructuredOutputUnsupportedError ¶
StructuredOutputUnsupportedError carries diagnostic detail while unwrapping to ErrStructuredOutputUnsupported.
func (*StructuredOutputUnsupportedError) Error ¶
func (e *StructuredOutputUnsupportedError) Error() string
func (*StructuredOutputUnsupportedError) Unwrap ¶
func (e *StructuredOutputUnsupportedError) Unwrap() error
Unwrap exposes the stable error category for errors.Is.
type TerminalPayload ¶
type TerminalPayload struct {
Event string
JSON json.RawMessage
}
TerminalPayload preserves the provider's official terminal protocol event. JSON contains the exact JSON value recognized by the driver parser, before downstream normalization. Event is the provider-native event or method name (for example "result" or "turn/completed").
Drivers MUST populate this value only from an official terminal event. They must not synthesize it from Output, Summary, Transcript, or arbitrary JSON found elsewhere in stdout.
type TranscriptItem ¶
type TranscriptItem struct {
Kind TranscriptKind
Text string
Delta bool
ToolUseID string
ToolName string
Input any
IsError bool
Model string
SessionID string
Usage *Usage
CostUSD *float64
Subtype string
Errors []string
Metadata map[string]string
Data map[string]any
}
TranscriptItem is the host-facing normalized transcript unit.
Kind field rules:
- assistant / thinking / user: Text required. Delta allowed for assistant and thinking only.
- tool_call: ToolName required, ToolUseID recommended, Input optional.
- tool_result: ToolUseID required, Text recommended, IsError optional.
- init: Model and SessionID recommended.
- result: Text/Usage/CostUSD/Subtype/IsError/Errors optional.
- stdout/stderr/system: Text required (parser fallback).
- summary/question/failure: Text required; Data["choices"] for question, Metadata["code"] for failure.
Metadata carries short string tags; Data carries provider-specific structured extensions. A field already captured by a struct member must not be duplicated into Metadata or Data.
type TranscriptKind ¶
type TranscriptKind string
TranscriptKind identifies the semantic category of a transcript item.
const ( // TranscriptAssistant is assistant-facing text. TranscriptAssistant TranscriptKind = "assistant" // TranscriptThinking is reasoning/thinking text. TranscriptThinking TranscriptKind = "thinking" // TranscriptUser is user text captured from the provider transcript. TranscriptUser TranscriptKind = "user" // TranscriptToolCall is a normalized tool invocation. TranscriptToolCall TranscriptKind = "tool_call" // TranscriptToolResult is a normalized tool result. TranscriptToolResult TranscriptKind = "tool_result" // TranscriptInit records provider/model/session initialization metadata. TranscriptInit TranscriptKind = "init" // TranscriptResult records a terminal provider result event. TranscriptResult TranscriptKind = "result" // TranscriptStdout is parser fallback text from stdout. TranscriptStdout TranscriptKind = "stdout" // TranscriptStderr is parser fallback text from stderr. TranscriptStderr TranscriptKind = "stderr" // TranscriptSystem is driver/system text. TranscriptSystem TranscriptKind = "system" // TranscriptSummary is a short terminal summary item. TranscriptSummary TranscriptKind = "summary" // TranscriptQuestion is a provider follow-up question. TranscriptQuestion TranscriptKind = "question" // TranscriptFailure is a structured failure item. TranscriptFailure TranscriptKind = "failure" )
type Usage ¶
type Usage struct {
InputTokens int
OutputTokens int
CachedInputTokens int
EstimatedCostMilli int64
}
Usage is normalized token/cost accounting reported by drivers when the provider protocol exposes it. Individual values may legitimately be zero. A nil *Usage on Response, TranscriptItem, or a terminal event means usage was not observed; a non-nil zero Usage means the provider explicitly reported zero for every normalized metric.
type WorkspaceCapability ¶
type WorkspaceCapability struct {
Supported bool
}
WorkspaceCapability declares whether a driver can honor SDK-resolved workspace leases.
type WorkspaceLease ¶
type WorkspaceLease struct {
ID string
Mode WorkspaceMode
StrategyType WorkspaceStrategyType
CWD string
Fingerprint string
Metadata map[string]string
InstructionsID string
}
WorkspaceLease is the concrete working directory and metadata returned by a WorkspaceManager. Drivers should use CWD as the process working directory and treat Fingerprint as part of resume compatibility.
type WorkspaceMode ¶
type WorkspaceMode string
WorkspaceMode names the isolation/reuse semantics of a workspace lease.
const ( WorkspaceModeShared WorkspaceMode = "shared_workspace" // WorkspaceModeIsolated uses a run-scoped isolated workspace. WorkspaceModeIsolated WorkspaceMode = "isolated_workspace" // WorkspaceModeOperator uses an operator-owned branch/workspace. WorkspaceModeOperator WorkspaceMode = "operator_branch" // WorkspaceModeReuse asks the manager to reuse an existing workspace. WorkspaceModeReuse WorkspaceMode = "reuse_existing" // WorkspaceModeAgentDefault lets the driver choose its default workspace. WorkspaceModeAgentDefault WorkspaceMode = "agent_default" )
type WorkspaceRuntimeConfig ¶
type WorkspaceRuntimeConfig struct {
Services []RuntimeServiceSpec
}
WorkspaceRuntimeConfig declares runtime services associated with a Driver's default workspace configuration.
type WorkspaceStrategy ¶
type WorkspaceStrategy struct {
Type WorkspaceStrategyType
BaseRef string
BranchTemplate string
WorktreeParentDir string
}
WorkspaceStrategy describes the default workspace provisioning intent carried by a built-in Driver configuration. Call-scoped workspace options may replace it while resolving an invocation.
type WorkspaceStrategyType ¶
type WorkspaceStrategyType string
WorkspaceStrategyType names the host/workspace provisioning strategy.
const ( // WorkspaceStrategyProjectPrimary uses the existing project directory. WorkspaceStrategyProjectPrimary WorkspaceStrategyType = "project_primary" // WorkspaceStrategyGitWorktree provisions a separate git worktree. WorkspaceStrategyGitWorktree WorkspaceStrategyType = "git_worktree" // WorkspaceStrategyDriverManaged delegates workspace selection to the Driver. WorkspaceStrategyDriverManaged WorkspaceStrategyType = "driver_managed" // WorkspaceStrategyCloudSandbox represents an externally managed sandbox. WorkspaceStrategyCloudSandbox WorkspaceStrategyType = "cloud_sandbox" )