ir

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 6 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ir defines the protocol-neutral internal representation that sits between API frontends (OpenAI, Anthropic) and agent CLI adapters.

Frontends decode wire requests into an Request; adapters translate CLI output into a stream of [Event]s; frontends encode those events back into their own dialect. Neither side knows about the other.

Index

Constants

View Source
const DefaultRateLimitRetry = 10 * time.Second

DefaultRateLimitRetry is the retry hint attached to an upstream rate limit. The CLIs do not say how long to wait, and both vendor SDKs back off on their own, but a hint keeps a client from hammering a limit it has just hit.

Variables

Efforts is every level a frontend will decode. A value outside it is the caller's mistake and is refused before any backend is consulted.

Functions

func ValidEffort added in v0.1.5

func ValidEffort(s string) bool

ValidEffort reports whether s names a level.

Types

type Code

type Code string

Code is a protocol-neutral error class. Frontends translate it into their own dialect's error shape; the HTTP status comes from Code.HTTPStatus.

const (
	// CodeInvalidRequest — the caller sent something we cannot serve (400).
	CodeInvalidRequest Code = "invalid_request"
	// CodeModelNotFound — no adapter serves the requested model (404).
	CodeModelNotFound Code = "model_not_found"
	// CodeUnauthorized — the gateway's own bearer key check failed (401).
	CodeUnauthorized Code = "unauthorized"
	// CodeOverloaded — no concurrency slot became free in time (429).
	CodeOverloaded Code = "overloaded"
	// CodeUpstreamUnavailable — the CLI is missing or not logged in (503).
	CodeUpstreamUnavailable Code = "upstream_unavailable"
	// CodeUpstreamError — the CLI ran but failed (502).
	CodeUpstreamError Code = "upstream_error"
	// CodeTimeout — the CLI exceeded a request or idle deadline (504).
	CodeTimeout Code = "timeout"
	// CodeCanceled — the client went away before the response was complete.
	CodeCanceled Code = "canceled"
	// CodeInternal — a bug in agent2api (500).
	CodeInternal Code = "internal"
)

func (Code) HTTPStatus

func (c Code) HTTPStatus() int

HTTPStatus maps a code to the status frontends should return.

type Completion

type Completion struct {
	Text       string
	Thinking   string
	Usage      *Usage
	StopReason StopReason
	Model      string
}

Completion is a fully collected response, as a non-streaming frontend needs it. Adapters always stream internally; "non-streaming" is just this.

func Collect

func Collect(ctx context.Context, events <-chan Event) (Completion, error)

Collect drains an adapter's event channel until the run ends.

The channel is consumed to completion even after an error, so the adapter's goroutine always finishes and its subprocess resources are released.

type Effort added in v0.1.5

type Effort string

Effort is how hard the caller asked the model to think.

The values are the union of what the dialects and the CLIs use, carried verbatim rather than normalised: the vocabularies do not line up, and mapping one onto another would mean inventing a correspondence. `minimal` has no counterpart in Claude Code's scale and `max` has none in OpenAI's, so a backend that cannot take a level refuses it by name instead of rounding it to a neighbour.

const (
	EffortMinimal Effort = "minimal"
	EffortLow     Effort = "low"
	EffortMedium  Effort = "medium"
	EffortHigh    Effort = "high"
	EffortXHigh   Effort = "xhigh"
	EffortMax     Effort = "max"
)

type Error

type Error struct {
	Code    Code
	Message string
	// Param names the offending request field, when there is one.
	Param string
	// Detail is extra diagnostic context, e.g. the tail of the CLI's stderr.
	Detail string
	// RetryAfter, when set, is rendered as the Retry-After header. Both vendor
	// SDKs honour it when deciding how long to back off.
	RetryAfter time.Duration
	// Err is the wrapped cause, if any.
	Err error
}

Error is an agent2api error carrying enough context for a frontend to render an actionable message. Detail holds operator-facing context (a stderr tail, for instance) and is included in the response body: this is a local, single-user gateway, and hiding the CLI's own complaint helps nobody.

func AsError

func AsError(err error) *Error

AsError extracts an *Error from err, wrapping anything unrecognized as an internal error so callers always have something to render.

func Errorf

func Errorf(code Code, format string, args ...any) *Error

Errorf builds an Error with a formatted message.

func IncompleteRun

func IncompleteRun() *Error

IncompleteRun is the error for a run that ended without a terminal event: a backend that stopped mid-answer. It must never be reported as a short answer, because the caller has no way to tell the difference.

func InvalidRequest

func InvalidRequest(param, format string, args ...any) *Error

InvalidRequest builds a 400 tied to a specific request field.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Event

type Event struct {
	Type EventType

	// Text is set for EventTextDelta and EventThinkingDelta.
	Text string

	// Usage is set for EventUsage and may also be set on EventDone.
	Usage *Usage

	// StopReason may be set on EventDone.
	StopReason StopReason

	// Model is the concrete backend model the CLI reported, when it does. Set
	// on EventStart or EventDone.
	Model string

	// Err is set for EventError.
	Err *Error
}

Event is one unit of adapter output. Exactly one of Text, Usage or Err is meaningful, depending on Type.

func ErrorEvent

func ErrorEvent(err *Error) Event

ErrorEvent wraps an error as a terminal event.

func TextEvent

func TextEvent(s string) Event

TextEvent builds an assistant text delta.

func ThinkingEvent

func ThinkingEvent(s string) Event

ThinkingEvent builds a reasoning delta.

type EventType

type EventType int

EventType discriminates the events an adapter streams while a CLI runs.

const (
	// EventStart is emitted once, when the backend has accepted the request.
	EventStart EventType = iota
	// EventTextDelta carries a chunk of assistant-visible text.
	EventTextDelta
	// EventThinkingDelta carries a chunk of reasoning text, when the CLI
	// exposes one. Frontends may drop it.
	EventThinkingDelta
	// EventUsage carries token accounting; it may arrive more than once, in
	// which case later events supersede earlier ones.
	EventUsage
	// EventDone is the final event of a successful run.
	EventDone
	// EventError is the final event of a failed run.
	EventError
)

func (EventType) String

func (t EventType) String() string

type Message

type Message struct {
	Role    Role
	Content string
}

Message is a single turn of the conversation. Content is plain text; the frontends flatten richer wire formats (content part arrays) down to text and reject anything that cannot be represented, such as images.

type Request

type Request struct {
	// Model is the resolved, namespaced backend model, e.g. "claude-code:opus".
	Model string
	// Adapter is the adapter id the request was routed to, e.g. "claude-code".
	Adapter string
	// Variant is the adapter-specific model name, e.g. "opus".
	Variant string

	Messages []Message
	Stream   bool

	// MaxTokens and Temperature are best-effort: most CLIs cannot enforce them
	// and adapters are free to ignore them.
	MaxTokens   *int
	Temperature *float64

	// Schema, when non-empty, is a JSON Schema the answer must conform to. It
	// is not best-effort: a frontend only sets it after the backend has said it
	// can enforce one, so an adapter that receives it must honour it or fail.
	Schema string

	// Effort, when non-empty, is how hard the caller asked the model to think.
	// Like Schema and unlike MaxTokens, it is only set after the backend has
	// said it takes that particular level, so an adapter receiving it has a
	// flag to put it on.
	Effort Effort

	// Metadata carries non-essential request annotations (e.g. the caller's
	// "user" field). Never used for routing.
	Metadata map[string]string
}

Request is a protocol-neutral completion request. It carries the entire conversation: agent2api keeps no server-side state, so every request must be self-contained.

type Role

type Role string

Role identifies the author of a Message.

const (
	RoleSystem    Role = "system"
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
)

type StopReason

type StopReason string

StopReason mirrors the Anthropic vocabulary; frontends map it into their own.

const (
	StopEndTurn   StopReason = "end_turn"
	StopMaxTokens StopReason = "max_tokens"
	StopStopSeq   StopReason = "stop_sequence"
)

type Usage

type Usage struct {
	InputTokens              int
	OutputTokens             int
	CacheReadInputTokens     int
	CacheCreationInputTokens int
	// ReasoningOutputTokens is the part of OutputTokens the backend spent on
	// reasoning, whether or not that reasoning reached the caller as thinking
	// text. Only some CLIs report it; the rest leave it zero, which is
	// indistinguishable from "reasoned about nothing" and is the honest answer
	// either way.
	ReasoningOutputTokens int
}

Usage reports token accounting as the CLI understands it. Fields the backend does not report stay zero.

Jump to

Keyboard shortcuts

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