agent

package
v0.1.61 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 25 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 is the daemon CORE: the generic, agent-agnostic contracts every agent adapter implements (capabilities, dynamic settings/auth, unified events) plus the registry. ONE daemon per sandbox hosts EVERY registered adapter; a request selects one (?agent=<type>) and the client only ever speaks this one generic protocol. Adding an agent (Codex, Copilot, …) = one new adapter, zero core or client changes.

Index

Constants

View Source
const (
	AuthFlowIDKey   = "_flowId"
	AuthActionKey   = "_action"
	AuthCodeKey     = "authorizationCode"
	AuthCallbackKey = "_callbackUrl"
)

Interactive auth uses the same step endpoint as field forms. These reserved keys scope a request to one attempt; cancellation must always include its ID.

View Source
const (
	CanonModel              = "model"
	CanonFallbackModel      = "fallbackModel"
	CanonReasoningEffort    = "reasoningEffort"
	CanonReasoningSummary   = "reasoningSummary"
	CanonSystemPrompt       = "systemPrompt"       // full override
	CanonAppendSystemPrompt = "appendSystemPrompt" // appended to the agent's default
	CanonPermissionMode     = "permissionMode"
	CanonApprovalReviewer   = "approvalReviewer"
	CanonAllowedTools       = "allowedTools"      // restrict to these built-in tools
	CanonAllowRules         = "allowRules"        // permission allow rules
	CanonDenyRules          = "denyRules"         // permission deny rules
	CanonExtraDirs          = "extraDirs"         // additional accessible directories
	CanonMaxSpendUSD        = "maxSpendUsd"       // hard spend cap for the turn
	CanonMaxTurns           = "maxTurns"          // cap on agent turns (tool-use cycles) for the turn
	CanonAutoCompactTokens  = "autoCompactTokens" // auto-compact the conversation at this context-token threshold
)

Canonical keys — the stable, cross-agent vocabulary the CLIENT addresses regardless of which agent is selected. A unified Field carries one of these in Field.Canon; the adapter maps it to its own Field.Key (its internal/flag-aligned name). Per-turn options are addressed by canon and resolved canon→key in the runner (the single security choke point), so a client can say "reasoningEffort" and have it land on whichever flag the selected agent uses.

This registry is a CLOSED vocabulary: adding a unified concept means adding a constant here (a daemon build), never inventing one at the edge. Agent-specific concepts do NOT get a canon — they are custom fields (Scope==ScopeCustom) whose Canon conventionally equals their Key.

View Source
const (
	CheckOK   = "ok"
	CheckWarn = "warn"
	CheckFail = "fail"
)
View Source
const AuthSourceEnvironment = "MINDWIRE_AUTH_SOURCE"
View Source
const ChatForkVersion = 1
View Source
const ExistingAuthMethod = "existing"
View Source
const HandoffContextVersion = 1
View Source
const HelpCacheTTL = 10 * time.Minute

HelpCacheTTL is how long a captured `--help` blob stays fresh: one exec per window (so opening the settings UI repeatedly doesn't shell out each time), refreshed periodically so a CLI upgrade (e.g. via POST /update) is picked up without a daemon restart.

View Source
const ImageAttachmentsVersion = 1

ImageAttachmentsVersion advertises image-only turns and durable image history.

View Source
const MaxHandoffContextBytes = 32 << 10
View Source
const MaxHandoffWireBytes = 256 << 10 // worst-case JSON escaping of a reviewed 32 KiB text
View Source
const NativeSessionVersion = 1
View Source
const Version = "0.1.61"

Version identifies this daemon binary's agent definitions. The app caches the fetched schema/catalog keyed by this, and refreshes when it changes.

View Source
const WorkspaceIsolationVersion = 1

WorkspaceIsolationVersion describes the placement contract reported by /healthz.

Variables

View Source
var ErrHandoffHistoryChanged = errors.New("native history changed while preparing handoff")
View Source
var ErrInputClosed = errors.New("the native turn is no longer accepting input")

ErrInputClosed means input was not submitted to a live native turn. Callers may safely resume the conversation instead; other errors must not auto-retry.

View Source
var ErrVoiceClosed = errors.New("This voice conversation has ended. Start voice again to reconnect.")
View Source
var NativeTranscripts = newHistoryCache(8, 64<<20)

NativeTranscripts caches parsing, never the source of truth. Every read checks the native file identity, size, and nanosecond modification time. Recorded run state and interaction answers are overlaid by the adapters/API after this cache.

Functions

func AcknowledgeInput

func AcknowledgeInput(in Inbound, err error, emit Emit)

AcknowledgeInput publishes acceptance in native event order before releasing the caller. ErrInputClosed proves nothing was submitted and permits a safe continuation; an ambiguous transport failure must never be retried automatically.

func AttachmentReferenceText

func AttachmentReferenceText(attachments []Attachment) string

func BuildUnifiedDiff

func BuildUnifiedDiff(path, oldText, newText string) string

BuildUnifiedDiff produces a best-effort unified diff (git-style, with a/ b/ headers and @@ hunks) from oldText → newText using a hand-rolled line-based LCS (the daemon carries zero third-party deps). It returns "" when there is no change or when the inputs are too large to diff cheaply; the caller then falls back to OldText/NewText. Very large diffs are truncated with a marker so transcripts stay bounded.

func CanonToKey

func CanonToKey(schema SettingsSchema, canon string) (string, bool)

CanonToKey resolves a canonical key to the given schema's adapter-specific field key. The bool is false when no field in the schema declares that canon. This is how the runner turns a client's canon-addressed per-turn option into the key the adapter stores/flags.

func CommandCacheKey

func CommandCacheKey(binary string, query CommandQuery) string

func ConfigDir

func ConfigDir(envVar, defaultSub string) string

ConfigDir resolves an agent's config directory: the value of envVar if set, else ~/<defaultSub> (os.UserHomeDir honors $HOME, so it's correct under any sandbox home). Empty when the home directory can't be resolved.

func Configured

func Configured(schema SettingsSchema, config map[string]string) bool

Configured reports whether every required text/secret field has a value.

func Continuable

func Continuable(subtype string) bool

Continuable reports whether a terminal result subtype means the turn "stopped short but can be resumed" — the agent hit a self-imposed budget (max turns / max cost) rather than genuinely finishing or erroring. It is the single source of truth the resolve loop uses to decide whether to auto-continue. Agents with no subtype concept (Codex) always return false here (their terminal event is fully settled), so resolve completes them in one iteration.

func DefaultTitle

func DefaultTitle(c Condition, agentName string) string

DefaultTitle is the fallback title for a condition the agent didn't customize.

func Denied

func Denied(decision string) bool

Denied reports whether an interaction decision id is a rejection. It is the UNION of every adapter's reject vocabulary, so allow stays the default and any adapter can answer with any of these tokens. Case- and whitespace-insensitive.

func DeriveEnvVar

func DeriveEnvVar(id, override string) string

DeriveEnvVar picks the env-var name a custom provider's key is exported under. A non-empty override (already the caller's explicit choice) wins verbatim; otherwise it is derived from the id by upper-casing and mapping every non-alphanumeric rune to '_', then appending "_API_KEY" (e.g. "my-llm" → "MY_LLM_API_KEY"). Callers pass the result to both the config placeholder and the stored ProviderEnvKey so EnvForRun and the config file agree.

func FirstNonEmpty

func FirstNonEmpty(vals ...string) string

FirstNonEmpty returns the first argument that is non-empty after trimming (returned verbatim, not trimmed), or "" if all are blank.

func FoundryBaseURL

func FoundryBaseURL(base, resource, resourceDomain, apiPath string) (string, error)

FoundryBaseURL accepts a resource endpoint or an API base URL. Codex and Claude use different API paths; accepting the other one's URL produces a broken setup.

func HandoffLossDescription added in v0.1.54

func HandoffLossDescription(code string) string

HandoffLossDescription keeps omission reports readable without exposing codec names or internal field names in the review interface.

func HasUserInput

func HasUserInput(message string, options TurnOptions) bool

func ImportNativeAuth

func ImportNativeAuth(ctx context.Context, store CredStore, files map[string][]byte, settings map[string]string, verify func(context.Context) bool) error

ImportNativeAuth restores both the private files and connection fields if native verification fails. It never writes to the source account's files or keychain.

func IsCanon

func IsCanon(key string) bool

IsCanon reports whether key is a registered unified canonical key.

func JoinShellWords

func JoinShellWords(args []string) string

JoinShellWords renders an argv vector without changing arguments containing quotes or spaces. This is also used for command display when a harness stores argv instead of a command string.

func LegacyAsyncFormID

func LegacyAsyncFormID(it *Interaction) string

LegacyAsyncFormID recognizes the informational question rows emitted by older daemons. It uses their explicit native item IDs, never guesses from chat prose.

func MapChangeOp

func MapChangeOp(kind string) string

MapChangeOp normalizes an agent's file-change verb (Codex uses "add"/"modify"/"delete", etc.) to the canonical Op vocabulary ("create" | "edit" | "delete"). Unknown verbs default to "edit".

func NativeActionUnsupported

func NativeActionUnsupported(kind string) error

func NativeAudioMime

func NativeAudioMime(at Attachment) string

NativeAudioMime identifies the formats accepted by Codex localAudio. Other audio remains an ordinary file; adapters still decide whether the model hears it.

func NativeAuthSettings

func NativeAuthSettings(module AuthModule, method string) map[string]string

NativeAuthSettings clears only this agent's connection fields when switching. Models, other agents and shared provider credentials are preserved unless the importing adapter explicitly supplies a new value.

func NativeError

func NativeError(code, message string) error

func NativeHistoryFileRevision

func NativeHistoryFileRevision(path string) (string, error)

NativeHistoryFileRevision stats a file without parsing or hashing its contents. File identity detects replacement even when size and modification time match.

func NativeImageMime

func NativeImageMime(at Attachment) string

NativeImageMime is the common raster-image input understood by the harnesses. Other media are handled separately by the adapter or kept as readable files.

func NormalizeAuthInput

func NormalizeAuthInput(fields []Field, input map[string]string) (map[string]string, error)

NormalizeAuthInput applies the same declared defaults, visibility, and required rules as the client. Hidden drafts never take precedence over the chosen mode, even when a client submits them. Unknown keys are not forwarded to an adapter.

func NormalizeSettings

func NormalizeSettings(schema SettingsSchema, input map[string]string) (map[string]string, error)

NormalizeSettings validates the complete patch before anything is persisted. It retains raw/canonical compatibility and the existing unknown-key filtering.

func NormalizeSurfaceTool

func NormalizeSurfaceTool(tool *ToolEvent)

func ParseCSV

func ParseCSV(s string) []string

ParseCSV splits a comma-separated list, trimming whitespace and surrounding quotes from each item and dropping empties. Used to read enum choices out of CLI `--help` text.

func PermissionLabel

func PermissionLabel(value string) string

Labels describe native values; adapters still discover which values are supported.

func ProviderCredKey

func ProviderCredKey(id string) string

ProviderCredKey is the CredStore key under which a custom provider's secret is stored, namespaced by provider id so multiple providers coexist. The CredView already prefixes the agent type, so the full key is "<agentType>:provider:<id>:apiKey". providerEnvKey does the same for the exported env-var name, letting EnvForRun re-export a stored key without re-parsing the harness config.

func ProviderEnvForRun

func ProviderEnvForRun(store CredStore) map[string]string

ProviderEnvForRun collects the env map a custom-provider-capable agent's EnvForRun should merge, unioning BOTH storage schemes so every registered provider's credentials reach the run:

  • legacy single-var: the env-var NAME under "provider:<id>:envVar" paired with its value under "provider:<id>:apiKey" — one var per provider (custom endpoints, single-key catalog brands).
  • multi-var: every "provider:<id>:env:<VARNAME>" entry, the var NAME embedded in the key and the value stored directly (catalog providers whose env[] declares several vars, e.g. AWS Bedrock).

The new scheme wins on a NAME collision (a var stored both ways resolves to the multi-var value), and values cleared to "" contribute nothing. This stays the sole credential seam (EnvForRun → process env) without any adapter re-parsing its config file.

func ProviderEnvKey

func ProviderEnvKey(id string) string

ProviderEnvKey is the CredStore key holding the env-var NAME a custom provider's key is exported as (so EnvForRun knows where to inject it without parsing config). Full key: "<agentType>:provider:<id>:envVar". This is the SINGLE-var (legacy) scheme; ProviderEnvValueKey is the MULTI-var one.

func ProviderEnvValueKey

func ProviderEnvValueKey(id, name string) string

ProviderEnvValueKey is the CredStore key holding ONE env var's value for a multi-var provider — the var NAME is embedded in the key, so a provider that authenticates through several env vars (e.g. AWS Bedrock's key/secret/region) stores one entry per var. Full key: "<agentType>:provider:<id>:env:<VARNAME>". The ":env:" infix can't collide with the legacy ":envVar" key (no ":env:" substring) nor the single-slot auth keys, and — because provider ids and env-var names contain no colon — the first ":env:" after "provider:" always marks the id/name boundary.

func ReadNativeAuthFile

func ReadNativeAuthFile(path string) ([]byte, error)

ReadNativeAuthFile bounds credential reads and never includes file contents in errors.

func ReadSettings

func ReadSettings(adapter Adapter, store CredStore) map[string]string

func Register

func Register(a Adapter)

Register adds an adapter (called from each adapter's init()).

func RenderHandoffContext added in v0.1.54

func RenderHandoffContext(c HandoffContext) string

RenderHandoffContext is the exact review surface for the structured capsule. Any edits replace the capsule's contents rather than leaving hidden originals.

func ResolveDir

func ResolveDir(dir, fallback string) string

ResolveDir picks the working directory a project-scope memory/prompt operation targets: an explicit request value wins, else the supplied fallback (the daemon's own cwd), else the process working directory. This mirrors how a turn's cwd is resolved, so a project memory read aligns with where turns actually run. Returns "" only when all three are empty (os.Getwd failing on a daemon with no cwd — pathological).

func ResolveSettingKey

func ResolveSettingKey(schema SettingsSchema, key string) (string, bool)

ResolveSettingKey maps an incoming sticky-config key to the schema's declared, non-secret RAW key it should persist under. It accepts either a raw key directly (back-compat) OR a canonical key that resolves via CanonToKey to a declared non-secret field — so the sticky setConfig path accepts "reasoningEffort" exactly like the canon-addressed per-turn path, landing it on whichever raw field the selected agent uses. Raw wins over canon (checked first). Returns ("", false) when the key is neither a declared non-secret raw key nor a canon resolving to one; callers skip those, preserving the existing "silently ignore unrecognized keys" behavior. The non-secret allow-list (SettingsKeys) guards both branches, so a canon can never resolve onto a secret field.

func SafeArchiveName

func SafeArchiveName(name string) bool

func SameHistoryPart

func SameHistoryPart(final, recorded Part) bool

func SessionTitle

func SessionTitle(text string) string

func SettingsKeys

func SettingsKeys(schema SettingsSchema) map[string]bool

SettingsKeys is the allow-list of NON-secret setting keys an agent declares. It is the exact set of keys /config may read or write AND the set the runner passes into a turn's TurnInput.Config. Secrets live outside the settings schema (touched only by the auth flow), so config can neither leak nor overwrite them, and they never enter a turn's Config — only its Env (via AuthModule.EnvForRun).

func ShellQuote

func ShellQuote(s string) string

ShellQuote single-quotes a string for POSIX sh, escaping embedded single quotes. Used to build the `bash -lc` command line so user text (a message, a path, an option value) can never break framing or inject a second command.

func ShellWords

func ShellWords(command string) []string

ShellWords decodes shell-quoted argv for comparison, without executing or expanding anything. Unbalanced input is not comparable. Quoting style alone must not give a tool a new identity.

func StoredProviderEnv

func StoredProviderEnv(store CredStore, id string) map[string]string

StoredProviderEnv returns the NAME→VALUE map of a multi-var provider's stored env vars (the ":env:<VAR>" scheme), skipping entries cleared to "" (Set(k,"") stores an empty string rather than deleting the key). Empty when the store is nil or the provider has no multi-var entries. The legacy single-var pair (:envVar/:apiKey) is NOT included — callers that need it read it separately.

func UnsupportedTurnOption

func UnsupportedTurnOption(caps Capabilities, opts TurnOptions) (string, bool)

UnsupportedTurnOption enforces the turn-option capability gate: it reports the first per-turn option the agent doesn't support (ok=false + a client-facing message), or ok=true when the request is clean. Each option has two client entry points — the typed TurnOptions field and the canon-addressed setting — and both are gated so no path silently drops. Mirrors the per-route capability checks (Cancel/SetModel/…): an unsupported input is an honest 400, never a no-op.

This is the single source of truth for the gate, shared by the HTTP surface (api.turn) and the in-process Go SDK (mindwire.Client.Turn) so neither can drift from the other.

func ValidCommandName

func ValidCommandName(name string) bool

func ValidNativeSessionID

func ValidNativeSessionID(id string) bool

func ValidateEnvVarName

func ValidateEnvVarName(name string) error

ValidateEnvVarName enforces a POSIX-ish env-var name: a non-empty run of letters, digits and underscores not starting with a digit. This both matches what the models.dev catalog declares (e.g. AWS_ACCESS_KEY_ID, GOOGLE_GENERATIVE_AI_API_KEY) and — critically — guarantees the name carries no ':', so it can be embedded in a ProviderEnvValueKey without breaking the ":env:" boundary parse. Names arrive from the client through the HTTP API, so this is a security boundary, not just a sanity check.

func ValidateHandoffContext added in v0.1.54

func ValidateHandoffContext(c HandoffContext) error

func ValidateNativeSessionQuery

func ValidateNativeSessionQuery(q NativeSessionQuery) error

func ValidatePromptName

func ValidatePromptName(name string) error

ValidatePromptName rejects a saved-prompt template name that isn't a single safe filename segment. The caller appends ".md"; the name must be a bare basename — non-empty, no "."/".." traversal, and no path separator — so a joined path can never escape its prompt directory. Combined with the single-segment API route, this is defense-in-depth against traversal from client input.

func ValidateProviderID

func ValidateProviderID(id string) error

ValidateProviderID enforces a conservative id shape safe to use as a JSON/TOML config key AND as the stem of a derived env-var name: it must start with a letter or digit and contain only letters, digits, '-' and '_'. Rejecting anything looser keeps the materialized config predictable and the env-var derivation collision-free.

func ValidateSchema

func ValidateSchema(schema SettingsSchema) error

ValidateSchema enforces the taxonomy invariants on an adapter's settings schema:

  • every field declares a Scope (unified | custom);
  • a unified field's Canon is non-empty AND registered (no invented cross-agent concepts);
  • a custom field's Canon equals its Key (custom concepts don't share a namespace);
  • Canon is unique within the schema (canon→key must resolve unambiguously).

It is called by an adapter conformance test so a mis-annotated field fails CI, not a live turn.

func WorkspaceIsolation

func WorkspaceIsolation() string

WorkspaceIsolation is set by the trusted launcher, not by a profile or a turn. Container launchers provide the filesystem/process boundary themselves. In particular, Codex must not require a second set of Linux namespaces inside an unprivileged Docker container. Approval policy remains independent of placement.

Types

type Action

type Action struct {
	ID          string `json:"id"`
	Label       string `json:"label"`
	Description string `json:"description,omitempty"`
	Preview     string `json:"preview,omitempty"`
}

Action is a user action surfaced with the notification (e.g. Approve / Reject).

type Adapter

type Adapter interface {
	ID() string
	Meta() CatalogEntry
	Capabilities() Capabilities
	Settings() SettingsSchema
	InstallSteps() []Step
	VersionCommand() string
	// ConfigPath is the agent's user-editable config file (absolute), so the app can open it in
	// its editor. Empty if the agent has none.
	ConfigPath() string
	Auth(store CredStore) AuthModule
	RunStream(ctx context.Context, in TurnInput, emit Emit) (TurnResult, error)
	History(q HistoryQuery) ([]Message, error)
	// Notifications declares the conditions this agent produces + their UX.
	Notifications() NotificationSpec
	// Doctor runs agent-specific health checks (CLI installed, toolchain, …) that the
	// daemon's generic doctor appends to its own checks.
	Doctor(ctx context.Context) []Check
}

Adapter is everything the daemon needs to own ONE agent's lifecycle generically: catalog identity, capabilities (the hybrid switch), dynamic settings, auth module, install toolchain + verify, a streaming turn, and native history.

func All

func All() []Adapter

All returns every registered adapter, ordered by ID — the daemon hosts them all and routes each request to the one the client selects. Ordering is stable across restarts (map iteration is randomized) so the catalog and any default-selection fallback are deterministic.

type Attachment

type Attachment struct {
	ArtifactID string `json:"artifactId,omitempty"` // durable upload in this conversation
	Bytes      int    `json:"bytes,omitempty"`
	Name       string `json:"name,omitempty"` // display/file name (shown to the agent when referenced)
	Path       string `json:"path,omitempty"` // absolute path already on disk (preferred)
	Mime       string `json:"mime,omitempty"`
	Data       []byte `json:"data,omitempty"` // inline bytes (base64 on the wire); written to a file, then referenced
}

Attachment is a file made available to a turn. Native image-capable adapters use image content blocks or local-image input; other files are referenced by path. Inline bytes are base64 on the wire and retained in user history so a temporary materialized file can be removed without losing the client's image preview.

func ImageFromDataURL

func ImageFromDataURL(value string) (Attachment, bool)

func ImagesFromContent

func ImagesFromContent(raw json.RawMessage) []Attachment

ImagesFromContent reads user input blocks only. Tool outputs remain artifacts, and remote URLs/local paths are never fetched while rendering history.

func InputAttachmentsFromContent

func InputAttachmentsFromContent(raw json.RawMessage) []Attachment

InputAttachmentsFromContent also preserves native audio. It only decodes user input; fetching remote media or opening local paths is never part of history.

func MergeInputAttachments

func MergeInputAttachments(native, recorded []Attachment) []Attachment

MergeInputAttachments keeps native input order. Recorded bytes restore previews when a harness persists only a temporary image path which it later deletes.

type AuthCallbackModule added in v0.1.57

type AuthCallbackModule interface {
	Callback(context.Context, string, string) (AuthState, error)
}

AuthCallbackModule delivers a flow-scoped native browser response. It is separate from field submission so network delivery can run without blocking auth admission: the user must remain able to cancel that same login.

type AuthDiscoveryModule added in v0.1.60

type AuthDiscoveryModule interface {
	DiscoverMethods(context.Context) ([]AuthMethod, error)
}

AuthDiscoveryModule discovers native provider/plugin login methods on explicit auth reads. Static catalog reads remain cheap and never launch a login.

type AuthFlow

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

AuthFlow owns a native login's lifetime and generic client state. Both device codes and browser/code handoffs use it; credentials stay with the native CLI.

func NewAuthFlow

func NewAuthFlow(method string) *AuthFlow

func (*AuthFlow) Active

func (f *AuthFlow) Active() bool

func (*AuthFlow) Cancel

func (f *AuthFlow) Cancel()

func (*AuthFlow) Complete

func (f *AuthFlow) Complete(commit func() error)

Complete commits the selected method only while this attempt is active. A canceled or superseded login can never change the daemon's selected account.

func (*AuthFlow) Context

func (f *AuthFlow) Context() context.Context

func (*AuthFlow) Fail

func (f *AuthFlow) Fail(message string)

func (*AuthFlow) InitialState

func (f *AuthFlow) InitialState(ctx context.Context) AuthState

InitialState briefly waits for a URL without binding the native login's lifetime to the HTTP request (which ends as soon as this state is returned).

func (*AuthFlow) SetCallback added in v0.1.57

func (f *AuthFlow) SetCallback(deliver func(string) error)

SetCallback binds delivery to this native attempt. The adapter validates the exact callback target and OAuth state; this is never an arbitrary HTTP proxy.

func (*AuthFlow) SetInput

func (f *AuthFlow) SetInput(input func(string) error)

func (*AuthFlow) State

func (f *AuthFlow) State() AuthState

func (*AuthFlow) Step

func (f *AuthFlow) Step(input map[string]string) (AuthState, error)

func (*AuthFlow) Update

func (f *AuthFlow) Update(st AuthState)

type AuthLogoutModule

type AuthLogoutModule interface {
	Logout(context.Context) error
}

AuthLogoutModule removes a harness's native subscription session. Field-based connections are cleared by ManagedAuth; shared provider connections and model settings belong to the workspace and are deliberately preserved.

type AuthMethod

type AuthMethod struct {
	ID          string                  `json:"id"`
	Label       string                  `json:"label"`
	Scope       Scope                   `json:"scope,omitempty"` // unified | custom (taxonomy; empty = unified)
	Help        string                  `json:"help,omitempty"`
	Interactive bool                    `json:"interactive,omitempty"`
	Fields      []Field                 `json:"fields,omitempty"` // reuses the settings Field shape
	Sections    []AuthSection           `json:"sections,omitempty"`
	Existing    *ExistingAuthConnection `json:"existing,omitempty"`
}

AuthMethod is one way to authenticate an agent — the client shows these as an options list. A field-based method collects Fields; an interactive one drives a begin→step→status flow (e.g. a login command that surfaces a URL).

Scope carries the same taxonomy as a settings Field: a UNIFIED method is a cross-agent authentication concept (an API key, an interactive login, a gateway bearer token — one every agent has some form of); a CUSTOM method is agent-specific (e.g. Claude's Bedrock/Vertex/Foundry cloud providers), declared + typed in the adapter, never open passthrough. Empty scope reads as unified for backward compatibility.

func DiscoverAuthMethods added in v0.1.60

func DiscoverAuthMethods(ctx context.Context, module AuthModule) ([]AuthMethod, error)

type AuthModule

type AuthModule interface {
	Methods() []AuthMethod
	Begin(ctx context.Context, methodID string) (AuthState, error)
	Step(ctx context.Context, input map[string]string) (AuthState, error)
	Status(ctx context.Context) AuthStatus
	EnvForRun() map[string]string
}

AuthModule is an agent's auth logic. The client drives a generic methods → begin → step → status flow; the module (bound to a CredStore at construction) handles each method's specifics and persists credentials.

type AuthPrepareModule

type AuthPrepareModule interface {
	PrepareAuth(context.Context) error
}

AuthPrepareModule initializes a trusted native connection on first use. The runner calls it before reading settings or auth environment, so clients do not need to open settings or poll status before starting their first turn.

type AuthSection

type AuthSection struct {
	ID        string   `json:"id"`
	Title     string   `json:"title"`
	Help      string   `json:"help,omitempty"`
	FieldKeys []string `json:"fieldKeys"`
}

AuthSection groups declared field keys in display order. Titles and help belong to the daemon; clients render native form sections without provider-specific UI.

type AuthSource

type AuthSource struct {
	Home        string            `json:"home"`
	Environment map[string]string `json:"environment,omitempty"`
	// A trusted host connection is reused on first setup unless the host requests
	// manual selection. Explicit sign-out and existing connection choices always win.
	Reuse    string                                                            `json:"reuse,omitempty"`
	Keychain func(context.Context, string, string, bool) ([]byte, bool, error) `json:"-"`
}

AuthSource is supplied by a trusted native host at boot, never by an HTTP request. Its environment is used only to resolve selected credential references. It is not stored, returned by the API, or inherited by agent processes.

func ConsumeAuthSource

func ConsumeAuthSource() (*AuthSource, error)

ConsumeAuthSource removes the bootstrap value before the daemon starts any native child. Ordinary daemons need no source: they already use their host login.

func (*AuthSource) ConfigDir

func (s *AuthSource) ConfigDir(variable, fallback string) string

func (*AuthSource) ReadKeychain

func (s *AuthSource) ReadKeychain(ctx context.Context, service, account string, reveal bool) ([]byte, bool, error)

type AuthState

type AuthState struct {
	Method      string        `json:"method"`
	Status      string        `json:"status"`           // "needs_input" | "pending" | "complete" | "error"
	FlowID      string        `json:"flowId,omitempty"` // echo as _flowId when polling, submitting, or canceling
	URL         string        `json:"url,omitempty"`
	CallbackURL string        `json:"callbackUrl,omitempty"` // native loopback callback; relay through scoped auth/step
	Code        string        `json:"code,omitempty"`
	Message     string        `json:"message,omitempty"`
	Fields      []Field       `json:"fields,omitempty"` // inputs the client should collect next
	Sections    []AuthSection `json:"sections,omitempty"`
}

AuthState is the current step of an in-progress auth flow.

type AuthStatus

type AuthStatus struct {
	Configured bool   `json:"configured"`
	SignedOut  bool   `json:"signedOut,omitempty"`
	Method     string `json:"method,omitempty"`
	Detail     string `json:"detail,omitempty"`
}

AuthStatus is the resting state: is the agent authenticated, and via which method.

type Capabilities

type Capabilities struct {
	Negotiated    bool                       `json:"negotiated,omitempty"` // this session's native handshake is authoritative
	NativeVersion string                     `json:"nativeVersion,omitempty"`
	Protocol      Protocol                   `json:"protocol"` // cli | http | persistent | acp
	Output        OutputMode                 `json:"output"`
	History       Support                    `json:"history"`                 // CORE switch (messages endpoint)
	Sessions      Support                    `json:"sessions"`                // client hint
	Resume        bool                       `json:"resume"`                  // client hint
	Fork          bool                       `json:"fork,omitempty"`          // native edit-and-resend branching
	ToolEvents    bool                       `json:"toolEvents"`              // client hint
	Cancel        bool                       `json:"cancel"`                  // CORE switch (cancel endpoint)
	Persistent    bool                       `json:"persistent"`              // client hint: holds a live stdin process (else one-shot per turn)
	Models        bool                       `json:"models"`                  // client hint
	Commands      bool                       `json:"commands,omitempty"`      // GET /commands and native command dispatch
	NativeSession *NativeSessionCapabilities `json:"nativeSession,omitempty"` // attachment to an already-running native owner; per-session status is authoritative
	AuthLogout    bool                       `json:"authLogout,omitempty"`    // workspace-owned sign-out
	// ImageInput is a client hint: the agent delivers image attachments as TRUE vision content (the
	// model sees pixels), not just a path the model must open with a Read tool. Attachments themselves
	// are ungated (any agent may receive them); this only tells a UI whether images are seen natively.
	ImageInput bool `json:"imageInput"` // client hint: image attachments are sent as real vision input
	// Native audio is available when the selected model's input modalities include audio.
	// Other models/adapters retain the recording as an ordinary file.
	AudioInput bool `json:"audioInput,omitempty"`
	// Harness-native voice is a separate interface from model audio attachments.
	Voice *VoiceCapability `json:"voice,omitempty"`
	// User-in-loop ingress — each a CORE switch gating its route. The supervisor allocates a run's
	// inbound channel when any of these (or the runtime-control pair below) is set; the adapter must
	// pick a transport that can pump it.
	Respond     bool `json:"respond"`               // CORE switch: POST /runs/{id}/respond (answer an approval/question/plan)
	Input       bool `json:"input"`                 // CORE switch: POST /runs/{id}/input (inject a follow-up message mid-turn)
	QueuedInput bool `json:"queuedInput,omitempty"` // native acknowledgements and safe completion-boundary continuation
	Interrupt   bool `json:"interrupt"`             // CORE switch: POST /runs/{id}/interrupt (soft-stop, keeping the turn open)
	// Runtime controls require native acknowledgement. Unsupported controls,
	// rejected changes and timeouts return errors. Each flag gates its route.
	SetModel          bool `json:"setModel"`          // CORE switch: POST /runs/{id}/set-model (switch model mid-turn)
	SetPermissionMode bool `json:"setPermissionMode"` // CORE switch: POST /runs/{id}/set-permission-mode (switch permission mode mid-turn)
	// Turn-option support — whether the agent honors these per-turn inputs. Each a CORE switch gating
	// api.turn: a request carrying an option the selected agent can't honor gets a 400 (an honest
	// rejection) rather than a silent drop. SystemPrompt/AppendSystemPrompt cover the systemPrompt /
	// appendSystemPrompt inputs (typed TurnOptions.SystemPrompt OR the canon-addressed setting);
	// MCPServers covers TurnOptions.MCPServers. Declared per adapter so clients can also read them as
	// hints before sending.
	SystemPrompt       bool `json:"systemPrompt"`               // CORE switch (api.turn): honors a full system-prompt override
	BotProfiles        bool `json:"botProfiles"`                // CORE switch: refreshes saved bot instructions/tools on every new or resumed turn
	AppendSystemPrompt bool `json:"appendSystemPrompt"`         // CORE switch (api.turn): honors appending to the default system prompt
	MCPServers         bool `json:"mcpServers"`                 // CORE switch (api.turn): honors per-turn MCP server config
	StructuredOutput   bool `json:"structuredOutput,omitempty"` // CORE switch: honors outputSchema
	// Subagents / ClaudeSettings gate the two per-turn agent-native passthroughs (TurnOptions.Subagents,
	// TurnOptions.ClaudeSettings) exactly like MCPServers: an agent that can't honor the shape declares
	// false and api.turn 400s. Subagents = per-turn subagent defs (Claude --agents); ClaudeSettings = a
	// per-turn settings/hooks bundle (Claude --settings).
	Subagents      bool `json:"subagents"`      // CORE switch (api.turn): honors per-turn subagent definitions
	ClaudeSettings bool `json:"claudeSettings"` // CORE switch (api.turn): honors a per-turn settings/hooks bundle
	// Persistent prompt/memory surface — CLIENT hints that the agent exposes fetch+set for its
	// persistent artifacts, surfaced by GET /agent so a UI can show/hide the panels. The authoritative
	// gate is the type assertion in the API handler (agent.MemoryModule / agent.PromptsModule), not
	// these flags — an adapter that implements the module sets the matching flag true.
	Memory          bool `json:"memory"`          // agent exposes persistent memory files (CLAUDE.md / AGENTS.md) via /memory
	PromptTemplates bool `json:"promptTemplates"` // agent exposes saved prompt templates (slash-commands / saved prompts) via /prompts
	// SubagentDefs gates the persistent subagent-definition store (/subagents), type-asserted via
	// agent.SubagentsModule. DISTINCT from the per-turn Subagents passthrough above: Subagents honors a
	// per-turn --agents payload; SubagentDefs reads/writes the on-disk .claude/agents/*.md files. Claude-only.
	SubagentDefs bool `json:"subagentDefs"` // agent exposes persistent subagent definition files via /subagents
	// MCPConfig gates the persistent MCP-server config store (/mcp), type-asserted via
	// agent.MCPServerModule. DISTINCT from the per-turn MCPServers passthrough above: MCPServers honors a
	// per-turn --mcp-config payload for one turn; MCPConfig reads/writes the on-disk config the agent
	// loads on every run (Claude .claude.json / .mcp.json, Codex config.toml [mcp_servers.*]).
	MCPConfig bool `json:"mcpConfig"` // agent exposes persistent MCP-server config via /mcp
	// CustomProviders gates the custom-LLM-provider control plane (/providers), type-asserted via
	// agent.CustomProvidersModule. An agent that can point at a custom OpenAI-compatible endpoint
	// (opencode's opencode.json provider block, Codex's config.toml [model_providers.*]) implements the
	// module and sets this true; the registered provider's models then appear in /models (Custom:true)
	// and the secret flows only through EnvForRun (config carries an {env:VAR} placeholder, never the
	// key). Claude declares false — its custom-endpoint story is the gateway auth lane, not a provider
	// registry — so /providers 400s for it.
	CustomProviders      bool `json:"customProviders"`      // agent exposes custom-provider registration via /providers
	CustomProviderModels bool `json:"customProviderModels"` // registered provider/model routes per turn without changing native sign-in
	// CompactNow is a client hint that the agent supports on-demand conversation compaction via
	// POST /chats/{id}/compact. The authoritative gate is the type assertion agent.CompactModule in the
	// API handler, not this flag — an adapter that implements the module sets it true.
	CompactNow bool `json:"compactNow"` // agent supports on-demand compaction (POST /chats/{id}/compact)
	// Resolve is a client hint that the agent can run in GLOBAL-RESOLVE mode (POST /turns {mode:"resolve"}):
	// the daemon holds the run open and auto-continues the agent's own multi-step work until the task is
	// globally complete. UNLIKE the other CORE switches, resolve is NOT type-asserted or gated in the API —
	// it is pure daemon logic (the supervisor loops over the existing RunStream + session resume every
	// adapter already has), so every agent that can resume can be resolved. The flag is a UI hint only.
	Resolve bool `json:"resolve"` // agent supports global-resolve runs (POST /turns {mode:"resolve"})
}

Capabilities is the per-agent feature matrix. Two audiences read it:

  • the CORE switches behavior on some fields (native-vs-emulated). Today: History (Native → read the agent's transcript; else serve the recorded log), Cancel (gates POST /runs/{id}/cancel), the user-in-loop ingress trio Respond/Input/ Interrupt, and the runtime-control pair SetModel/SetPermissionMode (each gates its route exactly like Cancel). As emulation lands, more move here.
  • the CLIENT reads the rest as capability HINTS to shape its UI (Output, Sessions, Resume, ToolEvents, Persistent, Models). They are declared per agent so the app hardcodes nothing; the daemon does not yet branch on them.

Keeping this split explicit avoids the trap of a field that looks like a switch but nothing consults — add core branching when the emulation for that field exists.

type CatalogEntry

type CatalogEntry struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Tagline     string `json:"tagline"`
	BotProfiles bool   `json:"botProfiles"`
}

CatalogEntry is the minimum the create-screen picker needs (no schema).

func Catalog

func Catalog() []CatalogEntry

Catalog lists every agent this binary supports (for the app's picker), ID-ordered.

type Check

type Check struct {
	Name   string `json:"name"`
	Status string `json:"status"` // ok | warn | fail
	Detail string `json:"detail,omitempty"`
}

Check is one diagnostic result. The daemon's doctor aggregates generic daemon-level checks with each agent adapter's own checks (Adapter.Doctor) into one health report — so "doctor" is generic at the daemon and EXTENDED per agent.

func CLIDoctor

func CLIDoctor(ctx context.Context, name, versionCmd, _ string) []Check

CLIDoctor is the health check shared by every npm-distributed CLI adapter: is the CLI installed (and which version, via versionCmd), and is Node present (needed to install/update it via the toolchain). Installation hints use the daemon's tested policy, never an unversioned npm command. Adapters whose Doctor differs beyond these two checks append their own.

type Command

type Command struct {
	Name             string   `json:"name"`
	Label            string   `json:"label"`
	Description      string   `json:"description,omitempty"`
	Kind             string   `json:"kind"` // settings | compact | prompt | new_chat | history | rename
	Aliases          []string `json:"aliases,omitempty"`
	ArgumentHint     string   `json:"argumentHint,omitempty"`
	AcceptsArguments bool     `json:"acceptsArguments,omitempty"`
	SettingCanons    []string `json:"settingCanons,omitempty"`
	RequiresIdle     bool     `json:"requiresIdle,omitempty"`
	RequiresSession  bool     `json:"requiresSession,omitempty"`
	// Native dispatch details stay on the server. Clients send only the advertised name.
	Input     string `json:"-"`
	SkillPath string `json:"-"`
}

Command describes an action, a settings selector, or a native prompt/skill. Clients must route by Kind: a settings command is never sent to the model as ordinary text.

func FilterSettingsCommands

func FilterSettingsCommands(commands []Command, schema SettingsSchema) []Command

FilterSettingsCommands omits controls whose fields the installed CLI doesn't expose.

func (Command) Matches

func (c Command) Matches(name string) bool

type CommandCache

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

CommandCache performs bounded, on-demand, single-flight discovery. No idle worker, transcript reads or model requests. Account/config/cwd/executable changes get a new key.

func (*CommandCache) Get

func (c *CommandCache) Get(ctx context.Context, key string, refresh bool, fetch func(context.Context) (CommandCatalog, error)) (CommandCatalog, error)

type CommandCatalog

type CommandCatalog struct {
	Commands []Command `json:"commands"`
	Warning  string    `json:"warning,omitempty"`
}

type CommandInvocation

type CommandInvocation struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments,omitempty"`
}

func (CommandInvocation) Text

func (c CommandInvocation) Text() string

type CommandQuery

type CommandQuery struct {
	CWD     string
	Config  map[string]string
	Env     map[string]string
	Refresh bool `json:"-"`
}

type CommandsModule

type CommandsModule interface {
	Commands(context.Context, CommandQuery) (CommandCatalog, error)
}

CommandsModule discovers the installed harness's command surface without a model turn.

type CompactModule

type CompactModule interface {
	Compact(ctx context.Context, in TurnInput, emit Emit) (TurnResult, error)
}

CompactModule is an OPTIONAL adapter capability (type-asserted like MemoryModule, NOT bolted onto the mandatory Adapter interface): compact a chat's conversation ON DEMAND, folding prior context into a summary the agent carries forward. An adapter that implements it sets Capabilities.CompactNow=true; the API type-asserts THIS interface as the authoritative gate before serving POST /chats/{id}/compact.

It has the SAME shape as Adapter.RunStream so the supervisor drives it through the identical runner path — a compaction runs as a first-class RUN (its own run id + SSE stream) and the boundary is accumulated into the transcript with zero extra plumbing. The adapter emits the same EventCompaction the auto-compaction path does, so an on-demand compaction surfaces in the live stream and the reloaded history exactly like one the agent triggered itself.

in.Message carries any optional focus instructions (may be empty); the adapter prepends its own native trigger (Claude's /compact slash command, Codex's thread/compact/start RPC). in.SessionID is the conversation to compact — the API rejects a chat with no session yet, so an implementation may assume there is something to compact.

type CompactionInfo

type CompactionInfo struct {
	Trigger    string `json:"trigger,omitempty"`    // "auto" | "manual" (empty when the agent doesn't say)
	PreTokens  int    `json:"preTokens,omitempty"`  // context size before compaction
	PostTokens int    `json:"postTokens,omitempty"` // context size after compaction
	Summary    string `json:"summary,omitempty"`    // the continuation summary the agent wrote, when present
}

CompactionInfo describes a conversation compaction — auto (the agent hit its window and summarized on its own) or manual (an on-demand compact). It's the agent-agnostic payload for an EventCompaction event AND for a "compaction" transcript Part, so the SSE stream and reloaded history show a compaction the same way. Every field is best-effort: an agent that doesn't report token counts or a trigger leaves them zero/empty.

type Condition

type Condition string

Condition is a unified agent state worth notifying about.

const (
	Finished        Condition = "finished"         // turn completed
	Errored         Condition = "error"            // turn failed
	WaitingApproval Condition = "waiting_approval" // needs the user to approve a tool/edit to continue
	WaitingFeedback Condition = "waiting_feedback" // needs the user's answer to continue
	WaitingInput    Condition = "waiting_input"    // generic awaiting input
)

type ConditionUX

type ConditionUX struct {
	Condition Condition `json:"condition"`
	Title     string    `json:"title"`
	Actions   []Action  `json:"actions,omitempty"`
}

ConditionUX is an agent's per-condition notification UX.

type ConfiguredModelCatalogModule

type ConfiguredModelCatalogModule interface {
	ConfiguredModelCatalogProviders(store CredStore) []string
}

ConfiguredModelCatalogModule refines ModelCatalogModule for an adapter whose runnable catalog providers depend on credentials the user has connected. It lets the API expose that exact set to the client without putting catalog data or provider-specific credential logic in the daemon core.

An adapter implementing this interface is authoritative even when it returns an empty list: an empty result means it has no catalog-backed providers connected, not that the client should fall back to its static broad scope.

type ContinuationInfo

type ContinuationInfo struct {
	Iteration  int    `json:"iteration"`            // 0-based iteration index this boundary opens
	Reason     string `json:"reason,omitempty"`     // "start" | "continue" | "probe" | "max_turns" | "max_budget"
	ChildRunID string `json:"childRunId,omitempty"` // the child Run this iteration streams under (its own record in the tree)
	StopReason string `json:"stopReason,omitempty"` // set on the final boundary: "done" | "capped" | "error"
}

ContinuationInfo delimits one iteration of a resolve-mode run on the merged parent stream. The supervisor emits an EventContinuation before each child turn (and once at the caps boundary), so a client reading the parent topic can tell one sub-turn from the next and see WHY the loop advanced.

type CredStore

type CredStore interface {
	Get(key string) string
	Set(key, val string) error
	All() map[string]string
}

CredStore persists an agent's credentials/settings (backed by the daemon's state file).

type CustomProvider

type CustomProvider struct {
	ID      string   `json:"id"`                // provider id, e.g. "my-llm" (URL/config key)
	Name    string   `json:"name,omitempty"`    // human label; falls back to ID
	BaseURL string   `json:"baseUrl"`           // OpenAI-compatible base URL
	Models  []string `json:"models"`            // model ids offered by this endpoint
	EnvVar  string   `json:"envVar,omitempty"`  // primary env var the key is exported/referenced as; derived from ID when blank
	EnvVars []string `json:"envVars,omitempty"` // ALL env-var NAMES a secret is stored for (multi-var providers); NEVER the values
	HasKey  bool     `json:"hasKey"`            // whether a secret is stored (NEVER echoes the key itself)
}

CustomProvider is one registered custom-LLM provider, the canonical agent-agnostic shape. Every field but BaseURL/Models is omitempty so a round-trip carries only what a provider actually sets. The secret is NEVER part of this struct — it is supplied out-of-band on SetProvider and reported only as HasKey.

type CustomProvidersModule

type CustomProvidersModule interface {
	// ProviderScopes lists the scopes this agent's custom-provider config supports (opencode/Codex:
	// user only, matching where each harness reads global config).
	ProviderScopes() []MemoryScope
	// ListProviders returns the providers registered at a scope, keyed by id. dir is the resolved
	// project directory (used for project scope; ignored for user scope). A missing config file yields
	// an empty map — reads are forgiving. HasKey is filled from the store, never the config file.
	ListProviders(store CredStore, scope MemoryScope, dir string) (map[string]CustomProvider, error)
	// SetProvider registers one provider under p.ID at a scope, writing the harness config subtree
	// (base URL + model ids + an {env:VAR} placeholder) and preserving every sibling key. Two write-only
	// secret channels, both optional: apiKey is a single key the adapter exports under the derived/one env
	// var (custom endpoints, single-key catalog brands); secrets is a NAME→VALUE map for providers whose
	// catalog entry declares MULTIPLE env vars (e.g. AWS Bedrock's key/secret/region), each stored under
	// its own namespaced cred key. Passing neither leaves any previously stored secret intact (metadata-only
	// update). Replaces an existing entry of the same id.
	SetProvider(store CredStore, scope MemoryScope, dir, id string, p CustomProvider, apiKey string, secrets map[string]string) error
	// DeleteProvider removes one provider by id at a scope and clears its stored key. Removing an absent
	// provider is not an error (idempotent), so the caller can DELETE without a prior existence check.
	DeleteProvider(store CredStore, scope MemoryScope, dir, id string) error
}

CustomProvidersModule is an OPTIONAL adapter capability (type-asserted like MCPServerModule): list, set, and delete the agent's registered custom LLM providers across canonical scopes. An implementer sets Capabilities.CustomProviders=true; the API type-asserts this interface as the authoritative gate before serving /providers. A single-provider GET is served by listing the scope and indexing the map, so there is no separate read method.

Every method takes the per-agent CredStore because — unlike MCP config — provider registration touches a secret: SetProvider stashes the key, DeleteProvider clears it, and ListProviders reads it only to report HasKey. Adapters are stateless singletons, so the store is threaded in from the API handler (ag.Creds) rather than held on the adapter.

type Emit

type Emit func(Event)

Emit is how an adapter reports unified events during a turn.

type Event

type Event struct {
	Type EventType `json:"type"`
	// Sequence is assigned by the run hub, across all harnesses. Reconnect with
	// ?after=<sequence> to receive only unseen events. Replay marks buffered events
	// on an SSE connection; it is never set on newly published activity.
	Sequence int64 `json:"sequence,omitempty"`
	Replay   bool  `json:"replay,omitempty"`
	// ItemID correlates text/thinking snapshots with their streaming item. A non-delta
	// event replaces that item's text even if other components have arrived since it.
	ItemID       string            `json:"itemId,omitempty"`
	SessionID    string            `json:"sessionId,omitempty"`
	Text         string            `json:"text,omitempty"`
	Delta        bool              `json:"delta,omitempty"`
	Tokens       int               `json:"tokens,omitempty"` // cumulative token count for the block (e.g. thinking preview)
	Tool         *ToolEvent        `json:"tool,omitempty"`
	Result       *ResultInfo       `json:"result,omitempty"`
	Interaction  *Interaction      `json:"interaction,omitempty"`
	Compaction   *CompactionInfo   `json:"compaction,omitempty"`   // populated on EventCompaction
	Continuation *ContinuationInfo `json:"continuation,omitempty"` // populated on EventContinuation (resolve mode)
	Input        *UserInput        `json:"input,omitempty"`
	Capabilities *Capabilities     `json:"capabilities,omitempty"` // negotiated session features
	Task         *TaskInfo         `json:"task,omitempty"`
	Error        string            `json:"error,omitempty"`
	Meta         map[string]any    `json:"meta,omitempty"`
	At           string            `json:"at,omitempty"`
}

Event is the unified stream item. Optional fields are populated per Type.

type EventType

type EventType string

EventType is one kind of unified streaming event. Every adapter normalizes its agent's native output into these, so the client renders one stream regardless of agent.

const (
	EventSession      EventType = "session"     // session started; Meta has model/tools
	EventText         EventType = "text"        // assistant text (Delta=true for live tokens)
	EventThinking     EventType = "thinking"    // extended-thinking text
	EventToolUse      EventType = "tool_use"    // the agent invoked a tool
	EventToolResult   EventType = "tool_result" // a tool returned
	EventResult       EventType = "result"      // turn finished; Result has the final summary
	EventError        EventType = "error"
	EventStatus       EventType = "status"       // generic status (retry, queued, …) in Meta
	EventInput        EventType = "input"        // durable follow-up queued/accepted/failed
	EventTask         EventType = "task"         // native background task lifecycle
	EventInteraction  EventType = "interaction"  // structured agent-defined prompt/feedback (todos, approval, …)
	EventCompaction   EventType = "compaction"   // the conversation was compacted; Compaction has trigger + token counts
	EventContinuation EventType = "continuation" // resolve-mode iteration boundary; Continuation has the iteration + reason
)

type ExistingAuthConnection

type ExistingAuthConnection struct {
	Name  string `json:"name"`
	Model string `json:"model,omitempty"`
}

ExistingAuthConnection contains display metadata only. A saved connection is offered for reuse; its existence is not a claim that a credential is valid.

type ExistingAuthModule

type ExistingAuthModule interface {
	SetAuthSource(*AuthSource)
	ExistingMethod() *AuthMethod
	UseExisting(context.Context) (AuthState, error)
}

ExistingAuthModule is optional; adapters own native formats and verification. ManagedAuth uses it on first setup and exposes explicit reconnect through the ordinary methods -> begin -> status flow.

type Field

type Field struct {
	Key            string          `json:"key"`
	Label          string          `json:"label"`
	Type           FieldType       `json:"type"`
	Scope          Scope           `json:"scope,omitempty"` // unified | custom (taxonomy)
	Canon          string          `json:"canon,omitempty"` // stable cross-agent key; == Key for custom fields
	Required       bool            `json:"required,omitempty"`
	RequiredUnless []string        `json:"requiredUnless,omitempty"` // required unless any of these alternative field keys has a value
	Advanced       bool            `json:"advanced,omitempty"`       // optional/alternative inputs, initially collapsed by auth forms
	Placeholder    string          `json:"placeholder,omitempty"`
	Help           string          `json:"help,omitempty"`
	Options        []Option        `json:"options,omitempty"` // for select
	Default        string          `json:"default,omitempty"`
	VisibleWhen    *FieldCondition `json:"visibleWhen,omitempty"`
	Presentation   string          `json:"presentation,omitempty"` // select: segmented | menu; empty = native default
	InputMode      string          `json:"inputMode,omitempty"`    // text keyboard hint, e.g. url
	Minimum        *int64          `json:"minimum,omitempty"`      // inclusive integer limits for numeric text fields
	Maximum        *int64          `json:"maximum,omitempty"`
}

func MethodFields

func MethodFields(m AuthModule, id string) []Field

MethodFields returns the input fields for one of an AuthModule's method ids (empty for an unknown or interactive method). Adapters expose a field-based auth method's inputs through this without re-implementing the lookup.

type FieldCondition

type FieldCondition struct {
	Key    string `json:"key"`
	Equals string `json:"equals"`
}

FieldCondition makes a field active only for one value of another field. Clients resolve defaults first and omit inactive fields from submissions.

type FieldType

type FieldType string
const (
	FieldText   FieldType = "text"
	FieldSecret FieldType = "secret"      // masked input; persisted in the sandbox state via the auth flow, never returned to the client
	FieldSelect FieldType = "select"      // one-of, from Options
	FieldMulti  FieldType = "multiselect" // many-of, from Options (stored comma-joined)
	FieldToggle FieldType = "toggle"
)

type FileChange

type FileChange struct {
	Path    string `json:"path"`
	Op      string `json:"op,omitempty"`
	Diff    string `json:"diff,omitempty"`    // best-effort; absent when the agent doesn't supply enough
	OldText string `json:"oldText,omitempty"` // best-effort
	NewText string `json:"newText,omitempty"` // best-effort
}

FileChange is one file touched by a file_edit action. Op is "create" | "edit" | "delete". Diff (a best-effort unified diff), OldText, and NewText are all optional: present only when the agent supplies enough to compute them (e.g. Codex's live file_change reports path+op only, so Diff is empty there).

type ForkPoint

type ForkPoint struct {
	BeforeMessageID string `json:"beforeMessageId,omitempty"`
	ResumeAt        string `json:"resumeAt,omitempty"`
	Fresh           bool   `json:"fresh,omitempty"`
}

ForkPoint identifies a native history boundary immediately BEFORE a human message. ResumeAt is an opaque harness cursor (a turn ID or a message UUID). It is prepared from native history, never accepted from a client's options.

func PrepareFork

func PrepareFork(adapter Adapter, query HistoryQuery, before string) (ForkPoint, error)

type FoundryAuthSpec

type FoundryAuthSpec struct {
	Prefix                string
	ResourceDomain        string
	APIPath               string
	ModelPlaceholder      string
	AllowAzureCredentials bool
}

FoundryAuthSpec declares the entire form in the daemon, shared by adapters while keeping their endpoints and supported authentication methods distinct.

func (FoundryAuthSpec) Fields

func (s FoundryAuthSpec) Fields() []Field

func (FoundryAuthSpec) NormalizeInput

func (s FoundryAuthSpec) NormalizeInput(input map[string]string) (map[string]string, error)

NormalizeInput honors explicit choices. Requests from older clients have no selectors, so retain their URL/token precedence and Claude's Azure sign-in path.

func (FoundryAuthSpec) Sections

func (s FoundryAuthSpec) Sections() []AuthSection

type HandoffArtifact added in v0.1.54

type HandoffArtifact struct {
	Name       string `json:"name,omitempty"`
	Path       string `json:"path,omitempty"`
	ArtifactID string `json:"artifactId,omitempty"`
	Mime       string `json:"mime,omitempty"`
	Bytes      int    `json:"bytes,omitempty"`
	Available  bool   `json:"available"` // reference is usable on the same computer; no inline binary payload
}

type HandoffContext added in v0.1.54

type HandoffContext struct {
	Version  int             `json:"version"`
	Source   HandoffSource   `json:"source"`
	Goal     string          `json:"goal,omitempty"`
	Summary  *HandoffSummary `json:"summary,omitempty"`
	Tasks    []TodoItem      `json:"tasks,omitempty"`
	Turns    []HandoffTurn   `json:"turns,omitempty"`
	Losses   []HandoffLoss   `json:"losses,omitempty"`
	Reviewed bool            `json:"reviewed,omitempty"`
}

HandoffContext contains transferable task state, never native session state, credentials, permission grants, hidden reasoning or executable tool calls.

type HandoffEncoder added in v0.1.54

type HandoffEncoder interface {
	EncodeHandoff(HandoffContext, string) (HandoffInput, error)
}

type HandoffEnvelope added in v0.1.54

type HandoffEnvelope struct {
	Version     int            `json:"version"`
	Codec       string         `json:"codec"`
	TargetAgent string         `json:"targetAgent"`
	Task        string         `json:"task"`
	Context     HandoffContext `json:"context"`
}

func DecodeHandoffPrompt added in v0.1.54

func DecodeHandoffPrompt(message string) (HandoffEnvelope, error)

DecodeHandoffPrompt provides a strict round trip for receipts, fixtures and integrations inspecting a generated bootstrap; it never executes its content.

type HandoffHistory added in v0.1.54

type HandoffHistory struct {
	Messages  []Message
	Available bool
	Revision  string
	Losses    []HandoffLoss
}

HandoffHistory distinguishes an unavailable native transcript from an authoritative empty one (for example after undo). Neither is inferred from len.

func ReadHandoffSnapshot added in v0.1.54

func ReadHandoffSnapshot(ctx context.Context, a Adapter, q HistoryQuery, available bool) (HandoffHistory, error)

ReadHandoffSnapshot verifies that native files did not change while exporting. Availability is supplied by the adapter, not guessed from an empty transcript.

type HandoffHistoryProvider added in v0.1.54

type HandoffHistoryProvider interface {
	ExportHandoff(context.Context, HistoryQuery) (HandoffHistory, error)
}

type HandoffInput added in v0.1.54

type HandoffInput struct {
	Message string
	Codec   string
}

func EncodeHandoffPrompt added in v0.1.54

func EncodeHandoffPrompt(c HandoffContext, task, target, codec string) (HandoffInput, error)

EncodeHandoffPrompt is the common validated payload for native input codecs. Adapters deliver it through their ordinary user-input transport in a NEW session. It does not fabricate a vendor transcript or resume the source.

type HandoffLoss added in v0.1.54

type HandoffLoss struct {
	Code  string `json:"code"`
	Count int    `json:"count"`
}

type HandoffSource added in v0.1.54

type HandoffSource struct {
	AgentType string `json:"agentType"`
	ChatID    string `json:"chatId"`
	Title     string `json:"title,omitempty"`
	RunID     string `json:"runId,omitempty"`
	Revision  string `json:"revision"`
	History   string `json:"history"`
	Forked    bool   `json:"forked,omitempty"`
}

type HandoffSummary added in v0.1.54

type HandoffSummary struct {
	MessageID string `json:"messageId,omitempty"`
	Text      string `json:"text"`
}

type HandoffTool added in v0.1.54

type HandoffTool struct {
	Kind     ToolKind     `json:"kind"`
	Title    string       `json:"title,omitempty"`
	Status   string       `json:"status"`            // completed, failed, or unknown; absent output never means success
	Files    []FileChange `json:"files,omitempty"`   // paths and operations only, no raw edit bodies
	Command  string       `json:"command,omitempty"` // historical data, never replayed
	ExitCode *int         `json:"exitCode,omitempty"`
	Output   string       `json:"output,omitempty"` // bounded normalized result
}

type HandoffTurn added in v0.1.54

type HandoffTurn struct {
	ID        string            `json:"id,omitempty"`
	Role      string            `json:"role"`
	Text      string            `json:"text,omitempty"`
	Tools     []HandoffTool     `json:"tools,omitempty"`
	Artifacts []HandoffArtifact `json:"artifacts,omitempty"`
}

type HelpCache

type HelpCache struct {
	Command string   // binary to exec, e.g. "claude" or "codex"
	Args    []string // arguments, e.g. {"--help"} or {"exec", "--help"}
	// contains filtered or unexported fields
}

HelpCache memoizes the combined output of one CLI help invocation with a TTL, keeping the last good value if a refresh exec fails. Each distinct help surface (root vs a subcommand) is its own instance. Safe for concurrent use.

func (*HelpCache) Get

func (c *HelpCache) Get() string

Get returns the cached help text, refreshing it if the TTL has elapsed. A failed refresh leaves the previous value in place (so a transient CLI hiccup doesn't blank the settings enums).

type HistoryDeleter

type HistoryDeleter interface {
	DeleteHistory(q HistoryQuery) (removed bool, err error)
}

HistoryDeleter is an OPTIONAL adapter capability: the agent can delete a chat's native transcript — its source of truth on disk (Claude's projects/<slug>/<sid>.jsonl, Codex's rollout file). The API's DELETE /chats/{id} type-asserts this and, for every session the chat mapped to, removes the native file so a true delete leaves nothing behind. Adapters without it simply skip native deletion (the bookkeeping is still purged); a delete of an absent transcript is not an error.

The bool reports whether a transcript ACTUALLY existed and was removed. The caller lists an agent under `nativePurged` only when it returns (true, nil); a genuinely-absent transcript is (false, nil) and belongs to neither the purged nor the failed list — so a delete never falsely claims to have removed a file that was never there.

type HistoryQuery

type HistoryQuery struct {
	ChatID    string
	SessionID string
	CWD       string
	// Recorded is the daemon's transcript for this chat. Native readers may supplement
	// their transcript with streamed components the CLI does not persist, such as warnings.
	Recorded []Message
	Fork     *ForkPoint // pending fork: only return native history before this message
}

HistoryQuery locates a chat's native transcript (used when History == Native).

type HistoryRevisionProvider

type HistoryRevisionProvider interface {
	HistoryRevision(HistoryQuery) (string, error)
}

HistoryRevisionProvider opts native harnesses into conditional history reads. It must cover every transcript dependency, including native fork ancestors. An empty token or error asks the API to read history normally.

type Inbound

type Inbound struct {
	// Kind selects the ingress: "response" answers an interaction (approval / question / plan),
	// "input" injects a follow-up user message mid-turn, "interrupt" asks the agent to stop the
	// current action while keeping the turn open (softer than a hard cancel), "set_model" switches
	// the live turn's model (Text = model, empty ⇒ reset to default), "set_permission_mode" switches
	// its permission mode (Text = mode). The last two are runtime control, not a reply to any
	// interaction, and only reach a persistent transport.
	Kind string `json:"kind"`
	// InteractionID is the interaction being answered (Kind=="response"): the Interaction.ID the
	// adapter emitted — a control-request id for approvals, a tool_use id for questions/plans.
	InteractionID string `json:"interactionId,omitempty"`
	// Decision is the chosen action id: "allow"/"deny" for an approval, "approve"/"reject" for a plan,
	// or a single selected option id for a choice.
	Decision string `json:"decision,omitempty"`
	// Options are the selected option ids for a multi-select question.
	Options []string `json:"options,omitempty"`
	// Text is free-text input, a deny reason, or a free-text answer.
	Text    string                    `json:"text,omitempty"`
	Answers map[string]QuestionAnswer `json:"answers,omitempty"`
	// Internal correlators never come from a client's request body.
	Interaction *Interaction `json:"-"`
	// Buffered acknowledgement for native controls and message-question steering.
	// When supplied for input, an adapter must report acceptance or failure; merely
	// writing to stdin is not acceptance. ErrInputClosed means no input was submitted.
	Ack       chan error `json:"-"`
	ControlID string     `json:"-"`
	// Input is a durable follow-up receipt. Adapters acknowledge it only after
	// their native protocol accepts the message, using AcknowledgeInput.
	Input *UserInput `json:"-"`
	// Meta is the adapter's own correlators, copied verbatim from the interaction's Meta by the
	// supervisor and handed back so the adapter can encode the native response without server state
	// (e.g. respondVia, toolUseId).
	Meta map[string]string `json:"meta,omitempty"`
}

Inbound is one piece of mid-turn ingress from the user, addressed to a running turn. It is the generic, agent-agnostic counterpart to the Interaction the adapter surfaces: the client answers an interaction (or steers/interrupts the turn) and the daemon hands the adapter this value to encode onto its native control channel. The adapter reads the correlators it stashed in Interaction.Meta back out of Meta here (echoed unchanged by the supervisor), so the encoding stays stateless.

type Interaction

type Interaction struct {
	ID            string     `json:"id,omitempty"`
	Kind          string     `json:"kind"`
	Title         string     `json:"title,omitempty"`
	Detail        string     `json:"detail,omitempty"`
	Items         []TodoItem `json:"items,omitempty"`     // kind=todos
	Options       []Action   `json:"options,omitempty"`   // kind=approval|choice|select|plan
	Questions     []Question `json:"questions,omitempty"` // one form, answered atomically
	Blocking      *bool      `json:"blocking,omitempty"`  // nil means a pending request blocks
	Feedback      string     `json:"feedback,omitempty"`  // approval text: "always" or "rejection"; empty = unsupported
	NeedsResponse bool       `json:"needsResponse,omitempty"`
	// Message questions are non-blocking harness messages, not native control requests.
	// They remain answerable after the originating turn ends. The daemon owns RunID and
	// Response, including persistence and delivery as steering or a resumed user turn.
	ResponseMode string               `json:"responseMode,omitempty"` // "message"; empty = native control
	RunID        string               `json:"runId,omitempty"`
	Response     *InteractionResponse `json:"response,omitempty"`
	Meta         map[string]any       `json:"meta,omitempty"`
}

Interaction is a structured, self-describing request the agent surfaces mid-turn for the client to render generically — and, when NeedsResponse, for the user to answer. Each adapter maps its agent's native signals onto these kinds; the client switches on Kind, so a new kind needs no client release to at least render its title/detail.

todos    — a checklist (Items)                  Claude: TodoWrite
approval — approve/reject a tool/edit (Options)
form     — one or more questions answered together (Questions)
choice   — pick one of Options
select   — pick many of Options
input    — free-text answer
plan     — a proposed plan to accept (Detail + Options)

func (Interaction) AnswerText

func (it Interaction) AnswerText(reply InteractionResponse) string

AnswerText is used only for native async questions, whose reply transport is an ordinary user message. Native control forms retain their structured RPC response.

func (Interaction) IsMessageQuestion

func (it Interaction) IsMessageQuestion() bool

func (Interaction) ValidateResponse

func (it Interaction) ValidateResponse(reply InteractionResponse) (InteractionResponse, error)

ValidateResponse rejects incomplete forms and unknown decisions before any harness can interpret an empty or misspelled approval as permission to execute a tool.

type InteractionResponse

type InteractionResponse struct {
	InteractionID string                    `json:"interactionId"`
	Decision      string                    `json:"decision,omitempty"`
	Options       []string                  `json:"options,omitempty"`
	Text          string                    `json:"text,omitempty"`
	Answers       map[string]QuestionAnswer `json:"answers,omitempty"`
}

type MCPCall

type MCPCall struct {
	Server string `json:"server,omitempty"`
	Tool   string `json:"tool,omitempty"`
}

MCPCall identifies an MCP server tool invocation.

type MCPServer

type MCPServer struct {
	Command           string            `json:"command,omitempty"`
	Args              []string          `json:"args,omitempty"`
	Env               map[string]string `json:"env,omitempty"`
	Cwd               string            `json:"cwd,omitempty"`
	URL               string            `json:"url,omitempty"`
	BearerTokenEnvVar string            `json:"bearerTokenEnvVar,omitempty"`
	HTTPHeaders       map[string]string `json:"httpHeaders,omitempty"`
	// Codex's per-server native approval mode: auto, prompt, writes, or approve.
	// Other adapters retain their native permission rules.
	DefaultToolsApprovalMode string `json:"defaultToolsApprovalMode,omitempty"`
}

MCPServer is one persistent MCP-server definition, the canonical agent-agnostic shape (promoted from the codex per-turn transcode). Two forms: stdio (Command/Args/Env/Cwd) and streamable-HTTP (URL/BearerTokenEnvVar/HTTPHeaders). Every field is omitempty so a round-trip carries only what a server actually sets.

type MCPServerModule

type MCPServerModule interface {
	// MCPScopes lists the scopes this agent's persistent MCP config supports (Claude: project + user;
	// Codex: user only).
	MCPScopes() []MemoryScope
	// ListMCPServers returns the servers configured at a scope, keyed by name. dir is the resolved
	// project directory (used for project scope; ignored for user scope). A missing config file yields
	// an empty map — reads are forgiving.
	ListMCPServers(scope MemoryScope, dir string) (map[string]MCPServer, error)
	// SetMCPServer writes one server under name at a scope (creating the config file / directory as
	// needed), preserving every other server AND all sibling config. Replaces an existing entry of the
	// same name.
	SetMCPServer(scope MemoryScope, dir, name string, server MCPServer) error
	// DeleteMCPServer removes one server by name at a scope. Removing an absent server is not an error
	// (idempotent), so the caller can DELETE without a prior existence check.
	DeleteMCPServer(scope MemoryScope, dir, name string) error
}

MCPServerModule is an OPTIONAL adapter capability (type-asserted like MemoryModule): list, set, and delete the agent's persistent MCP-server config across canonical scopes. An implementer sets Capabilities.MCPConfig=true; the API type-asserts this interface as the authoritative gate before serving /mcp. Claude (project + user) and Codex (user only) implement it. A single-server GET is served by listing the scope and indexing the map, so there is no separate read method.

type ManagedAuth

type ManagedAuth struct {
	AuthModule
	// contains filtered or unexported fields
}

ManagedAuth reuses a trusted host connection on first setup and keeps explicit sign-out authoritative across clients and daemon restarts. After sign-out, only completing a new authentication flow reconnects the harness.

func ManageAuth

func ManageAuth(auth AuthModule, store CredStore) *ManagedAuth

func (*ManagedAuth) Active

func (m *ManagedAuth) Active() bool

func (*ManagedAuth) Begin

func (m *ManagedAuth) Begin(ctx context.Context, method string) (AuthState, error)

func (*ManagedAuth) Disconnected

func (m *ManagedAuth) Disconnected() bool

func (*ManagedAuth) DiscoverMethods added in v0.1.60

func (m *ManagedAuth) DiscoverMethods(ctx context.Context) ([]AuthMethod, error)

func (*ManagedAuth) EnvForRun

func (m *ManagedAuth) EnvForRun() map[string]string

func (*ManagedAuth) Logout

func (m *ManagedAuth) Logout(ctx context.Context) error

func (*ManagedAuth) Methods

func (m *ManagedAuth) Methods() []AuthMethod

func (*ManagedAuth) PrepareAuth

func (m *ManagedAuth) PrepareAuth(ctx context.Context) error

PrepareAuth takes the same first-use path as Status, without repeating native status commands on subsequent turns. An absent host login remains discoverable later, but an existing choice or failed import needs explicit user action.

func (*ManagedAuth) SetAuthSource

func (m *ManagedAuth) SetAuthSource(source *AuthSource)

SetAuthSource binds trusted host configuration at startup. Native adapters own format/keychain discovery; the shared auth layer owns first-use and sign-out.

func (*ManagedAuth) Status

func (m *ManagedAuth) Status(ctx context.Context) AuthStatus

func (*ManagedAuth) Step

func (m *ManagedAuth) Step(ctx context.Context, input map[string]string) (AuthState, error)

type MemoryDoc

type MemoryDoc struct {
	Scope   MemoryScope `json:"scope"`
	Path    string      `json:"path"`
	Exists  bool        `json:"exists"`
	Content string      `json:"content"`
}

MemoryDoc is one persistent memory file (Claude's CLAUDE.md / Codex's AGENTS.md) at a canonical scope. Path is ALWAYS populated — even when the file is absent — so a client can show where a memory would be written; Exists distinguishes an empty file from a missing one.

type MemoryLayout

type MemoryLayout struct {
	// MemoryFile is the basename of the persistent memory file (e.g. "CLAUDE.md", "AGENTS.md"), placed
	// directly in the project dir (project scope) or the user config home (user scope).
	MemoryFile string
	// UserBase is the agent's user config home (e.g. ~/.claude, ~/.codex); "" when it can't be resolved
	// (no home), which drops the user scope.
	UserBase string
	// ProjectPromptDir is the prompt-template directory RELATIVE to a project dir (e.g.
	// ".claude/commands"); "" means the agent has no project-scope templates.
	ProjectPromptDir string
	// UserPromptDir is the prompt-template directory relative to UserBase (e.g. "commands", "prompts");
	// "" means no user-scope templates.
	UserPromptDir string
}

MemoryLayout describes WHERE one adapter's persistent memory and prompt-template files live, so the read/write/list logic is shared (DRY) across adapters — the same philosophy as helpers.go. Its methods implement the whole MemoryModule + PromptsModule surface; an adapter builds a layout PER CALL (resolving its config home lazily, so a test that sets CLAUDE_CONFIG_DIR / CODEX_HOME after init sees the change) and delegates each module method straight to the matching layout method.

func (MemoryLayout) DeleteMemory

func (l MemoryLayout) DeleteMemory(scope MemoryScope, dir string) (MemoryDoc, error)

DeleteMemory removes the scope's memory file and returns the resulting doc (Exists=false). Removing an absent file is not an error (idempotent) — the post-state is "no memory" either way.

func (MemoryLayout) DeletePrompt

func (l MemoryLayout) DeletePrompt(scope MemoryScope, dir, name string) error

DeletePrompt removes one template. Removing an absent template (or from a missing directory) is not an error (idempotent) — the post-state is "no such template" either way.

func (MemoryLayout) ListPrompts

func (l MemoryLayout) ListPrompts(dir string) ([]PromptTemplate, error)

ListPrompts enumerates every "*.md" template across the supported scopes with Content omitted. A missing directory contributes nothing (reads are forgiving); any other read error is returned.

func (MemoryLayout) MemoryScopes

func (l MemoryLayout) MemoryScopes() []MemoryScope

MemoryScopes lists the memory scopes this layout supports: project whenever a memory file is declared, user additionally when the config home resolved.

func (MemoryLayout) PromptScopes

func (l MemoryLayout) PromptScopes() []MemoryScope

PromptScopes lists the prompt-template scopes this layout supports: project when ProjectPromptDir is set, user when UserPromptDir is set and the config home resolved.

func (MemoryLayout) ReadMemory

func (l MemoryLayout) ReadMemory(scope MemoryScope, dir string) (MemoryDoc, error)

ReadMemory returns the scope's memory doc. A missing file is not an error (Exists=false).

func (MemoryLayout) ReadPrompt

func (l MemoryLayout) ReadPrompt(scope MemoryScope, dir, name string) (PromptTemplate, error)

ReadPrompt returns one template's full content. A missing file bubbles up an fs.ErrNotExist error.

func (MemoryLayout) WriteMemory

func (l MemoryLayout) WriteMemory(scope MemoryScope, dir, content string) (MemoryDoc, error)

WriteMemory writes content to the scope's memory file. For user scope the config home is created (0700); for project scope the project dir must already exist (a memory file is never a reason to create a project tree), so a missing dir surfaces as an error.

func (MemoryLayout) WritePrompt

func (l MemoryLayout) WritePrompt(scope MemoryScope, dir, name, content string) (PromptTemplate, error)

WritePrompt writes a template. The user prompt dir is created (0700 tree); a project prompt dir is created (0755) only when the project dir already exists — the project tree itself is never created.

type MemoryModule

type MemoryModule interface {
	// MemoryScopes lists the scopes this agent's memory supports (project and/or user).
	MemoryScopes() []MemoryScope
	// ReadMemory returns the memory doc for a scope. dir is the resolved project directory (used for
	// project scope; ignored for user scope). A MISSING file is not an error — Exists is false and
	// Content is "".
	ReadMemory(scope MemoryScope, dir string) (MemoryDoc, error)
	// WriteMemory writes content to the scope's memory file (creating the user config home if needed;
	// the project dir must already exist) and returns the resulting doc.
	WriteMemory(scope MemoryScope, dir, content string) (MemoryDoc, error)
	// DeleteMemory removes the scope's memory file and returns the resulting doc (Exists=false).
	// Removing an absent file is not an error (idempotent) — the post-state is "no memory" either way.
	DeleteMemory(scope MemoryScope, dir string) (MemoryDoc, error)
}

MemoryModule is an OPTIONAL adapter capability (type-asserted like Titler, not part of the mandatory Adapter interface): read and write the agent's persistent memory file across canonical scopes. An adapter that implements it sets Capabilities.Memory=true; the API type-asserts this interface as the authoritative gate before serving /memory.

type MemoryScope

type MemoryScope string

MemoryScope is the canonical, agent-agnostic location of a persistent artifact. It is a DIFFERENT axis from Scope (schema.go), which is the settings-field taxonomy (unified|custom) — hence the distinct name. A scope answers "whose file is this": tied to a working directory (project) or the agent's own config home (user).

const (
	// MemoryProject is an artifact inside a working directory — Claude's CLAUDE.md, Codex's AGENTS.md,
	// a project slash-command — shared with anyone working in that tree.
	MemoryProject MemoryScope = "project"
	// MemoryUser is an artifact in the agent's config home (~/.claude, ~/.codex) — it applies to every
	// project the user runs that agent in.
	MemoryUser MemoryScope = "user"
)

type Message

type Message struct {
	Command      *CommandInvocation `json:"command,omitempty"` // identifies an explicitly selected command for native-history reconciliation
	ID           string             `json:"id"`
	ChatID       string             `json:"chatId"`
	Role         string             `json:"role"` // "user" | "assistant"
	Text         string             `json:"text"`
	CreatedAt    string             `json:"createdAt"`
	NativeTurnID string             `json:"nativeTurnId,omitempty"` // correlates native history with a live owner snapshot
	Parts        []Part             `json:"parts,omitempty"`
	Attachments  []Attachment       `json:"attachments,omitempty"`
	CanFork      bool               `json:"canFork,omitempty"`
	ForkPoint    *ForkPoint         `json:"-"` // native cursor; clients send only the message ID
}

Message is a chat message in the unified shape served to the client. `Text` stays the joined visible text (back-compat: chat titles, old clients). `Parts` is the ordered rich transcript — text / thinking / tool — that the app renders as inline cards; omitempty so it's absent for user and text-only messages and pre-parts clients simply ignore it.

func ForkHistory

func ForkHistory(messages []Message, point *ForkPoint) ([]Message, error)

ForkHistory prevents a deferred fork from showing the source's discarded suffix. Recorded input belongs to the NEW chat and is merged by the caller after this cut. A missing boundary fails closed instead of showing the future.

func MergeRecordedHistory

func MergeRecordedHistory(native, recorded []Message) []Message

Codex does not persist every app-server notification. Keep its authoritative item snapshots and imported turns, adding recorded warnings, failures and partial output within the matching user turn. Matching is chronological so repeated prompts cannot consume an earlier reply; compaction boundaries stay separate messages.

func NormalizeSurfaceHistory

func NormalizeSurfaceHistory(messages []Message) []Message

func SurfaceRecords

func SurfaceRecords(messages []Message) []Message

Other adapters can retain only service-origin additions without changing their normal native history merge policy. User boundaries anchor repeated prompts.

type ModelCatalogModule

type ModelCatalogModule interface {
	ModelCatalogProviders() []string
}

ModelCatalogModule is an OPTIONAL adapter capability: declare which models.dev catalog providers this agent's models come from. Because the daemon no longer ships the models.dev catalog, an agent that cannot self-enumerate a full list instead names its provider scope here, and the client — which owns the live catalog — sources the model picker from those providers and enriches every model by (provider, id). The sentinel "*" means "all providers" (a provider-agnostic agent like opencode, which uses models.dev as its own registry). An adapter that self-enumerates its complete list (Claude's account API) need not implement this: its returned models already carry Provider, so the client enriches them, and an empty account list stays honestly empty rather than dumping the whole catalog. Surfaced as `modelProviders` on GET /agent.

type ModelCost

type ModelCost struct {
	Input      float64 `json:"input,omitempty"`
	Output     float64 `json:"output,omitempty"`
	CacheRead  float64 `json:"cacheRead,omitempty"`
	CacheWrite float64 `json:"cacheWrite,omitempty"`
}

ModelCost is per-million-token pricing for a model, in USD. Every field is omitempty so a model with unknown pricing carries no cost block at all.

type ModelInfo

type ModelInfo struct {
	ID    string `json:"id"`
	Label string `json:"label"`

	// Provider is the harness/catalog provider id that runs this model (e.g. "anthropic", "openai").
	// It makes provider-binding explicit: claude-code runs anthropic, codex runs openai-compatible,
	// opencode is provider-agnostic, so the catalog is agent-scoped rather than a flat global list.
	Provider string `json:"provider,omitempty"`

	// Context/MaxOut are the model's context-window and max-output token limits (catalog limit.context
	// / limit.output). Modalities list the accepted input and produced output kinds ("text","image",…).
	Context int      `json:"contextWindow,omitempty"`
	MaxOut  int      `json:"maxOutput,omitempty"`
	Input   []string `json:"inputModalities,omitempty"`
	Output  []string `json:"outputModalities,omitempty"`

	// Reasoning/ToolCall/Attachment are capability flags from the catalog.
	Reasoning              bool     `json:"reasoning,omitempty"`
	ReasoningEfforts       []Option `json:"reasoningEfforts,omitempty"`
	DefaultReasoningEffort string   `json:"defaultReasoningEffort,omitempty"`
	Default                bool     `json:"default,omitempty"`
	ToolCall               bool     `json:"toolCall,omitempty"`
	Attachment             bool     `json:"attachment,omitempty"`

	// Cost is per-million-token pricing when the catalog knows it.
	Cost *ModelCost `json:"cost,omitempty"`

	// Custom marks a model sourced from a client-registered custom provider (see CustomProvidersModule)
	// rather than the built-in catalog. Such a model's metadata is typically sparse (a custom endpoint
	// isn't in the on-disk catalog), so only ID/Provider/Custom are populated — surfaced honestly.
	Custom bool `json:"custom,omitempty"`
}

ModelInfo is one model an agent can run: its API id plus a human label, plus provider-aware metadata when the source knows it. The daemon populates only what an adapter enumerates natively (id, label, provider); the richer fields (context, cost, modalities, capability flags) are filled CLIENT-SIDE from the live models.dev catalog the SDK owns. It is the public, agent-agnostic shape of a model choice, served by GET /models. Every field beyond ID/Label is omitempty so the wire stays byte-compatible: an adapter that emits exactly {id,label,provider} is normal, and the client enriches by (provider, id).

type ModelsModule

type ModelsModule interface {
	// Models returns the models the agent enumerates NATIVELY — Claude fetches them from the Anthropic
	// account API, opencode shells `opencode models`. env carries the run credentials (from
	// AuthModule.EnvForRun) so an adapter that fetches its list from a provider API authenticates as the
	// configured account. mindwire no longer stores the models.dev catalog in the daemon (the client owns
	// it and fetches it live), so an adapter returns only what it truly knows locally — no catalog
	// enrichment, no catalog-sourced list. An EMPTY list (no credentials, offline, no scriptable list) is
	// not an error: it degrades to "unknown", and the client fills the picker from the live catalog for
	// the providers named by ModelCatalogModule.
	Models(env map[string]string) ([]ModelInfo, error)
}

ModelsModule is an OPTIONAL adapter capability (type-asserted like Titler): enumerate the models available to the configured account. An adapter that implements it sets Capabilities.Models=true; the API type-asserts this interface as the authoritative gate before serving /models.

type NativeArchive

type NativeArchive struct {
	Version   int          `json:"version"`
	Harness   string       `json:"harness"`
	SessionID string       `json:"sessionId"`
	Files     []NativeFile `json:"-"`
}

type NativeFile

type NativeFile struct {
	Name      string // adapter-relative, validated again by ImportSessionPath
	Path      string
	JSONLines bool // normalize only structured cwd fields; preserve unknown records
	Resource  bool // selected native database record, applied through SessionDataPorter
	Data      []byte
}

func ArchiveTree

func ArchiveTree(ctx context.Context, path, prefix string) ([]NativeFile, error)

ArchiveTree includes every regular auxiliary file, including unknown future file types. Special files and links fail explicitly instead of disappearing.

type NativeSession

type NativeSession struct {
	ID        string
	CWD       string
	Title     string
	CreatedAt string
	UpdatedAt string
	// Some harness versions expose both a thread ID and a session ID.
	Aliases []string
}

NativeSession is a reference to a harness-owned conversation, never a copy of its messages. ID is passed unchanged to the adapter's existing resume/history.

type NativeSessionAction

type NativeSessionAction struct {
	ConnectionID   string               `json:"connectionId"`
	RequestID      string               `json:"requestId"`
	Kind           string               `json:"kind"` // input | interrupt | response
	ExpectedTurnID string               `json:"expectedTurnId,omitempty"`
	Text           string               `json:"text,omitempty"`
	Attachments    []Attachment         `json:"attachments,omitempty"`
	Response       *InteractionResponse `json:"response,omitempty"`
}

ConnectionID is supplied by the daemon and makes retries fail closed after an attachment expires/restarts. RequestID deduplicates commands on that connection. ExpectedTurnID prevents Stop/steer from targeting a newer turn after a race.

type NativeSessionCapabilities

type NativeSessionCapabilities struct {
	Status    bool `json:"status"`
	Observe   bool `json:"observe"`
	Input     bool `json:"input"`
	Interrupt bool `json:"interrupt"`
	Respond   bool `json:"respond"`
}

type NativeSessionConnection

type NativeSessionConnection interface {
	Initial() NativeSessionInitial
	Updates() <-chan NativeSessionUpdate
	Action(context.Context, NativeSessionAction) (NativeSessionReceipt, error)
	Close()
}

type NativeSessionError

type NativeSessionError struct {
	Code    string `json:"code"`
	Message string `json:"error"`
}

NativeSessionError is safe for clients. Adapters must not include raw logs or credentials. An unknown outcome must never be silently retried as a new send.

func (*NativeSessionError) Error

func (e *NativeSessionError) Error() string

type NativeSessionInitial

type NativeSessionInitial struct {
	Activity        SessionActivity
	Events          []Event
	TurnID          string
	HistoryRequired bool
}

type NativeSessionModule

type NativeSessionModule interface {
	SessionActivity(context.Context, NativeSessionQuery) (SessionActivity, error)
	OpenNativeSession(context.Context, NativeSessionQuery) (NativeSessionConnection, error)
}

NativeSessionModule attaches to an existing harness owner. Opening or closing a viewer must never start a turn, replace a process, or change its configuration. History continues through the existing native History/HistoryPager interfaces.

type NativeSessionQuery

type NativeSessionQuery struct {
	SessionID string
	CWD       string
}

type NativeSessionReceipt

type NativeSessionReceipt struct {
	RequestID string `json:"requestId"`
	Status    string `json:"status"` // accepted | submitted (answer written; await native resolution)
	TurnID    string `json:"turnId,omitempty"`
}

type NativeSessionUpdate

type NativeSessionUpdate struct {
	Activity       *SessionActivity `json:"activity,omitempty"`
	Event          *Event           `json:"event,omitempty"`
	TurnID         string           `json:"turnId,omitempty"`
	Reset          bool             `json:"reset,omitempty"`
	HistoryChanged bool             `json:"historyChanged,omitempty"`
	Partial        bool             `json:"partial,omitempty"` // projection omits earlier/oversized items; merge native history
}

NativeSessionUpdate is ordered by the native connection. Initial contains a bounded recent-turn seed; Updates begins strictly after that native snapshot. Reset starts a new turn. HistoryChanged asks a client to use the ordinary paginated history API (e.g. a read-only harness has appended its transcript).

type NativeSettingsModule

type NativeSettingsModule interface {
	NativeSettings(CredStore) map[string]string
}

NativeSettingsModule reports declared non-secret defaults from the harness's own config. Managed overrides take precedence; an empty override resets to the native default. The client never needs to parse harness config files.

type Notification

type Notification struct {
	Condition   Condition `json:"condition"`
	Title       string    `json:"title"`
	Body        string    `json:"body"`
	Agent       string    `json:"agent,omitempty"`
	BotID       string    `json:"botId,omitempty"`
	BotName     string    `json:"botName,omitempty"`
	BotIcon     string    `json:"botIcon,omitempty"`
	WorkspaceID string    `json:"workspaceId,omitempty"`
	ChatID      string    `json:"chatId,omitempty"`
	RunID       string    `json:"runId,omitempty"`
	AppID       string    `json:"appId,omitempty"`
	AppName     string    `json:"appName,omitempty"`
	AppIcon     string    `json:"appIcon,omitempty"`
	EventID     string    `json:"eventId,omitempty"`
	Actions     []Action  `json:"actions,omitempty"`
}

Notification is the unified payload the daemon emits; the webhook receiver fans it out.

type NotificationSpec

type NotificationSpec struct {
	Conditions []ConditionUX `json:"conditions"`
}

NotificationSpec is the set of conditions an agent declares + their UX.

func (NotificationSpec) For

For returns the declared UX for a condition, if any.

type NotifyChannel

type NotifyChannel struct {
	ID      string            `json:"id"`
	Type    NotifyChannelType `json:"type"`
	Label   string            `json:"label,omitempty"`
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers,omitempty"` // extra request headers (values are secret)
	Token   string            `json:"token,omitempty"`   // sent as Authorization: Bearer <token>
	Secret  string            `json:"secret,omitempty"`  // webhook type only: HMAC-SHA256 signing key
	Enabled bool              `json:"enabled"`
}

NotifyChannel is one named delivery target: a webhook URL plus optional auth (custom headers, a bearer token, and — for the webhook type — an HMAC signing secret). The daemon owns the list and persists it; a rule references channels by ID. Token/Secret/Headers are secrets: the API masks them on read and merge-preserves them on write.

type NotifyChannelType

type NotifyChannelType string

NotifyChannelType is the delivery shape of a notification channel. It selects only how the outgoing payload is framed — every type is ultimately an HTTP POST to a URL the client owns.

const (
	ChannelWebhook  NotifyChannelType = "webhook"  // raw Notification JSON (optionally HMAC-signed)
	ChannelPush     NotifyChannelType = "push"     // title/body plus string-valued data for push relays
	ChannelSlack    NotifyChannelType = "slack"    // {"text": "<title>\n<body>"} — Slack incoming webhook
	ChannelDiscord  NotifyChannelType = "discord"  // {"content": "<title>\n<body>"} — Discord webhook
	ChannelTelegram NotifyChannelType = "telegram" // {"text": "<title>\n<body>"} — bot sendMessage URL
)

type NotifyRule

type NotifyRule struct {
	ID         string          `json:"id"`
	Scope      NotifyRuleScope `json:"scope"`
	Agent      string          `json:"agent,omitempty"`   // scope=agent: the adapter type to match
	Session    string          `json:"session,omitempty"` // scope=session: the chatId to match
	Conditions []Condition     `json:"conditions,omitempty"`
	ChannelIDs []string        `json:"channelIds"`
	Enabled    bool            `json:"enabled"`
}

NotifyRule routes matching notifications to a set of channels. A rule fires when it is enabled, the notification's condition is in Conditions (empty = all conditions), and its scope matches: global always; agent when Agent == n.Agent; session when Session == n.ChatID.

func (NotifyRule) Matches

func (r NotifyRule) Matches(n Notification) bool

Matches reports whether this rule should route the given notification.

type NotifyRuleScope

type NotifyRuleScope string

NotifyRuleScope selects which notifications a rule applies to by origin.

const (
	ScopeGlobal  NotifyRuleScope = "global"  // every notification
	ScopeAgent   NotifyRuleScope = "agent"   // only notifications from a given agent (adapter type)
	ScopeSession NotifyRuleScope = "session" // only notifications from a given chat/session (ChatID)
)

type Option

type Option struct {
	Value string `json:"value"`
	Label string `json:"label"`
	Help  string `json:"help,omitempty"` // shown when this option is selected
}

type OutputMode

type OutputMode string

OutputMode is how an agent emits a turn's output.

const (
	// OutputStructuredJSON: the CLI emits structured JSON we map to unified events.
	OutputStructuredJSON OutputMode = "structured_json"
	// OutputTerminal: plain/ANSI terminal output → a terminal-to-structured converter (later).
	OutputTerminal OutputMode = "terminal"
)

type Part

type Part struct {
	Task        *TaskInfo       `json:"task,omitempty"`
	Type        string          `json:"type"`                 // "text" | "thinking" | "tool" | "interaction" | "compaction"
	ID          string          `json:"id,omitempty"`         // streaming item identity, when supplied
	Text        string          `json:"text,omitempty"`       // body for text / thinking
	DurationMs  int             `json:"durationMs,omitempty"` // thinking window, or tool duration
	Tokens      int             `json:"tokens,omitempty"`     // thinking-token estimate (Claude Code's preview counter)
	Tool        *ToolPart       `json:"tool,omitempty"`
	Interaction *Interaction    `json:"interaction,omitempty"` // structured prompt (todos / plan / choice / …)
	Compaction  *CompactionInfo `json:"compaction,omitempty"`  // set on a "compaction" part (a conversation boundary)
	Input       *UserInput      `json:"input,omitempty"`       // accepted follow-up boundary within a live run
	At          string          `json:"at,omitempty"`
}

Part is one ordered piece of an assistant turn. A `tool` part pairs the tool_use and its tool_result on one `Tool` payload (keyed by tool-use id) so the wire shape matches the app's DaemonMessagePart/DaemonToolCall exactly.

func UpgradeAsyncQuestionParts

func UpgradeAsyncQuestionParts(parts []Part, forms map[string]Interaction) []Part

UpgradeAsyncQuestionParts replaces legacy notices only when the actual native structured form is available. One form replaces all of its old question rows and their duplicated native text. Used by both native history and state migration.

type PromptTemplate

type PromptTemplate struct {
	Name    string      `json:"name"`
	Scope   MemoryScope `json:"scope"`
	Path    string      `json:"path"`
	Content string      `json:"content,omitempty"`
}

PromptTemplate is one saved, reusable prompt — a Claude custom slash-command (.claude/commands/<name>.md) or a Codex saved prompt (~/.codex/prompts/<name>.md). Name is the bare template name (no directory, no ".md" suffix); Content is omitted from LIST results and populated only on a single READ, so listing stays cheap.

type PromptsModule

type PromptsModule interface {
	// PromptScopes lists the scopes this agent's templates support. Claude supports both project and
	// user; Codex supports user only (a project-scope op → unsupported-scope error).
	PromptScopes() []MemoryScope
	// ListPrompts returns every template across the supported scopes with Content omitted. dir is the
	// resolved project directory. A missing directory yields NO entries for that scope (reads are
	// forgiving; only writes fail on a missing directory).
	ListPrompts(dir string) ([]PromptTemplate, error)
	// ReadPrompt returns one template's full content. A missing template returns an error satisfying
	// errors.Is(err, fs.ErrNotExist), which the API maps to 404.
	ReadPrompt(scope MemoryScope, dir, name string) (PromptTemplate, error)
	// WritePrompt writes a template (creating the prompt directory as needed) and returns it.
	WritePrompt(scope MemoryScope, dir, name, content string) (PromptTemplate, error)
	// DeletePrompt removes one template. Removing an absent template (or from a missing directory) is
	// not an error (idempotent) — the post-state is "no such template" either way.
	DeletePrompt(scope MemoryScope, dir, name string) error
}

PromptsModule is an OPTIONAL adapter capability (type-asserted like Titler): list, read, and write the agent's saved prompt templates. An adapter that implements it sets Capabilities.PromptTemplates=true; the API type-asserts this interface as the authoritative gate before serving /prompts.

type Protocol

type Protocol string

Protocol is how the daemon DRIVES the agent for a turn — the control channel, orthogonal to Output (the result format). Declared per adapter; the adapter's RunStream composes the matching driver (internal/driver). CLI is the universal fallback — any agent that ships only a command line uses it; agents with a native REST/SSE API or a persistent protocol declare those and implement driver.Driver directly. The core never branches on this; it only reads unified events.

const (
	ProtocolCLI        Protocol = "cli"        // spawn the agent CLI per turn (Claude: claude -p)
	ProtocolHTTP       Protocol = "http"       // call the agent's native REST/SSE API
	ProtocolACP        Protocol = "acp"        // native Agent Client Protocol over stdio
	ProtocolPersistent Protocol = "persistent" // a long-lived process spoken to over a protocol
)

type Question

type Question struct {
	ID          string   `json:"id"`
	Title       string   `json:"title"`
	Header      string   `json:"header,omitempty"`
	Options     []Action `json:"options,omitempty"`
	MultiSelect bool     `json:"multiSelect,omitempty"`
	AllowOther  bool     `json:"allowOther,omitempty"`
	IsSecret    bool     `json:"isSecret,omitempty"`
	Optional    bool     `json:"optional,omitempty"`
}

Question retains the harness's stable id, descriptions and selection rules. Text may accompany selected options as feedback; AllowOther also permits text alone.

type QuestionAnswer

type QuestionAnswer struct {
	Options []string `json:"options,omitempty"`
	Text    string   `json:"text,omitempty"`
}

type ResultInfo

type ResultInfo struct {
	Text      string  `json:"text,omitempty"`
	IsError   bool    `json:"isError,omitempty"`
	Cancelled bool    `json:"cancelled,omitempty"`
	SessionID string  `json:"sessionId,omitempty"`
	CostUSD   float64 `json:"costUsd,omitempty"`
	// Usage is best-effort per-turn token accounting, sitting alongside CostUSD. Nil when the agent
	// reported no token counts for the turn (additive wire field).
	Usage      *Usage `json:"usage,omitempty"`
	NumTurns   int    `json:"numTurns,omitempty"`
	DurationMS int    `json:"durationMs,omitempty"`
	// Subtype is the agent's own terminal-result classifier when it distinguishes one (Claude's
	// result subtype: "success", "error_max_turns", "error_max_budget_usd", …). Empty for agents
	// whose terminal event is always fully settled (Codex). Continuable(Subtype) reports whether it
	// means "stopped short but resumable" — the signal the resolve loop drives on.
	Subtype string `json:"subtype,omitempty"`
	// Incomplete is a derived convenience: true when the turn stopped short on a continuable subtype
	// (i.e. Continuable(Subtype)). A resolve iteration reads it to decide whether to auto-resume.
	Incomplete bool `json:"incomplete,omitempty"`
}

type Scope

type Scope string

Scope marks whether a field is a UNIFIED cross-agent concept — one every agent has some form of (model, permission mode, system prompt) — or a CUSTOM agent-specific one. Unified fields carry a stable Canon key (see canon.go) the client addresses regardless of which agent is selected; the adapter maps that canon to its own key/flag. Custom fields are still typed & declared (shipped in a daemon build, never open passthrough) and conventionally set Canon == Key. This split is the normalization contract: the unified surface is a closed, declared vocabulary, and everything agent-specific is explicitly marked as such.

const (
	ScopeUnified Scope = "unified"
	ScopeCustom  Scope = "custom"
)

type SearchQuery

type SearchQuery struct {
	Query string `json:"query,omitempty"`
	Path  string `json:"path,omitempty"`
	Glob  string `json:"glob,omitempty"`
}

SearchQuery is a workspace-search action (grep/glob). Fields are populated as the tool supplies them.

type Section

type Section struct {
	Title  string  `json:"title"`
	Fields []Field `json:"fields"`
}

Section groups fields under a heading (the app renders one group per section).

type SessionActivity

type SessionActivity struct {
	SessionID    string                    `json:"sessionId"`
	CWD          string                    `json:"cwd"`
	Owner        string                    `json:"owner"` // native | none | unknown
	State        string                    `json:"state"` // running | waiting | idle | stopped | unavailable
	TurnID       string                    `json:"turnId,omitempty"`
	StartedAt    string                    `json:"startedAt,omitempty"`
	Reason       string                    `json:"reason,omitempty"`
	Capabilities NativeSessionCapabilities `json:"capabilities"`
}

func NativeSessionUnavailable

func NativeSessionUnavailable(q NativeSessionQuery, reason string) SessionActivity

type SessionDataPorter

type SessionDataPorter interface {
	ValidSessionDataName(string) bool
	ReadSessionData(context.Context, string, string, string) ([]byte, error)
	ValidateSessionData(context.Context, string, string, string, []byte) error
	ApplySessionData(context.Context, string, string, string, []byte, []byte) error
}

SessionDataPorter transports selected database-backed context without copying an entire database over the destination's unrelated sessions or credentials.

type SessionLister

type SessionLister interface {
	ListSessions(ctx context.Context, cwd string) ([]NativeSession, error)
}

SessionLister is optional. Listing is read-only: it must not start a turn, create a session, install a CLI, or change the harness's authentication. CWD selects one exact project directory, including its filesystem aliases. An empty CWD lists all folders. Every result retains its original directory.

type SessionPorter

type SessionPorter interface {
	ExportSession(context.Context, string, string) (NativeArchive, error) // cwd, native ID
	ImportSessionPath(cwd, sessionID, name string) (string, error)
}

SessionPorter describes selected native files; the shared sync engine owns hashing, transport, merging and recoverable installation for every harness. It never exports an entire home or replaces a harness database/configuration.

type SettingsSchema

type SettingsSchema struct {
	Sections []Section `json:"sections"`
}

type ShellCommand

type ShellCommand struct {
	Command  string `json:"command,omitempty"`
	Cwd      string `json:"cwd,omitempty"`
	Stdout   string `json:"stdout,omitempty"`
	Stderr   string `json:"stderr,omitempty"`   // best-effort; nil pointer ⇒ not reported (≠ "")
	ExitCode *int   `json:"exitCode,omitempty"` // best-effort; nil ⇒ not reported (≠ 0)
}

ShellCommand is a shell action. Stderr and ExitCode are POINTERS: nil means the agent didn't report them (Claude's Bash tool merges stderr into stdout and never surfaces an exit code), which is distinct from an empty stderr or exit 0. Stdout is the combined/aggregated output as the agent gave it.

type Step

type Step struct {
	Name        string                                `json:"name"`
	Check       string                                `json:"-"`
	Install     string                                `json:"-"`
	Requires    []string                              `json:"-"`
	CheckFunc   func(context.Context) (string, error) `json:"-"`
	InstallFunc func(context.Context) (string, error) `json:"-"`
}

Step is one ensure-or-install in an agent's toolchain. Check runs first (exit 0 = already satisfied); otherwise Install runs. Requires names other tools (catalog or sibling steps) that must be satisfied BEFORE this one, so the resolver can order dependencies-first and dedup shared tools across agents. Shell commands aren't serialized to the app — install is the daemon's job.

type Subagent

type Subagent struct {
	Name    string        `json:"name"`
	Scope   MemoryScope   `json:"scope"`
	Path    string        `json:"path"`
	Content string        `json:"content,omitempty"`
	Meta    *SubagentMeta `json:"meta,omitempty"`
}

Subagent is one persistent subagent definition file (Claude .claude/agents/<name>.md). Content is the canonical raw file body — omitted from LIST results and populated only on a single READ/WRITE, so listing stays cheap. Meta is the parsed convenience view (nil when the file has no usable frontmatter). Name is the definition's identity: its frontmatter `name` when present, else the filename stem.

type SubagentLayout

type SubagentLayout struct {
	// ProjectDir is the definitions directory RELATIVE to a project dir (e.g. ".claude/agents"); ""
	// means the agent has no project-scope definitions.
	ProjectDir string
	// UserDir is the ABSOLUTE definitions directory for the user scope (e.g. "<config home>/agents"); ""
	// (unresolved config home, or no user scope) drops the user scope.
	UserDir string
}

SubagentLayout describes WHERE one adapter's persistent subagent definition files live, so the read/write/list logic is shared (DRY) across adapters — the same philosophy as MemoryLayout. It is a dedicated layout (not folded into MemoryLayout) because subagent stores diverge in two ways: they are scanned RECURSIVELY (a definition may sit in a nested folder), and a definition's identity comes from its frontmatter `name` rather than its filename. An adapter builds a layout PER CALL (resolving its config home lazily) and delegates each SubagentsModule method to the matching layout method.

func (SubagentLayout) DeleteSubagent

func (l SubagentLayout) DeleteSubagent(scope MemoryScope, dir, name string) error

DeleteSubagent removes the definition in the scope whose identity matches name — the SAME match ReadSubagent uses (frontmatter `name`, else filename stem), so a nested file is found and removed. Removing an absent definition is not an error (idempotent).

func (SubagentLayout) ListSubagents

func (l SubagentLayout) ListSubagents(dir string) ([]Subagent, error)

ListSubagents enumerates every definition across the supported scopes with Content omitted (Meta populated). A missing directory contributes nothing; any other read error is returned.

func (SubagentLayout) ReadSubagent

func (l SubagentLayout) ReadSubagent(scope MemoryScope, dir, name string) (Subagent, error)

ReadSubagent returns the first definition in the scope whose identity (frontmatter name, else filename stem) matches name, with full raw Content + parsed Meta. A missing definition returns fs.ErrNotExist.

func (SubagentLayout) SubagentScopes

func (l SubagentLayout) SubagentScopes() []MemoryScope

SubagentScopes lists the scopes this layout supports: project when ProjectDir is set, user when UserDir is set.

func (SubagentLayout) WriteSubagent

func (l SubagentLayout) WriteSubagent(scope MemoryScope, dir, name, content string) (Subagent, error)

WriteSubagent writes a definition verbatim to "<scopeDir>/<name>.md" (flat top-level, even though reads recurse). The user dir is created (0700 tree); a project dir is created (0755) only when the project dir already exists — the project tree itself is never created.

type SubagentMeta

type SubagentMeta struct {
	Name        string   `json:"name,omitempty"`
	Description string   `json:"description,omitempty"`
	Tools       []string `json:"tools,omitempty"`
	Model       string   `json:"model,omitempty"`
}

SubagentMeta is the best-effort parsed view of a subagent definition's YAML-ish frontmatter. It is a CONVENIENCE only — the raw Content of a Subagent is the canonical, lossless unit. Every field is optional (omitempty); a definition with no parseable frontmatter yields a nil *SubagentMeta.

type SubagentsModule

type SubagentsModule interface {
	// SubagentScopes lists the scopes this agent's subagent definitions support (Claude: project + user).
	SubagentScopes() []MemoryScope
	// ListSubagents returns every definition across the supported scopes with Content omitted (Meta
	// populated). dir is the resolved project directory. A missing scope directory yields NO entries for
	// that scope (reads are forgiving; only writes fail on a missing project directory).
	ListSubagents(dir string) ([]Subagent, error)
	// ReadSubagent returns one definition's full raw Content plus parsed Meta. A missing definition
	// returns an error satisfying errors.Is(err, fs.ErrNotExist), which the API maps to 404.
	ReadSubagent(scope MemoryScope, dir, name string) (Subagent, error)
	// WriteSubagent writes a definition verbatim (creating the scope directory as needed) and returns it.
	WriteSubagent(scope MemoryScope, dir, name, content string) (Subagent, error)
	// DeleteSubagent removes the definition in the scope whose identity matches name (the same match
	// ReadSubagent uses, so a nested file is found). Removing an absent definition is not an error
	// (idempotent).
	DeleteSubagent(scope MemoryScope, dir, name string) error
}

SubagentsModule is an OPTIONAL adapter capability (type-asserted like PromptsModule): list, read, and write the agent's persistent subagent definition files. Distinct from the per-turn Subagents passthrough (Capabilities.Subagents / TurnOptions.Subagents) — this is the on-disk definition store. An implementer sets Capabilities.SubagentDefs=true; the API type-asserts this interface as the authoritative gate before serving /subagents. Claude-only today.

type Support

type Support string

Support says whether an agent provides a feature natively, needs the core to emulate it, or doesn't have it. The hybrid rule: Native → use the agent; Emulated → the core implements it (e.g. records the relayed stream for history).

const (
	SupportNone     Support = "none"
	SupportNative   Support = "native"
	SupportEmulated Support = "emulated"
)

type SurfaceToolAction

type SurfaceToolAction struct {
	SurfaceID string              `json:"surfaceId"`
	DesktopID string              `json:"desktopId,omitempty"`
	Operation string              `json:"operation"`
	SessionID string              `json:"sessionId,omitempty"`
	ReceiptID string              `json:"receiptId,omitempty"`
	Status    string              `json:"status,omitempty"`
	Capture   *SurfaceToolCapture `json:"capture,omitempty"`
}

SurfaceToolAction is shared by live events and saved tool cards. Images are durable artifact references; base64 image/clipboard content stays out of feeds.

type SurfaceToolCapture

type SurfaceToolCapture struct {
	ID         string `json:"id"`
	ArtifactID string `json:"artifactId"`
	Width      int    `json:"width"`
	Height     int    `json:"height"`
}

type TaskInfo added in v0.1.60

type TaskInfo struct {
	ID       string `json:"id"`
	ParentID string `json:"parentId,omitempty"`
	Kind     string `json:"kind,omitempty"`
	Title    string `json:"title,omitempty"`
	Status   string `json:"status"`
	Output   string `json:"output,omitempty"`
}

TaskInfo reports native work whose lifetime can extend past the foreground response. A launch acknowledgement is not a completed task.

type TaskTracker added in v0.1.60

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

func (*TaskTracker) Active added in v0.1.60

func (t *TaskTracker) Active() bool

func (*TaskTracker) Get added in v0.1.60

func (t *TaskTracker) Get(id string) TaskInfo

func (*TaskTracker) Update added in v0.1.60

func (t *TaskTracker) Update(task TaskInfo, start bool) bool

type TempFiles

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

TempFiles accumulates temp files written while materializing a turn's options so a single deferred Cleanup removes them all. The zero value is ready to use; bind Cleanup as the caller's deferred cleanup before the first Write so partial failures still tidy up.

func (*TempFiles) Cleanup

func (t *TempFiles) Cleanup()

Cleanup removes every temp file Write created. Safe to call on the zero value and to defer even when a later step errors.

func (*TempFiles) Write

func (t *TempFiles) Write(pattern string, data []byte) (string, error)

Write creates a temp file matching pattern (os.CreateTemp semantics), writes data, records the path for Cleanup, and returns it. A write error still leaves the (empty) file recorded for cleanup.

type Titler

type Titler interface {
	// Title returns the agent's current title for the chat, or "" if none yet (best-effort;
	// any lookup error → "" so the caller keeps its fallback).
	Title(q HistoryQuery) string
}

Titler is an OPTIONAL adapter capability: the agent owns an auto-generated chat title in its native data (e.g. Claude Code writes an `ai-title` record into its transcript). When an adapter implements this, the API prefers its title over the daemon's derived first-message snippet, so the list shows the agent's own naming. Adapters without it simply keep the derived fallback.

type TodoItem

type TodoItem struct {
	Content string `json:"content"`
	Status  string `json:"status"` // pending | in_progress | completed
}

TodoItem is one entry of a todos interaction (mirrors Claude's TodoWrite shape).

type ToolAction

type ToolAction struct {
	Surface *SurfaceToolAction `json:"surface,omitempty"`
	Kind    ToolKind           `json:"kind"`
	Title   string             `json:"title,omitempty"` // short human label (e.g. the command, the path)
	Files   []FileChange       `json:"files,omitempty"`
	Shell   *ShellCommand      `json:"shell,omitempty"`
	Search  *SearchQuery       `json:"search,omitempty"`
	Web     *WebSearch         `json:"web,omitempty"`
	MCP     *MCPCall           `json:"mcp,omitempty"`
}

ToolAction is the normalized view of a tool call. Only the sub-object matching Kind is populated; the rest stay nil/empty. It attaches to both ToolEvent (live stream) and ToolPart (transcript) as the same pointer type, so use and result carry the progressively-completed same shape.

func (*ToolAction) SameInvocation

func (a *ToolAction) SameInvocation(b *ToolAction) bool

SameInvocation compares the work a tool was asked to do, excluding output and display labels. Live streams and native transcripts can have different IDs and progressively richer results. Callers still match chronologically, so two executions of the same command remain two calls.

type ToolEvent

type ToolEvent struct {
	ID      string `json:"id,omitempty"`
	Name    string `json:"name,omitempty"`
	Input   any    `json:"input,omitempty"`
	Output  string `json:"output,omitempty"`
	IsError bool   `json:"isError,omitempty"`
	Status  string `json:"status,omitempty"` // native completed/failed/cancelled; incomplete is not success
	// Action is the deep-normalized view of this tool call (canonical kind + structured payload),
	// carried alongside the raw Input/Output. Best-effort and optional: nil when the adapter can't
	// classify the tool. See toolaction.go.
	Action *ToolAction `json:"action,omitempty"`
}

type ToolKind

type ToolKind string

ToolKind is the canonical, agent-independent classification of a tool call.

const (
	KindFileEdit  ToolKind = "file_edit"  // create / edit / delete a file
	KindFileRead  ToolKind = "file_read"  // read a file
	KindShell     ToolKind = "shell"      // run a shell command
	KindSearch    ToolKind = "search"     // search the workspace (grep / glob)
	KindWebSearch ToolKind = "web_search" // search the web
	KindWebFetch  ToolKind = "web_fetch"  // fetch a URL
	KindMCP       ToolKind = "mcp"        // an MCP server tool call
	KindOther     ToolKind = "other"      // anything not yet classified
)

type ToolPart

type ToolPart struct {
	ID      string          `json:"id,omitempty"`
	Name    string          `json:"name,omitempty"`
	Input   json.RawMessage `json:"input,omitempty"`
	Output  string          `json:"output,omitempty"`
	IsError bool            `json:"isError,omitempty"`
	// Status is explicit native outcome evidence. Empty or in-progress is unknown.
	Status string `json:"status,omitempty"`
	// Action is the deep-normalized view of the tool call (same pointer type as ToolEvent.Action). The
	// runner sets it from the tool_use, then overwrites with the completed action (with output) at the
	// tool_result. Best-effort/optional; nil when unclassified. See toolaction.go.
	Action *ToolAction `json:"action,omitempty"`
}

ToolPart is a paired tool call (use + result).

type ToolchainModule

type ToolchainModule interface {
	Toolchain() toolchain.Spec
}

ToolchainModule opts a CLI adapter into the shared, versioned installation policy.

type TurnInput

type TurnInput struct {
	Message   string
	SessionID string            // the agent's own session id (for resume), if any
	CWD       string            // project dir inside the sandbox
	Config    map[string]string // settings (non-secret), e.g. model — per-turn overrides already folded in
	Env       map[string]string // runtime env from the AuthModule (e.g. ANTHROPIC_API_KEY)
	Options   TurnOptions       // per-turn structured options (Settings already resolved into Config)
	Fork      *ForkPoint        // durable, server-prepared native branch boundary
	Command   *Command          // server-resolved native dispatch; never accepted as a client path
	// Inbound carries the user's mid-turn ingress — permission answers, follow-up input, interrupts —
	// for a turn that pauses (user-in-loop). It is receive-only for the adapter and nil for the one-shot
	// hot path; an adapter that pauses picks a persistent transport and pumps these to the live process.
	// The supervisor owns the send end (Respond/SendInput/Interrupt); it is closed at turn end.
	Inbound <-chan Inbound
	Voice   *VoiceBridge // ephemeral microphone/speaker channel; never persisted
}

TurnInput is one chat turn's parameters.

func PrepareCommand

func PrepareCommand(ctx context.Context, adapter Adapter, in TurnInput) (TurnInput, error)

PrepareCommand resolves against fresh-enough native metadata, including exact skill paths. A stale/unsupported selection fails explicitly instead of becoming a model prompt.

type TurnOptions

type TurnOptions struct {
	Command *CommandInvocation `json:"command,omitempty"` // explicit native command/skill selected from GET /commands
	// Settings are per-turn overrides addressed by CANONICAL key. Consumed by the runner (the single
	// security choke point); cleared before the adapter sees TurnInput. A client says "reasoningEffort"
	// regardless of which agent runs.
	Settings map[string]string `json:"settings,omitempty"`

	// SystemPrompt fully REPLACES the agent's default system prompt for this turn (distinct from the
	// sticky appendSystemPrompt, which augments it). Per-turn overrides the sticky system-prompt setting.
	SystemPrompt string `json:"systemPrompt,omitempty"`
	// ContextInstructions is daemon-owned additive context (a saved bot's identity,
	// memory and tools). It must never replace a harness's native system prompt.
	// Recomputed from the registry on each turn; excluded from public turn receipts.
	ContextInstructions string `json:"-"`
	// SkillsRoot is a private, turn-scoped bundle supplied by the bot service.
	// Harness adapters may discover its skills without changing global settings.
	SkillsRoot string `json:"-"`

	// Session controls (precedence resolved by the adapter): SessionID pins an explicit session id for
	// this turn; ContinueLatest resumes the most recent session in the cwd; ForkOnResume branches a new
	// session id from the resumed one instead of continuing it in place.
	SessionID      string `json:"sessionId,omitempty"`
	ContinueLatest bool   `json:"continueLatest,omitempty"`
	ForkOnResume   bool   `json:"forkOnResume,omitempty"`

	// Structured unified fields the flat string map can't express. The runner passes these through
	// untouched; the adapter materializes them to per-turn temp files in RunStream (defer-cleaned).
	OutputSchema json.RawMessage `json:"outputSchema,omitempty"` // JSON Schema for structured output
	MCPServers   json.RawMessage `json:"mcpServers,omitempty"`   // MCP servers config object

	// Subagents defines per-turn subagents in the selected agent's native shape (e.g. Claude's
	// `--agents` inline JSON: {name:{description,prompt,…}}). ClaudeSettings is a per-turn settings
	// bundle in that agent's native format (e.g. Claude's `--settings`, where hooks/permissions/env
	// live). Both are opaque, agent-native passthroughs like MCPServers — an agent that can't honor the
	// shape declares the matching capability false, so api.turn 400s rather than silently dropping.
	Subagents      json.RawMessage `json:"subagents,omitempty"`      // subagent definitions (Claude --agents)
	ClaudeSettings json.RawMessage `json:"claudeSettings,omitempty"` // settings/hooks bundle (Claude --settings)

	Attachments []Attachment  `json:"attachments,omitempty"` // files referenced from the message
	Voice       *VoiceOptions `json:"voice,omitempty"`       // explicit native voice conversation
}

TurnOptions carries per-turn parameters distinct from the agent's sticky settings. It is a value type on TurnInput, so existing one-shot callers that leave it zero are unchanged. Two layers:

(a) Settings — per-turn setting OVERRIDES addressed by CANON (see canon.go). The runner resolves
    each canon→the selected agent's field key, drops secrets/unknowns, and overlays them onto the
    sticky Config (overrides win). By the time an adapter sees TurnInput, these are already folded
    into Config and Options.Settings is cleared — adapters read overrides from Config, never here.
(b) Typed structured unified fields the flat string map can't express — system prompt, session
    controls (and, from Stage 3, output schema / MCP config / attachments).

type TurnResult

type TurnResult struct {
	Text      string
	SessionID string
	IsError   bool
	Cancelled bool // the harness stopped the turn at the user's request
	// Subtype is the agent's terminal-result classifier when it has one (Claude's result subtype).
	// Empty for agents whose terminal event is always settled (Codex). Continuable(Subtype) reports
	// whether it means "stopped short but resumable" — the signal the resolve loop drives on.
	Subtype string
}

TurnResult is the final outcome of a turn (the stream carries the detail).

type Usage

type Usage struct {
	InputTokens      int `json:"inputTokens,omitempty"`
	OutputTokens     int `json:"outputTokens,omitempty"`
	CacheReadTokens  int `json:"cacheReadTokens,omitempty"`
	CacheWriteTokens int `json:"cacheWriteTokens,omitempty"`
	ReasoningTokens  int `json:"reasoningTokens,omitempty"`
	TotalTokens      int `json:"totalTokens,omitempty"`
}

Usage is best-effort per-turn token accounting. All fields omitempty (additive wire field).

type UserInput

type UserInput struct {
	ID          string       `json:"id"`
	Text        string       `json:"text"`
	Attachments []Attachment `json:"attachments,omitempty"`
	CreatedAt   string       `json:"createdAt"`
	Status      string       `json:"status"` // queued | accepted | failed | cancelled
	Error       string       `json:"error,omitempty"`
}

UserInput is a follow-up owned by the running conversation, not by a connected client. Its ID is also the retry receipt. Native transcripts remain authoritative.

type VoiceAudio

type VoiceAudio struct {
	Data       []byte `json:"data"`
	SampleRate int    `json:"sampleRate"`
	Channels   int    `json:"channels"`
}

PCM16 little-endian, mono, 24 kHz. Native adapters resample only when their protocol requires it. Audio bytes never enter the durable transcript/event hub.

type VoiceBridge

type VoiceBridge struct {
	ClientID string
	Commands chan VoiceCommand
	Stop     <-chan struct{}
	// contains filtered or unexported fields
}

VoiceBridge is a bounded, ephemeral media channel owned by one live run. A disconnect ends microphone access, not the coding task already in progress. No idle daemon polling, replay of spoken commands, or audio files are involved.

func NewVoiceBridge

func NewVoiceBridge(clientID string) *VoiceBridge

func (*VoiceBridge) Close

func (v *VoiceBridge) Close()

func (*VoiceBridge) EndInput

func (v *VoiceBridge) EndInput()

func (*VoiceBridge) InputOpen

func (v *VoiceBridge) InputOpen() bool

func (*VoiceBridge) Publish

func (v *VoiceBridge) Publish(event VoiceEvent)

func (*VoiceBridge) Send

func (v *VoiceBridge) Send(ctx context.Context, sequence int64, audio VoiceAudio) error

Send accepts strictly ordered microphone batches. The receipt is recorded before enqueueing, so a lost HTTP acknowledgement cannot duplicate speech.

func (*VoiceBridge) Subscribe

func (v *VoiceBridge) Subscribe() (VoiceEvent, <-chan VoiceEvent, func(), error)

func (*VoiceBridge) Touch

func (v *VoiceBridge) Touch() error

type VoiceCapability

type VoiceCapability struct {
	Mode    string  `json:"mode"` // conversation, dictation, or none
	Support Support `json:"support"`
	Remote  bool    `json:"remote"`
	Detail  string  `json:"detail,omitempty"`
}

Voice describes the harness interface, independently of a coding model's audio attachment modalities. Local-only dictation is not a remote microphone API.

type VoiceCommand

type VoiceCommand struct {
	Audio *VoiceAudio
	Ack   chan error
}

type VoiceEvent

type VoiceEvent struct {
	Type   string      `json:"type"` // ready, audio, transcript, listening, error, closed
	Audio  *VoiceAudio `json:"audio,omitempty"`
	Text   string      `json:"text,omitempty"`
	Role   string      `json:"role,omitempty"`
	ItemID string      `json:"itemId,omitempty"`
	Final  bool        `json:"final,omitempty"`
}

type VoiceModule

type VoiceModule interface {
	VoiceStatus(context.Context, CredStore) (VoiceStatus, error)
}

VoiceModule probes the selected harness on demand. This must not start a voice session, record audio, change authentication, or call the coding model.

type VoiceOptions

type VoiceOptions struct {
	ClientID string `json:"clientId"`
	Voice    string `json:"voice,omitempty"`
}

type VoiceStatus

type VoiceStatus struct {
	Capability VoiceCapability `json:"capability"`
	Available  bool            `json:"available"`
	Code       string          `json:"code,omitempty"`
	Detail     string          `json:"detail,omitempty"`
	Voices     []string        `json:"voices,omitempty"`
}

type WebSearch

type WebSearch struct {
	Query string `json:"query,omitempty"`
	URL   string `json:"url,omitempty"`
}

WebSearch covers both a web search (Query) and a URL fetch (URL); Kind on the parent disambiguates.

Directories

Path Synopsis
Package antigravity drives Google's official ACP runtime and companion harness.
Package antigravity drives Google's official ACP runtime and companion harness.
Package claude is the Claude Code adapter.
Package claude is the Claude Code adapter.
Package codex is the OpenAI Codex CLI adapter — mindwire's second agent, proving the architecture's promise that adding an agent is one new adapter with zero core or client changes.
Package codex is the OpenAI Codex CLI adapter — mindwire's second agent, proving the architecture's promise that adding an agent is one new adapter with zero core or client changes.
Package cursor drives Cursor's official ACP CLI, independently of its IDE.
Package cursor drives Cursor's official ACP CLI, independently of its IDE.
Package grok drives xAI's open-source Grok Build CLI in its documented headless mode.
Package grok drives xAI's open-source Grok Build CLI in its documented headless mode.
Package opencode is the SST opencode adapter — mindwire's third agent, and the first driven over a native HTTP + SSE API rather than a one-shot CLI.
Package opencode is the SST opencode adapter — mindwire's third agent, and the first driven over a native HTTP + SSE API rather than a one-shot CLI.

Jump to

Keyboard shortcuts

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