orchestrator

package
v0.1.53 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: Apache-2.0 Imports: 29 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 orchestrator is the daemon's per-sandbox SUPERVISOR. It hosts every registered agent adapter as an Agent runtime (adapter + auth + per-turn runner + namespaced cred/config view), routes a request to the selected one, and supervises turn execution: one turn per chat, cancellation, timeout, and panic isolation so one misbehaving adapter can't take down the daemon (or the other agents' in-flight turns). It streams unified events to the hub and emits notifications. The HTTP layer (internal/api) is thin glue over this.

Index

Constants

View Source
const QueuedInputVersion = 1
View Source
const ServiceUpdateVersion = 2
View Source
const TurnRequestVersion = 1

Variables

View Source
var (
	ErrInputUnsupported = errors.New("this harness does not support queued messages")
	ErrInputOptions     = errors.New("a running conversation accepts messages and attachments; change turn settings after it finishes")
	ErrInputQueueFull   = errors.New("too many queued messages; wait for the agent to accept them")
)
View Source
var (
	ErrServiceBusy     = errors.New("workspace operations are still running; the service update must wait")
	ErrServiceUpdating = errors.New("the Mindwire service is updating; retry shortly")
)
View Source
var ErrAgentBusy = errors.New("agent has running chats; wait for them to finish before installing or updating")
View Source
var ErrAuthBusy = errors.New("wait for this agent's running chats or installation to finish before signing out")
View Source
var ErrAuthDisconnected = errors.New("agent is signed out; connect an account to continue")
View Source
var ErrChatBusy = errors.New("this chat or harness is busy; try again when it is ready")
View Source
var ErrInteractionNotPending = errors.New("interaction is no longer waiting for an answer")
View Source
var ErrInteractionSending = errors.New("this answer is already being sent")
View Source
var ErrInvalidTurnRequest = errors.New("requestId must contain 1 to 128 letters, numbers, hyphens or underscores")

Functions

This section is empty.

Types

type Agent

type Agent struct {
	Adapter agent.Adapter
	Auth    agent.AuthModule
	Runner  *runner.Runner
	Creds   *CredView
}

Agent is one hosted adapter and everything the supervisor needs to run it: its auth module, per-turn runner, and namespaced cred/config view. One per registered adapter.

func (*Agent) Capabilities

func (a *Agent) Capabilities() agent.Capabilities

func (*Agent) ID

func (a *Agent) ID() string

ID is the agent type (e.g. "claude-code").

type CredView

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

CredView is a per-agent-type namespaced view of the shared store: every key is prefixed with "<agentType>:", so each agent's creds AND settings (apiKey, oauthToken, authMethod, model, …) are isolated. Implements agent.CredStore.

The ONE exception is the provider-connection subtree ("provider:<id>:apiKey" / ":envVar"): a connected LLM provider is SHARED across agents, so connect Google once and every agent that supports it reads the same key. Those keys are routed to a fixed cross-agent namespace (sharedCredNamespace) instead of "<agentType>:", so any agent's view — and thus any agent's EnvForRun via ProviderEnvForRun — sees the same connection. Everything else stays per-agent.

func (*CredView) All

func (v *CredView) All() map[string]string

All returns this agent's keys with the prefix stripped (bare keys like "model", "apiKey"), unioned with the shared cross-agent subtree (provider connections). Stale per-agent "provider:*" keys from before providers were shared are ignored — the shared namespace is authoritative — so an old connection simply needs re-connecting once.

func (*CredView) Get

func (v *CredView) Get(key string) string

func (*CredView) Set

func (v *CredView) Set(key, val string) error

func (*CredView) SetMany

func (v *CredView) SetMany(values map[string]string) error

type DoctorReport

type DoctorReport struct {
	OK     bool          `json:"ok"`
	Checks []agent.Check `json:"checks"`
}

DoctorReport is the daemon-level health snapshot for one agent: daemon-generic checks (workspace, auth) plus the adapter's own checks (Adapter.Doctor), with ok=false if any check FAILs. JSON tags match the shape the HTTP layer emits so api.doctor can marshal it unchanged, and the Go SDK returns it directly.

type GitPreparation

type GitPreparation func(context.Context, string, string, *gitaccess.Auth) (*gitaccess.Lease, error)

type InteractionContext

type InteractionContext interface {
	InteractionCWD(chatID, agentType, fallbackCWD string) (string, error)
}

InteractionContext revalidates a saved chat's harness and project before an async answer starts more work. The workspace registry implements this port.

type Option

type Option func(*Supervisor)

func WithAuthSource

func WithAuthSource(source *agent.AuthSource) Option

WithAuthSource is native-host configuration; no API route accepts a source path.

func WithTurnTimeout

func WithTurnTimeout(limit time.Duration) Option

WithTurnTimeout opts into a wall-clock limit. By default turns run until the native harness finishes or an explicit Stop/shutdown cancels them. Viewer disconnects never cancel a turn. Non-positive durations leave it unlimited.

type ResolveOptions

type ResolveOptions struct {
	MaxIterations int           // cap on auto-continued iterations before StopReason "capped"
	Deadline      time.Duration // overall wall-clock budget for the whole resolve
}

ResolveOptions bounds a resolve run. Zero values fall back to the package defaults (resolveMaxIterations / resolveDeadline), so a caller can request resolve with an empty struct.

type RunSnapshot

type RunSnapshot struct {
	Run session.Run `json:"run"`
	stream.Snapshot
}

RunSnapshot is shared by the HTTP API and embedded SDK. Sequence belongs to Parts; subscribing after that cursor cannot replay or skip any of the materialized output.

type ServiceUpdateLease

type ServiceUpdateLease struct {
	ID        string    `json:"id"`
	PID       int       `json:"pid"`
	ExpiresAt time.Time `json:"expiresAt"`
}

ServiceUpdateLease closes admission only for the final binary replacement. The installer downloads first, acquires this lease, then replaces the service. Explicit owner updates may interrupt work; automatic updates still require idle. A crashed installer cannot leave admission closed indefinitely.

type ServiceUpdateState

type ServiceUpdateState struct {
	Idle             bool `json:"idle"`
	Updating         bool `json:"updating"`
	ActiveOperations int  `json:"activeOperations"`
}

type StartTurnInput

type StartTurnInput struct {
	RequestID      string // stable client receipt; retrying returns the same durable run
	QueueIfRunning bool   // native follow-up when busy; ordinary turn when idle
	ChatID         string
	Message        string
	CWD            string // run this turn in a specific dir (a project workdir); else the daemon default
	Options        agent.TurnOptions
	GitAuth        *gitaccess.Auth // write-only; never session or transcript state
	// contains filtered or unexported fields
}

StartTurnInput is one turn's request from the API layer. Bundled into a value object so the StartTurn signature doesn't grow per-field as per-turn options expand.

type Supervisor

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

Supervisor hosts all agents and supervises their turns for one sandbox.

func New

func New(store *session.Store, hub *stream.Hub, notifier notify.Notifier, cwd, defaultAgent string, options ...Option) *Supervisor

func (*Supervisor) AcquireServiceUpdate

func (s *Supervisor) AcquireServiceUpdate(force ...bool) (ServiceUpdateLease, error)

func (*Supervisor) AddNotifier

func (s *Supervisor) AddNotifier(notifier notify.Notifier)

New builds a supervisor over EVERY registered adapter (each with its own auth + runner + namespaced creds). defaultAgent selects the agent for requests that omit ?agent=; if it isn't registered, the first adapter by ID is used (deterministic). AddNotifier is startup wiring and must run before any turns are admitted.

func (*Supervisor) ApproveServiceOperation

func (s *Supervisor) ApproveServiceOperation(ctx context.Context, runID, title, detail string) error

ApproveServiceOperation uses the same pending interaction, transcript, push and owner-response path as desktop approvals. An agent cannot answer it via tools.

func (*Supervisor) BeginServiceOperation

func (s *Supervisor) BeginServiceOperation() (func(), error)

BeginServiceOperation covers a mutating API request until its synchronous work finishes or its asynchronous job has been registered. New turns/setup also check this same admission lock, including calls from the embedded SDK.

func (*Supervisor) BotRunSnapshot

func (s *Supervisor) BotRunSnapshot(runID string) (session.Run, []agent.Part, bool)

func (*Supervisor) BotService

func (s *Supervisor) BotService() *bots.Service

func (*Supervisor) Busy

func (s *Supervisor) Busy(chatID string) bool

Busy reports whether a turn is currently running for a chat. The API uses it to 409 a delete or fork while the chat is live (a rename is safe to proceed). Reads s.active under the same lock StartTurn/execRun mutate it.

func (*Supervisor) BusyPath

func (s *Supervisor) BusyPath(path string) bool

BusyPath prevents removing files underneath any live turn, even one started through the legacy API without a saved project/chat relationship.

func (*Supervisor) CLIVersion

func (s *Supervisor) CLIVersion(ctx context.Context, ag *Agent) string

CLIVersion runs the agent's version command and returns the trimmed output ("" on any error). Used to report the installed CLI version alongside agent info.

func (*Supervisor) CWD

func (s *Supervisor) CWD() string

CWD is the daemon's default working directory (a turn may override it per request).

func (*Supervisor) Cancel

func (s *Supervisor) Cancel(runID string) bool

Cancel stops an in-flight turn (cancels its context, killing the CLI). false = no turn is currently running for that run id.

func (*Supervisor) CheckNativeChatMutation

func (s *Supervisor) CheckNativeChatMutation(ctx context.Context, chatID string) error

CheckNativeChatMutation protects native transcript files even when Mindwire did not launch their owner. Call after hydrating the registry's session mapping.

func (*Supervisor) CompatibilityCatalog

func (s *Supervisor) CompatibilityCatalog() toolchain.Catalog

func (*Supervisor) ConfirmPermissionMode

func (s *Supervisor) ConfirmPermissionMode(ctx context.Context, runID, mode string) error

ConfirmPermissionMode returns only after the harness has applied or rejected the mode.

func (*Supervisor) Default

func (s *Supervisor) Default() string

Default is the agent type used when a request omits a selector.

func (*Supervisor) Doctor

func (s *Supervisor) Doctor(ctx context.Context, ag *Agent) DoctorReport

Doctor reports daemon-level health (workspace, auth) plus the selected agent's own checks (Adapter.Doctor) — one report, generic at the daemon, extended per agent. Shared by the HTTP surface (api.doctor) and the in-process Go SDK so both report identically.

func (*Supervisor) Interrupt

func (s *Supervisor) Interrupt(runID string) bool

Interrupt soft-stops a running turn (asks the agent to halt current work) WITHOUT the hard context kill Cancel does — the turn stays active for a follow-up over /input. false = no open ingress channel for that run id.

func (*Supervisor) IsServiceInteraction

func (s *Supervisor) IsServiceInteraction(runID, interactionID string) bool

IsServiceInteraction reports whether the supervisor itself is waiting for this answer. Service approvals do not require the agent adapter's Respond capability.

func (*Supervisor) Logout

func (s *Supervisor) Logout(ctx context.Context, a *Agent) (agent.AuthStatus, error)

Logout shares turn/setup admission. Credentials cannot be removed from a running chat, and a new turn cannot slip in while native sign-out is pending.

func (*Supervisor) NativeSessions

func (s *Supervisor) NativeSessions() *nativesessions.Service

func (*Supervisor) Notes

func (s *Supervisor) Notes() *notify.Stream

Notes is the local notification SSE broadcaster (the API's /notify/stream subscribes here).

func (*Supervisor) ProcMon

func (s *Supervisor) ProcMon() *procmon.Monitor

ProcMon is the on-demand per-turn CPU/mem sampler (the API's /processes/stream subscribes here). It is idle until a client subscribes and stops when the last one leaves — no background work, no leak.

func (*Supervisor) RefreshSoftware

func (s *Supervisor) RefreshSoftware(ctx context.Context, a *Agent, force bool) *toolchain.Software

func (*Supervisor) ReleaseServiceUpdate

func (s *Supervisor) ReleaseServiceUpdate(id string) bool

func (*Supervisor) Resolve

func (s *Supervisor) Resolve(agentType string) (*Agent, bool)

Resolve returns the agent runtime for a type (empty = the default). ok=false = unknown.

func (*Supervisor) Respond

func (s *Supervisor) Respond(runID, interactionID, decision string, options []string, text string) bool

Respond delivers the user's answer to a mid-turn interaction (a permission approval, or an AskUserQuestion / ExitPlanMode reply) into the running turn. It echoes the interaction's adapter correlators — recorded in pending from Interaction.Meta (respondVia, toolUseId) — back on the Inbound so the adapter frames the native wire response statelessly. false = no turn with an open ingress channel for that run id (unknown, finished, or the agent takes no ingress).

func (*Supervisor) RespondInteraction

func (s *Supervisor) RespondInteraction(runID string, reply agent.InteractionResponse) error

RespondInteraction accepts exactly one complete answer for a currently pending request.

func (*Supervisor) RespondInteractionWithGitAuth

func (s *Supervisor) RespondInteractionWithGitAuth(runID string, reply agent.InteractionResponse, gitAuth *gitaccess.Auth) error

func (*Supervisor) SendInput

func (s *Supervisor) SendInput(runID, text string) bool

SendInput queues a follow-up user message into a running turn (steer/append without cancelling). false = no open ingress channel for that run id.

func (*Supervisor) SendInputChecked

func (s *Supervisor) SendInputChecked(runID, text, requestID string, attachments []agent.Attachment) (session.Run, error)

SendInputChecked is the run-addressed counterpart of queueIfRunning. It preserves the old endpoint's active-run contract and adds durable retries.

func (*Supervisor) ServiceUpdateState

func (s *Supervisor) ServiceUpdateState() ServiceUpdateState

func (*Supervisor) SetBots

func (s *Supervisor) SetBots(service *bots.Service)

func (*Supervisor) SetGitPreparation

func (s *Supervisor) SetGitPreparation(prepare GitPreparation)

func (*Supervisor) SetInteractionContext

func (s *Supervisor) SetInteractionContext(provider InteractionContext)

func (*Supervisor) SetModel

func (s *Supervisor) SetModel(runID, model string) bool

SetModel switches the model of a live turn (empty model resets to the agent/CLI default). Only a persistent transport reads this; on a one-shot turn the send succeeds into the buffer but the CLI never consumes it (a documented best-effort no-op). false = no open ingress channel for that run id.

func (*Supervisor) SetNotificationPreferences

func (s *Supervisor) SetNotificationPreferences(preferences notify.Preferences)

SetNotificationPreferences binds workspace-owned settings for the HTTP and Go SDK hosts. Read under the supervisor lock; registry I/O never holds that lock.

func (*Supervisor) SetPermissionMode

func (s *Supervisor) SetPermissionMode(runID, mode string) bool

SetPermissionMode switches the permission mode of a live turn (mode is required). Same persistent-only best-effort semantics as SetModel. false = no open ingress channel for that run id.

func (*Supervisor) SetSurfaces

func (s *Supervisor) SetSurfaces(service *surface.Service)

func (*Supervisor) Setup

func (s *Supervisor) Setup(a *Agent, force bool) (setup.Status, error)

Setup owns the same harness lock as turn admission. An HTTP client, SDK caller, or second persona cannot start a turn during installation, or replace a CLI beneath an existing turn. Repeated setup/update requests still attach to the one detached job.

func (*Supervisor) SetupStatus

func (s *Supervisor) SetupStatus(a *Agent) setup.Status

func (*Supervisor) Shutdown

func (s *Supervisor) Shutdown(ctx context.Context) error

Shutdown cancels service-owned turns and waits for their final transcript save. The caller's deadline bounds an unresponsive harness; no new work can enter.

func (*Supervisor) Snapshot

func (s *Supervisor) Snapshot(id string) (RunSnapshot, bool)

func (*Supervisor) Software

func (s *Supervisor) Software(ctx context.Context, a *Agent, refresh bool) *toolchain.Software

func (*Supervisor) StartBotTurn

func (s *Supervisor) StartBotTurn(botID string, chat registry.Chat, profile registry.Agent, project registry.Project, message, requestID string) (session.Run, error)

func (*Supervisor) StartCompact

func (s *Supervisor) StartCompact(a *Agent, req StartTurnInput) (session.Run, bool)

StartCompact runs an on-demand compaction as a first-class run through the IDENTICAL execRun path as a turn, so the compaction boundary streams and records exactly like an auto-compaction. It differs from StartTurn in two ways: it records no user message (the /compact trigger isn't a user turn) and allocates no ingress channel (a compaction never pauses for the user). It still takes the per-chat turn lock — a compaction is mutually exclusive with a turn. ok=false ⇒ that chat is busy or the harness is being installed/updated. The API gates this on agent.CompactModule.

func (*Supervisor) StartConflict

func (s *Supervisor) StartConflict(a *Agent) string

StartConflict describes a failed admission for both transports. Admission itself happens under s.mu in start/StartResolve; this read only supplies a useful retry reason to the client.

func (*Supervisor) StartResolve

func (s *Supervisor) StartResolve(a *Agent, req StartTurnInput, ro ResolveOptions) (session.Run, bool)

StartResolve launches a GLOBAL-RESOLVE run: instead of returning after one turn, the daemon holds the run open and auto-continues the agent's own multi-step work until the task is globally complete (the agent emits the completion sentinel), an unrecoverable error occurs, or a cap is hit. It creates a PARENT run (Kind "resolve") the caller waits on and streams under; each auto-continued iteration is a child run whose events publish onto the parent's topic (one merged stream). Like start() it takes the per-chat turn lock for the whole resolve (ok=false ⇒ a turn is already running for that chat) and records the user message once. It allocates NO ingress channel: resolve runs unattended, and with no Inbound channel neither adapter can enter its pausing transport (both gate persistent/app-server on Inbound != nil), so the loop can't stall on an approval.

func (*Supervisor) StartResolveChecked

func (s *Supervisor) StartResolveChecked(a *Agent, req StartTurnInput, ro ResolveOptions) (session.Run, error)

func (*Supervisor) StartTurn

func (s *Supervisor) StartTurn(a *Agent, req StartTurnInput) (session.Run, bool)

StartTurn records the user message, creates a running Run, registers cancellation, and launches execution on a DETACHED context (survives app disconnect). It guards one turn per chat: ok=false means that chat is busy or this harness is being installed/updated.

func (*Supervisor) StartTurnChecked

func (s *Supervisor) StartTurnChecked(a *Agent, req StartTurnInput) (session.Run, error)

func (*Supervisor) SubscribeRun

func (s *Supervisor) SubscribeRun(id string, after int64) (replay []agent.Event, ch <-chan agent.Event, done bool, cancel func())

SubscribeRun keeps the producer's lifetime authoritative for stream completion. A terminal record can be saved before its final events/notification are sent; subscribers must drain through hub.Close, never close that topic themselves. The start/teardown lock also prevents a new run from being mistaken for an old run whose replay buffer expired or disappeared after a daemon restart.

func (*Supervisor) Voice

func (s *Supervisor) Voice(runID, clientID string) (*agent.VoiceBridge, bool)

func (*Supervisor) Wait

func (s *Supervisor) Wait()

Wait blocks until every in-flight turn goroutine has fully finished — including its terminal SaveRun — so a caller can Cancel all runs and then safely tear down the state directory without racing a late persist. It does NOT itself cancel; a clean drain is Cancel-all followed by Wait. Safe to call concurrently and repeatedly (a later turn that starts mid-drain is simply waited on too, never a WaitGroup-style panic).

Jump to

Keyboard shortcuts

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