agents

package
v0.219.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT 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 agents is muster's agent domain: the stored record of a managed agent, its chat threads, the model catalogue that decides what it runs on, and the pure decision table a reconciler drives it with.

🔴 IT DOES NOT PROVISION ANYTHING, AND THAT IS THE CARVE'S WHOLE SHAPE. Upstream this package also owned a Helm client, a cluster client, a vendored chart and the agent's chat transport, all hanging off one type. Creating, scaling, destroying and reaching an instance is internal/provision's job here; this package holds what is true about an agent regardless of what runs it. The carve notes at the foot of reconcile.go and modelauth.go name what that leaves owed, and who closes it.

This file holds the record and the Store interface.

Index

Constants

View Source
const (
	// CheckoutUnknown: not read (no repository, the read failed, or a ccd that does
	// not report one).
	CheckoutUnknown = ""
	// CheckoutCloning: ccd has not finished its first clone attempt.
	CheckoutCloning = "cloning"
	// CheckoutAwaitingGrant: a clone failed and this agent's `github` connector
	// request is pending (ccd filed it, or it already was).
	CheckoutAwaitingGrant = "awaiting_grant"
	// CheckoutFailed: a clone failed for any other reason (the grant is approved
	// but git has not caught up, it was denied, the repository is missing …).
	// The first turn is sent as before: ccd answers not_ready with the reason, and
	// the deliverer's bounded re-send records it if it does not clear.
	CheckoutFailed = "failed"
	// CheckoutReady: the repository is checked out and the CLI starts.
	CheckoutReady = "ready"
)

The repository checkout a claude-code agent's ccd reports on /healthz under `repo.state` (cmd/ccd/checkout.go). ccd clones the agent's repository BEFORE it starts the Claude Code CLI, and a private one cannot be cloned until the owner approves the agent's `github` connector grant — which ccd asks for itself.

🔴 THE FIRST TURN WAITS FOR IT, UNSTAMPED. Before this, the deliverer stamped the row kicked_off, sent the turn into ccd's `503 not_ready`, re-sent for three minutes and recorded a failed kickoff — so approving the grant afterwards left an agent that had never been told its task, and the owner had to re-send it by hand. Now internal/agentkickoff reads this state under its claim, BEFORE the stamp, and while it says the checkout is coming (cloning, or waiting for the grant) it sends nothing and stamps nothing; a later tick tries again. The stamp-before-send rule (a paid turn never runs twice) is untouched: the read is one more pre-stamp check.

View Source
const (
	KickoffAwaitingGrantReason = "kickoff not sent yet: waiting for the owner to approve this agent's " +
		"github connector request, without which its repository cannot be checked out"
	KickoffAwaitingCloneReason = "kickoff not sent yet: the agent's repository is still being cloned"
)

KickoffAwaitingGrantReason / KickoffAwaitingCloneReason open agents.kickoff_error while a first turn is held for its checkout. They are written by internal/agentkickoff on a row that is NOT kicked off, so KickoffFailed (which requires kicked_off) never reads them as a failure; the deliverer clears them before it stamps. KickoffAwaitingGrant and WaitedForCheckout read them by prefix — one constant per state, so writer and readers cannot drift.

View Source
const (
	KindGateway    = "gateway"
	KindClaudeCode = "claude-code"
)

The agent KINDS: which runtime an agent row is provisioned as.

🔴 KindGateway IS EVERY AGENT THAT EXISTED BEFORE KINDS DID, AND IT IS THE DEFAULT. It is the operator-configured runtime image reached over the `hooks-sha256` gateway wire (MUSTER_AGENT_IMAGE_REPO and friends). Migration 0003 backfills every existing row to it, and ResolveKind maps an unset kind to it, so a deployment that never names a kind builds exactly the specs it built before. The image's own identifier is a denied token in this public repository, which is why the kind is spelled after the wire it speaks.

KindClaudeCode is the Claude Code pod: the claude-code-agent image (cmd/ccd + the pinned CLI) authenticated by one `claude setup-token` drawn from muster's per-account pool (internal/ccpool). Its spec profile is in internal/agentspec/claudecode.go.

View Source
const (
	SessionRuntimeLegacy     = ""
	SessionRuntimeClaudeCode = KindClaudeCode
)

A CHAT SESSION'S RUNTIME AND MODEL (migration 0030).

A claude-code chief's ccd runs more than one Claude Code CLI. A session is tagged with its runtime, and a model, when it is created, and both are fixed for its life (a database trigger refuses a change). muster routes each turn by the tag (internal/api's sessionRoute).

SessionRuntimeLegacy     ""            the agent's own kind; for a claude-code
                                       agent, the ONE CLI ccd has always run.
                                       Every session that existed before 0030.
SessionRuntimeClaudeCode "claude-code" a CLI of its own in ccd, started with
                                       --model when Model is set.

⚠ THE COLUMN STILL ADMITS "gateway": a second runtime, run beside ccd in the chief's pod, was offered here until it was removed with no session ever started on it. A row carrying it routes as legacy.

View Source
const (
	StatusPending      = "pending"
	StatusProvisioning = "provisioning"
	StatusRunning      = "running"
	StatusStopped      = "stopped"
	StatusError        = "error"
)

Status values for an agent (mirrors the agents.status CHECK constraint).

View Source
const (
	SearchSnippetRadius = 60
	SearchSnippetLen    = 180
)

SearchSnippetRadius is how many characters of context a snippet carries on each side of the match, and SearchSnippetLen its total length.

🔴 A SNIPPET IS BOUNDED BY THE STORE, NOT BY CSS. chat_messages.content has no length limit and the longest text row on the deployment this was extracted from was 174 KB — so a reader that returned whole bodies and let the browser clamp them would ship that 174 KB over the wire for one search result. The excerpt is cut in SQL.

View Source
const (
	NameDefault  = "default"
	NameDispatch = "dispatch"
	NameSystem   = "system"
	NameManual   = "manual"
)

Who set an agent's DisplayName (Agent.DisplayNameSource; migration 0090's agents_display_name_source_check holds the same four).

View Source
const (
	// HeaderCCSession is the session key of an EXPLICIT Claude Code session:
	// ccd runs it in a CLI of its own. Absent: ccd's original CLI, the one
	// every legacy session has always shared.
	HeaderCCSession = "X-Muster-CC-Session"
	// HeaderCCModel is the model that CLI is started with (`--model`).
	HeaderCCModel = "X-Muster-CC-Model"
	// HeaderCCWorkdir is the working directory that CLI is started in: a job's
	// own worktree ([JobWorktreeDir]). Absent: the agent's working directory,
	// as for every session before jobs had worktrees. ccd accepts only a
	// directory [IsJobWorktreeDir] admits, and only on a turn that also names
	// an explicit session (HeaderCCSession), whose CLI it then fixes in that
	// directory for the session's life.
	HeaderCCWorkdir = "X-Muster-CC-Workdir"
	// HeaderCCWorkdirUsed is ccd's ANSWER on an explicit session's turn: the
	// directory that session's CLI actually works in. A sha job's runner
	// compares it with the HeaderCCWorkdir it sent and refuses the turn's result
	// when it is missing or different — a ccd from before job worktrees ignores
	// HeaderCCWorkdir and would run the job in the agent's own checkout.
	HeaderCCWorkdirUsed = "X-Muster-CC-Workdir-Used"
	// HeaderCCEphemeral, "1", marks an explicit session (HeaderCCSession) as a
	// THROWAWAY check: ccd stops that session's CLI as soon as its turn is over,
	// and at its cap (CCD_MAX_SESSIONS) refuses it (FailureCapacity) rather
	// than stop another session's CLI to make room. Set only on a chief's stall
	// check (internal/api nudgeRoute). A ccd that predates it ignores it and
	// keeps the CLI like any other session's.
	HeaderCCEphemeral = "X-Muster-CC-Ephemeral"
	// HeaderCCToolless, "1", marks an explicit session (HeaderCCSession) as
	// TOOL-LESS: ccd starts that session's CLI with no built-in tool and no MCP
	// server (`--tools= --strict-mcp-config`), so its only possible effect is
	// its text reply. Set only on a chief's stall check, alongside
	// HeaderCCEphemeral (internal/api withRoute): the check's prompt quotes other
	// sessions' transcripts, and a CLI with tools could be steered by them. Fixed
	// for the session's life. A ccd that predates it IGNORES it and starts the
	// CLI with the chief's full tool set (docs/chief-nudges.md, "Rolling out").
	HeaderCCToolless = "X-Muster-CC-Toolless"
	// HeaderCCPinned, "1", marks an explicit session (HeaderCCSession) as the
	// chief's PRIMARY chat (internal/api withRoute, chief_chats.go): ccd never
	// stops its CLI to make room for another session, and does not count it
	// against CCD_MAX_SESSIONS, so a delivery to the primary always gets its
	// CLI. One lane is pinned at a time: the latest turn that says so pins its
	// lane and unpins any other (a fresh primary's old one). A ccd that predates
	// it ignores it and treats the lane like any other.
	HeaderCCPinned = "X-Muster-CC-Pinned"
	// HeaderCCNewConversation, "1", on a turn of the agent's ORIGINAL CLI (no
	// HeaderCCSession): ccd starts a NEW conversation in that CLI before it
	// pastes the turn — the CLI's /clear, whose new session ccd records as the
	// one every later start resumes — when the current conversation has a
	// transcript; the old transcript is kept. Set only by the officer runtime,
	// on every turn of an instance of a fresh_session_per_item pool (internal/
	// api OfficerTurnContext). ccd ignores it on an explicit session's turn,
	// and a ccd that predates it ignores it everywhere: the turn then runs in
	// the conversation the CLI already has, and its answer carries no
	// HeaderCCNewConversationSession, which is how muster notices
	// (docs/officers.md, "One conversation per item").
	HeaderCCNewConversation = "X-Muster-CC-New-Conversation"
	// HeaderCCNewConversationSession is ccd's ANSWER to a turn carrying
	// HeaderCCNewConversation: the session id of the new conversation the turn
	// was typed into, on the 103 that says the CLI accepted it (turnaccepted.go
	// TurnAcceptance.NewConversation) and on the final answer. A ccd that
	// predates HeaderCCNewConversation never sends it, which is how muster
	// tells a stale image from a current one (internal/api
	// OfficerTurnContext).
	HeaderCCNewConversationSession = "X-Muster-CC-New-Conversation-Session"
)

A TURN'S ROUTE INSIDE THE POD: which CLI, and which model, one turn goes to when an agent's ccd runs more than one (session_runtime.go).

🔴 THE ADDRESS DOES NOT CHANGE, ONLY THESE HEADERS DO. Every turn still goes to the agent's one endpoint, ccd's port: ccd is the only thing the pod's network policy lets muster reach. So a session's route is a property of the REQUEST, set by the one place that knows the session (internal/api's sessionRoute) and read by the two request builders here, rather than a parameter threaded through every turn function between them.

The header names are a wire contract with cmd/ccd, which spells them itself; cmd/ccd's tests pin the two (TestTheLaneHeadersAreMustersHeaders, TestTheWorkdirHeaderIsMusters).

View Source
const CLIActivityVersion = 1

CLIActivityVersion is the shape of the answer below.

View Source
const CLIStatusIdle = "idle"

CLIStatusIdle is the one sessions-file status that means "not working".

View Source
const ChiefName = "chief"

ChiefName is the one RESERVED agent name: the standing agent the operator talks to, as opposed to a worker dispatched against a task.

🔴 IT IS A CONSTANT BECAUSE THE INSTRUCTIONS BRANCH ON IT, AND A NAME THE GENERATOR PRODUCED WOULD SILENTLY FAIL THAT BRANCH. Ordinary agent names come from the adjective-noun pool above, so nothing a human can type reaches this value — POST /chief/provision is the only producer. Upstream, a release that reserved this name before anything could create one shipped an agent whose whole instruction set was unreachable: it was handed the WORKER instructions, dutifully asked for its assigned task, was told it had none, and reported to the operator that there was nothing to do. It was not malfunctioning; it was executing the only instructions it had.

⚠ IT IS NOT IN adjectives/nouns AND MUST NOT BE. The collision loop in BuildUniqueAgentName guards against an accidental duplicate of an EXISTING agent, not against the pool minting a reserved word — so a reserved name that the pool could also produce would be a coin flip, not a guard.

View Source
const ClaudeCodeTurnTimeout = 35 * time.Minute

ClaudeCodeTurnTimeout bounds ONE request to a claude-code agent's ccd.

🔴 IT IS LONGER THAN ccd's OWN TURN BUDGET ON PURPOSE, AND THE ORDER IS THE DECISION. ccd ends a turn that has seen no Stop/StopFailure after CCD_TURN_TIMEOUT (default 30m, cmd/ccd/main.go) with a TYPED `504 turn_timeout` whose message says the turn is still running in the session. If muster's client gave up first — the gateway kind's 10m (agentgateway.DefaultTurnTimeout) — a long Claude Code turn would surface as a bare client timeout with no body, ccd would stay busy until the CLI's Stop, and the next message would get a 409 `busy` for a turn nobody is waiting for. Outlasting ccd by five minutes means the typed answer always arrives first.

⚠ A TURN THAT GENUINELY RUNS LONGER THAN ccd's BUDGET STILL ENDS AS A 504 TO THE CALLER; the work keeps going in the TUI and is visible in the transcript.

View Source
const DefaultCheckoutWaitTimeout = 24 * time.Hour

DefaultCheckoutWaitTimeout bounds how long a first turn waits for a checkout that is coming (cloning, or waiting for the github grant). An owner may not see the request for hours; a day is long enough to come back to it and short enough that an agent nobody approves goes red rather than sitting owed for ever.

View Source
const FailureCapacity = "capacity"

FailureCapacity is the `error.type` of ccd's typed 503 for a turn that names an explicit session (HeaderCCSession) whose CLI is not running while every CLI ccd may run at once (CCD_MAX_SESSIONS) is held by a turn. ccd answers it from lane selection, BEFORE it starts a CLI or pastes anything. cmd/ccd spells it itself (failCapacity); TestTheCapacityFailureIsMusters pins the two.

View Source
const HeaderCCPromptAccepted = "X-Muster-CC-Prompt-Accepted"

HeaderCCPromptAccepted, "1" on ccd's 103 informational response, says the CLI has accepted the pasted prompt (its UserPromptSubmit matched it). "1" on the REQUEST asks for that 103; ccd sends none to a caller that did not ask. cmd/ccd spells it itself (headerCCPromptAccepted); TestThePromptAcceptedHeaderIsMusters pins the two.

View Source
const JobWorktreesDirName = ".muster-jobs"

JobWorktreesDirName is the directory, beside the agent's working directory, that holds its jobs' worktrees.

View Source
const KickoffBusyReason = "kickoff turn NOT ACCEPTED by the agent runtime: it answered " +
	"busy (another turn held the session, or a dialog was on its screen) for the whole delivery, so " +
	"nothing was sent. The row was already marked delivered, so it is not retried automatically"

KickoffBusyReason is KickoffNotAcceptedReason's sibling for a typed `409 busy`: ccd's answer, before anything is pasted, when another turn holds the session or (code awaiting_approval) its pane shows a dialog a paste would answer. It proves nothing was sent, so a re-send is safe.

View Source
const KickoffEmptyReplyReason = "kickoff turn returned an EMPTY reply, so it is recorded as NOT " +
	"delivered: the gateway answered without error and with no text. The known cause is a " +
	"reasoning model behind the agent runtime's /v1/responses, which discards its own " +
	"successful retry for that model class, so the agent may have done the work anyway. Pin a " +
	"non-reasoning model for this agent, and check its logs or transcript before re-sending."

KickoffEmptyReplyReason is written to agents.kickoff_error when the first turn came back with no text.

View Source
const KickoffNeverConnectedReason = "kickoff turn NEVER REACHED the agent runtime: the " +
	"connection could not be opened, so the turn was not sent and nothing was paid. The row " +
	"was already marked delivered, so it is not retried automatically"

KickoffNeverConnectedReason opens agents.kickoff_error when a stamped first turn failed because the connection to the agent runtime could not be OPENED (a dial error: DNS, connection refused, unreachable). internal/agentkickoff writes it; KickoffResendSafe reads it. One constant, so the writer and the reader cannot drift apart.

🔴 IT IS ONE OF THE TWO POST-STAMP CAUSES THAT PROVE NOTHING WAS SENT (the other is KickoffNotAcceptedReason). Go's HTTP client reports a dial error only from opening a NEW connection, before any byte of the request is written on it, and it does not retry a POST whose bytes were written. So no turn ran and none is running. (agentgateway.Gateway.Send can reach a dial only after a /v1/responses request that the runtime answered 404, meaning it has no such endpoint; that request ran no turn either.)

View Source
const KickoffNotAcceptedReason = "kickoff turn NOT ACCEPTED by the agent runtime: it answered " +
	"not_ready (its session was not at the prompt) for the whole delivery, so nothing was sent. The " +
	"row was already marked delivered, so it is not retried automatically"

KickoffNotAcceptedReason opens agents.kickoff_error when the runtime was reached but kept refusing the first turn with a typed `not_ready` — ccd's answer before the Claude Code CLI is at its prompt, given before anything is pasted — until the delivery gave up (its bound, or this process shutting down). Like KickoffNeverConnectedReason, it proves nothing was sent, so a re-send is safe.

View Source
const MaxKickoffAttempts = 3

MaxKickoffAttempts bounds how many times the kickoff message may be DELIVERED for one agent — the initial dispatch plus each recovery re-send after the receiving instance died.

It exists because the recovery below is otherwise unbounded against an agent that dies DETERMINISTICALLY: the out-of-memory kill that motivated it (a real-repository clone plus install against a small memory limit) reproduces on every retry, so an uncapped re-send would re-run an expensive model kickoff every tick, forever, silently. Spending the budget is what converts "silently stuck" into "visibly failed".

View Source
const MaxToolLoopIterations = 8

MaxToolLoopIterations caps the call→execute→continue loop per user turn.

⚠ IT IS EXPORTED SO A CALLER CAN REASON ABOUT THE CEILING IT IMPLIES: each iteration is its own HTTP request with its own client timeout, so a turn-level budget is this many multiples of that — see agentgateway.DefaultTurnTimeout, whose doc asserted the opposite until an audit measured it.

View Source
const NamespacePrefix = "devpod-"

NamespacePrefix is the DEFAULT prefix an agent's Agent.Namespace is built from: the prefix plus the agent's slug Name.

🔴 IT IS A DEFAULT, NOT THE VALUE, AND THAT DISTINCTION IS A FIX FOR A MEASURED LIVE DEFECT. It used to be the value — NamespaceFor took only a name and returned NamespacePrefix+name — while the provisioning driver used the prefix its OWN configuration named. Two literals, in subsystems that never talk, and nothing fails when they differ: the value is recorded, displayed and labelled, never used to place anything, so `kubectl -n <what the row says>` returns nothing and reads as "the agent was never provisioned" while the instance is running one namespace over. Measured live on a deployment that sets MUSTER_AGENT_NAMESPACE_PREFIX=muster-agent-: a freshly provisioned agent's row said `devpod-lively-newt` while the driver had created `muster-agent-lively-newt`.

The two sides now read ONE configured value. api.Extensions.AgentNamespace is the row-writing path's only expression, the deployment's MUSTER_AGENT_NAMESPACE_PREFIX feeds it and the driver from the same config field, and TestTheStoredNamespacePrefixIsWhatTheDriverIsConfiguredWith holds the pair against the namespace the driver DEMONSTRABLY creates — for a configured prefix and not only for this default, which is the case the old guard exempted by design and is why the defect shipped.

View Source
const NoteWithheld = "[kickoff note withheld]"

NoteWithheld replaces any part of the pending note found inside text a surface emits. See ScrubNote.

View Source
const ProvisioningStuckTimeout = 15 * time.Minute

ProvisioningStuckTimeout bounds how long an agent may dwell in provisioning before the reconciler gives up and errors it. It is safely greater than any reasonable readiness timeout so a slow-but-healthy instance has room to recover before the backstop fires.

View Source
const SearchSessionsMaxLimit = 50

SearchSessionsMaxLimit bounds what a caller can ask for, whatever it passes.

⚠ A limit <= 0 IS THE CALLER'S BUG AND YIELDS AN EMPTY PAGE, not everything — the same direction ListChatMessagesPage chose, and for the same reason: this reader is reachable from a query string.

View Source
const StoppedReapClaimLease = time.Hour

StoppedReapClaimLease is how long a reaper's claim on a row excludes another claim. A claim is normally followed at once by the teardown, which deletes the row; the lease only matters when the teardown removed the instance but not the row, and then the row is claimable again after it.

View Source
const TerminalReadOnlyFlag = "-r"

TerminalReadOnlyFlag is tmux's read-only attach flag. With it the client's keys are ignored by tmux itself — the second of two layers, the first being that muster forwards no input to a read-only terminal at all (internal/api's terminal handler).

View Source
const TurnEndedNotRun = `{"error":"not run: your turn ended (you asked your owner a question) before this call; wait for their answer"}`

TurnEndedNotRun is the output of a call made in the same round as, and after, a tool that ended the turn (EndTurn): it was not run.

Variables

View Source
var CheckoutWaitTimeout = DefaultCheckoutWaitTimeout

CheckoutWaitTimeout is the bound in force: DefaultCheckoutWaitTimeout unless cmd/muster-server set MUSTER_CHECKOUT_WAIT_TIMEOUT, which it applies with SetCheckoutWaitTimeout once at boot, before any deliverer runs.

⚠ IT IS MEASURED FROM THE ROW'S updated_at — its last real transition — NOT from when the wait was first recorded (DecideFirstTurn's dwell). Recording or refreshing the wait marker (SetKickoffError) does not move updated_at, so a raised bound applies to an agent ALREADY waiting the moment a server carrying it starts: its deadline becomes updated_at + the new bound.

View Source
var ClaudeCodeModels = []string{"opus", "sonnet", "haiku"}

ClaudeCodeModels are the models the picker offers for a Claude Code session. Aliases, so a model release does not need a muster release; any id matching the pattern above is accepted from the API as well.

View Source
var ErrArchivePrimary = errors.New("the primary chat cannot be archived; start a fresh primary instead, which archives this one")

ErrArchivePrimary refuses archiving an agent's primary chat: make another chat primary first (a fresh primary does both at once).

View Source
var ErrFreshPrimaryBusy = errors.New("a fresh primary is already being made")

ErrFreshPrimaryBusy: another fresh primary of the same agent holds its primary right now; nothing was changed.

View Source
var ErrModelNotCredentialed = errors.New("model provider has no credential in the agent")

ErrModelNotCredentialed is what every ValidateModelCredential refusal wraps, so an HTTP handler can answer 400 (the operator typed a bad slug) instead of 500 (the server broke). Without it a refusal is indistinguishable from a database failure at the call site, and the operator gets "could not create agent" with the corrected slug hidden in a server log.

View Source
var ErrNoTerminal = errors.New("agents: this agent's kind has no terminal to attach to")

ErrNoTerminal is the refusal for an agent whose kind has no terminal to attach to.

View Source
var ErrResponsesUnsupported = errors.New("agent runtime does not support /v1/responses (HTTP 404)")

ErrResponsesUnsupported signals the agent runtime lacks /v1/responses (404), so the caller should fall back to /v1/chat/completions (no tools).

Kinds is every kind this build knows, in the order a picker shows them. It is the same set the latest agents_kind_check admits (migration 0047); a test pins the two.

View Source
var ModelOptions = []ModelOption{
	{Value: "openrouter/xiaomi/mimo-v2.5", Default: true},
	{Value: "openrouter/deepseek/deepseek-v4-flash-0731"},
	{Value: "openrouter/auto"},
}

ModelOptions are the suggested models surfaced in the dispatch form's model selector. Extend this slice to add more suggestions; the field stays typeable so unlisted slugs still work.

View Source
var SessionRuntimes = []string{SessionRuntimeClaudeCode}

SessionRuntimes is every explicit runtime, in the order a picker shows them.

Functions

func BuildUniqueAgentName

func BuildUniqueAgentName(ctx context.Context, store Store) (string, error)

BuildUniqueAgentName returns a name that is not TAKEN, where taken means "held by a live agent, OR ever held by one that was destroyed".

🔴 A DESTROYED AGENT'S NAME IS NEVER REISSUED, AND THE REFUSAL IS THE WHOLE POINT OF THE LOOP RATHER THAN A TIDINESS RULE. The name is the provisioning driver's Ref.Name, so it is what the per-instance namespace and the ServiceAccount are named after. A namesake reuses both: whatever a partial Destroy left in that namespace, and anything bound to that ServiceAccount name out of band (a hand-made RoleBinding, say), passes to it silently. (The strongest version of this argument — muster's own granted ClusterRoleBindings outliving the row — went away with the privilege subsystem; the namespace and ServiceAccount reuse did not.) The enforcement lives in the STORE — PGStore.NameExists consults the agent_retired_names ledger that migration 0002's AFTER DELETE trigger fills — because a check written here would only cover this one call path, while the trigger covers every DELETE in any binary.

🔴 A RETIRED NAME IS NEVER FREED, SO THE POOL ONLY SHRINKS — AND THAT IS WHY THIS FUNCTION MUST NOT BE ABLE TO FAIL FOR WANT OF A NAME. 16 adjectives x 16 nouns is 256 combinations. An earlier revision took ten draws and then returned an error, which with k of 256 consumed is a provisioning failure with probability (k/256)^10 — and since k only ever goes UP, that probability is a clock. The failure would land on the operator as "creating an agent stopped working", at a moment nobody chose, for a reason nothing in the UI names.

So the draws are a FAST PATH, not the whole search. When all of them collide the last drawn name is DISCRIMINATED — `brave-heron` becomes `brave-heron-2`, `-3`, … — counting up until the store says free. The namespace that search walks is unbounded in every sense that matters:

  • The only ceiling is provision.Ref's own, asked HERE rather than restated: a candidate the provisioner would refuse is refused here instead of being handed on. That package caps a name at 48 characters today and the longest name this pool can produce is 12 (`clever-otter`), which leaves 35 digits of discriminator — on the order of 10^35 names per base, against a pool whose entire supply of bases is 256. It is not a cliff that has been moved; it is a number no deployment reaches. TestTheDiscriminatorCeilingIsDerivedFromProvisionRef re-derives it from provision.Ref.Validate rather than trusting this paragraph.
  • The discriminated candidate is tested through THE SAME PREDICATE as a drawn one — store.NameExists, which consults live rows AND the tombstone ledger. There is deliberately no second existence check here: one rule, one place, or a discriminated name becomes the one path the tombstone does not cover.

🔴 THE ONLY BOUND ON THE SEARCH IS REQUEST CANCELLATION. NOT A DEADLINE — THERE IS NONE ON THIS PATH. An earlier revision of this paragraph said "the caller already owns a deadline (see agentprovision's opCtx)". That is false: opCtx is never in this call path. BuildUniqueAgentName has exactly one caller, internal/api's createAndDispatchAgent, reached from handleAPIAgentCreate, handleChiefProvision and agent_dispatch — each hands it its request's context. cmd/muster-server sets only ReadHeaderTimeout on its http.Server: no WriteTimeout, no http.TimeoutHandler, and no context.WithTimeout anywhere between the handler and here. So `ctx` is done when the CLIENT DISCONNECTS, and at no other moment.

That justification is therefore withdrawn rather than replaced. The loop has no deadline bound; it has a cancellation bound, and ctx.Err() is checked on every iteration so a cancelled caller gets an answer even from a store that ignores its context. TestBuildUniqueAgentNameStopsWhenTheCallerCancels is what pins that, and it is the whole of it.

⚠ WHY THAT IS TOLERATED, AS SCALE RATHER THAN AS A BOUND. Reaching a hundred discriminators on one base takes on the order of 25,600 agent creations, because the discriminators fill in across all 256 bases. The consumption rate measured on the live deployment is ≈19.5 names/month — TWO ENDPOINTS IN ONE 53-DAY WINDOW, quoted at that scope only — which puts 25,600 creations a century out. A run of the loop costs one NameExists round trip per occupied discriminator on the drawn base, so the work per call is set by how many names have actually been issued, not by anything unbounded.

⚠ AND THE DECISION, STATED RATHER THAN ASSUMED: THE LOOP GETS NO CAP OF ITS OWN. A cap is a new exhaustion cliff, and the cliff is the thing this fallback exists to remove — the previous revision's error return was exactly that, and it made agent creation fail at a moment nobody chose. The case a cap would catch is a store whose NameExists answers `true` for everything: that spins, with nothing logged, until the request is cancelled. It is a BROKEN STORE, not a full pool, and this function is not the right place to diagnose one — it has no logger, and giving it one would thread a dependency through a pure function for a failure mode with no production instance. What it does instead is make the spin legible when it ends: the cancellation error names how many discriminators were tried.

⚠ IT DOES NOT CHANGE THE SHAPE OF AN ORDINARY NAME. The fast path returns exactly what it always did, so every name already issued, every namespace and ServiceAccount named after one, and every guard that asserts the adjective-noun format of generateName's output are untouched. The discriminator is what a deployment sees only after 10 consecutive collisions.

func ChatCompletionsURL

func ChatCompletionsURL(ep provision.Endpoint) string

ChatCompletionsURL is the agent runtime's /v1/chat/completions URL, derived from wherever the provisioner says that instance is reachable.

It is the sibling of ResponsesURL and shares its reasoning about taking an endpoint rather than a name, including the trailing-slash trim: Endpoint.Path is a BASE path, and a caller that spelled it "/agent/" would otherwise produce a double slash some routers treat as a different route.

func ChatStream

func ChatStream(ctx context.Context, client *http.Client, url, token, sessionKey, model string, messages []ChatMessageIn, emit func(delta string)) (string, error)

ChatStream POSTs a streaming chat-completions turn to the agent runtime and invokes emit for each assistant content delta, returning the full assembled assistant text. A nil emit just assembles.

model is the runtime's passthrough sentinel and is REQUIRED on the wire — the same input RunToolLoop takes, for the same reason: the value belongs to the attached runtime, not to this package. See agentgateway for where it comes from.

🔴 A MALFORMED DATA LINE IS SKIPPED, NOT FATAL, AND THAT IS A DELIBERATE ASYMMETRY WITH THE STATUS CHECK ABOVE IT. A stream that begins is a stream the runtime accepted; one unparseable chunk in the middle of a good turn would otherwise discard every delta that already arrived. A bad STATUS, by contrast, means the turn never started and is an error.

func CheckTerminal

func CheckTerminal(kind string) error

CheckTerminal is ErrNoTerminal for a kind with no terminal to attach to, and nil for one with.

func CheckoutGates

func CheckoutGates(a Agent, inst *provision.Instance) bool

CheckoutGates reports whether the checkout decides this tick's first turn: the agent needs one, has not been kicked off, is not errored, and its instance is ready (the only state in which a first turn would otherwise be sent or the ready-but-never-kicked dwell bound applied). It is the ONE predicate the deliverer routes on and DecideFirstTurn gates on.

func ChiefNameFor

func ChiefNameFor(owner int64) string

ChiefNameFor is the reserved slug of user owner's chief (accounts PR 3b: one chief PER USER). The operator — user 1 — keeps ChiefName itself, so the single-user deployment, its namespace and `muster chief ask`'s default are unchanged; every other user's chief is "chief-<id>".

🔴 agents.name IS ONE GLOBAL NAMESPACE (it keys the instance's namespace), so two users cannot both be "chief"; the id suffix is what makes each user's reserved slug unique without a lookup. The adjective-noun pool can mint none of these (it has no "chief"), and migration 0009's partial unique index holds one reserved chief per owner.

func ClaudeContextWindow added in v0.201.0

func ClaudeContextWindow(model string) int64

ClaudeContextWindow is the context window, in tokens, of a Claude model as muster names one — an alias (opus, sonnet, haiku) or a claude-* id — and 0 for any other (a claude-code chief on its CLI's unknown default included) model: 1,000,000 with the CLI's "[1m]" suffix, else 200,000, the window every current Claude model has by default.

⚠ IT IS A TABLE OF MUSTER'S, NOT A READING: Claude Code reports no window. A model released with a different default window needs this changed.

func ComputeStatus

func ComputeStatus(a Agent, inst *provision.Instance) string

ComputeStatus reconciles the STORED agent status with the LIVE instance state to produce the status shown on the card. The stored status is authoritative for error and for the "provisioned but never started" (stopped) case; the live phase refines running/provisioning.

🔴 IT TAKES A provision.Instance, NOT A POD. Upstream this read a `PodInfo` built from the Kubernetes API, and switched on that API's own phase spellings ("Running", "Pending", "Failed") as bare strings. Both are now the provisioner contract's vocabulary, which is what lets this function answer for an agent running under any driver — and the provision.Phase constants are typed, so a misspelling is a compile error rather than a branch that silently falls through to the default.

⚠ inst.Reason IS STILL A DRIVER-DEFINED STRING and the three values matched below are the Kubernetes driver's spellings. That is deliberate rather than an oversight: the contract does not enumerate reasons, and a driver that reports none simply never takes this branch — it falls through to the phase, which every driver does set. See provision.Instance.Reason.

func DefaultModelOption

func DefaultModelOption() string

DefaultModelOption returns the pre-selected model slug (empty if none flagged).

func DescribeKickoffLoss

func DescribeKickoffLoss(a Agent, inst *provision.Instance) string

DescribeKickoffLoss renders WHY the recipient is judged gone, in the terms an operator can act on. The backend's last-termination reason is the load-bearing part: "OOMKilled" turns "the agent never started" into "the agent's memory limit is too small for this repository", which is a capacity finding rather than a mystery. Without it a restart is just a number.

func EndTurn added in v0.161.0

func EndTurn(ctx context.Context) bool

EndTurn sets ctx's turn-end mark; a no-op for a ctx without one (an MCP call). It reports whether there was a mark to set.

func InstanceFailed added in v0.116.0

func InstanceFailed(inst *provision.Instance) bool

InstanceFailed reports whether a live instance ITSELF shows a failure — a crash loop, an image that will not pull, a failed phase — whatever the stored row says. ComputeStatus's instance half of `error`; chief_restart reads it to end its wait early on a new pod that is failing (a stored `error` alone is not that evidence).

func InstanceIndex

func InstanceIndex(insts []provision.Instance) map[string]*provision.Instance

InstanceIndex maps an agent NAME to its live instance, for quick reconciliation against a stored agent list.

🔴 THE KEY IS Ref.Name, NOT THE GROUP. Upstream keyed this on the pod's namespace, because every agent had one and it matched Agent.Namespace. Group is the driver's own scoping unit and provision.Instance states it is EMPTY where the concept does not apply — so a group-keyed index collapses every instance of a non-namespaced driver onto the single key "", and the last one wins. Ref.Name is the contract's identity and is always set.

func IsChiefName

func IsChiefName(name string) bool

IsChiefName reports whether name is a reserved chief slug — ChiefName, or ChiefNameFor some other user. The instructions branch on it (agentprovision.buildSpec) and deletion protection covers it.

func IsClientTimeout added in v0.176.0

func IsClientTimeout(err error) bool

IsClientTimeout reports whether err is (or wraps) a ClientTimeoutError.

func IsJobWorktreeDir

func IsJobWorktreeDir(workingDir, dir string) bool

IsJobWorktreeDir reports whether dir is, as a string, a job worktree of an agent whose CLI works in workingDir: exactly JobWorktreeDir(workingDir, n) for some positive n. It checks the string only; whether the directory exists is the caller's to check.

func JobWorktreeDir

func JobWorktreeDir(workingDir string, jobID int64) string

JobWorktreeDir is job jobID's worktree for an agent whose CLI works in workingDir.

func JobWorktreesDir

func JobWorktreesDir(workingDir string) string

JobWorktreesDir is the directory holding the worktrees of the jobs of an agent whose CLI works in workingDir.

func KickoffAwaitingGrant

func KickoffAwaitingGrant(a Agent) bool

KickoffAwaitingGrant reports a first turn held because the agent's github connector request is not approved yet: the agent page's "waiting for your github approval" notice. Like KickoffOwed it is a separate boolean, never a status. An errored row answers false: the wait ended (see DecideFirstTurn).

func KickoffErrorSuffix

func KickoffErrorSuffix(a Agent) string

KickoffErrorSuffix appends the recorded send failure to the terminal error when one exists, so the red card carries the primary evidence ("unexpected EOF") instead of making someone go find the server log before it rolls.

func KickoffFailed

func KickoffFailed(a Agent) bool

KickoffFailed reports a first turn that was HANDED to a gateway and did not complete: the row is stamped Agent.KickedOff and a failure is recorded in Agent.KickoffError. In SQL, `kicked_off AND kickoff_error <> ”`.

🔴 IT EXISTS BECAUSE THE STAMP CLEARS KickoffOwed. internal/agentkickoff stamps kicked_off BEFORE the paid turn so a turn is never run twice, and does not retry a turn that fails after the stamp (an operator decision: at-most-once). So a failed, empty, timed-out or shutdown-cancelled first turn turns the "kickoff owed" badge OFF while nothing was delivered — and before this predicate the failure lived only in kickoff_error, which no page rendered. This is that state, as its own signal.

It is the same SHAPE as KickoffOwed and for the same reasons: a separate boolean beside the status, never a sixth status value. The two are MUTUALLY EXCLUSIVE by construction (one requires kicked_off, the other its negation), so a card never carries both badges. TestKickoffFailedTruthTable covers every cell.

⚠ IT DOES NOT READ THE NOTE. An agent kicked off by an upstream writer with no stored note but a recorded send failure still failed its kickoff, and says so.

⚠ WHAT KEEPS IT FROM FIRING ON A SUCCESS: every production write of kickoff_error on a kicked-off row is a post-stamp FAILURE (agentkickoff.recordError after the stamp); agentprovision writes it only on a never-kicked-off row; and a successful first turn's agents.Store.RecordKickoffDelivery clears it — or, when that write failed, the deliverer clears it itself.

🔴 AND IT DOES NOT OUTLIVE A LATER SUCCESS. The failed first turn is never retried, so before the next clause existed nothing ever cleared it: an agent that went on to complete many turns (operator chat, chief nudges and asks, plugin and memo deliveries) read "kickoff failed" for ever. Now ANY later turn that completes — no error and a non-blank reply — clears it through agents.Store.ClearKickoffFailure, called from the one place every turn passes (internal/agentgateway's Send / SendWithTools). kicked_off and kickoff_attempts are untouched, so nothing is re-sent. A failed, timed-out or blank later turn leaves the record.

⚠ EXCEPT A RESEND-SAFE CAUSE (KickoffResendSafe: never connected, not accepted, busy). That cause proves the task was never delivered, and a later turn that completed did not carry it, so the badge and its re-send remedy stay until the operator re-sends. Only causes under which the task may have arrived (timeout, shutdown, transport error, empty reply, unrecognised text) clear.

func KickoffFailureText

func KickoffFailureText(a Agent) string

KickoffFailureText is the error text a surface may show for a failed kickoff: Agent.KickoffError with the pending note scrubbed out (ScrubNote), or "" when KickoffFailed is false. It is the ONE reader both tiers use, so the scrub cannot be present on one and missing on the other.

func KickoffOwed

func KickoffOwed(a Agent) bool

KickoffOwed reports whether this agent still OWES its first turn: a kickoff message is stored on the row (Agent.PendingNote) and nothing has delivered it (Agent.KickedOff is false).

🔴 IT IS A SEPARATE SIGNAL AND NOT A SIXTH STATUS, DELIBERATELY. The five values above are the agents.status CHECK constraint, they key DecideReconcile's decision table, and every consumer switches on them; a new member would reach all of that untested. This answers an ORTHOGONAL question — "was this agent ever told what to do" — which is why it is true ALONGSIDE every one of the five rather than instead of one. ComputeStatus does not read it and must not, and TWO guards divide that claim rather than one: TestTheStatusEnumDidNotGrowToCarryAnOwedKickoff pins the declared values and ComputeStatus' OUTPUT SET, while TestAnOwedKickoffSurvivesEveryStatusIncludingRunning pins that an owed agent on a live ready instance still computes `running`. The second is the one that catches a ComputeStatus which READS these columns and answers one of the five anyway — measured: a mutant returning StatusError for an owed agent leaves the output set unchanged, so the enum guard alone is blind to it.

🔴 WHY IT IS WORTH RENDERING AT ALL, WHICH IS A MEASURED DEFECT AND NOT A POLISH ITEM. An agent brought up by agentprovision.Adapter.Start with its note never delivered reaches a live, ready instance, and ComputeStatus refines that to StatusRunning — a branch that reads neither PendingNote nor KickoffError. BEFORE this function had a reader the card therefore read HEALTHY over an agent that was never told what to do, and the only evidence was machine-tier columns: agents.pending_note, which had no reader at all, and agents.kickoff_error, which reaches one hook-token-gated JSON route. `running` + owed is the exact combination this exists to make visible, and it is the combination the guard asserts — a fixture that cannot produce it cannot see the bug.

⚠ THE PendingNote CONJUNCT IS NARROWER THAN internal/agentprovision'S OWN `!ag.KickedOff` TEST, AND THAT IS THE POINT RATHER THAN A DISAGREEMENT. Start records a non-delivery whenever the agent was never kicked off; this reports a first turn that is owed, and with no stored message there is no turn to deliver — an agent created with no note text has nothing outstanding, so flagging it would be a badge on every agent that was simply never dispatched with one. Both conjuncts are load-bearing and both are mutation-covered by TestKickoffOwedTruthTable.

⚠ IT SAYS NOTHING ABOUT WHY. A refused dispatch (status `error`, nothing provisioned) and a running pod whose note was never handed over both answer true, because both owe the same turn. The reason lives in agents.error_message / agents.kickoff_error.

func KickoffResendSafe

func KickoffResendSafe(a Agent) bool

KickoffResendSafe reports whether a failed kickoff's recorded cause PROVES no turn is running for it, so re-sending the task cannot pay for it twice. Only KickoffNeverConnectedReason, KickoffNotAcceptedReason and KickoffBusyReason prove that.

🔴 EVERY OTHER CAUSE ANSWERS false, AN EMPTY REPLY INCLUDED. A shutdown or a timeout abandons a request the runtime already received and may still be running. A transport error after the request was written says nothing about the runtime's side. And an empty reply is not a finished turn either: KickoffEmptyReplyReason itself names the cause as a runtime that DISCARDS ITS OWN SUCCESSFUL RETRY, so the work may have been done, or may still be under way, behind the empty answer.

⚠ IT READS kickoff_error BY ITS PREFIX, which muster writes from the constant above. An unrecognised text answers false, the side that tells the operator to check before re-sending.

func KindLabel

func KindLabel(kind string) string

KindLabel is the human name a picker and a card show.

func KindTurnTimeout

func KindTurnTimeout(kind string) time.Duration

KindTurnTimeout is the per-request budget a kind's turns need, or ZERO for "use the gateway's configured client unchanged" — which is what the gateway kind gets, so its behaviour is byte-identical to before kinds existed.

func LastActivity

func LastActivity(a Agent, lastMessage time.Time) time.Time

LastActivity is THE definition of when an agent was last active: the newer of its row's UpdatedAt and lastMessage, the created_at of its most recent persisted transcript message (the zero time when it has none).

It is the ONE rule both tiers use. GET /api/agents publishes it as `lastActivityAt` (internal/api's newAgentJSON, whose field comment is the full contract: what moves each half, and what neither can see), and the sidebar orders its agents by it (SortByLastActivity) and tints each row's recency dot by it. Before this function the API computed it inline while the (since retired) Agents list was ordered by CREATION time and labelled UpdatedAt "active" — three answers to one question, which is how the list read as unsorted.

Why these two and not created_at: UpdatedAt already starts AT created_at (the row is inserted with both set to now()) and only moves forward, so created_at can never be the newer one; and a transcript message is the only durable trace of an agent WORKING, which UpdatedAt deliberately does not follow (see the API field comment — an agent running a long task has a frozen UpdatedAt).

func MarkTurnAccepted added in v0.132.0

func MarkTurnAccepted(ctx context.Context, a TurnAcceptance)

MarkTurnAccepted runs ctx's WithTurnAccepted callback, if any. The transport calls it on ccd's 103; a test's fake runtime calls it to play a ccd that took the text in lane a.Lane.

func MarkTurnActivity added in v0.165.0

func MarkTurnActivity(ctx context.Context)

MarkTurnActivity runs ctx's WithTurnActivity callback, if any. The transport calls it per read; a test's fake runtime calls it to play a stream.

func ModelFallbacksFor

func ModelFallbacksFor(configured []string) []string

ModelFallbacksFor resolves the runtime fallback chain for a configured list: the caller's own when it set one, the built-in otherwise.

⚠ AN EMPTY SLICE MEANS "UNSET", NOT "NO FALLBACKS". Nothing in this package can tell the two apart — a caller that genuinely wants an agent with no fallback at all has to say so some other way. Stated here because the alternative reading is the one a reader arrives with.

func ModelProvider

func ModelProvider(slug string) (string, bool)

ModelProvider reports the provider the agent runtime will resolve a model slug to, and whether that provider is determinable FROM THE SLUG ALONE.

It mirrors the runtime's own model-reference parser, read out of the live agent image rather than out of its documentation: trim, split on the FIRST "/", provider = the left half, lowercased.

⚠ ok=false for a slug with NO "/", and that is a deliberate limit, not an oversight. That parser falls back to a default-provider argument in that case — a value resolved inside the agent process from its own config, which this service cannot see at provision time. Judging such a slug would be a guess, and a guessed refusal is worse than no refusal. Slugs WITH a "/" — which is every slug this service's own model picker and ModelOptions produce, and the shape the live defect had — are decided exactly.

⚠ NO ALIAS TABLE, ON PURPOSE. The runtime also normalises provider aliases (z-ai and z.ai both become zai, and there are a dozen more). Reproducing that table here would be a second copy of someone else's data, free to drift — and it would change NOTHING: not one alias in that table maps to the credentialed provider, so normalisation cannot flip this function's verdict. The cost is cosmetic: the message below names the prefix as the operator typed it ("z-ai") while the agent's log names the normalised id ("zai"). That is a fair trade for a table that cannot go stale.

func NamespaceFor

func NamespaceFor(prefix, name string) string

NamespaceFor builds an agent's namespace from a CONFIGURED prefix and its slug name.

🔴 THE PREFIX IS A PARAMETER SO THAT NO CALLER CAN GET A NAMESPACE WITHOUT DECIDING ONE. This took only a name until the defect above; a zero-argument spelling is what let a caller capture the package constant while the driver used something else, and the caller looked correct at every line. An empty prefix resolves to the default via ResolveNamespacePrefix rather than producing a bare slug.

⚠ PREFER api.Extensions.AgentNamespace ON THE ROW-WRITING PATH. That method is the one expression the HTTP layer uses and the one the guard reads; this function is what it is built from.

func NeedsCheckout

func NeedsCheckout(a Agent) bool

NeedsCheckout reports whether an agent's first turn depends on a repository checkout: a claude-code agent dispatched with a repository (its supervisor, ccd, clones it before the agent starts and reports `repo.state`). A gateway agent, or one without a repository, never waits.

func PastFirstRequest

func PastFirstRequest(err error) bool

PastFirstRequest reports whether err is a RunToolLoop failure after its first request — one that must never be read as "nothing was sent".

func PromoteToRunning

func PromoteToRunning(a Agent, inst *provision.Instance) bool

PromoteToRunning reports whether an agent STORED as `provisioning` should now be stored as `running`: its live instance computes to running (ComputeStatus — present, phase running, ready, not crash-looping). It is the decision internal/agentstatus acts on; nothing else writes this transition.

🔴 IT DOES NOT WAIT FOR THE FIRST TURN. An agent whose kickoff is still owed is promoted too, because that is what every view already shows for it — a `running` dot plus the separate "kickoff owed" badge (KickoffOwed); a stored status that kept saying `provisioning` for the same agent was the defect. The owed turn's dwell bound is unaffected: DecideReconcile's ready-but-never-kicked branch keys on updated_at, which the promotion moves once, by one tick.

Only `provisioning` is promoted. `pending` is a row that was never dispatched, `stopped` was put there by a Stop and `error` is sticky; none of them is this function's to overrule.

func RefOf

func RefOf(a Agent) provision.Ref

RefOf is the one place an agent row becomes a driver reference.

🔴 IT KEYS ON Name, NOT ON Namespace, AND THE DIFFERENCE IS A SILENT ONE. api.Server.instanceIndex indexes live instances by provision.Instance.Ref.Name — InstanceIndex's own doc says Group is empty for a driver with no namespacing concept, so a group-keyed index collapses every instance onto "". A reference built from the namespace would not fail: it would resolve to nothing, and every agent would render stopped while running perfectly.

🔴 IT LIVES HERE, NOT IN THE PACKAGE THAT FIRST NEEDED IT, BECAUSE THERE ARE NOW TWO CONSUMERS AND A SECOND COPY WOULD BE WRONG IN THE SAME WAY. It was an unexported refOf in internal/agentprovision; internal/agentgateway needs the same mapping to ask the driver where an agent is reachable, and a lifecycle call and a chat call that disagreed about an instance's identity would each work in isolation — the pod would start, and chat would resolve no endpoint for it. One function is what makes them agree by construction.

func ResolveDisplayNameSource added in v0.170.0

func ResolveDisplayNameSource(src string) string

ResolveDisplayNameSource is src as stored: one of the four, "" (or anything else) as NameDefault.

func ResolveKind

func ResolveKind(kind string) string

ResolveKind maps the unset kind to KindGateway — the one place that default is spelled. A row read from the database always carries a kind; an Agent built in Go (every fake store, every test fixture) may not.

func ResolveModel

func ResolveModel(agentModel, deploymentDefault string) string

ResolveModel picks the slug an agent is provisioned with, in precedence order: the agent's own model, then the deployment-wide default, then the built-in.

🔴 THE PRECEDENCE IS THE WHOLE FUNCTION, AND IT IS WHY THIS IS NOT INLINED AT THE CALL SITE. Upstream the same three-way choice was open-coded inside the deployment renderer, so the only thing that could test it was a test that rendered a whole deployment and dug the slug back out of a nested map — coverage that disappears the moment the renderer changes shape. It is a pure choice over two strings; it belongs where it can be asserted as one.

⚠ EMPTY MEANS UNSET AT BOTH LEVELS. An operator cannot express "no model" by clearing the field; that is what makes the fall-through total, and it is why the built-in must itself be a slug the agent can authenticate (see TestOwnSlugsPass).

func ResolveNamespacePrefix

func ResolveNamespacePrefix(raw string) string

ResolveNamespacePrefix is the ONE place an unset prefix becomes NamespacePrefix.

🔴 EVERY DEFAULTING SITE MUST BE THIS CALL. Two places resolving "" — the binary's config load and the HTTP layer's wiring — is how one of them comes to hold a different literal, which is the defect described above in miniature. Whitespace resolves to the default too: an operator's trailing newline in a ConfigMap would otherwise build a namespace Kubernetes refuses, inside a dispatch goroutine.

func ResponsesURL

func ResponsesURL(ep provision.Endpoint) string

ResponsesURL is the agent runtime's /v1/responses URL, derived from wherever the provisioner says that instance is reachable.

🔴 IT TAKES AN ENDPOINT BECAUSE UPSTREAM IT TOOK A NAME AND BUILT THE ADDRESS ITSELF. The upstream body interpolated the agent's name twice into a fixed in-cluster DNS format string, prefixed "http://" and appended the path — one cluster's DNS layout, one port, one scheme, hardcoded with no override anywhere in the codebase: not an environment variable, not a config field, not a per-agent one. Reaching an agent through anything that was not that specific cluster was simply not expressible. provision.Endpoint is the replacement, and it has three layers behind it (a per-instance override on the Spec, the driver's configurable template, the driver's default), so this function's whole job is now the path suffix.

The trailing-slash trim matters: Endpoint.Path is a BASE path and a caller that spells it "/agent/" would otherwise produce a double slash, which some routers treat as a different route.

func RunToolLoop

func RunToolLoop(
	ctx context.Context,
	client *http.Client,
	url, token, sessionKey, model, instructions, userMessage string,
	tools []ToolDef,
	dispatch ToolDispatch,
	emit StreamEmit,
) (string, error)

RunToolLoop runs the /v1/responses call→execute→continue loop: POST {input, tools, instructions}; for each function_call, dispatch it and feed back a function_call_output; stop when the model emits no function_call (terminal text) or the iteration cap is hit. Each turn streams live via streamResponses — text/thinking deltas reach emit as they arrive; before each tool dispatch a "tool_call" event fires, after it a "tool_result" event. emit is OPTIONAL (nil-safe; the kickoff path passes nil and only the assembled text is used).

Re-dispatch guard: the loop only continues while the model keeps emitting function_calls and is hard-capped at MaxToolLoopIterations, so a mid-turn failure cannot cause unbounded re-dispatch. The terminal-text turn (no calls) always stops the loop. RunToolLoop drives one user turn to completion: request, dispatch any function calls the model asks for, feed the outputs back, repeat.

🔴 model IS A PARAMETER RATHER THAN A CONSTANT, AND THE CALLER MUST SUPPLY THE ATTACHED RUNTIME'S OWN PASSTHROUGH SENTINEL. Upstream this was a hardcoded literal naming one specific agent image — a transport helper deciding what model a request names, which is neither its job nor portable. A runtime that runs whatever model its own configuration selects still requires the `model` field to be present and to carry the value IT expects; there is no neutral spelling this package can invent. See the carve note at the foot of this file.

func RunToollessTurn

func RunToollessTurn(
	ctx context.Context,
	client *http.Client,
	url, token, sessionKey, model, instructions, userMessage string,
	emit StreamEmit,
) (string, error)

RunToollessTurn runs ONE /v1/responses turn carrying NO tools and returns the assembled assistant text, streaming text/thinking deltas to emit (nil-safe). 404 → ErrResponsesUnsupported, unwrapped, so a caller can fall back to ChatStream.

🔴 IT EXISTS BECAUSE THE STREAMING CHAT-COMPLETIONS PATH LOSES A REASONING MODEL'S WHOLE ANSWER, AND THAT WAS MEASURED RATHER THAN REASONED. Against one live agent runtime, all else held identical and only the request changed: /v1/chat/completions with stream:true produced a role chunk, an EMPTY content delta and finish_reason=stop — zero content deltas, so ChatStream assembled the empty string and returned it with a nil error, which every caller reads as "the agent answered nothing". The same prompt over /v1/responses with stream:true returned the text, in two output_text deltas. Switching only the MODEL on the chat-completions path moved the delta count between 0 and 10, which is what identifies the model class rather than the request as the trigger — and the runtime's own log showed it rejecting the first non-reasoning attempt and retrying internally AFTER the HTTP call had already returned.

⚠ IT IS NOT RunToolLoop WITH NIL ARGUMENTS, AND THE DIFFERENCE IS A PANIC. That loop calls dispatch for every function_call the model emits; a nil dispatch there is a nil func call, i.e. a server crash, reachable the moment a runtime emits a call for a tool the request never offered. One turn with no loop cannot reach it.

⚠ THE TEXT COMES FROM response.completed, NOT FROM THE DELTAS, which is the same property RunToolLoop has: a stream that emits deltas and ends with [DONE] but no completion assembles to "", and one that simply stops (EOF, no [DONE]) is an error (parseResponsesSSE). That is the transport's contract, not a fallback this function adds.

func RunsPodSupervisor

func RunsPodSupervisor(kind string) bool

RunsPodSupervisor reports whether kind's image runs muster's OWN in-pod supervisor, ccd (claude-code), rather than the operator's gateway runtime. Such a kind gets a persistent /data volume, the repository checked out by the supervisor before the agent starts (and, so, the first turn held for it), a connected repository only, and the spec re-applied on every Start.

func ScrubNote

func ScrubNote(s, note string) string

ScrubNote returns s with every run of at least noteEchoMinBytes bytes (or the whole note, if it is shorter) that also occurs in note replaced by NoteWithheld. An empty note returns s unchanged.

🔴 WHY ERROR TEXT NEEDS THIS AT ALL: kickoff_error is muster-authored PREFIX plus, for a failed turn, the gateway's error — and agents' responses transport quotes up to 512 bytes of a non-200 runtime BODY into that error ("responses HTTP %d: %s"). A runtime that echoes the request it rejected therefore puts the operator's note — instruction text, `json:"-"` everywhere — into a column this package now surfaces on a public-repo service. The guarantee is "no 16-byte run of the note leaves the process through kickoff text", which is what this enforces.

🔴 RUNS, NOT ONLY THE WHOLE NOTE, BECAUSE THE QUOTE IS TRUNCATED. A 512-byte snippet of a body echoing a 2 KB note contains a PREFIX of it, which strings.ReplaceAll on the whole note would never match. Pinned by TestScrubNoteRemovesATruncatedEcho.

⚠ ITS LIMITS, STATED RATHER THAN IMPLIED: a fragment shorter than 16 bytes survives (an echo re-escaped every few characters would leak in pieces that small), and a TRANSFORMED echo — case-folded, re-encoded — is not recognised. Matching works on whole runes, so the output stays valid UTF-8.

func SessionRuntimeLabel

func SessionRuntimeLabel(runtime string) string

SessionRuntimeLabel is what the session list and the picker show.

func SetCheckoutWaitTimeout

func SetCheckoutWaitTimeout(d time.Duration)

SetCheckoutWaitTimeout replaces CheckoutWaitTimeout; d <= 0 restores the default. Call it at boot only: the deliverer reads the value unsynchronised.

func SortByLastActivity

func SortByLastActivity(list []Agent, lastMessage map[int64]time.Time)

SortByLastActivity orders list most-recently-active first by LastActivity, in place. lastMessage maps an agent ID to its newest transcript time; a missing entry is "no transcript" (the zero time), so a failed lookup degrades to ordering by UpdatedAt rather than to no order at all.

Ties — two rows touched in the same microsecond, which a batch writer produces — break by ID descending (newest agent first), so an idiomorph re-render never swaps two cards for a reason nobody can see.

func TerminalCommand

func TerminalCommand(kind string, readOnly bool, tag TerminalTag) ([]string, error)

TerminalCommand is the command that attaches a terminal to an agent's live session, or ErrNoTerminal for a kind without one. tag identifies the attach for TerminalReleaseCommand; a malformed one is refused, because an attach nothing can find is an attach nothing can end.

🔴 READ-ONLY IS AN ARGUMENT, NOT A DEFAULT THE CALLER CAN FORGET: the flag is the LAST argv element when set, so it is visible to anything that logs or inspects the command (the e2e fake backend reports it), and there is no spelling of this function that attaches read-write by omission.

🔴 EVERY ATTACH MUST BE FOLLOWED BY ITS RELEASE. The attached client outlives the exec stream that started it (see terminalReleaseScript), so whoever runs this command owes a TerminalReleaseCommand with the same tag once the stream ends, however it ends.

⚠ A CLIENT AFFECTS THE WINDOW SIZE EVEN WHEN READ-ONLY. Measured on tmux 3.7c: an `attach-session -r` client reports flags `ignore-size,read-only` and the window still took its size (200x50 → 60x19, then 45x29 on a resize), and KEPT it after the client detached (ignore-size only applies while some other client is NOT ignore-size). That is why the attach is no longer sized by the browser alone: internal/agentprovision asks the window's size first (TerminalSizeCommand) and never gives the client a size that would shrink it (internal/termsize) — a phone renders the wider TUI in a scrolling view.

func TerminalReleaseCommand

func TerminalReleaseCommand() []string

TerminalReleaseCommand is the command that ends the attach tagged TerminalReleaseInput's tag: run it as an ordinary (non-terminal) exec in the same container with that input on stdin. It prints "released N".

func TerminalReleaseInput

func TerminalReleaseInput(tag TerminalTag) string

TerminalReleaseInput is the stdin TerminalReleaseCommand reads its tag from.

func TerminalSizeCommand

func TerminalSizeCommand(format string) []string

TerminalSizeCommand is the command that prints the agent session's current window in the tmux format given (the caller's — internal/agentprovision passes termsize.TmuxWindowFormat; this package only knows WHERE the session is), for the no-shrink rule: the attach then sizes its client so the window is not shrunk. Its failure — no session yet, an image without tmux — means "size unknown", and the attach proceeds as it did before.

func TurnBearer

func TurnBearer(a Agent, derive func(hooksToken string) string) string

TurnBearer is the credential muster presents to a's turn API, and so the one a's pod must accept: a's own Agent.GatewaySecret when it has one, else derive over a's hooks token (the deployment's agentgateway.Runtime scheme).

🔴 ONE RULE, ONE PLACE. The sender (agentgateway's reach) and the spec builder (agentspec's claude-code Build, which ships the pod the value it must accept) both call this, so the two cannot disagree — a disagreement is a 401 on every turn that reads as a bad credential.

⚠ THE FALLBACK IS FOR ROWS, NOT FOR KINDS. Only claude-code rows are ever minted a secret (agentprovision's ensureGatewaySecret); every other kind, and a claude-code row whose pod predates the secret, keeps the derived bearer its pod was built with. Such a claude-code pod's session can derive that bearer from its own MUSTER_HOOK_TOKEN, and its ccd (from this change on) refuses to start on it. Stop then Start is the one route that moves such an agent over: Start re-applies a claude-code spec, which mints the secret and ships it (a claude-code model change is refused 409, so it is not a route).

func TurnEnded added in v0.161.0

func TurnEnded(ctx context.Context) bool

TurnEnded reports whether ctx's turn-end mark is set.

func ValidKind

func ValidKind(kind string) bool

ValidKind reports whether kind (after ResolveKind) is one this build knows.

func ValidWorkerPool

func ValidWorkerPool(name string) bool

ValidWorkerPool reports whether name may name a worker pool: 1-63 of [a-z0-9-], not starting with '-'.

func ValidateModelCredential

func ValidateModelCredential(slug string) error

ValidateModelCredential refuses a primary model slug whose provider this service will not have credentials for inside the agent.

Empty is always fine: it means "use the cluster default", which the provisioner supplies and which this same guard covers wherever an operator can set it.

🔴 IT REFUSES RATHER THAN WARNS. A warning reproduces the bug it is warning about — the whole failure mode is that nobody reads the pod log. Refusing at the moment the operator types the slug turns a fleet agent that has "never run on its configured model" into a 400 with the corrected slug in it.

⚠ WHAT IT CANNOT SEE. (a) A slug with no "/" — see ModelProvider. (b) The runtime can also resolve a provider key from the ENVIRONMENT, so an environment variable could in principle credential a second provider. Measured on a live agent, the only credential in its environment was the one this service puts there, and no privilege profile in this tree ships a provider key — so the agent's credential set is exactly the one profile the renderer writes. If that changes, widen credentialedAuthProvider (see its comment), not this function. (c) Opaque runtime configuration could define a custom provider id; this service sets none today.

func ValidateSessionRuntime

func ValidateSessionRuntime(runtime, model string) (string, error)

ValidateSessionRuntime checks an explicit (runtime, model) pair a caller asks a new session to carry, and returns the model as it will be stored.

func WaitedForCheckout

func WaitedForCheckout(a Agent) bool

WaitedForCheckout reports that the deliverer recorded a checkout wait on this row and has not stamped it. The stamp clears the marker in the same write (Store.SetKickedOff), or the stamped row would read as a failed kickoff (KickoffFailed) until the turn ends.

func WithTurnAccepted added in v0.132.0

func WithTurnAccepted(ctx context.Context, fn func(TurnAcceptance)) context.Context

WithTurnAccepted returns ctx carrying fn, run AT MOST ONCE when ccd accepts the turn's text (MarkTurnAccepted). fn may run on a transport goroutine.

func WithTurnActivity added in v0.165.0

func WithTurnActivity(ctx context.Context, fn func()) context.Context

WithTurnActivity returns ctx carrying fn, run on every read of a turn's stream that returned bytes. fn may run on the transport's goroutine and must be cheap (throttle inside it).

func WithTurnEnd added in v0.161.0

func WithTurnEnd(ctx context.Context) context.Context

WithTurnEnd returns ctx carrying a fresh, unset turn-end mark. Each turn starts its own: a mark never leaks from one turn to the next.

func WithTurnRoute

func WithTurnRoute(ctx context.Context, r TurnRoute) context.Context

WithTurnRoute returns ctx carrying r for the turn run under it.

Types

type AfterFirstRequestError

type AfterFirstRequestError struct {
	// Request is the 1-based number of the request that failed (2 or more).
	Request int
	Err     error
}

AfterFirstRequestError is a RunToolLoop failure on a request AFTER the first one: the runtime had already answered request 1 with function calls, and THIS process had already dispatched them.

🔴 IT EXISTS SO NO CALLER READS SUCH A FAILURE AS "NOTHING HAPPENED". The cause it wraps can be exactly the shape that means "nothing was sent" on a FIRST request — a typed 409 busy, a dial error after a pod restart, a 404 — and every reader that branches on those (agentgateway.Unsent, a toolless 404 fallback) would then resend a turn whose tools already ran: a second gated task, a second paste of the same message. PastFirstRequest is the test each of them applies first. Unwrap keeps the cause visible to errors.As (an account mark on a typed rate_limited, a log line); it is the CALLERS' rule, not the wrapper's, that decides what the cause may no longer mean.

func (*AfterFirstRequestError) Error

func (e *AfterFirstRequestError) Error() string

Error is the cause's text, unchanged: a RuntimeError's text is stored and matched by prefix (see RuntimeError), and the mark must not move it.

func (*AfterFirstRequestError) Unwrap

func (e *AfterFirstRequestError) Unwrap() error

type Agent

type Agent struct {
	ID          int64  `json:"id"`
	Name        string `json:"name"`      // short slug; also the provision.Ref.Name
	Namespace   string `json:"namespace"` // the driver's scoping unit (provision.Instance.Group)
	DisplayName string `json:"displayName"`
	// DisplayNameSource is who set DisplayName (migration 0090): NameDefault
	// (the slug, copied), NameDispatch (derived from the source task),
	// NameSystem (a role muster pinned: the chief, an officer) or NameManual
	// (the person renamed it). "" reads as NameDefault. NameManual, NameSystem
	// and NameDispatch all outrank a session's auto name (internal/sessionname).
	DisplayNameSource string `json:"displayNameSource,omitempty"`
	// DisplayNameAt is when DisplayName was last set — the row's creation, or
	// a rename (migration 0091): the moment a name the drift offer measures
	// against took effect (internal/focus DriftOffer's since).
	DisplayNameAt time.Time `json:"-"`
	Repo          string    `json:"repo"` // owner/name
	RepoBranch    string    `json:"repoBranch"`
	NoteID        *int64    `json:"noteId,omitempty"`
	NoteText      string    `json:"noteText,omitempty"`

	// PendingNote is the first message an agent was created WITH: the text a
	// dispatch asked to be delivered as its opening turn. It is written once, by
	// internal/api's createAndDispatchAgent, and from then on only round-tripped
	// by the store.
	//
	// ✅ internal/agentkickoff DELIVERS IT. When the agent's instance is ready
	// and the row has never been kicked off, that background loop sends this text
	// as the agent's first turn through agentgateway.Gateway (Resolve, then Send,
	// which together are Gateway.Chat) and stamps KickedOff BEFORE the Send. The text is KEPT after delivery rather than cleared: it is
	// the task the agent was given, and a re-send after a lost recipient
	// (ActionResendKickoff) would need it.
	//
	// ⚠ THIS COMMENT ONCE SAID "NOTHING DELIVERS IT", which was true while
	// agentprovision.KickoffDeliveryWired was false — the field had no production
	// reader beyond the store. That constant is bound to a measurement of the
	// module's call graph (modulegate.TestKickoffDeliveryLedgerAgreesWithTheModule),
	// so it could not flip without a deliverer landing. On a deployment with no
	// gateway a dispatch asking for a first turn is still refused, so a row there
	// can still hold one of these for ever.
	//
	// [KickoffOwed] is its derived reader for the UI. It answers "is a first turn
	// still owed" from this field together with KickedOff, and that BOOLEAN is
	// what the agent card and the machine projection (api.agentJSON) report.
	//
	// 🔴 THE TEXT IS NEVER SERIALISED WITH THE ROW, AND `json:"-"` IS THE WHOLE
	// MECHANISM. ⚠ This read "NEVER LEAVES THE PROCESS", which delivery made false
	// by design: internal/agentkickoff sends it to the agent's own gateway and
	// writes it to the agent's transcript as the first user message — the same two
	// places any operator message goes. What stays true is that no projection of
	// the ROW carries it. It is operator-authored instruction text, this repository is
	// public, and the leak gate (tests/leakscan.py) is the standing reason. So the
	// derived boolean is surfaced and the content is not — asserted both ways by
	// agents.TestKickoffOwedTruthTable's sibling
	// TestAnOwedKickoffIsReportedWithoutTheNotesText in internal/api, which reads
	// the rendered card and the JSON body for the fixture's own words.
	PendingNote string `json:"-"`

	Model string `json:"model"` // OpenRouter slug; "" = cluster default
	// Kind is the runtime this agent is provisioned as: [KindGateway] or
	// [KindClaudeCode]. "" reads as KindGateway (see [ResolveKind]). Fixed at
	// creation — migration 0003's trigger refuses an UPDATE of it.
	Kind string `json:"kind"`
	// CCAccount is the Claude account (a name from MUSTER_AGENT_CC_ACCOUNTS) whose
	// setup-token this claude-code agent runs on; "" for every other kind. It is a
	// NAME, never the token. Chosen at dispatch by internal/ccpool; it changes
	// afterwards ONLY by an account failover (internal/ccfailover, migration
	// 0066), which migration 0003's trigger refuses to every other UPDATE.
	CCAccount string `json:"ccAccount,omitempty"`
	// CCAccountPinned: the account was named explicitly at creation (a pin), so
	// the agent is not failed over to another account unless CCFailover is also
	// set (agents.cc_account_pinned / cc_failover, migration 0066).
	CCAccountPinned bool `json:"ccAccountPinned,omitempty"`
	// CCFailover is a pinned agent's opt-in to account failover. It means
	// nothing on an unpinned agent, which fails over by default.
	CCFailover bool `json:"ccFailover,omitempty"`
	// WorkerPool is the named worker pool this claude-code agent serves machine
	// jobs for (agents.worker_pool, migration 0042); "" for an agent in none.
	// Set at creation (dispatch's worker_pool) and never written after; a job
	// naming the pool instead of an agent is given one of its members
	// (internal/api createPoolJob). See [ValidWorkerPool].
	WorkerPool string `json:"workerPool,omitempty"`
	// OwnerID is the user this agent belongs to (agents.owner_id, migration
	// 0006). A request authenticated by THIS agent's own token acts as this
	// user (internal/api agentOwnerID). Not serialised: the JSON shape is
	// unchanged, and an owner id is not something an agent or a page needs.
	// Zero only for an Agent that never came from the database (a fake store).
	OwnerID    int64  `json:"-"`
	Status     string `json:"status"`
	HooksToken string `json:"-"`
	// GatewaySecret is the credential muster presents to a claude-code agent's
	// turn API (ccd's /v1/responses), minted per agent at provision time
	// (agents_gateway_secret, migration 0042). "" for every other kind, and for a
	// claude-code row provisioned before it existed — see [TurnBearer].
	//
	// 🔴 IT IS RANDOM AND NOT DERIVED FROM HooksToken, AND THAT IS ITS WHOLE
	// PURPOSE. HooksToken is the agent's muster identity, which its session must
	// hold (MUSTER_HOOK_TOKEN: the approval hook, the MCP entry, git routing), so
	// every tool call the session makes can read it. A turn credential computable
	// from it — muster's hooks-sha256 derivation — let any tool call drive the
	// agent's own turn API. Never serialised, never logged.
	GatewaySecret string    `json:"-"`
	KickedOff     bool      `json:"kickedOff"`
	LastOutput    string    `json:"lastOutput,omitempty"`
	ErrorMessage  string    `json:"errorMessage,omitempty"`
	CreatedAt     time.Time `json:"createdAt"`
	UpdatedAt     time.Time `json:"updatedAt"`

	// KickoffPod is the provision.Instance.InstanceID that received the
	// kickoff. Empty = unknown (a row predating these columns, or a delivery
	// whose instance lookup failed), which DISABLES restart detection for that
	// agent — the fail-safe direction.
	KickoffPod string `json:"kickoffPod,omitempty"`
	// KickoffRestarts is the container restart count observed AT delivery. A
	// later count strictly greater than this means the recipient was restarted
	// in place (the out-of-memory shape, where the instance id does not change).
	KickoffRestarts int32 `json:"kickoffRestarts,omitempty"`
	// KickoffAttempts counts deliveries made (the first dispatch plus each
	// recovery re-send). It bounds recovery at MaxKickoffAttempts so an agent
	// that dies deterministically ends VISIBLY failed rather than re-kicked
	// forever.
	KickoffAttempts int `json:"kickoffAttempts,omitempty"`
	// KickoffError is the last kickoff SEND failure ("unexpected EOF" when the
	// container died mid-turn). Cleared at the start of each delivery. It exists
	// because that failure used to be a log line and nothing else.
	KickoffError string `json:"kickoffError,omitempty"`

	// Outcome is agents.outcome: "" (not tracked), or one of agentoutcome's
	// Running / Done / Failed / Stuck.
	Outcome string `json:"-"`
	// OutcomeReason is why, in muster's words ("" while running or done).
	OutcomeReason string `json:"-"`
	// OutcomeAt is when Outcome last changed; nil when it never has.
	OutcomeAt *time.Time `json:"-"`
	// ActivityAt is the newest activity muster observed of the agent (a turn's
	// start, end or stream event, a pod's work report); nil when none.
	ActivityAt *time.Time `json:"-"`
	// FirstReplyAt is when the agent's first reply arrived; nil before it.
	FirstReplyAt *time.Time `json:"-"`
	// OutcomeToldAt is when a waiting outcome was told (pushed and noted, or
	// seen by the owner); nil while untold. Every transition clears it.
	OutcomeToldAt *time.Time `json:"-"`
	// DispatchedBy is the chief agent that started this one (agent_dispatch);
	// nil for every other start.
	DispatchedBy *int64 `json:"-"`
}

Agent is the stored record of one managed agent.

type AgentUnread

type AgentUnread struct {
	AgentID     int64  `json:"agentId"`
	AgentName   string `json:"agentName"`
	DisplayName string `json:"displayName"`
	// DisplayNameSource is the agent's Agent.DisplayNameSource: who set
	// DisplayName, which the name rule (internal/sessionname) ranks by.
	DisplayNameSource string `json:"displayNameSource,omitempty"`
	SessionID         int64  `json:"sessionId"` // the link target (most-recently-active session)
	Count             int    `json:"count"`     // total unread assistant messages across the agent
}

AgentUnread summarises one agent's unread assistant replies for the notifications panel: the total unread count plus the session to deep-link to (the agent's most-recently-active session — the link target).

type CLIActivity added in v0.132.0

type CLIActivity struct {
	Version int        `json:"version"`
	CLIs    []CLIState `json:"clis"`
}

CLIActivity is GET /v1/clis's answer.

type CLIState added in v0.132.0

type CLIState struct {
	// Lane is the lane's session key (the HeaderCCSession its turns carry);
	// "" for the primary CLI and for a CLI ccd does not know.
	Lane string `json:"lane"`
	// Primary: ccd's primary CLI (turns with no HeaderCCSession).
	Primary bool `json:"primary"`
	// Known: ccd matched it to the primary or one of its lanes. An unknown CLI
	// (a background job's process, anything else in the pod) is still listed.
	Known bool `json:"known"`
	// PID is the CLI's process id in the pod.
	PID       int    `json:"pid"`
	SessionID string `json:"session_id"`
	// Status is the sessions file's status as Claude Code wrote it; only
	// "idle" means idle.
	Status string `json:"status"`
	// Unaccounted: a live CLI process with no matching sessions file, so no
	// status of its own — it may be working, and counts as working.
	Unaccounted bool `json:"unaccounted"`
}

CLIState is one live CLI in the pod.

type ChatListing added in v0.201.0

type ChatListing struct {
	ChatSession
	// Unread: an assistant message was stored after the session's read_at.
	Unread bool
}

ChatListing is one chat as the switcher lists it: the session, and whether a reply arrived since it was last opened.

type ChatMessage

type ChatMessage struct {
	ID        int64     `json:"id"`
	AgentID   int64     `json:"agentId"`
	SessionID int64     `json:"sessionId"` // the chat session this message belongs to
	Role      string    `json:"role"`      // "user" | "assistant"
	Content   string    `json:"content"`
	CreatedAt time.Time `json:"createdAt"`

	// Structured-transcript fields (migration 0015). An assistant turn persists as
	// ORDERED parts so the canonical transcript matches the live stream. Kind is
	// 'text' (a normal message — the default for every legacy row), 'tool_call'
	// (Content = raw JSON args), or 'tool_result' (Content = dispatch output).
	Kind     string `json:"kind,omitempty"`
	ToolID   string `json:"toolId,omitempty"`   // links a tool_call to its tool_result
	ToolName string `json:"toolName,omitempty"` // function name (tool_call/tool_result)
	ToolOK   bool   `json:"toolOk,omitempty"`   // tool_result: dispatch success

	// TypedBy is the user who TYPED this turn into muster's chat (migration
	// 0081, chat_messages.typed_by), 0 for everything else. 🔴 ONE WRITER SETS
	// IT: runEnteredTurn, from the owner's signed-in chat doors only
	// (ownerTypedBy: the chat page's socket and the composer's POST — web or
	// phone). A relayed answer, a session question or `chief ask` over a token,
	// a plugin message, a task event, an agent's or muster's own turn and every
	// assistant row leave it 0, and rows from before 0081 read 0 (nothing is
	// backfilled). It is what lets a Chief-chat turn be quoted as the owner's
	// covering words (docs/design/session-state.md, step 3b-1);
	// internal/api's TestEveryChatWriterIsClassified pins every writer. Not
	// serialised: no API reader needs it.
	TypedBy int64 `json:"-"`

	// PluginMessageID is the plugin message this USER row relays to the chief
	// (migration 0096, chat_messages.plugin_message_id), 0 for every other row
	// and for every row written before 0096. Only internal/plugins' Deliverer
	// sets it (Deliver, Handed); the agent page draws such a row as a collapsed
	// system row (internal/api relayOf). Not serialised: no API reader needs it.
	PluginMessageID int64 `json:"-"`

	// WrittenBeforeRelayLink: this row was written before migration 0096 added
	// plugin_message_id (its created_at precedes 0096's applied_at in
	// schema_migrations; chatMessageCols computes it). Only such a row may be
	// taken for a plugin relay by its TEXT (internal/api relayOf's fallback):
	// a row written since carries the link when it is one. false for every
	// row a store that does not compute it returns.
	WrittenBeforeRelayLink bool `json:"-"`

	// AboutKey is the KEY of the session the owner was VIEWING when they typed
	// this USER row to the chief from its rendered view (migration 0098,
	// chat_messages.about): a Claude Code session id or "opencode:<ses_…>";
	// "" for every other row and for every row written before 0098. Only the
	// key is stored (operator decision, PR #537 D1): the window's place and
	// dispatch are read from the view when the line is sent, for the chief's
	// header only. 🔴 ONE WRITER SETS IT: runEnteredTurn, from the view's chief
	// door (POST /mirror/view/chief), which resolves it on the SERVER from the
	// hub's owner-scoped state, never from the page. internal/api's
	// TestOnlyTheViewDoorBindsASubject pins the writers. Not serialised: no API
	// reader needs it.
	AboutKey string `json:"-"`
}

ChatMessage is one persisted web-chat message in an agent's transcript.

type ChatMessageIn

type ChatMessageIn struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

ChatMessageIn is one message in a chat-completions request.

type ChatSession

type ChatSession struct {
	ID         int64     `json:"id"`
	AgentID    int64     `json:"agentId"`
	SessionKey string    `json:"sessionKey"` // the session-key header value sent to the runtime
	Title      string    `json:"title"`      // derived from the first user message ("" until then)
	CreatedAt  time.Time `json:"createdAt"`
	UpdatedAt  time.Time `json:"updatedAt"`
	// ReadAt is when the human last opened this session. An assistant message
	// created after ReadAt counts as unread (the notification panel + FAB badge).
	ReadAt time.Time `json:"readAt"`
	// Runtime and Model are fixed when the session is created (migration 0030,
	// session_runtime.go): Runtime "" is a LEGACY session, on the agent's own
	// kind. IsDefault marks the one session plugin deliveries and `chief ask`
	// go to.
	Runtime   string `json:"runtime"`
	Model     string `json:"model"`
	IsDefault bool   `json:"isDefault"`
	// ArchivedAt is when the session was archived (migration 0115), nil while
	// it is not: hidden from the chief's chat switcher, its history kept. The
	// default (the chief's PRIMARY chat) is never archived.
	ArchivedAt *time.Time `json:"archivedAt,omitempty"`
}

ChatSession is one independent conversation with an agent's gateway. Each session has its own gateway session key (= a fresh agent context), so a user can hold several parallel conversations with the same agent.

type ChatStore added in v0.201.0

type ChatStore interface {
	// ListChats is every session of agentID, archived ones included, each with
	// its unread mark.
	ListChats(ctx context.Context, agentID int64) ([]ChatListing, error)
	// SetArchived archives (or unarchives) agentID's session sessionID and
	// returns it. ErrArchivePrimary for the agent's default; pgx.ErrNoRows
	// when the session is not agentID's (or not visible to the caller).
	SetArchived(ctx context.Context, agentID, sessionID int64, archived bool) (ChatSession, error)
	// FreshPrimary makes a NEW session (on runtime, model) agentID's primary,
	// and archives the old primary, in ONE transaction: a reader of the default
	// sees the old one or the new one, never both and never neither. It returns
	// both. The agent must have a default already (DefaultSession elects one).
	FreshPrimary(ctx context.Context, agentID int64, agentName, runtime, model string) (old, fresh ChatSession, err error)
}

ChatStore is the part of the session store migration 0115 added. PGStore implements it; a separate interface like SessionRuntimeStore, so the many fakes of Store do not each grow these.

type ChatSwitcher added in v0.201.0

type ChatSwitcher struct {
	// Primary is the default session; nil when the agent has none yet.
	Primary *ChatListing
	// Side are the unarchived side chats, most recently active first.
	Side []ChatListing
	// Archived are the archived chats, most recently active first.
	Archived []ChatListing
}

ChatSwitcher is a chief's chats in the switcher's order (SwitcherOrder).

func SwitcherOrder added in v0.201.0

func SwitcherOrder(chats []ChatListing) ChatSwitcher

SwitcherOrder is THE switcher's order, for every surface that lists a chief's chats (the chief page's drawer and the panel's thread list): the primary first, then the side chats by last activity (updated_at, newest first; id breaks a tie, newest first), and the archived ones apart, in the same order. 🔴 ONE RULE, ONE PLACE: a surface that sorted on its own would put a busy side chat above the primary.

type CheckoutStatus

type CheckoutStatus struct {
	State  string `json:"state"`
	Detail string `json:"detail,omitempty"`
}

CheckoutStatus is ccd's `repo` object as muster reads it.

type ClientTimeoutError added in v0.176.0

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

ClientTimeoutError is the HTTP client's own Timeout ending a /v1/responses request while the caller's context was still alive (streamResponses).

🔴 IT DELIBERATELY DOES NOT MATCH context.DeadlineExceeded (net/http's error does): the outcome tracker reads DeadlineExceeded as "the caller gave up" and records nothing, and this is a failure of the runtime. A reader that wants "the turn outlived a budget" — a log label — asks IsClientTimeout as well.

func (*ClientTimeoutError) Error added in v0.176.0

func (e *ClientTimeoutError) Error() string

type FoldResult

type FoldResult int

FoldResult is what FoldIntoPendingNote did.

const (
	// FoldNotOwed: the first message is no longer owed (stamped, or none);
	// nothing was written and the caller delivers another way.
	FoldNotOwed FoldResult = iota
	// FoldAdded: the text was folded in.
	FoldAdded
	// FoldOverLimit: the text was NOT added — the first message is at its
	// size bound; it says so (the over line, once). The text was not delivered.
	FoldOverLimit
)

type ModelOption

type ModelOption struct {
	Value   string
	Default bool
}

ModelOption is one suggested model for the dispatch model selector. The field is typeable (a datalist), so these are suggestions only — any slug the configured provider routes may be entered. Default marks the option pre-filled into the form.

type OwnerTurn added in v0.132.0

type OwnerTurn struct {
	By        int64
	MessageID int64
	// Lane is the ccd lane (chat session key) the turn runs in; "" = ccd's
	// primary CLI.
	Lane      string
	ExpiresAt time.Time
}

OwnerTurn is the marker of an owner-typed turn in flight on an agent (migration 0069): the user who typed it, the chat row it stored, and when the marker lapses. The zero value is "no owner turn in flight".

type PGStore

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

PGStore is the Postgres-backed agents Store.

func NewPG

func NewPG(pool *pgxpool.Pool) *PGStore

NewPG constructs a Postgres-backed agents Store.

func NewPGTx

func NewPGTx(tx pgx.Tx) *PGStore

NewPGTx is a Store whose every statement runs inside tx, so several calls commit or roll back together. The caller owns tx (Commit / Rollback).

func (*PGStore) AddChatMessage

func (s *PGStore) AddChatMessage(ctx context.Context, m ChatMessage) (ChatMessage, error)

AddChatMessage inserts a message scoped to m.SessionID, then (in the same best-effort follow-up) bumps the session's updated_at and names it from the first user message when it's still untitled.

func (*PGStore) AgentsByNoteIDs

func (s *PGStore) AgentsByNoteIDs(ctx context.Context, ids []int64) (map[int64]Agent, error)

AgentsByNoteIDs returns the latest agent per requested note id. It queries with `note_id = ANY($1)` ordered created_at ASC so, as rows are scanned, a later (more recent) agent overwrites an earlier one for the same note — leaving the most-recent linked agent in the map. Uses the STORED status column (no k8s).

func (*PGStore) AppendPendingNote

func (s *PGStore) AppendPendingNote(ctx context.Context, id int64, text string) (bool, error)

AppendPendingNote appends text to agent id's first message while that message is still owed — not kicked off, and non-empty — and reports whether it did. The kickoff re-reads the note AFTER stamping kicked_off (agentkickoff.deliver), so an append either lands before the stamp and rides the first turn, or is refused (false) and the caller delivers another way. updated_at is left alone: an append is not the agent's activity, and the kickoff's dwell bound reads it.

func (*PGStore) ChatMessage added in v0.132.0

func (s *PGStore) ChatMessage(ctx context.Context, id int64) (ChatMessage, error)

ChatMessage reads one chat row by id (pgx.ErrNoRows when there is none visible to ctx's principal).

func (*PGStore) ClaimKickoff

func (s *PGStore) ClaimKickoff(ctx context.Context, id int64, owner string, ttl time.Duration) (bool, error)

ClaimKickoff takes the agent's cross-process kickoff claim (see the Store contract; the columns are in internal/db/migrations/0001_init.sql). One atomic conditional UPDATE: it wins iff the claim is unheld (NULL) or already expired, and holds NO connection afterwards — which is the whole reason this is a row and not pg_try_advisory_lock (a session lock would pin one of MaxConns=8 for up to KickoffWorkTimeout).

`now()` is Postgres's clock on BOTH sides of the comparison, so two pods with skewed system clocks still agree about whether a claim has expired.

updated_at is deliberately NOT bumped: a claim is bookkeeping about who is working, not a state transition worth surfacing as agent activity (and the renew ticker would otherwise make every long kickoff look continuously busy).

func (*PGStore) ClaimStoppedReap

func (s *PGStore) ClaimStoppedReap(ctx context.Context, id int64, after time.Duration) (bool, error)

ClaimStoppedReap takes the reaper's claim on agent id and reports whether it won. It wins only while the row STILL matches reapableStopped for the window after, re-checked in the claim's own statement: an agent Started since the scan read it is `provisioning` or `running` (not `stopped`), and one Started and stopped again carries a stopped_at from moments ago (not past the window), so either way the claim loses. Two pods claiming at once serialise on the row lock, and the second re-reads the winner's reap_claimed_at, which is inside the lease: it loses.

func (*PGStore) ClearKickoffClaimsByOwnerPrefix

func (s *PGStore) ClearKickoffClaimsByOwnerPrefix(ctx context.Context, prefix string) (int64, error)

ClearKickoffClaimsByOwnerPrefix clears claims whose owner begins with prefix (see the Store contract). An empty prefix is REFUSED rather than treated as "match everything": `LIKE '%'` would clear every live peer pod's claim.

The prefix is escaped for LIKE, so a hostname containing % or _ (legal in a container hostname override) cannot widen the match.

func (*PGStore) ClearKickoffDelivery

func (s *PGStore) ClearKickoffDelivery(ctx context.Context, id int64) error

ClearKickoffDelivery drops the recipient stamp (see the Store contract). The attempt counter and the last send error are left alone — they are history.

func (*PGStore) ClearKickoffFailure added in v0.219.0

func (s *PGStore) ClearKickoffFailure(ctx context.Context, id int64) error

ClearKickoffFailure erases a stale first-turn failure once a later turn on the agent completed (see the Store contract). At-most-once kickoff is untouched: kicked_off and kickoff_attempts are not written, so nothing is re-sent.

🔴 updated_at IS DELIBERATELY NOT BUMPED, for the same reason SetKickoffError does not bump it. The dwell clock (agents.DecideReconcile's ActionRetryKickoff bound, MarkKickoffStuck's equality) is read only for OWED rows, which the `kicked_off` conjunct already excludes — so bumping could not help there and could only disturb a row it was never meant to touch. Erasing stale evidence is not a transition; the turn that justified it already moved the agent's order through its transcript message.

⚠ THE `kicked_off` CONJUNCT IS LOAD-BEARING: on a row that is NOT kicked off, kickoff_error is the checkout-wait marker (WaitedForCheckout) or a not-delivered record, and an operator chat turn to such an agent must not erase either. Pinned by TestClearKickoffFailureLeavesAnOwedRowAlone.

🔴 A RESEND-SAFE CAUSE IS KEPT (operator decision). A first turn whose recorded cause PROVES the task was never delivered — KickoffResendSafe: the never-connected, not-accepted and busy prefixes — keeps its badge and its "safe to re-send" remedy after a later turn completes, because that later turn did not carry the task and the operator still owes the re-send. Only causes under which the task may have arrived (timeout, shutdown, transport error, empty reply, unrecognised text) are cleared. The three prefixes are the SAME constants KickoffResendSafe reads, passed as parameters, so the SQL cannot drift from it. Pinned by TestClearKickoffFailureKeepsAResendSafeCause.

func (*PGStore) ClearOwnerTurn added in v0.132.0

func (s *PGStore) ClearOwnerTurn(ctx context.Context, agentID, messageID int64) error

ClearOwnerTurn removes agentID's marker IF it is still the one for messageID: a turn ending never clears a later turn's marker.

func (*PGStore) Create

func (s *PGStore) Create(ctx context.Context, a Agent) (Agent, error)

Create inserts an agent and returns it with generated id/timestamps.

func (*PGStore) CreateSession

func (s *PGStore) CreateSession(ctx context.Context, agentID int64, agentName string) (ChatSession, error)

func (*PGStore) CreateSessionOn

func (s *PGStore) CreateSessionOn(ctx context.Context, agentID int64, agentName, runtime, model string) (ChatSession, error)

CreateSessionOn implements SessionRuntimeStore. The pair is validated here as well as by the caller: it is argv to a CLI (a Claude model) or a request header (an OpenRouter model), and the store is the last place a bad value could be stopped before it is written for good.

func (*PGStore) DefaultSession

func (s *PGStore) DefaultSession(ctx context.Context, agentID int64, agentName string) (ChatSession, error)

DefaultSession implements SessionRuntimeStore.

🔴 THE ELECTION IS THE MIGRATION'S RULE, IN ONE PLACE PER LAYER: the legacy-key session first, then the oldest. "Latest" would be wrong — it is whatever was touched last, which for a chief is usually a plugin's session — and a default that moved every time a message arrived would not be a default.

⚠ TWO CALLERS ELECTING AT ONCE: the partial unique index lets one UPDATE win; the other matches no row it may set (its WHERE re-checks that the agent still has no default) and falls through to the re-read, which returns the winner.

func (*PGStore) Delete

func (s *PGStore) Delete(ctx context.Context, id int64) error

func (*PGStore) DeleteChatMessagesOlderThan

func (s *PGStore) DeleteChatMessagesOlderThan(ctx context.Context, cutoff time.Time) (int64, error)

DeleteChatMessagesOlderThan removes chat messages created before cutoff.

func (*PGStore) FoldIntoPendingNote

func (s *PGStore) FoldIntoPendingNote(ctx context.Context, id int64, text, last string, maxBytes int, over string) (FoldResult, error)

FoldIntoPendingNote is AppendPendingNote for a message folded into an owed first turn by someone other than its author (a forward): text goes BEFORE last when the note ends with it (muster's rules stay the last word), else at the end. 🔴 THE BOUND IS ON THE ENCODED SIZE: maxBytes is compared with the note's JSON-encoded length (jsonLen), because the runtime's read limit applies to the encoded request, and an HTML-heavy text grows up to six-fold. Past it the text is not added and over is (once): FoldOverLimit.

func (*PGStore) FreshPrimary added in v0.201.0

func (s *PGStore) FreshPrimary(ctx context.Context, agentID int64, agentName, runtime, model string) (ChatSession, ChatSession, error)

FreshPrimary implements ChatStore.

🔴 THE OLD DEFAULT ROW IS LOCKED FIRST, WITH A BOUNDED WAIT (freshPrimaryLockWait, lock_timeout) — NOT NOWAIT. Ordinary chat writes hold that row's locks for a moment: a chat_messages insert takes FOR KEY SHARE through its foreign key, and AddChatMessage's `UPDATE chat_sessions SET updated_at` a row lock. NOWAIT answered "a fresh primary is already being made" whenever a delivery was being written (PR #609 round 2 N2); the wait lets those finish, and the switch then runs.

A second fresh-primary call (another process: in one process the handler's guard refuses it first) waits behind the first; once the first commits, its re-check under READ COMMITTED finds the old row no longer the default and reads no row — ErrFreshPrimaryBusy, changing nothing. So does a wait that runs out (55P03). One call wins, never two primaries; the partial unique index (chat_sessions_one_default) is the backstop.

func (*PGStore) Get

func (s *PGStore) Get(ctx context.Context, id int64) (Agent, error)

func (*PGStore) GetByHooksToken

func (s *PGStore) GetByHooksToken(ctx context.Context, token string) (Agent, error)

GetByHooksToken looks an agent up by its per-agent hooks token. This is the agent self-service auth path: the token is unique per agent and injected into the pod, so a valid bearer both authenticates and identifies the caller.

func (*PGStore) GetByName

func (s *PGStore) GetByName(ctx context.Context, name string) (Agent, error)

func (*PGStore) GetSession

func (s *PGStore) GetSession(ctx context.Context, sessionID int64) (ChatSession, error)

func (*PGStore) KickoffClaimHolder added in v0.116.0

func (s *PGStore) KickoffClaimHolder(ctx context.Context, id int64) (string, error)

KickoffClaimHolder reads who holds the agent's claim (see the Store contract): "" when unheld or expired — by Postgres's clock, as ClaimKickoff judges it — and for a row that does not exist.

func (*PGStore) LastMessageByAgentIDs

func (s *PGStore) LastMessageByAgentIDs(ctx context.Context, ids []int64) (map[int64]time.Time, error)

LastMessageByAgentIDs returns the newest chat_messages.created_at per requested agent id, in ONE grouped query (no per-agent fan-out — the machine API resolves a whole page of agents at once). Agents with no persisted transcript row are absent from the map rather than mapped to the zero time, so the caller can tell "never produced a turn" from "produced one at the epoch".

func (*PGStore) LatestOrCreateSession

func (s *PGStore) LatestOrCreateSession(ctx context.Context, agentID int64, agentName string) (ChatSession, error)

LatestOrCreateSession returns the agent's most-recently-updated session, or creates one. The created session uses the LEGACY key (so a pre-sessions agent keeps its gateway context) — the legacy key is UNIQUE, so a second call after one exists takes the latest branch and never collides.

func (*PGStore) LatestSessionIDs

func (s *PGStore) LatestSessionIDs(ctx context.Context, ids []int64) (map[int64]int64, error)

LatestSessionIDs returns, per requested agent id, the id of the session LatestOrCreateSession would return for it, in ONE query, WITHOUT creating anything: an agent with no session is absent from the map (its link stays the bare page, whose handler creates one). It exists so a list of agent links can name each agent's canonical ?session= URL instead of paying the bare URL's 303.

func (*PGStore) List

func (s *PGStore) List(ctx context.Context) ([]Agent, error)

func (*PGStore) ListChatMessages

func (s *PGStore) ListChatMessages(ctx context.Context, sessionID int64) ([]ChatMessage, error)

func (*PGStore) ListChatMessagesPage

func (s *PGStore) ListChatMessagesPage(ctx context.Context, sessionID, beforeID int64, limit int) ([]ChatMessage, error)

ListChatMessagesPage returns up to limit messages for ONE session in chronological order, ending immediately before beforeID (0 = the newest page).

It selects newest-first with a LIMIT — so a huge transcript only ships the tail, and the `(session_id, created_at)` index's sibling primary key does the ordering — then reverses to chronological in Go. See the interface comment for why the cursor is the id and not a timestamp.

func (*PGStore) ListChats added in v0.201.0

func (s *PGStore) ListChats(ctx context.Context, agentID int64) ([]ChatListing, error)

ListChats implements ChatStore.

func (*PGStore) ListReapableStopped

func (s *PGStore) ListReapableStopped(ctx context.Context, after time.Duration) ([]StoppedAgent, error)

ListReapableStopped returns every agent the caller can see that matches reapableStopped for the window after, oldest stop first.

func (*PGStore) ListRecentChatMessages

func (s *PGStore) ListRecentChatMessages(ctx context.Context, sessionID int64, limit int) ([]ChatMessage, error)

ListRecentChatMessages returns the most recent limit messages for ONE session in chronological order. A limit <= 0 falls back to the full session transcript.

🔴 IT IS ONE CALL TO ListChatMessagesPage RATHER THAN A SECOND COPY OF THE SAME QUERY. It used to open-code `ORDER BY id DESC LIMIT $2` + reverse; the paged reader needs exactly that plus a cursor predicate, and two spellings of "the newest N rows of a session, chronological" is two places for the ordering or the reversal to be got wrong — with the disagreement visible only as the page render and the machine read describing the same conversation differently.

func (*PGStore) ListSessions

func (s *PGStore) ListSessions(ctx context.Context, agentID int64) ([]ChatSession, error)

func (*PGStore) MarkKickoffStuck

func (s *PGStore) MarkKickoffStuck(ctx context.Context, id int64, seenUpdatedAt time.Time, errMsg string) (bool, error)

MarkKickoffStuck is the conditional `error` write for an owed row the deliverer judged stuck (see the Store contract). updated_at is compared for EQUALITY with the value the caller read: every writer that moves the row on (UpdateStatus, SetKickedOff, RecordKickoffDelivery) bumps it, and SetKickoffError, which a failed retry writes every tick, deliberately does not.

⚠ THERE IS NO `NOT kicked_off` CONJUNCT, AND THAT IS NOT AN OMISSION. The caller only judges rows it read with kicked_off=f, and the only writer of kicked_off (SetKickedOff) bumps updated_at, so the equality already refuses a stamped row; a second conjunct could not change any outcome and no test could fail without it. The claim conjunct is separate because ClaimKickoff deliberately does NOT bump updated_at.

func (*PGStore) MarkRunning

func (s *PGStore) MarkRunning(ctx context.Context, id int64, seenUpdatedAt time.Time) (bool, error)

MarkRunning promotes a provisioning row the caller saw at seenUpdatedAt to running (see the Store contract). updated_at is bumped: this IS a status transition, and it is what moves agents.LastActivity for the sidebar's order.

func (*PGStore) MarkSessionRead

func (s *PGStore) MarkSessionRead(ctx context.Context, sessionID int64) error

MarkSessionRead stamps a session's read_at to now(), clearing its unread assistant replies.

func (*PGStore) NameExists

func (s *PGStore) NameExists(ctx context.Context, name string) (bool, error)

NameExists reports whether a name is TAKEN — by a live agent, or forever by one that was destroyed.

🔴 THE SECOND EXISTS IS THE ENFORCEMENT POINT FOR THE NAME TOMBSTONE, AND IT IS HERE BECAUSE THIS IS THE ONLY THING THE GENERATOR ASKS. BuildUniqueAgentName accepts any candidate this returns false for. Delete is a HARD delete, so without the second clause a destroyed agent's name goes straight back into the bounded pool in names.go and the next generated agent can be its namesake — landing in the per-instance namespace and ServiceAccount NAMED after the dead one. Destroy can leave objects behind (a partial teardown that keeps going, a stranger's object it refuses to delete), and anything bound to that name out of band — a hand-made RoleBinding naming the ServiceAccount, say — would pass to the namesake silently. See migration 0002 for the trigger that fills the ledger this reads.

⚠ THE LEDGER IS ONLY EVER READ HERE. Nothing refuses an INSERT of a retired name, deliberately (migration 0002 says why: `chief` is provisioned with a hand-set name and a refusal would make re-provisioning it impossible). So this closes the AUTO-GENERATED path and no other.

🔴 THIS SELECT RUNS AS THE CONNECTING ROLE, WHICH IS WHY 0002 GRANTS SELECT ON THE LEDGER. The write side is a SECURITY DEFINER trigger and needs no grant; this side is ordinary application SQL and cannot be made to run as anyone else. `CREATE TABLE` grants nothing to anyone but the owner, so a deployment whose migrating role is not its connecting role got `permission denied for table agent_retired_names` (42501) here — on EVERY auto-named agent creation, since BuildUniqueAgentName asks nothing else. TestANonOwnerRoleCanBothRetireANameAndReadTheLedger pins both halves together; each passes alone while the pair is broken.

🔴 IT ASKS A SECURITY DEFINER FUNCTION, NOT THE TABLE (accounts PR 3a). An agent name is ONE GLOBAL NAMESPACE — it becomes a Kubernetes namespace — but under row-level security a plain SELECT on agents sees only the caller's own agents, so user B would be told user A's agent's name is free and fail later on the UNIQUE index (or, for a retired name, not at all). Migration 0007's muster_agent_name_taken reads every user's names and returns ONLY the boolean; it is the same two EXISTS clauses this method used to run.

func (*PGStore) OwnerTurnInFlight added in v0.132.0

func (s *PGStore) OwnerTurnInFlight(ctx context.Context, agentID int64) (OwnerTurn, error)

OwnerTurnInFlight reads agentID's marker; the zero OwnerTurn when there is none, it has lapsed (by Postgres's clock), or the agent does not exist.

func (*PGStore) OwnerTypedChatMessages added in v0.145.0

func (s *PGStore) OwnerTypedChatMessages(ctx context.Context, agentID, by int64, since time.Time, limit int) ([]ChatMessage, error)

OwnerTypedChatMessages is up to limit of agentID's text USER rows that user by TYPED (typed_by, migration 0081), written at or after since, in every chat session of the agent, oldest first: the newest limit of them. The stall sweep reads it for the owner's Chief chat (docs/design/session-state.md, step 3b-1); a caller that must vouch for the whole window asks for one more than it shows and treats a full page as a partial read.

func (*PGStore) RearmKickoff added in v0.106.0

func (s *PGStore) RearmKickoff(ctx context.Context, id int64, note string) error

RearmKickoff makes agent id owe a NEW first turn: note becomes its pending note and every kickoff marker is reset, so the kickoff deliverer (internal/agentkickoff) hands note to the agent once its instance is ready — the same path, claim and bookkeeping as a dispatch's first turn.

🔴 ITS ONE CALLER IS THE OFFICER RUNTIME waking a stopped instance (internal/api's officer fleet). agentkickoff deliberately never re-sends a delivered note by itself ("deciding to re-send a task is a different, costlier decision … not taken here by omission"); this method is that decision, taken explicitly, for an agent whose every wake IS a new session of work. It is not on the Store interface for that reason: a caller has to name *PGStore (or a test fake) to reach it.

func (*PGStore) RebindCCAccount added in v0.114.0

func (s *PGStore) RebindCCAccount(ctx context.Context, id int64, from, to string) (bool, error)

RebindCCAccount moves claude-code agent id from Claude account from to account to, and reports whether it did. It is the ACCOUNT FAILOVER's one write (internal/ccfailover, through agentprovision.Adapter.Rebind), and not on the Store interface for RearmKickoff's reason.

🔴 CONDITIONAL ON from, SO A REBIND IS IDEMPOTENT ON (agent, from). Two turns on one agent hitting the limit at once — in this process or another — both ask to move it off from; the first moves it, and the second matches no row (false) instead of moving it again. Migration 0066's trigger refuses this UPDATE unless the transaction set muster.cc_account_rebind, which only this statement does.

func (*PGStore) RecordKickoffDelivery

func (s *PGStore) RecordKickoffDelivery(ctx context.Context, id int64, pod string, restarts int32) error

RecordKickoffDelivery stamps the recipient pod + restart count, burns one unit of the re-send budget, and clears the previous send error. updated_at is deliberately bumped: this IS a state transition worth showing as activity.

func (*PGStore) ReleaseKickoffClaim

func (s *PGStore) ReleaseKickoffClaim(ctx context.Context, id int64, owner string) error

ReleaseKickoffClaim clears this owner's claim (see the Store contract). Same owner predicate, same reason: releasing someone else's claim would hand a third process a green light while the second is still working.

func (*PGStore) RenewKickoffClaim

func (s *PGStore) RenewKickoffClaim(ctx context.Context, id int64, owner string, ttl time.Duration) (bool, error)

RenewKickoffClaim extends this owner's claim (see the Store contract). The owner predicate is load-bearing: without it a process whose TTL lapsed would stamp over the claim another pod legitimately took, and two kickoffs would run.

func (*PGStore) SearchSessions

func (s *PGStore) SearchSessions(ctx context.Context, agentID int64, q string, limit int) ([]SessionMatch, error)

SearchSessions implements Store.

🔴 A PLAIN ILIKE AND NO INDEX, AND THE DECISION IS MEASURED RATHER THAN ASSUMED. On the deployment this was extracted from: chat_messages held 34 rows in total (12 of them kind='text'), and the whole relation — table plus its two indexes — was 248 kB. A sequential scan of 248 kB is sub-millisecond, so an index here would be pure cost. pg_trgm IS available on that server (1.6, uninstalled) should the table ever grow enough to need one, but installing it means CREATE EXTENSION in a migration, which is a privilege a managed Postgres can refuse — so it is a deliberate later decision, not a default.

⚠ THE FIGURE TO RE-MEASURE BEFORE ADDING ONE IS THE kind='text' ROW COUNT, not the total: the scan this query does is already restricted to those rows by the subquery's predicate.

func (*PGStore) SessionByKey

func (s *PGStore) SessionByKey(ctx context.Context, agentID int64, sessionKey string) (ChatSession, error)

SessionByKey implements SessionRuntimeStore.

func (*PGStore) SetArchived added in v0.201.0

func (s *PGStore) SetArchived(ctx context.Context, agentID, sessionID int64, archived bool) (ChatSession, error)

SetArchived implements ChatStore.

func (*PGStore) SetDefaultSession

func (s *PGStore) SetDefaultSession(ctx context.Context, agentID, sessionID int64) error

SetDefaultSession implements SessionRuntimeStore.

func (*PGStore) SetDisplayName

func (s *PGStore) SetDisplayName(ctx context.Context, id int64, name string) (Agent, error)

SetDisplayName updates an agent's display name — the person's own name for it, so its source becomes NameManual (migration 0090), which nothing automatic overwrites. A blank name falls back to the agent's immutable slug (the `name` column), source NameDefault, so the card is never label-less and the auto name may head it again.

func (*PGStore) SetGatewaySecret

func (s *PGStore) SetGatewaySecret(ctx context.Context, id int64, secret string) error

func (*PGStore) SetHooksToken

func (s *PGStore) SetHooksToken(ctx context.Context, id int64, token string) error

func (*PGStore) SetKickedOff

func (s *PGStore) SetKickedOff(ctx context.Context, id int64, v bool) error

func (*PGStore) SetKickoffError

func (s *PGStore) SetKickoffError(ctx context.Context, id int64, msg string) error

SetKickoffError records a kickoff send failure. It touches neither status nor updated_at — the status verdict belongs to the reconciler.

🔴 updated_at IS DELIBERATELY NOT BUMPED, AND THIS WAS A LATENT DEFECT UNTIL A DELIVERER DROVE THE DECISION TABLE. agents.DecideReconcile bounds the ActionRetryKickoff branch ONLY by `now − updated_at > ProvisioningStuckTimeout`, so a write here that bumped it reset that clock on every failed retry and made ActionError unreachable — an agent whose send failed every tick stayed in `provisioning` for ever. A failed send is evidence, not activity. RecordKickoffDelivery still bumps it: a delivery IS a transition. Pinned by TestSetKickoffErrorDoesNotMoveTheDwellClock (and, behaviourally, by internal/agentkickoff's dwell-boundary test against this store).

func (*PGStore) SetModel

func (s *PGStore) SetModel(ctx context.Context, id int64, model string) (Agent, error)

func (*PGStore) SetOwnerTurn added in v0.132.0

func (s *PGStore) SetOwnerTurn(ctx context.Context, agentID, by, messageID int64, lane string, ttl time.Duration) error

SetOwnerTurn marks agentID as running, in ccd lane lane, a turn user by typed (chat row messageID), until ttl from now by Postgres's clock. It overwrites any earlier marker: one owner turn in flight per agent.

func (*PGStore) UnreadByAgent

func (s *PGStore) UnreadByAgent(ctx context.Context) ([]AgentUnread, error)

UnreadByAgent returns one row per agent that has at least one unread assistant message — the total unread count plus the agent's most-recently-active session id (the deep-link target). Unread = an assistant message created after its session's read_at. Ordered by most-recent unread message first.

The per-agent count sums unread assistant messages across all the agent's sessions; the link target is the session with the newest updated_at (the one "New chat" / the detail page lands on), resolved via DISTINCT ON.

func (*PGStore) UpdateStatus

func (s *PGStore) UpdateStatus(ctx context.Context, id int64, status, lastOutput, errMsg string) error

type PartCollector

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

PartCollector reconstructs a turn's ordered parts by OBSERVING the same stream events that drive the live UI. Text deltas accumulate into a running segment that is flushed (as a text part) at each tool boundary, so a turn like text→tool→text yields three parts in arrival order — with NO change to the tool-loop internals (the caller just wraps its emit with Observe). 'user', 'thinking', and 'done' events are not persisted as parts (the user message is stored separately; thinking is ephemeral), but 'thinking' flushes pending text so a text→thinking→text turn keeps its ordering.

func (*PartCollector) Observe

func (pc *PartCollector) Observe(ev StreamEvent)

Observe folds one stream event into the collector.

func (*PartCollector) Parts

func (pc *PartCollector) Parts() []TurnPart

Parts flushes any trailing text and returns the ordered parts of the turn.

type ReconcileAction

type ReconcileAction int

ReconcileAction is the decision the reconciler makes for a single agent given its live instance state.

const (
	ActionNone              ReconcileAction = iota // no change needed
	ActionPersistStatus                            // persist the computed status (it changed)
	ActionRetryKickoff                             // instance ready but kickoff never sent → retry
	ActionResendKickoff                            // kickoff was sent, but its recipient died → re-send
	ActionError                                    // stuck too long → mark error
	ActionErrorKickoffLost                         // re-send budget spent against a dying instance → mark error
	ActionWaitCheckout                             // first turn held: the repository checkout is coming (DecideFirstTurn)
	ActionErrorCheckoutWait                        // the checkout wait outlived CheckoutWaitTimeout → mark error
)

func DecideFirstTurn

func DecideFirstTurn(a Agent, inst *provision.Instance, checkout string, now time.Time) ReconcileAction

DecideFirstTurn is DecideReconcile for a first turn whose agent needs a checkout (CheckoutGates), given the checkout state ccd reported. For any other row it IS DecideReconcile's action, so agents without a repository and gateway agents are decided exactly as before.

Rules, for a gated row (dwell = now − updated_at, the same clock as ProvisioningStuckTimeout):

  1. The checkout is coming — cloning or awaiting_grant, or unreadable on a row that already recorded a wait — so nothing is sent: ActionWaitCheckout while dwell ≤ CheckoutWaitTimeout, then ActionErrorCheckoutWait.
  2. The checkout is ready or failed on a row that waited: the dwell bound is CheckoutWaitTimeout, not ProvisioningStuckTimeout — a grant approved after an hour must not find the row already past its 15 minutes and fail it in the tick that could finally deliver it.
  3. Otherwise (never waited; ready, failed or unreadable): DecideReconcile, as before.

🔴 RULE 1's "UNREADABLE ON A ROW THAT WAITED" KEEPS A HELD TURN HELD. One failed /healthz read after hours of waiting must neither error the row (it is past 15 minutes) nor send into a checkout that, last anyone saw, did not exist.

func DecideReconcile

func DecideReconcile(a Agent, inst *provision.Instance, now time.Time) (action ReconcileAction, newStatus string)

DecideReconcile decides what to do for one agent given its live instance (nil if none) and the current time. It is a pure function so the full decision matrix is testable without a live backend. When the action is ActionPersistStatus the returned newStatus is the status to persist; otherwise newStatus is "".

Rules, in priority order:

  1. An errored agent is sticky (stored-status-authoritative, matching ComputeStatus).
  2. A ready instance whose kickoff was never sent is recovered: retried while young, errored once it has dwelt past ProvisioningStuckTimeout (the agent runtime is likely dead).
  3. A kickoff that WAS delivered, to an instance that no longer exists, is re-sent while budget remains and errored once it is spent.
  4. An agent that has dwelled in the stored `provisioning` status past ProvisioningStuckTimeout without ever being kicked off is errored — keyed on the stored status plus dwell, independent of whether the current snapshot reads pending or absent (a dispatched-but-never-scheduled agent collapses to "stopped" via ComputeStatus, so a computed-status guard misses it). Otherwise the live status is recomputed; a changed status is persisted, and an unchanged status is left alone — so no write happens and the dwell clock keeps running.

func (ReconcileAction) String

func (a ReconcileAction) String() string

String names the action.

⚠ IT EXISTS FOR TEST FAILURE MESSAGES, and that is a real reason rather than polish. Upstream every assertion on this type printed it with %d, so a regression read `action = 3, want 2` and told the reader nothing about which two behaviours had been swapped.

type RuntimeError

type RuntimeError struct {
	Status         int
	Type           string
	Code           string
	UpstreamStatus int
	Message        string
	// contains filtered or unexported fields
}

RuntimeError is a non-200, non-404 answer from an agent runtime's /v1/responses endpoint.

🔴 ITS Error() IS BYTE-IDENTICAL TO THE fmt.Errorf IT REPLACED ("responses HTTP <status>: <body snippet>"), BECAUSE THAT TEXT IS STORED. It lands in agents.kickoff_error and is matched by prefix and scrubbed by ScrubNote; changing it would change every stored failure's rendering. What the type ADDS is the runtime's own typed failure, when the body carries one.

⚠ Type IS FILLED ONLY FROM THE WIRE SHAPE ccd SPEAKS — `{"error":{"type":…,"code":…,"upstream_status":…,"message":…}}` (cmd/ccd's failure.go). A body that is not that JSON leaves Type empty, which every consumer treats as "untyped", never as a failure kind. That is what makes it safe to branch on: internal/agentgateway marks a Claude account rate-limited only when Type is exactly "rate_limited", so a 429 from some other runtime or a proxy is not mistaken for one.

func (*RuntimeError) Error

func (e *RuntimeError) Error() string

type SessionMatch

type SessionMatch struct {
	ChatSession
	Snippet string `json:"snippet"`
}

SessionMatch is one SearchSessions hit: the session plus one excerpt around the newest matching kind='text' message body, or "" when only the title matched.

type SessionRuntimeStore

type SessionRuntimeStore interface {
	// CreateSessionOn opens a new session on an explicit runtime and model
	// (ValidateSessionRuntime first). It is never the default.
	CreateSessionOn(ctx context.Context, agentID int64, agentName, runtime, model string) (ChatSession, error)
	// DefaultSession returns the agent's default session, electing one when it
	// has none: its legacy-key session, else its oldest, else a new legacy one.
	// The election and an existing default are the same row for every caller
	// (a partial unique index allows one).
	DefaultSession(ctx context.Context, agentID int64, agentName string) (ChatSession, error)
	// SetDefaultSession makes sessionID — which must be agentID's — the agent's
	// default, in one transaction with clearing the previous one.
	SetDefaultSession(ctx context.Context, agentID, sessionID int64) error
	// SessionByKey loads the agent's session with this session key.
	SessionByKey(ctx context.Context, agentID int64, sessionKey string) (ChatSession, error)
}

SessionRuntimeStore is the part of the session store migration 0030 added. PGStore implements it; it is a separate interface so the many fakes of Store do not each grow three methods, and a caller asserts it and falls back to the pre-0030 behaviour when the store lacks it.

type StoppedAgent

type StoppedAgent struct {
	ID        int64
	Name      string
	OwnerID   int64
	NoteID    *int64
	StoppedAt time.Time
}

StoppedAgent is a reap candidate: enough to claim it and to log the reap.

type Store

type Store interface {
	Create(ctx context.Context, a Agent) (Agent, error)
	Get(ctx context.Context, id int64) (Agent, error)
	GetByName(ctx context.Context, name string) (Agent, error)
	// GetByHooksToken identifies an agent by its unique per-agent hooks token
	// (the agent self-service auth path).
	GetByHooksToken(ctx context.Context, token string) (Agent, error)
	List(ctx context.Context) ([]Agent, error)
	// AgentsByNoteIDs returns, per requested note id, the note's LATEST linked
	// agent (the most-recently-created one when several point at the same note),
	// using the STORED agent status (no live k8s call — mirrors how the agents
	// list avoids per-agent pod lookups). Notes with no linked agent are simply
	// absent from the returned map. An empty ids slice returns an empty map.
	AgentsByNoteIDs(ctx context.Context, ids []int64) (map[int64]Agent, error)
	// LastMessageByAgentIDs returns, per requested agent id, the created_at of
	// that agent's most recent PERSISTED transcript message (any session, any
	// role, any kind). Agents with no persisted message are simply absent from
	// the returned map; an empty ids slice returns an empty map.
	//
	// It exists because agents.updated_at is NOT an activity signal: it is
	// bumped only by UpdateStatus / SetModel / SetDisplayName / SetHooksToken /
	// SetKickedOff, so an agent that reaches `running` and then works (or
	// wedges) for hours has a frozen updated_at. A transcript row, by contrast,
	// is written every time a turn completes, so it is the newest durable
	// evidence this service holds that the agent was alive.
	LastMessageByAgentIDs(ctx context.Context, ids []int64) (map[int64]time.Time, error)
	// LatestSessionIDs returns, per requested agent id, the id of the session
	// LatestOrCreateSession would return, creating nothing: an agent with no
	// session is absent. An empty ids slice returns an empty map. It is what an
	// in-app link to an agent names (ui.AgentSessionHref), so the link goes
	// straight to the page the bare URL would 303 to.
	LatestSessionIDs(ctx context.Context, ids []int64) (map[int64]int64, error)
	NameExists(ctx context.Context, name string) (bool, error)
	UpdateStatus(ctx context.Context, id int64, status, lastOutput, errMsg string) error
	// SetModel updates an agent's model (OpenRouter slug; "" = cluster default) and
	// returns the updated record. The new model takes effect on the agent's next
	// (re)provision — the caller rolls the pod.
	SetModel(ctx context.Context, id int64, model string) (Agent, error)
	// SetDisplayName updates an agent's human-facing display name (the slug Name —
	// the namespace key — is immutable) and returns the updated record. A blank
	// name falls back to the slug Name so the card is never label-less.
	SetDisplayName(ctx context.Context, id int64, name string) (Agent, error)
	SetHooksToken(ctx context.Context, id int64, token string) error
	// SetGatewaySecret stores the agent's turn credential ([Agent.GatewaySecret]).
	SetGatewaySecret(ctx context.Context, id int64, secret string) error
	// SetKickedOff stamps (or un-stamps) the first turn. Stamping also clears a
	// checkout-wait marker (WaitedForCheckout's kickoff_error) in the SAME write:
	// on a kicked-off row the marker would read as a failed kickoff, and cleared
	// in a separate earlier write, a failed stamp would leave a row that no longer
	// reads as waited, which the next tick errors past ProvisioningStuckTimeout.
	SetKickedOff(ctx context.Context, id int64, v bool) error
	// RecordKickoffDelivery stamps WHICH pod received the kickoff (name +
	// container restart count at that instant), increments the attempt counter,
	// and clears any previous send error. Called once per delivery, immediately
	// after the gateway is confirmed ready and KickedOff is flipped.
	//
	// An empty pod (unknown recipient) is written verbatim rather than skipped:
	// leaving a DEAD pod's name stamped would make the agent read as permanently
	// "lost" and burn its whole re-send budget against a recipient we never
	// confirmed. Empty disables detection — no worse than a row with no provenance.
	RecordKickoffDelivery(ctx context.Context, id int64, pod string, restarts int32) error
	// SetKickoffError records the reason a kickoff SEND failed, without touching
	// the agent's status: the pod may still be alive and mid-work (the 0.7.80
	// model-timeout case), so this is evidence, not a verdict. The reconciler is
	// what escalates a dead recipient to `error`.
	SetKickoffError(ctx context.Context, id int64, msg string) error
	// ClearKickoffFailure erases a recorded first-turn failure ([KickoffFailed])
	// because a LATER turn on the agent completed: `kickoff_error=”` only where the
	// row is kicked_off and the error is set. It touches nothing else — not
	// kicked_off, not kickoff_attempts, not updated_at — and a row that is not
	// kicked off (an owed agent's awaiting-grant / awaiting-clone marker, a
	// never-delivered record) is never matched. Nor is a RESEND-SAFE cause
	// ([KickoffResendSafe]): it proves the task was never delivered, so its badge
	// and re-send remedy stay until the operator acts. Called from the one place
	// every turn completes: internal/agentgateway's Send / SendWithTools.
	ClearKickoffFailure(ctx context.Context, id int64) error
	// MarkKickoffStuck sets an owed row to `error` with errMsg (and clears
	// last_output, as UpdateStatus does) ONLY if the row is still the one the
	// caller judged stuck — updated_at exactly seenUpdatedAt, which every stamp,
	// delivery record and status write moves — and no live kickoff claim. It
	// reports whether the write applied.
	//
	// 🔴 IT IS CONDITIONAL BECAUSE THE VERDICT COMES FROM A LIST READ, AND THE ROW
	// CAN MOVE BEFORE THE WRITE. A delivery that stamped it meanwhile has paid a
	// turn; a Start meanwhile set it `provisioning` again (and bumped updated_at).
	// An unconditional write turned either into an `error` card. A live claim means
	// a delivery is past its own re-read and may be about to stamp. Pinned against
	// real Postgres by agentkickoff's TestAStuckVerdictDoesNotOverwriteARowThatMoved.
	MarkKickoffStuck(ctx context.Context, id int64, seenUpdatedAt time.Time, errMsg string) (bool, error)
	// MarkRunning moves a row from `provisioning` to `running` ONLY if it is still
	// the row the caller observed — status `provisioning` and updated_at exactly
	// seenUpdatedAt — and reports whether the write applied. It clears
	// error_message (a running agent has none) and leaves last_output alone.
	//
	// 🔴 CONDITIONAL FOR THE SAME REASON AS MarkKickoffStuck: the verdict ("its
	// instance is ready") comes from a list read and a separate instance read, and
	// the row can move in between — a Stop writes `stopped`, a Start or a
	// re-dispatch writes `provisioning` again with a newer updated_at, an error
	// writes `error`. Each of those must win over a promotion decided from the
	// older snapshot. See [PromoteToRunning] and internal/agentstatus.
	MarkRunning(ctx context.Context, id int64, seenUpdatedAt time.Time) (bool, error)
	// ClearKickoffDelivery forgets which pod received the kickoff, which disables
	// restart-detection for this agent until the next delivery re-stamps it.
	//
	// It exists for ONE case: a DELIBERATE scale-down (Stop). Start then creates a
	// pod with a new name, which is indistinguishable from an eviction — so
	// without this, stopping and starting a finished agent would re-send its
	// original task. A stop is the operator saying "the pod is meant to go away",
	// so the provenance it invalidates is dropped rather than acted on. The
	// attempt counter is deliberately NOT reset: it is history, not state.
	ClearKickoffDelivery(ctx context.Context, id int64) error

	// ClaimKickoff atomically takes the agent's kickoff claim for `owner`,
	// expiring `ttl` from now, and reports whether it WON. It wins iff the claim
	// is currently unheld or already expired; it never blocks and never waits.
	//
	// A losing caller must not run a kickoff. It must also NOT release: the claim
	// it saw belongs to someone else.
	//
	// 🔴 ON ERROR IT MUST RETURN won == false. The caller's fail-closed guarantee
	// rides entirely on `!won`: an implementation that returned (true, err) would
	// make the kickoff proceed on an unverified claim and reopen the duplicate
	// silently, on exactly the occasion the database is unhealthy.
	ClaimKickoff(ctx context.Context, id int64, owner string, ttl time.Duration) (bool, error)
	// RenewKickoffClaim extends the agent's claim to `ttl` from now, but ONLY if
	// `owner` still owns it — an owner mismatch means another process legitimately
	// took the claim after this one's TTL lapsed, and stamping over that would
	// resurrect the duplicate the claim exists to prevent. It reports whether the
	// extension landed; false is a real signal (this process no longer holds the
	// claim), not a no-op, and is logged loudly by the caller.
	//
	// An owner match with an already-lapsed expiry is deliberately renewable: the
	// claim lapsed but nobody took it, so re-fencing it is strictly better than
	// leaving the row takeable while the work is still running.
	RenewKickoffClaim(ctx context.Context, id int64, owner string, ttl time.Duration) (bool, error)
	// ReleaseKickoffClaim clears the agent's claim, but ONLY if `owner` still owns
	// it — same reason as the renew predicate. Called from the kickoff's defer, so
	// the next kickoff can start immediately instead of waiting out the TTL. The
	// TTL is the crash backstop, not the normal path.
	ReleaseKickoffClaim(ctx context.Context, id int64, owner string) error
	// KickoffClaimHolder reports the owner string of the agent's claim while it is
	// held (unexpired), or "" when it is unheld or expired. A READ, for a caller
	// that lost ClaimKickoff and must say who won (chief_restart tells a delivery,
	// which force may cut off, from a chief restart or replacement, which it may
	// not). It decides nothing by itself: the holder can release a moment later.
	KickoffClaimHolder(ctx context.Context, id int64) (string, error)
	// ClearKickoffClaimsByOwnerPrefix clears every claim whose owner starts with
	// prefix, returning how many rows it cleared. It backs the STARTUP sweep
	// (Provisioner.SweepOwnStaleKickoffClaims), whose prefix is this pod's own
	// hostname — so it recovers claims stranded by an in-place container restart,
	// where the pod name survives but the process uuid does not.
	//
	// 🔴 The caller must scope the prefix to itself. A wildcard (or empty) prefix
	// would clear a LIVE peer pod's claims during a rollout — handing out a green
	// light for the very duplicate this mechanism prevents.
	ClearKickoffClaimsByOwnerPrefix(ctx context.Context, prefix string) (int64, error)

	Delete(ctx context.Context, id int64) error

	// CreateSession opens a new conversation for an agent with a fresh, unique
	// gateway session key (so it starts with no context). Title is empty until
	// the first user message names it.
	CreateSession(ctx context.Context, agentID int64, agentName string) (ChatSession, error)
	// ListSessions returns an agent's sessions most-recently-active first.
	ListSessions(ctx context.Context, agentID int64) ([]ChatSession, error)
	// SearchSessions returns the agent's sessions whose TITLE or whose kind='text'
	// message content contains q (case-insensitive substring), RANKED: a title that
	// starts with q first, then a title with a word that starts with q, then every
	// other match — most-recently-active first within each rank — each carrying
	// one excerpt around the newest body match. The rank is applied before the
	// limit, so a prefix match is never cut off by a page of newer substrings. A session
	// matched by title alone carries an EMPTY Snippet — the title is already on
	// screen, and repeating it would claim a body match that does not exist.
	//
	// 🔴 kind='text' ONLY, AND EXCLUDING kind='tool_result' IS THE POINT RATHER
	// THAN AN OPTIMISATION. Those rows are file contents and command output: on the
	// deployment this was extracted from they were 11 of 34 chat_messages rows, and a
	// transcript tail is where an agent's `cat` of a config file lands. Searching
	// them would make every common word match noise AND would paste raw file bytes
	// on screen as a snippet, on a surface whose whole content-sensitivity question
	// is still open. tool_call args are excluded for the same reason.
	//
	// ⚠ SCOPED TO ONE agent_id, AND THE SCOPE IS THE SECURITY PROPERTY. The
	// caller is a panel showing one agent's own threads; an unscoped search would
	// return every agent's conversation with the operator, which is the exact
	// widening a neighbouring reader was narrowed to close.
	//
	// ⚠ A BLANK q RETURNS NO ROWS, not everything: the caller renders the plain
	// recent list for that case, and "an empty query dumps the table" is the shape
	// this reader exists not to have.
	SearchSessions(ctx context.Context, agentID int64, q string, limit int) ([]SessionMatch, error)
	// GetSession loads one session by id.
	GetSession(ctx context.Context, sessionID int64) (ChatSession, error)
	// LatestOrCreateSession returns the agent's most-recently-updated session, or
	// creates one if it has none. The first auto-created session reuses the LEGACY
	// gateway key (`agent:<name>:webchat`) so a pre-sessions agent keeps its
	// existing gateway context; subsequent sessions get fresh keys.
	LatestOrCreateSession(ctx context.Context, agentID int64, agentName string) (ChatSession, error)

	// AddChatMessage persists a message scoped to m.SessionID, bumps that
	// session's updated_at, and — when the session is still untitled and the
	// message is a user turn — names the session from the message's first line.
	AddChatMessage(ctx context.Context, m ChatMessage) (ChatMessage, error)
	ListChatMessages(ctx context.Context, sessionID int64) ([]ChatMessage, error)
	// ListRecentChatMessages returns the most recent limit messages for ONE
	// session in chronological order — the capped reader the page render uses so a
	// long transcript doesn't ship the whole history on every load.
	ListRecentChatMessages(ctx context.Context, sessionID int64, limit int) ([]ChatMessage, error)
	// ListChatMessagesPage returns up to limit messages for ONE session in
	// chronological order, ending immediately BEFORE beforeID. beforeID == 0 means
	// "the newest page", which makes this a strict generalisation of
	// ListRecentChatMessages rather than a second reader beside it — the PG
	// implementation of that method is one call to this one.
	//
	// 🔴 THE CURSOR IS THE MESSAGE id, NOT created_at, AND THAT IS NOT A DETAIL.
	// AddChatMessage persists an assistant turn as several rows (migration 0015:
	// narration text, tool_call, tool_result) written in one burst, so two rows in
	// one turn can share a created_at to whatever resolution the clock gives. A
	// timestamp cursor would then either re-serve or skip part of a turn at the page
	// boundary, and both failures look like a coherent conversation with a hole in
	// it. The id is the sequence the rows were written in and is unique by
	// construction.
	//
	// ⚠ A limit <= 0 is the CALLER's bug, not a request for everything: it returns
	// an empty page. ListRecentChatMessages' "<= 0 means the whole transcript"
	// fallback is deliberately NOT inherited — that reader is called by the page
	// render with a constant, while this one is reachable from a query string, and
	// "?limit=0 dumps the table" is the shape this route exists not to have.
	ListChatMessagesPage(ctx context.Context, sessionID, beforeID int64, limit int) ([]ChatMessage, error)
	// DeleteChatMessagesOlderThan removes chat messages created before cutoff and
	// returns the number removed (retention sweep).
	DeleteChatMessagesOlderThan(ctx context.Context, cutoff time.Time) (int64, error)

	// MarkSessionRead stamps a session's read_at = now(), clearing its unread
	// assistant replies. Called when the human opens (or finishes a turn in) a
	// session.
	MarkSessionRead(ctx context.Context, sessionID int64) error
	// UnreadByAgent returns, per agent with ≥1 unread assistant message, the total
	// unread count and the session to deep-link to (the agent's most-recently-
	// active session). Ordered most-recent-unread first. Unread = an assistant
	// message whose created_at is after its session's read_at.
	UnreadByAgent(ctx context.Context) ([]AgentUnread, error)
}

Store is the agents persistence behaviour.

type StreamEmit

type StreamEmit func(StreamEvent)

StreamEmit receives streaming events during a turn. It is always nil-safe at call sites (the kickoff path passes nil).

type StreamError added in v0.165.0

type StreamError struct {
	// Code is the runtime's error code, when it sent one.
	Code string
	// Message is the runtime's own sentence.
	Message string
}

StreamError is a turn the runtime itself reported as failed, mid-stream.

func (*StreamError) Error added in v0.165.0

func (e *StreamError) Error() string

type StreamEvent

type StreamEvent struct {
	Kind       string // "text" | "thinking" | "tool_call" | "tool_result" | "user" | "done" | "queued" / "accepted" (muster's own: the message waits for a turn in flight, then the runtime took it; internal/api chat_busy.go)
	Text       string // text/thinking chunk; for "queued", the notice to show
	ToolID     string // tool_call / tool_result: the function call_id
	ToolName   string // tool_call / tool_result: the function name
	ToolArgs   string // tool_call: raw JSON arguments
	ToolOutput string // tool_result: dispatch output (truncated)
	ToolOK     bool   // tool_result: whether the dispatch reported success
}

StreamEvent is one server-side streaming event surfaced to the chat UI as the tool loop runs. Kind is one of "text", "thinking", "tool_call", "tool_result". The KICKOFF stream (provision.go) additionally uses two synthetic kinds the tool loop never emits: "user" (the kickoff prompt, shown first) and "done" (terminal, releasing the chat's streaming guard) — carried over the same StreamEmit/hook.

type TerminalTag

type TerminalTag string

TerminalTag identifies ONE terminal attach inside the agent's container, so that attach's process can be found and ended when the browser leaves. It is `MUSTER_TERMINAL_ID=<32 hex>`: an environment assignment, exactly as it appears in the attach's argv and in its tmux client's environment.

func NewTerminalTag

func NewTerminalTag() (TerminalTag, error)

NewTerminalTag mints a fresh random tag.

type ToolDef

type ToolDef struct {
	Type        string         `json:"type"`
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Parameters  map[string]any `json:"parameters"`
}

ToolDef is the flat Responses-API tool shape:

{"type":"function","name":"...","description":"...","parameters":{json-schema}}

🔴 THE SHAPE IS RUNTIME-VERSION-SPECIFIC, AND THE TWO FORMS ARE EACH OTHER'S HTTP 400. This comment used to read "verified against 2026.5.7 … The nested {"function":{...}} form is rejected (HTTP 400) on this codepath", which is true of that image and reads as universal. Measured live against two running agent gateways, one POST /v1/responses per cell — the reproducible form is internal/agentgateway/liveruntime_test.go, which re-runs the tool cell against whichever gateway it is pointed at:

agent image tag   flat (this type)                        nested {"function":{…}}
2026.5.7          200                                     400 tools.0.name: expected string
latest            400 tools.0.function: expected object   200

So a reader debugging a 400 from a `latest` gateway is looking at a version mismatch, not at a malformed request — and the previous wording sent them to check their own JSON. The flat form is kept because it is the shape the image tag the measured deployment provisions accepts; agentspec takes that tag from configuration and has no default of its own.

🔴 A SHAPE MISMATCH IS A LOST TURN, NOT A DEGRADED ONE. The toolless fallback keys on ErrResponsesUnsupported, which is a 404 ONLY — a 400 propagates to the caller, so an agent on the wrong image loses its kickoff rather than delivering it without tools.

⚠ OWED, NAMED RATHER THAN FIXED, BECAUSE NOTHING IN THE DEPLOYED PATH NEEDS IT YET: the shape belongs on the runtime descriptor (agentgateway.Runtime), beside the bearer derivation and the model sentinel, which is where the other two version-specific facts already live. CLOSING CONDITION: either a Runtime method selecting the shape with a live 200 recorded for BOTH images, or a deployment that pins the agent image tag to one whose shape this type matches, with the pin asserted by a test. WHO CHECKS IT: whoever first provisions an agent on an image other than the one measured above — the symptom will be a kickoff that 400s.

type ToolDispatch

type ToolDispatch func(name, arguments string) string

ToolDispatch executes a tool call (by name, with raw JSON arguments) and returns the output string fed back to the model as a function_call_output. Errors should be returned as a string the model can read (e.g. JSON error); the loop never aborts on a tool error.

type TurnAcceptance added in v0.132.0

type TurnAcceptance struct {
	Lane string
	// NewConversation is the session ccd's 103 names in
	// HeaderCCNewConversationSession: the NEW conversation a turn that asked
	// for one (HeaderCCNewConversation) was typed into. "" when the turn did
	// not ask, or when its ccd predates the header.
	NewConversation string
}

TurnAcceptance is what MarkTurnAccepted reports: the ccd lane the accepted text runs in — the request's HeaderCCSession, "" for ccd's primary CLI.

type TurnPart

type TurnPart struct {
	Kind     string // "text" | "tool_call" | "tool_result"
	Content  string // text body, or tool args (tool_call) / output (tool_result)
	ToolID   string // links a tool_call to its tool_result
	ToolName string
	ToolOK   bool // tool_result: dispatch success
}

TurnPart is one ORDERED piece of an assistant turn: a text segment, a tool call, or a tool result. A turn is persisted as a sequence of these so the canonical transcript (reload / reconcile) reproduces the live stream — full narration with tool calls interleaved — instead of only the final text.

type TurnRoute

type TurnRoute struct {
	// Runtime is the session's runtime (SessionRuntime*); "" is the agent's own.
	Runtime string
	// Header is set on every request of the turn, after the transport's own.
	Header http.Header
	// OnResponse, when set, is handed the response headers of every request of
	// the turn that got an answer, whatever its status.
	OnResponse func(http.Header)
}

TurnRoute is what a turn carries about where in the pod it goes.

func TurnRouteFrom

func TurnRouteFrom(ctx context.Context) (TurnRoute, bool)

TurnRouteFrom is the route ctx carries, if any.

type TurnUsage added in v0.191.0

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

TurnUsage accumulates one turn's tokens over every request it made.

func WithTurnUsage added in v0.191.0

func WithTurnUsage(ctx context.Context) (context.Context, *TurnUsage)

WithTurnUsage returns ctx carrying a fresh sink every request made under it adds its reported usage to, and the sink.

func (*TurnUsage) Context added in v0.201.0

func (t *TurnUsage) Context() (tokens int64, known bool)

Context is the context the turn's LAST model request was sent — input + cache read + cache creation of that request alone, not the turn's sum — and whether any request reported usage.

func (*TurnUsage) Snapshot added in v0.191.0

func (t *TurnUsage) Snapshot() (input, output, cacheRead, cacheCreation int64, known bool)

Snapshot is the tokens so far and whether any request reported usage.

Jump to

Keyboard shortcuts

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