builtin

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2026 License: Apache-2.0 Imports: 36 Imported by: 0

Documentation

Overview

Package builtin is the generic ADK host for builtin-runtime agents: the gateway ships this one host compiled into agw/agwd, and a builtin agent is a persisted definition (agent.BuiltinRuntime) that the host materializes into an eino ADK object graph on demand. See docs/design/agents-control-plane.md §5.7.

Index

Constants

View Source
const (
	EventSession    = "session"
	EventDelta      = "delta"
	EventContent    = "content"
	EventToolCall   = "tool_call"
	EventUsage      = "usage"
	EventPermission = "permission"
	EventDone       = "done"
	EventError      = "error"
)

Turn event names.

View Source
const (
	StopReasonPermissionRequired = "permission_required"
	StopReasonCancelled          = "cancelled"
)

Done stop reasons beyond "end_turn".

Variables

View Source
var ErrAgentNotFound = errors.New("builtin agent not found")

ErrAgentNotFound is returned when the agent id does not resolve.

View Source
var ErrInvalidRequest = errors.New("invalid builtin turn request")

ErrInvalidRequest marks client-correctable turn failures (unknown agent runtime, disabled agent, empty input, depth exceeded). The dispatcher maps it to HTTP 400, mirroring the ACP error contract.

View Source
var ErrPermissionCapacity = errors.New("builtin agent pending permission capacity exceeded")

ErrPermissionCapacity is returned when permissions.max_pending is reached: the interrupting turn fails instead of storing another checkpoint (fail-closed, §5.7.7).

View Source
var ErrSessionBusy = errors.New("builtin session has a turn in flight")

ErrSessionBusy is returned when waiting for an in-flight turn on the same session is cancelled (client disconnect or turn timeout). Fail-closed and client-correctable: retry once the running turn finishes.

View Source
var ErrSessionLimitExceeded = errors.New("builtin agent session limit exceeded")

ErrSessionLimitExceeded is returned when an agent is at its session cap and no idle session can be evicted. Fail-closed: the new session is rejected, never queued.

View Source
var ErrTurnLimitExceeded = errors.New("builtin agent concurrent turn limit exceeded")

ErrTurnLimitExceeded is returned when limits.max_concurrent_turns is reached. Fail-closed: the turn is rejected, never queued.

Functions

func RegisterFactory

func RegisterFactory(name string, f Factory) error

RegisterFactory registers a compiled-in custom agent factory, mirroring provider.RegisterProviderFactory. It also records the name in pkg/agent's name registry so definition validation can reject unknown factories.

Types

type AgentSource

type AgentSource interface {
	Get(ctx context.Context, id string) (agent.Agent, error)
}

AgentSource resolves agent definitions; *agent.Manager satisfies it.

type CancelMode

type CancelMode string

CancelMode selects how an operator-requested cancel stops a running turn. It answers the "forced-cancel for stuck turns" question in docs/design/agents-control-plane.md §10 by adopting the ADK Runner cancel primitive (eino-reuse.md §5) for the builtin host.

const (
	// CancelModeForce aborts the turn immediately (adk.CancelImmediate): the
	// in-flight model or tool step is abandoned and the turn ends now. This is
	// the default and the answer for stuck turns.
	CancelModeForce CancelMode = "force"
	// CancelModeGraceful stops after the current model or tool step completes
	// (the adk safe-points CancelAfterChatModel|CancelAfterToolCalls),
	// propagating those safe-points through nested agents and escalating to
	// force if none is reached within cancelGracePeriod.
	CancelModeGraceful CancelMode = "graceful"
)

func ParseCancelMode

func ParseCancelMode(s string) (CancelMode, error)

ParseCancelMode normalizes an operator-supplied mode; empty defaults to force. An unknown mode is a client-correctable error.

type ChatModelResolver

type ChatModelResolver interface {
	ResolveChatModel(ctx context.Context, llmRouteID, model string, requireTools bool) (einomodel.ToolCallingChatModel, error)
}

ChatModelResolver resolves a gateway LLM route to an eino chat model. The gateway-side implementation wraps a RoutedProvider through the einomodel bridge, so credential scheduling, candidate fallback, and LLM usage recording apply unchanged. requireTools narrows logical-model candidates to tool-capable bindings so a node that carries tools never routes to a model that cannot call them.

type Config

type Config struct {
	Agents   AgentSource
	Models   ChatModelResolver
	Tools    einotool.ToolCaller
	Observer usage.InteractionObserver
}

Config wires the host's collaborator seams.

type ContinuationCursor

type ContinuationCursor struct {
	RunID        string
	NextSequence uint64
	NextSegment  uint32
}

ContinuationCursor is opaque common event-ordering state stored beside a pending Host checkpoint. The gateway adapter translates it to/from its runtime-neutral cursor without exposing ADK checkpoint data.

type EntryState

type EntryState struct {
	Materialized   bool      `json:"materialized"`
	MaterializedAt time.Time `json:"materialized_at,omitzero"`
	TopologyKind   string    `json:"topology_kind,omitempty"`
	InflightTurns  int       `json:"inflight_turns"`
	LiveSessions   int       `json:"live_sessions"`
}

EntryState is the workspace-facing materialization view of one agent.

type EventSink

type EventSink func(TurnEvent) error

EventSink receives turn events in emission order.

type Factory

type Factory func(ctx context.Context, deps FactoryDeps, def *agent.BuiltinRuntime) (adk.Agent, error)

Factory builds a custom ADK agent from a builtin definition. It is the escape hatch for agents that need custom Go logic (docs/design/agents-control-plane.md §5.7.3): implement the factory, register it, and blank-import the package in cmd/agw/main.go, cmd/agwd/main.go, and cmd/agwctl/cmd_gateway.go.

type FactoryDeps

type FactoryDeps struct {
	Models ChatModelResolver
	Tools  einotool.ToolCaller
}

FactoryDeps hands a custom factory the same gateway-governed building blocks the declarative materializer uses.

type Host

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

Host is the generic ADK host. One instance serves every builtin agent: definitions are materialized lazily and cached keyed by agent id + updated_at, so a definition update re-materializes on the next turn while in-flight turns drain on the old graph.

func NewHost

func NewHost(cfg Config) *Host

func (*Host) CancelRun

func (h *Host) CancelRun(agentID, runID string, mode CancelMode) (bool, error)

CancelRun targets the exact logical run id used by the common Agent API.

func (*Host) CancelTurn

func (h *Host) CancelTurn(agentID, sessionID string, mode CancelMode) (bool, error)

CancelTurn requests cancellation of the running turn for (agentID, sessionID) and reports whether one was in flight. force aborts immediately; graceful stops after the current model/tool step, escalating to force after a grace period. The cancelled turn's own SSE stream emits a done event with stop_reason "cancelled"; a discarded (uncommitted) partial exchange leaves the session history untouched.

func (*Host) ExpirePermission

func (h *Host) ExpirePermission(agentID, requestID string) bool

ExpirePermission discards one opaque suspended checkpoint fail-closed.

func (*Host) ListInFlight

func (h *Host) ListInFlight() []InFlightTurnView

ListInFlight reports the running turns for the Admin API.

func (*Host) LoadContinuationCursor

func (h *Host) LoadContinuationCursor(agentID, requestID string) (ContinuationCursor, bool)

LoadContinuationCursor reads, but does not consume, the cursor attached to a pending permission. The Host's one-shot checkpoint take owns deletion, so a request rejected before take may be corrected and retried.

func (*Host) Runtime

func (h *Host) Runtime() RuntimeView

Runtime reports the host-wide runtime view for the Admin API.

func (*Host) ServeTurn

func (h *Host) ServeTurn(ctx context.Context, agentID string, req TurnRequest, emit EventSink) error

ServeTurn runs one turn of a builtin agent and streams events to emit. Client-correctable failures wrap ErrInvalidRequest; concurrency rejection wraps ErrTurnLimitExceeded; unknown agents wrap ErrAgentNotFound.

func (*Host) State

func (h *Host) State(agentID string) EntryState

State reports the materialization/runtime state for the workspace view.

func (*Host) StoreContinuationCursor

func (h *Host) StoreContinuationCursor(agentID, requestID string, cursor ContinuationCursor) bool

StoreContinuationCursor attaches common event-ordering state to a pending permission checkpoint. It fails closed if the checkpoint identity no longer exists or belongs to another Agent/run.

type InFlightTurnView

type InFlightTurnView struct {
	AgentID      string    `json:"agent_id"`
	SessionID    string    `json:"session_id"`
	RunID        string    `json:"run_id"`
	RequestID    string    `json:"request_id,omitempty"`
	Operation    string    `json:"operation"`
	TopologyKind string    `json:"topology_kind,omitempty"`
	StartedAt    time.Time `json:"started_at"`
}

InFlightTurnView is the admin view of one running turn.

type PendingPermissionCall

type PendingPermissionCall struct {
	CallID       string `json:"call_id"`
	MCPServiceID string `json:"mcp_service_id"`
	ToolName     string `json:"name"`
	Arguments    string `json:"arguments,omitempty"`
}

PendingPermissionCall is the admin/SSE view of one gated tool call.

type PendingPermissionView

type PendingPermissionView struct {
	RequestID string                  `json:"request_id"`
	AgentID   string                  `json:"agent_id"`
	SessionID string                  `json:"session_id"`
	RunID     string                  `json:"run_id"`
	CreatedAt time.Time               `json:"created_at"`
	ExpiresAt time.Time               `json:"expires_at"`
	Calls     []PendingPermissionCall `json:"calls"`
}

PendingPermissionView is the admin runtime view of one suspended turn.

type RuntimeView

type RuntimeView struct {
	Agents             map[string]EntryState   `json:"agents"`
	PendingPermissions []PendingPermissionView `json:"pending_permissions"`
	InFlight           []InFlightTurnView      `json:"in_flight"`
}

RuntimeView is the /admin/builtin/runtime payload: per-agent materialization state plus the suspended interactive turns awaiting a decision.

type TurnEvent

type TurnEvent struct {
	Event      string          `json:"-"`
	SessionID  string          `json:"session_id,omitempty"`
	RunID      string          `json:"run_id,omitempty"`
	RequestID  string          `json:"request_id,omitempty"`
	Text       string          `json:"text,omitempty"`
	StopReason string          `json:"stop_reason,omitempty"`
	Message    string          `json:"message,omitempty"`
	Data       json.RawMessage `json:"data,omitempty"`
}

TurnEvent is one SSE event of a builtin turn. The vocabulary is a marked subset of the ACP turn vocabulary: session, delta, content, tool_call, usage, permission, done, error.

type TurnPermission

type TurnPermission struct {
	RequestID string                   `json:"request_id"`
	Outcome   string                   `json:"outcome,omitempty"`
	Decisions []TurnPermissionDecision `json:"decisions,omitempty"`
}

TurnPermission answers a pending tool-permission request. Outcome is empty to deliver per-call decisions, or "cancel" to discard the suspended turn. A pending call absent from Decisions is denied (fail-closed).

type TurnPermissionDecision

type TurnPermissionDecision struct {
	CallID  string `json:"call_id"`
	Outcome string `json:"outcome"`
}

TurnPermissionDecision resolves one gated tool call: outcome "allow" or "deny".

type TurnRequest

type TurnRequest struct {
	// RunID is allocated by the Agent execution boundary for a fresh run. A
	// permission resume preserves the pending checkpoint's logical run id.
	RunID      string          `json:"-"`
	SessionID  string          `json:"session_id,omitempty"`
	Input      string          `json:"input,omitempty"`
	Permission *TurnPermission `json:"permission,omitempty"`
}

TurnRequest is the data-plane turn input. Sessions are in-memory conversation histories keyed by session_id; state does not survive a gateway restart (documented PB1 semantics — durable checkpoints wait for eino v0.10). Exactly one of Input and Permission must be set: Input starts a turn, Permission resumes one suspended on a tool-permission interrupt (§5.7.7) and streams the continuation on this request's SSE response.

Jump to

Keyboard shortcuts

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