coordinator

package
v1.0.0-rc.9 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: Apache-2.0 Imports: 35 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 coordinator is the elected leader's live state of an installation's runners, tasks, sessions and subscriptions.

It is the only writer of their status. Every input change (an offered or canceled task, a registered runner, a stream opened or closed, an answer, a session report, a pressure or usage report) runs placement.Place and acts on its decisions at once: an offer is persisted, then sent on the runner's stream. One timer wakes it at the next instant a decision can change on its own: an offer's answer window, a heartbeat lease, the end of an affinity wait or a decline backoff, a deadline, a reading going stale, a host token expiring, or retention. Nothing polls.

Its Go API is what the MCP tools and the runner API call. Every call says who calls; the coordinator checks it, so no transport can forget to.

Index

Constants

View Source
const (

	// ContextRepoPattern, ContextIssuePattern and ContextCulpritPattern describe
	// the repository and GitHub references accepted by the tool's input schema.
	ContextRepoPattern    = "^" + repoPath + "$"
	ContextIssuePattern   = "^(?:" + githubPath + `issues/[1-9][0-9]*)?$`
	ContextCulpritPattern = `^(?:` + shaPattern + "|" + githubPath + `(?:commit/` + shaPattern + `|pull/[1-9][0-9]*))?$`
)
View Source
const (
	OpContextBundle    = "context_bundle"
	OpOfferTask        = "offer_task"
	OpCancelTask       = "cancel_task"
	OpCapacity         = "capacity"
	OpTask             = "task"
	OpRegisterRunner   = "register_runner"
	OpDeregisterRunner = "deregister_runner"
	OpListRunners      = "list_runners"
	OpUsage            = "usage"
)

The operations whose refusals are counted, by the tool or endpoint name.

View Source
const MaxPlacements = 3

MaxPlacements is how many sessions a task gets: a session that fails within the placement-failure lease of its start places the task again, until the task has had this many.

Variables

View Source
var (
	ErrUnauthenticated = errors.New("unauthenticated")
	ErrForbidden       = errors.New("forbidden")
	ErrNotFound        = errors.New("not found")
	ErrConflict        = errors.New("conflict")
	ErrInvalid         = errors.New("invalid")
	ErrUnavailable     = errors.New("unavailable")
)

The errors a call fails with. Transports map them to their own: HTTP statuses, MCP errors.

Functions

func Handle

func Handle(namespace, key string) string

Handle is the name of the task a key offers in a namespace: `t-` and the first 20 hex digits of SHA-256(namespace, newline, key).

Types

type Collector

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

Collector computes the gauges of the live state and the invariants on every scrape, from the current leader's coordinator. It reports nothing while this process isn't the leader.

func NewCollector

func NewCollector(current func() *Coordinator) *Collector

NewCollector collects from the coordinator current returns, or nothing when it returns nil.

func (*Collector) Collect

func (col *Collector) Collect(ch chan<- prometheus.Metric)

Collect implements prometheus.Collector.

func (*Collector) Describe

func (*Collector) Describe(ch chan<- *prometheus.Desc)

Describe implements prometheus.Collector.

type Conn

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

Conn is a runner's open stream: the messages to send it.

func (*Conn) Done

func (s *Conn) Done() <-chan struct{}

Done closes when the stream must end: a new stream replaced it, its runner was deregistered, or the coordinator stopped.

func (*Conn) Messages

func (s *Conn) Messages() <-chan runnerapi.Message

Messages are the messages to write to the stream.

type ContextBundleResult

type ContextBundleResult struct {
	Bundle   string          `json:"bundle"`
	Contents json.RawMessage `json:"contents"`
}

ContextBundleResult carries a stateless reference and the current view of its contents.

type Coordinator

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

Coordinator is the leader's live state.

func Start

func Start(ctx context.Context, o Options) (*Coordinator, error)

Start loads every resource of the organizations' namespaces and starts coordinating them. Each started task's heartbeat lease and each offer's answer window start now, so runners have time to reconnect to a new leader. The coordinator stops when ctx ends or Stop is called.

func (*Coordinator) Answer

Answer takes a runner's answer to an offer. An accept starts the task and records its session, `<task>-<n>`. A decline puts the task back to Queued with the decline recorded, so it goes to another runner. A task not offered to this runner is a conflict.

func (*Coordinator) AuthenticateRunner

func (c *Coordinator) AuthenticateRunner(ctx context.Context, keyHash string, host auth.HostToken) (RunnerRef, error)

AuthenticateRunner finds the runner of a key's hash and checks that the host token is its host's. It keeps the newest host token; a newer token for a host whose access was refused checks the host again at once.

func (*Coordinator) Cancel

func (c *Coordinator) Cancel(ctx context.Context, caller auth.Caller, handle, reason string) (TaskRef, error)

Cancel cancels a task for the organization's principal. A queued or offered task ends Canceled at once, its offer withdrawn. A started one records the request and gets a cancel on its runner's stream; it ends Canceled when the runner confirms, or when its lease expires. An ended task stays as it ended.

func (*Coordinator) Capacity

func (c *Coordinator) Capacity(_ context.Context, caller auth.Caller, probe v1alpha1.AgentTaskSpec) (placement.Answer, error)

Capacity says, for the organization's principal, whether a runner whose focus matches would take a task like probe now, and where. It is placement.Capacity on the live state.

func (*Coordinator) Connect

func (c *Coordinator) Connect(ctx context.Context, ref RunnerRef) (*Conn, error)

Connect opens a runner's stream, replacing an older one. Offers the runner hasn't answered and cancels it hasn't confirmed are sent again.

func (*Coordinator) ContextBundle

func (c *Coordinator) ContextBundle(_ context.Context, caller auth.Caller, args map[string]json.RawMessage) (ContextBundleResult, error)

ContextBundle previews an organization's bundle using only the leader's in-memory state.

func (*Coordinator) Deregister

func (c *Coordinator) Deregister(ctx context.Context, caller auth.Caller, organization, name string) error

Deregister deregisters a runner for its host. See DeregisterRunner.

func (*Coordinator) DeregisterRunner

func (c *Coordinator) DeregisterRunner(ctx context.Context, ref RunnerRef, organization, name string) error

DeregisterRunner deregisters a runner with its own key. It deletes the Runner, closes its stream and makes its key fail at once. Its offered tasks go back to Queued; its started ones end Lost with "runner deregistered".

func (*Coordinator) Disconnect

func (c *Coordinator) Disconnect(ref RunnerRef, conn *Conn)

Disconnect closes a runner's stream, unless a newer one replaced it.

func (*Coordinator) Leases

func (c *Coordinator) Leases() (heartbeatInterval, lease time.Duration)

Leases are the configured heartbeat lease and the interval at which a runner sends heartbeats, a third of it.

func (*Coordinator) ListRunners

func (c *Coordinator) ListRunners(ctx context.Context, caller auth.Caller, organization string) (RunnerList, error)

ListRunners lists an organization's runners, by name, for its principal or a member.

func (*Coordinator) Offer

func (c *Coordinator) Offer(ctx context.Context, caller auth.Caller, spec v1alpha1.AgentTaskSpec) (TaskRef, error)

Offer offers a task for the organization's principal. The task's key is its idempotency key: offering it again returns the task it offered, as it stands.

func (*Coordinator) PrincipalNamespace

func (c *Coordinator) PrincipalNamespace(op string, caller auth.Caller) (string, error)

PrincipalNamespace checks that the caller is an organization's principal and returns its namespace.

func (*Coordinator) Register

Register registers a runner of an organization for a member, who becomes its host. The installation comes from the configuration. Missing Subscriptions are created with their provider. A runner of the same name is a conflict, unless its host registers it again with Replace, which rotates its key, ends its stream and makes the old key fail at once.

func (*Coordinator) ReportSession

func (c *Coordinator) ReportSession(ctx context.Context, ref RunnerRef, rep runnerapi.SessionReport) error

ReportSession takes a started session's report, which is also its heartbeat. The first Running report makes the task Running. An outcome ends the task, except that a Failed within the placement-failure lease of the start places the task again, until it had MaxPlacements sessions. Progress is written at most every 30 seconds.

func (*Coordinator) ReportStatus

func (c *Coordinator) ReportStatus(ctx context.Context, ref RunnerRef, report runnerapi.StatusReport) error

ReportStatus keeps a runner's pressure.

func (*Coordinator) ReportUsage

ReportUsage keeps a reading of one of the runner's subscriptions, unless it is older than the kept one.

func (*Coordinator) Settle

func (c *Coordinator) Settle()

Settle waits until the coordinator has handled every timer that fired. Tests call it after moving a fake clock.

func (*Coordinator) Stop

func (c *Coordinator) Stop()

Stop closes every stream and stops the timer. Later calls fail with ErrUnavailable.

func (*Coordinator) Task

func (c *Coordinator) Task(_ context.Context, caller auth.Caller, handle string) (TaskView, error)

Task returns a task's source for the organization's principal.

type Options

type Options struct {
	Config  *config.Config
	Store   *store.Store
	Access  auth.AccessReviewer
	Clock   clock.WithDelayedExecution
	Metrics *metrics.Metrics
	Log     *slog.Logger
}

Options are a coordinator's dependencies.

type ProgressView

type ProgressView struct {
	Turns     int32 `json:"turns"`
	ToolCalls int32 `json:"toolCalls"`
	Pushes    int32 `json:"pushes"`
	Tokens    int64 `json:"tokens"`
}

ProgressView is what a session has done so far.

type ResultView

type ResultView struct {
	Summary   string   `json:"summary"`
	Commits   []string `json:"commits"`
	Findings  []string `json:"findings"`
	Questions []string `json:"questions"`
}

ResultView is a session's structured result.

type RunnerList

type RunnerList struct {
	Count   int          `json:"count"`
	Runners []RunnerView `json:"runners"`
}

RunnerList is an organization's runners, as list_runners returns them.

type RunnerRef

type RunnerRef struct {
	Organization string
	Namespace    string
	Name         string
	Host         string
	// contains filtered or unexported fields
}

RunnerRef is an authenticated runner.

type RunnerView

type RunnerView struct {
	Name         string             `json:"name"`
	Host         string             `json:"host"`
	Slots        int32              `json:"slots"`
	Used         int32              `json:"used"`
	Focus        string             `json:"focus"`
	Purposes     []string           `json:"purposes"`
	Harnesses    []v1alpha1.Harness `json:"harnesses"`
	Capabilities []string           `json:"capabilities"`
	Connected    bool               `json:"connected"`
	LastSeen     *time.Time         `json:"lastSeen"`
}

RunnerView is a runner as list_runners shows it.

type TaskRef

type TaskRef struct {
	Handle string             `json:"handle"`
	State  v1alpha1.TaskPhase `json:"state"`
	Reason string             `json:"reason"`
}

TaskRef is a task's handle and where it stands.

type TaskView

type TaskView struct {
	Handle       string             `json:"handle"`
	State        v1alpha1.TaskPhase `json:"state"`
	Ended        bool               `json:"ended"`
	Outcome      string             `json:"outcome"`
	Reason       string             `json:"reason"`
	Runner       string             `json:"runner"`
	Host         string             `json:"host"`
	Harness      string             `json:"harness"`
	Provider     string             `json:"provider"`
	Subscription string             `json:"subscription"`
	// HeartbeatAge is the seconds since the live session's last heartbeat,
	// null without a live session.
	HeartbeatAge *int64       `json:"heartbeatAge"`
	Progress     ProgressView `json:"progress"`
	FirstPush    *time.Time   `json:"firstPush"`
	Result       *ResultView  `json:"result"`
	Placements   int32        `json:"placements"`
	// Verified is false until signed session records exist.
	Verified bool `json:"verified"`
}

TaskView is the task source a run follows.

Jump to

Keyboard shortcuts

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