Documentation
¶
Overview ¶
Package inject implements the HTTP endpoint that receives edge-trigger payloads (from k8s-event-watcher and any other source speaking the envelope.InjectPayload shape) and dispatches them into the mast runtime.
For the v0.1 spike this endpoint is single-session and single-bearer. Multi-session substrate and the X-Asserted-Caller proxy-identity mechanism from core-agent's recipe are deferred.
Index ¶
- Constants
- Variables
- type AbortHandler
- type AbortRequest
- type AckEffectsHandler
- type AckEffectsRequest
- type AppliedCall
- type Call
- type ChangeSet
- type Config
- type ExtendTokenHandler
- type ExtendTokenRequest
- type ExtendTokenResult
- type Handler
- type Hold
- type MonitorAckHandler
- type MonitorAckRequest
- type MonitorAckResult
- type Park
- type ParksHandler
- type ParksRequest
- type ParksResult
- type PauseHandler
- type PauseRequest
- type PauseResult
- type ProposedCall
- type ResumeHandler
- type ResumeRequest
- type Server
- type SessionParks
- type StopHandler
- type StopRequest
- type StopResult
Constants ¶
const ( // ParkKindApproval is a write-gate park: a mutating call waiting to // be approved, rejected or edited. Change is set. ParkKindApproval = "approval" // ParkKindInput is a question the agent asked — // request_operator_input, or an ADK RequestedInput. Change is nil. ParkKindInput = "input" )
Park kinds. These are the same two strings transcript.Detail.Awaiting reports, and they are duplicated rather than imported because pkg/inject declares a wire contract and pkg/transcript declares a projection: a Go rename in either one must not silently change the other's JSON. cmd/mast holds both and pins the correspondence.
SharedCredentialIdentity is the Caller identity recorded when no Authenticator is configured. It is deliberately not "anonymous" and deliberately not a person: the request did present a credential — the daemon's shared bearer token — and the honest audit record says that a holder of that token approved, not that nobody did and not that somebody in particular did.
Variables ¶
var ErrBadPayload = errors.New("invalid inject payload")
ErrBadPayload, returned (or wrapped) by a Handler, marks a request the daemon refuses on its content (e.g. a payload UID deriving a reserved session ID). Mapped to 400 instead of the generic 500 so emitters don't retry a request that can never succeed.
var ErrConflict = errors.New("session state refuses this request")
ErrConflict, returned (or wrapped) by a handler, marks a request the daemon refuses because of the session's current state — aborted (terminal), gate-paused, or an expired resume token. Mapped to 409: not the emitter's payload (400), not a transient daemon condition (503) — the session's state has to change first (resume, ack, extend-token), so blind retries are wrong.
var ErrNotFound = errors.New("session not found")
ErrNotFound, returned (or wrapped) by a ParksHandler, reports that the named session does not exist. Mapped to 404.
A session that exists and is not parked is NOT this error: it answers 200 with an empty parks list, because "nothing to approve" is an answer and "no such session" is a different one, and a client that polls cannot tell them apart from a status code alone.
ErrUnavailable, returned (or wrapped) by a Handler or ResumeHandler, tells the server the daemon is refusing new work — a shutdown drain is underway. The server maps it to 503 + Retry-After instead of the generic 500, so emitters retry against the replacement pod rather than treating a rolling restart as a crash.
Functions ¶
This section is empty.
Types ¶
type AbortHandler ¶
type AbortHandler func(ctx context.Context, req AbortRequest) error
AbortHandler applies an abort request. Optional; when nil the /abort route responds 404.
type AbortRequest ¶
type AbortRequest struct {
// SessionID identifies the session to mark aborted.
SessionID string `json:"session_id"`
// Reason is the operator-supplied reason, recorded in the abort
// marker and surfaced by `mast sessions list/show`.
Reason string `json:"reason,omitempty"`
}
AbortRequest asks the daemon to mark a session aborted.
Semantics are those of pkg/transcript's Store.Abort — a durable operator-abort marker appended to the session's event log, not preemption of in-flight work. See that method's doc for the full contract (docs/durable-execution-design.md, "Operator-facing surface"; engine-level terminal abort is v0.2).
type AckEffectsHandler ¶ added in v0.2.0
type AckEffectsHandler func(ctx context.Context, req AckEffectsRequest) error
AckEffectsHandler applies an effects acknowledgement. Optional; when nil the /ack-effects route responds 404.
type AckEffectsRequest ¶ added in v0.2.0
type AckEffectsRequest struct {
// SessionID identifies the session being acknowledged.
SessionID string `json:"session_id"`
// Reason is the operator-supplied note, recorded in the marker.
Reason string `json:"reason,omitempty"`
}
AckEffectsRequest records the operator's acknowledgement of ambiguous prior effects on a session — the standalone twin of ResumeRequest.AckEffects, for the outbox's primary scenario: an interrupted turn leaves a dangling mutating tool call but NO pending interrupt, so there is nothing to resume. Semantics are those of pkg/transcript's Store.AckEffects (a durable watermark on the companion ops row; covers only intents persisted at or before it).
type AppliedCall ¶ added in v0.9.0
type AppliedCall struct {
CallID string `json:"call_id,omitempty"`
// Tool and Args are the call AS IT RAN. On an edited approval that
// is the operator's arguments, not the model's.
Tool string `json:"tool"`
Args map[string]any `json:"args,omitempty"`
Key string `json:"key,omitempty"`
CapturedAt time.Time `json:"captured_at,omitzero"`
// Read is the read that produced the capture, so a client can take
// it again and compare. Digest hashes its whole result.
Read string `json:"read,omitempty"`
Digest string `json:"digest,omitempty"`
// PriorFields are the declared paths the capture narrowed to. The
// VALUES are deliberately not here: they are cluster state, they
// can be arbitrarily large, and this projection is read by relays.
// Take the read again if you need them.
PriorFields []string `json:"prior_fields,omitempty"`
// Revert is the call that restores the captured state, already
// checked against the revert tool's declared input schema. Nil when
// the workload declared no inverse. mast never fires it: capture,
// not restore.
Revert *Call `json:"revert,omitempty"`
}
AppliedCall is a mutating call that already ran and that the gate captured prior state for.
type Call ¶ added in v0.9.0
Call is a tool call named without a verdict attached to it — a member of a change set, or a revert.
type ChangeSet ¶ added in v0.9.0
type ChangeSet struct {
Specialist string `json:"specialist,omitempty"`
Changes []Call `json:"changes,omitempty"`
// Grantable reports whether `scope: change_set` is admissible;
// Ungrantable says why it is not.
Grantable bool `json:"grantable"`
Ungrantable string `json:"ungrantable,omitempty"`
// TTLSeconds is how long approving the set authorizes its remaining
// calls for.
TTLSeconds int `json:"ttl_seconds,omitempty"`
// Preconditions names, per tool, the read each granted call is
// re-checked against before it fires — and says where there is
// none, because "approved for ten minutes" and "approved while the
// Deployment still has 3 replicas" are different promises.
Preconditions map[string]string `json:"preconditions,omitempty"`
}
ChangeSet is the set a parked call belongs to.
type Config ¶
type Config struct {
// Listen is the bind address, e.g. ":7777".
Listen string
// BearerToken is the shared secret required in the Authorization
// header. Empty disables auth (intended only for local development;
// production deploys must set it).
BearerToken string
// Handler is called for each valid inject. Required.
Handler Handler
// ResumeHandler is called for each valid resume POST. Optional.
ResumeHandler ResumeHandler
// Authenticator, when set, resolves the caller identity behind a
// /resume request and puts it on the handler's context
// (auth.CallerFromContext). It runs IN ADDITION to BearerToken, not
// instead of it: a resume presenting the shared token is still
// admitted and recorded as [SharedCredentialIdentity], and one
// presenting a token from the user table is recorded as the person.
// Both credentials arrive in the same Authorization header, so
// /resume tries the table first and falls back to the shared token
// (see [Server.resumeAuthOK]); a token that is neither is refused
// rather than downgraded.
//
// Only /resume consults it, deliberately. An approval is the one
// place in v0.3 where identity is load-bearing — "who authorized
// this change" is the audit question the release exists to answer,
// and it is the half that cannot be backfilled (docs/v0.3-plan.md
// W2.1). Extending authentication to the other routes is a
// behaviour change for every existing emitter and belongs with the
// multi-session substrate, not here.
//
// Nil means unauthenticated: verdicts record the shared-credential
// identity, which is honest about what a single bearer token can
// prove.
Authenticator auth.Authenticator
// AssertedCallerHeader is the header a proxy Caller uses to assert
// the effective identity. Empty means auth.HeaderAssertedCaller.
// Ignored unless Authenticator implements auth.AuthenticatorWithProxy.
AssertedCallerHeader string
// AbortHandler is called for each valid abort POST. Optional.
AbortHandler AbortHandler
// AckEffectsHandler is called for each valid ack-effects POST.
// Optional.
AckEffectsHandler AckEffectsHandler
// MonitorAckHandler is called for each valid monitor-ack POST
// (v0.5 W4.6). Optional.
//
// Note the name: this is NOT AckEffectsHandler's neighbour in
// anything but spelling. /ack-effects acknowledges mast's own
// ambiguous prior effects on a session so a resume can proceed;
// /monitor-ack acknowledges a finding in the monitored world so a
// producer stops reporting it. Different subject, different store
// of record, no shared machinery.
MonitorAckHandler MonitorAckHandler
// PauseHandler is called for each valid pause POST. Optional.
PauseHandler PauseHandler
// ExtendTokenHandler is called for each valid extend-token POST.
// Optional.
ExtendTokenHandler ExtendTokenHandler
// StopHandler is called for each valid stop POST. Optional.
StopHandler StopHandler
// ParksHandler answers GET /parks and GET /parks/{session} — the
// only read on this server. Optional; nil leaves both routes
// answering 404. See parks.go for the projection it returns and,
// more importantly, for what that projection deliberately omits.
ParksHandler ParksHandler
// Logger is the structured logger. Defaults to slog.Default().
Logger *slog.Logger
// Metrics, when non-nil, is served at GET /metrics (Prometheus
// scrape). Unauthenticated by design — scrape configs don't carry
// the inject bearer token, and the payload is aggregate counters
// only. Nil leaves the route unregistered.
Metrics http.Handler
// BaseContext, when non-nil, is the context every request context
// derives from. The daemon passes its turn-lifetime context so
// that when the shutdown drain window elapses, in-flight handler
// turns are cancelled and unwind instead of dying at process exit.
BaseContext context.Context
}
Config configures the inject server.
type ExtendTokenHandler ¶ added in v0.2.0
type ExtendTokenHandler func(ctx context.Context, req ExtendTokenRequest) (ExtendTokenResult, error)
ExtendTokenHandler applies a token extension. Optional; when nil the /extend-token route responds 404.
type ExtendTokenRequest ¶ added in v0.2.0
type ExtendTokenRequest struct {
// Token is the mast resume token (mrt_...).
Token string `json:"token"`
// TTL (Go duration) sets the new lifetime from now.
TTL string `json:"ttl"`
}
ExtendTokenRequest lengthens a resume token's lifetime — the audited recovery for an expired (or expiring) token; the pause itself is untouched.
type ExtendTokenResult ¶ added in v0.2.0
ExtendTokenResult reports the token's new expiry.
type Handler ¶
type Handler func(ctx context.Context, payload envelope.InjectPayload) error
Handler receives a validated inject payload and drives the mast runtime. It returns an error if dispatch fails; the server maps that to a 5xx response (503 + Retry-After for ErrUnavailable).
type Hold ¶ added in v0.9.0
type Hold struct {
Reason string `json:"reason,omitempty"`
Message string `json:"message,omitempty"`
// Token is the pause handle a resume may be keyed by.
Token string `json:"token,omitempty"`
MintedAt time.Time `json:"minted_at,omitzero"`
ExpiresAt time.Time `json:"expires_at,omitzero"`
// ResumeAt is set for a timed hold that releases itself.
ResumeAt time.Time `json:"resume_at,omitzero"`
}
Hold is an active operator-placed gate pause.
type MonitorAckHandler ¶ added in v0.5.0
type MonitorAckHandler func(ctx context.Context, req MonitorAckRequest) (MonitorAckResult, error)
MonitorAckHandler forwards an acknowledgement. Optional; when nil the /monitor-ack route responds 404 — a daemon whose workload declares no monitor.ack has nowhere to forward one.
type MonitorAckRequest ¶ added in v0.5.0
type MonitorAckRequest struct {
// Subject is the producer's subject key, verbatim as it appeared in
// the classification mast reported. Required — an ack with no
// subject is a request to silence everything, which no operator
// means and which mast will not infer.
Subject string `json:"subject"`
// Reason is the operator's note ("known, fix rolling out"),
// recorded in mast's audit record and forwarded if the producer's
// tool takes one.
Reason string `json:"reason,omitempty"`
// Workload, when set, must match the workload this daemon serves.
// Optional and checked rather than required: a relay that has
// several mast deployments configured should fail loudly when it
// posts to the wrong one, rather than suppress a finding on a
// cluster nobody was looking at.
Workload string `json:"workload,omitempty"`
}
MonitorAckRequest is an operator saying "I have seen this finding, stop telling me about it" (v0.5 W4.6).
There is no ack_by field, and there will not be one ¶
Who acked is resolved from the request's credential (handleMonitorAck → callerContext), exactly as an approver is on /resume. A body-supplied acker is an attribution a caller writes about itself, which after an incident is worth nothing: the audit question is who had the credential, not what the client typed. This route goes further than /resume and REFUSES a body carrying ack_by rather than ignoring it — silently dropping a field a client believed in produces a log naming the wrong person with no sign anything went wrong. A relay acking on a human's behalf names them with X-Asserted-Caller, the proxy path, which works only for a credential provisioned to assert.
And no window ¶
How long a suppression lasts belongs to whoever owns the finding state; mast forwards, records who asked, and holds no opinion about expiry. The deployment's default lives in the bundle's monitor.ack.args.
type MonitorAckResult ¶ added in v0.5.0
type MonitorAckResult struct {
// Workload and Subject echo what was acked.
Workload string `json:"workload"`
Subject string `json:"subject"`
// AckBy is who mast attributed it to — the value it forwarded and
// recorded. Echoed so the caller renders the identity mast resolved
// rather than the one it assumed; for a relay, those differ.
AckBy string `json:"ack_by"`
// PreviouslyAckedBy and PreviouslyAckedAt describe the last
// recorded ack of this subject, when there was one. Informational:
// mast forwards a repeat ack regardless, because whether a second
// one is redundant is the producer's call.
PreviouslyAckedBy string `json:"previously_acked_by,omitempty"`
PreviouslyAckedAt string `json:"previously_acked_at,omitempty"`
}
MonitorAckResult reports what mast recorded and forwarded.
type Park ¶ added in v0.9.0
type Park struct {
// InterruptID is the resume correlation key: POST /resume with this
// and the session ID, or with a pause token that names it.
InterruptID string `json:"interrupt_id"`
// Kind is ParkKindApproval or ParkKindInput.
Kind string `json:"kind"`
// Question is the operator-facing one-liner the pausing node wrote.
Question string `json:"question,omitempty"`
// Author is the agent that raised it.
Author string `json:"author,omitempty"`
// RaisedAt is when the pausing event was recorded.
RaisedAt time.Time `json:"raised_at"`
// Change is the call this park gates. Set for ParkKindApproval and
// nil otherwise — a question is not a change.
Change *ProposedCall `json:"change,omitempty"`
}
Park is one open interrupt.
type ParksHandler ¶ added in v0.9.0
type ParksHandler func(ctx context.Context, req ParksRequest) (ParksResult, error)
ParksHandler answers a park read. Optional; when nil the /parks routes respond 404.
It is a handler rather than a store because that is how every other route on this server is fed: pkg/inject owns the wire shape and cmd/mast owns where the answer comes from. Keeping it that way is what lets these declarations stay free of pkg/transcript and pkg/approval, which is the difference between a wire contract and a second Go spelling of an internal projection.
type ParksRequest ¶ added in v0.9.0
type ParksRequest struct {
SessionID string `json:"session_id,omitempty"`
}
ParksRequest asks for the parks on one session, or on every parked session when SessionID is empty.
type ParksResult ¶ added in v0.9.0
type ParksResult struct {
Sessions []SessionParks `json:"sessions"`
}
ParksResult is the body of GET /parks and GET /parks/{session}.
The two routes differ in which sessions appear, not in what a session looks like:
- GET /parks lists every PARKED session, each in full. Sessions with nothing to answer are omitted.
- GET /parks/{session} returns the named session whether it is parked or not, with an empty park list when it is not.
Always an object with a `sessions` array, including for the single-session route and including when nothing is parked. A bare array would make adding a field later a breaking change, and a 404 for "this session exists and is not parked" would be a lie a poller has to special-case.
type PauseHandler ¶ added in v0.2.0
type PauseHandler func(ctx context.Context, req PauseRequest) (PauseResult, error)
PauseHandler applies a gate pause. Optional; when nil the /pause route responds 404.
type PauseRequest ¶ added in v0.2.0
type PauseRequest struct {
// SessionID identifies the session to pause.
SessionID string `json:"session_id"`
// Reason is the pause-reason enum value (transcript.ValidReasons).
Reason string `json:"reason"`
// Message is the human-readable context, surfaced by list/show.
Message string `json:"message,omitempty"`
// Metadata is free-form context recorded on the pause record.
Metadata map[string]any `json:"metadata,omitempty"`
// ResumeAt (RFC3339), when set, arms the timed-pause scheduler.
ResumeAt string `json:"resume_at,omitempty"`
// Interrupt additionally cancels the session's in-flight turn (hard
// pause). The cancellation leaves no engine record — the pause
// record is the durable truth — and may strand dangling mutating
// intents for the effects outbox to guard.
Interrupt bool `json:"interrupt,omitempty"`
// TTL (Go duration, e.g. "48h") shortens the resume token's default
// 7-day lifetime. Lengthening at mint is not offered — extend-token
// is the audited operator path.
TTL string `json:"ttl,omitempty"`
}
PauseRequest asks the daemon to gate-pause a session (plane B of the v0.2 pause/abort surface, docs/durable-execution-design.md "The v0.2 pause/abort mechanics"): the daemon's turn chokepoint refuses every subsequent turn on the session until the pause is resumed by token.
type PauseResult ¶ added in v0.2.0
type PauseResult struct {
Token string `json:"token"`
SessionID string `json:"session_id"`
ExpiresAt string `json:"expires_at"`
}
PauseResult carries the minted pause handle back to the caller.
type ProposedCall ¶ added in v0.9.0
type ProposedCall struct {
// CallID is the function-call ID. It is the join key: every other
// durable record of the same call — the decision, the applied edit,
// the capture — is keyed by it.
CallID string `json:"call_id,omitempty"`
Tool string `json:"tool"`
Args map[string]any `json:"args,omitempty"`
// Key is the rendered one-line call the deny policy matches against
// and the audit record stores.
Key string `json:"key,omitempty"`
// Policy is the gate posture that parked it.
Policy string `json:"policy,omitempty"`
// Agent is the specialist that proposed it.
Agent string `json:"agent,omitempty"`
// Stale, when set, is why an approval the operator already gave no
// longer covers this call. Its presence is the difference between
// "please approve this" and "you approved this and the ground
// moved".
Stale string `json:"stale,omitempty"`
// VerdictFormat is the gate's own description of the answer it
// accepts, carried so a client answering over raw HTTP can read the
// shape of the reply in the question.
VerdictFormat map[string]any `json:"verdict_format,omitempty"`
// ChangeSet is the approved-as-a-unit set this call belongs to,
// when it belongs to one. Present means `scope: change_set` is on
// the table, and an operator can only make that trade if they are
// shown what the rest of the set is.
ChangeSet *ChangeSet `json:"change_set,omitempty"`
}
ProposedCall is a tool call waiting on a verdict.
type ResumeHandler ¶
type ResumeHandler func(ctx context.Context, req ResumeRequest) error
ResumeHandler feeds a resume payload into the runtime. Optional; when nil the /resume route responds 404.
type ResumeRequest ¶
type ResumeRequest struct {
// SessionID identifies the paused session (e.g. "incident-<uid>").
// Not required when Token is set.
SessionID string `json:"session_id,omitempty"`
// InterruptID matches the pending RequestInput's InterruptID. Not
// required when Token is set.
InterruptID string `json:"interrupt_id,omitempty"`
// Token is a mast resume token (mrt_...) minted at pause time —
// the v0.2 programmatic-pause keying. Mutually exclusive with
// SessionID/InterruptID.
Token string `json:"token,omitempty"`
// Response is the reply payload; validated against the interrupt's
// ResponseSchema by the workflow engine on resume.
Response any `json:"response"`
// AckEffects acknowledges ambiguous prior effects before the resume
// turn runs: dangling mutating tool calls from an interrupted turn
// stop tripping the recorded-effect outbox's fail-closed refusal
// (docs/durable-execution-design.md, "Recorded-effect outbox"). The
// operator asserts they have checked whether those calls took
// effect externally.
AckEffects bool `json:"ack_effects,omitempty"`
}
ResumeRequest is the operator's answer to a pending HITL interrupt (keyed by session + interrupt ID), or a token-keyed resume of a v0.2 pause (Token alone suffices; the daemon resolves it to the session and, for interrupt pauses, the pending call ID).
There is deliberately no approver field on the wire. Who approved is resolved from the request's credential (handleResume → callerContext) and recorded on the pause record's ConsumedBy; a body-supplied approver would be an attribution a caller writes about itself, which is exactly the thing an audit record must not accept. A relay that answers on a human's behalf — a chat bot with an approve button — names them with the X-Asserted-Caller header, which works only for a credential provisioned as a proxy. Same reasoning as attach's GuardrailResetRequest.Caller (`json:"-"`).
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the HTTP inject endpoint.
func (*Server) ListenAndServe ¶
ListenAndServe blocks serving requests. Returns http.ErrServerClosed on graceful shutdown.
type SessionParks ¶ added in v0.9.0
type SessionParks struct {
SessionID string `json:"session_id"`
// State is the session's projected state (paused, running, idle,
// aborted, interrupted). A parked session is paused, but a paused
// session is not necessarily parked — see Hold.
State string `json:"state"`
// Awaiting is what the session is waiting on overall:
// ParkKindApproval when any park is an approval, ParkKindInput when
// the open parks are only questions, empty when nothing is pending.
// An approval outranks a question, the same ranking the attach
// turn_state uses (#313).
Awaiting string `json:"awaiting,omitempty"`
// Parks are the open parks, oldest first.
Parks []Park `json:"parks,omitempty"`
// Hold is an operator-placed gate pause, if one is active. It is
// reported beside the parks and never as one: nothing resolves by
// answering a hold, so a client that renders it as a question puts
// a prompt in front of somebody with nothing to say back.
Hold *Hold `json:"hold,omitempty"`
// Applied are calls this session already ran that the gate captured
// a revert for, oldest first (#296). They are here because the
// obvious operator affordance beside "approve this change" is "put
// the last one back", and nothing outside the process could read
// one.
Applied []AppliedCall `json:"applied,omitempty"`
}
SessionParks is one session's parks.
type StopHandler ¶ added in v0.2.0
type StopHandler func(ctx context.Context, req StopRequest) (StopResult, error)
StopHandler initiates a planned stop. Optional; when nil the /stop route responds 404.
type StopRequest ¶ added in v0.2.0
type StopRequest struct {
// Reason is appended to the interruption markers' "operator stop"
// classification.
Reason string `json:"reason,omitempty"`
// PauseSessions gate-pauses every session that receives an
// interruption marker during the drain, so boot-time auto-resume
// hands them back to the operator instead of continuing them.
PauseSessions bool `json:"pause_sessions,omitempty"`
}
StopRequest asks the daemon for a planned stop (issue #42): the same drain the SIGTERM path runs, classified in the interruption markers as an operator stop.
type StopResult ¶ added in v0.2.0
type StopResult struct {
DrainBound string `json:"drain_bound"`
}
StopResult reports the drain bound the daemon will honor.