adapter

package
v0.7.22 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package adapter defines the harness adapter interface and its registry. The harness ecosystem moves fast; the runner's value is the contract-to-enforcement compiler, not the model loop, so harnesses sit behind the smallest interface that lets the engine stay harness-agnostic: compile definition files + describe the agent container, then normalize the event stream.

The claude adapter: the person's own installation of Claude Code, driven as a host process rather than an image the runner builds or pins. Headless print mode with the stream-json event protocol is the autonomous run; the same protocol in both directions is the interactive session.

The runner's invariants are kept by construction, not by trust:

  • Gateway-only tools. The single MCP server in the generated mcp.json is the run's gateway; --strict-mcp-config makes that file the ONLY source of MCP servers, --tools "" removes every built-in tool (Bash, the file tools, WebFetch), and --permission-mode dontAsk denies anything the --allowedTools prefix does not name.
  • Secrets by name. The gateway token reaches the config as ${MCP_GATEWAY_TOKEN}, expanded by Claude Code from the process environment; the plan file holds the variable's name, never a value.
  • No ambient context. --bare skips the person's hooks, plugins, skills, auto memory and CLAUDE.md; --setting-sources "" loads no user, project or local settings; CLAUDE_CONFIG_DIR points at a run-scoped directory. What the model sees is the QuickAgent's instruction and nothing else, which is also what makes a run reproducible on someone else's machine. For a subscription token the run has no --bare (see Compile): the config dir and the setting sources still close hooks, plugins, skills, memory and the person's login, the engine refuses the run when an ancestor of the harness directory holds a CLAUDE.md, and managed settings stay the administrator's — a weaker construction for that kind, recorded as such.
  • Operator-owned model credentials. The model endpoint is the operator policy's (ANTHROPIC_BASE_URL plus the key by name), never the person's own login: with an API key, --bare reads no OAuth credential and no keychain entry; with a subscription token (policy apiKeyKind), which Claude Code reads only from CLAUDE_CODE_OAUTH_TOKEN and only without --bare, the run-scoped CLAUDE_CONFIG_DIR is what holds no login of the person's. That matches the runner's rule that the model key is always the operator's, and it is why harness.claude.baseUrl / .model / .apiKeyEnv / .apiKeyKind exist in the policy.

Written against Claude Code 2.1.263 (claudeProbeVersion); the flags, the mcp.json shape and the event shapes below were established by running that release, and the conformance fixtures are a recording of a real run.

The claude-image adapter: Anthropic's Claude Code, unmodified, in an image built on this machine from the npm packages this build pins (pkg/runner/harnessbuild), run in the agent container as docker-agent is. It is the default whenever the policy's model is a Claude subscription through Claude Code (apiKeyKind claude-signin), and runs on nothing else: an Anthropic key stays docker-agent's, or the installed claude's.

What it shares with the host claude adapter: the gateway-only MCP config, the argv and the stream-json driver, so the invariants described in claude.go hold the same way (--strict-mcp-config with the gateway alone, --tools "", --setting-sources ""). What the container adds:

  • Claude Code's own sign-in, kept in its config directory: a docker volume of Agentry's own, which only Claude Code reads and writes, mounted read-write at harnessbuild.ClaudeConfigDir by the compiler (I3, I4). The runner never reads it.
  • No --bare (bare mode reads no OAuth credential) and no key variable at all, so nothing outranks the sign-in: the container's environment is the plan's alone, without ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN or ANTHROPIC_BASE_URL, and --setting-sources "" loads no settings that could name an apiKeyHelper.
  • The run network's egress proxy, which allows Anthropic's API and the host Claude Code refreshes its sign-in at, nothing else (I2), and claude.ai's connectors off.
  • The image's own user on a read-only root, the working directory an empty tmpfs home: the ancestors whose CLAUDE.md a run without --bare reads are the image's, so the ancestor-file refusal is not needed here.

The codex adapter: the person's own installation of the OpenAI Codex CLI, driven as a host process from a run-scoped CODEX_HOME. On a key `codex exec --json` is the autonomous run; codex's own app-server protocol over stdio is the interactive session (the vendor's ACP package would be a second install), and both modes of a run paid by a ChatGPT plan (codex_image.go says why).

The runner's invariants, by construction:

  • Gateway-only tools. The generated config.toml declares one MCP server, the run's gateway, and switches every built-in tool off: the shell (features.shell_tool), the image viewer (features.view_image), web search, apps, the browser, computer use, image generation, sub-agents, hooks, memories, code mode, goals, the question to the person (request_user_input). What is left to the model is the gateway's catalog plus codex's own three MCP resource readers, which read from that same gateway. --strict-config makes a renamed key a loud failure rather than a silently re-enabled tool. Some tools are not feature keys but come from the model's catalog entry: codex's bundled catalog gives every real OpenAI model apply_patch and deferred tool_search, and most of them code mode. So the config points codex at a one-model catalog the adapter renders (codexCatalog), which replaces the bundled one for the process, and keeps the gateway's tools out of the deferred surface, so none hides behind tool_search.
  • Secrets by name. The gateway token reaches the config as the NAME of the variable codex reads it from (bearer_token_env_var); the model key likewise (env_key). No plan file holds a value.
  • No ambient context. CODEX_HOME points inside the run, so none of the person's config, rules, skills or sessions is read and nothing of this run lands in theirs; --ignore-rules keeps their execpolicy out; --ephemeral (an ephemeral thread, under app-server) persists no session, but on the restart token route, whose thread is kept in the run's own CODEX_HOME so it can be resumed. Codex's own bundled skills are switched off too ([skills.bundled], [skills].include_instructions), so the prompt lists none, and so are codex's permissions message and environment context, which describe its own sandbox, not the run's grant, and carry the host's working directory and timezone.
  • Operator-owned model access. The model endpoint is a provider block built from the policy: codex speaks the OpenAI Responses API and nothing else in this release, and the policy's baseUrl, key variable and model name are what it is given.

Written against codex-cli 0.153.4 (codexProbeVersion); the flags, keys and event shapes were established by running it, and the conformance fixture is a recording of a real run. The plan-usage provider block, the auth command and the error shapes a ChatGPT plan meets were measured on 0.162.0, the Codex image's release.

The codex-image adapter: OpenAI's Codex CLI in agentry-dockerimages' Codex harness image, run in the agent container as docker-agent is. It is the default for a ChatGPT plan, and may run on an OpenAI API key as a choice.

What it shares with the host codex adapter: the generated config.toml, the one-model catalog and the app-server driver, so the invariants described in codex.go hold the same way (gateway-only tools, secrets by name, no ambient context). What the container adds:

  • The image's own user (uid 10001) on a read-only root. CODEX_HOME is the user's home, a tmpfs: codex must write there (its helper links, its state) and refuses a read-only home, so the entrypoint copies the plan's config.toml and models.json into it and starts codex (measured on 0.162.0: a read-only CODEX_HOME fails at start). A session on the restart token route keeps CODEX_HOME in the run's session store instead, so a new container resumes the conversation.
  • A ChatGPT plan's access token in one read-only file (/run/agentry/model-signin/token, mounted by the compiler, I4), which the runner rewrites before it expires; codex reads it with cat. No refresh token enters the container (I3).
  • The run network's egress proxy, which allows api.openai.com:443 alone for a plan (I2).

Both modes are app-server: an autonomous run is its one turn (the originator OpenAI's plan usage serves is the app's clientInfo name, "Agentry", which exec does not send).

The copilot-image adapter: GitHub's Copilot CLI, unmodified, in an image built on this machine from GitHub's release download (pkg/runner/harnessbuild), run in the agent container as docker-agent is and driven through its JSON-RPC server mode (`--headless --stdio`) by the runner's own transport (copilot_session.go). It is the default whenever the policy's model is a Copilot plan (apiKeyKind copilot-signin), and runs on nothing else. There is no host adapter.

How each adapter invariant holds:

  1. Gateway-only tools: --available-tools mcp:* on the argv and availableTools ["mcp:*"] in the session, Copilot CLI's allowlist, which it classifies by source when a tool registers, so every built-in (shell, files, web, sub-agents, ask_user, tool search) is unloaded and a built-in a later release adds is too. The built-in MCP servers are off (--disable-builtin-mcps) and the gateway is the session's one MCP server.
  2. Secrets by name: the plan holds no secret. The person's GitHub token reaches Copilot CLI through the session's token callback, over its stdio alone (spec.ModelSignInCallback), and the gateway's bearer in the session's MCP server headers, sent by the driver: neither is in the container's environment, a file or the plan.
  3. One route out: the run network's egress proxy, which allows GitHub's API and the plan's Copilot API host alone (policy.CopilotProxyAllow, I2); telemetry and experiment hosts are denied.
  4. Deterministic plan content: the instruction and the session's configuration are plan files (instruction.md, session.json), which the driver sends as they are, adding only the session's ids and the bearer.
  5. Best-effort events: the session's events are read for the dozen kinds the runner needs; the rest are kept as they came.
  6. The same envelope: tokens from assistant.usage; a plan run reports no dollars. A quota or rate-limit error is the plan's limit (I9); an organization's policy refusing the run is its own outcome.
  7. Telemetry off: enableSessionTelemetry false, and the proxy denies GitHub's telemetry hosts besides. GitHub's System Prompt is replaced by the run's (systemMessage replace); no custom instructions, skills, memory, hooks, plugins or remote agents.

The container: the image's own user on a read-only root, the home an empty tmpfs (COPILOT_HOME there), Copilot CLI's unpacked package read from the image (it would otherwise unpack into the home, which docker mounts noexec), no keychain, no login shell, no auto-update, no auto login, no sandbox of its own (it would want namespaces the run's capabilities do not give it). The plan's folder is not mounted at all: the driver hands the harness what it needs over the session.

The docker-agent adapter, the default: Apache-2.0 static binary, verified `--exec` one-shot semantics, remote-MCP toolsets with header auth, and the widest provider matrix. The adapter renders one agent.yaml whose ONLY toolset is the run's MCP gateway: docker-agent's built-in shell/filesystem/fetch toolsets are never enabled, whatever the manifest says — tools come from the gateway or not at all.

Pieces every harness adapter shares. The point is that a QuickAgent behaves the same whichever harness runs it: the same instruction text reaches the model, the same result kind comes back, and the conformance suite can hold every adapter to one contract.

Index

Constants

View Source
const (
	StopInterrupted = "interrupted"
	StopCancelled   = "cancelled"
)

StopInterrupted and StopCancelled are the stop reasons of a turn its harness was told to stop: codex's and Claude Code's word, and the Agent Client Protocol's and Copilot's.

View Source
const (
	// ClaudeImageAdapterName is the registry key and --adapter value.
	ClaudeImageAdapterName = "claude-image"

	// ClaudeImageConfigDir is where the image keeps Claude Code's config
	// directory, the sign-in's volume: made by the build for the image's
	// user.
	ClaudeImageConfigDir = harnessbuild.ClaudeConfigDir
)
View Source
const AgentryInferenceTokenEnv = "AGENTRY_INFERENCE_TOKEN"

AgentryInferenceTokenEnv is the variable a credit-paid run's harness reads its credits session token from (spec.EnvVar.FromInference): the named provider's token_key.

View Source
const (
	// ClaudeAdapterName is the registry key and --adapter value.
	ClaudeAdapterName = "claude"
)
View Source
const (
	// CodexAdapterName is the registry key and --adapter value.
	CodexAdapterName = "codex"
)
View Source
const (
	// CodexImageAdapterName is the registry key and --adapter value.
	CodexImageAdapterName = "codex-image"
)
View Source
const ColdCompactionFloor = 40_000

ColdCompactionFloor is the smallest conversation, in tokens, a cold-cache compaction compacts: below it the history costs too little to be worth a compaction's own request.

View Source
const (
	// CopilotImageAdapterName is the registry key and --adapter value.
	CopilotImageAdapterName = harnessbuild.CopilotImageAdapter
)
View Source
const DefaultName = "docker-agent"

DefaultName is the default adapter.

View Source
const HarnessConfigVersion = "16"

HarnessConfigVersion is the docker-agent config schema version the adapter writes (`version:` in agent.yaml). It belongs to the pinned harness image (policy.DefaultHarnessImage, 1.154.0 ships schema 16).

View Source
const ToolExcerptMax = 2048

ToolExcerptMax is the most bytes of a tool's output a live run's driver is handed (engine.Params.OnEvent). The receipts keep the whole raw line; the live event is for following a run as it happens, where a tool that returns a whole file must not flood the reader.

Variables

View Source
var ErrNotSupported = errors.New("adapter does not support interactive sessions")

ErrNotSupported is returned by Session for adapters without an interactive transport.

View Source
var InputTools = []string{"read_input", "search_inputs"}

InputTools are the runner's tools that answer with the person's own inputs, served unchanged.

Functions

func AtCapacity

func AtCapacity(text string) bool

AtCapacity reports whether a harness's error is a model provider saying the model is at capacity: a refusal of the moment, not of the run, which the engine waits out and sends again.

func ColdAfter added in v0.6.999

func ColdAfter(name, provider string) time.Duration

ColdAfter is how long after a model response the adapter named name, on provider (the policy's name), takes its prompt cache as expired: the adapter's row for that provider, else its row for any, else the longest.

func CopilotListContainer

func CopilotListContainer(image string) spec.ContainerSpec

CopilotListContainer is the container a model list runs Copilot CLI in: a run's (the same argv, environment, read-only root and empty home), in image.

func DefaultFor

func DefaultFor(pol *policy.Policy) string

DefaultFor is the adapter a run uses when none is named, for a model sign-in docker-agent cannot spend: the Codex image for a ChatGPT plan, the Claude Code image for a Claude subscription, the Copilot CLI image for a Copilot plan; else DefaultName. docker-agent stays the default for every key.

func HarnessTitle

func HarnessTitle(name string) string

HarnessTitle is the harness an adapter runs, as a person knows it: a host harness's DisplayName, for its image counterpart too, and the Copilot CLI image's; "" for the default harness, which a person never chooses, and for a name this build does not know.

func Names

func Names() []string

Names lists registered adapters, sorted.

func OutOfCredits

func OutOfCredits(text string) bool

OutOfCredits reports whether a harness's error is a provider saying the account that pays for the model has no credits left.

func Register

func Register(a Adapter)

Register installs an adapter; duplicate names are a programmer error.

func SpendsModelSignIn

func SpendsModelSignIn(a Adapter, kind string) bool

SpendsModelSignIn reports whether a can spend a model sign-in of kind.

func TOMLEscape

func TOMLEscape(s string) string

TOMLEscape escapes s for the inside of a TOML basic string. The engine uses it too, for the host paths it substitutes into a rendered .toml file after the plan was compiled.

func ToolExcerpt

func ToolExcerpt(s string) string

ToolExcerpt is the first ToolExcerptMax bytes of a tool's output, cut at a character boundary and marked as cut when it is longer, with surrounding whitespace trimmed. Cut only text that is already masked: a secret the cut splits no longer matches the value it would be masked by.

Types

type Adapter

type Adapter interface {
	// Name is the registry key (--adapter flag value).
	Name() string
	// Compile renders harness definition files and the agent container.
	Compile(in Input) (Result, error)
	// Events parses one harness stdout line into normalized events. A
	// non-JSON or unrecognized line yields a single EventOther/EventAssistantText
	// per the adapter's judgment; never an error — parsing must not kill
	// a run the harness thinks is fine.
	Events(line []byte) []Event
	// Session returns the driver for an interactive session over the
	// harness container's attached stdio. Adapters without an interactive
	// transport return ErrNotSupported.
	Session(ctx context.Context, rw io.ReadWriteCloser, opts SessionOptions) (SessionDriver, error)
}

Adapter compiles a run plan's harness half and interprets its output.

func Get

func Get(name string) (Adapter, error)

Get resolves an adapter name.

type Budget

type Budget struct {
	Bytes int64
	Lines int
}

Budget is the most one tool result may hold for a harness to pass it to the model whole: bytes and lines. The compiler stamps it into the tools spec, and the tools server pages every result within it.

func PageBudget added in v0.7.20

func PageBudget(name string, m policy.Model) Budget

PageBudget is the result budget of a run on model m under the adapter named name: the adapter's own (ResultBudget), held to a sixteenth of the model's window where the policy records one, in whole KiB and never under minPageBytes; on an endpoint of the person's own with no recorded window, to unknownWindowPageBytes. A hosted model with no recorded window keeps the adapter's budget: its harness knows its window, and every hosted window is large enough to hold that page.

func ResultBudget

func ResultBudget(name string) Budget

ResultBudget is the result budget of the adapter named name; an adapter with no measured row gets the tightest measured.

type Compacting added in v0.6.999

type Compacting interface {
	CompactConversation(ctx context.Context) error
}

Compacting is a Continuing driver whose harness can compact the conversation it is in, between turns, without a turn of the agent's: CompactConversation asks the harness to summarise the history in place and returns when it has. On an error the conversation is as it was, or the harness's own compaction state says otherwise in the events.

type Continuing

type Continuing interface {
	// ConversationID is the harness's own id for the conversation the
	// session is in, set by Start.
	ConversationID() string
	// Continued reports whether Start continued ContinueID's conversation,
	// and why not when it did not ("" when none was asked for).
	Continued() (bool, string)
}

Continuing is a SessionDriver that can continue a conversation an earlier harness process stored (SessionOptions.ContinueID). After Start it names the conversation it is in, and says whether that is the one it was asked to continue and, when it is not, why: a harness that could not load it opens a new conversation rather than failing the start.

type CopilotModel

type CopilotModel struct {
	// ID is the model id a policy names (model.name), such as
	// claude-sonnet-5.5.
	ID string `json:"id"`
	// Name is GitHub's display name, "" when it gave none.
	Name string `json:"name,omitempty"`
	// Multiplier is the premium-request multiplier GitHub bills the model
	// at (billing.multiplier), 0 when it gave none.
	Multiplier float64 `json:"multiplier,omitempty"`
}

CopilotModel is one model a Copilot plan offers, as Copilot CLI lists it.

func ListCopilotModels

func ListCopilotModels(ctx context.Context, rw io.ReadWriteCloser, token func(ctx context.Context, refresh bool) (SignInToken, error)) ([]CopilotModel, error)

ListCopilotModels drives Copilot CLI on rw (the list container's stdio) and returns the models the signed-in account's plan offers, in the order Copilot CLI gives them. token is the sign-in, handed to Copilot CLI through its token callback and nowhere else. A model the account's policy disables is left out, and so is a model of a provider of the person's own (an id carrying its provider, provider/id): neither is the plan's to offer. ListCopilotModels closes rw.

type Event

type Event struct {
	Kind EventKind
	// Text is the assistant text (EventAssistantText), the error message
	// (EventError), the tool's name (EventToolCall) or the text it
	// returned (EventToolResult).
	Text string
	// Tool is the tool's name on EventToolCall, and on EventToolResult
	// when the harness repeats it with the answer; a harness that does
	// not leaves the pairing to CallID.
	Tool string
	// CallID is the harness's id for a tool call, on EventToolCall and on
	// the EventToolResult that answers it; "" when the harness gives none.
	CallID string
	// Failed marks an EventToolResult whose tool reported an error.
	Failed bool
	// Redacted marks an EventToolResult whose content held an embedded
	// resource, which Text leaves out: the tool server answers with one
	// when the content is the person's own input. The receipts keep it.
	Redacted bool
	// Delta marks Text as one streamed chunk of the current assistant
	// message rather than a whole message: the engine concatenates deltas
	// until a tool call or usage event ends the message.
	Delta bool
	// InputTokens/OutputTokens/CostUSD are set on EventUsage.
	InputTokens  int64
	OutputTokens int64
	CostUSD      float64
	// TotalTokens is set on EventUsage by a harness that reports context
	// tokens without an input/output split: docker-agent's ACP
	// `usage_update` carries a cumulative `used`, and the driver emits the
	// delta since the previous update. Input and output stay zero then —
	// unknown, not guessed.
	TotalTokens int64
	// ContextTokens and ContextLimit are set on EventUsage by a harness
	// that says how large the conversation now is: the latest model
	// request's input, cached tokens included, and the model's window as
	// the harness knows it. Zero is unknown. A persistent agent compacts
	// its conversation by them.
	ContextTokens int64
	ContextLimit  int64
	// ContextCompacted is set on EventUsage when the harness has just
	// compacted the conversation itself: ContextTokens is then its size
	// after, and zero says the harness did not tell it, so the size known
	// before is no longer true either.
	ContextCompacted bool
	// ResetsAt is set on EventPlanLimit when the harness said when the
	// plan's limit lifts.
	ResetsAt time.Time
	// Policy is set on EventOrgPolicy: which policy refused the run.
	Policy string
	// Raw is the original line for receipts.
	Raw json.RawMessage
}

Event is one normalized harness event.

type EventKind

type EventKind string

EventKind classifies normalized harness events.

const (
	// EventToolCall counts against --max-turns (exit 16). Text and Tool
	// both name the tool; CallID is the harness's id for the call.
	EventToolCall EventKind = "tool_call"
	// EventToolResult is a tool's answer to a call: CallID names the call
	// it answers, Tool the tool where the harness says it, Failed whether
	// the tool reported an error, and Text the text it returned. It is an
	// observation, never a turn: it counts against no budget and is never
	// the run's result.
	EventToolResult EventKind = "tool_result"
	// EventAssistantText carries assistant output text; the engine keeps
	// the last one as the result.
	EventAssistantText EventKind = "assistant_text"
	// EventUsage carries token/cost accounting.
	EventUsage EventKind = "usage"
	// EventError carries a harness-reported error.
	EventError EventKind = "error"
	// EventPermissionGranted records an in-harness permission request the
	// runner allowed: the tool is one the gateway serves, so the policy
	// already bounds it (interactive sessions).
	EventPermissionGranted EventKind = "permission_granted"
	// EventPermissionDenied records an in-harness permission request the
	// runner refused: a tool outside the gateway's catalog, which should
	// never occur (interactive sessions).
	EventPermissionDenied EventKind = "permission_denied"
	// EventPlanLimit says the person's plan refused the run's model calls
	// for its usage limit (invariant I9): the engine ends the run with the
	// plan-limit outcome, never retries it and never reports it as success.
	// Text is the vendor's own words, ResetsAt when it said when the limit
	// lifts (zero otherwise: no reset time is invented).
	EventPlanLimit EventKind = "plan_limit"
	// EventOrgPolicy says a policy of the person's organization or
	// enterprise at the vendor refused the run: the engine ends the run
	// with that policy named, never retries it and never reports it as
	// success. Policy is which, a word of receipt's closed list
	// (receipt.OrgPolicy*); Text the vendor's words.
	EventOrgPolicy EventKind = "org_policy"
	// EventOutOfCredits says the model's provider refused the run's calls
	// because the account that pays has no credits left: an HTTP 402, or
	// the provider's own words for it. The engine ends the run with the
	// out-of-credits outcome and the provider's reason, never retried,
	// never a success. Text is the provider's words.
	EventOutOfCredits EventKind = "out_of_credits"
	// EventReasoning marks a chunk of the model's reasoning stream. It
	// carries no text: reasoning is never the result. The engine notes only
	// that the model's last output was reasoning, to name why a
	// schema-checked run has no answer.
	EventReasoning EventKind = "reasoning"
	// EventOther is an unrecognized-but-valid harness event.
	EventOther EventKind = "other"
)

Event kinds. Parsed best-effort: harness NDJSON schemas are not stable contracts, so adapters map what they recognize and pass the rest through as Other; receipts keep every raw line regardless.

type HostHarness

type HostHarness interface {
	// Executable is the program name looked up on PATH, then in
	// WellKnownPaths; the operator policy's harness.<name>.path
	// overrides both.
	Executable() string
	// ProbeVersion is the harness release this adapter was written
	// against. A different one is a warning, never a refusal: the
	// adapters read event shapes best-effort by design.
	ProbeVersion() string
	// VersionArgv prints the harness's version.
	VersionArgv() []string
	// InstallURL is where a person gets the harness when it is not on
	// this machine — the vendor's own page, for a client to show.
	InstallURL() string
	// DisplayName is the product's name for a person ("Claude Code"),
	// where Name is the adapter's ("claude").
	DisplayName() string
	// MCPCommand is the one line that registers the agentry-mcp server with
	// this host, verbatim from agentry-mcp's README ("Install"; the README
	// also shows an AGENTRY_BIN variant these strings leave out); the path
	// is the person's own build of the server. A client shows it; nothing
	// runs it.
	MCPCommand() string
	// WellKnownPaths are the places the harness's executable is usually
	// installed on goos ("linux", "darwin", "windows"), tried in order
	// after PATH: a GUI launched from the dock or the Start Menu carries
	// the login session's PATH, not the shell's, and the desktop apps that
	// bundle a harness put it nowhere on PATH at all. Each is a path
	// template, and this is the whole rule (harnessprobe applies it and
	// defines nothing of its own):
	//
	//   - "~" as the whole first element is the home directory ("~user"
	//     is left alone); it is substituted after the variables, so a
	//     "$" in the home path is a character, not an expansion;
	//   - "${VAR}", braces required, is an environment variable; a bare
	//     "$VAR" is literal; a template whose variable is unset or empty
	//     is skipped, never resolved against an empty prefix;
	//   - a final "*" is a directory of version-named builds, of which
	//     the newest by dotted version is taken (a prerelease suffix does
	//     not demote a build; on a tie between "2.1.275" and
	//     "2.1.275.exe" the executable wins).
	//
	// Only the executable's existence is read from them — a regular file,
	// through a link; nothing is run but the version flag.
	WellKnownPaths(goos string) []string
}

HostHarness is implemented by adapters that drive the person's own installation of a harness instead of a container, so `agentry doctor --adapter <name>` can report what is actually installed before a scheduled run finds out.

type Input

type Input struct {
	// Mode is the run mode the plan is compiled for (autonomous or
	// interactive); it selects the harness argv and the Session block and
	// changes nothing else.
	Mode manifest.Mode
	// Instruction is the fully rendered system instruction: the System
	// Prompt, then the package's instruction body.
	Instruction string
	// Summary is the manifest one-liner (harness description fields).
	Summary string
	// Model is the operator's model policy.
	Model policy.Model
	// HarnessImage is the pinned harness container image.
	HarnessImage string
	// GatewayURL is the MCP endpoint on the run network.
	GatewayURL string
	// SchemaJSON is the optional output.schema.json content.
	SchemaJSON []byte
	// Harness is the operator policy's block for THIS adapter
	// (harness.<name>), the configuration an adapter that drives the
	// person's own installation of a harness needs: which executable, and —
	// because such a harness speaks its own protocol to its own endpoint —
	// which model and credential variable it is given. Zero for a
	// containerised harness.
	Harness policy.HarnessPolicy
	// UnchangedTools are tools beyond the input tools whose results reach
	// the model unchanged, past a harness's own scrub of tool output: the
	// host link's, where the release declares a target host. Empty for
	// every other plan.
	UnchangedTools []string
	// BrowserTools are the browser server's tools when the plan has one: a
	// harness that keeps only the newest of their results reads them here.
	// Empty without a browser.
	BrowserTools []string
	// Persistent says the plan is a persistent agent's: its harness keeps
	// the conversation on the session store, where the agent's next
	// segment continues it. Mode is then interactive.
	Persistent bool
}

Input is everything an adapter may use to compile harness files. Note what is absent: secret values, host paths, run ids — adapters compile deterministic plan content only.

type Interrupter added in v0.6.1004

type Interrupter interface {
	Interrupt(ctx context.Context) error
}

Interrupter is a SessionDriver that can tell its harness to stop the turn in flight. Interrupt asks and returns; the Prompt in flight then returns with what the turn had produced, its StopReason the protocol's word for a stopped turn. With no turn in flight it does nothing.

type ModelSignInAdapter

type ModelSignInAdapter interface {
	ModelSignIns() []string
}

ModelSignInAdapter is implemented by an adapter that can spend a model sign-in: it names the kinds it can, and for those its Compile returns Result.ModelSignIn. The compiler refuses a policy naming a sign-in kind for any other adapter by policy, before the adapter compiles, so no adapter renders a key for a sign-in.

type NotContinuedError

type NotContinuedError struct {
	// Reason is the harness's account of why, for the segment's envelope.
	Reason string
}

NotContinuedError is a driver's Start refused because the harness could not load the conversation it was asked to continue, and ended: the engine starts the harness again on a new conversation. A harness that can open a new conversation itself does so instead and says why (Continuing).

func (*NotContinuedError) Error

func (e *NotContinuedError) Error() string

type OrgPolicyRefusal

type OrgPolicyRefusal struct {
	// Policy is which, a word of receipt's closed list; Text the vendor's
	// words.
	Policy, Text string
}

OrgPolicyRefusal is a driver's Start refused by a policy of the person's organization at the vendor: the engine ends the run with that outcome, as it does for an EventOrgPolicy mid-run.

func (*OrgPolicyRefusal) Error

func (r *OrgPolicyRefusal) Error() string

type Refusal

type Refusal struct{ Reason string }

Refusal is an adapter's policy-shaped refusal at compile time: the compiler reports it as a refusal by policy (exit 11), not a compile failure, because the policy is what has to change.

func (*Refusal) Error

func (r *Refusal) Error() string

type Renewing added in v0.6.999

type Renewing interface {
	NewConversation(ctx context.Context) (string, error)
}

Renewing is a Continuing driver that can start a new conversation in the running harness, between turns, without the harness or its servers starting again. NewConversation returns the new conversation's id; the session is in it from then on, and the one it leaves stays stored. On an error the session is still in the conversation it was in.

type Result

type Result struct {
	// Files are harness-native definition files, written by the compiler
	// under plan/harness/ and mounted read-only at spec.PlanMount.
	Files map[string][]byte
	// Session is the interactive drive (Input.Mode interactive); nil for
	// an autonomous plan.
	Session *spec.SessionSpec
	// Agent is the agent container to run.
	Agent spec.ContainerSpec
	// Host runs the harness on this machine from the person's own
	// installation instead of Agent.
	Host *spec.HostProcessSpec
	// Model is the provider/model string for receipts.
	Model string
	// ResultKind is "json" when SchemaJSON was wired, else "text".
	ResultKind string
	// OneTurn, on an autonomous plan, is the session protocol the run is
	// driven by as one turn (spec.HarnessSpec.OneTurn); the adapter's
	// Session is its driver. Nil when the harness prints its events.
	OneTurn *spec.SessionSpec
	// ModelSignIn is how the harness reads the model sign-in the policy
	// names (policy.IsModelSignIn of its key kind): its kind, its delivery
	// and the container path the harness reads it at. The compiler adds
	// the mount itself (invariant I4) and refuses the plan when the policy
	// names a sign-in and the adapter returned none. Nil for a key.
	ModelSignIn *spec.ModelSignInSpec
}

Result is what an adapter compiles.

type Resumer

type Resumer interface {
	Resume(ctx context.Context, rw io.ReadWriteCloser) error
}

Resumer is a SessionDriver that carries its conversation over to a new harness process: after the engine has ended the old one between turns (its stdin closed, the process gone), Resume performs the handshake on rw and resumes the conversation, on the same event stream (the restart token route).

type SessionDriver

type SessionDriver interface {
	// Start performs the protocol handshake and opens the session.
	Start(ctx context.Context) error
	// Prompt sends one user turn and returns when the harness ends it.
	Prompt(ctx context.Context, text string) (*Turn, error)
	// Events streams the session's events; closed after Close.
	Events() <-chan Event
	// Close ends the protocol; the harness exits on stdin EOF.
	Close() error
}

SessionDriver drives one interactive harness session. Turns go in through Prompt; everything the harness says comes out of Events as the same normalized kinds an autonomous run produces, so receipts have one shape. A permission request from the harness is answered by the driver — granted for a gateway tool (EventPermissionGranted), denied for anything else (EventPermissionDenied) — and surfaced either way, so the transcript shows every approval. Every event a turn produces is on Events before its Prompt returns: the engine records them ahead of the turn's end on that promise, so none is lost to an End that follows the turn.

type SessionOptions

type SessionOptions struct {
	// GatewayTools are the tool names the run's gateway serves — the run's
	// own grant: the plan's `tools`, bounded by policy at compile, plus the
	// knowledge and voice tools a run-time attachment adds, plus every tool
	// the gateway lists to the session's probe, which is how a declared MCP
	// server's tools are known. A harness permission request for one of
	// them is granted; anything else is denied (under ACP the client is the
	// permission authority for every tool call, and a denial does not reach
	// the model as a refused tool result — docker-agent fails the whole
	// turn).
	GatewayTools []string
	// ModelSignIn says the run is paid by a model sign-in: a 429 from the
	// model is then the plan's limit (EventPlanLimit), not a rate limit to
	// wait out (invariant I9).
	ModelSignIn bool
	// Resumable asks for a conversation the driver can carry over to a new
	// harness process (spec.SessionSpec.RestartOnRenewal): the engine may
	// end the harness between turns and hand the driver a new one (Resumer).
	Resumable bool
	// SignInToken is the run's model sign-in for a harness that asks its
	// driver for a token (spec.ModelSignInCallback): the token to hand it,
	// renewed first when refresh is set or the one held is near its end.
	// Nil when the run hands its sign-in no such way.
	SignInToken func(ctx context.Context, refresh bool) (SignInToken, error)
	// GatewayToken is the run's bearer for its gateway, for a driver that
	// tells its harness the gateway's MCP server over the session itself
	// rather than through a plan file that names the variable.
	GatewayToken string
	// HarnessFile reads one of the plan's harness files as the run
	// rendered it, for a driver that hands its harness the instruction
	// over the session rather than by path.
	HarnessFile func(name string) ([]byte, error)
	// ContinueID names a conversation the harness stored in an earlier
	// process, on the session store the run mounts again: a driver that can
	// continue one (Continuing) loads it at Start instead of opening a new
	// one. Empty opens a new conversation.
	ContinueID string
	// ConversationID is the id the engine told the harness to open a new
	// conversation under, on its command line
	// (spec.SessionSpec.ConversationArgs); empty when the harness or its
	// driver chooses the id.
	ConversationID string
	// Persistent says the session is a persistent agent's segment: the
	// conversation is kept on the session store for the agent's next
	// segment, whether or not this one continued an earlier one.
	Persistent bool
}

SessionOptions is what the engine tells a driver about the run it will drive.

type SignInToken

type SignInToken struct {
	AccessToken string
	ExpiresAt   time.Time
}

SignInToken is a model sign-in's access token as a driver hands it to its harness, and when it expires. Never a refresh token (I3).

type Turn

type Turn struct {
	// StopReason is the protocol's reason (end_turn, cancelled, ...).
	StopReason string
	// Text is the assistant text of the turn.
	Text string
	// Usage is the turn's token usage when the harness reports it.
	Usage *TurnUsage
}

Turn is the harness's answer to one Prompt.

func (*Turn) Stopped added in v0.6.1004

func (t *Turn) Stopped() bool

Stopped says a turn ended because its harness was told to stop it.

type TurnUsage

type TurnUsage struct {
	InputTokens  int
	OutputTokens int
	TotalTokens  int
}

TurnUsage is the token usage of one turn.

Directories

Path Synopsis
Package copilottest is a fake Copilot CLI server mode for tests: the JSON-RPC 2.0 server of `copilot --headless --stdio`, framed by Content-Length, in the shapes Copilot CLI 1.0.95 answers with (recorded against the real binary with no account) and copilot-sdk go/v1.0.19 names.
Package copilottest is a fake Copilot CLI server mode for tests: the JSON-RPC 2.0 server of `copilot --headless --stdio`, framed by Content-Length, in the shapes Copilot CLI 1.0.95 answers with (recorded against the real binary with no account) and copilot-sdk go/v1.0.19 names.
Package signintest is a fake harness adapter for tests of model sign-ins: a container harness that reads its model credential from the file or directory a model sign-in hands it, and speaks a small NDJSON event stream the tests script.
Package signintest is a fake harness adapter for tests of model sign-ins: a container harness that reads its model credential from the file or directory a model sign-in hands it, and speaks a small NDJSON event stream the tests script.

Jump to

Keyboard shortcuts

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