Documentation
¶
Overview ¶
Package podagent is the part of an agent pod's in-pod supervisor that does not depend on which agent runtime the pod runs: muster's agent-facing routes as the pod reaches them, git's routing through muster's connector proxy, and the agent's repository checkout.
Its user is cmd/ccd (the claude-code kind). The code was ccd's; it moved here unchanged in behaviour when a second supervisor (the since-removed hermes kind's hermesd) needed the same rules. The messages a person reads name the supervisor that wrote them, through Voice.
Index ¶
- Constants
- Variables
- func ApplyGitRouting(base, token string, c AgentConnector) (bool, error)
- func BearerOK(r *http.Request, want string) bool
- func LastLines(s string, n, max int) string
- func MusterCall(ctx context.Context, client *http.Client, method, base, token, path string, ...) (int, []byte, error)
- func MusterGET(ctx context.Context, base, token, path string, out any) error
- func MusterPOST(ctx context.Context, base, token, path string, body any) error
- func ParseRepo(repo string) bool
- func PromptFrom(raw json.RawMessage) (string, error)
- func ProxyPrefix(base, name string) string
- func RecordExit(exits []time.Time, now time.Time, window time.Duration, maxExits int, ...) (kept []time.Time, delay time.Duration, latched bool)
- func ResolveBearer(who, hooksToken, gatewayBearer string) (string, error)
- func RunGitRoutingLoop(ctx context.Context, who, base, token string, interval time.Duration, ...)
- func SyncGitRouting(ctx context.Context, base, token string) ([]string, error)
- func WriteFailure(w http.ResponseWriter, f *Failure)
- func WriteResponse(w http.ResponseWriter, id string, items []ReplyItem, stream bool)
- type AgentConnector
- type ApprovalDecision
- type ApprovalRelay
- type Checkout
- func (c *Checkout) Attempt(ctx context.Context) error
- func (c *Checkout) Explain(ctx context.Context, cloneErr error) (detail string, awaiting bool)
- func (c *Checkout) NotReady() string
- func (c *Checkout) Ready() bool
- func (c *Checkout) Run(ctx context.Context)
- func (c *Checkout) SetStateForTest(state, detail string)
- func (c *Checkout) State() CheckoutState
- func (c *Checkout) Wait(ctx context.Context) bool
- type CheckoutConfig
- type CheckoutState
- type Failure
- type NativeToolItem
- type ReplyItem
- type Voice
Constants ¶
const ( // GithubConnector is the connector git reaches GitHub through. GithubConnector = "github" // CheckoutRetry is how often a failed clone is retried. The grants are // re-read every GitSyncInterval, so a clone retried after an approval goes // through the proxy within CheckoutRetry + GitSyncInterval. CheckoutRetry = 30 * time.Second // CheckoutTimeout bounds one clone. CheckoutTimeout = 10 * time.Minute // GithubCloneBase is where a repository is cloned from. A test points git at // a local repository with url.<local>.insteadOf this prefix, exactly as the // connector routing does with muster's proxy. GithubCloneBase = "https://github.com/" )
const ( CheckoutCloning = agents.CheckoutCloning CheckoutFailed = agents.CheckoutFailed CheckoutReady = agents.CheckoutReady // CheckoutAwaitingGrant: a clone failed and this agent's github connector // request is pending (the supervisor just filed it, or it already was) — // the one state the owner's approval alone resolves. CheckoutAwaitingGrant = agents.CheckoutAwaitingGrant )
The states /healthz reports under `repo`. They ARE internal/agents' constants: muster's kickoff deliverer reads this field (agents.DecideFirstTurn) and holds an agent's first turn, unsent and unstamped, while it reads cloning or awaiting_grant — so a spelling that drifted on either side would send the turn into a checkout that does not exist yet.
const ( // EnvConnectURL is the base URL of muster's agent-facing connector surface, // set on the pod only when the deployment offers it. EnvConnectURL = "MUSTER_CONNECT_URL" // EnvAgentToken is the agent's OWN per-agent muster token. EnvAgentToken = "MUSTER_HOOK_TOKEN" )
const GitSyncInterval = 15 * time.Second
GitSyncInterval is how often the routing is re-read from the grants. One cheap GET.
Variables ¶
var NoRedirects = &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
NoRedirects is the client every call to muster uses. 🔴 IT NEVER FOLLOWS A REDIRECT: Go's client resends custom headers (X-Muster-Token among them) to a redirect's target, even on another host. muster's agent routes do not redirect, so a redirect here is something to refuse, not to follow.
Functions ¶
func ApplyGitRouting ¶
func ApplyGitRouting(base, token string, c AgentConnector) (bool, error)
ApplyGitRouting brings one connector's routing in line with its grant and reports whether it wrote anything.
func BearerOK ¶
BearerOK reports whether r carries `Authorization: Bearer <want>`.
The comparison is over SHA-256 digests with subtle.ConstantTimeCompare, so it takes the same time whatever the presented value's length or content.
func LastLines ¶
LastLines is the last n non-empty lines of s, joined with "; ", control characters removed and capped at max bytes.
func MusterCall ¶
func MusterCall(ctx context.Context, client *http.Client, method, base, token, path string, in, out any) (int, []byte, error)
MusterCall sends one request to muster's agent routes with the agent's own token, decoding a 2xx JSON answer into out (when non-nil), and reports the status. A non-2xx is NOT an error here: callers that branch on the status (the approval relay) read it; MusterGET and MusterPOST turn it into one. client nil is NoRedirects.
func MusterGET ¶
MusterGET reads one of muster's agent JSON routes into out. It is a GET and files nothing.
func MusterPOST ¶
MusterPOST sends a JSON body to one of muster's agent routes.
func PromptFrom ¶
func PromptFrom(raw json.RawMessage) (string, error)
PromptFrom extracts the LAST user message's text from `input`, which may be a bare string or an array of items whose content is a string or an array of {type: input_text|text, text} parts.
func ProxyPrefix ¶
ProxyPrefix is connector name's prefix on muster's proxy.
func RecordExit ¶
func RecordExit(exits []time.Time, now time.Time, window time.Duration, maxExits int, backoffMin, backoffMax time.Duration) (kept []time.Time, delay time.Duration, latched bool)
RecordExit counts one exit at now against the exits already within window and decides what follows it: the delay before the next start, or (latched) no next start at all. It returns the exits still within the window, including this one.
func ResolveBearer ¶
ResolveBearer decides the credential a pod supervisor's /v1/responses accepts. who names the supervisor in the error ("ccd").
🔴 THE DERIVATION IS muster's OWN FUNCTION, IMPORTED, NOT A COPY. The supervisors live in muster's module precisely so the `hooks-sha256` formula cannot drift between the side that sends the bearer (agentgateway.Gateway) and the side that checks it.
muster's agent spec ships BOTH the raw token (HOOKS_TOKEN) and the derived value (MUSTER_GATEWAY_BEARER). Either is enough; when both are present they must agree, because a pod holding two credentials that disagree would accept one and 401 the other, and which one muster sends is not this process's decision.
func RunGitRoutingLoop ¶
func RunGitRoutingLoop(ctx context.Context, who, base, token string, interval time.Duration, logf func(string, ...any))
RunGitRoutingLoop runs SyncGitRouting now and every interval until ctx ends. A failed round (muster unreachable) leaves the routing as it is: with muster down the proxy is down too, and tearing the routing out would only make the next round's restore a change. who prefixes the log lines ("ccd").
func SyncGitRouting ¶
SyncGitRouting makes git's global config route exactly the connectors this agent holds an approved grant on, and nothing else under this muster's /connect/ prefix. It writes only what changed, so a git command running at the same moment never sees a routing torn down and rebuilt for nothing. It returns the names whose routing it changed.
func WriteFailure ¶
func WriteFailure(w http.ResponseWriter, f *Failure)
WriteFailure writes f as the response.
func WriteResponse ¶
func WriteResponse(w http.ResponseWriter, id string, items []ReplyItem, stream bool)
WriteResponse writes a settled turn. The REPLY is the text segments (each its own message item; muster joins items with a blank line); tool calls are streamed as native tool items.
Types ¶
type AgentConnector ¶
type AgentConnector struct {
Name string `json:"name"`
Exists bool `json:"exists"`
Hosts []string `json:"hosts"`
Grant string `json:"grant"`
}
AgentConnector is the subset of muster's /agent/connectors answers read here.
func (AgentConnector) Usable ¶
func (c AgentConnector) Usable() bool
Usable reports whether the connector exists and this agent's grant on it is approved.
type ApprovalDecision ¶
type ApprovalDecision int
ApprovalDecision is what the relay concluded.
const ( // ApprovalUndecided: no answer (the caller's fallback applies). ApprovalUndecided ApprovalDecision = iota ApprovalApproved ApprovalRejected )
func ApprovalResponse ¶
func ApprovalResponse(resp string) ApprovalDecision
ApprovalResponse maps the router's decision vocabulary onto a decision. 🔴 ONLY THE TWO SPELLINGS A HUMAN'S APPROVE CAN PRODUCE MAP TO APPROVED. Anything else, including "ignore" (a dismissed card) and an empty value, is undecided.
type ApprovalRelay ¶
type ApprovalRelay struct {
Base, Token string
// Deadline bounds the wait for an answer.
Deadline time.Duration
Poll time.Duration
Client *http.Client
Logf func(format string, args ...any)
// Fallback names what the caller does with ApprovalUndecided, for the log
// ("deferring", "denying"); TimeoutFallback is the same for the deadline
// ("deferring to the terminal prompt").
Fallback, TimeoutFallback string
}
ApprovalRelay files one prompt and waits for its answer.
func (ApprovalRelay) Decide ¶
func (r ApprovalRelay) Decide(ctx context.Context, req map[string]any) ApprovalDecision
Decide files req (the body muster's POST /agent/approvals takes) and waits for the answer, clearing the card on every exit that is not a decision.
type Checkout ¶
type Checkout struct {
// Retry is how often a failed clone is retried.
Retry time.Duration
// Timeout bounds one clone; 0 is CheckoutTimeout.
Timeout time.Duration
Logf func(string, ...any)
// contains filtered or unexported fields
}
Checkout is one agent's repository checkout. Retry, Timeout and Logf may be changed before Run.
func NewCheckout ¶
func NewCheckout(cfg CheckoutConfig) *Checkout
NewCheckout makes the checkout cfg describes, in state cloning. The caller has validated cfg.Repo with ParseRepo and made cfg.Dir absolute.
func (*Checkout) Attempt ¶
Attempt makes the checkout exist: an existing one is used as it is; an empty (or absent) directory is cloned into; a directory holding anything else is refused rather than cloned over.
A failure of anything but git reaching GitHub is a *localError: the checkout's own files, and a clone command that failed on THIS side (localCloneFailure).
🔴 A CHECKOUT IS A .git WITH A COMMIT CHECKED OUT, NOT A .git. A clone that is killed (the timeout, the supervisor shutting down, the pod evicted) leaves a .git whose HEAD names no commit; treating that as ready would start the agent in an empty tree. So: the clone goes into a sibling scratch directory and is moved into place (moveCheckout, .git last) only once `git rev-parse --verify HEAD` succeeds there — a kill leaves the workspace untouched (the scratch directory is replaced on the next attempt) — and an existing .git counts only when HEAD verifies too. One with no HEAD (an interrupted clone by an older supervisor) is refused, not deleted: it never removes what it did not just create. The one exception is an EMPTY repository (emptyCloneKey).
func (*Checkout) Explain ¶
Explain is the operator-facing sentence for a failed clone: git's error, and what the `github` connector needs — filing this agent's request for it when it holds no grant (see the file comment). awaiting reports that the agent's request for the connector is pending — the one case the owner's approval alone resolves.
func (*Checkout) NotReady ¶
NotReady is the not_ready message a turn gets while there is no checkout.
func (*Checkout) SetStateForTest ¶
SetStateForTest overwrites the reported state without running a clone. It exists for a supervisor's own tests (a package outside this one cannot reach the unexported state), never for production code.
type CheckoutConfig ¶
type CheckoutConfig struct {
Repo, Branch, Dir string
// ConnectBase and Token reach muster's connector routes; empty when the pod
// is not offered the connector store.
ConnectBase, Token string
Voice Voice
}
CheckoutConfig is what a checkout is made from.
type CheckoutState ¶
type CheckoutState struct {
Repo string `json:"repo"`
Branch string `json:"branch,omitempty"`
Dir string `json:"dir"`
State string `json:"state"`
Detail string `json:"detail,omitempty"`
}
CheckoutState is the `repo` object /healthz reports.
type Failure ¶
type Failure struct {
Status int `json:"-"`
Type string `json:"type"`
Code string `json:"code,omitempty"` // the runtime's own error code, when there is one
Upstream int `json:"upstream_status,omitempty"` // the API's HTTP status, when known
Message string `json:"message"`
}
Failure is a typed failed turn: `{"error":{type,code,upstream_status,message}}`.
type NativeToolItem ¶
type NativeToolItem struct {
Type string `json:"type"`
ID string `json:"id"`
CallID string `json:"call_id"`
Name string `json:"name"`
Arguments string `json:"arguments"`
// Status: "completed", "failed", or "in_progress" (no result before the
// turn ended).
Status string `json:"status"`
Output string `json:"output,omitempty"`
}
NativeToolItem is one tool call the agent ran itself during the turn, streamed as a cctranscript.NativeToolItem output item so muster draws it as a collapsed row and never dispatches it. It never appears in response.completed's output.
func NewNativeToolItem ¶
func NewNativeToolItem(id, name, arguments, status, output string) NativeToolItem
NewNativeToolItem is a NativeToolItem for call id with the given fields.
type ReplyItem ¶
type ReplyItem struct {
Text string
Tool *NativeToolItem
}
ReplyItem is one piece of a settled turn, in order: a text segment, or one tool call.
type Voice ¶
type Voice struct {
// Who is the supervisor ("ccd"): log prefixes, "<who> retries".
Who string
// Agent is the thing that starts once the checkout exists, with its article
// ("the Claude Code session").
Agent string
// AgentOf is the same with a possessive ("its Claude Code session"), for the
// reason filed with the connector request.
AgentOf string
}
Voice is how a supervisor names itself and the agent it starts in the sentences a person reads.