apiclient

package
v0.0.0-...-15b348c Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 17 Imported by: ? 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 apiclient talks to AuthBridge's session events HTTP API at :9094 by default. It owns the wire protocol so the TUI only deals in domain types.

Index

Constants

View Source
const HeaderTimeout = 2 * time.Minute

HeaderTimeout is the longest this client waits for a peer to BEGIN answering, on every call, buffered or streamed. See New for why the bound belongs to the transport.

A LIVENESS BACKSTOP, NEVER A BUDGET, and the difference is the whole reason it is two minutes rather than the 10s the deleted http.Client.Timeout used. "Waiting for headers" is not the same as "reaching the server": net/http starts this clock at the request and stops it at the first response header, so everything the SERVER does in between is inside the window. /v1/usage does all of its work there — handleUsage computes the snapshot and only then writes headers, and for a symbolic window that means walking up to eight day files off a path an operator configured and possibly a slow mount.

So a 10s value reinstated exactly the pre-emption removing http.Client.Timeout was meant to end: `agentop cost` budgets 15s BECAUSE the ledger scan is slow, and a scan over 10s died at 10s with "timeout awaiting response headers". Measured, not reasoned about: with the bound at 200ms and a caller budget of 2s, a server that spent 500ms scanning failed at 202ms.

Two minutes is above every budget any caller in this module sets and still bounds a wedged peer, which is all this is for. EXPORTED so that relationship can be asserted rather than remembered — see TestCallerBudgets_FitUnderTheHeaderBackstop in package main. A caller adding a longer budget than this has to raise it.

View Source
const SnapshotEventLimit = 2000

SnapshotEventLimit is how many events a snapshot asks for.

Sent explicitly rather than relying on the server's default, so what this client is willing to hold is visible here and tunable without a server change.

RAISED FROM 500 TO THE SERVER'S OWN CEILING, because the reason for the smaller number is gone. 500 was picked when a snapshot carried message bodies: a day-old session was 5000 events and a gigabyte of JSON, 17s of transfer against a 10s client-wide timeout, and the whole request failed with an empty timeline to show for it. That timeout is GONE — the bound is on response HEADERS now and does not cap the body read, so the 17s transfer would succeed today; see New. The limit is about what agentop HOLDS IN MEMORY, which was always the better reason for it. With view=summary an event is ~1KB rather than ~209KB, so 2000 events is about 2MB — less than half of what 500 full events cost, fetched in a fraction of the time.

The cost of the old number was not just latency. A 1000-event session showed its newest 500 and the operator had to know to press [o] for the rest, so "sort oldest first" silently meant "oldest of the newest 500". Reaching the server's maxEventLimit means a normal session arrives whole and that trap is gone.

A ceiling still exists, and this is it: 2000 is what the server clamps to, so asking for more would be a request the server quietly shrinks. Sessions longer than that still page, which is what the ▲ row and the "N older" footer note are for.

View Source
const SummaryView = "summary"

SummaryView is the projection every timeline fetch asks for. Must match sessionapi's recognised `view` value.

Variables

View Source
var ErrBadRequest = fmt.Errorf("apiclient: bad request")

ErrBadRequest is returned when the server responds 400 — it understood the request and refused it.

Distinguished from every other non-200 because it is the one that is the CALLER's fault and the one a caller can act on: an unsupported window, a resolution the storage cannot divide, session= alongside a symbolic window. Without it "unexpected status 400" was indistinguishable from a dial failure, and a CLI would tell a user their proxy was down when the real answer was "that proxy does not know that window". The server's own message is carried through — see getBody for why that is safe.

View Source
var ErrClearRefused = errors.New("clear refused")

ErrClearRefused is a 403: the proxy does not accept a clear from here. The error carries its reason.

View Source
var ErrClearUnsupported = errors.New("this Cortex predates clearing sessions; upgrade it")

ErrClearUnsupported is a proxy that predates DELETE /v1/sessions.

View Source
var ErrDeleteUnsupported = errors.New("this Cortex predates erasing single sessions; upgrade it")

ErrDeleteUnsupported is a proxy that predates DELETE /v1/sessions/{id}. It answers 405, because GET is registered on the same path.

View Source
var ErrImportRunning = errors.New("an import is already running")

ErrImportRunning is a 409 from POST /v1/import: the proxy runs an import already.

View Source
var ErrNoDetail = fmt.Errorf("apiclient: no detail")

ErrNoDetail accompanies ErrBadRequest when the server's own words did NOT survive: the 400 body was not the documented shape, or it was longer than the 512 bytes getBody reads and the JSON arrived cut.

Wrapped ALONGSIDE ErrBadRequest, never instead of it, so an errors.Is(err, ErrBadRequest) caller is unaffected. It exists because "the refusal explained itself" and "it did not" are different situations for a caller that wants to add a hint: the only other way to tell them apart is to match the formatting getBody itself applies, or to guess from the server's wording — and a message about a different parameter then reads as a missing detail. See cmd_export.go's ErrBadRequest branch.

View Source
var ErrNoRecordUnsupported = errors.New("this Cortex erased the session but predates stopping its recording: " +
	"its next calls are recorded again; upgrade Cortex")

ErrNoRecordUnsupported is a proxy that answered StopRecording without stopping the recording: it predates DELETE /v1/sessions/{id}?norecord=1, ignored the query, and erased the session only. Its next calls are recorded again.

View Source
var ErrNoSearch = errors.New("apiclient: this Cortex has no details search")

ErrNoSearch is the answer of a proxy that has no search route, because it predates it.

View Source
var ErrNotFound = fmt.Errorf("apiclient: not found")

ErrNotFound is returned when the server responds 404.

View Source
var ErrSessionGone = errors.New("this Cortex holds no such session")

ErrSessionGone is a 404 from DELETE /v1/sessions/{id}: this Cortex holds no such session, in memory or on disk — erased already, or never there.

Functions

This section is empty.

Types

type ClearResult

type ClearResult struct {
	Sessions         int   `json:"sessions"`
	ArchivedSessions int   `json:"archivedSessions"`
	Bytes            int64 `json:"bytes"`
	// ArchiveError is why the disk half failed. Memory is cleared even then.
	ArchiveError string `json:"archiveError,omitempty"`
	// NoRecord is true when StopRecording's erase also stopped the session's recording.
	NoRecord bool `json:"noRecord,omitempty"`
}

ClearResult is DELETE /v1/sessions' answer: what went from memory, and what went from disk.

type Client

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

Client is a handle to a session API endpoint. Safe for concurrent use.

Two http.Clients share a single Transport: `http` for short REST calls, `httpStream` for SSE. NEITHER carries an http.Client.Timeout — the CALLER's context deadline is the bound, and getJSON supplies restDefaultTimeout only when the caller passed no deadline at all. Sharing the Transport keeps the idle-connection pool warm across reconnects so a long session doesn't leak Transports.

NO CLIENT-WIDE TIMEOUT, because one applies to every call this Client will ever make and so cannot be reconciled with per-call budgets that legitimately differ by 3x. A per-call default that DEFERS to a deadline the caller set keeps the protection for callers with none (the TUI passes its root context to GetPipeline / GetPluginCatalog / ListSessions / GetSession) without overriding one that does. The transport's HeaderTimeout is the liveness backstop underneath both, sized so it cannot pre-empt either.

func New

func New(endpoint string) *Client

New returns a Client pointed at endpoint (e.g. "http://localhost:9094"). Trailing slash is tolerated.

func (*Client) ClearSessions

func (c *Client) ClearSessions(ctx context.Context) (ClearResult, error)

ClearSessions asks the proxy to clear every session, in memory and on disk. A 500 still returns the counts — memory was cleared — with ArchiveError saying why the disk half was not.

func (*Client) DeleteSession

func (c *Client) DeleteSession(ctx context.Context, id string) (ClearResult, error)

DeleteSession asks the proxy to erase one session, in memory and on disk. Answers as ClearSessions, plus ErrSessionGone for a 404 and ErrDeleteUnsupported for a 405.

func (*Client) Endpoint

func (c *Client) Endpoint() string

Endpoint returns the server's base URL. Used by the TUI to display context.

func (*Client) Export

func (c *Client) Export(ctx context.Context, sessions []string, since string, withToolCalls bool) (io.ReadCloser, error)

Export streams GET /v1/export: the session archive as content-free records, one NDJSON line per archived event. sessions names the sessions to carry (nil or empty: every one the archive holds); since is the raw query value the server parses ("168h" or "7d") and "" omits the floor.

A STREAM, NOT A DOCUMENT: the body is the whole export — a month of traffic, ~12MB — and the caller reads and closes it. getBody's status mapping is the whole error contract here: an unknown session or a malformed since is a 400 the server answers BEFORE its first byte, carrying its own words (the archived session ids, or the accepted since forms). A current proxy renders that refusal under a byte budget sized to fit the 512 bytes getBody reads of a 400 body, so the detail survives; an older one caps by id COUNT rather than by bytes, and long ids there can still overrun the read, in which case badRequestDetail finds nothing and the error carries ErrNoDetail beside ErrBadRequest — check that rather than the server's wording to tell "it would not say why" from "it refused something else". A proxy without an archive is a 404.

A WALK THAT DIES PAST ITS FIRST RECORD IS AN ERROR ON THE BODY READ, not a short success: the server resets the connection rather than ending the body cleanly, so the caller's read fails instead of returning io.EOF (an older proxy predating that ends the body cleanly, and a truncated export there is indistinguishable from a whole one). Every complete line already read stays valid NDJSON either way. withToolCalls ADDS the paired tool-call records to the stream (`?include=toolCalls`).

A PROXY PREDATING THE PARAMETER IGNORES IT AND ANSWERS 200 WITH THE PLAIN STREAM. net/url puts unknown keys in the query like any other, and that handler never looked at `include`, so there is no refusal to rely on: the caller asked for tool calls and silently received an export without them. An earlier version of this comment claimed a 400, which was true only of a server that already has the feature — exactly the case where it does not matter.

So detection is the CALLER's job, and ExportSkewError is what it gets. Do not infer support from the presence of toolCall records: an archive with no tool calls legitimately produces none, so their absence cannot distinguish an old proxy from a quiet one. The signal is `kind` on the EVENT records, which a current server stamps on every line whenever the opt-in applies (spec T28) and an old one never writes at all.

func (*Client) GetEventRaw

func (c *Client) GetEventRaw(ctx context.Context, id string, seq uint64) (*pipeline.SessionEvent, *pipeline.RawCapture, error)

GetEventRaw fetches one event in full, payloads included, with its exact capture (#1494): the request as the agent sent it and as it was forwarded, or the response as the origin sent it. raw is nil when the proxy holds no capture for the event, and against a proxy that predates ?raw=1, which ignores it.

The counterpart to view=summary: the timeline no longer carries message bodies, so the detail pane fetches the row under the cursor. This is the one thing the projection makes slower — a round trip where it used to read from memory — and it buys a session that opens in milliseconds instead of seconds.

Not decoded through decodeSessionView's interning path: that exists to stop a hundred-megabyte document being held whole, and this is one event.

func (*Client) GetPipeline

func (c *Client) GetPipeline(ctx context.Context) (*PipelineView, error)

GetPipeline fetches /v1/pipeline.

func (*Client) GetPluginCatalog

func (c *Client) GetPluginCatalog(ctx context.Context) (*PluginCatalog, error)

GetPluginCatalog fetches /v1/plugins. Returns ErrNotFound when the server is too old to serve the endpoint (no WithCatalog option) so callers can degrade gracefully.

func (*Client) GetSession

func (c *Client) GetSession(ctx context.Context, id string) (*pipeline.SessionView, error)

GetSession fetches the most recent SnapshotEventLimit events of a session. Returns an error whose Unwrap chain includes ErrNotFound if the server returned 404.

The returned view's TotalEvents is non-zero when older events exist that this response does not carry.

func (*Client) GetSessionPage

func (c *Client) GetSessionPage(ctx context.Context, id string, before uint64, limit int) (*pipeline.SessionView, error)

GetSessionPage fetches up to limit events ending just BEFORE the given Seq — the page older than a cursor the caller already holds. before == 0 means "from the newest", so the first request and every later page are the same call.

The response is decoded one event at a time rather than as a document, and repeated strings are collapsed as they arrive. Both matter more here than anywhere else in this client: a snapshot of a real session is hundreds of megabytes of JSON, and agentop was holding more memory than the proxy it was watching — 1.64GB against 1.03GB, and the only one of the two still climbing. See decodeSessionView.

func (*Client) GetSessionTail

func (c *Client) GetSessionTail(ctx context.Context, id string, limit int) (*pipeline.SessionView, error)

GetSessionTail fetches the most recent limit events of a session. The tail is the newest page, so this is GetSessionPage with no cursor.

func (*Client) GetTimeline

func (c *Client) GetTimeline(ctx context.Context, id string) (*timeline.Timeline, error)

GetTimeline fetches the session's spans, whole: the pane bins every window from one fetch. ErrNotFound means an unknown session, or a proxy too old to serve the endpoint; the two share a 404, and the Timeline pane says which is likelier.

func (*Client) GetUsage

func (c *Client) GetUsage(ctx context.Context, window, resolution time.Duration, sessionID string, group usage.Group) (*usage.Snapshot, error)

GetUsage fetches time-bucketed usage aggregates from GET /v1/usage.

sessionID empty means all sessions combined. resolution is the width of the buckets returned — the server folds, so a 1h window at 5m arrives as 12 buckets rather than 60. Read the returned Snapshot.BucketSeconds rather than assuming the requested resolution was honored.

Returns ErrNotFound when the proxy has no usage aggregator wired (older binary, or session tracking disabled), which callers should render as "unavailable" rather than as an empty chart.

func (*Client) GetUsageWindow

func (c *Client) GetUsageWindow(ctx context.Context, window string, resolution time.Duration, sessionID string, group usage.Group) (*usage.Snapshot, error)

GetUsageWindow fetches a snapshot for a symbolic window the server names — "today", "7d", "month" — which a time.Duration cannot express.

A sibling of GetUsage rather than a widened signature: GetUsage has several callers and its duration parameters are the right shape for the chart windows, which really are fixed lengths. "Today" is not a length, it is a boundary.

Read Snapshot.Window rather than assuming this one was served. A symbolic window requested where the proxy has no durable cost ledger — Kubernetes, by design — is answered from the in-memory ring's maximum span instead, and the response names the window it actually served. Labelling that figure "today" would report six hours as a day.

resolution of 0 omits the parameter, leaving the server's default. The ledger serves a symbolic window as a single bucket and does not read the resolution at all, so there is no meaningful value for a caller to invent — and "0s" would be rejected as finer than the storage bucket.

func (*Client) GetUsageWindowForAgent

func (c *Client) GetUsageWindowForAgent(ctx context.Context, window string, resolution time.Duration, sessionID, agent string, group usage.Group) (*usage.Snapshot, error)

GetUsageWindowForAgent is GetUsageWindow narrowed to one agent's traffic by the server. A server that predates agent= ignores it; Snapshot.Agent is empty then, and the caller must narrow itself.

func (*Client) GetUsageWindowScoped

func (c *Client) GetUsageWindowScoped(ctx context.Context, window string, resolution time.Duration, sessionID, agent, project string, group usage.Group) (*usage.Snapshot, error)

GetUsageWindowScoped is GetUsageWindowForAgent narrowed also to one project by the server. A server that predates project= ignores it; Snapshot.Project is empty then, and the caller must narrow itself.

func (*Client) Import

func (c *Client) Import(ctx context.Context, req importer.Request, onProgress func(importer.Progress)) (importer.Report, error)

Import asks the proxy to import agent transcripts, and returns its report. A 404 returns ErrNotFound: the proxy has no import route (archive off, or not loopback-only). A 400 returns an error that wraps ErrBadRequest and holds the server's reason.

The caller sets the deadline. The proxy sends the header before it starts the work, so the transport's HeaderTimeout does not limit a long import.

A non-nil onProgress asks for progress, and gets each Progress line. A proxy without progress lines sends only the report, and onProgress is never called.

func (*Client) ListSessions

func (c *Client) ListSessions(ctx context.Context) ([]session.SessionSummary, error)

ListSessions fetches /v1/sessions.

func (*Client) ListSessionsArchived

func (c *Client) ListSessionsArchived(ctx context.Context) (SessionList, error)

ListSessionsArchived fetches /v1/sessions?archived=true: the live sessions plus every one the proxy's session archive holds and memory no longer does, marked Resident false.

func (*Client) SearchSession

func (c *Client) SearchSession(ctx context.Context, id, q string) (SearchResult, error)

SearchSession asks the proxy which of session id's events hold q in what view=summary drops. It reads a 404's body itself, which getBody does not do: the route answers an unknown session with a JSON body (ErrNotFound), and a proxy without the route with the mux's plain text (ErrNoSearch). A long session takes seconds, so the default deadline is the stream's.

func (*Client) StopRecording

func (c *Client) StopRecording(ctx context.Context, id string, conversation bool) (ClearResult, error)

StopRecording asks the proxy to stop recording one session and erase what it holds (#1923, mid-session): DELETE /v1/sessions/{id}?norecord=1. Answers as DeleteSession, except that a session the proxy has not seen is not ErrSessionGone (it is marked ahead of its first call), and ErrNoRecordUnsupported when the proxy erased without stopping the recording. conversation says whether id is one conversation's: the proxy never withholds a shared bucket, so for one of those an answer without noRecord is no older proxy.

func (*Client) Stream

func (c *Client) Stream(ctx context.Context, sessionFilter string) <-chan StreamEvent

Stream opens an SSE connection to /v1/events and publishes SessionEvents to the returned channel until ctx is cancelled. On transport errors it auto-reconnects with exponential backoff (1s..30s, capped, indefinite). Heartbeat comments are discarded silently.

The caller owns ctx — cancelling it both stops reconnect attempts and closes the returned channel. Status transitions (open, reconnecting, closed) are published on the same channel so the UI can render a banner without a side-channel.

Optional sessionFilter narrows the stream to one session server-side.

type PipelinePlugin

type PipelinePlugin struct {
	Name          string          `json:"name"`
	Direction     string          `json:"direction"`
	Position      int             `json:"position"`
	ReadsBody     bool            `json:"readsBody"`
	Requires      []string        `json:"requires,omitempty"`
	RequiresAny   []string        `json:"requiresAny,omitempty"`
	RequiresLater []string        `json:"requiresLater,omitempty"`
	Description   string          `json:"description,omitempty"`
	Config        json.RawMessage `json:"config,omitempty"`
	// OnError is the plugin's on_error policy, "" for the default (enforce): the proxy sends
	// it only when it is not. A plugin under observe runs, but its rejections, body writes and
	// redirects are dropped — header writes still apply — so in those respects its Config says
	// what it would do rather than what it does.
	OnError pipeline.ErrorPolicy `json:"onError,omitempty"`
	Metrics []PluginMetric       `json:"metrics,omitempty"`
}

PipelinePlugin describes one plugin's position, direction, and capabilities. Mirrors the server's pipelinePluginView exactly.

type PipelineView

type PipelineView struct {
	Inbound  []PipelinePlugin `json:"inbound"`
	Outbound []PipelinePlugin `json:"outbound"`
}

PipelineView is the decoded shape of GET /v1/pipeline.

type PluginCatalog

type PluginCatalog struct {
	Plugins []PluginCatalogEntry `json:"plugins"`
}

PluginCatalog is the decoded shape of GET /v1/plugins.

type PluginCatalogEntry

type PluginCatalogEntry struct {
	Name          string             `json:"name"`
	Direction     string             `json:"direction,omitempty"`
	ReadsBody     bool               `json:"readsBody,omitempty"`
	Requires      []string           `json:"requires,omitempty"`
	RequiresAny   []string           `json:"requiresAny,omitempty"`
	RequiresLater []string           `json:"requiresLater,omitempty"`
	Description   string             `json:"description,omitempty"`
	Fields        []PluginFieldEntry `json:"fields,omitempty"`
}

PluginCatalogEntry mirrors the server's sessionapi.CatalogEntry. Describes a registered plugin's static type-level metadata; the catalog includes plugins not currently in the active pipeline.

type PluginFieldEntry

type PluginFieldEntry struct {
	Name        string             `json:"name"`
	Type        string             `json:"type"`
	Required    bool               `json:"required,omitempty"`
	Description string             `json:"description,omitempty"`
	Default     string             `json:"default,omitempty"`
	Enum        []string           `json:"enum,omitempty"`
	Fields      []PluginFieldEntry `json:"fields,omitempty"`
}

PluginFieldEntry mirrors sessionapi.FieldSchemaEntry — per-field schema metadata for a plugin's config. Used by agentop edit's templates renderer; nil for plugins without configs.

type PluginMetric

type PluginMetric struct {
	Name  string  `json:"name"`
	Value float64 `json:"value"`
	Unit  string  `json:"unit,omitempty"`
	Note  string  `json:"note,omitempty"`
}

PluginMetric mirrors core/pipeline.Metric on the wire. Kept as a local type rather than importing the server struct, matching PluginFieldEntry: the client owns its decode shape, and a decode test guards the tags against drift.

type SearchResult

type SearchResult struct {
	Seqs    []uint64 `json:"seqs"`
	LastSeq uint64   `json:"lastSeq"`
}

SearchResult is GET /v1/sessions/{id}/search: the seqs of the session's events whose bodies or capture hold the query, ascending, and the newest seq the proxy read.

type SessionList

type SessionList struct {
	Sessions []session.SessionSummary `json:"sessions"`
	// Archive is nil from a proxy with no session archive — or one that predates it, and
	// answered the plain list because it ignores the query.
	Archive *pipeline.ArchiveUsage `json:"archive,omitempty"`
}

SessionList is /v1/sessions with history: the sessions, and the session archive's usage.

type StreamEvent

type StreamEvent struct {
	Event  *pipeline.SessionEvent
	Status StreamStatus
}

StreamEvent is what Stream publishes. One of Event or Status is set per message — never both. The TUI treats Status as UI-only state (banner, footer); Event as authoritative session data.

type StreamStatus

type StreamStatus struct {
	Phase   string // "open" | "reconnecting"
	Attempt int    // reconnect attempt count (0 for open)
	Err     error
	// Wait is how long until the next connect attempt, for the "reconnecting"
	// phase. Zero for other phases.
	Wait time.Duration
}

StreamStatus is a non-data transition on the stream. Terminal states are signalled by the channel closing; StreamStatus is only for live transitions the UI wants to render as a banner (open, reconnecting-with-backoff).

Jump to

Keyboard shortcuts

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