agent

package
v0.7.17 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: 11 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 agent is the extension point for a client agent (an IDE, a CLI) that talks to a host in its own way. The shared request path asks the agent for the route's answer and does not branch on which agent it is. A new agent is one package that embeds Base, overrides only what differs, and registers its route paths.

Host contract: a host must strip every x-context-guru-* header before it forwards a request upstream, or HeaderRequestKind (see requestkind.go) leaks to the provider. The proxy does it already. A plugin host such as Cortex must do the same.

This is a library package. A host (the proxy, the bifrost adapter) imports it; it never imports a host. imports_test.go enforces that.

Index

Constants

View Source
const (
	ClientClaude   = "claude"
	ClientBob      = "bob"
	ClientCodex    = codex.Name
	ClientOpenCode = "opencode"
	ClientPi       = "pi"
)

Identify is the one library entry point that names the client behind a request. Every host (the proxy, the bifrost adapter, Cortex) calls Identify once per request, with the request headers, and passes the Client down. Library code takes the Client it returns, never a raw User-Agent. It uses headers only (the User-Agent and the clients' own marks), never the route path: Claude Code, Codex, OpenCode and Pi share routes, and a host can mount routes elsewhere. The per-client rules live in agent/claudecode, agent/codex, agent/opencode and agent/pi. The path registry stays for an agent that owns a route (Bob's gateway).

Names of the clients Client.Name can hold. "" is any other client.

View Source
const (
	HeaderRequestKind     = "x-context-guru-request-kind"
	RequestKindCompaction = "compaction"
)

HeaderRequestKind is our own header. A client plugin (OpenCode, Pi) sets it on the client's own compaction request, with the value RequestKindCompaction. A host strips every x-context-guru-* header before it forwards a request.

View Source
const TaskIDHeader = "x-task-id"

TaskIDHeader is the header the Bob IDE sends its task id in. It is here, not in package bob, because package bob imports this package. Its direct reader is agent/bob (SessionID). apply (the host id of a route, through ExplicitSessionFor) and proxy/recctx.go (the recorder's session key) read it through bob.SessionID.

Variables

This section is empty.

Functions

func CorrelationHeaders added in v0.7.10

func CorrelationHeaders() []string

CorrelationHeaders lists the request headers that only carry a client's session, thread or task id, read by Identify and by the agents' SessionID. They are random ids, not credentials, so a recorder may write them. It is built from the same constants the parsers use, so a new id header added to a parser is added here in one place. Claude Code names its session in the body (see Identify), so no session header of it is listed.

func IsClientCompaction added in v0.7.9

func IsClientCompaction(c Client, body []byte) bool

IsClientCompaction reports whether body is the client's own compaction request: the client's mark first, then the prompt match in the thread package. It is the one call for a host that holds a Client. Pass the result to the thread Tracker as agentCompaction. A host with no headers passes Identify(nil), which leaves the prompt match as the fallback.

func MarkedCompaction added in v0.7.9

func MarkedCompaction(c Client, body []byte) bool

MarkedCompaction reports whether the client marked this request as its own compaction, by a mark that needs no request text: the headers (Client.Compaction), or Codex's body metadata. body is the request as the client sent it.

func ModelAgentOf added in v0.7.9

func ModelAgentOf(label, provider string) string

ModelAgentOf is the agent label the prediction model reads from a stored row. Before the Pi label, a Pi row held the token of the provider SDK's User-Agent, and the model's agent feature one-hots "openai" (and "asyncopenai", "claude-cli"). A Pi row now holds "pi", so the provider column gives a token back: "openai" and "anthropic" are the SDK tokens Pi's two routed providers send. Any other provider has no known token: the provider string is returned, which the model reads as an unseen value, as it read the old unknown SDK token. Every other label passes through.

func PluginMarksCompaction added in v0.7.8

func PluginMarksCompaction(h http.Header) bool

PluginMarksCompaction reports whether a context-guru client plugin marked this request as the client's own compaction. It reads one header and no request text. A nil h gives false.

func Register

func Register(a Agent)

Register adds a to the default registry. It panics on a refusal: that is a wiring error in an init(), found at start-up (the components.Register pattern).

Types

type Agent

type Agent interface {
	// Name is the agent label on the dashboard. "" means the shared code picks the label.
	Name() string
	// Paths are the model routes this agent owns, as UPSTREAM paths: the path the host forwards to
	// (for example /inference/v1/chat/completions), not the path the client calls on the host
	// (which can carry a host prefix such as /openai). The registry finds the agent by them, by the
	// exact path: no method, no query string, the same trailing slash.
	Paths() []string
	// SessionID is a session id that only this agent's client sends in a header. The host tries
	// it LAST: after x-context-guru-session and the ids in the body. It is per agent because such
	// a header often has no vendor prefix, so any client can send it, and only the route that
	// owns it may read it. "" means none.
	SessionID(h http.Header) string
	// ReadUsage corrects the shared parser's reading of a reply's usage, for an agent whose
	// upstream reports fields the shared parser does not know. base is that reading. A reply it
	// cannot read must return base unchanged (fail open).
	ReadUsage(contentType string, reply []byte, base Usage) Usage
	// ModelTarget is where the host sends its own calls to this route's model (a summary, the
	// sweep's question). The agent never sees the key: the host builds the header from it.
	ModelTarget() ModelTarget
}

Agent is what the shared request path asks of the client agent on a route.

func All added in v0.7.4

func All() []Agent

All is every agent in the default registry. See (*Registry).All.

func ForPath

func ForPath(path string) Agent

ForPath looks path up in the default registry.

type Base

type Base struct{}

Base is the neutral agent: it changes nothing on the shared path. An agent embeds it and overrides only the methods where it differs, so a new method on Agent does not break it. That is why Agent holds only what a host wires today: a method is added when its first caller is.

func (Base) ModelTarget

func (Base) ModelTarget() ModelTarget

func (Base) Name

func (Base) Name() string

func (Base) Paths

func (Base) Paths() []string

func (Base) ReadUsage

func (Base) ReadUsage(_ string, _ []byte, base Usage) Usage

func (Base) SessionID

func (Base) SessionID(http.Header) string

type Client added in v0.7.9

type Client struct {
	// Label is the dashboard's agent family: "claude-code", "codex", "pi", the first token of an
	// unknown User-Agent, or "unknown". It is never empty.
	Label string
	// SDK is the User-Agent family: the label before a client mark (the Pi header) replaced it. For
	// Pi it is the provider SDK's token ("anthropic", "openai"). A reader that depends on the
	// provider, not on the harness, takes this and not Label. Never empty.
	SDK string
	// Name is the narrow identity that rules (the compaction point) key on. It is one of the
	// constants above, or "" for any other client. It is narrower than Label: a wrong match would
	// give a stranger's request another client's rule, so Bob and Codex are matched by the start of
	// their User-Agent, not anywhere in it.
	Name string
	// Entrypoint is how the client was started, from its User-Agent: "cli" (interactive),
	// "headless" (`-p`), "sdk", or "other". "" when there is no User-Agent.
	Entrypoint string
	// SessionID is the session id the client names in a header, or "". Codex: session-id.
	// OpenCode: x-opencode-session-id. Claude Code names its session in the body, not here.
	SessionID string
	// AgentID is the id of this agent's own thread, as the raw header value, or "". Claude Code:
	// x-claude-code-agent-id (subagents only). Codex: thread-id.
	AgentID string
	// AgentIDHeader names the header AgentID came from, or "".
	AgentIDHeader string
	// Compaction is true when the headers mark this request as the client's own compaction: a context-guru
	// plugin header (OpenCode, Pi), or Codex's turn metadata header. A mark in the body (Codex over a
	// WebSocket) needs the body: see MarkedCompaction.
	Compaction bool
	// ParentID is the id of the parent agent's thread or session, or "" for a main thread.
	// Codex: x-codex-parent-thread-id. OpenCode: x-opencode-parent-session-id.
	ParentID string
	// Version is the client's own version, from its User-Agent, or "". Only Claude Code has a rule today:
	// its User-Agent is "claude-cli/<version> (<entrypoint>, ...)" (Claude Code 2.1.334 bundle). Any other client,
	// and a User-Agent with no usable version, give "" (fallback: the learned compaction point then has no
	// version to compare and is not used). #1629
	Version string
}

Client is what the headers of one request say about its client. Identify of no headers gives the generic result: Label "unknown", every other field empty.

func Identify added in v0.7.9

func Identify(h http.Header) Client

Identify names the client of a request from its headers. A nil or empty header gives the generic Client (see Client). It never fails and never panics.

func IdentifyUserAgent added in v0.7.9

func IdentifyUserAgent(ua string) Client

IdentifyUserAgent is Identify for a caller that has nothing but a stored User-Agent, such as a dashboard row. A request path must call Identify with the headers instead: the client marks (Pi, Codex ids) are in the headers, not in the User-Agent.

func (Client) AsksHuman added in v0.7.11

func (c Client) AsksHuman(tool string) bool

AsksHuman reports whether a call to tool waits on a person, not on the tool. Claude Code: AskUserQuestion and ExitPlanMode. Codex: request_user_input. A request whose client is not named (no User-Agent, a zero Client) takes both lists. The fallback for any other named client is the same union, so its behavior does not change.

func (Client) Injected added in v0.7.11

func (c Client) Injected() InjectedText

Injected is the client's injected-text rule. Claude Code: see claudecode.InjectedPrefixes and claudecode.WrapperTags.

func (Client) IsBuiltinSubagentType added in v0.7.11

func (c Client) IsBuiltinSubagentType(t string) bool

IsBuiltinSubagentType reports whether t is a subagent type that ships with the client.

func (Client) IsBuiltinTool added in v0.7.11

func (c Client) IsBuiltinTool(tool string) bool

IsBuiltinTool reports whether tool is a tool the client ships, one a user cannot remove without breaking the agent. Claude Code's list includes its own ToolSearch.

func (Client) IsQuestionTool added in v0.7.11

func (c Client) IsQuestionTool(tool string) bool

IsQuestionTool reports whether a call to tool asks the person a question, not for an approval. It is one of the AsksHuman tools. The fallback is the same as AsksHuman's.

func (Client) IsSubagentTool added in v0.7.11

func (c Client) IsSubagentTool(tool string) bool

IsSubagentTool reports whether a call to tool starts a subagent. Claude Code: Agent and Task.

func (Client) ModelAgent added in v0.7.10

func (c Client) ModelAgent(provider string) string

ModelAgent is the agent value the prediction model reads for a live request from c. It is the value training reads from the stored row of the same request: ModelAgentOf(c.Label, provider). A host passes the Client it found once and the request's provider, and nothing else.

func (Client) SubagentID added in v0.7.9

func (c Client) SubagentID() string

SubagentID is the id of this request's thread when the client says the request comes from a subagent, or "" for a main thread and for a client that gives no signal. Claude Code: the agent header. Codex: the request's own thread-id, when it names a parent thread. OpenCode: the request's own session id, when it names a parent session. A host passes it to thread.HeaderAgentID, then to thread.Tracker.ResolveSession.

func (Client) SubagentTypeField added in v0.7.11

func (c Client) SubagentTypeField() string

SubagentTypeField is the argument of a subagent call that names the subagent's type.

func (Client) UserID added in v0.7.11

func (c Client) UserID(body []byte) string

UserID is the per-person id the request body carries, or "". Only Claude Code sends it, in metadata.user_id. A body with none gives "": the same answer as the fallback for any client.

type ControlCall added in v0.7.4

type ControlCall struct {
	Method string
	Path   string // without the query
	Hosted bool   // the host serves many tenants
}

ControlCall is the control-plane call the client made, as plain strings.

type ControlPlane added in v0.7.4

type ControlPlane interface {
	// WantsReply reports whether the agent reads the reply to c. True: the host asks the upstream
	// for an uncompressed reply, and calls Reply on a readable 200.
	WantsReply(c ControlCall) bool
	// Reply reads or changes the 200 reply body of c. body is at most the host's size limit, and
	// is the agent's own copy. A body the agent cannot read gives the zero value: the host sends
	// the body unchanged.
	Reply(c ControlCall, body []byte) ControlReply
}

ControlPlane is an optional capability, usually of the CatchAll Gateway: it reads or changes the reply to a control-plane call (a call that is not a model call). The host asks the agent of the route the call came in on. Like ModelTarget, it sees no header: the host keeps auth, the size limit and metering.

type ControlReply added in v0.7.4

type ControlReply struct {
	Body    []byte         // nil: send the upstream body unchanged
	Windows map[string]int // model id -> context window from the agent's catalog; nil: none
}

ControlReply is what the agent makes of a reply.

type Gateway added in v0.7.4

type Gateway interface {
	Agent
	Gateway() GatewaySpec
}

Gateway is an optional capability: the agent's client calls the host on the agent's own paths, at the host's root. From A2.5 PR 3, the host mounts each path in Paths() at the same path. A Gateway must have a Name, one per Gateway: the host keys its upstream by it. Register refuses an empty Name and a second Gateway with the same Name.

type GatewaySpec added in v0.7.4

type GatewaySpec struct {
	// Dialect is the wire dialect of the agent's model paths: "openai" today. From A2.5 PR 3, the
	// host refuses, at start-up, a dialect it does not serve.
	Dialect string
	// CatchAll forwards every request no other route matched to this agent's upstream. At most one
	// agent has it: Register refuses a second one.
	CatchAll bool
}

GatewaySpec is how the host mounts a Gateway.

type InjectedText added in v0.7.11

type InjectedText struct {
	// Prefixes mark a message that starts with one of them as injected. Match after trimming
	// whitespace, ignoring case.
	Prefixes []string
	// Tags are element names (without the angle brackets) that enclose injected content.
	Tags []string
	// contains filtered or unexported fields
}

InjectedText is what a client injects into the transcript as if the user had typed it. The two lists differ in how they match, on purpose: a prefix marks a whole message as injected, and a tag encloses injected content inside a message that may also hold real user text.

func (InjectedText) HasExactPrefix added in v0.7.11

func (t InjectedText) HasExactPrefix(text string) bool

HasExactPrefix is HasPrefix with the case kept. The wake check uses it: a person's prompt that starts with "api error" must not read as injected. The transcript reconstruction uses HasPrefix, which ignores case, because the list was built from its corpus that way. One list, two match modes.

func (InjectedText) HasPrefix added in v0.7.11

func (t InjectedText) HasPrefix(text string) bool

HasPrefix reports whether text starts, after trimming white space, with a prefix marker, or is injected by its exact shape.

func (InjectedText) HasTag added in v0.7.11

func (t InjectedText) HasTag(text string) bool

HasTag reports whether text holds the opening of an enclosing tag anywhere, case-sensitive.

func (InjectedText) IsTeammate added in v0.7.11

func (t InjectedText) IsTeammate(text string) bool

IsTeammate reports whether text starts with another agent's message (a coordinator, a teammate or another session), case kept.

type ModelTarget

type ModelTarget struct {
	Path       string // for example /inference/v1/chat/completions
	AuthScheme string // for example Apikey
}

ModelTarget is the chat path on the route's upstream, and the scheme of the Authorization header that carries the caller's key. "" in a field means the host default for it (/v1/chat/completions, Bearer). The host ignores a field it cannot use safely, and keeps its default for that field.

type Registry

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

Registry maps a route path to the agent that owns it. It is safe for concurrent use.

func NewRegistry

func NewRegistry() *Registry

func (*Registry) All added in v0.7.4

func (r *Registry) All() []Agent

All is every registered agent, each once, sorted by Name. The slice is the caller's own copy.

func (*Registry) ForPath

func (r *Registry) ForPath(path string) Agent

ForPath is the agent that owns path, or Base when no agent claims it.

func (*Registry) Register

func (r *Registry) Register(a Agent) error

Register adds a, with every path it claims. A path that is empty, repeated, or claimed by an agent already registered is refused, and then a claims no path at all. A Gateway with an empty Name, a second Gateway with the same Name, and a second CatchAll Gateway, are refused the same way.

type Usage

type Usage struct {
	FreshInput int64
	CacheRead  int64
	CacheWrite int64
	// CacheWrite1h is the part of CacheWrite billed at the one-hour write tier.
	CacheWrite1h int64
	Output       int64
	// Backend is a short label of which backend of the agent's upstream served the reply (for
	// example "A" or "B"), or "" for none. The agent sets it from marks it reads in the reply and
	// never returns the marks themselves. It is set whether or not the reply has usage.
	Backend string
}

Usage is the token counts ReadUsage reads and returns. It is a neutral copy of the counts in the host's own usage type: a library cannot import the host to use that type. The host maps its type to this one and back.

Directories

Path Synopsis
Package all blank-imports every built-in agent so their init() registrations run.
Package all blank-imports every built-in agent so their init() registrations run.
Package bob is the agent for IBM Bob: the Bob IDE and Bob Shell.
Package bob is the agent for IBM Bob: the Bob IDE and Bob Shell.
Package claudecode holds Claude Code's header rules.
Package claudecode holds Claude Code's header rules.
Package codex reads the ids OpenAI Codex (the CLI, the exec mode, the IDE extension and the apps built on its app server) puts in its request headers.
Package codex reads the ids OpenAI Codex (the CLI, the exec mode, the IDE extension and the apps built on its app server) puts in its request headers.
Package opencode holds OpenCode's header rules.
Package opencode holds OpenCode's header rules.
Package pi holds Pi's mark.
Package pi holds Pi's mark.

Jump to

Keyboard shortcuts

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