agent

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package agent defines the contract between the gateway and native coding agent CLIs.

Each adapter runs its CLI with the CLI's own native protocol. The gateway only sees the common Request / Event / Result model below; native events are always forwarded untouched in Event.Raw so no agent-specific feature is lost.

Index

Constants

View Source
const (
	ObservationTask     = "task"
	ObservationSubagent = "subagent"
	ObservationProcess  = "process"

	ObservationActive    = "active"
	ObservationCompleted = "completed"
	ObservationFailed    = "failed"
	ObservationCancelled = "cancelled"
)

Observation kinds and states.

View Source
const (
	PermissionCommand    = "command"
	PermissionFileChange = "file_change"
	PermissionMCP        = "mcp"
	PermissionOther      = "other"
)

Permission kinds: what the agent asks to do. Session and workspace rules match by kind.

View Source
const (
	// FlowPasteCode: open the URL; the page shows a code the user submits to the gateway.
	FlowPasteCode = "paste_code"
	// FlowDeviceCode: open the URL and enter the user code shown by the gateway.
	FlowDeviceCode = "device_code"
	// FlowBrowser: open the URL in a browser on the gateway host; nothing to submit.
	FlowBrowser = "browser"
)

Login flows: what the user does to finish a login.

View Source
const (
	SessionNew    = "new"
	SessionResume = "resume"
	// SessionFork starts SessionID as a copy of the ForkFrom session.
	SessionFork = "fork"
)

Session modes.

View Source
const (
	// PermissionsBypass lets the agent use every tool without asking.
	PermissionsBypass = "bypass"
	// PermissionsAsk sends permission_request events that the client must answer.
	PermissionsAsk = "ask"
)

Permission modes for workspace runs.

View Source
const (
	MaxPromptBytes       = 1_000_000
	MaxSystemPromptBytes = 256_000
	MaxOutputSchemaBytes = 64_000
)

Limits on request fields that apply to every agent.

View Source
const MaxAddDirs = 16

MaxAddDirs bounds add_dirs and similar directory lists.

View Source
const MaxLoginCode = 4096

MaxLoginCode bounds a code pasted from a sign-in page.

View Source
const ProfileNative = "native"

ProfileNative selects the native CLI's own default profile location under HOME.

Variables

View Source
var (
	ErrInvalidRequest = errors.New("invalid request")
	ErrLoginRequired  = errors.New("agent login is required")
	ErrLoginExpired   = errors.New("agent login expired; run the login command again")
	ErrForbidden      = errors.New("the agent login does not grant this operation")
	ErrUnsupported    = errors.New("operation is not supported by this agent")
	ErrUpstream       = errors.New("agent upstream request failed")
)

Errors shared by adapters. The HTTP layer maps them to status codes with errors.Is.

View Source
var (
	ErrInputClosed       = errors.New("conversation input is closed")
	ErrUnknownPermission = errors.New("permission request is not pending")
	ErrUnknownControl    = errors.New("control request is not pending")
	// ErrControlRejected wraps the agent's error answer to a control request.
	ErrControlRejected = errors.New("agent rejected the control request")
)

Errors returned by Conversation methods.

PermissionKinds lists every kind.

RequestSections are the sections clients send.

ResponseSections map response sections to their Go type.

View Source
var TokenFields = [4]string{"input", "output", "cache_read", "cache_creation"}

TokenFields are the JSON names of the Tokens fields, in Fields order.

Functions

func DecodeStrict

func DecodeStrict(raw json.RawMessage, field string, target any) error

DecodeStrict decodes an adapter's provider fields into target, rejecting unknown members. Empty input leaves target unchanged.

func EnumOf added in v0.2.0

func EnumOf[T any](field string) []string

EnumOf returns the values in the `enum` tag of field in struct T. Adapters validate a provider option with it, so the API document and the validation share one list.

func Invalid

func Invalid(format string, args ...any) error

Invalid returns an error wrapping ErrInvalidRequest.

func ResolveProfile

func ResolveProfile(profileDir, home, nativeName string) (dir string, custom bool, err error)

ResolveProfile validates an agent profile setting. It returns the effective profile directory and whether it is a custom location that must be passed to the CLI. A custom directory equal to the native default is rejected: some CLIs change behavior merely because the location is set explicitly (Claude's macOS Keychain entry name, for example).

func SplitProvider

func SplitProvider(raw json.RawMessage, field, served string) (json.RawMessage, error)

SplitProvider checks a request's provider section (field names it in errors) against the served agent and returns the agent's own fields without name. Empty input yields nil.

func ValidateMessage

func ValidateMessage(text string) error

ValidateMessage checks a prompt or follow-up message.

Types

type Account

type Account struct {
	Email string `json:"email,omitempty" doc:"Account e-mail."`
	Plan  string `json:"plan,omitempty"  doc:"Subscription plan as the agent names it, for display (e.g. pro); absent for API-key logins."`
}

Account is the logged-in account.

type Agent

type Agent interface {
	// Info describes the adapter.
	Info() Info
	// Name is Info().Name.
	Name() string
	// Validate applies agent-specific checks to an already normalized request.
	// Failures wrap ErrInvalidRequest.
	Validate(req *Request) error
	// Start launches the CLI, sends req.Prompt as the first message and returns the live
	// conversation. Events are passed to onEvent from a single goroutine, in order; returning
	// an error from onEvent aborts the conversation. Cancelling ctx kills the process.
	Start(ctx context.Context, req Request, onEvent EventFunc) (Conversation, error)
	// Version returns the CLI version string.
	Version(ctx context.Context) (string, error)
	// AuthStatus reports the native login state. Being logged out is a result, not an error.
	AuthStatus(ctx context.Context) (AuthStatus, error)
	// Interactive runs a CLI maintenance flow (login, status) on a terminal.
	Interactive(ctx context.Context, stdio IO, command InteractiveCommand) error
}

Agent is a native coding agent CLI.

type AuthProvider

type AuthProvider struct{ Provider }

AuthProvider is the provider section of an auth status.

type AuthStatus

type AuthStatus struct {
	LoggedIn bool `json:"logged_in"`
	// Account is present when logged in.
	Account  *Account     `json:"account,omitempty"`
	Provider AuthProvider `json:"provider"`
}

AuthStatus is the native login state.

type Authenticator

type Authenticator interface {
	StartLogin(ctx context.Context, req LoginRequest) (Login, error)
	Logout(ctx context.Context) error
}

Authenticator is implemented by agents whose native login flow can be driven over the API. The context passed to StartLogin bounds the whole login; cancelling it ends the flow.

type Capability

type Capability string

Capability is one native CLI surface implemented by an adapter. Gateway-wide transports and storage features are not listed here. Unknown future values must be ignored by API clients.

const (
	CapabilityAuth              Capability = "auth"
	CapabilityCustomAgents      Capability = "custom_agents"
	CapabilityDebugOutput       Capability = "debug_output"
	CapabilityDiagnostics       Capability = "diagnostics"
	CapabilityFileCheckpointing Capability = "file_checkpointing"
	CapabilityFileInputs        Capability = "file_inputs"
	CapabilityHooks             Capability = "hooks"
	CapabilityInteractive       Capability = "interactive"
	CapabilityMCP               Capability = "mcp"
	CapabilityModels            Capability = "models"
	CapabilityNativeControl     Capability = "native_control"
	CapabilityPartialMessages   Capability = "partial_messages"
	CapabilityPermissions       Capability = "permissions"
	CapabilityPlugins           Capability = "plugins"
	CapabilitySessionFork       Capability = "session_fork"
	CapabilitySessions          Capability = "sessions"
	CapabilitySkills            Capability = "skills"
	CapabilitySubscriptionUsage Capability = "subscription_usage"
	CapabilitySystemPromptState Capability = "system_prompt_snapshot"
	CapabilityTools             Capability = "tools"
)

Adapter capabilities. Keep values provider-neutral and add one only when clients can use it.

func KnownCapabilities

func KnownCapabilities() []Capability

KnownCapabilities returns the complete provider-neutral capability vocabulary.

func (Capability) Meaning added in v0.2.0

func (c Capability) Meaning() string

Meaning describes the capability, or returns "" for an unknown value.

type ContextUsage

type ContextUsage struct {
	Window int64 `json:"window" doc:"Context window of the turn's model, in tokens."`
	Used   int64 `json:"used"   doc:"Input tokens of the turn's last model call (cached included): what the model holds in context."`
}

ContextUsage is the occupancy of the model's context window.

type ControlProvider

type ControlProvider struct{ Provider }

ControlProvider is the provider section of a control request from the agent.

type ControlRequest

type ControlRequest struct {
	ID       string          `json:"control_id"`
	Provider ControlProvider `json:"provider"`
}

ControlRequest is a native control request from the agent that the client answers. It has no common content: what it asks is in the provider section.

type Conversation

type Conversation interface {
	// Send queues a user message. A message sent during a turn starts the next turn.
	Send(text string) error
	// Interrupt stops the current turn; the conversation stays open.
	Interrupt() error
	// Answer resolves a pending permission request.
	Answer(answer PermissionAnswer) error
	// Control sends a native control request (a JSON object) to the agent and waits for its
	// response. Agents without a control protocol return ErrUnsupported.
	Control(ctx context.Context, request json.RawMessage) (json.RawMessage, error)
	// Respond answers a control request the agent sent (Event.Control). Exactly one of
	// response and errMessage is used.
	Respond(id string, response json.RawMessage, errMessage string) error
	// CloseInput ends the conversation after the current turn; the process then exits.
	CloseInput() error
	// Wait blocks until the process has exited. It returns nil for a clean exit.
	Wait() error
}

Conversation is a live CLI process. A conversation has one or more turns; each turn ends with an Event carrying a Result. Methods are safe for concurrent use.

type Diagnostics

type Diagnostics struct {
	Format string `json:"format" enum:"text,json" doc:"text: a plain report; json: output holds a JSON document."`
	Output string `json:"output"`
}

Diagnostics is the native diagnostic report.

type DiagnosticsReporter

type DiagnosticsReporter interface {
	Diagnostics(ctx context.Context) (Diagnostics, error)
}

DiagnosticsReporter is implemented by agents with a bounded, non-interactive native health check.

type Event

type Event struct {
	// Type is the native event type (e.g. Claude "assistant", "result").
	Type string
	// Raw is the unmodified native JSON event.
	Raw json.RawMessage
	// TurnStarted marks the first event of a turn.
	TurnStarted bool
	// Result is set on the terminal event of a turn.
	Result *Result
	// Permission is set when the agent asks whether it may use a tool. Raw is then the
	// native protocol message and is not forwarded to clients.
	Permission *PermissionRequest
	// Control is set when the agent sends any other control request that the client must
	// answer with Conversation.Respond (e.g. Claude hook callbacks registered by the client).
	Control *ControlRequest
	// Partial marks incremental output (token deltas). Partial events are delivered to live
	// readers but not stored: the complete message follows as a normal event.
	Partial bool
	// Diagnostic is bounded, redacted adapter diagnostic output requested by the client. It is
	// a gateway event, not a native event.
	Diagnostic string
	// Observation is optional structured lifecycle data for a native task, subagent, or
	// background process. Raw remains the lossless native event.
	Observation *Observation
}

Event is one event emitted by the CLI. Native events are forwarded unmodified in Raw; the typed fields are set by the adapter for the events the gateway itself must understand.

type EventFunc

type EventFunc func(Event) error

EventFunc receives events while a conversation is in progress.

type IO

type IO struct {
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
}

IO is the terminal used by interactive commands.

type Info

type Info struct {
	// Name is the stable identifier used in the API and configuration ("claude").
	Name string `json:"name"`
	// Title is the product name of the CLI ("Claude Code").
	Title string `json:"title"`
	// Provider is the vendor of the CLI ("Anthropic").
	Provider string `json:"provider"`
	// Binary is the executable the adapter starts.
	Binary string `json:"binary"`
	// Capabilities lists native CLI surfaces implemented by this adapter. It is sorted and
	// contains no duplicates. Gateway-wide REST, streaming, file and workspace features are
	// described by the OpenAPI document instead.
	Capabilities []Capability `json:"capabilities"`
	// LoginMethods lists the native login flows accepted by POST /v1/agent/login/start.
	LoginMethods []string `json:"login_methods"`
	// TestedVersion is the CLI version the adapter is verified against.
	TestedVersion string `json:"tested_version"`
	// Docs points to the support matrix in the repository.
	Docs string `json:"docs"`
}

Info describes an adapter. It is static and safe to expose over the API.

Terminology: the *agent* is the native CLI (Claude Code), the *provider* is the vendor behind it (Anthropic), and the *adapter* is the gateway code that drives the CLI.

type InstructionPatch

type InstructionPatch struct {
	SystemPrompt *string `json:"system_prompt,omitempty" doc:"Replaces the system prompt; \"\" restores the agent's own."`
}

InstructionPatch changes the instructions.

type InstructionSettings

type InstructionSettings struct {
	SystemPrompt string `json:"system_prompt" doc:"Replaces the agent's system prompt."`
}

InstructionSettings shape the agent's behavior.

type InteractiveCommand

type InteractiveCommand string

InteractiveCommand names a terminal flow supported by Agent.Interactive.

const (
	CommandLogin  InteractiveCommand = "login"
	CommandStatus InteractiveCommand = "status"
)

Interactive commands.

type Login

type Login interface {
	Challenge() LoginChallenge
	// SubmitCode passes the code shown by the sign-in page to the native CLI.
	SubmitCode(code string) error
	// Wait blocks until the flow ends and returns nil only when the login succeeded.
	Wait() error
	// Cancel stops the flow; Wait then returns an error.
	Cancel()
}

Login is one running native login flow.

type LoginChallenge

type LoginChallenge struct {
	// Flow is one of the Flow* constants.
	Flow string
	// URL is the page the user opens in a browser.
	URL string
	// UserCode is the code the user enters on the page (FlowDeviceCode only).
	UserCode string
}

LoginChallenge is what the user must do to finish a login.

type LoginRequest

type LoginRequest struct {
	Method string
	// Options are the agent's own fields of the login request's provider section (without
	// name), validated by the adapter; nil when none were sent.
	Options json.RawMessage
}

LoginRequest selects one native login method from Info.LoginMethods.

type Model

type Model struct {
	ID   string `json:"id"   doc:"Value for model.id."`
	Name string `json:"name" doc:"Display name."`
	// Efforts are the reasoning efforts the model accepts; requests are validated against them.
	Efforts  []string      `json:"efforts" doc:"Reasoning efforts the model accepts, as the CLI reports them; values for model.effort."`
	Provider ModelProvider `json:"provider"`
}

Model is one model the native CLI reports.

type ModelPatch

type ModelPatch struct {
	ID     string `json:"id,omitempty"     doc:"Model ID from GET /v1/agent/models." example:"sonnet"`
	Effort string `json:"effort,omitempty" doc:"Reasoning effort; one of the model's efforts." example:"high"`
}

ModelPatch changes the model or effort.

type ModelProvider

type ModelProvider struct{ Provider }

ModelProvider is the provider section of a model.

type ModelReporter

type ModelReporter interface {
	Models(ctx context.Context) ([]Model, error)
}

ModelReporter is implemented only when a native CLI can discover its available models.

type ModelSettings

type ModelSettings struct {
	ID     string `json:"id"     doc:"Model ID from GET /v1/agent/models (or a native model name)." example:"sonnet"`
	Effort string `json:"effort" doc:"Reasoning effort; one of the model's efforts from GET /v1/agent/models." example:"high"`
}

ModelSettings select the model and its reasoning effort.

type NativeSession

type NativeSession interface {
	NativeSessionID() string
}

NativeSession is implemented by conversations backed by a provider-owned persistent session.

type Observation

type Observation struct {
	ID       string `json:"id"`
	Kind     string `json:"kind"  enum:"task,subagent,process"`
	State    string `json:"state" enum:"active,completed,failed,cancelled"`
	Label    string `json:"label,omitempty"     doc:"Human-readable description."`
	ParentID string `json:"parent_id,omitempty" doc:"Observation that started this one."`
}

Observation is the lifecycle of a native task, subagent or background process. An update may leave Kind, Label and ParentID empty to keep the known values.

type Outcome

type Outcome string

Outcome is how a turn ended.

const (
	// OutcomeCompleted: the agent answered.
	OutcomeCompleted Outcome = "completed"
	// OutcomeFailed: the turn ended with an error.
	OutcomeFailed Outcome = "failed"
	// OutcomeInterrupted: the client interrupted the turn.
	OutcomeInterrupted Outcome = "interrupted"
	// OutcomeLimitReached: a configured turn, budget or retry limit ended the turn.
	OutcomeLimitReached Outcome = "limit_reached"
)

Outcomes.

type OutputPatch

type OutputPatch struct {
	Schema map[string]any `json:"schema,omitempty" doc:"Replaces the JSON Schema of the answer; {} removes it."`
}

OutputPatch changes the output settings.

type OutputSettings

type OutputSettings struct {
	Schema map[string]any `json:"schema" doc:"JSON Schema the final answer must follow."`
}

OutputSettings shape the answer.

type PermissionAnswer

type PermissionAnswer struct {
	ID    string
	Allow bool
	// Message explains a denial to the agent.
	Message string
	// Options are the agent's own fields of the allow request's provider section (without
	// name), validated by the adapter; nil when none were sent.
	Options json.RawMessage
}

PermissionAnswer resolves a PermissionRequest.

type PermissionProvider

type PermissionProvider struct{ Provider }

PermissionProvider is the provider section of a permission request.

type PermissionRequest

type PermissionRequest struct {
	ID      string `json:"permission_id"`
	Kind    string `json:"kind"    enum:"command,file_change,mcp,other"`
	Summary string `json:"summary" doc:"What the agent wants to do: the command, the file, or the tool."`
	// Provider holds the native tool or method and the unmodified native request.
	Provider PermissionProvider `json:"provider"`
}

PermissionRequest asks the client whether the agent may do something.

type ProfileReporter

type ProfileReporter interface {
	ProfileDir() string
}

ProfileReporter is implemented by adapters to report their effective profile directory, so the gateway can keep it out of workspaces and show it to operators.

type Provider

type Provider struct {
	// Name is the served agent ("claude"); it selects the section's schema.
	Name string
	// Fields is an adapter-defined struct with the agent's own typed fields, or nil.
	Fields any
	// Native is the unmodified native document, or nil.
	Native json.RawMessage
}

Provider is the provider section of an API object: {"name": "<agent>", the fields only that agent has, "native": its unmodified native data}. Everything outside the section is gateway data or data every agent supplies with the same meaning.

func NewProvider

func NewProvider(name string, fields any, native json.RawMessage) Provider

NewProvider returns a provider section.

func (Provider) MarshalJSON

func (p Provider) MarshalJSON() ([]byte, error)

MarshalJSON writes name first, then the adapter fields, then native.

func (*Provider) UnmarshalJSON

func (p *Provider) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a section written by MarshalJSON; Fields becomes the remaining members as a json.RawMessage object.

type ProviderMismatchError

type ProviderMismatchError struct {
	Field, Provider, Served string
}

ProviderMismatchError reports a provider section written for another agent.

func (*ProviderMismatchError) Error

func (e *ProviderMismatchError) Error() string

type Request

type Request struct {
	Prompt       string
	Model        string
	SystemPrompt string
	Effort       string
	OutputSchema map[string]any
	WorkspaceID  string
	SessionID    string
	SessionMode  string
	// ForkFrom is the parent session of SessionFork.
	ForkFrom string
	// Permissions is PermissionsBypass or PermissionsAsk (workspace runs only).
	Permissions string
	// Provider is the request's provider section, {"name": ..., the agent's own options}.
	Provider json.RawMessage
	// Options are the agent's own options of Provider without name, validated by the adapter
	// (see docs/agents/). Set by the server.
	Options json.RawMessage
	// AddDirs are extra directories the agent may use besides the workspace. Each must be
	// inside an allowed root or the workspace.
	AddDirs []string

	// WorkspaceDir is resolved by the server from WorkspaceID.
	WorkspaceDir string
	// RunID identifies the run; set by the server or the run manager.
	RunID string
	// Native session identifiers are opaque adapter bindings loaded by the server.
	NativeSessionID string
	NativeForkFrom  string
	// ResolveDir maps a client-supplied directory to its real path, or fails when it is
	// outside the allowed roots and the workspace. Set by the server; nil rejects all.
	ResolveDir func(dir string) (string, error)
}

Request is one prompt sent to an agent. It is internal: the HTTP API builds it from the grouped public Settings and server-managed session state.

Without WorkspaceID the run is stateless: no tools, no session persistence. With a WorkspaceID the agent runs natively in that workspace with all of its features (tools, skills, hooks, MCP, user/project settings) and a resumable session.

func (*Request) Dir

func (r *Request) Dir(field, dir string) (string, error)

Dir resolves a client-supplied directory with ResolveDir.

func (*Request) Normalize

func (r *Request) Normalize() error

Normalize trims fields and performs the agent-independent validation.

func (*Request) Stateless

func (r *Request) Stateless() bool

Stateless reports whether the request runs without a workspace.

type Result

type Result struct {
	// Text is the agent's answer; for a turn that did not complete, whatever it answered
	// before it stopped (often empty).
	Text    string  `json:"text"`
	Outcome Outcome `json:"outcome" enum:"completed,failed,interrupted,limit_reached"`
	// Error says why the turn did not complete (redacted); set exactly when outcome is not
	// completed.
	Error string `json:"error,omitempty"`
	// Tokens are the turn's token counts; absent when the agent reported none.
	Tokens *Tokens `json:"tokens,omitempty"`
	// Context is how full the model's context window is after the turn; absent when the turn
	// made no model call.
	Context *ContextUsage `json:"context,omitempty"`
	// Provider holds the native outcome code, the agent's own usage data and the native result.
	Provider ResultProvider `json:"provider"`
	// AgentInitiated marks a native turn the agent started on its own (Claude Code reacting to
	// a background-task notification), not an answer to a client message. The run forwards it
	// as a native event but does not count it as a turn or replace the run result.
	AgentInitiated bool `json:"-"`
}

Result is the outcome of one turn.

func (*Result) Failed

func (r *Result) Failed() bool

Failed reports whether the turn did not complete.

type ResultProvider

type ResultProvider struct{ Provider }

ResultProvider is the provider section of a turn result.

type SandboxMode

type SandboxMode string

SandboxMode selects who isolates the commands an agent runs.

const (
	// SandboxCLI enables the CLI's own OS sandbox (Seatbelt on macOS, bubblewrap on
	// Linux). Runs fail instead of executing unconfined when that sandbox is unavailable.
	SandboxCLI SandboxMode = "cli"
	// SandboxExternal disables the CLI's own sandbox because an outer boundary, such as a
	// hardened container, already isolates the process.
	SandboxExternal SandboxMode = "external"
)

func (SandboxMode) Valid

func (s SandboxMode) Valid() bool

Valid reports whether s is a supported sandbox mode.

type Section

type Section string

Section names an API object that has a provider section. Request sections carry provider options from the client; response sections carry provider data to the client.

const (
	SectionRun          Section = "run"          // request: run settings (provider options)
	SectionLogin        Section = "login"        // request: login start
	SectionAllow        Section = "allow"        // request: permission allow
	SectionAuth         Section = "auth"         // response: AuthProvider
	SectionSubscription Section = "subscription" // response: SubscriptionProvider
	SectionModel        Section = "model"        // response: ModelProvider
	SectionResult       Section = "result"       // response: ResultProvider
	SectionPermission   Section = "permission"   // response: PermissionProvider
	SectionControl      Section = "control"      // response: ControlProvider
)

Sections.

type SectionDescriber

type SectionDescriber interface {
	ProviderSections() map[Section]reflect.Type
}

SectionDescriber is implemented by adapters to describe their provider sections: the Go type of the agent's own fields per section. A missing section has no fields besides name (and native, for responses). The OpenAPI document is generated from it.

type Settings

type Settings struct {
	Model        ModelSettings        `json:"model"`
	Tools        *ToolSettings        `json:"tools,omitempty"`
	Instructions *InstructionSettings `json:"instructions,omitempty"`
	Output       *OutputSettings      `json:"output,omitempty"`
	// Provider is the provider section: {"name": "<agent>", the agent's own options}.
	Provider json.RawMessage `json:"provider,omitempty"`
}

Settings are the client-chosen run settings, grouped as in the public API. A session remembers the settings of its last run and its next run reuses them.

func SettingsOf

func SettingsOf(req *Request) Settings

SettingsOf returns the settings of a validated request (add_dirs resolved).

func (Settings) Apply

func (s Settings) Apply(req *Request)

Apply copies the settings into req.

type SettingsPatch

type SettingsPatch struct {
	Model        *ModelPatch       `json:"model,omitempty"`
	Tools        *ToolPatch        `json:"tools,omitempty"`
	Instructions *InstructionPatch `json:"instructions,omitempty"`
	Output       *OutputPatch      `json:"output,omitempty"`
	Provider     json.RawMessage   `json:"provider,omitempty" doc:"Replaces the remembered provider section as a whole."`
}

SettingsPatch changes some settings of a session. Every group and field is optional; a supplied field replaces the remembered one, an omitted field keeps it.

func (SettingsPatch) Merge

func (p SettingsPatch) Merge(base Settings) Settings

Merge returns base with the patch applied.

type SubscriptionProvider

type SubscriptionProvider struct{ Provider }

SubscriptionProvider is the provider section of the subscription usage.

type Tokens

type Tokens struct {
	Input         *int64 `json:"input,omitempty"`
	Output        *int64 `json:"output,omitempty"`
	CacheRead     *int64 `json:"cache_read,omitempty"`
	CacheCreation *int64 `json:"cache_creation,omitempty"`
}

Tokens is a token breakdown. A nil field was not reported, which is not the same as zero. Input is the uncached input; cached and cache-write input are counted only in CacheRead and CacheCreation, for every agent. A turn's counts cover all of its model calls.

func (*Tokens) Fields

func (t *Tokens) Fields() [4]**int64

Fields returns pointers to the four counts, for summing.

type ToolPatch

type ToolPatch struct {
	Permissions string    `json:"permissions,omitempty" enum:"bypass,ask"`
	AddDirs     *[]string `json:"add_dirs,omitempty"    maxItems:"16" doc:"Replaces the list; [] removes every extra directory."`
}

ToolPatch changes the tool settings.

type ToolSettings

type ToolSettings struct {
	Permissions string   `json:"permissions"        enum:"bypass,ask" doc:"bypass: tools run without asking; ask: every tool use waits for an answer."`
	AddDirs     []string `` /* 128-byte string literal not displayed */
}

ToolSettings decide how the agent may use tools in a workspace.

type Usage

type Usage struct {
	Windows  []UsageWindow        `json:"windows"`
	Provider SubscriptionProvider `json:"provider"`
}

Usage is the subscription allowance.

type UsageReporter

type UsageReporter interface {
	Usage(ctx context.Context) (Usage, error)
}

UsageReporter is implemented by agents that can report subscription usage.

type UsageTotal

type UsageTotal struct {
	Turns  UsageTurns `json:"turns"`
	Tokens Tokens     `json:"tokens"`
	// Partial lists the token counts that at least one reported turn did not include; their
	// sums cover fewer turns than turns.reported. Turns without any counts are in
	// turns.unreported instead.
	Partial []string `json:"partial" enum:"input,output,cache_read,cache_creation"`
}

UsageTotal sums the token counts of the turns the gateway observed.

func NewUsageTotal

func NewUsageTotal() UsageTotal

NewUsageTotal returns an empty total.

func (*UsageTotal) Add

func (u *UsageTotal) Add(tokens *Tokens)

Add folds one turn's tokens (nil: unreported) into the total.

func (UsageTotal) Clone

func (u UsageTotal) Clone() UsageTotal

Clone returns a deep copy.

func (*UsageTotal) Merge

func (u *UsageTotal) Merge(other UsageTotal)

Merge folds another total into u.

type UsageTurns

type UsageTurns struct {
	Reported   int `json:"reported"   doc:"Turns that reported token counts."`
	Unreported int `json:"unreported" doc:"Turns without token counts."`
}

UsageTurns counts the observed turns.

type UsageWindow

type UsageWindow struct {
	ID          string     `json:"id" doc:"Stable window identifier as the agent reports it (e.g. session, weekly)."`
	UsedPercent float64    `json:"used_percent"`
	ResetsAt    *time.Time `json:"resets_at,omitempty" doc:"When the window resets; absent while it has no usage."`
}

UsageWindow is one rate-limit window of the subscription.

Directories

Path Synopsis
Package agenttest provides a scriptable agent.Agent for tests of the run manager and the HTTP API.
Package agenttest provides a scriptable agent.Agent for tests of the run manager and the HTTP API.
Package builtin is the single list of agent adapters compiled into the gateway.
Package builtin is the single list of agent adapters compiled into the gateway.
Package claude runs the native Claude Code CLI in non-interactive stream-json mode.
Package claude runs the native Claude Code CLI in non-interactive stream-json mode.
Package codex adapts the native Codex CLI app-server protocol to the common agent contract.
Package codex adapts the native Codex CLI app-server protocol to the common agent contract.

Jump to

Keyboard shortcuts

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