agentgateway

package
v0.144.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 17 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 agentgateway is the CHAT half of the agent seam: it turns an agent row plus a live provisioner into one turn against that agent's model gateway.

🔴 IT IS A SEPARATE PACKAGE FROM internal/agentprovision, AND THE SPLIT IS THE SAME ONE internal/api MADE BETWEEN Provisioner AND Gateway. A driver contract (provision.Provisioner) has no notion of a chat turn at all: it creates, scales, destroys and reports. Chat is a conversation with the thing the driver created, over a protocol the driver knows nothing about. Behind one type the two would have to be wired together or not at all — and "lifecycle works, chat honestly refuses" is a real deployment state that api.Gateway's own doc names as such.

WHAT THIS PACKAGE IS, PRECISELY: a bridge with no protocol of its own. The two wire formats live in internal/agents (responses.go, chatcompletions.go); the credential derivation lives in Runtime; the sentinel is configuration (Config.Model); the address comes from the driver. This package supplies the two inputs internal/agents deliberately would not invent — the model sentinel and the endpoint — and nothing else.

⚠ WHAT IT DOES NOT DO, STATED SO IT IS NOT INFERRED: it does not fall back from tools to plain chat. api.Gateway's contract puts that decision at the CALLER, because the caller is the only place that knows whether a toolless answer is acceptable for the turn it is running — a kickoff that silently lost its tools produces an agent that cannot read the task it was dispatched for.

⚠ IT DOES FALL BACK BETWEEN THE TWO *TRANSPORTS*, AND THE TWO ARE DIFFERENT DECISIONS. Gateway.Chat runs over /v1/responses and drops to /v1/chat/completions only when the runtime answers 404 there — a choice about which wire format an image speaks, which no caller has information about and which changes nothing the caller asked for. Losing TOOLS changes what the agent can do; changing transport does not. The reasoning-model measurement that forced this is on Chat.

Index ¶

Constants ¶

View Source
const (
	UnsentBusy           = "busy"
	UnsentNotReady       = "not_ready"
	UnsentUnauthorized   = "unauthorized" // the runtime refused muster's own bearer
	UnsentRejected       = "rejected"     // the runtime refused the request's shape (a typed 400)
	UnsentNeverConnected = "never_connected"
	UnsentUnresolved     = "unresolved" // Resolve failed: no runtime was contacted
)

The reasons Unsent names. Each is a send failure that PROVES nothing was pasted into the agent's session.

View Source
const DefaultTurnTimeout = 10 * time.Minute

DefaultTurnTimeout bounds ONE REQUEST to the agent runtime — it is the default http.Client.Timeout, nothing more.

🔴 IT DOES *NOT* BOUND A TURN, AND THIS COMMENT SAID IT DID. The retracted sentence read "bounds one chat turn, including every tool round inside a tool-enabled one … stops a wedged turn holding a request goroutine for ever, and this is that". Measured false by audit: a tool-enabled turn issues up to agents.MaxToolLoopIterations requests, EACH getting its own budget — so the reachable ceiling is that many multiples of this value, plus whatever an in-process tool dispatch blocks for, which is under no HTTP timeout at all because agents.ToolDispatch takes no context.

⚠ AN EARLIER RETRACTION OF THIS PARAGRAPH ADDED ITS OWN FALSE CLAUSE — "and the loop only checks ctx between them" — AND THEN A FIX ROUND CLAIMED TO HAVE REMOVED IT WITHOUT WRITING THE FILE. Both transports build with http.NewRequestWithContext (responses.go, chatcompletions.go), so a caller deadline aborts an IN-FLIGHT request too; that is exactly why the next paragraph can say the caller's context is what bounds a turn. Naming the loop instead of the tool dispatch sends a reader adding a ceiling to the wrong layer — and a record asserting a retraction that did not happen is worse than the clause, because it stops the next reader checking.

âš  SO THE THING THAT ACTUALLY BOUNDS A TURN IS THE CALLER'S CONTEXT, and this package deliberately does not invent one: a request-scoped ctx already carries the caller's own deadline, and replacing it here would silently shorten a turn the caller was willing to wait for. If a turn-level ceiling is wanted it belongs at the call site, where the deadline has an owner.

View Source
const SchemeHooksSHA256 = "hooks-sha256"

SchemeHooksSHA256 is HooksSHA256's configuration spelling. Exported because the binary's configuration compares against it and its banner prints it — two copies of the string is how a value an operator sets stops matching the value the code checks.

Variables ¶

View Source
var ErrCLIActivityUnsupported = errors.New("agentgateway: the agent's runtime does not report its CLIs (GET /v1/clis); its image predates it")

ErrCLIActivityUnsupported is an agent runtime without GET /v1/clis: a ccd image older than the route, or a runtime that is not ccd.

View Source
var ErrTranscriptUnsupported = errors.New("agentgateway: the agent's runtime does not serve its transcript (GET /v1/transcript); its image predates it")

ErrTranscriptUnsupported is an agent runtime without GET /v1/transcript: a ccd image older than the route, or a runtime that is not ccd.

Functions ¶

func LanesFull ¶ added in v0.114.0

func LanesFull(err error) bool

LanesFull reports whether err is ccd's typed 503 `capacity` refusal (agents.FailureCapacity): the turn named an explicit session, its CLI was not running, and every CLI ccd may run at once is held by a turn. ccd answers it before starting a CLI or pasting anything, so it too proves the turn was not sent.

⚠ IT IS NOT ONE OF Unsent's REASONS, DELIBERATELY. Adding it there would change what every unsolicited deliverer does with it (a plugin delivery to a chief whose default session is an explicit one, the memo relay, …), and each of those is its own decision. A caller that routes a turn to a lane of its own and wants "skip, retry later" asks this as well (chief_nudge.go).

func ParseHealthzCheckout ¶

func ParseHealthzCheckout(body []byte) (agents.CheckoutStatus, error)

ParseHealthzCheckout extracts `repo` from a ccd /healthz body. Exported so cmd/ccd's test can feed it the body ccd's own handler writes: the two sides of this wire meet only in a running pod otherwise.

func Unsent ¶

func Unsent(err error) string

Unsent names a Gateway.Send failure that PROVES nothing was pasted into the agent's session, or "" for success and for every failure that does not prove it. Moved here from internal/memorelay so every deliverer of an UNSOLICITED turn (the memo relay, plugin messages) reads one rule.

  • the runtime's own TYPED refusals — 409 `busy`, 503 `not_ready`, 401 `unauthorized`, and a 400 (`bad_request`, `invalid_input`) — are each answered before it pastes anything. Only its typed body sets Type, so an untyped 409 or 503 from anything else is NOT read as "nothing was sent";
  • a 409 `rate_limited`: ccd's refusal from a pane parked on the CLI's usage-limit menu (cmd/ccd failure.go limitMenuFailure), also before anything is typed. It reads as UnsentBusy, so a deliverer queues the message again as it did when ccd answered that menu `busy`; the gateway has already marked the account and failed the agent over. A rate-limited turn that WAS pasted is a 429 and is not read here;
  • a dial error is a connection that was never opened, so no byte of the request left;
  • a Gateway.Resolve failure, from a turn that resolves its agent itself, contacted nothing.

None of those is read on a tool turn's SECOND or later request (agents.PastFirstRequest): request 1 was answered and its tools dispatched, so the turn happened whatever request 2 came back with.

⚠ ONE CASE THIS CANNOT PROVE, AND IT ERRS TOWARDS "MAY HAVE BEEN SENT": a send cancelled while its connection was still being opened surfaces as a bare context error, with no dial error inside it. A caller records that `unconfirmed` and does not send it again; the alternative reading — a cancelled send was never sent — would repeat every turn a redeploy cut off mid-flight.

Types ¶

type AccountFailover ¶ added in v0.114.0

type AccountFailover interface {
	NoteAccountFailure(ctx context.Context, agentID int64, account, failure, detail string)
}

AccountFailover is what the gateway tells after a typed `rate_limited` / `auth_failed` was marked against a claude-code agent's account (internal/ccfailover.Service). It may move the agent to another account and restart its pod; the gateway does not wait for the new pod, and the failed turn's error is returned unchanged.

type AccountMarker ¶

type AccountMarker interface {
	//
	// owner is the agent's owner: an account is (owner, name) since members
	// bring their own (internal/ccpool's Store doc).
	MarkFailure(ctx context.Context, owner int64, account, failure, detail string) error
}

AccountMarker is the one thing this package needs from the Claude account pool (internal/ccpool.Pool satisfies it). It is narrow for the reason EndpointResolver is: a chat path has no business selecting accounts or reading tokens.

type Config ¶

type Config struct {
	// Driver resolves an agent's reachable address. REQUIRED.
	Driver EndpointResolver
	// Runtime is the credential scheme the attached agent image uses. REQUIRED —
	// there is no default, because guessing one means deriving a credential by the
	// wrong formula and reporting 401s.
	Runtime Runtime
	// Model is the runtime's passthrough sentinel: REQUIRED on the wire by both
	// endpoints, and REQUIRED here for the same reason.
	//
	// 🔴 IT IS NOT THE MODEL AN AGENT RUNS, AND IT HAS NO DEFENSIBLE DEFAULT. The
	// runtime resolves the actual model from its own configuration; this field only
	// satisfies the wire's required `model` field, and the value is whatever the
	// attached image recognises. Substituting something more descriptive — a real
	// provider/model slug, which is the obvious guess — produces a request the
	// runtime rejects. It is configuration rather than a constant because the value
	// belongs to the image, not to this project.
	Model string
	// Client is the HTTP client for gateway calls. Optional; a client with
	// [DefaultTurnTimeout] is built when nil.
	//
	// ⚠ A KIND WITH ITS OWN TURN BUDGET (agents.KindTurnTimeout — today
	// claude-code) gets a COPY of this client with that Timeout; the transport is
	// shared. The gateway kind uses this client exactly as given.
	Client *http.Client
	// Accounts records a claude-code agent's typed `rate_limited` / `auth_failed`
	// failures against the Claude account it runs on. Optional: nil means no
	// claude-code kind is enabled, and nothing is marked.
	Accounts AccountMarker
}

Config is everything the gateway needs. Every field without a stated default is required, and New says which one is missing rather than producing a gateway that fails at the first turn.

type EndpointResolver ¶

type EndpointResolver interface {
	Endpoint(ctx context.Context, ref provision.Ref) (provision.Endpoint, error)
}

EndpointResolver is the one thing this package needs from a provisioner: where an instance is reachable.

🔴 IT IS A NARROW INTERFACE RATHER THAN provision.Provisioner, AND THAT IS A CLAIM ABOUT BLAST RADIUS, NOT A STYLE CHOICE. A gateway holding the full driver contract could Create, Scale and Destroy — a chat path with the authority to delete the instance it is talking to. It is satisfied by provision.Provisioner as written, so the wiring passes the same driver the lifecycle adapter holds and the two cannot disagree about where an agent lives.

type Gateway ¶

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

Gateway implements the consumer-side chat interface over a driver and a runtime.

⚠ IT DOES NOT NAME THAT INTERFACE IN A COMPILE-TIME ASSERTION, for the reason agentprovision.Adapter's doc gives: internal/api declares it consumer-side so this direction of the dependency does not exist. The binding is checked where it is used — cmd/muster-server assigns a *Gateway to api.Extensions.Gateway — and internal/api's own seam test pins it from the side that owns the interface, including what a *Gateway must NOT satisfy.

func New ¶

func New(cfg Config) (*Gateway, error)

New validates the configuration and builds the gateway.

func (*Gateway) CLIActivity ¶ added in v0.132.0

func (g *Gateway) CLIActivity(ctx context.Context, a agents.Agent) (agents.CLIActivity, error)

CLIActivity reads which CLIs in agent a's pod are working (ccd's GET /v1/clis, agents.CLIActivity). The bearer is the turn bearer.

func (*Gateway) Chat ¶

func (g *Gateway) Chat(ctx context.Context, a agents.Agent, sessionKey, message string, emit func(string)) (string, error)

Chat sends one user message to the agent's gateway under sessionKey, streaming assistant text deltas to emit (nil-safe), and returns the full reply. It carries NO tools — see the package doc on why the TOOLS fallback decision is the caller's. The TRANSPORT choice below is not that decision and is made here.

🔴 IT RUNS OVER /v1/responses AND ONLY FALLS BACK TO /v1/chat/completions ON A 404, BECAUSE THE STREAMING CHAT-COMPLETIONS PATH SILENTLY LOSES A REASONING MODEL'S ENTIRE ANSWER. The measurement is recorded on agents.RunToollessTurn: the same prompt to the same live agent produced zero content deltas over streaming chat-completions — an HTTP 200 and `{"reply":""}` out of POST /api/agents/{name}/messages, which is `chief ask`'s door — and the full text over /v1/responses. Nothing in this package could have detected it: a 200 with no deltas is indistinguishable here from a model that genuinely said nothing.

🔴 THE 404 FALLBACK IS THE *ONLY* ONE, AND THAT IS DELIBERATE RATHER THAN INCOMPLETE. ErrResponsesUnsupported means the endpoint is absent (responses.go maps a 404 and nothing else), so chat-completions is then the only transport that runtime has. Every OTHER failure propagates: falling back on a 400 or a 500 would route the turn straight back into the transport this change exists to leave, and the observable would be the empty reply returning under a different cause.

⚠ WHAT THE FALLBACK COSTS, SINCE THE CALLER CANNOT SEE IT: on a runtime that lacks /v1/responses, one turn is two requests — the 404 probe and the real call. That is paid only by images old enough to lack the endpoint, and it buys a caller that does not have to know which transport an agent's image speaks.

âš  IT SENDS NO `instructions`, AND THAT IS PARITY RATHER THAN AN OVERSIGHT. The transport this replaces posted one user message and no system prompt at all, so supplying one here would change what the agent is told on a path whose only defect was the wire format. Chat's signature has nowhere to carry a prompt; a caller that needs one has ChatWithTools, which takes it.

It is exactly Gateway.Resolve followed by Gateway.Send; the split exists for a caller that must know whether a failure happened BEFORE anything was sent.

func (*Gateway) ChatWithTools ¶

func (g *Gateway) ChatWithTools(ctx context.Context, a agents.Agent, sessionKey, instructions, message string, tools []agents.ToolDef, dispatch agents.ToolDispatch, emit agents.StreamEmit) (string, error)

ChatWithTools runs one tool-enabled turn through the runtime's /v1/responses endpoint: the model gets the native function tools and dispatch executes each call in this process. Returns agents.ErrResponsesUnsupported unwrapped when the runtime lacks the endpoint, so a caller's errors.Is fallback works.

func (*Gateway) Checkout ¶

func (g *Gateway) Checkout(ctx context.Context, t Target) (agents.CheckoutStatus, error)

Checkout reads the repository checkout a claude-code agent's ccd reports on /healthz (`repo`; cmd/ccd/checkout.go): the input internal/agentkickoff needs to hold a first turn, unstamped, until the repository exists (agents.DecideFirstTurn). It contacts the runtime but sends it no turn.

A pod with no repository reports no `repo`, which is agents.CheckoutUnknown with a nil error. A read that fails is an error; the caller decides what an unread checkout means (agents.DecideFirstTurn: as before, unless the row already recorded a wait).

âš  IT ACCEPTS A 503. ccd's /healthz answers non-200 when the session is unhealthy (a CLI in crash_loop), and its body still carries `repo`; the probe is a liveness signal, not this read's.

func (*Gateway) Resolve ¶

func (g *Gateway) Resolve(ctx context.Context, a agents.Agent) (Target, error)

Resolve does the part of Gateway.Chat that contacts no agent runtime: it refuses a token-less row and asks the driver where the agent is (for the k8s driver, a Deployment read from the Kubernetes API).

🔴 IT IS SEPARATE SO A CALLER THAT PAYS FOR A TURN CAN RUN IT BEFORE ITS POINT OF NO RETURN. internal/agentkickoff marks a first turn delivered before sending it, so it is never paid twice. A transient Kubernetes API error here costs nothing and sends nothing; inside Chat it used to land after that mark and was recorded as a failed, unretried kickoff.

func (*Gateway) Runtime ¶

func (g *Gateway) Runtime() string

Runtime returns the attached runtime's name, for the boot banner and for error messages that have to say which wire contract applies.

func (*Gateway) Send ¶

func (g *Gateway) Send(ctx context.Context, t Target, sessionKey, message string, emit func(string)) (string, error)

Send runs the turn half of Gateway.Chat against a Target from Gateway.Resolve: /v1/responses, falling back to /v1/chat/completions on a 404 (see Chat).

func (*Gateway) Transcript ¶ added in v0.127.0

func (g *Gateway) Transcript(ctx context.Context, a agents.Agent, session string, after int64, backfill int) (cctranscript.Page, error)

Transcript reads agent a's session transcript from its runtime (ccd's GET /v1/transcript): the complete lines after offset after in session (after -1: the tail, its last backfill bytes). It is the officer transcript forwarder's source (internal/officers/transcript). The bearer is the turn bearer, the same credential a turn carries; it never appears in an error.

func (*Gateway) UseFailover ¶ added in v0.114.0

func (g *Gateway) UseFailover(f AccountFailover)

UseFailover installs the account failover. It is set after construction because the failover needs the lifecycle adapter, which is built after the gateway (cmd/muster-server buildAgentPlaneWith).

type Runtime ¶

type Runtime interface {
	// Name is how this scheme is spelled in configuration and on the boot banner.
	Name() string
	// Bearer derives the gateway's Authorization credential from the agent's
	// hooks token.
	Bearer(hooksToken string) string
}

Runtime is the one fact about an agent runtime's chat wire that has to be CODE rather than configuration: how the gateway's credential is derived.

🔴 IT HOLDS EXACTLY ONE BEHAVIOUR, AND THE OTHER RUNTIME-SPECIFIC FACT IS DELIBERATELY NOT HERE. A chat turn needs two things this project cannot invent — the bearer and the model sentinel — and they differ in kind. The bearer is a FORMULA, so only code can express it. The sentinel is a VALUE, so configuration can: it lives on Config.Model, supplied by the deployment. Putting the value here too would have meant a runtime's own name and string constants in this module's source, which is precisely what this project is not allowed to carry.

🔴 SCHEMES ARE NAMED AFTER THE DERIVATION, NOT AFTER A PRODUCT. HooksSHA256 is "the gateway credential is sha256 over a prefixed hooks token", and any agent image computing it that way is served by it whatever the image is called. That is also the only naming that survives this module being public.

WHAT EARNS A SECOND IMPLEMENTATION: an agent image whose gateway derives its credential differently. A runtime that needed a second METHOD would be evidence the seam is in the wrong place — the transport in internal/agents is shared by construction, and anything expressible as a value belongs in Config.

func HooksSHA256 ¶

func HooksSHA256() Runtime

HooksSHA256 is the credential scheme in which the gateway's bearer is sha256("gw-" + HOOKS_TOKEN), rendered lower-case hex.

type Target ¶

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

Target is an agent whose address and credential are resolved: everything a Gateway.Chat turn needs before it opens a connection. Obtain one with Gateway.Resolve. Its fields are unexported, so a caller outside this package cannot fill one in; only a zero value can be built there, and that has no address.

Jump to

Keyboard shortcuts

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