Documentation
¶
Overview ¶
Package agentops is the UX-free execute/inspect core shared by the `jentic` command tree and future embedders (the local MCP server, phase 1 of the local-MCP plan). It owns the resolve → build → send → classify lifecycle of a brokered call, lifted out of the cobra layer.
Dependency rules (phase-0 §0.2, deliberate and load-bearing):
- agentops receives token strings and a RESOLVED broker target. Token acquisition (sessions, credential resolution) and broker-target precedence (flag reading, environment broker_url, SEC-21 pinning, fail-closed guards) stay caller-side.
- Control-plane resolve/inspect calls go through the narrow Inspector seam, never the whole generated client surface.
- No io.Writer output, no cobra, no exit-code mapping, no TTY detection, no stdin. Errors are *ux.CodedError values carrying the closed-enum machine contract; the exit taxonomy stays in ux/contract.go.
Index ¶
- Constants
- Variables
- func BrokerError(r *ExecuteResult) *ux.CodedError
- func BrokerTransportError(r *ExecuteResult, retrySafe bool) *ux.CodedError
- func BrokerTransportRetryable(rec BrokerTransportRecovery, retrySafe bool) bool
- func BuildRequest(ctx context.Context, r ExecuteRequest) (*http.Request, error)
- func IsBrokerDenial(r *ExecuteResult) bool
- func IsBrokerHeld(r *ExecuteResult) bool
- func IsFinishedHeldStatus(status string) bool
- func IsLoopbackHost(host string) bool
- func LoopbackConnRefused(err error) bool
- func ParseMethodPath(target string) (method, path string)
- func RetryAfterSeconds(h http.Header) (float64, bool)
- func RetrySafe(method, idempotencyKey string) bool
- func TransportFailurePreSend(err error) bool
- func TrustedReviewURL(reviewURL, controlBaseURL, brokerURL string) bool
- type BrokerErrorRecovery
- type BrokerTransportRecovery
- type Denial
- type ExecuteRequest
- type ExecuteResult
- func Do(req *http.Request) (*ExecuteResult, error)
- func DoWith(hc *http.Client, req *http.Request) (*ExecuteResult, error)
- func Execute(ctx context.Context, r ExecuteRequest) (*ExecuteResult, error)
- func ExecutionResultFromHeld(contentType string, body []byte, executionID string) (*ExecuteResult, bool)
- type HTTPError
- type Held
- type HeldLinks
- type Inspector
- type KV
- type Operation
Constants ¶
const ( HeldStatusHeld = "held" HeldStatusQueued = "queued" HeldStatusRunning = "running" HeldStatusCompleted = "completed" HeldStatusFailed = "failed" HeldStatusCancelled = "cancelled" )
Execution statuses of a held execution (the control plane's HeldExecution execution_status): where the held call stands.
Variables ¶
var ErrInspectMissingFields = errors.New("inspect response missing method or url")
ErrInspectMissingFields reports an inspect document that resolved but carries no usable method/url pair.
Functions ¶
func BrokerError ¶ added in v0.42.0
func BrokerError(r *ExecuteResult) *ux.CodedError
BrokerError classifies a broker-origin 4xx that is not a recoverable denial: the broker could not resolve the call (an unknown credential id or name, an unregistered operation, a malformed request) and never reached the upstream, so it must not read as an upstream response that exits 0 (#1429). It returns RESOLVE_FAILED (exit 2) carrying the problem reason, or nil.
Unlike IsBrokerDenial it requires Jentic-Error-Origin to say "broker" explicitly: 400/404/422 are exactly what an upstream answers on a call that ran, so a missing header keeps the pass-through reading rather than turning a real upstream answer into a failure. Because of that origin requirement the denial-status exclusion is equivalent to skipping 401/403/409/424 — those stay on the Classify (denial) path.
Two broker-origin statuses are deliberately excluded, because RESOLVE_FAILED means "change the ask, don't retry" and both can be retryable as sent: 429 (rate_limit_exceeded, with Retry-After) and every 5xx. BrokerTransportError classifies those.
func BrokerTransportError ¶ added in v0.44.0
func BrokerTransportError(r *ExecuteResult, retrySafe bool) *ux.CodedError
BrokerTransportError classifies a 5xx or 429 the broker itself generated (its circuit breaker is open, a runner is degraded, it shed the call, a token refresh failed, it timed out or hit its deadline, it aborted an oversized response, it cannot carry the scheme). It is a TRANSPORT_ERROR (exit 1), not an upstream response that exits 0 (#1531). Details carry http_status, origin, problem_type, the retryable hint and, when the broker sent Retry-After, retry_after_s.
Like BrokerError it requires Jentic-Error-Origin to say "broker" explicitly. The header decides, never the body: a vendor 5xx the broker mirrored is stamped "upstream" and is the caller's data, and a missing header keeps the same pass-through reading. Every error the broker generates itself is stamped "broker", including its timeout, deadline, response-size and refresh failures (#1675).
func BrokerTransportRetryable ¶ added in v0.44.0
func BrokerTransportRetryable(rec BrokerTransportRecovery, retrySafe bool) bool
BrokerTransportRetryable reports whether re-sending the same call is safe for a recovery class. retrySafe is the caller's proof that the call cannot double-execute (see RetrySafe); only a timeout depends on it.
func BuildRequest ¶
BuildRequest assembles the outbound broker request from a resolved ExecuteRequest: path-parameter substitution, query append, the broker catch-all URL, the SEC-1 secure-transport guard, bearer/correlation/ idempotency headers. It does NOT send — the CLI's --dry-run/--export-plan hook renders the built request and stops before firing.
All traffic goes through the Jentic broker so the agent authenticates to the broker with its own token (Authorization: Bearer) and the broker injects the stored upstream credential. We never send the agent token to the upstream API directly. The broker is addressed as a catch-all proxy: {brokerScheme}://{brokerHost}/{upstreamURL} (mirroring the broker's /{upstream_url:path} route).
- r.URL (absolute upstream URL, from inspect / METHOD:url) is prefixed with the broker host.
- r.Path (broker-relative METHOD:/path) is sent to the broker host verbatim — the caller supplied the broker path themselves.
func IsBrokerDenial ¶
func IsBrokerDenial(r *ExecuteResult) bool
IsBrokerDenial reports whether a result is one the broker itself emitted to deny a call the agent can recover from: missing credential binding → 403 (wire type no_credential_binding), ambiguous credential binding → 409, credential needs reconnect → 401, no credential provisioned → 424. Each carries an agent_directive (see broker/web/errors.STATUS_BY_ERROR).
Status alone is NOT sufficient: the broker is a transparent forward proxy, so an *upstream* API can return these same 4xx codes on a call the broker successfully proxied (the upstream auth failed, the resource is forbidden, etc.). Treating those as broker denials would exit 2 and print a misleading "recovery required" for a call that actually ran. The broker disambiguates with the Jentic-Error-Origin response header (broker/core/headers): it stamps "broker" on its own errors and "upstream" on mirrored pass-through 4xx/5xx (broker/services/execution/pipeline.enrich_error_origin). So a denial-class status is a broker denial only when the origin is not "upstream" (a missing header is treated as broker, since the loopback broker always sets it on its own errors and only a non-conformant proxy would omit it).
func IsBrokerHeld ¶ added in v0.45.1
func IsBrokerHeld(r *ExecuteResult) bool
IsBrokerHeld reports whether the broker itself emitted a 202. Mirrored upstream responses carry Jentic-Upstream-Status; broker-held responses must never carry that header, even when their body has the held-envelope shape.
func IsFinishedHeldStatus ¶ added in v0.44.0
IsFinishedHeldStatus reports whether a held call's execution status is final: it ran (completed or failed) or will never run (cancelled).
func IsLoopbackHost ¶
IsLoopbackHost reports whether host is "localhost" or a loopback IP. It is the single loopback classifier the execute path and the CLI's broker-target guards share (the auth layer keeps its own private copy by design).
func LoopbackConnRefused ¶ added in v0.44.0
LoopbackConnRefused reports whether err is a refused TCP connection (isConnRefused) to a loopback target — 127.0.0.0/8, ::1, or "localhost" — the signature of a local jentic-one install that is not running (#849).
The target is read from every host the chain names: the request URL on a *url.Error and the dialed address on a *net.OpError. All of them must be loopback, and at least one must be present. Requiring the URL host keeps a refused loopback forward proxy in front of a REMOTE target from reading as a stopped local instance; requiring the dialed address keeps a loopback URL that was rerouted elsewhere from counting either.
func ParseMethodPath ¶
ParseMethodPath checks if target is in METHOD:/path format (a broker-relative path, e.g. GET:/v1/pets). Returns the method and path if valid, or empty strings if not in this format. A METHOD:URL absolute form (GET:https://…) is deliberately NOT matched here — that is handled as an inspectable identifier.
func RetryAfterSeconds ¶ added in v0.44.0
RetryAfterSeconds parses a Retry-After header to whole seconds (matching jentic_one.shared.http.retry_after.parse_retry_after): non-negative ASCII decimal delay-seconds (a fraction rounds up; a sign, exponent or non-ASCII digit is rejected), or an HTTP-date converted to the seconds remaining (floored at zero), capped at one day (86400s). ok is false when the header is absent or unparseable, so callers never relay a made-up delay.
func RetrySafe ¶ added in v0.44.0
RetrySafe reports whether re-sending a call cannot double-execute it: a GET/HEAD (case-insensitive), or a call carrying a non-blank Idempotency-Key the broker de-duplicates on. Pass the key that rides the wire (the built request's header), so a key supplied via a custom header counts too. The MCP mount's twin is jentic_one.mcp.execute.retry_safe.
func TransportFailurePreSend ¶
TransportFailurePreSend reports whether a transport failure provably happened BEFORE the request could reach the server: dial failures (connection refused, unreachable host, DNS) and TLS handshake/verification failures. For these a retry cannot double-execute — the upstream never saw the request. Everything else (deadline exceeded, connection reset, EOF mid-response) is ambiguous: the request MAY have been delivered, so callers must not advertise a blind retry for unkeyed mutating calls. The classification is a whitelist on purpose — the fail-safe answer is false.
func TrustedReviewURL ¶ added in v0.45.1
TrustedReviewURL reports whether reviewURL uses an approved transport and belongs to the configured control-plane or broker origin.
Types ¶
type BrokerErrorRecovery ¶ added in v0.42.0
type BrokerErrorRecovery string
BrokerErrorRecovery names what a broker resolve failure needs fixed. The CLI actionable prose and the MCP next_tool both key on it, so the two lanes never disagree about where to send the agent.
const ( // RecoverOperation means no registered operation serves the call — rediscover it. RecoverOperation BrokerErrorRecovery = "operation" // RecoverCredential means a Jentic-Credential-Id/Name header named a credential // the broker could not resolve — pick a valid one. RecoverCredential BrokerErrorRecovery = "credential" // RecoverContract means any other broker 4xx (method, revision pin, payload size, // idempotency key, egress-blocked URL, request validation) — fix the request // against the operation's contract. RecoverContract BrokerErrorRecovery = "contract" )
func BrokerErrorRecoveryFor ¶ added in v0.42.0
func BrokerErrorRecoveryFor(status int, problemType string) BrokerErrorRecovery
BrokerErrorRecoveryFor routes a broker resolve failure by status and exact problem type: a 404 or operation_not_found is a discovery problem, a known credential-resolution type is a header problem, and everything else is a contract problem (never a bare identity check, which cannot fix a malformed request).
type BrokerTransportRecovery ¶ added in v0.44.0
type BrokerTransportRecovery string
BrokerTransportRecovery names how an agent recovers from a broker-origin 5xx or 429. The CLI actionable prose, the MCP next_tool and the retryable hint all key on it, so the lanes never disagree about whether a retry is safe.
const ( // RecoverWait means the broker failed the call before the upstream could // act on it (circuit open, runner degraded, admission shed, resolution // overloaded, rate limit, transient credential refresh, connect failure): // re-sending the same call after a wait is safe for any method, because // the upstream never saw it. RecoverWait BrokerTransportRecovery = "wait" // RecoverTimeout means the broker ran out of time on the call. The request // may already have reached the upstream, so a retry is only safe when the // call cannot double-execute (GET/HEAD, or an Idempotency-Key). RecoverTimeout BrokerTransportRecovery = "timeout" // RecoverScheme means the broker has no runner for the upstream's URL // scheme: re-sending cannot succeed, the agent needs a different operation. RecoverScheme BrokerTransportRecovery = "scheme" // RecoverUnknown is any other broker 5xx. Its type does not say whether the // failure happened before or after the upstream call, so it is never // advertised as retryable. RecoverUnknown BrokerTransportRecovery = "unknown" )
func BrokerTransportRecoveryFor ¶ added in v0.44.0
func BrokerTransportRecoveryFor(status int, problemType string) BrokerTransportRecovery
BrokerTransportRecoveryFor routes a broker-origin 5xx/429 by status and exact problem type. Any 429 is a wait (the status itself means "slow down, then retry"). The timeout types may have reached the upstream. runner_scheme_unsupported (RunnerSchemeUnsupportedError, 501) needs a different operation. Everything else is unknown, including upstream_response_too_large (UpstreamResponseTooLargeError, 502: the upstream answered, so the call ran), upstream_transport_error (UpstreamTransportError, 502: the connection failed mid-request) and upstream_request_invalid (500: the broker built a request its HTTP client refused to send, so re-sending the same call will fail the same way).
type Denial ¶
type Denial struct {
Status int
// ProblemType is the problem+json "type" member the denial body carried
// ("no_credential_binding", "action_denied", …), empty when the body was
// not parseable. Recovery pointers key on it — the HTTP status alone is
// ambiguous (403 covers both a missing binding and a permission-rule
// denial, whose recoveries are opposites).
ProblemType string
// Directive is the parsed agent_directive, or nil when the denial carried
// none (the caller synthesizes a status-keyed recovery hint instead).
Directive *ux.Directive
// DirectiveRaw is the verbatim agent_directive JSON sub-object the denial
// carried (nil when Directive is nil). Relaying surfaces (the MCP payload)
// use it so unknown future broker fields survive intact; the CLI's styled
// renderer keeps reading the typed Directive projection.
DirectiveRaw json.RawMessage
}
Denial is the classification of a broker-denied call (classify.go): the denying HTTP status plus the recovery directive when the body carried one.
func Classify ¶
func Classify(r *ExecuteResult) *Denial
Classify is the unfused classification step (response → denial-or-not) the old executeOutput performed inline with printing: nil for every non-denial result (2xx, upstream pass-through 4xx/5xx), else the Denial carrying the denying status and the parsed directive (nil Directive when the body carried none — the caller synthesizes a status-keyed recovery hint). The exit code keys off the *status*, not the presence of an agent_directive: some denials (e.g. action_denied from a permission rule) carry no directive, and gating on a parsed directive would let those silently exit 0.
func (*Denial) Err ¶
func (d *Denial) Err() *ux.CodedError
Err returns the typed denial every broker-denial exit shares (AGT-6): BROKER_DENIED with the denying HTTP status in Details, so the agent envelope and the exit code come from the same table. The recovery directive is rendered by the caller before this is returned.
type ExecuteRequest ¶
type ExecuteRequest struct {
// Method is the HTTP method of the resolved operation.
Method string
// URL is the absolute upstream URL to route through the broker. Exactly one
// of URL or Path is set (mirroring Operation).
URL string
// Path is a broker-relative path sent to the broker host verbatim.
Path string
// PathParams substitute {key} placeholders in the upstream target
// (percent-escaped, in order).
PathParams []KV
// QueryParams are appended to the upstream target before broker-wrapping.
QueryParams []KV
// Headers are extra request headers, applied after the automatic ones so a
// caller-supplied header always wins.
Headers []KV
// Body is the request body reader, or nil for a bodyless request (nil vs a
// reader — even an empty one — gates the automatic Content-Type, matching
// the historical behavior). The stdin fallback and --data/--data-file
// reading stay caller-side (under stdio MCP, stdin is the JSON-RPC wire).
Body io.Reader
// BrokerScheme/BrokerHost are the RESOLVED broker target — precedence
// (defaults < environment broker_url < flags) has already run caller-side.
BrokerScheme string
BrokerHost string
// Token is the agent bearer forwarded to the broker (never to the upstream).
Token string
// SessionID, when set, is stamped as X-Jentic-Session-Id (already sanitized
// by the caller). Correlation is best-effort and never blocks a call.
SessionID string
// IdempotencyKey, when set, is stamped as Idempotency-Key so a retried
// POST/PUT is de-duplicated by the broker and treated as replayable by the
// SDK transport's retry policy.
IdempotencyKey string
}
ExecuteRequest is the UX-free input to BuildRequest/Execute: a resolved operation, the request surface (params/headers/body), the RESOLVED broker target, and the caller's credentials/correlation strings. No flag state, no session objects.
type ExecuteResult ¶
ExecuteResult is the UX-free outcome of a brokered call: the relayed status, the full response headers, the bounded-read body, and the broker's execution id. Rendering (envelope vs pretty vs raw) and exit-code mapping happen caller-side; classification lives in classify.go.
func Do ¶
func Do(req *http.Request) (*ExecuteResult, error)
Do sends a built broker request through the SDK broker transport (client.BrokerTransport) rather than a bare http.Client, so execute inherits the same response policy (401 re-exchange, 429 Retry-After, bounded 5xx/transport backoff — 13 §5) every generated broker call gets, while still composing the broker catch-all URL itself to preserve its exact contract and exit-2 denial handling. The 60s ceiling is carried on the base client the policy decorates. The response body is read bounded (MaxBodyBytes) into the returned ExecuteResult.
func DoWith ¶
DoWith is Do with a caller-supplied base *http.Client for the broker leg — the §3.7.2 CA-pinning seam: a long-lived embedder (the MCP server) resolves the SEC-20 CA-pinned client (plus its attribution TransportHook) through clictx and passes it here, so the broker leg honors the environment's ca_cert_path exactly like every control-plane call. The SDK broker response policy still decorates the OUTSIDE (client.BrokerTransport wraps hc's transport), so hooked headers ride every retry attempt. A nil hc keeps the historical default client. A missing timeout gets the 60s execute ceiling.
func Execute ¶
func Execute(ctx context.Context, r ExecuteRequest) (*ExecuteResult, error)
Execute is the one-call UX-free core (ExecuteRequest → ExecuteResult): BuildRequest + Do. The CLI and MCP handler drive the two phases separately (so --dry-run/--export-plan can stop before firing and MCP can pass its CA-pinned client to DoWith); parity tests and simple callers use this helper.
func ExecutionResultFromHeld ¶ added in v0.44.0
func ExecutionResultFromHeld(contentType string, body []byte, executionID string) (*ExecuteResult, bool)
ExecutionResultFromHeld turns a held execution's result (GET /executions/holds/{id}/result: its body and Content-Type) into the ExecuteResult a synchronous call would have produced, so a waited-for held call renders and classifies exactly like one that ran at once:
- a run: the upstream status and decoded body, under the upstream Content-Type, stamped Jentic-Error-Origin "upstream" on an error status like the broker stamps a mirrored upstream error;
- a call that never ran (a denied, expired or unresumable hold, or a run-time denial): the problem body at its own status, stamped origin "broker", so Classify reads it as the broker denial it is.
It reports false when the document is neither (a run that failed before the upstream answered carries no status).
func (*ExecuteResult) Envelope ¶
func (r *ExecuteResult) Envelope() ux.ExecuteEnvelope
Envelope projects the result onto the shared success envelope (ux.ExecuteEnvelope, schema version stamped): single-value headers, the body parsed as JSON when it decodes (else the raw string).
func (*ExecuteResult) EnvelopeWithin ¶ added in v0.45.1
func (r *ExecuteResult) EnvelopeWithin(limit int64) (env ux.ExecuteEnvelope, oversize bool)
EnvelopeWithin projects the result onto the shared success envelope when the body fits within limit bytes. When limit > 0 and len(r.Body) exceeds limit, it returns the envelope with Body: nil and oversize: true without unmarshaling the body.
type HTTPError ¶
HTTPError is a non-2xx control-plane response from the Inspector seam. It mirrors the shape the hand-written httpx.HTTPError offered — StatusCode plus the raw problem-details body — so error-mapping logic ports unchanged. The api command tree aliases it (api.HTTPError) so its call sites are untouched.
type Held ¶ added in v0.44.0
type Held struct {
Status string `json:"status"`
HeldExecutionID string `json:"held_execution_id"`
ReviewURL string `json:"review_url"`
ExpiresAt string `json:"expires_at"`
AgentDirective string `json:"agent_directive"`
Links HeldLinks `json:"_links"`
}
Held is the broker's 202 answer to a call a require-approval rule held for a human: the held execution, the review page a person opens to approve or deny it, and the directive telling the agent what to do next.
func ParseHeld ¶ added in v0.44.0
func ParseHeld(r *ExecuteResult) (*Held, bool)
ParseHeld reports whether a broker result is a held call: a broker-generated 202 whose body is the held envelope (status "held", a held execution id and a review URL). Any other 202 — a plain respond-async job or an upstream response — is not held.
type HeldLinks ¶ added in v0.44.0
type HeldLinks struct {
Self string `json:"self"`
Result string `json:"result"`
Withdraw string `json:"withdraw"`
}
HeldLinks are a held envelope's links: the held execution itself, its eventual result, and where to withdraw it.
type Inspector ¶
type Inspector interface {
// Inspect resolves an operation (opaque id or METHOD:url) to its full
// structural document. format is one of "json", "markdown", or "openapi";
// revision optionally pins a revision ID. A non-2xx backend response
// surfaces as *HTTPError.
Inspect(ctx context.Context, target, revision, format string) ([]byte, error)
}
Inspector is the narrow control-plane seam agentops needs: the raw inspect call returning the FULL inspect document (JSON/Markdown/OpenAPI negotiated by format), not just the {method,url} projection ResolveOperation reads from it. The raw form is deliberate: the MCP inspect_operation tool needs the whole body, and `jentic inspect` delegates through the same seam. The api layer's generated-SDK wrapper satisfies it; token acquisition happens behind the implementation, never here.
type KV ¶
KV is one parsed key=value pair (path parameter, query parameter, or header). The caller owns the flag-syntax parsing — under MCP the parameters arrive structured, so the key=value CLI surface never reaches this package. A slice (not a map) preserves the caller's ordering semantics exactly: path substitution applies pairs in order (a repeated key is a no-op after the first replaced every placeholder), and repeated query keys accumulate.
func ParseKVs ¶
ParseKVs parses raw key=value strings (the CLI's --path/--query/--header value syntax) into KV pairs. Both halves are kept VERBATIM — the header path trims whitespace at application time (BuildRequest), path/query never did — so the split is pure syntax. badKV builds the caller's typed error for a malformed pair (the CLI keeps its coded MISSING_ARGUMENT with the flag name; other callers supply their own), so input-shape errors stay caller-owned.
type Operation ¶
type Operation struct {
Method string `json:"method"`
URL string `json:"url"`
Path string `json:"-"`
}
Operation holds the resolved HTTP method and target for an operation. URL is an absolute upstream URL (from inspect or a METHOD:URL target); Path is a broker-relative path (from a METHOD:/path target). Exactly one of URL or Path is set.
func ResolveOperation ¶
func ResolveOperation(ctx context.Context, ins Inspector, target, revision string) (*Operation, error)
ResolveOperation resolves an execute target to its method and destination: METHOD:/path short-circuits to a broker-relative Operation with no network call; METHOD:URL (absolute) and opaque operation_ids resolve via the Inspector, which returns the absolute upstream URL to send to. Failures are coded RESOLVE_FAILED so the caller's exit taxonomy maps them to exit 2.