agents

package
v0.101.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 25 Imported by: 0 modules, 0 packages

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

Documentation ΒΆ

Overview ΒΆ

Package 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 (
	// 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"
)

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 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 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).

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 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 handleAgentCreate and handleChiefProvision β€” both hand it `r.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 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 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 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 card's "waiting for your github approval" line. 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 turn's agents.Store.RecordKickoffDelivery clears it β€” or, when that write failed, the deliverer clears it itself.

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 Agents list orders its cards by it (SortByLastActivity) and prints it in each card's footer. Before this function the API computed it inline while the 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 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 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 never completes assembles to "". 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 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 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"`
	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 once at dispatch by internal/ccpool and kept
	// for the agent's life (migration 0003 enforces both halves).
	CCAccount string `json:"ccAccount,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"`
}

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"`
	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 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
}

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"`
}

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 CheckoutStatus ΒΆ

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

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

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 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) 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) 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) 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) 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) 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 Agents list.

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) 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) 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. A blank name falls back to the agent's immutable slug (the `name` column) so the card is never label-less.

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) 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
	// 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
	// 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 StreamEvent ΒΆ

type StreamEvent struct {
	Kind       string // "text" | "thinking" | "tool_call" | "tool_result" | "user" | "done"
	Text       string // text/thinking chunk
	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 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.

Jump to

Keyboard shortcuts

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