subagent

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Overview

Package subagent owns durable, read-only specialist executions for the Coding application. It deliberately does not expand the generic agent API.

Index

Constants

View Source
const (
	// AgentIdentitySchema identifies the durable, non-secret child identity
	// snapshot written by the Coding subagent protocol.
	AgentIdentitySchema = "pips.coding.subagent.identity/v1alpha1"
	// ExecutionPlanSchema identifies the immutable execution snapshot consumed
	// by Manager. A plan is compiled by Coding; a definition is never executed
	// directly by this package.
	ExecutionPlanSchema = "pips.coding.subagent.plan/v1alpha1"

	// MaxDelegationDepth is the product hard bound for recursive custom Agent
	// edges below a root child.
	MaxDelegationDepth = 3
)
View Source
const (
	// SpawnToolName is the stable asynchronous delegation protocol name.
	SpawnToolName = "spawn_agent"
	// SpawnResultSchema identifies the immediate admission result.
	SpawnResultSchema = "pips.coding.agent.spawn/v1alpha1"
)
View Source
const (
	// ToolName is the stable main-agent delegation protocol name.
	ToolName = "run_subagent"
	// ResultSchema identifies the bounded Tool result envelope.
	ResultSchema = "pips.coding.subagent.result/v1alpha1"
)

Variables

View Source
var (
	// ErrInvalid means configuration, request, or durable data is invalid.
	ErrInvalid = errors.New("coding subagent: invalid input")
	// ErrBusy preserves the single-slot compatibility error when a manager is
	// configured with MaxConcurrent equal to one.
	ErrBusy = errors.New("coding subagent: busy")
	// ErrCapacity means the Runtime's concurrent child limit is exhausted.
	ErrCapacity = errors.New("coding subagent: capacity exhausted")
	// ErrSpawnLimit means one root interaction exhausted its child budget.
	ErrSpawnLimit = errors.New("coding subagent: spawn limit exhausted")
	// ErrClosed means the manager no longer accepts executions.
	ErrClosed = errors.New("coding subagent: closed")
	// ErrInvalidResult means a specialist returned malformed or unsafe output.
	ErrInvalidResult = errors.New("coding subagent: invalid result")
)

Functions

func InstructionsDigest

func InstructionsDigest(value string) string

InstructionsDigest returns the durable digest used to prove a compiled execution plan still carries its exact rendered instruction text.

func Reconcile

func Reconcile(ctx context.Context, repository *session.Repository, parent *session.Handle) error

Reconcile repairs the current parent's bounded descendant tree from authoritative child Sessions, deepest first, and converts incomplete executions to interrupted.

func ValidateExecutionPlan

func ValidateExecutionPlan(plan ExecutionPlan) error

ValidateExecutionPlan validates a non-legacy plan at the Coding composition boundary. Legacy snapshots remain readable through journal inspection but cannot be dispatched through this API.

func ValidateIdentity

func ValidateIdentity(identity AgentIdentity) error

ValidateIdentity validates the bounded, non-secret identity contract.

Types

type Activity

type Activity struct {
	Revision  uint64
	Phase     ActivityPhase
	StartedAt time.Time
	UpdatedAt time.Time
	RunID     string
	Turn      int
	Tools     []ToolActivity
}

Activity is an immutable point-in-time view of an active child execution. It is presentation state and is not persisted in the parent lifecycle.

type ActivityAction

type ActivityAction string

ActivityAction is one sanitized semantic action suitable for parent UI projection. It deliberately excludes raw Tool arguments and results.

const (
	// ActivityActionRead means the child is reading a workspace file.
	ActivityActionRead ActivityAction = "read"
	// ActivityActionSearch means the child is searching workspace text.
	ActivityActionSearch ActivityAction = "search"
	// ActivityActionGlob means the child is matching workspace paths.
	ActivityActionGlob ActivityAction = "glob"
	// ActivityActionList means the child is listing a workspace directory.
	ActivityActionList ActivityAction = "list"
)

type ActivityPhase

type ActivityPhase string

ActivityPhase describes the currently observable child execution phase.

const (
	// ActivityPhaseUnknown means live phase data is unavailable.
	ActivityPhaseUnknown ActivityPhase = ""
	// ActivityPhaseStarting means the child run is being initialized.
	ActivityPhaseStarting ActivityPhase = "starting"
	// ActivityPhaseThinking means the child is between observable Tool calls.
	ActivityPhaseThinking ActivityPhase = "thinking"
	// ActivityPhaseWorking means the child is executing an observable Tool.
	ActivityPhaseWorking ActivityPhase = "working"
	// ActivityPhaseFinalizing means the child is validating its final result.
	ActivityPhaseFinalizing ActivityPhase = "finalizing"
)

type ActivitySummary

type ActivitySummary struct {
	Action ActivityAction `json:"action"`
	Target string         `json:"target"`
}

ActivitySummary is a bounded, content-safe description of the child's latest observable action. Target is a workspace-relative path or pattern.

type AdmissionEvent

type AdmissionEvent struct {
	Outcome         AdmissionOutcome
	Reason          AdmissionReason
	Delivery        Delivery
	DelegationDepth int
}

AdmissionEvent is one content-free shared-budget decision. It deliberately excludes Agent, Session, run, Tool-call, task, and root-interaction identity.

type AdmissionObserver

type AdmissionObserver func(context.Context, AdmissionEvent)

AdmissionObserver receives a synchronous, non-authoritative budget signal. Manager isolates observer panics and never lets observation change admission.

type AdmissionOutcome

type AdmissionOutcome string

AdmissionOutcome is the bounded result of one shared-budget reservation.

const (
	// AdmissionOutcomeAccepted means the request reserved an active slot.
	AdmissionOutcomeAccepted AdmissionOutcome = "accepted"
	// AdmissionOutcomeRejected means the shared budget refused the request.
	AdmissionOutcomeRejected AdmissionOutcome = "rejected"
)

type AdmissionReason

type AdmissionReason string

AdmissionReason is a low-cardinality rejection classification.

const (
	// AdmissionReasonBusy preserves the single-slot compatibility reason.
	AdmissionReasonBusy AdmissionReason = "busy"
	// AdmissionReasonCapacity means the active tree limit was exhausted.
	AdmissionReasonCapacity AdmissionReason = "capacity"
	// AdmissionReasonSpawnLimit means the root cumulative limit was exhausted.
	AdmissionReasonSpawnLimit AdmissionReason = "spawn_limit"
	// AdmissionReasonClosed means the Manager no longer accepts work.
	AdmissionReasonClosed AdmissionReason = "closed"
	// AdmissionReasonInvalid means the reservation input was malformed.
	AdmissionReasonInvalid AdmissionReason = "invalid"
)

type AgentEvent

type AgentEvent struct {
	ChildSessionID string
	Ownership      Ownership
	Task           string
	Event          agent.Event
}

AgentEvent associates one raw child Agent event with its stable child Session and immutable ownership.

type AgentEventObserver

type AgentEventObserver func(context.Context, AgentEvent) error

AgentEventObserver receives raw child events for ordinary Session-state projection. Returning an error cancels that child execution.

type AgentIdentity

type AgentIdentity struct {
	Schema           string    `json:"schema"`
	ID               string    `json:"id"`
	Kind             AgentKind `json:"kind"`
	Name             string    `json:"name"`
	DefinitionSchema string    `json:"definition_schema"`
	DefinitionDigest string    `json:"definition_digest"`
	DefinitionSource string    `json:"definition_source"`
}

AgentIdentity is the stable, non-secret identity of an execution. ID is canonical and must never be reconstructed from Name. Definition fields are a snapshot, so inspecting an old child does not depend on its source file still existing.

func BuiltinIdentity

func BuiltinIdentity(role Role) (AgentIdentity, error)

BuiltinIdentity returns the registry-equivalent identity for one legacy specialist role.

func IdentityFromDefinition

func IdentityFromDefinition(definition agentprofile.Definition) (AgentIdentity, error)

IdentityFromDefinition converts one validated registry definition into the durable identity used by a compiled execution plan.

func (AgentIdentity) IsZero

func (i AgentIdentity) IsZero() bool

IsZero reports whether no identity was supplied. It exists only for legacy journal and event decoding; new execution admission never accepts it.

func (AgentIdentity) LegacyRole

func (i AgentIdentity) LegacyRole() Role

LegacyRole returns the builtin role projection for this identity. Custom and ephemeral identities intentionally have no synthetic role.

type AgentKind

type AgentKind string

AgentKind identifies the durable source class of one child agent.

const (
	// AgentKindBuiltin identifies a program-owned compatibility agent.
	AgentKindBuiltin AgentKind = "builtin"
	// AgentKindCustom identifies a loaded user or trusted-project definition.
	AgentKindCustom AgentKind = "custom"
	// AgentKindEphemeral identifies an explicit, non-persisted one-shot
	// definition.
	AgentKindEphemeral AgentKind = "ephemeral"
)

type Config

type Config struct {
	Context    context.Context
	Repository *session.Repository
	Parent     *session.Handle
	Tree       *workspace.Tree
	Model      ai.LanguageModel
	// GenerationID identifies the immutable Coding integration snapshot that
	// compiled this manager's builtin execution plan. Custom dispatch will
	// acquire a per-child generation lease in the next slice.
	GenerationID   uint64
	SummaryModel   ai.LanguageModel
	Compaction     *harness.CompactionSettings
	RequestPolicy  func(*ai.Request)
	Lifecycle      Lifecycle
	Options        ExecutionOptions
	AgentObservers []func(context.Context, agent.Event)
	EventObservers []AgentEventObserver
	// AdmissionObserver receives content-free shared-budget decisions. It is
	// observational only and cannot veto or alter a reservation.
	AdmissionObserver AdmissionObserver
	// Share joins this Manager to an existing root execution tree. It is
	// required when Parent is a subagent Session.
	Share *Manager
	// DelegationDepth is the depth expected for children created by this
	// manager. Root conversation Managers use zero.
	DelegationDepth int
}

Config contains the application-owned dependencies for one parent Session.

type Delivery

type Delivery string

Delivery selects whether the parent Tool waits for the child or returns immediately while the Runtime retains execution ownership.

const (
	// DeliveryForeground is the existing run_subagent behavior.
	DeliveryForeground Delivery = "foreground"
	// DeliveryBackground is used by spawn_agent.
	DeliveryBackground Delivery = "background"
)

type Detail

type Detail struct {
	Summary    Summary
	Plan       ExecutionPlan
	Transcript []ai.Message
	Activity   Activity
	Result     any
}

Detail extends Summary with durable replay data and optional live activity.

type DispatchInput

type DispatchInput struct {
	Plan     ExecutionPlan
	Request  Request
	Child    *session.Handle
	Observer Observer
	OnEvent  func(context.Context, agent.Event)
}

DispatchInput is the bounded, application-owned input for a child runtime binding. The Session belongs solely to this child execution.

type Dispatcher

type Dispatcher interface {
	// AgentIDs returns the bounded model-visible custom IDs captured for this
	// Tool declaration. It is advisory schema metadata only; Compile remains
	// the authorization boundary.
	AgentIDs() []string
	// Compile validates the request against the caller-visible immutable
	// registry and returns a complete, non-legacy execution plan.
	Compile(context.Context, Request) (ExecutionPlan, error)
	// Open creates the child-owned runtime binding after the durable child
	// Session exists. It must not retain a parent-bound controller, Tool, or
	// interaction context.
	Open(context.Context, DispatchInput) (Runner, error)
}

Dispatcher compiles and opens a non-builtin child execution. It is supplied by the Coding composition root for one parent interaction, never by a profile file or a generic caller. Compile must only narrow the ambient capability snapshot captured for that interaction.

Builtin compatibility agents intentionally bypass Dispatcher and retain their existing typed execution path.

type EffectiveCapability

type EffectiveCapability struct {
	WireName string `json:"wire_name"`
	Source   string `json:"source"`
	Risk     string `json:"risk"`
}

EffectiveCapability is one exact, runtime-owned Tool descriptor frozen into an execution plan. It is descriptive only; invoking the capability still requires a child-scoped factory and every normal execution-time policy gate.

type Event

type Event struct {
	Progress            bool
	State               State
	Identity            AgentIdentity
	Role                Role
	ChildSessionID      string
	ParentSessionID     string
	ParentInteractionID string
	ParentRunID         string
	ParentToolCallID    string
	RootInteractionID   string
	Delivery            Delivery
	ChildRunID          string
	Model               string
	TaskPreview         string
	Activity            ActivitySummary
	Code                string
	Stop                agent.StopReason
	Turns               int
	ToolCalls           int
	Usage               ai.Usage
	Duration            time.Duration
	Time                time.Time
	// Result is present only on an in-process terminal callback. It is never
	// copied into the parent lifecycle event or telemetry projection.
	Result *Result
}

Event is one content-bounded child lifecycle update.

type Evidence

type Evidence struct {
	Path      string `json:"path"`
	StartLine int    `json:"start_line"`
	EndLine   int    `json:"end_line"`
	Claim     string `json:"claim"`
}

Evidence ties one Explore claim to an observed workspace range.

type Execution

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

Execution is one cancelable, waitable child lifetime. It intentionally does not retain a context.Context.

func (*Execution) Cancel

func (e *Execution) Cancel()

Cancel requests child cancellation. It is safe to call repeatedly.

func (*Execution) Wait

func (e *Execution) Wait(ctx context.Context) (Result, error)

Wait waits for terminal persistence or for only this wait context to end.

type ExecutionOptions

type ExecutionOptions struct {
	Limits                       Limits
	MaxDepth                     int
	MaxConcurrent                int
	MaxSpawnedPerRootInteraction int
	MaxAutoFollowUps             int
}

ExecutionOptions provides embedder/test overrides without adding a user configuration protocol in P1. A zero Limits value selects DefaultLimits.

type ExecutionPlan

type ExecutionPlan struct {
	Schema             string                `json:"schema"`
	Identity           AgentIdentity         `json:"identity"`
	GenerationID       uint64                `json:"generation_id,omitempty"`
	Delivery           Delivery              `json:"delivery"`
	Model              string                `json:"model"`
	Instructions       string                `json:"instructions"`
	InstructionsDigest string                `json:"instructions_digest"`
	Capabilities       []EffectiveCapability `json:"capabilities"`
	Skills             []string              `json:"skills"`
	PreloadedSkills    []string              `json:"preloaded_skills"`
	ToolSearch         bool                  `json:"tool_search,omitempty"`
	DelegationDepth    int                   `json:"delegation_depth,omitempty"`
	MaxDelegationDepth int                   `json:"max_delegation_depth,omitempty"`
	Ancestry           []string              `json:"ancestry,omitempty"`
	DelegationTargets  []string              `json:"delegation_targets,omitempty"`
	PrivateMCP         []PrivateBinding      `json:"private_mcp,omitempty"`
	PrivateHooks       []PrivateBinding      `json:"private_hooks,omitempty"`
	Limits             Limits                `json:"limits"`
	Output             OutputContract        `json:"output"`
	// Legacy records did not carry an execution snapshot. It is set only while
	// normalizing those durable records for read-only inspection; dispatch must
	// never admit a legacy plan.
	Legacy bool `json:"legacy,omitempty"`
}

ExecutionPlan is the immutable, auditable input accepted by subagent execution. It records the authority intersection computed by Coding, not merely the agent definition's requested capabilities.

func (ExecutionPlan) Clone

func (p ExecutionPlan) Clone() ExecutionPlan

Clone returns a detached execution-plan snapshot.

func (ExecutionPlan) Digest

func (p ExecutionPlan) Digest() (string, error)

Digest returns the SHA-256 digest of the canonical JSON plan payload.

type ExploreResult

type ExploreResult struct {
	Summary  string     `json:"summary"`
	Evidence []Evidence `json:"evidence"`
	Unknowns []string   `json:"unknowns"`
}

ExploreResult is the structured output of the Explore specialist.

type Lifecycle

type Lifecycle struct {
	BeforeStart func(context.Context, LifecycleStart) string
	BeforeStop  func(context.Context, LifecycleStop) LifecycleStopDecision
}

Lifecycle provides Runtime-owned child lifecycle callbacks. Manager only transports bounded context and continuation requests; it neither discovers nor executes user hook configuration.

type LifecycleStart

type LifecycleStart struct {
	ChildSessionID string
	Identity       AgentIdentity
	Role           Role
	Task           string
	Ownership      Ownership
}

LifecycleStart describes a child after its durable session exists and before its harness begins its first run.

type LifecycleStop

type LifecycleStop struct {
	ChildSessionID       string
	Identity             AgentIdentity
	Role                 Role
	Ownership            Ownership
	StopHookActive       bool
	LastAssistantMessage string
}

LifecycleStop describes one clean child-agent stop before Manager commits its terminal child record.

type LifecycleStopDecision

type LifecycleStopDecision struct {
	Continue bool
	Reason   string
}

LifecycleStopDecision asks Manager to issue one follow-up prompt to the already-open child harness. A false Continue leaves the child terminal.

type Limits

type Limits struct {
	MaxTurns              int
	FinalizationTurns     int
	RepeatedToolCallLimit int
	MaxTokens             int
	MaxToolCalls          int
	MaxDuration           time.Duration
	MaxActivityTools      int
	MaxOutputTokens       int
	MaxTaskBytes          int
	MaxResultBytes        int
	MaxResultItems        int
	MaxFieldBytes         int
}

Limits bounds one child execution and its persisted projections.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns the legacy embedder policy. Total turns, cumulative tokens, tool calls, and wall time are unlimited; payloads and live projections remain bounded independently.

func NormalizeLimits

func NormalizeLimits(limits Limits) Limits

NormalizeLimits applies the stable inherited defaults used by a compiled execution plan. It returns a value copy and grants no additional authority.

func ProductionLimits

func ProductionLimits() Limits

ProductionLimits returns the bounded policy selected by a zero-value Coding Runtime configuration. Embedders that explicitly need unlimited execution can continue to pass DefaultLimits, whose payload fields make it non-zero.

type Manager

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

Manager owns a bounded set of live child executions and all of their cleanup. Each admitted child runs until natural completion, cancellation, an explicit positive execution limit, or a structural safety policy stops it.

func New

func New(config Config) (*Manager, error)

New constructs a current-parent child manager. Call Reconcile before New so interrupted child journals are repaired before the manager accepts work.

func (*Manager) Cancel

func (m *Manager) Cancel(ctx context.Context, childSessionID string) error

Cancel cancels one running child. Repeating cancellation, including after the child is terminal, is safe.

func (*Manager) CancelRoot

func (m *Manager) CancelRoot(rootInteractionID string) int

CancelRoot cancels every running background child created by one root interaction and returns the number of cancellation requests issued.

func (*Manager) Close

func (m *Manager) Close(ctx context.Context) error

Close stops admission, cancels every child, and waits for terminal persistence before returning.

func (*Manager) Inspect

func (m *Manager) Inspect(
	ctx context.Context,
	childSessionID string,
) (Detail, error)

Inspect loads one current-parent child transcript and validated structured result. Arbitrary session IDs outside the current parent are rejected.

func (*Manager) List

func (m *Manager) List(ctx context.Context) ([]Summary, error)

List returns newest-first durable descendants owned by this manager's execution tree.

func (*Manager) MaxAutoFollowUps

func (m *Manager) MaxAutoFollowUps() int

MaxAutoFollowUps returns the validated Runtime coordination bound.

func (*Manager) SpawnToolFor

func (m *Manager) SpawnToolFor(owner Ownership, observer Observer) agent.Tool

SpawnToolFor returns a concurrency-safe asynchronous child Tool bound to one parent interaction. Completion is delivered by the Runtime rather than through model polling.

func (*Manager) SpawnToolForDispatcher

func (m *Manager) SpawnToolForDispatcher(
	owner Ownership,
	observer Observer,
	dispatcher Dispatcher,
) agent.Tool

SpawnToolForDispatcher is the asynchronous adapter for an interaction-scoped custom dispatcher.

func (*Manager) Start

func (m *Manager) Start(
	ctx context.Context,
	request Request,
	observer Observer,
) (*Execution, error)

Start reserves one execution slot and starts one owned goroutine.

func (*Manager) StartWithDispatcher

func (m *Manager) StartWithDispatcher(
	ctx context.Context,
	request Request,
	observer Observer,
	dispatcher Dispatcher,
) (*Execution, error)

StartWithDispatcher admits either a builtin compatibility request or a Runtime-compiled custom execution. Dispatcher is interaction-scoped: it owns registry visibility and the child-specific control binding, while this Manager retains quotas, durable lineage, lifecycle, and terminal cleanup.

func (*Manager) Tool

func (m *Manager) Tool(observer Observer) agent.Tool

Tool returns the serial main-agent adapter for this manager.

func (*Manager) ToolFor

func (m *Manager) ToolFor(owner Ownership, observer Observer) agent.Tool

ToolFor returns the run_subagent adapter bound to one parent interaction.

func (*Manager) ToolForDispatcher

func (m *Manager) ToolForDispatcher(
	owner Ownership,
	observer Observer,
	dispatcher Dispatcher,
) agent.Tool

ToolForDispatcher returns the parent adapter with one interaction-scoped custom dispatcher. The dispatcher controls compilation; schema enum values are advisory and deliberately bounded.

func (*Manager) ToolForTargets

func (m *Manager) ToolForTargets(
	owner Ownership,
	observer Observer,
	dispatcher Dispatcher,
	targets []string,
) agent.Tool

ToolForTargets returns the recursive foreground adapter for one exact custom Agent allowlist. It deliberately has no builtin role compatibility path.

func (*Manager) Wait

func (m *Manager) Wait(ctx context.Context, childSessionID string) (Result, error)

Wait waits for one owned child to become terminal. A child that already completed is reconstructed from its durable journal.

type Notification

type Notification struct {
	ID          string        `json:"id"`
	AgentID     string        `json:"agent_id"`
	Ownership   Ownership     `json:"ownership"`
	Identity    AgentIdentity `json:"identity,omitzero"`
	Role        Role          `json:"role"`
	Outcome     Outcome       `json:"outcome"`
	Code        string        `json:"code"`
	TaskPreview string        `json:"task_preview,omitempty"`
	Result      ai.JSON       `json:"result,omitempty"`
	Usage       ai.Usage      `json:"usage"`
	TerminalAt  time.Time     `json:"terminal_at"`
}

Notification is one bounded background-child completion waiting to be injected into its owning parent conversation.

type NotificationInbox

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

NotificationInbox persists completion delivery state in the parent Harness Session. It is safe for concurrent terminal callbacks and Runtime coordination.

func NewNotificationInbox

func NewNotificationInbox(
	parent *harness.Session,
	parentSessionID string,
	maxResultBytes int,
) (*NotificationInbox, error)

NewNotificationInbox constructs a parent-owned durable completion inbox.

func (*NotificationInbox) Acknowledge

func (i *NotificationInbox) Acknowledge(ids ...string) error

Acknowledge marks known pending notifications delivered. It is idempotent.

func (*NotificationInbox) Contains

func (i *NotificationInbox) Contains(id string) (bool, error)

Contains reports whether a pending or delivered notification already exists for the child ID.

func (*NotificationInbox) Enqueue

func (i *NotificationInbox) Enqueue(value Notification) error

Enqueue appends a pending record unless the exact completion is already known. A delivered notification remains delivered.

func (*NotificationInbox) EnqueueCompletion

func (i *NotificationInbox) EnqueueCompletion(event Event) error

EnqueueCompletion durably records one background terminal result. Repeated callbacks for the same child are idempotent only when the payload matches.

func (*NotificationInbox) EnqueueRecovered

func (i *NotificationInbox) EnqueueRecovered(summary Summary, result any) error

EnqueueRecovered repairs the crash window between a durable child terminal record and creation of its parent completion notification.

func (*NotificationInbox) Pending

func (i *NotificationInbox) Pending() ([]Notification, error)

Pending returns terminal-time ordered undelivered notifications.

type Observer

type Observer func(context.Context, Event) error

Observer synchronously receives child lifecycle events. Implementations must return quickly, must not retain mutable input references, and return an error when the parent event stream can no longer accept the lifecycle.

type Outcome

type Outcome string

Outcome is the durable terminal classification of an execution.

const (
	// OutcomeSucceeded means a validated result was committed.
	OutcomeSucceeded Outcome = "succeeded"
	// OutcomeFailed means execution ended without a usable result.
	OutcomeFailed Outcome = "failed"
	// OutcomeCanceled means cancellation or a deadline stopped execution.
	OutcomeCanceled Outcome = "canceled"
	// OutcomeInterrupted means restart reconciliation found no terminal record.
	OutcomeInterrupted Outcome = "interrupted"
)

type OutputContract

type OutputContract struct {
	Format OutputFormat    `json:"format"`
	Name   string          `json:"name"`
	Schema json.RawMessage `json:"schema,omitempty"`
	Digest string          `json:"digest"`
}

OutputContract is a frozen output-validation contract. Schema is canonical JSON for JSON Schema and builtin adapters, and is copied on every boundary.

func NewOutputContract

func NewOutputContract(
	format OutputFormat,
	name string,
	schema json.RawMessage,
) (OutputContract, error)

NewOutputContract freezes one custom output contract and computes its durable digest. Schema is copied so callers cannot mutate a compiled plan through a retained YAML/JSON slice.

func (OutputContract) Clone

func (c OutputContract) Clone() OutputContract

Clone returns a detached output contract.

type OutputFormat

type OutputFormat string

OutputFormat identifies the local final-result contract selected by a compiled plan.

const (
	// OutputFormatBuiltin delegates validation to one of the existing typed
	// builtin result adapters.
	OutputFormatBuiltin OutputFormat = "builtin"
	// OutputFormatText accepts a bounded UTF-8 text final answer.
	OutputFormatText OutputFormat = "text"
	// OutputFormatJSONSchema requires a locally validated JSON Schema result.
	OutputFormatJSONSchema OutputFormat = "json_schema"
)

type OutputValidator

type OutputValidator interface {
	Validate(string) (any, error)
}

OutputValidator validates one final custom-Agent response against the immutable contract captured in its execution plan.

func NewOutputValidator

func NewOutputValidator(contract OutputContract, limits Limits) (_ OutputValidator, returnErr error)

NewOutputValidator compiles a local output validator. JSON Schema resolution receives no external loader, so a profile can never make result validation fetch an external reference.

type Ownership

type Ownership struct {
	ParentSessionID     string
	ParentInteractionID string
	ParentRunID         string
	ParentToolCallID    string
	RootInteractionID   string
}

Ownership is the immutable parent location of one child execution.

type PlanResult

type PlanResult struct {
	Summary      string     `json:"summary"`
	Assumptions  []string   `json:"assumptions"`
	Steps        []PlanStep `json:"steps"`
	Risks        []string   `json:"risks"`
	Verification []string   `json:"verification"`
}

PlanResult is the structured output of the Plan specialist.

type PlanStep

type PlanStep struct {
	Title     string   `json:"title"`
	Files     []string `json:"files"`
	Rationale string   `json:"rationale"`
}

PlanStep is one implementation step in a Plan result.

type PrivateBinding

type PrivateBinding struct {
	ID          string `json:"id"`
	Fingerprint string `json:"fingerprint"`
}

PrivateBinding freezes one Agent-private executable resource selected from the immutable Coding integration generation.

type Request

type Request struct {
	AgentID   string
	Role      Role
	Task      string
	Ownership Ownership
	Delivery  Delivery
}

Request is the compatibility admission shape for one builtin specialist delegation. AgentID is the primary selector; Role remains a temporary wire alias for explore, plan, and review. Custom definitions are admitted only through a Runtime-compiled ExecutionPlan.

type Result

type Result struct {
	Identity       AgentIdentity
	Role           Role
	ChildSessionID string
	ChildRunID     string
	Outcome        Outcome
	Code           string
	Stop           agent.StopReason
	Turns          int
	ToolCalls      int
	Usage          ai.Usage
	Duration       time.Duration
	Value          any
}

Result is the terminal execution result returned to the parent Tool.

type ReviewFinding

type ReviewFinding struct {
	Severity       string `json:"severity"`
	Title          string `json:"title"`
	Path           string `json:"path"`
	Line           int    `json:"line"`
	Evidence       string `json:"evidence"`
	Recommendation string `json:"recommendation"`
}

ReviewFinding is one evidence-backed Review issue.

type ReviewResult

type ReviewResult struct {
	Summary       string          `json:"summary"`
	Findings      []ReviewFinding `json:"findings"`
	ResidualRisks []string        `json:"residual_risks"`
}

ReviewResult is the structured output of the Review specialist.

type Role

type Role string

Role selects one isolated read-only specialist behavior and output schema.

const (
	// RoleExplore gathers evidence from the workspace.
	RoleExplore Role = "explore"
	// RolePlan produces an evidence-backed implementation plan.
	RolePlan Role = "plan"
	// RoleReview reports evidence-backed defects and risks.
	RoleReview Role = "review"
)

type Runner

type Runner interface {
	Run(context.Context, string) (RunnerResult, error)
	// Close releases the child control scope after Manager durably persists its
	// terminal record. It must be idempotent and safe after a failed Run.
	Close(context.Context) error
}

Runner owns the child-specific execution/control scope for one compiled custom plan. Run returns only after terminal output validation; a paused approval or question remains internal to the runner until its child-owned resolver is resumed by Coding.

type RunnerResult

type RunnerResult struct {
	Run       *agent.RunResult
	Value     any
	Text      string
	ToolCalls int
}

RunnerResult is the validated terminal output returned by a child-owned Runner. Run is retained for standard stop/usage accounting; Value and Text have already passed the exact frozen output contract.

type State

type State string

State is the durable lifecycle state of an execution.

const (
	// StateCreated means durable child ownership has been established.
	StateCreated State = "created"
	// StateRunning means the child Agent run has started.
	StateRunning State = "running"
	// StateSucceeded means the child returned a validated result.
	StateSucceeded State = "succeeded"
	// StateFailed means the child ended without a usable result.
	StateFailed State = "failed"
	// StateCanceled means cancellation or a deadline stopped the child.
	StateCanceled State = "canceled"
	// StateInterrupted means reconciliation closed an orphan execution.
	StateInterrupted State = "interrupted"
)

type Summary

type Summary struct {
	ChildSessionID string
	Ownership      Ownership
	Delivery       Delivery
	Identity       AgentIdentity
	Role           Role
	State          State
	TaskPreview    string
	Model          string
	CreatedAt      time.Time
	Duration       time.Duration
	Turns          int
	ToolCalls      int
	Usage          ai.Usage
	Code           string
}

Summary is the durable current-parent list projection.

type ToolActivity

type ToolActivity struct {
	RunID  string
	Turn   int
	Call   ai.ToolCallPart
	Status ToolStatus
	Update []ai.Part
	Result ai.ToolResultPart
}

ToolActivity is one ordered, bounded child Tool observation.

type ToolStatus

type ToolStatus string

ToolStatus is the observable lifecycle of one child Tool call.

const (
	// ToolStatusUnknown means Tool lifecycle data is unavailable.
	ToolStatusUnknown ToolStatus = ""
	// ToolStatusRunning means the Tool has started but has not completed.
	ToolStatusRunning ToolStatus = "running"
	// ToolStatusCompleted means the Tool has produced its terminal result.
	ToolStatusCompleted ToolStatus = "completed"
)

Jump to

Keyboard shortcuts

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